diff --git a/crates/engine/src/cmd/distortcmds/perspective.rs b/crates/engine/src/cmd/distortcmds/perspective.rs index edffa17055..5dfce8eb8e 100644 --- a/crates/engine/src/cmd/distortcmds/perspective.rs +++ b/crates/engine/src/cmd/distortcmds/perspective.rs @@ -63,6 +63,7 @@ pub(crate) fn silent(s: &mut Session, f: impl FnOnce(&mut PerspectiveGrid)) -> R store_grid(Arc::make_mut(&mut st.doc), &g); if let Some(it) = &mut st.interaction { store_grid(Arc::make_mut(&mut it.doc), &g); + it.revision = st.revision + 1; } st.revision += 1; Ok(g) @@ -745,6 +746,7 @@ pub(crate) fn finish_edit_text(st: &mut crate::DocState, id: NodeId) { } if let Some(it) = &mut st.interaction { clear(&mut it.doc); + it.revision = st.revision + 1; } st.revision += 1; } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 323d5d0918..ea28d8675e 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -7,6 +7,11 @@ use vectorcraft_geom::Rect; use crate::Session; +/// The new-art paint state before the running preview, or its current value without a preview. +pub fn new_art_paint_before_preview(s: &Session) -> &vectorcraft_tools::PaintDefaults { + s.active().and_then(|st| st.interaction.as_ref()).map_or(&s.paint, |it| &it.paint) +} + pub(crate) fn rect_json(r: Option) -> Value { match r { Some(r) => json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height() }), diff --git a/crates/engine/src/interaction.rs b/crates/engine/src/interaction.rs index 825fd4c986..34d5eb0bbc 100644 --- a/crates/engine/src/interaction.rs +++ b/crates/engine/src/interaction.rs @@ -11,8 +11,8 @@ pub struct Interaction { /// The selection the previews start from (shared, so a preview frame copies nothing). pub selection: Arc, pub(crate) active_appearance_item: Option, - /// The document's [`crate::DocState::revision`] when the interaction began. The previews change the document's - /// revision, and this value stays the same until the interaction ends. + /// The baseline document's [`crate::DocState::revision`]. Previews keep this value; replacing or changing the + /// baseline advances it to the document's next revision. pub revision: u64, pub preview: Option<(String, Value)>, /// The active tool began it (a drag): a command from outside the tool runs as a step of its diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index dd31393158..8b1bb476c6 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -522,6 +522,8 @@ impl Session { return; } let began = std::mem::replace(&mut it.doc, st.doc.clone()); + st.revision += 1; + it.revision = st.revision; // The drag acts on the objects it began with: a selection the command made (a paste, a // duplicate, Select All) does not change what the drag moves. A dialog's preview acts on // the selection the command left, and its dialog previews again on its next pass, from the diff --git a/crates/engine/src/tests/interaction_commands.rs b/crates/engine/src/tests/interaction_commands.rs index 00588ecf0c..4eefe43bc3 100644 --- a/crates/engine/src/tests/interaction_commands.rs +++ b/crates/engine/src/tests/interaction_commands.rs @@ -846,3 +846,58 @@ fn a_command_during_a_quick_pen_press_runs_inside_it() { assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{at}: no step of its own during the press"); } } + +#[test] +fn a_rebased_drag_advances_its_baseline_revision() { + for real_time in [true, false] { + let (mut s, _, other) = two_squares(real_time); + s.select_tool("selection", view()).unwrap(); + pointer(&mut s, PointerKind::Down, 120.0, 120.0); + pointer(&mut s, PointerKind::Drag, 140.0, 130.0); + let revision = s.doc().unwrap().interaction.as_ref().unwrap().revision; + pointer(&mut s, PointerKind::Drag, 150.0, 140.0); + assert_eq!(s.doc().unwrap().interaction.as_ref().unwrap().revision, revision, "previews keep the baseline revision"); + s.execute("appearance.setItem", &json!({"ids": [other.0], "index": 1, "weight": 3})).unwrap(); + let rebased = s.doc().unwrap().interaction.as_ref().unwrap().revision; + assert!(rebased > revision, "an outside document edit advances the baseline revision"); + pointer(&mut s, PointerKind::Drag, 160.0, 150.0); + assert_eq!(s.doc().unwrap().interaction.as_ref().unwrap().revision, rebased, "later previews keep the rebased revision"); + s.cancel_interaction().unwrap(); + assert_eq!(s.doc().unwrap().doc.node(other).unwrap().appearance.stroke().unwrap().width, 3.0); + } +} + +#[test] +fn a_grid_change_during_an_interaction_advances_its_baseline_revision() { + let (mut s, _) = session(true); + s.begin_interaction("Grid").unwrap(); + let revision = s.doc().unwrap().interaction.as_ref().unwrap().revision; + crate::cmd::distortcmds::silent(&mut s, |grid| grid.visible = !grid.visible).unwrap(); + let st = s.doc().unwrap(); + let it = st.interaction.as_ref().unwrap(); + assert!(it.revision > revision, "a direct baseline change advances its revision"); + assert_eq!(crate::cmd::distortcmds::grid_of(&it.doc).visible, crate::cmd::distortcmds::grid_of(&st.doc).visible); +} + +#[test] +fn leaving_perspective_type_editing_during_an_interaction_advances_its_baseline_revision() { + let (mut s, _) = crate::tests_persp_select::persp_session(); + let r = s.execute("text.create", &json!({"x": 430, "y": 400, "text": "HELLO", "size": 48})).unwrap(); + let id = NodeId(r["id"].as_u64().unwrap()); + s.execute("perspective.attach", &json!({"ids": [id.0], "plane": "right"})).unwrap(); + s.execute("perspective.editText", &json!({"id": id.0})).unwrap(); + s.begin_interaction("Edit").unwrap(); + let it = s.doc().unwrap().interaction.as_ref().unwrap(); + let revision = it.revision; + let text = it.doc.node(id).unwrap(); + assert!(text.extras().perspective.as_deref().unwrap().editing, "the baseline starts in Edit Text mode"); + assert!(text.projection().is_none(), "the baseline text is flat while editing"); + crate::cmd::distortcmds::finish_edit_text(s.doc_mut().unwrap(), id); + let st = s.doc().unwrap(); + let it = st.interaction.as_ref().unwrap(); + let text = it.doc.node(id).unwrap(); + assert!(!text.extras().perspective.as_deref().unwrap().editing, "the baseline leaves Edit Text mode"); + assert!(text.projection().is_some(), "the baseline text is projected again"); + assert!(it.revision > revision, "leaving Edit Text advances the baseline revision"); + assert_eq!(it.revision, st.revision, "the baseline revision is the document's new revision"); +} diff --git a/crates/ui-egui/src/panels/appearance.rs b/crates/ui-egui/src/panels/appearance.rs index c6c791b645..c98048a526 100644 --- a/crates/ui-egui/src/panels/appearance.rs +++ b/crates/ui-egui/src/panels/appearance.rs @@ -452,9 +452,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let copy = craft::ui::runtime::pointer::frame(ui.ctx()).mods.alt; let pass = RefCell::new(Pass::default()); let footer = RefCell::new(None); + let shown_target = stroke::target_key(&stroke::edit_target(app, ui.ctx())); let shared: &VectorcraftApp = app; let cx = RowCx { app: shared, + shown_target, node: node.as_deref(), new_art: &new_art, mix, @@ -751,6 +753,7 @@ struct Pass { /// What a row reads to build itself. struct RowCx<'a> { app: &'a VectorcraftApp, + shown_target: u64, node: Option<&'a Node>, new_art: &'a Appearance, mix: Option<&'a Mixed>, @@ -860,10 +863,12 @@ fn item_row<'r>(cx: &'r RowCx<'_>, key: RowKey, i: usize) -> ListRow<'r> { } if let Some(st) = stroke_layer { let target = if new_art { WeightTarget::Shown } else { WeightTarget::Item(i) }; + let field = + if new_art { row_weight(cx.app, Some(st.width), &cx.shown_target) } else { row_weight(cx.app, Some(st.width), &(cx.shown_target, i)) }; let pass = cx.pass; - row = row.trailing_field(row_weight(cx.app, Some(st.width)), move |out| pass.borrow_mut().acts.push(Act::Weight(target, Box::new(out)))); + row = row.trailing_field(field, move |out| pass.borrow_mut().acts.push(Act::Weight(target, Box::new(out)))); } else { - row = row.trailing_space(row_weight(cx.app, None)); + row = row.trailing_space(row_weight(cx.app, None, &())); } let painted = if new_art { Painted::NewArt { fill } } else { Painted::Item(i) }; let pass = cx.pass; @@ -894,8 +899,8 @@ fn paint_swatch(fill: bool, paint: &Paint) -> Swatch { /// The weight field of a stroke row, or the room it takes in a fill row: the Stroke panel's field as a small control, /// as the row's swatch is, without the presets list (a step still stops at each preset), so the row's label shows /// whole in the narrowest group. -fn row_weight(app: &VectorcraftApp, weight: Option) -> NumberField<'static> { - stroke::steps_weight(app, weight).size(ControlSize::Sm) +fn row_weight(app: &VectorcraftApp, weight: Option, target: &impl egui::AsIdSalt) -> NumberField<'static> { + stroke::steps_weight(app, weight, target).size(ControlSize::Sm) } /// A stroke row's notes after the weight: its brush and "Dashed". diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index 676a7dd32c..bd03b832d7 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -3,6 +3,7 @@ // PLAN: import paths of craft_ui / craft_draw items are assumed from the crates' own module layout (craft_draw is // not yet a dependency of ui-egui; its owner adds it to Cargo.toml). +use std::hash::{DefaultHasher, Hash, Hasher}; use std::sync::LazyLock; mod profile_picker; @@ -32,7 +33,9 @@ use craft::ui::text::{NumberField, NumberOutput, NumberPick, StepArrows}; use egui::{Rect, Response, Ui, pos2}; use serde_json::{Value, json}; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, ArrowAlign, Arrowhead, Dash, Document, LineCap, LineJoin, Node, StrokeAlign, StrokeLayer, Unit, WidthProfile}; +use vectorcraft_doc::{ + Appearance, ArrowAlign, Arrowhead, Dash, Document, LineCap, LineJoin, Node, NodeId, StrokeAlign, StrokeLayer, Unit, WidthProfile, +}; use vectorcraft_engine::inspect::StrokeMixed; use vectorcraft_tools::PaintDefaults; @@ -50,6 +53,15 @@ const ARROWHEAD_ASPECT: (u16, u16) = (2, 1); /// The key of [`StrokePanel::brushed`]: (document uid, revision, active Appearance row). type BrushedKey = (u64, u64, Option); +#[derive(Clone, Debug, Default)] +struct FieldGesture { + held: Option<(EditTarget, EditTarget)>, + serial: u64, +} + +/// Global Edit members in propagation order, with the transforms that place each member. +type GlobalEditTarget = Option>; + /// What the Stroke panel remembers between frames; `UiState::stroke_panel` holds it. #[derive(Clone, Debug, Default)] pub(crate) struct StrokePanel { @@ -63,6 +75,10 @@ pub(crate) struct StrokePanel { pub brushed: Option<(BrushedKey, Option)>, /// The running gesture of a Stroke panel select. pub select_gesture: Option, + /// The editor gesture's starting target and targeting state. + editor_gesture: FieldGesture, + /// The arrow scale gesture's starting target and targeting state. + scale_gesture: FieldGesture, } /// The stroke a weight edit goes to. @@ -394,22 +410,125 @@ static BLANK_WEIGHT_STOPS: [f64; 2] = [0.25, 0.5]; /// scrubbing by its label, blank when mixed. A plain step stops at each preset (0.52 pt goes down to 0.5 pt, not to /// 0 pt); Shift or Page steps the grid by ten. // PLAN: the sheet names `NumberField<'static, f64>`; `NumberField::length` takes `Option`. -pub(crate) fn weight_number(app: &VectorcraftApp, weight: Option) -> NumberField<'static> { - let field = steps_weight(app, weight); +pub(crate) fn weight_number(app: &VectorcraftApp, weight: Option, target: &EditTarget) -> NumberField<'static> { + let field = steps_weight(app, weight, target); match weight_ladder(app) { Some(l) => field.presets(&l.rows), None => field, } } +/// The document edit state and session destination before a preview. +/// A field drops its unfinished value when either changes. +#[derive(Clone, Debug, Hash, PartialEq, Eq)] +pub(crate) struct Target { + /// The document. + doc: u64, + /// How many times File > Revert replaced the document's content. + reverts: u64, + /// The revision of the document that the next preview builds on. + revision: u64, + /// The pre-preview new-art paint state. + new_art: u64, + /// Whether new art uses a basic appearance. + new_art_basic: bool, + /// The selected objects and subjects, in targeting order. + objects: Vec, + subjects: Vec, + /// The active appearance row. + row: Option, + /// The selected object inside a dynamic symbol instance: its instance and path through the symbol's art. + symbol_part: Option<(NodeId, Vec)>, + /// Whether the Live Paint Bucket's stroke is edited. + bucket: bool, + /// The type object and characters the Type tool has selected. + characters: Option<(NodeId, usize, usize)>, + /// The frame ids in thread order when the Type tool has selected the whole story. + story: Option>, + /// The members and placement transforms used to propagate Global Edit changes. + global_edit: GlobalEditTarget, + /// Distinguishes a canceled gesture from a replacement with the same starting content. + gesture: u64, +} + +/// The edit target of the Stroke panel's fields, `None` without a document. +pub(crate) type EditTarget = Option; + +/// The [`EditTarget`] of the active document. +pub(crate) fn edit_target(app: &VectorcraftApp, _ctx: &egui::Context) -> EditTarget { + let st = app.session.active()?; + Some(Target { + doc: st.uid, + reverts: st.reverts, + revision: st.interaction.as_ref().map_or(st.revision, |it| it.revision), + new_art: if may_edit_new_art(app) { + paint_digest(vectorcraft_engine::inspect::new_art_paint_before_preview(&app.session)) + } else { + vectorcraft_engine::inspect::new_art_paint_before_preview(&app.session).stroke_width.to_bits() + }, + new_art_basic: app.session.prefs.new_art_basic, + objects: st.selection.objects.clone(), + subjects: st.selection.subjects().to_vec(), + row: app.session.appearance_item(), + symbol_part: st.selection.symbol_part.as_ref().map(|part| (part.instance, part.path.clone())), + bucket: app.session.tool_paints(true), + characters: character::text_editing(app), + story: character::text_story(app), + global_edit: st.global_edit.as_ref().map(|ge| ge.members.iter().map(|(id, xf)| (*id, xf.as_coeffs().map(f64::to_bits))).collect()), + gesture: 0, + }) +} + +pub(crate) fn target_key(target: &EditTarget) -> u64 { + let mut hasher = DefaultHasher::new(); + target.hash(&mut hasher); + hasher.finish() +} + +/// Whether the fields can edit the new-art paint. A selected path the Stroke panel edits directly +/// (not a guide, a clipping path or a Live Paint part) is always a target, so with one selected +/// the fields edit objects and the target skips formatting the new-art paint. +fn may_edit_new_art(app: &VectorcraftApp) -> bool { + use vectorcraft_tools::builder::{SOURCES_NAME, is_live_paint}; + let Some(st) = app.session.active() else { return true }; + if app.session.tool_paints(true) { + return true; + } + let d = &st.doc; + let edited_path = |id: NodeId| { + d.node(id).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Path { guide: false, clipping: false, .. }) && !n.is_ruler_guide()) + && d.parent_of(id).and_then(|p| d.node(p)).is_none_or(|p| !is_live_paint(p) && p.name.as_deref() != Some(SOURCES_NAME)) + }; + !st.selection.objects.iter().any(|id| edited_path(*id)) +} + +fn paint_digest(paint: &impl std::fmt::Debug) -> u64 { + use std::fmt::Write as _; + + struct HashSink(DefaultHasher); + impl std::fmt::Write for HashSink { + fn write_str(&mut self, s: &str) -> std::fmt::Result { + self.0.write(s.as_bytes()); + Ok(()) + } + } + + let mut sink = HashSink(DefaultHasher::new()); + let _ = write!(sink, "{paint:?}"); + sink.0.finish() +} + /// [`weight_number`] without the presets list: a plain step still stops at each preset. -pub(crate) fn steps_weight(app: &VectorcraftApp, weight: Option) -> NumberField<'static> { +pub(crate) fn steps_weight(app: &VectorcraftApp, weight: Option, target: &impl egui::AsIdSalt) -> NumberField<'static> { let unit = app.session.stroke_unit(); let lengths = crate::fields::bare_points(LengthUnits::new(UnitKind::Points, shown_kind(unit), 72.0), app.session.prefs.numbers_without_units_are_points); let ladder = weight_ladder(app); - let field = - NumberField::length(tl!("Weight"), Bind::given(weight), lengths).range(0.0..=1000.0).step_arrows(StepArrows::Leading).scrub_by_label(); + let field = NumberField::length(tl!("Weight"), Bind::given(weight), lengths) + .range(0.0..=1000.0) + .step_arrows(StepArrows::Leading) + .scrub_by_label() + .edit_target(target); // The stepper steps the number the field shows; the ladders are in points. let in_points = move |stops: &'static [f64], blank: bool| { let step = crate::fields::stops_stepper(1.0, stops, move |pt| unit.format(pt)); @@ -452,8 +571,15 @@ pub(crate) fn apply_weight(app: &mut VectorcraftApp, out: &NumberOutput, target: /// The weight field in a row labelled `label` with the side label `side`: the field response and the output of /// the number field when the row's body ran. -fn weight_row(app: &VectorcraftApp, ui: &mut Ui, label: &'static str, side: SideLabel, weight: Option) -> Inner { - Field::new(label).side(side).id_salt("weight").sizing(Sizing::Content).show(ui, |ui, _| weight_number(app, weight).show(ui)) +fn weight_row( + app: &VectorcraftApp, + ui: &mut Ui, + label: &'static str, + side: SideLabel, + weight: Option, + target: &EditTarget, +) -> Inner { + Field::new(label).side(side).id_salt("weight").sizing(Sizing::Content).show(ui, |ui, _| weight_number(app, weight, target).show(ui)) } /// The weight field whose link side label (`label`: the Control bar's "Stroke:", the Properties panel's "Stroke") @@ -461,7 +587,8 @@ fn weight_row(app: &VectorcraftApp, ui: &mut Ui, label: &'static str, side: Side /// Weight: the label beside the Stroke chip says which paint it is the weight of. pub(crate) fn link_field(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, weight: Option) { let side = SideLabel::new().scrub(true).link().role(FieldLabelRole::Describes).tooltip(TooltipSpec::new(tl!("Stroke options"))); - let field = weight_row(app, ui, label, side, weight); + let target = edit_target(app, ui.ctx()); + let field = weight_row(app, ui, label, side, weight, &target); let open_id = field.output.id.with("stroke_popover_open"); let mut open = ui.data(|d| d.get_temp::(open_id).unwrap_or(false)); if let Some(out) = field.inner { @@ -492,30 +619,66 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// Keeps a group's starting key while its own gesture runs in the same targeting state. +fn gesture_target(gesture: &mut FieldGesture, target: EditTarget) -> EditTarget { + let changed = gesture.held.as_ref().is_some_and(|(_, produced)| produced != &target); + if changed { + gesture.held = None; + gesture.serial = gesture.serial.wrapping_add(1); + } + let mut target = gesture.held.as_ref().map_or(target, |(target, _)| target.clone()); + if let Some(target) = &mut target { + target.gesture = gesture.serial; + } + target +} + +/// Keeps the starting target and the content produced after the component's edits are applied. +fn remember_gesture(gesture: &mut FieldGesture, target: &EditTarget, events: &craft::behavior::EditEvents, produced: EditTarget) { + for event in events.iter() { + match event { + EditEvent::Begin { .. } => gesture.held = Some((target.clone(), produced.clone())), + EditEvent::Commit { .. } | EditEvent::Cancel { .. } => gesture.held = None, + _ => {} + } + } + if let Some((_, last)) = &mut gesture.held { + *last = produced; + } +} + /// The rows of [`show`]. fn rows(app: &mut VectorcraftApp, ui: &mut Ui) { let st = current_stroke(app); let mixed = stroke_mixed(app, ui.ctx()); let weight = shown_weight(app, st.as_ref(), &mixed); - if let Some(out) = weight_row(app, ui, tl!("Weight"), SideLabel::new().scrub(true), weight).inner { + let mut target = edit_target(app, ui.ctx()); + if let Some(out) = weight_row(app, ui, tl!("Weight"), SideLabel::new().scrub(true), weight, &target).inner { apply_weight(app, &out, WeightTarget::Shown); + target = edit_target(app, ui.ctx()); } if app.ui.stroke_panel.hide_options { + app.ui.stroke_panel.editor_gesture.held = None; + app.ui.stroke_panel.scale_gesture.held = None; return; } let style = style_of(st.as_ref()); + let editor_target = gesture_target(&mut app.ui.stroke_panel.editor_gesture, target.clone()); let editor = StrokeEditor::new(tl!("Stroke"), Bind::given(style.clone())) .sections(StrokeSections::PANEL | StrokeSections::DASH_ALIGN) .closed(mixed.can_align) .caps_on_closed(true) .mixed(&mixed_of(&mixed)) - .host_labels(true); + .host_labels(true) + .edit_target(&editor_target); let output = editor.show(ui); if let (Some(new), Some(field)) = (output.events.landed(), output.field) { apply_style(app, &style, new.clone(), field); + target = edit_target(app, ui.ctx()); } + remember_gesture(&mut app.ui.stroke_panel.editor_gesture, &editor_target, &output.events, target.clone()); Divider::horizontal().show(ui); - arrow_rows(app, ui, st.as_ref()); + arrow_rows(app, ui, st.as_ref(), target); Divider::horizontal().show(ui); Field::new(tl!("Profile")).show(ui, |ui, _| { Row::new().wrap(true).show(ui, |ui, _| { @@ -525,8 +688,11 @@ fn rows(app: &mut VectorcraftApp, ui: &mut Ui) { }); } -/// The arrowhead rows: the start and end heads with Swap, the two scales with their link, and the alignment. -fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>) { +/// The arrowhead rows: the start and end heads with Swap, the two scales with their link, and the alignment. `target` +/// is the current edit target used to track scale gestures. +fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>, target: EditTarget) { + let scale_target = gesture_target(&mut app.ui.stroke_panel.scale_gesture, target.clone()); + let mut updated = false; let custom: Vec = app.session.arrowheads.heads().iter().cloned().map(Arrowhead::Custom).collect(); let entries: Vec>> = std::iter::once(None) .chain(Arrowhead::ALL.iter().cloned().map(Some)) @@ -551,10 +717,12 @@ fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>) { let out = if listed { select } else { select.unlisted_label(unlisted_arrow_name(head.as_ref())) }.show(ui); // A custom head goes with its art, as document.inspect reports it. apply_select(app, key, &out, |app, a| set(app, json!({ key: a }))); + updated |= out.events.iter().next().is_some(); } let swap = IconButton::new(IconId::new("arrow-left-right")).label(tl!("Swap start and end arrowheads")).enabled(st.is_some()).show(ui); if swap.clicked() { app.run("stroke.setAdvanced", json!({"swapArrows": true})).ok(); + updated = true; } }); }); @@ -568,6 +736,7 @@ fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>) { .mode(LinkMode::Equal) .unit_kind(UnitKind::Percent) .enabled(has_head) + .edit_target(&scale_target) .show(ui) }) .inner; @@ -576,6 +745,13 @@ fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>) { } if let Some([a, b]) = out.as_ref().and_then(|out| out.edit.events.landed()).map(|p| (*p).map(|m| m.same().copied().flatten())) { app.run("stroke.setAdvanced", json!({"arrowScale": [a.unwrap_or(scale.0), b.unwrap_or(scale.1)]})).ok(); + updated = true; + } + if let Some(out) = &out { + let produced = if updated { edit_target(app, ui.ctx()) } else { target }; + remember_gesture(&mut app.ui.stroke_panel.scale_gesture, &scale_target, &out.edit.events, produced); + } else { + app.ui.stroke_panel.scale_gesture.held = None; } let aligns: Vec> = ARROW_ALIGN.iter().map(|(v, _, icon, tip)| Entry::new(*v, *tip).icon(IconId::new(icon))).collect(); let out = Field::new(tl!("Align")) @@ -1021,6 +1197,15 @@ mod tests { use super::*; use crate::tests::panel_harness::Panel; + #[test] + fn paint_digest_tracks_stroke_width() { + let paint = PaintDefaults::default(); + let mut changed = paint.clone(); + assert_eq!(paint_digest(&paint), paint_digest(&changed)); + changed.stroke_width += 1.0; + assert_ne!(paint_digest(&paint), paint_digest(&changed)); + } + #[test] fn editing_an_extended_dash_keeps_other_stroke_options_and_is_undoable() { use vectorcraft_engine::Session; @@ -1042,6 +1227,41 @@ mod tests { assert_eq!(current_stroke(&app).unwrap(), after); } + /// A field group's running gesture keeps the target it began with while its own edits change the stroke, and + /// takes the current target again once the gesture ends or the selection changes. + #[test] + fn a_gesture_keeps_its_starting_target_until_it_ends() { + let (mut app, path) = profiled_line(None); + let other = app.run("shape.line", json!({"x1": 10, "y1": 80, "x2": 90, "y2": 80})).unwrap(); + app.run("select.set", json!({"ids": [path["id"]]})).unwrap(); + let ctx = egui::Context::default(); + let shown = |target: &EditTarget| format!("{target:?}"); + let event = |e: EditEvent| craft::behavior::EditEvents::from(e); + let id = GestureId::new(1); + let mut gesture = FieldGesture::default(); + + let start = edit_target(&app, &ctx); + remember_gesture(&mut gesture, &start, &event(EditEvent::begin(id, Mixed::Same(10.0), std::sync::Arc::from("Miter"), None)), start.clone()); + app.run("stroke.set", json!({"miterLimit": 22})).unwrap(); + let fresh = edit_target(&app, &ctx); + assert_ne!(shown(&fresh), shown(&start), "the gesture's own edit changes the stroke's target"); + remember_gesture(&mut gesture, &start, &craft::behavior::EditEvents::::new(), fresh.clone()); + let held = gesture_target(&mut gesture, fresh.clone()); + assert_eq!(shown(&held), shown(&start), "the running gesture keeps its starting target"); + + remember_gesture(&mut gesture, &held, &event(EditEvent::commit(id, Mixed::Same(10.0), 22.0)), fresh.clone()); + let fresh = edit_target(&app, &ctx); + assert_eq!(shown(&gesture_target(&mut gesture, fresh)), shown(&edit_target(&app, &ctx)), "a commit ends it"); + + let start = edit_target(&app, &ctx); + remember_gesture(&mut gesture, &start, &event(EditEvent::begin(id, Mixed::Same(22.0), std::sync::Arc::from("Miter"), None)), start.clone()); + app.run("select.set", json!({"ids": [other["id"]]})).unwrap(); + let fresh = edit_target(&app, &ctx); + let now = gesture_target(&mut gesture, fresh); + assert_ne!(shown(&now), shown(&start), "another selection ends the held target"); + assert!(gesture.held.is_none()); + } + /// The Profile and arrowhead selects name a current value that is none of their choices on the closed face, and /// the open list keeps only the choices. #[test] diff --git a/crates/ui-egui/src/panels/tests_stroke.rs b/crates/ui-egui/src/panels/tests_stroke.rs index 66cf954339..04057e291d 100644 --- a/crates/ui-egui/src/panels/tests_stroke.rs +++ b/crates/ui-egui/src/panels/tests_stroke.rs @@ -1,6 +1,9 @@ -//! Headless frames of the Stroke panel's Dashed Line section. +//! Headless frames of the Stroke panel: its Dashed Line section, its row layout, and what its number fields edit. +use craft::ui::contract::Role; +use egui::{Key, Modifiers}; use serde_json::json; +use vectorcraft_doc::NodeId; use crate::tests::panel_harness::Panel; // PLAN: assumed path of object-panels-w8's `Panel` harness (op.A15). @@ -41,3 +44,1155 @@ fn the_panel_rows_start_their_controls_at_one_x() { let first = starts[0].1; assert!(starts.iter().all(|(_, x)| (x - first).abs() < 0.5), "controls start at {starts:?}"); } + +/// A document with two lines, `a` and `b`, with the same dashed stroke and start arrowhead, and `a` selected. +fn two_lines() -> (VectorcraftApp, NodeId, NodeId) { + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + run(&mut app, "file.new", json!({"width": 200, "height": 200})); + let mut line = |y: f64| NodeId(run(&mut app, "shape.line", json!({"x1": 10, "y1": y, "x2": 190, "y2": y}))["id"].as_u64().unwrap()); + let (a, b) = (line(50.0), line(150.0)); + let head = serde_json::to_value(&vectorcraft_doc::Arrowhead::ALL[0]).unwrap(); + run(&mut app, "select.set", json!({"ids": [a.0, b.0]})); + run(&mut app, "stroke.set", json!({"dash": [12, 12], "startArrow": head})); + run(&mut app, "select.set", json!({"ids": [a.0]})); + (app, a, b) +} + +/// The top stroke of object `id`. +fn stroke_of(app: &VectorcraftApp, id: NodeId) -> vectorcraft_doc::StrokeLayer { + app.session.active().unwrap().doc.node(id).unwrap().appearance.stroke().unwrap().clone() +} + +/// Starts an unfinished value in the number field `name`: selects its text and types `3+`. +fn start_typing(p: &mut Panel, name: &str) { + p.click_role(name, Role::SPIN_BUTTON); + p.key(Key::A, Modifiers::COMMAND); + p.type_text("3+"); +} + +/// Types `5` into the focused field and presses Enter. +fn finish_typing(p: &mut Panel) { + p.type_text("5"); + p.key(Key::Enter, Modifiers::NONE); +} + +#[test] +fn an_unfinished_value_does_not_reach_another_line_with_the_same_stroke() { + type Read = fn(&vectorcraft_doc::StrokeLayer) -> f64; + let fields: [(&str, Read); 6] = [ + ("Weight", |s| s.width), + ("Miter limit", |s| s.miter_limit), + ("Dash 1", |s| s.dash.as_ref().map_or(0.0, |d| d.pattern[0])), + ("Gap 1", |s| s.dash.as_ref().map_or(0.0, |d| d.pattern[1])), + ("Dash offset", |s| s.dash.as_ref().map_or(0.0, |d| d.offset)), + ("Scale 1", |s| s.arrow_scale.0), + ]; + for (name, read) in fields { + let (app, a, b) = two_lines(); + let before = read(&stroke_of(&app, a)); + assert_eq!(before, read(&stroke_of(&app, b)), "{name}: both lines start with one value"); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, name); + p.app().run("select.set", json!({"ids": [b.0]})).unwrap(); + p.frame(); + assert_ne!(p.value_role(name, Role::SPIN_BUTTON).as_deref(), Some("3+"), "{name}: the field drops the value typed for a"); + finish_typing(&mut p); + let app = p.app(); + assert_eq!((read(&stroke_of(&app, a)), read(&stroke_of(&app, b))), (before, 5.0), "{name}: b takes 5, not 3+5"); + } +} + +/// The weight field the Control bar and the Properties panel show beside their Stroke link label. +fn show_link_field(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + let shown = current_stroke(app); + let mixed = stroke_mixed(app, ui.ctx()); + let weight = stroke::shown_weight(app, shown.as_ref(), &mixed); + stroke::link_field(app, ui, "Stroke:", weight); +} + +#[test] +fn an_unfinished_link_field_weight_does_not_reach_another_line() { + let (mut app, a, b) = two_lines(); + run(&mut app, "select.set", json!({"ids": [a.0, b.0]})); + run(&mut app, "stroke.set", json!({"weight": 2})); + run(&mut app, "select.set", json!({"ids": [a.0]})); + let mut p = Panel::new(app, show_link_field); + start_typing(&mut p, "Weight"); + p.app().run("select.set", json!({"ids": [b.0]})).unwrap(); + p.frame(); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+"), "the field drops the value typed for a"); + p.type_text("1"); + p.key(Key::Enter, Modifiers::NONE); + let app = p.app(); + assert_eq!((stroke_of(&app, a).width, stroke_of(&app, b).width), (2.0, 1.0), "b takes 1 pt, not 3+1, and a keeps 2 pt"); +} + +#[test] +fn changing_the_new_art_width_drops_an_unfinished_weight_on_a_selected_path() { + let mut app = app_with_rect(); + let id = app.session.active().unwrap().selection.objects[0]; + run(&mut app, "stroke.set", json!({"weight": 2})); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + p.app().run("stroke.set", json!({"defaultsOnly": true, "weight": 7})).unwrap(); + p.frame(); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+")); + p.type_text("1"); + p.key(Key::Enter, Modifiers::NONE); + let app = p.app(); + assert_ne!(app.session.paint.stroke_width, 4.0, "the new-art width does not receive the unfinished expression"); + assert_eq!(stroke_of(&app, id).width, 1.0); +} + +#[test] +fn replacing_the_new_art_stroke_drops_an_unfinished_weight() { + let (mut app, _, _) = two_lines(); + run(&mut app, "select.set", json!({"ids": []})); + let before = app.session.new_art_stroke(); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + p.app().run("stroke.set", json!({"cap": "round"})).unwrap(); + assert_eq!(p.app().session.new_art_stroke().width, before.width); + assert_ne!(p.app().session.new_art_stroke().cap, before.cap); + p.frame(); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+")); + finish_typing(&mut p); + assert_eq!(p.app().session.new_art_stroke().width, 5.0); +} + +#[test] +fn adding_an_identical_new_art_stroke_drops_an_unfinished_weight() { + let (mut app, _, _) = two_lines(); + let name = run(&mut app, "graphicStyle.new", json!({"name": "Stroke"}))["name"].as_str().unwrap().to_owned(); + run(&mut app, "select.set", json!({"ids": []})); + run(&mut app, "graphicStyle.apply", json!({"name": name})); + let before = app.session.new_art(); + assert_eq!(before.items.iter().filter(|item| !item.is_fill()).count(), 1); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + p.app().run("graphicStyle.apply", json!({"name": name, "add": true})).unwrap(); + let after = p.app().session.new_art(); + assert_eq!(after.items.iter().filter(|item| !item.is_fill()).count(), 2); + assert_eq!(before.stroke(), after.stroke()); + p.frame(); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+")); + finish_typing(&mut p); + let app = p.app(); + assert_eq!(app.session.new_art_stroke().width, 5.0); + assert_eq!(app.session.new_art().items.iter().filter(|item| !item.is_fill()).count(), 2, "new art keeps both strokes"); + assert!(app.session.new_art().items.iter().all(|item| match item { + vectorcraft_doc::AppearanceItem::Stroke(stroke) => stroke.width != 8.0, + _ => true, + })); +} + +#[test] +fn changing_a_later_character_stroke_drops_an_unfinished_weight() { + use vectorcraft_doc::NodeKind; + let mut app = app_with_rect(); + let id = NodeId(run(&mut app, "text.create", json!({"x": 20, "y": 100, "text": "Stroke"}))["id"].as_u64().unwrap()); + run(&mut app, "select.set", json!({"ids": [id.0]})); + run(&mut app, "paint.setStroke", json!({"color": "#ff0000"})); + let before = app.session.shown_stroke().unwrap().width; + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + p.app().run("text.setRangeStyle", json!({"id": id.0, "start": 2, "end": 6, "strokeOptions": {"weight": 2}})).unwrap(); + assert_eq!(p.app().session.shown_stroke().unwrap().width, before); + p.frame(); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+")); + p.type_text("1"); + p.key(Key::Enter, Modifiers::NONE); + let app = p.app(); + let NodeKind::Text(t) = &app.session.active().unwrap().doc.node(id).unwrap().kind else { panic!("type") }; + assert_eq!(t.plain_text(), "Stroke"); + assert!(!t.runs.is_empty(), "the text keeps its runs"); + assert!(t.runs.iter().all(|run| run.style.stroke_width == 1.0), "each character takes the fresh weight"); +} + +#[test] +fn a_collapsed_type_caret_drops_an_unfinished_weight_when_other_characters_change() { + use vectorcraft_doc::NodeKind; + let mut app = app_with_rect(); + let id = NodeId(run(&mut app, "text.create", json!({"x": 20, "y": 100, "text": "Stroke"}))["id"].as_u64().unwrap()); + run(&mut app, "text.setRangeStyle", json!({"id": id.0, "strokeOptions": {"weight": 1}})); + run(&mut app, "select.set", json!({"ids": [id.0]})); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": id.0, "anchor": 1, "caret": 1})); + assert_eq!(character::text_editing(&app), Some((id, 1, 1))); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + p.app().run("text.setRangeStyle", json!({"id": id.0, "start": 3, "end": 6, "strokeOptions": {"weight": 2}})).unwrap(); + p.frame(); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+")); + p.type_text("1"); + p.key(Key::Enter, Modifiers::NONE); + let app = p.app(); + let NodeKind::Text(t) = &app.session.active().unwrap().doc.node(id).unwrap().kind else { panic!("type") }; + assert_eq!(t.plain_text(), "Stroke"); + assert!(!t.runs.is_empty(), "the text keeps its runs"); + assert!(t.runs.iter().all(|run| run.style.stroke_width != 4.0), "the unfinished expression reaches no character"); + assert!(t.runs.iter().all(|run| run.style.stroke_width == 1.0), "the fresh weight edits the whole frame"); +} + +#[test] +fn moving_a_run_boundary_in_selected_characters_drops_an_unfinished_weight() { + use vectorcraft_doc::NodeKind; + let mut app = app_with_rect(); + let id = NodeId(run(&mut app, "text.create", json!({"x": 20, "y": 100, "text": "Stroke"}))["id"].as_u64().unwrap()); + run(&mut app, "text.setRangeStyle", json!({"id": id.0, "start": 0, "end": 2, "strokeOptions": {"weight": 1}})); + run(&mut app, "text.setRangeStyle", json!({"id": id.0, "start": 2, "end": 6, "strokeOptions": {"weight": 2}})); + run(&mut app, "select.set", json!({"ids": [id.0]})); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": id.0, "anchor": 1, "caret": 5})); + assert_eq!(character::text_editing(&app), Some((id, 1, 5))); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + p.app().run("text.setRangeStyle", json!({"id": id.0, "start": 2, "end": 3, "strokeOptions": {"weight": 1}})).unwrap(); + p.frame(); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+")); + p.type_text("1"); + p.key(Key::Enter, Modifiers::NONE); + let app = p.app(); + let NodeKind::Text(t) = &app.session.active().unwrap().doc.node(id).unwrap().kind else { panic!("type") }; + assert!(t.runs.iter().all(|run| run.style.stroke_width != 4.0), "the unfinished expression reaches no character"); + let widths: Vec<_> = t.runs.iter().map(|run| (run.text.as_str(), run.style.stroke_width)).collect(); + assert_eq!(widths, [("Strok", 1.0), ("e", 2.0)], "the fresh weight edits only the selected characters"); +} + +/// Enables drags on numeric field bodies while showing the Stroke panel. +fn show_with_field_scrubbing(app: &mut VectorcraftApp, ui: &mut egui::Ui) { + use craft::ui::runtime::env::{ScrubDrags, with_env}; + with_env( + ui, + |env| { + env.values.set(ScrubDrags::FieldAndLabel); + }, + |ui| stroke::show(app, ui), + ); +} + +#[test] +fn moving_another_stroke_to_the_top_ends_a_held_dash_scrub() { + let (mut app, a, _) = two_lines(); + run(&mut app, "appearance.addStroke", json!({})); + run(&mut app, "stroke.set", json!({"dash": [12, 12]})); + run(&mut app, "appearance.moveItem", json!({"from": 0, "to": 2})); + assert_eq!(app.session.active().unwrap().doc.node(a).unwrap().appearance.items.iter().rposition(|item| !item.is_fill()), Some(1)); + let mut p = Panel::new(app, show_with_field_scrubbing); + p.drag_hold_role("Dash 1", Role::SPIN_BUTTON, egui::vec2(12.0, 0.0)); + let first = stroke_of(&p.app(), a).dash.unwrap().pattern[0]; + let at = p.ctx().input(|i| i.pointer.latest_pos()).unwrap(); + p.frame_with(vec![egui::Event::PointerMoved(at + egui::vec2(24.0, 0.0))]); + assert!(stroke_of(&p.app(), a).dash.unwrap().pattern[0] > first, "the held gesture changes its starting stroke"); + p.app().run("appearance.moveItem", json!({"from": 0, "to": 2})).unwrap(); + assert_eq!(p.app().session.active().unwrap().doc.node(a).unwrap().appearance.items.iter().rposition(|item| !item.is_fill()), Some(2)); + let before = stroke_of(&p.app(), a); + p.frame(); + let at = p.ctx().input(|i| i.pointer.latest_pos()).unwrap(); + p.frame_with(vec![egui::Event::PointerMoved(at + egui::vec2(48.0, 0.0))]); + p.frame(); + p.release(); + assert_eq!(stroke_of(&p.app(), a), before, "later pointer moves leave the new top stroke unchanged"); +} + +#[test] +fn swapping_the_top_strokes_ends_a_held_scrub_at_the_same_row() { + let (mut app, a, _) = two_lines(); + run(&mut app, "appearance.addStroke", json!({})); + run(&mut app, "stroke.set", json!({"dash": [12, 12]})); + let top = app.session.active().unwrap().doc.node(a).unwrap().appearance.items.iter().rposition(|item| !item.is_fill()); + let mut p = Panel::new(app, show_with_field_scrubbing); + p.drag_hold_role("Dash 1", Role::SPIN_BUTTON, egui::vec2(12.0, 0.0)); + let first = stroke_of(&p.app(), a).dash.unwrap().pattern[0]; + let at = p.ctx().input(|i| i.pointer.latest_pos()).unwrap(); + p.frame_with(vec![egui::Event::PointerMoved(at + egui::vec2(24.0, 0.0))]); + p.frame(); + assert!(stroke_of(&p.app(), a).dash.unwrap().pattern[0] > first, "the scrub keeps changing its starting stroke"); + p.app().run("appearance.moveItem", json!({"from": 1, "to": 2})).unwrap(); + assert_eq!(p.app().session.active().unwrap().doc.node(a).unwrap().appearance.items.iter().rposition(|item| !item.is_fill()), top); + let before = stroke_of(&p.app(), a); + p.frame(); + let at = p.ctx().input(|i| i.pointer.latest_pos()).unwrap(); + p.frame_with(vec![egui::Event::PointerMoved(at + egui::vec2(48.0, 0.0))]); + p.frame(); + p.release(); + assert_eq!(stroke_of(&p.app(), a), before, "the held scrub leaves the replacement stroke unchanged"); +} + +#[test] +fn changing_global_edit_members_drops_an_unfinished_weight() { + for change in ["start", "stop", "exclude"] { + let mut app = app_with_rect(); + let a = app.session.active().unwrap().selection.objects[0]; + let b = NodeId(run(&mut app, "edit.duplicate", json!({"dx": 20}))["ids"][0].as_u64().unwrap()); + let c = NodeId(run(&mut app, "edit.duplicate", json!({"dy": 20}))["ids"][0].as_u64().unwrap()); + run(&mut app, "select.set", json!({"ids": [a.0]})); + if change != "start" { + run(&mut app, "select.globalEdit", json!({})); + assert_eq!(app.session.active().unwrap().global_edit.as_ref().unwrap().members.len(), 3); + } + let before = [a, b, c].map(|id| stroke_of(&app, id)); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + if change == "exclude" { + p.app().run("select.globalEditExclude", json!({"id": b.0})).unwrap(); + } else { + p.app().run("select.globalEdit", json!({})).unwrap(); + } + p.frame(); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+"), "{change}: the draft is dropped"); + finish_typing(&mut p); + for (id, before) in [a, b, c].into_iter().zip(before) { + let after = stroke_of(&p.app(), id); + assert_ne!(after.width, 8.0, "{change}: the unfinished value reaches no member"); + assert!(after.width == before.width || after.width == 5.0, "{change}: only the fresh weight can be applied"); + } + assert_eq!(stroke_of(&p.app(), a).width, 5.0, "{change}: the field still takes a fresh weight"); + } +} + +#[test] +fn replacing_text_with_the_same_byte_length_drops_an_unfinished_weight() { + use vectorcraft_doc::NodeKind; + let mut app = app_with_rect(); + let id = NodeId(run(&mut app, "text.create", json!({"x": 20, "y": 100, "text": "Stroke"}))["id"].as_u64().unwrap()); + run(&mut app, "select.set", json!({"ids": [id.0]})); + run(&mut app, "paint.setStroke", json!({"color": "#ff0000"})); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + p.app().run("text.setText", json!({"id": id.0, "text": "Weight"})).unwrap(); + p.frame(); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+")); + finish_typing(&mut p); + let app = p.app(); + let NodeKind::Text(t) = &app.session.active().unwrap().doc.node(id).unwrap().kind else { panic!("type") }; + assert_eq!(t.plain_text(), "Weight"); + assert!(!t.runs.is_empty(), "the replacement text has runs"); + assert!(t.runs.iter().all(|run| run.style.stroke_width == 5.0), "the replacement text takes only the fresh value"); +} + +#[test] +fn a_new_art_weight_scrub_keeps_going() { + let (mut app, _, _) = two_lines(); + run(&mut app, "select.set", json!({"ids": []})); + let mut p = Panel::new(app, stroke::show); + p.drag_hold_role("Weight", Role::LABEL, egui::vec2(12.0, 0.0)); + let first = p.app().session.new_art_stroke().width; + p.frame(); + let at = p.ctx().input(|i| i.pointer.latest_pos()).unwrap(); + p.frame_with(vec![egui::Event::PointerMoved(at + egui::vec2(24.0, 0.0))]); + p.frame(); + let further = p.app().session.new_art_stroke().width; + assert!(further > first, "the held scrub keeps increasing the new-art weight"); + p.release(); + assert_eq!(p.app().session.new_art_stroke().width, further); +} + +#[test] +fn an_unfinished_weight_stays_with_its_line_and_document() { + let (mut app, a, _) = two_lines(); + // A second document built the same way: its line `a` has the same id and weight. + run(&mut app, "file.new", json!({"width": 200, "height": 200})); + let other = run(&mut app, "shape.line", json!({"x1": 10, "y1": 50, "x2": 190, "y2": 50}))["id"].as_u64().unwrap(); + assert_eq!(other, a.0, "both documents' lines have the same id"); + run(&mut app, "select.set", json!({"ids": [a.0]})); + run(&mut app, "document.activate", json!({"index": 0})); + let mut p = Panel::new(app, stroke::show); + + // With the selection and the document unchanged, the value typed so far is kept: 3+5 gives 8. + start_typing(&mut p, "Weight"); + p.frame(); + finish_typing(&mut p); + assert_eq!(stroke_of(&p.app(), a).width, 8.0, "an unchanged target keeps the typed value"); + p.app().run("stroke.set", json!({"weight": 1})).unwrap(); + + // Another document with the same selection drops it. + start_typing(&mut p, "Weight"); + p.app().run("document.activate", json!({"index": 1})).unwrap(); + p.frame(); + finish_typing(&mut p); + let width = |index: u64| { + p.app().run("document.activate", json!({"index": index})).unwrap(); + stroke_of(&p.app(), a).width + }; + assert_eq!((width(0), width(1)), (1.0, 5.0), "the other document takes 5 pt"); +} + +#[test] +fn an_unfinished_weight_is_dropped_by_file_revert() { + let (mut app, a, _) = two_lines(); + let dir = vectorcraft_testkit::TempDir::new("stroke-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("Lines.vectorcraft")})).unwrap(); + // An unsaved change for Revert to undo, leaving the lines as saved. + app.run("shape.rectangle", json!({"x": 100, "y": 80, "width": 20, "height": 20})).unwrap(); + app.run("select.set", json!({"ids": [a.0]})).unwrap(); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + + // The restored document has the same line and, selected again, the same selection. + p.app().run("file.revert", json!({"confirmed": true})).unwrap(); + p.app().run("select.set", json!({"ids": [a.0]})).unwrap(); + p.frame(); + finish_typing(&mut p); + assert_eq!(stroke_of(&p.app(), a).width, 5.0, "Revert drops the unfinished value"); +} + +#[test] +fn an_unfinished_weight_is_dropped_when_another_appearance_row_becomes_active() { + let (mut app, a, _) = two_lines(); + // Two strokes of 1 pt: the Stroke panel edits the active one. + run(&mut app, "appearance.addStroke", json!({})); + let strokes: Vec = { + let ap = &app.session.active().unwrap().doc.node(a).unwrap().appearance; + (0..ap.items.len()).filter(|i| ap.stroke_at(Some(*i)).is_some()).collect() + }; + let [first, second] = strokes[..] else { panic!("two stroke rows: {strokes:?}") }; + appearance::select_row(&mut app, appearance::Sel::Item(first)); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + appearance::select_row(&mut p.app(), appearance::Sel::Item(second)); + assert_eq!(p.app().session.appearance_item(), Some(second)); + p.frame(); + finish_typing(&mut p); + let widths = { + let app = p.app(); + let ap = &app.session.active().unwrap().doc.node(a).unwrap().appearance; + (ap.stroke_at(Some(first)).unwrap().width, ap.stroke_at(Some(second)).unwrap().width) + }; + assert_eq!(widths, (1.0, 5.0), "the second row takes 5 pt, not 3+5"); +} + +#[test] +fn an_unfinished_weight_is_dropped_when_its_layer_is_targeted() { + let (mut app, a, b) = two_lines(); + run(&mut app, "edit.clear", json!({"ids": [b.0]})); + let layer = app.session.active().unwrap().doc.parent_of(a).unwrap(); + // The layer's rows match the path's: a fill under a 1 pt stroke. + run(&mut app, "appearance.addFill", json!({"ids": [layer.0]})); + run(&mut app, "appearance.addStroke", json!({"ids": [layer.0]})); + assert_eq!(stroke_of(&app, a).width, stroke_of(&app, layer).width); + let fills = |id: NodeId| -> Vec { + app.session.active().unwrap().doc.node(id).unwrap().appearance.items.iter().map(|item| item.is_fill()).collect() + }; + assert_eq!(fills(a), fills(layer), "the path and the layer have their rows in one order"); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + // The path stays selected, and `stroke.set` with no active row still edits the path's stroke. + p.app().run("layer.target", json!({"id": layer.0})).unwrap(); + assert_eq!(p.app().session.active().unwrap().selection.objects, [a]); + assert_eq!(p.app().session.appearance_item(), None, "no row is active"); + p.frame(); + finish_typing(&mut p); + let app = p.app(); + assert_eq!((stroke_of(&app, a).width, stroke_of(&app, layer).width), (5.0, 1.0), "the subject change drops the draft and the layer keeps 1 pt"); +} + +#[test] +fn an_unfinished_weight_is_dropped_when_strokes_of_one_color_swap_places() { + let (mut app, a, _) = two_lines(); + run(&mut app, "appearance.addStroke", json!({})); + run(&mut app, "stroke.set", json!({"cap": "round"})); + let strokes: Vec = { + let ap = &app.session.active().unwrap().doc.node(a).unwrap().appearance; + (0..ap.items.len()).filter(|i| ap.stroke_at(Some(*i)).is_some()).collect() + }; + let [bottom, top] = strokes[..] else { panic!("two stroke rows: {strokes:?}") }; + { + let ap = &app.session.active().unwrap().doc.node(a).unwrap().appearance; + let (lower, upper) = (ap.stroke_at(Some(bottom)).unwrap(), ap.stroke_at(Some(top)).unwrap()); + assert_eq!((&lower.paint, lower.width), (&upper.paint, upper.width)); + assert_ne!(lower.cap, upper.cap); + } + let before = stroke_of(&app, a); + assert_eq!(app.session.appearance_item(), None); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + p.app().run("appearance.moveItem", json!({"from": top, "to": bottom})).unwrap(); + p.frame(); + finish_typing(&mut p); + let app = p.app(); + let moved = app.session.active().unwrap().doc.node(a).unwrap().appearance.stroke_at(Some(bottom)).unwrap(); + assert_eq!((moved.cap, moved.width), (before.cap, before.width), "the moved stroke keeps its weight"); + let shown = stroke_of(&app, a); + assert_ne!(shown.cap, before.cap, "the other stroke is now on top"); + assert_eq!(shown.width, 5.0, "the top stroke takes 5 pt, not 3+5"); +} + +#[test] +fn an_unfinished_weight_is_dropped_when_strokes_that_differ_in_miter_limit_swap() { + let mut app = app_with_rect(); + let a = app.session.active().unwrap().selection.objects[0]; + run(&mut app, "stroke.set", json!({"miterLimit": 4})); + run(&mut app, "appearance.addStroke", json!({})); + run(&mut app, "stroke.set", json!({"miterLimit": 10})); + let strokes: Vec = { + let ap = &app.session.active().unwrap().doc.node(a).unwrap().appearance; + (0..ap.items.len()).filter(|i| ap.stroke_at(Some(*i)).is_some()).collect() + }; + let [bottom, top] = strokes[..] else { panic!("two stroke rows: {strokes:?}") }; + { + let ap = &app.session.active().unwrap().doc.node(a).unwrap().appearance; + let (lower, upper) = (ap.stroke_at(Some(bottom)).unwrap(), ap.stroke_at(Some(top)).unwrap()); + assert_eq!(lower.width, upper.width); + assert_eq!((lower.miter_limit, upper.miter_limit), (4.0, 10.0)); + let mut matched = upper.clone(); + matched.miter_limit = lower.miter_limit; + assert_eq!(lower, &matched, "only the miter limits differ"); + } + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + p.app().run("appearance.moveItem", json!({"from": top, "to": bottom})).unwrap(); + p.frame(); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+")); + finish_typing(&mut p); + let app = p.app(); + let ap = &app.session.active().unwrap().doc.node(a).unwrap().appearance; + let (lower, upper) = (ap.stroke_at(Some(bottom)).unwrap(), ap.stroke_at(Some(top)).unwrap()); + assert_eq!((lower.miter_limit, upper.miter_limit), (10.0, 4.0)); + assert_eq!((lower.width, upper.width), (1.0, 5.0), "the top stroke takes a fresh 5 pt, not 3+5"); +} + +#[test] +fn a_miter_only_stroke_swap_drops_the_miter_draft() { + let (mut app, a, b) = two_lines(); + run(&mut app, "select.set", json!({"ids": [b.0]})); + run(&mut app, "stroke.set", json!({"miterLimit": 6})); + let lower = stroke_of(&app, b); + run(&mut app, "appearance.addStroke", json!({})); + let upper = stroke_of(&app, a); + app.session + .edit("Strokes", |d, _| { + let ap = &mut d.node_mut(b).unwrap().appearance; + let indices: Vec<_> = (0..ap.items.len()).filter(|i| ap.stroke_at(Some(*i)).is_some()).collect(); + *ap.stroke_at_mut(Some(indices[0])).unwrap() = lower.clone(); + *ap.stroke_at_mut(Some(indices[1])).unwrap() = upper.clone(); + Ok(()) + }) + .unwrap(); + let strokes: Vec<_> = { + let ap = &app.session.active().unwrap().doc.node(b).unwrap().appearance; + (0..ap.items.len()).filter(|i| ap.stroke_at(Some(*i)).is_some()).collect() + }; + let [bottom, top] = strokes[..] else { panic!("two stroke rows: {strokes:?}") }; + let mut matched = lower.clone(); + matched.miter_limit = upper.miter_limit; + assert_eq!(matched, upper, "only the miter limits differ"); + assert_ne!(lower.miter_limit, upper.miter_limit); + run(&mut app, "select.set", json!({"ids": [a.0, b.0]})); + let shown = current_stroke(&app).unwrap().miter_limit; + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Miter limit"); + assert_eq!(p.value_role("Miter limit", Role::SPIN_BUTTON).as_deref(), Some("3+")); + p.app().run("appearance.moveItem", json!({"ids": [b.0], "from": top, "to": bottom})).unwrap(); + p.frame(); + assert_eq!(current_stroke(&p.app()).unwrap().miter_limit, shown, "the first path keeps the shown value"); + assert_ne!(p.value_role("Miter limit", Role::SPIN_BUTTON).as_deref(), Some("3+"), "the field drops the draft"); + p.type_text("1"); + p.key(Key::Enter, Modifiers::NONE); + let app = p.app(); + for id in [a, b] { + let ap = &app.session.active().unwrap().doc.node(id).unwrap().appearance; + for i in 0..ap.items.len() { + if let Some(stroke) = ap.stroke_at(Some(i)) { + assert_ne!(stroke.miter_limit, 4.0, "the draft cannot reach either path's strokes"); + } + } + } +} + +#[test] +fn an_unfinished_weight_is_dropped_when_strokes_swap_places() { + let (mut app, a, _) = two_lines(); + run(&mut app, "paint.setStroke", json!({"color": "#ff0000"})); + run(&mut app, "appearance.addStroke", json!({})); + run(&mut app, "paint.setStroke", json!({"color": "#0000ff"})); + let strokes: Vec = { + let ap = &app.session.active().unwrap().doc.node(a).unwrap().appearance; + (0..ap.items.len()).filter(|i| ap.stroke_at(Some(*i)).is_some()).collect() + }; + let [bottom, top] = strokes[..] else { panic!("two stroke rows: {strokes:?}") }; + let before = stroke_of(&app, a); + assert_eq!(app.session.appearance_item(), None); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + p.app().run("appearance.moveItem", json!({"from": top, "to": bottom})).unwrap(); + p.frame(); + finish_typing(&mut p); + let app = p.app(); + let ap = &app.session.active().unwrap().doc.node(a).unwrap().appearance; + let moved = ap.stroke_at(Some(bottom)).unwrap(); + assert_eq!((moved.paint.clone(), moved.width), (before.paint.clone(), before.width), "the moved stroke keeps its weight"); + let shown = stroke_of(&app, a); + assert_ne!(shown.paint, before.paint, "the other stroke is now on top"); + assert_eq!(shown.width, 5.0, "the top stroke takes 5 pt, not 3+5"); +} + +#[test] +fn an_unfinished_weight_is_dropped_when_the_group_gets_its_own_stroke() { + let (mut app, a, b) = two_lines(); + run(&mut app, "select.set", json!({"ids": [a.0, b.0]})); + run(&mut app, "object.group", json!({})); + let group = app.session.active().unwrap().selection.objects[0]; + assert!(app.session.active().unwrap().doc.node(group).unwrap().appearance.stroke().is_none()); + let before = stroke_of(&app, a).width; + assert_eq!(stroke_of(&app, b).width, before); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + p.app().run("appearance.addStroke", json!({"ids": [group.0]})).unwrap(); + assert_eq!(stroke_of(&p.app(), group).width, before, "the group's stroke has the members' weight"); + p.frame(); + finish_typing(&mut p); + assert_eq!(stroke_of(&p.app(), group).width, 5.0, "the group's stroke takes 5 pt, not 3+5"); +} + +#[test] +fn an_unfinished_weight_is_dropped_when_a_group_member_gets_a_stroke_on_top() { + let (mut app, a, b) = two_lines(); + run(&mut app, "select.set", json!({"ids": [a.0, b.0]})); + run(&mut app, "object.group", json!({})); + let group = app.session.active().unwrap().selection.objects[0]; + assert!(app.session.active().unwrap().doc.node(group).unwrap().appearance.stroke().is_none()); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + p.app().run("appearance.addStroke", json!({"ids": [a.0]})).unwrap(); + p.frame(); + finish_typing(&mut p); + assert_eq!(stroke_of(&p.app(), a).width, 5.0, "the member's top stroke takes 5 pt, not 3+5"); +} + +#[test] +fn an_unfinished_arrowhead_scale_is_dropped_when_a_member_of_a_stroked_group_gets_a_stroke_on_top() { + let (mut app, a, b) = two_lines(); + run(&mut app, "select.set", json!({"ids": [a.0, b.0]})); + run(&mut app, "object.group", json!({})); + let group = app.session.active().unwrap().selection.objects[0]; + run(&mut app, "appearance.addStroke", json!({"ids": [group.0]})); + assert!(app.session.active().unwrap().doc.node(group).unwrap().appearance.stroke().is_some()); + assert_eq!(app.session.appearance_item(), None, "no row is active"); + let before = stroke_of(&app, b).arrow_scale; + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Scale 1"); + p.app().run("appearance.addStroke", json!({"ids": [b.0]})).unwrap(); + assert_eq!(stroke_of(&p.app(), b).arrow_scale, before, "the new top stroke has the same arrowhead scale"); + assert_eq!(p.app().session.active().unwrap().selection.objects, [group]); + assert_eq!(p.app().session.appearance_item(), None, "no row is active"); + p.frame(); + finish_typing(&mut p); + assert_eq!(stroke_of(&p.app(), b).arrow_scale.0, 5.0, "the member's top stroke takes 5, not 3+5"); +} + +#[test] +fn an_unfinished_weight_is_dropped_when_a_stroke_is_added_to_the_compound_of_a_selected_member() { + let (mut app, a, b) = two_lines(); + run(&mut app, "select.set", json!({"ids": [a.0, b.0]})); + let compound = NodeId(run(&mut app, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + run(&mut app, "select.set", json!({"ids": [a.0]})); + assert_eq!(app.session.active().unwrap().selection.objects, [a]); + assert_eq!(app.session.active().unwrap().doc.parent_of(a), Some(compound)); + let before = stroke_of(&app, compound).width; + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + p.app().run("appearance.addStroke", json!({"ids": [compound.0]})).unwrap(); + assert_eq!(p.app().session.active().unwrap().selection.objects, [a]); + assert_eq!(p.app().session.appearance_item(), None, "no row is active"); + assert_eq!(stroke_of(&p.app(), compound).width, before, "the top stroke has the same weight"); + p.frame(); + finish_typing(&mut p); + let app = p.app(); + let widths: Vec = app.session.active().unwrap().doc.node(compound).unwrap().appearance.painted_strokes().map(|s| s.width).collect(); + assert_eq!(widths, [before, 5.0], "the compound's new top stroke takes 5 pt, not 3+5"); + assert!(app.session.active().unwrap().doc.node(a).unwrap().appearance.stroke().is_none(), "the member has no stroke of its own"); +} + +#[test] +fn an_unfinished_weight_is_dropped_when_another_symbol_part_is_selected() { + let (mut app, a, b) = two_lines(); + let instance = run(&mut app, "symbol.new", json!({"name": "Lines", "ids": [a.0, b.0], "type": "dynamic"}))["id"].as_u64().unwrap(); + run(&mut app, "symbol.instance.selectPart", json!({"id": instance, "path": [0]})); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + p.app().run("symbol.instance.selectPart", json!({"id": instance, "path": [1]})).unwrap(); + p.frame(); + assert_eq!(p.app().session.active().unwrap().selection.objects, [NodeId(instance)]); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+"), "the field drops the first part's draft"); +} + +#[test] +fn an_unfinished_weight_is_dropped_when_a_fill_row_becomes_active() { + let (mut app, a, _) = two_lines(); + run(&mut app, "appearance.addFill", json!({})); + let fill = app.session.active().unwrap().doc.node(a).unwrap().appearance.items.iter().position(|item| item.is_fill()).unwrap(); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + appearance::select_row(&mut p.app(), appearance::Sel::Item(fill)); + assert_eq!(p.app().session.appearance_item(), Some(fill)); + p.frame(); + finish_typing(&mut p); + assert_eq!(stroke_of(&p.app(), a).width, 5.0, "the edit state change drops the unfinished value"); +} + +#[test] +fn an_unfinished_weight_is_dropped_when_the_live_paint_bucket_is_chosen() { + let (app, a, _) = two_lines(); + assert_eq!(stroke_of(&app, a).width, app.session.paint.stroke_width, "the line and the bucket's stroke have one weight"); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + p.app().session.select_tool("livePaintBucket", Default::default()).unwrap(); + p.frame(); + finish_typing(&mut p); + let app = p.app(); + assert_eq!((stroke_of(&app, a).width, app.session.paint.stroke_width), (1.0, 5.0), "the bucket's stroke takes 5 pt, not 3+5"); +} + +#[test] +fn an_unfinished_weight_is_dropped_when_other_characters_are_selected() { + use vectorcraft_doc::NodeKind; + use vectorcraft_engine::ViewInfo; + use vectorcraft_tools::{PointerEvent, PointerKind}; + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + run(&mut app, "file.new", json!({"width": 400, "height": 300})); + let v = ViewInfo::default(); + app.session.select_tool("type", v).unwrap(); + for k in [PointerKind::Down, PointerKind::Up] { + app.session.pointer(&PointerEvent::new(k, 50.0, 200.0), v).unwrap(); + } + app.session.tool_text("Make this bold", v).unwrap(); + app.session.set_tool_option("select", &json!({"start": 0, "end": 4})); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + p.app().session.set_tool_option("select", &json!({"start": 5, "end": 9})); + p.frame(); + finish_typing(&mut p); + let app = p.app(); + let id = app.session.active().unwrap().selection.objects[0]; + let NodeKind::Text(t) = &app.session.active().unwrap().doc.node(id).unwrap().kind else { panic!("type") }; + let widths: Vec<(&str, f64)> = t.runs.iter().map(|r| (r.text.as_str(), r.style.stroke_width)).collect(); + assert_eq!(widths, [("Make ", 0.0), ("this", 5.0), (" bold", 0.0)], "the second selection takes 5 pt, not 3+5"); +} + +#[test] +fn a_weight_scrub_that_creates_the_stroke_keeps_going() { + let (mut app, a, _) = two_lines(); + let stroke = app.session.active().unwrap().doc.node(a).unwrap().appearance.items.iter().position(|item| !item.is_fill()).unwrap(); + run(&mut app, "appearance.removeItem", json!({"index": stroke})); + assert!(app.session.active().unwrap().doc.node(a).unwrap().appearance.stroke().is_none()); + let original = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut p = Panel::new(app, stroke::show); + p.drag_hold_role("Weight", Role::LABEL, egui::vec2(12.0, 0.0)); + let first = stroke_of(&p.app(), a).width; + p.frame(); + let at = p.ctx().input(|i| i.pointer.latest_pos()).unwrap(); + p.frame_with(vec![egui::Event::PointerMoved(at + egui::vec2(24.0, 0.0))]); + p.frame(); + let further = stroke_of(&p.app(), a).width; + assert!(further > first, "the held scrub keeps increasing the weight after creating the stroke: {first} to {further}"); + p.release(); + assert_eq!(stroke_of(&p.app(), a).width, further, "release keeps the weight from the whole drag"); + { + let app = p.app(); + let ap = &app.session.active().unwrap().doc.node(a).unwrap().appearance; + assert_eq!(ap.items.iter().filter(|item| !item.is_fill()).count(), 1, "the scrub creates exactly one stroke row"); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1, "the whole scrub is one undo step"); + } + p.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(p.app().session.active().unwrap().doc, original, "one undo removes the scrub's stroke"); +} + +#[test] +fn an_unfinished_weight_is_dropped_when_a_stroke_is_added_on_top() { + let (app, a, _) = two_lines(); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + // The new stroke has the line's 1 pt and goes on top, where `stroke.set` edits with no active row. + p.app().run("appearance.addStroke", json!({})).unwrap(); + assert_eq!(p.app().session.appearance_item(), None, "no row is active"); + p.frame(); + finish_typing(&mut p); + let app = p.app(); + let widths: Vec = app.session.active().unwrap().doc.node(a).unwrap().appearance.painted_strokes().map(|s| s.width).collect(); + assert_eq!(widths, [1.0, 5.0], "the new top stroke takes 5 pt, not 3+5"); +} + +#[test] +fn an_unfinished_weight_is_dropped_when_a_fill_is_added() { + let (app, a, _) = two_lines(); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + // A fill on top leaves the stroke `stroke.set` edits as it was. + p.app().run("appearance.addFill", json!({})).unwrap(); + p.frame(); + finish_typing(&mut p); + assert_eq!(stroke_of(&p.app(), a).width, 5.0, "the edit state change drops the unfinished value"); +} + +#[test] +fn an_unfinished_weight_is_dropped_when_the_whole_story_is_selected() { + use vectorcraft_doc::NodeKind; + let mut app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + run(&mut app, "file.new", json!({"width": 900, "height": 300})); + let story = "The quick brown fox jumps over the lazy dog and keeps running far beyond the first frame. ".repeat(6); + let area = json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 100}}); + let a = run(&mut app, "text.create", area)["id"].as_u64().unwrap(); + let b = run(&mut app, "text.thread.add", json!({"from": a, "rect": [200, 10, 150, 200]}))["id"].as_u64().unwrap(); + // Every character of frame `a`, then the whole story from it: the same frame and characters either way. + run(&mut app, "select.set", json!({"ids": [a]})); + app.session.select_tool("type", Default::default()).unwrap(); + let NodeKind::Text(t) = &app.session.active().unwrap().doc.node(NodeId(a)).unwrap().kind else { panic!("type") }; + let len = vectorcraft_text::edit::runs_len(&t.runs); + app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 0, "caret": len})); + let frame = character::text_editing(&app); + assert!(character::text_story(&app).is_none(), "one frame's characters"); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + p.app().run("select.all", json!({})).unwrap(); + assert!(character::text_story(&p.app()).is_some(), "the whole story"); + assert_eq!(character::text_editing(&p.app()), frame, "the same frame and characters"); + p.frame(); + finish_typing(&mut p); + let app = p.app(); + let widths = |id: u64| { + let NodeKind::Text(t) = &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("type") }; + t.runs.iter().map(|r| r.style.stroke_width).collect::>() + }; + let text_len = |id: u64| { + let NodeKind::Text(t) = &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("type") }; + vectorcraft_text::edit::runs_len(&t.runs) + }; + assert!(text_len(a) > 0 && text_len(b) > 0, "both frames hold characters"); + let (first, second) = (widths(a), widths(b)); + assert!(!first.is_empty(), "the first frame has runs"); + assert!(first.iter().all(|w| *w == 5.0), "the story takes 5 pt, not 3+5: {first:?}"); + assert!(!second.is_empty(), "the second frame has runs"); + assert!(second.iter().all(|w| *w == 5.0), "the story takes 5 pt, not 3+5: {second:?}"); +} + +#[test] +fn an_unfinished_weight_in_an_appearance_row_does_not_reach_another_line() { + let (app, a, b) = two_lines(); + let mut p = Panel::new(app, appearance::show); + start_typing(&mut p, "Weight"); + p.app().run("select.set", json!({"ids": [b.0]})).unwrap(); + p.frame(); + finish_typing(&mut p); + let app = p.app(); + assert_eq!((stroke_of(&app, a).width, stroke_of(&app, b).width), (1.0, 5.0), "b takes 5 pt, not 3+5"); +} + +#[test] +fn changing_global_edit_members_drops_an_unfinished_appearance_weight() { + for change in ["start", "stop", "exclude"] { + let mut app = app_with_rect(); + let a = app.session.active().unwrap().selection.objects[0]; + let b = NodeId(run(&mut app, "edit.duplicate", json!({"dx": 20}))["ids"][0].as_u64().unwrap()); + let c = NodeId(run(&mut app, "edit.duplicate", json!({"dy": 20}))["ids"][0].as_u64().unwrap()); + run(&mut app, "select.set", json!({"ids": [a.0]})); + if change != "start" { + run(&mut app, "select.globalEdit", json!({})); + assert_eq!(app.session.active().unwrap().global_edit.as_ref().unwrap().members.len(), 3); + } + let before = [a, b, c].map(|id| stroke_of(&app, id)); + let mut p = Panel::new(app, appearance::show); + start_typing(&mut p, "Weight"); + if change == "exclude" { + p.app().run("select.globalEditExclude", json!({"id": b.0})).unwrap(); + } else { + p.app().run("select.globalEdit", json!({})).unwrap(); + } + p.frame(); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+"), "{change}: the draft is dropped"); + finish_typing(&mut p); + for (id, before) in [a, b, c].into_iter().zip(before) { + let after = stroke_of(&p.app(), id); + assert_ne!(after.width, 8.0, "{change}: the unfinished value reaches no member"); + assert!(after.width == before.width || after.width == 5.0, "{change}: only the fresh weight can be applied"); + } + assert_eq!(stroke_of(&p.app(), a).width, 5.0, "{change}: the field still takes a fresh weight"); + } +} + +#[test] +fn an_unfinished_weight_in_an_appearance_row_is_dropped_when_equal_width_strokes_swap() { + let mut app = app_with_rect(); + let a = app.session.active().unwrap().selection.objects[0]; + run(&mut app, "stroke.set", json!({"miterLimit": 4})); + run(&mut app, "appearance.addStroke", json!({})); + run(&mut app, "stroke.set", json!({"miterLimit": 10})); + let strokes: Vec = { + let ap = &app.session.active().unwrap().doc.node(a).unwrap().appearance; + (0..ap.items.len()).filter(|i| ap.stroke_at(Some(*i)).is_some()).collect() + }; + let [bottom, top] = strokes[..] else { panic!("two stroke rows: {strokes:?}") }; + { + let ap = &app.session.active().unwrap().doc.node(a).unwrap().appearance; + let (lower, upper) = (ap.stroke_at(Some(bottom)).unwrap(), ap.stroke_at(Some(top)).unwrap()); + assert_eq!(lower.width, upper.width); + assert_ne!(lower.miter_limit, upper.miter_limit); + let mut matched = upper.clone(); + matched.miter_limit = lower.miter_limit; + assert_eq!(lower, &matched, "only the miter limits differ"); + } + let mut p = Panel::new(app, appearance::show); + start_typing(&mut p, "Weight"); + p.frame(); + assert_eq!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+")); + let focused = p.ctx().memory(|m| m.focused()).expect("the row weight has focus"); + p.app().run("appearance.moveItem", json!({"from": top, "to": bottom})).unwrap(); + p.frame(); + assert_eq!(p.ctx().memory(|m| m.focused()), Some(focused), "the same row field keeps focus across the swap"); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+")); + finish_typing(&mut p); + let app = p.app(); + let ap = &app.session.active().unwrap().doc.node(a).unwrap().appearance; + let widths: Vec<_> = ap + .items + .iter() + .filter_map(|item| match item { + vectorcraft_doc::AppearanceItem::Stroke(stroke) => Some(stroke.width), + _ => None, + }) + .collect(); + assert!(widths.iter().all(|width| *width != 8.0), "neither stroke receives 3+5: {widths:?}"); + assert_eq!(widths.iter().filter(|width| **width == 5.0).count(), 1, "the focused row takes a fresh 5 pt: {widths:?}"); +} + +#[test] +fn an_unfinished_group_weight_is_dropped_when_a_member_gets_a_stroke() { + let (mut app, a, b) = two_lines(); + run(&mut app, "select.set", json!({"ids": [a.0, b.0]})); + run(&mut app, "object.group", json!({})); + let group = app.session.active().unwrap().selection.objects[0]; + run(&mut app, "appearance.addStroke", json!({"ids": [group.0]})); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + p.app().run("appearance.addStroke", json!({"ids": [a.0]})).unwrap(); + p.frame(); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+")); + finish_typing(&mut p); + assert_eq!(stroke_of(&p.app(), group).width, 5.0, "the document change drops the unfinished value"); +} + +#[test] +fn a_weight_scrub_on_an_active_row_at_different_indices_keeps_going() { + let mut app = app_with_rect(); + let a = app.session.active().unwrap().selection.objects[0]; + let b = NodeId(run(&mut app, "shape.rectangle", json!({"x": 120, "y": 10, "width": 50, "height": 100}))["id"].as_u64().unwrap()); + run(&mut app, "appearance.addFill", json!({"ids": [b.0]})); + run(&mut app, "appearance.moveItem", json!({"ids": [b.0], "from": 2, "to": 0})); + run(&mut app, "select.set", json!({"ids": [a.0, b.0]})); + run(&mut app, "appearance.setActiveItem", json!({"index": 1})); + for (id, index) in [(a, 1), (b, 2)] { + assert!(app.session.active().unwrap().doc.node(id).unwrap().appearance.stroke_at(Some(index)).is_some()); + } + let original = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut p = Panel::new(app, stroke::show); + p.drag_hold_role("Weight", Role::LABEL, egui::vec2(12.0, 0.0)); + let first = stroke_of(&p.app(), a).width; + assert!(first > 1.0, "the first preview changes the weight"); + assert_eq!(stroke_of(&p.app(), b).width, first, "both matched rows receive the preview"); + p.frame(); + let at = p.ctx().input(|i| i.pointer.latest_pos()).unwrap(); + p.frame_with(vec![egui::Event::PointerMoved(at + egui::vec2(24.0, 0.0))]); + p.frame(); + let further = stroke_of(&p.app(), a).width; + assert!(further > first, "the held scrub continues after its first preview"); + assert_eq!(stroke_of(&p.app(), b).width, further); + p.release(); + assert_eq!(stroke_of(&p.app(), a).width, further); + assert_eq!(stroke_of(&p.app(), b).width, further); + assert_eq!(p.app().session.active().unwrap().history.undo.len(), undo + 1, "the whole scrub is one undo step"); + p.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(p.app().session.active().unwrap().doc, original); +} + +#[test] +fn a_weight_scrub_matching_a_lower_stroke_keeps_going() { + let mut app = app_with_rect(); + let a = app.session.active().unwrap().selection.objects[0]; + let b = NodeId(run(&mut app, "shape.rectangle", json!({"x": 120, "y": 10, "width": 50, "height": 100}))["id"].as_u64().unwrap()); + app.session + .edit("Strokes", |d, _| { + let top = d.node(a).unwrap().appearance.stroke().unwrap().clone(); + let ap = &mut d.node_mut(b).unwrap().appearance; + ap.stroke_mut().unwrap().width = 2.0; + ap.items.push(vectorcraft_doc::AppearanceItem::Stroke(top)); + Ok(()) + }) + .unwrap(); + run(&mut app, "select.set", json!({"ids": [a.0, b.0]})); + run(&mut app, "appearance.setActiveItem", json!({"index": 1})); + let original = app.session.active().unwrap().doc.clone(); + let undo = app.session.active().unwrap().history.undo.len(); + let mut p = Panel::new(app, stroke::show); + // A vertical move starts the horizontal scrub without changing the weight. + p.drag_hold_role("Weight", Role::LABEL, egui::vec2(0.0, 12.0)); + let at = p.ctx().input(|i| i.pointer.latest_pos()).unwrap(); + p.frame_with(vec![egui::Event::PointerMoved(at + egui::vec2(1.0, 0.0))]); + p.frame(); + assert_eq!(stroke_of(&p.app(), a).width, 2.0); + assert_eq!(stroke_of(&p.app(), b).width, 2.0, "the top stroke receives the matching preview"); + assert!(p.app().session.active().unwrap().interaction.is_some(), "the held scrub is still running at 2 pt"); + p.frame_with(vec![egui::Event::PointerMoved(at + egui::vec2(3.0, 0.0))]); + p.frame(); + let further = stroke_of(&p.app(), a).width; + assert!(further > 2.0, "the scrub continues past the lower stroke's weight"); + assert_eq!(stroke_of(&p.app(), b).width, further, "both top strokes keep receiving previews"); + assert_eq!(p.app().session.active().unwrap().doc.node(b).unwrap().appearance.stroke_at(Some(1)).unwrap().width, 2.0); + p.release(); + assert_eq!(stroke_of(&p.app(), a).width, further); + assert_eq!(stroke_of(&p.app(), b).width, further); + assert_eq!(p.app().session.active().unwrap().history.undo.len(), undo + 1, "the scrub is one undo step"); + p.app().run("edit.undo", json!({})).unwrap(); + assert_eq!(p.app().session.active().unwrap().doc, original); +} + +#[test] +fn a_width_only_stroke_swap_drops_the_weight_draft() { + let mut app = app_with_rect(); + let a = app.session.active().unwrap().selection.objects[0]; + let b = NodeId(run(&mut app, "shape.rectangle", json!({"x": 120, "y": 10, "width": 50, "height": 100}))["id"].as_u64().unwrap()); + app.session + .edit("Strokes", |d, _| { + let mut top = d.node(a).unwrap().appearance.stroke().unwrap().clone(); + top.width = 3.0; + let ap = &mut d.node_mut(b).unwrap().appearance; + ap.stroke_mut().unwrap().width = 2.0; + ap.items.push(vectorcraft_doc::AppearanceItem::Stroke(top)); + Ok(()) + }) + .unwrap(); + run(&mut app, "select.set", json!({"ids": [a.0, b.0]})); + let mut p = Panel::new(app, stroke::show); + assert_eq!(p.value_role("Weight", Role::SPIN_BUTTON).unwrap_or_default(), ""); + start_typing(&mut p, "Weight"); + p.app().run("appearance.moveItem", json!({"ids": [b.0], "from": 2, "to": 1})).unwrap(); + p.frame(); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+"), "the swap drops the typed value"); + p.type_text("1"); + p.key(Key::Enter, Modifiers::NONE); + let app = p.app(); + for id in [a, b] { + let ap = &app.session.active().unwrap().doc.node(id).unwrap().appearance; + assert!(ap.painted_strokes().all(|s| s.width != 4.0), "no stroke receives the discarded 3+1 draft"); + } + assert_eq!((stroke_of(&app, a).width, stroke_of(&app, b).width), (1.0, 1.0), "the fresh value reaches both top strokes"); +} + +#[test] +fn an_empty_groups_new_art_stroke_change_drops_an_unfinished_weight() { + let (mut app, _, _) = two_lines(); + let group = app + .session + .edit("Empty group", |doc, _| { + let id = doc.alloc_id(); + doc.insert(doc.default_layer(), 0, vectorcraft_doc::Node::group(id, vec![]))?; + Ok(id) + }) + .unwrap(); + run(&mut app, "select.set", json!({"ids": [group.0]})); + let mut p = Panel::new(app, stroke::show); + start_typing(&mut p, "Weight"); + let before = p.app().session.new_art_stroke(); + p.app().run("stroke.set", json!({"cap": "round"})).unwrap(); + let after = p.app().session.new_art_stroke(); + assert_eq!(after.width, before.width); + assert_ne!(after.cap, before.cap); + p.frame(); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+")); + finish_typing(&mut p); + assert_eq!(p.app().session.new_art_stroke().width, 5.0, "new art receives only the fresh value"); +} + +#[test] +fn simplifying_the_new_art_stack_drops_an_unfinished_appearance_weight() { + let mut app = app_with_rect(); + run(&mut app, "appearance.setNewArtBasic", json!({"on": false})); + run(&mut app, "appearance.addStroke", json!({})); + run(&mut app, "select.none", json!({})); + let inherited = app.session.new_art(); + assert_eq!(inherited.items.len(), 3, "a fill below two strokes"); + let lower = inherited.stroke_at(Some(1)).unwrap(); + assert_eq!(lower.width, inherited.stroke_at(Some(2)).unwrap().width); + let mut p = Panel::new(app, appearance::show); + p.click_role_nth("Weight", Role::SPIN_BUTTON, 1); + p.key(Key::A, Modifiers::COMMAND); + p.type_text("3+"); + p.frame(); + assert!(p.shows_value("3+"), "the lower stroke holds the unfinished value"); + let revision = p.app().session.active().unwrap().revision; + p.app().run("appearance.setNewArtBasic", json!({"on": true})).unwrap(); + assert_eq!(p.app().session.active().unwrap().revision, revision, "only the preference changes"); + assert_eq!(p.app().session.new_art().items.len(), 2, "one stroke survives at the lower stroke's row index"); + p.frame(); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+")); + finish_typing(&mut p); + assert_eq!(p.app().session.new_art_stroke().width, 5.0, "new art receives 5 pt, not 3+5"); +} + +#[test] +fn unlocking_a_global_edit_member_drops_an_unfinished_weight() { + for show in [stroke::show, appearance::show] { + let mut app = app_with_rect(); + let a = app.session.active().unwrap().selection.objects[0]; + let b = NodeId(run(&mut app, "edit.duplicate", json!({"dx": 20}))["ids"][0].as_u64().unwrap()); + run(&mut app, "select.set", json!({"ids": [a.0]})); + run(&mut app, "select.globalEdit", json!({})); + run(&mut app, "object.lock", json!({"ids": [b.0]})); + assert!(app.session.active().unwrap().global_edit.as_ref().unwrap().members.iter().any(|(id, _)| *id == b)); + let mut p = Panel::new(app, show); + start_typing(&mut p, "Weight"); + p.app().run("object.unlockAll", json!({})).unwrap(); + assert!(!p.app().session.active().unwrap().doc.node(b).unwrap().locked); + p.app().run("select.set", json!({"ids": [a.0]})).unwrap(); + assert_eq!(p.app().session.active().unwrap().global_edit.as_ref().unwrap().members.len(), 2); + p.frame(); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+")); + finish_typing(&mut p); + assert_ne!(stroke_of(&p.app(), b).width, 8.0, "the unfinished expression does not reach the unlocked member"); + } +} + +#[test] +fn an_outside_appearance_change_ends_a_held_scrub() { + for name in ["Miter limit", "Dash 1", "Gap 1", "Dash offset", "Scale 1"] { + let (app, a, _) = two_lines(); + let mut p = Panel::new(app, show_with_field_scrubbing); + p.drag_hold_role(name, Role::SPIN_BUTTON, egui::vec2(12.0, 0.0)); + p.app().run("appearance.setItem", json!({"index": 0, "opacity": 0.5})).unwrap(); + let before = stroke_of(&p.app(), a); + p.frame(); + let at = p.ctx().input(|i| i.pointer.latest_pos()).unwrap(); + p.frame_with(vec![egui::Event::PointerMoved(at + egui::vec2(48.0, 0.0))]); + p.frame(); + p.release(); + assert_eq!(stroke_of(&p.app(), a), before, "{name}: later pointer moves leave the changed stroke alone"); + } +} + +#[test] +fn rebasing_a_tool_preview_drops_an_unfinished_weight() { + use vectorcraft_engine::ViewInfo; + use vectorcraft_tools::{PointerEvent, PointerKind}; + for show in [stroke::show, appearance::show] { + let (mut app, a, b) = two_lines(); + let view = ViewInfo { smart_guides: false, ..Default::default() }; + app.session.select_tool("selection", view).unwrap(); + for (kind, x) in [(PointerKind::Down, 50.0), (PointerKind::Drag, 60.0)] { + app.session.pointer(&PointerEvent::new(kind, x, 50.0), view).unwrap(); + } + assert!(app.session.active().unwrap().interaction.as_ref().unwrap().by_tool()); + let mut p = Panel::new(app, show); + start_typing(&mut p, "Weight"); + let revision = p.app().session.active().unwrap().interaction.as_ref().unwrap().revision; + p.app().run("appearance.setItem", json!({"ids": [b.0], "index": 1, "opacity": 0.5})).unwrap(); + assert!(p.app().session.active().unwrap().interaction.as_ref().unwrap().revision > revision); + p.frame(); + assert_ne!(p.value_role("Weight", Role::SPIN_BUTTON).as_deref(), Some("3+")); + finish_typing(&mut p); + assert_eq!(stroke_of(&p.app(), a).width, 5.0, "the rebased document receives only the fresh value"); + assert_ne!(stroke_of(&p.app(), b).width, 8.0, "the unfinished expression reaches no other stroke"); + } +}