2bc41aeb8602
tests.rs
use super::*;
use vectorcraft_engine::Session;
fn frame(app: &mut VectorcraftApp) {
let ctx = egui::Context::default();
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
show(app, ui);
menu(app, ui);
});
out.textures_delta.clear();
}
#[test]
fn panel_draws_empty_with_text_and_with_stops() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
frame(&mut app);
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a\tb", "area": {"width": 300, "height": 100}})).unwrap();
frame(&mut app);
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 50}, {"position": 120, "align": "decimal"}]})).unwrap();
frame(&mut app);
let (_, stops, span) = current(&app).unwrap();
assert_eq!(stops.len(), 2);
assert_eq!(span, 300.0);
// The stops survive a JSON round trip through the panel's encoding.
let back: Vec<serde_json::Value> = stops_json(&stops).as_array().unwrap().clone();
assert_eq!(back[1]["align"], json!("decimal"));
}
/// A rectangle and two area texts, the first with a stop at 40 pt and the second with one at
/// 90 pt, nothing selected. โ the app and the ids of the rectangle and the two texts.
fn mixed_selection_app() -> (VectorcraftApp, [u64; 3]) {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({})).unwrap();
let id = |v: serde_json::Value| v["id"].as_u64().unwrap();
let rect = id(app.run("shape.rectangle", json!({"x": 10, "y": 200, "width": 40, "height": 40})).unwrap());
let a = id(app.run("text.create", json!({"x": 10, "y": 20, "text": "a\tb", "area": {"width": 300, "height": 60}})).unwrap());
let b = id(app.run("text.create", json!({"x": 10, "y": 100, "text": "c\td", "area": {"width": 250, "height": 60}})).unwrap());
for (text, position) in [(a, 40), (b, 90)] {
app.run("select.set", json!({"ids": [text]})).unwrap();
app.run("text.tabs.set", json!({"stops": [{"position": position}]})).unwrap();
}
app.run("select.set", json!({"ids": []})).unwrap();
(app, [rect, a, b])
}
/// With a rectangle selected first and a text after it, the panel shows the text's stops on its
/// ruler, not the "No text selected" state.
#[test]
fn the_ruler_shows_text_selected_after_an_object_that_is_not_text() {
let (mut app, [rect, a, _]) = mixed_selection_app();
app.run("select.set", json!({"ids": [rect, a]})).unwrap();
let (node, stops, span) = current(&app).unwrap();
assert_eq!(node.id.0, a);
assert_eq!(stops.iter().map(|s| s.position).collect::<Vec<_>>(), [40.0]);
assert_eq!(span, 300.0);
let ctx = egui::Context::default();
assert_eq!(ruler_labels(&ctx, &mut app).first().map(String::as_str), Some("0"));
}
/// With a group selected first whose text follows a rectangle in it, the panel shows that text's
/// stops, ahead of a text selected after the group.
#[test]
fn the_ruler_shows_text_inside_a_selected_group() {
let (mut app, [rect, a, b]) = mixed_selection_app();
app.run("select.set", json!({"ids": [rect, b]})).unwrap();
let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [group, a]})).unwrap();
let (node, stops, span) = current(&app).unwrap();
assert_eq!(node.id.0, b);
assert_eq!(stops.iter().map(|s| s.position).collect::<Vec<_>>(), [90.0]);
assert_eq!(span, 250.0);
let ctx = egui::Context::default();
assert_eq!(ruler_labels(&ctx, &mut app).first().map(String::as_str), Some("0"));
}
/// A stop added on the ruler of a mixed selection sets the first text's stops plus the new one on
/// every selected text, and leaves the rectangle as it was.
#[test]
fn a_stop_added_on_a_mixed_selection_sets_every_selected_text() {
let (mut app, [rect, a, b]) = mixed_selection_app();
let shape = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(rect)).unwrap().clone();
let before = shape(&app);
app.run("select.set", json!({"ids": [rect, a, b]})).unwrap();
let ctx = egui::Context::default();
drag_on_ruler(&ctx, &mut app, 60.0, 60.0, false);
for text in [a, b] {
assert_eq!(text_of(&app, text).para_at(0).tabs.iter().map(|s| s.position).collect::<Vec<_>>(), [40.0, 60.0], "text {text}");
}
assert_eq!(shape(&app), before);
}
/// A selection without text keeps the "No text selected" state and draws no ruler.
#[test]
fn a_selection_without_text_shows_no_ruler() {
let (mut app, [rect, ..]) = mixed_selection_app();
let id = app.run("shape.rectangle", json!({"x": 100, "y": 200, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [rect, id]})).unwrap();
let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [group]})).unwrap();
assert!(current(&app).is_none());
let ctx = egui::Context::default();
assert!(ruler_labels(&ctx, &mut app).is_empty());
assert!(crate::tests_labels::painted_text(&mut app, show).contains("No text selected"));
}
/// In vertical type the Left and Right alignment buttons are named Top-Justified Tab and
/// Bottom-Justified Tab, in their tool tips and for screen readers, and the position field is
/// labeled Y. Horizontal type keeps Left-Justified Tab, Right-Justified Tab and X.
#[test]
fn vertical_type_names_the_alignments_top_and_bottom_and_the_position_y() {
use crate::widgets::accessibility_tests::{role_and_state, tree};
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 50}]})).unwrap();
let horizontal = ["Left-Justified Tab", "Center-Justified Tab", "Right-Justified Tab", "Decimal-Justified Tab"];
let vertical = ["Top-Justified Tab", "Center-Justified Tab", "Bottom-Justified Tab", "Decimal-Justified Tab"];
for (names, other, axis, other_axis) in [(horizontal, vertical, "X:", "Y:"), (vertical, horizontal, "Y:", "X:")] {
if axis == "Y:" {
app.session.execute("type.orientation.vertical", &json!({})).unwrap();
}
// Screen readers find the four buttons by name, and the selected stop's alignment is pressed.
let nodes = tree(|ui| show(&mut app, ui));
for (i, name) in names.iter().enumerate() {
let pressed = if i == 0 { egui::accesskit::Toggled::True } else { egui::accesskit::Toggled::False };
assert_eq!(role_and_state(&nodes, name), (egui::accesskit::Role::Button, Some(pressed)), "{name}");
}
for name in other.iter().filter(|n| !names.contains(n)) {
assert!(!nodes.iter().any(|n| n.label() == Some(name)), "{name} with {axis}");
}
// Hovering each button shows its tool tip, and the panel shows the position field's label.
let ctx = egui::Context::default();
ctx.global_style_mut(|s| s.interaction.tooltip_delay = 0.0);
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0));
let mut time = 0.0;
let mut frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
time += 0.5;
let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() };
let mut out = ctx.run_ui(input, |ui| show(app, ui));
out.textures_delta.clear();
out.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::Text(t) => Some((t.galley.text().to_string(), t.visual_bounding_rect())),
_ => None,
})
.collect::<Vec<_>>()
};
let texts = frame(&mut app, vec![]);
assert!(texts.iter().any(|(t, _)| t == axis) && !texts.iter().any(|(t, _)| t == other_axis), "{axis} in {texts:?}");
for ((_, glyph), name) in ALIGNS.iter().zip(names) {
let at = texts.iter().find(|(t, _)| t == glyph).unwrap_or_else(|| panic!("{glyph} in {texts:?}")).1.center();
frame(&mut app, vec![egui::Event::PointerMoved(at)]);
let tips = (0..3).flat_map(|_| frame(&mut app, vec![])).collect::<Vec<_>>();
assert!(tips.iter().any(|(t, _)| t == name), "the tip {name} in {tips:?}");
}
}
}
/// The position field's label is translated: French puts a no-break space before the colon,
/// Chinese writes a full-width colon.
#[test]
fn position_label_is_translated() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 50}]})).unwrap();
let labels = |app: &mut VectorcraftApp| {
let text = crate::tests_labels::painted_text(app, show);
["X:", "Y:", "X\u{a0}:", "Y\u{a0}:", "X๏ผ", "Y๏ผ"].into_iter().filter(|l| text.lines().any(|t| t.trim() == *l)).collect::<Vec<_>>()
};
for (code, horizontal, vertical) in [("fr", "X\u{a0}:", "Y\u{a0}:"), ("zh-hans", "X๏ผ", "Y๏ผ"), ("en", "X:", "Y:")] {
crate::i18n::set_current(crate::i18n::Lang::from_code(code).unwrap());
app.session.execute("type.orientation.horizontal", &json!({})).unwrap();
assert_eq!(labels(&mut app), [horizontal], "{code}");
app.session.execute("type.orientation.vertical", &json!({})).unwrap();
assert_eq!(labels(&mut app), [vertical], "{code}");
}
}
/// #924: Leader and Align On keep what is typed, frame after frame, until Enter applies it
/// (spaces kept, eight characters at most).
#[test]
fn leader_and_align_on_keep_what_is_typed_until_enter() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 50, "align": "decimal"}]})).unwrap();
let ctx = egui::Context::default();
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 400.0));
// One frame with `events` โ the texts painted and where.
let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
out.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::Text(t) => Some((t.galley.text().to_string(), t.visual_bounding_rect())),
_ => None,
})
.collect::<Vec<_>>()
};
let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() };
let click = |at| {
[true, false].map(|pressed| egui::Event::PointerButton {
pos: at,
button: egui::PointerButton::Primary,
pressed,
modifiers: Default::default(),
})
};
let stop = |app: &VectorcraftApp| current(app).unwrap().1[0].clone();
for (label, typed, want) in [("Leader:", [". ", "_", "123456789"], ". _12345"), ("Align On:", [",", "", ""], ",")] {
let texts = frame(&mut app, vec![]);
let r = texts.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("{label} in {texts:?}")).1;
let at = egui::pos2(r.right() + 30.0, r.center().y);
let [down, up] = click(at);
frame(&mut app, vec![egui::Event::PointerMoved(at), down]);
frame(&mut app, vec![up]);
// Select what is there, then type in pieces over several frames.
frame(
&mut app,
vec![egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }],
);
for piece in typed.iter().filter(|p| !p.is_empty()) {
frame(&mut app, vec![egui::Event::Text(piece.to_string())]);
frame(&mut app, vec![]);
}
frame(&mut app, vec![key(egui::Key::Enter)]);
frame(&mut app, vec![]);
let s = stop(&app);
let got = if label == "Leader:" { s.leader } else { s.align_on.to_string() };
assert_eq!(got, want, "{label}");
}
}
/// #1458: a stop moves when the drag starts on it, even though egui only reports the drag once
/// the pointer is past its threshold (farther from the press than the 5 px hit tolerance).
#[test]
fn dragging_a_stop_moves_it() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 50}]})).unwrap();
let ctx = egui::Context::default();
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 400.0));
// One frame with `events` โ where the ruler's inch labels (9 pt) are painted.
let frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
out.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::Text(t) if t.galley.job.sections.first().is_some_and(|s| s.format.font_id.size == 9.0) => {
Some((t.galley.text().to_string(), t.pos))
}
_ => None,
})
.collect::<Vec<_>>()
};
let labels = frame(&mut app, vec![]);
let at = |label: &str| labels.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("{label} in {labels:?}")).1;
// A label sits 2 px right of its tick: 0 and 100 pt give the ruler's scale.
let (zero, hundred) = (at("0"), at("100"));
let to_x = |pt: f32| zero.x - 2.0 + pt * (hundred.x - zero.x) / 100.0;
let y = zero.y + 15.0;
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
// Press 3 px right of the stop, then drag right; egui starts the drag 6+ px from the press.
let press = egui::pos2(to_x(50.0) + 3.0, y);
frame(&mut app, vec![egui::Event::PointerMoved(press), button(press, true)]);
for dx in [9.0, 20.0, 40.0] {
frame(&mut app, vec![egui::Event::PointerMoved(press + vec2(dx, 0.0))]);
}
let end = press + vec2(40.0, 0.0);
frame(&mut app, vec![button(end, false)]);
frame(&mut app, vec![]);
let stops = current(&app).unwrap().1;
assert_eq!(stops.len(), 1);
let moved_to = to_x(stops[0].position as f32);
assert!((moved_to - end.x).abs() < 1.0, "stop at {moved_to}, released at {}", end.x);
}
/// One frame of the panel with `events`, Shift held when `shift` โ the ruler's labels (9 pt) and
/// where they are painted, left to right.
fn ruler_frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>, shift: bool) -> Vec<(String, egui::Pos2)> {
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0));
let modifiers = if shift { egui::Modifiers::SHIFT } else { egui::Modifiers::NONE };
let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect();
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
out.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::Text(t) if t.galley.job.sections.first().is_some_and(|s| s.format.font_id.size == 9.0) => {
Some((t.galley.text().to_string(), t.pos))
}
_ => None,
})
.collect()
}
/// The labels the ruler shows in a frame of [`ruler_frame`].
fn ruler_labels(ctx: &egui::Context, app: &mut VectorcraftApp) -> Vec<String> {
ruler_frame(ctx, app, vec![], false).into_iter().map(|(t, _)| t).collect()
}
/// Press on the ruler at `from` (points), move to `to` and release there, Shift held when
/// `shift`. A label sits 2 px right of its tick, so the first two labels give the ruler's scale.
fn drag_on_ruler(ctx: &egui::Context, app: &mut VectorcraftApp, from: f64, to: f64, shift: bool) {
let labels = ruler_frame(ctx, app, vec![], shift);
let [(zero, a), (next, b), ..] = &labels[..] else { panic!("ruler labels {labels:?}") };
assert_eq!(zero, "0");
let per = next.parse::<f64>().unwrap() * app.session.general_unit().points();
let x = |pt: f64| a.x - 2.0 + (pt / per) as f32 * (b.x - a.x);
let y = a.y + 15.0;
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
let (press, end) = (egui::pos2(x(from), y), egui::pos2(x(to), y));
ruler_frame(ctx, app, vec![egui::Event::PointerMoved(press), button(press, true)], shift);
if press != end {
for f in [0.25, 0.5, 1.0] {
ruler_frame(ctx, app, vec![egui::Event::PointerMoved(press.lerp(end, f))], shift);
}
}
ruler_frame(ctx, app, vec![button(end, false)], shift);
ruler_frame(ctx, app, vec![], shift);
}
fn indent_app(left: f64, first: f64) -> VectorcraftApp {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({})).unwrap();
app.run("text.create", json!({"x": 10, "y": 20, "text": "one\ntwo", "area": {"width": 300, "height": 100}})).unwrap();
app.run("text.setFormat", json!({"leftIndent": left, "firstLineIndent": first})).unwrap();
app
}
fn indent_values(app: &VectorcraftApp, paragraph: usize) -> (f64, f64) {
let (node, _, _) = current(app).unwrap();
let NodeKind::Text(t) = node.kind else { panic!("selected text") };
let p = t.para_at(paragraph);
(p.left_indent, p.first_line_indent)
}
fn marker_event(ctx: &egui::Context, app: &mut VectorcraftApp, from: f64, to: f64, upper: bool, command: bool, shift: bool) {
let labels = ruler_frame(ctx, app, vec![], shift);
let [(zero, a), (next, b), ..] = &labels[..] else { panic!("ruler labels {labels:?}") };
assert_eq!(zero, "0");
let per = next.parse::<f64>().unwrap() * app.session.general_unit().points();
let x = |pt: f64| a.x - 2.0 + (pt / per) as f32 * (b.x - a.x);
let y = a.y + if upper { 3.0 } else { 11.0 };
let (press, end) = (egui::pos2(x(from), y), egui::pos2(x(to), y));
let modifiers = match (command, shift) {
(true, true) => egui::Modifiers { command: true, shift: true, ..Default::default() },
(true, false) => egui::Modifiers::COMMAND,
(false, true) => egui::Modifiers::SHIFT,
(false, false) => egui::Modifiers::NONE,
};
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers };
ruler_frame(ctx, app, vec![egui::Event::ModifiersChanged(modifiers), egui::Event::PointerMoved(press), button(press, true)], shift);
if press != end {
for f in [0.25, 0.5, 1.0] {
ruler_frame(ctx, app, vec![egui::Event::ModifiersChanged(modifiers), egui::Event::PointerMoved(press.lerp(end, f))], shift);
}
}
ruler_frame(ctx, app, vec![egui::Event::ModifiersChanged(modifiers), button(end, false)], shift);
ruler_frame(ctx, app, vec![], shift);
}
#[test]
fn indent_markers_show_positions_and_select_without_adding_stops() {
let mut app = indent_app(24.0, 12.0);
let ctx = egui::Context::default();
assert_eq!(marker_position(IndentMarker::Lower, ¤t_para(&app).unwrap().1), 24.0);
assert_eq!(marker_position(IndentMarker::Upper, ¤t_para(&app).unwrap().1), 36.0);
let labels = ruler_frame(&ctx, &mut app, vec![], false);
let [(zero, a), (next, b), ..] = &labels[..] else { panic!("ruler labels {labels:?}") };
assert_eq!(zero, "0");
let per = next.parse::<f64>().unwrap() * app.session.general_unit().points();
let x = |pt: f64| a.x - 2.0 + (pt / per) as f32 * (b.x - a.x);
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0));
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| show(&mut app, ui));
out.textures_delta.clear();
let triangles: Vec<egui::Pos2> = out
.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::Path(path) if path.points.len() == 3 && path.points.iter().all(|p| p.y >= a.y && p.y <= a.y + 16.0) => {
Some(egui::pos2(path.points.iter().map(|p| p.x).sum::<f32>() / 3.0, path.points.iter().map(|p| p.y).sum::<f32>() / 3.0))
}
_ => None,
})
.collect();
assert!(triangles.iter().any(|p| (p.x - x(36.0)).abs() < 0.5 && p.y < a.y + 8.0), "upper marker at 36 pt: {triangles:?}");
assert!(triangles.iter().any(|p| (p.x - x(24.0)).abs() < 0.5 && p.y > a.y + 8.0), "lower marker at 24 pt: {triangles:?}");
marker_event(&ctx, &mut app, 36.0, 36.0, true, false, false);
assert_eq!(pstate::<Option<IndentMarker>>(&ctx, "tabs-marker-sel"), Some(IndentMarker::Upper));
assert!(current(&app).unwrap().1.is_empty());
marker_event(&ctx, &mut app, 24.0, 24.0, false, false, false);
assert_eq!(pstate::<Option<IndentMarker>>(&ctx, "tabs-marker-sel"), Some(IndentMarker::Lower));
assert!(current(&app).unwrap().1.is_empty());
}
#[test]
fn upper_and_lower_marker_drags_map_indents_and_undo_once() {
let mut app = indent_app(24.0, 12.0);
let ctx = egui::Context::default();
let before = app.session.active().unwrap().history.undo.len();
marker_event(&ctx, &mut app, 36.0, 60.0, true, false, false);
assert_eq!(indent_values(&app, 0), (24.0, 36.0));
assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1);
app.run("edit.undo", json!({})).unwrap();
assert_eq!(indent_values(&app, 0), (24.0, 12.0));
marker_event(&ctx, &mut app, 24.0, 40.0, false, false, false);
assert_eq!(indent_values(&app, 0), (40.0, -4.0));
marker_event(&ctx, &mut app, 40.0, 50.0, false, true, false);
assert_eq!(indent_values(&app, 0), (50.0, -4.0));
}
#[test]
fn marker_shift_drag_snaps_and_coincident_halves_remain_separate() {
let mut app = indent_app(24.0, 0.0);
let ctx = egui::Context::default();
marker_event(&ctx, &mut app, 24.0, 33.4, true, false, true);
assert_eq!(indent_values(&app, 0), (24.0, 11.0));
app.run("text.setFormat", json!({"leftIndent": 24, "firstLineIndent": 0})).unwrap();
marker_event(&ctx, &mut app, 24.0, 40.0, false, false, false);
assert_eq!(indent_values(&app, 0), (40.0, -16.0));
}
#[test]
fn mixed_indent_upper_marker_keeps_each_left_indent_in_one_undo_step() {
let mut app = indent_app(24.0, 12.0);
let id = current(&app).unwrap().0.id.0;
app.run("text.setFormat", json!({"id": id, "start": 4, "end": 4, "leftIndent": 60, "firstLineIndent": -10})).unwrap();
let ctx = egui::Context::default();
let before = app.session.active().unwrap().history.undo.len();
marker_event(&ctx, &mut app, 36.0, 70.0, true, false, false);
assert_eq!(indent_values(&app, 0), (24.0, 46.0));
assert_eq!(indent_values(&app, 1), (60.0, 10.0));
assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1);
app.run("edit.undo", json!({})).unwrap();
assert_eq!(indent_values(&app, 0), (24.0, 12.0));
assert_eq!(indent_values(&app, 1), (60.0, -10.0));
marker_event(&ctx, &mut app, 60.0, 60.0, false, false, false);
assert_ne!(pstate::<Option<IndentMarker>>(&ctx, "tabs-marker-sel"), Some(IndentMarker::Lower));
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({})).unwrap();
let a = app.run("text.create", json!({"x": 10, "y": 20, "text": "one", "area": {"width": 300, "height": 100}})).unwrap()["id"].clone();
let b = app.run("text.create", json!({"x": 10, "y": 140, "text": "two", "area": {"width": 300, "height": 100}})).unwrap()["id"].clone();
app.run("text.setFormat", json!({"id": a, "leftIndent": 24, "firstLineIndent": 12})).unwrap();
app.run("text.setFormat", json!({"id": b, "leftIndent": 60, "firstLineIndent": -10})).unwrap();
app.run("select.set", json!({"ids": [a, b.clone()]})).unwrap();
let ctx = egui::Context::default();
assert_eq!(current_para(&app).unwrap().1.left_indent, 24.0);
marker_event(&ctx, &mut app, 36.0, 70.0, true, false, false);
assert_eq!(indent_values(&app, 0), (24.0, 46.0));
let second = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(b.as_u64().unwrap())).unwrap();
let NodeKind::Text(second) = &second.kind else { panic!("second text") };
assert_eq!((second.para_at(0).left_indent, second.para_at(0).first_line_indent), (60.0, 10.0));
}
#[test]
fn lower_marker_keeps_each_first_line_position_in_one_undo_step() {
let mut app = indent_app(24.0, 12.0);
let id = current(&app).unwrap().0.id.0;
app.run("text.setFormat", json!({"id": id, "start": 4, "end": 7, "firstLineIndent": 28})).unwrap();
assert_eq!(indent_values(&app, 0), (24.0, 12.0));
assert_eq!(indent_values(&app, 1), (24.0, 28.0));
let ctx = egui::Context::default();
let before = app.session.active().unwrap().history.undo.len();
marker_event(&ctx, &mut app, 24.0, 40.0, false, false, false);
assert_eq!(indent_values(&app, 0), (40.0, -4.0));
assert_eq!(indent_values(&app, 1), (40.0, 12.0));
assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1);
app.run("edit.undo", json!({})).unwrap();
assert_eq!(indent_values(&app, 0), (24.0, 12.0));
assert_eq!(indent_values(&app, 1), (24.0, 28.0));
marker_event(&ctx, &mut app, 24.0, 40.0, false, true, false);
assert_eq!(indent_values(&app, 0), (40.0, 12.0));
assert_eq!(indent_values(&app, 1), (40.0, 28.0));
}
/// After Select All in threaded text, a marker change keeps the left indent and first-line position
/// of each paragraph in every frame of the story, when the edited frame's paragraphs agree and
/// another frame's differ.
#[test]
fn indent_markers_after_select_all_keep_each_story_paragraphs_indents() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 600, "height": 300})).unwrap();
let story = (1..=12).map(|i| format!("line {i}")).collect::<Vec<_>>().join("\n");
let a = app.run("text.create", json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 200, "height": 60}})).unwrap()["id"]
.as_u64()
.unwrap();
app.run("text.setFormat", json!({"ids": [a], "leftIndent": 24, "firstLineIndent": 12})).unwrap();
let b = app.run("text.thread.add", json!({"from": a, "rect": [300, 10, 200, 250]})).unwrap()["id"].as_u64().unwrap();
app.run("text.setFormat", json!({"ids": [b], "leftIndent": 60, "firstLineIndent": -10})).unwrap();
let paragraphs = |app: &VectorcraftApp| -> Vec<(u64, f64, f64)> {
let st = app.session.active().unwrap();
[a, b]
.into_iter()
.flat_map(|id| match &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind {
NodeKind::Text(t) => {
(0..t.paragraph_count()).map(|i| (id, t.para_at(i).left_indent, t.para_at(i).first_line_indent)).collect::<Vec<_>>()
}
_ => panic!("not text"),
})
.collect()
};
assert!(paragraphs(&app).iter().any(|p| p.1 == 24.0) && paragraphs(&app).iter().any(|p| p.1 == 60.0), "{:?}", paragraphs(&app));
let select_all = |app: &mut VectorcraftApp| {
app.run("select.set", json!({"ids": [a]})).unwrap();
app.session.select_tool("type", Default::default()).unwrap();
app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 0, "caret": 0}));
app.run("select.all", json!({})).unwrap();
assert_eq!(super::super::character::text_story(app), Some(vec![vectorcraft_doc::NodeId(a), vectorcraft_doc::NodeId(b)]));
};
select_all(&mut app);
let before = paragraphs(&app);
let (node, para, span) = current_para(&app).unwrap();
assert_eq!(node.id.0, a);
let targets = indent_targets(&app, &node);
set_marker(&mut app, IndentMarker::Upper, 70.0, ¶, span, &targets, false);
let after = paragraphs(&app);
assert_eq!(after.len(), before.len());
for (was, now) in before.iter().zip(&after) {
assert_eq!((now.1, now.1 + now.2), (was.1, 70.0), "a paragraph of frame {} keeps its left indent: {after:?}", now.0);
}
app.run("edit.undo", json!({})).unwrap();
assert_eq!(paragraphs(&app), before);
select_all(&mut app);
let (node, para, span) = current_para(&app).unwrap();
let targets = indent_targets(&app, &node);
set_marker(&mut app, IndentMarker::Lower, 40.0, ¶, span, &targets, false);
let after = paragraphs(&app);
assert_eq!(after.len(), before.len());
for (was, now) in before.iter().zip(&after) {
assert_eq!((now.1, now.1 + now.2), (40.0, was.1 + was.2), "a paragraph of frame {} keeps its first-line position: {after:?}", now.0);
}
}
/// After Select All in threaded text with mixed indents, a marker change that makes the first
/// frame's paragraphs wrap onto more lines pushes text into the next frame while the change is
/// applied. Every paragraph of the story still gets the new position: the upper marker keeps each
/// left indent, and the lower marker keeps each first-line position.
#[test]
fn indent_markers_after_select_all_follow_text_that_reflows_into_the_next_frame() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 600, "height": 1000})).unwrap();
let story = (1..=12).map(|i| format!("p{i} aaa bbb ccc")).collect::<Vec<_>>().join("\n");
let a = app.run("text.create", json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 200, "height": 60}})).unwrap()["id"]
.as_u64()
.unwrap();
let b = app.run("text.thread.add", json!({"from": a, "rect": [300, 10, 200, 950]})).unwrap()["id"].as_u64().unwrap();
app.run("text.setFormat", json!({"ids": [b], "leftIndent": 10})).unwrap();
// Each paragraph of the story by its first word, with its left indent and first-line position;
// a paragraph continued from the frame before is counted once. No paragraph of the story is
// empty, so an empty piece (after a frame's last line break) is not one.
let paragraphs = |app: &VectorcraftApp| -> Vec<(String, f64, f64)> {
let st = app.session.active().unwrap();
[a, b]
.into_iter()
.flat_map(|id| match &st.doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind {
NodeKind::Text(t) => t
.plain_text()
.split('\n')
.enumerate()
.filter(|(i, text)| !text.is_empty() && (*i > 0 || !t.first_para_continues))
.map(|(i, text)| {
let p = t.para_at(i);
(text.split(' ').next().unwrap_or_default().to_string(), p.left_indent, p.left_indent + p.first_line_indent)
})
.collect::<Vec<_>>(),
_ => panic!("not text"),
})
.collect()
};
let in_a = |app: &VectorcraftApp| match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(a)).unwrap().kind {
NodeKind::Text(t) => t.plain_text().len(),
_ => panic!("not text"),
};
// Select All in the first frame and move `marker` to `to` โ the story's paragraphs before and
// after.
let apply = |app: &mut VectorcraftApp, marker, to| {
let before = paragraphs(app);
assert_eq!(before.len(), 12, "{before:?}");
let shown = in_a(app);
app.run("select.set", json!({"ids": [a]})).unwrap();
app.session.select_tool("type", Default::default()).unwrap();
app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 0, "caret": 0}));
app.run("select.all", json!({})).unwrap();
let (node, para, span) = current_para(app).unwrap();
let targets = indent_targets(app, &node);
set_marker(app, marker, to, ¶, span, &targets, false);
let after = paragraphs(app);
assert!(in_a(app) < shown, "the first frame holds less text once it wraps: {} of {shown} bytes, {after:?}", in_a(app));
assert_eq!(after.iter().map(|p| &p.0).collect::<Vec<_>>(), before.iter().map(|p| &p.0).collect::<Vec<_>>());
(before, after)
};
let (before, after) = apply(&mut app, IndentMarker::Upper, 150.0);
assert!(before.iter().any(|p| p.1 == 0.0) && before.iter().any(|p| p.1 == 10.0), "{before:?}");
for (was, now) in before.iter().zip(&after) {
assert_eq!((now.1, now.2), (was.1, 150.0), "{} keeps its left indent and starts at 150 pt: {after:?}", now.0);
}
app.run("edit.undo", json!({})).unwrap();
assert_eq!(paragraphs(&app), before);
// First lines at 150 and 160 pt; a left indent of 180 pt leaves room for one word a line.
app.run("text.setFormat", json!({"ids": [a, b], "firstLineIndent": 150})).unwrap();
let (before, after) = apply(&mut app, IndentMarker::Lower, 180.0);
assert!(before.iter().any(|p| p.2 == 150.0) && before.iter().any(|p| p.2 == 160.0), "{before:?}");
for (was, now) in before.iter().zip(&after) {
assert_eq!((now.1, now.2), (180.0, was.2), "{} is indented 180 pt and keeps its first-line position: {after:?}", now.0);
}
}
/// A story of twelve paragraphs that wrap, threaded through three frames: the first two frames each
/// end inside a paragraph, which runs on into the next frame. โ the app and the frames in thread
/// order.
fn split_story_app() -> (VectorcraftApp, [u64; 3]) {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 900, "height": 1000})).unwrap();
// Each paragraph takes more lines than a short frame holds.
let words = "aaa bbb ccc ddd eee fff ggg hhh iii jjj ".repeat(3);
let story = (1..=12).map(|i| format!("p{i} {}", words.trim_end())).collect::<Vec<_>>().join("\n");
let a = app.run("text.create", json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 50}})).unwrap()["id"]
.as_u64()
.unwrap();
let b = app.run("text.thread.add", json!({"from": a, "rect": [300, 10, 150, 50]})).unwrap()["id"].as_u64().unwrap();
let c = app.run("text.thread.add", json!({"from": b, "rect": [600, 10, 250, 950]})).unwrap()["id"].as_u64().unwrap();
for id in [b, c] {
assert!(text_of(&app, id).first_para_continues, "frame {id} starts inside a paragraph: {:?}", text_of(&app, id).plain_text());
}
(app, [a, b, c])
}
fn text_of(app: &VectorcraftApp, id: u64) -> vectorcraft_doc::TextObject {
match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind {
NodeKind::Text(t) => (**t).clone(),
_ => panic!("not text"),
}
}
/// With the Selection tool, tab stops set in the panel go to every paragraph of every frame of a
/// selected threaded story, its locked and hidden frames included.
#[test]
fn selection_tool_tab_stops_reach_every_frame_of_the_story() {
let (mut app, frames) = split_story_app();
app.run("select.set", json!({"ids": [frames[1]]})).unwrap();
app.run("object.lock", json!({})).unwrap();
app.run("select.set", json!({"ids": [frames[2]]})).unwrap();
app.run("object.hide", json!({})).unwrap();
app.run("select.set", json!({"ids": [frames[0]]})).unwrap();
let stop = TabStop { position: 36.0, align: Default::default(), leader: String::new(), align_on: '.' };
assert!(apply(&mut app, std::slice::from_ref(&stop)));
for id in frames {
let t = text_of(&app, id);
assert!((0..t.paragraph_count()).all(|i| t.para_at(i).tabs == [stop.clone()]), "frame {id} takes the stop");
}
}
/// With the Selection tool, Clear All Tabs is on when only another frame of the selected story has
/// tab stops, and clears them there.
#[test]
fn clear_all_tabs_is_on_when_another_frame_of_the_story_has_stops() {
let (mut app, [a, b, c]) = split_story_app();
app.run("text.tabs.set", json!({"ids": [c], "stops": [{"position": 36}]})).unwrap();
app.run("select.set", json!({"ids": [c]})).unwrap();
app.run("object.hide", json!({})).unwrap();
app.run("select.set", json!({"ids": [a]})).unwrap();
assert!(current(&app).unwrap().1.is_empty(), "the selected frame has no stops");
assert!(story_has_tabs(&app));
super::super::paragraph::run_on_paragraphs(&mut app, "text.tabs.clear", json!({})).unwrap();
for id in [a, b, c] {
let t = text_of(&app, id);
assert!((0..t.paragraph_count()).all(|i| t.para_at(i).tabs.is_empty()), "frame {id} has no stops");
}
assert!(!story_has_tabs(&app));
}
/// Each paragraph of the story of `frames` by its first word, with its left indent and first-line
/// position, counted once; each piece of a paragraph split between frames has the same values.
fn story_paragraphs(app: &VectorcraftApp, frames: &[u64]) -> Vec<(String, f64, f64)> {
let mut out: Vec<(String, f64, f64)> = vec![];
for (k, id) in frames.iter().enumerate() {
let t = text_of(app, *id);
for (i, text) in t.plain_text().split('\n').enumerate() {
let p = t.para_at(i);
let values = (p.left_indent, p.left_indent + p.first_line_indent);
if i == 0 && k > 0 && t.first_para_continues {
let last = out.last().unwrap();
assert_eq!((last.1, last.2), values, "both pieces of {} agree", last.0);
} else if !text.is_empty() {
out.push((text.split(' ').next().unwrap_or_default().to_string(), values.0, values.1));
}
}
}
out
}
/// Where each target is in the story: its frame's place in `frames` and its start there.
fn story_positions(targets: &[IndentTarget], frames: &[u64]) -> Vec<(usize, usize)> {
targets.iter().map(|p| (frames.iter().position(|f| *f == p.id).unwrap(), p.start)).collect()
}
/// With the Selection tool on every frame of a threaded story, selected last frame first, the
/// indent markers list each paragraph of the story once, in the story's order, and a marker drag
/// over mixed indents sets every paragraph in one undo step, the two split paragraphs included.
#[test]
fn indent_markers_on_selected_threaded_frames_follow_the_story_and_set_a_split_paragraph_once() {
let (mut app, [a, b, c]) = split_story_app();
app.run("text.setFormat", json!({"ids": [c], "leftIndent": 10})).unwrap();
app.run("select.set", json!({"ids": [c, b, a]})).unwrap();
assert_eq!(app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect::<Vec<_>>(), vec![c, b, a]);
let before = story_paragraphs(&app, &[a, b, c]);
assert_eq!(before.len(), 12, "{before:?}");
assert!(before.iter().any(|p| p.1 == 0.0) && before.iter().any(|p| p.1 == 10.0), "{before:?}");
let (node, para, span) = current_para(&app).unwrap();
let targets = indent_targets(&app, &node);
let positions = story_positions(&targets, &[a, b, c]);
assert_eq!(positions.len(), 12, "one target for each paragraph of the story: {positions:?}");
assert!(positions.windows(2).all(|w| w[0] < w[1]), "the targets follow the story: {positions:?}");
let undo = app.session.active().unwrap().history.undo.len();
set_marker(&mut app, IndentMarker::Upper, 60.0, ¶, span, &targets, false);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
let after = story_paragraphs(&app, &[a, b, c]);
assert_eq!(after.iter().map(|p| &p.0).collect::<Vec<_>>(), before.iter().map(|p| &p.0).collect::<Vec<_>>());
for (was, now) in before.iter().zip(&after) {
assert_eq!((now.1, now.2), (was.1, 60.0), "{} keeps its left indent and starts at 60 pt: {after:?}", now.0);
}
}
/// A marker drag over many paragraphs of a threaded story with mixed indents sends one
/// `text.setFormat` for all of them, in one undo step, and a drag that changes no paragraph runs
/// nothing.
#[test]
fn indent_markers_over_many_threaded_paragraphs_send_one_format_command() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 900, "height": 3000})).unwrap();
let story = (1..=128).map(|i| format!("p{i}")).collect::<Vec<_>>().join("\n");
let a = app.run("text.create", json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 100}})).unwrap()["id"]
.as_u64()
.unwrap();
let b = app.run("text.thread.add", json!({"from": a, "rect": [300, 10, 200, 2900]})).unwrap()["id"].as_u64().unwrap();
app.run("text.setFormat", json!({"ids": [b], "leftIndent": 10})).unwrap();
app.run("select.set", json!({"ids": [a, b]})).unwrap();
let before = story_paragraphs(&app, &[a, b]);
assert_eq!(before.len(), 128, "{before:?}");
assert!(before.iter().any(|p| p.1 == 0.0) && before.iter().any(|p| p.1 == 10.0), "{before:?}");
let steps = |app: &VectorcraftApp| (app.session.active().unwrap().history.undo.len(), app.session.journal.len());
let drag = |app: &mut VectorcraftApp, marker, to| {
let (node, para, span) = current_para(app).unwrap();
let targets = indent_targets(app, &node);
assert_eq!(targets.len(), 128);
set_marker(app, marker, to, ¶, span, &targets, false);
};
let (undo, journal) = steps(&app);
drag(&mut app, IndentMarker::Upper, 60.0);
assert_eq!(steps(&app), (undo + 1, journal + 1));
let (name, params) = app.session.journal.last().cloned().unwrap();
assert_eq!(name, "command.batch");
let commands = params["commands"].as_array().unwrap();
assert_eq!(commands.len(), 1, "one command for every paragraph");
assert_eq!(commands[0]["command"], "text.setFormat");
assert_eq!(commands[0]["params"]["paragraphIndents"].as_array().unwrap().len(), 128);
let after = story_paragraphs(&app, &[a, b]);
for (was, now) in before.iter().zip(&after) {
assert_eq!((&now.0, now.1, now.2), (&was.0, was.1, 60.0), "{after:?}");
}
// The same position again changes no paragraph.
drag(&mut app, IndentMarker::Upper, 60.0);
assert_eq!(steps(&app), (undo + 1, journal + 1), "nothing ran");
app.run("edit.undo", json!({})).unwrap();
assert_eq!(story_paragraphs(&app, &[a, b]), before);
app.run("edit.redo", json!({})).unwrap();
assert_eq!(story_paragraphs(&app, &[a, b]), after);
}
/// After Select All in threaded text, a paragraph split between two frames is one target.
#[test]
fn indent_markers_after_select_all_list_a_split_paragraph_once() {
let (mut app, [a, b, c]) = split_story_app();
app.run("select.set", json!({"ids": [a]})).unwrap();
app.session.select_tool("type", Default::default()).unwrap();
app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 0, "caret": 0}));
app.run("select.all", json!({})).unwrap();
let ids = [a, b, c].map(vectorcraft_doc::NodeId);
assert_eq!(super::super::character::text_story(&app), Some(ids.to_vec()));
let (node, _, _) = current_para(&app).unwrap();
let positions = story_positions(&indent_targets(&app, &node), &[a, b, c]);
assert_eq!(positions.len(), 12, "{positions:?}");
assert!(positions.windows(2).all(|w| w[0] < w[1]), "{positions:?}");
}
/// With the Selection tool on any frame of a threaded story, the indent markers list every
/// paragraph of the story, each once in story order: a selected story is one text. Text in a
/// selected group is listed with the story's frames, and an empty text object keeps its one
/// paragraph.
#[test]
fn indent_markers_on_some_threaded_frames_list_the_whole_story_once() {
let (mut app, [a, b, c]) = split_story_app();
let count = |app: &VectorcraftApp, id: u64| text_of(app, id).paragraph_count();
let targets_of = |app: &mut VectorcraftApp, ids: Vec<u64>| {
app.run("select.set", json!({"ids": ids})).unwrap();
let (node, _, _) = current_para(app).unwrap();
story_positions(&indent_targets(app, &node), &[a, b, c])
};
let story = count(&app, a) + count(&app, b) + count(&app, c) - 2;
let all = targets_of(&mut app, vec![c, a, b]);
assert_eq!(all.len(), story, "two frames that share a paragraph list it once: {all:?}");
assert!(all.windows(2).all(|w| w[0] < w[1]), "{all:?}");
for frame in [a, b, c] {
assert_eq!(targets_of(&mut app, vec![frame]), all, "frame {frame} alone lists the whole story");
}
// A grouped empty text object besides the last frame of the story.
let empty = app.run("text.create", json!({"x": 10, "y": 900, "text": "", "area": {"width": 100, "height": 40}})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [empty, c]})).unwrap();
let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [group]})).unwrap();
let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(c)).unwrap().clone();
let targets = indent_targets(&app, &node);
let ids: Vec<u64> = targets.iter().map(|p| p.id).collect();
assert_eq!(ids.iter().filter(|id| **id == empty).count(), 1, "{ids:?}");
let in_story: Vec<IndentTarget> = targets.into_iter().filter(|p| p.id != empty).collect();
assert_eq!(story_positions(&in_story, &[a, b, c]), all);
}
/// A marker drag on one selected frame of a threaded story sets every paragraph of the story, in
/// its locked and hidden frames too, in one undo step, whether the paragraphs share their indents
/// or have their own.
#[test]
fn indent_markers_on_one_threaded_frame_set_its_locked_and_hidden_frames() {
let (mut app, [a, b, c]) = split_story_app();
app.run("select.set", json!({"ids": [b]})).unwrap();
app.run("object.lock", json!({})).unwrap();
app.run("select.set", json!({"ids": [c]})).unwrap();
app.run("object.hide", json!({})).unwrap();
app.run("select.set", json!({"ids": [a]})).unwrap();
// Every paragraph has the same indents.
let (node, para, span) = current_para(&app).unwrap();
let targets = indent_targets(&app, &node);
assert_eq!(targets.len(), 12);
let undo = app.session.active().unwrap().history.undo.len();
set_marker(&mut app, IndentMarker::Upper, 30.0, ¶, span, &targets, false);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
let shared = story_paragraphs(&app, &[a, b, c]);
assert_eq!(shared.len(), 12, "{shared:?}");
assert!(shared.iter().all(|p| (p.1, p.2) == (0.0, 30.0)), "{shared:?}");
// The paragraphs of the hidden frame have a left indent of their own.
app.run("text.setFormat", json!({"ids": [c], "leftIndent": 10})).unwrap();
app.run("select.set", json!({"ids": [a]})).unwrap();
let before = story_paragraphs(&app, &[a, b, c]);
assert_eq!(before.len(), 12, "{before:?}");
assert!(before.iter().any(|p| p.1 == 0.0) && before.iter().any(|p| p.1 == 10.0), "{before:?}");
let (node, para, span) = current_para(&app).unwrap();
let targets = indent_targets(&app, &node);
assert_eq!(targets.len(), 12);
let undo = app.session.active().unwrap().history.undo.len();
set_marker(&mut app, IndentMarker::Upper, 60.0, ¶, span, &targets, false);
assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1);
let after = story_paragraphs(&app, &[a, b, c]);
assert_eq!(after.iter().map(|p| &p.0).collect::<Vec<_>>(), before.iter().map(|p| &p.0).collect::<Vec<_>>());
for (was, now) in before.iter().zip(&after) {
assert_eq!((now.1, now.2), (was.1, 60.0), "{} keeps its left indent and starts at 60 pt: {after:?}", now.0);
}
}
#[test]
fn lower_marker_bounds_cover_each_touched_first_line() {
let targets = [
IndentTarget { id: 1, start: 0, left: 24.0, first_line: -20.0, level: 0.0 },
IndentTarget { id: 1, start: 4, left: 24.0, first_line: 280.0, level: 0.0 },
];
assert_eq!(bounded_marker_position(IndentMarker::Lower, 40.0, 300.0, &targets, true), Some(20.0));
assert_eq!(bounded_marker_position(IndentMarker::Lower, 1200.0, 300.0, &targets, false), Some(300.0));
// A paragraph at list level 2 is laid out 18 pt further in: its own left indent stays at 0 or more.
let listed = [IndentTarget { id: 1, start: 0, left: 18.0, first_line: 0.0, level: 18.0 }];
assert_eq!(bounded_marker_position(IndentMarker::Lower, 5.0, 300.0, &listed, true), Some(18.0));
}
/// A list paragraph at level 2 is laid out 18 pt further in than its left indent: the ruler shows
/// its markers there, and a marker moved on the ruler sets the paragraph's own left indent.
#[test]
fn indent_markers_show_and_set_a_list_paragraphs_laid_out_indent() {
let mut app = indent_app(10.0, 6.0);
app.run("text.setFormat", json!({"list": "bullet", "listLevel": 2})).unwrap();
let para = current_para(&app).unwrap().1;
assert_eq!((marker_position(IndentMarker::Lower, ¶), marker_position(IndentMarker::Upper, ¶)), (28.0, 34.0));
let ctx = egui::Context::default();
marker_event(&ctx, &mut app, 28.0, 40.0, false, true, false);
assert_eq!(indent_values(&app, 0), (22.0, 6.0), "the ruler's 40 pt is the paragraph's 22 pt and the level's 18");
marker_event(&ctx, &mut app, 46.0, 70.0, true, false, false);
assert_eq!(indent_values(&app, 0), (22.0, 30.0));
marker_event(&ctx, &mut app, 40.0, 20.0, false, false, false);
assert_eq!(indent_values(&app, 0), (2.0, 50.0), "the first line stays at 70 pt");
}
#[test]
fn hidden_lower_selection_returns_x_field_to_tab_stop() {
let mut app = indent_app(24.0, 12.0);
app.run("text.tabs.set", json!({"stops": [{"position": 100}]})).unwrap();
let ctx = egui::Context::default();
marker_event(&ctx, &mut app, 24.0, 24.0, false, false, false);
assert_eq!(pstate::<Option<IndentMarker>>(&ctx, "tabs-marker-sel"), Some(IndentMarker::Lower));
let id = current(&app).unwrap().0.id.0;
app.run("text.setFormat", json!({"id": id, "start": 4, "end": 7, "leftIndent": 60})).unwrap();
assert_eq!(indent_values(&app, 0), (24.0, 12.0));
assert_eq!(indent_values(&app, 1), (60.0, 12.0));
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0));
let frame = |app: &mut VectorcraftApp, events| {
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
out.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::Text(t) => Some((t.galley.text().to_string(), t.visual_bounding_rect())),
_ => None,
})
.collect::<Vec<_>>()
};
let texts = frame(&mut app, vec![]);
let at = texts.iter().find(|(text, _)| text == "100 pt").unwrap_or_else(|| panic!("tab X field missing: {texts:?}")).1.center();
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
frame(&mut app, vec![egui::Event::PointerMoved(at), button(true)]);
frame(&mut app, vec![button(false)]);
let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
frame(&mut app, vec![key(egui::Key::A, egui::Modifiers::COMMAND)]);
frame(&mut app, vec![egui::Event::Text("120".into())]);
frame(&mut app, vec![key(egui::Key::Enter, egui::Modifiers::NONE)]);
assert_eq!(indent_values(&app, 0).0, 24.0);
assert_eq!(indent_values(&app, 1).0, 60.0);
assert_eq!(current(&app).unwrap().1[0].position, 120.0);
}
#[test]
fn selected_marker_position_field_sets_its_absolute_position() {
let mut app = indent_app(24.0, 12.0);
let ctx = egui::Context::default();
marker_event(&ctx, &mut app, 36.0, 36.0, true, false, false);
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0));
let field_frame = |app: &mut VectorcraftApp, events| {
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
out.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::Text(t) => Some((t.galley.text().to_string(), t.visual_bounding_rect())),
_ => None,
})
.collect::<Vec<_>>()
};
let texts = field_frame(&mut app, vec![]);
let at = texts.iter().find(|(text, _)| text == "36 pt").unwrap_or_else(|| panic!("36 pt in {texts:?}")).1.center();
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
field_frame(&mut app, vec![egui::Event::PointerMoved(at), button(true)]);
field_frame(&mut app, vec![button(false)]);
let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
field_frame(&mut app, vec![key(egui::Key::A, egui::Modifiers::COMMAND)]);
field_frame(&mut app, vec![egui::Event::Text("80".into())]);
field_frame(&mut app, vec![key(egui::Key::Enter, egui::Modifiers::NONE)]);
assert_eq!(indent_values(&app, 0), (24.0, 56.0));
marker_event(&ctx, &mut app, 24.0, 24.0, false, false, false);
let texts = field_frame(&mut app, vec![]);
let at = texts.iter().find(|(text, _)| text == "24 pt").unwrap_or_else(|| panic!("24 pt in {texts:?}")).1.center();
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
field_frame(&mut app, vec![egui::Event::PointerMoved(at), button(true)]);
field_frame(&mut app, vec![button(false)]);
field_frame(&mut app, vec![key(egui::Key::A, egui::Modifiers::COMMAND)]);
field_frame(&mut app, vec![egui::Event::Text("40".into())]);
field_frame(&mut app, vec![key(egui::Key::Enter, egui::Modifiers::NONE)]);
assert_eq!(indent_values(&app, 0), (40.0, 40.0));
}
/// The ruler is numbered in the General unit (the document's units), with labels at least 50 px
/// apart as on the canvas rulers.
#[test]
fn ruler_is_numbered_in_the_general_unit() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
let ctx = egui::Context::default();
assert_eq!(ruler_labels(&ctx, &mut app), ["0", "50", "100", "150", "200", "250", "300"]);
app.session.execute("document.setUnits", &json!({"units": "in"})).unwrap();
assert_eq!(ruler_labels(&ctx, &mut app), ["0", "1", "2", "3", "4"]);
app.session.execute("document.setUnits", &json!({"units": "mm"})).unwrap();
assert_eq!(ruler_labels(&ctx, &mut app), ["0", "25", "50", "75", "100"]);
}
/// Snap to Unit, chosen from the panel menu with or without text selected, puts a stop dragged
/// or placed by a click on the ruler on its nearest tick (every 5 pt on this points ruler).
/// Chosen again, it turns off.
#[test]
fn snap_to_unit_puts_dragged_and_clicked_stops_on_the_nearest_tick() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
let ctx = egui::Context::default();
let row = |app: &mut VectorcraftApp| {
let rows = menu_frame(&ctx, app, vec![]);
rows.into_iter().find(|(t, _)| t.trim_start_matches(['โ', ' ']) == "Snap to Unit").unwrap_or_else(|| panic!("Snap to Unit"))
};
choose(&ctx, &mut app, "Snap to Unit");
assert_eq!(row(&mut app).0, "โ Snap to Unit");
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 50}]})).unwrap();
assert_eq!(ruler_labels(&ctx, &mut app)[..2], ["0", "50"]);
let positions = |app: &VectorcraftApp| current(app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>();
drag_on_ruler(&ctx, &mut app, 50.0, 13.4, false);
assert_eq!(positions(&app), [15.0]);
// A click at 33.4 pt adds a stop at 35.
drag_on_ruler(&ctx, &mut app, 33.4, 33.4, false);
assert_eq!(positions(&app), [15.0, 35.0]);
assert_eq!(row(&mut app).0, "โ Snap to Unit");
// Chosen again, Snap to Unit turns off and the stop lands on the whole point nearest where it
// is dropped.
let at = row(&mut app).1.center();
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
menu_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(at), button(true)]);
menu_frame(&ctx, &mut app, vec![button(false)]);
assert_eq!(row(&mut app).0.trim_start(), "Snap to Unit");
drag_on_ruler(&ctx, &mut app, 35.0, 23.4, false);
assert_eq!(positions(&app), [15.0, 23.0]);
}
/// A snapped click more than 5 px from a stop, nearest to the tick that stop is on, selects the
/// stop and records no undo step. On this millimeters ruler the ticks are 2.5 mm (7.09 pt, 12.4
/// px) apart.
#[test]
fn a_snapped_click_onto_a_stop_selects_it() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("document.setUnits", &json!({"units": "mm"})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 224, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 100}]})).unwrap();
let ctx = egui::Context::default();
assert_eq!(ruler_labels(&ctx, &mut app), ["0", "25", "50", "75"]);
set_pstate(&ctx, "tabs-snap", true);
let tick = 2.5 * 72.0 / 25.4;
drag_on_ruler(&ctx, &mut app, 28.4, 28.4, false);
let positions = |app: &VectorcraftApp| current(app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>();
assert_eq!(positions(&app).len(), 2);
assert!((positions(&app)[0] - 4.0 * tick).abs() < 1e-9, "{:?}", positions(&app));
set_pstate(&ctx, "tabs-sel", 1usize);
let steps = app.session.active().unwrap().history.undo.len();
// The click is 3.3 pt (5.8 px) right of the stop, past the 5 px hit tolerance and nearest its tick.
drag_on_ruler(&ctx, &mut app, 4.0 * tick + 3.3, 4.0 * tick + 3.3, false);
assert_eq!(positions(&app).len(), 2, "{:?}", positions(&app));
assert_eq!(pstate::<usize>(&ctx, "tabs-sel"), 0);
assert_eq!(app.session.active().unwrap().history.undo.len(), steps, "no undo step");
}
/// With Snap to Unit off, Shift held during the drag puts the stop on the ruler's nearest tick.
#[test]
fn shift_drag_snaps_a_stop_to_the_nearest_tick() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 50}]})).unwrap();
let ctx = egui::Context::default();
let position = |app: &VectorcraftApp| current(app).unwrap().1[0].position;
drag_on_ruler(&ctx, &mut app, 50.0, 13.4, false);
assert!((position(&app) - 13.4).abs() < 1.0, "{}", position(&app));
let from = position(&app);
drag_on_ruler(&ctx, &mut app, from, 41.6, true);
assert_eq!(position(&app), 40.0);
// In an inches document the ticks divide the inch in half, not in ten (#2827), so the
// nearest one to 100 pt is 99 pt -- 1 3/8 in, an eighth of an inch from 1 1/4.
app.session.execute("document.setUnits", &json!({"units": "in"})).unwrap();
drag_on_ruler(&ctx, &mut app, 40.0, 100.0, true);
assert!((position(&app) - 99.0).abs() < 1e-9, "{}", position(&app));
assert_eq!((position(&app) / 72.0 * 8.0).round(), position(&app) / 72.0 * 8.0, "a binary fraction of an inch");
}
/// One frame of the panel with `events` โ the texts painted and where.
fn panel_frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> Vec<(String, egui::Rect)> {
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0));
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
out.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::Text(t) => Some((t.galley.text().to_string(), t.visual_bounding_rect())),
_ => None,
})
.collect()
}
/// A stop dragged past another stays selected once the stops are sorted, so the X field shows
/// where it was dropped.
#[test]
fn a_stop_dragged_past_another_stays_selected() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 30}, {"position": 50}]})).unwrap();
let ctx = egui::Context::default();
drag_on_ruler(&ctx, &mut app, 50.0, 10.0, false);
let stops = current(&app).unwrap().1;
assert_eq!(stops.len(), 2);
assert!((stops[0].position - 10.0).abs() < 1.0 && stops[1].position == 30.0, "{stops:?}");
assert_eq!(pstate::<usize>(&ctx, "tabs-sel"), 0);
let shown = app.session.general_unit().format(stops[0].position);
let texts = panel_frame(&ctx, &mut app, vec![]);
assert!(texts.iter().any(|(t, _)| *t == shown), "{shown} in {texts:?}");
}
/// Press on the stop at `from` (points), move to `to` and release there with Ctrl (Command on
/// macOS) held โ the stems' x positions painted in the frame before the release.
fn command_drag_on_ruler(ctx: &egui::Context, app: &mut VectorcraftApp, from: f64, to: f64) -> Vec<f32> {
let labels = ruler_frame(ctx, app, vec![], false);
let [(zero, a), (next, b), ..] = &labels[..] else { panic!("ruler labels {labels:?}") };
assert_eq!(zero, "0");
let per = next.parse::<f64>().unwrap() * app.session.general_unit().points();
let x = |pt: f64| a.x - 2.0 + (pt / per) as f32 * (b.x - a.x);
let y = a.y + 15.0;
let command = egui::Event::ModifiersChanged(egui::Modifiers::COMMAND);
let button =
|pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::COMMAND };
let (press, end) = (egui::pos2(x(from), y), egui::pos2(x(to), y));
ruler_frame(ctx, app, vec![command.clone(), egui::Event::PointerMoved(press), button(press, true)], false);
for f in [0.25, 0.5] {
ruler_frame(ctx, app, vec![command.clone(), egui::Event::PointerMoved(press.lerp(end, f))], false);
}
let stems = stems_frame(ctx, app, vec![command.clone(), egui::Event::PointerMoved(end)]);
ruler_frame(ctx, app, vec![command, button(end, false)], false);
ruler_frame(ctx, app, vec![], false);
stems.into_iter().map(|(x, _)| x).collect()
}
/// Ctrl-dragging a stop (Command on macOS) moves every stop by the same distance in one
/// `text.tabs.set`, one undo step, keeping each stop's alignment and leader, and the ruler shows
/// them moving during the drag. A plain drag still moves one stop.
#[test]
fn command_drag_moves_all_the_stops_together() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b c", "area": {"width": 300, "height": 100}})).unwrap();
app.session
.execute(
"text.tabs.set",
&json!({"stops": [{"position": 30, "leader": "."}, {"position": 50, "align": "right"}, {"position": 80, "align": "decimal", "alignOn": ","}]}),
)
.unwrap();
let ctx = egui::Context::default();
let positions = |app: &VectorcraftApp| current(app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>();
let before = app.session.active().unwrap().history.undo.len();
let during = command_drag_on_ruler(&ctx, &mut app, 50.0, 70.0);
assert_eq!(positions(&app), [50.0, 70.0, 100.0]);
let stops = current(&app).unwrap().1;
assert_eq!(stops.iter().map(|s| s.align).collect::<Vec<_>>(), [TabAlign::Left, TabAlign::Right, TabAlign::Decimal]);
assert_eq!((stops[0].leader.as_str(), stops[2].align_on), (".", ','));
assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1);
assert_eq!(pstate::<usize>(&ctx, "tabs-sel"), 1);
let after: Vec<f32> = stems_frame(&ctx, &mut app, vec![]).into_iter().map(|(x, _)| x).collect();
assert_eq!(during.len(), 3, "{during:?}");
assert!(during.iter().zip(&after).all(|(d, a)| (d - a).abs() < 0.5), "during the drag {during:?}, after it {after:?}");
app.run("edit.undo", json!({})).unwrap();
assert_eq!(positions(&app), [30.0, 50.0, 80.0]);
drag_on_ruler(&ctx, &mut app, 50.0, 70.0, false);
assert_eq!(positions(&app), [30.0, 70.0, 80.0]);
}
/// A Ctrl-drag (Command on macOS) that would put a stop below 0 stops when the leftmost stop
/// reaches 0, so the stops keep their spacing.
#[test]
fn command_drag_stops_at_zero_and_keeps_the_spacing() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 30}, {"position": 50}]})).unwrap();
let ctx = egui::Context::default();
command_drag_on_ruler(&ctx, &mut app, 50.0, 5.0);
assert_eq!(current(&app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>(), [0.0, 20.0]);
assert_eq!(moved_all(¤t(&app).unwrap().1, 1, 0.0).unwrap().iter().map(|s| s.position).collect::<Vec<_>>(), [0.0, 20.0]);
assert!(moved_all(&[], 0, 10.0).is_none());
}
/// A drag that leaves the stops where they were records no undo step: a Ctrl-drag (Command on
/// macOS) to the left while the leftmost stop is at 0, and a plain drag that takes a stop away and
/// releases it where it started. The dragged stop is still selected.
#[test]
fn a_drag_that_moves_no_stop_records_no_undo_step() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 0}, {"position": 20}]})).unwrap();
let ctx = egui::Context::default();
let positions = |app: &VectorcraftApp| current(app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>();
let before = app.session.active().unwrap().history.undo.len();
command_drag_on_ruler(&ctx, &mut app, 20.0, 5.0);
assert_eq!(positions(&app), [0.0, 20.0]);
assert_eq!(app.session.active().unwrap().history.undo.len(), before, "Ctrl-drag");
assert_eq!(pstate::<usize>(&ctx, "tabs-sel"), 1);
set_pstate(&ctx, "tabs-sel", 0usize);
let labels = ruler_frame(&ctx, &mut app, vec![], false);
let [(zero, a), (next, b), ..] = &labels[..] else { panic!("ruler labels {labels:?}") };
assert_eq!(zero, "0");
let per = next.parse::<f64>().unwrap() * app.session.general_unit().points();
let x = |pt: f64| egui::pos2(a.x - 2.0 + (pt / per) as f32 * (b.x - a.x), a.y + 15.0);
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
ruler_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(x(20.0)), button(x(20.0), true)], false);
for pt in [40.0, 60.0, 30.0, 20.0] {
ruler_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(x(pt))], false);
}
ruler_frame(&ctx, &mut app, vec![button(x(20.0), false)], false);
ruler_frame(&ctx, &mut app, vec![], false);
assert_eq!(positions(&app), [0.0, 20.0]);
assert_eq!(app.session.active().unwrap().history.undo.len(), before, "plain drag");
assert_eq!(pstate::<usize>(&ctx, "tabs-sel"), 1);
}
/// A Ctrl-drag (Command on macOS) that would put a stop past 100,000 pt stops when the rightmost
/// stop reaches 100,000 pt, so the stops move and keep their spacing.
#[test]
fn command_drag_stops_at_the_largest_position_and_keeps_the_spacing() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 50}, {"position": 99_990}]})).unwrap();
let ctx = egui::Context::default();
command_drag_on_ruler(&ctx, &mut app, 50.0, 70.0);
assert_eq!(current(&app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>(), [60.0, 100_000.0]);
}
/// Press on the stop at `from` (points), move to `to` and `below` px under the ruler, and release
/// there in the same frame as Escape, Ctrl (Command on macOS) held when `command`.
fn escaped_drag_on_ruler(ctx: &egui::Context, app: &mut VectorcraftApp, from: f64, to: f64, below: f32, command: bool) {
let labels = ruler_frame(ctx, app, vec![], false);
let [(zero, a), (next, b), ..] = &labels[..] else { panic!("ruler labels {labels:?}") };
assert_eq!(zero, "0");
let per = next.parse::<f64>().unwrap() * app.session.general_unit().points();
let x = |pt: f64| a.x - 2.0 + (pt / per) as f32 * (b.x - a.x);
let y = a.y + 15.0;
let modifiers = if command { egui::Modifiers::COMMAND } else { egui::Modifiers::NONE };
let held = egui::Event::ModifiersChanged(modifiers);
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers };
let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers };
let (press, end) = (egui::pos2(x(from), y), egui::pos2(x(to), y + below));
ruler_frame(ctx, app, vec![held.clone(), egui::Event::PointerMoved(press), button(press, true)], false);
for f in [0.25, 0.5, 1.0] {
ruler_frame(ctx, app, vec![held.clone(), egui::Event::PointerMoved(press.lerp(end, f))], false);
}
ruler_frame(ctx, app, vec![held, escape, button(end, false)], false);
ruler_frame(ctx, app, vec![], false);
}
/// Escape pressed in the frame a stop is released cancels the drag: a plain drag, a Ctrl-drag
/// (Command on macOS) and a drag off the ruler all leave the stops where they were.
#[test]
fn escape_in_the_release_frame_cancels_a_stop_drag() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 30}, {"position": 50}]})).unwrap();
let ctx = egui::Context::default();
let positions = |app: &VectorcraftApp| current(app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>();
let before = app.session.active().unwrap().history.undo.len();
for (below, command) in [(0.0, false), (0.0, true), (60.0, false), (60.0, true)] {
escaped_drag_on_ruler(&ctx, &mut app, 50.0, 70.0, below, command);
assert_eq!(positions(&app), [30.0, 50.0], "{below} px below, command {command}");
}
assert_eq!(app.session.active().unwrap().history.undo.len(), before);
// The next drag without Escape still moves the stop.
drag_on_ruler(&ctx, &mut app, 50.0, 70.0, false);
assert_eq!(positions(&app), [30.0, 70.0]);
}
/// Press on the stop at `from` (points) and move to `to`, `below` px under the ruler, with
/// `modifiers` held, without letting go โ where the pointer is.
fn hold_drag_on_ruler(ctx: &egui::Context, app: &mut VectorcraftApp, from: f64, to: f64, below: f32, modifiers: egui::Modifiers) -> egui::Pos2 {
let labels = ruler_frame(ctx, app, vec![], false);
let [(zero, a), (next, b), ..] = &labels[..] else { panic!("ruler labels {labels:?}") };
assert_eq!(zero, "0");
let per = next.parse::<f64>().unwrap() * app.session.general_unit().points();
let x = |pt: f64| a.x - 2.0 + (pt / per) as f32 * (b.x - a.x);
let y = a.y + 15.0;
let held = egui::Event::ModifiersChanged(modifiers);
let press = egui::pos2(x(from), y);
let end = egui::pos2(x(to), y + below);
let button = egui::Event::PointerButton { pos: press, button: egui::PointerButton::Primary, pressed: true, modifiers };
ruler_frame(ctx, app, vec![held.clone(), egui::Event::PointerMoved(press), button], false);
for f in [0.25, 0.5, 1.0] {
ruler_frame(ctx, app, vec![held.clone(), egui::Event::PointerMoved(press.lerp(end, f))], false);
}
end
}
/// Let go at `at` with `modifiers` held, then draw one more frame.
fn release_on_ruler(ctx: &egui::Context, app: &mut VectorcraftApp, at: egui::Pos2, modifiers: egui::Modifiers) {
let button = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers };
ruler_frame(ctx, app, vec![egui::Event::ModifiersChanged(modifiers), button], false);
ruler_frame(ctx, app, vec![], false);
}
/// Area type at (10, 20), 300 by 100 pt, with stops at `stops` points, and the app.
fn guide_app(stops: &[f64]) -> VectorcraftApp {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({})).unwrap();
app.run("text.create", json!({"x": 10, "y": 20, "text": "a\tb\tc", "area": {"width": 300, "height": 100}})).unwrap();
let stops: Vec<_> = stops.iter().map(|p| json!({"position": p})).collect();
app.run("text.tabs.set", json!({"stops": stops})).unwrap();
app
}
fn near(a: Point, b: Point) -> bool {
(a - b).hypot() < 0.01
}
/// While a stop is dragged on the ruler, a guide crosses the selected area type at the place the
/// stop would land, measured from the frame's left edge, from the frame's top to its bottom. It
/// follows the pointer, adds nothing to the document or its undo history, and is gone after the
/// release, which moves the stop as before.
#[test]
fn dragging_a_stop_draws_a_guide_through_the_text() {
let mut app = guide_app(&[50.0]);
let ctx = egui::Context::default();
ruler_frame(&ctx, &mut app, vec![], false);
assert_eq!(stop_guide(&app, &ctx), None, "before the drag");
let frame = current(&app).unwrap().0.geometric_bounds().unwrap();
let (before, layers) = (app.session.active().unwrap().history.undo.len(), app.session.active().unwrap().doc.layers.clone());
let end = hold_drag_on_ruler(&ctx, &mut app, 50.0, 70.0, 0.0, egui::Modifiers::NONE);
let (a, b) = stop_guide(&app, &ctx).expect("a guide during the drag");
assert!(near(a, Point::new(frame.x0 + 70.0, frame.y0)) && near(b, Point::new(frame.x0 + 70.0, frame.y1)), "{a:?} {b:?} in {frame:?}");
let doc = app.session.active().unwrap();
assert_eq!((doc.history.undo.len(), &doc.doc.layers), (before, &layers), "the guide is not part of the document");
// The guide follows the pointer while the button stays down.
let held = egui::Event::ModifiersChanged(egui::Modifiers::NONE);
ruler_frame(&ctx, &mut app, vec![held, egui::Event::PointerMoved(end - vec2(20.0, 0.0))], false);
let (moved, _) = stop_guide(&app, &ctx).unwrap();
assert!(moved.x < a.x - 1.0, "{moved:?} after {a:?}");
release_on_ruler(&ctx, &mut app, end, egui::Modifiers::NONE);
assert_eq!(stop_guide(&app, &ctx), None, "after the release");
assert_eq!(current(&app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>(), [70.0]);
assert_eq!(app.session.active().unwrap().history.undo.len(), before + 1);
}
/// When a text wrap object pushes the paragraph's lines right, the guide is measured from where the
/// first line starts, as the layout measures the stops, and a first-line indent does not move it.
#[test]
fn the_stop_guide_starts_where_a_wrap_object_lets_the_line_start() {
let mut app = guide_app(&[50.0]);
let text = current(&app).unwrap().0.id.0;
app.run("text.setFormat", json!({"firstLineIndent": 12})).unwrap();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 60, "height": 200})).unwrap();
app.run("object.textWrap.make", json!({"offset": 0})).unwrap();
app.run("select.set", json!({"ids": [text]})).unwrap();
let ctx = egui::Context::default();
let end = hold_drag_on_ruler(&ctx, &mut app, 50.0, 70.0, 0.0, egui::Modifiers::NONE);
let (a, b) = stop_guide(&app, &ctx).unwrap();
assert!((a.x - 130.0).abs() < 0.01 && (b.x - 130.0).abs() < 0.01, "70 pt right of the wrap object's edge at 60: {a:?} {b:?}");
release_on_ruler(&ctx, &mut app, end, egui::Modifiers::NONE);
// The tab after "a" ends at the stop: "b" starts 70 pt right of the wrap object's edge.
let NodeKind::Text(t) = ¤t(&app).unwrap().0.kind else { panic!("text") };
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let b_at = lay.glyphs.iter().find(|g| t.plain_text().get(g.byte..).is_some_and(|s| s.starts_with('b'))).unwrap().origin.x;
assert!(((t.xf * Point::new(b_at, 0.0)).x - 130.0).abs() < 0.01, "b at {b_at}");
}
/// In a Ctrl-drag (Command on macOS) the guide follows the stop under the pointer, also when the
/// leftmost stop stops the drag at 0.
#[test]
fn a_command_drag_guide_follows_the_grabbed_stop() {
let mut app = guide_app(&[30.0, 50.0, 80.0]);
let ctx = egui::Context::default();
let x0 = current(&app).unwrap().0.geometric_bounds().unwrap().x0;
let end = hold_drag_on_ruler(&ctx, &mut app, 50.0, 70.0, 0.0, egui::Modifiers::COMMAND);
let (a, _) = stop_guide(&app, &ctx).unwrap();
assert!((a.x - (x0 + 70.0)).abs() < 0.01, "{a:?}");
release_on_ruler(&ctx, &mut app, end, egui::Modifiers::COMMAND);
assert_eq!(current(&app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>(), [50.0, 70.0, 100.0]);
// The stop grabbed at 70 pt can move 50 pt left before the stop at 50 pt reaches 0.
let end = hold_drag_on_ruler(&ctx, &mut app, 70.0, 5.0, 0.0, egui::Modifiers::COMMAND);
let (a, _) = stop_guide(&app, &ctx).unwrap();
assert!((a.x - (x0 + 20.0)).abs() < 0.01, "{a:?}");
release_on_ruler(&ctx, &mut app, end, egui::Modifiers::COMMAND);
assert_eq!(stop_guide(&app, &ctx), None);
}
/// No guide shows while a release would delete the stop, after Escape, after a release the ruler
/// did not see, or once the panel is no longer drawn.
#[test]
fn the_stop_guide_ends_with_the_drag() {
let mut app = guide_app(&[30.0, 50.0]);
let ctx = egui::Context::default();
let positions = |app: &VectorcraftApp| current(app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>();
// Off the ruler, where a release deletes the stop.
let end = hold_drag_on_ruler(&ctx, &mut app, 50.0, 70.0, 60.0, egui::Modifiers::NONE);
assert_eq!(stop_guide(&app, &ctx), None, "off the ruler");
release_on_ruler(&ctx, &mut app, end, egui::Modifiers::NONE);
assert_eq!(positions(&app), [30.0]);
// Escape during the drag.
let end = hold_drag_on_ruler(&ctx, &mut app, 30.0, 60.0, 0.0, egui::Modifiers::NONE);
assert!(stop_guide(&app, &ctx).is_some());
let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
ruler_frame(&ctx, &mut app, vec![escape], false);
ruler_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(end + vec2(5.0, 0.0))], false);
assert_eq!(stop_guide(&app, &ctx), None, "after Escape");
release_on_ruler(&ctx, &mut app, end, egui::Modifiers::NONE);
assert_eq!(positions(&app), [30.0]);
// A drag whose release the ruler never got: the next frame without a button down ends it, so a
// later press elsewhere shows no guide and a later release moves nothing.
set_pstate(&ctx, "tabs-drag", Some(0usize));
ruler_frame(&ctx, &mut app, vec![], false);
assert_eq!(pstate::<Option<usize>>(&ctx, "tabs-drag"), None);
// A place in the panel right of its fields, above the ruler.
let ruler_y = ruler_frame(&ctx, &mut app, vec![], false)[0].1.y;
let away = egui::pos2(380.0, ruler_y - 30.0);
let press = egui::Event::PointerButton { pos: away, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE };
ruler_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(away), press], false);
assert_eq!(stop_guide(&app, &ctx), None, "a press after a lost release");
release_on_ruler(&ctx, &mut app, away, egui::Modifiers::NONE);
assert_eq!(positions(&app), [30.0]);
// The panel closed during a drag.
hold_drag_on_ruler(&ctx, &mut app, 30.0, 60.0, 0.0, egui::Modifiers::NONE);
assert!(stop_guide(&app, &ctx).is_some());
for _ in 0..2 {
let mut out = ctx.run_ui(egui::RawInput::default(), |_| {});
out.textures_delta.clear();
}
assert_eq!(stop_guide(&app, &ctx), None, "the panel is no longer drawn");
}
/// The guide turns with rotated area type, and runs through point type from the type's origin
/// across its lines; in vertical type it runs across the columns.
#[test]
fn the_stop_guide_follows_rotated_point_and_vertical_type() {
let ctx = egui::Context::default();
// Rotated area type: the guide is the frame's edge moved 70 pt along the frame's top.
let mut app = guide_app(&[50.0]);
app.run("object.rotate", json!({"angle": 30})).unwrap();
let node = current(&app).unwrap().0;
let NodeKind::Text(t) = &node.kind else { panic!("text") };
let TextKind::Area { frame } = &t.kind else { panic!("area type") };
let local = frame.bounds().unwrap();
let end = hold_drag_on_ruler(&ctx, &mut app, 50.0, 70.0, 0.0, egui::Modifiers::NONE);
let (a, b) = stop_guide(&app, &ctx).unwrap();
let (ea, eb) = (t.xf * Point::new(local.x0 + 70.0, local.y0), t.xf * Point::new(local.x0 + 70.0, local.y1));
assert!(near(a, ea) && near(b, eb), "{a:?} {b:?}, expected {ea:?} {eb:?}");
assert!((a.x - b.x).abs() > 10.0, "not upright: {a:?} {b:?}");
release_on_ruler(&ctx, &mut app, end, egui::Modifiers::NONE);
// Point type with its origin at (10, 20): the guide is upright at 10 + 70 and crosses the baseline.
for vertical in [false, true] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({})).unwrap();
app.run("text.create", json!({"x": 10, "y": 20, "text": "a\tb", "vertical": vertical})).unwrap();
app.run("text.tabs.set", json!({"stops": [{"position": 50}]})).unwrap();
let ctx = egui::Context::default();
let end = hold_drag_on_ruler(&ctx, &mut app, 50.0, 70.0, 0.0, egui::Modifiers::NONE);
let (a, b) = stop_guide(&app, &ctx).unwrap_or_else(|| panic!("a guide, vertical {vertical}"));
let NodeKind::Text(t) = ¤t(&app).unwrap().0.kind else { panic!("text") };
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let at = t.xf * lay.physical_point(Point::new(70.0, 0.0));
if vertical {
assert!((a.y - at.y).abs() < 0.01 && (b.y - at.y).abs() < 0.01, "across the column: {a:?} {b:?}, {at:?}");
assert!((a.x - b.x).abs() > 1.0, "{a:?} {b:?}");
} else {
assert!((a.x - 80.0).abs() < 0.01 && (b.x - 80.0).abs() < 0.01, "{a:?} {b:?}");
assert!(a.y < 19.0 && b.y > 20.0, "across the baseline: {a:?} {b:?}");
}
release_on_ruler(&ctx, &mut app, end, egui::Modifiers::NONE);
assert_eq!(stop_guide(&app, &ctx), None);
}
}
/// A stop placed by a click on the ruler or dragged on it lands on the nearest whole point, and
/// the moved stop stays selected. A position typed in the X field keeps its hundredths of a point.
#[test]
fn the_ruler_places_and_moves_stops_on_whole_points() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 50}]})).unwrap();
let ctx = egui::Context::default();
let positions = |app: &VectorcraftApp| current(app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>();
// A click at 33.4 pt adds a stop at 33 pt and selects it.
drag_on_ruler(&ctx, &mut app, 33.4, 33.4, false);
assert_eq!(positions(&app), [33.0, 50.0]);
assert_eq!(pstate::<usize>(&ctx, "tabs-sel"), 0);
// The stop at 50 pt dragged to 13.6 pt lands on 14 pt, left of the stop at 33 pt, and stays selected.
drag_on_ruler(&ctx, &mut app, 50.0, 13.6, false);
assert_eq!(positions(&app), [14.0, 33.0]);
assert_eq!(pstate::<usize>(&ctx, "tabs-sel"), 0);
// 13.47 typed in the X field keeps its hundredths.
let texts = panel_frame(&ctx, &mut app, vec![]);
let at = texts.iter().find(|(t, _)| t == "14 pt").unwrap_or_else(|| panic!("14 pt in {texts:?}")).1.center();
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
panel_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(at), button(true)]);
panel_frame(&ctx, &mut app, vec![button(false)]);
panel_frame(&ctx, &mut app, vec![key(egui::Key::A, egui::Modifiers::COMMAND)]);
panel_frame(&ctx, &mut app, vec![egui::Event::Text("13.47".into())]);
panel_frame(&ctx, &mut app, vec![key(egui::Key::Enter, egui::Modifiers::NONE)]);
assert_eq!(positions(&app), [13.47, 33.0]);
assert_eq!(pstate::<usize>(&ctx, "tabs-sel"), 0);
}
/// An X typed past the next stop keeps the stop selected once the stops are sorted. An X the
/// stops cannot take (past 100,000 pt) leaves the stops and the selection as they were.
#[test]
fn an_x_typed_past_the_next_stop_keeps_the_stop_selected() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 30}, {"position": 50}]})).unwrap();
let ctx = egui::Context::default();
let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
// Click the X field showing `shown`, type `typed` over it and press Enter โ the texts painted next.
let type_x = |app: &mut VectorcraftApp, shown: &str, typed: &str| {
let texts = panel_frame(&ctx, app, vec![]);
let at = texts.iter().find(|(t, _)| t == shown).unwrap_or_else(|| panic!("{shown} in {texts:?}")).1.center();
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
panel_frame(&ctx, app, vec![egui::Event::PointerMoved(at), button(true)]);
panel_frame(&ctx, app, vec![button(false)]);
panel_frame(&ctx, app, vec![key(egui::Key::A, egui::Modifiers::COMMAND)]);
panel_frame(&ctx, app, vec![egui::Event::Text(typed.into())]);
panel_frame(&ctx, app, vec![key(egui::Key::Enter, egui::Modifiers::NONE)]);
panel_frame(&ctx, app, vec![])
};
let positions = |app: &VectorcraftApp| current(app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>();
set_pstate(&ctx, "tabs-sel", 0usize);
let texts = type_x(&mut app, "30 pt", "70");
assert_eq!(positions(&app), [50.0, 70.0]);
assert_eq!(pstate::<usize>(&ctx, "tabs-sel"), 1);
assert!(texts.iter().any(|(t, _)| t == "70 pt"), "70 pt in {texts:?}");
set_pstate(&ctx, "tabs-sel", 0usize);
let texts = type_x(&mut app, "50 pt", "200000");
assert_eq!(positions(&app), [50.0, 70.0]);
assert_eq!(pstate::<usize>(&ctx, "tabs-sel"), 0);
assert!(texts.iter().any(|(t, _)| t == "50 pt"), "50 pt in {texts:?}");
// An X less than 1e-6 pt above another stop merges the two into the stop already there,
// which is selected.
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 30}, {"position": 50}, {"position": 70}]})).unwrap();
set_pstate(&ctx, "tabs-sel", 0usize);
type_x(&mut app, "30 pt", "50.0000001");
assert_eq!(positions(&app), [50.0, 70.0]);
assert_eq!(pstate::<usize>(&ctx, "tabs-sel"), 0);
}
/// One frame of the panel with `events` โ the stops' stems on the ruler, left to right, with
/// their colors.
fn stems_frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> Vec<(f32, egui::Color32)> {
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(400.0, 400.0));
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
out.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::LineSegment { points: [a, b], stroke } if stroke.width == 1.5 && a.x == b.x => Some((a.x, stroke.color)),
_ => None,
})
.collect()
}
/// In the frame where Enter commits an X the stops cannot take (past 100,000 pt), the ruler
/// shows the stops and the selected stop as they were.
#[test]
fn a_refused_x_leaves_the_ruler_as_it_was() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 30}, {"position": 50}]})).unwrap();
let ctx = egui::Context::default();
set_pstate(&ctx, "tabs-sel", 1usize);
let before = stems_frame(&ctx, &mut app, vec![]);
assert_eq!(before.len(), 2, "{before:?}");
let texts = panel_frame(&ctx, &mut app, vec![]);
let at = texts.iter().find(|(t, _)| t == "50 pt").unwrap_or_else(|| panic!("50 pt in {texts:?}")).1.center();
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers };
panel_frame(&ctx, &mut app, vec![egui::Event::PointerMoved(at), button(true)]);
panel_frame(&ctx, &mut app, vec![button(false)]);
panel_frame(&ctx, &mut app, vec![key(egui::Key::A, egui::Modifiers::COMMAND)]);
panel_frame(&ctx, &mut app, vec![egui::Event::Text("200000".into())]);
let committed = stems_frame(&ctx, &mut app, vec![key(egui::Key::Enter, egui::Modifiers::NONE)]);
assert_eq!(current(&app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>(), [30.0, 50.0]);
assert_eq!(pstate::<usize>(&ctx, "tabs-sel"), 1);
assert_eq!(committed, before);
}
/// One frame of the panel menu with `events` โ the rows' texts and where they are painted.
fn menu_frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> Vec<(String, egui::Rect)> {
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 400.0));
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| menu(app, ui));
out.textures_delta.clear();
out.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::Text(t) => Some((t.galley.text().to_string(), t.visual_bounding_rect())),
_ => None,
})
.collect()
}
/// Click the panel menu's row `label`, which shows no check mark.
fn choose(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str) {
let rows = menu_frame(ctx, app, vec![]);
let (text, r) = rows.iter().find(|(t, _)| t.trim_start_matches(['โ', ' ']) == label).unwrap_or_else(|| panic!("{label} in {rows:?}"));
assert!(!text.contains('โ'), "{label} shows a check mark");
let at = r.center();
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
menu_frame(ctx, app, vec![egui::Event::PointerMoved(at), button(true)]);
menu_frame(ctx, app, vec![button(false)]);
}
/// The panel menu's Repeat Tab, Delete Tab and Clear All Tabs can be chosen while the text has
/// tab stops and show no check mark. Repeat Tab and Delete Tab act on the stop selected on the
/// ruler, and Clear All Tabs removes every stop.
#[test]
fn panel_menu_repeats_deletes_and_clears_tab_stops() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 30}, {"position": 50, "leader": "."}]})).unwrap();
let ctx = egui::Context::default();
let positions = |app: &VectorcraftApp| current(app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>();
// Repeat Tab with the second stop selected: 20 copies of it, 20 pt apart (its distance from
// the first stop), leader and all.
set_pstate(&ctx, "tabs-sel", 1usize);
choose(&ctx, &mut app, "Repeat Tab");
let repeated = positions(&app);
assert_eq!((repeated.len(), &repeated[..4]), (22, &[30.0, 50.0, 70.0, 90.0][..]));
assert!(current(&app).unwrap().1[2..].iter().all(|s| s.leader == "."));
// Delete Tab removes the selected stop.
choose(&ctx, &mut app, "Delete Tab");
assert_eq!(positions(&app)[..3], [30.0, 70.0, 90.0]);
// Clear All Tabs removes every stop, in one undo step of its own name.
choose(&ctx, &mut app, "Clear All Tabs");
assert!(positions(&app).is_empty());
assert_eq!(app.session.active().unwrap().history.undo.last().unwrap().label, "Clear All Tabs");
app.run("edit.undo", json!({})).unwrap();
assert_eq!(positions(&app).len(), 21);
}
#[test]
fn panel_menu_does_not_change_stops_while_an_indent_marker_is_selected() {
let mut app = indent_app(24.0, 12.0);
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 50}, {"position": 70}]})).unwrap();
let ctx = egui::Context::default();
set_pstate(&ctx, "tabs-sel", 1usize);
marker_event(&ctx, &mut app, 36.0, 36.0, true, false, false);
assert_eq!(pstate::<Option<IndentMarker>>(&ctx, "tabs-marker-sel"), Some(IndentMarker::Upper));
let before = current(&app).unwrap().1;
choose(&ctx, &mut app, "Repeat Tab");
assert_eq!(current(&app).unwrap().1, before);
choose(&ctx, &mut app, "Delete Tab");
assert_eq!(current(&app).unwrap().1, before);
}
/// With 256 stops, a click on an empty part of the ruler adds none and shows the limit in the
/// status bar. Repeat Tab near the end of the list adds copies only up to 256 stops and shows the
/// limit too.
#[test]
fn the_ruler_and_repeat_tab_stop_at_256_stops() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
// 250 stops 1 pt apart from 0 pt, then six 2 pt apart from 260 pt.
let start: Vec<f64> = (0..250).map(f64::from).chain((0..6).map(|i| 260.0 + 2.0 * f64::from(i))).collect();
let stops: Vec<Value> = start.iter().map(|p| json!({"position": p})).collect();
app.session.execute("text.tabs.set", &json!({ "stops": stops })).unwrap();
let ctx = egui::Context::default();
let positions = |app: &VectorcraftApp| current(app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>();
set_pstate(&ctx, "tabs-sel", 3usize);
drag_on_ruler(&ctx, &mut app, 290.0, 290.0, false);
assert_eq!(positions(&app), start);
assert_eq!(pstate::<usize>(&ctx, "tabs-sel"), 3);
assert_eq!(app.ui.status, "at most 256 tab stops");
// Repeat Tab on the stop at 260 pt (11 pt past the one before it): five copies, not 20.
app.status("");
set_pstate(&ctx, "tabs-sel", 250usize);
choose(&ctx, &mut app, "Repeat Tab");
let repeated = positions(&app);
assert_eq!(repeated.len(), 256);
assert_eq!(repeated[249..], [249.0, 260.0, 271.0, 282.0, 293.0, 304.0, 315.0]);
assert_eq!(app.ui.status, "at most 256 tab stops");
}
/// Repeat Tab on the first stop spaces the copies by the stop's distance from the paragraph's
/// left indent (18 pt further in for each list level past the first), from the paragraph the
/// caret is in while the Type tool edits text.
#[test]
fn repeat_tab_measures_the_first_stop_from_the_left_indent() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b\nc d", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.setFormat", &json!({"leftIndent": 20})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 50}]})).unwrap();
let ctx = egui::Context::default();
let positions = |app: &VectorcraftApp| current(app).unwrap().1.iter().map(|s| s.position).collect::<Vec<_>>();
// 30 pt from the indent at 20: copies at 80, 110, ...
set_pstate(&ctx, "tabs-sel", 0usize);
choose(&ctx, &mut app, "Repeat Tab");
let repeated = positions(&app);
assert_eq!((repeated.len(), &repeated[..4]), (21, &[50.0, 80.0, 110.0, 140.0][..]));
// A stop left of the indent: 15 pt from the indent at 20.
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 5}]})).unwrap();
choose(&ctx, &mut app, "Repeat Tab");
assert_eq!(positions(&app)[..4], [5.0, 20.0, 35.0, 50.0]);
// A list paragraph at level 2 is set 18 pt further in, at 38: copies every 12 pt.
app.session.execute("text.setFormat", &json!({"list": "bullet", "listLevel": 2})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 50}]})).unwrap();
choose(&ctx, &mut app, "Repeat Tab");
assert_eq!(positions(&app)[..3], [50.0, 62.0, 74.0]);
// The Type tool's caret in the second paragraph, indented 40 pt: its stop at 50 repeats
// every 10 pt, and the first paragraph keeps its stop.
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({})).unwrap();
app.session.select_tool("type", Default::default()).unwrap();
let id = app.run("text.create", json!({"x": 10, "y": 20, "text": "a b\nc d"})).unwrap()["id"].clone();
app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap();
app.run("text.setFormat", json!({"id": id, "leftIndent": 20})).unwrap();
app.run("text.setFormat", json!({"id": id, "start": 4, "end": 7, "leftIndent": 40})).unwrap();
app.run("text.tabs.set", json!({"id": id, "stops": [{"position": 50}]})).unwrap();
app.session.set_tool_option("select", &json!({"start": 5, "end": 5}));
choose(&ctx, &mut app, "Repeat Tab");
assert_eq!(positions(&app)[..3], [50.0, 60.0, 70.0]);
app.session.set_tool_option("select", &json!({"start": 0, "end": 0}));
assert_eq!(positions(&app), [50.0]);
}
/// After Delete Tab removes the last stop, the ruler shows the stop before it selected, and
/// Delete Tab removes that one next.
#[test]
fn delete_tab_after_the_last_stop_deletes_the_stop_the_ruler_shows_selected() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({})).unwrap();
app.session.execute("text.create", &json!({"x": 10, "y": 20, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.session.execute("text.tabs.set", &json!({"stops": [{"position": 30}, {"position": 50}]})).unwrap();
let ctx = egui::Context::default();
set_pstate(&ctx, "tabs-sel", 1usize);
choose(&ctx, &mut app, "Delete Tab");
assert_eq!(current(&app).unwrap().1.len(), 1);
choose(&ctx, &mut app, "Delete Tab");
assert!(current(&app).unwrap().1.is_empty());
}
/// Position Panel Above Text on text narrower than a floating panel can be at the zoom: the panel
/// comes out wider than asked, and its ruler draws the text at the zoom, running on past the text,
/// so its marks stay over the text. A ruler wider than the narrowest panel, for other text or in
/// another document fits the span to its width as before.
#[test]
fn above_text_keeps_the_zoom_on_a_ruler_wider_than_asked() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
app.session.execute("text.create", &json!({"x": 40, "y": 200, "text": "a b", "area": {"width": 100, "height": 100}})).unwrap();
app.canvas_rect = Some(egui::Rect::from_min_size(egui::pos2(50.0, 40.0), vec2(1000.0, 700.0)));
if let Some(v) = app.view_mut() {
v.zoom = 0.5;
}
let ctx = egui::Context::default();
let (node, _, span) = current(&app).unwrap();
place_above_text(&mut app, &ctx, &node, span);
// The panel asked for: a 50 pt ruler, less than the narrowest panel's.
let asked = app.ui.docking.clone().unwrap().floating.iter().find(|w| w.contains(&"tabs".to_string())).unwrap().rect[2];
assert!((asked - RULER_LEFT * 2.0 - 50.0).abs() < 0.01, "{asked}");
// Screen points per point of text on a ruler `width` wide, from its first two labels.
let scale = |app: &mut VectorcraftApp, width: f32| {
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(width, 400.0));
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| show(app, ui));
out.textures_delta.clear();
let labels: Vec<(f64, f32)> = out
.shapes
.iter()
.filter_map(|c| match &c.shape {
egui::Shape::Text(t) if t.galley.job.sections.first().is_some_and(|s| s.format.font_id.size == 9.0) => {
Some((t.galley.text().parse::<f64>().ok()?, t.pos.x))
}
_ => None,
})
.collect();
let [(0.0, a), (next, b), ..] = labels[..] else { panic!("ruler labels {labels:?}") };
(b - a) as f64 / next
};
let narrowest = crate::panel_docking::PANEL_MIN_WIDTH;
let fitted = (f64::from(narrowest) - 8.0) / span;
let at_zoom = scale(&mut app, narrowest);
assert!((at_zoom - 0.5).abs() < 1e-3, "{at_zoom}");
let other =
app.session.execute("text.create", &json!({"x": 300, "y": 200, "text": "c", "area": {"width": 100, "height": 100}})).unwrap()["id"].clone();
app.session.execute("select.set", &json!({"ids": [other]})).unwrap();
assert!((scale(&mut app, narrowest) - fitted).abs() < 1e-3, "other text fits its span to the ruler");
app.session.execute("select.set", &json!({"ids": [node.id.0]})).unwrap();
assert!((scale(&mut app, narrowest) - 0.5).abs() < 1e-3);
// At another zoom the ruler follows it.
if let Some(v) = app.view_mut() {
v.zoom = 2.0;
}
assert!((scale(&mut app, narrowest) - 2.0).abs() < 1e-3, "another zoom");
if let Some(v) = app.view_mut() {
v.zoom = 0.5;
}
app.session.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
app.session.execute("text.create", &json!({"x": 40, "y": 200, "text": "d", "area": {"width": 100, "height": 100}})).unwrap();
if let Some(v) = app.view_mut() {
v.zoom = 0.5;
}
assert!((scale(&mut app, narrowest) - fitted).abs() < 1e-3, "another document");
assert!(app.session.set_active(0));
assert!((scale(&mut app, narrowest) - 0.5).abs() < 1e-3);
// The panel made wider than the narrowest floating window fits the span to its ruler again.
let docking = app.ui.docking.as_mut().unwrap();
docking.floating.iter_mut().find(|w| w.contains(&"tabs".to_string())).unwrap().rect[2] = 400.0;
let wide = scale(&mut app, 400.0);
assert!((wide - (400.0 - 8.0) / span).abs() < 1e-3, "{wide}");
}
/// Position Panel Above Text floats the panel over the text, its ruler's 0 on the frame's left
/// edge and a stop's mark over the column it sets, at any zoom (#729).
#[test]
fn above_text_puts_the_ruler_over_the_text_at_the_zoom() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
app.session.execute("text.create", &json!({"x": 40, "y": 200, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
// The canvas starts low enough in the window for the panel to fit above the text at 200%.
app.canvas_rect = Some(egui::Rect::from_min_size(egui::pos2(50.0, 440.0), vec2(1000.0, 700.0)));
for zoom in [1.0, 2.0] {
if let Some(v) = app.view_mut() {
v.zoom = zoom;
}
let (node, _, span) = current(&app).unwrap();
let ctx = egui::Context::default();
above_text(&mut app, &ctx, &node, span).unwrap();
let layout = app.ui.docking.clone().unwrap();
let g = layout.floating.iter().find(|w| w.contains(&"tabs".to_string())).unwrap();
let xf = crate::canvas::Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
let frame = xf.rect_to_screen(node.geometric_bounds().unwrap());
assert!((g.rect[0] + RULER_LEFT - frame.left()).abs() < 0.01, "0 on the frame's left edge");
assert!(g.rect[1] < frame.top(), "above the text");
// The ruler (the panel less its margins) spans the frame at this zoom.
let ruler = g.rect[2] - RULER_LEFT * 2.0;
assert!((ruler - frame.width()).abs() < 0.01, "{ruler} {}", frame.width());
assert!((ruler - 300.0 * zoom as f32).abs() < 0.01);
}
assert_eq!(app.ui.docking.unwrap().floating.len(), 1, "placed again, not floated twice");
}
/// Position Panel Above Text moves the panel when it already floats in an OS window of its own:
/// the window's desktop rect goes above the text too, from the main window's top-left (#4995).
#[test]
fn above_text_moves_a_panel_floating_in_its_own_window() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
app.session.execute("text.create", &json!({"x": 40, "y": 200, "text": "a b", "area": {"width": 300, "height": 100}})).unwrap();
app.canvas_rect = Some(egui::Rect::from_min_size(egui::pos2(50.0, 40.0), vec2(1000.0, 700.0)));
if let Some(v) = app.view_mut() {
v.zoom = 1.0;
}
let (node, _, span) = current(&app).unwrap();
let ctx = egui::Context::default();
above_text(&mut app, &ctx, &node, span).unwrap();
// The panel's OS window sits elsewhere on the desktop, as after the user dragged it there.
let mut layout = app.ui.docking.clone().unwrap();
let window = layout.floating.iter_mut().find(|w| w.contains(&"tabs".to_string())).unwrap();
window.native = Some([1500.0, 900.0, window.rect[2], window.rect[3]]);
app.ui.docking = Some(layout);
// The main window's content starts at (200, 100) on the desktop.
let mut raw = egui::RawInput::default();
raw.viewports.entry(egui::ViewportId::ROOT).or_default().inner_rect =
Some(egui::Rect::from_min_size(egui::pos2(200.0, 100.0), vec2(1200.0, 800.0)));
ctx.run_ui(raw, |_| {}).textures_delta.clear();
above_text(&mut app, &ctx, &node, span).unwrap();
let layout = app.ui.docking.clone().unwrap();
let g = layout.floating.iter().find(|w| w.contains(&"tabs".to_string())).unwrap();
let native = g.native.unwrap();
assert_eq!([native[0], native[1]], [200.0 + g.rect[0], 100.0 + g.rect[1]], "the OS window goes above the text");
assert_eq!([native[2], native[3]], [g.rect[2], g.rect[3]]);
}
/// Text near the top of the window: Position Panel Above Text puts the panel just below the text,
/// so neither the panel nor its OS window goes above the screen and the text stays in view. Text
/// with no room below it either gets the panel at the window's top.
#[test]
fn above_text_keeps_the_panel_bar_in_the_window() {
for (text_height, below) in [(100.0, true), (760.0, false)] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 600, "height": 400})).unwrap();
app.session.execute("text.create", &json!({"x": 40, "y": 10, "text": "a b", "area": {"width": 300, "height": text_height}})).unwrap();
app.canvas_rect = Some(egui::Rect::from_min_size(egui::pos2(50.0, 40.0), vec2(1000.0, 700.0)));
if let Some(v) = app.view_mut() {
v.zoom = 1.0;
}
let (node, _, span) = current(&app).unwrap();
let xf = crate::canvas::Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
let frame = xf.rect_to_screen(node.geometric_bounds().unwrap());
assert!(frame.top() < 240.0, "no room above the text");
let ctx = egui::Context::default();
above_text(&mut app, &ctx, &node, span).unwrap();
let mut layout = app.ui.docking.clone().unwrap();
let window = layout.floating.iter_mut().find(|w| w.contains(&"tabs".to_string())).unwrap();
let top = if below { frame.bottom() + 6.0 } else { 0.0 };
assert_eq!(window.rect[1], top, "text {text_height} high");
window.native = Some([1500.0, 900.0, window.rect[2], window.rect[3]]);
app.ui.docking = Some(layout);
let mut raw = egui::RawInput::default();
raw.viewports.entry(egui::ViewportId::ROOT).or_default().inner_rect =
Some(egui::Rect::from_min_size(egui::pos2(200.0, 100.0), vec2(1200.0, 800.0)));
ctx.run_ui(raw, |_| {}).textures_delta.clear();
above_text(&mut app, &ctx, &node, span).unwrap();
let layout = app.ui.docking.clone().unwrap();
let g = layout.floating.iter().find(|w| w.contains(&"tabs".to_string())).unwrap();
assert_eq!(g.native.unwrap()[1], 100.0 + top, "text {text_height} high: the OS window");
}
}
/// Position Panel Above Text puts the panel at the window's top when the place below the text is
/// above the window (text panned above the canvas), or when the panel at the height it floats at
/// does not fit below the text in the canvas.
#[test]
fn above_text_puts_the_panel_at_the_top_when_below_the_text_does_not_fit() {
// The view's centre and the text's height: panned so the text is above the canvas, and a text
// whose bottom leaves room for 240 points of panel but not for the 360 it floats at.
for (center_y, text_height) in [(600.0, 100.0), (350.0, 340.0)] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 600, "height": 800})).unwrap();
app.session.execute("text.create", &json!({"x": 40, "y": 20, "text": "a b", "area": {"width": 300, "height": text_height}})).unwrap();
app.canvas_rect = Some(egui::Rect::from_min_size(egui::pos2(50.0, 40.0), vec2(1000.0, 700.0)));
if let Some(v) = app.view_mut() {
v.zoom = 1.0;
v.center = vectorcraft_geom::Point::new(300.0, center_y);
}
let (node, _, span) = current(&app).unwrap();
let ctx = egui::Context::default();
above_text(&mut app, &ctx, &node, span).unwrap();
let layout = app.ui.docking.clone().unwrap();
let g = layout.floating.iter().find(|w| w.contains(&"tabs".to_string())).unwrap();
assert_eq!(g.rect[1], 0.0, "view centered at y {center_y}");
}
}
No file is open. Choose one in the tree, or press Ctrl+O (โO on a Mac) to find one by name.
Syntax highlighting could not load. The unmodified read-only text remains available above.