Merge main into fix/frame-taskbar-neighbor-monitor

This commit is contained in:
dotCooCoo committed 2026-12-05 03:31:42 -08:00
commit f5a11b9bba
31 files changed
+338 -63

No files matched your search

+8 -6
View File
@@ -308,10 +308,12 @@ fn reads_editing_copy(opts: &LoadOptions) -> bool {
/// May a file opened with `opts` open from the editor's own copy of its art without its PDF part
/// being imported ([`vectorcraft_eps::ai_layers_alone`]): it reads the editor's copy, on the pages'
/// trim boxes (the crop box asked for, as a file with the editor's copy opens on them), with its
/// type as text?
/// trim boxes by default, with its type as text?
fn reads_layers_alone(opts: &LoadOptions) -> bool {
reads_editing_copy(opts) && opts.crop == vectorcraft_pdf::CropTo::Crop && opts.text_as != vectorcraft_pdf::TextAs::Outlines
reads_editing_copy(opts)
&& !opts.explicit_crop_box
&& opts.crop == vectorcraft_pdf::CropTo::Crop
&& opts.text_as != vectorcraft_pdf::TextAs::Outlines
}
/// The editor's own copy of its art that `opened` carries, decoded ([`decoded_copy`]), when `opts`
@@ -475,8 +477,8 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
// The file is read and checked once, for the document it carries, its pages, the
// editor's copy and its File Info.
let opened = vectorcraft_pdf::open_pdf(bytes, opts.password.as_deref());
// Saved with Preserve Editing: the document it carries, unless some pages are picked.
let editing = (opts.pages.is_none() && opts.native)
// Restore the preserved document when opening all pages at their original size.
let editing = (opts.pages.is_none() && opts.native && !opts.explicit_crop_box)
.then(|| opened.as_ref().ok().and_then(|o| o.editing()))
.flatten()
.map(|e| (e.intact, move || Some(e.data)));
@@ -524,7 +526,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
}
None => None,
};
let alone = (r.only_text || empty)
let alone = (!opts.explicit_crop_box && (r.only_text || empty))
.then(copy_alone)
.flatten()
.and_then(|read| read.ok())
+7 -1
View File
@@ -173,7 +173,13 @@ impl LoadOptions {
/// box, a password, without its hidden layers, without the VectorCraft document it carries, its
/// pages linked)? Writing it back would lose the rest, so Save doesn't (it asks for a name).
pub fn is_partial(&self) -> bool {
self.pages.is_some() || self.crop != CropTo::default() || self.password.is_some() || !self.layers || !self.native || self.link_pages
self.pages.is_some()
|| self.crop != CropTo::default()
|| self.explicit_crop_box
|| self.password.is_some()
|| !self.layers
|| !self.native
|| self.link_pages
}
/// The PDF import options: `pages` resolved against the file's page count. A PDF or PDF-compatible
@@ -1395,8 +1395,7 @@ fn link_pages_refuses_an_ai_file_saved_without_its_pdf_part() {
let _ = std::fs::remove_dir_all(&d);
}
/// `document.open` with `linkPages` opens a PDF-compatible `.ai` asked for its crop box on its trim
/// box, as it opens as art, showing its bleed box round the artboard, which is the document's bleed.
/// Linked pages default to the trim box with the bleed and honor an explicit Crop Box.
#[test]
fn link_pages_open_an_ai_file_on_its_trim_box_with_its_bleed() {
let d = std::env::temp_dir().join(format!("vc-ailinkpagestrim-{}", std::process::id()));
@@ -1416,6 +1415,13 @@ fn link_pages_open_an_ai_file_on_its_trim_box_with_its_bleed() {
let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("{:?}", placed.kind) };
assert_eq!((p.width, p.height, p.page_box), (192.0, 96.0, vectorcraft_doc::PageBox::Bleed));
assert_eq!(p.xf.translation(), vectorcraft_geom::Vec2::new(-6.0, -8.0), "the trim box on the artboard");
s.execute("document.open", &json!({"path": path, "linkPages": true, "cropTo": "crop"})).unwrap();
let cropped = &s.doc().unwrap().doc;
assert!(cropped.artboards[0].rect.width() > board.width());
let placed = &cropped.layers[0].children().unwrap()[0];
let NodeKind::PlacedDocument(p) = &placed.kind else { panic!("{:?}", placed.kind) };
assert_eq!(p.page_box, vectorcraft_doc::PageBox::Crop);
let _ = std::fs::remove_dir_all(&d);
}
+28 -1
View File
@@ -3,7 +3,7 @@
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, NodeKind};
use vectorcraft_geom::{FillRule, PathData, Rect};
use vectorcraft_geom::{FillRule, PathData, Point, Rect, SubPath};
use crate::*;
@@ -211,6 +211,33 @@ fn exclude_makes_compound() {
assert!((area_of(&s, r[0]) - 15000.0).abs() < 1.0);
}
#[test]
fn divide_over_work_budget_preserves_art_and_selection() {
let mut s = session();
let square = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
let line = s.execute("shape.line", &json!({"x1": -10, "y1": -10, "x2": 110, "y2": 110})).unwrap();
let cutter = NodeId(line["id"].as_u64().unwrap());
// The existing pathops work-budget fixture uses 1,500 overlapping lines.
// Put them in one open path so the setup only makes two document objects.
let line = SubPath::polyline(&[Point::new(-10.0, -10.0), Point::new(110.0, 110.0)], false);
s.edit("complex cutter", |d, _| {
let NodeKind::Path { path, .. } = &mut d.node_mut(cutter).unwrap().kind else { panic!("expected a path") };
*path = PathData::new(vec![line; 1_500]);
Ok(())
})
.unwrap();
s.execute("select.set", &json!({"ids": [square.0, cutter.0]})).unwrap();
let before = s.doc().unwrap().doc.clone();
let selection = s.doc().unwrap().selection.clone();
let undo = s.doc().unwrap().history.undo.len();
let error = s.execute("object.pathfinder.divide", &json!({})).unwrap_err().to_string();
assert!(error.contains("too many segments or pieces"), "{error}");
let state = s.doc().unwrap();
assert!(std::sync::Arc::ptr_eq(&state.doc, &before), "the original document must be restored");
assert_eq!(state.selection, selection);
assert_eq!(state.history.undo.len(), undo);
}
#[test]
fn divide_produces_group_of_faces() {
let mut s = session();
+1 -1
View File
@@ -19,7 +19,7 @@ fn folder(name: &str) -> PathBuf {
let base = std::env::temp_dir().join(format!("vc-script-io-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
std::fs::create_dir_all(base.join("main")).unwrap();
std::fs::canonicalize(&base).unwrap()
crate::cmd::findfiles::plain(std::fs::canonicalize(&base).unwrap())
}
fn write(path: &Path, bytes: &[u8]) {
+1 -1
View File
@@ -57,7 +57,7 @@ impl AsRef<Path> for Folder {
/// A fresh folder for test `name`, with a `main` folder inside it for the script, by its real path.
fn folder(name: &str) -> Folder {
let guard = vectorcraft_testkit::TempDir::new(&format!("script-xmp-{name}"));
let base = std::fs::canonicalize(&*guard).unwrap();
let base = crate::cmd::findfiles::plain(std::fs::canonicalize(&*guard).unwrap());
std::fs::create_dir_all(base.join("main")).unwrap();
Folder { _guard: guard, path: base }
}
+1 -1
View File
@@ -171,7 +171,7 @@ mod tests {
(TYPE, &["editing"]),
(&["puppetWarp"], &["pins", "selected"]),
// With nothing queued, `current` (0) is no file's index either.
(&["place"], &["count", "current", "sourceIndex", "name", "width", "height", "names"]),
(&["place"], &["count", "total", "current", "sourceIndex", "name", "width", "height", "names"]),
];
let read_only = |id: &str, k: &str| READ_ONLY.iter().any(|(ids, keys)| ids.contains(&id) && keys.contains(&k));
// Tools that `create` makes and the catalog doesn't list.
+32 -1
View File
@@ -32,6 +32,8 @@ struct Entry {
#[derive(Default)]
pub struct PlaceTool {
entries: Vec<Entry>,
/// How many files the last load held, before any was placed or discarded.
total: usize,
current: usize,
/// The tool to return to when the last file is placed or discarded.
prev: Option<String>,
@@ -67,6 +69,7 @@ impl PlaceTool {
}
if self.entries.is_empty() {
self.current = 0;
self.total = 0;
return vec![Action::SwitchTool(self.prev.clone().unwrap_or_else(|| "selection".into()))];
}
self.current %= self.entries.len();
@@ -153,11 +156,13 @@ impl Tool for PlaceTool {
Cursor::Crosshair
}
/// `{count, current, sourceIndex, name, width, height, names}`: what the cursor holds (no file data).
/// `{count, total, current, sourceIndex, name, width, height, names}`: what the cursor holds (no file data);
/// `total` is how many files the load held.
fn options(&self) -> Value {
let e = self.entry();
json!({
"count": self.entries.len(),
"total": self.total,
"current": self.current,
"sourceIndex": e.map(|e| e.source_index),
"name": e.map(|e| &e.name),
@@ -187,6 +192,7 @@ impl Tool for PlaceTool {
})
})
.collect();
self.total = entries.len();
self.entries = entries;
self.current = 0;
self.drag = None;
@@ -233,6 +239,7 @@ impl Tool for PlaceTool {
/// Switching tools discards what the cursor holds.
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
self.entries.clear();
self.total = 0;
self.drag = None;
vec![]
}
@@ -399,6 +406,30 @@ mod tests {
assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::SwitchTool("pen".into())]);
}
#[test]
fn the_total_is_the_size_of_the_load_until_the_cursor_empties() {
let (d, _) = doc_with_rect();
let (s, p) = (Default::default(), paint());
let c = cx(&d, &s, &p);
let counts = |t: &PlaceTool| (t.options()["count"].clone(), t.options()["total"].clone());
let mut t = loaded(3);
assert_eq!(counts(&t), (json!(3), json!(3)));
t.pointer(&c, &ev(PointerKind::Down, 0.0, 0.0));
t.pointer(&c, &ev(PointerKind::Up, 0.0, 0.0));
assert_eq!(counts(&t), (json!(2), json!(3)), "a placed file leaves the total");
t.key(&c, ToolKey::Escape, Mods::default());
assert_eq!(counts(&t), (json!(1), json!(3)), "a discarded file leaves the total");
// A new load replaces the total, and an empty cursor has none.
let mut t = loaded(3);
t.set_option("queue", &json!({"entries": [{"params": {"path": "g.png"}, "name": "g.png", "width": 4.0, "height": 2.0}]}));
assert_eq!(counts(&t), (json!(1), json!(1)));
t.key(&c, ToolKey::Escape, Mods::default());
assert_eq!(counts(&t), (json!(0), json!(0)));
let mut t = loaded(2);
t.deactivate(&c);
assert_eq!(counts(&t), (json!(0), json!(0)));
}
#[test]
fn source_indices_survive_removal_in_cursor_requests() {
let (d, _) = doc_with_rect();
@@ -134,7 +134,7 @@ mod tests {
let undo = panel.app().session.active().unwrap().history.undo.len();
panel.click_role(label, Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text(typed);
panel.type_text(&crate::tests::regional_text(typed));
panel.frame();
let proposed = panel.app().session.tool_options_of(tool);
assert_ne!(proposed[key], before[key], "{label} changes while typing");
+1 -1
View File
@@ -663,7 +663,7 @@ mod cancel_tests {
panel.frame();
panel.click_role("TL", Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text("4.125");
panel.type_text(&crate::tests::regional_text("4.125"));
panel.frame();
let proposed = panel.app().session.tool_options();
assert_ne!(proposed["cornerRadii"], before["cornerRadii"]);
+2 -1
View File
@@ -11,7 +11,8 @@ pub(crate) fn navigation(p: &Prefs) -> NavigationOptions {
let mut options = NavigationOptions::default();
options.wheel = if p.zoom_with_mouse_wheel { WheelScheme::Zoom } else { WheelScheme::Scroll };
options.animated_zoom = crate::canvas::animated_zoom(p);
options.scrubby_zoom = crate::canvas::animated_zoom(p);
options.eased_wheel_zoom = p.zoom_with_mouse_wheel && options.animated_zoom;
options.scrubby_zoom = options.animated_zoom;
options.trackpad_rotate = p.trackpad_rotate_view;
options.touch_gestures = p.touch_gestures;
options.overscroll = true;
+2 -2
View File
@@ -25,8 +25,8 @@ const TIP: PartKey = PartKey::new("tip");
const CHIP: f32 = 5.0;
const CHIP_RIM: f32 = 6.0;
const CHIP_RING: f32 = 8.0;
/// Where the Selection tool's rule badge sits from the pointer, in points.
const BADGE_OFFSET: Vec2 = Vec2::new(14.0, 14.0);
/// Where the Selection tool's rule badge and the loaded place cursor's file sit from the pointer, in points.
pub(super) const BADGE_OFFSET: Vec2 = Vec2::new(14.0, 14.0);
/// Shows `overlays` (the session's list, read after the tool host ran) over `extra` (the thread and gap overlays),
/// on the canvas of `space`. The extras lie under the tool's own marks.
+1 -1
View File
@@ -257,6 +257,6 @@ fn ruler_labels_carry_the_sign_and_the_steps_decimals() {
(1.0, 0.0625, "1"),
(1.1875, 0.0625, "1.1875"),
] {
assert_eq!(x.tick_label(&units, value, step), want, "the tick at {value} of a {step} step");
assert_eq!(x.tick_label(&units, value, step), crate::tests::regional_text(want), "the tick at {value} of a {step} step");
}
}
+14 -1
View File
@@ -866,7 +866,8 @@ fn host_run_session(tool: &mut SessionTool<'_>, ui: &Ui, pass: &ToolPass) -> Too
response
}
/// The session's overlays, then the text threads and Live Paint gaps under them, shown over the picture.
/// The session's overlays, then the text threads and Live Paint gaps under them, shown over the picture, and the
/// loaded place cursor's file over them.
fn show_overlays(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass, view_info: ViewInfo) {
let Some(space) = pass.space else { return };
let revolve = crate::dialogs::three_d::gizmo_shown(app);
@@ -892,6 +893,18 @@ fn show_overlays(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass, view_in
}
}
super::overlays::show(app, ui, &space, &list, &extra);
// The loaded place cursor shows its current file and the files left beside the pointer, while the canvas has the
// pointer and no view tool is held. A press that began on the canvas keeps `hover_doc` while it is dragged off it,
// so the pointer must also be over the canvas.
if app.session.tool_id() == "place"
&& app.ui.screen_mode < 3
&& app.hover_doc.is_some()
&& !view_tool_held(app)
&& let Some(at) = ui.input(|i| i.pointer.hover_pos())
&& space.view.rect.contains(at)
{
crate::place::cursor_overlay(app, ui, at, space.view.rect, super::overlays::BADGE_OFFSET);
}
}
/// Whether the canvas has a tool gesture in progress. Only the current window's body is live: panes and the other
@@ -825,7 +825,7 @@ mod tests {
assert_eq!(pending.size_choice, Some(ArtboardSizeChoice::Orientation(true)));
panel.click_role(label, Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text(typed);
panel.type_text(&crate::tests::regional_text(typed));
assert_eq!(actual_value(&panel), pending, "typing must not discard the pending orientation or reference-point policy");
panel.key(Key::Escape, Modifiers::NONE);
assert!(!is_open(&panel.app()), "Escape discards the modal for {label}");
@@ -875,7 +875,7 @@ mod tests {
panel.frame();
panel.click_role(label, Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text(typed);
panel.type_text(&crate::tests::regional_text(typed));
if blur {
panel.key(Key::Tab, Modifiers::NONE);
}
+21 -4
View File
@@ -381,16 +381,22 @@ fn two_pages(editing_data: bool, password: Option<&str>) -> Vec<u8> {
/// Two 100 pt pages and, on the first, editing data with two artboards to match and a layer of its
/// own, which draws the square the first page draws.
fn two_pages_with_a_layer_in_the_editing_data(layer: &str) -> Vec<u8> {
fn two_pages_with_a_layer_in_the_editing_data(layer: &str, with_trim_box: bool) -> Vec<u8> {
let point = |x: i32, y: i32, n: u8| format!("%_{x} {y} /RealPointRelToROrigin\n%_ (PositionPoint{n}) ,\n");
let board = |top: i32| format!("%_/Dictionary :\n{}{}%_; ,\n", point(0, top, 1), point(100, top - 100, 2));
let boards = format!("%_/Document :\n%_/Dictionary :\n%_/Array :\n{}{}%_; (ArtboardArray) ,\n%_; /NotRecorded ,\n%_;\n", board(100), board(-50));
let art = format!("0 0 0 1 k\n{}f\n", ai::rect(10.0, 10.0, 30.0, 30.0));
let data = ai::editing_data(100.0, 100.0, &format!("{boards}{}", ai::layer(layer, &art)));
let mut first = PdfPage::new(100.0, 100.0, "0 0 0 1 k 10 10 20 20 re f");
let page = |content| {
let edge = if with_trim_box { 120.0 } else { 100.0 };
let mut page = PdfPage::new(edge, edge, content);
page.trim = with_trim_box.then_some([10.0, 10.0, 110.0, 110.0]);
page
};
let mut first = page("0 0 0 1 k 10 10 20 20 re f");
first.entries = format!("/PieceInfo << /Illustrator << /Private << /AIPrivateData1 {} 0 R /NumBlock 1 >> >> >>", first_extra(2));
let stream = format!("<< /Length {} >>\nstream\n{data}\nendstream", data.len());
pdf_with(&[first, PdfPage::new(100.0, 100.0, "")], &[&stream], None)
pdf_with(&[first, page("")], &[&stream], None)
}
/// #6135: the editing data of a `.ai` holds every artboard, so opening one asks nothing, opens
@@ -398,7 +404,7 @@ fn two_pages_with_a_layer_in_the_editing_data(layer: &str) -> Vec<u8> {
#[test]
fn opening_an_ai_with_editing_data_reads_it_without_asking() {
let mut app = app();
let bytes = two_pages_with_a_layer_in_the_editing_data("Only in the editing data");
let bytes = two_pages_with_a_layer_in_the_editing_data("Only in the editing data", false);
io::open_bytes(&mut app, "two.ai", &bytes, Some("/tmp/two.ai".into())).unwrap();
assert!(!is_open(&app), "no Import PDF dialog");
assert_eq!(app.session.documents().len(), 2);
@@ -435,6 +441,17 @@ fn opening_a_pdf_with_editing_data_keeps_its_trim_boxes_unless_a_box_is_picked()
confirm(&mut app).unwrap();
assert_eq!(artboard_widths(&app), [100.0, 200.0], "an explicit crop box");
let bytes = two_pages_with_a_layer_in_the_editing_data("An editable layer", true);
let mut app = self::app();
assert!(import_pdf::offer(&mut app, "readable.pdf", &bytes, None, None));
confirm(&mut app).unwrap();
assert_eq!(artboard_widths(&app), [100.0, 100.0], "the trim boxes match the artboards in the editing data");
let mut app = self::app();
assert!(import_pdf::offer(&mut app, "readable.pdf", &bytes, None, None));
set(&mut app, "cropTo", json!("crop"));
confirm(&mut app).unwrap();
assert_eq!(artboard_widths(&app), [120.0, 120.0], "the crop boxes override the artboards in the editing data");
let mut app = self::app();
assert!(import_pdf::offer(&mut app, "locked.pdf", &trimmed(Some("pw")), None, None));
set(&mut app, "password", json!("pw"));
+2 -2
View File
@@ -131,7 +131,7 @@ mod tests {
for (label, text) in [("Value", typed), ("Variation:", variation)] {
panel.click_role(label, Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text(text);
panel.type_text(&crate::tests::regional_text(text));
panel.key(Key::Escape, Modifiers::NONE);
assert!(!panel.app().dialogs().unwrap().with(|host| host.is_open::<HostedParamDialog>()));
assert_eq!(panel.app().session.tool_options_of(tool), original, "the canceled {label} leaves the tool unchanged");
@@ -143,7 +143,7 @@ mod tests {
for (label, text) in [("Value", typed), ("Variation:", variation)] {
panel.click_role(label, Role::SPIN_BUTTON);
panel.key(Key::A, Modifiers::COMMAND);
panel.type_text(text);
panel.type_text(&crate::tests::regional_text(text));
panel.key(Key::Tab, Modifiers::NONE);
}
panel.click_role("Mode", Role::COMBO_BOX);
+6
View File
@@ -1076,6 +1076,12 @@ fn run(app: &mut VectorcraftApp, actions: Vec<Action<String>>, reveal: Option<St
if layout_of(&app.ui).opens_in_flyout(&panel) {
app.ui.open_panel = Some(panel);
} else {
// An open flyout is a popup layer of the main window, and palette windows stay hidden while one shows: a
// floating window revealed with a flyout open (a built-in workspace opens its panel's flyout) would open
// hidden, so the flyout closes.
if floating_window(layout_of(&app.ui), &panel).is_some() {
app.ui.open_panel = None;
}
app.dock_rt.raise = Some(panel);
}
}
@@ -601,6 +601,21 @@ fn a_panel_floated_in_any_built_in_workspace_opens_a_shown_window() {
}
}
/// Palette windows hide while the main window shows a popup, which an open flyout is: a built-in workspace opens its
/// panel's flyout, and a panel floated then closes it, so its window shows.
#[test]
fn floating_a_panel_closes_the_open_flyout_that_would_hide_its_window() {
let mut h = Harness::new();
h.app.run("window.workspace", json!({"name": "Essentials Classic"})).unwrap();
h.frames(3);
assert_eq!(h.app.ui.open_panel.as_deref(), Some("color"), "Essentials Classic opens its Color flyout");
h.app.run("window.panel.float", json!({"panel": "tools", "x": 200, "y": 200})).unwrap();
h.frames(6);
assert_eq!(h.app.ui.open_panel, None, "the flyout closed");
let viewport = h.viewport("tools");
assert!(h.host.borrow().windows[&viewport].visible, "the tools window shows");
}
/// A panel opened from the Window menu floats in an OS window that keeps showing while the art on
/// the canvas is selected and moved, and the Selection tool's move ends where it is released.
#[test]
@@ -227,7 +227,7 @@ fn a_plug_in_effect_s_editor_follows_its_manifest() {
}
assert!(!panel.shows("spacing") && !panel.shows("width"), "the labels replace the names");
let spacing = panel.value_role("Spacing", craft::ui::contract::Role::SPIN_BUTTON);
assert!(spacing.as_deref().is_some_and(|v| v.contains("1.5") && v.contains("mm")), "{spacing:?}");
assert!(spacing.as_deref().is_some_and(|v| v.contains(&crate::tests::regional_text("1.5")) && v.contains("mm")), "{spacing:?}");
assert!(panel.value("Angles").is_some_and(|v| v.contains("45, 135")), "{:?}", panel.value("Angles"));
// Without the outline, its width isn't shown.
panel.app().run("effect.setParams", json!({"item": null, "index": 0, "params": {"outline": false}})).unwrap();
+6 -3
View File
@@ -463,6 +463,7 @@ fn an_open_color_or_gradient_pop_out_runs_one_pass_a_frame() {
#[test]
fn the_color_panel_edits_the_selected_stroke_well_without_changing_fill() {
use crate::tests::panel_harness::Panel;
use craft::ui::contract::Role;
let mut app = app();
app.run("paint.setFill", json!({"color": "#224466"})).unwrap();
@@ -470,8 +471,8 @@ fn the_color_panel_edits_the_selected_stroke_well_without_changing_fill() {
app.run("paint.toggleActive", json!({"fill": true})).unwrap();
let mut panel = Panel::new(app, show);
let (fill, stroke) = paints_hex(&panel.app());
let fill_well = panel.rect("Fill");
let stroke_well = panel.rect("Stroke");
let fill_well = panel.rect_role_with_value(Role::RADIO_BUTTON, &fill);
let stroke_well = panel.rect_role_with_value(Role::RADIO_BUTTON, &stroke);
let stroke_hit = egui::pos2(stroke_well.center().x, (fill_well.bottom() + stroke_well.bottom()) / 2.0);
assert!(stroke_well.contains(stroke_hit) && !fill_well.contains(stroke_hit), "click the exposed part of Stroke");
panel.click_at(stroke_hit);
@@ -487,7 +488,9 @@ fn the_color_panel_edits_the_selected_stroke_well_without_changing_fill() {
panel.click("None");
assert_eq!(paints_hex(&panel.app()), ("#ffffff".into(), String::new()));
panel.click("Fill");
let fill_hit = egui::pos2(fill_well.center().x, (fill_well.top() + stroke_well.top()) / 2.0);
assert!(fill_well.contains(fill_hit) && !stroke_well.contains(fill_hit), "click the exposed part of Fill");
panel.click_at(fill_hit);
assert!(panel.app().session.fill_active);
panel.click("Black");
assert_eq!(paints_hex(&panel.app()), ("#000000".into(), String::new()));
+3 -1
View File
@@ -312,7 +312,9 @@ mod tests {
app.run("view.setZoom", json!({"zoom": 100})).unwrap();
let mut panel = crate::tests::panel_harness::Panel::new(app, draw);
panel.app().ui.status.clear();
panel.type_into("Zoom", "80..2");
let decimal = craft::i18n::Format::new(&craft::i18n::Region::system(), craft::i18n::Digits::Latin).number_ungrouped(0.2, 1);
let mark = decimal.strip_prefix('0').unwrap().strip_suffix('2').unwrap();
panel.type_into("Zoom", &format!("80{mark}{mark}2"));
{
let app = panel.app();
assert!((app.view().unwrap().zoom - 0.8).abs() < 1e-9, "applies the valid prefix");
+1
View File
@@ -58,6 +58,7 @@ fn bar(app: &mut VectorcraftApp, ui: &mut Ui) {
pub(crate) fn reads(value: Option<String>, unit: Unit, pt: f64) -> bool {
value.is_some_and(|v| {
let Some(number) = v.strip_suffix(unit.suffix()).map(str::trim_end) else { return false };
let number = vectorcraft_doc::decimal_point(number);
let decimals = number.split_once('.').map_or(0, |(_, d)| d.len());
number.parse::<f64>().is_ok_and(|shown| (shown - unit.from_pt(pt)).abs() <= 0.5 * 10f64.powi(-(decimals as i32)) + 1e-9)
})
+1 -1
View File
@@ -20,7 +20,7 @@ fn pt(v: f64) -> String {
/// A shown angle, in degrees.
fn degrees(p: &Panel, name: &str) -> Option<f64> {
p.value(name)?.trim_end_matches('°').trim_end().parse().ok()
vectorcraft_doc::parse_number(&vectorcraft_doc::decimal_point(p.value(name)?.trim_end_matches('°').trim_end()))
}
/// The state of panel-menu row `id`, as the panel menus' states give it.
+56 -22
View File
@@ -111,6 +111,9 @@ pub struct PlaceState {
/// [`ASKED`]), with the automation roots the cursor was loaded in: its OK, pressed outside any
/// roots, places the file within them. Cleared when the cursor is loaded again.
asked: Option<(u64, std::sync::Arc<vectorcraft_engine::file_access::AutomationRoots>)>,
/// The size the loaded cursor's thumbnail and count took when last shown, which places them on the side of the
/// pointer where they fit ([`cursor_overlay`]).
cursor_size: Vec2,
}
/// The `file.place` param that ties an import options dialog's OK to the click of the place cursor
@@ -838,35 +841,66 @@ pub(crate) fn show_thumbnails(app: &mut VectorcraftApp, r: &Value, asks: bool) {
.collect();
}
/// The loaded place cursor at `at` in the overlay layer `ui`: the current file's thumbnail with the
/// number of files loaded. A thumbnail is named by its place in the cursor's list, which
/// [`show_thumbnails`] replaces only together with a new load number.
pub fn cursor_overlay(app: &mut VectorcraftApp, ui: &mut egui::Ui, at: egui::Pos2) {
/// The loaded place cursor beside the pointer at `pointer`, `offset` from it, over `ui` (the canvas
/// `canvas`): the current file's thumbnail and, for a load of more than one file, the files left of
/// the load (`remaining/total`, `1/3` for the last of three). An empty cursor shows nothing. A
/// thumbnail is named by its place in the cursor's list, which [`show_thumbnails`] replaces only
/// together with a new load number.
pub(crate) fn cursor_overlay(app: &mut VectorcraftApp, ui: &mut egui::Ui, pointer: egui::Pos2, canvas: egui::Rect, offset: Vec2) {
let size = app.place.cursor_size;
let shown = show_cursor(app, ui, beside(pointer, offset, size, canvas)).unwrap_or(Vec2::ZERO);
// The first frame of a new size placed it by the old one.
if shown != size {
app.place.cursor_size = shown;
ui.ctx().request_repaint();
}
}
/// Where a box of `size` goes beside the pointer at `pointer` in `canvas`: `offset` below and to its
/// right, on an axis where that passes the canvas's edge `offset` above or to its left instead, and
/// inside the canvas where it fits on neither side.
fn beside(pointer: egui::Pos2, offset: Vec2, size: Vec2, canvas: egui::Rect) -> egui::Pos2 {
let axis = |at: f32, offset: f32, len: f32, min: f32, max: f32| {
let after = at + offset;
let start = if after + len > max { at - offset - len } else { after };
start.min(max - len).max(min)
};
egui::pos2(axis(pointer.x, offset.x, size.x, canvas.min.x, canvas.max.x), axis(pointer.y, offset.y, size.y, canvas.min.y, canvas.max.y))
}
/// [`cursor_overlay`]'s thumbnail and count with their top-left corner at `at`, and the size they
/// took; `None` for an empty cursor.
fn show_cursor(app: &VectorcraftApp, ui: &mut egui::Ui, at: egui::Pos2) -> Option<Vec2> {
let opts = app.session.tool_options();
let count = opts["count"].as_u64().unwrap_or(0);
if count == 0 {
return None;
}
let total = opts["total"].as_u64().unwrap_or(count).max(count);
let name = opts["name"].as_str().unwrap_or_default();
let found = (app.place.queue_load == app.session.place_queue_loads()).then(|| app.place.cursor_thumbnail(&opts)).flatten();
let revision = Revision::new(app.place.queue_load);
let room = egui::Rect::from_min_max(at, ui.max_rect().max.max(at));
ui.scope_builder(egui::UiBuilder::new().max_rect(room), |ui| {
match found {
Some((key, image)) => {
let side = |n: usize| u16::try_from(n.max(1)).unwrap_or(u16::MAX);
let [w, h] = image.size;
Picture::new(name.to_string(), key as u64, &|| image.clone())
.revision(revision)
.aspect(ThumbAspect::new(side(w), side(h)))
.extent(PictureSize::Thumb(ThumbSize::Medium))
.show(ui);
}
None => {
Text::new(name.to_string()).shade(Shade::Muted).show(ui);
}
let room = egui::Rect::from_min_max(at, ui.clip_rect().max.max(at));
// A child `Ui`: the overlay takes no room in the canvas's layout.
let ui = &mut ui.new_child(egui::UiBuilder::new().id_salt("place-cursor").max_rect(room));
match found {
Some((key, image)) => {
let side = |n: usize| u16::try_from(n.max(1)).unwrap_or(u16::MAX);
let [w, h] = image.size;
Picture::new(name.to_string(), key as u64, &|| image.clone())
.revision(revision)
.aspect(ThumbAspect::new(side(w), side(h)))
.extent(PictureSize::Thumb(ThumbSize::Medium))
.show(ui);
}
if count > 1 {
Badge::count(u32::try_from(count).unwrap_or(u32::MAX)).show(ui);
None => {
Text::new(name.to_string()).shade(Shade::Muted).show(ui);
}
});
}
if total > 1 {
Badge::new(format!("{count}/{total}")).show(ui);
}
Some(ui.min_rect().size())
}
// ---------- drops ----------
+7
View File
@@ -70,3 +70,10 @@ mod trace_runs;
/// test also installs, or that check how plug-ins sharing a name are told apart, hold this lock
/// while their plug-ins are installed, so each sees only its own plug-ins under that name.
pub(super) static SHARED_PLUGIN_NAMES: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// Formats a decimal fixture with the system region used by the UI.
pub(crate) fn regional_text(text: &str) -> String {
let decimal = craft::i18n::Format::new(&craft::i18n::Region::system(), craft::i18n::Digits::Latin).number_ungrouped(0.1, 1);
let mark = decimal.strip_prefix('0').unwrap().strip_suffix('1').unwrap();
text.replace('.', mark)
}
+11
View File
@@ -464,6 +464,17 @@ impl Panel {
part_rect_of_node(self.ctx(), self.look_role(name, role).node.into(), part.into())
}
/// Where the control of `role` reporting `value` is, for an unnamed part such as a color well.
pub(crate) fn rect_role_with_value(&self, role: Role, value: &str) -> Rect {
let tree = self.fixture.tree();
self.fixture
.by_role(role)
.into_iter()
.find(|target| tree.value_of(target.node) == Some(value))
.unwrap_or_else(|| panic!("no {role:?} with value {value:?}"))
.rect
}
/// The value text of the control named `name`.
pub(crate) fn value(&self, name: &str) -> Option<String> {
self.fixture.tree().value_of(self.look(name).node).map(str::to_owned)
+91
View File
@@ -414,6 +414,97 @@ fn an_automated_place_queue_keeps_same_named_file_bytes_in_order() {
}
}
/// The loaded place cursor shows its current file's thumbnail beside the pointer on the canvas and, for a load of
/// several files, the files left of the load: `3/3`, `2/3` once one is placed, `1/3` once another is discarded. A load
/// of one file shows no count, and nothing shows off the canvas or once the cursor is empty.
#[test]
fn the_loaded_place_cursor_shows_its_file_and_the_files_left_beside_the_pointer() {
let mut app = app();
let ctx = window(&app);
ctx.enable_accesskit();
let canvas = laid_out(&mut app, &ctx);
let pointer = canvas.center();
let load = |app: &mut VectorcraftApp, names: &[&str]| {
let data = vectorcraft_format::base64_encode(&png(8, 5, 72.0));
let files: Vec<Value> = names.iter().map(|name| json!({"name": name, "dataBase64": data})).collect();
app.run("file.place.queue", json!({"link": false, "files": files})).unwrap();
};
// The thumbnails named `name` and the counts (`n/m`) shown on the canvas in one frame with the pointer at `at`.
let shown = |app: &mut VectorcraftApp, at: Option<Pos2>, name: &str| -> (Vec<egui::Rect>, Vec<(String, egui::Rect)>) {
let event = at.map_or(egui::Event::PointerGone, egui::Event::PointerMoved);
let out = crate::testing::app_frame(app, &ctx, raw_input(vec![event], vec![], vec![]));
let nodes: Vec<(String, egui::accesskit::Role, egui::Rect)> = out
.platform_output
.accesskit_update
.iter()
.flat_map(|u| u.nodes.iter())
.filter_map(|(_, n)| {
let b = n.bounds()?;
let rect = egui::Rect::from_min_max(egui::pos2(b.x0 as f32, b.y0 as f32), egui::pos2(b.x1 as f32, b.y1 as f32));
let label = n.label()?.to_string();
canvas.intersects(rect).then_some((label, n.role(), rect))
})
.collect();
let thumbs = nodes.iter().filter(|(l, role, _)| l == name && *role == egui::accesskit::Role::Image).map(|n| n.2).collect();
let is_count =
|l: &str| l.split_once('/').is_some_and(|(a, b)| [a, b].iter().all(|s| !s.is_empty() && s.bytes().all(|c| c.is_ascii_digit())));
let counts = nodes.into_iter().filter(|(l, ..)| is_count(l)).map(|(l, _, r)| (l, r)).collect();
(thumbs, counts)
};
// Beside the pointer: below and to the right of it, inside the canvas, the count under the thumbnail.
let beside = |thumbs: &[egui::Rect], counts: &[(String, egui::Rect)], want: Option<&str>| {
assert_eq!(thumbs.len(), 1, "one thumbnail: {thumbs:?}");
let thumb = thumbs[0];
assert!(thumb.min.x >= pointer.x && thumb.min.y >= pointer.y && canvas.contains_rect(thumb), "{thumb:?} beside {pointer:?} in {canvas:?}");
match want {
Some(want) => {
assert_eq!(counts.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(), [want]);
let count = counts[0].1;
assert!(count.min.y >= thumb.max.y && canvas.contains_rect(count), "{count:?} under {thumb:?}");
}
None => assert!(counts.is_empty(), "{counts:?}"),
}
};
load(&mut app, &["first.png", "second.png", "third.png"]);
let (thumbs, counts) = shown(&mut app, Some(pointer), "first.png");
beside(&thumbs, &counts, Some("3/3"));
// At the canvas's bottom-right corner they go above and to the left of the pointer, inside the canvas.
let corner = canvas.max - vec2(1.0, 1.0);
let (thumbs, counts) = shown(&mut app, Some(corner), "first.png");
assert_eq!((thumbs.len(), counts.len()), (1, 1), "{thumbs:?} {counts:?}");
let both = thumbs[0].union(counts[0].1);
assert!(canvas.contains_rect(both) && both.max.x < corner.x && both.max.y < corner.y, "{both:?} beside {corner:?} in {canvas:?}");
// Off the canvas the cursor shows nothing.
let (thumbs, counts) = shown(&mut app, None, "first.png");
assert!(thumbs.is_empty() && counts.is_empty(), "{thumbs:?} {counts:?}");
click(&mut app);
let (thumbs, counts) = shown(&mut app, Some(pointer), "second.png");
beside(&thumbs, &counts, Some("2/3"));
tool_key(&mut app, vectorcraft_tools::ToolKey::Escape);
let (thumbs, counts) = shown(&mut app, Some(pointer), "third.png");
beside(&thumbs, &counts, Some("1/3"));
click(&mut app);
assert_ne!(app.session.tool_id(), "place", "the last file placed ends the cursor");
let (thumbs, counts) = shown(&mut app, Some(pointer), "third.png");
assert!(thumbs.is_empty() && counts.is_empty(), "{thumbs:?} {counts:?}");
// One file: its thumbnail, no count.
load(&mut app, &["only.png"]);
let (thumbs, counts) = shown(&mut app, Some(pointer), "only.png");
beside(&thumbs, &counts, None);
// A press on the canvas dragged across it keeps the thumbnail, and dragged off the canvas shows nothing.
let press = egui::Event::PointerButton { pos: pointer, button: egui::PointerButton::Primary, pressed: true, modifiers: Default::default() };
crate::testing::app_frame(&mut app, &ctx, raw_input(vec![egui::Event::PointerMoved(pointer), press], vec![], vec![]));
let (thumbs, _) = shown(&mut app, Some(pointer + vec2(10.0, 10.0)), "only.png");
assert_eq!(thumbs.len(), 1, "dragged on the canvas: {thumbs:?}");
let outside = egui::pos2(pointer.x, canvas.min.y - 4.0);
assert!(outside.y > 0.0, "{canvas:?} leaves room above it");
let (thumbs, counts) = shown(&mut app, Some(outside), "only.png");
assert!(thumbs.is_empty() && counts.is_empty(), "dragged off the canvas: {thumbs:?} {counts:?}");
}
/// A tiny SVG document.
const SVG: &str = r#"<svg xmlns="http://www.w3.org/2000/svg" width="50" height="40"><path d="M5 5 L45 5 L30 30 Z"/></svg>"#;
+1 -1
View File
@@ -1624,7 +1624,7 @@ fn the_smooth_tools_fidelity_label_is_one_line_beside_its_field() {
let labels = tree.with_role(craft::ui::contract::Role::LABEL);
assert!(labels.iter().any(|key| tree.name_of(*key) == Some("Fidelity:")), "the label is in the access tree");
let run = |text: &str| fx.texts().iter().find(|t| t.text == text).cloned().unwrap_or_else(|| panic!("no `{text}` painted"));
let (label, value) = (run("Fidelity:"), run("2.50 px"));
let (label, value) = (run("Fidelity:"), run(&crate::tests::regional_text("2.50 px")));
assert!(label.rect.height() < 2.0 * value.rect.height(), "the label is one line: {:?}", label.rect);
assert!((label.baseline - value.baseline).abs() <= 1.0, "the label sits on the field's baseline: {label:?} {value:?}");
});
@@ -1,6 +1,7 @@
//! Selected Dimension extension-line controls through the real Properties panel.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use craft::i18n::{Digits, Format, Region};
use craft::ui::dialog::DialogId;
use craft::ui::runtime::env::WindowKey;
use craft::ui::shell::WindowDialogs;
@@ -236,7 +237,7 @@ fn properties_edits_both_extensions_preserves_main_text_and_roundtrips_editable_
let original = recipe(&d.app.borrow(), id);
let selection = d.app.borrow().session.active().unwrap().selection.clone();
let paint = d.app.borrow().session.paint.clone();
d.type_number("Extension Line Weight", "0.35");
d.type_number("Extension Line Weight", &Format::new(&Region::system(), Digits::Locale).number_ungrouped(0.35, 2));
let weighted = recipe(&d.app.borrow(), id);
assert_eq!(weighted.options.extension_weight, 0.35);
assert_eq!(geometry(&weighted), geometry(&original));
@@ -266,7 +267,7 @@ fn properties_edits_both_extensions_preserves_main_text_and_roundtrips_editable_
d.run("document.open", json!({"name": "dimension.vectorcraft", "dataBase64": data}));
assert_eq!(recipe(&d.app.borrow(), id), edited);
select_properties(&mut d, id);
d.type_number("Extension Line Weight", "0.6");
d.type_number("Extension Line Weight", &Format::new(&Region::system(), Digits::Locale).number_ungrouped(0.6, 1));
assert_eq!(recipe(&d.app.borrow(), id).options.extension_weight, 0.6, "the native recipe remains editable through Properties");
assert_eq!(geometry(&recipe(&d.app.borrow(), id)), geometry(&edited));
generated_styles(&d.app.borrow(), id, [128, 128, 128], 0.6);
@@ -298,7 +299,7 @@ fn properties_apply_all_copies_full_style_to_editable_dimensions_and_undoes_as_o
let other_original = recipe(&d.app.borrow(), other);
let locked_original = recipe(&d.app.borrow(), locked);
select_properties(&mut d, id);
d.type_number("Extension Line Weight", "0.35");
d.type_number("Extension Line Weight", &Format::new(&Region::system(), Digits::Locale).number_ungrouped(0.35, 2));
d.pick_color("Extension Line Color", "extensionColor", "#808080");
assert_eq!(recipe(&d.app.borrow(), other), other_original, "selected edits do not change an unselected dimension");
assert_eq!(recipe(&d.app.borrow(), locked), locked_original);
@@ -327,7 +328,7 @@ fn properties_set_default_is_inherited_by_an_options_free_new_dimension() {
NodeId(d.run("dimension.create", json!({"a": [200,150], "b": [241.13,150], "options": {"extensionWeight": 0.8}}))["id"].as_u64().unwrap());
let other_original = recipe(&d.app.borrow(), other);
select_properties(&mut d, id);
d.type_number("Extension Line Weight", "0.35");
d.type_number("Extension Line Weight", &Format::new(&Region::system(), Digits::Locale).number_ungrouped(0.35, 2));
d.pick_color("Extension Line Color", "extensionColor", "#808080");
let selected = recipe(&d.app.borrow(), id);
let document = d.app.borrow().session.active().unwrap().doc.clone();
+2 -1
View File
@@ -12026,7 +12026,8 @@ Placement does not trim composite font or character set names as `type.composite
effective ppi. `file.place.queue` loads the place cursor (the `place` tool) with several files: headless, drive it
with `pointer_gesture` (a click places at 100% with the top-left corner there, a drag at the dragged size) and
`press_key` (Left/Right/Up/Down cycle, Escape discards the current file). The place tool's state includes a
read-only `sourceIndex`: the current file's zero-based position in the original load, or null when empty.
read-only `sourceIndex`: the current file's zero-based position in the original load, or null when empty, and a
read-only `total`: how many files the load held (0 when empty), which the app's cursor shows as `count/total`.
It stays with that file when other files are placed or discarded; `current` indexes the remaining files.
In the app, same-named files also keep their own queued size and password requirement. Choosing another PDF
page after a cursor click places that page at its own size; a drag keeps the chosen box.