Merge main into fix/type-tool-tab-keeps-panels

This commit is contained in:
dotCooCoo committed 2026-12-05 03:21:26 -08:00
commit 2d99cd02ef
26 files changed
+288 -36

No files matched your search

+4
View File
@@ -799,6 +799,10 @@ fn main() -> std::process::ExitCode {
// window, so eframe's windows are recorded as it makes and drops them (`quit_windows`).
#[cfg(target_os = "linux")]
let options = eframe::NativeOptions { viewport_hooks: Some(std::sync::Arc::new(quit_windows::Hooks)), ..options };
// Floating panels and dialogs that draw their own title bar stay borderless on Windows, as the
// main window does (`window_frame`, #10797).
#[cfg(all(windows, feature = "wgpu"))]
let options = eframe::NativeOptions { viewport_hooks: Some(std::sync::Arc::new(window_frame::Hooks)), ..options };
#[cfg(feature = "wgpu")]
let options = {
let mut options = options;
+144 -1
View File
@@ -22,10 +22,20 @@
//! monitor. In PhotoCraft the taskbar then did not show when the pointer reached its edge
//! (storytold/photocraft#4845). On each edge with an auto-hidden taskbar the guard stops the window
//! one pixel short of the monitor instead, as PhotoCraft does (storytold/photocraft#6878).
//!
//! Floating panels and dialogs that draw their own title bar (Preferences, a floating Color panel)
//! are undecorated winit windows as well, and on the same systems their content was drawn offset
//! by the caption and border too (#10797). `Hooks` records those windows as eframe makes them and
//! runs the same guard on each one in each of its frames.
use std::collections::HashMap;
use std::sync::{Mutex, MutexGuard, PoisonError};
/// Run once per frame; a no-op once the window is borderless.
pub type WindowFrameFn = Box<dyn FnMut()>;
#[cfg(all(windows, feature = "wgpu"))]
pub use platform::Hooks;
pub use platform::service;
#[cfg(all(windows, feature = "wgpu"))]
@@ -49,6 +59,33 @@ mod platform {
Some(Box::new(move || reapply(&hwnd)))
}
/// The undecorated windows of floating panels and dialogs, which [`Hooks`] records.
static SECONDARY: std::sync::LazyLock<super::Viewports<HWND>> = std::sync::LazyLock::new(super::Viewports::default);
/// Keeps the undecorated windows of floating panels and dialogs borderless, as [`service`]
/// keeps the main window: the guard runs when eframe makes such a window and before each of its
/// frames. Set as [`eframe::NativeOptions::viewport_hooks`].
pub struct Hooks;
impl eframe::ViewportHooks for Hooks {
fn window_created(&self, viewport: egui::ViewportId, window: &winit::window::Window) {
let hwnd = match window.window_handle().map(|h| h.as_raw()) {
Ok(RawWindowHandle::Win32(h)) => find_window(h.hwnd.get()),
_ => None,
};
SECONDARY.created(viewport, window.is_decorated(), hwnd);
SECONDARY.with(viewport, reapply);
}
fn window_destroyed(&self, viewport: egui::ViewportId) {
SECONDARY.destroyed(viewport);
}
fn raw_input(&self, _ctx: &egui::Context, raw_input: &mut egui::RawInput) {
SECONDARY.with(raw_input.viewport_id, reapply);
}
}
/// One pass of the per-frame guard: the styles winit put back come off again, and a parked
/// maximize stays clear of the taskbar.
fn reapply(hwnd: &HWND) {
@@ -152,6 +189,55 @@ mod platform {
}
}
/// The windows of the undecorated floating panels and dialogs, by viewport, while eframe holds
/// them. A record holds `None` while [`Viewports::with`] has its window out. Platform-neutral so
/// it is tested everywhere.
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
struct Viewports<H>(Mutex<HashMap<egui::ViewportId, Option<H>>>);
impl<H> Default for Viewports<H> {
fn default() -> Self {
Self(Mutex::new(HashMap::new()))
}
}
#[cfg_attr(not(all(windows, feature = "wgpu")), allow(dead_code))]
impl<H> Viewports<H> {
/// eframe made `viewport`'s window, with `handle`. It is recorded when it is an undecorated
/// window other than the main one, which [`service`] keeps; otherwise any earlier record of the
/// viewport is removed, so a window made again with the system title bar is left alone.
fn created(&self, viewport: egui::ViewportId, decorated: bool, handle: Option<H>) {
let mut windows = self.lock();
match handle {
Some(handle) if viewport != egui::ViewportId::ROOT && !decorated => windows.insert(viewport, Some(handle)),
_ => windows.remove(&viewport),
};
}
/// eframe dropped `viewport`'s window.
fn destroyed(&self, viewport: egui::ViewportId) {
self.lock().remove(&viewport);
}
/// Runs `f` on `viewport`'s recorded window, if any. The window is taken out of its record
/// while `f` runs, so window messages that `f` sends and that reach the hooks again do not wait
/// on the lock. It goes back only if the record is still there and empty: a window dropped or
/// made again for the viewport in the meantime wins.
fn with(&self, viewport: egui::ViewportId, f: impl FnOnce(&H)) {
let Some(handle) = self.lock().get_mut(&viewport).and_then(Option::take) else {
return;
};
f(&handle);
if let Some(slot @ None) = self.lock().get_mut(&viewport) {
*slot = Some(handle);
}
}
fn lock(&self) -> MutexGuard<'_, HashMap<egui::ViewportId, Option<H>>> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
/// How far a parked maximize reaches past a monitor or work-area edge: the resize border (about
/// 8 pt at 100 %, more with DPI). Past that, a maximized window's rect is not parked but being
/// dragged or snapped, and is left alone.
@@ -260,7 +346,64 @@ fn short_of_autohide_taskbars(rect: Rect, monitor: Rect, work: Rect, taskbars: &
#[cfg(test)]
mod tests {
use super::{Edge, clamped_rect, short_of_autohide_taskbars, taskbar_edge};
use super::{Edge, Viewports, clamped_rect, short_of_autohide_taskbars, taskbar_edge};
fn viewport(name: &str) -> egui::ViewportId {
egui::ViewportId::from_hash_of(name)
}
/// The windows `with` reaches for each viewport, in order.
fn reached(windows: &Viewports<u32>, viewports: &[egui::ViewportId]) -> Vec<Option<u32>> {
viewports
.iter()
.map(|&id| {
let mut seen = None;
windows.with(id, |&h| seen = Some(h));
seen
})
.collect()
}
/// Floating panels and dialogs with their own title bar are kept borderless (#10797); the main
/// window, which `service` keeps, and windows with the system title bar are not recorded.
#[test]
fn undecorated_floating_windows_are_recorded_until_dropped() {
let windows = Viewports::default();
let (prefs, color, hang) = (viewport("Preferences"), viewport("Color"), viewport("Not responding"));
windows.created(egui::ViewportId::ROOT, false, Some(1));
windows.created(prefs, false, Some(7));
windows.created(color, false, Some(9));
windows.created(hang, true, Some(11));
assert_eq!(reached(&windows, &[egui::ViewportId::ROOT, prefs, color, hang]), [None, Some(7), Some(9), None]);
// Each frame reaches the window again.
assert_eq!(reached(&windows, &[prefs]), [Some(7)]);
windows.destroyed(prefs);
assert_eq!(reached(&windows, &[prefs, color]), [None, Some(9)]);
// A window made again with the system title bar, or without a handle, is left alone.
windows.created(color, true, Some(13));
assert_eq!(reached(&windows, &[color]), [None]);
windows.created(color, false, Some(15));
windows.created(color, false, None);
assert_eq!(reached(&windows, &[color]), [None]);
}
/// A window dropped or made again while the guard runs on the old one is not brought back.
#[test]
fn a_window_dropped_or_made_again_during_the_guard_wins() {
let windows = Viewports::default();
let prefs = viewport("Preferences");
windows.created(prefs, false, Some(7));
windows.with(prefs, |_| windows.destroyed(prefs));
assert_eq!(reached(&windows, &[prefs]), [None]);
windows.created(prefs, false, Some(7));
windows.with(prefs, |_| windows.created(prefs, false, Some(8)));
assert_eq!(reached(&windows, &[prefs]), [Some(8)]);
// The guard can reach the hooks again for the same viewport without waiting on itself.
let mut inner = None;
windows.with(prefs, |_| windows.with(prefs, |&h| inner = Some(h)));
assert_eq!(inner, None);
assert_eq!(reached(&windows, &[prefs]), [Some(8)]);
}
#[test]
fn a_maximize_covering_the_taskbar_is_trimmed_to_the_work_area() {
+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 }
}
@@ -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;
+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");
}
}
@@ -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.
+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)
+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();