Merge upstream/main into cursor/properties-quick-actions-groups

Resolve docs conflicts in gaps.md, roadmap.md, target-app-parity.md and
ui-parity.md: take main's Last reviewed banner, keep both history rows
(newest first).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ruchirguitarandClaude Opus 5.5 committed 2026-11-27 13:59:16 +05:30
commit 077930d760
283 files changed
+22431 -1669

No files matched your search

+33 -8
View File
@@ -4,7 +4,7 @@
use std::mem;
use craft::ui::dialog::{DialogResult, StackDialog};
use craft::ui::dialog::{DialogId, DialogResult, StackDialog};
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, ParamDialog};
use egui::Context;
use serde_json::{Value, json};
@@ -32,13 +32,27 @@ pub(crate) struct Spec {
/// The add-on dialog open now and the live preview it drives; one at a time, since a preview owns the document.
#[derive(Default)]
pub(crate) struct AddonDialogs {
open: Option<(craft::ui::dialog::DialogId, &'static Spec)>,
open: Option<Open>,
preview: LivePreview,
}
#[derive(Clone, Copy)]
struct Open {
id: DialogId,
spec: &'static Spec,
document: Option<u64>,
}
impl Open {
fn on_document(self, app: &VectorcraftApp) -> bool {
self.document == app.session.active().map(|state| state.uid)
}
}
/// Closes the open add-on dialog without an answer and rolls its preview back.
fn close_open(app: &mut VectorcraftApp) {
let Some((id, _)) = app.addon_dialogs.open.take() else { return };
let Some(open) = app.addon_dialogs.open.take() else { return };
let id = open.id;
if let (Some(host), Some(ctx)) = (app.dialogs(), app.ui_ctx.clone()) {
host.with(|h| {
h.cancel_by_id(&ctx, id);
@@ -46,7 +60,10 @@ fn close_open(app: &mut VectorcraftApp) {
let _ = h.take_by_id::<HostedParamDialog>(id);
});
}
mem::take(&mut app.addon_dialogs.preview).cancel(app);
let preview = mem::take(&mut app.addon_dialogs.preview);
if open.on_document(app) {
preview.cancel(app);
}
}
/// Opens the dialog `spec` describes over `fields`, built each pass by `build`.
@@ -62,7 +79,7 @@ pub(crate) fn open(
close_open(app);
let id = dialog.id();
host.with(|h| h.open(dialog));
app.addon_dialogs.open = Some((id, spec));
app.addon_dialogs.open = Some(Open { id, spec, document: app.session.active().map(|state| state.uid) });
Ok(json!({ "dialog": spec.command }))
}
@@ -94,10 +111,16 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) {
}
fn pump_commit(app: &mut VectorcraftApp) {
let Some((id, spec)) = app.addon_dialogs.open else { return };
let Some(open) = app.addon_dialogs.open else { return };
let Some(host) = app.dialogs() else { return };
let Open { id, spec, .. } = open;
let on_document = open.on_document(app);
if !on_document {
// Switching drawings already ends the old preview. Discard its bookkeeping without touching the other drawing.
app.addon_dialogs.preview = LivePreview::default();
}
let live = host.with(|h| h.get_mut_by_id::<HostedParamDialog>(id).map(|d| (d.is_previewing(), (spec.params)(d.fields()))));
if let Some((previewing, params)) = &live {
if on_document && let Some((previewing, params)) = &live {
let mut preview = mem::take(&mut app.addon_dialogs.preview);
let label = vectorcraft_engine::find_command(spec.command).map_or(spec.command, |command| command.label);
let answer = preview.run(app, *previewing, label, spec.command, params);
@@ -115,7 +138,9 @@ fn pump_commit(app: &mut VectorcraftApp) {
app.addon_dialogs.open = None;
let preview = mem::take(&mut app.addon_dialogs.preview);
// The dialog is closed already, so a refusal can only go to the status line.
if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) {
if !on_document {
app.status(tl!("The add-on settings apply only to the drawing where the dialog opened.").to_owned());
} else if let Err(error) = preview.commit(app, spec.command, (spec.params)(&result.fields)) {
app.status(error);
}
}
@@ -76,13 +76,29 @@ fn new_app() -> VectorcraftApp {
/// Two rectangles without a stroke, both selected.
fn two_rects() -> VectorcraftApp {
let mut app = new_app();
select_two_rects(&mut app);
app
}
fn select_two_rects(app: &mut VectorcraftApp) {
app.run("paint.setStroke", json!({"none": true})).unwrap();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 20, "height": 10})).unwrap();
app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 40, "height": 40})).unwrap();
app.run("select.all", json!({})).unwrap();
}
fn two_drawings() -> VectorcraftApp {
let mut app = two_rects();
app.run("file.new", json!({"width": 700, "height": 500})).unwrap();
select_two_rects(&mut app);
activate(&mut app, 0);
app
}
fn activate(app: &mut VectorcraftApp, index: usize) {
app.run("document.activate", json!({"index": index})).unwrap();
}
fn two_circles() -> VectorcraftApp {
let mut app = new_app();
let ids: Vec<u64> = [100.0, 160.0]
@@ -280,3 +296,68 @@ fn opening_a_second_add_on_dialog_closes_the_first_and_rolls_back_its_preview()
assert_eq!(app.dialogs().unwrap().with(|h| h.open_dialogs().len()), 1);
assert_eq!(x0(&app, 1), 100.0, "the first preview rolled back");
}
#[test]
fn an_add_on_preview_waits_for_its_opening_drawing() {
let mut app = two_drawings();
open_item(&mut app, "Arrange Tools", "Arrange in Grid…");
let id = dialog_id(&app);
set(&app, id, "layout", json!("row"));
set(&app, id, "preview", json!(true));
frame(&mut app);
assert_eq!(x0(&app, 1), 30.0, "previewed in the opening drawing");
activate(&mut app, 1);
let undo = undo_len(&app);
frame(&mut app);
assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, undo), "the other drawing never shows the preview");
assert!(!app.session.in_interaction());
activate(&mut app, 0);
assert_eq!(x0(&app, 1), 100.0, "the old preview rolled back when leaving the drawing");
frame(&mut app);
assert_eq!(x0(&app, 1), 30.0, "the retained settings preview again on the original drawing");
cancel(&app, id);
frame(&mut app);
assert_eq!(x0(&app, 1), 100.0);
}
#[test]
fn an_add_on_confirmation_does_not_edit_another_drawing_before_the_pump() {
let mut app = two_drawings();
let source_undo = undo_len(&app);
open_item(&mut app, "Arrange Tools", "Arrange in Grid…");
let id = dialog_id(&app);
set(&app, id, "layout", json!("row"));
set(&app, id, "preview", json!(false));
assert!(confirm(&app, id));
activate(&mut app, 1);
let target_undo = undo_len(&app);
frame(&mut app);
assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, target_undo), "the other drawing is never rearranged or given an undo step");
assert_eq!(app.session.active_index(), Some(1));
activate(&mut app, 0);
assert_eq!((x0(&app, 1), undo_len(&app)), (100.0, source_undo));
}
#[test]
fn an_add_on_cancel_leaves_the_other_drawings_interaction_running() {
let mut app = two_drawings();
open_item(&mut app, "Arrange Tools", "Arrange in Grid…");
let id = dialog_id(&app);
set(&app, id, "layout", json!("row"));
set(&app, id, "preview", json!(true));
frame(&mut app);
assert_eq!(x0(&app, 1), 30.0);
activate(&mut app, 1);
app.session.begin_interaction("Other drawing's edit").unwrap();
app.session.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap();
let other = app.session.active().unwrap().doc.clone();
cancel(&app, id);
let context = ctx(&app);
super::pump(&mut app, &context);
let active = app.session.active().unwrap();
assert_eq!(active.interaction.as_ref().map(|edit| edit.label.as_str()), Some("Other drawing's edit"));
assert_eq!(active.doc, other);
}
+77 -2
View File
@@ -3,6 +3,7 @@
//! circles selected; Keep Originals), which previews on the canvas and runs
//! `addon.pathtools.bridge` on OK.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind};
use craft::ui::runtime::env::UnitKind;
use serde_json::{Value, json};
@@ -50,7 +51,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
("many", FieldValue::Bool(many)),
]);
let lengths = general_lengths(app);
dialogs::open(app, &SPEC, fields, move |_| {
dialogs::open(app, &SPEC, fields, move |fields| {
let rows = vec![
Param::new("constantGap", tl!("Constant Gap"), ParamKind::bool(false)),
Param::number("gap", tl!("Gap:"), GAP, 1.0, 2)
@@ -67,7 +68,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
.enabled_when("many", FieldValue::Bool(true)),
Param::new("keepOriginals", tl!("Keep Originals"), ParamKind::bool(false)),
];
ParamDialog::new(COMMAND, tl!("Smooth Bridge"), rows).previews(true)
ParamDialog::new(COMMAND, tl!("Smooth Bridge"), rows).previews(true).values(Bind::bound(fields))
})
}
@@ -83,6 +84,80 @@ mod tests {
app.run("shape.ellipse", json!({"x": x - r, "y": 100.0 - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap()
}
fn bridge_app(xs: &[f64]) -> VectorcraftApp {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let ids: Vec<u64> = xs.iter().map(|&x| circle(&mut app, x, 10.0)).collect();
app.run("select.set", json!({"ids": ids})).unwrap();
app
}
fn geometry(app: &VectorcraftApp) -> Vec<vectorcraft_doc::NodeKind> {
app.session.doc().unwrap().doc.layers[0].children().unwrap().iter().map(|node| node.kind.clone()).collect()
}
fn type_number(panel: &mut crate::tests::panel_harness::Panel, label: &str, text: &str) {
panel.click(label);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text(text);
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
panel.frame();
}
#[test]
fn real_bridge_controls_change_the_preview_and_confirmed_geometry() {
use crate::tests::panel_harness::Panel;
let mut panel = Panel::new(bridge_app(&[100.0, 124.0]), crate::tests::picks::dialogs);
let before = panel.app().session.doc().unwrap().history.undo.len();
menus::invoke(&mut panel.app(), super::COMMAND, Value::Null);
panel.frame();
assert!(!panel.enabled("Reach"), "two circles can be bridged at any distance");
panel.click("Keep Originals");
type_number(&mut panel, "Radius", "150");
let id = dialog_id(&panel.app());
assert_eq!(read(&panel.app(), id, |f| f.number("radius")), Some(150.0));
let mut expected = bridge_app(&[100.0, 124.0]);
expected.session.execute(super::COMMAND, &json!({"radius": 150, "keepOriginals": true})).unwrap();
assert_eq!(geometry(&panel.app()), geometry(&expected));
assert_eq!(geometry(&panel.app()).len(), 3, "both circles stay beside the bridge");
panel.click("Constant Gap");
type_number(&mut panel, "Gap", "6");
let params = read(&panel.app(), id, super::params);
assert_eq!(params, json!({"gap": 6.0, "reach": 10.0, "keepOriginals": true}));
let mut expected = bridge_app(&[100.0, 124.0]);
expected.session.execute(super::COMMAND, &params).unwrap();
let preview = geometry(&panel.app());
assert_eq!(preview, geometry(&expected));
panel.click("OK");
panel.frame();
assert_eq!(geometry(&panel.app()), preview);
assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), before + 1);
assert!(!panel.app().any_dialog_open());
}
#[test]
fn real_bridge_reach_edit_reaches_the_command_and_cancel_restores_the_originals() {
use crate::tests::panel_harness::Panel;
let mut panel = Panel::new(bridge_app(&[100.0, 124.0, 148.0, 300.0]), crate::tests::picks::dialogs);
let original = geometry(&panel.app());
menus::invoke(&mut panel.app(), super::COMMAND, Value::Null);
panel.frame();
assert!(panel.enabled("Reach"));
type_number(&mut panel, "Reach", "5");
let id = dialog_id(&panel.app());
let params = read(&panel.app(), id, super::params);
assert_eq!(params["reach"], 5.0);
let mut expected = bridge_app(&[100.0, 124.0, 148.0, 300.0]);
expected.session.execute(super::COMMAND, &params).unwrap();
assert_eq!(geometry(&panel.app()), geometry(&expected));
panel.click("Cancel");
panel.frame();
assert_eq!(geometry(&panel.app()), original);
}
#[test]
fn constant_gap_shows_the_gap_and_bridges_many_circles_within_reach() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
+92 -2
View File
@@ -1,6 +1,7 @@
//! Divide into Dashes in the interface: its dialog (dash and gap lengths, Fit to Corners and Ends,
//! Remove Gaps), which previews on the canvas and runs `addon.pathtools.divideDashes` on OK.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind};
use serde_json::{Value, json};
@@ -36,7 +37,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
("removeGaps", FieldValue::Bool(true)),
]);
let lengths = general_lengths(app);
dialogs::open(app, &SPEC, fields, move |_| {
dialogs::open(app, &SPEC, fields, move |fields| {
let rows = vec![
Param::number("dash", tl!("Dash:"), 10.0, 1.0, 2).length(lengths).bounds(Some(*DASHES.start()), Some(*DASHES.end())),
Param::number("gap", tl!("Gap:"), 0.0, 1.0, 2).length(lengths).bounds(Some(*GAPS.start()), Some(*GAPS.end())),
@@ -45,6 +46,95 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
// PLAN: assumed `Param::enabled_above(key, threshold)` (pl.F4, forms-w1)
Param::new("removeGaps", tl!("Remove Gaps"), ParamKind::bool(true)).enabled_above("gap", 0.0),
];
ParamDialog::new(COMMAND, tl!("Divide into Dashes"), rows).previews(true)
ParamDialog::new(COMMAND, tl!("Divide into Dashes"), rows).values(Bind::bound(fields)).previews(true)
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::addons::dialogs::tests::{dialog_id, open_item, read};
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
use vectorcraft_engine::Session;
fn app() -> VectorcraftApp {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
let path = app.run("path.create", json!({"anchors": [{"x": 0, "y": 0}, {"x": 100, "y": 0}]})).unwrap();
app.run("select.set", json!({"ids": [path["id"]]})).unwrap();
app
}
fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| host.run(ui));
}
crate::dialogs::host::pump(app, ui.ctx());
}
fn spans(app: &VectorcraftApp) -> Vec<(f64, f64)> {
app.session.active().unwrap().doc.layers[0]
.children()
.unwrap()
.iter()
.map(|node| {
let bounds = node.geometric_bounds().unwrap();
(bounds.x0, bounds.x1)
})
.collect()
}
/// Real input controls the preview and approval; Cancel restores the undivided path.
#[test]
fn keyboard_and_toggle_edits_control_dashes_preview_cancel_and_ok() {
let mut expected = app();
expected.run(COMMAND, json!({"dash": 30, "gap": 10, "fit": true, "removeGaps": false})).unwrap();
let expected = spans(&expected);
assert!(expected.len() > 1);
for cancel in [true, false] {
let app = app();
let original = app.session.active().unwrap().doc.clone();
let selection = app.session.active().unwrap().selection.clone();
let undo = app.session.active().unwrap().history.undo.len();
let mut panel = Panel::new(app, draw);
panel.room(egui::vec2(800.0, 600.0));
open_item(&mut panel.app(), "Path Precision Tools", "Divide into Dashes…");
panel.frame();
panel.click_role("Preview", Role::CHECK_BOX);
let id = dialog_id(&panel.app());
for (label, key, text, value) in [("Dash", "dash", "30 pt", 30.0), ("Gap", "gap", "10 pt", 10.0)] {
panel.click_role(label, Role::SPIN_BUTTON);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text(text);
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
assert_eq!(read(&panel.app(), id, |fields| fields.number(key)), Some(value));
}
panel.click_role("Fit to Corners and Ends", Role::CHECK_BOX);
panel.click_role("Remove Gaps", Role::CHECK_BOX);
assert_eq!(read(&panel.app(), id, |fields| fields.bool("fit")), Some(true));
assert_eq!(read(&panel.app(), id, |fields| fields.bool("removeGaps")), Some(false));
panel.click_role("Preview", Role::CHECK_BOX);
let preview = spans(&panel.app());
assert_eq!(preview.len(), expected.len());
assert!(preview.iter().zip(&expected).all(|(a, b)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6));
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
panel.click(if cancel { "Cancel" } else { "OK" });
assert!(panel.app().dialogs().unwrap().with(|host| host.open_dialogs().is_empty()));
assert!(!panel.app().session.in_interaction());
if cancel {
let app = panel.app();
let state = app.session.active().unwrap();
assert_eq!(state.doc, original);
assert_eq!(state.selection, selection);
assert_eq!(state.history.undo.len(), undo);
} else {
assert_eq!(spans(&panel.app()), preview);
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1);
panel.app().run("edit.undo", json!({})).unwrap();
assert_eq!(panel.app().session.active().unwrap().doc, original);
}
}
}
}
@@ -2,6 +2,7 @@
//! circle to draw, or all), which previews the circles on the canvas and runs
//! `addon.pathtools.tangentCircle` on OK.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind};
use serde_json::{Value, json};
@@ -71,7 +72,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
.enabled_when("twoShapes", FieldValue::Bool(true)),
Param::new("circle", tl!("Circle:"), ParamKind::choice(options, Some("0".into()))),
];
ParamDialog::new(COMMAND, tl!("Tangent Circle"), rows).previews(true)
ParamDialog::new(COMMAND, tl!("Tangent Circle"), rows).values(Bind::bound(fields)).previews(true)
})
}
@@ -87,6 +88,97 @@ mod tests {
app.run("shape.ellipse", json!({"x": cx - r, "y": cy - r, "width": 2.0 * r, "height": 2.0 * r})).unwrap()["id"].as_u64().unwrap()
}
#[test]
fn actual_radius_and_circle_edits_control_preview_cancel_and_ok() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
use craft::ui::patterns::form_dialogs::HostedParamDialog;
fn app() -> VectorcraftApp {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let a = circle(&mut app, 100.0, 100.0, 10.0);
let b = circle(&mut app, 130.0, 100.0, 10.0);
app.run("select.set", json!({"ids": [a, b]})).unwrap();
app
}
fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| host.run(ui));
}
crate::dialogs::host::pump(app, ui.ctx());
}
fn previewing(app: &VectorcraftApp) -> bool {
let id = dialog_id(app);
app.dialogs().unwrap().with(|host| host.get_by_id::<HostedParamDialog>(id).unwrap().is_previewing())
}
fn count(app: &VectorcraftApp) -> usize {
app.session.active().unwrap().doc.layers[0].children().unwrap().len()
}
fn last_bounds(app: &VectorcraftApp) -> vectorcraft_geom::Rect {
app.session.active().unwrap().doc.layers[0].children().unwrap().last().unwrap().geometric_bounds().unwrap()
}
let mut expected = app();
expected.run(super::COMMAND, json!({"radius": 20, "circle": 2})).unwrap();
let expected = last_bounds(&expected);
for cancel in [true, false] {
let app = app();
let original = app.session.active().unwrap().doc.clone();
let selection = app.session.active().unwrap().selection.clone();
let undo = app.session.active().unwrap().history.undo.len();
let mut panel = Panel::new(app, draw);
panel.room(egui::vec2(800.0, 600.0));
crate::addons::dialogs::tests::open_item(&mut panel.app(), "Path Precision Tools", "Tangent Circle…");
panel.frame();
let id = dialog_id(&panel.app());
assert!(previewing(&panel.app()), "the hosted dialog starts with Preview on");
assert_eq!(count(&panel.app()), 10);
panel.click_role("Preview", Role::CHECK_BOX);
assert!(!previewing(&panel.app()));
assert_eq!(panel.app().session.active().unwrap().doc, original);
panel.click_role("Radius", Role::SPIN_BUTTON);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text("20 pt");
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
assert_eq!(read(&panel.app(), id, |fields| fields.number("radius")), Some(20.0));
assert_eq!(count(&panel.app()), 2, "editing with Preview off keeps the originals");
panel.click_role("Preview", Role::CHECK_BOX);
assert!(previewing(&panel.app()));
assert_eq!(count(&panel.app()), 8);
assert_eq!(read(&panel.app(), id, |fields| fields.int("found")), Some(6));
panel.click("Circle");
panel.click("2");
assert_eq!(read(&panel.app(), id, |fields| fields.text("circle").map(str::to_owned)), Some("2".into()));
assert_eq!(count(&panel.app()), 3);
let actual = last_bounds(&panel.app());
assert!((actual.x0 - expected.x0).abs() < 1e-6 && (actual.y0 - expected.y0).abs() < 1e-6);
assert!((actual.x1 - expected.x1).abs() < 1e-6 && (actual.y1 - expected.y1).abs() < 1e-6);
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
panel.click(if cancel { "Cancel" } else { "OK" });
assert!(panel.app().dialogs().unwrap().with(|host| host.open_dialogs().is_empty()));
assert!(!panel.app().session.in_interaction());
if cancel {
let app = panel.app();
let state = app.session.active().unwrap();
assert_eq!(state.doc, original);
assert_eq!(state.selection, selection);
assert_eq!(state.history.undo.len(), undo);
} else {
assert_eq!(count(&panel.app()), 3);
assert_eq!(last_bounds(&panel.app()), actual);
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1);
panel.app().run("edit.undo", json!({})).unwrap();
assert_eq!(panel.app().session.active().unwrap().doc, original);
}
}
}
#[test]
fn tangent_circle_previews_picks_one_cancels_and_runs_on_ok() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
+1 -4
View File
@@ -200,10 +200,7 @@ fn body(ui: &mut Ui, fields: &mut Fields, rows: &[(String, String)], go_to: &mut
});
let relations: Vec<Entry<String>> = RELATIONS.iter().map(|&(value, text)| Entry::new(value.to_owned(), label(tl!(text)))).collect();
Field::new(label(tl!("Select:"))).show(ui, |ui, _| {
let picked = Select::new(label(tl!("Select:")), Bind::given(fields.relation.clone()), &relations).show(ui).value().cloned();
if let Some(relation) = picked {
fields.relation = relation;
}
Select::new(label(tl!("Select:")), Bind::bound(&mut fields.relation), &relations).show(ui);
});
}
@@ -290,10 +290,7 @@ fn body(ui: &mut Ui, fields: &mut Fields, rows: &[Value]) {
TextField::search(label(tl!("Search images")), Bind::bound(&mut fields.search)).show(ui);
let shows: Vec<Entry<String>> = SHOW.iter().map(|&(value, text)| Entry::new(value.to_owned(), label(tl!(text)))).collect();
Field::new(label(tl!("Show:"))).show(ui, |ui, _| {
let picked = Select::new(label(tl!("Show:")), Bind::given(fields.show.clone()), &shows).show(ui).value().cloned();
if let Some(show) = picked {
fields.show = show;
}
Select::new(label(tl!("Show:")), Bind::bound(&mut fields.show), &shows).show(ui);
});
let visible = shown(rows, &fields.search, &fields.show, &Env::of(ui).folder());
let lines: Vec<Line> = visible
@@ -95,6 +95,43 @@ fn selected(app: &VectorcraftApp) -> Vec<u64> {
ids
}
#[test]
fn canceling_a_keyboard_show_filter_restores_all_rows_before_selecting() {
use craft::ui::contract::Role;
let dir = Folder::new("cancel-show-filter");
let (app, river, harbour, stamp) = app(&dir);
let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 600.0));
menus::invoke(&mut panel.app(), COMMAND, Value::Null);
panel.frame();
panel.click_role("Show", Role::COMBO_BOX);
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
assert_eq!(host(&panel.app(), |host| host.get::<LinkStatusDialog>().unwrap().fields.show.clone()), "linked");
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
assert_eq!(host(&panel.app(), |host| host.get::<LinkStatusDialog>().unwrap().fields.show.clone()), "all");
for name in ["river.png", "harbour.png", "stamp.png"] {
assert!(panel.shows(name), "canceling the filter restores {name}");
}
panel.click_role("All", Role::BUTTON);
panel.click_role("Zoom to Selection", Role::CHECK_BOX);
panel.click("Select");
let mut want = vec![river, harbour, stamp];
want.sort_unstable();
assert_eq!(selected(&panel.app()), want);
menus::invoke(&mut panel.app(), COMMAND, Value::Null);
panel.frame();
panel.click_role("Show", Role::COMBO_BOX);
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
assert_eq!(host(&panel.app(), |host| host.get::<LinkStatusDialog>().unwrap().fields.show.clone()), "linked");
assert!(panel.shows("river.png"));
assert!(!panel.shows("harbour.png") && !panel.shows("stamp.png"));
panel.click("Cancel");
assert_eq!(selected(&panel.app()), want);
}
#[test]
fn the_message_says_what_was_selected_and_what_was_left_out() {
assert_eq!(message(&["missing"], 9, &[]), "Selected 9 missing images");
+35
View File
@@ -39,6 +39,41 @@ fn names(v: &[&str]) -> Vec<String> {
v.iter().map(|s| s.to_string()).collect()
}
#[test]
fn canceling_a_keyboard_relation_choice_restores_the_original_selection_rule() {
use craft::ui::contract::Role;
let mut app = new_app();
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let inside = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
let edge = app.run("shape.rectangle", json!({"x": 90, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("select.none", json!({})).unwrap();
let mut panel = crate::tests::panel_harness::Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 600.0));
menus::invoke(&mut panel.app(), COMMAND, Value::Null);
panel.frame();
panel.click_role("Select", Role::COMBO_BOX);
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
assert_eq!(host(&panel.app(), |host| host.get::<ArtboardsDialog>().unwrap().fields.relation.clone()), "inside");
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
assert_eq!(host(&panel.app(), |host| host.get::<ArtboardsDialog>().unwrap().fields.relation.clone()), "overlap");
panel.click("OK");
let mut actual = panel.app().session.active().unwrap().selection.objects.clone();
let mut expected = vec![vectorcraft_doc::NodeId(inside), vectorcraft_doc::NodeId(edge)];
actual.sort_unstable();
expected.sort_unstable();
assert_eq!(actual, expected);
menus::invoke(&mut panel.app(), COMMAND, Value::Null);
panel.frame();
panel.click_role("Select", Role::COMBO_BOX);
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
assert_eq!(host(&panel.app(), |host| host.get::<ArtboardsDialog>().unwrap().fields.relation.clone()), "inside");
panel.click("OK");
assert_eq!(panel.app().session.active().unwrap().selection.objects, vec![vectorcraft_doc::NodeId(inside)]);
}
/// A 100 × 100 document with a Banner artboard at x 150, an object in each artboard, and nothing selected.
fn banner() -> (VectorcraftApp, u64) {
let mut app = new_app();
+2 -1
View File
@@ -3,6 +3,7 @@
//! and runs `addon.type.textTweaker` on OK.
use craft::menu::Node;
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind};
use craft::ui::runtime::env::UnitKind;
use serde_json::{Value, json};
@@ -116,7 +117,7 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
.enabled_when("shape", FieldValue::Text("random".into())),
Param::new("skipSpaces", tl!("Skip Spaces"), ParamKind::bool(true)),
]);
ParamDialog::new(COMMAND, tl!("Text Tweaker"), rows).previews(true)
ParamDialog::new(COMMAND, tl!("Text Tweaker"), rows).values(Bind::bound(fields)).previews(true)
})
}
+79 -1
View File
@@ -6,13 +6,91 @@ use crate::addons::dialogs::tests::{dialog_id, frame, open_item, read, set};
/// A window's app with one type object, selected.
fn app() -> VectorcraftApp {
app_with_text("abc")
}
fn app_with_text(text: &str) -> VectorcraftApp {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let id = app.run("text.create", json!({"x": 40, "y": 100, "text": "abc", "size": 20})).unwrap()["id"].as_u64().unwrap();
let id = app.run("text.create", json!({"x": 40, "y": 100, "text": text, "size": 20})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
app
}
/// The real form controls the same text changes as the command, including attribute-dependent
/// defaults, random seed and whether a space is included. Cancel restores the original text.
#[test]
fn keyboard_and_choice_edits_reach_text_tweaker_preview_and_approval() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
use craft::ui::patterns::form_dialogs::HostedParamDialog;
fn text(app: &VectorcraftApp) -> vectorcraft_doc::TextObject {
let state = app.session.active().unwrap();
let node = state.doc.node(state.selection.objects[0]).unwrap();
match &node.kind {
vectorcraft_doc::NodeKind::Text(text) => (**text).clone(),
_ => panic!("selected object is not text"),
}
}
fn type_number(panel: &mut Panel, label: &str, input: &str) {
panel.click_role(label, Role::SPIN_BUTTON);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text(input);
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
}
let params = json!({"attribute": "rotation", "from": 10.0, "to": 40.0, "shape": "random", "seed": 42, "skipSpaces": false});
let mut expected = app_with_text("a b");
expected.run(super::COMMAND, params.clone()).unwrap();
let expected = text(&expected);
for cancel in [true, false] {
let app = app_with_text("a b");
let original = app.session.active().unwrap().doc.clone();
let selection = app.session.active().unwrap().selection.clone();
let undo = app.session.active().unwrap().history.undo.len();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 700.0));
open_item(&mut panel.app(), "Type Tools", "Text Tweaker…");
panel.frame();
let id = dialog_id(&panel.app());
assert!(panel.app().dialogs().unwrap().with(|host| host.get_by_id::<HostedParamDialog>(id).unwrap().is_previewing()));
panel.click_role("Preview", Role::CHECK_BOX);
assert_eq!(panel.app().session.active().unwrap().doc, original);
panel.click("Attribute");
panel.click("Character Rotation");
assert_eq!(read(&panel.app(), id, |fields| (fields.number("from"), fields.number("to"))), (Some(0.0), Some(30.0)));
type_number(&mut panel, "From", "10");
type_number(&mut panel, "To", "40");
panel.click("Shape");
panel.click("Random");
assert!(panel.enabled("Seed"));
type_number(&mut panel, "Seed", "42");
panel.click_role("Skip Spaces", Role::CHECK_BOX);
assert_eq!(read(&panel.app(), id, super::params), params);
assert_eq!(panel.app().session.active().unwrap().doc, original, "Preview off leaves the text unchanged");
panel.click_role("Preview", Role::CHECK_BOX);
assert_eq!(text(&panel.app()), expected, "the real controls reach the same text formatting as automation");
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
panel.click(if cancel { "Cancel" } else { "OK" });
assert!(!panel.app().any_dialog_open());
assert!(!panel.app().session.in_interaction());
if cancel {
let app = panel.app();
let state = app.session.active().unwrap();
assert_eq!(state.doc, original);
assert_eq!(state.selection, selection);
assert_eq!(state.history.undo.len(), undo);
} else {
assert_eq!(text(&panel.app()), expected);
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1);
panel.app().run("edit.undo", json!({})).unwrap();
assert_eq!(panel.app().session.active().unwrap().doc, original);
}
}
}
#[test]
fn another_attribute_starts_from_its_own_values() {
let mut app = app();
+4 -1
View File
@@ -120,7 +120,9 @@ impl VectorcraftApp {
last_ms: 0.0,
moved: false,
from_worker: false,
worker_parts: false,
whole_frames: false,
view_sized_bounds: None,
web_patch_renderer: None,
reused: None,
waits_for_still: cfg!(target_arch = "wasm32"),
still: None,
@@ -242,6 +244,7 @@ impl VectorcraftApp {
three_d_dialog: None,
three_d: Default::default(),
export_dialogs: Default::default(),
package_document: None,
web_export: Default::default(),
flattener_preview: Default::default(),
flatten_dialog: Default::default(),
+10 -4
View File
@@ -25,10 +25,16 @@ pub struct CanvasCache {
/// The frame shown was rendered on the worker: an interaction's frames stay there
/// ([`canvas::show`]).
pub from_worker: bool,
/// The worker's frame shown drew art in a way that depends on its size, or a part of it drawn
/// again on this thread would not have matched the frame around it: until the worker's next
/// frame is shown, edits of the frame shown render on the worker ([`canvas::show`]).
pub worker_parts: bool,
/// The frame shown drew art in a way that depends on its size, or a part of it drawn again on
/// this thread would not have matched the frame around it. Edits that reach the affected area
/// render whole, on the worker when the frame is heavy ([`canvas::show`]).
pub whole_frames: bool,
/// The shown web frame can still be patched outside this enclosure in its own raster pixels.
/// Present only when all frame-size-dependent output has a known bound.
pub view_sized_bounds: Option<vectorcraft_geom::Rect>,
/// Draws for a patch against a web frame with bounded view-sensitive art.
/// The renderer of the whole frame keeps its raster and derived-art caches across these patches.
pub web_patch_renderer: Option<Box<vectorcraft_render::Renderer>>,
/// The frame shown holds pixels the worker copied from its last frame, and when it was shown
/// (seconds, egui's input time): it renders whole once it has been shown for
/// [`canvas::STILL_SECS`] with the view unmoved.
+1 -1
View File
@@ -74,7 +74,7 @@ pub(crate) fn animated_zoom(p: &vectorcraft_engine::Prefs) -> bool {
/// Whether a 3D effect is edited in its dialog: the selection's marks and widgets give way to the dialog's gizmo.
pub(crate) fn revolve_editing(app: &VectorcraftApp) -> bool {
app.three_d_dialog.is_some()
crate::dialogs::three_d::editing_current_drawing(app)
}
/// The arrows the canvas takes with nothing in the window focused, as it takes every arrow while it has the focus:
+14 -4
View File
@@ -173,7 +173,9 @@ impl Component for CanvasDrops<'_> {
let panel = Target::new(rect, view, covered, |p: &PanelDrag| (!matches!(p, PanelDrag::Art { .. })).then(|| Payload::Panel(p.clone())));
let style = Target::new(rect, view, covered, |d: &StyleDrag| (d.document == self.document).then(|| Payload::Style(d.clone())));
let symbol = Target::new(rect, view, covered, |d: &ListDrag<SymbolKey>| Some(Payload::Symbol(d.grabbed.clone())));
let brush = Target::new(rect, view, covered, |d: &ListDrag<BrushKey>| Some(Payload::Brush(d.grabbed.clone())));
let brush = Target::new(rect, view, covered, |d: &ListDrag<BrushKey>| {
(d.grabbed.doc == self.document).then(|| Payload::Brush(d.grabbed.clone()))
});
let library = Target::new(rect, view, covered, |d: &ListDrag<LibraryKey>| Some(Payload::Library(d.grabbed.clone())));
let panel = cx.drop_target::<PanelDrag, _>(&panel);
let style = cx.drop_target::<StyleDrag, _>(&style);
@@ -336,7 +338,7 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
Payload::Panel(PanelDrag::LibraryGraphic { library, item }) => {
run(app, "library.use", json!({"library": library, "kind": "graphic", "item": item, "center": [at.x, at.y]}))
}
Payload::Brush(key) => match hit() {
Payload::Brush(key) if app.session.active().is_some_and(|st| st.uid == key.doc) => match hit() {
None if brush_has_art(app, key) => run(app, "brush.placeArt", json!({"name": key.name, "x": at.x, "y": at.y})),
None => Ok(()),
Some(hit) => {
@@ -344,13 +346,14 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
run(app, "brush.apply", json!({"name": key.name, "ids": [owner]}))
}
},
Payload::Brush(_) => Ok(()),
Payload::Style(style) if app.session.active().is_some_and(|st| st.uid == style.document) => {
let Some(hit) = hit() else { return Ok(()) };
let top = top_object(app, &hit)?;
run(app, "graphicStyle.apply", json!({"name": style.name, "ids": [top], "add": drop.op == DropOperation::Copy}))
}
Payload::Style(_) => Ok(()),
Payload::Panel(PanelDrag::Paint { params, paint, .. }) if !params.is_null() => {
Payload::Panel(drag @ PanelDrag::Paint { params, paint, rows, .. }) if !params.is_null() => {
if let Some(color) = paint.color()
&& crate::panels::proxy_cmd(app, false) == "paint.setFill"
&& let Some((id, points)) = selected_mesh_drop(app, at, zoom)
@@ -359,7 +362,14 @@ pub(crate) fn apply_drop(app: &mut VectorcraftApp, drop: &Dropped) -> Result<(),
return run(app, "object.mesh.setPointColor", params);
}
let Some(hit) = hit() else { return Ok(()) };
let mut params = params.clone();
let destination = app.session.active().map(|st| st.uid);
if rows.as_ref().is_some_and(|rows| !rows.unlinked_process_color && destination.is_some_and(|uid| uid != rows.document))
&& paint.color().is_some()
&& !paint.is_registration()
{
return Err(tl!("A linked color swatch can only be applied in its own document.").into());
}
let Some(mut params) = drag.paint_drop_params(destination) else { return Ok(()) };
params["ids"] = json!([owner(app, &hit)?]);
params["focus"] = json!(false);
let cmd = crate::panels::proxy_cmd(app, false);
+159 -1
View File
@@ -10,7 +10,7 @@ use vectorcraft_engine::Session;
use vectorcraft_geom::Point;
use super::{CarriedArt, Dropped, Payload, apply_drop};
use crate::panel_drag::PanelDrag;
use crate::panel_drag::{PanelDrag, SwatchRows};
use crate::panels::brushes::{BrushKey, BrushLibraries};
use crate::panels::graphic_styles::StyleDrag;
use crate::panels::library_panel::{self, LibraryKey, LibraryKind as _};
@@ -202,6 +202,32 @@ fn a_drop_runs_the_effect_of_its_payload() {
symbol_at(&app, empty);
}
#[test]
fn a_foreign_brush_drop_never_applies_or_places_a_same_named_brush() {
let (mut app, ctx) = app_with_canvas();
let make_brush = |app: &mut VectorcraftApp, width| {
app.run("shape.rectangle", json!({"x": 15, "y": 15, "width": width, "height": 30})).unwrap();
app.run("brush.new", json!({"name": "Shared Brush", "type": "art"})).unwrap();
};
make_brush(&mut app, 30);
let document = app.session.active().unwrap().uid;
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
make_brush(&mut app, 60);
app.run("brush.setCurrent", json!({"name": null})).unwrap();
let path = NodeId(app.run("path.create", json!({"anchors": [{"x": 50, "y": 200}, {"x": 350, "y": 200}]})).unwrap()["id"].as_u64().unwrap());
frame(&mut app, &ctx, vec![]);
let brush_of = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(path).unwrap().appearance.stroke().and_then(|s| s.brush.clone());
let before = brush_of(&app);
assert!(before.is_none());
let history = undo_len(&app);
let payload = Payload::Brush(BrushKey { doc: document, name: "Shared Brush".into(), group: false });
drop_at(&mut app, payload.clone(), Point::new(200.0, 200.0), DropOperation::Move).unwrap();
assert_eq!(brush_of(&app), before, "the foreign drop leaves the path's stroke alone");
drop_at(&mut app, payload, Point::new(200.0, 260.0), DropOperation::Move).unwrap();
assert_eq!(undo_len(&app), history, "no artwork is placed on empty canvas either");
}
/// A symbol of another document is added here and placed in one undo step, the source is unchanged, and a symbol of
/// a closed document places nothing.
#[test]
@@ -230,6 +256,138 @@ fn a_symbol_from_another_document_is_added_and_placed_in_one_step() {
/// A colour dropped on a selected mesh recolors the point under the pointer, else the patch's four points; the same
/// colour again records no step.
#[test]
fn a_process_swatch_canvas_drop_keeps_its_color_in_another_document() {
let (mut app, ctx) = app_with_canvas();
let name = "Shared Swatch";
let at = Point::new(250.0, 70.0);
let add_target = |app: &mut VectorcraftApp| {
NodeId(app.run("shape.rectangle", json!({"x": 200, "y": 20, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap())
};
let fill = |app: &VectorcraftApp, target| app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint();
app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap();
let source = app.session.active().unwrap();
let paint = source.doc.swatch(name).unwrap().paint.clone();
let rows = SwatchRows { document: source.uid, grabbed: name.into(), names: vec![name.into()], groups: false, unlinked_process_color: true };
let payload = PanelDrag::Paint { paint: paint.clone(), params: json!({"swatch": name}), rows: Some(rows), library: None };
let local_target = add_target(&mut app);
app.run("swatch.edit", json!({"name": name, "color": "#ff8800"})).unwrap();
let edited = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone();
drop_at(&mut app, Payload::Panel(payload.clone()), at, DropOperation::Move).unwrap();
assert_eq!(fill(&app, local_target), edited, "a same-document drop still resolves the swatch by name");
assert_ne!(edited, paint);
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("swatch.new", json!({"name": name, "color": "#0000ff"})).unwrap();
let destination = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone();
let target = add_target(&mut app);
app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap();
frame(&mut app, &ctx, vec![]);
drop_at(&mut app, Payload::Panel(payload), at, DropOperation::Move).unwrap();
assert_eq!(fill(&app, target), paint);
assert_eq!(app.session.active().unwrap().doc.swatch(name).unwrap().paint, destination);
}
#[test]
fn a_swatch_drag_keeps_its_color_after_next_document() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
use craft::ui::runtime::drag;
use egui::{Key, Modifiers};
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let name = "Shared Swatch";
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("swatch.new", json!({"name": name, "color": "#ff0000"})).unwrap();
let source = app.session.active().unwrap().doc.swatch(name).unwrap().paint.clone();
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("swatch.new", json!({"name": name, "color": "#0000ff"})).unwrap();
let target = NodeId(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap());
app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap();
let destination = app.session.active().unwrap().uid;
app.run("window.previousDocument", json!({})).unwrap();
let mut panel = Panel::new(app, |app, ui| {
app.sync_views();
ui.allocate_ui_with_layout(egui::vec2(280.0, 480.0), egui::Layout::top_down(egui::Align::Min), |ui| {
crate::panels::swatches::show(app, ui);
});
canvas::show(app, ui);
});
let label = "Shared Swatch, #ff0000";
let from = panel.rect(label).center();
let to = panel.app().canvas_view().unwrap().to_screen(Point::new(100.0, 100.0));
panel.drag_hold_role(label, Role::LIST_ITEM, to - from);
assert!(drag::active::<PanelDrag>(panel.ctx()).is_some(), "the Swatches row starts a paint drag");
panel.key(Key::F6, Modifiers::COMMAND);
assert_eq!(panel.app().session.active().unwrap().uid, destination);
assert!(drag::active::<PanelDrag>(panel.ctx()).is_some(), "the drag stays held during Next Document");
panel.release();
let app = panel.app();
assert_eq!(app.session.active().unwrap().doc.node(target).unwrap().appearance.fill_paint(), source);
}
#[test]
fn linked_swatch_drops_stay_in_their_source_document() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
use craft::ui::runtime::drag;
use egui::{Key, Modifiers};
for spot in [false, true] {
for (different_drawing, same_name) in [(false, false), (true, false), (true, true)] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let name = "Shared Swatch";
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("swatch.new", json!({"name": name, "color": "#ff0000", "global": true, "spot": spot})).unwrap();
if different_drawing {
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
}
if same_name {
app.run("swatch.new", json!({"name": name, "color": "#0000ff", "global": true})).unwrap();
}
let target = NodeId(app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap());
app.run("paint.setFill", json!({"color": "#00ff00"})).unwrap();
let destination = app.session.active().unwrap().uid;
if different_drawing {
app.run("window.previousDocument", json!({})).unwrap();
}
let mut panel = Panel::new(app, |app, ui| {
app.sync_views();
ui.allocate_ui_with_layout(egui::vec2(280.0, 480.0), egui::Layout::top_down(egui::Align::Min), |ui| {
crate::panels::swatches::show(app, ui);
});
canvas::show(app, ui);
});
let label = "Shared Swatch, #ff0000";
let from = panel.rect(label).center();
let to = panel.app().canvas_view().unwrap().to_screen(Point::new(100.0, 100.0));
panel.drag_hold_role(label, Role::LIST_ITEM, to - from);
assert!(drag::active::<PanelDrag>(panel.ctx()).is_some(), "the Swatches row starts a paint drag");
if different_drawing {
panel.key(Key::F6, Modifiers::COMMAND);
}
assert_eq!(panel.app().session.active().unwrap().uid, destination);
assert!(drag::active::<PanelDrag>(panel.ctx()).is_some(), "the drag stays active");
panel.release();
let app = panel.app();
let doc = &app.session.active().unwrap().doc;
let fill = doc.node(target).unwrap().appearance.fill_paint();
if different_drawing {
assert_eq!(fill, Paint::solid(Color::rgb8(0, 255, 0)), "the destination fill stays unchanged");
assert_eq!(app.ui.status, "A linked color swatch can only be applied in its own document.");
assert_eq!(doc.swatch(name).and_then(|s| s.paint.color()), same_name.then_some(Color::rgb8(0, 0, 255)));
} else {
assert_eq!(fill, doc.tint_paint(name, 1.0).unwrap(), "the fill remains linked to its swatch");
}
}
}
}
#[test]
fn a_color_dropped_on_a_selected_mesh_recolors_the_point_or_patch_under_it() {
use vectorcraft_doc::GradientMesh;
+21
View File
@@ -87,6 +87,8 @@ fn thumbnails(ctx: &egui::Context) -> Thumbnails<PaneKey> {
pub struct Panes {
/// The panes the last frame drew, as (window, pane rect).
pub(crate) last: Vec<(Win, egui::Rect)>,
/// The UI layer that drew the last tiled canvases.
last_layer: Option<egui::LayerId>,
/// The slots of `last`'s windows, in the same order: which windows they were, as document
/// indices shift when a document closes.
last_slots: Vec<Option<Slot>>,
@@ -110,6 +112,7 @@ impl Panes {
/// Forget every pane. The pictures go with the next frame that does not tile.
fn clear(&mut self) {
self.last.clear();
self.last_layer = None;
self.last_slots.clear();
self.fits.clear();
self.at = SplitAt::default();
@@ -322,6 +325,7 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
app.canvas.panes.fits.clear();
}
app.canvas.panes.last.clear();
app.canvas.panes.last_layer = None;
app.canvas.panes.last_slots.clear();
return false;
}
@@ -361,8 +365,10 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
let mut lines = std::mem::take(&mut app.canvas.panes.at);
let placed = lines.clone();
let mut cells: Vec<(Win, egui::Rect)> = vec![];
let mut layer = None;
let split = SplitViews::new("Documents", arranged, Bind::bound(&mut lines)).count(shown.len()).active(active_pane).show(ui, |ui, body| {
cells = shown.iter().copied().zip(placed.placed(arranged, shown.len(), body.rect, body.env.direction().is_rtl())).collect();
layer = Some(ui.layer_id());
let areas: Vec<(Win, egui::Rect)> = cells.iter().map(|(w, cell)| (*w, art_area(app, *w, *cell))).collect();
let unfitted = refit_resized(app, &areas);
// The other panes first, so that what the canvas draws past its pane (the Contextual Task Bar)
@@ -381,6 +387,7 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool {
let activated = split.output.activated;
app.canvas.panes.at = lines;
app.canvas.panes.last = cells;
app.canvas.panes.last_layer = layer;
if let Some(&(w, _)) = activated.and_then(|i| app.canvas.panes.last.get(i)) {
crate::doc_windows::show_window(app, w);
}
@@ -410,6 +417,20 @@ fn slot(app: &VectorcraftApp, (i, n): Win) -> Option<Slot> {
app.session.documents().get(i).map(|d| (d.uid, n))
}
/// The drawing and document point under a browser file drop in the last shown tiled panes.
pub(crate) fn file_drop_at(app: &VectorcraftApp, pos: egui::Pos2) -> Option<(u64, Point)> {
let panes = &app.canvas.panes;
let layer = panes.last_layer?;
if app.ui_ctx.as_ref().and_then(|ctx| ctx.layer_id_at(pos)).is_some_and(|front| front != layer) {
return None;
}
panes.last.iter().zip(&panes.last_slots).find_map(|(&(win, cell), &shown)| {
let (doc, _) = shown.filter(|&shown| Some(shown) == slot(app, win) && cell.contains(pos))?;
let view = crate::doc_windows::view(app, win)?;
view.rect.contains(pos).then(|| (doc, view.canvas(app.ui_scaling(), view.rect).to_doc(pos)))
})
}
/// The area window `w`'s view shows its art in: what its body last showed, `cell` before the first.
fn art_area(app: &VectorcraftApp, w: Win, cell: egui::Rect) -> egui::Rect {
crate::doc_windows::view(app, w).map(|v| v.rect).filter(|r| r.is_positive()).unwrap_or(cell)
+76 -23
View File
@@ -55,12 +55,16 @@ pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered) -> egui::Colo
/// frame. A frame the worker rendered is drawn again here too, so an edit (a Pen drag's curve)
/// shows in the frame it is made in, when the part's share of the frame's last whole render time
/// is at most 8 ms, and except when that frame drew raster effects from rasters made before their
/// objects moved ([`crate::CanvasCache::moved`]), holds pixels copied from the worker's last frame
/// ([`crate::CanvasCache::reused`]), drew art in a way that depends on its size, or a part drawn
/// again here since it arrived would have differed from it ([`crate::CanvasCache::worker_parts`]):
/// the worker's renderer keeps the rasters of the art's effects, and this thread's doesn't. What
/// changed is measured by this thread's renderer: it keeps what it measures (a 3D effect's art) to
/// draw the part again.
/// objects moved ([`crate::CanvasCache::moved`]) or holds pixels copied from the worker's last frame
/// ([`crate::CanvasCache::reused`]): the worker's renderer keeps the rasters of the art's effects,
/// and this thread's doesn't. A web frame with known view-sensitive output bounds can still be
/// patched outside them, accounting for the patch's rounding. Otherwise view-sensitive art or
/// an earlier rejected patch requires a whole render ([`crate::CanvasCache::whole_frames`]).
/// A frame that drew nothing from moved rasters or at a
/// drag's lower resolution can supply the unchanged pixels when a Pen press starts an interaction
/// over a worker frame, even when [`CacheKey::interacting`] and [`CacheKey::dragging`] change.
/// Leaving an interaction still replaces the whole frame. What changed is measured by this thread's renderer: it keeps what
/// it measures (a 3D effect's art) to draw the part again.
pub(super) fn changed_pixels(
app: &mut VectorcraftApp,
key: &CacheKey,
@@ -70,14 +74,20 @@ pub(super) fn changed_pixels(
w: u32,
h: u32,
) -> Option<Option<[u32; 4]>> {
let (shown, _) = app.canvas.shown.as_ref().filter(|(_, o)| o == opts)?;
let shown_key = app.canvas.key.as_ref()?;
// The worker keeps its still rasters while the UI thread draws the first edit. Rendering only
// part of a UI-thread frame could evict its own still rasters before a drag needs them.
let starting = app.canvas.from_worker && !app.canvas.moved && key.interacting && !shown_key.interacting;
let (shown, _) = app.canvas.shown.as_ref().filter(|(_, o)| {
o == opts || starting && vectorcraft_render::RenderOptions { interacting: opts.interacting, dragging: opts.dragging, ..o.clone() } == *opts
})?;
// A viewed opacity mask shows its coverage wherever its art reaches, past its object's bounds.
if opts.mask_view.is_some() {
return None;
}
let shown_key = app.canvas.key.as_ref()?;
let same_view = *shown_key == CacheKey { revision: shown_key.revision, placed: shown_key.placed, ..key.clone() };
let worker_kept = app.canvas.from_worker && (app.canvas.moved || app.canvas.worker_parts || app.canvas.reused.is_some());
let (interacting, dragging) = if starting { (shown_key.interacting, shown_key.dragging) } else { (key.interacting, key.dragging) };
let same_view = *shown_key == CacheKey { revision: shown_key.revision, placed: shown_key.placed, interacting, dragging, ..key.clone() };
let worker_kept = app.canvas.from_worker && (app.canvas.moved || app.canvas.reused.is_some());
// A frame on its way of an older revision is not shown when it arrives ([`show_worker_frame`]).
let on_its_way = app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|p| p.doc != key.doc || p.revision >= key.revision);
if !same_view || app.canvas.texture.is_none() || worker_kept || on_its_way {
@@ -94,6 +104,14 @@ pub(super) fn changed_pixels(
None => Some(None),
Some([x0, y0, x1, y1]) => {
let ((x0, x1), (y0, y1)) = (in_steps(x0, x1, w), in_steps(y0, y1, h));
let patch = Rect::new(f64::from(x0), f64::from(y0), f64::from(x1), f64::from(y1));
if app.canvas.whole_frames && app.canvas.view_sized_bounds.is_none_or(|bounds| !bounds.intersect(patch).is_zero_area()) {
return None;
}
// A full draw can use 3D art measured here. Do not rebuild it in the scratch renderer.
if app.canvas.view_sized_bounds.is_some() && app.canvas.renderer.measured_bytes() > 0 {
return None;
}
let share = (f64::from(x1 - x0) * f64::from(y1 - y0)) / (f64::from(w) * f64::from(h));
(share <= budget.min(0.5)).then_some(Some([x0, y0, x1, y1]))
}
@@ -102,6 +120,14 @@ pub(super) fn changed_pixels(
}
}
fn web_patch_renderer(slot: &mut Option<Box<vectorcraft_render::Renderer>>) -> &mut vectorcraft_render::Renderer {
slot.get_or_insert_with(|| {
let mut renderer = vectorcraft_render::Renderer::new();
renderer.threads = 0;
Box::new(renderer)
})
}
/// `a..b` of `0..n`, grown to whole eighths of `n` and moved back into `0..n`: the parts of a
/// frame rendered again come in few sizes, which keep the contexts the renderer keeps.
fn in_steps(a: u32, b: u32, n: u32) -> (u32, u32) {
@@ -597,7 +623,9 @@ fn show_worker_frame(app: &mut VectorcraftApp, ctx: &egui::Context, done: crate:
app.canvas.reused = done.reused.then(|| frame::clock(ctx));
app.canvas.moved = done.moved > 0;
app.canvas.from_worker = true;
app.canvas.worker_parts = done.view_sized;
app.canvas.whole_frames = done.view_sized;
app.canvas.view_sized_bounds = None;
app.canvas.web_patch_renderer = None;
}
/// The size and view matrix of the frame to render: the pixel region in Pixel Preview, else the whole canvas.
@@ -686,25 +714,38 @@ pub(crate) const FIRST_FRAME_GRACE: std::time::Duration = std::time::Duration::f
/// key: only the document changed since the frame shown, in that part of it
/// ([`changed_pixels`]). `None`: nothing in view changed. `last_ms` stays the whole frame's.
///
/// Over a frame the worker rendered, a part that drew raster effects from rasters made before
/// their objects moved or at a drag's lower resolution ([`vectorcraft_render::FrameStats::moved`]),
/// or art in a way that depends on the frame's size ([`vectorcraft_render::FrameStats::view_sized`]),
/// would not match the frame around it: it is not drawn, false is returned, and the edits after it
/// render on the worker until the worker's next frame is shown ([`crate::CanvasCache::worker_parts`]).
/// A part that drew art in a way that depends on the frame's size
/// ([`vectorcraft_render::FrameStats::view_sized`]), draws effects at a drag's lower resolution
/// ([`vectorcraft_render::FrameStats::previewed`]), or uses this thread's moved rasters over a
/// worker frame, could differ from the frame around it. It is not drawn, false is returned,
/// and the edits after it render whole until the next whole frame is
/// shown ([`crate::CanvasCache::whole_frames`]).
fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]>) -> bool {
let Frame { key, doc, effects, view, opts, pixel, .. } = frame;
let t0 = monotonic_ms();
if region.is_none() {
// Nothing in view to draw again: what was made to measure the edit isn't drawn.
app.canvas.renderer.let_go_of_measured();
app.canvas.renderer.finish_measurement_only();
}
let display = app.display_profile.transform(app.session.prefs.monitor_profile_display);
if let (Some([x0, y0, x1, y1]), Some(tex)) = (region, &mut app.canvas.texture) {
let renderer = &mut app.canvas.renderer;
let part_view = Affine::translate((-f64::from(x0), -f64::from(y0))) * *view;
let mut part = effects.view(|| renderer.render(doc, x1 - x0, y1 - y0, part_view, opts));
if app.canvas.from_worker && (renderer.stats.moved > 0 || renderer.stats.view_sized > 0) {
app.canvas.worker_parts = true;
let plain_patch = app.canvas.view_sized_bounds.is_some();
let renderer = if plain_patch { web_patch_renderer(&mut app.canvas.web_patch_renderer) } else { &mut app.canvas.renderer };
let part = effects.view(|| {
if plain_patch {
renderer.render_plain_patch(doc, x1 - x0, y1 - y0, part_view, opts)
} else {
Some(renderer.render(doc, x1 - x0, y1 - y0, part_view, opts))
}
});
let Some(mut part) = part else {
app.canvas.view_sized_bounds = None;
return false;
};
if renderer.stats.view_sized > 0 || renderer.stats.previewed > 0 || app.canvas.from_worker && renderer.stats.moved > 0 {
app.canvas.whole_frames = true;
app.canvas.view_sized_bounds = None;
return false;
}
let width = part.width;
@@ -712,7 +753,10 @@ fn draw_changed(app: &mut VectorcraftApp, frame: &Frame, region: Option<[u32; 4]
let color = color_image(&part);
let options = if pixel.is_some() { egui::TextureOptions::NEAREST } else { egui::TextureOptions::LINEAR };
tex.set_partial([x0 as usize, y0 as usize], color, options);
app.canvas.moved |= app.canvas.renderer.stats.moved > 0;
app.canvas.moved |= renderer.stats.moved > 0;
if plain_patch {
app.canvas.renderer.finish_measurement_only();
}
}
app.canvas.key = Some((*key).clone());
app.canvas.shown = Some(((*doc).clone(), opts.clone()));
@@ -768,6 +812,9 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
// thread's renderer has none, so a frame fast on the worker would be slow here. An edit in a
// part of the frame shown is drawn again here, unless that part would differ ([`draw_changed`]).
let same_doc = app.canvas.key.as_ref().is_some_and(|k| k.doc == key.doc);
if !same_doc {
app.canvas.web_patch_renderer = None;
}
let settling = app.canvas.moved && !key.interacting;
let staying = key.interacting && app.canvas.from_worker;
// A document's first frame (opened, or its tab chosen) renders on the worker too: how long it
@@ -791,7 +838,7 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
(Some(worker), true, false) => {
// The worker draws the frame: what this thread's renderer made to measure the edit
// isn't drawn here.
app.canvas.renderer.let_go_of_measured();
app.canvas.renderer.finish_measurement_only();
let queued = worker.submit(crate::render_worker::Job {
key: key.clone(),
doc: doc.clone(),
@@ -824,6 +871,12 @@ fn draw_frame(app: &mut VectorcraftApp, ui: &Ui, frame: Frame) {
app.perf.render_ms = monotonic_ms() - t0;
app.canvas.last_ms = app.perf.render_ms;
app.canvas.moved = app.canvas.renderer.stats.moved > 0;
let stats = app.canvas.renderer.stats;
app.canvas.whole_frames = stats.view_sized > 0 || stats.previewed > 0;
app.canvas.view_sized_bounds = if app.canvas.waits_for_still && stats.previewed == 0 { stats.view_sized_bounds() } else { None };
if app.canvas.view_sized_bounds.is_none() {
app.canvas.web_patch_renderer = None;
}
app.canvas.from_worker = false;
app.canvas.reused = None;
}
+231 -19
View File
@@ -899,6 +899,48 @@ fn halftone_preview_hides_dot_outlines_and_keeps_selection_bounds() {
assert!(outlined(&mut app), "OK brings ordinary outlines back on the applied dots");
}
#[test]
fn halftone_waits_for_the_drawing_that_opened_the_preview() {
use crate::dialogs::{halftone, host};
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
let ctx = app.ui_ctx.clone().unwrap();
let draw = |app: &mut VectorcraftApp, x| {
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("shape.ellipse", json!({"x": x, "y": 40, "width": 60, "height": 40})).unwrap();
app.run("paint.setFill", json!({"color": "#000000"})).unwrap();
};
draw(&mut app, 40);
let first = app.session.doc().unwrap().doc.clone();
draw(&mut app, 200);
let second = app.session.doc().unwrap().doc.clone();
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("ui.menuDialog", json!({"command": halftone::CMD})).unwrap();
host::pump(&mut app, &ctx);
assert!(halftone::previewing(&app));
let id = app.effect_dialogs.halftone.as_ref().unwrap().id;
app.run("document.activate", json!({"index": 1})).unwrap();
app.session.begin_interaction("Other drawing's edit").unwrap();
let dialogs = app.dialogs().unwrap();
dialogs.with(|h| h.set_json_field(&ctx, id, "frequency", json!(25))).unwrap();
host::pump(&mut app, &ctx);
assert_eq!(app.session.doc().unwrap().doc, second);
assert_eq!(app.session.doc().unwrap().interaction.as_ref().unwrap().label, "Other drawing's edit");
dialogs.with(|h| h.confirm_by_id(&ctx, id));
host::pump(&mut app, &ctx);
assert!(app.any_dialog_open());
assert_eq!(app.session.doc().unwrap().doc, second);
app.run("document.activate", json!({"index": 0})).unwrap();
host::pump(&mut app, &ctx);
assert!(halftone::previewing(&app));
crate::tests::picks::answer_dialog(&mut app, id, &[], true);
assert!(!app.any_dialog_open());
assert_ne!(app.session.doc().unwrap().doc, first);
assert_eq!(app.session.documents()[1].doc, second);
}
// One headless canvas frame → the shapes drawn, `Shape::Vec`s flattened.
fn shapes(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<Shape> {
let (shapes, mut delta) = frame_output(app, ctx);
@@ -964,6 +1006,144 @@ fn an_edit_renders_only_its_part_of_the_canvas() {
assert!(canvas(&app, delta).is_some_and(|(pos, _)| pos.is_none()), "a new view renders all of it");
}
/// An edit over art that a part of the canvas would draw with other pixels than the whole canvas
/// does ([`vectorcraft_render::FrameStats::view_sized`]) renders all of it, on this thread too,
/// and shows what a fresh renderer draws: a blur cropped to the view, which the frame shown drew,
/// and an inner glow that fits the view but not the part the edit changed.
#[test]
fn an_edit_over_art_drawn_for_the_frames_size_renders_all_of_it() {
keeping_color_settings(an_edit_over_art_drawn_for_the_frames_size);
}
fn an_edit_over_art_drawn_for_the_frames_size() {
for cropped in [true, false] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.ui.task_bar = false;
app.ui.view.rulers = false;
app.canvas.worker_started = true; // every frame on this thread, however long it takes
app.canvas.renderer.threads = 2;
let (rect, effect) = if cropped {
(json!({"x": 0, "y": 0, "width": 400, "height": 300}), json!({"effect": "blur.gaussian", "params": {"radius": 8}}))
} else {
(json!({"x": 150, "y": 110, "width": 100, "height": 80}), json!({"effect": "stylize.innerGlow", "params": {"blur": 8}}))
};
let art = app.run("shape.rectangle", rect).unwrap()["id"].clone();
let mut effect = effect;
effect["ids"] = json!([art]);
app.run("effect.apply", effect).unwrap();
let id = app.run("shape.rectangle", json!({"x": 145, "y": 105, "width": 10, "height": 10})).unwrap()["id"].clone();
let outside = app.run("shape.rectangle", json!({"x": 5000, "y": 5000, "width": 10, "height": 10})).unwrap()["id"].clone();
app.run("select.none", json!({})).unwrap();
let ctx = crate::testing::ui_context();
shapes(&mut app, &ctx);
// A new view: the next frame renders whole.
if let Some(vm) = app.view_mut() {
(vm.zoom, vm.center) = if cropped { (16.0, Point::new(150.0, 110.0)) } else { (1.5, Point::new(200.0, 150.0)) };
}
// Where the canvas texture changed in a frame, and its pixels there.
let canvas = |app: &VectorcraftApp, mut delta: egui::TexturesDelta| {
let tex = app.canvas.texture.as_ref().map(|t| t.id());
let set = delta.set.iter().find(|(t, _)| tex == Some(**t)).and_then(|(_, d)| d.last()).map(|d| {
let egui::ImageData::Color(img) = &d.image;
(d.pos, img.pixels.clone())
});
delta.clear();
set
};
let (_, delta) = frame_output(&mut app, &ctx);
assert!(canvas(&app, delta).is_some_and(|(pos, _)| pos.is_none()), "the first frame renders all of it");
assert_eq!(app.canvas.renderer.stats.view_sized > 0, cropped, "the frame shown drew art for its size: {cropped}");
assert_eq!(app.canvas.whole_frames, cropped, "the frame records whether its art depends on its size");
app.run("paint.setFill", json!({"color": "#00ff00", "ids": [outside]})).unwrap();
let (_, delta) = frame_output(&mut app, &ctx);
assert!(canvas(&app, delta).is_none(), "an edit outside the view does not upload a new canvas");
app.run("paint.setFill", json!({"color": "#ff0000", "ids": [id]})).unwrap();
let (_, delta) = frame_output(&mut app, &ctx);
let (pos, edited) = canvas(&app, delta).expect("the edit shows");
assert!(pos.is_none(), "the edit renders all of it, cropped: {cropped}");
assert_eq!(app.canvas.whole_frames, cropped, "the replacement records its own render stats");
app.canvas.renderer = vectorcraft_render::Renderer::new();
app.canvas.renderer.threads = 2;
app.canvas.key = None;
let (_, delta) = frame_output(&mut app, &ctx);
let fresh = canvas(&app, delta).map(|(_, px)| px);
assert!(fresh.as_ref() == Some(&edited), "what a fresh renderer draws, cropped {cropped}: {}", differing(&edited, fresh.as_deref()));
}
}
#[test]
fn web_partial_redraws_skip_unchanged_view_sensitive_art() {
keeping_color_settings(|| {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 300, "colorMode": "rgb"})).unwrap();
app.ui.task_bar = false;
app.ui.view.rulers = false;
app.canvas.worker_started = true;
app.canvas.waits_for_still = true;
app.canvas.renderer.threads = 0;
let glow = app.run("shape.rectangle", json!({"x": 55, "y": 70, "width": 55, "height": 55})).unwrap()["id"].clone();
app.run("effect.apply", json!({"ids": [glow], "effect": "stylize.innerGlow", "params": {"blur": 8}})).unwrap();
let large = app.run("shape.rectangle", json!({"x": -980, "y": -700, "width": 965, "height": 1010})).unwrap()["id"].clone();
app.run("effect.apply", json!({"ids": [large], "effect": "texture.texturizer", "params": {}})).unwrap();
let far = app.run("shape.rectangle", json!({"x": 300, "y": 200, "width": 12, "height": 12})).unwrap()["id"].clone();
let near = app.run("shape.rectangle", json!({"x": 60, "y": 80, "width": 12, "height": 12})).unwrap()["id"].clone();
app.run("paint.setFill", json!({"ids": [near], "color": "#ffffff"})).unwrap();
app.run("select.none", json!({})).unwrap();
let ctx = crate::testing::ui_context();
shapes(&mut app, &ctx);
if let Some(vm) = app.view_mut() {
(vm.zoom, vm.center) = (1.2, Point::new(200.0, 150.0));
}
// Start from a full raster at the chosen view rather than waiting for the reprojected view to settle.
app.canvas.key = None;
let read = |app: &mut VectorcraftApp| {
let (_, mut delta) = frame_output(app, &ctx);
let tex = app.canvas.texture.as_ref().unwrap().id();
delta.set.remove(&tex).and_then(|mut uploads| uploads.pop()).expect("the edit uploads canvas pixels")
};
let first = read(&mut app);
assert!(first.pos.is_none());
assert!(app.canvas.renderer.stats.view_sized > 0, "single-threaded filter layers depend on the frame size");
let egui::ImageData::Color(first) = first.image;
let mut composed = (*first).clone();
for color in ["#ff0000", "#00ff00"] {
app.run("paint.setFill", json!({"ids": [far], "color": color})).unwrap();
let delta = read(&mut app);
let [x, y] = delta.pos.expect("an edit away from the glow uploads only a patch");
let egui::ImageData::Color(patch) = delta.image;
for row in 0..patch.height() {
let start = (y + row) * composed.width() + x;
composed.pixels[start..start + patch.width()].copy_from_slice(&patch.pixels[row * patch.width()..(row + 1) * patch.width()]);
}
}
let key = app.canvas.key.as_ref().unwrap();
let view = app.canvas_view().unwrap();
let (w, h, view) = frame_view(key.pixel, (key.w, key.h), &view, key.ppp);
let (doc, still) = app.canvas.shown.as_ref().unwrap();
let drag = vectorcraft_render::RenderOptions { interacting: true, dragging: true, ..still.clone() };
let mut cold = vectorcraft_render::Renderer::new();
cold.threads = 0;
cold.render(doc, w, h, view, &drag);
assert!(cold.stats.previewed > 0, "a cold renderer draws the large effect at drag resolution");
app.canvas.renderer.render(doc, w, h, view, &drag);
assert_eq!(app.canvas.renderer.stats.previewed, 0, "distant canvas patches left the full-resolution effect available for the drag");
// The old glow's bounds survive successive partial renders, even though neither draws it.
app.run("paint.setFill", json!({"ids": [near], "color": "#0202ee"})).unwrap();
let overlap = read(&mut app);
assert!(overlap.pos.is_none(), "editing inside the old glow's bounds renders the whole frame");
app.run("paint.setFill", json!({"ids": [near], "color": "#ffffff"})).unwrap();
let restored = read(&mut app);
assert!(restored.pos.is_none());
let egui::ImageData::Color(restored) = restored.image;
assert_eq!(restored.size, composed.size);
assert!(restored.pixels == composed.pixels, "partial updates equal a full redraw: {}", differing(&composed.pixels, Some(&restored.pixels)));
app.run("effect.apply", json!({"ids": [far], "effect": "stylize.innerGlow", "params": {"blur": 8}})).unwrap();
assert!(read(&mut app).pos.is_none(), "the new glow in the part also requires a whole frame");
});
}
/// A canvas more device pixels across than the largest texture side the display supports renders
/// its art at fewer pixels a point, within that size, and draws it over the whole canvas. Pixel
/// Preview's region of document pixels stays within it too.
@@ -1737,10 +1917,15 @@ fn dragging_with_raster_effects() {
/// without a drag, renders without `dragging` and draws the same.
#[test]
fn a_drag_on_the_canvas_draws_raster_effects_at_a_lower_resolution() {
keeping_color_settings(a_drag_at_a_lower_resolution);
keeping_color_settings(|| a_drag_at_a_lower_resolution(false));
}
fn a_drag_at_a_lower_resolution() {
#[test]
fn a_whole_drag_preview_keeps_the_next_canvas_render_whole() {
keeping_color_settings(|| a_drag_at_a_lower_resolution(true));
}
fn a_drag_at_a_lower_resolution(fits_frame: bool) {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
app.canvas.worker_started = true; // render on this thread
@@ -1763,7 +1948,7 @@ fn a_drag_at_a_lower_resolution() {
};
run(&mut app, vec![]);
if let Some(vm) = app.view_mut() {
(vm.zoom, vm.center) = (32.0, Point::new(200.0, 155.0));
(vm.zoom, vm.center) = (if fits_frame { 6.4 } else { 32.0 }, Point::new(200.0, 155.0));
}
let still = run(&mut app, vec![]).expect("the zoomed view renders");
assert_eq!(app.canvas.renderer.stats.previewed, 0, "a still frame");
@@ -1771,10 +1956,19 @@ fn a_drag_at_a_lower_resolution() {
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
run(&mut app, vec![egui::Event::PointerMoved(at)]);
run(&mut app, vec![button(at, true)]);
if fits_frame {
// Force the first move to draw a whole frame without a previous effect raster.
app.canvas.renderer = vectorcraft_render::Renderer::new();
app.canvas.key = None;
}
for step in [1.0, 2.0] {
let drawn = run(&mut app, vec![egui::Event::PointerMoved(at + vec2(13.0, 7.0) * step)]).expect("each frame of the drag renders");
assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting && k.dragging), "step {step}");
assert_eq!(app.canvas.renderer.stats.previewed, 1, "the filtered content, step {step}");
if fits_frame {
assert_eq!(app.canvas.renderer.stats.view_sized, 0, "only the drag budget reduced the raster");
assert!(app.canvas.whole_frames, "a whole drag preview cannot accept a full-resolution patch");
}
assert!(app.canvas.moved);
assert!(drawn != still, "the rectangle moved, step {step}");
}
@@ -1788,9 +1982,15 @@ fn a_drag_at_a_lower_resolution() {
assert!(fresh.as_ref() == Some(&after), "the frame after the drag is what a fresh renderer draws: {}", differing(&after, fresh.as_deref()));
// A dialog's preview: an interaction, and no drag.
app.session.begin_interaction("Texturizer").unwrap();
assert!(run(&mut app, vec![]) == Some(after), "a dialog's preview draws the effect at full resolution");
app.session.preview("effect.setParams", &json!({"index": 0, "item": null, "ids": [id], "params": {"relief": 20}})).unwrap();
let preview = run(&mut app, vec![]).expect("the preview renders");
assert!(preview != after, "the preview changes the art");
assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting && !k.dragging));
assert_eq!(app.canvas.renderer.stats.previewed, 0);
app.canvas.renderer = vectorcraft_render::Renderer::new();
app.canvas.key = None;
let fresh = run(&mut app, vec![]);
assert!(fresh.as_ref() == Some(&preview), "a dialog's preview draws the effect at full resolution: {}", differing(&preview, fresh.as_deref()));
}
/// Where frame `b` differs from `a`: how many pixels, the first, and the largest channel difference.
@@ -1885,10 +2085,10 @@ fn a_drag_over_a_wide_blur() {
}
}
/// An interaction's frames stay on the worker once it drew the frame shown, however fast that
/// frame was: the worker's renderer keeps the effect rasters that made it fast, and this
/// thread's renderer, without them, would draw the next frame slowly. Without a frame from the
/// worker, a fast frame renders on this thread as before.
/// An interaction's whole frames (here after a new zoom) stay on the worker once it drew the frame
/// shown, however fast that frame was: the worker's renderer keeps the effect rasters that made it
/// fast, and this thread's renderer, without them, would draw the next frame slowly. Without a
/// frame from the worker, a fast frame renders on this thread as before.
#[test]
fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
@@ -1901,6 +2101,9 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() {
app.canvas.worker = crate::render_worker::Worker::spawn(ctx.clone());
(app.canvas.from_worker, app.canvas.last_ms) = (from_worker, 1.0);
app.session.begin_interaction("Preview").unwrap();
if let Some(vm) = app.view_mut() {
vm.zoom *= 1.25;
}
shapes(&mut app, &ctx);
let pending = app.canvas.worker.as_ref().and_then(|w| w.pending.as_ref()).is_some_and(|k| k.interacting);
assert_eq!(pending, from_worker, "sent to the worker: {from_worker}");
@@ -1913,9 +2116,9 @@ fn an_interaction_stays_on_the_worker_that_drew_the_frame_shown() {
}
}
/// A Pen drag over a frame the worker drew draws each move's curve into that frame, here, in the
/// frame of the move: once the press's frame arrives from the worker, every move shows the
/// document's revision and queues nothing on the worker. When the frame shown drew effect rasters
/// A Pen drag over a frame the worker drew draws the press's anchor and each move's curve into
/// that frame, here, in the frame of the press or the move: each shows the document's revision and
/// queues nothing on the worker. When the frame shown drew effect rasters
/// from before their objects moved, when a part drawn here would have differed from it, or when
/// the part's share of the whole frame's time is over 8 ms, the next move renders on the worker,
/// and the moves after the worker's frame are drawn here again. A frame of an older revision on
@@ -1936,6 +2139,14 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() {
let (worker, mut side) = WorkerSide::start();
app.canvas.worker = Some(worker);
app.canvas.last_ms = 50.0;
// A new zoom: the frame shown is the worker's.
if let Some(vm) = app.view_mut() {
vm.zoom *= 1.25;
}
frame(&mut app, &ctx, vec![]);
assert!(side.render());
frame(&mut app, &ctx, vec![]);
assert!(app.canvas.from_worker, "the worker drew the frame shown");
app.select_tool("pen");
let revision = |app: &VectorcraftApp| Some(app.session.active().unwrap().revision);
let shown = |app: &VectorcraftApp| app.canvas.key.as_ref().map(|k| k.revision);
@@ -1943,8 +2154,9 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() {
let mut at = app.canvas_view().unwrap().to_screen(Point::new(105.0, 155.0));
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
frame(&mut app, &ctx, vec![button(at, true)]);
assert!(shown(&app) < revision(&app), "the press's frame, the first of the drag, renders on the worker");
assert!(side.render());
assert_eq!(shown(&app), revision(&app), "the press's anchor, the first frame of the drag, is drawn in its own frame");
assert!(app.canvas.key.as_ref().is_some_and(|k| k.interacting), "the press's frame is the interaction's");
assert!(side.jobs.try_recv().is_err(), "the press queues nothing on the worker");
let mut drag = |app: &mut VectorcraftApp| {
at += vec2(9.0, 5.0);
frame(app, &ctx, vec![egui::Event::PointerMoved(at)]);
@@ -1957,7 +2169,7 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() {
for case in ["moved", "differs", "slow"] {
match case {
"moved" => app.canvas.moved = true,
"differs" => app.canvas.worker_parts = true,
"differs" => app.canvas.whole_frames = true,
_ => app.canvas.last_ms = 10_000.0,
}
drag(&mut app);
@@ -1965,26 +2177,26 @@ fn a_pen_drag_over_a_worker_frame_draws_each_move_in_its_frame() {
assert!(side.render(), "{case}: the move renders on the worker");
drag(&mut app);
assert_eq!(shown(&app), revision(&app), "{case}: after the worker's frame, the next move is drawn here");
assert!(!app.canvas.worker_parts, "{case}");
assert!(!app.canvas.whole_frames, "{case}");
}
// A worker's frame that drew art in a way that depends on its size: the move after it renders
// on the worker too.
app.canvas.worker_parts = true;
app.canvas.whole_frames = true;
drag(&mut app);
let job = side.jobs.try_iter().last().expect("the move is on the worker");
let done = crate::render_worker::render(&mut side.renderer, &mut side.kept, job);
side.done.send(crate::render_worker::Done { ms: 50.0, view_sized: true, ..done }).unwrap();
drag(&mut app);
assert!(app.canvas.worker_parts, "the frame shown drew art that depends on its size");
assert!(app.canvas.whole_frames, "the frame shown drew art that depends on its size");
assert!(shown(&app) < revision(&app) && side.render(), "the move after it renders on the worker");
drag(&mut app);
assert_eq!(shown(&app), revision(&app), "after the next worker frame, the move is drawn here");
// A frame on its way of an older revision: the next move is drawn here, and that frame is not
// shown when it arrives.
app.canvas.worker_parts = true;
app.canvas.whole_frames = true;
drag(&mut app);
assert!(app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()), "a frame is on its way");
app.canvas.worker_parts = false;
app.canvas.whole_frames = false;
for late in [false, true] {
if late {
assert!(side.render());
+10 -2
View File
@@ -9,6 +9,7 @@ use craft::ui::form::Field;
use craft::ui::layout_components::Row;
use craft::ui::menu::Menu;
use craft::ui::pickers::{Select, SelectLook};
use craft::ui::runtime::env::Env;
use craft::ui::style::TypeRole;
use craft::ui::text::ZoomField;
@@ -47,6 +48,7 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
let busy = busy_labels(app);
let (mut zoom_to, mut rotate_to, mut go, mut show_pick, mut stop) = (None, None, None, None, false);
let mut invalid_zoom = None;
// The readouts end the bar, the pointer's position and then the timings; a narrow bar leaves out the timings
// first, then the position, before the message.
let readouts = |ui: &mut Ui, _: &mut BodyCx<'_>| {
@@ -73,8 +75,11 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
.side(SideLabel::new().kind(LabelKind::Hidden))
.show(ui, |ui, _| ZoomField::new(tl!("Zoom"), app.canvas_view(), document).scrub(true).show(ui));
// The field edits the canvas view, whose zoom is divided by UI Scaling; `view.setZoom` takes the view's zoom.
if let Some(view) = zoom.inner.and_then(|z| z.view.committed().copied()) {
zoom_to = Some(crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(&view, app.ui_scaling()), print));
if let Some(zoom) = zoom.inner {
if let Some(view) = zoom.view.committed() {
zoom_to = Some(crate::state::zoom_display_percent(crate::state::View::zoom_of_canvas(view, app.ui_scaling()), print));
}
invalid_zoom = zoom.invalid_zoom.map(|invalid| invalid.message(&Env::of(ui)));
}
Field::new(tl!("Rotation")).side(SideLabel::new().kind(LabelKind::Hidden)).show(ui, |ui, _| {
// Entries are keyed by index: an angle is not a hashable value.
@@ -156,6 +161,9 @@ pub fn status_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
{
app.status(e);
}
if let Some(message) = invalid_zoom {
app.status(message);
}
}
/// What the bar shows as work in progress: the running script, then background jobs, opens and places. The first
@@ -6,8 +6,8 @@
//! 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.
//! An invalid `set`, `action` or function key is an error, as are a name the list refuses and a
//! library change while editing an existing set or action. The dialog stays open with the error.
use craft::ui::contract::{Bind, Show as _, ShowContainer as _};
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldOk, StackDialog, dialog_id};
@@ -67,12 +67,14 @@ pub struct SetOptionsDialog {
pub set: Option<usize>,
/// The index of the action in its set; only for Action Options.
pub action: Option<usize>,
/// The action library revision these addresses described when Options opened.
revision: Option<u64>,
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) }
fn new(kind: SetOptionsKind, set: Option<usize>, action: Option<usize>, revision: Option<u64>, fields: SetOptionsFields) -> Self {
SetOptionsDialog { id: dialog_id(KEY), kind, set, action, revision, form: Form::new(fields, check) }
}
}
@@ -81,14 +83,15 @@ pub fn open_new(app: &mut VectorcraftApp) {
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_or_say(app, SetOptionsDialog::new(SetOptionsKind::NewSet, None, 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(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));
let revision = app.ui.actions.revision();
open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Set, Some(set), None, Some(revision), fields));
}
}
@@ -105,22 +108,26 @@ pub fn open_action(app: &mut VectorcraftApp, set: usize, action: usize) {
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));
let revision = app.ui.actions.revision();
open_or_say(app, SetOptionsDialog::new(SetOptionsKind::Action, Some(set), Some(action), Some(revision), fields));
}
impl ActionDialog for SetOptionsDialog {
/// What OK files, with the kind and place the dialog had.
type Answer = (SetOptionsKind, Option<usize>, Option<usize>, SetOptionsFields);
/// What OK files, with the kind, place and library revision the dialog had.
type Answer = (SetOptionsKind, Option<usize>, Option<usize>, Option<u64>, SetOptionsFields);
fn take_ok(&mut self) -> Option<Self::Answer> {
self.form.take().map(|fields| (self.kind, self.set, self.action, fields))
self.form.take().map(|fields| (self.kind, self.set, self.action, self.revision, fields))
}
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> {
fn run(app: &mut VectorcraftApp, (kind, set, action, revision, fields): Self::Answer) -> Result<(), String> {
if revision.is_some_and(|revision| app.ui.actions.revision() != revision) {
return Err("The action library changed. Reopen Options to edit it.".into());
}
match kind {
SetOptionsKind::NewSet => edits::new_set(app, &fields.name),
SetOptionsKind::Set => {
+40 -1
View File
@@ -154,6 +154,7 @@ struct Setup {
#[derive(Clone, Copy)]
struct Target {
document: u64,
reverts: u64,
/// The current artboard's ID, or no ID while creating a new artboard.
artboard: Option<u32>,
}
@@ -556,7 +557,7 @@ pub(crate) fn active_index(app: &VectorcraftApp) -> usize {
fn present(app: &mut VectorcraftApp, mut value: ArtboardOptionsValue, artboard: Option<u32>) -> Result<Value, String> {
let host = app.dialogs().ok_or("no window")?;
let st = app.session.active().ok_or("no document")?;
let target = Target { document: st.uid, artboard };
let target = Target { document: st.uid, reverts: st.reverts, artboard };
let artwork = vectorcraft_render::encode::art_bounds(&st.doc);
let [(_, fade), (_, update_while_dragging)] = global_fields(app);
(value.fade, value.update_while_dragging, value.reference) = (fade, update_while_dragging, app.ui.transform_panel.reference_point);
@@ -652,6 +653,9 @@ fn confirm(app: &mut VectorcraftApp, target: Target, v: &ArtboardOptionsValue) -
.active()
.filter(|st| st.uid == target.document)
.ok_or(tl!("Artboard Options can only change the document where it was opened."))?;
if st.reverts != target.reverts {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
let globals = global_changes(app, v);
if v.new {
let r = confirm_new(app, v)?;
@@ -1063,4 +1067,39 @@ mod tests {
assert!(!is_open(&app));
assert_eq!(*app.session.doc().unwrap().doc, *before);
}
#[test]
fn artboard_options_refuses_a_stale_draft_after_confirmed_revert() {
let file = std::env::temp_dir().join(format!("vectorcraft-artboard-options-revert-{}.vectorcraft", std::process::id()));
let path = file.to_string_lossy();
let mut app = app();
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string())));
app.run("file.saveAs", json!({"path": path})).unwrap();
let original = app.session.active().unwrap();
let (uid, reverts, artboard) = (original.uid, original.reverts, original.doc.artboards[0].id);
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
open(&mut app).unwrap();
set(&app, &[("name", json!("Stale Draft"))]).unwrap();
app.run("file.revert", json!({"confirmed": true})).unwrap();
let _ = std::fs::remove_file(&file);
let reverted = app.session.active().unwrap();
assert_eq!((reverted.uid, reverted.reverts, reverted.doc.artboards[0].id), (uid, reverts + 1, artboard));
let undo = undo_len(&app);
let answer = ok(&mut app);
assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Artboard 1");
assert_eq!(undo_len(&app), undo);
assert_eq!(answer, Err("The document was reverted. Reopen this dialog to continue.".into()));
assert!(is_open(&app));
let host = app.dialogs().unwrap();
let ctx = app.ui_ctx.clone().unwrap();
assert_eq!(host.with(|h| h.get::<ArtboardOptionsDialog>().unwrap().value.name.clone()), "Stale Draft");
host.with(|h| h.cancel_by_id(&ctx, id()));
open(&mut app).unwrap();
set(&app, &[("name", json!("Fresh Draft"))]).unwrap();
ok(&mut app).unwrap();
assert_eq!(app.session.active().unwrap().doc.artboards[0].name, "Fresh Draft");
}
}
+70 -2
View File
@@ -130,7 +130,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let state = app
.dialogs()
.and_then(|d| d.with(|host| host.get_by_id::<HostedParamDialog>(dialog_id(KIND)).map(|d| (d.is_previewing(), params(d.fields())))));
if let Some((previewing, p)) = state {
if let Some((previewing, p)) = state
&& (!previewing || app.session.has_selected_blend())
{
// With no blend selected, the command sets application defaults instead of previewing artwork.
// The answer only reports the preview's status, which the preview itself shows.
let _ = preview.run(app, previewing, PREVIEW_LABEL, CMD, &p);
}
@@ -139,8 +142,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
/// OK: keeps the preview as one undo step on a blend; sets the defaults otherwise.
fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> {
let on_blend = result.fields.text("__target") == Some("blend");
if on_blend != app.session.has_selected_blend() {
let reason = if on_blend {
tl!("Select a blend before applying these options.")
} else {
tl!("Deselect any selected blends before applying the options for new blends.")
};
return Err(reason.to_owned());
}
let p = params(&result.fields);
if result.fields.text("__target") != Some("blend") {
if !on_blend {
return app.run(CMD, p).map(|_| ());
}
let preview = app.object_dialogs.blend.take().unwrap_or_default();
@@ -212,6 +224,62 @@ mod tests {
}
}
fn app_with_smooth_blend() -> (VectorcraftApp, u64) {
let mut app = app();
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
for x in [0, 200] {
app.run("shape.rectangle", json!({"x": x, "y": 0, "width": 20, "height": 20})).unwrap();
}
app.run("select.all", json!({})).unwrap();
let id = app.run("object.blend.make", json!({"smooth": true})).unwrap()["id"].as_u64().unwrap();
(app, id)
}
#[test]
fn opening_blend_defaults_does_not_edit_a_later_selected_blend() {
let (mut app, id) = app_with_smooth_blend();
app.run("select.none", json!({})).unwrap();
app.run("ui.blendOptions", json!({})).unwrap();
assert_eq!(fields(&app).text("__target"), Some("defaults"));
set(&app, "spacing", json!("steps"));
set(&app, "steps", json!(7));
app.run("select.set", json!({"ids": [id]})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
confirm(&mut app);
assert_eq!(spec(&app, id).spacing, BlendSpacing::SmoothColor, "a newly selected blend keeps its spacing");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(is_open(&app));
app.run("select.none", json!({})).unwrap();
confirm(&mut app);
assert!(!is_open(&app));
assert_eq!(app.session.prefs.blend_options.unwrap().spacing, BlendSpacing::Steps(7));
}
#[test]
fn opening_blend_options_for_a_selection_does_not_write_defaults() {
let (mut app, id) = app_with_smooth_blend();
let defaults = app.session.prefs.blend_options;
app.run("ui.blendOptions", json!({})).unwrap();
assert_eq!(fields(&app).text("__target"), Some("blend"));
set(&app, "spacing", json!("steps"));
set(&app, "steps", json!(7));
app.run("select.none", json!({})).unwrap();
frame(&mut app);
assert_eq!(app.session.prefs.blend_options, defaults, "the blend preview leaves new-blend defaults intact");
assert!(!app.session.in_interaction());
confirm(&mut app);
assert_eq!(app.session.prefs.blend_options, defaults);
assert!(is_open(&app));
app.run("select.set", json!({"ids": [id]})).unwrap();
confirm(&mut app);
assert!(!is_open(&app));
assert_eq!(spec(&app, id).spacing, BlendSpacing::Steps(7));
}
#[test]
fn opens_on_the_blend_previews_and_keeps_smooth_color() {
let mut app = app();
+17 -3
View File
@@ -21,7 +21,7 @@ super::confirm::wrapped_dialog!(BrushDeleteQuestion, StandardPrompt, KIND);
/// What the question is about: the document it was asked in, the `brush.delete` params and whether a
/// stroke uses one of the brushes.
struct BrushDeleteAsk {
doc: Option<u64>,
doc: Option<(u64, u64)>,
params: Value,
used: bool,
}
@@ -33,7 +33,7 @@ pub fn ask(app: &mut VectorcraftApp, params: Value, used: bool) {
return;
};
let (message, yes, no) = words(used);
let doc = app.session.active().map(|d| d.uid);
let doc = app.session.active().map(|d| (d.uid, d.reverts));
let prompt =
StandardPrompt::custom(message).button(PromptChoice::Proceed, yes).button(PromptChoice::Cancel, no).tag(BrushDeleteAsk { doc, params, used });
dialogs.with(|host| host.open(BrushDeleteQuestion(prompt)));
@@ -89,7 +89,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
/// Yes on brushes that a stroke has started to use since the question opened asks again with Remove
/// Strokes and Cancel. When another document has become the active one, nothing is deleted.
fn confirm(app: &mut VectorcraftApp, question: BrushDeleteAsk) {
if question.doc != app.session.active().map(|doc| doc.uid) {
if !confirmation_is_current(app, question.doc) {
return;
}
if !question.used {
@@ -111,5 +111,19 @@ pub(crate) fn open_question(app: &VectorcraftApp) -> Option<(String, bool)> {
Some((words(used).0.to_string(), used))
}
/// Whether the opening Brush confirmation still owns the active drawing's contents.
pub(super) fn confirmation_is_current(app: &mut VectorcraftApp, opening: Option<(u64, u64)>) -> bool {
let current = app.session.active().map(|st| (st.uid, st.reverts));
if opening == current {
return true;
}
if let (Some((document, _)), Some((active, _))) = (opening, current)
&& document == active
{
app.status(tl!("The document was reverted. Reopen this dialog to continue."));
}
false
}
#[cfg(test)]
pub(super) mod tests;
@@ -10,6 +10,15 @@ pub(in crate::dialogs) fn app() -> VectorcraftApp {
crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()))
}
/// Writes a native file for the test to revert to.
pub(in crate::dialogs) fn save_for_revert(app: &mut VectorcraftApp, tag: &str) -> std::path::PathBuf {
let file = std::env::temp_dir().join(format!("vectorcraft-brush-{tag}-{}.vectorcraft", std::process::id()));
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string())));
app.run("file.saveAs", json!({"path": file.to_string_lossy()})).unwrap();
file
}
/// Answers the open question `D` the way its button does (`Some(choice)`: the button of that choice,
/// `None`: Cancel's close), then runs the module's `pump`.
pub(in crate::dialogs) fn answer<D: StackDialog>(app: &mut VectorcraftApp, choice: Option<&str>, pump: fn(&mut VectorcraftApp, &egui::Context)) {
@@ -84,3 +93,36 @@ fn remove_strokes_runs_the_delete_and_cancel_changes_nothing() {
assert!(stroke.width > 0.0);
}
}
#[test]
fn stale_delete_approval_keeps_the_saved_brush_after_revert() {
let mut app = app();
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
let slim = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 8})).unwrap()["id"].as_u64().unwrap();
let tall = app.run("shape.rectangle", json!({"x": 10, "y": 30, "width": 40, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("brush.new", json!({"type": "art", "name": "Bar", "ids": [slim]})).unwrap();
let file = save_for_revert(&mut app, "delete-revert");
let brush_height = |app: &mut VectorcraftApp| {
let brush = app.run("brush.get", json!({"name": "Bar"})).expect("the saved brush still exists");
let art: vectorcraft_doc::Node = serde_json::from_value(brush["art"].clone()).unwrap();
art.geometric_bounds().unwrap().height()
};
let saved = brush_height(&mut app);
let st = app.session.active().unwrap();
let (uid, reverts) = (st.uid, st.reverts);
app.run("brush.replaceArt", json!({"name": "Bar", "ids": [tall], "applyToStrokes": true})).unwrap();
assert!((brush_height(&mut app) - saved).abs() > 1e-6);
ask(&mut app, json!({"names": ["Bar"]}), false);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let _ = std::fs::remove_file(file);
let st = app.session.active().unwrap();
assert_eq!((st.uid, st.reverts), (uid, reverts + 1));
assert!((brush_height(&mut app) - saved).abs() < 1e-6);
let undo = app.session.active().unwrap().history.undo.len();
answer::<BrushDeleteQuestion>(&mut app, Some("proceed"), pump);
assert!((brush_height(&mut app) - saved).abs() < 1e-6);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue.");
}
+40 -3
View File
@@ -163,12 +163,13 @@ pub fn open(app: &mut VectorcraftApp, name: Option<&str>) -> Result<Value, Strin
/// `object_keys` are the option keys of Options of Selected Object, which the dialog then records
/// with the values it opened with. OK reaches [`ok`] once the dialog's own rows accept it.
fn open_dialog(app: &mut VectorcraftApp, f: &Map<String, Value>, object_keys: Option<&[&str]>) -> Result<Value, String> {
let source = app.session.active().ok_or("no document open")?;
let (document, reverts) = (source.uid, source.reverts);
let ty = f.get("__type").and_then(Value::as_str).unwrap_or_default();
let object = object_keys.is_some();
let ctx = app.ui_ctx.clone().ok_or("no window")?;
// Modal: no edit changes the document while the dialog is open, so the previews read this snapshot.
let doc = app.session.active().map(|st| st.doc.clone());
let rows = rows(ty, object, doc, crate::canvas::rulers::unit_kind(app.session.general_unit()));
let rows = rows(ty, object, Some(source.doc.clone()), crate::canvas::rulers::unit_kind(app.session.general_unit()));
let title = Label::from(title(ty, object));
let mut initial = form::fields_of(&rows, f);
// The hidden values the rows read whole stay JSON: an untagged read makes an array a list of values.
@@ -192,7 +193,19 @@ fn open_dialog(app: &mut VectorcraftApp, f: &Map<String, Value>, object_keys: Op
}
})
.held_ok();
app.ui.brush_options = Some(host::open_held(app, dialog, ok).ok_or("no window")?);
app.ui.brush_options = Some(
host::open_held(app, dialog, move |app, result: &ParamResult| {
match app.session.active().filter(|st| st.uid == document) {
Some(source) if source.reverts != reverts => {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
None if !object => return Err(tl!("Return to the original drawing to edit its brush").into()),
_ => {}
}
ok(app, result)
})
.ok_or("no window")?,
);
Ok(Value::Null)
}
@@ -672,3 +685,27 @@ fn confirm(app: &mut VectorcraftApp, d: &DialogFields) -> Result<(), String> {
#[cfg(test)]
mod tests;
#[cfg(test)]
mod document_tests {
use super::*;
use crate::dialogs::tests_export;
#[test]
fn brush_options_does_not_rename_the_other_drawings_brush() {
let (mut app, _) = tests_export::app(1);
open(&mut app, Some("Diamonds")).unwrap();
tests_export::set(&mut app, "name", json!("Source diamonds"));
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let previous = app.run("brush.get", json!({"name": "Diamonds"})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
let error = tests_export::try_confirm(&mut app).expect_err("Brush Options must refuse the other drawing");
assert!(error.contains("original drawing"), "{error}");
assert_eq!(app.run("brush.get", json!({"name": "Diamonds"})).unwrap(), previous);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(tests_export::fields(&app)["name"], "Source diamonds");
app.run("document.activate", json!({"index": 0})).unwrap();
tests_export::try_confirm(&mut app).unwrap();
assert_eq!(app.run("brush.get", json!({"name": "Source diamonds"})).unwrap()["name"], "Source diamonds");
}
}
@@ -22,7 +22,7 @@ super::confirm::wrapped_dialog!(ReplaceArtQuestion, StandardPrompt, KIND);
/// What the question is about: the document it was asked in, the brush and the art.
struct ReplaceArtAsk {
doc: Option<u64>,
doc: Option<(u64, u64)>,
name: String,
ids: Vec<u64>,
}
@@ -59,7 +59,7 @@ pub fn ask(app: &mut VectorcraftApp, name: &str, ids: &[u64]) {
app.status("no window");
return;
};
let doc = app.session.active().map(|d| d.uid);
let doc = app.session.active().map(|d| (d.uid, d.reverts));
let prompt = StandardPrompt::custom(tl!(
"Strokes use this brush. Apply the new art to those strokes, or leave them as they are and add a copy of the brush with the new art?"
))
@@ -86,7 +86,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
/// Runs `brush.replaceArt`. When another document has become the active one, no brush changes.
fn confirm(app: &mut VectorcraftApp, question: ReplaceArtAsk, apply: bool) {
if question.doc != app.session.active().map(|doc| doc.uid) {
if !super::brush_delete::confirmation_is_current(app, question.doc) {
return;
}
let params = json!({"name": question.name, "ids": question.ids, "applyToStrokes": apply});
@@ -1,7 +1,7 @@
use serde_json::json;
use vectorcraft_doc::NodeId;
use super::super::brush_delete::tests::{answer, app};
use super::super::brush_delete::tests::{answer, app, save_for_revert};
use super::*;
fn rect(app: &mut VectorcraftApp, x: f64, y: f64, w: f64, h: f64) -> u64 {
@@ -95,3 +95,30 @@ fn a_button_changes_no_brush_after_another_document_became_active() {
app.run("document.activate", json!({"index": 0})).unwrap();
assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6);
}
#[test]
fn stale_replace_approval_keeps_the_saved_brush_art_after_revert() {
let mut app = app();
let (_, tall) = used_brush(&mut app);
let thick = rect(&mut app, 10.0, 65.0, 40.0, 30.0);
let file = save_for_revert(&mut app, "replace-revert");
let st = app.session.active().unwrap();
let (uid, reverts) = (st.uid, st.reverts);
app.run("brush.replaceArt", json!({"name": "Bar", "ids": [tall], "applyToStrokes": true})).unwrap();
assert!((art_height(&mut app, "Bar") - 20.0).abs() < 1e-6);
replace(&mut app, "Bar", &[thick]);
assert!(asks(&app));
app.run("file.revert", json!({"confirmed": true})).unwrap();
let _ = std::fs::remove_file(file);
let st = app.session.active().unwrap();
assert_eq!((st.uid, st.reverts), (uid, reverts + 1));
assert!(st.doc.node(NodeId(thick)).is_some(), "the restored drawing shares the same local source ID");
assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6);
let undo = app.session.active().unwrap().history.undo.len();
answer::<ReplaceArtQuestion>(&mut app, Some("proceed"), pump);
assert!((art_height(&mut app, "Bar") - 8.0).abs() < 1e-6, "the stale answer leaves the restored brush intact");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(app.ui.status, "The document was reverted. Reopen this dialog to continue.");
}
+275 -39
View File
@@ -25,18 +25,21 @@
//! <https://web.archive.org/web/20260417034638/https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-bulleted-or-numbered-lists.html>.
use std::borrow::Cow;
use std::sync::{Arc, Weak};
use craft::behavior::{Mixed, Selection, SelectionChange, keyed};
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use craft::ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id};
use craft::ui::display::Text;
use craft::ui::form::{Field, FieldGroup};
use craft::ui::layout_components::{Row, Stack};
use craft::ui::list::ThumbAspect;
use craft::ui::pickers::Select;
use craft::ui::primitives::{HAlign, IconSpec, TextRun};
use craft::ui::runtime::env::{Env, LengthUnits};
use craft::ui::runtime::env::{Env, Label, LengthUnits};
use craft::ui::runtime::measure;
use craft::ui::runtime::overlay::CloseReason;
use craft::ui::runtime::words::CommonWords;
use craft::ui::sections::{DialogRole, FooterButton};
use craft::ui::tabs::{Tab, TabKind, TabStrip};
@@ -44,11 +47,14 @@ use craft::ui::text::NumberField;
use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid};
use egui::{Context, Ui};
use serde_json::{Map, Value, json};
use vectorcraft_doc::Selection as ArtworkSelection;
use vectorcraft_doc::text::{LIST_HANGING_INDENT, LIST_LEVELS, MAX_LIST_START, NumberStyle, ParaList};
use crate::VectorcraftApp;
use crate::panels::paragraph::BulletGlyph;
use super::preview::LivePreview;
/// The dialog kind of Bullets and Numbering.
pub const KIND: &str = "bulletsAndNumbering";
@@ -122,9 +128,73 @@ pub(crate) struct BulletsDialog {
hanging: bool,
/// The General unit the indent fields show; the pump keeps it current.
lengths: LengthUnits,
active_document: bool,
held: HeldAnswer<Map<String, Value>>,
open: bool,
}
/// The preview from the opening drawing and the interaction that owns its undo snapshot.
pub(crate) struct Preview {
document: (u64, u64),
live: LivePreview,
selection: Option<Weak<ArtworkSelection>>,
}
impl Preview {
fn owns_interaction(&self, app: &VectorcraftApp) -> bool {
let Some(selection) = &self.selection else { return false };
app.session.active().is_some_and(|state| {
(state.uid, state.reverts) == self.document
&& state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection))
})
}
fn update(&mut self, app: &mut VectorcraftApp, fields: Map<String, Value>) {
let Some(state) = app.session.active().filter(|state| (state.uid, state.reverts) == self.document) else { return };
if !self.owns_interaction(app) {
self.live = LivePreview::default();
self.selection = None;
if state.interaction.is_some() {
return;
}
}
let on = changes(&fields);
let ran = self.live.run(app, on, tl!("Bullets and Numbering"), CMD, &Value::Object(fields)).is_some();
if !on {
self.selection = None;
} else if ran {
self.selection = app.session.active().and_then(|state| state.interaction.as_ref()).map(|it| Arc::downgrade(&it.selection));
}
}
fn apply(&mut self, app: &mut VectorcraftApp, fields: Map<String, Value>) -> Result<(), String> {
if !changes(&fields) {
if self.owns_interaction(app) {
std::mem::take(&mut self.live).cancel(app);
self.selection = None;
}
return Ok(());
}
let Some(state) = app.session.active().filter(|state| state.uid == self.document.0) else {
return Err(tl!("Bullets and Numbering can only change the document where it was opened.").to_owned());
};
if state.reverts != self.document.1 {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
if app.session.in_interaction() && !self.owns_interaction(app) {
return Err(tl!("Finish the active edit before applying Bullets and Numbering.").to_owned());
}
self.selection = None;
std::mem::take(&mut self.live).commit(app, CMD, Value::Object(fields)).map(drop)
}
fn cancel(self, app: &mut VectorcraftApp) {
if self.owns_interaction(app) {
self.live.cancel(app);
}
}
}
/// The kind of list `list` is, as the `list` field names it.
fn kind(list: Option<ParaList>) -> &'static str {
match list {
@@ -144,8 +214,12 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
Some(v) => Some(v.as_str().and_then(ListTab::of).ok_or_else(|| format!("`{key}` must be one of {}", TABS.join(", ")))?),
};
crate::panels::character::text_style(app).ok_or("select some type first")?;
let active = app.session.active().ok_or("no document")?;
let document = (active.uid, active.reverts);
// A dialog this one replaces leaves its preview on the type: end it, so the values read below are the document's own.
std::mem::take(&mut app.bullets_preview).cancel(app);
if let Some(old) = app.bullets_preview.take() {
old.cancel(app);
}
// While typing, the dialog acts on the paragraphs of the text being edited.
let mut targets = json!({});
if let Some((id, a, b)) = crate::panels::character::text_editing_kept(app)? {
@@ -192,9 +266,12 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
targets,
hanging: false,
lengths: crate::canvas::general_lengths(app),
active_document: true,
held: HeldAnswer::default(),
open: true,
};
host.with(|h| h.open(dialog));
app.bullets_preview = Some(Preview { document, live: LivePreview::default(), selection: None });
Ok(Value::Null)
}
@@ -468,8 +545,7 @@ fn changes(p: &Map<String, Value>) -> bool {
}
impl StackDialog for BulletsDialog {
/// The `text.setFormat` parameters OK runs.
type Result = Value;
type Result = ();
fn id(&self) -> DialogId {
dialog_id(KIND)
@@ -479,20 +555,46 @@ impl StackDialog for BulletsDialog {
Some(KIND)
}
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<Value>> {
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> {
let common = Env::of(ui).words::<CommonWords>();
let buttons = [FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)];
let finish = self.held.is_accepted();
let refusal = self.held.refusal().map(|(reason, _)| reason.clone());
let buttons = [
FooterButton::new(common.ok.clone(), DialogRole::Accept).stays_open(true).enabled(!self.held.is_waiting()),
FooterButton::new(common.cancel.clone(), DialogRole::Cancel),
];
let mut open = self.open;
let dialog = Dialog::new(tl!("Bullets and Numbering")).buttons(buttons).opened(Bind::bound(&mut open));
let shown = dialog.show(ui, |ui, _| self.body(ui));
let dialog = Dialog::new(tl!("Bullets and Numbering")).buttons(buttons).opened(Bind::bound(&mut open)).refusal(move || refusal.clone());
let shown = dialog.show(ui, |ui, cx| {
if finish && !measure::active(ui.ctx()) {
cx.request_close_as(CloseReason::Activated);
}
self.body(ui);
});
self.open = open;
let DialogOutput { closed, picked, .. } = shown.output;
closed?;
Some(if picked == Some(OK) { DialogResult::Ok(Value::Object(params(self))) } else { DialogResult::Cancel })
if picked == Some(OK) && !self.held.is_waiting() {
self.held.file(params(self));
}
match closed {
Some(CloseReason::Activated) if finish => self.held.finish().map(|_| DialogResult::Ok(())),
Some(_) => Some(DialogResult::Cancel),
None => None,
}
}
fn confirm(&mut self, _: &Context) -> Option<Value> {
Some(Value::Object(params(self)))
fn confirm(&mut self, _: &Context) -> Option<()> {
if self.held.is_accepted() {
return self.held.finish().map(drop);
}
if !self.held.is_waiting() {
self.held.file(params(self));
}
None
}
fn held_state(&self) -> Option<HeldOk> {
self.held.state()
}
fn json_fields(&self) -> Option<Value> {
@@ -515,38 +617,41 @@ impl StackDialog for BulletsDialog {
}
}
/// Runs once per frame: keeps the indent fields' unit current, shows the dialog's values on the type while they change
/// something, and answers a finished dialog: OK keeps the preview as one undo step, Cancel (Escape and the close box
/// too) and an OK that changes nothing put the type back.
/// Shows the draft on its opening drawing and answers OK before the dialog closes.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
let Some(host) = app.dialogs() else { return };
if let Some(result) = host.with(|h| h.take::<BulletsDialog>()) {
let live = std::mem::take(&mut app.bullets_preview);
match result {
DialogResult::Ok(Value::Object(p)) if changes(&p) => {
if let Err(e) = live.commit(app, CMD, Value::Object(p)) {
app.status(e);
// The dialog is gone: a preview the refused OK left running goes with it. Nothing runs
// when the refusal came before the interaction began, which is the right outcome too.
let _ = app.session.cancel_interaction();
}
}
_ => live.cancel(app),
}
}
let Some(mut preview) = app.bullets_preview.take() else { return };
let active_document = app.session.active().is_some_and(|state| (state.uid, state.reverts) == preview.document);
let lengths = crate::canvas::general_lengths(app);
// The host's lock is released before the preview runs: a command never runs inside `with`.
let Some(p) = host.with(|h| {
let Some((fields, answer)) = host.with(|h| {
h.get_mut::<BulletsDialog>().map(|d| {
d.lengths = lengths;
params(d)
let fields = params(d);
if (active_document && !d.active_document) || d.held.refusal().is_some_and(|(_, at)| *at != fields) {
d.held.clear_refusal();
}
d.active_document = active_document;
(fields, d.held.take())
})
}) else {
preview.cancel(app);
return;
};
let mut live = std::mem::take(&mut app.bullets_preview);
let _ = live.run(app, changes(&p), tl!("Bullets and Numbering"), CMD, &Value::Object(p));
app.bullets_preview = live;
if let Some(answer) = answer {
let result = preview.apply(app, answer).map_err(Label::from);
let accepted = result.is_ok();
host.with(|h| {
if let Some(dialog) = h.get_mut::<BulletsDialog>() {
dialog.held.answer(result);
}
});
if accepted {
return;
}
} else {
preview.update(app, fields);
}
app.bullets_preview = Some(preview);
}
#[cfg(test)]
@@ -618,13 +723,23 @@ mod tests {
crate::dialogs::host::pump(app, &ctx);
}
/// OK on the open dialog, as automation answers it, then the frame's pump.
fn ok(app: &mut VectorcraftApp) {
fn press_ok(app: &mut VectorcraftApp) {
let (ctx, (id, _)) = (window(app), top(app));
assert!(app.dialogs().expect("a window").with(|h| h.confirm_by_id(&ctx, id)), "OK is enabled");
let host = app.dialogs().unwrap();
host.with(|h| {
assert!(!h.confirm_by_id(&ctx, id), "the app must accept the answer first");
assert_eq!(h.held_state(id), Some(HeldOk::Waiting));
});
frame(app);
}
/// Files OK and closes with the accepted answer, as the view or automation does.
fn ok(app: &mut VectorcraftApp) {
press_ok(app);
let (ctx, (id, _)) = (window(app), top(app));
assert!(app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)), "the app accepted OK");
}
/// Cancel on the open dialog, as Esc gives it, then the frame's pump.
fn cancel(app: &mut VectorcraftApp) {
let (ctx, (id, _)) = (window(app), top(app));
@@ -641,6 +756,127 @@ mod tests {
with_dialog(app, |d| params(d))
}
fn other_drawing(app: &mut VectorcraftApp) -> u64 {
app.run("file.new", json!({"width": 600, "height": 400})).unwrap();
let id = app.run("text.create", json!({"x": 15, "y": 10, "text": "Other\nDrawing", "area": {"width": 200, "height": 100}})).unwrap()["id"]
.as_u64()
.unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
id
}
#[test]
fn bullets_preview_pauses_in_another_drawing() {
let (mut app, id) = app();
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
pick_preset(&mut app, "bullet", Some("square"));
let other = other_drawing(&mut app);
let before = first(&app, other);
frame(&mut app);
assert_eq!(first(&app, other), before, "the other drawing's paragraphs are unchanged by preview");
assert!(!app.session.in_interaction());
app.run("document.activate", json!({"index": 0})).unwrap();
frame(&mut app);
assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square)));
ok(&mut app);
assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square)));
}
#[test]
fn bullets_ok_does_not_change_the_other_drawings_type() {
let (mut app, id) = app();
let opening = first(&app, id);
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
pick_preset(&mut app, "number", Some("arabic"));
let other = other_drawing(&mut app);
let before = first(&app, other);
let undo = app.session.doc().unwrap().history.undo.len();
press_ok(&mut app);
assert_eq!(first(&app, other), before, "the other drawing's paragraphs are unchanged by OK");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
assert!(with_dialog(&app, |d| matches!(d.held.state(), Some(HeldOk::Refused(_)))));
assert_eq!(fields(&app)["number"], "arabic");
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(first(&app, id), opening);
frame(&mut app);
assert!(with_dialog(&app, |d| d.held.state().is_none()));
ok(&mut app);
assert_eq!(first(&app, id).0, Some(ParaList::numbered(NumberStyle::Arabic)));
}
#[test]
fn bullets_preview_and_ok_leave_restored_paragraphs_unchanged() {
let (mut app, id) = app();
let dir = vectorcraft_testkit::TempDir::new("bullets-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let saved = paras(&app, id);
app.run("file.saveAs", json!({"path": dir.join("Paragraphs.vectorcraft")})).unwrap();
app.run("text.setFormat", json!({"ids": [id], "leftIndent": 19})).unwrap();
let drawing = app.session.active().unwrap();
let (uid, reverts) = (drawing.uid, drawing.reverts);
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
pick_preset(&mut app, "bullet", Some("square"));
frame(&mut app);
assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square)));
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
let restored = app.session.active().unwrap();
assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1));
let undo = restored.history.undo.len();
frame(&mut app);
assert_eq!(paras(&app, id), saved);
assert!(!app.session.in_interaction());
press_ok(&mut app);
assert!(with_dialog(&app, |dialog| matches!(dialog.held.state(), Some(HeldOk::Refused(_)))));
assert_eq!(paras(&app, id), saved);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
}
#[test]
fn bullets_cancel_keeps_the_other_drawings_pending_edit() {
let (mut app, id) = app();
let opening = first(&app, id);
let other = other_drawing(&mut app);
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
pick_preset(&mut app, "bullet", Some("square"));
frame(&mut app);
assert!(app.session.in_interaction());
app.run("document.activate", json!({"index": 1})).unwrap();
app.session.begin_interaction("Other paragraph edit").unwrap();
app.session.preview("text.setFormat", &json!({"ids": [other], "leftIndent": 41})).unwrap();
let editing = first(&app, other);
assert_eq!(editing.1, 41.0);
cancel(&mut app);
assert!(app.session.in_interaction(), "Cancel preserves the other drawing's pending edit");
assert_eq!(first(&app, other), editing);
app.session.commit_interaction().unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(first(&app, id), opening);
}
#[test]
fn accepted_bullets_close_on_the_next_view_pass() {
let (mut app, id) = app();
app.run("ui.bulletsAndNumbering", json!({})).unwrap();
pick_preset(&mut app, "bullet", Some("square"));
press_ok(&mut app);
let ctx = window(&app);
crate::tests_synthetic::key_frame(&mut app, &ctx, vec![]);
assert!(!is_open(&app));
assert_eq!(first(&app, id).0, Some(ParaList::bulleted(Bullet::Square)));
}
/// `ui.bulletsAndNumbering` opens on the selected type's values; a preset, Alignment and the
/// indents show on the type at once, and OK keeps them as one `text.setFormat`, which one Undo
/// takes back.
@@ -1165,6 +1165,7 @@ pub(crate) use style_dialog;
pub(crate) struct CharStyleOptions {
inner: HostedPropertiesDialog,
opening: Arc<Opening>,
document: u64,
}
impl CharStyleOptions {
@@ -1180,12 +1181,21 @@ impl CharStyleOptions {
}
style_dialog!(CharStyleOptions, KIND);
/// The preview and the document activation that owns it, retained until the host reports Cancel.
#[derive(Default)]
pub(crate) struct Preview {
live: LivePreview,
activation: Option<(u64, u64)>,
interaction_selection: Option<Arc<vectorcraft_doc::Selection>>,
}
pub fn open(app: &mut VectorcraftApp, name: &str) -> Result<Value, String> {
crate::panels::character::end_typing(app);
let doc = &app.session.active().ok_or("no document open")?.doc;
let state = app.session.active().ok_or("no document open")?;
let (document, doc) = (state.uid, &state.doc);
let def = doc.char_styles.iter().find(|s| s.name == name).ok_or_else(|| format!("no character style `{name}`"))?;
let opening = Arc::new(Opening::new(name, def.attrs.clone(), &doc.setup, swatch_choices(doc)));
let dialog = CharStyleOptions { inner: hosted(KIND, tl!("Character Style Options"), &opening, name).previews(), opening };
let dialog = CharStyleOptions { inner: hosted(KIND, tl!("Character Style Options"), &opening, name).previews(), opening, document };
app.dialogs().ok_or("no window")?.with(|host| host.open(dialog));
Ok(json!({"dialog": KIND}))
}
@@ -1210,15 +1220,46 @@ pub fn reset_panel(app: &mut VectorcraftApp) -> Result<Value, String> {
/// The dialog's frame work: previews the values, commits at OK, and rolls the preview back at Cancel.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let Some(frame) = dialogs.with(|host| host.get_mut::<CharStyleOptions>().map(CharStyleOptions::frame)) else {
let active = app.session.active().map(|doc| (doc.uid, app.session.tool_resets()));
let interaction_selection = app.session.active().and_then(|doc| doc.interaction.as_ref().map(|interaction| interaction.selection.clone()));
let owns_interaction = app.char_style_preview.activation == active
&& app
.char_style_preview
.interaction_selection
.as_ref()
.zip(interaction_selection.as_ref())
.is_some_and(|(owned, current)| Arc::ptr_eq(owned, current));
let Some((document, frame)) = dialogs.with(|host| host.get_mut::<CharStyleOptions>().map(|d| (d.document, d.frame()))) else {
if matches!(dialogs.with(|host| host.take::<CharStyleOptions>()), Some(DialogResult::Cancel)) {
std::mem::take(&mut app.char_style_preview).cancel(app);
let preview = std::mem::take(&mut app.char_style_preview);
if owns_interaction {
preview.live.cancel(app);
}
}
return;
};
let live = std::mem::take(&mut app.char_style_preview);
let (live, done) = drive(app, live, tl!("Character Style Options"), "charStyle.edit", &frame);
app.char_style_preview = live;
let done = if let Some(activation) = active.filter(|(uid, _)| *uid == document) {
if interaction_selection.is_some() && !owns_interaction {
frame.ok.then(|| Err("finish the active edit before applying Character Style Options".into()))
} else {
let preview = std::mem::take(&mut app.char_style_preview);
let live = if owns_interaction { preview.live } else { LivePreview::default() };
let (live, answer) = drive(app, live, tl!("Character Style Options"), "charStyle.edit", &frame);
let interaction_selection =
app.session.active().and_then(|doc| doc.interaction.as_ref().map(|interaction| interaction.selection.clone()));
app.char_style_preview = Preview { live, activation: Some(activation), interaction_selection };
answer
}
} else if frame.ok {
let reason = if app.session.documents().iter().any(|doc| doc.uid == document) {
"switch back to the document where Character Style Options was opened"
} else {
"the document where Character Style Options was opened has closed"
};
Some(Err(reason.into()))
} else {
None
};
if let Some(done) = done {
let answer = done.map(drop).map_err(|why| reason(&why));
dialogs.with(|host| {
@@ -126,6 +126,150 @@ fn styled(app: &mut VectorcraftApp, attrs: Value, text: &str) -> u64 {
id
}
fn options_in_the_first_of_two_documents() -> VectorcraftApp {
let mut app = app();
styled(&mut app, json!({"size": 24.0}), "Opening document");
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
styled(&mut app, json!({"size": 12.0}), "Other document");
app.run("document.activate", json!({"index": 0})).unwrap();
open(&mut app, "Body");
app
}
#[test]
fn the_style_preview_stays_in_its_opening_document() {
let mut app = options_in_the_first_of_two_documents();
let opening = app.session.doc().unwrap().doc.clone();
set::<Existing>(&app, "name", json!("Revised"));
pump(&mut app);
assert!(app.session.in_interaction());
app.run("document.activate", json!({"index": 1})).unwrap();
let other = app.session.doc().unwrap().doc.clone();
set::<Existing>(&app, "size", json!(18));
pump(&mut app);
assert_eq!(app.session.doc().unwrap().doc, other, "Preview leaves the other document's Body style unchanged");
assert!(!app.session.in_interaction());
app.run("document.activate", json!({"index": 0})).unwrap();
pump(&mut app);
assert!(app.session.doc().unwrap().doc.char_styles.iter().any(|style| style.name == "Revised"));
cancel::<Existing>(&mut app);
assert_eq!(app.session.doc().unwrap().doc, opening);
}
#[test]
fn a_style_options_confirmation_stays_in_its_opening_document() {
let mut app = options_in_the_first_of_two_documents();
set::<Existing>(&app, "preview", json!(false));
set::<Existing>(&app, "name", json!("Revised"));
app.run("document.activate", json!({"index": 1})).unwrap();
let other = app.session.doc().unwrap().doc.clone();
let closed = ok::<Existing>(&mut app);
assert_eq!(app.session.doc().unwrap().doc, other, "OK leaves the other document's Body style unchanged");
assert!(!closed, "the same draft remains available");
app.run("document.activate", json!({"index": 0})).unwrap();
assert!(ok::<Existing>(&mut app));
assert!(app.session.doc().unwrap().doc.char_styles.iter().any(|style| style.name == "Revised"));
}
#[test]
fn cancelling_style_options_leaves_the_other_documents_gesture() {
let mut app = options_in_the_first_of_two_documents();
set::<Existing>(&app, "name", json!("Revised"));
pump(&mut app);
assert!(app.session.in_interaction());
app.run("document.activate", json!({"index": 1})).unwrap();
app.session.begin_interaction("Another gesture").unwrap();
app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap();
let gesture = app.session.doc().unwrap().doc.clone();
cancel::<Existing>(&mut app);
assert_eq!(app.session.doc().unwrap().doc, gesture);
assert!(app.session.in_interaction());
}
#[test]
fn switching_back_leaves_a_new_gesture_in_the_opening_document() {
let mut app = options_in_the_first_of_two_documents();
set::<Existing>(&app, "name", json!("Revised"));
pump(&mut app);
assert!(app.session.in_interaction());
app.run("document.activate", json!({"index": 1})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
app.session.begin_interaction("Another gesture").unwrap();
app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap();
let gesture = app.session.doc().unwrap().doc.clone();
set::<Existing>(&app, "size", json!(18));
pump(&mut app);
assert!(!ok::<Existing>(&mut app));
assert_eq!(app.session.doc().unwrap().doc, gesture);
cancel::<Existing>(&mut app);
assert_eq!(app.session.doc().unwrap().doc, gesture);
assert!(app.session.in_interaction());
}
fn options_with_a_newer_gesture() -> VectorcraftApp {
let mut app = app();
styled(&mut app, json!({"size": 24.0}), "Opening document");
open(&mut app, "Body");
set::<Existing>(&app, "name", json!("Revised"));
pump(&mut app);
assert!(app.session.in_interaction());
let resets = app.session.tool_resets();
app.session.cancel_interaction().unwrap();
app.session.begin_interaction("Character Style Options").unwrap();
app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap();
assert_eq!(app.session.tool_resets(), resets);
app
}
#[test]
fn cancelling_style_options_preserves_a_newer_gesture_in_the_same_document() {
let mut app = options_with_a_newer_gesture();
let gesture = app.session.doc().unwrap().doc.clone();
cancel::<Existing>(&mut app);
assert_eq!(app.session.doc().unwrap().doc, gesture);
assert!(app.session.in_interaction());
}
#[test]
fn style_options_preview_preserves_a_newer_gesture_in_the_same_document() {
let mut app = options_with_a_newer_gesture();
let gesture = app.session.doc().unwrap().doc.clone();
set::<Existing>(&app, "size", json!(18));
pump(&mut app);
assert_eq!(app.session.doc().unwrap().doc, gesture);
assert!(app.session.in_interaction());
}
#[test]
fn style_options_confirmation_preserves_a_newer_gesture_in_the_same_document() {
let mut app = options_with_a_newer_gesture();
let gesture = app.session.doc().unwrap().doc.clone();
let undo = app.session.doc().unwrap().history.undo.len();
assert!(!ok::<Existing>(&mut app));
assert_eq!(app.session.doc().unwrap().doc, gesture);
assert!(app.session.in_interaction());
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
}
#[test]
fn a_first_style_preview_preserves_an_existing_gesture() {
let mut app = app();
styled(&mut app, json!({"size": 24.0}), "Opening document");
open(&mut app, "Body");
app.session.begin_interaction("Character Style Options").unwrap();
app.session.preview("object.move", &json!({"dx": 20, "dy": 0})).unwrap();
let gesture = app.session.doc().unwrap().doc.clone();
set::<Existing>(&app, "size", json!(18));
pump(&mut app);
assert_eq!(app.session.doc().unwrap().doc, gesture);
assert!(app.session.in_interaction());
}
#[test]
fn unchanged_basic_fields_preserve_original_keys() {
for attrs in [
+124 -14
View File
@@ -4,7 +4,7 @@
//! and the pump that runs each action against the document.
//!
//! The walk's state:
//! - `doc`: uid of the document it started on; another active document ends it
//! - `doc` and `reverts`: the drawing contents it started on; switching or reverting ends it
//! - `ids`: object IDs checked (None: entire document; Some(empty): nothing)
//! - `layer`: the one object checked while the dialog's Check All Layers is off
//! - `skipped`: `(node_id, start, word)` skipped by Ignore, which Change All leaves alone
@@ -43,6 +43,8 @@ type Word = (u64, usize, usize, String, String);
pub(crate) struct SpellingWalk {
/// Uid of the document the walk started on.
doc: u64,
/// File Revert generation of the document the walk started on.
reverts: u64,
/// The selected objects; None is the whole document, which Some(empty) is not.
ids: Option<Vec<u64>>,
/// The one object checked while Check All Layers is off.
@@ -66,23 +68,28 @@ fn start(app: &mut VectorcraftApp) -> Result<SpellingWalk, String> {
if app.session.active().is_none() {
return Err("no document".into());
}
let (doc, ids) = {
let (doc, reverts, ids) = {
let st = app.session.doc().map_err(|e| e.to_string())?;
// The selection (groups too: the check goes through the type inside them), or, with
// nothing selected, every visible, unlocked type object (the check's default).
let selected: Vec<u64> = st.selection.objects.iter().map(|n| n.0).collect();
(st.uid, (!selected.is_empty()).then_some(selected))
(st.uid, st.reverts, (!selected.is_empty()).then_some(selected))
};
let mut w = SpellingWalk { doc, ids, ..Default::default() };
let mut w = SpellingWalk { doc, reverts, ids, ..Default::default() };
advance(app, &mut w, None, 1)?;
Ok(w)
}
/// Open Check Spelling on the active document's type.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let w = start(app)?;
let items = items_of(app, &w)?;
let mut w = start(app)?;
let dialogs = app.dialogs().ok_or("no window")?;
let all_layers = dialogs.with(|host| host.get::<CheckSpellingDialog>().is_none_or(CheckSpellingDialog::all_layers_checked));
if !all_layers {
w.layer = w.shown.as_ref().map(|word| word.0);
advance(app, &mut w, None, 1)?;
}
let items = items_of(app, &w)?;
dialogs.with(|host| match host.get_mut::<CheckSpellingDialog>() {
Some(d) => d.restart(items),
None => {
@@ -109,7 +116,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
});
return;
}
if check_doc_uid(app, &w).is_err() {
if check_opening_drawing(app, &w).is_err() {
dialogs.with(|host| host.cancel::<CheckSpellingDialog>(ctx));
return;
}
@@ -417,17 +424,17 @@ fn shown_word(app: &VectorcraftApp, w: &SpellingWalk) -> Option<(u64, usize, usi
Some((*id, *start, *end, still_there))
}
/// Fails when the active document is not the one the walk started on.
fn check_doc_uid(app: &VectorcraftApp, w: &SpellingWalk) -> Result<(), String> {
if app.session.active().map(|st| st.uid) != Some(w.doc) {
return Err("the document was switched".into());
/// Fails when the active drawing's contents are not the ones the walk started on.
fn check_opening_drawing(app: &VectorcraftApp, w: &SpellingWalk) -> Result<(), String> {
if !app.session.active().is_some_and(|st| st.uid == w.doc && st.reverts == w.reverts) {
return Err("the document was switched or reverted".into());
}
Ok(())
}
/// The word shown, when the walk is still going and on the walk's document.
fn shown_text(app: &VectorcraftApp, w: &SpellingWalk) -> Result<Option<String>, String> {
check_doc_uid(app, w)?;
check_opening_drawing(app, w)?;
Ok(w.shown.as_ref().map(|s| s.3.clone()))
}
@@ -969,6 +976,47 @@ mod tests {
assert_eq!(plain(&app, b), "fixed y");
}
#[test]
fn reopening_keeps_the_unchecked_all_layers_scope_for_change_all() {
use crate::tests::panel_harness::Panel;
use craft::ui::dialog::StackDialog as _;
fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| host.run(ui));
}
super::pump(app, ui.ctx());
}
let _dictionary = crate::testing::custom_dictionary();
let mut app = app();
let first = text(&mut app, 50.0, WORD_A);
app.run("layer.new", json!({"name": "Other text"})).unwrap();
let second = text(&mut app, 100.0, WORD_A);
app.run("select.none", json!({})).unwrap();
let mut panel = Panel::new(app, draw);
panel.app().run(super::COMMAND, json!({})).unwrap();
panel.frame();
let checked = shown(&panel.app()).0;
let other = if checked == first { second } else { first };
panel.click("Check All Layers");
panel.app().run(super::COMMAND, json!({})).unwrap();
panel.frame();
{
let app = panel.app();
let ctx = panel.ctx();
app.dialogs().unwrap().with(|host| {
let dialog = host.get::<super::CheckSpellingDialog>().unwrap();
assert!(!dialog.all_layers_checked(), "reopening preserves the chosen scope");
let id = dialog.id();
host.set_json_field(ctx, id, "changeTo", json!("fixed")).unwrap();
});
}
panel.click("Change All");
assert_eq!(plain(&panel.app(), checked), "fixed");
assert_eq!(plain(&panel.app(), other), WORD_A, "the unchecked scope leaves the other layer's text alone");
}
fn app() -> VectorcraftApp {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
@@ -1112,13 +1160,75 @@ mod tests {
begin(&mut app);
// PLAN: the pump's close-on-switch needs the window host fixture of the hosted-dialog
// tests; this drives the guard the pump calls (`check_doc_uid`) through the walk's steps.
// tests; this drives the guard the pump calls (`check_opening_drawing`) through the walk's steps.
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let mut w = app.spelling.take().unwrap();
assert!(super::check_doc_uid(&app, &w).is_err());
assert!(super::check_opening_drawing(&app, &w).is_err());
assert!(super::ignore(&mut app, &mut w).is_err(), "no step runs on another document");
}
#[test]
fn queued_spelling_changes_leave_reverted_text_unchanged() {
use crate::tests::panel_harness::Panel;
use craft::ui::dialog::StackDialog as _;
// The host files the real button's action; the test decides when the app consumes it.
fn draw(app: &mut VectorcraftApp, ui: &mut egui::Ui) {
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| host.run(ui));
}
}
let _dictionary = crate::testing::custom_dictionary();
for button in ["Change", "Change All"] {
let mut app = app();
let saved = format!("{WORD_A} saved");
let id = text(&mut app, 50.0, &saved);
app.run("select.none", json!({})).unwrap();
app.services.read = Some(Box::new(|path: &str| std::fs::read(path).map_err(|error| error.to_string())));
app.services.write = Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|error| error.to_string())));
let dir = vectorcraft_testkit::TempDir::new("spelling-revert");
app.run("file.saveAs", json!({"path": dir.join("Spelling.vectorcraft")})).unwrap();
let state = app.session.active().unwrap();
let (uid, reverts) = (state.uid, state.reverts);
app.run("text.editRange", json!({"id": id, "start": saved.len(), "end": saved.len(), "insert": " draft"})).unwrap();
let mut panel = Panel::new(app, draw);
panel.app().run(super::COMMAND, json!({})).unwrap();
panel.frame();
let ctx = panel.ctx().clone();
let set_replacement = |app: &VectorcraftApp| {
app.dialogs().unwrap().with(|host| {
let dialog = host.get::<super::CheckSpellingDialog>().unwrap().id();
host.set_json_field(&ctx, dialog, "changeTo", json!("fixed")).unwrap();
});
};
set_replacement(&panel.app());
panel.click(button);
assert_eq!(plain(&panel.app(), id), format!("{saved} draft"), "the action is still queued");
panel.app().run("file.revert", json!({"confirmed": true})).unwrap();
let undo = {
let app = panel.app();
let state = app.session.active().unwrap();
assert_eq!((state.uid, state.reverts), (uid, reverts + 1));
assert_eq!(plain(&app, id), saved, "the same word and local ID were reloaded from the native file");
state.history.undo.len()
};
super::pump(&mut panel.app(), &ctx);
assert_eq!(plain(&panel.app(), id), saved, "{button} from the old walk must not edit restored text");
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
assert!(panel.app().spelling.is_none(), "the reverted walk is retired");
assert!(!panel.app().dialogs().unwrap().with(|host| host.is_open::<super::CheckSpellingDialog>()));
panel.app().run(super::COMMAND, json!({})).unwrap();
panel.frame();
set_replacement(&panel.app());
panel.click(button);
super::pump(&mut panel.app(), &ctx);
assert_eq!(plain(&panel.app(), id), "fixed saved", "a fresh check can still change the restored text");
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo + 1);
}
}
#[test]
fn check_spelling_ignores_uneditable_text() {
let _dictionary = crate::testing::custom_dictionary();
+154 -21
View File
@@ -51,6 +51,8 @@ const GLOBAL: &str = "global";
pub(crate) struct Open {
/// The dialog's id on the host.
pub id: DialogId,
/// The drawing and loaded generation whose art the dialog can adjust.
document: Option<(u64, u64)>,
/// The preview the dialog's values run as one interaction.
pub preview: LivePreview,
}
@@ -85,22 +87,31 @@ impl Adjust {
fn try_open(self, app: &mut VectorcraftApp) -> Result<(), String> {
const NO_WINDOW: &str = "no window to open the dialog in";
let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?;
if let Some(old) = (self.slot)(&mut app.color_dialogs).take() {
let document = app.session.active().map(|st| (st.uid, st.reverts));
if let Some(old) = (self.slot)(&mut app.color_dialogs).take()
&& old.document == document
{
old.preview.cancel(app);
}
let dialog = HostedParamDialog::new(&ctx, self.kind, (self.initial)(), move |fields| {
ParamDialog::new(self.kind, self.label, (self.rows)()).values(Bind::bound(fields)).previews(true)
});
let id = host::open_held(app, dialog, move |app, answer| self.commit(app, answer)).ok_or(NO_WINDOW)?;
*(self.slot)(&mut app.color_dialogs) = Some(Open { id, preview: LivePreview::default() });
*(self.slot)(&mut app.color_dialogs) = Some(Open { id, document, preview: LivePreview::default() });
Ok(())
}
/// OK: keeps the preview as one undo step; an `Err` keeps the dialog open with the reason.
fn commit(self, app: &mut VectorcraftApp, answer: &ParamResult) -> Result<(), String> {
let live = (self.slot)(&mut app.color_dialogs).as_ref().map(|open| open.preview.clone()).unwrap_or_default();
// PLAN: assumed `LivePreview::commit(self, ..)` as the contract row says; the clone keeps the record when it fails.
live.commit(app, self.cmd, (self.params)(&answer.fields))?;
let document = app.session.active().map(|st| (st.uid, st.reverts));
let open = (self.slot)(&mut app.color_dialogs).as_ref().ok_or(tl!("This adjustment can only apply to the document where it was opened."))?;
if open.document != document {
if open.document.zip(document).is_some_and(|((uid, _), (active, _))| uid == active) {
return Err(tl!("Reopen the color adjustment after reverting the drawing").into());
}
return Err(tl!("This adjustment can only apply to the document where it was opened.").into());
}
open.preview.clone().commit(app, self.cmd, (self.params)(&answer.fields))?;
*(self.slot)(&mut app.color_dialogs) = None;
Ok(())
}
@@ -108,17 +119,22 @@ impl Adjust {
/// Once per frame: previews the dialog's values while its Preview box is on, and rolls the preview back once the
/// dialog is gone without OK.
pub(super) fn pump(self, app: &mut VectorcraftApp) {
let Some(Open { id, mut preview }) = (self.slot)(&mut app.color_dialogs).take() else { return };
let Some(mut open) = (self.slot)(&mut app.color_dialogs).take() else { return };
let on_its_document = app.session.active().map(|st| (st.uid, st.reverts)) == open.document;
let shown = app.dialogs().and_then(|dialogs| {
dialogs.with(|host| host.get_mut_by_id::<HostedParamDialog>(id).map(|dialog| (dialog.is_previewing(), (self.params)(dialog.fields()))))
dialogs.with(|host| host.get_by_id::<HostedParamDialog>(open.id).map(|dialog| (dialog.is_previewing(), (self.params)(dialog.fields()))))
});
match shown {
Some((on, params)) => {
if let Some((on, params)) = shown {
if on_its_document {
// `run` reports a failed preview to the status line itself.
let _ = preview.run(app, on, self.label, self.cmd, &params);
*(self.slot)(&mut app.color_dialogs) = Some(Open { id, preview });
let _ = open.preview.run(app, on, self.label, self.cmd, &params);
} else {
// Switching or reverting the drawing rolled back the original interaction.
open.preview = LivePreview::default();
}
None => preview.cancel(app),
*(self.slot)(&mut app.color_dialogs) = Some(open);
} else if on_its_document {
open.preview.cancel(app);
}
}
}
@@ -144,7 +160,7 @@ fn slot(dialogs: &mut ColorDialogs) -> &mut Option<Open> {
/// Open the dialog with every channel at 0, adjusting fills and strokes.
pub fn open(app: &mut VectorcraftApp) {
ADJUST.open(app);
Adjust { label: tl!(ADJUST.label), ..ADJUST }.open(app);
}
/// Previews the open dialog; one line of `dialogs::host::pump`.
@@ -201,28 +217,28 @@ fn track(key: &str, x: f32) -> Srgba {
fn channels(ui: &mut egui::Ui, fields: &mut DialogFields, _cx: &mut CustomContext) -> egui::Response {
super::form::stacked(ui, fields, |ui, fields| {
for (key, label) in mode(fields).channels {
percent_row(ui, fields, key, label, |x| track(key, x));
percent_row(ui, fields, key, tl!(label), |x| track(key, x));
}
})
}
fn rows() -> Vec<Param> {
let modes = MODES.iter().map(|m| (m.id.to_owned(), Label::from(m.label))).collect();
let modes = MODES.iter().map(|m| (m.id.to_owned(), Label::from(tl!(m.label)))).collect();
let with_model = MODES.iter().map(|m| m.id).filter(|id| *id != GLOBAL);
vec![
Param::new("mode", "Color Mode", ParamKind::choice(modes, Some("rgb".to_owned()))),
Param::new("convert", "Convert", ParamKind::bool(false)).enabled_when_in("mode", with_model),
Param::read_only_text("note", "", "Shifts the tints of global and spot colors; other colors stay.").visible_when("mode", GLOBAL),
Param::new("mode", tl!("Color Mode"), ParamKind::choice(modes, Some("rgb".to_owned()))),
Param::new("convert", tl!("Convert"), ParamKind::bool(false)).enabled_when_in("mode", with_model),
Param::read_only_text("note", "", tl!("Shifts the tints of global and spot colors; other colors stay.")).visible_when("mode", GLOBAL),
Param::custom("channels", "Channels", channels).companions(channel_keys()),
Param::section("Adjust Options"),
Param::new("fill", "Fill", ParamKind::bool(true)),
Param::new("stroke", "Stroke", ParamKind::bool(true)),
Param::new("fill", tl!("Fill"), ParamKind::bool(true)),
Param::new("stroke", tl!("Stroke"), ParamKind::bool(true)),
]
}
#[cfg(test)]
mod tests {
use craft::ui::dialog::dialog_id;
use craft::ui::dialog::{HeldOk, dialog_id};
use vectorcraft_engine::Session;
use super::*;
@@ -250,6 +266,123 @@ mod tests {
host::pump(app, ctx);
}
fn two_documents(color: &str) -> (VectorcraftApp, egui::Context, [u64; 2]) {
let (mut app, ctx) = app();
let ids = [0, 1].map(|_| {
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50})).unwrap()["id"].as_u64().unwrap();
app.run("paint.setFill", json!({"color": color})).unwrap();
id
});
app.run("document.activate", json!({"index": 0})).unwrap();
(app, ctx, ids)
}
#[test]
fn color_adjustment_stays_in_its_opening_document_with_preview_on() {
let (mut app, ctx, [source, destination]) = two_documents("#808080");
let id = dialog_id(KIND);
let dialogs = app.dialogs().unwrap();
let source_undo = app.session.active().unwrap().history.undo.len();
open(&mut app);
set(&app, &ctx, "r", json!(20));
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, source), "#b38080");
app.run("document.activate", json!({"index": 1})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, destination), "#808080", "another document is not previewed");
assert!(!app.session.in_interaction());
confirm(&mut app, &ctx);
assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Refused(_))));
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
app.run("document.activate", json!({"index": 0})).unwrap();
confirm(&mut app, &ctx);
assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Accepted)));
assert_eq!(fill_hex(&app, source), "#b38080");
assert_eq!(app.session.active().unwrap().history.undo.len(), source_undo + 1);
}
#[test]
fn color_adjustment_stays_in_its_opening_document_with_preview_off() {
let (mut app, ctx, [source, destination]) = two_documents("#cc6666");
let id = dialog_id(crate::dialogs::saturate::KIND);
let dialogs = app.dialogs().unwrap();
crate::dialogs::saturate::open(&mut app);
dialogs.with(|host| {
host.set_json_field(&ctx, id, "intensity", json!(-100)).unwrap();
host.set_json_field(&ctx, id, "preview", json!(false)).unwrap();
});
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, source), "#cc6666");
app.run("document.activate", json!({"index": 1})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
dialogs.with(|host| host.confirm_by_id(&ctx, id));
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, destination), "#cc6666", "another document is not adjusted");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Refused(_))));
app.run("document.activate", json!({"index": 0})).unwrap();
dialogs.with(|host| host.confirm_by_id(&ctx, id));
host::pump(&mut app, &ctx);
assert!(matches!(dialogs.with(|h| h.held_state(id)), Some(HeldOk::Accepted)));
assert_ne!(fill_hex(&app, source), "#cc6666");
}
#[test]
fn stale_color_adjustment_leaves_the_fill_restored_by_revert() {
let (mut app, ctx) = app();
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let dir = vectorcraft_testkit::TempDir::new("color-adjustment-revert");
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap()["id"].as_u64().unwrap();
app.run("paint.setFill", json!({"color": "#808080"})).unwrap();
app.run("file.saveAs", json!({"path": dir.join("color.vectorcraft")})).unwrap();
app.run("paint.setFill", json!({"color": "#406080"})).unwrap();
open(&mut app);
let doc = app.session.active().unwrap();
let version = (doc.uid, doc.reverts);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let doc = app.session.active().unwrap();
assert_eq!(doc.uid, version.0);
assert_ne!(doc.reverts, version.1);
let undo = doc.history.undo.len();
app.run("select.set", json!({"ids": [id]})).unwrap();
assert_eq!(fill_hex(&app, id), "#808080");
set(&app, &ctx, "r", json!(20));
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, id), "#808080", "old Preview leaves the saved fill in place");
set(&app, &ctx, "preview", json!(false));
confirm(&mut app, &ctx);
assert_eq!(fill_hex(&app, id), "#808080", "old OK leaves the saved fill in place");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
}
#[test]
fn color_adjustment_cancel_leaves_the_new_documents_interaction_intact() {
let (mut app, ctx, [source, destination]) = two_documents("#808080");
let id = dialog_id(KIND);
let dialogs = app.dialogs().unwrap();
open(&mut app);
set(&app, &ctx, "r", json!(20));
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, source), "#b38080");
app.run("document.activate", json!({"index": 1})).unwrap();
app.session.begin_interaction("Change fill").unwrap();
app.session.preview("paint.setFill", &json!({"color": "#00ff00"})).unwrap();
dialogs.with(|host| host.cancel_by_id(&ctx, id));
host::pump(&mut app, &ctx);
assert_eq!(fill_hex(&app, destination), "#00ff00", "cancelling the old dialog leaves the new edit intact");
assert!(app.session.in_interaction());
}
#[test]
fn previews_live_and_commits_one_undo_step() {
let (mut app, ctx) = app();
@@ -3,7 +3,7 @@
//! as they are.
//!
//! Fields: `name`. The group being renamed (its name, its place in the list of color groups, the names of
//! its swatches and the uid of its document when the dialog opened) is kept by the dialog's OK.
//! its swatches and the document's identity and revert generation at opening) is kept by the dialog's OK.
use craft::ui::patterns::form_dialogs::{DialogFields, Param, ParamKind, ParamResult};
use serde_json::{Value, json};
@@ -16,8 +16,9 @@ pub const KIND: &str = "colorGroupOptions";
/// A color group as the dialog found it: what tells it apart from the others, since color groups carry nothing else.
struct Identity {
/// The uid of the document the dialog opened on.
/// The document and its saved-content generation when the dialog opened.
doc: u64,
reverts: u64,
/// The group's place in the document's list of color groups.
at: usize,
/// The group's name.
@@ -40,14 +41,15 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let st = app.session.active().ok_or("no document open")?;
let at = st.doc.swatch_groups.iter().position(|g| g.name == group).ok_or_else(|| format!("no colour group `{group}`"))?;
let g = &st.doc.swatch_groups[at];
let identity = Identity { doc: st.uid, at, group: g.name.clone(), swatches: g.swatches.iter().map(|w| w.name.clone()).collect() };
let identity =
Identity { doc: st.uid, reverts: st.reverts, at, group: g.name.clone(), swatches: g.swatches.iter().map(|w| w.name.clone()).collect() };
let mut fields = DialogFields::new();
fields.set("name", g.name.as_str());
let ctx = app.ui_ctx.clone().ok_or(NO_WINDOW)?;
let rows = vec![Param::new("name", field_label(tl!("Name:")), ParamKind::text(""))];
let dialog = hosted(&ctx, KIND, tl!("Color Group Options"), fields, rows, false);
let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
// Another document or group: it closes as Cancel does and renames nothing.
// A different document, a revert, or a different group closes the draft without renaming.
if !same_group(app, &identity) {
return Ok(());
}
@@ -60,9 +62,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
}
/// Whether the dialog's group is still in its document, at the place in the list, under the name
/// and with the swatches it opened with, and that document is the active one.
/// and with the swatches it opened with, and the document is still active and has not been reverted.
fn same_group(app: &VectorcraftApp, identity: &Identity) -> bool {
let Some(st) = app.session.active().filter(|st| st.uid == identity.doc) else { return false };
let Some(st) = app.session.active().filter(|st| st.uid == identity.doc && st.reverts == identity.reverts) else { return false };
st.doc
.swatch_groups
.get(identity.at)
@@ -101,6 +103,42 @@ mod tests {
app.session.active().unwrap().history.undo.len()
}
#[test]
fn an_old_rename_draft_keeps_the_color_group_restored_by_revert() {
let (ctx, mut app) = app();
let dir = vectorcraft_testkit::TempDir::new("color-group-options-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string())));
app.run("file.saveAs", json!({"path": dir.join("colors.vectorcraft")})).unwrap();
let color = |app: &VectorcraftApp| app.session.active().unwrap().doc.swatch("Bright Red").unwrap().paint.color();
let saved_color = color(&app);
let saved_groups = groups(&app);
let st = app.session.active().unwrap();
let (uid, reverts) = (st.uid, st.reverts);
app.run("swatch.edit", json!({"name": "Bright Red", "color": "#1784ca"})).unwrap();
assert_ne!(color(&app), saved_color);
app.run("ui.colorGroupOptions", json!({"group": "Brights"})).unwrap();
let id = dialog_id(KIND);
app.dialogs().unwrap().with(|h| h.set_json_field(&ctx, id, "name", json!("Old palette draft"))).unwrap();
app.run("file.revert", json!({"confirmed": true})).unwrap();
let restored = app.session.active().unwrap();
assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1));
assert_eq!(color(&app), saved_color);
assert_eq!(groups(&app), saved_groups);
let undo = undo_len(&app);
crate::tests::picks::answer_dialog(&mut app, id, &[], true);
assert_eq!(groups(&app), saved_groups, "old Color Group Options must leave the restored group named Brights");
assert_eq!(color(&app), saved_color);
assert_eq!(undo_len(&app), undo);
app.run("ui.colorGroupOptions", json!({"group": "Brights"})).unwrap();
ok(&mut app, &ctx, "Restored palette");
assert!(groups(&app).iter().any(|name| name == "Restored palette"));
assert_eq!(undo_len(&app), undo + 1);
}
/// Whether the dialog is still open.
fn is_open(app: &VectorcraftApp) -> bool {
app.dialogs().unwrap().with(|h| h.get_by_id::<craft::ui::patterns::form_dialogs::HostedParamDialog>(dialog_id(KIND)).is_some())
+45 -19
View File
@@ -3,7 +3,7 @@
//! as one undo step through `paint.setFill` / `paint.setStroke` and makes the colour the Color
//! Guide's base colour; Cancel puts the art back. Opened for an artboard (Properties › Artboards ›
//! Fill), it shows the colour on the artboard's paper and OK keeps it through
//! `artboard.setProps {index, color}`.
//! `artboard.setProps {index, color}`. Preview and OK require the opening document to be active.
//!
//! A command dialog's colour row raises a `ColorRequest`; [`pump`] opens a picker over that dialog
//! and answers the row with its OK. Every picker has the Color Swatches view; one over Recolor
@@ -43,11 +43,26 @@ pub(crate) enum Target {
/// The stroke proxy.
Stroke,
/// The background colour of this artboard.
Artboard(usize),
Artboard { document: u64, reverts: u64, index: usize },
/// A colour row `key` of the open dialog `parent`.
Answer { parent: DialogId, key: String },
}
impl Target {
fn in_active_document(&self, app: &VectorcraftApp) -> bool {
self.document_problem(app).is_none()
}
fn document_problem(&self, app: &VectorcraftApp) -> Option<&'static str> {
let Self::Artboard { document, reverts, .. } = self else { return None };
match app.session.active() {
Some(st) if st.uid == *document && st.reverts == *reverts => None,
Some(st) if st.uid == *document => Some(tl!("The document was reverted. Reopen this dialog to continue.")),
_ => Some(tl!("The active document changed while the Color Picker was open")),
}
}
}
/// One open Color Picker: what the dialog itself does not know.
pub(crate) struct Open {
/// The dialog's id on the window's host.
@@ -150,14 +165,17 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
None | Some(Value::Null) => None,
Some(v) => {
let index = v.as_u64().and_then(|i| usize::try_from(i).ok());
let found = index.and_then(|i| Some((i, app.session.active()?.doc.artboards.get(i)?.color)));
let (i, color) = found.ok_or("no such artboard")?;
Some((i, color.unwrap_or(Color::WHITE)))
let found = index.and_then(|i| {
let st = app.session.active()?;
let color = st.doc.artboards.get(i)?.color.unwrap_or(Color::WHITE);
Some((st.uid, st.reverts, i, color))
});
Some(found.ok_or("no such artboard")?)
}
};
let color = match (p.get("color"), artboard) {
(Some(v), _) => color_value(v).ok_or_else(|| format!("bad color {v}"))?,
(None, Some((_, c))) => c,
(None, Some((_, _, _, c))) => c,
(None, None) => proxy_color(app, stroke),
};
let dialogs = app.dialogs().ok_or("no window")?;
@@ -184,19 +202,20 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) {
dialog = dialog.kept(model_values(&color));
}
// PLAN: assumed the dialog's own `instance` keeps artboards apart; the host replaces a picker only for the same target.
if let Some((i, _)) = artboard {
dialog = dialog.instance(i);
// The host replaces a picker only for the same document and artboard.
if let Some((document, _, index, _)) = artboard {
dialog = dialog.instance((document, index));
}
let id = dialogs.with(|h| h.open(dialog));
// A picker the open replaced leaves its preview behind: end it.
let before = app.color_dialogs.pickers.len();
app.color_dialogs.pickers.retain(|o| o.id != id);
if app.color_dialogs.pickers.len() != before {
let _ = app.session.cancel_interaction();
if let Some(at) = app.color_dialogs.pickers.iter().position(|open| open.id == id) {
let retired = app.color_dialogs.pickers.remove(at);
if retired.target.in_active_document(app) {
let _ = app.session.cancel_interaction();
}
}
let target = match artboard {
Some((i, _)) => Target::Artboard(i),
Some((document, reverts, index, _)) => Target::Artboard { document, reverts, index },
None if stroke => Target::Stroke,
None => Target::Fill,
};
@@ -274,6 +293,13 @@ fn finish(
open: &mut Open,
result: Option<DialogResult<craft::color_ui::ui::ColorPickerResult>>,
) {
// Switching or restoring a drawing ends the preview belonging to its old contents.
if let Some(reason) = open.target.document_problem(app) {
if matches!(result, Some(DialogResult::Ok(_))) {
app.status(reason);
}
return;
}
let preview = std::mem::take(&mut open.preview);
match (result, &open.target) {
(Some(DialogResult::Ok(r)), Target::Answer { parent, key }) => {
@@ -293,7 +319,7 @@ fn finish(
/// The command that applies colour `c` to the picker's target, and its params.
fn paint_command(target: &Target, c: Color) -> (&'static str, Value) {
match target {
Target::Artboard(i) => ("artboard.setProps", json!({ "index": i, "color": color_json(&c) })),
Target::Artboard { index, .. } => ("artboard.setProps", json!({ "index": index, "color": color_json(&c) })),
Target::Stroke => ("paint.setStroke", json!({ "color": color_json(&c) })),
Target::Fill | Target::Answer { .. } => ("paint.setFill", json!({ "color": color_json(&c) })),
}
@@ -314,18 +340,18 @@ fn in_document_model(app: &VectorcraftApp, c: Color) -> Color {
/// then only becomes the default paint, on OK). An artboard shows it with or without a selection.
fn preview(app: &mut VectorcraftApp, open: &mut Open, picked: &PickedColor) {
// A picker over a command dialog only fills a row; the dialog previews it.
if matches!(open.target, Target::Answer { .. }) {
if matches!(open.target, Target::Answer { .. }) || !open.target.in_active_document(app) {
return;
}
let (cmd, params) = paint_command(&open.target, in_document_model(app, color_of(picked)));
let untouched = !app.session.in_interaction() && picked.color == open.start;
let artboard = matches!(open.target, Target::Artboard(_));
let artboard = matches!(open.target, Target::Artboard { .. });
let selected = artboard || app.session.active().is_some_and(|st| !st.selection.objects.is_empty());
if untouched || !selected {
return;
}
let label = match open.target {
Target::Artboard(_) => "Artboard Options",
Target::Artboard { .. } => "Artboard Options",
Target::Stroke => "Stroke Color",
_ => "Fill Color",
};
@@ -342,7 +368,7 @@ fn commit(app: &mut VectorcraftApp, open: &Open, preview: LivePreview, picked: &
let (cmd, params) = paint_command(&open.target, c);
preview.commit(app, cmd, params)?;
// A color picked for the fill or stroke also becomes the Color Guide's base color.
if !matches!(open.target, Target::Artboard(_)) {
if !matches!(open.target, Target::Artboard { .. }) {
crate::panels::color_guide::choose_base(app, c);
}
Ok(())
@@ -52,6 +52,15 @@ fn artboard_color(app: &VectorcraftApp) -> Option<Color> {
app.session.doc().unwrap().doc.artboards[1].color
}
fn two_documents_with_artboards() -> (VectorcraftApp, egui::Context) {
let (mut app, ctx) = app();
app.run("artboard.new", json!({})).unwrap();
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
app.run("artboard.new", json!({})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
(app, ctx)
}
/// The selected art takes each colour as it is picked; OK keeps the last as one undo step and
/// Cancel puts the art back.
#[test]
@@ -101,6 +110,71 @@ fn an_artboard_shows_its_background_color_live() {
assert!(app.run("ui.colorPicker", json!({"artboard": 9})).is_err());
}
#[test]
fn the_artboard_picker_previews_only_in_its_opening_document() {
let (mut app, ctx) = two_documents_with_artboards();
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
set_hex(&mut app, &ctx, "#ff0000");
assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#ff0000"));
app.run("document.activate", json!({"index": 1})).unwrap();
let before = undo_len(&app);
set_hex(&mut app, &ctx, "#00ff00");
assert_eq!(artboard_color(&app), None, "the other document never previews the color");
assert!(!app.session.in_interaction());
assert_eq!(undo_len(&app), before);
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(artboard_color(&app), None, "leaving the source rolled its preview back");
let before = undo_len(&app);
ok(&mut app, &ctx);
assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#00ff00"));
assert_eq!(undo_len(&app), before + 1);
}
#[test]
fn confirming_an_artboard_picker_in_another_document_leaves_both_unchanged() {
let (mut app, ctx) = two_documents_with_artboards();
let source_undo = undo_len(&app);
app.run("ui.colorPicker", json!({"artboard": 1, "color": "#00ff00"})).unwrap();
frame(&mut app, &ctx);
app.run("document.activate", json!({"index": 1})).unwrap();
let destination_undo = undo_len(&app);
ok(&mut app, &ctx);
assert_eq!(app.ui.status, "The active document changed while the Color Picker was open");
assert_eq!(artboard_color(&app), None);
assert_eq!(undo_len(&app), destination_undo);
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(artboard_color(&app), None);
assert_eq!(undo_len(&app), source_undo);
}
#[test]
fn canceling_an_artboard_picker_preserves_the_other_documents_interaction() {
let (mut app, ctx) = two_documents_with_artboards();
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
set_hex(&mut app, &ctx, "#ff0000");
app.run("document.activate", json!({"index": 1})).unwrap();
app.begin_interaction("Other edit").unwrap();
app.session.preview("artboard.setProps", &json!({"index": 1, "color": "#445566"})).unwrap();
cancel(&mut app, &ctx);
assert!(app.session.in_interaction(), "the current document keeps its own interaction");
assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#445566"));
}
#[test]
fn artboard_pickers_for_the_same_index_in_different_documents_have_separate_instances() {
let (mut app, _) = two_documents_with_artboards();
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
let first = id(&app);
app.run("document.activate", json!({"index": 1})).unwrap();
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
assert_ne!(id(&app), first);
assert_eq!(app.color_dialogs.pickers.len(), 2);
}
/// OK on an untouched picker for an artboard without a color leaves it without one and adds no
/// undo step; a white the opener passes as `color` is set.
#[test]
@@ -213,3 +287,44 @@ fn sampler_above_the_field_previews_and_cancel_restores_the_original() {
cancel(&mut app, &ctx);
assert_eq!(fill_hex(&app), original);
}
#[test]
fn the_artboard_picker_leaves_restored_artboards_unchanged() {
for accept in [true, false] {
let (mut app, ctx) = app();
app.run("artboard.new", json!({})).unwrap();
app.run("artboard.setProps", json!({"index": 1, "color": "#123456"})).unwrap();
let dir = vectorcraft_testkit::TempDir::new("artboard-picker-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
app.run("artboard.setProps", json!({"index": 1, "color": "#ff0000"})).unwrap();
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
set_hex(&mut app, &ctx, "#abcdef");
assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#abcdef"));
app.run("file.revert", json!({"confirmed": true})).unwrap();
let restored = artboard_color(&app);
assert_eq!(restored.map(|c| c.to_hex()).as_deref(), Some("#123456"));
let steps = undo_len(&app);
frame(&mut app, &ctx);
assert_eq!(artboard_color(&app), restored);
assert!(!app.session.in_interaction());
if accept {
ok(&mut app, &ctx);
assert!(app.ui.status.contains("document was reverted"));
} else {
app.begin_interaction("New drawing edit").unwrap();
cancel(&mut app, &ctx);
assert!(app.session.in_interaction());
app.session.cancel_interaction().unwrap();
}
assert_eq!(artboard_color(&app), restored);
assert_eq!(undo_len(&app), steps);
app.run("ui.colorPicker", json!({"artboard": 1})).unwrap();
set_hex(&mut app, &ctx, "#abcdef");
ok(&mut app, &ctx);
assert_eq!(artboard_color(&app).map(|c| c.to_hex()).as_deref(), Some("#abcdef"));
}
}
+73 -2
View File
@@ -88,8 +88,10 @@ pub(crate) fn open(app: &mut VectorcraftApp, command: &str, label: &str, mut par
let token = Arc::new(());
let dialog = {
let (key, heading, opening) = (command.to_string(), heading_label(label), params.clone());
HostedParamDialog::command(&ctx, command, fields, move |_: &mut DialogFields| {
ParamDialog::command(key.clone(), heading.clone(), command_params(&key, &opening, setting)).previews(previews)
HostedParamDialog::command(&ctx, command, fields, move |fields| {
ParamDialog::command(key.clone(), heading.clone(), command_params(&key, &opening, setting))
.previews(previews)
.values(craft::ui::contract::Bind::bound(fields))
})
// The Preview box starts off, as production's dialogs did (#5360).
.preview_off()
@@ -590,6 +592,75 @@ mod tests {
crate::panels::pattern_options::repeat_fields(app).unwrap()["cols"].as_u64().unwrap()
}
#[test]
fn hosted_commands_keep_actual_keyboard_edits_until_ok() {
use egui::accesskit::Role;
use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
let viewport = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
let type_and_accept = |app: &mut VectorcraftApp, command: &str, name: &str, role: Role, value: &str, preview: bool| {
let ctx = app.ui_ctx.clone().unwrap();
let time = std::cell::Cell::new(0.0);
let frame = |app: &mut VectorcraftApp, events: Vec<Event>| {
ctx.enable_accesskit();
time.set(time.get() + 0.1);
crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time.get()), screen_rect: Some(viewport), ..Default::default() })
};
let locate = |app: &mut VectorcraftApp, label: &str, role: Role| {
frame(app, vec![]);
let nodes = frame(app, vec![]).platform_output.accesskit_update.unwrap().nodes;
let node = nodes
.iter()
.map(|(_, node)| node)
.find(|node| {
node.role() == role
&& (node.label() == Some(label)
|| node.labelled_by().iter().any(|id| nodes.iter().any(|(key, name)| key == id && name.label() == Some(label))))
})
.unwrap_or_else(|| panic!("{command}: missing {role:?} {label}"));
let b = node.bounds().unwrap();
let at = pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5);
assert!(viewport.contains(at), "{command}: {label} is reachable");
at
};
let click = |app: &mut VectorcraftApp, at: Pos2| {
frame(app, vec![Event::PointerMoved(at)]);
for pressed in [true, false] {
frame(app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
frame(app, vec![]);
};
frame(app, vec![]);
assert_eq!(ctx.content_rect(), viewport);
crate::menus::invoke(app, command, json!({}));
let id = id_of(app);
if preview {
let toggle = locate(app, "Preview", Role::CheckBox);
click(app, toggle);
assert!(app.session.in_interaction(), "{command}: pointer turns Preview on");
}
let at = locate(app, name, role);
click(app, at);
frame(app, vec![Event::Key { key: Key::A, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND }]);
frame(app, vec![Event::Text(value.to_owned())]);
frame(app, vec![Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }]);
frame(app, vec![]);
let live_columns = preview.then(|| cols(app));
let ok = locate(app, "OK", Role::Button);
click(app, ok);
frame(app, vec![]);
assert!(app.dialogs().unwrap().with(|h| h.get_by_id::<HostedParamDialog>(id).is_none()), "{command}: OK closes the dialog");
live_columns
};
let (mut repeat, _) = prepared("object.repeat.options");
let preview = type_and_accept(&mut repeat, "object.repeat.options", "Columns", Role::SpinButton, "5", true);
let (mut selection, _) = prepared("select.save");
type_and_accept(&mut selection, "select.save", "Name", Role::TextInput, "Typed selection", false);
let saved = &selection.session.active().unwrap().doc.saved_selections;
assert_eq!((preview, cols(&repeat), saved.last().map(|s| s.name.as_str())), (Some(5), 5, Some("Typed selection")));
}
#[test]
fn area_type_options_choices_match_the_params_doc() {
let doc = vectorcraft_engine::find_command("text.areaOptions").unwrap().params;
+45 -17
View File
@@ -26,6 +26,7 @@
use std::cell::RefCell;
use std::ops::RangeInclusive;
use std::path::Path;
use std::sync::Arc;
use craft::behavior::{ColumnKey, ColumnWidth, Selection, SelectionChange, keyed};
@@ -56,11 +57,11 @@ use egui::{Context, Ui};
use serde_json::{Map, Value, json};
use vectorcraft_doc::text::{COMPOSITE_BASELINE, COMPOSITE_SCALE, COMPOSITE_SIZE, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX};
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CustomCharSet};
use vectorcraft_engine::cmd::compositefonts::{EXTS, file_bytes};
use vectorcraft_engine::cmd::compositefonts::{EXTS, MAX_FILE_BYTES, file_bytes};
use vectorcraft_text::FontDb;
use crate::VectorcraftApp;
use crate::file_asks::{Owner, ask, open_params, save};
use crate::file_asks::{Owner, ask_while, open_params, save};
use crate::font_menu::{PickerHold, family_picker, family_sets};
mod sample;
@@ -135,6 +136,8 @@ enum PartEdit {
/// The Composite Fonts dialog on the dialog host. OK files the fonts for [`pump`], which runs
/// [`COMMAND`] and answers whether the dialog may close.
pub struct CompositeFontsDialog {
/// The document whose fonts the draft edits.
document: (u64, u64),
fonts: Vec<CompositeFont>,
/// The index of the font picked.
selected: usize,
@@ -156,6 +159,8 @@ pub struct CompositeFontsDialog {
held: HeldAnswer<Vec<CompositeFont>>,
/// The file dialog a Load…, Replace… or Save… asked for, which [`pump`] takes.
file: Option<PresetFileRequest>,
/// Identifies the draft that opened a Load or Replace picker.
file_owner: Arc<()>,
/// Why the last action on the fonts or sets was refused.
refusal: Option<String>,
/// The words of the file status line, kept from the last pass for [`pump`].
@@ -165,9 +170,9 @@ pub struct CompositeFontsDialog {
/// Open Composite Fonts on the active document's composite fonts, the first one picked, with the
/// custom character sets and the sample hidden and nothing typed.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let fonts = app.session.active().ok_or("no document open")?.doc.composite_fonts.to_vec();
let document = app.session.active().ok_or("no document open")?;
let dialogs = app.dialogs().ok_or("no window to show the dialog in")?;
let dialog = CompositeFontsDialog::new(fonts, crate::font_menu::hold(app));
let dialog = CompositeFontsDialog::new((document.uid, document.reverts), document.doc.composite_fonts.to_vec(), crate::font_menu::hold(app));
dialogs.with(|host| host.open(dialog));
Ok(Value::Null)
}
@@ -239,10 +244,11 @@ fn part_mut(f: &mut CompositeFont, at: usize) -> Option<&mut CompositePart> {
impl CompositeFontsDialog {
/// The dialog over `fonts`, the first picked.
fn new(fonts: Vec<CompositeFont>, hold: PickerHold) -> Self {
fn new(document: (u64, u64), fonts: Vec<CompositeFont>, hold: PickerHold) -> Self {
let mut sample = Map::new();
sample::defaults(&mut sample);
CompositeFontsDialog {
document,
fonts,
selected: 0,
set: 0,
@@ -255,6 +261,7 @@ impl CompositeFontsDialog {
hold,
held: HeldAnswer::new(),
file: None,
file_owner: Arc::new(()),
refusal: None,
words: None,
}
@@ -848,25 +855,35 @@ impl StackDialog for CompositeFontsDialog {
/// Runs once per frame after the shell pass: answers OK's held fonts with the command's result, and takes the
/// file dialog a Load…, Replace… or Save… asked for.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
let Some((held, request)) = with_dialog(app, |d| (d.held.take(), d.file.take())) else { return };
if let Some(fonts) = held {
// A name two fonts share or a value out of range keeps the dialog open with the reason.
let answer = app.run(COMMAND, json!({ "fonts": fonts })).map(|_| ()).map_err(Label::from);
let Some((held, request)) = with_dialog(app, |d| {
let held = d.held.take().map(|fonts| (d.document, fonts));
let request = d.file.take().map(|request| (request, Arc::clone(&d.file_owner)));
(held, request)
}) else {
return;
};
if let Some(((document, reverts), fonts)) = held {
let answer = match app.session.active().filter(|active| active.uid == document) {
Some(active) if active.reverts == reverts => app.run(COMMAND, json!({ "fonts": fonts })).map(|_| ()).map_err(Label::from),
Some(_) => Err(Label::from(tl!("The document was reverted. Reopen this dialog to continue."))),
None => Err(Label::from(tl!("Composite Fonts can only change the document where it was opened."))),
};
with_dialog(app, |d| d.held.answer(answer));
}
if let Some(request) = request {
ask_file(app, request);
if let Some((request, owner)) = request {
ask_file(app, request, owner);
}
}
/// Asks for the file `request` names; the answer reaches the dialog by [`with_dialog`].
fn ask_file(app: &mut VectorcraftApp, request: PresetFileRequest) {
/// Asks for the file `request` names. Open answers belong to the draft that requested them.
fn ask_file(app: &mut VectorcraftApp, request: PresetFileRequest, owner: Arc<()>) {
// The pick's answer comes back through the continuation, so the immediate `{pending}` value says nothing more.
match request.clone() {
PresetFileRequest::Open { purpose, filter, extensions, replace, .. } => {
let exts: Vec<&str> = extensions.iter().map(String::as_str).collect();
let pick = PickRequest::open(purpose).filter(filter, &exts);
ask(app, pick, Owner::Free, move |app, picked| load_file(app, &request, replace, &picked));
let current = move |app: &VectorcraftApp| with_dialog(app, |draft| Arc::ptr_eq(&draft.file_owner, &owner)).unwrap_or(false);
ask_while(app, pick, Owner::Free, current, move |app, picked| load_file(app, &request, replace, &picked));
}
PresetFileRequest::Save { purpose, filter, extensions, file_name, bytes, .. } => {
let exts: Vec<&str> = extensions.iter().map(String::as_str).collect();
@@ -882,14 +899,25 @@ fn ask_file(app: &mut VectorcraftApp, request: PresetFileRequest) {
/// Reads the fonts of the file picked and gives them to the dialog (Load… or Replace…).
fn load_file(app: &mut VectorcraftApp, request: &PresetFileRequest, replace: bool, picked: &Picked) -> Result<Value, String> {
// PLAN: assumed fl.A23 `file_asks::open_params(&Picked) -> Option<Map<String, Value>>`; `None` is a cancelled pick.
// Refuse the browser's raw file before open_params allocates its base64 representation.
if let Picked::Contents(files) = picked
&& files.first().is_some_and(|(_, bytes)| bytes.len() > MAX_FILE_BYTES)
{
return Err(vectorcraft_engine::EngineError::BadParams { cmd: IMPORT.into(), msg: "the file is larger than 4 MB".into() }.to_string());
}
let Some(mut params) = open_params(picked) else { return Ok(Value::Null) };
let browser_name = params.remove("name");
let name = picked
.first_path()
.as_deref()
.or_else(|| browser_name.as_ref().and_then(Value::as_str).map(Path::new))
.and_then(Path::file_name)
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
params.insert("apply".into(), json!(false));
let read = app.run(IMPORT, Value::Object(params))?;
let fonts: Vec<CompositeFont> = serde_json::from_value(read["fonts"].clone()).map_err(|e| e.to_string())?;
with_dialog(app, |d| d.load(fonts, replace));
let name = picked.first_path().and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned())).unwrap_or_default();
// Only the file's name goes into the status line.
if let Some(event) = request.loaded(name, Vec::new()) {
report(app, event);
}
@@ -61,6 +61,108 @@ fn names(app: &VectorcraftApp) -> Vec<String> {
app.session.active().unwrap().doc.composite_fonts.iter().map(|f| f.name.clone()).collect()
}
#[test]
fn delayed_load_and_replace_leave_the_reopened_composite_fonts_draft_alone() {
let choices: [(PresetCommands, &[&str]); 2] = [(PresetCommands::Load, &["New draft", "From file"]), (PresetCommands::Replace, &["From file"])];
for (command, expected_live) in choices {
let mut app = app();
let picker = scripted(&mut app);
let ctx = ctx(&app);
open(&mut app).unwrap();
let bytes = dialog(&mut app, |d| {
d.new_font("From file".into());
file_bytes(&d.fonts).unwrap()
});
let dir = vectorcraft_testkit::TempDir::new("composite-fonts-late-picker");
let file = dir.join("picked.vccomposite");
std::fs::write(&file, bytes).unwrap();
let path = file.to_str().unwrap();
request(&mut app, command, None);
assert_eq!(picker.requests().len(), 1);
cancel(&mut app);
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("New draft".into()));
picker.answer(&[path]);
poll(&mut app, &ctx);
let draft_names = |app: &mut VectorcraftApp| dialog(app, |d| d.fonts.iter().map(|font| font.name.clone()).collect::<Vec<_>>());
assert_eq!(draft_names(&mut app), ["New draft"], "the stale picker leaves the new draft alone");
request(&mut app, command, None);
assert_eq!(picker.requests().len(), 2);
picker.answer(&[path]);
poll(&mut app, &ctx);
assert_eq!(draft_names(&mut app), expected_live, "a picker opened by the new draft still works");
assert!(names(&app).is_empty(), "a picker only edits the draft");
}
}
#[test]
fn load_and_replace_accept_a_browser_picked_file() {
let choices: [(PresetCommands, &[&str]); 2] = [(PresetCommands::Load, &["Draft", "From Web"]), (PresetCommands::Replace, &["From Web"])];
for (command, expected) in choices {
let mut app = app();
let picker = scripted(&mut app);
let ctx = ctx(&app);
open(&mut app).unwrap();
let bytes = dialog(&mut app, |d| {
d.new_font("From Web".into());
file_bytes(&d.fonts).unwrap()
});
cancel(&mut app);
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("Draft".into()));
let dialogs = app.dialogs().unwrap();
ctx.run_ui(egui::RawInput::default(), |ui| dialogs.with(|host| host.run(ui))).textures_delta.clear();
let step = steps(&app);
request(&mut app, command, None);
picker.answer_contents(&[("picked.vccomposite", &bytes)]);
poll(&mut app, &ctx);
let draft_names = dialog(&mut app, |d| d.fonts.iter().map(|font| font.name.clone()).collect::<Vec<_>>());
assert_eq!(draft_names, expected, "{}", app.ui.status);
assert!(app.ui.status.contains("picked.vccomposite"), "{}", app.ui.status);
assert!(names(&app).is_empty(), "picking a file edits only the draft");
assert_eq!(steps(&app), step);
}
}
/// Load and Replace refuse an oversized browser file while preserving both the draft and artwork;
/// a later valid file still reaches that same draft.
#[test]
fn oversized_browser_composite_font_files_leave_the_draft_unchanged() {
for command in [PresetCommands::Load, PresetCommands::Replace] {
let mut app = app();
let picker = scripted(&mut app);
let ctx = ctx(&app);
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("Draft".into()));
let dialogs = app.dialogs().unwrap();
ctx.run_ui(egui::RawInput::default(), |ui| dialogs.with(|host| host.run(ui))).textures_delta.clear();
let before = dialog(&mut app, |d| d.fonts.clone());
let bytes = file_bytes(&before).unwrap();
let step = steps(&app);
let large = vec![b' '; MAX_FILE_BYTES + 1];
request(&mut app, command, None);
picker.answer_contents(&[("large.vccomposite", &large)]);
poll(&mut app, &ctx);
assert_eq!(
app.ui.status,
vectorcraft_engine::EngineError::BadParams { cmd: IMPORT.into(), msg: "the file is larger than 4 MB".into() }.to_string()
);
assert_eq!(dialog(&mut app, |d| d.fonts.clone()), before);
assert!(names(&app).is_empty());
assert_eq!(steps(&app), step);
request(&mut app, command, None);
picker.answer_contents(&[("valid.vccomposite", &bytes)]);
poll(&mut app, &ctx);
assert!(app.ui.status.contains("valid.vccomposite"), "{}", app.ui.status);
assert_eq!(dialog(&mut app, |d| d.fonts.clone()), before);
assert!(names(&app).is_empty());
assert_eq!(steps(&app), step);
}
}
fn steps(app: &VectorcraftApp) -> usize {
app.session.active().unwrap().history.undo.len()
}
@@ -133,6 +235,41 @@ fn composite_fonts_change_on_ok_as_one_undo_step() {
assert!(names(&app).is_empty());
}
#[test]
fn a_held_composite_fonts_ok_keeps_the_draft_with_its_opening_document() {
let mut app = app();
app.run("file.new", json!({"width": 440, "height": 440})).unwrap();
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("Destination only".into()));
ok(&mut app).unwrap();
let destination = (names(&app), steps(&app));
app.run("document.activate", json!({"index": 0})).unwrap();
let source = (names(&app), steps(&app));
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("From the source".into()));
let ctx = ctx(&app);
let id = dialog_id(KIND);
let dialogs = app.dialogs().unwrap();
dialogs.with(|host| {
assert!(!host.confirm_by_id(&ctx, id));
assert_eq!(host.held_state(id), Some(HeldOk::Waiting));
});
app.run("document.activate", json!({"index": 1})).unwrap();
pump(&mut app, &ctx);
assert_eq!((names(&app), steps(&app)), destination, "the other document keeps its fonts and undo history");
assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_))));
assert!(is_open(&app));
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!((names(&app), steps(&app)), source);
ok(&mut app).unwrap();
assert_eq!(names(&app), ["From the source"]);
assert_eq!(steps(&app), source.1 + 1);
assert!(!is_open(&app));
}
/// New is based on the font picked and takes the next free name; a name two fonts share, or one
/// left empty, keeps the dialog open and changes nothing.
#[test]
@@ -474,3 +611,33 @@ fn custom_character_sets_draw_their_characters_and_the_buttons() {
assert!(p.shows(name), "{name} is drawn");
}
}
#[test]
fn composite_fonts_approval_does_not_replace_definitions_restored_by_revert() {
let mut app = app();
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("Saved Font".into()));
ok(&mut app).unwrap();
let dir = vectorcraft_testkit::TempDir::new("composite-fonts-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("Unsaved Font".into()));
ok(&mut app).unwrap();
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("Stale Draft Font".into()));
app.run("file.revert", json!({"confirmed": true})).unwrap();
let restored_step = steps(&app);
assert_eq!(names(&app), ["Saved Font"]);
assert_eq!(ok(&mut app), Err("The document was reverted. Reopen this dialog to continue.".into()));
assert_eq!(names(&app), ["Saved Font"]);
assert_eq!(steps(&app), restored_step);
cancel(&mut app);
open(&mut app).unwrap();
dialog(&mut app, |d| d.new_font("Fresh Font".into()));
ok(&mut app).unwrap();
assert_eq!(names(&app), ["Saved Font", "Fresh Font"]);
}
+39 -4
View File
@@ -89,11 +89,19 @@ pub(crate) struct Question(StandardPrompt);
struct Asked {
command: String,
params: Value,
/// The document that must still be active for a document-specific confirmation.
document: Option<DocumentOwner>,
/// The automation roots in force when asked: the command runs under them.
scope: ScopeHandle,
/// Automation asked ([`VectorcraftApp::automation_asked`]): the command runs as automation.
automated: bool,
}
struct DocumentOwner {
uid: u64,
reverts: Option<u64>,
}
wrapped_dialog!(Question, StandardPrompt, KIND);
/// A message with a Close button.
@@ -129,6 +137,24 @@ pub(crate) struct ReplaceFiles {
/// Ask `message` (with an optional `detail` line), both in the UI language; OK runs `command`
/// with `params`.
pub fn ask(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, params: Value) {
ask_for(app, None, message, detail, command, params);
}
/// Ask about the active document. OK is valid only while that document is active.
pub(crate) fn ask_in_document(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, params: Value) {
if let Some(document) = app.session.active().map(|st| DocumentOwner { uid: st.uid, reverts: None }) {
ask_for(app, Some(document), message, detail, command, params);
}
}
/// Ask about items in the active document. Reverting its contents invalidates the approval.
pub(crate) fn ask_in_document_contents(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str, params: Value) {
if let Some(document) = app.session.active().map(|st| DocumentOwner { uid: st.uid, reverts: Some(st.reverts) }) {
ask_for(app, Some(document), message, detail, command, params);
}
}
fn ask_for(app: &mut VectorcraftApp, document: Option<DocumentOwner>, message: &str, detail: &str, command: &str, params: Value) {
let Some(dialogs) = app.dialogs() else {
app.status(format!("{message} (no window to ask in)"));
return;
@@ -137,7 +163,7 @@ pub fn ask(app: &mut VectorcraftApp, message: &str, detail: &str, command: &str,
if !detail.is_empty() {
prompt = prompt.paragraph(detail.to_string());
}
let asked = Asked { command: command.to_string(), params, scope: ScopeHandle::capture(), automated: app.automation_asked() };
let asked = Asked { command: command.to_string(), params, document, scope: ScopeHandle::capture(), automated: app.automation_asked() };
let prompt = prompt.button(PromptChoice::Proceed, tl!("OK")).button(PromptChoice::Cancel, tl!("Cancel")).tag(asked);
dialogs.with(|host| host.open(Question(prompt)));
}
@@ -263,10 +289,19 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
};
if let Some(DialogResult::Ok(mut answer)) = dialogs.with(|host| host.take::<Question>())
&& answer.choice == PromptChoice::Proceed
&& let Some(Asked { command, params, scope, automated }) = answer.take_tag::<Asked>()
&& let Err(e) = scope.run(|| crate::file_asks::as_automated(app, automated, |app| app.run(&command, params)))
&& let Some(Asked { command, params, document, scope, automated }) = answer.take_tag::<Asked>()
{
app.status(e);
let refusal = document.and_then(|owner| match app.session.active() {
Some(st) if st.uid == owner.uid => {
owner.reverts.filter(|reverts| *reverts != st.reverts).map(|_| tl!("The document was reverted. Reopen this dialog to continue."))
}
_ => Some(tl!("This dialog was opened in a different document.")),
});
if let Some(reason) = refusal {
app.status(reason);
} else if let Err(e) = scope.run(|| crate::file_asks::as_automated(app, automated, |app| app.run(&command, params))) {
app.status(e);
}
}
// The host opens queued messages in `enqueue` order, so the one closed is the oldest.
while dialogs.with(|host| host.take::<Message>()).is_some() {
+40 -1
View File
@@ -9,6 +9,7 @@
use std::collections::BTreeSet;
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::runtime::env::{LengthUnits, UnitKind};
use serde_json::{Value, json};
@@ -65,7 +66,9 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
}
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let lengths = general_lengths(app);
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| dialog(fields.text("radii") == Some("relative"), lengths));
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| {
dialog(fields.text("radii") == Some("relative"), lengths).values(Bind::bound(fields))
});
open_held(app, dialog, ok).ok_or("no window")?;
Ok(Value::Null)
}
@@ -341,4 +344,40 @@ mod tests {
app.run("edit.undo", json!({})).unwrap();
assert!(!lc(&app).0, "undo brings back absolute radii");
}
#[test]
fn a_live_radius_edit_applies_to_the_corners_that_opened_the_dialog() {
use craft::ui::testing::Fixture;
use std::cell::RefCell;
use std::rc::Rc;
let (app, id) = app();
let app = Rc::new(RefCell::new(app));
let shown = app.clone();
let mut fixture = Fixture::new(move |ui| {
let mut app = shown.borrow_mut();
let dialogs = app.dialogs().unwrap();
dialogs.with(|host| host.run(ui));
super::super::host::pump(&mut app, ui.ctx());
});
fixture.room(egui::vec2(880.0, 720.0));
let undo = {
let mut app = app.borrow_mut();
app.ui_ctx = Some(fixture.ctx().clone());
app.run("ui.corners", json!({"id": id, "corners": [1, 3]})).unwrap();
app.session.active().unwrap().history.undo.len()
};
fixture.settle();
let radius = fixture.by_label("Radius:").or_else(|| fixture.by_label("Radius")).expect("the Corners radius field");
fixture.click(&radius).key(egui::Key::A, egui::Modifiers::COMMAND).type_text("12").key(egui::Key::Tab, egui::Modifiers::NONE).settle();
let ok = fixture.by_label("OK").expect("the Corners confirmation button");
fixture.click(&ok).settle();
let mut app = app.borrow_mut();
assert_eq!(corners(&app, id).0, [0.0, 12.0, 0.0, 12.0], "OK applies the typed radius only to the opening corners");
assert!(!is_open(&app));
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
app.run("edit.undo", json!({})).unwrap();
assert_eq!(corners(&app, id).0, [0.0; 4]);
}
}
+42 -14
View File
@@ -41,6 +41,12 @@ fn state_id() -> egui::Id {
egui::Id::unique("custom-dictionary-words")
}
#[derive(Clone)]
struct Draft {
original: Vec<String>,
words: Vec<String>,
}
/// The custom dictionary's words.
fn dictionary(app: &mut VectorcraftApp) -> Result<Vec<String>, String> {
let words = app.run(COMMAND, json!({})).map_err(|e| e.to_string())?;
@@ -65,7 +71,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
];
let dialog = HostedListManager::new(COMMAND, tl!("Edit Custom Dictionary"), tl!("Entry:"), actions).entries(entries(&words)).renames(WORD);
dialogs.with(|host| host.open(dialog));
ctx.data_mut(|data| data.insert_temp(state_id(), words));
ctx.data_mut(|data| data.insert_temp(state_id(), Draft { original: words.clone(), words }));
Ok(Value::Null)
}
@@ -79,7 +85,8 @@ fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, choice: &ListManagerChoi
if choice.action == DONE {
return save(app, ctx);
}
let Some(mut words) = ctx.data(|data| data.get_temp::<Vec<String>>(state_id())) else { return };
let Some(mut draft) = ctx.data(|data| data.get_temp::<Draft>(state_id())) else { return };
let words = &mut draft.words;
match (choice.action.as_str(), choice.entry.as_deref()) {
(ADD, _) => match custom_word(&choice.name) {
Some(word) => words.push(word),
@@ -100,24 +107,20 @@ fn apply(app: &mut VectorcraftApp, ctx: &egui::Context, choice: &ListManagerChoi
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| {
if let Some(list) = host.get_dyn_mut(id()).and_then(|d| d.downcast_mut::<HostedListManager>()) {
list.set_entries(entries(&words));
list.set_entries(entries(words));
}
});
}
ctx.data_mut(|data| data.insert_temp(state_id(), words));
ctx.data_mut(|data| data.insert_temp(state_id(), draft));
}
/// Done: deletes the words no longer in the list and adds the new ones in one
/// `text.spelling.editDictionary`, saved once. When it can't be saved, none of it is kept: the
/// dialog stays open with the error, its list as edited, and Cancel leaves the dictionary as it was.
fn save(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(words) = ctx.data(|data| data.get_temp::<Vec<String>>(state_id())) else { return };
let orig = match dictionary(app) {
Ok(orig) => orig,
Err(e) => return app.status(e),
};
let remove: Vec<&String> = orig.iter().filter(|w| !words.contains(w)).collect();
let add: Vec<&String> = words.iter().filter(|w| !orig.contains(w)).collect();
let Some(Draft { original, words }) = ctx.data(|data| data.get_temp::<Draft>(state_id())) else { return };
let remove: Vec<&String> = original.iter().filter(|w| words.binary_search(w).is_err()).collect();
let add: Vec<&String> = words.iter().filter(|w| original.binary_search(w).is_err()).collect();
match app.run(EDIT, json!({ "remove": remove, "add": add })) {
Ok(_) => {
if let Some(dialogs) = app.dialogs() {
@@ -136,8 +139,8 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
if let Some(choice) = dialogs.with(|host| host.get_mut_by_id::<HostedListManager>(id()).and_then(HostedListManager::take_choice)) {
apply(app, ctx, &choice);
}
if dialogs.with(|host| host.take_by_id::<HostedListManager>(id())).is_some() {
ctx.data_mut(|data| data.remove::<Vec<String>>(state_id()));
if dialogs.with(|host| host.take_by_id::<HostedListManager>(id()).is_some() && host.get_by_id::<HostedListManager>(id()).is_none()) {
ctx.data_mut(|data| data.remove::<Draft>(state_id()));
}
}
@@ -190,7 +193,7 @@ mod tests {
/// The dialog's list, of `mine` (other tests may have their words in the dictionary meanwhile).
fn words(app: &VectorcraftApp, mine: &[&str]) -> Vec<String> {
let ctx = app.ui_ctx.clone().expect("a window");
let all = ctx.data(|data| data.get_temp::<Vec<String>>(super::state_id())).unwrap_or_default();
let all = ctx.data(|data| data.get_temp::<super::Draft>(super::state_id())).map(|draft| draft.words).unwrap_or_default();
all.into_iter().filter(|w| mine.contains(&w.as_str())).collect()
}
@@ -235,6 +238,31 @@ mod tests {
forget(&mut app, &[A, B, C]);
}
#[test]
fn done_preserves_dictionary_changes_made_after_opening() {
let _dictionary = crate::testing::custom_dictionary();
const KEPT: &str = "zqvdictoutsideadd";
const REMOVED: &str = "zqvdictoutsideremove";
let mut app = app();
forget(&mut app, &[A, B, KEPT, REMOVED]);
for word in [A, REMOVED] {
app.run("text.spelling.addWord", json!({"word": word})).unwrap();
}
let mut p = Panel::new(app, draw);
super::open(&mut p.app()).unwrap();
p.app().run("text.spelling.addWord", json!({"word": KEPT})).unwrap();
p.app().run("text.spelling.removeWord", json!({"word": REMOVED})).unwrap();
p.click(A);
p.click("Delete");
enter(&mut p, B);
p.click("Add");
p.click("Done");
let mut app = p.app();
let final_words = [A, B, KEPT, REMOVED].map(|word| has(&mut app, word));
forget(&mut app, &[A, B, KEPT, REMOVED]);
assert_eq!(final_words, [false, true, true, false]);
}
/// Done that can't be saved keeps none of the edits: the dialog stays open and Cancel leaves the
/// dictionary as it was.
#[test]
+100 -4
View File
@@ -143,13 +143,15 @@ struct Edited {
pick: Option<ColorRequest>,
}
/// The Properties section's colour picker: the dialog it opened, the colour it answers for and the dimension it edits.
/// The Properties section's colour picker and the swatch, document and dimension it edits.
#[derive(Clone, Debug)]
pub(crate) struct Pick {
/// The open colour picker.
pub id: DialogId,
/// The key of the swatch that asked.
pub key: String,
/// The document and loaded contents that contain the dimension.
pub document: (u64, u64),
/// The dimension the colour goes to.
pub target: NodeId,
}
@@ -340,8 +342,16 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &egui::Context) {
let Some(pick) = app.object_dialogs.dimension.clone() else { return };
let Some(finished) = dialogs.with(|host| host.take_by_id::<ColorPickerDialog>(pick.id)) else { return };
app.object_dialogs.dimension = None;
if let Some(ColorPickerResult { picked, .. }) = finished.ok()
&& let Some(mut o) = options_of(app, pick.target)
let Some(ColorPickerResult { picked, .. }) = finished.ok() else { return };
let Some(source) = app.session.active().filter(|st| st.uid == pick.document.0) else {
app.status("The active document changed while the Color Picker was open");
return;
};
if source.reverts != pick.document.1 {
app.status(tl!("The document was reverted. Reopen this dialog to continue."));
return;
}
if let Some(mut o) = options_of(app, pick.target)
&& set_color(&mut o, &pick.key, picked.color)
{
update(app, pick.target.0, &o);
@@ -715,12 +725,13 @@ pub fn properties_section(app: &mut VectorcraftApp, ui: &mut Ui) {
});
}
if let Some(request) = edited.pick
&& let Some(document) = app.session.active().map(|st| (st.uid, st.reverts))
&& let Some(dialogs) = app.dialogs()
{
let key = request.key.clone();
let picker = ColorPickerDialog::from_request(request).swatch_view(super::color_picker::swatch_view(app));
let picker = dialogs.with(|host| host.open(picker));
app.object_dialogs.dimension = Some(Pick { id: picker, key, target: NodeId(id) });
app.object_dialogs.dimension = Some(Pick { id: picker, key, document, target: NodeId(id) });
}
Row::new().show(ui, |ui, _| {
if Button::new(tl!("Apply to All")).show(ui).clicked()
@@ -775,6 +786,91 @@ mod tests {
serde_json::from_value(app.borrow().session.tool_options_of("dimension")["style"].clone()).unwrap()
}
#[test]
fn dimension_properties_picker_keeps_its_source_document() {
use crate::tests::panel_harness::Panel;
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
let mut add_dimension = |line_color: [u8; 3]| {
app.run("file.new", json!({"width":200,"height":200})).unwrap();
let created = app.run("dimension.create", json!({"a":[0,0],"b":[72,0],"options":{"lineColor":line_color}})).unwrap();
let id = created["id"].as_u64().unwrap();
app.run("select.set", json!({"ids":[id]})).unwrap();
NodeId(id)
};
let source = add_dimension([17, 34, 51]);
let other = add_dimension([51, 34, 17]);
assert_eq!(source, other, "each drawing allocates its own object ids");
app.run("document.activate", json!({"index":0})).unwrap();
let mut panel = Panel::new(app, properties_section);
let ctx = panel.ctx().clone();
let host = WindowDialogs::of(&ctx, &WindowKey::main());
panel.click("Line Color");
let picker = panel.app().object_dialogs.dimension.as_ref().unwrap().id;
host.with(|h| h.set_json_field(&ctx, picker, "color", json!("#123456"))).unwrap();
panel.app().run("document.activate", json!({"index":1})).unwrap();
assert!(host.with(|h| h.confirm_by_id(&ctx, picker)));
pump(&mut panel.app(), &ctx);
assert_eq!(options_of(&panel.app(), other).unwrap().line_color, [51, 34, 17]);
panel.app().run("document.activate", json!({"index":0})).unwrap();
assert_eq!(options_of(&panel.app(), source).unwrap().line_color, [17, 34, 51]);
panel.click("Line Color");
let picker = panel.app().object_dialogs.dimension.as_ref().unwrap().id;
host.with(|h| h.set_json_field(&ctx, picker, "color", json!("#123456"))).unwrap();
assert!(host.with(|h| h.confirm_by_id(&ctx, picker)));
pump(&mut panel.app(), &ctx);
assert_eq!(options_of(&panel.app(), source).unwrap().line_color, [18, 52, 86]);
panel.app().run("edit.undo", json!({})).unwrap();
assert_eq!(options_of(&panel.app(), source).unwrap().line_color, [17, 34, 51]);
}
#[test]
fn dimension_properties_picker_cannot_edit_a_dimension_restored_by_file_revert() {
use crate::tests::panel_harness::Panel;
let dir = vectorcraft_testkit::TempDir::new("dimension-color-revert");
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let made = app.run("dimension.create", json!({"a": [0, 0], "b": [72, 0], "options": {"lineColor": [17, 34, 51]}})).unwrap();
let dimension = NodeId(made["id"].as_u64().unwrap());
app.run("file.saveAs", json!({"path": dir.join("Dimension.vectorcraft")})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
app.run("select.set", json!({"ids": [dimension.0]})).unwrap();
let state = app.session.active().unwrap();
let opening = (state.uid, state.reverts);
let mut panel = Panel::new(app, properties_section);
let ctx = panel.ctx().clone();
let host = WindowDialogs::of(&ctx, &WindowKey::main());
let choose = |panel: &mut Panel| {
panel.click("Line Color");
let id = panel.app().object_dialogs.dimension.as_ref().unwrap().id;
host.with(|h| h.set_json_field(&ctx, id, "color", json!("#123456"))).unwrap();
id
};
let stale = choose(&mut panel);
panel.app().run("file.revert", json!({"confirmed": true})).unwrap();
let (drawing, undo) = {
let app = panel.app();
let state = app.session.active().unwrap();
((state.uid, state.reverts), state.history.undo.len())
};
assert_eq!(drawing, (opening.0, opening.1 + 1));
assert!(host.with(|h| h.confirm_by_id(&ctx, stale)));
pump(&mut panel.app(), &ctx);
assert_eq!(options_of(&panel.app(), dimension).unwrap().line_color, [17, 34, 51]);
assert_eq!(panel.app().session.active().unwrap().history.undo.len(), undo);
panel.app().run("select.set", json!({"ids": [dimension.0]})).unwrap();
let fresh = choose(&mut panel);
assert!(host.with(|h| h.confirm_by_id(&ctx, fresh)));
pump(&mut panel.app(), &ctx);
assert_eq!(options_of(&panel.app(), dimension).unwrap().line_color, [18, 52, 86]);
}
/// The Arrow Style rule of `ui.dialog.set` and the saved style: a head clears with `arrowStyle`, a built-in head
/// sets its entry's two values, a name that is no built-in head is refused, and a draft that does not validate
/// cannot be saved.
+46 -2
View File
@@ -73,7 +73,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
fields["rgbProfile"] = json!(rgb.unwrap_or_else(|| WORKING_RGB.into()));
fields["cmykProfile"] = json!(cmyk.unwrap_or_else(|| WORKING_CMYK.into()));
fields["convertColors"] = json!(true);
let (source, mode, setup) = (st.uid, st.doc.color_mode, st.doc.setup.clone());
let (source, mode, setup) = ((st.uid, st.reverts), st.doc.color_mode, st.doc.setup.clone());
let Value::Object(map) = fields else { return Err("document.setup reported no settings".into()) };
let presets: Vec<String> = app.session.flattener_presets().into_iter().map(|p| p.name).collect();
let display = app.display_profile.transform(app.session.prefs.monitor_profile_display);
@@ -186,8 +186,12 @@ fn color_commands(app: &VectorcraftApp, fields: &Map<String, Value>) -> Result<V
}
fn confirm(app: &mut VectorcraftApp, fields: &DialogFields) -> Result<Value, String> {
if app.session.active().is_none_or(|st| Some(st.uid) != app.document_setup_source) {
let source = app.document_setup_source.and_then(|(uid, reverts)| app.session.active().filter(|st| st.uid == uid).map(|st| (st, reverts)));
let Some((doc, reverts)) = source else {
return Err(tl!("Document Setup can only change the document where it was opened.").to_owned());
};
if doc.reverts != reverts {
return Err(tl!("Reopen Document Setup after reverting the drawing.").to_owned());
}
let map = json_map(fields);
let params = nest(map.iter().filter(|(k, _)| !is_ui_only(k)).map(|(k, v)| (k.clone(), v.clone())).collect());
@@ -700,6 +704,46 @@ mod tests {
check_source_document(true);
}
#[test]
fn a_revert_refuses_a_stale_document_setup_for_both_confirmation_paths() {
for edit_artboards in [false, true] {
let (mut app, ctx) = new_app();
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let dir = vectorcraft_testkit::TempDir::new("document-setup-revert");
let path = dir.join("setup.vectorcraft");
app.run("document.setup", json!({"bleed": [2, 2, 2, 2]})).unwrap();
app.run("file.saveAs", json!({"path": path})).unwrap();
app.run("document.setup", json!({"bleed": [7, 7, 7, 7]})).unwrap();
app.run("file.documentSetup", json!({})).unwrap();
set(&app, &ctx, "bleed", json!([9, 9, 9, 9]));
let source = app.session.doc().unwrap();
let (uid, generation) = (source.uid, source.reverts);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let reverted = app.session.doc().unwrap();
assert_eq!(reverted.uid, uid);
assert_ne!(reverted.reverts, generation);
let undo = reverted.history.undo.len();
if edit_artboards {
set(&app, &ctx, "editArtboards", json!(true));
super::pump(&mut app, &ctx);
} else {
assert!(!press_ok(&mut app, &ctx));
}
assert!(is_open(&app));
assert_eq!(app.session.tool_id(), "selection");
let reverted = app.session.doc().unwrap();
assert_eq!(reverted.doc.setup.bleed, [2.0; 4]);
assert_eq!(reverted.history.undo.len(), undo);
app.run("file.documentSetup", json!({})).unwrap();
set(&app, &ctx, "bleed", json!([5, 5, 5, 5]));
assert!(press_ok(&mut app, &ctx));
assert_eq!(app.session.doc().unwrap().doc.setup.bleed, [5.0; 4]);
}
}
#[test]
fn edit_artboards_applies_settings_and_closes_the_dialog() {
let (mut app, ctx) = setup_open();
+359 -21
View File
@@ -10,7 +10,7 @@
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use std::sync::{Arc, Weak};
use craft::imaging::ui::filter_gallery::{
EffectChange, EffectLayer, EffectParameters, EffectStack, FilterCatalog, FilterCategory, FilterGallerySession, FilterIndex, FilterTree,
@@ -20,9 +20,9 @@ use craft::theme::variant::Tone;
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
use craft::ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, HoldsOk, StackDialog, dialog_id};
use craft::ui::display::Picture;
use craft::ui::display::{Picture, PictureSize};
use craft::ui::layout_components::{Row, Stack};
use craft::ui::list::ThumbAspect;
use craft::ui::list::{ThumbAspect, ThumbSize};
use craft::ui::notices::{Notice, NoticeLayout};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue};
use craft::ui::primitives::textures::{Revision, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails};
@@ -32,6 +32,7 @@ use craft::ui::runtime::words::CommonWords;
use craft::ui::sections::{DialogRole, FooterButton};
use egui::{Context, Ui};
use serde_json::{Map, Value, json};
use vectorcraft_doc::Selection;
use vectorcraft_effects::{EffectInfo, PIXEL_EFFECTS, PixelSpace};
use vectorcraft_geom::{Affine, Point};
@@ -45,7 +46,7 @@ use crate::file_asks::Owner;
/// Thumbnail of one filter, in pixels at most. The drawing is original; the filter is this app's.
const THUMB: usize = 36;
/// In-dialog preview, in pixels, drawn at twice this size.
/// Sample image dimensions before the dialog scales the image to its display size.
const PREVIEW_W: usize = 120;
const PREVIEW_H: usize = 84;
@@ -75,35 +76,121 @@ struct StackEntry {
params: Map<String, Value>,
}
/// What the app keeps of the open gallery: the dialog's id and the canvas preview it runs.
/// What the app keeps of the open gallery and the canvas preview it runs.
pub(crate) struct Open {
id: DialogId,
opening: Arc<()>,
source: (u64, u64),
preview: LivePreview,
preview_owner: Option<PreviewOwner>,
}
/// The interaction and batch preview last written by this gallery.
struct PreviewOwner {
selection: Weak<Selection>,
batch: Option<(String, Value)>,
}
impl Open {
fn check_source(&self, app: &VectorcraftApp) -> Result<(), String> {
let Some(doc) = app.session.active().filter(|doc| doc.uid == self.source.0) else {
return Err(tl!("Return to the original drawing to apply these effects").into());
};
if doc.reverts != self.source.1 {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
Ok(())
}
fn owns_preview(&self, app: &VectorcraftApp) -> bool {
app.session.active().filter(|doc| (doc.uid, doc.reverts) == self.source).and_then(|doc| doc.interaction.as_ref()).is_some_and(|interaction| {
self.preview_owner.as_ref().is_some_and(|owner| {
owner.selection.upgrade().is_some_and(|selection| Arc::ptr_eq(&selection, &interaction.selection))
&& owner.batch == interaction.preview
})
})
}
fn cancel_preview(self, app: &mut VectorcraftApp) {
if self.owns_preview(app) {
self.preview.cancel(app);
}
}
fn ready_to_edit(&mut self, app: &mut VectorcraftApp) -> Result<bool, String> {
if self.owns_preview(app) {
return Ok(true);
}
self.preview = LivePreview::default();
self.preview_owner = None;
if app.session.in_interaction() {
app.keep_typing()?;
}
Ok(!app.session.in_interaction())
}
fn run_preview(&mut self, app: &mut VectorcraftApp, on: bool, batch: &Value) -> Result<(), String> {
if (on || self.owns_preview(app)) && self.ready_to_edit(app)? {
let ran = self.preview.run(app, on, LABEL, COMMAND, batch);
if !on {
self.preview_owner = None;
} else if ran.is_some() {
self.preview_owner = app
.session
.active()
.and_then(|doc| doc.interaction.as_ref())
.map(|interaction| PreviewOwner { selection: Arc::downgrade(&interaction.selection), batch: interaction.preview.clone() });
}
}
Ok(())
}
}
/// Opens the gallery on the current selection. OK is held: [`commit`] keeps the previewed stack, and a refusal
/// keeps the dialog open with its reason; Cancel takes the canvas preview away.
pub fn open(app: &mut VectorcraftApp, _: &Value) -> Result<Value, String> {
if app.session.active().is_none_or(|s| s.selection.is_empty()) {
let Some(doc) = app.session.active().filter(|doc| !doc.selection.is_empty()) else {
return Err(tl!("Select artwork to apply effects").into());
}
};
let source = (doc.uid, doc.reverts);
let dialog = EffectGalleryDialog::new(app);
let rollback = |app: &mut VectorcraftApp| {
if let Some(open) = app.effect_dialogs.gallery.take() {
open.preview.cancel(app);
let opening = Arc::clone(&dialog.opening);
let cancelled = Arc::clone(&opening);
let rollback = move |app: &mut VectorcraftApp| {
if app.effect_dialogs.gallery.as_ref().is_some_and(|open| Arc::ptr_eq(&cancelled, &open.opening))
&& let Some(open) = app.effect_dialogs.gallery.take()
{
open.cancel_preview(app);
}
};
let options = HeldOptions { cancel: Some(Box::new(rollback)), ..HeldOptions::default() };
let id = open_held_with(app, dialog, commit, options).ok_or("no window")?;
app.effect_dialogs.gallery = Some(Open { id, preview: LivePreview::default() });
if let Some(old) = app.effect_dialogs.gallery.take() {
old.cancel_preview(app);
}
app.effect_dialogs.gallery = Some(Open { id, opening, source, preview: LivePreview::default(), preview_owner: None });
Ok(Value::Null)
}
/// The held OK: keeps the previewed stack as one undo step. A refused batch leaves the gallery and its preview open.
fn commit(app: &mut VectorcraftApp, batch: &Value) -> Result<(), String> {
let Some(open) = app.effect_dialogs.gallery.take() else { return app.run(COMMAND, batch.clone()).map(drop) };
let committed = open.preview.clone().commit(app, COMMAND, batch.clone()).map(drop);
fn commit(app: &mut VectorcraftApp, answer: &GalleryAnswer) -> Result<(), String> {
let Some(mut open) = app.effect_dialogs.gallery.take() else {
return Err(tl!("The Effect Gallery is closed").into());
};
if !Arc::ptr_eq(&answer.opening, &open.opening) {
app.effect_dialogs.gallery = Some(open);
return Err(tl!("The Effect Gallery is closed").into());
}
let ready = open
.check_source(app)
.and_then(|()| if open.ready_to_edit(app)? { Ok(()) } else { Err(tl!("Finish the current edit before applying the effects").into()) });
if let Err(why) = ready {
app.effect_dialogs.gallery = Some(open);
return Err(why);
}
let committed = std::mem::take(&mut open.preview).commit(app, COMMAND, answer.batch.clone()).map(drop);
if committed.is_err() {
open.preview_owner = None;
app.effect_dialogs.gallery = Some(open);
}
committed
@@ -116,7 +203,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) {
let Some(mut open) = app.effect_dialogs.gallery.take() else { return };
let id = open.id;
let shown = dialogs.with(|host| {
host.get_mut_by_id::<EffectGalleryDialog>(id).map(|dialog| {
host.get_mut_by_id::<EffectGalleryDialog>(id).filter(|dialog| Arc::ptr_eq(&open.opening, &dialog.opening)).map(|dialog| {
let visible = dialog.entries(true);
let asked = dialog.asked.take().map(|layer| (Arc::clone(&dialog.opening), layer));
(dialog.preview_on && !visible.is_empty(), stack_batch_params(&visible), asked)
@@ -126,8 +213,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) {
app.effect_dialogs.gallery = Some(open);
return;
};
// `run` reports a failed preview itself.
let _ = open.preview.run(app, on, LABEL, COMMAND, &batch);
if open.check_source(app).is_ok()
&& let Err(why) = open.run_preview(app, on, &batch)
{
app.status(why);
}
app.effect_dialogs.gallery = Some(open);
if let Some((opening, layer)) = asked {
ask_texture(app, id, opening, layer);
@@ -137,6 +227,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) {
/// Load Texture follows `layer` within its gallery opening and drops the reply when either is gone.
fn ask_texture(app: &mut VectorcraftApp, id: DialogId, opening: Arc<()>, layer: LayerId) {
effect::pick_texture(app, Owner::Free, move |app, _, fields| {
let live = app.effect_dialogs.gallery.as_ref().is_some_and(|open| {
Arc::ptr_eq(&opening, &open.opening) && app.session.documents().iter().any(|doc| (doc.uid, doc.reverts) == open.source)
});
if !live {
return;
}
let Some(dialogs) = app.dialogs() else { return };
dialogs.with(|host| {
if let Some(dialog) = host.get_mut_by_id::<EffectGalleryDialog>(id).filter(|dialog| Arc::ptr_eq(&opening, &dialog.opening)) {
@@ -291,15 +387,22 @@ impl EffectGalleryDialog {
}
}
/// The stack filed for OK and the opening that supplied it.
#[derive(Clone)]
pub(crate) struct GalleryAnswer {
opening: Arc<()>,
batch: Value,
}
impl HoldsOk for EffectGalleryDialog {
type Answer = Value;
type Answer = GalleryAnswer;
fn held_ok(self) -> Self {
self
}
fn take_ok(&mut self) -> Option<Value> {
self.held.take()
fn take_ok(&mut self) -> Option<GalleryAnswer> {
Some(GalleryAnswer { opening: Arc::clone(&self.opening), batch: self.held.take()? })
}
fn answer_ok(&mut self, answer: Result<(), Label>) {
@@ -356,7 +459,7 @@ impl StackDialog for EffectGalleryDialog {
let Some(layer) = effects.get(current) else { return };
let image = || color_image(&preview_rgba(&visible, PREVIEW_W, PREVIEW_H), PREVIEW_W, PREVIEW_H);
Stack::new().show(ui, |ui, _| {
Picture::new(tl!("Preview"), key, &image).aspect(ThumbAspect::new(10, 7)).show(ui);
Picture::new(tl!("Preview"), key, &image).aspect(ThumbAspect::new(10, 7)).extent(PictureSize::Sample(ThumbSize::Large)).show(ui);
Row::new().show(ui, |ui, _| {
let tree = FilterTree::new(index, &layer.filter, &thumbs, &Thumbs).layout(FilterTreeLayout::Lists).show(ui);
if let Some(filter) = tree.picked {
@@ -616,6 +719,122 @@ mod tests {
app.session.active().unwrap().doc.node(NodeId(node)).unwrap().appearance.effects.clone()
}
#[test]
fn localized_compact_gallery_pointer_applies_and_cancels() {
use egui::accesskit::Role;
use egui::{Event, Modifiers, MouseWheelSource, MouseWheelUnit, PointerButton, Pos2, RawInput, Rect, TouchPhase, pos2, vec2};
let viewport = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
let mut preview_heights = Vec::new();
for language in ["en", "de", "ja"] {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.session.prefs.interface_language = language.to_owned();
let lang = app.ui_language();
let ctx = app.ui_ctx.clone().unwrap();
let time = std::cell::Cell::new(0.0);
let frame = |app: &mut VectorcraftApp, events: Vec<Event>| {
ctx.enable_accesskit();
time.set(time.get() + 0.1);
crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time.get()), screen_rect: Some(viewport), ..Default::default() })
};
let locate = |app: &mut VectorcraftApp, label: &str, role: Option<Role>| {
frame(app, vec![]);
let nodes = frame(app, vec![]).platform_output.accesskit_update?.nodes;
let node = nodes.iter().map(|(_, node)| node).find(|node| {
let named = node.label() == Some(label)
|| node.labelled_by().iter().any(|id| nodes.iter().any(|(key, name)| key == id && name.label() == Some(label)));
named && role.is_none_or(|role| node.role() == role) && node.bounds().is_some()
})?;
let bounds = node.bounds()?;
Some(Rect::from_min_max(pos2(bounds.x0 as f32, bounds.y0 as f32), pos2(bounds.x1 as f32, bounds.y1 as f32)))
};
let click = |app: &mut VectorcraftApp, at: Pos2| {
assert!(viewport.contains(at), "{language}: pointer target is outside the actual 800 × 500 viewport: {at:?}");
frame(app, vec![Event::PointerMoved(at)]);
for pressed in [true, false] {
frame(app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
frame(app, vec![]);
frame(app, vec![]);
};
let reach = |app: &mut VectorcraftApp, name: &str, role: Option<Role>, x: f32| {
let mut found = None;
for _ in 0..7 {
found = locate(app, name, role);
if let Some(rect) = found.filter(|rect| viewport.contains(rect.center())) {
return rect;
}
frame(app, vec![Event::PointerMoved(pos2(x, 310.0))]);
frame(
app,
vec![Event::MouseWheel {
unit: MouseWheelUnit::Point,
delta: vec2(0.0, -110.0),
phase: TouchPhase::Move,
modifiers: Modifiers::NONE,
source: MouseWheelSource::Unknown,
}],
);
}
panic!("{language}: {name} cannot be reached in the actual viewport: {found:?}");
};
let label = |name: &'static str| crate::i18n::tr(lang, name);
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let node = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap();
let history = app.session.active().unwrap().history.undo.len();
frame(&mut app, vec![]);
assert_eq!(ctx.content_rect(), viewport);
app.run("ui.effectGalleryDialog", json!({})).unwrap();
let gallery = locate(&mut app, label("Effect Gallery"), Some(Role::Dialog)).expect("localized Effect Gallery");
let picture = locate(&mut app, label("Preview"), Some(Role::Image)).expect("localized preview image");
let ok = locate(&mut app, label("OK"), Some(Role::Button)).expect("localized OK button");
eprintln!("{language}: window {viewport:?}, Gallery {gallery:?}, picture {picture:?}, OK {ok:?}");
preview_heights.push((language, picture.height()));
assert!(app.session.in_interaction(), "{language}: initial live preview is active");
let cutout_label = crate::i18n::effect_name(lang, "artistic.cutout").unwrap();
let cutout = reach(&mut app, &cutout_label, None, 330.0);
click(&mut app, cutout.center());
assert_eq!(
effects(&app, node).first().map(|effect| effect.id.as_str()),
Some("artistic.cutout"),
"{language}: filter click updates preview"
);
let levels_label = label("Levels");
let levels = if let Some(rect) = locate(&mut app, levels_label, None) {
rect
} else {
let rect = reach(&mut app, "Levels", None, 550.0);
eprintln!("{language}: generic setting shown as Levels instead of {levels_label}");
rect
};
let preview = reach(&mut app, label("Preview"), Some(Role::CheckBox), 550.0);
eprintln!("{language}: Cutout {cutout:?}, Levels {levels:?}, Preview checkbox {preview:?}");
assert!(viewport.contains(levels.center()), "{language}: Levels numeric field is reachable");
click(&mut app, preview.center());
assert!(effects(&app, node).is_empty(), "{language}: turning Preview off restores the original");
click(&mut app, ok.center());
let applied = effects(&app, node);
assert_eq!(applied.len(), 1, "{language}: pointer OK applies one effect");
assert_eq!(applied[0].id, "artistic.cutout");
assert_eq!(app.session.active().unwrap().history.undo.len(), history + 1);
assert!(!app.session.in_interaction());
app.run("ui.effectGalleryDialog", json!({})).unwrap();
let cancel = locate(&mut app, label("Cancel"), Some(Role::Button)).expect("localized Cancel button");
assert!(app.session.in_interaction(), "{language}: reopening starts another preview");
click(&mut app, cancel.center());
let after_cancel = effects(&app, node);
assert_eq!(after_cancel.len(), 1, "{language}: pointer Cancel discards only the second preview");
assert_eq!(after_cancel[0].id, "artistic.cutout");
assert_eq!(app.session.active().unwrap().history.undo.len(), history + 1);
assert!(!app.session.in_interaction());
}
assert!(preview_heights.iter().all(|(_, height)| *height >= 64.0), "the preview is an artwork sample: {preview_heights:?}");
}
#[test]
fn stack_preview_is_one_interaction() {
let (mut app, ctx, node) = drawing();
@@ -716,4 +935,123 @@ mod tests {
assert_eq!(answers, [false, false], "a reopened gallery keeps its own textures");
let _ = std::fs::remove_dir_all(&dir);
}
fn ownership_stack(app: &VectorcraftApp, ctx: &egui::Context) {
set(app, ctx, "effects", json!([{ "filter": "artistic.cutout", "visible": true, "params": { "levels": 3 } }]));
}
fn second_drawing(app: &mut VectorcraftApp) -> u64 {
app.run("file.new", json!({"width": 220, "height": 220})).unwrap();
app.run("shape.rectangle", json!({"x": 80, "y": 80, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap()
}
fn hold_ok(app: &VectorcraftApp, ctx: &egui::Context) {
assert!(!app.dialogs().unwrap().with(|host| host.confirm_by_id(ctx, id())));
}
#[test]
fn gallery_ownership_preview_resumes_in_the_opening_drawing() {
let (mut app, ctx, original) = drawing();
ownership_stack(&app, &ctx);
frame(&mut app, &ctx);
assert_eq!(effects(&app, original)[0].id, "artistic.cutout");
let other = second_drawing(&mut app);
frame(&mut app, &ctx);
assert!(effects(&app, other).is_empty(), "gallery preview reached the other drawing");
assert!(!app.session.in_interaction());
app.run("document.activate", json!({"index": 0})).unwrap();
frame(&mut app, &ctx);
assert_eq!(effects(&app, original)[0].id, "artistic.cutout");
}
#[test]
fn gallery_ownership_ok_refuses_the_other_drawing_and_can_retry() {
let (mut app, ctx, original) = drawing();
ownership_stack(&app, &ctx);
hold_ok(&app, &ctx);
let other = second_drawing(&mut app);
let history = app.session.active().unwrap().history.undo.len();
frame(&mut app, &ctx);
assert!(effects(&app, other).is_empty(), "gallery OK reached the other drawing");
assert_eq!(app.session.active().unwrap().history.undo.len(), history);
app.run("document.activate", json!({"index": 0})).unwrap();
let history = app.session.active().unwrap().history.undo.len();
hold_ok(&app, &ctx);
frame(&mut app, &ctx);
assert_eq!(effects(&app, original)[0].id, "artistic.cutout");
assert_eq!(app.session.active().unwrap().history.undo.len(), history + 1);
}
#[test]
fn gallery_ownership_cancel_preserves_the_other_drawings_edit() {
let (mut app, ctx, _) = drawing();
ownership_stack(&app, &ctx);
frame(&mut app, &ctx);
second_drawing(&mut app);
app.session.begin_interaction("Other drawing's edit").unwrap();
app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap();
let before = app.session.active().unwrap().doc.clone();
assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id())));
frame(&mut app, &ctx);
assert!(app.session.in_interaction(), "gallery Cancel ended the other drawing's edit");
assert!(app.session.active().unwrap().doc == before);
}
#[test]
fn gallery_ownership_cancel_preserves_a_replaced_preview_in_the_same_drawing() {
let (mut app, ctx, _) = drawing();
ownership_stack(&app, &ctx);
frame(&mut app, &ctx);
app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap();
let before = app.session.active().unwrap().doc.clone();
assert!(app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, id())));
frame(&mut app, &ctx);
assert!(app.session.in_interaction(), "gallery Cancel ended another preview on the same interaction");
assert!(app.session.active().unwrap().doc == before);
}
#[test]
fn gallery_ownership_replacement_keeps_its_own_preview_and_answer() {
let (mut app, ctx, original) = drawing();
ownership_stack(&app, &ctx);
frame(&mut app, &ctx);
super::open(&mut app, &json!({})).unwrap();
set(&app, &ctx, "effects", json!([{ "filter": "artistic.cutout", "visible": true, "params": { "levels": 5 } }]));
frame(&mut app, &ctx);
assert!(app.effect_dialogs.gallery.is_some(), "a replaced gallery's Cancel removed the new opening");
assert_eq!(effects(&app, original)[0].params["levels"], 5);
hold_ok(&app, &ctx);
frame(&mut app, &ctx);
assert_eq!(effects(&app, original)[0].params["levels"], 5);
}
#[test]
fn gallery_ownership_ok_refuses_a_reloaded_drawing() {
let (mut app, ctx, original) = drawing();
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let folder = vectorcraft_testkit::TempDir::new("effect-gallery-opening-revert");
let path = folder.join("drawing.vectorcraft");
app.run("file.saveAs", json!({"path": path})).unwrap();
app.run("shape.rectangle", json!({"x": 80, "y": 80, "width": 30, "height": 30})).unwrap();
app.run("select.set", json!({"ids": [original]})).unwrap();
let source = app.session.active().unwrap();
let (uid, generation) = (source.uid, source.reverts);
ownership_stack(&app, &ctx);
hold_ok(&app, &ctx);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let reloaded = app.session.active().unwrap();
assert_eq!(reloaded.uid, uid);
assert_ne!(reloaded.reverts, generation);
app.run("select.set", json!({"ids": [original]})).unwrap();
let history = app.session.active().unwrap().history.undo.len();
frame(&mut app, &ctx);
assert!(effects(&app, original).is_empty(), "gallery OK reached the reloaded drawing");
assert_eq!(app.session.active().unwrap().history.undo.len(), history);
super::open(&mut app, &json!({})).unwrap();
ownership_stack(&app, &ctx);
hold_ok(&app, &ctx);
frame(&mut app, &ctx);
assert_eq!(effects(&app, original)[0].id, "artistic.cutout");
}
}
+68 -3
View File
@@ -103,15 +103,22 @@ pub(crate) fn effect_params(cx: &EffectCx, fields: &DialogFields) -> Vec<Param>
}
}
/// One row per default of an effect without a builder: the JSON type of the default decides the
/// kind, and the rows follow the effect's parameter documentation.
/// One row per default of a built-in effect without a builder: the JSON type of the default decides
/// the kind, labels use the UI language, and the rows follow the effect's parameter documentation.
pub(super) fn generic(cx: &EffectCx, fields: &DialogFields) -> Vec<Param> {
let id = cx.id.as_str();
let Some(info) = vectorcraft_effects::effect_info(id) else { return Vec::new() };
let relative = fields.contains("relative") && effect_rows::is_relative(fields);
let mut defaults: Vec<(&String, &Value)> = info.defaults.as_object().into_iter().flatten().collect();
defaults.sort_by_key(|(key, _)| doc_rank(info.params, key));
defaults.into_iter().filter_map(|(key, default)| generic_row(cx, key, default, relative)).collect()
defaults
.into_iter()
.filter_map(|(key, default)| {
let mut row = generic_row(cx, key, default, relative)?;
row.label = tl!(row.label.as_str()).to_owned().into();
Some(row)
})
.collect()
}
/// One row per stored value of an effect that has no rows of its own (a plug-in no longer
@@ -294,3 +301,61 @@ pub(super) fn doc_rank(doc: &str, key: &str) -> usize {
.find(|at| starts(*at) && doc.get(at + key.len()..).is_some_and(|rest| rest.starts_with(':') || rest.starts_with("?:")))
.unwrap_or(usize::MAX)
}
#[cfg(test)]
mod tests {
use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
use serde_json::json;
use vectorcraft_doc::NodeId;
use vectorcraft_engine::Session;
use crate::VectorcraftApp;
#[test]
fn gallery_cutout_setting_uses_its_localized_label() {
let viewport = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
let mut shown_labels = Vec::new();
for (language, expected) in [("en", "Levels"), ("de", "Stufen"), ("ja", "レベル数")] {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.session.prefs.interface_language = language.to_owned();
let lang = app.ui_language();
let ctx = app.ui_ctx.clone().unwrap();
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp, events: Vec<Event>| {
ctx.enable_accesskit();
time += 0.1;
crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(viewport), ..Default::default() })
};
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let square = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap();
frame(&mut app, vec![]);
assert_eq!(ctx.content_rect(), viewport);
app.run("ui.effectGalleryDialog", json!({})).unwrap();
frame(&mut app, vec![]);
let nodes = frame(&mut app, vec![]).platform_output.accesskit_update.unwrap().nodes;
let filter = crate::i18n::effect_name(lang, "artistic.cutout").unwrap();
let bounds = nodes.iter().filter(|(_, node)| node.label() == Some(filter.as_str())).find_map(|(_, node)| node.bounds()).unwrap();
let at = pos2((bounds.x0 + bounds.x1) as f32 * 0.5, (bounds.y0 + bounds.y1) as f32 * 0.5);
assert!(viewport.contains(at), "{language}: Cutout is reachable");
frame(&mut app, vec![Event::PointerMoved(at)]);
for pressed in [true, false] {
frame(&mut app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
frame(&mut app, vec![]);
let output = frame(&mut app, vec![]);
let state = app.session.active().unwrap();
let affected = &state.doc.node(NodeId(square)).unwrap().appearance.effects;
assert_eq!(affected.first().map(|effect| effect.id.as_str()), Some("artistic.cutout"), "{language}: Cutout is previewed");
let nodes = output.platform_output.accesskit_update.unwrap().nodes;
let found = [expected, "Levels"].into_iter().find(|label| {
nodes
.iter()
.any(|(_, node)| node.label() == Some(*label) && node.bounds().is_some_and(|b| viewport.contains(pos2(b.x0 as f32, b.y0 as f32))))
});
eprintln!("{language}: expected {expected:?}, found {found:?}");
shown_labels.push(found);
}
assert_eq!(shown_labels, [Some("Levels"), Some("Stufen"), Some("レベル数")]);
}
}
+228 -11
View File
@@ -61,6 +61,8 @@ pub(crate) struct Open {
pub id: DialogId,
/// Which of the three dialogs it is.
pub kind: &'static str,
/// The drawing and loaded contents that supplied the selection and defaults at opening.
document: Option<(u64, u64)>,
/// The envelope the dialog previews.
pub preview: LivePreview,
// PLAN: ef.C11's `Open` has no `generation`; the same kind reopened has the same id, so the id cannot tell the held Cancel of the replaced dialog from the new one's.
@@ -68,6 +70,18 @@ pub(crate) struct Open {
pub generation: u64,
}
impl Open {
fn on_original_drawing(&self, app: &VectorcraftApp) -> bool {
app.session.active().map(|st| (st.uid, st.reverts)) == self.document
}
fn cancel_preview(self, app: &mut VectorcraftApp) {
if self.on_original_drawing(app) {
self.preview.cancel(app);
}
}
}
/// The dialog's title.
fn heading(kind: &str, reset: bool) -> Label {
Label::from(
@@ -172,44 +186,53 @@ pub fn open(app: &mut VectorcraftApp, id: &str) -> Result<Value, String> {
/// Options dialog sets the defaults for new envelopes and has nothing to preview.
fn open_dialog(app: &mut VectorcraftApp, kind: &'static str, values: Map<String, Value>, envelope: bool) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let document = app.session.active().map(|st| (st.uid, st.reverts));
if let Some(previous) = app.effect_dialogs.envelope.take() {
previous.preview.cancel(app);
let id = previous.id;
previous.cancel_preview(app);
if let Some(dialogs) = app.dialogs() {
dialogs.with(|host| host.cancel_by_id(&ctx, previous.id));
dialogs.with(|host| host.cancel_by_id(&ctx, id));
}
}
let fields = fields_of(&params(kind, &DialogFields::new()), &values);
let dialog = HostedParamDialog::command(&ctx, kind, fields, move |fields| {
let reset = fields.bool("reset").unwrap_or(false);
ParamDialog::command(kind, heading(kind, reset), params(kind, fields)).previews(kind != OPTIONS || envelope)
ParamDialog::command(kind, heading(kind, reset), params(kind, fields)).previews(kind != OPTIONS || envelope).values(Bind::bound(fields))
});
let generation = OPENED.fetch_add(1, Ordering::Relaxed);
let cancel = Box::new(move |app: &mut VectorcraftApp| {
if app.effect_dialogs.envelope.as_ref().is_some_and(|open| open.generation == generation)
&& let Some(open) = app.effect_dialogs.envelope.take()
{
open.preview.cancel(app);
open.cancel_preview(app);
}
});
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| accept(app, kind, result);
let id = open_held_with(app, dialog, ok, HeldOptions { cancel: Some(cancel), ..Default::default() }).ok_or("no window")?;
app.effect_dialogs.envelope = Some(Open { id, kind, preview: LivePreview::default(), generation });
let id = open_held_with(app, dialog, accept, HeldOptions { cancel: Some(cancel), ..Default::default() }).ok_or("no window")?;
app.effect_dialogs.envelope = Some(Open { id, kind, document, preview: LivePreview::default(), generation });
Ok(Value::Null)
}
/// OK: keeps the preview as one undo step. A refused command keeps the dialog open.
fn accept(app: &mut VectorcraftApp, kind: &'static str, result: &ParamResult) -> Result<(), String> {
let (cmd, p, _) = command(kind, &json_of(&params(kind, &result.fields), &result.fields));
let Some(Open { id, generation, preview, .. }) = app.effect_dialogs.envelope.take() else {
fn accept(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> {
let Some(open) = app.effect_dialogs.envelope.as_ref().filter(|open| open.id == result.id) else {
return Err("the envelope dialog is gone".into());
};
if !open.on_original_drawing(app) {
if app.session.active().map(|st| st.uid) == open.document.map(|(uid, _)| uid) {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
return Err(tl!("Return to the original drawing to apply the envelope").into());
}
let kind = open.kind;
let (cmd, p, _) = command(kind, &json_of(&params(kind, &result.fields), &result.fields));
let Open { id, document, preview, generation, .. } = app.effect_dialogs.envelope.take().ok_or("the envelope dialog is gone")?;
match preview.commit(app, cmd, p) {
Ok(_) => Ok(()),
Err(e) => {
// The attempt ended the preview; the next pass starts a new one over the same values. Nothing to undo
// when no interaction was open, so the answer is not needed.
let _ = app.session.cancel_interaction();
app.effect_dialogs.envelope = Some(Open { id, kind, preview: LivePreview::default(), generation });
app.effect_dialogs.envelope = Some(Open { id, kind, document, preview: LivePreview::default(), generation });
Err(e)
}
}
@@ -252,6 +275,10 @@ fn command(kind: &str, f: &Map<String, Value>) -> (&'static str, Value, &'static
/// canvas shows them. The dialog's Cancel rolls the preview back through the held record's cancel.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(mut open) = app.effect_dialogs.envelope.take() else { return };
if !open.on_original_drawing(app) {
app.effect_dialogs.envelope = Some(open);
return;
}
let shown = app
.dialogs()
.and_then(|dialogs| dialogs.with(|host| host.get_mut_by_id::<HostedParamDialog>(open.id).map(|d| (d.is_previewing(), d.fields().clone()))));
@@ -426,6 +453,114 @@ mod tests {
app.effect_dialogs.envelope.as_ref().map(|open| open.id).expect("an open envelope dialog")
}
fn type_count(panel: &mut crate::tests::panel_harness::Panel, name: &str, text: &str) {
panel.click(name);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text(text);
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
panel.frame();
}
#[test]
fn real_warp_choice_radio_and_slider_edits_reach_the_preview_and_ok() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
let (app, _) = app_with_rect();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
let before = panel.app().session.doc().unwrap().history.undo.len();
crate::menus::invoke(&mut panel.app(), MAKE_WARP, json!({}));
panel.frame();
let opening_bounds = envelope(&panel.app()).1.geometric_bounds();
panel.click_role("Style", Role::COMBO_BOX);
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
panel.click("Vertical");
panel.click_role("Bend", Role::SLIDER);
panel.key(egui::Key::ArrowLeft, egui::Modifiers::NONE);
panel.frame();
let id = dialog(&panel.app());
let fields = json_fields(&panel.app(), id);
assert_ne!(fields["style"], "arc");
assert_ne!(fields["bend"], 50.0);
let preview = envelope(&panel.app()).1;
let NodeKind::Envelope { ref kind, .. } = preview.kind else { panic!("an envelope preview") };
let EnvelopeKind::Warp { style, bend, horizontal, .. } = &**kind else { panic!("a warp") };
assert_eq!(style.as_str(), fields["style"].as_str().unwrap());
assert_eq!(*bend, fields["bend"].as_f64().unwrap());
assert!(!*horizontal);
let bounds = preview.geometric_bounds();
assert_ne!(bounds, opening_bounds, "the nondefault warp changes the preview geometry");
panel.click("OK");
panel.frame();
panel.frame();
assert!(open_ids(&panel.app()).is_empty());
assert_eq!(envelope(&panel.app()).1.geometric_bounds(), bounds);
assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), before + 1);
}
#[test]
fn real_mesh_counts_and_reset_maintain_shape_edits_reach_the_model() {
use crate::tests::panel_harness::Panel;
let (app, _) = app_with_rect();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
crate::menus::invoke(&mut panel.app(), MAKE_MESH, json!({}));
type_count(&mut panel, "Rows", "2");
type_count(&mut panel, "Columns", "3");
assert!(
matches!(envelope(&panel.app()).1.kind, NodeKind::Envelope { ref kind, .. } if matches!(**kind, EnvelopeKind::Mesh { rows: 2, cols: 3, .. }))
);
panel.click("OK");
panel.frame();
panel.frame();
let confirmed = envelope(&panel.app()).1;
crate::menus::invoke(&mut panel.app(), MAKE_MESH, json!({}));
panel.frame();
assert!(panel.shows("Maintain Envelope Shape"));
panel.click("Maintain Envelope Shape");
type_count(&mut panel, "Rows", "1");
let id = dialog(&panel.app());
assert_eq!(json_fields(&panel.app(), id)["maintainShape"], false);
assert!(
matches!(envelope(&panel.app()).1.kind, NodeKind::Envelope { ref kind, .. } if matches!(**kind, EnvelopeKind::Mesh { rows: 1, cols: 3, .. }))
);
panel.click("Cancel");
panel.frame();
assert_eq!(envelope(&panel.app()).1, confirmed);
}
#[test]
fn real_options_controls_enable_dependents_and_confirm_defaults_without_preview() {
use crate::tests::panel_harness::Panel;
let (mut app, _) = app_with_rect();
app.run(OPTIONS_CMD, json!({"distortAppearance": false, "distortLinearGradients": false})).unwrap();
let initial = app.session.execute("object.envelope.info", &json!({})).unwrap();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
crate::menus::invoke(&mut panel.app(), OPTIONS_CMD, json!({}));
panel.frame();
assert!(!panel.enabled("Distort Linear Gradients"));
panel.click("Distort Appearance");
assert!(panel.enabled("Distort Linear Gradients"));
panel.click("Distort Linear Gradients");
panel.click("Anti-Alias");
assert!(!panel.app().session.in_interaction(), "defaults have no artwork preview");
panel.click("OK");
panel.frame();
panel.frame();
let info = panel.app().session.execute("object.envelope.info", &json!({})).unwrap();
assert_eq!(info["distortAppearance"], true);
assert_eq!(info["distortLinearGradients"], true);
assert_eq!(info["antiAlias"].as_bool(), initial["antiAlias"].as_bool().map(|on| !on));
crate::menus::invoke(&mut panel.app(), OPTIONS_CMD, json!({}));
panel.frame();
panel.click("Anti-Alias");
panel.click("Cancel");
panel.frame();
assert_eq!(panel.app().session.execute("object.envelope.info", &json!({})).unwrap(), info);
}
#[test]
fn warp_dialog_previews_and_ok_keeps_one_step() {
let (mut app, rect) = app_with_rect();
@@ -465,6 +600,88 @@ mod tests {
);
}
#[test]
fn envelope_warp_refuses_preview_and_ok_in_the_other_drawing() {
let (mut app, _) = app_with_rect();
open(&mut app, MAKE_WARP).unwrap();
let id = dialog(&app);
set(&app, id, "bend", json!(23));
pump(&mut app);
app.run("file.new", json!({"width": 300, "height": 150})).unwrap();
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 50})).unwrap();
app.run("select.all", json!({})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
set(&app, id, "bend", json!(31));
pump(&mut app);
assert!(matches!(envelope(&app).1.kind, NodeKind::Path { .. }), "the other drawing keeps the rectangle");
let ctx = app.ui_ctx.clone().unwrap();
host(&app, |h| h.confirm_by_id(&ctx, id));
pump(&mut app);
assert!(
matches!(host(&app, |h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(reason)) if reason.as_str().contains("original drawing"))
);
assert_eq!(json_fields(&app, id)["bend"], 31.0);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
app.run("document.activate", json!({"index": 0})).unwrap();
accept(&mut app, id);
let (_, node) = envelope(&app);
assert!(matches!(node.kind, NodeKind::Envelope { ref kind, .. } if matches!(**kind, EnvelopeKind::Warp { bend: 31.0, .. })));
}
#[test]
fn envelope_warp_and_mesh_do_not_preview_or_apply_to_restored_art() {
for command in [MAKE_WARP, MAKE_MESH] {
let (mut app, rect) = app_with_rect();
let dir = vectorcraft_testkit::TempDir::new("envelope-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
app.run("shape.ellipse", json!({"x": 5, "y": 5, "width": 20, "height": 20})).unwrap();
app.run("select.set", json!({"ids": [rect.0]})).unwrap();
open(&mut app, command).unwrap();
let id = dialog(&app);
pump(&mut app);
assert!(matches!(envelope(&app).1.kind, NodeKind::Envelope { .. }));
let source = app.session.active().unwrap();
let (uid, reverts) = (source.uid, source.reverts);
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [rect.0]})).unwrap();
let loaded = app.session.active().unwrap();
assert_eq!((loaded.uid, loaded.reverts), (uid, reverts + 1));
let undo = loaded.history.undo.len();
pump(&mut app);
assert!(matches!(envelope(&app).1.kind, NodeKind::Path { .. }), "{command} preview");
let ctx = app.ui_ctx.clone().unwrap();
host(&app, |h| h.confirm_by_id(&ctx, id));
pump(&mut app);
assert!(matches!(host(&app, |h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_))));
assert!(matches!(envelope(&app).1.kind, NodeKind::Path { .. }), "{command} approval");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
dismiss(&mut app, id);
open(&mut app, command).unwrap();
let fresh = dialog(&app);
accept(&mut app, fresh);
assert!(matches!(envelope(&app).1.kind, NodeKind::Envelope { .. }));
}
}
#[test]
fn cancelling_an_envelope_dialog_keeps_the_other_drawings_active_edit() {
let (mut app, _) = app_with_rect();
open(&mut app, MAKE_WARP).unwrap();
let id = dialog(&app);
pump(&mut app);
app.run("file.new", json!({"width": 300, "height": 150})).unwrap();
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 60, "height": 50})).unwrap();
app.run("select.all", json!({})).unwrap();
app.session.begin_interaction("Other drawing's edit").unwrap();
app.session.preview("paint.setFill", &json!({"color": "#00aa00"})).unwrap();
dismiss(&mut app, id);
assert!(app.session.in_interaction(), "the other drawing's edit stays active");
}
#[test]
fn reset_items_take_the_make_items_place_while_an_envelope_is_selected() {
let labels = |app: &VectorcraftApp| -> Vec<String> {
+141 -5
View File
@@ -10,8 +10,8 @@
//! `object.expand.info`), `__canGradient` (Expand Gradient To applies) and `__canSteps` (it
//! applies and makes objects). What only the art of symbol instances holds needs Object on.
use craft::ui::contract::SaveKey;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::contract::{Bind, SaveKey};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::runtime::memory::Lifetime;
use serde_json::{Value, json};
use vectorcraft_engine::cmd::expand::{DEFAULT_STEPS, MAX_STEPS};
@@ -22,6 +22,7 @@ use crate::VectorcraftApp;
pub const KIND: &str = "expand";
const CMD: &str = "object.expand";
const OPENING_DRAWING: &str = "__openingDrawing";
/// Where the choices OK expanded with are kept for the rest of the app's run.
const REMEMBER: SaveKey = SaveKey::new("vectorcraft.dialog.expand");
@@ -145,16 +146,33 @@ fn rows() -> Vec<Param> {
/// every option on before that.
fn dialog(app: &VectorcraftApp, info: ExpandInfo) -> Result<HostedParamDialog, String> {
let ctx = app.ui_ctx.as_ref().ok_or("no window")?;
let active = app.session.active().ok_or("no document open")?;
let mut fields = DialogFields::new();
fields.set(OPENING_DRAWING, FieldValue::Json(json!({"uid": active.uid, "reverts": active.reverts})));
let rows = rows();
Ok(HostedParamDialog::new(ctx, KIND, DialogFields::new(), move |fields| {
Ok(HostedParamDialog::new(ctx, KIND, fields, move |fields| {
refresh(info, fields);
ParamDialog::new(KIND, tl!("Expand"), rows.clone()).remember(REMEMBER).remember_for(Lifetime::Run)
ParamDialog::new(KIND, tl!("Expand"), rows.clone()).remember(REMEMBER).remember_for(Lifetime::Run).values(Bind::bound(fields))
}))
}
/// Shows `dialog`; its OK expands.
fn show(app: &mut VectorcraftApp, dialog: HostedParamDialog) -> Result<Value, String> {
crate::dialogs::host::open_held(app, dialog, ok).ok_or("no window")?;
crate::dialogs::host::open_held(app, dialog, |app, result: &ParamResult| {
let Some(FieldValue::Json(opening)) = result.fields.get(OPENING_DRAWING) else {
return Err(tl!("Return to the original drawing to expand the artwork").into());
};
let active = app
.session
.active()
.filter(|st| Some(st.uid) == opening["uid"].as_u64())
.ok_or_else(|| tl!("Return to the original drawing to expand the artwork").to_owned())?;
if Some(active.reverts) != opening["reverts"].as_u64() {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
ok(app, result)
})
.ok_or("no window")?;
Ok(Value::Null)
}
@@ -215,6 +233,77 @@ mod tests {
crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()))
}
#[test]
fn actual_fill_and_stroke_choices_leave_those_paints_unexpanded() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
let mut app = app();
gradient_rectangle(&mut app);
app.run("paint.setStroke", json!({"color": "#000000"})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 600.0));
panel.app().run("ui.expandDialog", json!({})).unwrap();
panel.click_role("Fill", Role::CHECK_BOX);
panel.click_role("Stroke", Role::CHECK_BOX);
let edited = fields(&panel.app());
assert_eq!((edited.bool("fill"), edited.bool("stroke")), (Some(false), Some(false)));
assert_eq!(edited.bool("__canGradient"), Some(false));
assert!(!panel.enabled("Gradient Mesh"));
assert!(!panel.enabled("Objects"));
panel.click("OK");
assert!(!is_open(&panel.app()));
let app = panel.app();
let state = app.session.active().unwrap();
let node = state.doc.node(state.selection.objects[0]).unwrap();
assert!(matches!(node.kind, NodeKind::Path { .. }), "the object remains one path");
assert!(matches!(node.appearance.fill_paint(), vectorcraft_color::Paint::Gradient(_)), "unticked Fill keeps its gradient");
assert!(!node.appearance.stroke_paint().is_none(), "unticked Stroke keeps its stroke");
assert_eq!(state.history.undo.len(), undo + 1);
}
#[test]
fn actual_gradient_controls_apply_and_remember_the_typed_object_count() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
let mut app = app();
gradient_rectangle(&mut app);
let original = app.session.active().unwrap().doc.clone();
let undo = app.session.active().unwrap().history.undo.len();
let mut panel = Panel::new(app, crate::tests::picks::dialogs);
panel.room(egui::vec2(800.0, 600.0));
panel.app().run("ui.expandDialog", json!({})).unwrap();
panel.click_role("Gradient Mesh", Role::RADIO_BUTTON);
assert_eq!(fields(&panel.app()).text("gradient"), Some("mesh"));
assert!(!panel.enabled("Objects"));
let specify = if panel.shows("Specify") { "Specify" } else { "Specify:" };
panel.click_role(specify, Role::RADIO_BUTTON);
assert!(panel.enabled("Objects"));
panel.click_role("Objects", Role::SPIN_BUTTON);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text("4");
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
assert_eq!(fields(&panel.app()).number("steps"), Some(4.0));
panel.click("OK");
assert!(!is_open(&panel.app()));
{
let app = panel.app();
let state = app.session.active().unwrap();
let node = state.doc.node(state.selection.objects[0]).unwrap();
let NodeKind::Group { children, clip: true } = &node.kind else { panic!("a gradient clip group") };
assert_eq!(children.iter().filter(|child| matches!(child.kind, NodeKind::Path { clipping: false, .. })).count(), 4);
assert_eq!(state.history.undo.len(), undo + 1);
}
panel.app().run("edit.undo", json!({})).unwrap();
panel.app().run("ui.expandDialog", json!({})).unwrap();
panel.frame();
assert_eq!(fields(&panel.app()).number("steps"), Some(4.0), "a successful real edit is remembered");
panel.click("Cancel");
assert_eq!(panel.app().session.active().unwrap().doc, original);
}
fn ctx(app: &VectorcraftApp) -> egui::Context {
app.ui_ctx.clone().expect("the test context")
}
@@ -285,6 +374,24 @@ mod tests {
assert!(matches!(children[1].kind, NodeKind::Mesh(_)));
}
#[test]
fn expand_keeps_its_draft_when_another_drawing_is_active() {
let mut app = app();
gradient_rectangle(&mut app);
open(&mut app).unwrap();
set(&app, "gradient", json!("mesh")).unwrap();
gradient_rectangle(&mut app);
let undo = app.session.active().unwrap().history.undo.len();
let before = app.session.active().unwrap().doc.clone();
assert!(matches!(press_ok(&mut app), Some(HeldOk::Refused(reason)) if reason.as_str().contains("original drawing")));
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(std::sync::Arc::ptr_eq(&app.session.active().unwrap().doc, &before));
assert_eq!(fields(&app).text("gradient"), Some("mesh"));
app.run("document.activate", json!({"index": 0})).unwrap();
ok_and_close(&mut app);
assert!(expanded_to_a_mesh(&app));
}
#[test]
fn expand_gradient_to_is_disabled_for_a_pattern_fill_alone() {
let mut app = app();
@@ -508,4 +615,33 @@ mod tests {
app.run("ui.expandDialog", json!({"immediate": false})).unwrap();
assert!(is_open(&app));
}
#[test]
fn expand_approval_does_not_expand_artwork_restored_by_revert() {
let mut app = app();
gradient_rectangle(&mut app);
let rectangle = app.session.active().unwrap().selection.objects[0];
let dir = vectorcraft_testkit::TempDir::new("expand-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
app.run("object.move", json!({"dx": 10, "dy": 0})).unwrap();
open(&mut app).unwrap();
set(&app, "gradient", json!("mesh")).unwrap();
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [rectangle.0]})).unwrap();
let restored = app.session.active().unwrap().doc.clone();
assert!(matches!(press_ok(&mut app), Some(HeldOk::Refused(_))));
assert_eq!(app.session.active().unwrap().doc, restored);
close(&app);
open(&mut app).unwrap();
set(&app, "gradient", json!("mesh")).unwrap();
ok_and_close(&mut app);
let st = app.session.active().unwrap();
let art = st.doc.node(st.selection.objects[0]).unwrap();
let NodeKind::Group { children, clip: true } = &art.kind else { panic!("expected a clip group") };
assert!(matches!(children[1].kind, NodeKind::Mesh(_)));
}
}
+24 -5
View File
@@ -19,7 +19,7 @@ use craft::ui::style::TypeRole;
use serde_json::{Value, json};
use vectorcraft_engine::cmd::fileio::{self, ArtboardPick, Format};
use super::export_host::{self, After, Export, Open};
use super::export_host::{self, After, Export};
use super::{dxf_options, eps_options, form, hpgl_options, plugin, png_options, save_pdf, svg_options, text_export};
use crate::{VectorcraftApp, io};
@@ -111,7 +111,9 @@ pub fn open(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) {
fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Result<(), String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let n = app.session.active().map_or(0, |s| s.doc.artboards.len());
let source = app.session.active();
let document = source.map(|source| (source.uid, source.reverts));
let n = source.map_or(0, |source| source.doc.artboards.len());
let missing = format.and_then(|f| UNAVAILABLE.iter().find(|u| u.0.eq_ignore_ascii_case(f.trim_start_matches('.'))));
let format = match missing {
Some((id, _)) => id,
@@ -133,12 +135,23 @@ fn open_dialog(app: &mut VectorcraftApp, format: Option<&str>, p: &Value) -> Res
})
.ok_label(Label::from("Export…"))
});
export_host::open(app, Export::As, false, dialog).map(|_| ()).ok_or_else(|| "no window".into())
export_host::open(app, Export::As { document }, false, dialog).map(|_| ()).ok_or_else(|| "no window".into())
}
fn require_source(app: &VectorcraftApp, document: Option<(u64, u64)>) -> Result<(), String> {
let (uid, reverts) = document.ok_or_else(|| tl!("Open Export As from the drawing you want to export").to_owned())?;
let source =
app.session.active().filter(|source| source.uid == uid).ok_or_else(|| tl!("Return to the original drawing to export it").to_owned())?;
if source.reverts != reverts {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
Ok(())
}
/// Check the artboard range and that there is something to export; the save panel and the format's options or
/// the file follow once the dialog has closed.
pub(super) fn confirm(app: &mut VectorcraftApp, _open: &Open, fields: &DialogFields) -> Result<After, String> {
pub(super) fn confirm(app: &mut VectorcraftApp, document: Option<(u64, u64)>, fields: &DialogFields) -> Result<After, String> {
require_source(app, document)?;
if let Some((_, hint)) = unavailable(fields) {
return Err(hint.into());
}
@@ -162,7 +175,13 @@ pub(super) fn confirm(app: &mut VectorcraftApp, _open: &Open, fields: &DialogFie
}
let range = if all { "all".to_string() } else { range };
let pages = Pages { use_artboards, all, range, selection: false };
Ok(Some(Box::new(move |app| io::export_path(app, None, f, move |app, path| options_or_write(app, f, plugin, path, pages)))))
Ok(Some(Box::new(move |app| {
require_source(app, document)?;
io::export_path(app, None, f, move |app, path| {
require_source(app, document)?;
options_or_write(app, f, plugin, path, pages)
})
})))
}
/// `params` of an options dialog for [`io::export`]: with [`io::EXPORT_SELECTION`] when
@@ -45,6 +45,7 @@ use craft::ui::list::{List, ListRow, ThumbAspect, ThumbSize, ToggleCell, ToggleS
use craft::ui::patterns::form_dialogs::{FormDialog, PathRow};
use craft::ui::primitives::{ContentPainterCx, fit_rect};
use craft::ui::runtime::env::Label;
use craft::ui::runtime::focus::Initial;
use craft::ui::tabs::{Tab, TabKind, TabStrip};
use craft::ui::text::TextField;
use craft::ui::tile_grid::{Tile, TileGrid, TilePartEvent};
@@ -506,7 +507,7 @@ pub(super) fn artboard_thumb(app: &mut VectorcraftApp, ctx: &Context, i: usize)
/// thumbnails.
fn document_view(app: &mut VectorcraftApp, ctx: &Context) -> (Option<Shown>, Vec<Option<TextureHandle>>) {
let Some(st) = app.session.active() else { return (None, Vec::new()) };
let shown = Shown { key: (st.uid, st.revision), doc: Arc::clone(&st.doc) };
let shown = Shown { key: (st.uid, st.revision), reverts: st.reverts, doc: Arc::clone(&st.doc) };
let thumbs = (0..shown.doc.artboards.len()).map(|i| artboard_thumb(app, ctx, i)).collect();
(Some(shown), thumbs)
}
@@ -515,6 +516,8 @@ fn document_view(app: &mut VectorcraftApp, ctx: &Context) -> (Option<Shown>, Vec
struct Shown {
/// The document's uid and revision.
key: (u64, u64),
/// Which contents of this tab were shown; File Revert preserves its uid.
reverts: u64,
doc: Arc<Document>,
}
@@ -535,9 +538,9 @@ pub(crate) struct ExportForScreensDialog {
/// What the format presets menu asked for, for the pump to run.
pending: Option<PresetPick>,
/// The document an artboard rename began in, while it runs.
renaming_in: Option<u64>,
/// A committed artboard name: (document uid, artboard id, name), for the pump to run.
rename: Option<(u64, u32, String)>,
renaming_in: Option<(u64, u64)>,
/// A committed artboard name: ((document uid, reverts), artboard id, name), for the pump to run.
rename: Option<((u64, u64), u32, String)>,
held: HeldAnswer<Map<String, Value>>,
}
@@ -620,13 +623,13 @@ impl ExportForScreensDialog {
}
}
if picks.rename_began {
self.renaming_in = Some(shown.key.0);
self.renaming_in = Some((shown.key.0, shown.reverts));
}
// The name goes to the document the rename began in.
if let Some((key, name)) = picks.renamed
&& let Ok(board) = u32::try_from(key)
{
self.rename = Some((self.renaming_in.take().unwrap_or(shown.key.0), board, name));
self.rename = Some((self.renaming_in.take().unwrap_or((shown.key.0, shown.reverts)), board, name));
}
if on != boards(doc.artboards.len(), fields) {
set_select(fields, if on.iter().all(|b| *b) { "all" } else { "range" });
@@ -958,6 +961,10 @@ impl StackDialog for ExportForScreensDialog {
let mut held = std::mem::take(&mut self.held);
let mut dialog =
FormDialog::new(tl!("Export for Screens"), Bind::bound(&mut fields)).ok_label(ok).ok_enabled(chosen.is_none()).held(&mut held);
if self.web {
// Keep the first artboard visible when the web dialog opens in a short viewport.
dialog = dialog.shaped(|surface| surface.initial_focus(Initial::First));
}
if let Some(reason) = chosen {
dialog = dialog.ok_reason(reason);
}
@@ -994,15 +1001,16 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) {
// The export ran when OK was filed: the closed dialog's answer is not read.
let _ = dialogs.with(|host| host.take_by_id::<ExportForScreensDialog>(id));
let key = app.session.active().map(|st| (st.uid, st.revision));
let contents = app.session.active().map(|st| (st.uid, st.reverts));
let pdf_presets = pdf::presets(&app.session);
let saved = &app.session.prefs.screen_export_presets;
let Some((shown, pending, rename, filed)) = dialogs.with(|host| {
let Some((shown, shown_contents, pending, rename, filed)) = dialogs.with(|host| {
let d = host.get_mut_by_id::<ExportForScreensDialog>(id)?;
screen_formats::preset_list(&mut d.presets, saved);
if d.pdf_presets != pdf_presets {
d.pdf_presets = pdf_presets;
}
Some((d.doc.as_ref().map(|s| s.key), d.pending.take(), d.rename.take(), d.held.take()))
Some((d.doc.as_ref().map(|s| s.key), d.doc.as_ref().map(|s| (s.key.0, s.reverts)), d.pending.take(), d.rename.take(), d.held.take()))
}) else {
return;
};
@@ -1024,15 +1032,15 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) {
}
});
}
// A name typed in another document than the active one is dropped.
if let Some((uid, board, name)) = rename
&& key.is_some_and(|(active, _)| active == uid)
// A name typed in another drawing or in content discarded by File Revert is dropped.
if let Some((origin, board, name)) = rename
&& contents == Some(origin)
{
rename_artboard(app, board, &name);
}
if let Some(fields) = filed {
// OK validated its selection against the document the dialog showed before refreshing.
let answer = if shown.map(|(uid, _)| uid) == app.session.active().map(|st| st.uid) {
// OK validated its selection against the loaded contents shown before refreshing.
let answer = if shown_contents == contents {
params(app, &fields).and_then(|p| io::export_for_screens(app, p)).map(drop).map_err(Label::from)
} else {
Err(Label::from(tl!("The active document changed. Review the export selection and try again.")))
+44 -11
View File
@@ -21,7 +21,10 @@ pub(crate) type After = Option<Box<dyn FnOnce(&mut VectorcraftApp) -> Result<Val
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Export {
/// Export As.
As,
As {
/// The drawing and content generation whose export the dialog configures, when one was open.
document: Option<(u64, u64)>,
},
/// The options of the raster format `format`.
Raster {
/// The format's id.
@@ -49,7 +52,7 @@ pub(crate) enum Export {
/// Save for Office Documents.
Office,
/// Text Export Options.
Text,
Text { source: Option<text_export::SelectionSource> },
/// The options a save or open asks for before it goes on, for `action`.
Save {
/// The action the options belong to.
@@ -61,6 +64,8 @@ pub(crate) enum Export {
pub(crate) struct Open {
/// The hosted dialog's id.
pub id: DialogId,
/// The drawing and loaded contents whose options and output this dialog controls.
document: Option<(u64, u64)>,
/// Which dialog it is.
pub kind: Export,
/// Whether Export Selection opened it: OK then writes the selection alone.
@@ -85,6 +90,22 @@ impl ExportDialogs {
}
}
impl Open {
fn check_source(&self, app: &VectorcraftApp) -> Result<(), String> {
if matches!(self.kind, Export::As { .. } | Export::Hpgl { .. }) {
return Ok(());
}
let active = app.session.active().map(|doc| (doc.uid, doc.reverts));
if active == self.document {
return Ok(());
}
if active.zip(self.document).is_some_and(|((uid, _), (source, _))| uid == source) {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
Err(tl!("Return to the original drawing to continue").into())
}
}
/// `ids` paired with `labels` as the options of a choice row.
pub(super) fn options<L: From<&'static str>>(ids: &[&'static str], labels: &[&'static str]) -> Vec<(String, L)> {
ids.iter().zip(labels).map(|(id, label)| (id.to_string(), L::from(label))).collect()
@@ -93,13 +114,18 @@ pub(super) fn options<L: From<&'static str>>(ids: &[&'static str], labels: &[&'s
/// Opens `dialog` as the export dialog `kind` and records it; `None` without a window. A dialog of the same key
/// replaces the one open, and its record.
pub(crate) fn open(app: &mut VectorcraftApp, kind: Export, selection: bool, dialog: HostedParamDialog) -> Option<DialogId> {
let document = match &kind {
Export::As { .. } | Export::Hpgl { .. } => None,
Export::EpsCustom { parent } => app.export_dialogs.find(*parent)?.document,
_ => app.session.active().map(|doc| (doc.uid, doc.reverts)),
};
let options = match &kind {
Export::EpsCustom { parent } => HeldOptions { parent: Some(*parent), cancel: None },
_ => HeldOptions::default(),
};
let id = host::open_held_with(app, dialog, answer, options)?;
app.export_dialogs.0.retain(|o| o.id != id);
app.export_dialogs.0.push(Open { id, kind, selection, after: None });
app.export_dialogs.0.push(Open { id, document, kind, selection, after: None });
Some(id)
}
@@ -114,9 +140,10 @@ pub(super) fn set_fields(app: &VectorcraftApp, id: DialogId, fields: &[(&str, Va
/// OK of the dialog `result` is from: its kind's `confirm`, and the step that follows kept for [`pump`].
fn answer(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> {
let (id, kind, selection) =
app.export_dialogs.find(result.id).map(|o| (o.id, o.kind.clone(), o.selection)).ok_or("this export dialog is no longer open")?;
let open = Open { id, kind, selection, after: None };
let open = app.export_dialogs.find(result.id).ok_or("this export dialog is no longer open")?;
open.check_source(app)?;
let id = open.id;
let open = Open { id, document: open.document, kind: open.kind.clone(), selection: open.selection, after: None };
let after = confirm(app, &open, &result.fields)?;
if let Some(record) = app.export_dialogs.0.iter_mut().find(|o| o.id == id) {
record.after = after;
@@ -126,7 +153,7 @@ fn answer(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String>
fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Result<After, String> {
match &open.kind {
Export::As => export_as::confirm(app, open, fields),
Export::As { document } => export_as::confirm(app, *document, fields),
Export::Raster { .. } => png_options::confirm(app, open, fields),
Export::Svg { .. } => svg_options::confirm(app, open, fields),
Export::Eps => eps_options::confirm(app, open, fields),
@@ -134,7 +161,7 @@ fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Resu
Export::Dxf => dxf_options::confirm(app, open, fields),
Export::Hpgl { .. } => hpgl_options::confirm(app, open, fields),
Export::Office => office_export::confirm(app, open, fields),
Export::Text => text_export::confirm(app, open, fields),
Export::Text { source } => text_export::confirm(app, open, source.as_ref(), fields),
Export::Save { .. } => save_options::confirm(app, open, fields),
}
}
@@ -194,14 +221,20 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some((footer, actions)) = taken else {
// The dialog closed: the step after an OK runs, a cancelled one has none.
if let Some(i) = app.export_dialogs.0.iter().position(|o| o.id == id) {
let record = app.export_dialogs.0.remove(i);
if let Some(after) = record.after {
let result = after(app);
let mut record = app.export_dialogs.0.remove(i);
if let Some(after) = record.after.take() {
let result = record.check_source(app).and_then(|()| after(app));
report(app, result);
}
}
continue;
};
if let Err(error) = open.check_source(app) {
if footer.is_some() || !actions.is_empty() {
app.status(error);
}
continue;
}
if let Export::Svg { mode } = kind {
if footer.as_deref() == Some(svg_options::BROWSER_ACTION)
&& let Some(fields) = fields_of(app, id)
+207 -9
View File
@@ -13,7 +13,7 @@
use std::path::PathBuf;
use craft::behavior::IconId;
use craft::host::{Host, PickId, PickKind, PickRequest};
use craft::host::{Host, PickId, PickKind, PickRequest, Picked};
use craft::theme::variant::Tone;
use craft::ui::buttons::{Button, IconButton};
use craft::ui::choice::{Radio, RadioGroup, Rating};
@@ -55,10 +55,12 @@ type Info = Map<String, Value>;
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let fields = app.session.execute("file.info", &json!({})).map_err(|e| e.to_string())?;
let fields = fields.as_object().cloned().ok_or("file.info gave no fields")?;
let document = app.session.active().ok_or("no document")?.uid;
let ok = |app: &mut VectorcraftApp, (document, fields): &(u64, Info)| {
if !app.session.active().is_some_and(|active| active.uid == *document) {
return Err(tl!("File Info can only change the document it was opened for.").to_owned());
let source = app.session.active().ok_or("no document")?;
let document = (source.uid, source.reverts);
let ok = |app: &mut VectorcraftApp, ((uid, generation), fields): &((u64, u64), Info)| {
let source = app.session.active().filter(|st| st.uid == *uid).ok_or(tl!("File Info can only change the document it was opened for."))?;
if source.reverts != *generation {
return Err(tl!("Reopen File Info after reverting the drawing").into());
}
app.run("file.info", Value::Object(fields.clone())).map(|_| ())
};
@@ -111,6 +113,10 @@ enum Request {
Folder,
/// Save the fields as a template at the path the save pick answered.
SaveTo(PathBuf),
/// A browser picker returned a template larger than the import limit.
TemplateTooLarge,
/// Download the current draft as a template, without requiring a filesystem path.
Download,
/// Merge the template `source` into the fields as `mode` says.
Import { source: Info, mode: &'static str },
}
@@ -134,6 +140,7 @@ enum Chosen {
#[derive(Default)]
struct Templates {
can_save: bool,
web_save: bool,
can_open: bool,
has_folder: bool,
/// The metadata templates folder, where the save pick starts, once listed.
@@ -151,6 +158,15 @@ impl Templates {
&& let Some(answer) = cx.take_pick_answer(id)
{
self.ticket = None;
if let (Pick::Open, Picked::Contents(files)) = (kind, &answer) {
let Some((_, bytes)) = files.first() else { return };
if bytes.len() > vectorcraft_pdf::MAX_TEMPLATE_BYTES {
self.requests.push(Request::TemplateTooLarge);
} else {
*import = Some(source("dataBase64", vectorcraft_format::base64_encode(bytes)));
}
return;
}
let Some(path) = answer.first_path() else { return };
match kind {
Pick::Open => *import = Some(source("path", path.to_string_lossy().into_owned())),
@@ -210,6 +226,7 @@ impl Templates {
}
});
match chosen {
Some(Chosen::Pick(Pick::Save)) if self.web_save => self.requests.push(Request::Download),
Some(Chosen::Pick(kind)) => self.pick(cx, kind, title),
Some(Chosen::Template(file)) => wait_for_template(import, file),
Some(Chosen::Folder) => self.requests.push(Request::Folder),
@@ -221,7 +238,7 @@ impl Templates {
/// The File Info dialog: a form over the fields `file.info` reports, whose OK is held for the app.
pub(crate) struct FileInfoDialog {
id: DialogId,
document: u64,
document: (u64, u64),
open: bool,
/// OK files its answer for the app instead of closing ([`HoldsOk::held_ok`]).
hold: bool,
@@ -237,7 +254,7 @@ pub(crate) struct FileInfoDialog {
}
impl FileInfoDialog {
fn new(document: u64, value: Info) -> Self {
fn new(document: (u64, u64), value: Info) -> Self {
FileInfoDialog {
id: dialog_id(KEY),
document,
@@ -379,7 +396,7 @@ fn import_options(ui: &mut egui::Ui, mode: &mut &'static str) -> Option<bool> {
}
impl HoldsOk for FileInfoDialog {
type Answer = (u64, Info);
type Answer = ((u64, u64), Info);
fn held_ok(mut self) -> Self {
self.hold = true;
@@ -556,6 +573,26 @@ fn save_template(app: &mut VectorcraftApp, picked: PathBuf, fields: Info) -> Res
save(app).map(|_| ())
}
/// Save the draft through the browser's file service. Serializing it changes neither drawing nor draft.
fn download_template(app: &mut VectorcraftApp, fields: Info) -> Result<(), String> {
let title = text_of(&fields, "title");
let stem = vectorcraft_engine::cmd::library::file_stem_for(if title.trim().is_empty() { "Metadata" } else { &title });
let name = format!("{stem}.{XMP_EXT}");
let result = app.run("file.info.saveTemplate", json!({"fields": fields}))?;
let data = result["data"].as_str().ok_or("the metadata template contains no data")?.as_bytes().to_vec();
let request = PickRequest::save(PURPOSE).file_name(name).suggested_extension(XMP_EXT).filter(tl!("XMP metadata templates"), &[XMP_EXT]);
file_asks::save(app, request, data, file_asks::Owner::Free, |app, picked| {
match picked {
Picked::Downloaded(name) => app.status(format!("Saved {name}")),
Picked::Saved { path, .. } => app.status(format!("Saved {}", path.display())),
Picked::Failed(error) => return Err(error),
_ => {}
}
Ok(Value::Null)
});
Ok(())
}
/// Merge the template `source` names into the dialog's fields as `mode` says.
fn import(app: &mut VectorcraftApp, d: &mut FileInfoDialog, source: Info, mode: &str) -> Result<(), String> {
let mut p = Value::Object(source);
@@ -576,10 +613,13 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
// PLAN: fl.A9 lists no `file_info::pump`; the Templates menu needs the session, so hub-w2 adds this line to `dialogs::host::pump`.
let Some(dialogs) = app.dialogs() else { return };
let id = dialog_id(KEY);
let (can_save, can_open, has_folder) = (file_asks::can(app, PickKind::Save), file_asks::can(app, PickKind::Open), has_templates_folder(app));
let web_save = app.ui_ctx.as_ref().and_then(Host::try_of_ctx).is_some_and(|host| host.files().browser_saves());
let (can_save, can_open, has_folder) =
(web_save || file_asks::can(app, PickKind::Save), file_asks::can(app, PickKind::Open), has_templates_folder(app));
let requests = dialogs.with(|host| {
host.get_mut_by_id::<FileInfoDialog>(id).map(|d| {
d.templates.can_save = can_save;
d.templates.web_save = web_save;
d.templates.can_open = can_open;
d.templates.has_folder = has_folder;
d.take_requests()
@@ -602,6 +642,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
Some(fields) => save_template(app, path, fields),
None => Ok(()),
},
Request::TemplateTooLarge => Err(tl!("The metadata template is larger than 8 MB.").to_owned()),
Request::Download => match dialogs.with(|host| host.get_by_id::<FileInfoDialog>(id).map(FileInfoDialog::filed_fields)) {
Some(fields) => download_template(app, fields),
None => Ok(()),
},
Request::Import { source, mode } => {
dialogs.with(|host| host.get_mut_by_id::<FileInfoDialog>(id).map(|d| import(app, d, source, mode))).unwrap_or(Ok(()))
}
@@ -640,6 +685,42 @@ mod tests {
app.dialogs().unwrap().with(|host| host.set_json_field(&ctx, dialog_id(KEY), field, value))
}
#[test]
fn stale_file_info_cannot_replace_metadata_restored_by_revert() {
let mut app = windowed();
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let dir = vectorcraft_testkit::TempDir::new("file-info-metadata-revert");
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("file.info", json!({"title": "Saved Title"})).unwrap();
app.run("file.saveAs", json!({"path": dir.join("metadata.vectorcraft")})).unwrap();
let saved = &app.session.active().unwrap().doc;
let (saved_title, saved_metadata) = (saved.info_title().to_owned(), saved.metadata.clone());
app.run("file.info", json!({"title": "Unsaved Title"})).unwrap();
app.run("ui.fileInfoDialog", json!({})).unwrap();
set(&app, "title", json!("Old Draft")).unwrap();
let source = app.session.active().unwrap();
let (uid, generation) = (source.uid, source.reverts);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let reverted = app.session.active().unwrap();
assert_eq!(reverted.uid, uid);
assert_ne!(reverted.reverts, generation);
assert_eq!(reverted.doc.info_title(), saved_title);
assert_eq!(reverted.doc.metadata, saved_metadata);
let undo = reverted.history.undo.len();
crate::tests::picks::answer_dialog(&mut app, dialog_id(KEY), &[], true);
let reverted = app.session.active().unwrap();
assert_eq!(reverted.doc.info_title(), saved_title);
assert_eq!(reverted.doc.metadata, saved_metadata);
assert_eq!(reverted.history.undo.len(), undo);
assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(dialog_id(KEY))), Some(HeldOk::Refused(_))));
app.run("ui.fileInfoDialog", json!({})).unwrap();
crate::tests::picks::answer_dialog(&mut app, dialog_id(KEY), &[("title", json!("Fresh Title"))], true);
assert_eq!(app.run("file.info", json!({})).unwrap()["title"], json!("Fresh Title"));
}
/// Presses OK: the dialog files its fields, and the frames after it run the app's OK and close an accepted dialog
/// (a second OK would file a refused answer again). Whether it closed.
fn press_ok(app: &mut VectorcraftApp) -> bool {
@@ -650,6 +731,75 @@ mod tests {
app.dialogs().unwrap().with(|host| host.held_state(dialog_id(KEY)))
}
#[test]
fn browser_template_saves_export_the_draft_and_preserve_it_on_cancel_or_failure() {
use std::cell::RefCell;
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use craft::host::{Picked, ScriptedFiles};
use craft::ui::testing::{Fixture, Room};
let mut app = windowed();
let files = Arc::new(ScriptedFiles::held().in_browser());
crate::tests::picks::install_files(&mut app, files.clone());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let original = app.session.active().unwrap().doc.metadata.clone();
let app = Rc::new(RefCell::new(app));
let shown = Rc::clone(&app);
let mut fixture = Fixture::new(move |ui| crate::tests::picks::dialogs(&mut shown.borrow_mut(), ui));
fixture.in_room(Room::Window);
let ctx = fixture.ctx().clone();
{
let mut app = app.borrow_mut();
app.ui_ctx = Some(ctx.clone());
craft::host::Host::clone(&app.host).install(&ctx);
app.run("ui.fileInfoDialog", json!({})).unwrap();
set(&app, "title", json!("Draft Template")).unwrap();
set(&app, "author", json!("Ada")).unwrap();
set(&app, PENDING, json!("print")).unwrap();
}
fixture.settle();
let draft = with_dialog(&app.borrow(), |d| d.filed_fields()).unwrap();
for answer in [
Picked::Saved { path: "draft.xmp".into(), file_type: None },
Picked::Downloaded("draft.xmp".into()),
Picked::Cancelled,
Picked::Failed("download refused".into()),
] {
let before = files.requests().len();
let menu = fixture.by_label("Templates").expect("the Templates menu");
fixture.click(&menu).settle();
let save = fixture.by_label("Save Metadata Template…").expect("browser hosts can save the draft");
fixture.click(&save).settle();
assert_eq!(files.requests().len(), before + 1, "one save per action");
let request = files.requests().pop().unwrap();
assert_eq!(request.kind, craft::host::PickKind::Save);
assert!(request.file_name.as_deref().is_some_and(|name| name.ends_with(".xmp")));
app.borrow_mut().ui.status = "before the answer".into();
assert!(files.answer(answer.clone()).is_some());
crate::file_asks::poll(&mut app.borrow_mut());
fixture.settle();
let app = app.borrow();
match answer {
Picked::Cancelled => assert_eq!(app.ui.status, "before the answer"),
Picked::Failed(_) => assert_eq!(app.ui.status, "download refused"),
_ => assert!(app.ui.status.starts_with("Saved ")),
}
assert_eq!(with_dialog(&app, |d| d.filed_fields()).unwrap(), draft);
let document = app.session.active().unwrap();
assert_eq!(document.doc.metadata, original);
assert!(document.history.undo.is_empty());
assert!(document.path.is_none(), "saving a template does not save the drawing");
}
let xmp = files.file(Path::new("draft.xmp")).expect("the service received the XMP bytes");
let template = vectorcraft_pdf::read_template(&xmp).expect("the saved draft is a metadata template");
assert_eq!(template.title.as_deref(), Some("Draft Template"));
assert_eq!(template.author.as_deref(), Some("Ada"));
assert_eq!(template.keywords, Some(vec!["print".into()]));
}
#[test]
fn file_info_draws_and_ok_is_one_undo_step() {
let mut app = windowed();
@@ -767,6 +917,54 @@ mod tests {
assert_eq!(st.history.undo.len(), 1);
}
#[test]
fn browser_picked_templates_enter_the_merge_choice_and_edit_only_the_draft() {
use std::sync::Arc;
use craft::host::{Files, PickRequest, Picked, ScriptedFiles};
let template = vectorcraft_pdf::metadata_template(&vectorcraft_pdf::FileInfo {
description: Some("À l’affiche 版".into()),
rating: Some(3),
..Default::default()
});
let utf16 = std::iter::once(0xfeff).chain(template.encode_utf16()).flat_map(u16::to_le_bytes).collect::<Vec<_>>();
for bytes in [template.into_bytes(), utf16] {
let mut app = windowed();
let files = Arc::new(ScriptedFiles::held());
crate::tests::picks::install_files(&mut app, files.clone());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("ui.fileInfoDialog", json!({})).unwrap();
set(&app, "author", json!("Ada")).unwrap();
let ticket = files.pick(PickRequest::open(super::PURPOSE));
with_dialog(&app, |d| d.templates.ticket = Some((ticket, super::Pick::Open))).unwrap();
assert!(files.answer(Picked::Contents(vec![("Studio.xmp".into(), bytes)])).is_some());
let ctx = app.ui_ctx.clone().unwrap();
for _ in 0..3 {
crate::tests::synthetic::key_frame(&mut app, &ctx, Vec::new());
}
with_dialog(&app, |d| {
assert!(d.templates.ticket.is_none(), "the File Info form consumed the picker answer");
assert!(d.import.is_some(), "a browser-selected template reaches the merge choice");
assert!(super::choose_mode(&mut d.import_mode, "append"));
super::ask_import(&mut d.templates, &d.import, d.import_mode);
})
.unwrap();
super::pump(&mut app, &ctx);
let fields = with_dialog(&app, |d| d.filed_fields()).unwrap();
assert_eq!(
(fields["author"].clone(), fields["description"].clone(), fields["rating"].clone()),
(json!("Ada"), json!("À l’affiche 版"), json!(3))
);
assert_eq!(app.session.active().unwrap().history.undo.len(), 0, "the template updates the draft before OK");
assert!(press_ok(&mut app));
let st = app.session.active().unwrap();
assert_eq!(st.doc.metadata.description, "À l’affiche 版");
assert_eq!(st.history.undo.len(), 1);
}
}
#[test]
fn ok_waits_for_the_merge_choice_of_a_template_being_imported() {
let mut app = windowed();
+2 -1
View File
@@ -311,10 +311,11 @@ pub(super) fn from_missing_links(
folder: &str,
) -> Result<(), String> {
let mut find = dialog(app, missing.clone(), modified.clone(), true)?;
let document = find["document"].as_u64().ok_or("no document open")?;
find.insert("notes".into(), json!(notes));
start_search(app, &mut find, folder)?;
open(app, find)?;
app.link_asks = Some(LinkAsk { missing, modified, notes, back: true });
app.link_asks = Some(LinkAsk { document, missing, modified, notes, back: true });
Ok(())
}
+48 -17
View File
@@ -14,10 +14,9 @@
//! closed, and opens the dialog when there has been none.
//!
//! The walk lives in `UiState::last_find`: the Find text and the switches of the last request, its
//! `replace` text and `backwards`, the place it reached in `from` (`{id, start, end}`), the `uid` of
//! that document in `doc` and the match found in `found` (`{index, count}`). A place in a document
//! other than the active one, or reached with other Find text or switches, is not used: the search
//! starts again. [`pump`] runs the dialog's requests once per frame.
//! `replace` text and `backwards`, the place it reached in `from` (`{id, start, end}`), the drawing's
//! UID and Revert counter in `doc`, and the match in `found` (`{index, count}`). Changing the
//! loaded drawing, Find text, or switches restarts the search. [`pump`] runs the requests each frame.
use craft::text::find::FindOptions;
use craft::text::ui::find::{FindCheck, FindReplaceDialog, FindRequest, FindTab, ReplaceButtons};
@@ -56,9 +55,18 @@ pub fn menu_params() -> Value {
json!({"find": null})
}
/// The `uid` of the active document.
fn active_uid(app: &VectorcraftApp) -> Option<u64> {
app.session.active().map(|d| d.uid)
/// The active drawing and its loaded generation.
fn active_drawing(app: &VectorcraftApp) -> Option<(u64, u64)> {
app.session.active().map(|d| (d.uid, d.reverts))
}
fn saved_drawing(last: &Map<String, Value>) -> Option<(u64, u64)> {
let [uid, reverts] = last.get("doc")?.as_array()?.as_slice() else { return None };
Some((uid.as_u64()?, reverts.as_u64()?))
}
fn same_drawing(last: &Map<String, Value>, drawing: (u64, u64)) -> bool {
saved_drawing(last) == Some(drawing)
}
/// The match found belongs to an open dialog: the last search keeps its place, not the match.
@@ -127,13 +135,20 @@ pub fn find_next(app: &mut VectorcraftApp) -> Result<Value, String> {
return open(app, &Map::new());
};
forget_found(app);
let uid = active_uid(app);
let drawing = active_drawing(app);
if let Some(o) = last.as_object_mut() {
let saved = saved_drawing(o);
o.remove("replace");
o.remove("found");
// A place in another document is no place in this one.
if uid.is_none() || o.remove("doc").and_then(|d| d.as_u64()) != uid {
o.remove("from");
o.remove("doc");
if saved != drawing || drawing.is_none() {
let restored = saved.zip(drawing).is_some_and(|((old_uid, _), (uid, _))| old_uid == uid);
if restored {
// An explicit start ignores the whole text frame currently selected.
o.insert("from".into(), Value::Null);
} else {
o.remove("from");
}
}
}
let r = app.run(NEXT, last)?;
@@ -143,7 +158,7 @@ pub fn find_next(app: &mut VectorcraftApp) -> Result<Value, String> {
}
if let Some(l) = app.ui.last_find.as_mut() {
l["from"] = json!({ "id": r["id"], "start": r["start"], "end": r["end"] });
l["doc"] = json!(uid);
l["doc"] = json!(drawing);
}
Ok(r)
}
@@ -178,9 +193,9 @@ fn form(d: &FindReplaceDialog) -> Form {
/// The place the last search reached, `{id, start, end}`, while its document is the active one and
/// the Find text and the switches are `query`, those it was reached with.
fn place<'a>(app: &VectorcraftApp, last: &'a Value, query: &Value) -> Option<&'a Value> {
let uid = active_uid(app)?;
let drawing = active_drawing(app)?;
let last = last.as_object()?;
let same = last.get("doc").and_then(Value::as_u64) == Some(uid) && query_in(last) == *query;
let same = same_drawing(last, drawing) && query_in(last) == *query;
same.then(|| last.get("from")).flatten().filter(|at| at.is_object())
}
@@ -204,7 +219,7 @@ fn remember(app: &mut VectorcraftApp, form: &Form, at: Option<Value>, found: Opt
last["backwards"] = json!(form.backwards);
if let Some(at) = at {
last["from"] = at;
last["doc"] = json!(active_uid(app));
last["doc"] = json!(active_drawing(app));
}
if let Some(found) = found {
last["found"] = found;
@@ -293,6 +308,22 @@ fn shown_match(app: &VectorcraftApp, at: &Value, found: &Value) -> Option<String
Some(format!("{} / {} {lead}{before}{hit}{after}{tail}", found["index"], found["count"]))
}
/// Refreshes the match line when a drawing or query change makes its match ineligible or current again.
fn refresh_match(app: &mut VectorcraftApp, query: &Value) -> (bool, Option<String>) {
let Some(last) = app.ui.last_find.as_ref() else { return (false, None) };
let Some(found) = last.get("found") else { return (false, None) };
let at = place(app, last, query);
let matched = at.is_some();
if found["visible"].as_bool().unwrap_or(true) == matched {
return (matched, None);
}
let message = at.and_then(|at| shown_match(app, at, found)).unwrap_or_default();
if let Some(found) = app.ui.last_find.as_mut().and_then(|last| last.get_mut("found")) {
found["visible"] = json!(matched);
}
(matched, Some(message))
}
/// Runs the request the dialog made this frame, then tells the dialog its message and whether a
/// match is current. The match is evaluated in every pump, so a changed Find text or switch
/// disables Replace and Replace & Find at once; a pass that has no request only refreshes it.
@@ -309,10 +340,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
};
Some(ran.unwrap_or_else(|e| said(&e)))
});
let matched = app.ui.last_find.as_ref().is_some_and(|last| current_match(app, last, &form.query).is_some());
let (matched, match_message) = refresh_match(app, &form.query);
dialogs.with(|host| {
if let Some(d) = host.get_mut::<FindReplaceDialog>() {
if let Some(message) = message {
if let Some(message) = message.or(match_message) {
d.set_message(message);
}
d.set_matched(matched);
@@ -97,6 +97,48 @@ fn selected(p: &Panel) -> Vec<u64> {
p.app().session.active().unwrap().selection.objects.iter().map(|id| id.0).collect()
}
#[test]
fn a_cached_match_cannot_replace_text_restored_by_revert() {
let (mut app, ids) = app_with(&["Needle Needle"]);
let id = ids[0];
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let dir = vectorcraft_testkit::TempDir::new("find-replace-reverted-match");
app.run("file.saveAs", json!({"path": dir.join("text.vectorcraft")})).unwrap();
app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 10, "height": 10})).unwrap();
app.run("select.none", json!({})).unwrap();
let st = app.session.active().unwrap();
let version = (st.uid, st.reverts);
let mut p = Panel::new(app, draw);
choose(&p);
set(&p, "find", json!("Needle"));
set(&p, "replace", json!("Changed"));
p.click("Find Next");
assert_eq!(matched(&p), Some((id, 0, 6)));
p.app().run("file.revert", json!({"confirmed": true})).unwrap();
{
let app = p.app();
let st = app.session.active().unwrap();
assert_eq!(st.uid, version.0);
assert_ne!(st.reverts, version.1);
}
let before = undo_steps(&p);
let form = with_dialog(&p, |d| super::form(d));
// A Replace action dispatched before the dialog has refreshed must still check the match.
super::replace(&mut p.app(), &form, false).unwrap();
assert_eq!(plain(&p, id), "Needle Needle");
assert_eq!(undo_steps(&p), before);
pump(&p);
assert_eq!(matched(&p), None);
assert!(message(&p).is_empty());
p.click("Find Next");
assert_eq!(matched(&p), Some((id, 0, 6)));
p.click("Replace");
assert_eq!(plain(&p, id), "Changed Needle");
}
/// The Edit menu's rows for Find and Replace, Check Spelling (in its Spelling submenu) and Edit Custom Dictionary
/// are enabled, and invoking each puts that dialog on the host.
#[test]
@@ -296,6 +338,37 @@ fn a_changed_search_starts_again() {
assert_eq!(matched(&p), Some((bottom, 4, 7)), "the same search goes on");
}
#[test]
fn the_match_line_follows_the_active_drawing_and_find_query() {
let (app, _) = app_with(&["source cat match"]);
let mut p = Panel::new(app, draw);
p.app().run("file.new", json!({"width": 800, "height": 600})).unwrap();
p.app().run("text.create", json!({"x": 50, "y": 50, "text": "destination dog match"})).unwrap();
p.app().run("document.activate", json!({"index": 0})).unwrap();
choose(&p);
set(&p, "find", json!("cat"));
p.click("Find Next");
assert!(message(&p).contains("source cat match"));
p.app().run("document.activate", json!({"index": 1})).unwrap();
pump(&p);
assert_eq!(matched(&p), None);
assert_eq!(message(&p), "", "the line must not describe a match from another drawing");
p.app().run("document.activate", json!({"index": 0})).unwrap();
pump(&p);
assert!(matched(&p).is_some());
assert!(message(&p).contains("source cat match"));
set(&p, "find", json!("dog"));
pump(&p);
assert_eq!(matched(&p), None);
assert_eq!(message(&p), "", "the line must not describe a match for the previous query");
p.click("Find Next");
pump(&p);
assert_eq!(message(&p), "No matches found", "refreshing the dialog leaves the search result visible");
}
/// The place a search reached belongs to its document: in another document, Edit › Find Next and
/// the dialog start at that document's first match, even where an object there has the same id.
/// The params of a `ui.paramDialog` call take the place of the last search's, a switch that is off
@@ -343,3 +416,30 @@ fn a_search_place_stays_in_its_document_and_given_params_win() {
choose(&p);
assert_eq!((field(&p, "find"), field(&p, "matchCase")), (json!("cat"), json!(true)));
}
#[test]
fn edit_find_next_starts_at_the_first_restored_match_with_that_frame_selected() {
let (mut app, ids) = app_with(&["cat in the back", "cat cat in front"]);
let first = ids[1];
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let dir = vectorcraft_testkit::TempDir::new("menu-find-next-revert");
app.run("file.saveAs", json!({"path": dir.join("text.vectorcraft")})).unwrap();
app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 10, "height": 10})).unwrap();
let mut p = Panel::new(app, draw);
choose(&p);
set(&p, "find", json!("cat"));
p.click("Find Next");
assert_eq!(matched(&p), Some((first, 0, 3)));
p.click("Find Next");
assert_eq!(matched(&p), Some((first, 4, 7)));
p.click("Close");
p.app().run("file.revert", json!({"confirmed": true})).unwrap();
p.app().run("select.set", json!({"ids": [first]})).unwrap();
let before = undo_steps(&p);
choose_find_next(&p);
assert_eq!(from(&p), json!({"id": first, "start": 0, "end": 3}));
assert_eq!(selected(&p), vec![first]);
assert_eq!(undo_steps(&p), before);
}
+107 -11
View File
@@ -16,6 +16,8 @@
//! (`ObjectDialogs::flare`), not fields.
// PLAN: the `craft_ui` paths and `LivePreview`'s home (`form`) are assumed; `general_lengths` is cv.B5b's.
use std::sync::Arc;
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{HostedParamDialog, Param, ParamDialog, ParamResult};
use craft::ui::runtime::env::{LengthUnits, UnitKind};
@@ -39,6 +41,8 @@ pub const KIND: &str = "flareOptions";
pub(crate) struct Open {
/// The hosted dialog.
id: DialogId,
opening: Arc<()>,
document: Option<(u64, u64)>,
/// Where a click opened it, to draw a flare there on OK.
click: Option<Point>,
/// The selected flares (ids) and the settings the dialog opened with, to change them on OK.
@@ -47,6 +51,27 @@ pub(crate) struct Open {
preview: Option<LivePreview>,
}
const PREVIEW_LABEL: &str = "Flare";
impl Open {
fn on_original_drawing(&self, app: &VectorcraftApp) -> bool {
self.preview.is_none() || app.session.active().map(|st| (st.uid, st.reverts)) == self.document
}
fn cancel_preview(self, app: &mut VectorcraftApp) {
if self.on_original_drawing(app)
&& !other_preview(app)
&& let Some(preview) = self.preview
{
preview.cancel(app);
}
}
}
fn other_preview(app: &VectorcraftApp) -> bool {
app.session.active().and_then(|st| st.interaction.as_ref()).is_some_and(|p| p.label != PREVIEW_LABEL)
}
/// Open the Flare Tool Options with the tool's values; `at`: where a click opened them, to draw a
/// flare there on OK. Opened without a click while flares are selected, they show the first one's
/// settings, to change the selected flares on OK.
@@ -91,24 +116,25 @@ pub fn open(app: &mut VectorcraftApp, at: Option<Point>) -> Value {
return Value::Null;
};
// An open the host replaces leaves its preview behind unless it is rolled back here.
if let Some(old) = app.object_dialogs.flare.take()
&& let Some(preview) = old.preview
{
preview.cancel(app);
if let Some(old) = app.object_dialogs.flare.take() {
old.cancel_preview(app);
}
let cancel: Box<dyn FnOnce(&mut VectorcraftApp)> = Box::new(|app| {
if let Some(open) = app.object_dialogs.flare.take()
&& let Some(preview) = open.preview
let opening = Arc::new(());
let cancelled = Arc::clone(&opening);
let cancel: Box<dyn FnOnce(&mut VectorcraftApp)> = Box::new(move |app| {
if app.object_dialogs.flare.as_ref().is_some_and(|open| Arc::ptr_eq(&open.opening, &cancelled))
&& let Some(open) = app.object_dialogs.flare.take()
{
preview.cancel(app);
open.cancel_preview(app);
}
});
let held = HeldOptions { parent: None, cancel: Some(cancel) };
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| {
ParamDialog::new(KIND, tl!("Flare Tool Options"), params(lengths)).values(Bind::bound(fields)).previews(previews).reset_to(defaults.clone())
});
let document = app.session.active().map(|st| (st.uid, st.reverts));
match open_held_with(app, dialog, ok, held) {
Some(id) => app.object_dialogs.flare = Some(Open { id, click: at, edit, preview: previews.then(LivePreview::default) }),
Some(id) => app.object_dialogs.flare = Some(Open { id, opening, document, click: at, edit, preview: previews.then(LivePreview::default) }),
None => app.status("no window"),
}
json!({ "dialog": KIND })
@@ -242,15 +268,27 @@ fn option_values(fields: &Map<String, Value>) -> Map<String, Value> {
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
// PLAN: registered in hub-w2's pump file (wg.A18), one line.
let Some(mut open) = app.object_dialogs.flare.take() else { return };
if !open.on_original_drawing(app) {
app.object_dialogs.flare = Some(open);
return;
}
if let Some(mut preview) = open.preview.take() {
let state = app
.dialogs()
.and_then(|host| host.with(|host| host.get_by_id::<HostedParamDialog>(open.id).map(|d| (d.is_previewing(), d.fields().clone()))));
if let Some((previewing, fields)) = state {
let values = form::json_of(&params(general_lengths(app)), &fields);
if let Some((cmd, params)) = command(app, &open, &values) {
if previewing
&& other_preview(app)
&& let Err(e) = app.keep_typing()
{
app.status(e);
}
if !other_preview(app)
&& let Some((cmd, params)) = command(app, &open, &values)
{
// The preview reports its own failures on the status line.
let _ = preview.run(app, previewing, "Flare", &cmd, &params);
let _ = preview.run(app, previewing, PREVIEW_LABEL, &cmd, &params);
}
}
open.preview = Some(preview);
@@ -261,6 +299,19 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
/// OK: set the tool's options; opened by a click, draw a flare there with them. Opened for the
/// selected flares, draw them again with the settings changed, leaving the tool's options.
fn ok(app: &mut VectorcraftApp, result: &ParamResult) -> Result<(), String> {
let open = app.object_dialogs.flare.as_ref().ok_or("the Flare Tool Options dialog is gone")?;
if !open.on_original_drawing(app) {
if app.session.active().map(|st| st.uid) == open.document.map(|(uid, _)| uid) {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
return Err(tl!("Return to the original drawing to place or edit the flare").into());
}
if open.preview.is_some() && other_preview(app) {
app.keep_typing()?;
if other_preview(app) {
return Err(tl!("Finish the current edit before drawing the flare").into());
}
}
let fields = form::json_of(&params(general_lengths(app)), &result.fields);
let accepted = accept(app, &fields);
if accepted.is_ok() {
@@ -430,6 +481,23 @@ mod tests {
assert_eq!(parts.iter().filter(|p| *p == "Ring").count(), 3, "{parts:?}");
}
#[test]
fn a_pending_flare_click_waits_for_its_original_drawing() {
let mut app = app();
open(&mut app, Some(Point::new(100.0, 110.0)));
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers[0].children().unwrap().len();
pump(&mut app);
assert_eq!(count(&app), 0, "the other drawing never shows the flare preview");
press_ok(&mut app);
assert_eq!(count(&app), 0, "the other drawing never keeps the flare");
assert!(app.object_dialogs.flare.is_some());
app.run("document.activate", json!({"index": 0})).unwrap();
press_ok(&mut app);
assert_eq!(count(&app), 1);
assert!(!flare_parts(&app).is_empty());
}
/// With a flare selected, the toolbar's Flare Tool Options show its settings, and OK draws it
/// again with the settings changed, as one undo step, leaving the tool's options.
#[test]
@@ -479,4 +547,32 @@ mod tests {
let parts = flare_parts(&app);
assert_eq!((parts.iter().filter(|p| *p == "Ring").count(), parts.iter().any(|p| p == "Rays")), (10, true), "{parts:?}");
}
#[test]
fn a_pending_flare_does_not_draw_on_restored_art() {
let mut app = app();
let dir = vectorcraft_testkit::TempDir::new("flare-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
app.run("shape.ellipse", json!({"x": 5, "y": 5, "width": 20, "height": 20})).unwrap();
let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers[0].children().unwrap().len();
open(&mut app, Some(Point::new(100.0, 110.0)));
pump(&mut app);
assert_eq!(count(&app), 2, "the original art and the flare preview");
app.run("file.revert", json!({"confirmed": true})).unwrap();
pump(&mut app);
assert_eq!(count(&app), 0, "the old preview leaves the restored art alone");
let options = app.session.tool_options_of("flare");
press_ok(&mut app);
assert_eq!(count(&app), 0, "the old approval leaves the restored art alone");
assert_eq!(app.session.tool_options_of("flare"), options);
assert!(app.object_dialogs.flare.is_some());
press_cancel(&mut app);
open(&mut app, Some(Point::new(100.0, 110.0)));
press_ok(&mut app);
assert_eq!(count(&app), 1);
}
}
+69 -3
View File
@@ -175,12 +175,13 @@ pub(crate) fn custom_dialog(ctx: &egui::Context, parent: &HostedPdfExport, job:
as_written(&mut o, parent.settings().advanced.overprint);
let mut fields = option_fields(&o);
fields.set(KEPT_OVERPRINTS, kept);
HostedParamDialog::new(ctx, CUSTOM_KEY, fields, |_| {
HostedParamDialog::new(ctx, CUSTOM_KEY, fields, |fields| {
ParamDialog::new(
CUSTOM_KEY,
tl!("Custom Transparency Flattener Options"),
option_params(&FIXED, tl!("PDF 1.3 files clip rasterized areas to their regions, and Overprint sets whether overprints are kept.")),
)
.values(Bind::bound(fields))
})
}
@@ -213,8 +214,8 @@ pub(crate) fn apply_custom(job: &mut SavePdfJob, parent: &HostedPdfExport, field
/// Open Flatten Transparency for the selection with the default preset.
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let dialog = HostedParamDialog::new(&ctx, KEY, option_fields(&FlattenOptions::default()), |_| {
ParamDialog::new(KEY, tl!("Flatten Transparency"), option_params(&[], "")).previews(true)
let dialog = HostedParamDialog::new(&ctx, KEY, option_fields(&FlattenOptions::default()), |fields| {
ParamDialog::new(KEY, tl!("Flatten Transparency"), option_params(&[], "")).values(Bind::bound(fields)).previews(true)
})
// Flattening complex art is slow: the preview waits until it is turned on.
.preview_off();
@@ -450,4 +451,69 @@ mod tests {
create(&mut app, &ctx, id, params, "High Resolution");
assert_eq!(app.session.prefs.flattener_presets.len(), 1);
}
#[test]
fn flattened_art_resolution_keeps_a_live_keyboard_edit() {
assert_live_resolution(false);
}
#[test]
fn pdf_flattener_resolution_keeps_a_live_keyboard_edit() {
assert_live_resolution(true);
}
fn assert_live_resolution(custom: bool) {
use craft::ui::testing::Fixture;
use std::cell::RefCell;
use std::rc::Rc;
let app = Rc::new(RefCell::new(scene()));
let shown = app.clone();
let mut fixture = Fixture::new(move |ui| {
let mut app = shown.borrow_mut();
let dialogs = app.dialogs().unwrap();
dialogs.with(|host| host.run(ui));
super::super::host::pump(&mut app, ui.ctx());
});
fixture.room(egui::vec2(880.0, 720.0));
let ctx = fixture.ctx().clone();
let mut job = SavePdfJob {
path: None,
save_mode: None,
flattener: Some(FlattenOptions { line_art_ppi: 611.0, ..FlattenOptions::default() }),
selection: false,
};
let parent = HostedPdfExport::new(vectorcraft_pdf::APP, vectorcraft_pdf::PdfSettings::default());
let id = {
let mut app = app.borrow_mut();
app.ui_ctx = Some(ctx.clone());
if custom {
let dialog = custom_dialog(&ctx, &parent, &job, &[]);
app.dialogs().unwrap().with(|host| host.open(dialog))
} else {
open(&mut app).unwrap();
app.flatten_dialog.open.as_ref().unwrap().id
}
};
fixture.settle();
let field = fixture
.by_label("Line Art and Text Resolution")
.or_else(|| fixture.by_label("Line Art and Text Resolution:"))
.expect("the hosted resolution field");
if custom {
let fields = app.borrow().dialogs().unwrap().with(|h| h.get_by_id::<HostedParamDialog>(id).unwrap().fields().clone());
assert_eq!(fields.number("lineArtPpi"), Some(611.0), "the PDF dialog opens with the job's own resolution");
}
fixture.click(&field).key(egui::Key::A, egui::Modifiers::COMMAND).type_text("399").key(egui::Key::Tab, egui::Modifiers::NONE).settle();
let app = app.borrow();
let fields = app.dialogs().unwrap().with(|h| h.get_by_id::<HostedParamDialog>(id).unwrap().fields().clone());
assert_eq!(fields.number("lineArtPpi"), Some(399.0), "the hosted form keeps its keyboard edit");
if custom {
apply_custom(&mut job, &parent, &fields, &[]).unwrap();
assert_eq!(job.flattener.unwrap().line_art_ppi, 399.0);
} else {
let params = command_params(&option_params(&[], ""), &fields, &[]).unwrap();
assert_eq!(params["lineArtPpi"], 399.0);
}
}
}
+327 -39
View File
@@ -13,24 +13,32 @@
//! Fields: `tab` (`color` or `swatches`). Agents can set `color` (hex), `opacity` and `location` (a
//! point: `spread`) as percentages, and confirm; confirming reports no stop index.
use std::sync::Arc;
use craft::behavior::IconId;
use craft::color_ui::ui::{ColorPanel, ColorPanelLayout, ColorPanelOutput, ColorPanelShown, ColorPanelState, DropperButton, SwatchPalette};
use craft::color_ui::ui::{
ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelOutput, ColorPanelShown, ColorPanelState, ColorPanelWords, DropperButton, SwatchPalette,
};
use craft::theme::Srgba;
use craft::theme::variant::Tone;
use craft::ui::buttons::Button;
use craft::ui::choice::Segmented;
use craft::ui::contract::{Bind, Entry, Show as _, ShowContainer as _};
use craft::ui::contract::{Bind, Entry, PopupKind, Show as _, ShowContainer as _, Trigger};
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use craft::ui::form::Field;
use craft::ui::layout_components::{Row, Stack};
use craft::ui::menu::{Menu, MenuItem};
use craft::ui::notices::Notice;
use craft::ui::popover::Popover;
use craft::ui::runtime::env::{Label, UnitKind};
use craft::ui::runtime::env::{Env, Label, UnitKind};
use craft::ui::runtime::overlay::CloseReason;
use craft::ui::text::NumberField;
use egui::{Pos2, Ui, vec2};
use serde_json::{Value, json};
use vectorcraft_color::gradient::move_stop;
use vectorcraft_color::{Color, FreeformPoint, GradientStop, Paint};
use vectorcraft_color::{Color, FreeformPoint, GradientPaint, GradientStop, Paint};
use vectorcraft_doc::NodeId;
use vectorcraft_engine::GradientEditPaints;
use vectorcraft_geom::{Point, Rect};
use vectorcraft_tools::params::color_json;
@@ -54,28 +62,90 @@ pub(crate) enum Anchor {
/// What the popover edits: the selected stop of the gradient behind the active proxy (with all
/// its stops), or the selected point of a freeform gradient.
enum Target {
Stop(Vec<GradientStop>, usize),
Point(FreeformPoint, usize),
Stop(Box<GradientPaint>, usize),
Point(Box<GradientPaint>, FreeformPoint, usize),
}
/// The paint target and selected stop or point shown when the popover opened.
#[derive(Clone, PartialEq, Eq)]
struct TargetKey {
document: u64,
objects: Vec<NodeId>,
item: Option<usize>,
fill: bool,
tool_paint: bool,
point: bool,
index: usize,
}
impl TargetKey {
fn of(app: &VectorcraftApp, target: &Target) -> Option<Self> {
let doc = app.session.active()?;
let fill = app.session.fill_active;
let (point, index) = match target {
Target::Stop(_, index) => (false, *index),
Target::Point(_, _, index) => (true, *index),
};
Some(Self {
document: doc.uid,
objects: doc.selection.objects.clone(),
item: app.session.appearance_item(),
fill,
tool_paint: app.session.tool_paints(!fill),
point,
index,
})
}
fn matches(&self, app: &VectorcraftApp, target: &Target) -> bool {
Self::of(app, target).as_ref() == Some(self)
}
}
/// The gradient in that slot as the popover last saw it, including any live edits it applied.
#[derive(Clone)]
struct TargetOwner {
key: TargetKey,
paints: Arc<TargetPaints>,
}
struct TargetPaints {
shown: GradientPaint,
edited: GradientEditPaints,
}
impl TargetOwner {
fn matches(&self, app: &VectorcraftApp, target: &Target) -> bool {
self.key.matches(app, target)
&& self.paints.shown == *target.paint()
&& app.session.gradient_edit_paints(!self.key.fill).is_ok_and(|paints| paints == self.paints.edited)
}
}
impl Target {
fn paint(&self) -> &GradientPaint {
match self {
Self::Stop(paint, _) | Self::Point(paint, _, _) => paint,
}
}
fn color(&self) -> Color {
match self {
Target::Stop(stops, i) => stops.get(*i).map_or(Color::BLACK, |s| s.color),
Target::Point(p, _) => p.color,
Target::Stop(paint, i) => paint.gradient.stops[*i].color,
Target::Point(_, p, _) => p.color,
}
}
fn opacity(&self) -> f32 {
match self {
Target::Stop(stops, i) => stops.get(*i).map_or(1.0, |s| s.opacity),
Target::Point(p, _) => p.opacity,
Target::Stop(paint, i) => paint.gradient.stops[*i].opacity,
Target::Point(_, p, _) => p.opacity,
}
}
/// The location of a stop or the spread of a point, 0 to 1.
fn amount(&self) -> f32 {
match self {
Target::Stop(stops, i) => stops.get(*i).map_or(0.0, |s| s.offset),
Target::Point(p, _) => p.spread,
Target::Stop(paint, i) => paint.gradient.stops[*i].offset,
Target::Point(_, p, _) => p.spread,
}
}
}
@@ -85,10 +155,11 @@ fn selected(app: &VectorcraftApp) -> Option<Target> {
if edits_points(app, &g) {
let f = shown_points(&g);
let i = app.session.selected_freeform_point().filter(|i| *i < f.points.len())?;
return Some(Target::Point(f.points[i], i));
let point = f.points[i];
return Some(Target::Point(g, point, i));
}
let i = app.session.selected_stop().filter(|i| *i < g.gradient.stops.len())?;
Some(Target::Stop(g.gradient.stops, i))
Some(Target::Stop(g, i))
}
/// `stops` with stop `i` given `color`, linked to `link` (a global swatch and tint) or unlinked.
@@ -127,13 +198,18 @@ impl Tab {
/// The fields set from outside the popover or edited in it, as percentages where the field is one; each `None` is
/// a field left alone.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct PopoverFields {
struct PopoverFields {
color: Option<Color>,
opacity: Option<f64>,
location: Option<f64>,
spread: Option<f64>,
}
pub(crate) struct PopoverAnswer {
target: TargetOwner,
fields: PopoverFields,
}
/// The target's values and what the Color panel shows, as `pump` last pushed them.
#[derive(Clone)]
struct Feed {
@@ -159,10 +235,13 @@ struct Filed {
swatch: Option<(String, Color)>,
eyedropper: bool,
panels: Vec<ColorPanelOutput>,
/// Only an actual Shift-cycle changes this; an unchanged local snapshot must not overwrite a menu command.
mode: Option<ColorPanelMode>,
}
/// The gradient stop popover.
pub(crate) struct GradientStopPopover {
target: TargetOwner,
/// Where it opened.
pub(crate) anchor: Anchor,
/// The view it shows.
@@ -177,8 +256,9 @@ pub(crate) struct GradientStopPopover {
}
impl GradientStopPopover {
fn new(anchor: Anchor) -> Self {
fn new(anchor: Anchor, target: TargetOwner) -> Self {
Self {
target,
anchor,
tab: Tab::default(),
at: Pos2::ZERO,
@@ -199,21 +279,24 @@ fn rejects(field: &str, value: &Value) -> String {
}
impl StackDialog for GradientStopPopover {
type Result = PopoverFields;
type Result = PopoverAnswer;
fn id(&self) -> DialogId {
dialog_id(KIND)
}
fn show(&mut self, ui: &mut Ui, _stack: &DialogStack) -> Option<DialogResult<PopoverFields>> {
let Self { feed: Some(feed), tab, panel, filed, at, set, .. } = self else { return None };
fn show(&mut self, ui: &mut Ui, _stack: &DialogStack) -> Option<DialogResult<PopoverAnswer>> {
let Self { feed: Some(feed), tab, panel, filed, at, .. } = self else { return None };
let mut open = true;
let shown = Popover::new("Gradient stop", Bind::bound(&mut open))
.at_point(*at)
.close_on_enter(true)
.show(ui, |ui, _| body(ui, feed, tab, panel, filed));
if shown.inner == Some(true) {
return Some(DialogResult::Cancel);
}
match shown.output.closed {
Some(CloseReason::Enter) => Some(DialogResult::Ok(set.clone())),
Some(CloseReason::Enter) => self.confirm(ui.ctx()).map(DialogResult::Ok),
Some(_) => Some(DialogResult::Cancel),
None => None,
}
@@ -255,14 +338,15 @@ impl StackDialog for GradientStopPopover {
}
/// OK (agents): the fields that were set, which `pump` applies; an untouched popover confirms to no change.
fn confirm(&mut self, _ctx: &egui::Context) -> Option<PopoverFields> {
Some(self.set.clone())
fn confirm(&mut self, _ctx: &egui::Context) -> Option<PopoverAnswer> {
Some(PopoverAnswer { target: self.target.clone(), fields: self.set.clone() })
}
}
/// The popover's body: the tabs and the eyedropper, the Color panel or the swatches, then opacity and location (a
/// point: spread). What the user edits is filed in `filed`.
fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, filed: &mut Filed) {
fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, filed: &mut Filed) -> bool {
let mut outside = false;
Stack::new().show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
let tabs = [
@@ -275,16 +359,23 @@ fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, fi
let tip = tl!("Eyedropper: click the art to sample the stop's colour").to_owned();
filed.eyedropper |= DropperButton::new(tip, Bind::given(false)).show(ui).edit.value() == Some(&true);
}
if *tab == Tab::Color {
outside |= mode_menu(ui, &feed.shown, panel.mode);
}
});
match *tab {
// The Color panel edits the selected stop (or point) of the active gradient.
Tab::Color => {
let before = panel.mode;
filed.panels.push(
ColorPanel::new(Bind::bound(&mut *panel), [feed.current; 2])
.layout(ColorPanelLayout::FillStroke)
.shown(feed.shown.clone())
.show(ui),
);
if panel.mode != before {
filed.mode = Some(panel.mode);
}
}
Tab::Swatches => swatches(ui, feed, filed),
}
@@ -294,6 +385,26 @@ fn body(ui: &mut Ui, feed: &Feed, tab: &mut Tab, panel: &mut ColorPanelState, fi
*amount = percent_field(ui, label.to_owned(), feed.amount).or(*amount);
});
});
outside
}
/// The Color panel's existing five mode commands. Native menu ownership keeps its parent popover
/// open on a pick and gives the child the first Escape, including rows outside the parent bounds.
fn mode_menu(ui: &mut Ui, shown: &ColorPanelShown, fallback: ColorPanelMode) -> bool {
let words = Env::of(ui).words::<ColorPanelWords>();
let label = match shown {
ColorPanelShown::Mode(mode) => mode.label(&words),
ColorPanelShown::Tint(_) => words.tint.clone(),
_ => fallback.label(&words),
};
let button = Button::new(label).popup(PopupKind::Menu).show(ui);
let menu = Menu::new(tl!("Color mode")).opened_by(&button, Trigger::Click).show(ui, |ui, _| {
for mode in ColorPanelMode::FILL_STROKE {
MenuItem::command(mode.command()).show(ui);
}
});
// The child absorbs an outside press before its parent sees it. Close both for that event only.
menu.output.closed == Some(CloseReason::Outside)
}
/// Document swatches as tiles: a pick gives the stop (or point) that colour.
@@ -380,6 +491,9 @@ fn refresh(app: &VectorcraftApp, ctx: &egui::Context, id: DialogId, target: &Tar
dialogs.with(|host| {
if let Some(popover) = host.get_mut_by_id::<GradientStopPopover>(id) {
(popover.at, popover.feed) = (at, Some(feed));
popover.panel = app.ui.color_panel;
// This panel edits the active stop/point, never the other paint behind the proxy.
popover.panel.background = false;
}
});
}
@@ -397,8 +511,11 @@ pub(crate) fn open_at(app: &mut VectorcraftApp, index: usize, anchor: Anchor) {
app.run("gradient.selectStop", json!({ "index": index })).ok();
}
let Some(target) = selected(app) else { return };
let Some(key) = TargetKey::of(app, &target) else { return };
let Ok(edited) = app.session.gradient_edit_paints(!key.fill) else { return };
let paints = Arc::new(TargetPaints { shown: target.paint().clone(), edited });
dialogs.with(|host| {
host.open(GradientStopPopover::new(anchor));
host.open(GradientStopPopover::new(anchor, TargetOwner { key, paints }));
});
refresh(app, &ctx, dialog_id(KIND), &target);
}
@@ -409,9 +526,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let id = dialog_id(KIND);
match dialogs.with(|host| host.take_by_id::<GradientStopPopover>(id)) {
Some(DialogResult::Ok(fields)) => {
Some(DialogResult::Ok(PopoverAnswer { target: owner, fields })) => {
if fields != PopoverFields::default()
&& let Some(target) = selected(app)
&& owner.matches(app, &target)
{
apply(app, &target, &fields);
}
@@ -420,11 +538,10 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
Some(_) => return,
None => {}
}
if !dialogs.with(|host| host.is_open::<GradientStopPopover>()) {
let Some(mut owner) = dialogs.with(|host| host.get_by_id::<GradientStopPopover>(id).map(|popover| popover.target.clone())) else {
return;
}
let Some(target) = selected(app) else {
// The stop or point went away (undo, another object selected): nothing left to edit.
};
let Some(target) = selected(app).filter(|target| owner.matches(app, target)) else {
dialogs.with(|host| host.cancel_by_id(ctx, id));
return;
};
@@ -432,6 +549,13 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
if filed.fields != PopoverFields::default() {
apply(app, &target, &filed.fields);
}
if filed.fields.location.is_some()
&& !owner.key.point
&& let Some(index) = app.session.selected_stop()
{
// The stop can cross its neighbor when its location changes.
owner.key.index = index;
}
if let Some((name, color)) = filed.swatch
&& let Some(target) = selected(app)
{
@@ -441,25 +565,43 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
// PLAN: assumed `panels::color::apply_output(app, &ColorPanelOutput)` (color-w9's decision).
crate::panels::color::apply_output(app, output);
}
if let Some(mode) = filed.mode {
let target = crate::panels::color::target_now(app);
crate::panels::color::set_mode(app, &target, mode);
}
if filed.eyedropper {
dialogs.with(|host| host.cancel_by_id(ctx, id));
crate::panels::gradient::stop_eyedropper(app);
return;
}
if let Some(target) = selected(app) {
refresh(app, ctx, id, &target);
let updated = selected(app).filter(|target| owner.key.matches(app, target)).zip(app.session.gradient_edit_paints(!owner.key.fill).ok());
let Some((target, edited)) = updated else {
dialogs.with(|host| host.cancel_by_id(ctx, id));
return;
};
// The popover can continue with the paints resulting from its own edits in this pass.
if owner.paints.shown != *target.paint() || owner.paints.edited != edited {
owner.paints = Arc::new(TargetPaints { shown: target.paint().clone(), edited });
}
dialogs.with(|host| {
if let Some(popover) = host.get_mut_by_id::<GradientStopPopover>(id) {
popover.target = owner;
}
});
refresh(app, ctx, id, &target);
}
/// Gives the target the swatch `name`'s colour. A global or spot color (or a tint of one) stays linked, and the
/// swatch's color keeps its model.
fn pick_swatch(app: &mut VectorcraftApp, target: &Target, name: &str, color: Color) {
match target {
Target::Stop(stops, i) => {
Target::Stop(paint, i) => {
let link = crate::panels::gradient::dropped_link(app, &json!({ "swatch": name }));
set_stops_keeping_models(app, &recolor(stops.clone(), *i, color, link), Some(*i), Live::Released);
set_stops_keeping_models(app, &recolor(paint.gradient.stops.clone(), *i, color, link), Some(*i), Live::Released);
}
Target::Point(_, _, i) => {
edit_point(app, "paint.freeform.setPoint", json!({ "index": i, "color": color_json(&color), "keepModel": true }));
}
Target::Point(_, i) => edit_point(app, "paint.freeform.setPoint", json!({ "index": i, "color": color_json(&color), "keepModel": true })),
}
}
@@ -467,8 +609,8 @@ fn pick_swatch(app: &mut VectorcraftApp, target: &Target, name: &str, color: Col
fn apply(app: &mut VectorcraftApp, target: &Target, f: &PopoverFields) {
let pct = |v: Option<f64>| v.map(|v| (v / 100.0).clamp(0.0, 1.0));
match target {
Target::Stop(stops, i) => {
let (mut stops, mut i) = (stops.clone(), *i);
Target::Stop(paint, i) => {
let (mut stops, mut i) = (paint.gradient.stops.clone(), *i);
if let Some(c) = f.color {
stops = recolor(stops, i, c, None);
}
@@ -482,7 +624,7 @@ fn apply(app: &mut VectorcraftApp, target: &Target, f: &PopoverFields) {
}
set_stops(app, &stops, Some(i), Live::Released);
}
Target::Point(_, i) => {
Target::Point(_, _, i) => {
let mut p = json!({ "index": i });
if let Some(c) = f.color {
p["color"] = color_json(&c);
@@ -499,6 +641,8 @@ fn apply(app: &mut VectorcraftApp, target: &Target, f: &PopoverFields) {
#[cfg(test)]
mod tests {
use craft::behavior::{EditEvent, GestureId, Mixed};
use craft::color_ui::ui::{PanelTarget, PickedColor};
use vectorcraft_engine::Session;
use super::*;
@@ -565,7 +709,7 @@ mod tests {
fn stops(app: &VectorcraftApp) -> Vec<GradientStop> {
match selected(app) {
Some(Target::Stop(stops, _)) => stops,
Some(Target::Stop(paint, _)) => paint.gradient.stops,
_ => panic!("no stop selected"),
}
}
@@ -591,13 +735,157 @@ mod tests {
assert!(set(&app, "color", json!("red")).is_err());
}
#[test]
fn the_popover_discards_a_pending_edit_after_selecting_other_art() {
let mut app = app();
let first = app.session.doc().unwrap().selection.objects[0];
let gradient = json!({"stops": [{"offset": 0, "color": "#000000"}, {"offset": 0.5, "color": "#0000ff"}, {"offset": 1, "color": "#ffffff"}]});
let second = app.run("shape.rectangle", json!({"x": 230, "y": 80, "width": 50, "height": 90})).unwrap()["id"].clone();
app.run("paint.setFill", json!({"gradient": gradient})).unwrap();
app.run("select.set", json!({"ids": [first.0]})).unwrap();
open_popover(&mut app);
set(&app, "opacity", json!(25)).unwrap();
app.run("select.set", json!({"ids": [second]})).unwrap();
app.run("gradient.selectStop", json!({"index": 1})).unwrap();
let before = app.session.doc().unwrap().doc.clone();
confirm(&mut app);
assert_eq!(app.session.doc().unwrap().doc, before);
assert!(!is_open(&app));
open_popover(&mut app);
set(&app, "opacity", json!(25)).unwrap();
confirm(&mut app);
assert_eq!(stops(&app)[1].opacity, 0.25);
}
#[test]
fn the_popover_does_not_send_live_edits_to_another_stop() {
let mut app = app();
open_popover(&mut app);
let dialogs = app.dialogs().unwrap();
let ctx = ctx(&app);
dialogs.with(|host| {
host.get_mut_by_id::<GradientStopPopover>(dialog_id(KIND)).unwrap().filed.fields.opacity = Some(25.0);
});
app.run("gradient.selectStop", json!({"index": 2})).unwrap();
host::pump(&mut app, &ctx);
assert!(!is_open(&app));
assert_eq!(stops(&app)[2].opacity, 1.0);
}
fn replace_gradient(app: &mut VectorcraftApp) {
let stops = json!([{"offset": 0, "color": "#000000"}, {"offset": 0.5, "color": "#0000ff"}, {"offset": 1, "color": "#ffffff"}]);
app.run("paint.setFill", json!({"gradient": {"stops": stops, "start": [100, 150], "end": [200, 150]}})).unwrap();
assert_eq!(app.session.selected_stop(), Some(1));
}
#[test]
fn the_popover_discards_confirmed_edits_to_a_replacement_gradient() {
let mut app = app();
open_popover(&mut app);
set(&app, "opacity", json!(25)).unwrap();
let ctx = ctx(&app);
app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, dialog_id(KIND)));
replace_gradient(&mut app);
host::pump(&mut app, &ctx);
assert_eq!(stops(&app)[1].opacity, 1.0, "the finished answer belongs to the original gradient");
}
#[test]
fn the_popover_discards_live_edits_to_a_replacement_gradient() {
let mut app = app();
open_popover(&mut app);
app.dialogs().unwrap().with(|host| {
host.get_mut_by_id::<GradientStopPopover>(dialog_id(KIND)).unwrap().filed.fields.opacity = Some(25.0);
});
replace_gradient(&mut app);
let ctx = ctx(&app);
host::pump(&mut app, &ctx);
assert_eq!(stops(&app)[1].opacity, 1.0, "the live edit belongs to the original gradient");
assert!(!is_open(&app));
}
#[test]
fn discards_edits_when_only_a_secondary_selected_gradient_is_replaced() {
let mut app = app();
let first = app.session.active().unwrap().selection.objects[0];
let second = app.run("shape.rectangle", json!({"x": 230, "y": 80, "width": 50, "height": 90})).unwrap()["id"].clone();
let initial = json!({"stops": [{"offset": 0, "color": "#ffffff"}, {"offset": 0.5, "color": "#00ff00"}, {"offset": 1, "color": "#000000"}],
"start": [100, 150], "end": [200, 150]});
app.run("paint.setFill", json!({"id": second, "gradient": initial})).unwrap();
app.run("select.set", json!({"ids": [first.0, second]})).unwrap();
app.run("gradient.selectStop", json!({"index": 1})).unwrap();
assert_eq!(app.session.active().unwrap().selection.objects[0], first);
open_popover(&mut app);
set(&app, "opacity", json!(25)).unwrap();
let proxy = active_paint(&app);
let selected = app.session.active().unwrap().selection.objects.clone();
let gradient = json!({"stops": [{"offset": 0, "color": "#000000"}, {"offset": 0.5, "color": "#0000ff"}, {"offset": 1, "color": "#ffffff"}]});
app.run("paint.setFill", json!({"id": second, "gradient": gradient})).unwrap();
assert_eq!(app.session.active().unwrap().selection.objects, selected);
assert_eq!(app.session.selected_stop(), Some(1));
assert_eq!(active_paint(&app), proxy);
let before = app.session.active().unwrap().doc.clone();
confirm(&mut app);
assert!(app.session.active().unwrap().doc == before, "the edit must not overwrite the secondary replacement");
}
#[test]
fn its_live_color_drag_stays_open_and_commits_once() {
let mut app = app();
open_popover(&mut app);
let undo = app.session.active().unwrap().history.undo.len();
let ctx = ctx(&app);
let dialogs = app.dialogs().unwrap();
let gesture = GestureId::new(1);
let pick = |hex| PickedColor::rgb(Srgba::from_hex(hex).unwrap());
let before = pick("#00ff00");
for (edit, expected) in
[(EditEvent::update(gesture, pick("#ff0000")), "#ff0000"), (EditEvent::commit(gesture, Mixed::Same(before), pick("#0000ff")), "#0000ff")]
{
let mut edit = Some(edit);
ctx.run_ui(Default::default(), |ui| {
let Some(edit) = edit.take() else { return };
let mut state = ColorPanelState::default();
let mut output = ColorPanel::new(Bind::bound(&mut state), [before.color; 2]).show(ui);
output.edits.push((PanelTarget::Foreground, edit));
dialogs.with(|host| {
host.get_mut_by_id::<GradientStopPopover>(dialog_id(KIND)).unwrap().filed.panels.push(output);
});
})
.textures_delta
.clear();
host::pump(&mut app, &ctx);
assert!(is_open(&app));
assert_eq!(stops(&app)[1].color.to_hex(), expected);
}
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
}
#[test]
fn the_popover_keeps_editing_the_stop_after_moving_it() {
let mut app = app();
open_popover(&mut app);
app.dialogs().unwrap().with(|host| {
host.get_mut_by_id::<GradientStopPopover>(dialog_id(KIND)).unwrap().filed.fields.location = Some(100.0);
});
let ctx = ctx(&app);
host::pump(&mut app, &ctx);
assert!(is_open(&app));
assert_eq!(app.session.selected_stop(), Some(2));
set(&app, "opacity", json!(25)).unwrap();
confirm(&mut app);
assert_eq!(stops(&app)[1].opacity, 1.0);
assert_eq!(stops(&app)[2].opacity, 0.25);
}
#[test]
fn on_a_freeform_gradient_it_edits_the_selected_point() {
let mut app = app();
app.run("paint.editGradient", json!({"kind": "freeform"})).unwrap();
app.run("paint.freeform.addPoint", json!({"at": [150, 150], "color": "#0000ff"})).unwrap();
let point = |app: &VectorcraftApp| match selected(app) {
Some(Target::Point(p, i)) => (p, i),
Some(Target::Point(_, p, i)) => (p, i),
_ => panic!("no point selected"),
};
let (p, i) = point(&app);
+188 -24
View File
@@ -25,14 +25,16 @@ use craft::host::{PickRequest, Picked};
use craft::table::ui::{
CellAt, CellDirection, CellEdit, CellGrid, CellSelection, CellSpace, ColumnEdges, GridEdit, GridModel, GridState, LineIndex, Positions,
};
use craft::theme::variant::Tone;
use craft::ui::buttons::Button;
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, PaintUi, Props as _, Show as _, ShowContainer as _};
use craft::ui::contract::{Bind, PaintUi, Politeness, Props as _, Show as _, ShowContainer as _};
use craft::ui::dialog::{
DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id, serde_fields, set_serde_field,
};
use craft::ui::display::Text;
use craft::ui::layout_components::Row;
use craft::ui::notices::{Notice, NoticeLayout};
use craft::ui::patterns::form_dialogs::FormDialog;
use craft::ui::primitives::TextRun;
use craft::ui::runtime::env::{Env, Label, Units};
@@ -48,6 +50,8 @@ use crate::file_asks::{self, Owner};
/// The dialog kind of Graph Data, the key of its dialog on the host.
pub const KIND: &str = "graphData";
const WRONG_DOCUMENT: &str = "Graph Data belongs to the document that opened this sheet.";
const REVERTED_DOCUMENT: &str = "Reopen Graph Data after reverting the drawing.";
/// The sheet's size: a row of labels over a graph's categories, a column of labels before its
/// series; the least rows it shows.
@@ -68,12 +72,11 @@ const ROW_H: f32 = 19.0;
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
// The query fails without a graph selected, with the engine's own message.
let v = app.session.execute("graph.setData", &json!({})).map_err(|e| e.to_string())?;
let graph = app.session.active().and_then(|st| st.selection.objects.iter().find_map(|id| graph_of(&st.doc, *id)).map(|id| (st, id)));
let scatter = graph.is_some_and(|(st, id)| {
st.doc.node(id).and_then(|n| n.extras().graph.as_deref()).is_some_and(|g| g.kind == vectorcraft_doc::GraphKind::Scatter)
});
let id = graph.map(|(_, id)| id.0);
let dialog = GraphDataDialog::new(grid_from_data(&v), id, scatter, can_import(app));
let st = app.session.active().ok_or("no document open")?;
let graph = st.selection.objects.iter().find_map(|id| graph_of(&st.doc, *id));
let scatter = graph
.is_some_and(|id| st.doc.node(id).and_then(|n| n.extras().graph.as_deref()).is_some_and(|g| g.kind == vectorcraft_doc::GraphKind::Scatter));
let dialog = GraphDataDialog::new(grid_from_data(&v), st.uid, st.reverts, graph.map(|id| id.0), scatter, can_import(app));
let dialogs = app.dialogs().ok_or("no window to show the dialog in")?;
dialogs.with(|host| host.open(dialog));
Ok(Value::Null)
@@ -391,9 +394,10 @@ fn graph_grid(app: &mut VectorcraftApp, graph: Option<u64>) -> Result<Grid, Stri
Ok(grid_from_data(&v))
}
/// Whether Import Data can ask for a file here: the host has a picker and the app can read files.
/// Browser picks carry their contents; native picks need a path reader.
fn can_import(app: &VectorcraftApp) -> bool {
file_asks::can(app, craft::host::PickKind::Open) && app.services.read.is_some()
file_asks::can(app, craft::host::PickKind::Open)
&& (app.host.files().browser_saves() || app.services.read_head.is_some() || app.services.read.is_some())
}
/// Import Data's answer: a tab-separated text file's rows into the sheet that asked for it.
@@ -431,6 +435,8 @@ fn import(app: &mut VectorcraftApp, owner: &Arc<()>, picked: Picked) -> Result<V
/// What the window asked of the app since the last [`pump`].
struct Asks {
document: u64,
reverts: u64,
graph: Option<u64>,
import_owner: Arc<()>,
apply: Option<Sheet>,
@@ -442,18 +448,31 @@ struct Asks {
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let can = can_import(app);
let active = app.session.active().map(|doc| (doc.uid, doc.reverts));
let asked = dialogs.with(|host| {
host.get_mut::<GraphDataDialog>().map(|d| {
d.can_import = can;
if active == Some((d.document, d.reverts)) {
d.held.clear_refusal();
}
d.take_asks()
})
});
let Some(Asks { graph, import_owner, apply: filed, actions }) = asked else { return };
let Some(Asks { document, reverts, graph, import_owner, apply: filed, actions }) = asked else { return };
let refusal = match active {
Some((uid, current_reverts)) if uid == document => (current_reverts != reverts).then_some(tl!(REVERTED_DOCUMENT)),
_ => Some(tl!(WRONG_DOCUMENT)),
};
if let Some(sheet) = filed {
if let Err(e) = apply(app, &sheet, graph) {
app.status(e);
}
dialogs.with(|host| host.get_mut::<GraphDataDialog>().map(GraphDataDialog::applied));
let answer = if let Some(reason) = refusal {
Err(Label::from(reason))
} else {
if let Err(e) = apply(app, &sheet, graph) {
app.status(e);
}
Ok(())
};
dialogs.with(|host| host.get_mut::<GraphDataDialog>().map(|dialog| dialog.applied(answer)));
}
for action in actions {
match action {
@@ -473,12 +492,18 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
move |app, picked| import(app, &owner, picked),
);
}
Action::Revert => match graph_grid(app, graph) {
Ok(grid) => {
dialogs.with(|host| host.get_mut::<GraphDataDialog>().map(|d| d.replace(grid)));
Action::Revert => {
if let Some(reason) = refusal {
app.status(reason.to_owned());
} else {
match graph_grid(app, graph) {
Ok(grid) => {
dialogs.with(|host| host.get_mut::<GraphDataDialog>().map(|d| d.replace(grid)));
}
Err(e) => app.status(e),
}
}
Err(e) => app.status(e),
},
}
}
}
}
@@ -657,6 +682,8 @@ pub(crate) struct GraphDataDialog {
sheet: Sheet,
state: GridState,
entry: Entry,
document: u64,
reverts: u64,
/// The graph the sheet opened on.
graph: Option<u64>,
scatter: bool,
@@ -669,7 +696,7 @@ pub(crate) struct GraphDataDialog {
impl GraphDataDialog {
/// The window over `grid`, the data of `graph`; Switch x/y is on for a `scatter` graph.
fn new(grid: Grid, graph: Option<u64>, scatter: bool, can_import: bool) -> Self {
fn new(grid: Grid, document: u64, reverts: u64, graph: Option<u64>, scatter: bool, can_import: bool) -> Self {
let sheet = Sheet { grid, ..Sheet::default() };
let state = GridState::new(CellSelection::cell(CellAt::new(0, 1)), 1.0);
let mut entry = Entry { text: String::new(), at: (0, 1) };
@@ -680,6 +707,8 @@ impl GraphDataDialog {
sheet,
state,
entry,
document,
reverts,
graph,
scatter,
can_import,
@@ -691,12 +720,19 @@ impl GraphDataDialog {
/// Everything the window asked since the last call, once.
fn take_asks(&mut self) -> Asks {
Asks { graph: self.graph, import_owner: self.import_owner.clone(), apply: self.held.take(), actions: std::mem::take(&mut self.actions) }
Asks {
document: self.document,
reverts: self.reverts,
graph: self.graph,
import_owner: self.import_owner.clone(),
apply: self.held.take(),
actions: std::mem::take(&mut self.actions),
}
}
/// The pump sent Apply's sheet to the graph; the window stays open and Apply is ready again.
fn applied(&mut self) {
self.held.answer(Ok(()));
fn applied(&mut self, answer: Result<(), Label>) {
self.held.answer(answer);
self.held.finish();
}
@@ -727,6 +763,7 @@ impl StackDialog for GraphDataDialog {
fn show(&mut self, ui: &mut egui::Ui, _: &DialogStack) -> Option<DialogResult<()>> {
let GraphDataDialog { sheet, state, entry, scatter, can_import, lines, actions, held, .. } = self;
let mut pane = Pane { state, entry, lines, actions, scatter: *scatter, can_import: *can_import };
let refusal = held.refusal().map(|(reason, _)| reason.clone());
let shown = FormDialog::new(tl!("Graph Data"), Bind::bound(&mut *sheet))
.ok_label(tl!("Apply"))
.ok_enabled(!held.is_waiting())
@@ -734,7 +771,12 @@ impl StackDialog for GraphDataDialog {
// The sheet owns the scroll; the controls above it stay in view.
.collection_body(true)
.shaped(|dialog| dialog.initial_focus(Initial::Default))
.show(ui, |ui, _, values| body(ui, values, &mut pane));
.show(ui, |ui, _, values| {
if let Some(reason) = refusal.clone() {
Notice::new(Tone::Bad, reason).layout(NoticeLayout::Inline).announce(Politeness::Assertive).show(ui);
}
body(ui, values, &mut pane)
});
// The 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) && !held.is_waiting() {
commit_text(sheet, pane.entry);
@@ -846,6 +888,107 @@ mod tests {
pump(app, &ctx);
}
fn sheet_with_matching_graphs() -> (VectorcraftApp, u64) {
let (mut app, id) = app_with("1,2\n3,4", "column");
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let other = app.run("graph.create", json!({"type": "column", "x": 0, "y": 0, "width": 200, "height": 150, "csv": "7,8\n9,10"})).unwrap();
assert_eq!(other["id"], id);
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
open(&mut app).unwrap();
set_field(&app, "grid", json!([[""], ["", "5", "6"]])).unwrap();
app.run("document.activate", json!({"index": 1})).unwrap();
(app, id)
}
#[test]
fn graph_data_apply_cannot_change_the_other_drawings_graph() {
let (mut app, id) = sheet_with_matching_graphs();
let other = data(&mut app, id);
let undo = app.session.active().unwrap().history.undo.len();
apply_through_host(&mut app);
assert_eq!(data(&mut app, id), other);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(matches!(read(&app, GraphDataDialog::held_state), Some(HeldOk::Refused(_))));
app.run("document.activate", json!({"index": 0})).unwrap();
apply_through_host(&mut app);
assert_eq!(data(&mut app, id)["rows"], json!([[5.0, 6.0]]));
}
#[test]
fn graph_data_revert_keeps_the_draft_in_the_other_drawing() {
let (mut app, id) = sheet_with_matching_graphs();
let draft = read(&app, |dialog| dialog.sheet.grid.clone());
let revert = |app: &mut VectorcraftApp| {
edit(app, |dialog| dialog.actions.push(Action::Revert));
pump(app, &crate::testing::ui_context());
};
revert(&mut app);
assert_eq!(read(&app, |dialog| dialog.sheet.grid.clone()), draft);
app.run("document.activate", json!({"index": 0})).unwrap();
let expected = grid_from_data(&data(&mut app, id));
revert(&mut app);
assert_eq!(read(&app, |dialog| dialog.sheet.grid.clone()), expected);
}
fn stale_sheet_after_file_revert(test: &str) -> (VectorcraftApp, u64, Value) {
struct SavedFile(std::path::PathBuf);
impl Drop for SavedFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
let (mut app, id) = app_with(",Original\nQ1,1", "column");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-graph-data-revert-{}-{test}.vectorcraft", std::process::id())));
app.run("file.saveAs", json!({"path": path.0})).unwrap();
assert!(path.0.is_file());
let saved = data(&mut app, id);
app.run("graph.setData", json!({"id": id, "series": ["Unsaved"], "categories": ["Q2"], "rows": [[3.0]]})).unwrap();
assert_ne!(data(&mut app, id), saved);
app.run("select.set", json!({"ids": [id]})).unwrap();
open(&mut app).unwrap();
set_field(&app, "grid", json!([["", "Draft"], ["Q2", "9"]])).unwrap();
let state = app.session.active().unwrap();
let (uid, reverts) = (state.uid, state.reverts);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let state = app.session.active().unwrap();
assert_eq!((state.uid, state.reverts), (uid, reverts + 1));
app.run("select.set", json!({"ids": [id]})).unwrap();
assert_eq!(data(&mut app, id), saved, "the restored graph uses the same ID");
(app, id, saved)
}
#[test]
fn graph_data_after_file_revert_cannot_apply_the_old_draft() {
let (mut app, id, saved) = stale_sheet_after_file_revert("apply");
let undo = app.session.active().unwrap().history.undo.len();
apply_through_host(&mut app);
assert_eq!(data(&mut app, id), saved);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(matches!(read(&app, GraphDataDialog::held_state), Some(HeldOk::Refused(_))));
app.run("select.set", json!({"ids": [id]})).unwrap();
open(&mut app).unwrap();
set_field(&app, "grid", json!([["", "Fresh"], ["Q3", "7"]])).unwrap();
apply_through_host(&mut app);
assert_eq!(data(&mut app, id)["rows"], json!([[7.0]]));
}
#[test]
fn graph_data_after_file_revert_keeps_the_old_sheet_on_worksheet_revert() {
let (mut app, id, saved) = stale_sheet_after_file_revert("worksheet");
let draft = read(&app, |dialog| dialog.sheet.grid.clone());
edit(&app, |dialog| dialog.actions.push(Action::Revert));
pump(&mut app, &crate::testing::ui_context());
assert_eq!(read(&app, |dialog| dialog.sheet.grid.clone()), draft);
assert_eq!(data(&mut app, id), saved);
}
/// The app with the window drawn each frame as the shell draws it.
// PLAN: the shell's own frame (hub-w2) replaces `host.run` here, and runs `file_asks::poll` (files-w7) itself.
fn harness(app: VectorcraftApp) -> Harness {
@@ -978,6 +1121,27 @@ mod tests {
assert_eq!(at(&h, 0, 1), "c");
}
#[test]
fn browser_graph_data_import_reads_picked_bytes_without_a_path_reader() {
let (mut app, _) = app_with(",original\nQ1,1", "column");
app.services.read = None;
app.services.read_head = None;
let files = Arc::new(ScriptedFiles::held().in_browser());
app.host.with_files(files.clone()).install(app.ui_ctx.as_ref().unwrap());
app.host = Arc::new(app.host.with_files(files.clone()));
open(&mut app).unwrap();
let mut h = harness(app);
h.run_steps(4);
h.get_by_label("Import Data…").click();
h.run_steps(3);
assert_eq!(files.open(), 1, "the browser can open the Import Data picker");
files.answer(Picked::Contents(vec![("data.txt".into(), b"\timported\nQ2\t8".to_vec())]));
h.run_steps(4);
assert_eq!(read(h.state(), |d| cell_of(&d.sheet.grid, 0, 1)), "imported");
assert_eq!(read(h.state(), |d| cell_of(&d.sheet.grid, 1, 0)), "Q2");
assert_eq!(read(h.state(), |d| cell_of(&d.sheet.grid, 1, 1)), "8");
}
#[test]
fn graph_data_import_keeps_late_answers_out_of_a_reopened_sheet() {
let (mut app, _) = app_with(",first\nQ1,1", "column");
+137 -10
View File
@@ -251,9 +251,15 @@ pub(crate) enum Answer {
impl Answer {
/// Runs the command; the refusal is its error.
fn run(&self, app: &mut VectorcraftApp) -> Result<(), Label> {
fn run(&self, app: &mut VectorcraftApp, target: &GraphTarget) -> Result<(), Label> {
let Some(active) = app.session.active().filter(|active| active.uid == target.document.0) else {
return Err(Label::from(tl!("This graph design belongs to the document that opened the dialog.")));
};
if active.reverts != target.document.1 {
return Err(Label::from(tl!("The document was reverted. Reopen this dialog to continue.")));
}
let design = |d: &Option<DesignKey>| json!({ "design": d.as_ref().map(|d| d.name.as_str()), "library": library_of(d.as_ref()) });
let (command, params) = match self {
let (command, mut params) = match self {
Answer::Column { design: d, options } => {
let mut params = design(d);
params["columnType"] = json!(options.column_type.as_str());
@@ -263,10 +269,35 @@ impl Answer {
}
Answer::Marker { design: d } => ("graph.marker", design(d)),
};
// When selection still describes the opening target, let the command keep its selected series highlighted.
let selected = vectorcraft_engine::graph_type_subject(&app.session).ok();
if !selected.is_some_and(|selected| selected.id.0 == target.graph && selected.series == target.series) {
params["id"] = json!(target.graph);
if !target.series.is_empty() {
params["seriesIndexes"] = json!(target.series);
}
}
app.run(command, params).map(|_| ()).map_err(Label::from)
}
}
/// The graph and picked series the Column or Marker form opened for.
#[derive(Clone)]
struct GraphTarget {
document: (u64, u64),
graph: u64,
series: Vec<usize>,
}
impl GraphTarget {
fn selected(app: &VectorcraftApp) -> Result<Self, String> {
let active = app.session.active().ok_or("no document open")?;
let document = (active.uid, active.reverts);
let selected = vectorcraft_engine::graph_type_subject(&app.session).map_err(|error| error.to_string())?;
Ok(Self { document, graph: selected.id.0, series: selected.series })
}
}
/// A loaded library's document, for the thumbnails of its designs.
struct LibraryDoc {
id: String,
@@ -361,6 +392,7 @@ impl Lists {
pub(crate) struct GraphDesignDialog {
id: DialogId,
kind: Kind,
target: Option<GraphTarget>,
lists: Lists,
/// The selected rows: any number of designs in Graph Design; one design, or None, in Column and Marker.
selection: Selection<RowKey>,
@@ -376,14 +408,16 @@ pub(crate) struct GraphDesignDialog {
/// What [`pump`] takes from the open dialog to run.
struct Work {
actions: Vec<Action>,
answer: Option<Answer>,
answer: Option<(Answer, GraphTarget)>,
document: Option<(u64, u64)>,
}
impl GraphDesignDialog {
fn new(kind: Kind, lists: Lists, chosen: Vec<DesignKey>, column: ColumnOptions) -> Self {
fn new(kind: Kind, lists: Lists, chosen: Vec<DesignKey>, column: ColumnOptions, target: Option<GraphTarget>) -> Self {
let mut dialog = GraphDesignDialog {
id: dialog_id(kind.key()),
kind,
target,
lists,
selection: Selection::new(Vec::new(), None, None),
name: String::new(),
@@ -432,7 +466,9 @@ impl GraphDesignDialog {
}
fn take_work(&mut self) -> Work {
Work { actions: std::mem::take(&mut self.actions), answer: self.held.take() }
let answer = self.held.take().and_then(|answer| self.target.clone().map(|target| (answer, target)));
let document = self.target.as_ref().map(|target| target.document);
Work { actions: std::mem::take(&mut self.actions), answer, document }
}
/// What OK files.
@@ -756,7 +792,7 @@ impl StackDialog for GraphDesignDialog {
pub fn open_design(app: &mut VectorcraftApp) -> Result<Value, String> {
let lists = Lists::read(app)?;
let first = lists.designs.first().map(|n| DesignKey::document(n));
open(app, GraphDesignDialog::new(Kind::Design, lists, first.into_iter().collect(), ColumnOptions::default()))
open(app, GraphDesignDialog::new(Kind::Design, lists, first.into_iter().collect(), ColumnOptions::default(), None))
}
/// Open Column for the selected graph series, on the design and options they draw their columns with (None for plain
@@ -769,14 +805,16 @@ pub fn open_column(app: &mut VectorcraftApp) -> Result<Value, String> {
fractions: v["fractions"].as_str().and_then(Fractions::parse).unwrap_or_default(),
};
let chosen = v["design"].as_str().map(DesignKey::document);
open(app, GraphDesignDialog::new(Kind::Column, Lists::read(app)?, chosen.into_iter().collect(), options))
let target = GraphTarget::selected(app)?;
open(app, GraphDesignDialog::new(Kind::Column, Lists::read(app)?, chosen.into_iter().collect(), options, Some(target)))
}
/// Open Marker for the selected graph series, on the design they draw with (None for the default).
pub fn open_marker(app: &mut VectorcraftApp) -> Result<Value, String> {
let v = app.session.execute("graph.marker", &json!({})).map_err(|e| e.to_string())?;
let chosen = v["design"].as_str().map(DesignKey::document);
open(app, GraphDesignDialog::new(Kind::Marker, Lists::read(app)?, chosen.into_iter().collect(), ColumnOptions::default()))
let target = GraphTarget::selected(app)?;
open(app, GraphDesignDialog::new(Kind::Marker, Lists::read(app)?, chosen.into_iter().collect(), ColumnOptions::default(), Some(target)))
}
fn open(app: &VectorcraftApp, dialog: GraphDesignDialog) -> Result<Value, String> {
@@ -815,8 +853,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
Err(e) => app.status(e),
}
}
let answered = work.answer.map(|answer| answer.run(app));
let lists = Lists::read(app).ok();
let answered = work.answer.map(|(answer, target)| answer.run(app, &target));
let same_document = work.document.is_none_or(|document| app.session.active().is_some_and(|active| (active.uid, active.reverts) == document));
let lists = if same_document { Lists::read(app).ok() } else { None };
dialogs.with(|host| {
if let Some(dialog) = host.get_mut::<GraphDesignDialog>() {
if let Some(lists) = lists {
@@ -881,6 +920,94 @@ mod tests {
assert!(!dialogs.with(|host| host.is_open::<GraphDesignDialog>()));
}
#[test]
fn graph_column_and_marker_keep_their_opening_graph() {
for (graph_kind, command) in [("column", "graph.column"), ("line", "graph.marker")] {
let (mut app, ctx) = app_with_design();
select_graph(&mut app, graph_kind);
let graph = app.session.active().unwrap().selection.objects[0].0;
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let r = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 20, "height": 20})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [r]})).unwrap();
app.run("graph.design", json!({"new": true})).unwrap();
select_graph(&mut app, graph_kind);
assert_eq!(app.session.active().unwrap().selection.objects[0].0, graph);
let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap();
let design = |app: &mut VectorcraftApp, id| app.session.execute(command, &json!({"id": id})).unwrap()["design"].clone();
activate(&mut app, 0);
crate::menus::invoke(&mut app, command, json!({}));
set(&app, &ctx, "selected", json!("New Design")).unwrap();
activate(&mut app, 1);
let undo = app.session.active().unwrap().history.undo.len();
app.dialogs().unwrap().with(|host| host.confirm::<GraphDesignDialog>(&ctx));
super::pump(&mut app, &ctx);
assert_eq!(design(&mut app, graph), Value::Null);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(fields(&app)["selected"], "New Design");
activate(&mut app, 0);
select_graph(&mut app, graph_kind);
let selected = app.session.active().unwrap().selection.objects[0].0;
assert_ne!(selected, graph);
ok(&mut app, &ctx);
assert_eq!(design(&mut app, graph), "New Design");
assert_eq!(design(&mut app, selected), Value::Null);
}
}
fn a_graph_design_draft_after_file_revert(graph_kind: &str, command: &str) {
struct SavedFile(std::path::PathBuf);
impl Drop for SavedFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
let (mut app, ctx) = app_with_design();
select_graph(&mut app, graph_kind);
let graph = app.session.active().unwrap().selection.objects[0].0;
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-graph-design-revert-{}-{graph_kind}.vectorcraft", std::process::id())));
app.run("file.saveAs", json!({"path": path.0})).unwrap();
assert!(path.0.is_file());
app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 20, "height": 20})).unwrap();
app.run("select.set", json!({"ids": [graph]})).unwrap();
crate::menus::invoke(&mut app, command, json!({}));
set(&app, &ctx, "selected", json!("New Design")).unwrap();
let state = app.session.active().unwrap();
let (uid, reverts) = (state.uid, state.reverts);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let state = app.session.active().unwrap();
assert_eq!((state.uid, state.reverts), (uid, reverts + 1));
app.run("select.set", json!({"ids": [graph]})).unwrap();
let selected_design = |app: &mut VectorcraftApp| app.session.execute(command, &json!({"id": graph})).unwrap()["design"].clone();
assert_eq!(selected_design(&mut app), Value::Null);
let undo = app.session.active().unwrap().history.undo.len();
app.dialogs().unwrap().with(|host| host.confirm::<GraphDesignDialog>(&ctx));
super::pump(&mut app, &ctx);
assert_eq!(selected_design(&mut app), Value::Null, "the stale draft must leave the restored graph's design alone");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(fields(&app)["selected"], "New Design", "the refused answer still shows the draft");
crate::menus::invoke(&mut app, command, json!({}));
set(&app, &ctx, "selected", json!("New Design")).unwrap();
ok(&mut app, &ctx);
assert_eq!(selected_design(&mut app), "New Design", "a fresh draft applies to the restored graph");
}
#[test]
fn graph_column_draft_after_file_revert_leaves_the_restored_columns_alone() {
a_graph_design_draft_after_file_revert("column", "graph.column");
}
#[test]
fn graph_marker_draft_after_file_revert_leaves_the_restored_markers_alone() {
a_graph_design_draft_after_file_revert("line", "graph.marker");
}
#[test]
fn graph_design_footer_ok_applies_column_and_marker_designs_unless_dismissed() {
for (graph_type, command, dismiss) in [("column", "graph.column", false), ("line", "graph.marker", false), ("column", "graph.column", true)] {
+35 -2
View File
@@ -197,6 +197,7 @@ impl GraphTypeValues {
#[derive(Clone)]
struct GraphSubject {
doc: u64,
reverts: u64,
graph_id: u64,
series: Vec<usize>,
graph: GraphKind,
@@ -385,6 +386,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
fields.insert(PAGE.into(), json!("options"));
let mut s = GraphSubject {
doc: st.uid,
reverts: st.reverts,
graph_id: subject.id.0,
series: subject.series,
graph: spec.kind,
@@ -433,8 +435,11 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &Context) {
/// have ids of their own) or with nothing changed, else `graph.setType` with these parameters.
/// `Err` while the dialog can't be applied.
fn verdict(app: &VectorcraftApp, v: &GraphTypeValues, s: &GraphSubject) -> Result<Option<Value>, &'static str> {
if !on_its_document(app, s) {
let Some(st) = app.session.active().filter(|st| st.uid == s.doc) else {
return Ok(None);
};
if st.reverts != s.reverts {
return Err(tl!("The document was reverted. Reopen this dialog to continue."));
}
if let Some(why) = problem(v, s) {
return Err(why);
@@ -569,7 +574,7 @@ fn pending(v: &GraphTypeValues, s: &GraphSubject) -> Value {
/// Whether the active document is the one the dialog opened on.
fn on_its_document(app: &VectorcraftApp, s: &GraphSubject) -> bool {
app.session.active().is_some_and(|st| st.uid == s.doc)
app.session.active().is_some_and(|st| (st.uid, st.reverts) == (s.doc, s.reverts))
}
/// What the calculated tick values were calculated for: the options they depend on and the
@@ -1591,4 +1596,32 @@ mod tests {
assert_eq!(steps(&app), before);
assert_eq!(app.session.execute(COMMAND, &json!({"id": second.0})).unwrap()["type"], "column");
}
#[test]
fn graph_type_refuses_to_change_the_restored_graph() {
let mut app = app_with_graph("column");
let graph = app.session.active().unwrap().selection.objects[0];
let dir = vectorcraft_testkit::TempDir::new("graph-type-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
app.run(COMMAND, json!({"id": graph.0, "type": "bar"})).unwrap();
open(&mut app).unwrap();
set(&app, "type", json!("line")).unwrap();
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [graph.0]})).unwrap();
let before = steps(&app);
crate::tests::picks::answer_dialog(&mut app, dialog_id(KIND), &[], true);
assert!(matches!(with(&app, |dialog| dialog.held_state()), Some(HeldOk::Refused(_))));
assert_eq!(query(&mut app)["type"], "column");
assert_eq!(steps(&app), before);
let ctx = ctx(&app);
app.dialogs().unwrap().with(|host| host.cancel_by_id(&ctx, dialog_id(KIND)));
open(&mut app).unwrap();
set(&app, "type", json!("line")).unwrap();
assert!(ok(&mut app));
assert_eq!(query(&mut app)["type"], "line");
}
}
@@ -7,7 +7,8 @@
//! OK, not by a field, so a name another style has refuses the OK and keeps the dialog open.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::host;
@@ -15,8 +16,10 @@ use crate::VectorcraftApp;
/// The dialog kind of Graphic Style Options.
pub const KIND: &str = "graphicStyleOptions";
const OPENING: &str = "__opening";
/// What OK does with the name.
#[derive(Deserialize, Serialize)]
enum Target {
/// Name the style made from the selection.
New,
@@ -40,13 +43,28 @@ impl Target {
/// Open the dialog with `name` in its field; OK runs `target`.
fn open_with(app: &mut VectorcraftApp, name: String, target: Target) -> Result<Value, String> {
let active = app.session.active().ok_or("no document open")?;
let mut fields = DialogFields::from_pairs([("name", name.clone())]);
fields.set(OPENING, FieldValue::Json(json!({"uid": active.uid, "reverts": active.reverts, "target": target})));
let params = vec![Param::new("name", tl!("Style Name:").to_string(), ParamKind::text(name.clone()))];
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let dialog = HostedParamDialog::command(&ctx, KIND, DialogFields::from_pairs([("name", name)]), move |fields| {
let dialog = HostedParamDialog::command(&ctx, KIND, fields, move |fields| {
ParamDialog::command(KIND, tl!("Graphic Style Options").to_string(), params.clone()).values(Bind::bound(fields))
});
// An `Err` (a name another style has) keeps the dialog open with the reason.
let ok = move |app: &mut VectorcraftApp, result: &ParamResult| target.run(app, result.fields.text("name").unwrap_or_default()).map(|_| ());
let ok = |app: &mut VectorcraftApp, result: &ParamResult| {
let Some(FieldValue::Json(opening)) = result.fields.get(OPENING) else { return Err("the graphic style target is missing".into()) };
let document = opening["uid"].as_u64().ok_or("the graphic style target is missing")?;
let target = Target::deserialize(&opening["target"]).map_err(|e| e.to_string())?;
let active = app.session.active();
if active.is_some_and(|active| active.uid == document && Some(active.reverts) != opening["reverts"].as_u64()) {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
if !active.is_some_and(|active| active.uid == document) {
return Err(tl!("This graphic style belongs to the document that opened the dialog.").to_owned());
}
target.run(app, result.fields.text("name").unwrap_or_default()).map(|_| ())
};
host::open_held(app, dialog, ok).ok_or("no window")?;
Ok(Value::Null)
}
@@ -132,4 +150,71 @@ mod tests {
assert_eq!(names(&app).last().unwrap(), "Halo");
assert!(app.run("ui.graphicStyleOptions", json!({"name": "nope"})).is_err());
}
#[test]
fn renaming_a_style_does_not_change_a_matching_name_in_another_drawing() {
let mut app = app();
app.run("graphicStyle.new", json!({"name": "Twin"})).unwrap();
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap();
app.run("graphicStyle.new", json!({"name": "Twin"})).unwrap();
let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap();
let other = names(&app);
let undo = app.session.active().unwrap().history.undo.len();
activate(&mut app, 0);
open(&mut app, Some("Twin")).unwrap();
let id = options(&app);
set(&app, id, "name", json!("Source style"));
activate(&mut app, 1);
accept(&mut app, id);
assert_eq!(names(&app), other);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert_eq!(options(&app), id);
activate(&mut app, 0);
accept(&mut app, id);
assert!(names(&app).iter().any(|name| name == "Source style"));
}
#[test]
fn graphic_style_options_leave_restored_definitions_alone() {
for action in ["rename", "merge", "new"] {
let mut app = app();
let art = app.session.active().unwrap().selection.objects[0];
app.run("graphicStyle.new", json!({"name": "First"})).unwrap();
app.run("paint.setFill", json!({"ids": [art.0], "color": "#abcdef"})).unwrap();
app.run("graphicStyle.new", json!({"name": "Second"})).unwrap();
let saved = names(&app);
let dir = vectorcraft_testkit::TempDir::new("graphic-style-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
app.run("object.move", json!({"ids": [art.0], "dx": 10, "dy": 0})).unwrap();
let open_action = |app: &mut VectorcraftApp| match action {
"rename" => open(app, Some("First")),
"merge" => open_merge(app, vec!["First".into(), "Second".into()]),
_ => open(app, None),
};
open_action(&mut app).unwrap();
let id = options(&app);
set(&app, id, "name", json!("Draft Style"));
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [art.0]})).unwrap();
let steps = app.session.active().unwrap().history.undo.len();
accept(&mut app, id);
assert_eq!(names(&app), saved, "{action}");
assert_eq!(app.session.active().unwrap().history.undo.len(), steps);
assert_eq!(options(&app), id);
let ctx = app.ui_ctx.clone().unwrap();
app.dialogs().unwrap().with(|h| h.cancel_by_id(&ctx, id));
open_action(&mut app).unwrap();
let id = options(&app);
set(&app, id, "name", json!("Current Style"));
accept(&mut app, id);
assert!(names(&app).iter().any(|name| name == "Current Style"), "{action}");
}
}
}
+33 -4
View File
@@ -25,6 +25,8 @@ pub(crate) const CMD: &str = "object.vectorHalftone";
pub(crate) struct Open {
/// The dialog's id on the host.
pub id: DialogId,
/// The drawing whose art the dialog previews and changes.
document: u64,
/// The temporary dots the dialog shows while it previews.
pub preview: LivePreview,
}
@@ -70,6 +72,7 @@ pub(crate) fn screen_params(live: bool, fields: &DialogFields) -> Vec<Param> {
/// Opens Object › Vector Halftone, previewing from its first frame.
pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let document = app.session.active().ok_or("no document")?.uid;
let defaults = fields();
let rows = screen_params(false, &DialogFields::new());
let initial = fields_of(&rows, defaults.as_object().unwrap_or(&Default::default()));
@@ -78,6 +81,10 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
ParamDialog::command(CMD, tl!("Vector Halftone"), rows).previews(true).values(Bind::bound(fields))
});
let ok = |app: &mut VectorcraftApp, result: &ParamResult| {
let open = app.effect_dialogs.halftone.as_ref().ok_or("the dialog is closed")?;
if !open.in_source(app) {
return Err(tl!("Return to the original drawing to apply Vector Halftone").into());
}
let params = Value::Object(json_of(&screen_params(false, &result.fields), &result.fields));
let mut open = app.effect_dialogs.halftone.take().ok_or("the dialog is closed")?;
let done = std::mem::take(&mut open.preview).commit(app, CMD, params);
@@ -87,18 +94,29 @@ pub(crate) fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
done.map(|_| ())
};
let cancel: Box<dyn FnOnce(&mut VectorcraftApp)> = Box::new(|app| {
if let Some(open) = app.effect_dialogs.halftone.take() {
if let Some(open) = app.effect_dialogs.halftone.take()
&& open.in_source(app)
&& owns_preview(app)
{
open.preview.cancel(app);
}
});
let id = open_held_with(app, dialog, ok, HeldOptions { cancel: Some(cancel), ..Default::default() }).ok_or("no window")?;
app.effect_dialogs.halftone = Some(Open { id, preview: LivePreview::default() });
app.effect_dialogs.halftone = Some(Open { id, document, preview: LivePreview::default() });
Ok(Value::Null)
}
/// Runs or ends the open dialog's preview for this frame.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(mut open) = app.effect_dialogs.halftone.take() else { return };
if !open.in_source(app) {
open.preview = LivePreview::default();
app.effect_dialogs.halftone = Some(open);
return;
}
if !owns_preview(app) {
open.preview = LivePreview::default();
}
let shown = app.dialogs().and_then(|host| {
host.with(|h| {
h.get_by_id::<HostedParamDialog>(open.id).map(|d| {
@@ -117,6 +135,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
/// Whether the open Object → Vector Halftone dialog is showing its temporary dot group.
pub(crate) fn previewing(app: &VectorcraftApp) -> bool {
let Some(open) = app.effect_dialogs.halftone.as_ref() else { return false };
app.dialogs().is_some_and(|host| host.with(|h| h.get_by_id::<HostedParamDialog>(open.id).is_some_and(HostedParamDialog::is_previewing)))
&& app.session.active().and_then(|st| st.interaction.as_ref()?.preview.as_ref()).is_some_and(|(cmd, _)| cmd == CMD)
open.in_source(app)
&& owns_preview(app)
&& app.dialogs().is_some_and(|host| host.with(|h| h.get_by_id::<HostedParamDialog>(open.id).is_some_and(HostedParamDialog::is_previewing)))
}
impl Open {
fn in_source(&self, app: &VectorcraftApp) -> bool {
app.session.active().is_some_and(|doc| doc.uid == self.document)
}
}
fn owns_preview(app: &VectorcraftApp) -> bool {
app.session.active().and_then(|st| st.interaction.as_ref()?.preview.as_ref()).is_some_and(|(cmd, _)| cmd == CMD)
}
+149 -8
View File
@@ -44,6 +44,7 @@ pub(crate) type Cancel = Box<dyn FnOnce(&mut VectorcraftApp)>;
type Drain = Box<dyn FnMut(&mut VectorcraftApp) -> Option<bool>>;
struct Record {
id: DialogId,
drain: Drain,
cancel: Option<Cancel>,
}
@@ -52,20 +53,39 @@ struct Record {
#[derive(Default)]
pub(crate) struct Held(Vec<Record>);
fn drain<D: HoldsOk>(id: DialogId, mut ok: impl FnMut(&mut VectorcraftApp, &D::Answer) -> Result<(), String> + 'static) -> Drain {
impl Held {
fn reopened(&self, id: DialogId) -> bool {
self.0.iter().any(|record| record.id == id)
}
}
fn drain<D: HoldsOk>(id: DialogId, serial: u64, mut ok: impl FnMut(&mut VectorcraftApp, &D::Answer) -> Result<(), String> + 'static) -> Drain {
Box::new(move |app| {
// Without a window nothing can answer: the dialog counts as cancelled so its rollback runs.
let Some(host) = app.dialogs() else { return Some(true) };
match host.with(|h| h.open_serial(id)) {
None => return host.with(|h| h.take_by_id::<D>(id)).map(|r| matches!(r, DialogResult::Cancel)),
Some(open) if open != serial => return Some(false),
Some(_) => {}
}
if let Some(answer) = host.with(|h| h.get_mut_by_id::<D>(id).and_then(D::take_ok)) {
// The host's lock is released while `ok` runs: it may open dialogs.
let verdict = ok(app, &answer).map_err(Into::into);
// A callback can reopen the same key. Its old verdict cannot answer that opening.
if app.held.reopened(id) {
return Some(false);
}
host.with(|h| {
if let Some(d) = h.get_mut_by_id::<D>(id) {
if h.open_serial(id) == Some(serial)
&& let Some(d) = h.get_mut_by_id::<D>(id)
{
d.answer_ok(verdict);
}
});
}
host.with(|h| h.take_by_id::<D>(id)).map(|r| matches!(r, DialogResult::Cancel))
// A replace-by-open can leave the retired opening's Cancel under the same dialog ID.
// A live opening has no final result for this record yet.
None
})
}
@@ -88,11 +108,16 @@ pub(crate) fn open_held_with<D: HoldsOk>(
) -> Option<DialogId> {
let host = app.dialogs()?;
let dialog = dialog.held_ok();
let id = host.with(|h| match options.parent {
Some(parent) => h.open_child(dialog, parent),
None => h.open(dialog),
});
app.held.0.push(Record { drain: drain::<D>(id, ok), cancel: options.cancel });
let (id, serial) = host.with(|h| {
let id = match options.parent {
Some(parent) => h.open_child(dialog, parent),
None => h.open(dialog),
};
h.open_serial(id).map(|serial| (id, serial))
})?;
// A host key can be reopened before the previous result has been pumped.
app.held.0.retain(|record| record.id != id);
app.held.0.push(Record { id, drain: drain::<D>(id, serial, ok), cancel: options.cancel });
Some(id)
}
@@ -226,6 +251,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
// A drain's `ok` may open held dialogs: those join the records that stay.
let mut kept = Vec::new();
for mut record in std::mem::take(&mut app.held.0) {
if app.held.reopened(record.id) {
continue;
}
match (record.drain)(app) {
None => kept.push(record),
Some(true) => {
@@ -236,6 +264,119 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
Some(false) => {}
}
}
kept.retain(|record| !app.held.reopened(record.id));
kept.append(&mut app.held.0);
app.held.0 = kept;
}
#[cfg(test)]
mod opening_tests {
use std::cell::RefCell;
use std::rc::Rc;
use craft::ui::dialog::HeldOk;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, ParamDialog};
use vectorcraft_engine::Session;
use super::*;
const KEY: &str = "testHeldOpening";
fn app() -> (VectorcraftApp, egui::Context) {
let app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
let ctx = app.ui_ctx.clone().unwrap();
(app, ctx)
}
fn dialog(ctx: &egui::Context) -> HostedParamDialog {
HostedParamDialog::new(ctx, KEY, DialogFields::new(), |_| ParamDialog::new(KEY, "Test dialog", vec![]))
}
#[test]
fn held_ok_uses_the_replacement_openings_callback() {
let (mut app, ctx) = app();
let host = app.dialogs().unwrap();
let retired = Rc::new(RefCell::new(Vec::new()));
let before = retired.clone();
let first = open_held(&mut app, dialog(&ctx), move |_, _| {
before.borrow_mut().push("old");
Ok(())
})
.unwrap();
assert!(host.with(|h| h.cancel_by_id(&ctx, first)));
let answers = retired.clone();
let fresh = open_held(&mut app, dialog(&ctx), move |_, _| {
answers.borrow_mut().push("new");
Ok(())
})
.unwrap();
assert_eq!(first, fresh);
assert!(!host.with(|h| h.confirm_by_id(&ctx, fresh)));
assert_eq!(host.with(|h| h.held_state(fresh)), Some(HeldOk::Waiting));
pump(&mut app, &ctx);
assert_eq!(*retired.borrow(), ["new"]);
assert_eq!(host.with(|h| h.held_state(fresh)), Some(HeldOk::Accepted));
}
#[test]
fn pumping_a_replacement_before_ok_keeps_its_callback() {
let (mut app, ctx) = app();
let host = app.dialogs().unwrap();
open_held(&mut app, dialog(&ctx), |_, _| panic!("the retired opening cannot answer")).unwrap();
let accepted = Rc::new(RefCell::new(Vec::new()));
let seen = accepted.clone();
let fresh = open_held(&mut app, dialog(&ctx), move |_, _| {
seen.borrow_mut().push("new");
Ok(())
})
.unwrap();
pump(&mut app, &ctx);
assert!(!host.with(|h| h.confirm_by_id(&ctx, fresh)));
pump(&mut app, &ctx);
assert_eq!(*accepted.borrow(), ["new"]);
assert_eq!(host.with(|h| h.held_state(fresh)), Some(HeldOk::Accepted));
}
#[test]
fn cancelling_a_replacement_runs_only_its_cancel_callback() {
let (mut app, ctx) = app();
let host = app.dialogs().unwrap();
let cancelled = Rc::new(RefCell::new(Vec::new()));
for flag in ["old", "new"] {
let log = cancelled.clone();
open_held_with(
&mut app,
dialog(&ctx),
|_, _| Ok(()),
HeldOptions { parent: None, cancel: Some(Box::new(move |_| log.borrow_mut().push(flag))) },
)
.unwrap();
}
assert!(host.with(|h| h.cancel_by_id(&ctx, craft::ui::dialog::dialog_id(KEY))));
pump(&mut app, &ctx);
assert_eq!(*cancelled.borrow(), ["new"]);
}
#[test]
fn an_old_verdict_does_not_answer_a_replacement_opened_by_its_callback() {
let (mut app, ctx) = app();
let host = app.dialogs().unwrap();
let replacement_ctx = ctx.clone();
let id = open_held(&mut app, dialog(&ctx), move |app, _| {
let id = open_held(app, dialog(&replacement_ctx), |_, _| Ok(())).unwrap();
let host = app.dialogs().unwrap();
assert!(!host.with(|h| h.confirm_by_id(&replacement_ctx, id)));
assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Waiting));
Err("old verdict".into())
})
.unwrap();
assert!(!host.with(|h| h.confirm_by_id(&ctx, id)));
pump(&mut app, &ctx);
assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Waiting));
pump(&mut app, &ctx);
assert_eq!(host.with(|h| h.held_state(id)), Some(HeldOk::Accepted));
}
}
+247 -4
View File
@@ -9,6 +9,7 @@
//! (letters, 1..15), `hyphenLimit` (hyphens, 0..25, 0: no limit), `hyphenationZone` (pt) and
//! `hyphenateCapitalized`, as `text.setFormat` takes them.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind};
// PLAN: assumed paths of `UnitKind` and `LengthUnits`
use craft::ui::runtime::env::{LengthUnits, UnitKind};
@@ -43,7 +44,30 @@ fn rows(lengths: LengthUnits) -> Vec<Param> {
/// Open Hyphenation on the paragraph attributes the Paragraph panel shows.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
crate::panels::character::text_style(app).ok_or("select some type first")?;
use crate::panels::character;
let editing = character::text_editing_kept(app)?;
character::text_style(app).ok_or("select some type first")?;
let source = app.session.active().ok_or("no document open")?;
let document = source.uid;
let mut target = Map::new();
let mut story_focus = None;
let ids = if let Some((id, start, end)) = editing {
if let Some(story) = character::text_story(app) {
story_focus = Some(id);
story
} else {
target.insert("start".into(), json!(start));
target.insert("end".into(), json!(end));
vec![id]
}
} else {
character::selected_stories(app)
};
if ids.is_empty() || source.selection.symbol_part.is_some() {
return Err("select some type first".into());
}
target.insert("ids".into(), json!(ids.iter().map(|id| id.0).collect::<Vec<_>>()));
let mut fields = DialogFields::new();
set_shared(&mut fields, FLAGS[0], crate::panels::paragraph::shared_hyphenate(app));
set_shared(&mut fields, FLAGS[1], crate::panels::paragraph::shared_hyphenation_field(app, |h| h.capitalized));
@@ -55,13 +79,24 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let initial = fields.clone();
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let lengths = crate::canvas::rulers::general_lengths(app);
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |_| ParamDialog::new(KIND, tl!("Hyphenation"), rows(lengths)));
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| {
ParamDialog::new(KIND, tl!("Hyphenation"), rows(lengths)).values(Bind::bound(fields))
});
super::host::open_held(app, dialog, move |app, result| {
let p = params(&result.fields, &initial);
let mut p = params(&result.fields, &initial);
if p.is_empty() {
return Ok(());
}
crate::panels::paragraph::run_on_paragraphs(app, "text.setFormat", Value::Object(p)).map(|_| ())
if app.session.active().is_none_or(|st| st.uid != document) {
return Err(tl!("This dialog was opened in a different document.").to_owned());
}
character::text_editing_kept(app)?;
p.extend(target.clone());
if let Some(id) = story_focus {
let story = app.session.active().ok_or("no document open")?.doc.story_of(id);
p.insert("ids".into(), json!(story.iter().map(|id| id.0).collect::<Vec<_>>()));
}
app.run("text.setFormat", Value::Object(p)).map(|_| ())
})
.ok_or("no window")?;
Ok(Value::Null)
@@ -108,6 +143,147 @@ mod tests {
}
}
/// Actual focused Hyphenation edits keep the hosted draft and apply to both selected paragraphs.
#[test]
fn hyphenation_keeps_focused_edits_until_cancel_or_ok() {
use craft::automation::{ControlRequest, Reply};
use egui::accesskit::{Node, Role, TreeUpdate};
use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
fn control(tree: &TreeUpdate, source: &str, role: Role, scope: Option<Rect>) -> Rect {
fn plain(s: &str) -> &str {
s.trim_end().trim_end_matches([':', ':']).trim_end()
}
fn bounds(node: &Node) -> Option<Rect> {
let b = node.bounds()?;
Some(Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)))
}
let expected = crate::i18n::t(source);
tree.nodes
.iter()
.map(|(_, n)| n)
.filter(|n| n.role() == role && n.label().is_some_and(|label| plain(label) == plain(expected)))
.filter_map(bounds)
.find(|rect| scope.is_none_or(|scope| scope.contains(rect.center())))
.unwrap_or_else(|| panic!("missing {role:?} {expected:?} in {scope:?}"))
}
fn draft(app: &VectorcraftApp, ctx: &egui::Context) -> Value {
let ui = crate::control::inspect(app, ctx);
ui["dialogs"].as_array().unwrap().iter().find(|dialog| dialog["key"] == KIND).expect("open Hyphenation dialog")["fields"].clone()
}
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
let mut failures = Vec::new();
for lang in ["en", "de", "fr", "ja"] {
for answer in ["Cancel", "OK", "ui.dialog.confirm"] {
let (mut app, id) = app();
app.session.prefs.interface_language = lang.into();
app.run("text.setFormat", json!({"ids": [id], "afterFirst": 2, "start": 5, "end": 5})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp, events: Vec<Event>| {
time += 0.1;
let raw = RawInput { events, time: Some(time), screen_rect: Some(screen), focused: true, ..Default::default() };
crate::testing::app_frame(app, &ctx, raw).platform_output.accesskit_update.unwrap()
};
let settle = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec<Event>) -> TreeUpdate| {
for _ in 0..5 {
frame(app, vec![]);
}
frame(app, vec![])
};
let click = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec<Event>) -> TreeUpdate, pos| {
frame(app, vec![Event::PointerMoved(pos)]);
for pressed in [true, false] {
frame(app, vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
frame(app, vec![]);
};
let press = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec<Event>) -> TreeUpdate, key, modifiers| {
for pressed in [true, false] {
frame(
app,
vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }],
);
}
};
let original = paras(&app, id);
let undo = app.session.active().unwrap().history.undo.len();
settle(&mut app, &mut frame);
let apply = answer != "Cancel";
app.run("ui.hyphenation", json!({})).unwrap();
let tree = settle(&mut app, &mut frame);
let modal = control(&tree, "Hyphenation", Role::Dialog, None);
let count = control(&tree, "Words Longer Than:", Role::SpinButton, Some(modal));
let enabled = control(&tree, "Hyphenation", Role::CheckBox, Some(modal));
let footer = control(&tree, if apply { "OK" } else { "Cancel" }, Role::Button, Some(modal));
assert!(screen.expand(0.5).contains_rect(modal));
for bounds in [count, enabled, footer] {
assert!(bounds.is_positive() && modal.expand(0.5).contains_rect(bounds), "{lang}: {bounds:?} outside {modal:?}");
}
let before = driver::fields(&app);
assert_eq!(before.number("wordsLongerThan"), Some(5.0));
assert_eq!(before.bool("hyphenate"), Some(false));
assert!(before.is_mixed("afterFirst"));
click(&mut app, &mut frame, count.center());
press(&mut app, &mut frame, Key::A, Modifiers::COMMAND);
frame(&mut app, vec![Event::ModifiersChanged(Modifiers::NONE), Event::Text("8".into())]);
press(&mut app, &mut frame, Key::Tab, Modifiers::NONE);
settle(&mut app, &mut frame);
let typed = draft(&app, &ctx)["wordsLongerThan"].as_f64();
click(&mut app, &mut frame, enabled.center());
let inspected = draft(&app, &ctx);
let kept = (inspected["wordsLongerThan"].as_f64(), inspected["hyphenate"].as_bool());
eprintln!("{lang}, {answer}: {modal:?}; ui.inspect after typing {typed:?}, after checkbox {kept:?}");
if typed != Some(8.0) || kept != (Some(8.0), Some(true)) || !driver::fields(&app).is_mixed("afterFirst") {
failures.push(format!("{lang} {answer}: {typed:?}, {kept:?}"));
}
assert_eq!(paras(&app, id), original, "{lang}: only the draft changes while open");
if answer == "ui.dialog.confirm" {
let (request, _) = ControlRequest::new(answer, json!({}));
match crate::control::handle(&mut app, &ctx, &request) {
Reply::Done(reply) => assert_eq!(reply["ok"], true, "{reply}"),
_ => panic!("confirmation should reply immediately"),
}
} else {
click(&mut app, &mut frame, footer.center());
}
settle(&mut app, &mut frame);
assert!(!driver::is_open(&app), "{lang}: footer closed the dialog");
let actual = paras(&app, id);
let undo_delta = app.session.active().unwrap().history.undo.len() - undo;
eprintln!(
"{lang}, {answer}: committed counts {}/{}, hyphenation {}/{}, after first {}/{}, undo {undo_delta}",
actual.0.hyphenation.words_longer_than,
actual.1.hyphenation.words_longer_than,
actual.0.hyphenate,
actual.1.hyphenate,
actual.0.hyphenation.after_first,
actual.1.hyphenation.after_first
);
if apply {
let mut expected = original.clone();
for p in [&mut expected.0, &mut expected.1] {
p.hyphenation.words_longer_than = 8;
p.hyphenate = true;
}
if actual != expected || undo_delta != 1 {
failures.push(format!(
"{lang} {answer}: left {:?} and {:?}, undo delta {undo_delta}",
actual.0.hyphenation, actual.1.hyphenation
));
}
} else {
assert_eq!(actual, original, "{lang}: Cancel discards both edits");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
}
}
crate::i18n::set_current(crate::i18n::Lang::EN);
}
assert!(failures.is_empty(), "Hyphenation lost physical edits: {failures:?}");
}
/// `ui.hyphenation` opens the dialog on the selected type; OK sets the paragraphs' hyphenation
/// options in one undo step.
#[test]
@@ -156,4 +332,71 @@ mod tests {
assert!(app.run("ui.hyphenation", json!({})).is_err());
assert!(!driver::is_open(&app));
}
#[test]
fn hyphenation_confirm_keeps_the_opening_selection() {
let (mut app, first) = app();
let second = app.run("text.create", json!({"x": 10, "y": 150, "text": "Other text"})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [first]})).unwrap();
app.run("ui.hyphenation", json!({})).unwrap();
driver::set(&mut app, "hyphenate", json!(true));
app.run("select.set", json!({"ids": [second]})).unwrap();
driver::ok(&mut app);
assert_eq!((paras(&app, first).0.hyphenate, paras(&app, second).0.hyphenate), (true, false));
}
#[test]
fn hyphenation_confirm_keeps_the_opening_caret_paragraph() {
let (mut app, id) = app();
app.session.select_tool("type", Default::default()).unwrap();
let caret = |at| json!({"editing": id, "anchor": at, "caret": at});
app.session.set_tool_option("textSelection", &caret(0));
app.run("ui.hyphenation", json!({})).unwrap();
driver::set(&mut app, "hyphenate", json!(true));
app.session.set_tool_option("textSelection", &caret(5));
driver::ok(&mut app);
let (first, second) = paras(&app, id);
assert_eq!((first.hyphenate, second.hyphenate), (true, false));
}
#[test]
fn hyphenation_confirms_the_caret_paragraph_after_buffered_typing() {
let (mut app, id) = app();
app.run("prefs.set", json!({"key": "realTimeDrawing", "value": false})).unwrap();
let view = Default::default();
app.session.select_tool("type", view).unwrap();
app.session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 7, "caret": 7}));
app.session.tool_text("\nThree", view).unwrap();
let text = &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind;
assert!(matches!(text, NodeKind::Text(t) if t.plain_text() == "One\nTwo"));
app.run("ui.hyphenation", json!({})).unwrap();
driver::set(&mut app, "hyphenate", json!(true));
driver::ok(&mut app);
let NodeKind::Text(t) = &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("not text") };
assert_eq!(t.plain_text(), "One\nTwo\nThree");
assert_eq!([t.para_at(0).hyphenate, t.para_at(1).hyphenate, t.para_at(2).hyphenate], [false, false, true]);
}
#[test]
fn hyphenation_confirm_leaves_the_other_drawing_unchanged() {
let (mut app, id) = app();
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let second = app.run("text.create", json!({"x": 10, "y": 10, "text": "Other drawing"})).unwrap()["id"].as_u64().unwrap();
assert_eq!(id, second, "local text IDs may match between drawings");
app.run("select.set", json!({"ids": [second]})).unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("ui.hyphenation", json!({})).unwrap();
driver::set(&mut app, "hyphenate", json!(true));
app.run("document.activate", json!({"index": 1})).unwrap();
driver::ok(&mut app);
assert!(!paras(&app, second).0.hyphenate);
assert!(driver::is_open(&app));
assert_eq!(driver::fields(&app).bool("hyphenate"), Some(true));
app.run("document.activate", json!({"index": 0})).unwrap();
driver::ok(&mut app);
assert!(!driver::is_open(&app));
assert!(paras(&app, id).0.hyphenate);
}
}
+201 -24
View File
@@ -4,6 +4,9 @@
//!
//! Fields: `reduction`, `colors`, `dither`, `ditherAmount` and `preview`.
use std::sync::Arc;
use craft::ui::contract::Bind;
use craft::ui::dialog::dialog_id;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult};
use craft::ui::runtime::env::UnitKind;
@@ -21,6 +24,37 @@ const CMD: &str = "edit.colors.toIndexed";
/// The undo step a preview and OK make.
const PREVIEW_LABEL: &str = "Convert to Indexed Color";
pub(crate) struct Open {
document: u64,
reverts: u64,
opening: Arc<()>,
preview: LivePreview,
}
impl Open {
fn on_original_drawing(&self, app: &VectorcraftApp) -> bool {
self.check_drawing(app).is_ok()
}
fn check_drawing(&self, app: &VectorcraftApp) -> Result<(), &'static str> {
let st = app.session.active().filter(|st| st.uid == self.document).ok_or(tl!("Return to the original drawing to convert its images"))?;
if st.reverts != self.reverts {
return Err(tl!("Reopen Convert to Indexed Color after reverting the drawing"));
}
Ok(())
}
fn cancel_preview(self, app: &mut VectorcraftApp) {
if self.on_original_drawing(app) && !other_preview(app) {
self.preview.cancel(app);
}
}
}
fn other_preview(app: &VectorcraftApp) -> bool {
app.session.active().and_then(|st| st.interaction.as_ref()).is_some_and(|p| p.label != PREVIEW_LABEL)
}
/// The reductions besides those of a PNG-8 export, as (value, label).
const MORE_REDUCTIONS: [(&str, &str); 2] = [("uniform", "Uniform"), ("document", "Document Swatches")];
@@ -53,7 +87,7 @@ fn build(fields: &mut DialogFields) -> ParamDialog<'_> {
fields.set("colors", clamped);
}
}
ParamDialog::new(KIND, tl!("Convert to Indexed Color"), rows()).previews(true)
ParamDialog::new(KIND, tl!("Convert to Indexed Color"), rows()).values(Bind::bound(fields)).previews(true)
}
/// Open the dialog with the defaults of `edit.colors.toIndexed`.
@@ -62,38 +96,69 @@ pub fn open(app: &mut VectorcraftApp) {
app.status("no window".to_string());
return;
};
let Some((document, reverts)) = app.session.active().map(|st| (st.uid, st.reverts)) else {
app.status(tl!("Open a drawing to convert its images"));
return;
};
if let Some(old) = app.object_dialogs.indexed.take() {
old.cancel_preview(app);
}
let dialog = HostedParamDialog::new(&ctx, KIND, DialogFields::new(), build);
app.object_dialogs.indexed = Some(LivePreview::default());
let opening = Arc::new(());
let cancelled = Arc::clone(&opening);
let ok = |app: &mut VectorcraftApp, r: &ParamResult| {
let preview = app.object_dialogs.indexed.take().unwrap_or_default();
let done = preview.commit(app, CMD, params(&r.fields)).map(|_| ());
let open = app.object_dialogs.indexed.as_ref().ok_or("the Indexed Color dialog is gone")?;
open.check_drawing(app)?;
if other_preview(app) {
app.keep_typing()?;
if other_preview(app) {
return Err(tl!("Finish the current edit before converting its images").into());
}
}
let open = app.object_dialogs.indexed.take().ok_or("the Indexed Color dialog is gone")?;
let done = open.preview.commit(app, CMD, params(&r.fields)).map(|_| ());
if done.is_err() {
// The dialog stays open and previews again.
app.object_dialogs.indexed = Some(LivePreview::default());
app.object_dialogs.indexed = Some(Open { preview: LivePreview::default(), ..open });
}
done
};
let cancel = Box::new(|app: &mut VectorcraftApp| {
if let Some(preview) = app.object_dialogs.indexed.take() {
preview.cancel(app);
let cancel = Box::new(move |app: &mut VectorcraftApp| {
if app.object_dialogs.indexed.as_ref().is_some_and(|open| Arc::ptr_eq(&open.opening, &cancelled))
&& let Some(open) = app.object_dialogs.indexed.take()
{
open.cancel_preview(app);
}
});
if open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }).is_none() {
app.object_dialogs.indexed = None;
if open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }).is_some() {
app.object_dialogs.indexed = Some(Open { document, reverts, opening, preview: LivePreview::default() });
} else {
app.status("no window".to_string());
}
}
/// Each frame: show the dialog's values on the canvas while its Preview box is on.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(mut preview) = app.object_dialogs.indexed.take() else { return };
let Some(mut open) = app.object_dialogs.indexed.take() else { return };
if !open.on_original_drawing(app) {
app.object_dialogs.indexed = Some(open);
return;
}
let shown = app
.dialogs()
.and_then(|h| h.with(|host| host.get_by_id::<HostedParamDialog>(dialog_id(KIND)).map(|d| (d.is_previewing(), params(d.fields())))));
if let Some((on, p)) = &shown {
let _ = preview.run(app, *on, PREVIEW_LABEL, CMD, p);
if *on
&& other_preview(app)
&& let Err(e) = app.keep_typing()
{
app.status(e);
}
if !other_preview(app) {
let _ = open.preview.run(app, *on, PREVIEW_LABEL, CMD, p);
}
}
app.object_dialogs.indexed = Some(preview);
app.object_dialogs.indexed = Some(open);
}
/// Whether reduction `r` takes a number of colors.
@@ -123,29 +188,34 @@ fn params(fields: &DialogFields) -> Value {
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::{panel_harness::Panel, picks::dialogs};
use craft::ui::contract::Role;
use std::collections::BTreeSet;
use vectorcraft_engine::Session;
#[test]
fn commits_the_chosen_palette_as_one_step() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
fn add_raster(app: &mut VectorcraftApp) -> vectorcraft_doc::NodeId {
add_raster_row(app, &[[200, 30, 90, 255], [20, 40, 220, 255]])
}
fn add_raster_row(app: &mut VectorcraftApp, rgba: &[[u8; 4]]) -> vectorcraft_doc::NodeId {
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let width = u32::try_from(rgba.len()).unwrap();
let img = craft_image_codecs::Image::from_raw(
2,
width,
1,
craft_image_codecs::ChannelLayout::Rgba,
craft_image_codecs::SampleType::U8,
vec![200, 30, 90, 255, 20, 40, 220, 255],
rgba.as_flattened().to_vec(),
)
.unwrap();
let png = craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap();
let id = app
.session
app.session
.edit("Place", |d, sel| {
d.images.insert("pic".into(), vectorcraft_doc::ImageBlob::png(png));
let id = d.alloc_id();
let im = vectorcraft_doc::ImageObject {
key: "pic".into(),
width: 2,
width,
height: 1,
xf: Default::default(),
link: None,
@@ -156,7 +226,56 @@ mod tests {
sel.set([id]);
Ok(id)
})
.unwrap();
.unwrap()
}
fn palette(app: &VectorcraftApp, id: vectorcraft_doc::NodeId) -> &vectorcraft_doc::ImageBlob {
let st = app.session.doc().unwrap();
let vectorcraft_doc::NodeKind::Image(im) = &st.doc.node(id).unwrap().kind else { panic!("not an image") };
&st.doc.images[&im.key]
}
#[test]
fn indexed_color_form_edits_update_the_preview_and_confirmation() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let id = add_raster_row(&mut app, &[[200, 30, 90, 255], [20, 40, 220, 255], [220, 240, 70, 255]]);
let original = palette(&app, id).rgba().unwrap().2;
let undo = app.session.doc().unwrap().history.undo.len();
let mut panel = Panel::new(app, dialogs);
let black_and_white = |panel: &mut Panel| {
panel.click_role("Reduction", Role::COMBO_BOX);
panel.click("Black & White");
panel.click_role("Dither", Role::COMBO_BOX);
panel.click("No Dither");
};
panel.app().run("ui.indexedColorDialog", json!({})).unwrap();
panel.frame();
panel.click_at(panel.rect_role("Colors", Role::SPIN_BUTTON).center());
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text("2");
panel.key(egui::Key::Tab, egui::Modifiers::NONE);
let preview = palette(&panel.app(), id).rgba().unwrap().2;
assert_eq!(preview.as_chunks::<4>().0.iter().collect::<BTreeSet<_>>().len(), 2);
black_and_white(&mut panel);
let preview = palette(&panel.app(), id).rgba().unwrap().2;
assert_eq!(preview, [0, 0, 0, 255, 0, 0, 0, 255, 255, 255, 255, 255]);
panel.click("Cancel");
assert_eq!(palette(&panel.app(), id).rgba().unwrap().2, original);
assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), undo);
panel.app().run("ui.indexedColorDialog", json!({})).unwrap();
black_and_white(&mut panel);
panel.click("OK");
assert_eq!(palette(&panel.app(), id).rgba().unwrap().2, preview);
assert_eq!(panel.app().session.doc().unwrap().history.undo.len(), undo + 1);
}
#[test]
fn commits_the_chosen_palette_as_one_step() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
let id = add_raster(&mut app);
let undo = app.session.doc().unwrap().history.undo.len();
app.run("ui.indexedColorDialog", json!({})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
@@ -170,9 +289,67 @@ mod tests {
crate::dialogs::host::pump(&mut app, &ctx);
let st = app.session.doc().unwrap();
assert_eq!(st.history.undo.len(), undo + 1);
let vectorcraft_doc::NodeKind::Image(im) = &st.doc.node(id).unwrap().kind else { panic!("not an image") };
let blob = &st.doc.images[&im.key];
let blob = palette(&app, id);
assert!(blob.indexed_png());
assert_eq!(blob.rgba().unwrap().2, [0, 0, 0, 255, 0, 0, 0, 255], "black and white only");
}
#[test]
fn indexed_color_preview_and_ok_leave_the_other_drawings_pixels_unchanged() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
let source = add_raster(&mut app);
open(&mut app);
let ctx = app.ui_ctx.clone().unwrap();
let host = app.dialogs().unwrap();
let id = dialog_id(KIND);
host.with(|h| h.set_json_field(&ctx, id, "reduction", json!("blackWhite"))).unwrap();
let other = add_raster(&mut app);
host.with(|h| h.set_json_field(&ctx, id, "dither", json!("none"))).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
crate::dialogs::host::pump(&mut app, &ctx);
assert!(!palette(&app, other).indexed_png(), "the other drawing does not show the preview");
host.with(|h| h.confirm_by_id(&ctx, id));
crate::dialogs::host::pump(&mut app, &ctx);
assert!(!palette(&app, other).indexed_png(), "the other drawing does not keep the preview");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
app.run("document.activate", json!({"index": 0})).unwrap();
host.with(|h| h.confirm_by_id(&ctx, id));
crate::dialogs::host::pump(&mut app, &ctx);
assert!(palette(&app, source).indexed_png());
}
#[test]
fn indexed_color_preview_and_ok_leave_reloaded_pixels_unchanged() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let dir = vectorcraft_testkit::TempDir::new("indexed-color-image-revert");
let image = add_raster(&mut app);
app.run("file.saveAs", json!({"path": dir.join("raster.vectorcraft")})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
app.run("select.set", json!({"ids": [image.0]})).unwrap();
open(&mut app);
let st = app.session.active().unwrap();
let version = (st.uid, st.reverts);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let st = app.session.active().unwrap();
assert_eq!(st.uid, version.0);
assert_ne!(st.reverts, version.1);
let undo = st.history.undo.len();
app.run("select.set", json!({"ids": [image.0]})).unwrap();
let before = palette(&app, image).rgba().unwrap().2;
let id = dialog_id(KIND);
crate::tests::picks::answer_dialog(
&mut app,
id,
&[("reduction", json!("blackWhite")), ("dither", json!("none")), ("preview", json!(true))],
false,
);
assert_eq!(palette(&app, image).rgba().unwrap().2, before, "old Preview leaves the saved pixels in place");
crate::tests::picks::answer_dialog(&mut app, id, &[("preview", json!(false))], true);
assert_eq!(palette(&app, image).rgba().unwrap().2, before, "old OK leaves the saved pixels in place");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
}
}
+46 -8
View File
@@ -14,7 +14,7 @@
//! its file name alone, as `svgInteractivity.info` does; `selected` keeps the file as linked.
use craft::behavior::{Selection, keyed};
use craft::host::PickRequest;
use craft::host::{PickId, PickRequest, Picked};
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::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
@@ -61,6 +61,8 @@ struct Form {
file: String,
/// The linked file selected in the list, as linked or as the list shows it.
selected: String,
/// The file chooser still waiting for its typed answer.
pick: Option<PickId>,
pending: Option<Pending>,
}
@@ -217,12 +219,29 @@ fn body(ui: &mut Ui, files: &[(String, String)], form: &mut Form) {
if selection.items.first() != selected {
form.selected = selection.items.into_iter().next().unwrap_or_default();
}
Field::new(caption("File or URL:")).show(ui, |ui, _| {
let request = PickRequest::open("javascript").filter("JavaScript", &["js"]);
let out = PathRow::new(caption("File or URL:"), Bind::bound(&mut form.file)).button(tl!("Choose…")).pick(request).show(ui);
// The answer is a path; the dialog links a `file:///` URL ([`crate::io::file_url`]).
if let Some(path) = out.picked {
form.file = crate::io::file_url(&path);
Field::new(caption("File or URL:")).show(ui, |ui, cx| {
if let Some(ticket) = form.pick
&& let Some(answer) = cx.take_pick_answer(ticket)
{
form.pick = None;
// Browser picks supply the file's bytes and basename. Only a filesystem path can be linked.
if let Picked::Paths(paths) = answer
&& let Some(path) = paths.first()
{
form.file = crate::io::file_url(&path.to_string_lossy());
}
}
let mut row = PathRow::new(caption("File or URL:"), Bind::bound(&mut form.file)).button(tl!("Choose…"));
if !cx.env.host().is_some_and(|host| host.files().can_pick()) {
row = row.browse_reason(tl!("To link a script here, enter its URL."));
}
let row = row.show(ui);
if row.browse
&& form.pick.is_none()
&& let Some(host) = cx.env.host()
{
let request = PickRequest::open("javascript").filter("JavaScript", &["js"]);
form.pick = Some(host.files().pick(request));
}
});
let chosen = selected_row(files, &form.selected);
@@ -242,7 +261,7 @@ mod tests {
use std::rc::Rc;
use std::sync::Arc;
use craft::host::{AppInfo, Host, Picked, ScriptedFiles};
use craft::host::{AppInfo, Host, ScriptedFiles};
use craft::ui::testing::Fixture;
use egui::{Key, Modifiers};
use vectorcraft_engine::Session;
@@ -380,4 +399,23 @@ mod tests {
let file = form.borrow().file.clone();
assert!(file.starts_with("file:///") && file.ends_with("/my%20menu.js") && !file.contains('\\'), "{file}");
}
#[test]
fn browser_can_link_a_url_without_offering_a_local_file_picker() {
let files = Arc::new(ScriptedFiles::held().in_browser());
let form = Rc::new(RefCell::new(Form { file: "https://example.test/menu.js".into(), ..Default::default() }));
let shown = Rc::clone(&form);
let mut fixture = Fixture::new(move |ui| body(ui, &[], &mut shown.borrow_mut()));
fixture.host(Arc::new(Host::builder(AppInfo { id: "test", name: "Test", version: "1.0" }).files(files.clone()).build()));
fixture.settle();
let choose = fixture.by_label(tl!("Choose…")).expect("the Choose button");
assert!(fixture.tree().is_disabled_key(choose.node));
fixture.click(&choose);
fixture.settle();
assert!(files.requests().is_empty());
assert_eq!(form.borrow().file, "https://example.test/menu.js");
let add = fixture.by_label(tl!("Add")).expect("the Add button");
fixture.click(&add);
assert_eq!(form.borrow().pending, Some(Pending::Add));
}
}
+214 -7
View File
@@ -16,6 +16,7 @@
//! Behaviour reference (public documentation):
//! <https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/adjust-word-and-letterspacing-in-justified-text.html>.
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind};
// PLAN: assumed paths of `UnitKind` and `DialogId`
use craft::ui::dialog::DialogId;
@@ -36,6 +37,8 @@ const CMD: &str = "text.setFormat";
pub(crate) struct Open {
/// The dialog on the host.
pub id: DialogId,
/// The drawing that owns the text IDs and the preview.
document: (u64, u64),
/// The preview on the canvas.
pub preview: LivePreview,
/// The `ids`, `start` and `end` the dialog's `text.setFormat` acts on.
@@ -47,6 +50,12 @@ pub(crate) struct Open {
initial: DialogFields,
}
impl Open {
fn in_opening_document(&self, app: &VectorcraftApp) -> bool {
app.session.active().is_some_and(|st| (st.uid, st.reverts) == self.document)
}
}
/// The three spacing rows: (`text.setFormat` key, field prefix, range).
const ROWS: [(&str, &str, (f64, f64)); 3] = [
("wordSpacing", "word", JustificationOptions::WORD_SPACING),
@@ -84,7 +93,7 @@ fn problem(fields: &DialogFields) -> Option<&'static str> {
/// The dialog over its values: three titled groups of Minimum, Desired and Maximum, Auto Leading and
/// Single Word Justification. Preview starts off ([`HostedParamDialog::preview_off`]).
fn form(fields: &DialogFields) -> ParamDialog<'_> {
fn form(fields: &mut DialogFields) -> ParamDialog<'_> {
let titles = [tl!("Word Spacing"), tl!("Letter Spacing"), tl!("Glyph Scaling")];
let columns = [tl!("Minimum"), tl!("Desired"), tl!("Maximum")];
let mut rows = Vec::new();
@@ -98,8 +107,9 @@ fn form(fields: &DialogFields) -> ParamDialog<'_> {
rows.push(Param::number("autoLeading", tl!("Auto Leading:"), 120.0, 1.0, 0).bounds(Some(lo), Some(hi)).unit(UnitKind::Percent));
let options = single_word_choices().into_iter().map(|(id, label)| (id.to_owned(), label.into())).collect();
rows.push(Param::new("singleWord", tl!("Single Word Justification:"), ParamKind::choice(options, Some("fullJustify".to_owned()))));
let dialog = ParamDialog::new(KIND, tl!("Justification"), rows).previews(true);
match problem(fields) {
let reason = problem(fields);
let dialog = ParamDialog::new(KIND, tl!("Justification"), rows).previews(true).values(Bind::bound(fields));
match reason {
Some(why) => dialog.ok_enabled(false).ok_reason(why.into()),
None => dialog,
}
@@ -108,6 +118,8 @@ fn form(fields: &DialogFields) -> ParamDialog<'_> {
/// Open Justification on the paragraph attributes the Paragraph panel shows.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
crate::panels::character::text_style(app).ok_or("select some type first")?;
let active = app.session.active().ok_or("no document open")?;
let document = (active.uid, active.reverts);
// While typing, the dialog acts on the paragraphs of the text being edited.
let mut targets = json!({});
let mut story = None;
@@ -133,23 +145,32 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
set_shared(&mut fields, "autoLeading", crate::panels::paragraph::shared_justification_f64(app, |j| j.auto_leading));
set_shared(&mut fields, "singleWord", crate::panels::paragraph::shared_single_word_justify(app).map(single_word_name));
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let dialog = HostedParamDialog::new(&ctx, KIND, fields.clone(), |f| form(f)).preview_off();
let dialog = HostedParamDialog::new(&ctx, KIND, fields.clone(), form).preview_off();
let id = super::host::open_held(app, dialog, |app, result| {
let Some(open) = app.justification.take() else { return Ok(()) };
if !open.in_opening_document(app) {
let message = if app.session.active().is_some_and(|st| st.uid == open.document.0) {
tl!("The document was reverted. Reopen this dialog to continue.")
} else {
tl!("This dialog was opened in a different document.")
};
app.justification = Some(open);
return Err(message.to_owned());
}
let p = params(app, &result.fields, &open);
if !changes(&p) {
// Nothing to apply: end the preview as production's OK did.
open.preview.cancel(app);
return Ok(());
}
let Open { id, preview, targets, story, initial } = open;
let Open { id, document, preview, targets, story, initial } = open;
preview.commit(app, CMD, Value::Object(p)).map(|_| ()).inspect_err(|_| {
// The dialog stays open on the refusal, with a preview of its own again.
app.justification = Some(Open { id, preview: LivePreview::default(), targets, story, initial });
app.justification = Some(Open { id, document, preview: LivePreview::default(), targets, story, initial });
})
})
.ok_or("no window")?;
app.justification = Some(Open { id, preview: LivePreview::default(), targets, story, initial: fields });
app.justification = Some(Open { id, document, preview: LivePreview::default(), targets, story, initial: fields });
Ok(Value::Null)
}
@@ -200,6 +221,14 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(mut open) = app.justification.take() else { return };
let shown =
app.dialogs().and_then(|d| d.with(|h| h.get_mut_by_id::<HostedParamDialog>(open.id).map(|d| (d.is_previewing(), d.fields().clone()))));
// A document switch or revert ends the opening preview. The active drawing may have started a different one.
if !open.in_opening_document(app) {
if shown.is_some() {
open.preview = LivePreview::default();
app.justification = Some(open);
}
return;
}
// The host lock is released: a command never runs inside `DialogHost::with`.
let Some((on, fields)) = shown else {
open.preview.cancel(app);
@@ -296,6 +325,96 @@ mod tests {
assert!(!driver::is_open(&app));
}
#[test]
fn justification_minimum_input_updates_validation_and_paragraphs() {
use egui::accesskit::Role;
use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
for lang in ["en", "de", "fr", "el"] {
for height in [700.0, 500.0] {
let (mut app, id) = app();
app.session.prefs.interface_language = lang.into();
let ctx = app.ui_ctx.clone().unwrap();
ctx.enable_accesskit();
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, height));
let undo = app.session.active().unwrap().history.undo.len();
let mut time = 0.0;
let mut draw = |app: &mut VectorcraftApp, events| {
time += 0.25;
crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() })
};
let control = |out: egui::FullOutput, role, name: &str| {
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
let by_id: std::collections::HashMap<_, _> = nodes.iter().map(|(id, node)| (*id, node)).collect();
let dialog = nodes.iter().find(|(_, node)| node.role() == Role::Dialog).expect("Justification modal").0;
let mut pending = vec![dialog];
let mut matches = Vec::new();
while let Some(id) = pending.pop() {
let Some(node) = by_id.get(&id) else { continue };
pending.extend_from_slice(node.children());
if node.role() == role
&& node.label() == Some(name)
&& let Some(bounds) = node.bounds()
{
let at = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32);
let text = node
.children()
.iter()
.filter_map(|id| by_id.get(id))
.find(|child| child.role() == Role::TextInput)
.and_then(|child| child.bounds());
let target = text.map_or(at, |text| pos2(((text.x0 + text.x1) * 0.5) as f32, ((text.y0 + text.y1) * 0.5) as f32));
if screen.contains(target) {
matches.push((at, target, node.is_disabled()));
}
}
}
// Word Spacing is the first Minimum control in the modal.
let (_, target, disabled) = matches
.into_iter()
.min_by(|a, b| a.0.y.total_cmp(&b.0.y))
.unwrap_or_else(|| panic!("{lang} 800x{height}: missing {role:?} {name:?}"));
(target, disabled)
};
let click = |draw: &mut dyn FnMut(&mut VectorcraftApp, Vec<Event>) -> egui::FullOutput, app: &mut VectorcraftApp, at| {
draw(app, vec![Event::PointerMoved(at)]);
for pressed in [true, false] {
draw(app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
};
let key = |key, modifiers| Event::Key { key, physical_key: Some(key), pressed: true, repeat: false, modifiers };
draw(&mut app, vec![]);
app.run("ui.justification", json!({})).unwrap();
for _ in 0..8 {
draw(&mut app, vec![]);
}
for (typed, value, invalid) in [("120", 120.0, true), ("85", 85.0, false)] {
let (min, _) = control(draw(&mut app, vec![]), Role::SpinButton, crate::i18n::t("Minimum"));
click(&mut draw, &mut app, min);
draw(&mut app, vec![key(Key::A, Modifiers::COMMAND)]);
draw(&mut app, vec![Event::Text(typed.into())]);
draw(&mut app, vec![key(Key::Tab, Modifiers::NONE)]);
draw(&mut app, vec![]);
assert_eq!(driver::fields(&app).number("wordMin"), Some(value));
let (ok, disabled) = control(draw(&mut app, vec![]), Role::Button, crate::i18n::t("OK"));
assert_eq!(disabled, invalid);
click(&mut draw, &mut app, ok);
for _ in 0..3 {
draw(&mut app, vec![]);
}
assert_eq!(driver::is_open(&app), invalid);
if invalid {
assert_eq!(paras(&app, id).0.justification.word_spacing, [80.0, 100.0, 133.0]);
}
}
assert_eq!(paras(&app, id).0.justification.word_spacing, [85.0, 100.0, 133.0]);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
crate::i18n::set_current(crate::i18n::Lang::EN);
}
}
}
/// Preview shows the values on the canvas; Cancel rolls them back.
#[test]
fn justification_dialog_previews_and_cancel_restores() {
@@ -433,4 +552,92 @@ mod tests {
app.run("edit.undo", json!({})).unwrap();
assert!(auto_leadings(&app, c).iter().all(|l| *l == 150.0), "undo restores the hidden frame");
}
fn two_drawings() -> (VectorcraftApp, u64) {
let (mut app, id) = app();
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let second = app.run("text.create", json!({"x": 10, "y": 10, "text": "Other drawing"})).unwrap()["id"].as_u64().unwrap();
assert_eq!(id, second, "local text IDs may match between drawings");
app.run("document.activate", json!({"index": 0})).unwrap();
(app, id)
}
#[test]
fn justification_approval_leaves_text_in_the_other_drawing_unchanged() {
let (mut app, id) = two_drawings();
app.run("ui.justification", json!({})).unwrap();
driver::set(&mut app, "autoLeading", json!(180));
app.run("document.activate", json!({"index": 1})).unwrap();
driver::ok(&mut app);
assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0);
assert!(driver::is_open(&app));
assert_eq!(driver::fields(&app).number("autoLeading"), Some(180.0));
app.run("document.activate", json!({"index": 0})).unwrap();
driver::ok(&mut app);
assert!(!driver::is_open(&app));
assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0);
}
#[test]
fn justification_preview_leaves_text_in_the_other_drawing_unchanged() {
let (mut app, id) = two_drawings();
app.run("ui.justification", json!({})).unwrap();
driver::set(&mut app, "autoLeading", json!(180));
app.run("document.activate", json!({"index": 1})).unwrap();
driver::set(&mut app, "preview", json!(true));
driver::pump(&mut app);
assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0);
assert!(!app.session.in_interaction());
app.run("document.activate", json!({"index": 0})).unwrap();
driver::pump(&mut app);
assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0);
driver::cancel(&mut app);
assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0);
}
#[test]
fn cancelling_justification_keeps_the_other_drawings_new_interaction() {
let (mut app, id) = two_drawings();
app.run("ui.justification", json!({})).unwrap();
driver::set(&mut app, "autoLeading", json!(180));
driver::set(&mut app, "preview", json!(true));
driver::pump(&mut app);
assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0);
app.run("document.activate", json!({"index": 1})).unwrap();
app.begin_interaction("New text edit").unwrap();
app.session.preview("text.setFormat", &json!({"ids": [id], "autoLeading": 190})).unwrap();
driver::cancel(&mut app);
assert_eq!(paras(&app, id).0.justification.auto_leading, 190.0);
assert!(app.session.in_interaction());
}
#[test]
fn justification_does_not_preview_or_apply_after_revert() {
let (mut app, id) = app();
let dir = vectorcraft_testkit::TempDir::new("justification-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
app.run("text.setFormat", json!({"ids": [id], "autoLeading": 145})).unwrap();
app.run("ui.justification", json!({})).unwrap();
driver::set(&mut app, "autoLeading", json!(180));
driver::set(&mut app, "preview", json!(true));
driver::pump(&mut app);
assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0);
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
driver::pump(&mut app);
assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0);
let dialog = craft::ui::dialog::dialog_id(KIND);
crate::tests::picks::answer_dialog(&mut app, dialog, &[], true);
assert_eq!(paras(&app, id).0.justification.auto_leading, 120.0);
assert!(matches!(app.dialogs().unwrap().with(|h| h.held_state(dialog)), Some(craft::ui::dialog::HeldOk::Refused(_))));
driver::cancel(&mut app);
app.run("ui.justification", json!({})).unwrap();
driver::set(&mut app, "autoLeading", json!(180));
driver::ok(&mut app);
assert_eq!(paras(&app, id).0.justification.auto_leading, 180.0);
}
}
+17 -10
View File
@@ -55,7 +55,8 @@ fn categories() -> [(&'static str, &'static str); 4] {
/// What OK files for the pump: the document the dialog opened on, the names of its sets then, and the sets.
#[derive(Clone)]
struct Request {
doc: Option<u64>,
doc: u64,
reverts: u64,
opened: Vec<String>,
sets: Value,
}
@@ -63,8 +64,9 @@ struct Request {
/// The Kinsoku Shori Settings dialog on the host.
pub(crate) struct KinsokuDialog {
id: DialogId,
/// The uid of the document the dialog opened on, which OK sets the sets of.
doc: Option<u64>,
/// The drawing and its saved-content generation when the dialog opened.
doc: u64,
reverts: u64,
/// The names of that document's sets when the dialog opened: OK keeps the sets the document gained
/// since, after the dialog's own, and New's suggestion skips these names.
opened: Vec<String>,
@@ -84,7 +86,7 @@ pub(crate) struct KinsokuDialog {
/// Open Kinsoku Shori Settings on the active document's custom sets, the first one picked.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let st = app.session.active().ok_or("no document open")?;
let dialog = KinsokuDialog::new(st.uid, st.doc.kinsoku_sets.iter());
let dialog = KinsokuDialog::new(st.uid, st.reverts, st.doc.kinsoku_sets.iter());
app.dialogs().ok_or("no window")?.with(|host| host.open(dialog));
Ok(Value::Null)
}
@@ -176,10 +178,11 @@ fn text_of(field: &str, value: &Value) -> Result<String, String> {
}
impl KinsokuDialog {
fn new<'a>(doc: u64, document_sets: impl Iterator<Item = &'a KinsokuSet> + Clone) -> Self {
fn new<'a>(doc: u64, reverts: u64, document_sets: impl Iterator<Item = &'a KinsokuSet> + Clone) -> Self {
let mut d = KinsokuDialog {
id: dialog_id(COMMAND),
doc: Some(doc),
doc,
reverts,
opened: document_sets.clone().map(|k| k.name.clone()).collect(),
sets: Value::Array(document_sets.map(listed).collect()),
selected: 0,
@@ -340,7 +343,7 @@ impl KinsokuDialog {
}
self.commit();
self.problem = None;
self.held.file(Request { doc: self.doc, opened: self.opened.clone(), sets: self.sets.clone() });
self.held.file(Request { doc: self.doc, reverts: self.reverts, opened: self.opened.clone(), sets: self.sets.clone() });
}
/// The answer OK filed, once.
@@ -517,7 +520,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) {
let Some(host) = app.dialogs() else { return };
let Some(request) = host.with(|h| h.get_mut::<KinsokuDialog>().and_then(KinsokuDialog::take_ok)) else { return };
let answer = apply(app, &request);
let gone = answer.is_err() && !app.session.documents().iter().any(|d| Some(d.uid) == request.doc);
let gone = answer.is_err() && !app.session.documents().iter().any(|d| d.uid == request.doc);
// The command ran outside the host's lock, which a dialog's own methods take.
host.with(|h| {
if let Some(d) = h.get_mut::<KinsokuDialog>() {
@@ -530,8 +533,12 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &Context) {
}
fn apply(app: &mut VectorcraftApp, request: &Request) -> Result<(), String> {
if app.session.active().map(|st| st.uid) != request.doc {
let index = app.session.documents().iter().position(|d| Some(d.uid) == request.doc).ok_or("that document is no longer open")?;
let (index, document) =
app.session.documents().iter().enumerate().find(|(_, st)| st.uid == request.doc).ok_or("that document is no longer open")?;
if document.reverts != request.reverts {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
if app.session.active().is_none_or(|st| st.uid != request.doc) {
app.run("document.activate", json!({ "index": index }))?;
}
// A `sets` that is not a list of sets goes to the command as it is, which refuses it.
@@ -226,6 +226,47 @@ fn ok_sets_the_document_the_dialog_opened_on() {
assert!(app.session.documents().iter().all(|d| d.doc.kinsoku_sets.is_empty()));
}
#[test]
fn old_ok_keeps_restored_kinsoku_rules_and_the_current_tab() {
let mut app = app();
app.run("type.kinsokuSets.set", json!({"sets": [{"name": "Custom", "cannotStart": "ゝ"}]})).unwrap();
let file = std::env::temp_dir().join(format!("vectorcraft-kinsoku-revert-{}.vectorcraft", std::process::id()));
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string())));
app.run("file.saveAs", json!({"path": file.to_string_lossy()})).unwrap();
let st = app.session.active().unwrap();
let (uid, reverts) = (st.uid, st.reverts);
app.run("type.kinsokuSets.set", json!({"sets": [{"name": "Custom", "cannotStart": "ゞ"}]})).unwrap();
open(&mut app).unwrap();
set(&app, "cannotStart", json!("ー"));
app.run("file.revert", json!({"confirmed": true})).unwrap();
let _ = std::fs::remove_file(file);
let st = app.session.active().unwrap();
assert_eq!((st.uid, st.reverts), (uid, reverts + 1));
assert_eq!(doc_sets(&app)[0].cannot_start, ['ゝ']);
let undo = steps(&app);
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let other = app.session.active().unwrap().uid;
assert_ne!(uid, other);
pump(&mut app);
let restored = app.session.documents().iter().find(|st| st.uid == uid).unwrap();
assert_eq!(restored.doc.kinsoku_sets[0].cannot_start, ['ゝ'], "an old OK must keep the saved line-breaking rule");
assert_eq!(restored.history.undo.len(), undo);
assert_eq!(app.session.active().unwrap().uid, other, "a stale OK does not activate the original tab");
assert!(is_open(&app));
dialog(&app, |d| assert_eq!(d.problem.as_deref(), Some("The document was reverted. Reopen this dialog to continue.")));
cancel(&app);
assert!(app.session.set_active(0));
open(&mut app).unwrap();
set(&app, "cannotStart", json!("ー"));
pump(&mut app);
assert!(!is_open(&app));
assert_eq!(doc_sets(&app)[0].cannot_start, ['ー'], "a fresh draft can edit the restored rule");
}
/// OK keeps a set the document gained while the dialog was open, after the dialog's sets, and a
/// set deleted in the dialog stays deleted. A `sets` field that is not a list of sets keeps the
/// dialog open and leaves the document's sets as they are, and New refuses to start from it.
+58 -6
View File
@@ -249,9 +249,9 @@ fn fields_of(n: &Node, xml_id: bool) -> LayerOptionsValue {
/// Opens the dialog on `value`.
fn open_value(app: &mut VectorcraftApp, value: LayerOptionsValue) -> Result<Value, String> {
let document = app.session.active().ok_or("no document open")?.uid;
let st = app.session.active().ok_or("no document open")?;
let dialogs = app.dialogs().ok_or("no window")?;
dialogs.with(|host| host.open(LayerOptionsDialog::new(document, value)));
dialogs.with(|host| host.open(LayerOptionsDialog::new(st.uid, st.reverts, value)));
Ok(Value::Null)
}
@@ -412,6 +412,7 @@ pub(crate) fn params(v: &LayerOptionsValue) -> (&'static str, Value) {
pub(crate) struct LayerOptionsDialog {
id: DialogId,
document: u64,
reverts: u64,
open: bool,
value: LayerOptionsValue,
held: HeldAnswer<LayerOptionsValue>,
@@ -423,8 +424,17 @@ pub(crate) struct LayerOptionsDialog {
impl LayerOptionsDialog {
/// The dialog over `value`.
fn new(document: u64, value: LayerOptionsValue) -> Self {
LayerOptionsDialog { id: dialog_id(KEY), document, open: true, value, held: HeldAnswer::new(), refused_at: None, color_request: None }
fn new(document: u64, reverts: u64, value: LayerOptionsValue) -> Self {
LayerOptionsDialog {
id: dialog_id(KEY),
document,
reverts,
open: true,
value,
held: HeldAnswer::new(),
refused_at: None,
color_request: None,
}
}
/// The OK filed by the user, once.
@@ -573,9 +583,9 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
// The closed dialog's answer was run when OK was filed.
let _ = dialogs.with(|host| host.take::<LayerOptionsDialog>());
let Some((document, value)) = dialogs.with(|host| {
let Some((document, reverts, value)) = dialogs.with(|host| {
let dialog = host.get_mut::<LayerOptionsDialog>()?;
Some((dialog.document, dialog.take_filed()?))
Some((dialog.document, dialog.reverts, dialog.take_filed()?))
}) else {
return;
};
@@ -588,6 +598,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
// Isolation mode can start while the dialog is open.
let answer = match app.session.active().filter(|st| st.uid == document) {
None => Err(Label::from(tl!("Layer Options can only change the document it was opened for."))),
Some(st) if st.reverts != reverts => Err(Label::from(tl!("The document was reverted. Reopen this dialog to continue."))),
Some(st) if sublayer.is_some_and(|sublayer| crate::panels::layers::new_layer_unlisted(st, sublayer, false)) => {
Err(Label::from("exit isolation mode first"))
}
@@ -935,4 +946,45 @@ mod tests {
let n = app.session.doc().unwrap().doc.node(NodeId(rect)).unwrap().clone();
assert_eq!((n.display_name(), n.locked), ("Box".to_string(), true));
}
#[test]
fn layer_options_refuses_a_stale_draft_after_confirmed_revert() {
let file = std::env::temp_dir().join(format!("vectorcraft-layer-options-revert-{}.vectorcraft", std::process::id()));
let path = file.to_string_lossy();
let mut app = app();
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string())));
app.run("file.saveAs", json!({"path": path})).unwrap();
let original = app.session.active().unwrap();
let (uid, reverts, layer) = (original.uid, original.reverts, original.doc.layers[0].id);
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
app.run("ui.layerOptions", json!({"id": layer.0})).unwrap();
set(&mut app, "name", json!("Stale Draft"));
app.run("file.revert", json!({"confirmed": true})).unwrap();
let _ = std::fs::remove_file(&file);
let reverted = app.session.active().unwrap();
assert_eq!((reverted.uid, reverted.reverts, reverted.doc.layers[0].id), (uid, reverts + 1, layer));
let undo = reverted.history.undo.len();
let ctx = app.ui_ctx.clone().unwrap();
let id = open_id(&app);
let dialogs = app.dialogs().unwrap();
dialogs.with(|host| host.confirm_by_id(&ctx, id));
crate::dialogs::host::pump(&mut app, &ctx);
let reverted = app.session.active().unwrap();
assert_eq!(reverted.doc.node(layer).unwrap().display_name(), "Layer 1");
assert_eq!(reverted.history.undo.len(), undo);
assert!(app.any_dialog_open(), "the refused draft stays available to inspect or cancel");
assert_eq!(fields(&app)["name"], "Stale Draft");
assert_eq!(
dialogs.with(|host| host.held_state(id)),
Some(HeldOk::Refused("The document was reverted. Reopen this dialog to continue.".into()))
);
dialogs.with(|host| host.cancel_by_id(&ctx, id));
app.run("ui.layerOptions", json!({"id": layer.0})).unwrap();
set(&mut app, "name", json!("Fresh Draft"));
ok(&mut app);
assert_eq!(app.session.active().unwrap().doc.node(layer).unwrap().display_name(), "Fresh Draft");
}
}
+164 -18
View File
@@ -26,6 +26,7 @@ use crate::VectorcraftApp;
pub const KIND: &str = "livePaintGapOptions";
const CMD: &str = "livePaint.gapOptions";
const WRONG_DOCUMENT: &str = "Gap Options can only be applied in the document this dialog was opened for.";
/// The undo step the preview and OK make.
const PREVIEW_LABEL: &str = "Gap Options";
@@ -51,20 +52,31 @@ pub(super) static SPEC: OptionSpec = OptionSpec {
pub(crate) struct Open {
/// The dialog the preview belongs to.
pub id: DialogId,
/// The drawing and loaded contents that own the preview interaction.
document: (u64, u64),
/// The preview the options run as.
pub preview: LivePreview,
}
impl Open {
fn cancel(self, app: &mut VectorcraftApp) {
if app.session.active().is_some_and(|active| (active.uid, active.reverts) == self.document) {
self.preview.cancel(app);
}
}
}
/// Open Gap Options on the selected Live Paint groups, filled in from the first one's options.
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let groups: Vec<u64> = app
.session
.doc()
.map(|d| {
let doc = &d.doc;
d.selection.objects.iter().filter(|id| doc.node(**id).is_some_and(vectorcraft_tools::builder::is_live_paint)).map(|id| id.0).collect()
})
.unwrap_or_default();
let active = app.session.active().ok_or("select a Live Paint group")?;
let (document, reverts) = (active.uid, active.reverts);
let groups: Vec<u64> = active
.selection
.objects
.iter()
.filter(|id| active.doc.node(**id).is_some_and(vectorcraft_tools::builder::is_live_paint))
.map(|id| id.0)
.collect();
let Some(&first) = groups.first() else { return Err("select a Live Paint group".into()) };
let info = app.session.execute("livePaint.info", &json!({ "group": first })).map_err(|e| e.to_string())?;
let o = &info["gapOptions"];
@@ -75,10 +87,15 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let fields =
[("detect", o["detect"].clone()), ("size", json!(size)), ("custom", custom), ("color", o["color"].clone()), ("closeGaps", json!(false))];
let values = Map::from_iter(fields.map(|(key, value)| (key.to_owned(), value)));
option_form::open(app, &SPEC, values, json!({ "ids": groups })).ok_or("no window")?;
option_form::open(app, &SPEC, values, json!({ "ids": groups, "document": document, "reverts": reverts })).ok_or("no window")?;
Ok(Value::Null)
}
fn original_document(app: &VectorcraftApp, extra: &Value) -> Option<(u64, u64)> {
let document = (extra["document"].as_u64()?, extra["reverts"].as_u64()?);
app.session.active().filter(|active| (active.uid, active.reverts) == document).map(|_| document)
}
/// `livePaint.gapOptions` parameters from the values and the groups in `extra`.
fn params(values: &Map<String, Value>, extra: &Value) -> Value {
let size = match values.get("size").and_then(Value::as_str) {
@@ -111,24 +128,49 @@ fn body(ui: &mut egui::Ui, rows: &mut Rows<'_>) {
/// OK: keep the previewed options as one undo step; with no preview running they run as one.
fn run(app: &mut VectorcraftApp, values: &Map<String, Value>, extra: &Value) -> Result<Value, String> {
let preview = app.object_dialogs.gaps.take().map_or_else(LivePreview::default, |open| open.preview);
let document = original_document(app, extra).ok_or_else(|| {
if app.session.active().is_some_and(|active| extra["document"].as_u64() == Some(active.uid)) {
tl!("The document was reverted. Reopen this dialog to continue.").to_owned()
} else {
tl!(WRONG_DOCUMENT).to_owned()
}
})?;
let preview = app.object_dialogs.gaps.take().filter(|open| open.document == document).map_or_else(LivePreview::default, |open| open.preview);
preview.commit(app, CMD, params(values, extra))
}
/// The dialog closed without OK: roll the preview back.
fn cancelled(app: &mut VectorcraftApp) {
if let Some(open) = app.object_dialogs.gaps.take() {
open.preview.cancel(app);
open.cancel(app);
}
}
/// Runs the open Gap Options' preview as its options stand, once per frame after the shell pass: with Preview on the
/// options apply to the groups, off they are rolled back; the gaps a new preview finds are kept for [`overlays`].
/// Nothing runs while an OK waits for its answer, which keeps or refuses the preview that is running.
pub(crate) fn pump(app: &mut VectorcraftApp, _: &egui::Context) {
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let shown = dialogs.with(|host| {
let form = host.get::<OptionForm>().filter(|form| form.is(KIND))?;
let form = host.get_mut::<OptionForm>().filter(|form| form.is(KIND))?;
let source = form.extra["document"].as_u64()?;
if !app.session.documents().iter().any(|doc| doc.uid == source) {
host.cancel::<OptionForm>(ctx);
return None;
}
let document = original_document(app, &form.extra);
let paused = document.is_none();
if form.preview_paused != paused {
form.preview_paused = paused;
if !paused && form.held.refusal().is_some_and(|(reason, _)| reason.as_str() == tl!(WRONG_DOCUMENT)) {
form.held.clear_refusal();
}
ctx.request_repaint();
}
let Some(document) = document else {
form.previewed = Value::Null;
return None;
};
if !form.held.state().is_none_or(|state| matches!(state, HeldOk::Refused(_))) {
return None;
}
@@ -137,17 +179,17 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _: &egui::Context) {
if form.values.get("color").and_then(Value::as_str).is_some_and(has_alpha) {
params["color"] = Value::Null;
}
Some((form.id(), params, form.preview))
Some((form.id(), document, params, form.preview))
});
let Some((id, params, on)) = shown else { return };
let Some((id, document, params, on)) = shown else { return };
// A preview of another dialog is rolled back before this one starts its own.
let mut open = match app.object_dialogs.gaps.take() {
Some(open) if open.id == id => open,
Some(open) if open.id == id && open.document == document => open,
stale => {
if let Some(stale) = stale {
stale.preview.cancel(app);
stale.cancel(app);
}
Open { id, preview: LivePreview::default() }
Open { id, document, preview: LivePreview::default() }
}
};
let ran = open.preview.run(app, on, PREVIEW_LABEL, CMD, &params);
@@ -177,6 +219,7 @@ pub(crate) fn overlays(app: &VectorcraftApp) -> Vec<Overlay> {
let Some(dialogs) = app.dialogs() else { return vec![] };
let shown = dialogs.with(|host| {
let form = host.get::<OptionForm>().filter(|form| form.is(KIND) && form.preview)?;
original_document(app, &form.extra)?;
Some((form.previewed.clone(), form.values.get("color").and_then(Value::as_str)?.to_owned()))
});
let Some((gaps, color)) = shown else { return vec![] };
@@ -236,6 +279,109 @@ mod tests {
app.run("livePaint.make", json!({})).unwrap()["id"].as_u64().unwrap()
}
fn open_with_matching_groups(app: &mut VectorcraftApp) -> u64 {
let group = gapped_group(app);
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
assert_eq!(gapped_group(app), group, "the new document reuses the group ID");
app.run("document.activate", json!({"index": 0})).unwrap();
app.run("select.set", json!({"ids": [group]})).unwrap();
app.run("ui.livePaintGapOptions", json!({})).unwrap();
set(app, "detect", json!(true)).unwrap();
group
}
#[test]
fn gap_confirmation_stays_with_its_document() {
let mut app = app();
let group = open_with_matching_groups(&mut app);
app.run("document.activate", json!({"index": 1})).unwrap();
let undo = app.session.doc().unwrap().history.undo.len();
assert!(!press_ok(&mut app), "the unrelated group cannot take the edit");
assert_eq!(options(&app, group), GapOptions::default());
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
app.run("document.activate", json!({"index": 0})).unwrap();
pump_all(&mut app);
assert!(held(&app).is_none(), "the stale refusal clears on the original tab");
assert!(press_ok(&mut app), "the original group's edit can be retried");
assert!(options(&app, group).detect);
}
#[test]
fn closing_the_original_document_dismisses_gap_options() {
let mut app = app();
let group = open_with_matching_groups(&mut app);
app.run("document.activate", json!({"index": 1})).unwrap();
assert!(app.session.close_document(0));
pump_all(&mut app);
assert!(!is_open(&app));
assert_eq!(options(&app, group), GapOptions::default());
}
#[test]
fn gap_preview_disappears_in_another_document_and_resumes_on_return() {
let mut app = app();
let group = open_with_matching_groups(&mut app);
set(&app, "preview", json!(true)).unwrap();
pump_all(&mut app);
assert!(options(&app, group).detect);
assert!(!overlays(&app).is_empty());
app.run("document.activate", json!({"index": 1})).unwrap();
let unrelated_overlays = overlays(&app);
pump_all(&mut app);
let paused = |app: &VectorcraftApp| app.dialogs().unwrap().with(|host| host.get::<OptionForm>().unwrap().preview_paused);
assert!(paused(&app));
assert_eq!(fields(&app)["preview"], json!(true));
assert_eq!(options(&app, group), GapOptions::default());
assert!(!app.session.in_interaction());
assert!(unrelated_overlays.is_empty());
assert!(overlays(&app).is_empty());
app.run("document.activate", json!({"index": 0})).unwrap();
pump_all(&mut app);
assert!(!paused(&app));
assert!(options(&app, group).detect);
assert!(!overlays(&app).is_empty());
cancel(&mut app);
assert_eq!(options(&app, group), GapOptions::default());
}
#[test]
fn gap_preview_and_ok_do_not_edit_live_paint_restored_by_revert() {
let mut app = app();
let dir = vectorcraft_testkit::TempDir::new("live-paint-gap-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let group = gapped_group(&mut app);
let saved = options(&app, group);
app.run("file.saveAs", json!({"path": dir.join("Live Paint.vectorcraft")})).unwrap();
app.run("shape.rectangle", json!({"x": 140, "y": 140, "width": 20, "height": 20})).unwrap();
app.run("select.set", json!({"ids": [group]})).unwrap();
app.run("ui.livePaintGapOptions", json!({})).unwrap();
set(&app, "detect", json!(true)).unwrap();
set(&app, "preview", json!(true)).unwrap();
pump_all(&mut app);
assert!(options(&app, group).detect);
let source = app.session.active().unwrap();
let (uid, reverts) = (source.uid, source.reverts);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let current = app.session.active().unwrap();
assert_eq!((current.uid, current.reverts), (uid, reverts + 1));
let undo = current.history.undo.len();
pump_all(&mut app);
assert_eq!(options(&app, group), saved);
assert!(overlays(&app).is_empty());
assert!(!press_ok(&mut app));
assert_eq!(options(&app, group), saved);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
cancel(&mut app);
app.run("select.set", json!({"ids": [group]})).unwrap();
app.run("ui.livePaintGapOptions", json!({})).unwrap();
set(&app, "detect", json!(true)).unwrap();
assert!(press_ok(&mut app));
assert!(options(&app, group).detect);
}
#[test]
fn the_menu_item_opens_gap_options_which_preview_the_gaps_and_ok_keeps_them() {
let mut app = app();
+18 -36
View File
@@ -21,7 +21,7 @@
use std::time::Duration;
use craft::host::{Host, PickId, PickKind, PickRequest};
use craft::host::{PickKind, PickRequest};
use craft::ui::buttons::Button;
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, clicked};
@@ -154,6 +154,8 @@ enum Act {
Search,
/// Stop the running search, and stay open.
Stop,
/// Ask for a folder to search: the dialog closes, and comes back searching it.
Pick,
}
/// How the dialog finished: what to do, and the state to open the dialog again with.
@@ -166,22 +168,11 @@ pub(crate) struct Answer {
pub(crate) struct MissingFontsDialog {
id: DialogId,
state: State,
/// The folder pick Find in Folder… filed, until its answer comes.
ticket: Option<PickId>,
}
impl MissingFontsDialog {
fn new(state: State) -> Self {
MissingFontsDialog { id: dialog_id(KIND), state, ticket: None }
}
/// Forget the pick the dialog is waiting for.
fn release(&mut self, ctx: &Context) {
if let Some(ticket) = self.ticket.take()
&& let Some(host) = Host::try_of_ctx(ctx)
{
host.files().forget(ticket);
}
MissingFontsDialog { id: dialog_id(KIND), state }
}
}
@@ -221,10 +212,6 @@ impl StackDialog for MissingFontsDialog {
self.state.set(field, value)
}
fn cancelled(&mut self, ctx: &Context) {
self.release(ctx);
}
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<Answer>> {
let searching = self.state.searching();
let can_add = self.state.can_add();
@@ -232,23 +219,14 @@ impl StackDialog for MissingFontsDialog {
let lines = progress(&Value::Object(self.state.status.clone()));
let any_found = self.state.found.iter().any(|f| f["files"].as_array().is_some_and(|files| !files.is_empty()));
let mut act = None;
let MissingFontsDialog { state, ticket, .. } = &mut *self;
let MissingFontsDialog { state, .. } = &mut *self;
let State { fonts, next, found, chosen, can_pick, search_folder, .. } = state;
let shown = FormDialog::new(tl!("Missing Fonts"), Bind::bound(chosen))
.ok_label(tl!("Add Fonts"))
.cancel_label(tl!("Close"))
.ok_enabled(can_add)
.extra_buttons([FooterButton::new(tl!("Find Fonts"), DialogRole::Other)])
.show(ui, |ui, form, chosen| {
if let Some(pending) = *ticket
&& let Some(answer) = form.take_pick_answer(pending)
{
*ticket = None;
if let Some(path) = answer.first_path() {
*search_folder = path.to_string_lossy().into_owned();
act = Some(Act::Search);
}
}
.show(ui, |ui, _, chosen| {
Stack::new().show(ui, |ui, _| {
Text::new(tl!("These fonts aren't available. Their text shows in another font.")).shade(Shade::Muted).show(ui);
for f in fonts.iter() {
@@ -284,11 +262,9 @@ impl StackDialog for MissingFontsDialog {
*search_folder = next.clone();
act = Some(Act::Search);
}
if *can_pick
&& clicked(&Button::new(tl!("Find in Folder…")).id_salt("pick").enabled(!searching).show(ui))
&& let Some(host) = form.env.host().cloned()
{
*ticket = Some(host.files().pick(PickRequest::folder("fonts")));
// The app asks for the folder, as Type › Find Font's Find in Folder… does.
if *can_pick && clicked(&Button::new(tl!("Find in Folder…")).id_salt("pick").enabled(!searching).show(ui)) {
act = Some(Act::Pick);
}
if searching && clicked(&Button::new(tl!("Stop")).id_salt("stop").show(ui)) {
act = Some(Act::Stop);
@@ -315,9 +291,6 @@ impl StackDialog for MissingFontsDialog {
act = Some(Act::Find);
}
let closed = act.is_none() && shown.closed.is_some();
if act.is_some() || closed {
self.release(ui.ctx());
}
match act {
Some(act) => Some(DialogResult::Ok(Answer { act, state: self.state.clone() })),
None if closed => Some(DialogResult::Cancel),
@@ -399,6 +372,9 @@ fn settle(app: &mut VectorcraftApp, Answer { act, mut state }: Answer) {
Act::Find => find_fonts(app, state.uid).map(|()| false),
// The folder is searched once: one that doesn't start leaves the dialog without it.
Act::Search => start_search(app, &mut state, &search_folder).map(|()| true),
// The app asks for the folder, as Type › Find Font's Find in Folder… does; the dialog comes back
// searching it. A question that is cancelled leaves the dialog closed.
Act::Pick => find_in_folder_for(app, state.uid, None).map(|_| false),
Act::Stop => app.run("text.findFontFiles", json!({ "stop": true })).map(|_| {
if let Ok(r) = app.session.execute("text.findFontFiles", &json!({})) {
let error = follow(&mut state, &r);
@@ -497,6 +473,12 @@ fn show_for(app: &mut VectorcraftApp, uid: u64, dialog: MissingFontsDialog) {
/// `folder`), then open the dialog for the active document, searching it.
pub(crate) fn find_in_folder_command(app: &mut VectorcraftApp, folder: Option<String>) -> Result<Value, String> {
let uid = app.session.active().map(|d| d.uid).ok_or("no document open")?;
find_in_folder_for(app, uid, folder)
}
/// [`find_in_folder_command`] for the document `uid`, which a dialog left open may not be the
/// active one.
fn find_in_folder_for(app: &mut VectorcraftApp, uid: u64, folder: Option<String>) -> Result<Value, String> {
// Nothing to look for: no folder is asked for.
dialog_for(app, uid).ok_or(NOTHING_MISSING)?;
match folder {
@@ -195,6 +195,59 @@ fn the_documents_fonts_folder_is_offered_and_searched_off_the_ui_thread() {
assert!(is_open::<MissingFontsDialog>(&app), "a failed add keeps the dialog");
}
/// Find in Folder… closes the dialog and asks for the folder as the app does for Type › Find Font's
/// Find in Folder…; the dialog comes back searching the folder picked.
#[test]
fn find_in_folder_asks_for_the_folder_and_the_dialog_comes_back_searching_it() {
let root = folder("pick");
std::fs::create_dir_all(root.join("somewhere")).unwrap();
let mut app = app_for(&root);
let picks = crate::tests::picks::scripted(&mut app);
let doc = root.join("doc.vectorcraft");
save_doc(&mut app, &doc, "No Such Font Family", false);
open(&mut app, &doc);
pump(&mut app);
let ctx = app.ui_ctx.clone().expect("a window context");
let state = host(&app, |h| h.get::<MissingFontsDialog>().map(|d| d.state.clone())).expect("the dialog is open");
answer_cancel(&mut app);
assert!(!is_open::<MissingFontsDialog>(&app));
settle(&mut app, Answer { act: Act::Pick, state });
assert_eq!(picks.requests().last().map(|r| r.kind), Some(PickKind::Folder), "the app asks for a folder");
assert!(!is_open::<MissingFontsDialog>(&app), "the dialog waits for the answer");
picks.answer(&[&root.join("somewhere").to_string_lossy()]);
crate::tests::picks::poll(&mut app, &ctx);
pump(&mut app);
let f = fields(&app).expect("the dialog comes back");
assert_eq!(f["folder"], json!(root.join("somewhere").to_string_lossy()), "searching the folder picked: {f}");
}
/// The dialog of a document that isn't the active one asks for its own folder, and searches for its
/// own fonts.
#[test]
fn find_in_folder_searches_for_the_fonts_of_the_dialogs_document() {
let root = folder("pick-other");
std::fs::create_dir_all(root.join("somewhere")).unwrap();
let mut app = app_for(&root);
let picks = crate::tests::picks::scripted(&mut app);
let (a, b) = (root.join("a.vectorcraft"), root.join("b.vectorcraft"));
save_doc(&mut app, &a, "No Such Font Family", false);
save_doc(&mut app, &b, "Source Sans 3", false);
open(&mut app, &a);
pump(&mut app);
let ctx = app.ui_ctx.clone().expect("a window context");
let state = host(&app, |h| h.get::<MissingFontsDialog>().map(|d| d.state.clone())).expect("the dialog is open");
answer_cancel(&mut app);
open(&mut app, &b);
assert!(app.session.active().is_some_and(|d| d.uid != state.uid), "another document is the active one");
settle(&mut app, Answer { act: Act::Pick, state: state.clone() });
assert_eq!(picks.requests().last().map(|r| r.kind), Some(PickKind::Folder), "the app asks for a folder");
picks.answer(&[&root.join("somewhere").to_string_lossy()]);
crate::tests::picks::poll(&mut app, &ctx);
pump(&mut app);
let back = host(&app, |h| h.get::<MissingFontsDialog>().map(|d| d.state.uid));
assert_eq!(back, Some(state.uid), "the dialog of the document it was for comes back");
}
/// Find Fonts opens Type › Find Font on the first missing font, to replace it, and the Missing
/// Fonts dialog doesn't come back for that open.
#[test]
+145 -6
View File
@@ -105,8 +105,10 @@ impl<W: Copy> Asked<W> {
/// What the questions about one open's linked files keep between their dialogs: the files still
/// asked about, the modified images to offer for update afterwards and the open's notes.
#[derive(Clone, Debug, Default, PartialEq)]
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct LinkAsk {
/// The document that owns the linked-file IDs.
pub(crate) document: u64,
/// The missing files still asked about (`[{name, path, ids}]`), the next one first.
pub(crate) missing: Vec<Value>,
/// The ids of the images whose file was modified.
@@ -353,7 +355,11 @@ fn questions_for(app: &VectorcraftApp, r: &Value, web: bool) -> (Vec<String>, Ve
/// Opens the dialog about the first of `missing`, keeping what the questions after it need
/// ([`LinkAsk`]). A window that isn't up has nothing to show a question in.
fn open(app: &mut VectorcraftApp, missing: Vec<Value>, modified: Vec<Value>, notes: &[String]) {
let ask = LinkAsk { missing, modified, notes: notes.to_vec(), back: false };
let Some(document) = app.session.active().map(|st| st.uid) else { return };
open_ask(app, LinkAsk { document, missing, modified, notes: notes.to_vec(), back: false });
}
fn open_ask(app: &mut VectorcraftApp, ask: LinkAsk) {
let Some(dialogs) = app.dialogs() else { return };
let dialog = MissingLinksDialog::new(app, ask.clone());
app.link_asks = Some(ask);
@@ -415,7 +421,7 @@ fn ask(app: &mut VectorcraftApp, ids: Vec<Value>, one: &str, other: &str) -> Opt
return Some(changed_on_disk_status(ids.len()));
}
let detail = crate::i18n::tn(ids.len() as u64, one, other);
super::confirm::ask(app, tl!("Update Modified Links"), &detail, "links.update", json!({ "ids": ids }));
super::confirm::ask_in_document(app, tl!("Update Modified Links"), &detail, "links.update", json!({ "ids": ids }));
None
}
@@ -436,9 +442,16 @@ pub(crate) fn changed_on_disk_status(n: usize) -> String {
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let Some(result) = dialogs.with(|h| h.take::<MissingLinksDialog>()) else { return };
let ask = app.link_asks.take().unwrap_or_default();
let Some(ask) = app.link_asks.take() else { return };
let Some(answer) = result.ok() else { return show_notes_again(app, &ask) };
let LinkAsk { missing, modified, notes, .. } = ask;
if app.session.active().is_none_or(|st| st.uid != ask.document) {
app.status(tl!("This dialog was opened in a different document."));
if app.session.documents().iter().any(|st| st.uid == ask.document) {
open_ask(app, ask);
}
return;
}
let LinkAsk { document, missing, modified, notes, .. } = ask;
let done = match answer {
MissingLinksAnswer::FindInFolder(folder) => {
super::find_links::from_missing_links(app, missing.clone(), modified.clone(), notes.clone(), &folder).map(|()| None)
@@ -450,7 +463,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
Ok(None) => {}
Err(e) => {
app.status(e);
open(app, missing, modified, &notes);
open_ask(app, LinkAsk { document, missing, modified, notes, back: false });
}
}
}
@@ -587,6 +600,84 @@ mod tests {
json!({ "name": format!("{n}.png"), "path": format!("/gone/{n}.png"), "ids": [n] })
}
fn check_replacing_a_missing_file_stays_in_the_opening_drawing(native_picker: bool) {
let name = if native_picker { "different-drawing-picker" } else { "different-drawing-path" };
let (mut app, dir, _) = opened_without_links(name);
let missing = drive::fields::<MissingLinksDialog>(&app)["missing"][0].clone();
let id = missing["ids"][0].as_u64().unwrap();
let picker = crate::tests::picks::scripted(&mut app);
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let mut second_ids = Vec::new();
for name in ["second-one.png", "second-two.png"] {
let path = dir.join(name);
std::fs::write(&path, png([0, 200, 0])).unwrap();
let place = app.run("file.place", json!({"path": path.to_string_lossy()})).unwrap();
second_ids.push(place["ids"][0].as_u64().unwrap());
}
assert!(second_ids.contains(&id), "the same ID refers to a different linked file");
let params = json!({"ids": [id]});
let original_path = app.run("links.check", params.clone()).unwrap()["links"][0]["path"].clone();
app.run("document.activate", json!({"index": 0})).unwrap();
if native_picker {
drive::answer::<MissingLinksDialog>(&mut app, &[], true);
assert_eq!(picker.requests().len(), 1);
}
app.run("document.activate", json!({"index": 1})).unwrap();
let replacement = dir.join("replacement.png");
std::fs::write(&replacement, png([0, 0, 200])).unwrap();
let replacement = replacement.to_string_lossy();
if native_picker {
picker.answer(&[&replacement]);
drive::frame(&mut app);
drive::pump(&mut app);
} else {
drive::answer::<MissingLinksDialog>(&mut app, &[("path", json!(replacement))], true);
}
assert_eq!(app.session.active_index(), Some(1));
let after = app.run("links.check", params).unwrap()["links"][0]["path"].clone();
assert_eq!(after, original_path, "the second drawing must keep its original link");
assert_eq!(app.ui.status, "This dialog was opened in a different document.");
assert_eq!(drive::fields::<MissingLinksDialog>(&app)["missing"][0], missing);
app.run("document.activate", json!({"index": 0})).unwrap();
drive::answer::<MissingLinksDialog>(&mut app, &[("path", json!(replacement))], true);
assert_eq!(app.run("links.check", json!({})).unwrap()["missing"], 1, "the opening drawing can still replace its file");
assert_eq!(asked_name(&app), "b.png", "the remaining missing file is still offered");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn typed_missing_file_replacement_keeps_the_other_drawing_untouched() {
check_replacing_a_missing_file_stays_in_the_opening_drawing(false);
}
#[test]
fn delayed_missing_file_picker_keeps_the_other_drawing_untouched() {
check_replacing_a_missing_file_stays_in_the_opening_drawing(true);
}
#[test]
fn a_missing_file_folder_search_starts_only_in_the_opening_drawing() {
use crate::dialogs::find_links::FindLinksDialog;
let (mut app, dir, _) = opened_without_links("different-drawing-search");
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let folder = [("searchFolder", json!(dir.to_string_lossy()))];
drive::answer::<MissingLinksDialog>(&mut app, &folder, true);
assert!(drive::is_open::<MissingLinksDialog>(&app));
assert!(!drive::is_open::<FindLinksDialog>(&app));
assert_eq!(app.session.active_index(), Some(1));
app.run("document.activate", json!({"index": 0})).unwrap();
drive::answer::<MissingLinksDialog>(&mut app, &folder, true);
assert!(drive::is_open::<FindLinksDialog>(&app));
assert_eq!(app.session.active_index(), Some(0));
drive::answer::<FindLinksDialog>(&mut app, &[], false);
let _ = std::fs::remove_dir_all(dir);
}
/// Replace relinks the first file and asks about the next; Ignore keeps its preview.
#[test]
fn opening_without_linked_files_asks_to_replace_or_ignore_each() {
@@ -893,4 +984,52 @@ mod tests {
assert_eq!(app.run("links.check", json!({})).unwrap()["modified"], 1);
let _ = std::fs::remove_dir_all(dir);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn accepting_a_modified_link_offer_does_not_update_another_drawing() {
let dir = std::env::temp_dir().join(format!("vectorcraft-modified-switch-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut app = drive::app();
app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string())));
app.session.prefs.update_links = "askWhenModified".into();
let mut ids = vec![];
for name in ["first.png", "second.png"] {
let path = dir.join(name);
std::fs::write(&path, png([200, 0, 0])).unwrap();
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("file.place", json!({"path": path.to_string_lossy()})).unwrap();
let links = app.run("links.list", json!({})).unwrap();
ids.push(links["links"][0]["id"].as_u64().unwrap());
let stamp = std::fs::metadata(&path).unwrap().modified().unwrap();
std::fs::write(&path, png([0, 0, 200])).unwrap();
std::fs::OpenOptions::new()
.write(true)
.open(&path)
.unwrap()
.set_times(std::fs::FileTimes::new().set_modified(stamp + std::time::Duration::from_secs(2)))
.unwrap();
}
assert_eq!(ids[0], ids[1], "the same ID refers to different files");
let answer = |app: &mut VectorcraftApp| {
let question = crate::tests::picks::open_dialogs(app).pop().unwrap().id;
crate::tests::picks::answer_dialog(app, question, &[], true);
};
app.run("document.activate", json!({"index": 0})).unwrap();
ask_update_changed(&mut app, vec![json!(ids[0])]);
app.run("document.activate", json!({"index": 1})).unwrap();
assert_eq!(app.run("links.check", json!({})).unwrap()["modified"], 1);
answer(&mut app);
let foreign_modified = app.run("links.check", json!({})).unwrap()["modified"].clone();
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(app.run("links.check", json!({})).unwrap()["modified"], 1);
ask_update_changed(&mut app, vec![json!(ids[0])]);
answer(&mut app);
let original_modified = app.run("links.check", json!({})).unwrap()["modified"].clone();
let _ = std::fs::remove_dir_all(dir);
assert_eq!(foreign_modified, 1, "the second drawing's link still needs approval");
assert_eq!(original_modified, 0, "approval updates the first drawing's link");
}
}
+58 -1
View File
@@ -25,6 +25,7 @@ const TYPES: [&str; 5] = ["calligraphic", "scatter", "art", "bristle", "pattern"
/// It starts on Art when there is art, and it starts on Calligraphic otherwise.
pub fn open(app: &mut VectorcraftApp, ids: Option<Value>) -> Result<Value, String> {
let st = app.session.active().ok_or("no document open")?;
let (document, reverts) = (st.uid, st.reverts);
let art = match &ids {
Some(ids) => ids.as_array().is_some_and(|a| !a.is_empty()),
None => !st.selection.is_empty(),
@@ -36,7 +37,16 @@ pub fn open(app: &mut VectorcraftApp, ids: Option<Value>) -> Result<Value, Strin
// PLAN: `HostedParamDialog::new` takes (ctx, key, fields, build); the sheet's (KIND, title, build) has no such form.
let dialog =
HostedParamDialog::new(&ctx, KIND, fields, move |f| ParamDialog::new(KIND, title.clone(), rows.clone()).values(Bind::bound(f))).held_ok();
host::open_held(app, dialog, move |app, answer| confirm(app, &answer.fields, ids.clone())).ok_or("no window")?;
host::open_held(app, dialog, move |app, answer| {
let Some(source) = app.session.active().filter(|st| st.uid == document) else {
return Err(tl!("Return to the original drawing to make the brush").into());
};
if source.reverts != reverts {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").into());
}
confirm(app, &answer.fields, ids.clone())
})
.ok_or("no window")?;
Ok(Value::Null)
}
@@ -156,6 +166,53 @@ mod tests {
assert_eq!((&def["type"], &def["size"]), (&json!("calligraphic"), &json!(9.0)));
}
#[test]
fn the_new_brush_type_chooser_waits_for_its_source_drawing() {
let mut app = app();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
app.run("ui.newBrush", json!({})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let id = craft::ui::dialog::dialog_id(KIND);
app.dialogs().unwrap().with(|h| h.set_json_field(&ctx, id, "type", json!("scatter"))).unwrap();
app.run("file.new", json!({"width": 500, "height": 400})).unwrap();
app.run("shape.ellipse", json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap();
let error = super::super::tests_export::try_confirm(&mut app).expect_err("cannot take another drawing's artwork");
assert!(error.contains("original drawing"), "{error}");
assert_eq!(open_fields(&app).text("type"), Some("scatter"));
app.run("document.activate", json!({"index": 0})).unwrap();
press_ok(&mut app, json!({}));
assert_eq!(open_fields(&app).text("__type"), Some("scatter"));
}
#[test]
fn the_type_chooser_and_brush_options_require_a_new_opening_after_revert() {
for in_options in [false, true] {
let dir = vectorcraft_testkit::TempDir::new("new-brush-revert");
let mut app = app();
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let saved = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap()["id"].clone();
app.run("file.saveAs", json!({"path": dir.join("Saved.vectorcraft")})).unwrap();
app.run("shape.ellipse", json!({"x": 10, "y": 60, "width": 60, "height": 40})).unwrap();
app.run("ui.newBrush", json!({})).unwrap();
if in_options {
press_ok(&mut app, json!({"type": "art"}));
assert_eq!(open_fields(&app).text("__type"), Some("art"));
}
let source = app.session.active().unwrap();
let (uid, reverts) = (source.uid, source.reverts);
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [saved]})).unwrap();
let restored = app.session.active().unwrap();
assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1));
let before = (library(&mut app), undo_steps(&app));
let error = super::super::tests_export::try_confirm(&mut app).expect_err("an old brush approval is refused");
assert_eq!(error, "The document was reverted. Reopen this dialog to continue.");
assert_eq!((library(&mut app), undo_steps(&app)), before);
}
}
/// The new brush takes the art its Brush Options opened with: changing or clearing the
/// selection while the dialog is open does not change the art, and OK still makes the brush.
#[test]
@@ -18,6 +18,7 @@ pub const KIND: &str = "newColorGroup";
/// art is selected and no swatches are.
pub fn open(app: &mut VectorcraftApp, swatches: Vec<String>) -> Result<Value, String> {
let st = app.session.active().ok_or("no document open")?;
let (document, reverts) = (st.uid, st.reverts);
let art = !st.selection.is_empty();
let mut fields = DialogFields::new();
fields.set("name", st.doc.free_swatch_name("Color Group"));
@@ -37,6 +38,12 @@ pub fn open(app: &mut VectorcraftApp, swatches: Vec<String>) -> Result<Value, St
];
let dialog = hosted(&ctx, KIND, tl!("New Color Group"), fields, rows, false);
let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
let Some(source) = app.session.active().filter(|active| active.uid == document) else {
return Err(tl!("Create this color group in the document that opened the dialog.").to_owned());
};
if source.reverts != reverts {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
app.run("swatch.newGroup", params(&answer.fields, &swatches)).map(|_| ())
};
super::host::open_held(app, dialog, ok).ok_or(NO_WINDOW)?;
@@ -53,3 +60,75 @@ fn params(fields: &DialogFields, swatches: &[String]) -> Value {
json!({"name": name, "swatches": swatches})
}
}
#[cfg(test)]
mod tests {
use craft::ui::dialog::dialog_id;
use vectorcraft_engine::Session;
use super::*;
#[test]
fn a_color_group_draft_cannot_change_the_drawing_restored_by_revert() {
for swatches in [vec!["Saved Ink".to_owned()], Vec::new()] {
let dir = vectorcraft_testkit::TempDir::new("new-color-group-revert");
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()["id"].clone();
app.run("paint.setFill", json!({"ids": [id], "color": "#123456"})).unwrap();
app.run("swatch.new", json!({"name": "Saved Ink", "color": "#446688"})).unwrap();
app.run("file.saveAs", json!({"path": dir.join("Saved.vectorcraft")})).unwrap();
app.run("paint.setFill", json!({"ids": [id], "color": "#abcdef"})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
let before = app.session.active().unwrap();
let (uid, reverts) = (before.uid, before.reverts);
open(&mut app, swatches).unwrap();
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
let loaded = app.session.active().unwrap();
assert_eq!((loaded.uid, loaded.reverts), (uid, reverts + 1));
let (saved, undo) = (loaded.doc.clone(), loaded.history.undo.len());
let refused = crate::dialogs::tests_export::try_confirm(&mut app);
let current = app.session.active().unwrap();
assert_eq!(current.doc, saved);
assert_eq!(current.history.undo.len(), undo);
assert_eq!(refused.unwrap_err(), "The document was reverted. Reopen this dialog to continue.");
}
}
#[test]
fn color_group_does_not_convert_the_other_drawings_artwork() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
for color in ["#123456", "#446688"] {
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 50, "y": 50, "width": 25, "height": 25})).unwrap()["id"].clone();
app.run("paint.setFill", json!({"ids": [id], "color": color})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
}
let activate = |app: &mut VectorcraftApp, index| app.run("document.activate", json!({"index": index})).unwrap();
let other = app.session.active().unwrap().doc.clone();
let undo = app.session.active().unwrap().history.undo.len();
activate(&mut app, 0);
open(&mut app, Vec::new()).unwrap();
activate(&mut app, 1);
let ctx = app.ui_ctx.clone().unwrap();
let dialogs = app.dialogs().unwrap();
let id = dialog_id(KIND);
let confirm = |app: &mut VectorcraftApp| {
dialogs.with(|host| host.confirm_by_id(&ctx, id));
crate::dialogs::host::pump(app, &ctx);
crate::testing::app_frame(app, &ctx, Default::default());
};
confirm(&mut app);
let current = app.session.active().unwrap();
assert_eq!(current.doc, other, "the other drawing keeps its swatches and process fills");
assert_eq!(current.history.undo.len(), undo);
activate(&mut app, 0);
confirm(&mut app);
assert!(app.session.active().unwrap().doc.swatch_groups.iter().any(|group| group.name == "Color Group"));
}
}
+64 -1
View File
@@ -296,7 +296,8 @@ impl DocumentSettings for VcNewDocument {
}
});
});
Row::new().show(ui, |ui, _| {
// Host viewports below the desktop main window's 800-point minimum need this row to wrap.
Row::new().wrap(ui.ctx().content_rect().width() < 800.0).show(ui, |ui, _| {
Field::new(height.clone()).show(ui, |ui, _| size_field(ui, &height, &mut s.height, lengths));
Field::new(orientation.clone()).show(ui, |ui, _| {
let entries = [
@@ -1109,4 +1110,66 @@ mod tests {
assert!(!dir.join("Print.vectorcraft").exists());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn orientation_remains_clickable_in_compact_web_windows() {
use crate::i18n::LangExt;
use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
for code in ["en", "de", "fr", "el"] {
for width in [800.0, 640.0, 540.0, 799.0, 801.0] {
let services = crate::Services { download: Some(Box::new(|_: &str, _: &[u8]| Ok(()))), ..Default::default() };
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services));
app.session.prefs.interface_language = code.into();
let lang = crate::i18n::Lang::from_code(code).unwrap();
crate::i18n::set_current(lang);
open(&mut app);
set(&app, "width", json!(400)).unwrap();
set(&app, "height", json!(600)).unwrap();
set(&app, "units", json!("pt")).unwrap();
let context = ctx(&app);
let size = vec2(width, 500.0);
let screen = Rect::from_min_size(Pos2::ZERO, size);
let mut time = 0.0;
let mut draw = |app: &mut VectorcraftApp, events| {
time += 0.25;
let out = crate::testing::app_frame(
app,
&context,
RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() },
);
assert_eq!(context.content_rect().size(), size, "the web host keeps the requested viewport");
out
};
for _ in 0..6 {
draw(&mut app, vec![]);
}
let original = fields(&app);
let out = draw(&mut app, vec![]);
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
let bounds = nodes
.iter()
.find(|(_, node)| node.role() == egui::accesskit::Role::RadioButton && node.label() == Some(crate::i18n::tr(lang, "Landscape")))
.and_then(|(_, node)| node.bounds())
.expect("Landscape is shown");
let at = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32);
draw(&mut app, vec![Event::PointerMoved(at)]);
for pressed in [true, false] {
draw(&mut app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
draw(&mut app, vec![]);
let turned = fields(&app);
assert_eq!(turned["width"], original["height"], "{code} {width}: Landscape swaps the page width");
assert_eq!(turned["height"], original["width"], "{code} {width}: Landscape swaps the page height");
for _ in 0..3 {
draw(&mut app, vec![]);
}
for idle in 0..3 {
let output = draw(&mut app, vec![]);
assert_eq!(output.platform_output.num_completed_passes, 1, "{code} {width}: idle frame {idle} repeats layout");
}
}
}
crate::i18n::set_current(crate::i18n::Lang::EN);
}
}
+92 -3
View File
@@ -26,13 +26,17 @@ pub(crate) struct Open {
pub(crate) id: DialogId,
/// The name the dialog proposes for its colour.
auto: String,
/// The drawing that supplied the paint and the possible colour group.
document: u64,
}
/// Open New Swatch for the active paint, going into color `group`. A color opens as a spot color
/// with `spot`, and as a global process color with `global` alone.
pub fn open(app: &mut VectorcraftApp, spot: bool, global: bool, group: Option<&str>) -> Result<Value, String> {
let paint = crate::panels::active_paint(app);
let name = app.session.active().ok_or("no document open")?.doc.new_swatch_name(&paint);
let source = app.session.active().ok_or("no document open")?;
let document = source.uid;
let name = source.doc.new_swatch_name(&paint);
let mut fields = DialogFields::new();
fields.set("name", name.as_str());
let (rows, kept) = match &paint {
@@ -48,20 +52,24 @@ pub fn open(app: &mut VectorcraftApp, spot: bool, global: bool, group: Option<&s
let dialog = hosted(&ctx, KIND, tl!("New Swatch"), fields, rows, false);
let group = group.unwrap_or_default().to_owned();
let ok = move |app: &mut VectorcraftApp, answer: &ParamResult| -> Result<(), String> {
if app.session.active().is_none_or(|st| st.uid != document) {
return Err(tl!("Return to the original drawing to create this swatch").into());
}
app.run("swatch.new", params(kept.as_ref(), &group, &answer.fields))?;
app.ui.new_swatch = None;
Ok(())
};
let options = HeldOptions { parent: None, cancel: Some(Box::new(|app: &mut VectorcraftApp| app.ui.new_swatch = None)) };
let id = open_held_with(app, dialog, ok, options).ok_or(NO_WINDOW)?;
app.ui.new_swatch = Some(Open { id, auto: name });
app.ui.new_swatch = Some(Open { id, auto: name, document });
Ok(Value::Null)
}
/// Keeps the default name following the colour while the name has not been edited, and applies the corrections the
/// colour row asked for.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some((id, auto)) = app.ui.new_swatch.as_ref().map(|o| (o.id, o.auto.clone())) else { return };
let Some(open) = app.ui.new_swatch.as_ref().filter(|o| app.session.active().is_some_and(|st| st.uid == o.document)) else { return };
let (id, auto) = (open.id, open.auto.clone());
super::swatch_options::correct(app, id);
let Some(fields) = with_dialog(app, id, |d| d.fields().clone()) else { return };
if !fields.contains("color") || fields.text("name") != Some(auto.as_str()) {
@@ -105,12 +113,93 @@ mod tests {
(ctx, app)
}
#[test]
fn a_new_swatch_stays_with_its_opening_drawing() {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
let ctx = app.ui_ctx.clone().unwrap();
let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 500.0)));
let frame = |app: &mut VectorcraftApp| {
crate::testing::app_frame(app, &ctx, egui::RawInput { screen_rect, ..Default::default() });
};
let new_file = |app: &mut VectorcraftApp| {
app.run("file.new", json!({"width":100,"height":100,"colorMode":"rgb"})).unwrap();
app.session.doc().unwrap().uid
};
let source = new_file(&mut app);
let other = new_file(&mut app);
assert_ne!(source, other);
app.run("document.activate", json!({"index":0})).unwrap();
app.run("paint.setFill", json!({"color":"#336699"})).unwrap();
let undo_source = app.session.doc().unwrap().history.undo.len();
for _ in 0..4 {
frame(&mut app);
}
app.run("ui.newSwatch", json!({})).unwrap();
let id = app.ui.new_swatch.as_ref().unwrap().id;
let name = "Opening Drawing Swatch";
with_dialog(&app, id, |d| d.set_field("name", FieldValue::Text(name.to_owned()))).unwrap();
for _ in 0..4 {
frame(&mut app);
}
app.run("document.activate", json!({"index":1})).unwrap();
let undo_other = app.session.doc().unwrap().history.undo.len();
assert_eq!(app.session.doc().unwrap().uid, other);
app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id));
frame(&mut app);
let st = app.session.doc().unwrap();
assert!(st.doc.swatch(name).is_none(), "OK created the opening drawing's swatch in the other drawing");
assert_eq!(st.history.undo.len(), undo_other);
assert_eq!(app.ui.new_swatch.as_ref().unwrap().id, id, "the refused draft remains open");
app.run("document.activate", json!({"index":0})).unwrap();
assert_eq!(app.session.doc().unwrap().uid, source);
app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id));
frame(&mut app);
let st = app.session.doc().unwrap();
assert_eq!(st.doc.swatch(name).and_then(|s| s.paint.color()).map(|c| c.to_hex()).as_deref(), Some("#336699"));
assert_eq!(st.history.undo.len(), undo_source + 1);
assert!(app.ui.new_swatch.is_none());
app.run("edit.undo", json!({})).unwrap();
assert!(app.session.doc().unwrap().doc.swatch(name).is_none());
}
/// Answers OK in the open dialog and lets the host run it.
fn ok(app: &mut VectorcraftApp, ctx: &egui::Context) {
app.dialogs().unwrap().with(|h| h.confirm_by_id(ctx, dialog_id(KIND)));
crate::dialogs::host::pump(app, ctx);
}
#[test]
fn an_untouched_name_uses_the_opening_drawings_swatches() {
use vectorcraft_color::Color;
let (ctx, mut app) = setup();
let suggested = |app: &VectorcraftApp, c: Color| app.session.doc().unwrap().doc.new_swatch_name(&Paint::solid(c));
let color = Color::from_hex("#336699").unwrap();
let name = suggested(&app, color);
app.run("file.new", json!({"width":100,"height":100})).unwrap();
app.run("swatch.new", json!({"name":name,"color":"#445566"})).unwrap();
assert_ne!(suggested(&app, color), name, "the other drawing would choose a different name");
app.run("document.activate", json!({"index":0})).unwrap();
app.run("paint.setFill", json!({"color":"#336699"})).unwrap();
app.run("ui.newSwatch", json!({})).unwrap();
let id = app.ui.new_swatch.as_ref().unwrap().id;
let draft_name = |app: &VectorcraftApp| with_dialog(app, id, |d| d.fields().text("name").unwrap().to_owned()).unwrap();
assert_eq!(draft_name(&app), name);
app.run("document.activate", json!({"index":1})).unwrap();
pump(&mut app, &ctx);
assert_eq!(draft_name(&app), name);
app.run("document.activate", json!({"index":0})).unwrap();
let color = Color::from_hex("#6789ab").unwrap();
with_dialog(&app, id, |d| d.set_field("color", FieldValue::Json(json!(color)))).unwrap();
pump(&mut app, &ctx);
assert_eq!(draft_name(&app), suggested(&app, color));
}
#[test]
fn a_warning_corrects_the_new_colour_only_until_ok() {
let (ctx, mut app) = setup();
+65 -7
View File
@@ -29,6 +29,7 @@ pub(crate) struct NewTextStyle {
opening: Opening,
/// Whether the dialog makes a paragraph style.
pub(crate) para: bool,
document: u64,
target: Value,
}
@@ -54,7 +55,8 @@ style_dialog!(NewTextStyle, KIND);
/// Open New Character Style (`para`: New Paragraph Style) with the name `charStyle.new` would give
/// the style, to make it from the text `target` names.
pub fn open(app: &mut VectorcraftApp, para: bool, target: Value) -> Result<Value, String> {
let doc = &app.session.active().ok_or("no document open")?.doc;
let state = app.session.active().ok_or("no document open")?;
let (document, doc) = (state.uid, &state.doc);
let name = vectorcraft_engine::cmd::textstyles::new_style_name(doc, para);
let mut target = if target.is_object() { target } else { json!({}) };
let selected_attrs = vectorcraft_engine::cmd::textstyles::target_style_attrs(&app.session, &target, para);
@@ -69,7 +71,7 @@ pub fn open(app: &mut VectorcraftApp, para: bool, target: Value) -> Result<Value
let inner = char_style_options::hosted(KIND, tl!("New Character Style"), &opening, &name);
(Opening::Char(opening), inner)
};
app.dialogs().ok_or("no window")?.with(|host| host.open(NewTextStyle { inner, opening, para, target }));
app.dialogs().ok_or("no window")?.with(|host| host.open(NewTextStyle { inner, opening, para, document, target }));
Ok(json!({ "dialog": KIND }))
}
@@ -78,7 +80,7 @@ pub fn open(app: &mut VectorcraftApp, para: bool, target: Value) -> Result<Value
/// into view when it next draws.
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let Some((para, frame)) = dialogs.with(|host| host.get_mut::<NewTextStyle>().map(|d| (d.para, d.frame()))) else {
let Some((para, document, frame)) = dialogs.with(|host| host.get_mut::<NewTextStyle>().map(|d| (d.para, d.document, d.frame()))) else {
// The dialog closed: its answer or cancel has nothing left for the app to do.
let _ = dialogs.with(|host| host.take::<NewTextStyle>());
return;
@@ -86,12 +88,18 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
if !frame.ok {
return;
}
let made = frame.params.and_then(|params| app.run(if para { "paraStyle.new" } else { "charStyle.new" }, params));
let made = if app.session.active().is_some_and(|doc| doc.uid == document) {
frame.params.and_then(|params| app.run(if para { "paraStyle.new" } else { "charStyle.new" }, params))
} else if app.session.documents().iter().any(|doc| doc.uid == document) {
Err("switch back to the document where this style was opened".into())
} else {
Err("the document where this style was opened has closed".into())
};
let answer = match &made {
Ok(v) => {
if let Some((uid, name)) = app.session.active().and_then(|doc| v["name"].as_str().map(|name| (doc.uid, name.to_string()))) {
app.ui.text_styles.made.retain(|(pending_uid, pending_para, _)| *pending_uid != uid || *pending_para != para);
app.ui.text_styles.made.push((uid, para, name));
if let Some(name) = v["name"].as_str() {
app.ui.text_styles.made.retain(|(pending_uid, pending_para, _)| *pending_uid != document || *pending_para != para);
app.ui.text_styles.made.push((document, para, name.to_string()));
}
Ok(())
}
@@ -103,3 +111,53 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
}
});
}
#[cfg(test)]
mod tests {
use craft::ui::dialog::{HeldOk, StackDialog};
use vectorcraft_engine::Session;
use super::*;
fn style_exists(app: &VectorcraftApp, para: bool, name: &str) -> bool {
let doc = &app.session.doc().unwrap().doc;
if para { doc.para_styles.iter().any(|style| style.name == name) } else { doc.char_styles.iter().any(|style| style.name == name) }
}
fn assert_style_stays_in_its_opening_document(para: bool) {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
let opening = app.session.doc().unwrap().uid;
app.run(if para { "ui.newParaStyle" } else { "ui.newCharStyle" }, json!({})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let host = app.dialogs().unwrap();
let dialog = host.with(|h| h.get::<NewTextStyle>().unwrap().id());
let name = "Opening Document Style";
host.with(|h| h.set_json_field(&ctx, dialog, "name", json!(name))).unwrap();
app.run("file.new", json!({"width": 300, "height": 100})).unwrap();
assert_ne!(app.session.doc().unwrap().uid, opening);
host.with(|h| h.confirm_by_id(&ctx, dialog));
pump(&mut app, &ctx);
assert!(!style_exists(&app, para, name), "OK must leave styles in the other document unchanged");
assert!(app.ui.text_styles.made.is_empty(), "the other document must not highlight a style");
assert!(matches!(host.with(|h| h.held_state(dialog)), Some(HeldOk::Refused(_))));
app.run("document.activate", json!({"index": 0})).unwrap();
host.with(|h| h.confirm_by_id(&ctx, dialog));
pump(&mut app, &ctx);
assert!(style_exists(&app, para, name), "the original document can accept the same draft");
assert_eq!(app.ui.text_styles.made, [(opening, para, name.to_string())]);
}
#[test]
fn new_character_style_confirmation_stays_in_its_document() {
assert_style_stays_in_its_opening_document(false);
}
#[test]
fn new_paragraph_style_confirmation_stays_in_its_document() {
assert_style_stays_in_its_opening_document(true);
}
}
+1 -1
View File
@@ -30,7 +30,7 @@ pub(crate) struct ObjectDialogs {
/// The open Blend Options dialog's live preview.
pub blend: Option<LivePreview>,
/// The open Indexed Color dialog's live preview.
pub indexed: Option<LivePreview>,
pub indexed: Option<indexed_color::Open>,
/// The open Gap Options dialog's live preview.
pub gaps: Option<live_paint_gaps::Open>,
/// The Properties section's pending colour pick: dialog id, field key and target dimension.
+147 -30
View File
@@ -32,7 +32,7 @@ use craft::ui::sections::GroupBox;
use craft::ui::text::{NumberField, StepArrows};
use egui::{Context, Ui};
use serde_json::{Value, json};
use vectorcraft_doc::NodeKind;
use vectorcraft_doc::{NodeId, NodeKind};
use crate::VectorcraftApp;
@@ -98,7 +98,8 @@ pub struct Mosaic {
pub struct ObjectMosaicDialog {
id: DialogId,
values: Mosaic,
/// The size (pt) of the image as of the last [`sync`]; the last size read while none is selected.
source: MosaicSource,
/// The last size (pt) read while the opening image was selected.
image: (f64, f64),
/// Whether an image is selected.
selected: bool,
@@ -115,12 +116,42 @@ fn label(text: &str) -> Label {
text.to_owned().into()
}
/// The size (pt) of the first selected image, which the mosaic is made from.
fn image_size(app: &VectorcraftApp) -> Option<(f64, f64)> {
/// The selected raster and the drawing contents it belongs to.
#[derive(Clone, Copy, PartialEq, Eq)]
struct MosaicSource {
document: u64,
reverts: u64,
history_restores: u64,
image: NodeId,
}
impl MosaicSource {
fn size(self, app: &VectorcraftApp) -> Result<(f64, f64), String> {
let st = app
.session
.active()
.filter(|st| st.uid == self.document)
.ok_or_else(|| tl!("Return to the original drawing to create the mosaic.").to_owned())?;
if st.reverts != self.reverts {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
if st.history_restores != self.history_restores {
return Err(tl!("Reopen Create Object Mosaic after Undo or Redo.").to_owned());
}
match selected_image(app) {
Some((source, size)) if source == self => Ok(size),
None => Err(NO_IMAGE.to_owned()),
_ => Err(tl!("Select the original image to create the mosaic.").to_owned()),
}
}
}
/// The first selected image and its size in points, as the mosaic command reads them.
fn selected_image(app: &VectorcraftApp) -> Option<(MosaicSource, (f64, f64))> {
let st = app.session.active()?;
let node = st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).find(|n| matches!(n.kind, NodeKind::Image(_)))?;
let b = node.geometric_bounds()?;
Some((b.width(), b.height()))
Some((MosaicSource { document: st.uid, reverts: st.reverts, history_restores: st.history_restores, image: node.id }, (b.width(), b.height())))
}
/// Open the dialog on the selected image, with the values `given` holds (the menu item's params, or
@@ -128,7 +159,7 @@ fn image_size(app: &VectorcraftApp) -> Option<(f64, f64)> {
/// command's defaults for the rest. With no image selected, or with params the command refuses,
/// nothing opens and the error says why.
pub fn open(app: &mut VectorcraftApp, given: &Value) -> Result<Value, String> {
let Some((w, h)) = image_size(app) else { return Err(NO_IMAGE.into()) };
let Some((source, (w, h))) = selected_image(app) else { return Err(NO_IMAGE.into()) };
let none = json!({});
let given = if given.is_null() { &none } else { given };
app.session.check_params(COMMAND, given).map_err(|e| e.to_string())?;
@@ -161,18 +192,19 @@ pub fn open(app: &mut VectorcraftApp, given: &Value) -> Result<Value, String> {
};
let dialogs = app.dialogs().ok_or("no window")?;
let lengths = crate::canvas::general_lengths(app);
dialogs.with(|host| host.open(ObjectMosaicDialog::new(values, (w, h), lengths)));
dialogs.with(|host| host.open(ObjectMosaicDialog::new(values, source, (w, h), lengths)));
Ok(json!({ "dialog": KIND }))
}
/// Pushes the selected image's size and the document's length units into the open dialog. A frame runs
/// Pushes the opening image's current size and length units into the open dialog. A frame runs
/// it before the dialogs, and `ui.dialog.*` before each method.
pub(crate) fn sync(app: &mut VectorcraftApp) {
let Some(dialogs) = app.dialogs() else { return };
let size = image_size(app);
let selected = selected_image(app);
let lengths = crate::canvas::general_lengths(app);
dialogs.with(|host| {
if let Some(dialog) = host.get_mut::<ObjectMosaicDialog>() {
let size = selected.filter(|(source, _)| *source == dialog.source).map(|(_, size)| size);
dialog.sync(size, lengths);
}
});
@@ -181,9 +213,9 @@ pub(crate) fn sync(app: &mut VectorcraftApp) {
/// What the dialog asked of the app.
enum Work {
/// Use Ratio: the counts for these values.
Ratio(Mosaic, (f64, f64)),
Ratio(Mosaic, MosaicSource),
/// The held OK: the command for these values.
Run(Mosaic, (f64, f64)),
Run(Mosaic, MosaicSource),
}
/// Runs what the open dialog asked of the app, outside the host's lock: Use Ratio's counts, and the
@@ -195,17 +227,19 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
let _ = host.take::<ObjectMosaicDialog>();
let dialog = host.get_mut::<ObjectMosaicDialog>()?;
if std::mem::take(&mut dialog.use_ratio) {
return Some(Work::Ratio(dialog.values.clone(), dialog.image));
return Some(Work::Ratio(dialog.values.clone(), dialog.source));
}
dialog.held.take().map(|values| Work::Run(values, dialog.image))
dialog.held.take().map(|values| Work::Run(values, dialog.source))
});
match work {
None => {}
Some(Work::Ratio(mut values, image)) => {
follow_ratio(&mut values, image);
let mut p = params(&values, image);
p["useRatio"] = json!(values.side.key());
let counts = vectorcraft_engine::cmd::mosaic_counts(&app.session, &p).map_err(|e| e.to_string());
Some(Work::Ratio(mut values, source)) => {
let counts = source.size(app).and_then(|image| {
follow_ratio(&mut values, image);
let mut p = params(&values, image);
p["useRatio"] = json!(values.side.key());
vectorcraft_engine::cmd::mosaic_counts(&app.session, &p).map_err(|e| e.to_string())
});
dialogs.with(|host| {
let Some(dialog) = host.get_mut::<ObjectMosaicDialog>() else { return };
match counts {
@@ -218,13 +252,14 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
}
});
}
Some(Work::Run(mut values, image)) => {
follow_ratio(&mut values, image);
// With no image selected the dialog says what it needs, not that the command is unavailable.
let answer = match image_size(app) {
Some(_) => app.run(COMMAND, params(&values, image)).map(|_| ()).map_err(Label::from),
None => Err(Label::from(NO_IMAGE.to_string())),
};
Some(Work::Run(mut values, source)) => {
let answer = source
.size(app)
.and_then(|image| {
follow_ratio(&mut values, image);
app.run(COMMAND, params(&values, image)).map(|_| ())
})
.map_err(Label::from);
dialogs.with(|host| {
if let Some(dialog) = host.get_mut::<ObjectMosaicDialog>() {
dialog.held.answer(answer);
@@ -235,16 +270,26 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &Context) {
}
impl ObjectMosaicDialog {
fn new(values: Mosaic, image: (f64, f64), lengths: LengthUnits) -> Self {
ObjectMosaicDialog { id: dialog_id(KIND), values, image, selected: true, lengths, note: None, use_ratio: false, held: HeldAnswer::new() }
fn new(values: Mosaic, source: MosaicSource, image: (f64, f64), lengths: LengthUnits) -> Self {
ObjectMosaicDialog {
id: dialog_id(KIND),
values,
source,
image,
selected: true,
lengths,
note: None,
use_ratio: false,
held: HeldAnswer::new(),
}
}
/// `size` is the selected image's size, `None` while none is selected: the last size stays and a
/// switch to percentages is refused until one is.
fn sync(&mut self, size: Option<(f64, f64)>, lengths: LengthUnits) {
self.lengths = lengths;
self.selected = size.is_some();
if let Some(size) = size {
self.lengths = lengths;
self.image = size;
if self.note.as_ref().is_some_and(|n| n.as_str() == NO_IMAGE) {
self.note = None;
@@ -375,7 +420,7 @@ impl StackDialog for ObjectMosaicDialog {
}
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<()>> {
let ObjectMosaicDialog { id: _, values, image, selected, lengths, note, use_ratio, held } = self;
let ObjectMosaicDialog { values, image, selected, lengths, note, use_ratio, held, .. } = self;
// A refusal shows until a value it refused changes.
if held.refusal().is_some_and(|(_, refused)| refused != values) {
held.clear_refusal();
@@ -557,11 +602,15 @@ mod tests {
/// An app with a 100 × 50 pt embedded image selected.
fn app_with_image() -> VectorcraftApp {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
add_image(&mut app);
app
}
fn add_image(app: &mut VectorcraftApp) {
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 50})).unwrap();
app.run("paint.setStroke", json!({"none": true})).unwrap();
app.run("object.rasterize", json!({"ppi": 72})).unwrap();
app
}
/// The mosaic group's size and tile count.
@@ -851,4 +900,72 @@ mod tests {
ok(&mut app);
assert_eq!(mosaic(&app).map(|m| m.2), Some(30));
}
#[test]
fn held_mosaic_does_not_delete_another_drawings_raster() {
let mut app = app_with_image();
open(&mut app, &json!({"columns": 2, "rows": 2, "deleteRaster": true})).unwrap();
add_image(&mut app);
let second = image_id(&app);
let undo = app.session.active().unwrap().history.undo.len();
ok(&mut app);
assert_eq!(mosaic(&app), None);
assert_eq!(image_id(&app), second);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(is_open(&mut app));
app.run("document.activate", json!({"index": 0})).unwrap();
ok(&mut app);
assert_eq!(mosaic(&app), Some((100.0, 50.0, 4)));
assert!(!is_open(&mut app));
}
#[test]
fn held_mosaic_does_not_delete_a_raster_restored_by_revert() {
let mut app = app_with_image();
let source = image_id(&app);
let dir = vectorcraft_testkit::TempDir::new("mosaic-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
app.run("object.move", json!({"dx": 10, "dy": 0})).unwrap();
open(&mut app, &json!({"columns": 2, "rows": 2, "deleteRaster": true})).unwrap();
app.run("file.revert", json!({"confirmed": true})).unwrap();
app.run("select.set", json!({"ids": [source]})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
ok(&mut app);
assert_eq!(mosaic(&app), None);
assert_eq!(image_id(&app), source);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(is_open(&mut app));
open(&mut app, &json!({"columns": 2, "rows": 2, "deleteRaster": true})).unwrap();
ok(&mut app);
assert_eq!(mosaic(&app), Some((100.0, 50.0, 4)));
assert!(!is_open(&mut app));
}
#[test]
fn held_mosaic_does_not_delete_a_raster_created_after_undo() {
let mut app = app_with_image();
let source = image_id(&app);
open(&mut app, &json!({"columns": 2, "rows": 2, "deleteRaster": true})).unwrap();
app.run("edit.undo", json!({})).unwrap();
assert!(app.session.active().unwrap().doc.node(NodeId(source)).is_none_or(|node| !matches!(node.kind, NodeKind::Image(_))));
app.run("object.rasterize", json!({"ppi": 72})).unwrap();
assert_eq!(image_id(&app), source, "the new raster repeats the same ID and pixels");
let undo = app.session.active().unwrap().history.undo.len();
ok(&mut app);
assert_eq!(mosaic(&app), None, "the old approval cannot delete the new raster");
assert_eq!(image_id(&app), source);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(is_open(&mut app));
open(&mut app, &json!({"columns": 2, "rows": 2, "deleteRaster": true})).unwrap();
ok(&mut app);
assert_eq!(mosaic(&app), Some((100.0, 50.0, 4)));
assert!(!is_open(&mut app));
}
}
@@ -58,3 +58,143 @@ pub fn open(app: &mut VectorcraftApp) -> Value {
}
json!({ "dialog": KIND })
}
/// The compact tool options expose translated Pivot corners and accept actual edits.
#[cfg(test)]
#[test]
fn compact_objects_on_path_options_pivot_rotate_reset_and_save() {
use egui::accesskit::{Node, Role, TreeUpdate};
use egui::{Event, Key, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
use vectorcraft_engine::Session;
fn bounds(node: &Node) -> Option<Rect> {
let b = node.bounds()?;
Some(Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)))
}
fn plain_label(label: &str) -> &str {
label.trim_end().trim_end_matches([':', ':']).trim_end()
}
const PIVOT_NAMES: [&str; 9] = ["Top Left", "Top", "Top Right", "Left", "Center", "Right", "Bottom Left", "Bottom", "Bottom Right"];
let screen = Rect::from_min_size(Pos2::ZERO, vec2(800.0, 500.0));
let mut untranslated = Vec::new();
for lang in ["en", "de", "fr", "ja"] {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.session.prefs.interface_language = lang.into();
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("tool.setOption", json!({"tool": TOOL, "values": {"pivot": 1,"rotate": 17}})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp, events: Vec<Event>| {
time += 0.1;
let raw = RawInput { events, time: Some(time), screen_rect: Some(screen), focused: true, ..Default::default() };
crate::testing::app_frame(app, &ctx, raw).platform_output.accesskit_update.unwrap()
};
let settle = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec<Event>) -> TreeUpdate| {
for _ in 0..5 {
frame(app, vec![]);
}
frame(app, vec![])
};
let click = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec<Event>) -> TreeUpdate, pos| {
frame(app, vec![Event::PointerMoved(pos)]);
for pressed in [true, false] {
frame(app, vec![Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
frame(app, vec![]);
};
let press = |app: &mut VectorcraftApp, frame: &mut dyn FnMut(&mut VectorcraftApp, Vec<Event>) -> TreeUpdate, key, modifiers| {
for pressed in [true, false] {
frame(app, vec![Event::ModifiersChanged(modifiers), Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }]);
}
};
let draft = |app: &VectorcraftApp| {
app.dialogs()
.unwrap()
.with(|host| host.get::<HostedParamDialog>().map(|d| (d.fields().int("pivot").unwrap(), d.fields().number("rotate").unwrap())))
};
let actual = |app: &VectorcraftApp| {
let options = app.session.tool_options_of(TOOL);
(options["pivot"].as_i64().unwrap(), options["rotate"].as_f64().unwrap())
};
settle(&mut app, &mut frame);
for save in [false, true] {
assert_eq!(app.run("tool.options", json!({"tool": TOOL})).unwrap()["dialog"], KIND);
let tree = settle(&mut app, &mut frame);
let by_name = |role, label: &str| {
tree.nodes
.iter()
.find(|(_, n)| {
n.role() == role
&& n.label().is_some_and(|actual| {
plain_label(actual) == plain_label(label)
|| (role == Role::RadioGroup && plain_label(actual) == plain_label(crate::i18n::t("Pivot:")))
})
})
.and_then(|(_, n)| bounds(n))
.unwrap_or_else(|| {
let names: Vec<_> = tree.nodes.iter().filter(|(_, n)| n.role() == role).filter_map(|(_, n)| n.label()).collect();
panic!("{lang}: missing {role:?} {label:?} in {names:?}")
})
};
let title = tool_options::title(TOOL);
let modal = by_name(Role::Dialog, title.as_str());
let picker = by_name(Role::RadioGroup, crate::i18n::t("Reference Point"));
let rotate = by_name(Role::SpinButton, crate::i18n::t("Rotate:"));
let reset = by_name(Role::Button, crate::i18n::t("Reset"));
let footer = by_name(Role::Button, crate::i18n::t(if save { "Save" } else { "Cancel" }));
assert!(screen.expand(0.5).contains_rect(modal), "{lang}: modal {modal:?} off screen");
for rect in [picker, rotate, reset, footer] {
assert!(rect.is_positive() && modal.expand(0.5).contains_rect(rect), "{lang}: {rect:?} outside modal {modal:?}");
}
let mut cells: Vec<_> = tree
.nodes
.iter()
.filter(|(_, n)| n.role() == Role::RadioButton)
.filter_map(|(_, n)| Some((n.label()?, bounds(n)?)))
.filter(|(_, rect)| picker.expand(0.5).contains(rect.center()))
.collect();
cells.sort_by(|(_, a), (_, b)| a.center().y.total_cmp(&b.center().y).then(a.center().x.total_cmp(&b.center().x)));
eprintln!(
"{lang}, save {save}: modal {modal:?}, pivot {picker:?}, cells {cells:?}, Rotate {rotate:?}, Reset {reset:?}, footer {footer:?}"
);
assert_eq!(cells.len(), 9, "{lang}: all Pivot options");
if save {
for ((name, _), legacy) in cells.iter().zip(PIVOT_NAMES) {
let expected = crate::i18n::t(legacy);
if expected != legacy && *name != expected {
untranslated.push(format!("{lang}: {name:?} instead of {expected:?}"));
}
}
}
assert!(cells.iter().all(|(_, cell)| picker.expand(0.5).contains_rect(*cell)), "{lang}: all cells lie in the picker");
assert_eq!(draft(&app), Some((1, 17.0)), "{lang}: opens from saved tool preferences");
click(&mut app, &mut frame, cells[8].1.center());
assert_eq!(draft(&app), Some((8, 17.0)), "{lang}: bottom-right physical pointer");
click(&mut app, &mut frame, rotate.center());
press(&mut app, &mut frame, Key::A, Modifiers::COMMAND);
frame(&mut app, vec![Event::ModifiersChanged(Modifiers::NONE), Event::Text("42".to_owned())]);
press(&mut app, &mut frame, Key::Tab, Modifiers::NONE);
settle(&mut app, &mut frame);
assert_eq!(draft(&app), Some((8, 42.0)), "{lang}: real Rotate keyboard edit");
if !save {
click(&mut app, &mut frame, reset.center());
assert_eq!(draft(&app), Some((4, 0.0)), "{lang}: pointer Reset keeps the dialog open and resets both settings");
}
assert_eq!(actual(&app), (1, 17.0), "{lang}: only a draft before accepting");
click(&mut app, &mut frame, footer.center());
settle(&mut app, &mut frame);
assert_eq!(draft(&app), None, "{lang}: footer closes the dialog");
assert_eq!(actual(&app), if save { (8, 42.0) } else { (1, 17.0) }, "{lang}: footer persistence");
}
app.run("tool.options", json!({"tool": TOOL})).unwrap();
settle(&mut app, &mut frame);
assert_eq!(draft(&app), Some((8, 42.0)), "{lang}: reopened saved values");
press(&mut app, &mut frame, Key::Escape, Modifiers::NONE);
settle(&mut app, &mut frame);
assert_eq!(draft(&app), None, "{lang}: Escape dismisses reopened options");
crate::i18n::set_current(crate::i18n::Lang::EN);
}
assert!(untranslated.is_empty(), "localized Pivot names were lost: {untranslated:?}");
}
+2 -2
View File
@@ -48,7 +48,7 @@ fn params(boards: &Boards, fields: &DialogFields) -> Vec<Param> {
let ppi = number(fields, "ppi").unwrap_or(RESOLUTIONS[1]);
let at = RESOLUTIONS.iter().position(|r| *r == ppi).unwrap_or(1);
let board = (number(fields, "artboard").unwrap_or(0.0).max(0.0) as usize).min(boards.names.len().saturating_sub(1));
let resolutions = RESOLUTIONS.iter().zip(RESOLUTION_LABELS.iter()).map(|(r, label)| (r.to_string(), Label::from(*label))).collect();
let resolutions = RESOLUTIONS.iter().zip(RESOLUTION_LABELS.iter()).map(|(r, label)| (r.to_string(), Label::from(tl!(*label)))).collect();
let mut rows = vec![Param::new("ppi", tl!("Resolution:"), ParamKind::choice(resolutions, Some(RESOLUTIONS[1].to_string())))];
if boards.names.len() > 1 {
let names = boards.names.iter().enumerate().map(|(i, name)| (i.to_string(), Label::from(name.clone()))).collect();
@@ -68,7 +68,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
fields.set("transparent", false);
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| {
let rows = params(&boards, fields);
ParamDialog::new(KIND, tl!("Save for Office Documents"), rows).values(Bind::bound(fields)).ok_label(Label::from("Save…"))
ParamDialog::new(KIND, tl!("Save for Office Documents"), rows).values(Bind::bound(fields)).ok_label(Label::from(tl!("Save…")))
});
export_host::open(app, Export::Office, false, dialog).ok_or("no window")?;
Ok(Value::Null)
+12 -2
View File
@@ -7,7 +7,7 @@ use std::ops::RangeInclusive;
use craft::theme::variant::Tone;
use craft::ui::choice::{Checkbox, Radio, RadioGroup};
use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
use craft::ui::contract::{Bind, Entry, Politeness, Props as _, Show as _, ShowContainer as _};
use craft::ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, StackDialog, dialog_id};
use craft::ui::form::{Field, FieldGroup};
use craft::ui::layout_components::Row;
@@ -175,6 +175,8 @@ pub(crate) struct OptionForm {
lengths: LengthUnits,
/// The Preview check box.
pub(super) preview: bool,
/// The current document does not own this dialog's preview.
pub(super) preview_paused: bool,
/// Whether the dialog's container is open.
open: bool,
/// The OK the dialog filed for [`pump`] to answer.
@@ -202,6 +204,7 @@ pub(super) fn open(app: &mut VectorcraftApp, spec: &'static OptionSpec, values:
extra,
lengths,
preview: false,
preview_paused: false,
open: true,
held: HeldAnswer::new(),
requests: HostRequests::new(),
@@ -249,8 +252,9 @@ impl StackDialog for OptionForm {
// The app accepted the held OK: this pass closes the dialog with it. A measuring run closes nothing.
let finish = self.held.is_accepted() && !measuring;
let answers = if measuring { Vec::new() } else { self.requests.take_answers() };
let OptionForm { spec, values, lengths, preview, open, held, requests, .. } = self;
let OptionForm { spec, values, lengths, preview, preview_paused, open, held, requests, .. } = self;
let (spec, lengths) = (*spec, *lengths);
let show_pause = *preview && *preview_paused;
let title = (spec.title)();
let refusal = held.refusal().map(|(reason, refused)| (reason.clone(), refused.clone()));
let mut form = FormDialog::new(word(&title), Bind::bound(&mut *values))
@@ -274,6 +278,12 @@ impl StackDialog for OptionForm {
if let Some((reason, _)) = refusal.as_ref().filter(|(_, refused)| *refused == *values) {
Notice::new(Tone::Bad, reason.clone()).layout(NoticeLayout::Inline).show(ui);
}
if show_pause {
Notice::new(Tone::Info, tl!("Preview is paused. Return to the document this dialog was opened for.").to_owned())
.layout(NoticeLayout::Inline)
.announce(Politeness::Polite)
.show(ui);
}
if finish {
form.request_close_as(CloseReason::Activated);
}
+25 -4
View File
@@ -20,7 +20,7 @@ use craft::ui::runtime::requests::PathKind;
use serde_json::{Value, json};
use vectorcraft_engine::EngineError;
use super::confirm::ask;
use super::confirm::{ask, ask_in_document};
use crate::background::{self, Writer};
use crate::{VectorcraftApp, file_asks, io};
@@ -46,7 +46,7 @@ fn downloads(app: &VectorcraftApp) -> bool {
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
let st = app.session.active().ok_or("no document")?;
let Some(path) = st.path.clone() else {
ask(
ask_in_document(
app,
tl!("Save the document first?"),
tl!("Package collects a saved document with its linked files and fonts."),
@@ -55,6 +55,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
);
return Ok(Value::Null);
};
let document = (st.uid, st.reverts);
let p = std::path::Path::new(&path);
let stem = p.file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned());
let folder = p.parent().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();
@@ -73,6 +74,7 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
.footer_note(Label::from(tl!("Fonts whose licence doesn't allow embedding are not copied.")))
});
crate::dialogs::host::open_held(app, dialog, |app, answer| confirm(app, &answer.fields).map(|_| ())).ok_or("no window")?;
app.package_document = Some(document);
Ok(Value::Null)
}
@@ -96,13 +98,30 @@ fn params(web: bool) -> Vec<Param> {
pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
let Some(dialogs) = app.dialogs() else { return };
let id = dialog_id(KEY);
let Some(request) = dialogs.with(|host| host.get_mut_by_id::<HostedParamDialog>(id).and_then(HostedParamDialog::pick_path)) else { return };
file_asks::browse(app, id, request, PickRequest::folder(PURPOSE), file_asks::answer_path);
let Some(request) = dialogs.with(|host| host.get_mut_by_id::<HostedParamDialog>(id).map(HostedParamDialog::pick_path)) else {
app.package_document = None;
return;
};
if let Some(request) = request {
file_asks::browse(app, id, request, PickRequest::folder(PURPOSE), file_asks::answer_path);
}
}
fn require_package_document(app: &VectorcraftApp, (document, reverts): (u64, u64)) -> Result<(), String> {
let Some(active) = app.session.active().filter(|st| st.uid == document) else {
return Err(tl!("Package can only save and collect the document where it was opened.").to_owned());
};
if active.reverts != reverts {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
Ok(())
}
/// What OK does: save a dirty document, then write the package (on the worker with Background Export on) or
/// download it. `Err` refuses the OK and keeps the dialog open; the reply says whether the package is in the background.
pub(super) fn confirm(app: &mut VectorcraftApp, fields: &DialogFields) -> Result<Value, String> {
let document = app.package_document.ok_or("no Package dialog open")?;
require_package_document(app, document)?;
let text = |key: &str| fields.text(key).unwrap_or_default();
let mut params = json!({ "folder": text("folder"), "name": text("name") });
for (key, _) in OPTIONS {
@@ -144,6 +163,8 @@ pub(super) fn confirm(app: &mut VectorcraftApp, fields: &DialogFields) -> Result
return r;
}
}
// A completed background job may have changed the active document or its loaded contents while Package waited.
require_package_document(app, document)?;
let package = app.session.prepare_package(&params).map_err(|e| e.to_string()).inspect_err(|e| app.ui.status = e.clone())?;
let label = format!("Packaging {}", text("name"));
let later = Rc::new(Cell::new(false));
@@ -609,7 +609,7 @@ fn tabs_buttons(unit: Unit) -> Param {
let (rows, _, _) = tab_rows(fields);
let can_add = new_tab_position(&rows, unit).is_some();
let (mut add, mut delete, mut clear) = (false, false, false);
let line = Row::new().show(ui, |ui, _| {
let line = Row::new().wrap(true).show(ui, |ui, _| {
add = clicked(&Button::new(tl!("Add")).enabled(can_add).show(ui));
delete = clicked(&Button::new(tl!("Delete Tab")).enabled(!rows.is_empty()).show(ui));
clear = clicked(&Button::new(tl!("Clear All Tabs")).enabled(!rows.is_empty()).show(ui));
@@ -348,6 +348,42 @@ fn tab_rows(app: &VectorcraftApp) -> Vec<Value> {
fields(app)["tabs"].as_array().cloned().unwrap_or_default()
}
#[test]
fn clear_all_tabs_can_be_clicked_in_a_narrow_viewport() {
use egui::accesskit::Role;
use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2};
for width in [800.0, 540.0] {
let mut app = app();
app.run("paraStyle.new", json!({"name": "Body", "attrs": {"tabs": [{"position": 36.0}, {"position": 72.0}]}})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let screen = Rect::from_min_size(Pos2::ZERO, vec2(width, 500.0));
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp, events| {
time += 0.25;
crate::testing::app_frame(app, &ctx, RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() })
};
frame(&mut app, vec![]);
open_tabs(&mut app, "Body");
for _ in 0..5 {
frame(&mut app, vec![]);
}
let out = frame(&mut app, vec![]);
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
let clear = nodes.iter().find(|(_, node)| node.role() == Role::Button && node.label() == Some("Clear All Tabs")).unwrap();
let bounds = clear.1.bounds().unwrap();
let at = pos2(((bounds.x0 + bounds.x1) * 0.5) as f32, ((bounds.y0 + bounds.y1) * 0.5) as f32);
assert_eq!(tab_rows(&app).len(), 2);
frame(&mut app, vec![Event::PointerMoved(at)]);
for pressed in [true, false] {
frame(&mut app, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
frame(&mut app, vec![]);
assert!(tab_rows(&app).is_empty(), "Clear All Tabs at {bounds:?} was not reachable in a {width}-point viewport");
}
}
/// Tabs shows a style's stops in the General unit with their alignment, leader and Align On
/// character; a stop left as it was keeps its position exactly, a changed one is read in the unit,
/// and the stops are stored sorted by position. Add puts a left stop half an inch past the furthest
+429 -56
View File
@@ -3,6 +3,8 @@
//! Every dialog is a held parameter dialog: its OK is the closure given to `open_held`, a refusal keeps it open with
//! the reason, and [`pump`] only runs the live preview of the kinds that have one.
use std::sync::{Arc, Weak};
// PLAN: the framework import paths below are assumed from the contract rows (craft-ui-patterns re-exports contract and
// runtime; the form-dialog items live under `patterns::form_dialogs`; `Field` and `NumberField` under craft-ui-widgets).
use craft::behavior::ColumnWidth;
@@ -19,7 +21,7 @@ use craft::ui::runtime::memory::{SaveKey, saved_value, set_saved_value};
use craft::ui::text::{NumberField, NumberOutput};
use craft::ui::value_drag::SliderScale;
use serde_json::{Map, Value, json};
use vectorcraft_doc::{NodeId, NodeKind};
use vectorcraft_doc::{NodeId, NodeKind, Selection};
use vectorcraft_geom::PathData;
use super::form;
@@ -111,7 +113,10 @@ impl PathOp {
pub(crate) struct Open {
op: PathOp,
id: DialogId,
document: u64,
preview: LivePreview,
/// A distinct selection snapshot identifies the interaction that ran this preview.
preview_selection: Option<Weak<Selection>>,
/// The params the preview last answered for.
last: Value,
/// Simplify: the paths the preview ran on.
@@ -123,8 +128,60 @@ pub(crate) struct Open {
/// The open Split Into Grid dialog's live state.
pub(crate) struct SplitOpen {
id: DialogId,
document: u64,
reverts: u64,
preview: LivePreview,
last: Value,
/// An interaction allocates its own selection snapshot, even when the selected objects did not change.
preview_selection: Option<Weak<Selection>>,
}
impl SplitOpen {
fn owns_preview(&self, app: &VectorcraftApp) -> bool {
let Some(selection) = &self.preview_selection else { return false };
app.session.active().is_some_and(|state| {
state.uid == self.document
&& state.reverts == self.reverts
&& state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection))
})
}
fn update_preview(&mut self, app: &mut VectorcraftApp, on: bool, fields: &DialogFields) {
let Some(state) = app.session.active().filter(|state| state.uid == self.document && state.reverts == self.reverts) else { return };
if !self.owns_preview(app) {
self.preview = LivePreview::default();
self.preview_selection = None;
if state.interaction.is_some() {
return;
}
}
let params = split_params(fields);
let ran = self.preview.run(app, on, tl!("Split Into Grid"), SPLIT_COMMAND, &params).is_some();
if !on {
self.preview_selection = None;
} else if ran {
self.preview_selection = app.session.active().and_then(|state| state.interaction.as_ref()).map(|it| Arc::downgrade(&it.selection));
}
}
fn confirm(&mut self, app: &mut VectorcraftApp, fields: &DialogFields) -> Result<(), String> {
let Some(state) = app.session.active().filter(|state| state.uid == self.document) else {
return Err(tl!("Split Into Grid can only change the document where it was opened.").to_owned());
};
if state.reverts != self.reverts {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
if app.session.in_interaction() && !self.owns_preview(app) {
return Err(tl!("Finish the active edit before applying Split Into Grid.").to_owned());
}
self.preview_selection = None;
std::mem::take(&mut self.preview).commit(app, SPLIT_COMMAND, split_params(fields)).map(drop)
}
fn cancel(self, app: &mut VectorcraftApp) {
if self.owns_preview(app) {
self.preview.cancel(app);
}
}
}
/// The command the dialog runs and its parameters.
@@ -309,6 +366,36 @@ fn take_open(app: &mut VectorcraftApp, op: PathOp) -> Option<Open> {
Some(app.object_dialogs.path.remove(i))
}
impl Open {
fn owns_preview(&self, app: &VectorcraftApp) -> bool {
let Some(selection) = &self.preview_selection else { return false };
app.session.active().is_some_and(|state| {
state.uid == self.document
&& state.interaction.as_ref().is_some_and(|interaction| selection.as_ptr() == Arc::as_ptr(&interaction.selection))
})
}
fn cancel(self, app: &mut VectorcraftApp) {
if self.owns_preview(app) {
self.preview.cancel(app);
}
}
fn commit(&mut self, app: &mut VectorcraftApp, cmd: &str, params: Value) -> Result<(), String> {
if app.session.active().is_none_or(|state| state.uid != self.document) {
return Err(tl!("Return to the document where this dialog opened.").to_owned());
}
if app.session.in_interaction() && !self.owns_preview(app) {
return Err(tl!("Finish the active edit before confirming.").to_owned());
}
self.preview_selection = None;
self.last = Value::Null;
self.original.clear();
self.shown = false;
std::mem::take(&mut self.preview).commit(app, cmd, params).map(drop)
}
}
/// Whether Object › Path › Simplify opens its dialog (the user kept its settings) instead of the slider.
pub(crate) fn retained_simplify(app: &VectorcraftApp) -> bool {
let Some(ctx) = app.ui_ctx.as_ref() else { return false };
@@ -344,6 +431,11 @@ fn open_dialog(app: &mut VectorcraftApp, op: PathOp, fields: DialogFields, remem
app.status("There is no window to show the dialog in.");
return;
};
let document = app.session.active().map(|state| state.uid);
if op.previews() && document.is_none() {
app.status("Open a document before editing paths.");
return;
}
let lengths = crate::canvas::general_lengths(app);
let opening = op.opening();
let key = op.key();
@@ -359,17 +451,11 @@ fn open_dialog(app: &mut VectorcraftApp, op: PathOp, fields: DialogFields, remem
});
let ok = move |app: &mut VectorcraftApp, result: &craft::ui::patterns::form_dialogs::ParamResult| {
let (cmd, params) = command(op, &result.fields);
match take_open(app, op) {
Some(record) => {
let id = record.id;
record.preview.commit(app, cmd, params).map(drop).inspect_err(|_| {
// The dialog stays open on the refusal, so it keeps previewing.
app.object_dialogs.path.push(Open { op, id, preview: LivePreview::default(), last: Value::Null, original: vec![], shown: false });
})?;
}
None => {
app.run(cmd, params).map(drop)?;
}
if op.previews() {
let Some(mut record) = take_open(app, op) else { return Err(tl!("The path dialog is closed.").to_owned()) };
record.commit(app, cmd, params).inspect_err(|_| app.object_dialogs.path.push(record))?;
} else {
app.run(cmd, params).map(drop)?;
}
match op {
PathOp::Simplify => {
@@ -383,24 +469,40 @@ fn open_dialog(app: &mut VectorcraftApp, op: PathOp, fields: DialogFields, remem
Ok(())
};
if let Some(old) = take_open(app, op) {
old.preview.cancel(app);
old.cancel(app);
}
let id = if op.previews() {
let cancel = Box::new(move |app: &mut VectorcraftApp| {
// A cancelled opening can leave a replacement with the same dialog ID.
let id = app.object_dialogs.path.iter().find(|record| record.op == op).map(|record| record.id);
if let Some(id) = id
&& app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::<HostedParamDialog>(id).is_some()))
{
return;
}
if let Some(record) = take_open(app, op) {
record.preview.cancel(app);
record.cancel(app);
}
});
open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) })
} else {
open_held(app, dialog, ok)
};
match id {
Some(id) if op.previews() => {
app.object_dialogs.path.push(Open { op, id, preview: LivePreview::default(), last: Value::Null, original: vec![], shown: false })
match (id, document) {
(Some(id), Some(document)) if op.previews() => {
app.object_dialogs.path.push(Open {
op,
id,
document,
preview: LivePreview::default(),
preview_selection: None,
last: Value::Null,
original: vec![],
shown: false,
});
}
Some(_) => {}
None => app.status("There is no window to show the dialog in."),
(Some(_), _) => {}
(None, _) => app.status("There is no window to show the dialog in."),
}
}
@@ -410,34 +512,26 @@ pub(crate) fn open_split(app: &mut VectorcraftApp) {
app.status("There is no window to show the dialog in.");
return;
};
let (width, height) =
app.session.active().and_then(|st| st.doc.bounds_of(&st.selection.objects, false)).map_or((0.0, 0.0), |b| (b.width(), b.height()));
let Some(state) = app.session.active() else {
app.status("Open a document before using Split Into Grid.");
return;
};
let document = state.uid;
let reverts = state.reverts;
let (width, height) = state.doc.bounds_of(&state.selection.objects, false).map_or((0.0, 0.0), |b| (b.width(), b.height()));
let lengths = crate::canvas::general_lengths(app);
let dialog = HostedParamDialog::new(&ctx, SPLIT_COMMAND, split_fields(width, height), move |f| {
ParamDialog::new(SPLIT_COMMAND, tl!("Split Into Grid"), split_rows(lengths)).values(Bind::bound(f)).previews(true)
});
let ok = |app: &mut VectorcraftApp, result: &craft::ui::patterns::form_dialogs::ParamResult| {
let params = split_params(&result.fields);
match app.object_dialogs.split.take() {
Some(record) => {
let id = record.id;
record.preview.commit(app, SPLIT_COMMAND, params).map(drop).inspect_err(|_| {
app.object_dialogs.split = Some(SplitOpen { id, preview: LivePreview::default(), last: Value::Null });
})
}
None => app.run(SPLIT_COMMAND, params).map(drop),
}
let Some(mut record) = app.object_dialogs.split.take() else { return Err(tl!("The Split Into Grid dialog is closed.").to_owned()) };
record.confirm(app, &result.fields).inspect_err(|_| app.object_dialogs.split = Some(record))
};
if let Some(old) = app.object_dialogs.split.take() {
old.preview.cancel(app);
old.cancel(app);
}
let cancel = Box::new(|app: &mut VectorcraftApp| {
if let Some(record) = app.object_dialogs.split.take() {
record.preview.cancel(app);
}
});
match open_held_with(app, dialog, ok, HeldOptions { parent: None, cancel: Some(cancel) }) {
Some(id) => app.object_dialogs.split = Some(SplitOpen { id, preview: LivePreview::default(), last: Value::Null }),
match open_held(app, dialog, ok) {
Some(id) => app.object_dialogs.split = Some(SplitOpen { id, document, reverts, preview: LivePreview::default(), preview_selection: None }),
None => app.status("There is no window to show the dialog in."),
}
}
@@ -456,22 +550,29 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
}
records.append(&mut app.object_dialogs.path);
app.object_dialogs.path = records;
if let Some(mut s) = app.object_dialogs.split.take() {
if let Some((on, fields)) = dialog_state(app, s.id) {
let params = split_params(&fields);
if !on {
s.last = Value::Null;
}
if s.preview.run(app, on, tl!("Split Into Grid"), SPLIT_COMMAND, &params).is_some() {
s.last = params;
}
if let Some(mut split) = app.object_dialogs.split.take() {
if let Some((on, fields)) = dialog_state(app, split.id) {
split.update_preview(app, on, &fields);
app.object_dialogs.split = Some(split);
} else {
split.cancel(app);
}
app.object_dialogs.split = Some(s);
}
}
fn step(app: &mut VectorcraftApp, r: &mut Open) {
let Some((on, fields)) = dialog_state(app, r.id) else { return };
let Some(state) = app.session.active().filter(|state| state.uid == r.document) else { return };
if !r.owns_preview(app) {
r.preview = LivePreview::default();
r.preview_selection = None;
r.last = Value::Null;
r.original.clear();
r.shown = false;
if state.interaction.is_some() {
return;
}
}
let (cmd, params) = command(r.op, &fields);
let stale = !on || r.last != params;
if stale {
@@ -479,13 +580,17 @@ fn step(app: &mut VectorcraftApp, r: &mut Open) {
}
if !on {
r.last = Value::Null;
r.preview_selection = None;
}
let mut counts = stale.then_some(None);
if let Some(Ok(answer)) = r.preview.run(app, on, r.op.title(), cmd, &params) {
r.last = params;
if r.op == PathOp::Simplify {
r.original = answer["ids"].as_array().into_iter().flatten().filter_map(|id| id.as_u64().map(NodeId)).collect();
counts = Some(Some(json!({"before": answer["before"], "after": answer["after"]})));
if let Some(answer) = r.preview.run(app, on, r.op.title(), cmd, &params) {
r.preview_selection = app.session.active().and_then(|state| state.interaction.as_ref()).map(|it| Arc::downgrade(&it.selection));
if let Ok(answer) = answer {
r.last = params;
if r.op == PathOp::Simplify {
r.original = answer["ids"].as_array().into_iter().flatten().filter_map(|id| id.as_u64().map(NodeId)).collect();
counts = Some(Some(json!({"before": answer["before"], "after": answer["after"]})));
}
}
}
r.shown = on && fields.bool("showOriginal").unwrap_or(false);
@@ -506,7 +611,7 @@ fn step(app: &mut VectorcraftApp, r: &mut Open) {
/// on, with its id, as it was before the preview (from the interaction's snapshot). Empty
/// otherwise.
pub(crate) fn original_paths(app: &VectorcraftApp) -> Vec<(NodeId, &PathData)> {
let Some(r) = app.object_dialogs.path.iter().find(|r| r.op == PathOp::Simplify && r.shown) else { return vec![] };
let Some(r) = app.object_dialogs.path.iter().find(|r| r.op == PathOp::Simplify && r.shown && r.owns_preview(app)) else { return vec![] };
let Some(it) = app.session.active().and_then(|st| st.interaction.as_ref()) else { return vec![] };
r.original
.iter()
@@ -516,3 +621,271 @@ pub(crate) fn original_paths(app: &VectorcraftApp) -> Vec<(NodeId, &PathData)> {
})
.collect()
}
#[cfg(test)]
mod split_tests {
use craft::ui::dialog::HeldOk;
use serde_json::json;
use super::*;
use crate::dialogs::tests::{app, cancel, confirm, frame, is_open, set};
fn selected_rectangle(app: &mut VectorcraftApp, width: u32, height: u32) {
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": width, "height": height})).unwrap();
app.run("select.all", json!({})).unwrap();
}
fn other_document(app: &mut VectorcraftApp) {
app.run("file.new", json!({"width": 300, "height": 200})).unwrap();
selected_rectangle(app, 150, 90);
}
fn grid_after_file_revert(hold_ok: bool) -> VectorcraftApp {
let mut app = app();
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let folder = vectorcraft_testkit::TempDir::new("split-into-grid-revert");
let path = folder.join("drawing.vectorcraft");
selected_rectangle(&mut app, 112, 62);
let original = app.session.active().unwrap().selection.objects[0];
app.run("file.saveAs", json!({"path": path})).unwrap();
selected_rectangle(&mut app, 50, 30);
app.run("select.set", json!({"ids": [original.0]})).unwrap();
let source = app.session.active().unwrap();
let (uid, generation) = (source.uid, source.reverts);
open_split(&mut app);
set(&mut app, "columns", json!(3));
set(&mut app, "preview", json!(false));
if hold_ok {
let ctx = app.ui_ctx.clone().unwrap();
let id = app.object_dialogs.split.as_ref().unwrap().id;
assert!(!app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id)));
}
app.run("file.revert", json!({"confirmed": true})).unwrap();
let reloaded = app.session.active().unwrap();
assert_eq!(reloaded.uid, uid);
assert_ne!(reloaded.reverts, generation);
app.run("select.set", json!({"ids": [original.0]})).unwrap();
app
}
#[test]
fn grid_revert_ignores_the_previous_generations_preview() {
let mut app = grid_after_file_revert(false);
let restored = app.session.active().unwrap().doc.clone();
set(&mut app, "preview", json!(true));
frame(&mut app, vec![]);
assert!(app.session.active().unwrap().doc == restored, "old grid preview reached the restored drawing");
assert!(!app.session.in_interaction());
}
#[test]
fn grid_revert_ignores_a_held_ok_and_accepts_a_fresh_opening() {
let mut app = grid_after_file_revert(true);
let restored = app.session.active().unwrap().doc.clone();
let undo = app.session.active().unwrap().history.undo.len();
let id = app.object_dialogs.split.as_ref().unwrap().id;
frame(&mut app, vec![]);
assert!(app.session.active().unwrap().doc == restored, "old grid OK reached the restored drawing");
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
let Some(HeldOk::Refused(message)) = app.dialogs().unwrap().with(|host| host.held_state(id)) else { panic!("expected a held refusal") };
assert_eq!(message.as_str(), "The document was reverted. Reopen this dialog to continue.");
assert!(cancel(&mut app));
open_split(&mut app);
set(&mut app, "columns", json!(3));
assert!(confirm(&mut app));
let active = app.session.active().unwrap();
assert_eq!(active.doc.layers[0].children().unwrap().len(), 6);
assert_eq!(active.history.undo.len(), undo + 1);
}
#[test]
fn split_into_grid_skips_preview_in_the_other_drawing() {
let mut app = app();
selected_rectangle(&mut app, 112, 62);
let original = app.session.doc().unwrap().doc.clone();
open_split(&mut app);
set(&mut app, "columns", json!(3));
other_document(&mut app);
let other = app.session.doc().unwrap().doc.clone();
set(&mut app, "preview", json!(true));
frame(&mut app, vec![]);
assert!(app.session.doc().unwrap().doc == other, "the other drawing is unchanged by Preview");
assert!(!app.session.in_interaction());
app.run("document.activate", json!({"index": 0})).unwrap();
frame(&mut app, vec![]);
assert_ne!(app.session.doc().unwrap().doc, original);
assert!(app.session.in_interaction());
assert!(confirm(&mut app));
assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 6);
assert!(!app.session.in_interaction());
}
#[test]
fn split_into_grid_keeps_the_draft_when_ok_is_in_another_drawing() {
let mut app = app();
selected_rectangle(&mut app, 112, 62);
open_split(&mut app);
set(&mut app, "columns", json!(3));
other_document(&mut app);
let other = app.session.doc().unwrap().doc.clone();
let undo = app.session.doc().unwrap().history.undo.len();
let closed = confirm(&mut app);
assert!(app.session.doc().unwrap().doc == other, "the other drawing is unchanged by OK");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
assert!(!closed && is_open(&app), "the user can return to confirm");
app.run("document.activate", json!({"index": 0})).unwrap();
assert!(confirm(&mut app));
assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 6);
}
#[test]
fn split_into_grid_cancel_preserves_the_other_drawings_edit() {
let mut app = app();
selected_rectangle(&mut app, 112, 62);
other_document(&mut app);
app.run("document.activate", json!({"index": 0})).unwrap();
let opening = app.session.doc().unwrap().doc.clone();
open_split(&mut app);
set(&mut app, "preview", json!(true));
frame(&mut app, vec![]);
assert!(app.session.in_interaction(), "the opening drawing is previewing");
app.run("document.activate", json!({"index": 1})).unwrap();
app.session.begin_interaction("Other edit").unwrap();
app.session.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap();
let other = app.session.doc().unwrap().doc.clone();
assert!(cancel(&mut app));
assert!(app.session.in_interaction(), "Cancel preserves the other drawing's pending edit");
assert_eq!(app.session.doc().unwrap().doc, other);
app.session.commit_interaction().unwrap();
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(app.session.doc().unwrap().doc, opening);
}
#[test]
fn split_into_grid_does_not_adopt_a_new_edit_on_return() {
let mut app = app();
selected_rectangle(&mut app, 112, 62);
other_document(&mut app);
app.run("document.activate", json!({"index": 0})).unwrap();
open_split(&mut app);
set(&mut app, "preview", json!(true));
frame(&mut app, vec![]);
assert!(app.session.in_interaction());
for index in [1, 0] {
app.run("document.activate", json!({"index": index})).unwrap();
}
app.session.begin_interaction("New edit").unwrap();
app.session.preview("paint.setFill", &json!({"color": "#00a000"})).unwrap();
let editing = app.session.doc().unwrap().doc.clone();
frame(&mut app, vec![]);
assert!(!confirm(&mut app));
assert!(cancel(&mut app));
assert!(app.session.in_interaction());
assert_eq!(app.session.doc().unwrap().doc, editing);
}
}
#[cfg(test)]
mod preview_document_tests {
use super::*;
use crate::dialogs::tests::{app, cancel, confirm, frame, set};
fn dense_path(app: &mut VectorcraftApp, top: f64) -> u64 {
let anchors: Vec<_> = (0..20).map(|i| json!({"x": 30 + i * 15, "y": top + (i % 2) as f64 * 0.1})).collect();
let id = app.run("path.create", json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap();
app.run("select.anchors", json!({"id": id, "anchors": [[0, 19]]})).unwrap();
id
}
fn drawings() -> (VectorcraftApp, NodeId) {
let mut app = app();
let id = dense_path(&mut app, 50.0);
app.run("file.new", json!({"width": 500, "height": 400})).unwrap();
let other = dense_path(&mut app, 180.0);
assert_eq!(id, other, "the two drawings use the same path ID");
app.run("document.activate", json!({"index": 0})).unwrap();
(app, NodeId(id))
}
fn more_options(app: &mut VectorcraftApp) {
crate::menus::invoke(app, "object.path.simplify", json!({}));
crate::dialogs::simplify_slider::more_options(app).unwrap();
}
#[test]
fn simplify_options_skip_the_other_drawings_artwork() {
for from_slider in [false, true] {
let (mut app, _) = drawings();
if from_slider {
more_options(&mut app);
} else {
let ctx = app.ui_ctx.clone().unwrap();
set_saved_value(&ctx, &SIMPLIFY_KEY, Some(simplify_dialog(DEFAULT_TOLERANCE)));
crate::menus::invoke(&mut app, "object.path.simplify", json!({}));
}
set(&mut app, "preview", json!(true));
app.run("document.activate", json!({"index": 1})).unwrap();
let other = app.session.doc().unwrap().doc.clone();
let undo = app.session.doc().unwrap().history.undo.len();
frame(&mut app, vec![]);
assert!(app.session.doc().unwrap().doc == other, "Simplify preview leaves the other drawing unchanged");
assert!(!app.session.in_interaction());
assert!(!confirm(&mut app), "the draft stays with the opening drawing");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo);
app.run("document.activate", json!({"index": 0})).unwrap();
frame(&mut app, vec![]);
assert!(app.session.in_interaction());
assert!(confirm(&mut app));
}
}
#[test]
fn simplify_options_never_outline_another_drawings_same_id() {
let (mut app, id) = drawings();
more_options(&mut app);
set(&mut app, "showOriginal", json!(true));
set(&mut app, "preview", json!(true));
frame(&mut app, vec![]);
assert_eq!(original_paths(&app).iter().map(|(path, _)| *path).collect::<Vec<_>>(), [id]);
app.run("document.activate", json!({"index": 1})).unwrap();
app.session.begin_interaction("Other edit").unwrap();
assert!(original_paths(&app).is_empty(), "Show Original leaves the other drawing's canvas alone");
assert!(cancel(&mut app));
assert!(app.session.in_interaction(), "Cancel leaves the other drawing's edit in progress");
}
#[test]
fn offset_path_skips_the_other_drawings_artwork() {
let mut app = app();
app.run("shape.rectangle", json!({"x": 10, "y": 20, "width": 100, "height": 60})).unwrap();
app.run("select.all", json!({})).unwrap();
crate::menus::invoke(&mut app, "object.path.offsetPath", json!({}));
set(&mut app, "offset", json!(12.0));
set(&mut app, "preview", json!(true));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("shape.rectangle", json!({"x": 140, "y": 30, "width": 80, "height": 100})).unwrap();
app.run("select.all", json!({})).unwrap();
let other = app.session.doc().unwrap().doc.clone();
frame(&mut app, vec![]);
assert!(app.session.doc().unwrap().doc == other, "Offset Path preview leaves the other drawing unchanged");
assert!(!confirm(&mut app));
app.run("document.activate", json!({"index": 0})).unwrap();
assert!(confirm(&mut app));
assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 2);
}
}
+10 -6
View File
@@ -134,7 +134,7 @@ fn open_on(app: &mut VectorcraftApp, def: GridDefinition, mode: GridMode) -> Res
let dialog = GridDialog::new(
def,
mode,
app.session.active().map(|st| st.uid),
app.session.active().map(|st| (st.uid, st.reverts)),
(general_lengths(app).pixels_per_inch, app.session.prefs.numbers_without_units_are_points),
app.session.perspective_presets(),
app.session.new_perspective_preset_name(),
@@ -172,8 +172,8 @@ pub fn open_edit(app: &mut VectorcraftApp, original: Option<&str>, base: &str) -
pub(super) struct GridDialog {
id: DialogId,
mode: GridMode,
/// The document whose grid Define Grid edits.
source_document: Option<u64>,
/// The document and loaded contents whose grid Define Grid edits.
source_document: Option<(u64, u64)>,
draft: GridDraft,
/// The presets the Preset row offers, as the document and the preferences have them.
presets: Vec<GridDefinition>,
@@ -196,7 +196,7 @@ impl GridDialog {
fn new(
def: GridDefinition,
mode: GridMode,
source_document: Option<u64>,
source_document: Option<(u64, u64)>,
(ppi, bare_points): (f64, bool),
presets: Vec<GridDefinition>,
new_name: String,
@@ -527,12 +527,16 @@ enum Next {
Presets(String),
}
fn file(app: &mut VectorcraftApp, mode: &GridMode, source_document: Option<u64>, def: &GridDefinition) -> Result<Next, String> {
fn file(app: &mut VectorcraftApp, mode: &GridMode, source_document: Option<(u64, u64)>, def: &GridDefinition) -> Result<Next, String> {
let mut params = serde_json::to_value(def).map_err(|e| e.to_string())?;
if *mode == GridMode::Define {
if app.session.active().map(|st| st.uid) != source_document {
let active = app.session.active().map(|st| (st.uid, st.reverts));
if active.map(|(uid, _)| uid) != source_document.map(|(uid, _)| uid) {
return Err(tl!("Define Grid can only change the document where it was opened.").to_owned());
}
if active != source_document {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
app.run("perspective.grid.define", params)?;
return Ok(Next::Close);
}
@@ -5,6 +5,7 @@
//! Fields: `show` (bool), `position` (`topLeft`, `topRight`, `bottomLeft`, `bottomRight`),
//! `anchorPoint` (bool) and `gridlineIntersection` (bool).
use craft::ui::contract::Bind;
use craft::ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind};
use serde_json::{Value, json};
use vectorcraft_tools::distort::perspective::widget::WidgetCorner;
@@ -31,8 +32,8 @@ fn params() -> Vec<Param> {
]
}
fn build(_fields: &mut DialogFields) -> ParamDialog<'_> {
ParamDialog::new(KIND, tl!("Perspective Grid Options"), params())
fn build(fields: &mut DialogFields) -> ParamDialog<'_> {
ParamDialog::new(KIND, tl!("Perspective Grid Options"), params()).values(Bind::bound(fields))
}
/// Open the dialog with the current options.
@@ -51,3 +52,39 @@ pub fn open(app: &mut VectorcraftApp) {
app.status("no window".to_string());
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::{panel_harness::Panel, picks::dialogs};
use craft::ui::contract::Role;
use vectorcraft_engine::Session;
fn open_options(panel: &mut Panel) {
panel.app().run("tool.options", json!({"tool": "perspectiveGrid"})).unwrap();
panel.frame();
}
#[test]
fn perspective_grid_options_show_and_apply_widget_preferences() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.prefs.perspective_widget.position = WidgetCorner::BottomRight;
let mut panel = Panel::new(app, dialogs);
open_options(&mut panel);
assert_eq!(panel.value_role("Widget Position", Role::COMBO_BOX).as_deref(), Some("Bottom Right"));
panel.click_role("Widget Position", Role::COMBO_BOX);
panel.click("Top Right");
panel.click("Intersection of Gridlines");
panel.click("OK");
let saved = panel.app().session.prefs.perspective_widget;
assert_eq!(saved.position, WidgetCorner::TopRight);
assert!(!saved.gridline_intersection);
open_options(&mut panel);
assert_eq!(panel.value_role("Widget Position", Role::COMBO_BOX).as_deref(), Some("Top Right"));
panel.click("Show Active Plane Widget");
panel.click("Cancel");
assert_eq!(panel.app().session.prefs.perspective_widget, saved);
}
}
+115 -7
View File
@@ -19,6 +19,9 @@ use crate::canvas::general_lengths;
/// The dialog kind of the plane options.
pub const KIND: &str = "perspectivePlane";
const OPENING_DOCUMENT: &str = "__openingDocument";
const OPENING_REVERTS: &str = "__openingReverts";
/// What becomes of the objects on the plane: (`objects` value, label).
const OBJECTS: [(&str, &str); 3] = [("none", "Do Not Move"), ("move", "Move All Objects"), ("copy", "Copy All Objects")];
@@ -47,8 +50,9 @@ fn build<'a>(title: &str, lengths: LengthUnits, _fields: &'a mut DialogFields) -
/// Open the options of `plane` (`{plane}`; default the active plane), filled in with its location.
pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let doc = &app.session.active().ok_or("no document")?.doc;
let g = PerspectiveGrid::current(doc);
let state = app.session.active().ok_or("no document")?;
let (document, reverts) = (state.uid, state.reverts);
let g = PerspectiveGrid::current(&state.doc);
let plane = match p.get("plane").and_then(Value::as_str) {
Some(s) => Plane::parse(s).ok_or("plane must be left, right or ground")?,
None => g.plane,
@@ -60,12 +64,25 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let lengths = general_lengths(app);
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let Value::Object(map) = json!({"plane": plane.id(), "location": offset, "objects": "none"}) else { return Err("no window".into()) };
let mut fields = form::fields_of(&params(lengths), &map);
// The held answer carries the drawing and plane from the same opening.
fields.set(OPENING_DOCUMENT, document.to_string());
fields.set(OPENING_REVERTS, reverts.to_string());
let heading = title(plane);
let dialog = HostedParamDialog::new(&ctx, KIND, form::fields_of(&params(lengths), &map), move |f| build(&heading, lengths, f));
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |f| build(&heading, lengths, f));
// A refusal keeps the dialog open with the reason under its rows.
let ok = move |app: &mut VectorcraftApp, r: &ParamResult| {
let ok = |app: &mut VectorcraftApp, r: &ParamResult| {
let document = r.fields.text(OPENING_DOCUMENT).and_then(|uid| uid.parse().ok());
let Some(active) = app.session.active().filter(|state| Some(state.uid) == document) else {
return Err(tl!("Perspective Plane Options can only change the document where it was opened.").to_owned());
};
let reverts = r.fields.text(OPENING_REVERTS).and_then(|value| value.parse::<u64>().ok());
if reverts != Some(active.reverts) {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
let plane = r.fields.text("plane").ok_or_else(|| tl!("The perspective plane is missing").to_owned())?;
let objects = r.fields.text("objects").unwrap_or("none");
let p = json!({"plane": plane.id(), "offset": r.fields.number("location").unwrap_or(0.0), "objects": objects});
let p = json!({"plane": plane, "offset": r.fields.number("location").unwrap_or(0.0), "objects": objects});
app.run("perspective.plane.move", p).map(|_| ())
};
open_held(app, dialog, ok).ok_or("no window")?;
@@ -100,15 +117,75 @@ mod tests {
host(app, |h| h.set_json_field(&ctx, id, field, value)).unwrap();
}
/// OK on the open dialog, then the frame's pump runs the held OK.
fn ok(app: &mut VectorcraftApp) {
fn pump_ok(app: &mut VectorcraftApp) {
let (ctx, (id, _)) = (app.ui_ctx.clone().unwrap(), the_dialog(app));
// A held OK reports `false` and files its answer for the app; the dialog closes at its next pass.
assert!(host(app, |h| h.confirm_by_id(&ctx, id) || h.held_state(id) == Some(craft::ui::dialog::HeldOk::Waiting)), "OK is enabled");
crate::dialogs::host::pump(app, &ctx);
}
fn ok(app: &mut VectorcraftApp) {
pump_ok(app);
let ctx = app.ui_ctx.clone().unwrap();
crate::tests_synthetic::key_frame(app, &ctx, vec![]);
}
fn right_plane_with_art(app: &mut VectorcraftApp) {
app.run("perspective.grid.preset", json!({"kind": 2})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 450, "y": 380, "width": 60, "height": 60})).unwrap()["id"].clone();
app.run("perspective.attach", json!({"ids": [id], "plane": "right"})).unwrap();
}
#[test]
fn plane_options_keep_the_plane_and_copied_objects_in_the_opening_document() {
let mut app = app();
right_plane_with_art(&mut app);
let opening = app.session.doc().unwrap().doc.clone();
app.run("ui.perspectivePlane", json!({"plane": "right"})).unwrap();
set(&app, "location", json!(40.0));
set(&app, "objects", json!("copy"));
app.run("file.new", json!({"width": 800, "height": 600})).unwrap();
right_plane_with_art(&mut app);
let other = app.session.doc().unwrap().doc.clone();
let history = app.session.doc().unwrap().history.undo.len();
let (id, _) = the_dialog(&app);
pump_ok(&mut app);
assert_eq!(app.session.doc().unwrap().doc, other, "foreign OK leaves the other drawing and its art unchanged");
assert_eq!(app.session.doc().unwrap().history.undo.len(), history);
assert!(matches!(host(&app, |h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_))));
assert_eq!(the_dialog(&app).1["location"], 40.0);
assert_eq!(the_dialog(&app).1["objects"], "copy");
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(app.session.doc().unwrap().doc, opening);
ok(&mut app);
let doc = &app.session.doc().unwrap().doc;
assert_eq!(PerspectiveGrid::current(doc).right_offset, 40.0);
assert_eq!(doc.layers[0].children().unwrap().len(), 2, "one copy in the opening drawing");
}
#[test]
fn replacement_plane_options_use_the_replacement_drawing_and_plane() {
let mut app = app();
app.run("perspective.grid.preset", json!({"kind": 2})).unwrap();
let opening = app.session.doc().unwrap().doc.clone();
app.run("ui.perspectivePlane", json!({"plane": "right"})).unwrap();
app.run("file.new", json!({"width": 800, "height": 600})).unwrap();
app.run("perspective.grid.preset", json!({"kind": 2})).unwrap();
app.run("ui.perspectivePlane", json!({"plane": "ground"})).unwrap();
set(&app, "location", json!(40.0));
ok(&mut app);
let grid = PerspectiveGrid::current(&app.session.doc().unwrap().doc);
assert_eq!(grid.offset(Plane::Ground), 40.0, "OK moves the replacement opening's plane");
assert_eq!(grid.offset(Plane::Right), 0.0);
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(app.session.doc().unwrap().doc, opening);
}
#[test]
fn double_clicking_a_plane_widget_opens_its_options_and_ok_moves_it() {
let mut app = app();
@@ -155,4 +232,35 @@ mod tests {
let id = *st.selection.objects.first().unwrap();
assert_eq!(vectorcraft_tools::distort::perspective::attachment(st.doc.node(id).unwrap()).map(|a| a.0), Some(Plane::Right));
}
#[test]
fn held_plane_options_cannot_move_or_copy_restored_artwork() {
let mut app = app();
right_plane_with_art(&mut app);
let dir = vectorcraft_testkit::TempDir::new("perspective-plane-revert");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
app.run("perspective.plane.move", json!({"plane": "right", "offset": 10.0, "objects": "none"})).unwrap();
app.run("ui.perspectivePlane", json!({"plane": "right"})).unwrap();
set(&app, "location", json!(40.0));
set(&app, "objects", json!("copy"));
app.run("file.revert", json!({"confirmed": true})).unwrap();
let restored = app.session.active().unwrap().doc.clone();
let (id, _) = the_dialog(&app);
pump_ok(&mut app);
assert!(matches!(host(&app, |h| h.held_state(id)), Some(craft::ui::dialog::HeldOk::Refused(_))));
assert_eq!(app.session.active().unwrap().doc, restored);
let ctx = app.ui_ctx.clone().unwrap();
host(&app, |h| h.cancel_by_id(&ctx, id));
app.run("ui.perspectivePlane", json!({"plane": "right"})).unwrap();
set(&app, "location", json!(40.0));
set(&app, "objects", json!("copy"));
ok(&mut app);
let doc = &app.session.active().unwrap().doc;
assert_eq!(PerspectiveGrid::current(doc).right_offset, 40.0);
assert_eq!(doc.layers[0].children().unwrap().len(), 2);
}
}
@@ -9,6 +9,8 @@
//!
//! Field: `selected` (a preset's name).
use std::sync::Arc;
use craft::behavior::{DisplayOrder, ItemSource, Selection};
use craft::host::PickRequest;
use craft::ui::buttons::Button;
@@ -117,13 +119,22 @@ pub(super) struct PresetsDialog {
names: Vec<String>,
/// The button pressed in the last pass, for [`pump`] to run outside the host's lock.
action: Option<Action>,
/// Identifies the manager that opened an Import picker.
import_owner: Arc<()>,
open: bool,
}
impl PresetsDialog {
fn new(selected: &str, presets: Vec<GridDefinition>) -> Self {
let mut dialog =
PresetsDialog { id: dialog_id(KIND), selected: selected.to_owned(), presets: Vec::new(), names: Vec::new(), action: None, open: true };
let mut dialog = PresetsDialog {
id: dialog_id(KIND),
selected: selected.to_owned(),
presets: Vec::new(),
names: Vec::new(),
action: None,
import_owner: Arc::new(()),
open: true,
};
dialog.set_presets(presets);
dialog
}
@@ -296,12 +307,18 @@ pub(super) fn run(app: &mut VectorcraftApp, act: Action, current: &str) -> Resul
select(app, &next);
}
Action::Import => {
let Some(owner) = with_dialog(app, |manager| Arc::clone(&manager.import_owner)) else { return Ok(()) };
let request = PickRequest::open(KIND).filter("Perspective grid presets", PRESET_EXTS);
file_asks::ask(app, request, Owner::Free, |app, picked| {
let path = picked.first_path().ok_or("cancelled")?;
let r = app.run("perspective.presets.import", json!({ "path": path }))?;
file_asks::ask(app, request, Owner::Free, move |app, picked| {
let mut params = file_asks::open_params(&picked).ok_or("cancelled")?;
params.remove("name");
let r = app.run("perspective.presets.import", Value::Object(params))?;
if let Some(first) = r["imported"].get(0).and_then(Value::as_str) {
select(app, first);
with_dialog(app, |manager| {
if Arc::ptr_eq(&manager.import_owner, &owner) {
manager.selected = first.to_owned();
}
});
}
Ok(r)
});
+104 -3
View File
@@ -16,6 +16,7 @@ use crate::VectorcraftApp;
use crate::dialogs::tool_options::reference_param;
const KEY: &str = "placementOptions";
const OPENING: &str = "__opening";
const CMD: &str = "links.placementOptions";
/// (value, label) of each Preserve choice.
const PRESERVE: [(&str, &str); 5] = [
@@ -43,15 +44,18 @@ fn params() -> Vec<Param> {
/// Open the dialog on the placement options of images `ids` (default: the selected ones).
pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let active = app.session.active().ok_or("no document open")?;
let source = (active.uid, active.reverts);
let ids = p.get("ids").cloned().unwrap_or(Value::Null);
let r = app.session.execute(CMD, &json!({ "ids": ids })).map_err(|e| e.to_string())?;
let placement = &r["placement"];
let align = ALIGN.iter().position(|a| Some(*a) == placement["align"].as_str()).unwrap_or(CENTRE);
let fields = DialogFields::from_pairs([
let mut fields = DialogFields::from_pairs([
("preserve", FieldValue::Text(placement["preserve"].as_str().unwrap_or("transforms").to_owned())),
("align", FieldValue::Int(align as i64)),
("clip", FieldValue::Bool(placement["clip"].as_bool().unwrap_or(false))),
]);
fields.set(OPENING, FieldValue::Json(json!({"uid": source.0, "reverts": source.1, "ids": ids})));
let ctx = app.ui_ctx.clone().ok_or("no window")?;
let dialog = HostedParamDialog::new(&ctx, KEY, fields, |fields| {
ParamDialog::new(KEY, tl!("Placement Options"), params())
@@ -59,12 +63,109 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
.footer_note(tl!("Applies when the linked file is relinked or updated."))
})
.held_ok();
crate::dialogs::host::open_held(app, dialog, move |app, result: &ParamResult| {
crate::dialogs::host::open_held(app, dialog, |app, result: &ParamResult| {
let f = &result.fields;
let Some(FieldValue::Json(opening)) = f.get(OPENING) else { return Err("the Placement Options target is missing".into()) };
let Some(active) = app.session.active().filter(|document| Some(document.uid) == opening["uid"].as_u64()) else {
return Err(tl!("Placement Options can only change the document where it was opened.").to_owned());
};
if Some(active.reverts) != opening["reverts"].as_u64() {
return Err(tl!("The document was reverted. Reopen this dialog to continue.").to_owned());
}
let align = f.int("align").and_then(|i| usize::try_from(i).ok()).and_then(|i| ALIGN.get(i).copied()).unwrap_or(ALIGN[CENTRE]);
let params = json!({ "ids": ids, "preserve": f.text("preserve"), "align": align, "clip": f.bool("clip").unwrap_or(false) });
let params = json!({ "ids": opening["ids"], "preserve": f.text("preserve"), "align": align, "clip": f.bool("clip").unwrap_or(false) });
app.run(CMD, params).map(|_| ())
})
.ok_or("no window")?;
Ok(Value::Null)
}
#[cfg(test)]
mod tests {
use craft::ui::dialog::{HeldOk, dialog_id};
use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, SampleType};
use vectorcraft_engine::Session;
use super::*;
#[test]
fn held_placement_options_keep_the_link_and_undo_in_the_opening_document() {
let dir = vectorcraft_testkit::TempDir::new("placement-options-document");
let path = dir.join("linked.png");
let image = Image::from_raw(2, 2, ChannelLayout::Rgba, SampleType::U8, vec![255; 16]).unwrap();
std::fs::write(&path, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap();
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
let link = |app: &mut VectorcraftApp| {
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
app.run("file.place", json!({"path": path, "at": [100, 100], "link": true})).unwrap()["ids"][0].as_u64().unwrap()
};
let source_link = link(&mut app);
let other_link = link(&mut app);
assert_eq!(source_link, other_link, "different documents reuse this object ID");
let settings = |app: &mut VectorcraftApp| {
let placement = app.run(CMD, json!({"ids": [source_link]})).unwrap()["placement"].clone();
(placement, app.session.active().unwrap().history.undo.len())
};
let other = settings(&mut app);
app.run("document.activate", json!({"index": 0})).unwrap();
let starting = settings(&mut app);
app.run("ui.placementOptionsDialog", json!({"ids": [source_link]})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let dialogs = app.dialogs().unwrap();
let id = dialog_id(KEY);
dialogs.with(|host| {
host.set_json_field(&ctx, id, "preserve", json!("fit")).unwrap();
assert!(!host.confirm_by_id(&ctx, id));
assert_eq!(host.held_state(id), Some(HeldOk::Waiting));
});
app.run("document.activate", json!({"index": 1})).unwrap();
crate::dialogs::host::pump(&mut app, &ctx);
assert_eq!(settings(&mut app), other, "the other link and its undo history are preserved");
assert!(matches!(dialogs.with(|host| host.held_state(id)), Some(HeldOk::Refused(_))));
app.run("document.activate", json!({"index": 0})).unwrap();
assert_eq!(settings(&mut app), starting);
assert!(crate::dialogs::tests::confirm(&mut app));
let (placement, steps) = settings(&mut app);
assert_eq!(placement["preserve"], json!("fit"));
assert_eq!(steps, starting.1 + 1);
}
#[test]
fn held_placement_options_do_not_edit_a_link_restored_by_file_revert() {
let dir = vectorcraft_testkit::TempDir::new("placement-options-revert");
let path = dir.join("linked.png");
let image = Image::from_raw(2, 2, ChannelLayout::Rgba, SampleType::U8, vec![255; 16]).unwrap();
std::fs::write(&path, craft_image_codecs::encode(&image, Format::Png, &EncodeOptions::default()).unwrap()).unwrap();
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Default::default()));
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let link = app.run("file.place", json!({"path": path, "at": [100, 100], "link": true})).unwrap()["ids"][0].as_u64().unwrap();
app.run("file.saveAs", json!({"path": dir.join("Art.vectorcraft")})).unwrap();
let placement = |app: &mut VectorcraftApp| app.run(CMD, json!({"ids": [link]})).unwrap()["placement"].clone();
let original = placement(&mut app);
app.run(CMD, json!({"ids": [link], "preserve": "fill"})).unwrap();
open(&mut app, &json!({"ids": [link]})).unwrap();
let ctx = app.ui_ctx.clone().unwrap();
let dialog = dialog_id(KEY);
let host = app.dialogs().unwrap();
host.with(|h| {
h.set_json_field(&ctx, dialog, "preserve", json!("fit")).unwrap();
assert!(!h.confirm_by_id(&ctx, dialog));
});
app.run("file.revert", json!({"confirmed": true})).unwrap();
let undo = app.session.active().unwrap().history.undo.len();
crate::dialogs::host::pump(&mut app, &ctx);
assert_eq!(placement(&mut app), original);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo);
assert!(matches!(host.with(|h| h.held_state(dialog)), Some(HeldOk::Refused(_))));
host.with(|h| h.cancel_by_id(&ctx, dialog));
open(&mut app, &json!({"ids": [link]})).unwrap();
crate::tests::picks::answer_dialog(&mut app, dialog, &[("preserve", json!("fit"))], true);
assert_eq!(placement(&mut app)["preserve"], "fit");
}
}
+30 -16
View File
@@ -100,6 +100,7 @@ pub(crate) struct PrintDialogs {
struct Open {
id: DialogId,
mode: PrintMode,
document: Option<u64>,
/// The preset the settings were loaded from last (the Print Preset row's selection).
preset: String,
/// The saved preset the editor edits (empty: a new one).
@@ -157,7 +158,8 @@ pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
// The saved preset these settings are, if any (else [Default], shown as [Custom] if they differ).
let preset = app.session.prefs.print_presets.iter().find(|p| p.settings == saved).map_or(DEFAULT_PRESET, |p| p.name.as_str()).to_string();
let fields = fields_of(&saved)?;
start(app, PrintMode::Print, fields, preset, Default::default())
let document = st.uid;
start(app, PrintMode::Print, Some(document), fields, preset, Default::default())
}
/// Open the preset editor on the saved preset `name`, or on a new preset starting from `preset`
@@ -173,7 +175,7 @@ pub fn open_preset(app: &mut VectorcraftApp, params: &Value) -> Result<Value, St
None => (s("preset").unwrap_or(DEFAULT_PRESET).to_string(), app.session.new_print_preset_name(), String::new()),
};
let set = app.session.print_preset_settings(&base).ok_or_else(|| format!("no print preset named `{base}`"))?;
start(app, PrintMode::PresetEditor, fields_of(&set)?, base, (editing, name))
start(app, PrintMode::PresetEditor, None, fields_of(&set)?, base, (editing, name))
}
/// Host the dialog over the settings `fields`; the preset editor edits the saved preset `editing` (empty: a new one)
@@ -181,6 +183,7 @@ pub fn open_preset(app: &mut VectorcraftApp, params: &Value) -> Result<Value, St
fn start(
app: &mut VectorcraftApp,
mode: PrintMode,
document: Option<u64>,
fields: DialogFields,
preset: String,
(editing, name): (String, String),
@@ -217,7 +220,7 @@ fn start(
hosted.set_json_field(&ctx, "name", json!(name))?;
}
let id = dialogs.with(|h| h.open(hosted));
app.print_dialog.open = Some(Open { id, mode, preset, editing, art: None, preview: None, driver });
app.print_dialog.open = Some(Open { id, mode, document, preset, editing, art: None, preview: None, driver });
Ok(Value::Null)
}
@@ -366,6 +369,30 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
let _ = dialogs.with(|h| h.take_by_id::<HostedPrint>(open.id));
return false;
};
for event in std::mem::take(&mut d.events) {
apply_preset_event(app, dialogs, open, &mut d.settings, event);
}
if open.mode == PrintMode::Print {
let same = serde_json::from_value::<PrintSettings>(d.settings.clone())
.ok()
.is_some_and(|s| app.session.print_preset_settings(&open.preset) == Some(s));
let held = same.then(|| open.preset.clone());
let rows: Vec<PresetRow<String>> = std::iter::once(PresetRow::item(DEFAULT_PRESET.to_string(), tl!(DEFAULT_PRESET), 0))
.chain(app.session.prefs.print_presets.iter().map(|p| PresetRow::item(p.name.clone(), p.name.clone(), 0)))
.collect();
on(dialogs, |p| p.set_presets(rows, held, vec![DEFAULT_PRESET.to_string()]));
}
if open.document.is_some_and(|document| app.session.active().is_none_or(|st| st.uid != document)) {
let message = tl!("Return to the original drawing to print it");
on(dialogs, |p| {
p.set_sheet(None);
p.set_message(Some(message.into()));
if d.ok.is_some() {
p.answer_ok(Err(message.into()));
}
});
return true;
}
// The row was drawn this frame with the controls of the printer before: the next frame shows the new ones.
if d.driver != open.driver {
open.driver = d.driver;
@@ -383,9 +410,6 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
{
app.status(e);
}
for event in std::mem::take(&mut d.events) {
apply_preset_event(app, dialogs, open, &mut d.settings, event);
}
let doc = app.session.active().map_or((0, 0), |s| (s.uid, s.revision));
let stamp = (d.settings.to_string(), doc);
let changed = open.preview.as_ref().is_none_or(|(s, _)| *s != stamp);
@@ -425,16 +449,6 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
p.set_field("__inks", FieldValue::Json(inks));
});
}
if open.mode == PrintMode::Print {
let same = serde_json::from_value::<PrintSettings>(d.settings.clone())
.ok()
.is_some_and(|s| app.session.print_preset_settings(&open.preset) == Some(s));
let held = same.then(|| open.preset.clone());
let rows: Vec<PresetRow<String>> = std::iter::once(PresetRow::item(DEFAULT_PRESET.to_string(), tl!(DEFAULT_PRESET), 0))
.chain(app.session.prefs.print_presets.iter().map(|p| PresetRow::item(p.name.clone(), p.name.clone(), 0)))
.collect();
on(dialogs, |p| p.set_presets(rows, held, vec![DEFAULT_PRESET.to_string()]));
}
if let Some(answer) = d.ok {
let result = accept(app, open, &answer, &d.name);
on(dialogs, |p| p.answer_ok(result.map_err(Into::into)));
+1 -1
View File
@@ -48,7 +48,7 @@ fn stored(app: &VectorcraftApp, name: &str) -> Value {
fn detail(app: &VectorcraftApp, name: &str) -> Vec<Detail> {
let builtin = name == DEFAULT_PRESET;
let title = if builtin { tl!(DEFAULT_PRESET).to_string() } else { name.to_string() };
let mut out = vec![Detail::Title(title), Detail::Note(crate::i18n::fmt(tl!("Differences from {preset}:"), &[("preset", DEFAULT_PRESET)]))];
let mut out = vec![Detail::Title(title), Detail::Note(crate::i18n::fmt(tl!("Differences from {preset}:"), &[("preset", tl!(DEFAULT_PRESET))]))];
let settings = app.session.prefs.print_presets.iter().find(|p| p.name == name).map(|p| &p.settings);
let mut changed = settings.map(|s| changes(s, &Default::default())).unwrap_or_default();
changed.sort_by_key(|c| section_of(c["option"].as_str().unwrap_or_default()).0);
+8 -10
View File
@@ -62,9 +62,8 @@ pub(crate) struct PasteAsk {
params: Value,
/// The models whose profiles differ, as `clipboard.profileMismatch` lists them.
mismatches: Vec<Value>,
/// The uid of the document the question was asked in: a paste that runs at once pastes nothing
/// once another document is active.
doc: Option<u64>,
/// The drawing and content generation the question was asked in.
drawing: Option<(u64, u64)>,
/// The chain of a deferred paste (one that waits for its clipboard), which placing answers.
deferred: Option<u64>,
}
@@ -271,8 +270,8 @@ fn open_paste(app: &mut VectorcraftApp, command: &str, params: &Value, mismatche
crate::placing::cancel_swatch_paste(app);
}
let dialog = paste_dialog(&ctx, &mismatches);
let doc = app.session.active().map(|st| st.uid);
app.pending_paste = Some(PasteAsk { command: command.to_string(), params: params.clone(), mismatches, doc, deferred: None });
let drawing = app.session.active().map(|st| (st.uid, st.reverts));
app.pending_paste = Some(PasteAsk { command: command.to_string(), params: params.clone(), mismatches, drawing, deferred: None });
dialogs.with(|h| h.open(dialog));
Some(Ok(json!({ "dialog": PASTE_KIND })))
}
@@ -389,12 +388,11 @@ fn pump_paste(app: &mut VectorcraftApp) {
}
}
/// OK: run the paste with the choice; any Swatch Conflict question comes next. When another
/// document has become the active one since a paste that runs at once asked, it pastes nothing. When
/// the profiles that paste or drop would bring have changed since it asked (the clipboard, the
/// dragged objects' document or the destination's profile changed), it asks again about the new ones.
/// OK: run the paste with the choice; any Swatch Conflict question comes next. An immediate paste
/// is canceled if its drawing is inactive or reverted. When the profiles it would bring have changed
/// since it asked (the clipboard, dragged objects or destination changed), it asks about the new ones.
fn paste_confirm(app: &mut VectorcraftApp, ask: PasteAsk, choice: Value) -> Result<Value, String> {
if ask.deferred.is_none() && ask.doc != app.session.active().map(|st| st.uid) {
if ask.deferred.is_none() && ask.drawing != app.session.active().map(|st| (st.uid, st.reverts)) {
return Ok(json!({}));
}
let params = with_choice(&ask.params, choice);
@@ -320,6 +320,31 @@ fn paste_asked_before_another_document_is_active(app: &mut VectorcraftApp) {
app.run("document.activate", json!({ "index": asked_in })).unwrap();
}
/// The destination still has a mismatch after reopening the saved contents. Its old approval is retired.
fn paste_asked_before_its_drawing_is_reverted(app: &mut VectorcraftApp) {
let dir = vectorcraft_testkit::TempDir::new("immediate-profile-mismatch-revert");
let path = dir.join("destination.vectorcraft");
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|err| err.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|err| err.to_string())));
app.run("file.saveAs", json!({"path": path.to_string_lossy()})).unwrap();
app.run("shape.rectangle", json!({"x": 60, "y": 60, "width": 20, "height": 20})).unwrap();
assert_eq!(app.run("edit.paste", json!({})).unwrap(), json!({ "dialog": PASTE_KIND }));
let before = app.session.active().unwrap();
let (uid, reverts) = (before.uid, before.reverts);
app.run("file.revert", json!({"confirmed": true})).unwrap();
let restored = app.session.active().unwrap();
assert_eq!((restored.uid, restored.reverts), (uid, reverts + 1));
assert!(app.pending_paste.is_some(), "the old question is still waiting");
let saved = restored.doc.clone();
let undo = restored.history.undo.len();
answer_ok(app, paste_id_open());
let after = app.session.active().unwrap();
assert!(after.doc == saved, "the old profile approval must leave the restored drawing intact");
assert_eq!(after.history.undo.len(), undo);
assert!(app.pending_paste.is_none());
}
/// A drag of the art of the document assigned Display P3 into the active one asks as Paste does:
/// Cancel drops nothing, and OK drops it as chosen. When the source document's profile changes while
/// the question is open, OK drops nothing and asks again about the new profile. `count` counts the
@@ -467,6 +492,7 @@ fn opening_and_pasting_ask_about_profiles() {
// Cancel pastes nothing; with the box off nothing asks.
paste_canceled(&mut app, count);
paste_asked_before_another_document_is_active(&mut app);
paste_asked_before_its_drawing_is_reverted(&mut app);
drop_asks_as_paste_does(&mut app, count);
let before = count(&app);
app.run("edit.colorSettings", json!({"askMismatchPaste": false})).unwrap();
+85 -19
View File
@@ -4,8 +4,8 @@
//! Preview shows the proof on the canvas while the dialog is open; OK sets the proof setup and
//! turns Proof Colors on (`view.proofSetup`), and Cancel puts the earlier proof view back. Save…
//! writes the dialog's settings to a proof setup file (`view.proofSetup.save`) and Load… reads one
//! into the dialog (`view.proofSetup.read`). Both are desktop only. Their pickers start in the
//! Proof Setups folder next to the preferences, whose setups View → Proof Setup lists below
//! into the dialog (`view.proofSetup.read`). The browser reads picked bytes and downloads a copy
//! when saving. Desktop pickers start in the Proof Setups folder next to the preferences, whose setups View → Proof Setup lists below
//! Customize… ([`saved_items`]): Save… makes the folder when it may be written, and Load…'s picker
//! starts in its own default folder until the folder exists.
//!
@@ -116,15 +116,10 @@ fn rgb_device(device: &str) -> bool {
/// The dialog over the host's values, made again every pass.
fn build(fields: &mut DialogFields) -> ParamDialog<'_> {
// The web has no folder to keep setups in.
let footer = if cfg!(target_arch = "wasm32") {
Vec::new()
} else {
vec![
(SAVE.to_string(), FooterButton::new(tl!("Save…").to_string(), DialogRole::Other)),
(LOAD_BUTTON.to_string(), FooterButton::new(tl!("Load…").to_string(), DialogRole::Other)),
]
};
let footer = vec![
(SAVE.to_string(), FooterButton::new(tl!("Save…").to_string(), DialogRole::Other)),
(LOAD_BUTTON.to_string(), FooterButton::new(tl!("Load…").to_string(), DialogRole::Other)),
];
ParamDialog::new(KIND, tl!("Proof Setup").to_string(), rows(fields)).values(Bind::bound(fields)).previews(true).extra_buttons(footer)
}
@@ -297,6 +292,29 @@ fn act(app: &mut VectorcraftApp, id: DialogId, fields: &DialogFields, action: &s
/// Save…: the dialog's settings go to the picked file, and the menu lists the saved setups again.
fn save(app: &mut VectorcraftApp, fields: &DialogFields) {
let mut request =
PickRequest::save("proof-setups").file_name(format!("{}.{EXT}", tl!("Proof Setup"))).filter("Proof setups", &[EXT]).suggested_extension(EXT);
let mut p = params(fields);
if let Some(o) = p.as_object_mut() {
o.remove("proof");
}
if app.host.files().browser_saves() {
match proof_file::draft_bytes(&p) {
Ok(bytes) => {
crate::file_asks::save(app, request, bytes, Owner::Free, |app, picked| {
match picked {
Picked::Saved { path, .. } => app.status(format!("Saved {}", path.display())),
Picked::Downloaded(name) => app.status(format!("Saved {name}")),
Picked::Failed(error) => return Err(error),
_ => {}
}
Ok(Value::Null)
});
}
Err(e) => app.status(e.to_string()),
}
return;
}
// The picker opens in the folder, made for it when it may be written. [`list_saved`] removes
// it again when the picker closes without a file in it.
let dir = app.session.proof_setup_dir().map(Path::to_path_buf);
@@ -307,15 +325,9 @@ fn save(app: &mut VectorcraftApp, fields: &DialogFields) {
if made.is_some() {
saved().made = made;
}
let mut request =
PickRequest::save("proof-setups").file_name(format!("{}.{EXT}", tl!("Proof Setup"))).filter("Proof setups", &[EXT]).suggested_extension(EXT);
if let Some(dir) = dir {
request = request.directory(dir);
}
let mut p = params(fields);
if let Some(o) = p.as_object_mut() {
o.remove("proof");
}
ask(app, request, Owner::Free, move |app, picked| {
let Picked::Saved { path, .. } = picked else { return Ok(Value::Null) };
let path = path.to_string_lossy().into_owned();
@@ -343,8 +355,16 @@ fn load(app: &mut VectorcraftApp, id: DialogId) {
&& app.dialogs().is_some_and(|dialogs| dialogs.with(|host| host.get_by_id::<HostedParamDialog>(id).is_some()))
};
ask_while(app, request, Owner::Free, is_live, move |app, picked| {
let Some(path) = picked.first_path() else { return Ok(Value::Null) };
let r = app.run("view.proofSetup.read", json!({ "path": path.to_string_lossy() }))?;
let r = match picked {
Picked::Contents(files) => {
let Some((name, bytes)) = files.into_iter().next() else { return Ok(Value::Null) };
proof_file::draft_fields(&bytes, &name).map_err(|e| e.to_string())?
}
other => {
let Some(path) = other.first_path() else { return Ok(Value::Null) };
app.run("view.proofSetup.read", json!({ "path": path.to_string_lossy() }))?
}
};
let fields = [
("device", "target"),
("intent", "intent"),
@@ -817,6 +837,52 @@ mod tests {
assert_eq!((v.setup.target, v.setup.intent), (ProofTarget::Rgb(cms::DISPLAY_P3.into()), Intent::Saturation));
}
#[test]
fn a_browser_pick_loads_a_proof_setup_into_the_draft() {
let _view = DefaultProofView::new();
let (mut app, ctx) = app();
let files = scripted(&mut app, ScriptedFiles::held().in_browser());
app.run("ui.proofSetupDialog", json!({})).unwrap();
set(&mut app, &ctx, "preview", json!(false));
let before = proof::view();
let mut source = before.setup.clone();
source.intent = Intent::Saturation;
press(&mut app, &ctx, LOAD_BUTTON);
files.answer(Picked::Contents(vec![("browser.vcproof".into(), proof_file::encode(&source))]));
crate::file_asks::poll(&mut app);
assert_eq!(values(&app)["intent"], "saturation");
assert_eq!(proof::view(), before);
press(&mut app, &ctx, LOAD_BUTTON);
files.answer(Picked::Contents(vec![("oversized.vcproof".into(), vec![b' '; proof_file::MAX_FILE + 1])]));
crate::file_asks::poll(&mut app);
assert!(app.ui.status.contains("larger than"));
assert_eq!(values(&app)["intent"], "saturation");
assert_eq!(proof::view(), before);
}
#[test]
fn saving_a_browser_proof_setup_gives_the_file_service_the_draft_bytes() {
let _view = DefaultProofView::new();
let (mut app, ctx) = app();
let files = scripted(&mut app, ScriptedFiles::held().in_browser());
app.run("ui.proofSetupDialog", json!({})).unwrap();
for (k, v) in [("intent", json!("saturation")), ("preview", json!(false))] {
set(&mut app, &ctx, k, v);
}
let before = proof::view();
let dir = vectorcraft_testkit::TempDir::new("proof-setup-browser-save");
let path = dir.join("draft.vcproof");
press(&mut app, &ctx, SAVE);
files.answer(Picked::Saved { path: path.clone(), file_type: None });
crate::file_asks::poll(&mut app);
let bytes = files.file(&path).expect("the browser file service receives the draft bytes");
assert_eq!(proof_file::parse(&bytes).unwrap().intent, Intent::Saturation);
assert_eq!(proof::view(), before);
assert_eq!(values(&app)["intent"], "saturation");
assert!(!path.exists(), "the browser save does not write through the native path");
}
#[test]
fn a_delayed_load_only_changes_the_proof_setup_that_requested_it() {
let _view = DefaultProofView::new();
+25 -1
View File
@@ -84,6 +84,7 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<St
fields.set("hasSlices", FieldValue::Bool(has_slices));
let summary = format!("{} × {} px · {} {}", info.width, info.height, crate::i18n::colon(tl!("Layers")), info.layers);
let placing = place.is_some();
let drawing = place.and_then(|params| crate::place::import_options_drawing(app, params));
let source = Source {
place: place.map(|p| other_place_params(p, &["layers", "hiddenLayers", "importSlices"])),
name: name.to_string(),
@@ -93,7 +94,11 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<St
};
let ctx = app.ui_ctx.clone().unwrap_or_default();
let dialog = HostedParamDialog::new(&ctx, KIND, fields, move |fields| build(fields, placing, &summary)).held_ok();
open_held(app, dialog, move |app, result| confirm(app, &source, result)).is_some()
open_held(app, dialog, move |app, result| {
crate::place::check_import_options_drawing(app, drawing)?;
confirm(app, &source, result)
})
.is_some()
}
/// `file.place` with params `p` asks first (true) when they embed a PSD or PSB file (`link: false`,
@@ -269,6 +274,25 @@ mod tests {
}
}
#[test]
fn normal_psd_place_options_wait_for_the_original_drawing() {
let mut app = host::app();
app.run("file.new", json!({"width": 100, "height": 100})).unwrap();
let encoded = vectorcraft_format::base64_encode(&layered());
let params = json!({"name": "poster.psd", "dataBase64": encoded, "at": [50, 50]});
assert_eq!(crate::place::run_for_user(&mut app, &params).unwrap()["dialog"], KIND);
set(&app, "convert", json!("flatten"));
app.run("file.new", json!({"width": 300, "height": 150})).unwrap();
let error = host::confirm(&mut app, KIND).expect_err("the other drawing must not receive the file");
assert!(error.contains("original drawing"), "{error}");
assert!(app.session.active().unwrap().history.undo.is_empty());
assert_eq!(host::fields(&app, KIND)["convert"], "flatten");
app.run("document.activate", json!({"index": 0})).unwrap();
host::confirm(&mut app, KIND).unwrap();
let st = app.session.active().unwrap();
assert!(matches!(st.doc.layers[0].children().map(Vec::as_slice), Some([node]) if matches!(node.kind, NodeKind::Image(_))));
}
#[test]
fn placing_without_link_asks_and_places_the_layers_as_a_group() {
let b64 = vectorcraft_format::base64_encode(&layered());
Loaded 100 of 283 files, more files were not shown because too many files have changed in this diff. Show more