DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge remote-tracking branch 'origin/main' into properties-wrap-offsets
moppeeer271d20ba7f67
diff --cc crates/ui-egui/src/panels/properties/object.rsindex 000000000,3819894fe..ea0fff6aamode 000000,100644..100644--- a/crates/ui-egui/src/panels/properties/object.rs+++ b/crates/ui-egui/src/panels/properties/object.rs@@@ -1,0 -1,604 +1,665 @@@+ use super::{+ CornerShape, DesignApp, FIELD_H, NumField, Rect, SelInfo, Sense, Stroke, StrokeKind, Tokens, Ui, Unit, Value, block, full_width, icon_toggle,+ icons, json, link_label, measure, more_options, outline_button, place, pos2, set_temp_bool, show_panel, sub, temp_bool, units, vec2, widgets,+ };++ // ---------------------------------------------------------------- Objects++ /// The 9-point reference-point proxy; returns a newly picked point (0..8, row-major).+ pub(crate) fn ref_point_proxy(ui: &mut Ui, r: Rect, cur: u8) -> Option<u8> {+ let t = Tokens::get(ui.ctx());+ let mut out = None;+ let pitch = r.width() / 3.0;+ for i in 0..9u8 {+ let c = pos2(r.min.x + pitch * (i % 3) as f32 + pitch / 2.0, r.min.y + pitch * (i / 3) as f32 + pitch / 2.0);+ let sq = Rect::from_center_size(c, vec2(6.0, 6.0));+ let resp = ui.interact(sq.expand(1.5), ui.scope_id().with(("refpt", i)), Sense::click());+ if i == cur {+ ui.painter().rect_filled(sq.expand(0.5), 0.0, egui::Color32::WHITE);+ } else {+ ui.painter().rect_stroke(sq, 0.0, Stroke::new(1.0, if resp.hovered() { t.text_strong } else { t.icon }), StrokeKind::Inside);+ }+ if resp.clicked() {+ out = Some(i);+ }+ }+ // Connecting lines between the squares.+ for k in 0..3 {+ let y = r.min.y + pitch * k as f32 + pitch / 2.0;+ let x = r.min.x + pitch * k as f32 + pitch / 2.0;+ for j in 0..2 {+ let a = r.min.x + pitch * j as f32 + pitch / 2.0 + 3.0;+ ui.painter().line_segment([pos2(a, y), pos2(a + pitch - 6.0, y)], Stroke::new(1.0, t.icon));+ let a = r.min.y + pitch * j as f32 + pitch / 2.0 + 3.0;+ ui.painter().line_segment([pos2(x, a), pos2(x, a + pitch - 6.0)], Stroke::new(1.0, t.icon));+ }+ }+ out+ }++ pub(super) fn transform_section(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) {+ let u = units(app);+ let rp = app.ui.ref_point;+ let b = block(ui, 2.0 * FIELD_H + 4.0);+ // Reference-point position of the bounds.+ let r = i.page_rect;+ let (fx, fy) = ((rp % 3) as f64 / 2.0, (rp / 3) as f64 / 2.0);+ let (x, y) = (r.x0 + r.width() * fx, r.y0 + r.height() * fy);+ if let Some(p) = ref_point_proxy(ui, sub(b, 5.0, 10.0, 26.0, 26.0), rp) {+ app.ui.ref_point = p;+ }+ let constrain = temp_bool(ui, "constrain_wh", false);+ let mut set = serde_json::Map::new();+ for (row, (lx, vx, kx, lw, vw, kw)) in+ [("X:", x, "x", "W:", r.width(), "width"), ("Y:", y, "y", "H:", r.height(), "height")].into_iter().enumerate()+ {+ let yy = row as f32 * 25.0;+ place(ui, sub(b, 40.0, yy, 18.0, FIELD_H), |ui| widgets::caption_w(ui, lx, 18.0));+ if let Some(v) = place(ui, sub(b, 59.0, yy, 54.0, FIELD_H), |ui| measure(ui, kx, Some(vx), u, 54.0)) {+ set.insert(kx.into(), json!(v));+ }+ place(ui, sub(b, 120.0, yy, 19.0, FIELD_H), |ui| widgets::caption_w(ui, lw, 19.0));+ if let Some(v) = place(ui, sub(b, 140.0, yy, 54.0, FIELD_H), |ui| measure(ui, kw, Some(vw), u, 54.0)) {+ set.insert(kw.into(), json!(v));+ if constrain && vw > 0.0 {+ let k = v / vw;+ let (ok, ov) = if kw == "width" { ("height", r.height()) } else { ("width", r.width()) };+ set.insert(ok.into(), json!(ov * k));+ }+ }+ }+ let clicked = place(ui, sub(b, 200.0, 12.0, 22.0, FIELD_H), |ui| {+ widgets::icon_toggle_sized(+ ui,+ if constrain { "link" } else { "link-broken" },+ constrain,+ "Constrain proportions for width and height",+ vec2(22.0, 21.0),+ )+ .clicked()+ });+ if clicked {+ set_temp_bool(ui, "constrain_wh", !constrain);+ }+ if !set.is_empty() {+ set.insert("ref".into(), json!(rp));+ let _ = app.run("transform.set", Value::Object(set));+ }+ transform_angles(app, ui, rp);+ if more_options(ui, &app.ui.language).clicked() {+ show_panel(app, "info");+ }+ }++ /// Properties › Transform for selected ruler guides: X for one vertical guide, Y for one+ /// horizontal guide; with several guides both fields are empty.+ pub(super) fn guide_section(app: &mut DesignApp, ui: &mut Ui) {+ let guide = crate::panels::guide_field(app);+ let b = block(ui, 2.0 * FIELD_H + 4.0);+ for (row, (label, key)) in [("X:", "gx"), ("Y:", "gy")].into_iter().enumerate() {+ let yy = row as f32 * 25.0;+ let on = guide.filter(|g| g.row() == row);+ place(ui, sub(b, 40.0, yy, 18.0, FIELD_H), |ui| widgets::caption_w(ui, label, 18.0));+ let typed = place(ui, sub(b, 59.0, yy, 135.0, FIELD_H), |ui| {+ if on.is_none() {+ ui.disable();+ }+ measure(ui, key, on.map(|g| g.value), on.map_or_else(|| units(app), |g| g.unit), 135.0)+ });+ if let (Some(v), Some(g)) = (typed, on) {+ let _ = app.run("guide.move", g.move_to(v));+ }+ }+ }++ /// Properties › Transform, below X/Y/W/H as in InDesign: rotation and shear angles beside the+ /// X and Y scales (totals, as Transformations are Totals), then rotate a quarter turn and flip.+ fn transform_angles(app: &mut DesignApp, ui: &mut Ui, rp: u8) {+ let t = Tokens::get(ui.ctx());+ let lang = app.ui.language.clone();+ let tv = app.session.execute("transform.info", &json!({})).ok();+ let tv_get = |k: &str| tv.as_ref().and_then(|v| v[k].as_f64());+ ui.add_space(4.0);+ let b = block(ui, 2.0 * FIELD_H + 4.0);+ let mut set = serde_json::Map::new();+ let rows = [+ [("tool-rotate", "Rotation Angle", "rotation", "°", "p_rot"), ("tool-scale", "Scale X Percentage", "scaleX", "%", "p_sx")],+ [("tool-shear", "Shear X Angle", "shear", "°", "p_shear"), ("tool-scale", "Scale Y Percentage", "scaleY", "%", "p_sy")],+ ];+ for (row, cells) in rows.into_iter().enumerate() {+ let yy = row as f32 * 25.0;+ for (col, (icon, tip, key, suffix, id)) in cells.into_iter().enumerate() {+ let x = if col == 0 { 40.0 } else { 120.0 };+ let ir = sub(b, x, yy + 2.0, 17.0, 17.0);+ icons::paint(ui.painter(), ir, icon, t.icon);+ ui.interact(ir, ui.scope_id().with(id), Sense::hover()).on_hover_text(crate::i18n::tr(&lang, tip));+ if let Some(v) = place(ui, sub(b, x + 19.0, yy, 54.0, FIELD_H), |ui| widgets::number(ui, id, tv_get(key), suffix, 54.0, 1)) {+ set.insert(key.into(), json!(v));+ }+ }+ }+ if !set.is_empty() {+ set.insert("ref".into(), json!(rp));+ let _ = app.run("transform.set", Value::Object(set));+ }+ ui.add_space(2.0);+ ui.horizontal(|ui| {+ ui.add_space(36.0);+ ui.spacing_mut().item_spacing.x = 10.0;+ for (icon, tip, cmd, params) in [+ ("rotate-clockwise", "Rotate 90° Clockwise", "transform.rotate", json!({"angle": -90})),+ ("tool-rotate", "Rotate 90° Counterclockwise", "transform.rotate", json!({"angle": 90})),+ ("flip-horizontal", "Flip Horizontal", "transform.flip", json!({"axis": "horizontal"})),+ ("flip-vertical", "Flip Vertical", "transform.flip", json!({"axis": "vertical"})),+ ] {+ let label = crate::i18n::tr(&lang, tip);+ let resp = icon_toggle(ui, icon, false, label);+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label));+ if resp.clicked() {+ let _ = app.run(cmd, params);+ }+ }+ });+ }++ /// A stroke-type preview dropdown (light box with the line style).+ pub(crate) fn stroke_type_dropdown(app: &mut DesignApp, ui: &mut Ui, cur: &str, w: f32) {+ const TYPES: &[(&str, &str)] = &[+ ("Solid", "solid"),+ ("Dashed", "dashed"),+ ("Dotted", "dotted"),+ ("Thick - Thin", "thickThin"),+ ("Thin - Thick", "thinThick"),+ ("Thin - Thin", "thinThin"),+ ("Thick - Thick", "thickThick"),+ ];+ let resp = preview_dropdown(ui, w, |p, r| paint_stroke_type(p, r, cur));+ egui::Popup::menu(&resp).show(|ui| {+ ui.set_min_width(140.0);+ for (label, kind) in TYPES {+ if ui.selectable_label(*kind == cur, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label))).clicked() {+ let ty = if *kind == "dashed" { json!({"kind": "dashed", "pattern": [12.0, 4.0]}) } else { json!({"kind": kind}) };+ let _ = app.run("object.stroke", json!({"type": ty}));+ ui.close();+ }+ }+ });+ }++ fn paint_stroke_type(p: &egui::Painter, r: Rect, kind: &str) {+ let c = egui::Color32::BLACK;+ let (x0, x1, y) = (r.min.x + 5.0, r.max.x - 5.0, r.center().y);+ match kind {+ "dashed" => {+ let mut x = x0;+ while x < x1 {+ p.line_segment([pos2(x, y), pos2((x + 6.0).min(x1), y)], Stroke::new(4.0, c));+ x += 9.0;+ }+ }+ "dotted" => {+ let mut x = x0 + 2.0;+ while x < x1 {+ p.circle_filled(pos2(x, y), 2.0, c);+ x += 6.0;+ }+ }+ "thickThin" | "thinThick" | "thinThin" | "thickThick" => {+ let (a, b) = match kind {+ "thickThin" => (3.0, 1.0),+ "thinThick" => (1.0, 3.0),+ "thinThin" => (1.0, 1.0),+ _ => (2.5, 2.5),+ };+ p.line_segment([pos2(x0, y - 3.0), pos2(x1, y - 3.0)], Stroke::new(a, c));+ p.line_segment([pos2(x0, y + 3.0), pos2(x1, y + 3.0)], Stroke::new(b, c));+ }+ _ => {+ p.line_segment([pos2(x0, y), pos2(x1, y)], Stroke::new(5.0, c));+ }+ }+ }++ /// A dropdown whose face is a light preview box (stroke type, corner shape).+ pub(super) fn preview_dropdown(ui: &mut Ui, w: f32, paint: impl FnOnce(&egui::Painter, Rect)) -> egui::Response {+ let t = Tokens::get(ui.ctx());+ let (r, resp) = ui.allocate_exact_size(vec2(w, FIELD_H), Sense::click());+ let face = Rect::from_min_max(r.min, pos2(r.max.x - widgets::SEG_W, r.max.y));+ ui.painter().rect_filled(face, 0.0, egui::Color32::from_gray(0xdf));+ paint(ui.painter(), face);+ let seg = Rect::from_min_max(pos2(face.max.x, r.min.y), r.max);+ ui.painter().rect_filled(seg, 0.0, if resp.hovered() { t.hover } else { t.input });+ widgets::chevron_down(ui.painter(), seg.center(), t.icon);+ ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);+ resp+ }++ fn paint_corner_shape(p: &egui::Painter, r: Rect, shape: CornerShape) {+ let c = egui::Color32::BLACK;+ let s = Stroke::new(1.5, c);+ let (x0, y0, x1, y1) = (r.min.x + 4.0, r.min.y + 4.0, r.max.x - 9.0, r.max.y - 3.0);+ let k = 8.0;+ let pts: Vec<egui::Pos2> = match shape {+ CornerShape::None => vec![pos2(x0, y0), pos2(x1, y0), pos2(x1, y1)],+ CornerShape::Bevel => vec![pos2(x0, y0), pos2(x1 - k, y0), pos2(x1, y0 + k), pos2(x1, y1)],+ CornerShape::Inset => vec![pos2(x0, y0), pos2(x1 - k, y0), pos2(x1 - k, y0 + k), pos2(x1, y0 + k), pos2(x1, y1)],+ CornerShape::Rounded | CornerShape::InverseRounded | CornerShape::Fancy => {+ let mut v = vec![pos2(x0, y0)];+ for i in 0..=8 {+ let a = i as f32 / 8.0 * std::f32::consts::FRAC_PI_2;+ v.push(if shape == CornerShape::InverseRounded {+ pos2(x1 - k * a.cos(), y0 + k * a.sin())+ } else {+ pos2(x1 - k + k * a.sin(), y0 + k - k * a.cos())+ });+ }+ v.push(pos2(x1, y1));+ v+ }+ };+ p.add(egui::Shape::line(pts, s));+ }++ pub(crate) fn corner_type_dropdown(app: &mut DesignApp, ui: &mut Ui, shape: CornerShape, size: f64, width: f32) {+ let resp = preview_dropdown(ui, width, |p, r| paint_corner_shape(p, r, shape));+ egui::Popup::menu(&resp).show(|ui| {+ ui.set_min_width(140.0);+ for s in CornerShape::ALL {+ if ui.selectable_label(s == shape, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, s.label()))).clicked() {+ let _ = app.run("object.cornerOptions", json!({"shape": s, "size": if size > 0.0 { size } else { 12.0 }}));+ ui.close();+ }+ }+ });+ }++ pub(super) fn appearance_section(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) {+ let t = Tokens::get(ui.ctx());+ let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return };+ // Fill.+ let b = block(ui, FIELD_H);+ let (fc, fg) = widgets::swatch_colors(&doc, &i.fill, 1.0);+ let chip = sub(b, 4.0, 2.0, 17.0, 17.0);+ widgets::paint_chip(ui.painter(), chip, fc, fg);+ ui.painter().rect_stroke(chip, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);+ let resp = ui.interact(chip, ui.scope_id().with("fillchip"), Sense::click()).on_hover_text(format!(+ "{}: {}",+ crate::i18n::tr(&app.ui.language, "Fill"),+ i.fill+ ));+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Fill swatch"));+ swatch_menu(app, &resp, &doc, &i.fill, false, i.is_text && i.count == 1, false);+ crate::rtl::paint(+ ui.painter(),+ b.min + vec2(34.0, FIELD_H / 2.0),+ egui::Align2::LEFT_CENTER,+ crate::i18n::tr(&app.ui.language, "Fill"),+ egui::FontId::proportional(11.5),+ t.text,+ );+ ui.add_space(4.0);+ // Stroke.+ let b = block(ui, FIELD_H);+ let (sc, _) = widgets::swatch_colors(&doc, &i.stroke, 1.0);+ let chip = sub(b, 4.0, 2.0, 17.0, 17.0);+ widgets::paint_stroke_chip(ui.painter(), chip, sc, egui::Color32::from_gray(20));+ ui.painter().rect_stroke(chip, 0.0, Stroke::new(1.0, t.field_border), StrokeKind::Inside);+ let resp = ui.interact(chip, ui.scope_id().with("strokechip"), Sense::click()).on_hover_text(format!(+ "{}: {}",+ crate::i18n::tr(&app.ui.language, "Stroke"),+ i.stroke+ ));+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Stroke swatch"));+ swatch_menu(app, &resp, &doc, &i.stroke, true, i.is_text && i.count == 1, false);+ if place(ui, sub(b, 34.0, 0.0, 56.0, FIELD_H), |ui| link_label(ui, crate::i18n::tr(&app.ui.language, "Stroke"), 56.0)).clicked() {+ show_panel(app, "stroke");+ }+ const WEIGHTS: &[f64] = &[0.0, 0.25, 0.5, 0.75, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 20.0, 30.0, 40.0, 50.0, 100.0];+ if let Some(v) = place(ui, sub(b, 96.0, 0.0, 69.0, FIELD_H), |ui| {+ NumField::number("sw", Some(i.stroke_weight), " pt", 3).width(69.0).spinner().presets(WEIGHTS).range(0.0, 800.0).show(ui)+ }) {+ let _ = app.run("object.stroke", json!({"weight": v}));+ }+ let kind = i.stroke_kind.clone();+ place(ui, sub(b, 171.0, 0.0, 54.0, FIELD_H), |ui| stroke_type_dropdown(app, ui, &kind, 54.0));+ ui.add_space(4.0);+ // Corner.+ let b = block(ui, FIELD_H);+ icons::paint(ui.painter(), sub(b, 3.0, 1.0, 19.0, 19.0), "corner", t.accent);+ if place(ui, sub(b, 34.0, 0.0, 56.0, FIELD_H), |ui| link_label(ui, crate::i18n::tr(&app.ui.language, "Corner"), 56.0)).clicked() {+ app.ui.dialog = Some(crate::dialogs::Dialog::new("frameSize", json!({})));+ }+ let (shape, size) = i.corner;+ if let Some(v) = place(ui, sub(b, 96.0, 0.0, 69.0, FIELD_H), |ui| {+ NumField::measure("corner", Some(size), Unit::Points).width(69.0).spinner().range(0.0, 1000.0).show(ui)+ }) {+ let sh = if shape == CornerShape::None { CornerShape::Rounded } else { shape };+ let _ = app.run("object.cornerOptions", json!({"shape": sh, "size": v}));+ }+ place(ui, sub(b, 171.0, 0.0, 54.0, FIELD_H), |ui| {+ corner_type_dropdown(app, ui, shape, size, 54.0);+ });+ ui.add_space(4.0);+ // Opacity.+ let b = block(ui, FIELD_H);+ icons::paint(ui.painter(), sub(b, 3.0, 1.0, 19.0, 19.0), "opacity", t.icon);+ if place(ui, sub(b, 34.0, 0.0, 56.0, FIELD_H), |ui| link_label(ui, crate::i18n::tr(&app.ui.language, "Opacity"), 56.0)).clicked() {+ show_panel(app, "effects");+ }+ if let Some(v) = place(ui, sub(b, 96.0, 0.0, 51.0, FIELD_H), |ui| {+ NumField::number("opacity", Some((i.opacity * 100.0).round()), "%", 0).width(51.0).range(0.0, 100.0).show(ui)+ }) {+ let _ = app.run("object.opacity", json!({"opacity": v / 100.0}));+ }+ let more = sub(b, 147.0, 0.0, 18.0, FIELD_H);+ let mresp = ui.interact(more, ui.scope_id().with("opmore"), Sense::click());+ ui.painter().rect(more, 0.0, if mresp.hovered() { t.hover } else { t.input }, Stroke::new(1.0, t.field_border), StrokeKind::Inside);+ icons::paint(ui.painter(), more.shrink(4.0), "chevron-right", t.icon);+ if mresp.clicked() {+ show_panel(app, "effects");+ }+ ui.add_space(6.0);+ ui.horizontal(|ui| {+ ui.spacing_mut().item_spacing.x = 10.0;+ if icon_toggle(ui, "frame-dashed", false, crate::i18n::tr(&app.ui.language, "Frame Fitting")).clicked() {+ show_panel(app, "textWrap");+ }+ if icon_toggle(ui, "fx", i.shadow, crate::i18n::tr(&app.ui.language, "Effects: Drop Shadow")).clicked() {+ let _ = app.run("object.dropShadow", json!({"on": !i.shadow}));+ }+ });+ }++ /// The Fill (or Stroke) popup of Properties › Appearance, as InDesign's: Apply To (a text frame's+ /// frame or its text), the tint, then the swatches. `cur` is the frame's swatch. With `text_only`+ /// (text selected) it colours the selected text.+ pub(super) fn swatch_menu(+ app: &mut DesignApp,+ resp: &egui::Response,+ doc: &designcraft_doc::Document,+ cur: &str,+ stroke: bool,+ text_frame: bool,+ text_only: bool,+ ) {+ let lang = app.ui.language.clone();+ let tr = |s: &'static str| crate::i18n::tr(&lang, s);+ let to_text_id = egui::Id::unique(("swatch_apply_to_text", stroke));+ let to_text = text_only || text_frame && resp.ctx.data(|d| d.get_temp::<bool>(to_text_id)).unwrap_or(false);+ // What the popup shows and changes: the frame's fill or stroke, or its text's.+ let (key, tint_key) = if stroke { ("stroke", "strokeTint") } else { ("fill", "fillTint") };+ let (cur, tint) = if to_text {+ let chars = crate::panels::text_attrs(app).map(|a| a["chars"].clone()).unwrap_or_default();+ (chars[key].as_str().unwrap_or("").to_string(), chars[tint_key].as_f64().unwrap_or(1.0))+ } else {+ (cur.to_string(), f64::from(crate::panels::sel_tint(app, stroke)))+ };+ let mut picked = None;+ let mut new_tint = None;+ let mut switch = None;+ egui::Popup::menu(resp).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {+ if text_frame {+ ui.horizontal(|ui| {+ crate::rtl::label(ui, tr("Apply To:"));+ for (label, text) in [("Frame", false), ("Text", true)] {+ if ui.selectable_label(to_text == text, crate::rtl::widget(ui, tr(label))).clicked() {+ switch = Some(text);+ }+ }+ });+ }+ ui.horizontal(|ui| {+ crate::rtl::label(ui, tr("Tint:"));+ if let Some(v) = NumField::number(if stroke { "stroke_tint" } else { "fill_tint" }, Some((tint * 100.0).round()), "%", 0)+ .width(60.0)+ .range(0.0, 100.0)+ .show(ui)+ {+ new_tint = Some(v / 100.0);+ }+ });+ ui.separator();+ picked = crate::panels::swatch_list(ui, doc, &cur);+ });+ if let Some(t) = switch {+ resp.ctx.data_mut(|d| d.insert_temp(to_text_id, t));+ }+ let cmd = |app: &mut DesignApp, attrs: Value| {+ if to_text {+ let _ = app.run("type.char", json!({ "attrs": attrs }));+ } else {+ let mut p = attrs.as_object().cloned().unwrap_or_default();+ // object.fill / object.stroke name the swatch `swatch` and the tint `tint`.+ if let Some(v) = p.remove(key) {+ p.insert("swatch".into(), v);+ }+ if let Some(v) = p.remove(tint_key) {+ p.insert("tint".into(), v);+ }+ let _ = app.run(if stroke { "object.stroke" } else { "object.fill" }, Value::Object(p));+ }+ };+ if let Some(n) = picked {+ cmd(app, json!({ key: n }));+ } else if let Some(t) = new_tint {+ cmd(app, json!({ tint_key: t }));+ }+ }++ pub(super) fn align_row(app: &mut DesignApp, ui: &mut Ui) {+ let t = Tokens::get(ui.ctx());+ ui.horizontal(|ui| {+ ui.spacing_mut().item_spacing.x = 8.0;+ // A key object switches Align To to Key Object; choosing another target drops the key.+ let key = app.session.active().and_then(|st| st.selection.key.filter(|_| st.selection.items.len() > 1));+ let to = if key.is_some() { "keyObject".to_string() } else { app.ui.align_to.clone() };+ let to_label = match to.as_str() {+ "selection" => "Selection",+ "keyObject" => "Key Object",+ "margins" => "Margins",+ "page" => "Page",+ "spread" => "Spread",+ other => other,+ };+ let tip = format!("{}: {}", crate::i18n::tr(&app.ui.language, "Align To"), crate::i18n::tr(&app.ui.language, to_label));+ let resp = icon_toggle(ui, "align-to", false, &tip);+ egui::Popup::menu(&resp).show(|ui| {+ for (label, id) in [+ ("Align to Selection", "selection"),+ ("Align to Key Object", "keyObject"),+ ("Align to Margins", "margins"),+ ("Align to Page", "page"),+ ("Align to Spread", "spread"),+ ] {+ if ui.selectable_label(to == id, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label))).clicked() {+ if let Some(k) = key.filter(|_| id != "keyObject") {+ let _ = app.run("selection.key", json!({"id": k.0}));+ }+ app.ui.align_to = id.into();+ ui.close();+ }+ }+ });+ let (r, _) = ui.allocate_exact_size(vec2(1.0, FIELD_H), Sense::hover());+ ui.painter().line_segment([r.center_top(), r.center_bottom()], Stroke::new(1.0, t.section_divider.gamma_multiply(1.6)));+ for (edge, icon, tip) in [+ ("left", "objalign-left", "Align left edges"),+ ("hcenter", "objalign-hcenter", "Align horizontal centers"),+ ("right", "objalign-right", "Align right edges"),+ ("top", "objalign-top", "Align top edges"),+ ("vcenter", "objalign-vcenter", "Align vertical centers"),+ ("bottom", "objalign-bottom", "Align bottom edges"),+ ] {+ if icon_toggle(ui, icon, false, crate::i18n::tr(&app.ui.language, tip)).clicked() {+ let _ = app.run("object.align", json!({"edge": edge, "to": to}));+ }+ }+ });+ }++ pub(super) fn wrap_section(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) {+ ui.horizontal(|ui| {+ ui.spacing_mut().item_spacing.x = 7.0;+ for (icon, mode, tip) in [+ ("wrap-none", "none", "No Text Wrap"),+ ("wrap-bbox", "boundingBox", "Wrap Around Bounding Box"),+ ("wrap-contour", "contour", "Wrap Around Object Shape"),+ ("wrap-jump", "jumpObject", "Jump Object"),+ ("wrap-next", "jumpToNextColumn", "Jump to Next Column"),+ ] {+ if icon_toggle(ui, icon, i.wrap == mode, crate::i18n::tr(&app.ui.language, tip)).clicked() {+ let _ = app.run("object.textWrap", json!({"mode": mode}));+ }+ }+ ui.add_space(2.0);+ let mut inv = i.wrap_invert;+ let enabled = i.wrap != "none";+ let r = ui.add_enabled_ui(enabled, |ui| widgets::checkbox(ui, &mut inv, crate::i18n::tr(&app.ui.language, "Invert"))).inner;+ if r.changed() {- let _ = app.run("object.textWrap", json!({"mode": i.wrap, "invert": inv}));++ // Each object keeps its own mode.++ let _ = app.run("object.textWrap", json!({"mode": null, "invert": inv}));+ }+ });++ wrap_offsets(app, ui, i);+ if more_options(ui, &app.ui.language).clicked() {+ show_panel(app, "textWrap");+ }+ }+++/// The wrap offsets under the wrap buttons, as InDesign's Properties panel shows them: Top and++/// Bottom, the link that makes all four the same, then Left and Right. Greyed with no wrap.++fn wrap_offsets(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) {++ let t = Tokens::get(ui.ctx());++ let lang = app.ui.language.clone();++ let tr = |s: &str| crate::i18n::tr(&lang, s).to_string();++ let u = units(app);++ let enabled = i.wrap != "none";++ let offsets = i.wrap_offsets;++ ui.add_space(4.0);++ let b = block(ui, 2.0 * FIELD_H + 5.0);++ let mut set = None;++ // The link's state belongs to the selection: another selection starts linked again when its++ // four offsets are the same.++ let selected: Vec<u64> = app.session.active().map(|st| st.selection.items.iter().map(|i| i.0).collect()).unwrap_or_default();++ let link_id = egui::Id::new(("prop_wrap_linked", selected));++ ui.add_enabled_ui(enabled, |ui| {++ // Linked while the four are the same, until the link is clicked.++ let same = offsets.iter().all(|v| (v - offsets[0]).abs() < 1e-9);++ let linked = ui.data(|d| d.get_temp::<bool>(link_id)).unwrap_or(same);++ // Offsets are [top, left, bottom, right].++ for (k, key, icon, tip, x, y) in [++ (0, "wrapTop", "margin-top", "Top", 0.0, 0.0),++ (2, "wrapBottom", "margin-bottom", "Bottom", 0.0, FIELD_H + 5.0),++ (1, "wrapLeft", "margin-inside", "Left", 140.0, 0.0),++ (3, "wrapRight", "margin-outside", "Right", 140.0, FIELD_H + 5.0),++ ] {++ let ir = sub(b, x, y + 2.0, 17.0, 17.0);++ icons::paint(ui.painter(), ir, icon, if enabled { t.icon } else { t.text_dim });++ ui.interact(ir, ui.id().with(("prop_wrap_off", k)), Sense::hover()).on_hover_ui(|ui| {++ crate::rtl::label(ui, tr(tip));++ });++ let nv = place(ui, sub(b, x + 20.0, y, 76.0, FIELD_H), |ui| {++ NumField::measure(key, Some(offsets[k]), u).width(76.0).spinner().range(-8000.0, 8000.0).enabled(enabled).show(ui)++ });++ if let Some(v) = nv {++ // Linked, all four; else this side alone, each object keeping its other offsets.++ let mut o = [None; 4];++ if linked {++ o = [Some(v); 4];++ } else {++ o[k] = Some(v);++ }++ set = Some(o);++ }++ }++ if place(ui, sub(b, 106.0, (FIELD_H + 5.0) / 2.0, 22.0, FIELD_H), |ui| {++ widgets::icon_toggle_sized(ui, if linked { "link" } else { "link-broken" }, linked, &tr("Make all settings the same"), vec2(22.0, 21.0))++ .clicked()++ }) {++ ui.data_mut(|d| d.insert_temp(link_id, !linked));++ }++ });++ if let Some(o) = set {++ // Each object keeps its own mode: only the offsets change.++ let _ = app.run("object.textWrap", json!({"mode": null, "offset": o}));++ }++}+++ fn arrange_menu(app: &mut DesignApp, resp: &egui::Response) {+ egui::Popup::menu(resp).show(|ui| {+ for (label, cmd) in [+ ("Bring to Front", "object.bringToFront"),+ ("Bring Forward", "object.bringForward"),+ ("Send Backward", "object.sendBackward"),+ ("Send to Back", "object.sendToBack"),+ ] {+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label))).clicked() {+ let _ = app.run(cmd, json!({}));+ ui.close();+ }+ }+ });+ }++ fn convert_shape_menu(app: &mut DesignApp, resp: &egui::Response) {+ egui::Popup::menu(resp).show(|ui| {+ for (label, to) in [+ ("Rectangle", "rectangle"),+ ("Rounded Rectangle", "roundedRectangle"),+ ("Beveled Rectangle", "beveledRectangle"),+ ("Inverse Rounded Rectangle", "inverseRoundedRectangle"),+ ("Ellipse", "ellipse"),+ ("Triangle", "triangle"),+ ("Polygon", "polygon"),+ ("Line", "line"),+ ("Orthogonal Line", "orthogonalLine"),+ ] {+ if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label))).clicked() {+ if let Err(e) = app.run("object.convertShape", json!({"to": to})) {+ app.status_error("Convert Shape", e);+ }+ ui.close();+ }+ }+ });+ }++ pub(super) fn quick_actions_object(app: &mut DesignApp, ui: &mut Ui, i: &SelInfo) {+ let fw = full_width(ui);+ let hw = (fw - 10.0) / 2.0;+ if i.is_text {+ ui.horizontal(|ui| {+ ui.spacing_mut().item_spacing.x = 10.0;+ let r = outline_button(ui, crate::i18n::tr(&app.ui.language, "Convert Shape"), hw);+ convert_shape_menu(app, &r);+ let r = outline_button(ui, crate::i18n::tr(&app.ui.language, "Arrange"), hw);+ arrange_menu(app, &r);+ });+ ui.add_space(4.0);+ if outline_button(ui, crate::i18n::tr(&app.ui.language, "Fill with Placeholder Text"), fw).clicked() {+ let _ = app.run("type.fillWithPlaceholder", json!({}));+ }+ ui.add_space(4.0);+ if outline_button(ui, crate::i18n::tr(&app.ui.language, "Edit in Story Editor"), fw).clicked() {+ let _ = app.run("app.storyEditor", json!({}));+ }+ return;+ }+ ui.horizontal(|ui| {+ ui.spacing_mut().item_spacing.x = 10.0;+ let r = outline_button(ui, crate::i18n::tr(&app.ui.language, "Arrange"), hw);+ arrange_menu(app, &r);+ if outline_button(ui, crate::i18n::tr(&app.ui.language, if i.count > 1 { "Group" } else { "Lock" }), hw).clicked() {+ let _ = app.run(if i.count > 1 { "object.group" } else { "object.lock" }, json!({}));+ }+ });+ ui.add_space(4.0);+ if i.kind == "<group>" {+ if outline_button(ui, crate::i18n::tr(&app.ui.language, "Ungroup"), fw).clicked() {+ let _ = app.run("object.ungroup", json!({}));+ }+ } else {+ let r = outline_button(ui, crate::i18n::tr(&app.ui.language, "Convert Shape"), fw);+ convert_shape_menu(app, &r);+ }+ }diff --cc crates/ui-egui/src/panels/properties/tests.rsindex 000000000,095bd5690..40226fa84mode 000000,100644..100644--- a/crates/ui-egui/src/panels/properties/tests.rs+++ b/crates/ui-egui/src/panels/properties/tests.rs@@@ -1,0 -1,815 +1,888 @@@+ use egui_kittest::{+ Harness,+ kittest::{NodeT, Queryable},+ };++ use super::*;++ /// A link to a panel whose flyout is open leaves the flyout open.+ #[test]+ fn a_panel_link_keeps_its_open_flyout() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ show_panel(&mut app, "stroke");+ assert_eq!(app.ui.docking_flyout.as_deref(), Some("stroke"));+ show_panel(&mut app, "stroke");+ assert!(crate::panel_docking::showing(&app, "stroke"));+ }++ fn language(app: &mut DesignApp) -> Value {+ text_attrs(app).unwrap()["chars"]["language"].clone()+ }++ fn linked_graphics(paths: &[Option<&str>]) -> (DesignApp, Vec<designcraft_doc::ItemId>, Vec<designcraft_doc::AssetId>) {+ use designcraft_doc::{Asset, AssetId, Content, Graphic, ItemId};+ use std::sync::Arc;+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"title": "Linked graphics"})).unwrap();+ let mut items = Vec::new();+ let mut assets = Vec::new();+ for (index, path) in paths.iter().enumerate() {+ let x = 72 + index * 100;+ let id = ItemId(app.run("frame.create", json!({"rect": [x, 72, x + 72, 144]})).unwrap()["id"].as_u64().unwrap());+ let doc = Arc::make_mut(&mut app.session.doc_mut().unwrap().doc);+ let aid = AssetId(doc.alloc());+ doc.assets.insert(+ aid,+ Arc::new(Asset {+ id: aid,+ name: "photo.svg".into(),+ mime: "image/svg+xml".into(),+ link: path.map(str::to_owned),+ data: Arc::new(+ br##"<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32"><rect width="32" height="32" fill="#4488cc"/></svg>"##+ .to_vec(),+ ),+ pixels: Some((32, 32)),+ ..Default::default()+ }),+ );+ doc.item_mut(id).unwrap().content = Content::Graphic(Graphic {+ layer_options: None,+ asset: aid,+ size: (72.0, 72.0),+ xf: designcraft_geom::Affine::IDENTITY,+ clip: None,+ auto_fit: Default::default(),+ fit_align: 4,+ crop: [0.0; 4],+ wrap: Default::default(),+ fill: Default::default(),+ });+ items.push(id);+ assets.push(aid);+ }+ (app, items, assets)+ }++ fn links_harness(app: DesignApp, width: f32) -> Harness<'static, DesignApp> {+ let mut ready = false;+ let mut h = Harness::builder().with_size(vec2(width, 600.0)).build_ui_state(+ move |ui, app: &mut DesignApp| {+ if !ready {+ crate::theme::install_fonts(ui.ctx(), "");+ crate::theme::apply(ui.ctx(), &Tokens::for_brightness(Default::default()));+ ready = true;+ return;+ }+ links_panel(app, ui);+ },+ app,+ );+ h.input_mut().max_texture_side = Some(8192);+ h.run_steps(3);+ h+ }++ /// With the caret in text, the Stroke panel offers the text's stroke options, not an empty panel.+ /// The first and last line indents take negative values, as InDesign's (and the Paragraph+ /// panel's) do; the left and right indents and the spacing don't.+ #[test]+ fn last_line_indent_may_be_negative() {+ for key in ["firstLineIndent", "lastLineIndent"] {+ assert!(super::para_field_min(key) < 0.0, "{key}");+ }+ for key in ["leftIndent", "rightIndent", "spaceBefore", "spaceAfter"] {+ assert_eq!(super::para_field_min(key), 0.0, "{key}");+ }+ }++ #[test]+ fn stroke_panel_shows_the_text_stroke_options_while_text_is_selected() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [72, 72, 400, 400], "content": "text", "caret": true})).unwrap();+ let mut ready = false;+ let mut h = Harness::builder().with_size(vec2(320.0, 400.0)).build_ui_state(+ move |ui, app: &mut DesignApp| {+ if !ready {+ crate::theme::install_fonts(ui.ctx(), "");+ crate::theme::apply(ui.ctx(), &Tokens::for_brightness(Default::default()));+ ready = true;+ return;+ }+ stroke_panel(app, ui);+ },+ app,+ );+ h.run_steps(3);+ assert!(h.query_by_label("Select an object.").is_none());+ h.get_by_label("Stroke Behind Fill");+ }++ /// As InDesign's: Edit Page takes the Page tool to the page in view, and Properties sets that+ /// page alone; Back returns to the document.+ #[test]+ fn edit_page_shows_the_page_and_sets_its_size_alone() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"pages": 3, "facingPages": false})).unwrap();+ app.ui.dock_tab = "properties".into();+ let mut h = crate::test_window::open(app, vec2(1400.0, 900.0));+ crate::canvas::go_to_page(&mut h.state_mut().app, 1);+ h.run_steps(3);+ h.get_by_label("Edit Page").click();+ h.run_steps(3);+ let st = h.state().app.session.active().unwrap();+ assert_eq!((h.state().app.session.tool_id(), st.selection.page), ("page", Some(1)));+ assert!(h.query_by_label("Document Setup").is_none(), "no dialog");+ let _ = h.get_by_label("Page Size");+ let _ = h.get_by_label("Margins and Columns");+ h.get_by_label("Landscape").click();+ h.run_steps(3);+ let doc = &h.state().app.session.active().unwrap().doc;+ let size = |abs: usize| doc.page(abs).map(|p| (p.width, p.height)).unwrap();+ assert_eq!(size(1), (792.0, 612.0), "the page turns");+ assert_eq!((size(0), size(2)), ((612.0, 792.0), (612.0, 792.0)), "the others don't");+ h.get_by_label("Back").click();+ h.run_steps(3);+ let st = h.state().app.session.active().unwrap();+ assert_eq!((h.state().app.session.tool_id(), st.selection.page), ("selection", None));+ let _ = h.get_by_label("Edit Page");+ }++ #[test]+ fn links_panel_distinguishes_same_named_sources_and_keeps_link_actions() {+ let first = "/project/assets/studio-a/photo.svg";+ let second = "/project/assets/studio-b/photo.svg";+ let (app, items, assets) = linked_graphics(&[Some(first), Some(second), None]);+ let mut h = links_harness(app, 320.0);+ assert_eq!(h.get_all_by_label("photo.svg").count(), 3);+ assert!(h.query_by_label(first).is_some(), "the first source path is visible in the row");+ h.get_by_label(second).click();+ h.run_steps(3);+ h.get_by_label("Go To").click();+ h.run_steps(3);+ assert_eq!(h.state().session.active().unwrap().selection.items, vec![items[1]]);+ h.get_by_label("Embed").click();+ h.run_steps(3);+ assert!(h.state().session.active().unwrap().doc.assets[&assets[1]].link.is_none());+ assert_eq!(h.state().session.active().unwrap().doc.assets[&assets[0]].link.as_deref(), Some(first));+ assert!(h.query_by_label(second).is_none(), "an embedded graphic no longer shows a source path");+ assert_eq!(h.get_all_by_label("Embedded").count(), 2);+ assert_eq!(h.get_all_by_label("photo.svg").count(), 3);+ h.get_by_label(first).click();+ h.run_steps(3);+ h.get_by_label("Go To").click();+ h.run_steps(3);+ assert_eq!(h.state().session.active().unwrap().selection.items, vec![items[0]]);+ }++ #[test]+ fn links_panel_keeps_long_source_paths_inside_a_narrow_panel() {+ let path = "/project/assets/studio-a/very-long-folder-name/another-long-folder-name/photo.svg";+ let (app, _, _) = linked_graphics(&[Some(path)]);+ let mut h = links_harness(app, 240.0);+ let source = h.get_by_label(path).rect();+ assert!(source.width() < 150.0, "the source is truncated to its column: {source:?}");+ assert!(source.right() <= 240.0, "the source stays inside the narrow panel: {source:?}");+ assert!(h.get_by_label("Page · PPI").rect().right() <= 240.0);+ h.get_by_label(path).click();+ h.run_steps(3);+ assert!(h.output().shapes.iter().any(|s| matches!(&s.shape, egui::Shape::Text(text) if text.galley.job.text == path && !text.galley.elided && text.visual_bounding_rect().right() <= 240.0)), "the selected path is painted in full and wraps inside the panel");+ }++ #[test]+ fn properties_character_section_sets_the_language() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "bunun", "caret": true})).unwrap();+ app.run("edit.selectAll", json!({})).unwrap();+ assert_ne!(language(&mut app), "French");+ let mut h = Harness::builder().with_size(vec2(320.0, 1400.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ // The panel's fonts are installed before its first frame.+ let id = egui::Id::unique("test_fonts");+ if ui.data(|d| d.get_temp::<bool>(id)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(id, true));+ return;+ }+ show(app, ui);+ },+ app,+ );+ h.run_steps(3);+ assert!(h.query_by_label("Language").is_none(), "under •••, as in InDesign");+ h.get_all_by_label("More Options").next().unwrap().click();+ h.run_steps(3);+ h.get_by_label("Language").click();+ h.run_steps(2);+ h.get_by_label("French").click();+ h.run_steps(2);+ assert_eq!(language(h.state_mut()), "French");+ }++ /// Properties › Character and Paragraph •••, as in InDesign: the sections expand in place,+ /// with the scales, baseline shift, skew, language, OpenType and the case buttons, and the+ /// indents, spacing and drop caps.+ /// Properties › Paragraph ••• on a First Line Only paragraph: Align to Baseline Grid shows+ /// pressed, and a click turns alignment off instead of making it All Lines.+ #[test]+ fn more_options_grid_button_keeps_first_line_only() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "If fine plants", "caret": true})).unwrap();+ app.run("edit.selectAll", json!({})).unwrap();+ app.run("type.para", json!({"attrs": {"gridAlign": "firstLineOnly"}})).unwrap();+ let mut h = panel_harness(app, show);+ h.run_steps(3);+ h.get_all_by_label("More Options").nth(1).unwrap().click();+ h.run_steps(3);+ assert_eq!(h.get_by_label("Align to Baseline Grid").accesskit_node().toggled(), Some(egui::accesskit::Toggled::True));+ assert_eq!(text_attrs(h.state_mut()).unwrap()["para"]["gridAlign"], "firstLineOnly");+ h.get_by_label("Align to Baseline Grid").click();+ h.run_steps(3);+ assert_eq!(text_attrs(h.state_mut()).unwrap()["para"]["gridAlign"], "none");+ }++ #[test]+ fn more_options_expand_character_and_paragraph_in_place() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "If fine plants", "caret": true})).unwrap();+ app.run("edit.selectAll", json!({})).unwrap();+ let mut h = panel_harness(app, show);+ h.run_steps(3);+ for l in ["Vertical Scale", "Small Caps", "Drop Cap Number of Lines", "Space Before"] {+ assert!(h.query_by_label(l).is_none(), "{l} hidden until •••");+ }+ h.get_all_by_label("More Options").next().unwrap().click();+ h.run_steps(3);+ h.get_by_label("Small Caps").click();+ h.run_steps(3);+ let _ = h.get_by_label("OpenType");+ let _ = h.get_by_label("Language");+ h.get_all_by_label("More Options").nth(1).unwrap().click();+ h.run_steps(3);+ let _ = h.get_by_label("Hyphenate");+ h.get_by_label("Align to Baseline Grid").click();+ h.run_steps(3);+ let a = text_attrs(h.state_mut()).unwrap();+ assert_eq!(a["chars"]["capitalization"], "smallCaps");+ assert_eq!(a["para"]["gridAlign"], "allLines");+ // ••• again folds the section.+ h.get_all_by_label("More Options").next().unwrap().click();+ h.run_steps(3);+ assert!(h.query_by_label("Small Caps").is_none());+ }++ /// The Paragraph panel on a First Line Only paragraph: Align to Baseline Grid shows pressed+ /// and keeps First Line Only, and the panel menu checks Only Align First Line to Grid.+ #[test]+ fn paragraph_panel_keeps_first_line_only() {+ let mut app = text_app();+ app.run("type.para", json!({"attrs": {"gridAlign": "firstLineOnly"}})).unwrap();+ let mut h = panel_harness(app, paragraph_panel);+ h.run_steps(3);+ assert_eq!(h.get_by_label("Align to Baseline Grid").accesskit_node().toggled(), Some(egui::accesskit::Toggled::True));+ h.get_by_label("Align to Baseline Grid").click();+ h.run_steps(3);+ assert_eq!(text_attrs(h.state_mut()).unwrap()["para"]["gridAlign"], "firstLineOnly");+ h.get_by_label("☰").click();+ h.run_steps(3);+ let _ = h.get_by_label("✓ Only Align First Line to Grid");+ }++ #[test]+ fn paragraph_panel_menu_toggles_ignore_optical_margin() {+ let mut h = panel_harness(text_app(), paragraph_panel);+ h.run_steps(3);+ h.get_by_label("☰").click();+ h.run_steps(3);+ h.get_by_label(" Ignore Optical Margin").click();+ h.run_steps(3);+ assert_eq!(text_attrs(h.state_mut()).unwrap()["para"]["ignoreOpticalMargin"], true);+ h.get_by_label("☰").click();+ h.run_steps(3);+ h.get_by_label("✓ Ignore Optical Margin").click();+ h.run_steps(3);+ assert_eq!(text_attrs(h.state_mut()).unwrap()["para"]["ignoreOpticalMargin"], false);+ }++ #[test]+ fn paragraph_panel_menu_define_lists_opens_its_dialog() {+ let mut h = panel_harness(text_app(), paragraph_panel);+ h.run_steps(3);+ h.get_by_label("☰").click();+ h.run_steps(3);+ h.get_by_label("Define Lists…").click();+ h.run_steps(3);+ assert!(h.state_mut().ui.dialog.is_some(), "Define Lists");+ }++ #[test]+ fn paragraph_panel_is_laid_out_as_indesigns_with_its_panel_menu() {+ let mut h = panel_harness(text_app(), paragraph_panel);+ h.run_steps(3);+ for l in [+ "Left Indent",+ "Right Indent",+ "First Line Left Indent",+ "Last Line Right Indent",+ "Space Before",+ "Space After",+ "Space Between Paragraphs Using Same Style",+ "Drop Cap Number of Lines",+ "Drop Cap One or More Characters",+ "Paragraph Shading",+ "Paragraph Border",+ "Hyphenate",+ "Do Not Align to Baseline Grid",+ ] {+ let _ = h.get_by_label(l);+ }+ let para = |h: &mut Harness<'static, DesignApp>| text_attrs(h.state_mut()).unwrap()["para"].clone();+ // Space Between Paragraphs Using Same Style starts at Ignore; a value is set, and emptying+ // the field ignores it again.+ assert!(para(&mut h)["sameParaStyleSpacing"].is_null());+ let field = h.get_all_by_role(egui::accesskit::Role::TextInput).nth(6).unwrap();+ field.focus();+ field.type_text("6 pt");+ h.run_steps(1);+ h.key_press(egui::Key::Enter);+ h.run_steps(3);+ assert_eq!(para(&mut h)["sameParaStyleSpacing"], 6.0);+ h.get_all_by_role(egui::accesskit::Role::TextInput).nth(6).unwrap().focus();+ h.run_steps(1);+ for _ in 0..8 {+ h.key_press(egui::Key::Backspace);+ }+ h.key_press(egui::Key::Enter);+ h.run_steps(3);+ assert!(para(&mut h)["sameParaStyleSpacing"].is_null(), "Ignore");+ // Shading on, then the grid buttons and Only Align First Line to Grid from the menu.+ h.get_by_label("Shading").click();+ h.run_steps(3);+ assert_eq!(para(&mut h)["shadingOn"], true);+ h.get_by_label("Align to Baseline Grid").click();+ h.run_steps(3);+ assert_eq!(para(&mut h)["gridAlign"], "allLines");+ h.get_by_label("☰").click();+ h.run_steps(3);+ for l in+ [" Balance Ragged Lines", "Keep Options…", "Drop Caps and Nested Styles…", "GREP Styles…", "Define Lists…", "Restart/Continue Numbering"]+ {+ let _ = h.get_by_label(l);+ }+ h.get_by_label(" Only Align First Line to Grid").click();+ h.run_steps(3);+ assert_eq!(para(&mut h)["gridAlign"], "firstLineOnly");+ h.get_by_label("Do Not Align to Baseline Grid").click();+ h.run_steps(3);+ assert_eq!(para(&mut h)["gridAlign"], "none");+ // Keep Options… opens the selected paragraphs' Keep Options, and OK applies them.+ h.get_by_label("☰").click();+ h.run_steps(3);+ h.get_by_label("Keep Options…").click();+ h.run_steps(3);+ let app = h.state_mut();+ let d = app.ui.dialog.as_mut().expect("Keep Options");+ assert_eq!((d.id.as_str(), d.s("section").as_str()), ("paragraphLocal", "keep"));+ d.fields.insert("p.keepWithNext".into(), json!(2));+ crate::dialogs::confirm(app).unwrap();+ assert_eq!(para(&mut h)["keepWithNext"], 2);+ }++ fn kerning(app: &mut DesignApp) -> Value {+ text_attrs(app).unwrap()["chars"]["kerning"].clone()+ }++ /// A harness drawing `panel` for `app` (fonts installed before the first frame).+ fn panel_harness(app: DesignApp, panel: fn(&mut DesignApp, &mut egui::Ui)) -> Harness<'static, DesignApp> {+ Harness::builder().with_size(vec2(320.0, 1400.0)).build_ui_state(+ move |ui, app: &mut DesignApp| {+ let id = egui::Id::unique("test_fonts");+ if ui.data(|d| d.get_temp::<bool>(id)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(id, true));+ return;+ }+ panel(app, ui);+ },+ app,+ )+ }++ fn text_app() -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "AVATAR", "caret": true})).unwrap();+ app.run("edit.selectAll", json!({})).unwrap();+ app+ }++ #[test]+ fn properties_kerning_menu_sets_zero_kerning() {+ let mut h = panel_harness(text_app(), show);+ h.run_steps(3);+ assert_eq!(kerning(h.state_mut())["kind"], "metrics");+ h.get_by_label("Kerning").click();+ h.run_steps(2);+ h.get_by_label("0").click();+ h.run_steps(2);+ assert_eq!(kerning(h.state_mut())["kind"], "none");+ }++ fn undo_steps(app: &DesignApp) -> usize {+ app.session.active().unwrap().history.undo.len()+ }++ fn font_style(app: &mut DesignApp) -> String {+ text_attrs(app).unwrap()["chars"]["fontStyle"].as_str().unwrap().to_string()+ }++ /// The Digits menu uses the reference names (documented as Arabic, Hindi and Farsi), which+ /// are translated, with a sample of each script's figures.+ #[test]+ fn digits_choices_use_the_reference_names() {+ assert_eq!(DIGIT_OPTIONS.map(|o| o.1), ["Default", "Arabic", "Hindi", "Farsi", "Native"]);+ for (lang, _) in crate::i18n::LANGUAGES {+ let tr = |s| crate::i18n::tr(lang, s);+ let shown: Vec<String> = DIGIT_OPTIONS.iter().map(|o| digit_label(lang, *o)).collect();+ let expected = [+ tr("Default").to_string(),+ format!("{} 0123", tr("Arabic")),+ format!("{} ٠١٢٣", tr("Hindi")),+ format!("{} ۰۱۲۳", tr("Farsi")),+ tr("Native").to_string(),+ ];+ assert_eq!(shown, expected, "{lang}");+ }+ }++ #[test]+ fn axes_with_an_inverted_or_missing_range_get_no_slider() {+ let axis = |tag: &str, min: f32, max: f32| (tag.to_string(), tag.to_string(), min, min, max);+ let kept = usable_axes(vec![axis("wght", 100.0, 900.0), axis("wdth", 125.0, 75.0), axis("opsz", f32::NAN, 72.0), axis("slnt", 0.0, 0.0)]);+ let tags: Vec<&str> = kept.iter().map(|a| a.0.as_str()).collect();+ assert_eq!(tags, ["wght", "slnt"]);+ }++ #[test]+ fn variable_font_style_keeps_two_decimals_at_most() {+ let values = [("wght".to_string(), 512.0_f32), ("wdth".to_string(), 1.25), ("opsz".to_string(), 0.4801)];+ assert_eq!(variable_font_style("Regular", &values), "Regular {wght:512,wdth:1.25,opsz:0.48}");+ assert_eq!(axis_step(100.0, 900.0), (1.0, 0));+ assert_eq!(axis_step(0.48, 3.2), (0.01, 2));+ }++ #[test]+ fn a_live_preview_held_over_many_frames_is_one_undo_step_once_let_go() {+ let mut app = text_app();+ let steps = undo_steps(&app);+ let size = |app: &mut DesignApp| text_attrs(app).unwrap()["chars"]["size"].as_f64().unwrap();+ // A drag: a preview on most frames, held without moving on others.+ for v in [20.0, 24.0, 30.0] {+ app.settle_live_preview();+ app.live_preview("Size", "type.char", json!({"attrs": {"size": v}}));+ app.settle_live_preview();+ app.hold_live_preview();+ }+ assert_eq!(size(&mut app), 30.0, "the page shows the last preview");+ assert_eq!(undo_steps(&app), steps, "nothing is undoable while held");+ // Let go: a frame without a hold, then the frame after it commits the preview.+ app.settle_live_preview();+ assert_eq!(undo_steps(&app), steps, "the last held frame keeps it open");+ app.settle_live_preview();+ assert_eq!(undo_steps(&app), steps + 1);+ assert!(app.session.active().unwrap().interaction.is_none());+ app.settle_live_preview();+ assert_eq!(undo_steps(&app), steps + 1, "committed once");+ // Later edits get their own undo steps.+ app.run("type.char", json!({"attrs": {"tracking": 50}})).unwrap();+ assert_eq!(undo_steps(&app), steps + 2);+ }++ /// A system variable font with two or more axes (macOS ships some), loaded into the shared fonts.+ fn system_variable_font() -> Option<&'static str> {+ let candidates = [("/System/Library/Fonts/Supplemental/Skia.ttf", "Skia"), ("/System/Library/Fonts/NewYork.ttf", "New York")];+ candidates.into_iter().find_map(|(path, family)| {+ let bytes = std::fs::read(path).ok()?;+ let db = designcraft_fonts::FontDb::global();+ db.add_font(bytes);+ let style = db.styles(family).first().cloned()?;+ (db.axes(family, &style).len() >= 2).then_some(family)+ })+ }++ #[test]+ fn dragging_one_of_several_axis_sliders_is_one_undo_step() {+ let Some(family) = system_variable_font() else {+ eprintln!("skipped: no variable font with two axes on this system");+ return;+ };+ let mut app = text_app();+ super::super::apply_font(&mut app, &super::super::FontPick { family: family.into(), style: None });+ let before = font_style(&mut app);+ let steps = undo_steps(&app);+ // The app commits a preview no panel held at the start of each frame (DesignApp::ui).+ let mut h = Harness::builder().with_size(vec2(320.0, 1400.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let id = egui::Id::unique("test_fonts");+ if ui.data(|d| d.get_temp::<bool>(id)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(id, true));+ return;+ }+ app.settle_live_preview();+ character_panel(app, ui);+ },+ app,+ );+ h.run_steps(3);+ let sliders = h.get_all_by_role(egui::accesskit::Role::Slider).map(|n| n.rect()).collect::<Vec<_>>();+ assert!(sliders.len() >= 2, "one slider per axis: {sliders:?}");+ let track = sliders[0];+ let y = track.center().y;+ h.hover_at(egui::pos2(track.left() + 2.0, y));+ h.run_steps(1);+ h.drag_at(egui::pos2(track.left() + 2.0, y));+ h.run_steps(1);+ for k in 1..=10 {+ h.hover_at(egui::pos2(track.left() + track.width() * k as f32 / 10.0, y));+ h.run_steps(1);+ assert_eq!(undo_steps(h.state()), steps, "no undo step while dragging (frame {k})");+ }+ let previewed = font_style(h.state_mut());+ assert_ne!(previewed, before, "the drag previews on the page");+ h.drop_at(egui::pos2(track.right(), y));+ h.run_steps(3);+ assert_eq!(undo_steps(h.state()), steps + 1, "the whole drag is one undo step");+ assert_eq!(font_style(h.state_mut()), previewed);+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(font_style(h.state_mut()), before);+ }++ #[test]+ fn character_panel_has_kerning_and_takes_a_typed_manual_value() {+ let mut h = panel_harness(text_app(), character_panel);+ h.run_steps(3);+ // The caption and the control share the name: click the control.+ h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Kerning").click();+ h.run_steps(2);+ // Address the manual-value editor by semantics, not tree traversal order.+ let field = h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Manual Kerning");+ field.focus();+ field.type_text("-40");+ h.run_steps(1);+ h.key_press(egui::Key::Enter);+ h.run_steps(3);+ assert_eq!(kerning(h.state_mut()), json!({"kind": "manual", "value": -40.0}));+ }++ #[test]+ fn a_manual_kerning_value_at_a_caret_kerns_the_pair() {+ let mut app = text_app();+ let story = app.session.active().unwrap().selection.text.unwrap().story;+ app.run("text.select", json!({"story": story.0, "anchor": 1, "focus": 1})).unwrap();+ let mut h = panel_harness(app, character_panel);+ h.run_steps(3);+ h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Kerning").click();+ h.run_steps(2);+ let field = h.get_by_role_and_label(egui::accesskit::Role::TextInput, "Manual Kerning");+ field.focus();+ field.type_text("-80");+ h.run_steps(1);+ h.key_press(egui::Key::Enter);+ h.run_steps(3);+ let st = h.state_mut().session.active().unwrap().doc.story(story).unwrap().format_after(0).over.kerning;+ assert_eq!(st, Some(designcraft_doc::Kerning::Manual(-80.0)), "A of the A|V pair");+ assert_eq!(kerning(h.state_mut()), json!({"kind": "manual", "value": -80.0}));+ }++ #[test]+ fn clicking_a_swatch_chip_in_the_appearance_fill_menu_applies_it() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ // A graphic frame: the Appearance section shows a single Fill chip.+ let id = app.run("frame.create", json!({"rect": [72, 72, 300, 200]})).unwrap()["id"].as_u64().unwrap();+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ let before = app.session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().fill.swatch.clone();+ assert_ne!(before, "[Paper]");+ let mut h = Harness::builder().with_size(vec2(320.0, 1400.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let id = egui::Id::unique("test_fonts");+ if ui.data(|d| d.get_temp::<bool>(id)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(id, true));+ return;+ }+ show(app, ui);+ },+ app,+ );+ h.run_steps(3);+ // Open the Fill menu from the Appearance chip.+ h.get_by_label("Fill swatch").click();+ h.run_steps(3);+ // Click the *chip* (the row's left edge), not the name.+ let name = "[Paper]".to_string();+ let row = h.get_by_label(&name).rect();+ // The row spans the menu (chip + name), not just the name text.+ assert!(row.width() > 150.0, "the row is the full menu width, chip included: {row:?}");+ let p = row.min + vec2(8.0, row.height() / 2.0);+ h.hover_at(p);+ h.drag_at(p);+ h.drop_at(p);+ h.run_steps(4);+ let after = h.state().session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().fill.swatch.clone();+ assert_eq!(after, name, "clicking the swatch chip applies it");+ }++ fn panel(app: DesignApp) -> Harness<'static, DesignApp> {+ let mut h = Harness::builder().with_size(vec2(320.0, 1400.0)).build_ui_state(+ |ui, app: &mut DesignApp| {+ let id = egui::Id::unique("test_fonts");+ if ui.data(|d| d.get_temp::<bool>(id)).is_none() {+ crate::theme::install_fonts(ui.ctx(), "");+ ui.data_mut(|d| d.insert_temp(id, true));+ return;+ }+ show(app, ui);+ },+ app,+ );+ h.run_steps(3);+ h+ }++ /// The course's chapter 21: Properties' Bulleted List button gives the selected paragraphs+ /// bullets with InDesign's hanging indent; pressed again, both go.+ #[test]+ fn the_bulleted_list_button_applies_a_hanging_indent() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let f = app+ .run(+ "frame.create",+ json!({"rect": [72, 72, 300, 200], "content": "text", "text": "4 eggs+ 1 cup milk"}),+ )+ .unwrap();+ app.run("text.select", json!({"story": f["story"], "anchor": 0, "focus": 15})).unwrap();+ let mut h = panel(app);+ h.get_by_label("Bulleted List").click();+ h.run_steps(3);+ let a = h.state_mut().run("type.selectionAttrs", json!({})).unwrap();+ assert_eq!(+ (a["para"]["listType"].as_str(), a["para"]["leftIndent"].as_f64(), a["para"]["firstLineIndent"].as_f64()),+ (Some("bullets"), Some(18.0), Some(-18.0))+ );+ assert_eq!(crate::menus::checked(h.state(), "list.bullets", &json!({})), Some(true), "Type › Apply Bullets shows it");+ h.get_by_label("Bulleted List").click();+ h.run_steps(3);+ let a = h.state_mut().run("type.selectionAttrs", json!({})).unwrap();+ assert_eq!((a["para"]["listType"].as_str(), a["para"]["leftIndent"].as_f64()), (Some("none"), Some(0.0)));+ }++ #[test]+ fn several_shapes_show_pathfinder_and_intersect_combines_them() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let a = app.run("frame.create", json!({"rect": [100, 100, 300, 300], "shape": "ellipse"})).unwrap()["id"].clone();+ let b = app.run("frame.create", json!({"rect": [200, 100, 300, 200]})).unwrap()["id"].clone();+ // One shape: no Pathfinder section.+ app.run("selection.set", json!({"ids": [a]})).unwrap();+ let mut h = panel(app);+ assert!(h.query_by_label("Pathfinder").is_none());+ // Two: the section and its five buttons; Intersect leaves one shape, the ellipse's quarter.+ h.state_mut().run("selection.set", json!({"ids": [a, b]})).unwrap();+ h.run_steps(3);+ assert!(h.query_by_label("Pathfinder").is_some());+ for op in ["Add", "Subtract", "Intersect", "Exclude Overlap", "Minus Back"] {+ assert!(h.query_by_label(op).is_some(), "{op}");+ }+ h.get_by_label("Intersect").click();+ h.run_steps(3);+ let doc = &h.state().session.active().unwrap().doc;+ let items = &doc.spreads[0].items;+ assert_eq!(items.len(), 1, "one shape left");+ let r = items[0].bounds();+ assert!((r.x0 - 200.0).abs() < 0.5 && (r.y1 - 200.0).abs() < 0.5 && (r.x1 - 300.0).abs() < 0.5, "{r:?}");+ }+++ /// Properties › Text Wrap shows the four offsets under the wrap buttons, as InDesign's++ /// Properties panel does: linked at first, so one value sets all four; unlinked, one side.++ #[test]++ fn properties_text_wrap_shows_and_sets_the_offsets() {++ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());++ app.run("file.new", json!({})).unwrap();++ let id = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "shape": "rectangle"})).unwrap()["id"].as_u64().unwrap();++ app.run("selection.set", json!({"ids": [id]})).unwrap();++ app.run("object.textWrap", json!({"mode": "boundingBox", "offset": 0})).unwrap();++ let offsets = |app: &DesignApp| app.session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().wrap.offsets;++ let mut h = panel(app);++ // The fields between the Text Wrap heading and Quick Actions: Top, Left, Bottom, Right.++ let fields = |h: &Harness<'_, DesignApp>| {++ let (top, bottom) = (h.get_by_label("Text Wrap").rect().bottom(), h.get_by_label("Quick Actions").rect().top());++ let mut v: Vec<egui::Rect> = h++ .get_all_by_role(egui::accesskit::Role::TextInput)++ .map(|n| n.rect())++ .filter(|r| r.center().y > top && r.center().y < bottom)++ .collect();++ v.sort_by(|a, b| (a.top(), a.left()).partial_cmp(&(b.top(), b.left())).unwrap());++ v++ };++ let f = fields(&h);++ assert_eq!(f.len(), 4, "four offsets: {f:?}");++ let type_in = |h: &mut Harness<'_, DesignApp>, at: egui::Rect, text: &str| {++ h.hover_at(at.center());++ h.drag_at(at.center());++ h.drop_at(at.center());++ h.run_steps(2);++ h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND });++ h.event(egui::Event::Text(text.into()));++ h.key_press(egui::Key::Enter);++ h.run_steps(3);++ };++ // Linked: the top offset sets all four.++ type_in(&mut h, f[0], "12pt");++ assert_eq!(offsets(h.state()), [12.0; 4]);++ // Unlinked: the bottom one alone.++ let (top, bottom) = (h.get_by_label("Text Wrap").rect().bottom(), h.get_by_label("Quick Actions").rect().top());++ h.get_all_by_label("Make all settings the same").find(|n| n.rect().center().y > top && n.rect().center().y < bottom).unwrap().click();++ h.run_steps(2);++ let f = fields(&h);++ type_in(&mut h, f[2], "6pt");++ assert_eq!(offsets(h.state()), [12.0, 12.0, 6.0, 12.0], "[top, left, bottom, right]");++ // Two objects with different offsets: a side typed in changes that side on each, and++ // each keeps its other three.++ let other = h.state_mut().run("frame.create", json!({"rect": [72, 300, 300, 400], "shape": "rectangle"})).unwrap()["id"].as_u64().unwrap();++ h.state_mut().run("object.textWrap", json!({"mode": "contour", "offset": [3, 4, 5, 6], "ids": [other]})).unwrap();++ let of = |h: &Harness<'_, DesignApp>, id: u64| {++ h.state().session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().wrap.offsets++ };++ h.state_mut().run("selection.set", json!({"ids": [id, other]})).unwrap();++ h.run_steps(3);++ let f = fields(&h);++ type_in(&mut h, f[0], "9pt");++ assert_eq!((of(&h, id), of(&h, other)), ([9.0, 12.0, 6.0, 12.0], [9.0, 4.0, 5.0, 6.0]), "the top alone, on each");++ let mode =++ |h: &Harness<'_, DesignApp>, id: u64| h.state().session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().wrap.mode;++ assert_eq!(++ (mode(&h, id), mode(&h, other)),++ (designcraft_doc::WrapMode::BoundingBox, designcraft_doc::WrapMode::Contour),++ "each keeps its mode"++ );++ // An object whose offsets are the same starts linked, though the link was off before.++ let third = h.state_mut().run("frame.create", json!({"rect": [320, 72, 500, 200], "shape": "rectangle"})).unwrap()["id"].as_u64().unwrap();++ h.state_mut().run("object.textWrap", json!({"mode": "boundingBox", "offset": 4, "ids": [third]})).unwrap();++ h.state_mut().run("selection.set", json!({"ids": [third]})).unwrap();++ h.run_steps(3);++ let f = fields(&h);++ type_in(&mut h, f[2], "8pt");++ assert_eq!(of(&h, third), [8.0; 4], "linked again for this selection");++ }+++ const CYAN: &str = "C=100 M=0 Y=0 K=0";++ #[test]+ fn the_fill_menu_sets_a_tint() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let id = app.run("frame.create", json!({"rect": [72, 72, 300, 200]})).unwrap()["id"].as_u64().unwrap();+ app.run("object.fill", json!({"swatch": CYAN, "ids": [id]})).unwrap();+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ let mut h = panel(app);+ h.get_by_label("Fill swatch").click();+ h.run_steps(3);+ // A frame that isn't a text frame: no Apply To.+ assert!(h.query_by_label("Apply To:").is_none());+ // The field on the Tint row (Opacity also reads 100%).+ let row = h.get_by_label("Tint:").rect();+ h.query_all_by(|n| n.role() == egui::accesskit::Role::TextInput && n.value().as_deref() == Some("100%"))+ .find(|n| (n.rect().center().y - row.center().y).abs() < 8.0)+ .expect("the Tint field")+ .click();+ h.run_steps(2);+ h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND });+ h.event(egui::Event::Text("25".into()));+ h.key_press(egui::Key::Enter);+ h.run_steps(3);+ let fill = h.state().session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().fill.clone();+ assert_eq!((fill.swatch.as_str(), fill.tint), (CYAN, 0.25), "the tint, on the same swatch");+ }++ #[test]+ fn a_tint_on_several_objects_keeps_each_ones_swatch() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let a = app.run("frame.create", json!({"rect": [72, 72, 200, 200]})).unwrap()["id"].as_u64().unwrap();+ let b = app.run("frame.create", json!({"rect": [220, 72, 300, 200]})).unwrap()["id"].as_u64().unwrap();+ app.run("object.fill", json!({"swatch": CYAN, "ids": [a]})).unwrap();+ app.run("object.fill", json!({"swatch": "[Black]", "ids": [b]})).unwrap();+ app.run("selection.set", json!({"ids": [a, b]})).unwrap();+ let mut h = panel(app);+ h.get_by_label("Fill swatch").click();+ h.run_steps(3);+ let row = h.get_by_label("Tint:").rect();+ h.query_all_by(|n| n.role() == egui::accesskit::Role::TextInput && n.value().as_deref() == Some("100%"))+ .find(|n| (n.rect().center().y - row.center().y).abs() < 8.0)+ .expect("the Tint field")+ .click();+ h.run_steps(2);+ h.event(egui::Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND });+ h.event(egui::Event::Text("25".into()));+ h.key_press(egui::Key::Enter);+ h.run_steps(3);+ let doc = &h.state().session.active().unwrap().doc;+ let fill = |id: u64| doc.item(designcraft_doc::ids::ItemId(id)).unwrap().fill.clone();+ assert_eq!((fill(a).swatch.as_str(), fill(a).tint), (CYAN, 0.25));+ assert_eq!((fill(b).swatch.as_str(), fill(b).tint), ("[Black]", 0.25), "the second keeps its own swatch");+ }++ #[test]+ fn apply_to_text_colours_a_text_frames_text_not_the_frame() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Heading"})).unwrap();+ let (id, story) = (r["id"].as_u64().unwrap(), designcraft_doc::StoryId(r["story"].as_u64().unwrap()));+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ let mut h = panel(app);+ h.get_by_label("Fill swatch").click();+ h.run_steps(3);+ h.get_by_label("Text").click();+ h.run_steps(3);+ h.get_by_label(CYAN).click();+ h.run_steps(3);+ let doc = &h.state().session.active().unwrap().doc;+ assert_eq!(doc.story(story).unwrap().char_format_at(0).over.fill.as_deref(), Some(CYAN), "the text is cyan");+ assert_eq!(doc.item(designcraft_doc::ids::ItemId(id)).unwrap().fill.swatch, "[None]", "the frame isn't");+ }++ #[test]+ fn transform_flips_and_rotates_from_properties() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let id = app.run("frame.create", json!({"rect": [72, 72, 300, 200]})).unwrap()["id"].as_u64().unwrap();+ app.run("selection.set", json!({"ids": [id]})).unwrap();+ let mut h = panel(app);+ let xf = |h: &Harness<'_, DesignApp>| h.state().session.active().unwrap().doc.item(designcraft_doc::ids::ItemId(id)).unwrap().xf;+ // Flip Horizontal mirrors the frame (a negative determinant); Flip Vertical as well brings it+ // back to a half turn, as in the tutorial's petal.+ h.get_by_label("Flip Horizontal").click();+ h.run_steps(3);+ assert!(xf(&h).determinant() < 0.0, "{:?}", xf(&h));+ h.get_by_label("Flip Vertical").click();+ h.run_steps(3);+ let c = xf(&h).as_coeffs();+ assert!((c[0] + 1.0).abs() < 1e-9 && (c[3] + 1.0).abs() < 1e-9, "a half turn: {c:?}");+ let info = h.state_mut().session.execute("transform.info", &json!({})).unwrap();+ assert!((info["rotation"].as_f64().unwrap().abs() - 180.0).abs() < 1e-6, "{info}");+ // A quarter turn clockwise from there.+ h.get_by_label("Rotate 90° Clockwise").click();+ h.run_steps(3);+ let info = h.state_mut().session.execute("transform.info", &json!({})).unwrap();+ assert!((info["rotation"].as_f64().unwrap() - 90.0).abs() < 1e-6, "{info}");+ // The angle and scale fields are there.+ assert!(h.query_by(|n| n.role() == egui::accesskit::Role::TextInput && n.value().as_deref() == Some("90°")).is_some());+ }