Merge queue batch #17274: #14659, #16402

Merge queue batch: 2 PRs (#14659, #16402)
This commit is contained in:
David Mann authored and GitHub committed 2026-11-28 13:28:06 +01:00
commit 2c88f264a0
8 files changed
+558 -4

No files matched your search

+1 -1
View File
@@ -88,8 +88,8 @@ use shape::{
can_paste_shape_fill, can_paste_shape_stroke, combine_shapes, copy_shape_fill, copy_shape_stroke, has_shape_fill, has_shape_stroke, merge_components,
paste_shape_fill, paste_shape_stroke, path_to_shape, selection_to_shape, shape_create, shape_edit, shape_info, shape_rasterize,
};
pub use shape::{line_frame_scale, line_frame_size, preview_shape_stroke, refresh_shape, shape_path, transform_shape, translate_vectors};
pub(crate) use shape::{map_path, map_shape, shift_shape, translate_vectors_wrapped};
pub use shape::{preview_shape_stroke, refresh_shape, shape_path, transform_shape, translate_vectors};
use vector_mask::{toggle_vector_mask, vector_mask_add, vector_mask_delete, vector_mask_edit, vector_mask_info, vector_mask_rasterize, with};
pub fn leak(s: String) -> &'static str {
@@ -189,6 +189,95 @@ fn arrow_axis_scales(a: &Affine, from: [f64; 2], to: [f64; 2]) -> Option<(f64, f
(dot.abs() <= 1e-10 * axial * perpendicular).then_some((axial, perpendicular))
}
/// A live line's own frame.
struct LineFrame {
/// The start.
from: [f64; 2],
/// The unit direction from the start to the end.
u: [f64; 2],
/// The normal, `(-u.y, u.x)`.
n: [f64; 2],
length: f64,
/// The weight, or the arrowhead width when it is wider and an arrowhead is on.
thickness: f64,
}
/// A live line's own frame; `None` for another live shape or a degenerate or non-finite line.
fn line_frame(live: &LiveShape) -> Option<LineFrame> {
let (from, to, thickness) = match live {
LiveShape::Line { from, to, weight } => (*from, *to, *weight),
LiveShape::ArrowLine { from, to, weight, start, end, width, .. } => (*from, *to, if *start || *end { weight.max(*width) } else { *weight }),
_ => return None,
};
let (dx, dy) = (to[0] - from[0], to[1] - from[1]);
let length = dx.hypot(dy);
if !length.is_finite() || length <= 1e-12 || !thickness.is_finite() || !from.iter().all(|v| v.is_finite()) {
return None;
}
let u = [dx / length, dy / length];
Some(LineFrame { from, u, n: [-u[1], u[0]], length, thickness })
}
/// The size of a live line in its own rotated frame, as the Line tool's W and H fields show it
/// (#13250): `(length, thickness)`, the thickness being the weight, or the arrowhead width when an
/// arrowhead is on and wider. `None` for another live shape or a degenerate line.
pub fn line_frame_size(live: &LiveShape) -> Option<(f64, f64)> {
line_frame(live).map(|f| (f.length, f.thickness))
}
/// The transform that resizes a live line in its own rotated frame to `new_length` (W) by
/// `new_thickness` (H), for `shape.edit {"transform": m}` (#13250; the Properties Transform of a
/// line, #13265, builds on it). Along the line it scales about the start, so the start stays put
/// and the angle is kept; across it, it scales about the edge of the rotated box on the start's
/// side opposite the normal, `from - (thickness / 2) * n` with `n = (-u.y, u.x)`: the measured
/// reference moves the start of a 15 px thick line from 400,300 to 398.88,302.24 for H 20.
/// [`transform_shape`] keeps the line live under it and scales the weight and arrowhead width by
/// the thickness factor and the arrowhead length by the length factor.
///
/// `None` (no edit) for another live shape, a degenerate line, or a size that is not finite and
/// positive. Never panics.
pub fn line_frame_scale(live: &LiveShape, new_length: f64, new_thickness: f64) -> Option<Affine> {
if !new_length.is_finite() || !new_thickness.is_finite() || new_length <= 0.0 || new_thickness <= 0.0 {
return None;
}
let LineFrame { from, u, n, length, thickness } = line_frame(live)?;
if thickness <= 1e-12 {
return None;
}
let (sa, sp) = (new_length / length, new_thickness / thickness);
if !sa.is_finite() || !sp.is_finite() {
return None;
}
// M = I + (sa - 1) u u^T + (sp - 1) n n^T, about the pivot P: x' = M x + (P - M P).
let (ka, kp) = (sa - 1.0, sp - 1.0);
let a = 1.0 + ka * u[0] * u[0] + kp * n[0] * n[0];
let b = ka * u[0] * u[1] + kp * n[0] * n[1];
let d = 1.0 + ka * u[1] * u[1] + kp * n[1] * n[1];
let pivot = [from[0] - thickness / 2.0 * n[0], from[1] - thickness / 2.0 * n[1]];
let e = pivot[0] - (a * pivot[0] + b * pivot[1]);
let f = pivot[1] - (b * pivot[0] + d * pivot[1]);
let m = [a, b, b, d, e, f];
m.iter().all(|v| v.is_finite()).then_some(Affine { m })
}
/// Whether `m` scales a live line only along and across itself (a non-trivial [`line_frame_scale`]):
/// its direction and normal map onto themselves with positive factors, not both 1.
fn is_line_frame_scale(live: &LiveShape, m: &[f64; 6]) -> bool {
let Some(LineFrame { u, n, .. }) = line_frame(live) else { return false };
let [a, b, c, d, _, _] = *m;
let map = |v: [f64; 2]| [a * v[0] + c * v[1], b * v[0] + d * v[1]];
let factor = |v: [f64; 2]| {
let w = map(v);
let along = w[0] * v[0] + w[1] * v[1];
let across = w[0] * -v[1] + w[1] * v[0];
(along.is_finite() && along > 1e-12 && across.abs() <= 1e-9 * along.max(1.0)).then_some(along)
};
match (factor(u), factor(n)) {
(Some(sa), Some(sp)) => (sa - 1.0).abs() > 1e-12 || (sp - 1.0).abs() > 1e-12,
_ => false,
}
}
/// Applies an affine transform to a shape's path, keeping the live shape when the transform
/// is a translation plus axis-aligned scale (otherwise the shape stops being parametric).
pub fn transform_shape(sh: &mut ShapeLayer, a: &Affine) {
@@ -317,6 +406,11 @@ pub fn transform_shape(sh: &mut ShapeLayer, a: &Affine) {
}
})
}
// A plain line under the same transforms (the W and H of a diagonal line, #13250).
(Some(LiveShape::Line { from, to, weight }), false) => arrow_axis_scales(a, from, to).map(|(_, perpendicular_scale)| {
let pt = |p: [f64; 2]| [m0 * p[0] + m2 * p[1] + tx, m1 * p[0] + m3 * p[1] + ty];
LiveShape::Line { from: pt(from), to: pt(to), weight: weight * perpendicular_scale }
}),
_ => None,
};
// Keep the exact transformed outline. Remove live arrow parameters
@@ -575,7 +669,9 @@ pub(super) fn path_to_shape(s: &mut Session, p: &Value) -> Result<Value> {
/// End and Width; Start, Length and Concavity follow the same pattern. Rounding a live triangle
/// alone is "Change Rounded Triangle" (#13354); a three-sided Polygon is not a Triangle and keeps
/// "Edit Shape" until the Polygon naming issue lands. Any other edit, several keys at once, or
/// these keys sent to another shape stay "Edit Shape".
/// these keys sent to another shape stay "Edit Shape". A lone `transform` of a line that only scales
/// it along and across itself (the options bar's W and H, [`line_frame_scale`]) is "Scale Paths"
/// (#13250).
fn edit_history_name(s: &Session, id: LayerId, p: &Value) -> &'static str {
const EDIT: &str = "Edit Shape";
let live = s.active().and_then(|st| st.doc.layer(id)).and_then(|l| match &l.content {
@@ -592,6 +688,8 @@ fn edit_history_name(s: &Session, id: LayerId, p: &Value) -> &'static str {
(Some("arrowLength"), None) if line => "Change Arrowhead Length",
(Some("arrowConcavity"), None) if line => "Change Arrowhead Concavity",
(Some("cornerRadius"), None) if matches!(live, Some(LiveShape::Triangle { .. })) => "Change Rounded Triangle",
// The options bar's W and H of a line (#13250): a resize in the line's own frame.
(Some("transform"), None) if live.zip(nums::<6>(p, "transform")).is_some_and(|(l, m)| is_line_frame_scale(l, &m)) => "Scale Paths",
_ => EDIT,
}
}
+29
View File
@@ -13,6 +13,17 @@ use serde_json::Value;
use crate::PhotocraftApp;
/// The File Info dialog's title: the active document's name without its extension (#13824).
pub(crate) fn file_info_title(app: &PhotocraftApp) -> String {
app.session.active().map_or_else(
|| tl!("File Info").to_string(),
|st| match st.doc.name.rsplit_once('.') {
Some((stem, _)) if !stem.is_empty() => stem.to_owned(),
_ => st.doc.name.clone(),
},
)
}
/// What a family of the hosted dialogs does with each result, and who owns which dialog key.
pub(crate) mod params {
use std::path::{Path, PathBuf};
@@ -64,6 +75,23 @@ pub(crate) mod params {
}
}
/// The File Info dialog's document, captured when it opened (#13824).
fn file_info_document(captured: &Value) -> Option<DocId> {
captured.get("document").and_then(Value::as_u64).map(DocId)
}
/// File Info's OK: run it on the document it opened on, even when another tab is active (#13824).
fn run_file_info(app: &mut PhotocraftApp, ctx: &egui::Context, result: ParamResult) {
let doc = file_info_document(&captured(app, "file.fileInfo"));
let outcome = match doc {
Some(doc) => app.with_document(doc, |app| filter_dialog::run_command(app, ctx, "file.fileInfo", result)),
None => filter_dialog::run_command(app, ctx, "file.fileInfo", result),
};
if let Err(error) = outcome {
crate::notices::error(app, error);
}
}
/// Every family of parameter dialogs, first match wins; the generic filter family owns what is left.
pub(crate) const PARAM_FAMILIES: &[ParamFamily] = &[
ParamFamily { check: Some(fill_ui::check), ..ParamFamily::new(fill_ui::owns, fill_ui::run) },
@@ -109,6 +137,7 @@ pub(crate) mod params {
cancel: Some(filter_dialog::cancel),
..ParamFamily::new(|key| key == "file.automate.batch", filter_dialog::run)
},
ParamFamily { document: Some(file_info_document), ..ParamFamily::new(|key| key == "file.fileInfo", run_file_info) },
ParamFamily { cancel: Some(filter_dialog::cancel), ..ParamFamily::new(crate::view_cmds::dialogs::is_form, filter_dialog::run) },
crate::prefs_ui::PRESETS_FAMILY,
crate::swatches_ui::SWATCH_NAME_FAMILY,
+4
View File
@@ -214,3 +214,7 @@ mod fit_image_sticky_tests;
#[cfg(test)]
#[path = "view_cmds/save_a_copy_name_tests.rs"]
mod save_a_copy_name_tests;
#[cfg(test)]
#[path = "view_cmds/file_info_title_labels_tests.rs"]
mod file_info_title_labels_tests;
+13 -2
View File
@@ -56,6 +56,11 @@ fn opened(id: DialogId) -> Value {
/// Opens the hosted parameter form of command `id`. `fixed` holds values the command needs that no row edits.
fn open_form(app: &mut PhotocraftApp, id: &str, title: &str, params: Vec<Param>, fields: DialogFields, fixed: Value) -> DialogId {
let title = crate::dialogs::filter_dialog::title_of(title);
open_form_label(app, id, title, params, fields, fixed)
}
/// [`open_form`] with its title already built (File Info's document name, #13824).
fn open_form_label(app: &mut PhotocraftApp, id: &str, title: Label, params: Vec<Param>, fields: DialogFields, fixed: Value) -> DialogId {
let key = id.to_owned();
let image_processor = id == image_processor_ui::COMMAND;
let calculations = id == crate::dialogs::calculations_ui::COMMAND;
@@ -514,7 +519,7 @@ pub(super) fn params_for(app: &mut PhotocraftApp, id: &str) -> Option<(Vec<Param
}
/// File › File Info…: the document's metadata in Photoshop's order and labels, then its read-only Camera Data.
fn file_info_form(app: &mut PhotocraftApp) -> Option<(Vec<Param>, DialogFields)> {
pub(super) fn file_info_form(app: &mut PhotocraftApp) -> Option<(Vec<Param>, DialogFields)> {
let info = app.session.execute("file.fileInfo", json!({})).ok()?;
let text = |key: &str| info[key].as_str().unwrap_or_default().to_owned();
let keywords = info["keywords"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>().join("; ")).unwrap_or_default();
@@ -1120,7 +1125,13 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para
"file.automate.batch" if crate::actions::selected_action(app).is_none() => Some(Err("record an action in the Actions panel first".into())),
_ if is_form(id) => {
let (rows, fields) = params_for(app, id)?;
Some(Ok(opened(open_form(app, id, label, rows, fields, Value::Null))))
if id == "file.fileInfo" {
let doc = app.session.active()?.doc.id;
let title = Label::from(crate::dialogs::file_info_title(app));
Some(Ok(opened(open_form_label(app, id, title, rows, fields, json!({"document": doc.0})))))
} else {
Some(Ok(opened(open_form(app, id, label, rows, fields, Value::Null))))
}
}
_ => None,
}
@@ -0,0 +1,74 @@
//! File Info (#13824): the dialog is titled with the document it opened on (the name without
//! its extension), edits that document even if another tab becomes active, and the Basic page's
//! two remaining labels are title case. Other generated form dialogs keep their labels.
use craft::ui::dialog::DialogId;
use super::*;
fn app_with_document(name: &str) -> Box<PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"name": name, "width": 64, "height": 64})).unwrap();
app.sync_views();
app
}
fn open_file_info(app: &mut PhotocraftApp) -> DialogId {
let ctx = app.ctx().clone();
crate::menus::invoke(app, &ctx, "file.fileInfo", json!({})).unwrap();
app.framework.dialogs.stack().top().expect("File Info opens")
}
#[test]
fn the_title_is_the_document_name_without_its_extension() {
for (document, title) in [("oracle.psd", "oracle"), ("oracle", "oracle"), ("my.photo.png", "my.photo"), (".hidden", ".hidden")] {
let app = app_with_document(document);
assert_eq!(crate::dialogs::file_info_title(&app), title, "{document}");
}
}
#[test]
fn the_author_title_and_copyright_status_labels_are_title_case() {
let mut app = app_with_document("oracle.psd");
let (rows, _) = super::dialogs::file_info_form(&mut app).expect("File Info form");
let label = |key: &str| rows.iter().find(|p| p.key == key).map(|p| p.label.as_str()).unwrap_or_default();
assert_eq!(label("authorTitle"), "Author Title");
assert_eq!(label("copyrightStatus"), "Copyright Status");
// The labels that were already fixed stay as they are.
assert_eq!(label("title"), "Document Title");
assert_eq!(label("copyright"), "Copyright Notice");
assert_eq!(label("copyrightUrl"), "Copyright Info URL");
}
#[test]
fn other_form_dialogs_keep_their_generated_labels() {
assert_eq!(super::dialogs::label_of("authorTitle"), "Author title");
assert_eq!(super::dialogs::label_of("copyrightStatus"), "Copyright status");
}
/// The dialog belongs to the document it opened on. Activating another tab keeps its title, and
/// OK writes the metadata there, never into the newly active document.
#[test]
fn switching_documents_keeps_the_edit_on_the_document_it_opened_on() {
let mut app = app_with_document("oracle.psd");
let id = open_file_info(&mut app);
assert_eq!(crate::dialogs::file_info_title(&app), "oracle");
app.run("file.new", json!({"name": "other.psd", "width": 32, "height": 32})).unwrap();
assert_eq!(app.session.active().map(|st| st.doc.name.as_str()), Some("other.psd"));
let ctx = app.ctx().clone();
app.framework.dialogs.set_json_field(&ctx, id, "title", json!("Oracle title")).unwrap();
crate::dialogs::testing::confirm(&mut app, id).unwrap();
let has_title = |name: &str| {
app.session
.documents()
.iter()
.find(|st| st.doc.name == name)
.is_some_and(|st| st.doc.metadata.xmp.as_deref().is_some_and(|xmp| xmp.contains("Oracle title")))
};
assert!(has_title("oracle.psd"), "the edited document gets the metadata");
assert!(!has_title("other.psd"), "the newly active document is untouched");
assert_eq!(app.session.active().map(|st| st.doc.name.as_str()), Some("other.psd"), "the active tab is restored");
}
@@ -0,0 +1,268 @@
//! #13250: the Line tool's options bar shows W, a link button and H after the stroke controls. With
//! no line active they read 0 px and the link is off; with a line active W is its length and H its
//! thickness (the weight, or the arrowhead width when wider). Typing W or H resizes the line in its
//! own rotated frame as one "Scale Paths" step, keeping it a live line; the tool's own Weight and
//! arrowhead options for the next line do not change.
//!
//! H follows the measured numbers: the start of a 15 px thick line moves from 400,300 to
//! 398.88,302.24 for H 20, a scale about the edge of the line's box on the start's side, not its
//! centre line (a scale about the centre line would keep the start at 400,300).
use egui::accesskit::{Role, Toggled};
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use photocraft_doc::{LayerContent, LayerId, LiveShape};
use serde_json::json;
use crate::PhotocraftApp;
use crate::canvas::{ToolEvent, tool_event};
use crate::state::Tool;
type H = Harness<'static, Box<PhotocraftApp>>;
/// An 800 x 600 document with the Line tool picked, its options bar in a harness; `drawn` drags a
/// line from 400,300 to 600,400 with the tool first.
fn bar(drawn: bool) -> H {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 800, "height": 600})).unwrap();
app.sync_views();
app.ui.tool = Tool::Line;
if drawn {
let none = egui::Modifiers::NONE;
tool_event(&mut app, ToolEvent::Down { x: 400.0, y: 300.0, pressure: 1.0 }, none);
tool_event(&mut app, ToolEvent::Move { x: 500.0, y: 350.0, pressure: 1.0 }, none);
tool_event(&mut app, ToolEvent::Move { x: 600.0, y: 400.0, pressure: 1.0 }, none);
tool_event(&mut app, ToolEvent::Up { x: 600.0, y: 400.0 }, none);
}
let mut h =
Harness::builder().with_context(app.ctx().clone()).with_size(vec2(2400.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app);
h.run_steps(4);
h
}
/// The drawn line with the End arrowhead on, 15 px wide and 10 px long, set as the Properties panel sets it.
fn arrow_bar() -> (H, LayerId) {
let mut h = bar(true);
let id = active(&h);
h.state_mut().run("shape.edit", json!({"layer": id.0, "arrowEnd": true, "arrowWidth": 15, "arrowLength": 10})).unwrap();
h.run_steps(3);
(h, id)
}
fn active(h: &H) -> LayerId {
h.state().session.active().unwrap().active_layer.unwrap()
}
/// The SpinButton labelled `label`.
fn field<'h>(h: &'h H, label: &'h str) -> egui_kittest::Node<'h> {
h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some(label)).unwrap_or_else(|| panic!("the {label} field"))
}
/// The number the field labelled `label` shows.
fn shown(h: &H, label: &str) -> f64 {
let text = field(h, label).value().unwrap_or_else(|| panic!("the {label} field shows a value"));
// The decimal mark follows the locale the test runs in.
let number = text.trim_end_matches("px").trim().replace(',', ".");
number.parse().unwrap_or_else(|e| panic!("the {label} field shows a number, not {text:?} ({e})"))
}
/// Types `text` into the field labelled `label`, then Tabs out of it.
fn type_into(h: &mut H, label: &str, text: &str) {
field(h, label).click();
h.run_steps(1);
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
h.event(egui::Event::Text(text.into()));
h.run_steps(1);
h.key_press(egui::Key::Tab);
h.run_steps(3);
}
/// Whether the link button is on.
fn link_on(h: &H) -> bool {
h.get_by_role_and_label(Role::Button, "Maintain aspect ratio").accesskit_node().toggled() == Some(Toggled::True)
}
/// The live arrow line of layer `id`: from, to, weight, width, length.
fn arrow(h: &H, id: LayerId) -> ([f64; 2], [f64; 2], f64, f64, f64) {
match &h.state().session.active().unwrap().doc.layer(id).unwrap().content {
LayerContent::Shape(sh) => match &sh.live {
Some(LiveShape::ArrowLine { from, to, weight, width, length, end: true, .. }) => (*from, *to, *weight, *width, *length),
other => panic!("a live line with its End arrowhead, got {other:?}"),
},
_ => panic!("a shape layer"),
}
}
fn steps(h: &H) -> usize {
h.state().session.active().unwrap().history.past_len()
}
fn undo_label(h: &H) -> Option<String> {
h.state().session.active().unwrap().history.undo_label().map(str::to_owned)
}
fn near(a: f64, b: f64, tol: f64) -> bool {
(a - b).abs() <= tol
}
fn assert_pt(got: [f64; 2], want: [f64; 2], what: &str) {
assert!(near(got[0], want[0], 0.01) && near(got[1], want[1], 0.01), "{what}: {got:?}, want {want:?}");
}
/// The tool's own settings the next line is drawn with.
fn tool_settings(h: &H) -> (f32, bool, bool, f32, f32) {
let o = &h.state().ui.tool_options;
(o.line_weight, o.arrow_start, o.arrow_end, o.arrow_width, o.arrow_length)
}
#[test]
fn no_line_reads_zero_and_the_link_is_off() {
let h = bar(false);
assert_eq!(shown(&h, "W:"), 0.0);
assert_eq!(shown(&h, "H:"), 0.0);
assert!(!link_on(&h), "the link is off");
}
#[test]
fn a_drawn_line_reads_its_length_and_thickness() {
let h = bar(true);
assert!(near(shown(&h, "W:"), 223.61, 0.006), "W {}", shown(&h, "W:"));
assert_eq!(shown(&h, "H:"), 1.0);
assert!(!link_on(&h), "the link is off");
}
#[test]
fn w_then_h_scale_the_line_in_its_own_frame_as_scale_paths_steps() {
let (mut h, id) = arrow_bar();
let tool = tool_settings(&h);
assert_eq!(shown(&h, "H:"), 15.0, "the thickness includes the 15 px arrowhead");
let before_w = (arrow(&h, id), steps(&h));
type_into(&mut h, "W:", "300");
let (from, to, weight, width, length) = arrow(&h, id);
assert_pt(from, [400.0, 300.0], "W keeps the start");
assert_pt(to, [668.33, 434.16], "W moves the end along the line");
assert!(near(length, 13.416, 0.001), "arrowhead length {length}");
assert!(near(weight, 1.0, 1e-9) && near(width, 15.0, 1e-9), "weight {weight}, width {width}");
assert_eq!(steps(&h), before_w.1 + 1, "one step");
assert_eq!(undo_label(&h).as_deref(), Some("Scale Paths"));
assert!(near(shown(&h, "W:"), 300.0, 0.006));
let before_h = (arrow(&h, id), steps(&h));
type_into(&mut h, "H:", "20");
let (from, to, weight, width, length) = arrow(&h, id);
assert!(near(weight, 1.333, 0.001), "weight {weight}");
assert!(near(width, 20.0, 1e-9), "arrowhead width {width}");
assert!(near(length, 13.416, 0.001), "arrowhead length {length}");
assert_pt(from, [398.88, 302.24], "H moves the start across the line");
assert!(near((to[0] - from[0]).hypot(to[1] - from[1]), 300.0, 1e-6), "H keeps the length");
assert_eq!(steps(&h), before_h.1 + 1, "one step");
assert_eq!(undo_label(&h).as_deref(), Some("Scale Paths"));
assert_eq!(shown(&h, "H:"), 20.0);
assert_eq!(tool_settings(&h), tool, "the tool's Weight and arrowhead options are unchanged");
// Each edit undoes in one step.
h.state_mut().session.undo();
h.run_steps(2);
assert_eq!((arrow(&h, id), steps(&h)), before_h);
h.state_mut().session.undo();
h.run_steps(2);
assert_eq!((arrow(&h, id), steps(&h)), before_w);
}
#[test]
fn zero_negative_or_no_number_changes_nothing() {
let (mut h, id) = arrow_bar();
let before = (arrow(&h, id), steps(&h));
for typed in ["0", "-5", "abc", "NaN", "inf"] {
for label in ["W:", "H:"] {
type_into(&mut h, label, typed);
assert_eq!((arrow(&h, id), steps(&h)), before, "{label} {typed}");
}
}
}
#[test]
fn typing_without_a_line_edits_nothing() {
let mut h = bar(false);
let n = h.state().session.active().unwrap().doc.layers.len();
type_into(&mut h, "W:", "300");
type_into(&mut h, "H:", "20");
assert_eq!(h.state().session.active().unwrap().doc.layers.len(), n);
assert_eq!((shown(&h, "W:"), shown(&h, "H:")), (0.0, 0.0));
}
#[test]
fn the_frame_scale_helper_refuses_sizes_that_are_not_positive_and_finite() {
use photocraft_engine::vector_cmds::{line_frame_scale, line_frame_size};
let line =
LiveShape::ArrowLine { from: [400.0, 300.0], to: [600.0, 400.0], weight: 1.0, start: false, end: true, width: 15.0, length: 10.0, concavity: 0.0 };
let (len, thick) = line_frame_size(&line).unwrap();
assert!(near(len, 223.607, 0.001) && thick == 15.0);
for (l, t) in [(0.0, 15.0), (300.0, 0.0), (f64::NAN, 15.0), (300.0, f64::INFINITY), (-1.0, 15.0)] {
assert!(line_frame_scale(&line, l, t).is_none(), "{l} x {t}");
}
let flat = LiveShape::ArrowLine { from: [1.0, 1.0], to: [1.0, 1.0], weight: 1.0, start: false, end: false, width: 15.0, length: 10.0, concavity: 0.0 };
assert!(line_frame_size(&flat).is_none() && line_frame_scale(&flat, 300.0, 20.0).is_none());
let rect = LiveShape::Rect { rect: [0.0, 0.0, 10.0, 10.0], radii: [0.0; 4] };
assert!(line_frame_size(&rect).is_none() && line_frame_scale(&rect, 300.0, 20.0).is_none());
// A plain line's thickness is its weight, whatever the (hidden) arrowhead width.
let plain =
LiveShape::ArrowLine { from: [400.0, 300.0], to: [600.0, 400.0], weight: 1.0, start: false, end: false, width: 15.0, length: 10.0, concavity: 0.0 };
assert_eq!(line_frame_size(&plain).map(|s| s.1), Some(1.0));
}
#[test]
fn another_transform_of_a_line_keeps_its_history_name() {
let (mut h, id) = arrow_bar();
// A rotation is no scale in the line's frame.
let (s, c) = 0.3f64.sin_cos();
h.state_mut().run("shape.edit", json!({"layer": id.0, "transform": [c, s, -s, c, 0.0, 0.0]})).unwrap();
assert_ne!(undo_label(&h).as_deref(), Some("Scale Paths"));
// A move is none either.
h.state_mut().run("shape.edit", json!({"layer": id.0, "transform": [1.0, 0.0, 0.0, 1.0, 5.0, 5.0]})).unwrap();
assert_ne!(undo_label(&h).as_deref(), Some("Scale Paths"));
}
/// The live plain line (no arrow parameters) of layer `id`: from, to, weight.
fn plain(h: &H, id: LayerId) -> ([f64; 2], [f64; 2], f64) {
match &h.state().session.active().unwrap().doc.layer(id).unwrap().content {
LayerContent::Shape(sh) => match &sh.live {
Some(LiveShape::Line { from, to, weight }) => (*from, *to, *weight),
other => panic!("a live plain line, got {other:?}"),
},
_ => panic!("a shape layer"),
}
}
#[test]
fn w_then_h_keep_a_diagonal_plain_line_live() {
// `shape.create` without arrow keys (or an imported line) makes a plain `LiveShape::Line`.
let mut h = bar(false);
h.state_mut().run("shape.create", json!({"kind": "line", "from": [0, 0], "to": [200, 100], "weight": 4})).unwrap();
h.run_steps(3);
let id = active(&h);
plain(&h, id);
assert!(near(shown(&h, "W:"), 223.61, 0.006), "W {}", shown(&h, "W:"));
assert_eq!(shown(&h, "H:"), 4.0);
type_into(&mut h, "W:", "300");
let (from, to, weight) = plain(&h, id);
assert_pt(from, [0.0, 0.0], "W keeps the start");
assert_pt(to, [268.33, 134.16], "W moves the end along the line");
assert!(near(weight, 4.0, 1e-9), "weight {weight}");
assert_eq!(undo_label(&h).as_deref(), Some("Scale Paths"));
assert!(near(shown(&h, "W:"), 300.0, 0.006));
type_into(&mut h, "H:", "8");
let (from, to, weight) = plain(&h, id);
assert!(near(weight, 8.0, 1e-9), "weight {weight}");
assert!(near((to[0] - from[0]).hypot(to[1] - from[1]), 300.0, 1e-6), "H keeps the length");
// The pivot is the box edge 2 px off the start; doubling the thickness moves the start 2 px
// along the normal (-0.447, 0.894).
assert_pt(from, [-0.894, 1.789], "H moves the start across the line");
assert_eq!(undo_label(&h).as_deref(), Some("Scale Paths"));
assert_eq!(shown(&h, "H:"), 8.0);
}
+70
View File
@@ -242,6 +242,71 @@ fn paint_dialog_target<C>(which: ShapePaint, fg: C, bg: C) -> Option<(crate::sha
}
}
/// The value a W or H field's event proposes, as [`proposal`] reads the bar's events.
fn number_proposal(event: &EditEvent<Option<f64>>) -> Option<f64> {
match event {
EditEvent::Update { value, .. } => *value,
EditEvent::Commit { after, .. } | EditEvent::Set { after, .. } => *after,
EditEvent::Cancel { before: Some(Mixed::Same(value)), .. } => *value,
_ => None,
}
}
/// The Line tool's W, link and H fields (#13250; nothing for another tool): the active line's length and thickness in its own
/// rotated frame, 0 px with no live line. A typed W or H resizes the line along or across itself
/// (`shape.edit {transform}`, one "Scale Paths" step per gesture); the tool's own Weight and
/// arrowhead settings for the next line stay as they are. What the link does was not measured: it
/// shows off and changes nothing.
fn line_size_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool, target: Option<&SelectedShape>) {
use craft::ui::contract::{ShowContainer as _, SideLabel};
use craft::ui::form::Field;
use craft::ui::runtime::env::{Label, UnitKind};
use craft::ui::text::NumberField;
if tool != Tool::Line {
return;
}
let live = target.and_then(|s| s.live.as_ref().map(|l| (s.doc, s.layer, l.clone())));
let size = live.as_ref().and_then(|(_, _, l)| photocraft_engine::vector_cmds::line_frame_size(l));
let (w, h) = size.unwrap_or((0.0, 0.0));
let field = |ui: &mut egui::Ui, key: &str, caption: &str, value: f64| {
let caption = Label::from(caption.to_owned());
Field::new(caption.clone())
.id_salt(key)
.side(SideLabel::new().scrub(true))
.show(ui, |ui, _| {
// Two decimals, as the reference shows a line's length (223.61 px); a whole number shows none.
let codec = craft::behavior::NumberCodec::new(Env::of(ui).units().reader(Some(UnitKind::Pixels)), 2);
NumberField::new(caption.clone(), Bind::given(Some(value))).unit_kind(UnitKind::Pixels).codec(codec).scrub_by_label().show(ui).edit.events
})
.inner
.unwrap_or_default()
};
Divider::vertical().show(ui);
let w_events = field(ui, "line-w", tl!("W:"), w);
let _ = craft::ui::text::link_toggle(Label::from(tl!("Maintain aspect ratio").to_owned()), Bind::given(false)).show(ui);
let h_events = field(ui, "line-h", tl!("H:"), h);
let (Some((doc, layer, live)), Some((w, h))) = (live, size) else { return };
for (axis, events) in [("w", w_events), ("h", h_events)] {
for event in &events {
let Some(value) = number_proposal(event) else { continue };
let (length, thickness) = if axis == "w" { (value, h) } else { (w, value) };
// A cleared, zero, negative or non-finite value is not a size: no edit.
let Some(m) = photocraft_engine::vector_cmds::line_frame_scale(&live, length, thickness) else { continue };
if m == photocraft_geom::Affine::IDENTITY {
continue;
}
let key = crate::history_keys::coalesce(&format!("line-size-{doc:?}-{}-{axis}", layer.0), event);
if let Err(e) = app.run("shape.edit", json!({"layer": layer.0, "transform": m.m, "coalesce": key})) {
app.ui.status = e;
app.ui.status_error = true;
}
// The first value applied changes the line: later events of this pass would scale from stale sizes.
return;
}
}
}
pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool, paint: bool) {
// Path mode edits only the next outline: an active shape layer is not the target.
let target = if paint { selected_shape(&app.session) } else { None };
@@ -291,6 +356,7 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool
.chips(|which, chip, chip_ui| decorate_chip(chip, which, &mut library, chip_ui))
.show(ui);
let (fill_gradient, stroke_gradient) = (library.gradient(ShapePaint::Fill), library.gradient(ShapePaint::Stroke));
line_size_fields(app, ui, tool, target.as_ref());
tool_extras(app, ui, tool);
let mut recent: Option<[f32; 3]> = None;
@@ -548,6 +614,10 @@ mod rectangle_radius_target_tests;
#[path = "polygon_sides_alert_tests.rs"]
mod polygon_sides_alert_tests;
#[cfg(test)]
#[path = "line_wh_fields_tests.rs"]
mod line_wh_fields_tests;
#[cfg(test)]
#[path = "star_points_field_tests.rs"]
mod star_points_field_tests;