mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-23 02:44:24 +01:00
Merge main into fix/graph-series-gradient-per-mark
This commit is contained in:
commit
78e7227358
85 files changed
+3056
-354
No files matched your search
@@ -107,7 +107,7 @@ use titlebar::opted_into_system_title_bar;
|
||||
#[cfg(windows)]
|
||||
use titlebar::set_taskbar_icon;
|
||||
#[cfg(all(test, feature = "wgpu"))]
|
||||
use titlebar::{app_draws_frame, opted_into_app_title_bar, start_frame, system_title_bar_applies};
|
||||
use titlebar::{app_draws_frame, caption_layout_from, opted_into_app_title_bar, start_frame, system_title_bar_applies};
|
||||
use titlebar::{custom_titlebar, native_options, titlebar_from_env};
|
||||
|
||||
struct App {
|
||||
@@ -367,7 +367,7 @@ fn main() -> std::process::ExitCode {
|
||||
};
|
||||
#[cfg(feature = "wgpu")]
|
||||
let crash = left_out.crash.clone();
|
||||
let custom_titlebar = custom_titlebar(saved.as_ref());
|
||||
let (custom_titlebar, caption_layout) = custom_titlebar(saved.as_ref());
|
||||
let options = native_options(custom_titlebar);
|
||||
// winit picks Wayland whenever `WAYLAND_DISPLAY` is set; Preferences › Performance › Linux
|
||||
// Display Server › X11 opens the window through XWayland instead, where file drops work (#1151),
|
||||
@@ -593,6 +593,7 @@ fn main() -> std::process::ExitCode {
|
||||
}
|
||||
app.titlebar_from_env = titlebar_from_env();
|
||||
app.custom_titlebar = custom_titlebar;
|
||||
app.caption_layout = caption_layout;
|
||||
app.desktop_frame = !custom_titlebar;
|
||||
if let Some(port) = control_port {
|
||||
let rx = control_server::start(port, cc.egui_ctx.clone());
|
||||
|
||||
@@ -220,8 +220,10 @@ fn the_app_title_bar_preference_gives_the_app_frame_on_desktop_frames() {
|
||||
}
|
||||
|
||||
/// The frame a start uses: the preference turns the desktop frame the probe chose into the app frame
|
||||
/// with the default window buttons, a probed app frame keeps its own buttons, and the desktop frame
|
||||
/// stays where the app frame is not drawn. System Title Bar takes precedence over the preference.
|
||||
/// with the default window buttons, an app frame the desktop left to the app keeps its own buttons,
|
||||
/// one that `VECTORCRAFT_TITLEBAR=app` forced or the preference kept through XWayland gets the
|
||||
/// default buttons, and the desktop frame stays
|
||||
/// where the app frame is not drawn. System Title Bar takes precedence over the preference.
|
||||
#[test]
|
||||
fn the_start_frame_applies_the_app_title_bar_preference() {
|
||||
use craft_window::{Button, Frame, Layout};
|
||||
@@ -233,9 +235,10 @@ fn the_start_frame_applies_the_app_title_bar_preference() {
|
||||
((Frame::Desktop, None, true, true), Frame::App(Layout::default())),
|
||||
((Frame::App(gnome.clone()), None, false, false), Frame::App(gnome.clone())),
|
||||
((Frame::App(gnome.clone()), None, true, false), Frame::Desktop),
|
||||
((Frame::App(gnome.clone()), None, true, true), Frame::App(gnome.clone())),
|
||||
((Frame::App(gnome.clone()), None, true, true), Frame::App(Layout::default())),
|
||||
((Frame::Desktop, Some(false), false, true), Frame::Desktop),
|
||||
((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(gnome.clone())),
|
||||
((Frame::App(gnome.clone()), Some(true), true, false), Frame::App(Layout::default())),
|
||||
((Frame::App(gnome.clone()), Some(true), false, false), Frame::App(Layout::default())),
|
||||
];
|
||||
for ((probed, overridden, forced_to_x11, opted_into_app), expected) in cases {
|
||||
let label = format!("{probed:?} {overridden:?} {forced_to_x11} {opted_into_app}");
|
||||
@@ -246,6 +249,30 @@ fn the_start_frame_applies_the_app_title_bar_preference() {
|
||||
assert!(!super::custom_titlebar_from(&both, true), "System Title Bar takes precedence over the app title bar preference");
|
||||
}
|
||||
|
||||
/// The app bar's caption buttons follow the window-button layout of the app frame on Linux and the
|
||||
/// BSDs (Close alone at the right, or all three at the left with Close outermost); the desktop frame,
|
||||
/// macOS and Windows keep all three at the right.
|
||||
#[test]
|
||||
fn the_caption_buttons_follow_the_frame_layout() {
|
||||
use craft_window::{Button, Frame, Layout};
|
||||
use vectorcraft_ui_egui::titlebar::{Caption, CaptionLayout};
|
||||
let close_only = Layout::parse("appmenu:close");
|
||||
let at_left = Layout { left: vec![Button::Close, Button::Minimize, Button::Maximize], right: vec![] };
|
||||
let split = Layout { left: vec![Button::Close], right: vec![Button::Minimize, Button::Maximize] };
|
||||
let probed = [
|
||||
(close_only, CaptionLayout { left: vec![], right: vec![Caption::Close] }),
|
||||
(at_left, CaptionLayout { left: vec![Caption::Close, Caption::Minimize, Caption::Maximize], right: vec![] }),
|
||||
(split, CaptionLayout { left: vec![Caption::Close], right: vec![Caption::Minimize, Caption::Maximize] }),
|
||||
];
|
||||
for (layout, expected) in probed {
|
||||
let shown = super::caption_layout_from(&Frame::App(layout.clone()));
|
||||
let expected = if cfg!(any(target_os = "macos", target_os = "windows")) { CaptionLayout::default() } else { expected };
|
||||
assert_eq!(shown, expected, "{layout:?}");
|
||||
}
|
||||
assert_eq!(super::caption_layout_from(&Frame::Desktop), CaptionLayout::default());
|
||||
assert_eq!(CaptionLayout::default().right, vec![Caption::Minimize, Caption::Maximize, Caption::Close]);
|
||||
}
|
||||
|
||||
/// `VECTORCRAFT_TITLEBAR` chooses the frame for the run it is set in, with System Title Bar off and
|
||||
/// on. The saved preference still decides while the variable is unset.
|
||||
#[test]
|
||||
@@ -303,7 +330,7 @@ fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
|
||||
let off = ui_state_with_prefs(serde_json::json!({"systemTitleBar": false}));
|
||||
let on = ui_state_with_prefs(serde_json::json!({"systemTitleBar": true}));
|
||||
for (saved, opted_into_system) in [(None, false), (Some(&off), false), (Some(&on), true)] {
|
||||
let custom = super::custom_titlebar(saved);
|
||||
let (custom, _) = super::custom_titlebar(saved);
|
||||
let expected = match value.as_str() {
|
||||
_ if not_read => !cfg!(target_os = "macos") && !opted_into_system,
|
||||
"app" => true,
|
||||
@@ -312,7 +339,7 @@ fn the_titlebar_variable_decides_the_frame_before_the_window_opens() {
|
||||
// `craft-window` probe decides, the same with System Title Bar off as with no saved
|
||||
// preferences.
|
||||
_ if opted_into_system => false,
|
||||
_ => super::custom_titlebar(None),
|
||||
_ => super::custom_titlebar(None).0,
|
||||
};
|
||||
assert_eq!(custom, expected, "{value}, preference {opted_into_system}");
|
||||
assert_eq!(super::native_options(custom).viewport.decorations, Some(!custom), "{value}, preference {opted_into_system}");
|
||||
|
||||
@@ -68,18 +68,45 @@ pub(crate) fn app_draws_frame(probed_app: bool, overridden: Option<bool>, forced
|
||||
}
|
||||
|
||||
/// The frame this start uses, before the System Title Bar preference is applied
|
||||
/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. A probed
|
||||
/// app frame keeps its window-button layout; an app frame the probe did not choose gets the default
|
||||
/// layout, since `custom_titlebar_from` reads only which frame it is.
|
||||
/// ([`custom_titlebar_from`]): [`app_draws_frame`] applied to the frame the probe chose. An app frame
|
||||
/// the desktop left to the app (no `VECTORCRAFT_TITLEBAR` override, not forced onto XWayland) keeps
|
||||
/// its window-button layout. An app frame turned on by `VECTORCRAFT_TITLEBAR=app` or by VectorCraft
|
||||
/// Title Bar on Every Desktop gets the default layout: on those desktops the `button-layout` key that `craft-window` reads can
|
||||
/// hold its schema default (`appmenu:close`) rather than the desktop's own buttons.
|
||||
pub(crate) fn start_frame(probed: craft_window::Frame, overridden: Option<bool>, forced_to_x11: bool, opted_into_app: bool) -> craft_window::Frame {
|
||||
let probed_app = matches!(probed, craft_window::Frame::App(_));
|
||||
match (app_draws_frame(probed_app, overridden, forced_to_x11, opted_into_app), probed) {
|
||||
(true, frame @ craft_window::Frame::App(_)) => frame,
|
||||
(true, craft_window::Frame::Desktop) => craft_window::Frame::App(craft_window::Layout::default()),
|
||||
(true, frame @ craft_window::Frame::App(_)) if overridden.is_none() && !forced_to_x11 => frame,
|
||||
(true, _) => craft_window::Frame::App(craft_window::Layout::default()),
|
||||
(false, _) => craft_window::Frame::Desktop,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the app bar puts its caption buttons for `frame`: on Linux and the BSDs, the window-button
|
||||
/// layout of an app frame, which `craft-window` reads from the desktop (the `button-layout` key of
|
||||
/// `org.gnome.desktop.wm.preferences`); otherwise all three at the right. Each list is copied in the
|
||||
/// key's order, first item leftmost, so `close,minimize,maximize:` puts Close at the left edge.
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
pub(crate) fn caption_layout_from(frame: &craft_window::Frame) -> vectorcraft_ui_egui::titlebar::CaptionLayout {
|
||||
use vectorcraft_ui_egui::titlebar::{Caption, CaptionLayout};
|
||||
let caption = |b: &craft_window::Button| match b {
|
||||
craft_window::Button::Minimize => Caption::Minimize,
|
||||
craft_window::Button::Maximize => Caption::Maximize,
|
||||
craft_window::Button::Close => Caption::Close,
|
||||
};
|
||||
match frame.layout() {
|
||||
Some(layout) => CaptionLayout { left: layout.left.iter().map(caption).collect(), right: layout.right.iter().map(caption).collect() },
|
||||
None => CaptionLayout::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// macOS and Windows: all three caption buttons at the right, whatever the probe says (see
|
||||
/// [`custom_titlebar_from`]).
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
pub(crate) fn caption_layout_from(_frame: &craft_window::Frame) -> vectorcraft_ui_egui::titlebar::CaptionLayout {
|
||||
vectorcraft_ui_egui::titlebar::CaptionLayout::default()
|
||||
}
|
||||
|
||||
/// The `craft-window` probe's answer for this process (its override variable is
|
||||
/// `VECTORCRAFT_TITLEBAR`). The probe runs once; on a Wayland session it opens a connection.
|
||||
fn probed_choice() -> &'static craft_window::Choice {
|
||||
@@ -131,7 +158,8 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
|
||||
CUSTOM_TITLEBAR && !opted_into_system
|
||||
}
|
||||
|
||||
/// Whether this start draws its own title bar. Probes the shared `craft-window` crate once (its
|
||||
/// Whether this start draws its own title bar, and where its caption buttons go
|
||||
/// ([`caption_layout_from`]). Probes the shared `craft-window` crate once (its
|
||||
/// override variable is `VECTORCRAFT_TITLEBAR`) and combines its decision with the saved System
|
||||
/// Title Bar preference, which does not apply while the variable is set to `app`, `system` or
|
||||
/// `desktop`. Call once at startup,
|
||||
@@ -142,7 +170,7 @@ pub(crate) fn custom_titlebar_from(_frame: &craft_window::Frame, opted_into_syst
|
||||
/// on X11, whose window manager draws the frame — so when XWayland is being forced, keep the native
|
||||
/// frame, the same as a real X11 session. A recognized `VECTORCRAFT_TITLEBAR` override still wins,
|
||||
/// and so does VectorCraft Title Bar on Every Desktop ([`app_draws_frame`]).
|
||||
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> bool {
|
||||
pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> (bool, vectorcraft_ui_egui::titlebar::CaptionLayout) {
|
||||
let choice = probed_choice();
|
||||
let opted_into_system = system_title_bar_applies(opted_into_system_title_bar(saved), titlebar_from_env());
|
||||
// macOS and Windows never read VectorCraft Title Bar on Every Desktop (`custom_titlebar_from`
|
||||
@@ -160,7 +188,7 @@ pub(crate) fn custom_titlebar(saved: Option<&vectorcraft_ui_egui::UiState>) -> b
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let forced_to_x11 = false;
|
||||
let frame = start_frame(choice.frame().clone(), choice.overridden(), forced_to_x11, opted_into_app);
|
||||
custom_titlebar_from(&frame, opted_into_system)
|
||||
(custom_titlebar_from(&frame, opted_into_system), caption_layout_from(&frame))
|
||||
}
|
||||
|
||||
pub(crate) fn native_options(custom_titlebar: bool) -> eframe::NativeOptions {
|
||||
|
||||
@@ -78,7 +78,11 @@ fn samples(t: &Track, step: Option<f64>) -> Vec<(Point, Vec2, f64)> {
|
||||
let pieces = (seg / step).ceil().clamp(1.0, MAX_STEPS) as usize;
|
||||
for k in 1..pieces {
|
||||
let u = k as f64 / pieces as f64;
|
||||
out.push((p.lerp(t.verts[i + 1], u), t.dirs[i], (t.cum[i] + seg * u) / len));
|
||||
let s = t.cum[i] + seg * u;
|
||||
// On a chord of a flattened curve the samples follow the smooth frame through the
|
||||
// vertices.
|
||||
let (q, tg) = if t.curved.get(i).copied().unwrap_or(false) { t.frame_in(i, u) } else { (p.lerp(t.verts[i + 1], u), t.dirs[i]) };
|
||||
out.push((q, tg, s / len));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1037,6 +1037,26 @@ fn pressed(points: Vec<(f64, f64)>) -> StrokeLayer {
|
||||
StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points }), ..stroke(1.0) }
|
||||
}
|
||||
|
||||
/// A nib that follows the pen is sampled between the vertices of the flattened path too. Along a
|
||||
/// curve those samples sit on the curve, and the outline keeps its distance from it.
|
||||
#[test]
|
||||
fn pen_driven_nib_outline_follows_the_curve_between_vertices() {
|
||||
// The top half of a circle of radius 50; a round nib 20 pt across, the same at any pressure.
|
||||
let (r, half) = (50.0, 10.0);
|
||||
let c = Point::new(r, r);
|
||||
let ring = shapes::ellipse(Rect::new(0.0, 0.0, 2.0 * r, 2.0 * r)).to_bezpath();
|
||||
let half_circle: BezPath = ring.elements().iter().take(3).copied().collect();
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &pressure_calli(20.0, 0.0), &half_circle, &pressed(vec![(0.0, 0.5), (1.0, 0.5)]));
|
||||
let mut pts = vec![];
|
||||
for n in &out {
|
||||
all_points(n, &mut pts);
|
||||
}
|
||||
// Away from the round caps at the two ends, every outline point is `half` from the curve.
|
||||
let middle = pts.iter().filter(|p| ((p.y - c.y).atan2(p.x - c.x).abs() - std::f64::consts::FRAC_PI_2).abs() <= 1.2);
|
||||
let worst = middle.map(|p| ((p.distance(c) - (r + half)).abs()).min((p.distance(c) - (r - half)).abs())).fold(0.0, f64::max);
|
||||
assert!(worst < 0.05, "an outline point strays {worst:.4} pt from the nib's reach");
|
||||
}
|
||||
|
||||
/// #852: with Size on Pressure the nib goes from size − variation at the lightest pressure to
|
||||
/// size + variation at the heaviest, along the stroke where the pen pressed.
|
||||
#[test]
|
||||
@@ -1686,6 +1706,35 @@ fn an_ordinary_stroke_is_unaffected_by_the_budget() {
|
||||
assert!(anchors(&out) < 2_000_000);
|
||||
}
|
||||
|
||||
/// A straight-sided art brush on a smooth curve draws smooth edges: they do not turn at the smooth
|
||||
/// anchors the fit puts along them.
|
||||
#[test]
|
||||
fn art_brush_edges_stay_smooth_along_a_curve() {
|
||||
for &(r, w, h, sw) in &[(100.0, 100.0, 10.0, 1.0), (300.0, 100.0, 10.0, 2.0), (30.0, 100.0, 10.0, 1.0), (2000.0, 100.0, 10.0, 1.0)] {
|
||||
// The top half of a circle, as one open path of two curves.
|
||||
let ring = shapes::ellipse(Rect::new(0.0, 0.0, 2.0 * r, 2.0 * r)).to_bezpath();
|
||||
let half_circle: BezPath = ring.elements().iter().take(3).copied().collect();
|
||||
let out = stroke_pieces(&Document::new(1.0, 1.0), &art_brush(rect_art(w, h), ArtScale::Stretch), &half_circle, &stroke(sw));
|
||||
let NodeKind::Path { path, .. } = &out[0].kind else { panic!("an art brush on a path draws a path") };
|
||||
|
||||
// The turn at each smooth anchor of the edges: the angle between the incoming and the
|
||||
// outgoing direction. Real corners (the ends of the art) turn by far more than 60°.
|
||||
let mut kink = 0.0f64;
|
||||
for sp in &path.subpaths {
|
||||
for (k, a) in sp.anchors.iter().enumerate().skip(1).take(sp.anchors.len().saturating_sub(2)) {
|
||||
let h_in = if a.h_in != a.p { a.h_in } else { sp.anchors[k - 1].p };
|
||||
let h_out = if a.h_out != a.p { a.h_out } else { sp.anchors[k + 1].p };
|
||||
let (u, v) = (a.p - h_in, h_out - a.p);
|
||||
if u.hypot() < 1e-9 || v.hypot() < 1e-9 || u.dot(v) < 0.5 * u.hypot() * v.hypot() {
|
||||
continue;
|
||||
}
|
||||
kink = kink.max(u.cross(v).atan2(u.dot(v)).abs().to_degrees());
|
||||
}
|
||||
}
|
||||
assert!(kink < 0.5, "r={r} art={w}x{h} weight {sw}: an edge turns by {kink:.3}° at a smooth anchor");
|
||||
}
|
||||
}
|
||||
|
||||
/// Anchors under `n`, and how many of them keep a handle (so the segment is a curve).
|
||||
fn anchors_and_curved(n: &Node) -> (usize, usize) {
|
||||
let NodeKind::Path { path, .. } = &n.kind else { return (0, 0) };
|
||||
|
||||
+346
-35
@@ -1,8 +1,9 @@
|
||||
//! Arc-length parameterised polylines ("tracks") that brushes lay art along.
|
||||
//!
|
||||
//! A track is one flattened subpath. `frame(s)` gives the point and unit tangent at arc length
|
||||
//! `s`; tangents are blended across the gentle vertices of flattened curves (so warped art bends
|
||||
//! smoothly) but stay discontinuous at real corners (so art folds there, like Illustrator).
|
||||
//! `s`. Along a flattened curve the frame runs on a smooth curve through the vertices, so warped
|
||||
//! art bends smoothly; along a line of the path it stays on the line. At real corners the tangent
|
||||
//! stays discontinuous, so art folds there.
|
||||
|
||||
use vectorcraft_geom::{BezPath, PathEl, Point, Vec2};
|
||||
|
||||
@@ -22,6 +23,11 @@ pub struct Track {
|
||||
pub tangents: Vec<Vec2>,
|
||||
/// Is the vertex a corner (turn > [`CORNER_DEG`])? Open ends are never corners.
|
||||
pub corner: Vec<bool>,
|
||||
/// Does the segment come from flattening a curve (rather than from a line of the path)?
|
||||
pub curved: Vec<bool>,
|
||||
/// How far (radians) a curved segment's end tangents may turn from its direction for `frame`
|
||||
/// to follow a curve through them; 0 for a line.
|
||||
turn: Vec<f64>,
|
||||
}
|
||||
|
||||
fn unit(v: Vec2) -> Vec2 {
|
||||
@@ -35,16 +41,53 @@ fn aligned(a: Vec2, b: Vec2) -> bool {
|
||||
a.dot(b) > 1.0 - 1e-12
|
||||
}
|
||||
|
||||
/// How far a vertex tangent may turn from a chord of a flattened curve, as a multiple of the
|
||||
/// flattening tolerance over the chord's length. A circular arc needs 4; the rest is slack for
|
||||
/// flattening that lands a little inside its tolerance.
|
||||
const TURN_PER_TOL: f64 = 6.0;
|
||||
|
||||
/// `t` turned by the smallest angle that brings it within `limit` radians of each `dir`. When no
|
||||
/// angle satisfies every limit, `t` turns to the middle of the gap between them.
|
||||
fn held_within(t: Vec2, limits: [Option<(Vec2, f64)>; 2]) -> Vec2 {
|
||||
let (mut lo, mut hi) = (f64::NEG_INFINITY, f64::INFINITY);
|
||||
for (d, limit) in limits.into_iter().flatten() {
|
||||
let to = t.cross(d).atan2(t.dot(d));
|
||||
lo = lo.max(to - limit);
|
||||
hi = hi.min(to + limit);
|
||||
}
|
||||
let turn = if lo <= hi { 0f64.max(lo).min(hi) } else { (lo + hi) / 2.0 };
|
||||
if turn == 0.0 || !turn.is_finite() {
|
||||
return t;
|
||||
}
|
||||
let (sin, cos) = turn.sin_cos();
|
||||
Vec2::new(t.x * cos - t.y * sin, t.x * sin + t.y * cos)
|
||||
}
|
||||
|
||||
/// Left-hand normal in y-down document space (for a path running +x it points +y).
|
||||
pub fn normal(t: Vec2) -> Vec2 {
|
||||
Vec2::new(-t.y, t.x)
|
||||
}
|
||||
|
||||
impl Track {
|
||||
fn new(mut pts: Vec<Point>, closed: bool) -> Option<Track> {
|
||||
pts.dedup_by(|a, b| a.distance(*b) < 1e-9);
|
||||
/// `raw` pairs each vertex with the tolerance the segment ending at it was flattened with
|
||||
/// when it comes from a curve, and `None` when it is a line of the path.
|
||||
fn new(raw: Vec<(Point, Option<f64>)>, closed: bool) -> Option<Track> {
|
||||
let mut pts: Vec<Point> = Vec::with_capacity(raw.len());
|
||||
// `ends_curve[k]`: the flattening tolerance of the segment ending at vertex `k`, when it
|
||||
// comes from a curve.
|
||||
let mut ends_curve: Vec<Option<f64>> = Vec::with_capacity(raw.len());
|
||||
for (p, c) in raw {
|
||||
// A duplicate vertex adds no segment, so it is dropped with its tolerance.
|
||||
if pts.last().is_some_and(|q| q.distance(p) < 1e-9) {
|
||||
continue;
|
||||
}
|
||||
pts.push(p);
|
||||
ends_curve.push(c);
|
||||
}
|
||||
let mut closing_curve = None;
|
||||
if closed && pts.len() > 2 && pts[0].distance(pts[pts.len() - 1]) < 1e-9 {
|
||||
pts.pop();
|
||||
closing_curve = ends_curve.pop().flatten();
|
||||
}
|
||||
if pts.len() < 2 {
|
||||
return None;
|
||||
@@ -52,8 +95,11 @@ impl Track {
|
||||
let closed = closed && pts.len() > 2;
|
||||
if closed {
|
||||
pts.push(pts[0]);
|
||||
ends_curve.push(closing_curve);
|
||||
}
|
||||
let nseg = pts.len() - 1;
|
||||
let curve_tol: Vec<Option<f64>> = (0..nseg).map(|i| ends_curve.get(i + 1).copied().flatten()).collect();
|
||||
let curved: Vec<bool> = curve_tol.iter().map(Option::is_some).collect();
|
||||
let dirs: Vec<Vec2> = (0..nseg).map(|i| unit(pts[i + 1] - pts[i])).collect();
|
||||
let mut cum = vec![0.0];
|
||||
for i in 0..nseg {
|
||||
@@ -62,34 +108,78 @@ impl Track {
|
||||
let mut tangents = Vec::with_capacity(nseg + 1);
|
||||
let mut corner = Vec::with_capacity(nseg + 1);
|
||||
let cos_limit = CORNER_DEG.to_radians().cos();
|
||||
let seg = |i: usize| (dirs[i], cum[i + 1] - cum[i], curved[i]);
|
||||
for i in 0..=nseg {
|
||||
let incoming = if i > 0 {
|
||||
Some(dirs[i - 1])
|
||||
Some(seg(i - 1))
|
||||
} else if closed {
|
||||
Some(dirs[nseg - 1])
|
||||
Some(seg(nseg - 1))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let outgoing = if i < nseg {
|
||||
Some(dirs[i])
|
||||
Some(seg(i))
|
||||
} else if closed {
|
||||
Some(dirs[0])
|
||||
Some(seg(0))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match (incoming, outgoing) {
|
||||
(Some(a), Some(b)) => {
|
||||
(Some((a, la, ca)), Some((b, lb, cb))) => {
|
||||
corner.push(a.dot(b) < cos_limit);
|
||||
tangents.push(unit(a + b));
|
||||
tangents.push(match (ca, cb) {
|
||||
// Between two chords of a flattened curve: each direction weighted by the
|
||||
// length of the other chord, which is the tangent of the circle through
|
||||
// the vertex and its two neighbors.
|
||||
(true, true) => unit(a * lb + b * la),
|
||||
// Where a line of the path meets a curve, the line's direction.
|
||||
(false, true) => a,
|
||||
(true, false) => b,
|
||||
(false, false) => unit(a + b),
|
||||
});
|
||||
}
|
||||
(a, b) => {
|
||||
// An end of an open track (both `None` only for a track without segments).
|
||||
corner.push(false);
|
||||
tangents.push(a.or(b).unwrap_or(Vec2::new(1.0, 0.0)));
|
||||
tangents.push(a.or(b).map_or(Vec2::new(1.0, 0.0), |(d, _, _)| d));
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Track { verts: pts, cum, closed, dirs, tangents, corner })
|
||||
// An open track's end on a curve continues the bend of its last chord: the tangent there
|
||||
// is the neighboring vertex's tangent mirrored about the chord, as on the circle through
|
||||
// the last three vertices.
|
||||
if !closed && nseg >= 2 {
|
||||
for (end, inner, d) in [(0, 1, dirs[0]), (nseg, nseg - 1, dirs[nseg - 1])] {
|
||||
let (s_end, s_inner) = if end == 0 { (0, 1) } else { (nseg - 1, nseg - 2) };
|
||||
if !corner[inner] && curved[s_end] && curved[s_inner] {
|
||||
let t = tangents[inner];
|
||||
tangents[end] = unit(d * (2.0 * d.dot(t)) - t);
|
||||
}
|
||||
}
|
||||
}
|
||||
// A curve lies within its flattening tolerance `tol` of each of its chords, so its tangent
|
||||
// at a vertex turns only a little from a chord: at most about `4 * tol / len` on a
|
||||
// circular arc. Next to a long chord the estimates above can turn much further (a
|
||||
// straight curve element beside a tight bend), and `frame` would then bow off the chord.
|
||||
// Between curved chords, each vertex tangent is held within `TURN_PER_TOL * tol / len` of
|
||||
// both chords. Where a line meets a curve the tangent stays the line's direction, and a
|
||||
// curved chord whose end tangents turn further than that from it keeps to the chord.
|
||||
let turn: Vec<f64> = (0..nseg)
|
||||
.map(|j| match curve_tol.get(j) {
|
||||
Some(Some(tol)) => (TURN_PER_TOL * tol / (cum[j + 1] - cum[j]).max(1e-12)).min(1.0).asin(),
|
||||
_ => 0.0,
|
||||
})
|
||||
.collect();
|
||||
for (i, t) in tangents.iter_mut().enumerate() {
|
||||
let incoming = if i > 0 { Some(i - 1) } else { closed.then_some(nseg - 1) };
|
||||
let outgoing = if i < nseg { Some(i) } else { closed.then_some(0) };
|
||||
let sides = [incoming, outgoing];
|
||||
if corner[i] || sides.iter().flatten().any(|&j| !curved[j]) {
|
||||
continue;
|
||||
}
|
||||
*t = held_within(*t, sides.map(|j| j.map(|j| (dirs[j], turn[j]))));
|
||||
}
|
||||
Some(Track { verts: pts, cum, closed, dirs, tangents, corner, curved, turn })
|
||||
}
|
||||
|
||||
pub fn len(&self) -> f64 {
|
||||
@@ -135,11 +225,11 @@ impl Track {
|
||||
let n = self.segments();
|
||||
let s = if self.closed && l > 0.0 { s.rem_euclid(l) } else { s };
|
||||
if s <= 0.0 && !self.closed {
|
||||
let t = self.dirs[0];
|
||||
let t = self.tangents[0];
|
||||
return (self.verts[0] + t * s, t);
|
||||
}
|
||||
if s >= l && !self.closed {
|
||||
let t = self.dirs[n - 1];
|
||||
let t = self.tangents[n];
|
||||
return (self.verts[n] + t * (s - l), t);
|
||||
}
|
||||
// Binary search the segment.
|
||||
@@ -149,10 +239,44 @@ impl Track {
|
||||
};
|
||||
let seg = self.cum[i + 1] - self.cum[i];
|
||||
let u = if seg > 1e-12 { ((s - self.cum[i]) / seg).clamp(0.0, 1.0) } else { 0.0 };
|
||||
let p = self.verts[i].lerp(self.verts[i + 1], u);
|
||||
let t0 = if self.corner[i] { self.dirs[i] } else { self.tangents[i] };
|
||||
let t1 = if self.corner[i + 1] { self.dirs[i] } else { self.tangents[i + 1] };
|
||||
(p, unit(t0 + (t1 - t0) * u))
|
||||
self.frame_in(i, u)
|
||||
}
|
||||
|
||||
/// Segment `i`'s direction and the tangents [`Self::frame`] uses at its two ends: the vertex
|
||||
/// tangents, or the segment's direction at a corner.
|
||||
fn end_tangents(&self, i: usize) -> Option<(Vec2, Vec2, Vec2)> {
|
||||
let (&d, &c0, &c1, &t0, &t1) =
|
||||
(self.dirs.get(i)?, self.corner.get(i)?, self.corner.get(i + 1)?, self.tangents.get(i)?, self.tangents.get(i + 1)?);
|
||||
Some((d, if c0 { d } else { t0 }, if c1 { d } else { t1 }))
|
||||
}
|
||||
|
||||
/// Point and unit tangent at the fraction `u` (0 to 1) of segment `i`, as [`Self::frame`]
|
||||
/// gives them. `i` must be below [`Self::segments`].
|
||||
pub fn frame_in(&self, i: usize, u: f64) -> (Point, Vec2) {
|
||||
let (Some(&p0), Some(&p1), Some((d, t0, t1))) = (self.verts.get(i), self.verts.get(i + 1), self.end_tangents(i)) else {
|
||||
return (self.verts.last().copied().unwrap_or(Point::ZERO), Vec2::new(1.0, 0.0));
|
||||
};
|
||||
let seg = self.cum.get(i + 1).zip(self.cum.get(i)).map_or(0.0, |(b, a)| b - a);
|
||||
if aligned(t0, d) && aligned(t1, d) {
|
||||
return (p0.lerp(p1, u), d);
|
||||
}
|
||||
// The tangents may turn this far from a curved chord, a little beyond it for rounding.
|
||||
let within = self.turn.get(i).map_or(-1.0, |a| a.sin() + 1e-9);
|
||||
let bends = |t: Vec2| t.dot(d) <= 0.0 || t.cross(d).abs() > within;
|
||||
if !self.curved.get(i).copied().unwrap_or(false) || bends(t0) || bends(t1) {
|
||||
// A line of the path, or a curved chord at a sharper turn than the curve can make
|
||||
// there: the point stays on it, and the tangent turns across it toward the vertex
|
||||
// tangents.
|
||||
return (p0.lerp(p1, u), unit(t0 + (t1 - t0) * u));
|
||||
}
|
||||
// On a chord of a flattened curve the frame follows the cubic through both vertices with
|
||||
// their tangents, at the chord's length per unit of `u`. Its position and tangent then
|
||||
// meet those of the next segment at each vertex.
|
||||
let (u2, u3) = (u * u, u * u * u);
|
||||
let (m0, m1) = (t0 * seg, t1 * seg);
|
||||
let p = p0 + (p1 - p0) * (3.0 * u2 - 2.0 * u3) + m0 * (u3 - 2.0 * u2 + u) + m1 * (u3 - u2);
|
||||
let dp = (p1 - p0) * (6.0 * u - 6.0 * u2) + m0 * (3.0 * u2 - 4.0 * u + 1.0) + m1 * (3.0 * u2 - 2.0 * u);
|
||||
(p, unit(dp))
|
||||
}
|
||||
|
||||
/// The point at arc length `s`, offset `d` along the left normal.
|
||||
@@ -183,8 +307,8 @@ impl Track {
|
||||
if self.closed && (lo < -1e-9 || hi > l + 1e-9) {
|
||||
return false;
|
||||
}
|
||||
// Past an open track's ends `frame` extrapolates along the end segment's direction, so
|
||||
// those segments are part of the span too.
|
||||
// Past an open track's ends `frame` extrapolates along the end tangent, which is checked
|
||||
// against the end segment's direction below, so those segments are part of the span too.
|
||||
let ends = [(!self.closed && lo < 0.0).then_some(0), (!self.closed && hi > l).then(|| n - 1)];
|
||||
let touched = (0..n).filter(|&i| {
|
||||
let (a, b) = (self.cum.get(i), self.cum.get(i + 1));
|
||||
@@ -193,9 +317,7 @@ impl Track {
|
||||
let mut dir: Option<Vec2> = None;
|
||||
let mut any = false;
|
||||
for i in touched.chain(ends.into_iter().flatten()) {
|
||||
let (Some(&d), Some(&t0), Some(&t1), Some(&c0), Some(&c1)) =
|
||||
(self.dirs.get(i), self.tangents.get(i), self.tangents.get(i + 1), self.corner.get(i), self.corner.get(i + 1))
|
||||
else {
|
||||
let Some((d, t0, t1)) = self.end_tangents(i) else {
|
||||
return false;
|
||||
};
|
||||
if dir.is_some_and(|first: Vec2| !aligned(first, d)) {
|
||||
@@ -203,11 +325,11 @@ impl Track {
|
||||
}
|
||||
dir = Some(d);
|
||||
any = true;
|
||||
// `frame` blends the two vertex tangents across the segment unless the vertex is a
|
||||
// corner, where it uses the segment's own direction. So a neighbour outside the span
|
||||
// can still bend the tangent inside it, and checking the directions alone would miss
|
||||
// that: segments d, d, e leave vertex 2's tangent at unit(d + e).
|
||||
if !(c0 || aligned(t0, d)) || !(c1 || aligned(t1, d)) {
|
||||
// `frame` blends the two end tangents across a line, and follows a curve through them
|
||||
// on a curved chord. So a neighbour outside the span can still bend the tangent
|
||||
// inside it, and checking the directions alone would miss that: segments d, d, e
|
||||
// leave vertex 2's tangent at unit(d + e).
|
||||
if !aligned(t0, d) || !aligned(t1, d) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -220,9 +342,10 @@ const MAX_FLATTENED: usize = 4_000_000;
|
||||
|
||||
/// Flatten `bp` into tracks (one per subpath) with `tol` accuracy.
|
||||
pub fn tracks(bp: &BezPath, tol: f64) -> Vec<Track> {
|
||||
let tol = tol.max(1e-4);
|
||||
let mut out = vec![];
|
||||
let mut cur: Vec<Point> = vec![];
|
||||
let flush = |cur: &mut Vec<Point>, closed: bool, out: &mut Vec<Track>| {
|
||||
let mut cur: Vec<(Point, Option<f64>)> = vec![];
|
||||
let flush = |cur: &mut Vec<(Point, Option<f64>)>, closed: bool, out: &mut Vec<Track>| {
|
||||
if let Some(t) = Track::new(std::mem::take(cur), closed) {
|
||||
out.push(t);
|
||||
}
|
||||
@@ -236,19 +359,40 @@ pub fn tracks(bp: &BezPath, tol: f64) -> Vec<Track> {
|
||||
return out;
|
||||
}
|
||||
let mut els = vec![];
|
||||
// When the element being flattened is a curve, the tolerance `flatten` uses for it: `flatten`
|
||||
// pulls each element before it reports that element's lines, and raises the tolerance of a
|
||||
// long curve as `vectorcraft_geom::flatten` describes.
|
||||
let in_curve = std::cell::Cell::new(None);
|
||||
let (last, start) = (std::cell::Cell::new(Point::ZERO), std::cell::Cell::new(Point::ZERO));
|
||||
let source = bp.iter().inspect(|el| {
|
||||
let from = last.get();
|
||||
let (curve, to) = match *el {
|
||||
PathEl::MoveTo(p) => {
|
||||
start.set(p);
|
||||
(None, p)
|
||||
}
|
||||
PathEl::LineTo(p) => (None, p),
|
||||
PathEl::QuadTo(a, p) => (Some(from.distance(a) + a.distance(p)), p),
|
||||
PathEl::CurveTo(a, b, p) => (Some(from.distance(a) + a.distance(b) + b.distance(p)), p),
|
||||
PathEl::ClosePath => (None, start.get()),
|
||||
};
|
||||
last.set(to);
|
||||
let per = vectorcraft_geom::MAX_FLATTEN_PER_CURVE * vectorcraft_geom::MAX_FLATTEN_PER_CURVE;
|
||||
in_curve.set(curve.map(|length| if length.is_finite() { tol.max(length / per) } else { f64::INFINITY }));
|
||||
});
|
||||
// Guarded: kurbo works out every subdivision of a curve even when the callback drops them.
|
||||
vectorcraft_geom::flatten(bp.iter(), tol.max(1e-4), |el| {
|
||||
vectorcraft_geom::flatten(source, tol, |el| {
|
||||
if els.len() < MAX_FLATTENED {
|
||||
els.push(el);
|
||||
els.push((el, in_curve.get()));
|
||||
}
|
||||
});
|
||||
for el in els {
|
||||
for (el, from_curve) in els {
|
||||
match el {
|
||||
PathEl::MoveTo(p) => {
|
||||
flush(&mut cur, false, &mut out);
|
||||
cur.push(p);
|
||||
cur.push((p, None));
|
||||
}
|
||||
PathEl::LineTo(p) => cur.push(p),
|
||||
PathEl::LineTo(p) => cur.push((p, from_curve)),
|
||||
PathEl::ClosePath => flush(&mut cur, true, &mut out),
|
||||
_ => {}
|
||||
}
|
||||
@@ -368,6 +512,173 @@ mod tests {
|
||||
assert_eq!(t.map(110.0, 0.0), Point::new(110.0, 0.0));
|
||||
}
|
||||
|
||||
/// Between two lines that meet at a gentle turn, the frame stays on the lines: only the chords
|
||||
/// of a flattened curve are smoothed. Where a line meets a curve at a gentle turn, the frame
|
||||
/// stays on the line with the line's direction, and its tangent does not jump at the join.
|
||||
#[test]
|
||||
fn a_polylines_frame_stays_on_its_lines() {
|
||||
// A line, then a line or a nearly straight curve at a 20° turn, below the corner angle, so
|
||||
// the vertex is not a corner.
|
||||
let turn = 20f64.to_radians();
|
||||
let (c, s) = (100.0 * turn.cos(), 100.0 * turn.sin());
|
||||
for curve in [false, true] {
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((0.0, 0.0));
|
||||
bp.line_to((100.0, 0.0));
|
||||
if curve {
|
||||
bp.curve_to((100.0 + c / 3.0, s / 3.0 + 0.5), (100.0 + 2.0 * c / 3.0, 2.0 * s / 3.0 + 0.5), (100.0 + c, s));
|
||||
} else {
|
||||
bp.line_to((100.0 + c, s));
|
||||
}
|
||||
let t = &tracks(&bp, 0.05)[0];
|
||||
for at in [10.0, 30.0, 50.0, 70.0, 90.0] {
|
||||
let (p, tg) = t.frame(at);
|
||||
assert!(p.y.abs() < 1e-9 && (p.x - at).abs() < 1e-9, "curve {curve}: at {at} the frame left the first line: {p:?}");
|
||||
if curve {
|
||||
assert!(tg.y.abs() < 1e-12, "at {at} the line's tangent turned toward the curve: {tg:?}");
|
||||
}
|
||||
}
|
||||
if curve {
|
||||
// The curve's first chord keeps to the chord rather than bending toward the line.
|
||||
let (a, b) = (t.cum[1], t.cum[2]);
|
||||
let (p, q) = (t.verts[1], t.verts[2]);
|
||||
let mid = t.frame((a + b) / 2.0).0;
|
||||
assert!((mid - p.midpoint(q)).hypot() < 1e-9, "the first curve chord bows: {mid:?}");
|
||||
}
|
||||
let (before, after) = (t.frame(100.0 - 1e-7).1, t.frame(100.0 + 1e-7).1);
|
||||
assert!(before.dot(after) > 1.0 - 1e-9, "curve {curve}: the tangent jumps at the join: {before:?} {after:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A curve of no length between two lines leaves them lines.
|
||||
#[test]
|
||||
fn a_curve_of_no_length_leaves_a_line_a_line() {
|
||||
let turn = 20f64.to_radians();
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((0.0, 0.0));
|
||||
bp.line_to((100.0, 0.0));
|
||||
bp.curve_to((100.0, 0.0), (100.0, 0.0), (100.0, 0.0));
|
||||
bp.line_to((100.0 + 100.0 * turn.cos(), 100.0 * turn.sin()));
|
||||
let t = &tracks(&bp, 0.05)[0];
|
||||
assert!(t.curved.iter().all(|c| !c), "no segment is a curve: {:?}", t.curved);
|
||||
for at in [10.0, 50.0, 90.0] {
|
||||
let (p, _) = t.frame(at);
|
||||
assert!(p.y.abs() < 1e-9 && (p.x - at).abs() < 1e-9, "at {at} the frame left the first line: {p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a line joins a curve smoothly, the line keeps its direction up to the join.
|
||||
#[test]
|
||||
fn a_line_into_a_smooth_curve_keeps_its_direction() {
|
||||
// A line along y = 0 into a quarter circle of radius 50 that starts along +x.
|
||||
let r = 50.0;
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((-100.0, 0.0));
|
||||
bp.line_to((0.0, 0.0));
|
||||
bp.curve_to((r * K, 0.0), (r, r - r * K), (r, r));
|
||||
let t = &tracks(&bp, 0.05)[0];
|
||||
for s in [10.0, 50.0, 90.0, 99.0] {
|
||||
let (p, tg) = t.frame(s);
|
||||
assert!(p.y.abs() < 1e-9 && tg.y.abs() < 1e-9, "at {s} the line's frame turned: {p:?} {tg:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The handle length of a cubic quarter circle.
|
||||
const K: f64 = 0.552_284_749_8;
|
||||
|
||||
/// A curve element whose handles lie on its chord is a line drawn as a curve. Next to a tight
|
||||
/// bend, at either end of a track, the frame along it stays within the flattening tolerance
|
||||
/// of the line.
|
||||
#[test]
|
||||
fn a_straight_curve_element_beside_a_tight_bend_stays_on_its_line() {
|
||||
let tol = 0.05;
|
||||
for bend_first in [false, true] {
|
||||
// A 200 pt line along y = 0 drawn as a cubic, joined smoothly to a quarter circle of
|
||||
// radius 5 that turns toward +y.
|
||||
let mut bp = BezPath::new();
|
||||
if bend_first {
|
||||
bp.move_to((-5.0, -5.0));
|
||||
bp.curve_to((-5.0, -5.0 + 5.0 * K), (-5.0 * K, 0.0), (0.0, 0.0));
|
||||
bp.curve_to((50.0, 0.0), (150.0, 0.0), (200.0, 0.0));
|
||||
} else {
|
||||
bp.move_to((0.0, 0.0));
|
||||
bp.curve_to((50.0, 0.0), (150.0, 0.0), (200.0, 0.0));
|
||||
bp.curve_to((200.0 + 5.0 * K, 0.0), (205.0, 5.0 - 5.0 * K), (205.0, 5.0));
|
||||
}
|
||||
let t = &tracks(&bp, tol)[0];
|
||||
// The bend lies outside 0 <= x <= 200, so every frame point in that range is on the
|
||||
// line's stretch of the track.
|
||||
let on_line: Vec<(Point, Vec2)> =
|
||||
(0..=2000).map(|k| t.frame(t.len() * k as f64 / 2000.0)).filter(|(p, _)| (0.0..=200.0).contains(&p.x)).collect();
|
||||
let worst = on_line.iter().map(|(p, _)| p.y.abs()).fold(0.0, f64::max);
|
||||
assert!(worst <= 2.0 * tol, "bend first {bend_first}: the frame strays {worst:.4} pt off the line");
|
||||
// Along the line the tangent turns by no more than the line's flattening allows.
|
||||
let lean = on_line.iter().map(|(_, tg)| tg.y.abs()).fold(0.0, f64::max);
|
||||
assert!(lean <= 0.01, "bend first {bend_first}: the tangent turns {lean:.4} off the line");
|
||||
}
|
||||
}
|
||||
|
||||
/// A curve long enough that flattening raises its tolerance still has its frame follow the
|
||||
/// curve between the vertices, not the chords.
|
||||
#[test]
|
||||
fn a_long_curve_flattened_coarser_is_still_followed() {
|
||||
// A line along y = 0 into a cubic quarter circle of radius 5,000,000 that starts along +x.
|
||||
let r = 5.0e6;
|
||||
let curve = kurbo::CubicBez::new((0.0, 0.0), (r * K, 0.0), (r, r - r * K), (r, r));
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((-100.0, 0.0));
|
||||
bp.line_to((0.0, 0.0));
|
||||
bp.curve_to(curve.p1, curve.p2, curve.p3);
|
||||
let t = &tracks(&bp, 0.05)[0];
|
||||
let worst = (1..400)
|
||||
.map(|k| t.frame(100.0 + (t.len() - 100.0) * k as f64 / 400.0).0)
|
||||
.map(|p| kurbo::ParamCurveNearest::nearest(&curve, p, 1e-9).distance_sq.sqrt())
|
||||
.fold(0.0, f64::max);
|
||||
assert!(worst < 0.05, "the frame strays {worst:.4} pt from the curve");
|
||||
}
|
||||
|
||||
/// A closed curve is smooth across its seam: the frame stays on the circle and at right angles
|
||||
/// to its radius all the way round, the start included.
|
||||
#[test]
|
||||
fn a_closed_curves_frame_is_smooth_across_its_seam() {
|
||||
let (r, tol) = (50.0, 0.05);
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((r, 0.0));
|
||||
bp.curve_to((r, r * K), (r * K, r), (0.0, r));
|
||||
bp.curve_to((-r * K, r), (-r, r * K), (-r, 0.0));
|
||||
bp.curve_to((-r, -r * K), (-r * K, -r), (0.0, -r));
|
||||
bp.curve_to((r * K, -r), (r, -r * K), (r, 0.0));
|
||||
bp.close_path();
|
||||
let t = &tracks(&bp, tol)[0];
|
||||
assert!(t.closed && t.curved.iter().all(|c| *c), "every chord of the circle is a chord of a curve");
|
||||
for k in -20..=20 {
|
||||
let (p, tg) = t.frame(k as f64 * 0.37);
|
||||
let radial = p.to_vec2() / p.to_vec2().hypot();
|
||||
assert!((p.to_vec2().hypot() - r).abs() <= tol, "at {k} the frame is off the circle: {p:?}");
|
||||
assert!(tg.dot(radial).abs() < 0.5f64.to_radians().sin(), "at {k} the tangent leans off the circle: {tg:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A closed path whose last side is the implicit line back to the start keeps that line
|
||||
/// straight.
|
||||
#[test]
|
||||
fn an_implicit_closing_line_is_not_a_curve() {
|
||||
let r = 50.0;
|
||||
let mut bp = BezPath::new();
|
||||
bp.move_to((r, 0.0));
|
||||
bp.curve_to((r, r * K), (r * K, r), (0.0, r));
|
||||
bp.curve_to((-r * K, r), (-r, r * K), (-r, 0.0));
|
||||
bp.close_path();
|
||||
let t = &tracks(&bp, 0.05)[0];
|
||||
assert!(t.closed);
|
||||
assert_eq!(t.curved.last(), Some(&false), "the closing line is a line");
|
||||
let n = t.segments();
|
||||
for u in [0.1, 0.5, 0.9] {
|
||||
let (p, _) = t.frame(t.cum[n - 1] + (t.cum[n] - t.cum[n - 1]) * u);
|
||||
assert!(p.y.abs() < 1e-9, "the frame leaves the closing line: {p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_square_has_four_corners() {
|
||||
let mut bp = BezPath::new();
|
||||
|
||||
@@ -183,8 +183,8 @@ impl Document {
|
||||
self.layers.retain(|l| !l.is_ruler_guide());
|
||||
gone -= self.layers.len();
|
||||
for l in &mut self.layers {
|
||||
if layer_untidy(l) {
|
||||
gone += tidy_layer(Arc::make_mut(l));
|
||||
if let Some(found) = untidy(l, &Node::is_ruler_guide) {
|
||||
gone += tidy_layer(Arc::make_mut(l), found);
|
||||
}
|
||||
}
|
||||
let others = self
|
||||
@@ -198,8 +198,8 @@ impl Document {
|
||||
if root.is_ruler_guide() {
|
||||
*root = Arc::new(Node::group(root.id, vec![]));
|
||||
gone += 1;
|
||||
} else if any_guide(root) {
|
||||
gone += drop_guides_below(Arc::make_mut(root));
|
||||
} else if let Some(found) = guides_below(root, &Node::is_ruler_guide) {
|
||||
gone += drop_guides_below(Arc::make_mut(root), found);
|
||||
}
|
||||
}
|
||||
gone
|
||||
@@ -272,8 +272,8 @@ impl Document {
|
||||
return;
|
||||
}
|
||||
for l in &mut self.layers {
|
||||
if l.holds_ruler_guides() {
|
||||
Arc::make_mut(l).strip_ruler_guides();
|
||||
if let Some(held) = picked_in_layers(l, &Node::is_ruler_guide) {
|
||||
drop_picked(l, held);
|
||||
}
|
||||
}
|
||||
self.saved_guides.extend(guides);
|
||||
@@ -347,16 +347,14 @@ impl Document {
|
||||
/// saved guide whose layer is gone opens. Returns the removed node, without the guides.
|
||||
pub fn remove_edit_layer(&mut self, id: NodeId) -> Result<Arc<Node>, crate::DocError> {
|
||||
let mut layer = self.remove(id)?;
|
||||
if !layer.holds_ruler_guides() {
|
||||
return Ok(layer);
|
||||
}
|
||||
let Some(held) = picked_in_layers(&layer, &Node::is_ruler_guide) else { return Ok(layer) };
|
||||
let mut guides = vec![];
|
||||
layer.walk(&mut |c| {
|
||||
if c.is_ruler_guide() {
|
||||
guides.push(Arc::new(c.clone()));
|
||||
}
|
||||
});
|
||||
Arc::make_mut(&mut layer).strip_ruler_guides();
|
||||
drop_picked(&mut layer, held);
|
||||
let home = self.default_layer().unwrap_or_else(|| self.add_layer(None));
|
||||
self.children_mut(Some(home))?.extend(guides);
|
||||
Ok(layer)
|
||||
@@ -418,21 +416,11 @@ impl Document {
|
||||
if gone.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
fn drop(layer: &mut Arc<Node>, gone: &HashSet<NodeId>) {
|
||||
fn holds(n: &Node, gone: &HashSet<NodeId>) -> bool {
|
||||
n.is_layer() && n.children().is_some_and(|ch| ch.iter().any(|c| gone.contains(&c.id) || holds(c, gone)))
|
||||
}
|
||||
if !holds(layer, gone) {
|
||||
return;
|
||||
}
|
||||
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
|
||||
ch.retain(|c| !(c.is_ruler_guide() && gone.contains(&c.id)));
|
||||
for c in ch.iter_mut().filter(|c| c.is_layer()) {
|
||||
drop(c, gone);
|
||||
}
|
||||
}
|
||||
let pick = |n: &Node| n.is_ruler_guide() && gone.contains(&n.id);
|
||||
for l in &mut self.layers {
|
||||
drop(l, &gone);
|
||||
if let Some(held) = picked_in_layers(l, &pick) {
|
||||
drop_picked(l, held);
|
||||
}
|
||||
}
|
||||
sel.guides.retain(|id| !gone.contains(id));
|
||||
if sel.key_guide.is_some_and(|k| gone.contains(&k)) {
|
||||
@@ -444,29 +432,11 @@ impl Document {
|
||||
/// Change the line of every ruler guide on artboard `id` with `f` (whether it is vertical, its
|
||||
/// position).
|
||||
fn edit_artboard_guides(&mut self, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
|
||||
fn visit(layer: &mut Arc<Node>, id: u32, f: &mut impl FnMut(bool, &mut f64)) {
|
||||
fn holds(n: &Node, id: u32) -> bool {
|
||||
n.is_layer()
|
||||
&& n.children().is_some_and(|ch| {
|
||||
ch.iter().any(|c| matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) || holds(c, id))
|
||||
})
|
||||
}
|
||||
if !holds(layer, id) {
|
||||
return;
|
||||
}
|
||||
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
|
||||
for c in ch.iter_mut() {
|
||||
if matches!(c.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id) {
|
||||
if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
|
||||
f(*vertical, pos);
|
||||
}
|
||||
} else if c.is_layer() {
|
||||
visit(c, id, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
let pick = |n: &Node| matches!(n.kind, NodeKind::RulerGuide { artboard: Some(a), .. } if a == id);
|
||||
for l in &mut self.layers {
|
||||
visit(l, id, f);
|
||||
if let Some(held) = picked_in_layers(l, &pick) {
|
||||
edit_picked(l, held, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -580,65 +550,172 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `n`, or anything below it (opacity-mask art included), hold a ruler guide?
|
||||
fn any_guide(n: &Node) -> bool {
|
||||
let mut any = false;
|
||||
crate::swatches::walk_with_masks(n, &mut |m| any |= m.is_ruler_guide());
|
||||
any
|
||||
/// What a walk picked in a node: its children by index in order, each with what was picked
|
||||
/// inside it, and what was picked in its opacity-mask art. Empty for a node picked itself.
|
||||
#[derive(Debug, Default)]
|
||||
struct Picked {
|
||||
children: Vec<(usize, Picked)>,
|
||||
mask: Option<Box<Picked>>,
|
||||
}
|
||||
|
||||
/// Remove every ruler guide below `n`, in its members and its opacity-mask art (`n` itself
|
||||
/// stays). Mask art that is a ruler guide becomes an empty group. Returns how many went.
|
||||
fn drop_guides_below(n: &mut Node) -> usize {
|
||||
let mut gone = drop_mask_guides(n);
|
||||
if let Some(ch) = n.children_mut() {
|
||||
let before = ch.len();
|
||||
ch.retain(|c| !c.is_ruler_guide());
|
||||
gone += before - ch.len();
|
||||
for c in ch.iter_mut().filter(|c| any_guide(c)) {
|
||||
gone += drop_guides_below(Arc::make_mut(c));
|
||||
impl Picked {
|
||||
fn is_empty(&self) -> bool {
|
||||
self.children.is_empty() && self.mask.is_none()
|
||||
}
|
||||
|
||||
/// `self`, or `None` when nothing was picked.
|
||||
fn some(self) -> Option<Self> {
|
||||
(!self.is_empty()).then_some(self)
|
||||
}
|
||||
}
|
||||
|
||||
/// The children of `n`, if it is a layer, that `pick` picks (with nothing inside), and its
|
||||
/// sublayers holding one (with what they hold), or `None` when it holds none. `pick` looks at
|
||||
/// each child of the layers once.
|
||||
fn picked_in_layers(n: &Node, pick: &impl Fn(&Node) -> bool) -> Option<Picked> {
|
||||
if !n.is_layer() {
|
||||
return None;
|
||||
}
|
||||
let children = n
|
||||
.children()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.enumerate()
|
||||
.filter_map(|(i, c)| if pick(c) { Some((i, Picked::default())) } else { picked_in_layers(c, pick).map(|p| (i, p)) })
|
||||
.collect();
|
||||
Picked { children, mask: None }.some()
|
||||
}
|
||||
|
||||
/// Remove the children of `layer` and of its sublayers that [`picked_in_layers`] picked (`held`).
|
||||
/// Only the layers holding one are copied, and only those are visited.
|
||||
fn drop_picked(layer: &mut Arc<Node>, held: Picked) {
|
||||
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
|
||||
let mut held = held.children.into_iter().peekable();
|
||||
let mut next = 0;
|
||||
ch.retain_mut(|c| {
|
||||
let at = next;
|
||||
next += 1;
|
||||
let Some((_, inner)) = held.next_if(|(i, _)| *i == at) else { return true };
|
||||
// A sublayer holds something; a child picked itself has nothing inside.
|
||||
if inner.is_empty() {
|
||||
return false;
|
||||
}
|
||||
drop_picked(c, inner);
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
/// Change with `f` (whether it is vertical, its position) the line of each ruler guide of `layer`
|
||||
/// and of its sublayers that [`picked_in_layers`] picked (`held`), in the order they lie in. Only
|
||||
/// the layers holding one, and the guides, are copied, and only those layers are visited.
|
||||
fn edit_picked(layer: &mut Arc<Node>, held: Picked, f: &mut impl FnMut(bool, &mut f64)) {
|
||||
let Some(ch) = Arc::make_mut(layer).children_mut() else { return };
|
||||
for (i, inner) in held.children {
|
||||
let Some(c) = ch.get_mut(i) else { continue };
|
||||
if !inner.is_empty() {
|
||||
edit_picked(c, inner, f);
|
||||
} else if let NodeKind::RulerGuide { vertical, pos, .. } = &mut Arc::make_mut(c).kind {
|
||||
f(*vertical, pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `n` picked itself when it is a ruler guide by `is_guide`, else the ruler guides below it
|
||||
/// ([`guides_below`]).
|
||||
fn guide_or_below(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
|
||||
if is_guide(n) { Some(Picked::default()) } else { guides_below(n, is_guide) }
|
||||
}
|
||||
|
||||
/// The ruler guides below `n`, by `is_guide`: those among its members and its opacity-mask art
|
||||
/// (each with nothing inside), and the members and mask art holding one further down (with what
|
||||
/// they hold), or `None` when there is none. `is_guide` looks at each node below `n` once, and at
|
||||
/// nothing inside a ruler guide.
|
||||
fn guides_below(n: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
|
||||
let mask = n.extras().mask.as_deref().and_then(|m| guide_or_below(&m.art, is_guide)).map(Box::new);
|
||||
let children = n.children().into_iter().flatten().enumerate().filter_map(|(i, c)| guide_or_below(c, is_guide).map(|p| (i, p))).collect();
|
||||
Picked { children, mask }.some()
|
||||
}
|
||||
|
||||
/// Remove the ruler guides below `n` that [`guides_below`] `found`, in its members and its
|
||||
/// opacity-mask art (`n` itself stays). Mask art that is a ruler guide becomes an empty group.
|
||||
/// Only the nodes holding one are copied, and only those are visited. Returns how many went.
|
||||
fn drop_guides_below(n: &mut Node, found: Picked) -> usize {
|
||||
let mut gone = drop_mask_guides(n, found.mask);
|
||||
if let Some(ch) = n.children_mut() {
|
||||
let mut found = found.children.into_iter().peekable();
|
||||
let mut next = 0;
|
||||
ch.retain_mut(|c| {
|
||||
let at = next;
|
||||
next += 1;
|
||||
let Some((_, inner)) = found.next_if(|(i, _)| *i == at) else { return true };
|
||||
if inner.is_empty() {
|
||||
gone += 1;
|
||||
return false;
|
||||
}
|
||||
gone += drop_guides_below(Arc::make_mut(c), inner);
|
||||
true
|
||||
});
|
||||
}
|
||||
gone
|
||||
}
|
||||
|
||||
/// Remove every ruler guide in the opacity-mask art of `n`. Mask art that is a ruler guide
|
||||
/// becomes an empty group. Returns how many went.
|
||||
fn drop_mask_guides(n: &mut Node) -> usize {
|
||||
/// Remove the ruler guides `found` in the opacity-mask art of `n` ([`guides_below`]'s mask
|
||||
/// part). Mask art that is a ruler guide becomes an empty group. Returns how many went.
|
||||
fn drop_mask_guides(n: &mut Node, found: Option<Box<Picked>>) -> usize {
|
||||
let Some(found) = found else { return 0 };
|
||||
let Some(mask) = n.extras_if_any().and_then(|e| e.mask.as_deref_mut()) else { return 0 };
|
||||
if mask.art.is_ruler_guide() {
|
||||
if found.is_empty() {
|
||||
mask.art = Arc::new(Node::group(mask.art.id, vec![]));
|
||||
1
|
||||
} else if any_guide(&mask.art) {
|
||||
drop_guides_below(Arc::make_mut(&mut mask.art))
|
||||
} else {
|
||||
0
|
||||
drop_guides_below(Arc::make_mut(&mut mask.art), *found)
|
||||
}
|
||||
}
|
||||
|
||||
/// Does layer `l` hold a ruler guide out of place: below art, in an object or in mask art, or so
|
||||
/// in one of its sublayers?
|
||||
fn layer_untidy(l: &Node) -> bool {
|
||||
let Some(ch) = l.children() else { return false };
|
||||
let start = Node::guide_run_start(ch);
|
||||
l.extras().mask.as_deref().is_some_and(|m| any_guide(&m.art))
|
||||
|| ch.iter().take(start).any(|c| c.is_ruler_guide() || if c.is_layer() { layer_untidy(c) } else { any_guide(c) })
|
||||
/// The ruler guides, by `is_guide`, that layer `l` holds out of place, or `None` when it holds
|
||||
/// none: those below art (each with nothing inside), those in its mask art and in its objects
|
||||
/// ([`guides_below`]), and its sublayers holding one out of place (with what they hold).
|
||||
/// `is_guide` looks at each node once; the guides at the end of a layer are in place and are
|
||||
/// not looked at.
|
||||
fn untidy(l: &Node, is_guide: &impl Fn(&Node) -> bool) -> Option<Picked> {
|
||||
let ch = l.children()?;
|
||||
let mask = l.extras().mask.as_deref().and_then(|m| guide_or_below(&m.art, is_guide)).map(Box::new);
|
||||
let children = ch
|
||||
.iter()
|
||||
.enumerate()
|
||||
.take(Node::guide_run_start(ch))
|
||||
.filter_map(|(i, c)| {
|
||||
let found = if is_guide(c) {
|
||||
Some(Picked::default())
|
||||
} else if c.is_layer() {
|
||||
untidy(c, is_guide)
|
||||
} else {
|
||||
guides_below(c, is_guide)
|
||||
};
|
||||
found.map(|p| (i, p))
|
||||
})
|
||||
.collect();
|
||||
Picked { children, mask }.some()
|
||||
}
|
||||
|
||||
/// [`Document::tidy_ruler_guides`] for layer `l`. Returns how many guides were removed.
|
||||
fn tidy_layer(l: &mut Node) -> usize {
|
||||
let mut gone = drop_mask_guides(l);
|
||||
/// [`Document::tidy_ruler_guides`] for layer `l`, whose guides out of place [`untidy`] `found`.
|
||||
/// Only the nodes holding one are copied, and only those are visited. Returns how many guides
|
||||
/// were removed.
|
||||
fn tidy_layer(l: &mut Node, found: Picked) -> usize {
|
||||
let mut gone = drop_mask_guides(l, found.mask);
|
||||
let Some(ch) = l.children_mut() else { return gone };
|
||||
for c in ch.iter_mut() {
|
||||
if c.is_layer() {
|
||||
if layer_untidy(c) {
|
||||
gone += tidy_layer(Arc::make_mut(c));
|
||||
}
|
||||
} else if !c.is_ruler_guide() && any_guide(c) {
|
||||
gone += drop_guides_below(Arc::make_mut(c));
|
||||
let mut below_art = false;
|
||||
for (i, inner) in found.children {
|
||||
let Some(c) = ch.get_mut(i) else { continue };
|
||||
if inner.is_empty() {
|
||||
below_art = true;
|
||||
} else if c.is_layer() {
|
||||
gone += tidy_layer(Arc::make_mut(c), inner);
|
||||
} else {
|
||||
gone += drop_guides_below(Arc::make_mut(c), inner);
|
||||
}
|
||||
}
|
||||
if ch.iter().take(Node::guide_run_start(ch)).any(|c| c.is_ruler_guide()) {
|
||||
if below_art {
|
||||
let (guides, art): (Vec<_>, Vec<_>) = std::mem::take(ch).into_iter().partition(|c| c.is_ruler_guide());
|
||||
*ch = art;
|
||||
ch.extend(guides);
|
||||
@@ -698,3 +775,286 @@ impl std::fmt::Debug for GuideCache {
|
||||
f.write_str("GuideCache")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{Appearance, OpacityMask, Symbol};
|
||||
use std::cell::Cell;
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
/// The sublayers in [`nested`]'s chain: with the top-level layer around them and the objects in
|
||||
/// the innermost, the deepest a document goes ([`crate::MAX_DEPTH`]).
|
||||
const CHAIN: u64 = 30;
|
||||
|
||||
fn rect(id: u64) -> Arc<Node> {
|
||||
Arc::new(Node::path(NodeId(id), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()))
|
||||
}
|
||||
|
||||
fn guide(id: u64, artboard: Option<u32>) -> Arc<Node> {
|
||||
Arc::new(Node::new(NodeId(id), NodeKind::RulerGuide { vertical: false, pos: id as f64, artboard }))
|
||||
}
|
||||
|
||||
fn group(id: u64, children: Vec<Arc<Node>>) -> Arc<Node> {
|
||||
Arc::new(Node::group(NodeId(id), children))
|
||||
}
|
||||
|
||||
/// `n` with `art` as its opacity-mask art.
|
||||
fn masked(n: Arc<Node>, art: Arc<Node>) -> Arc<Node> {
|
||||
let mut n = (*n).clone();
|
||||
n.extras_mut().mask = Some(Box::new(OpacityMask { art, clip: true, invert: false, disabled: false, linked: true }));
|
||||
Arc::new(n)
|
||||
}
|
||||
|
||||
/// A sublayer like a new document's first layer, holding `children`.
|
||||
fn sublayer(id: u64, children: Vec<Arc<Node>>) -> Arc<Node> {
|
||||
let mut l = (*Document::new(1.0, 1.0).layers[0]).clone();
|
||||
l.id = NodeId(id);
|
||||
if let Some(ch) = l.children_mut() {
|
||||
*ch = children;
|
||||
}
|
||||
Arc::new(l)
|
||||
}
|
||||
|
||||
/// A document whose first layer holds `children`.
|
||||
fn doc(children: Vec<Arc<Node>>) -> Document {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
if let Some(ch) = d.layers.first_mut().and_then(|l| Arc::make_mut(l).children_mut()) {
|
||||
*ch = children;
|
||||
}
|
||||
d
|
||||
}
|
||||
|
||||
/// The ids of the nodes in the layers, in tree order.
|
||||
fn ids(d: &Document) -> Vec<u64> {
|
||||
fn walk(n: &Node, out: &mut Vec<u64>) {
|
||||
out.push(n.id.0);
|
||||
for c in n.children().into_iter().flatten() {
|
||||
walk(c, out);
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
for l in &d.layers {
|
||||
walk(l, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// [`CHAIN`] sublayers, each inside the one before and holding an object, a canvas guide and a
|
||||
/// guide of artboard 7 (the innermost: object 150, guides 200 and 201). Beside the chain, a
|
||||
/// sublayer with a canvas guide only. Returns the document and that sublayer.
|
||||
fn nested() -> (Document, Arc<Node>) {
|
||||
let mut chain = sublayer(100, vec![rect(150), guide(200, None), guide(201, Some(7))]);
|
||||
for depth in 1..CHAIN {
|
||||
chain = sublayer(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth * 2, None), guide(301 + depth * 2, Some(7))]);
|
||||
}
|
||||
let still = sublayer(500, vec![rect(502), guide(501, None)]);
|
||||
(doc(vec![chain, Arc::clone(&still)]), still)
|
||||
}
|
||||
|
||||
/// How many children the layers of [`nested`] hold: the first layer's 2, the untouched
|
||||
/// sublayer's 2, the innermost sublayer's 3 and 4 in each sublayer around it.
|
||||
const NESTED_CHILDREN: usize = 2 + 2 + 3 + (CHAIN as usize - 1) * 4;
|
||||
|
||||
fn on_artboard_7(n: &Node) -> bool {
|
||||
matches!(n.kind, NodeKind::RulerGuide { artboard: Some(7), .. })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_guides_looks_at_each_child_of_nested_layers_once() {
|
||||
let (mut d, still) = nested();
|
||||
assert!(!d.clone().limit_depth(), "the chain is as deep as a document goes");
|
||||
let mut deeper = doc(vec![sublayer(999, d.layers[0].children().cloned().unwrap_or_default())]);
|
||||
assert!(deeper.limit_depth(), "a document nested deeper is brought within the cap when it is read");
|
||||
let mut whole = d.clone();
|
||||
let looked = Cell::new(0_usize);
|
||||
let pick = |n: &Node| {
|
||||
looked.set(looked.get() + 1);
|
||||
on_artboard_7(n)
|
||||
};
|
||||
let held = picked_in_layers(&d.layers[0], &pick).unwrap();
|
||||
assert_eq!(looked.get(), NESTED_CHILDREN, "each child of the layers is looked at once");
|
||||
drop_picked(&mut d.layers[0], held);
|
||||
assert_eq!(looked.get(), NESTED_CHILDREN, "removing looks at nothing again");
|
||||
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a sublayer with nothing to remove is not copied");
|
||||
|
||||
// The command's own entry point removes the same guides.
|
||||
let before = whole.clone();
|
||||
let mut sel = Selection::default();
|
||||
sel.set_guides([NodeId(200), NodeId(201), NodeId(501)]);
|
||||
sel.objects.push(NodeId(150));
|
||||
sel.key_guide = Some(NodeId(201));
|
||||
assert_eq!(whole.retain_guides(&mut sel, |g| g.artboard != Some(7)), CHAIN as usize);
|
||||
assert_eq!(ids(&whole), ids(&d));
|
||||
assert_eq!(ids(&whole).len(), ids(&before).len() - CHAIN as usize);
|
||||
assert!(whole.ruler_guides().iter().all(|g| g.artboard.is_none()));
|
||||
assert_eq!(whole.ruler_guides().len(), CHAIN as usize + 1);
|
||||
assert_eq!((sel.objects.as_slice(), sel.guides.as_slice(), sel.key_guide), (&[NodeId(150)][..], &[NodeId(200), NodeId(501)][..], None));
|
||||
assert!(whole.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)));
|
||||
// The document as it was (an undo step's copy) still holds every guide.
|
||||
assert_eq!(before.ruler_guides().len(), CHAIN as usize * 2 + 1);
|
||||
|
||||
// Saving the guides as a list, and removing a layer but not its guides, take the guides
|
||||
// out of the nested layers too.
|
||||
let mut saved = before.clone();
|
||||
saved.guides_to_saved();
|
||||
assert_eq!(saved.saved_guides, before.ruler_guides());
|
||||
assert_eq!(ids(&saved).len(), 1 + CHAIN as usize * 2 + 2);
|
||||
assert!(saved.layers[0].children().is_some_and(|c| !Arc::ptr_eq(&c[1], &still) && c[1].children().is_some_and(|c| c.len() == 1)));
|
||||
let mut edited = before.clone();
|
||||
let chain = edited.remove_edit_layer(NodeId(100 + CHAIN - 1)).unwrap();
|
||||
assert!(!chain.holds_ruler_guides());
|
||||
assert_eq!(edited.ruler_guides().len(), before.ruler_guides().len(), "the removed layer's guides stay in the document");
|
||||
assert_eq!(edited.guides_on(edited.layers[0].id).len(), CHAIN as usize * 2);
|
||||
|
||||
// Keeping every guide changes nothing and copies no layer.
|
||||
let kept = whole.clone();
|
||||
assert_eq!(whole.retain_guides(&mut sel, |_| true), 0);
|
||||
assert!(Arc::ptr_eq(&whole.layers[0], &kept.layers[0]));
|
||||
// Removing every guide leaves the objects.
|
||||
assert_eq!(whole.retain_guides(&mut sel, |_| false), CHAIN as usize + 1);
|
||||
assert!(whole.ruler_guides().is_empty() && sel.guides.is_empty());
|
||||
assert_eq!(ids(&whole).len(), 1 + CHAIN as usize * 2 + 2);
|
||||
assert_eq!(sel.objects, [NodeId(150)]);
|
||||
// A document without layers, and one without guides, have nothing to remove.
|
||||
let mut empty = Document::new(10.0, 10.0);
|
||||
assert_eq!(empty.retain_guides(&mut sel, |_| false), 0);
|
||||
empty.layers.clear();
|
||||
assert_eq!(empty.retain_guides(&mut sel, |_| false), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_an_artboards_guides_looks_at_each_child_of_nested_layers_once() {
|
||||
let (mut d, still) = nested();
|
||||
let mut whole = d.clone();
|
||||
let looked = Cell::new(0_usize);
|
||||
let pick = |n: &Node| {
|
||||
looked.set(looked.get() + 1);
|
||||
on_artboard_7(n)
|
||||
};
|
||||
let held = picked_in_layers(&d.layers[0], &pick).unwrap();
|
||||
assert_eq!(looked.get(), NESTED_CHILDREN, "each child of the layers is looked at once");
|
||||
let mut seen = vec![];
|
||||
edit_picked(&mut d.layers[0], held, &mut |vertical, pos: &mut f64| {
|
||||
seen.push((vertical, *pos));
|
||||
*pos += 9.0;
|
||||
});
|
||||
assert_eq!(looked.get(), NESTED_CHILDREN, "changing looks at nothing again");
|
||||
// A sublayer comes before its layer's own guides, so the innermost guide is changed first.
|
||||
let order: Vec<(bool, f64)> = [201.0].into_iter().chain((1..CHAIN).map(|depth| (301 + depth * 2) as f64)).map(|pos| (false, pos)).collect();
|
||||
assert_eq!(seen, order, "each guide of the artboard is changed once, in the order the guides lie in");
|
||||
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)), "a sublayer with no guide of the artboard is not copied");
|
||||
|
||||
// The public moves change the same guides by the same amount.
|
||||
let before = whole.clone();
|
||||
whole.move_artboard_guides(7, Vec2::new(5.0, 9.0));
|
||||
assert_eq!(whole, d);
|
||||
assert_eq!(ids(&whole), ids(&before));
|
||||
for g in whole.ruler_guides() {
|
||||
let id = g.id.map_or(0, |id| id.0) as f64;
|
||||
assert_eq!(g.pos, if g.artboard == Some(7) { id + 9.0 } else { id }, "guide {id}");
|
||||
}
|
||||
assert!(whole.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[1], &still)));
|
||||
assert_eq!(before.ruler_guide(NodeId(201)).map(|g| g.pos), Some(201.0), "the document as it was keeps its guides");
|
||||
whole.map_artboard_guides(7, Affine::scale(2.0));
|
||||
assert_eq!(whole.ruler_guide(NodeId(201)).map(|g| g.pos), Some(420.0));
|
||||
assert_eq!(whole.ruler_guide(NodeId(200)).map(|g| g.pos), Some(200.0), "a canvas guide stays");
|
||||
|
||||
// An artboard without guides, and a document without layers, change nothing and copy no layer.
|
||||
let kept = whole.clone();
|
||||
whole.move_artboard_guides(99, Vec2::new(5.0, 9.0));
|
||||
assert!(Arc::ptr_eq(&whole.layers[0], &kept.layers[0]));
|
||||
let mut empty = Document::new(10.0, 10.0);
|
||||
empty.layers.clear();
|
||||
empty.move_artboard_guides(7, Vec2::new(5.0, 9.0));
|
||||
assert!(empty.layers.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guides_in_objects_are_found_by_looking_at_each_node_once() {
|
||||
// Groups, each inside the one before and holding an object and a guide. Beside them, an
|
||||
// object whose mask art holds a guide, one whose mask art is a guide, and a group with none.
|
||||
let mut chain = group(100, vec![rect(150), guide(200, None)]);
|
||||
for depth in 1..CHAIN {
|
||||
chain = group(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth, None)]);
|
||||
}
|
||||
let still = group(700, vec![rect(701)]);
|
||||
let root = group(
|
||||
1,
|
||||
vec![chain, masked(rect(800), group(801, vec![guide(802, None), rect(803)])), masked(rect(810), guide(811, None)), Arc::clone(&still)],
|
||||
);
|
||||
let looked = Cell::new(0_usize);
|
||||
let is_guide = |n: &Node| {
|
||||
looked.set(looked.get() + 1);
|
||||
n.is_ruler_guide()
|
||||
};
|
||||
// The chain's groups, objects and guides; a masked object, its mask group and the two in
|
||||
// it; a masked object and its mask guide; the last group and its object.
|
||||
let nodes = CHAIN as usize * 3 + 4 + 2 + 2;
|
||||
let found = guides_below(&root, &is_guide).unwrap();
|
||||
assert_eq!(looked.get(), nodes, "each node below the root is looked at once");
|
||||
let mut cleared = (*root).clone();
|
||||
assert_eq!(drop_guides_below(&mut cleared, found), CHAIN as usize + 2);
|
||||
assert_eq!(looked.get(), nodes, "removing looks at nothing again");
|
||||
assert!(guides_below(&cleared, &Node::is_ruler_guide).is_none());
|
||||
let ch = cleared.children().unwrap();
|
||||
assert!(Arc::ptr_eq(&ch[3], &still), "a group without guides is not copied");
|
||||
assert_eq!(
|
||||
ch[1].extras().mask.as_deref().map(|m| m.art.children().map(|c| c.iter().map(|c| c.id.0).collect::<Vec<_>>())),
|
||||
Some(Some(vec![803]))
|
||||
);
|
||||
assert_eq!(ch[2].extras().mask.as_deref().map(|m| (m.art.id, m.art.children().map(Vec::len))), Some((NodeId(811), Some(0))));
|
||||
|
||||
// Opening a file removes the same guides from an object on a layer and from a symbol's art.
|
||||
let mut d = doc(vec![Arc::clone(&root), guide(900, None)]);
|
||||
d.symbols = vec![Symbol { name: "s".into(), art: Arc::clone(&root), dynamic: false }];
|
||||
assert_eq!(d.tidy_ruler_guides(), (CHAIN as usize + 2) * 2);
|
||||
assert_eq!(d.layers[0].children().map(|c| (*c[0]).clone()), Some(cleared.clone()));
|
||||
assert_eq!(*d.symbols[0].art, cleared);
|
||||
assert_eq!(d.ruler_guides().iter().map(|g| g.id).collect::<Vec<_>>(), [Some(NodeId(900))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guides_out_of_place_are_found_by_looking_at_each_node_once() {
|
||||
// Sublayers, each inside the one before, with their guides in place; the innermost also
|
||||
// holds a guide below its art. Beside them, a group holding a guide, a sublayer with its
|
||||
// guide in place, and a sublayer whose mask art holds a guide.
|
||||
let mut chain = sublayer(100, vec![guide(200, None), rect(150), guide(201, None)]);
|
||||
for depth in 1..CHAIN {
|
||||
chain = sublayer(100 + depth, vec![rect(600 + depth), chain, guide(300 + depth, None)]);
|
||||
}
|
||||
let still = sublayer(500, vec![rect(502), guide(501, None)]);
|
||||
let with_mask = masked(sublayer(510, vec![rect(513)]), group(511, vec![guide(512, None)]));
|
||||
let mut d = doc(vec![chain, group(700, vec![rect(701), guide(702, None)]), Arc::clone(&still), with_mask, guide(900, None)]);
|
||||
let mut whole = d.clone();
|
||||
let looked = Cell::new(0_usize);
|
||||
let is_guide = |n: &Node| {
|
||||
looked.set(looked.get() + 1);
|
||||
n.is_ruler_guide()
|
||||
};
|
||||
// Below the guides at the end of each layer: the first layer's 4, the group's 2, the
|
||||
// untouched sublayer's 1, the masked sublayer's mask group, its guide and the object, 2 in
|
||||
// the innermost sublayer and 2 in each sublayer around it.
|
||||
let nodes = 4 + 2 + 1 + 3 + 2 + (CHAIN as usize - 1) * 2;
|
||||
let found = untidy(&d.layers[0], &is_guide).unwrap();
|
||||
assert_eq!(looked.get(), nodes, "each node below the guides in place is looked at once");
|
||||
assert_eq!(tidy_layer(Arc::make_mut(&mut d.layers[0]), found), 2);
|
||||
assert_eq!(looked.get(), nodes, "tidying looks at nothing again");
|
||||
assert!(d.layers[0].children().is_some_and(|c| Arc::ptr_eq(&c[2], &still)), "a sublayer with its guides in place is not copied");
|
||||
assert!(untidy(&d.layers[0], &Node::is_ruler_guide).is_none());
|
||||
|
||||
// Opening a file does the same.
|
||||
let before = whole.clone();
|
||||
assert_eq!(whole.tidy_ruler_guides(), 2);
|
||||
assert_eq!(whole, d);
|
||||
let all = ids(&whole);
|
||||
assert!(!all.contains(&702) && all.len() == ids(&before).len() - 1);
|
||||
let innermost = whole.node(NodeId(100)).and_then(|n| n.children()).map(|c| c.iter().map(|c| c.id.0).collect::<Vec<_>>());
|
||||
assert_eq!(innermost, Some(vec![150, 200, 201]), "a guide below art moves up to the other guides");
|
||||
assert!(whole.node(NodeId(510)).is_some_and(|n| n.extras().mask.as_deref().is_some_and(|m| m.art.children().is_some_and(Vec::is_empty))));
|
||||
// A tidy document is left alone, and no layer is copied.
|
||||
let kept = whole.clone();
|
||||
assert_eq!(whole.tidy_ruler_guides(), 0);
|
||||
assert!(Arc::ptr_eq(&whole.layers[0], &kept.layers[0]));
|
||||
}
|
||||
}
|
||||
@@ -429,6 +429,12 @@ const MAX_MEMBERS: usize = 4096;
|
||||
/// normals): past it the object is too complex to export.
|
||||
const MAX_MESH_TRIANGLES: usize = 2_000_000;
|
||||
|
||||
/// The most facets of solid colors under colored lights that one 3D effect draws as faces of their
|
||||
/// own, to go in one order with other solids' faces. Each such face is about 16 nodes, a composite
|
||||
/// of a whole surface about 6 per facet, so at this count the faces hold about as many nodes as the
|
||||
/// composites do at the paint-copy allowance. Past it those solids draw as one composite each.
|
||||
const MAX_FACE_COMPOSITES: usize = 30_720;
|
||||
|
||||
/// The shapes a 3D effect on group or layer `n` builds its solids from: every visible path,
|
||||
/// compound path and type in it (after [`resolve`] gives it the art of its symbol instances, blends
|
||||
/// and clipping groups), at any depth of its groups, each through its own geometry
|
||||
@@ -535,9 +541,12 @@ pub fn validate_three_d_params(id: &str, p: &Value) -> Result<(), String> {
|
||||
}
|
||||
|
||||
/// One surface: each facet a path shaded from `paint`, as a group with the paint's opacity and
|
||||
/// blend mode (so overlapping facets don't add up their transparency).
|
||||
fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool) -> Node {
|
||||
if colored && paint.color().is_some() && facets.iter().any(|face| face.rgb_gradient.is_some()) {
|
||||
/// blend mode (so overlapping facets don't add up their transparency). Under colored lights a solid
|
||||
/// color with smooth facets is one composite of all its facets ([`composites_facets`]) unless
|
||||
/// `faces`: then each facet is a face of its own, as in a gradient, so the faces can go in one order
|
||||
/// with the faces of other solids.
|
||||
fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: BlendMode, colored: bool, faces: bool) -> Node {
|
||||
if !faces && composites_facets(&facets, paint, colored) {
|
||||
let mut group = crate::lighting::solid_surface(n.id, &facets, paint);
|
||||
group.opacity = opacity;
|
||||
group.blend = blend;
|
||||
@@ -583,6 +592,12 @@ fn surface(n: &Node, facets: Vec<Facet>, paint: &Paint, opacity: f32, blend: Ble
|
||||
group
|
||||
}
|
||||
|
||||
/// Is a surface of `facets` in `paint` one composite of all its facets when [`surface`] draws it
|
||||
/// whole: a solid color under colored lights with smooth shading?
|
||||
fn composites_facets(facets: &[Facet], paint: &Paint, colored: bool) -> bool {
|
||||
colored && paint.color().is_some() && facets.iter().any(|face| face.rgb_gradient.is_some())
|
||||
}
|
||||
|
||||
/// `item`'s paint, its opacity times `member` (the opacity of the objects it is in) and its blend.
|
||||
fn paint_of(item: &AppearanceItem, member: f32) -> (Paint, f32, BlendMode) {
|
||||
match item {
|
||||
@@ -600,10 +615,10 @@ fn paint_ref(item: &AppearanceItem) -> &Paint {
|
||||
}
|
||||
|
||||
/// Paint copies `surface` makes for `facets`: two per facet (fill and seam stroke), six when colored
|
||||
/// lights give each facet derived paints (`lighting::solid_surface`).
|
||||
/// lights give each facet derived paints (`lighting::solid_surface`, or `lighting::facet_art` for
|
||||
/// each face).
|
||||
fn facet_copies(facets: &[Facet], paint: &Paint, colored: bool) -> usize {
|
||||
let derived = colored && paint.color().is_some() && facets.iter().any(|f| f.rgb_gradient.is_some());
|
||||
facets.len().saturating_mul(if derived { 6 } else { 2 })
|
||||
facets.len().saturating_mul(if composites_facets(facets, paint, colored) { 6 } else { 2 })
|
||||
}
|
||||
|
||||
/// The area `item` paints on `path`, and the rule that fills it: the path itself for a fill, the
|
||||
@@ -1265,8 +1280,9 @@ type ShadowAndSurfaces = (Vec<Arc<Node>>, Vec<Arc<Node>>);
|
||||
/// The 3D art of one effect `fx` on `path` (already through the effects before it).
|
||||
/// Rotate turns every fill and stroke, each in its own paint. Extrude & Bevel and Inflate build a
|
||||
/// solid from the path for the top visible fill and one from the outline of each visible stroke,
|
||||
/// each in its own paint. When every one is opaque with normal blending and no colored light makes
|
||||
/// a surface one composite, their faces are drawn in one back-to-front order (where depths tie, as
|
||||
/// each in its own paint. When every one is opaque with normal blending, their faces are drawn in
|
||||
/// one back-to-front order, a solid color under colored lights included up to
|
||||
/// [`MAX_FACE_COMPOSITES`] facets (where depths tie, as
|
||||
/// for the caps turned toward the viewer, in the order of the appearance, and with caps, a shape's
|
||||
/// fill walls before the faces of its covering strokes that overlap them, and its fill's faces and
|
||||
/// its other strokes' faces, cut where they pass through each other ([`cut_stroke_faces`]), in the
|
||||
@@ -1521,7 +1537,8 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
filled.push(Filled { at: out.len(), member, caps, opacity, blend, masked: masks_surface(&paint, colored) });
|
||||
}
|
||||
}
|
||||
let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) };
|
||||
let art =
|
||||
if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored, false) };
|
||||
out.push((s.scopes.as_slice(), Arc::new(art)));
|
||||
}
|
||||
}
|
||||
@@ -1554,22 +1571,31 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
opacity >= 1.0 && blend == BlendMode::Normal
|
||||
});
|
||||
let closed = |shape: usize| shapes.get(shape).is_some_and(|s| holds_edge(&fx.id, &s.path));
|
||||
// A solid whose surface is one composite of all its facets ([`surface`]: a solid color under
|
||||
// colored lights with smooth shading) has no faces to order.
|
||||
let composite = |item: &AppearanceItem, f: &[Facet]| colored && paint_ref(item).color().is_some() && f.iter().any(|f| f.rgb_gradient.is_some());
|
||||
// The faces are drawn in one order (below) unless a composite draws the surfaces whole. Under
|
||||
// a member's opacity mask or blending, each member's faces go in one order of their own when its
|
||||
// fills and strokes are opaque, blend normally, carry no opacity mask and are not composites.
|
||||
let one_order = opaque && !solids.iter().any(|(item, _, _, f, _)| composite(item, f));
|
||||
// A solid color under colored lights with smooth shading draws as one composite of its facets
|
||||
// ([`surface`]) unless its facets go in one order with other solids' faces. They do while all
|
||||
// such facets together number at most MAX_FACE_COMPOSITES.
|
||||
let composite = |item: &AppearanceItem, f: &[Facet]| composites_facets(f, paint_ref(item), colored);
|
||||
let colored_faces: usize = solids.iter().filter(|(item, _, _, f, _)| composite(item, f)).map(|(.., f, _)| f.len()).sum();
|
||||
let split = colored_faces <= MAX_FACE_COMPOSITES;
|
||||
// The faces are drawn in one order (below) when every solid is opaque and blends normally and
|
||||
// no composite draws a surface whole. Under a member's opacity mask or blending, each member's
|
||||
// faces go in one order of their own when its fills and strokes are opaque, blend normally,
|
||||
// carry no opacity mask and are not composites.
|
||||
let one_order = opaque && (split || !solids.iter().any(|(item, _, _, f, _)| composite(item, f)));
|
||||
let shape_order: Vec<bool> = (0..shapes.len())
|
||||
.map(|shape| {
|
||||
solids.iter().filter(|s| s.4 == shape).all(|(item, member, _, f, _)| {
|
||||
let (paint, opacity, blend) = paint_of(item, *member);
|
||||
opacity >= 1.0 && blend == BlendMode::Normal && !masks_surface(&paint, colored) && !composite(item, f)
|
||||
opacity >= 1.0 && blend == BlendMode::Normal && !masks_surface(&paint, colored) && (split || !composite(item, f))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let ordered = |shape: usize| if masks { shape_order.get(shape).copied().unwrap_or(false) } else { one_order };
|
||||
// The solids whose faces share one order with another solid's: every solid in the one order of
|
||||
// the object, or of its member under a mask. A lone solid draws its facets in their own order,
|
||||
// so a solid color under colored lights stays one composite there ([`surface`]).
|
||||
let shared: Vec<bool> =
|
||||
(0..shapes.len()).map(|shape| ordered(shape) && solids.iter().filter(|s| !masks || s.4 == shape).nth(1).is_some()).collect();
|
||||
if solids.iter().any(|s| ordered(s.4)) {
|
||||
// A stroke face that passes through a fill wall or another stroke's face is cut where it
|
||||
// does. The pieces count against the limits as the faces did: cutting stops before the
|
||||
@@ -1605,6 +1631,10 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
.collect();
|
||||
placed_graphics(doc, n.id, (&fx.id, &p), bounds, &filled, masks)
|
||||
};
|
||||
// With the pieces of the cuts, solid colors under colored lights past MAX_FACE_COMPOSITES draw
|
||||
// as one composite each, so their surfaces draw whole (below).
|
||||
let split =
|
||||
split && solids.iter().filter(|(item, _, _, f, _)| composite(item, f)).map(|(.., f, _)| f.len()).sum::<usize>() <= MAX_FACE_COMPOSITES;
|
||||
let members: Vec<usize> = solids.iter().map(|s| s.4).collect();
|
||||
let surfaces: Vec<BuiltSurface> = solids
|
||||
.into_iter()
|
||||
@@ -1613,7 +1643,11 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
let depths: Vec<Placed> = f.iter().map(|f| Placed::of(f, shape, paints)).collect();
|
||||
let ends = f.iter().map(|f| f.end.filter(|_| !f.away)).collect();
|
||||
let (paint, opacity, blend) = paint_of(item, member);
|
||||
let art = if classic { classic::surface(n, f, &paint, opacity, blend, &p) } else { surface(n, f, &paint, opacity, blend, colored) };
|
||||
let art = if classic {
|
||||
classic::surface(n, f, &paint, opacity, blend, &p)
|
||||
} else {
|
||||
surface(n, f, &paint, opacity, blend, colored, split && shared.get(shape).copied().unwrap_or(false))
|
||||
};
|
||||
(depths, art, scopes, ends)
|
||||
})
|
||||
.collect();
|
||||
@@ -1622,8 +1656,8 @@ fn surfaces_for(doc: Option<&Document>, n: &Node, fx: &Effect, shapes: &[Profile
|
||||
CLASSIC_EXTRUDE => classic_extrude_options(&p).cap,
|
||||
_ => extrude_options(&p).cap,
|
||||
};
|
||||
// One order takes a plain group of faces from each solid, one face for each facet. With
|
||||
// colored lights a surface can instead be one clipped composite of all its facets. A composite
|
||||
// One order takes a plain group of faces from each solid, one face for each facet. A lone
|
||||
// solid's surface can instead be one clipped composite of all its facets ([`surface`]), which
|
||||
// has no faces to order, so it draws whole.
|
||||
let plain = |(depths, s, _, _): &BuiltSurface| matches!(&s.kind, NodeKind::Group { children, clip: false } if children.len() == depths.len());
|
||||
if masks {
|
||||
|
||||
@@ -491,8 +491,8 @@ fn a_masked_members_fill_and_stroke_faces_go_in_one_order() {
|
||||
}
|
||||
|
||||
/// Under a light that is not white, Inflate in gradients, whose faces are drawn one by one, draws the
|
||||
/// fill's and the dashed stroke's faces in one order, as it does under a white light. A solid color,
|
||||
/// drawn as one composite of each surface's facets, still draws each surface whole.
|
||||
/// fill's and the dashed stroke's faces in one order, as it does under a white light, and so does
|
||||
/// Inflate in solid colors.
|
||||
#[test]
|
||||
fn a_colored_inflate_in_gradients_draws_its_faces_in_one_order() {
|
||||
use vectorcraft_doc::color::{Gradient, GradientKind, GradientPaint, GradientStop};
|
||||
@@ -530,9 +530,111 @@ fn a_colored_inflate_in_gradients_draws_its_faces_in_one_order() {
|
||||
let cut = drawn_parts(&n, INFLATE, &json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0, "depth": 60})).len();
|
||||
assert_eq!(white.1, cut, "the white light's faces, cut");
|
||||
assert_eq!(drawn(&n, Some(colored.clone())).0, 1, "one order under the colored light");
|
||||
// A solid color under the colored light: a composite for each of the fill and the stroke.
|
||||
// A solid color under the colored light: the fill's and the stroke's faces in one order too.
|
||||
let solid = stroked(&letter_c());
|
||||
assert_eq!(drawn(&solid, Some(colored)).0, 2);
|
||||
assert_eq!(drawn(&solid, Some(colored)).0, 1);
|
||||
}
|
||||
|
||||
/// The bounds of face `f` of 3D art: its path's, or for a clipped colored composite
|
||||
/// ([`crate::lighting::facet_art`]) its color cover's, which is the face's bounds grown by 1 pt.
|
||||
fn drawn_face_bounds(f: &Node) -> Rect {
|
||||
match &f.kind {
|
||||
NodeKind::Path { .. } => f.path_data().and_then(PathData::bounds).unwrap(),
|
||||
NodeKind::Group { clip: true, children } => {
|
||||
let cover = &children[1].children().unwrap()[0];
|
||||
cover.path_data().and_then(PathData::bounds).unwrap().inflate(-1.0, -1.0)
|
||||
}
|
||||
_ => panic!("a face is a path or a clipped composite"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Under a light that is not white, a solid-color fill and a solid-color stroke, plain, dashed or
|
||||
/// with a width profile, draw their faces in one order, the faces of both solids in the order of
|
||||
/// their depths where they overlap, in Inflate and in Extrude & Bevel, with and without perspective
|
||||
/// and in a member with an opacity mask. Drawing each solid whole, the fill's faces before the
|
||||
/// stroke's, shows farther faces on top.
|
||||
#[test]
|
||||
fn colored_solid_fills_and_strokes_share_face_depth_order() {
|
||||
use vectorcraft_doc::{Dash, WidthProfile};
|
||||
type Style<'a> = (&'a str, &'a dyn Fn(&mut StrokeLayer));
|
||||
let styles: [Style; 3] = [
|
||||
("plain", &|_| {}),
|
||||
("dashed", &|s| s.dash = Some(Dash { pattern: vec![12.0, 12.0], offset: 0.0, align_corners: false })),
|
||||
("profiled", &|s| s.profile = Some(WidthProfile::lens())),
|
||||
];
|
||||
let views = [
|
||||
json!({"rotationX": -20, "rotationY": -40, "rotationZ": 0}),
|
||||
json!({"rotationX": -30, "rotationY": 20, "rotationZ": 5, "perspectiveAngle": 40}),
|
||||
];
|
||||
let mut whole_misdrawn = 0;
|
||||
for id in [INFLATE, EXTRUDE] {
|
||||
for view in &views {
|
||||
for (style, set) in &styles {
|
||||
let mut params = view.clone();
|
||||
params["depth"] = json!(60);
|
||||
params["lights"] = json!([{"color": "#ff8080"}, {"color": "#4060ff", "rotation": 120}]);
|
||||
let mut n = stroked(&letter_c());
|
||||
if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) {
|
||||
set(s);
|
||||
}
|
||||
let what = format!("{id} {view} {style}");
|
||||
let parts = drawn_parts(&n, id, ¶ms);
|
||||
if id == INFLATE {
|
||||
assert!(parts.iter().any(|(f, ..)| f.rgb_gradient.is_some()), "{what}: smooth colored facets");
|
||||
}
|
||||
let mut with = n.clone();
|
||||
with.appearance.effects.push(fx(id, params.clone()));
|
||||
let art = solid_art(&with).unwrap();
|
||||
let surfaces = art.children().unwrap();
|
||||
assert_eq!(surfaces.len(), 1, "{what}: one order");
|
||||
let faces = surfaces[0].children().unwrap();
|
||||
assert_eq!(faces.len(), parts.len(), "{what}: one face per facet");
|
||||
for (k, (face, (facet, ..))) in faces.iter().zip(&parts).enumerate() {
|
||||
let (a, b) = (drawn_face_bounds(face), facet.path().bounds().unwrap());
|
||||
let close = [a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 1e-6);
|
||||
assert!(close, "{what}: face {k} drawn out of the order of the depths");
|
||||
}
|
||||
let allowed = if id == INFLATE { 5 } else { 0 };
|
||||
let wrong = misdrawn(&parts);
|
||||
assert!(wrong.len() <= allowed, "{what}: {} points show a farther face, first {:?}", wrong.len(), wrong.first());
|
||||
// The same faces drawn as two whole surfaces, the fill's then the stroke's.
|
||||
let mut whole = parts.clone();
|
||||
whole.sort_by_key(|(_, part, _)| *part);
|
||||
whole_misdrawn += misdrawn(&whole).len();
|
||||
// In a group, under the member's opacity mask, the faces keep the same order.
|
||||
if id == INFLATE && *style == "plain" {
|
||||
let cover = Node::path(
|
||||
NodeId(900),
|
||||
vectorcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 400.0, 400.0)),
|
||||
Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0),
|
||||
);
|
||||
let mut masked = n.clone();
|
||||
masked.extras_mut().mask = Some(Box::new(OpacityMask::new(cover, true)));
|
||||
let mut plain = Node::group(NodeId(2), vec![Arc::new(n.clone())]);
|
||||
plain.appearance.effects.push(fx(id, params.clone()));
|
||||
let mut g = Node::group(NodeId(2), vec![Arc::new(masked)]);
|
||||
g.appearance.effects.push(fx(id, params.clone()));
|
||||
let bounds = |art: &Node| {
|
||||
let mut out = vec![];
|
||||
art.walk(&mut |n| {
|
||||
if let NodeKind::Group { clip: true, .. } = &n.kind {
|
||||
out.push(drawn_face_bounds(n));
|
||||
}
|
||||
});
|
||||
out
|
||||
};
|
||||
let (plain, scoped) = (solid_art(&plain).unwrap(), solid_art(&g).unwrap());
|
||||
let mut masks = 0;
|
||||
scoped.walk(&mut |n| masks += usize::from(n.extras().mask.is_some()));
|
||||
assert!(masks > 0, "{what}: drawn in the member's mask");
|
||||
let ordered = bounds(&plain);
|
||||
assert!(ordered.len() > 100, "{what}: clipped faces");
|
||||
assert_eq!(bounds(&scoped), ordered, "{what}: the member's faces in one order");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(whole_misdrawn > 0, "whole surfaces show farther faces");
|
||||
}
|
||||
|
||||
/// A face of a stroke that leaves gaps passing through the plane of its fill's wall where they
|
||||
@@ -1322,11 +1424,12 @@ fn legacy_white_inflate_keeps_polygon_faces_and_its_seam_range() {
|
||||
assert!(faces(&art).iter().all(|face| matches!(face.kind, NodeKind::Path { .. })));
|
||||
}
|
||||
|
||||
/// A solid color under colored lights is one composite of all its facets, with one clip and a fixed
|
||||
/// number of groups, where its solid's faces draw in no order shared with another solid's: a lone
|
||||
/// fill, or a fill and a translucent stroke. A fill and an opaque stroke draw each face on its own,
|
||||
/// in one order.
|
||||
#[test]
|
||||
fn colored_solid_inflate_batches_channels_and_clips_once_per_surface() {
|
||||
let mut n = square_node();
|
||||
n.appearance.effects.push(fx(INFLATE, json!({"lights":[{"color":"#ff0000"},{"color":"#0000ff"}]})));
|
||||
let art = solid_art(&n).unwrap();
|
||||
fn count(n: &Node) -> (usize, usize, usize) {
|
||||
let (mut groups, mut clips, mut paths) = match &n.kind {
|
||||
NodeKind::Group { clip, .. } => (1, usize::from(*clip), 0),
|
||||
@@ -1341,13 +1444,125 @@ fn colored_solid_inflate_batches_channels_and_clips_once_per_surface() {
|
||||
}
|
||||
(groups, clips, paths)
|
||||
}
|
||||
let (groups, clips, paths) = count(&art);
|
||||
assert!(paths > 1000, "exercise a tessellated surface");
|
||||
// The fill's solid and the stroke's, each one composite with its own clip.
|
||||
let surfaces = art.children().unwrap().len();
|
||||
assert_eq!(surfaces, 2);
|
||||
assert_eq!(clips, surfaces);
|
||||
assert_eq!(groups, 1 + 6 * surfaces, "group count must not grow with triangle count");
|
||||
let lights = json!({"lights":[{"color":"#ff0000"},{"color":"#0000ff"}]});
|
||||
let lone = |n: &mut Node| n.appearance.items.retain(|i| matches!(i, AppearanceItem::Fill(_)));
|
||||
let translucent = |n: &mut Node| {
|
||||
if let Some(AppearanceItem::Stroke(s)) = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Stroke(_))) {
|
||||
s.opacity = 0.5;
|
||||
}
|
||||
};
|
||||
for (what, set, surfaces) in [("a lone fill", &lone as &dyn Fn(&mut Node), 1), ("a translucent stroke", &translucent, 2)] {
|
||||
let mut n = square_node();
|
||||
set(&mut n);
|
||||
n.appearance.effects.push(fx(INFLATE, lights.clone()));
|
||||
let art = solid_art(&n).unwrap();
|
||||
let (groups, clips, paths) = count(&art);
|
||||
assert!(paths > 1000, "{what}: exercise a tessellated surface");
|
||||
// Each solid one composite with its own clip.
|
||||
assert_eq!(art.children().unwrap().len(), surfaces, "{what}");
|
||||
assert_eq!(clips, surfaces, "{what}");
|
||||
assert_eq!(groups, 1 + 6 * surfaces, "{what}: group count must not grow with triangle count");
|
||||
}
|
||||
// An opaque fill and stroke: one order of faces, each its own clipped composite or shaded path.
|
||||
let mut n = square_node();
|
||||
n.appearance.effects.push(fx(INFLATE, lights));
|
||||
let art = solid_art(&n).unwrap();
|
||||
let surfaces = art.children().unwrap();
|
||||
assert_eq!(surfaces.len(), 1, "one order");
|
||||
let faces = surfaces[0].children().unwrap();
|
||||
assert!(faces.len() > 100, "one face per facet");
|
||||
assert!(faces.iter().all(|f| matches!(&f.kind, NodeKind::Path { .. } | NodeKind::Group { clip: true, .. })));
|
||||
assert!(faces.iter().any(|f| matches!(&f.kind, NodeKind::Group { clip: true, .. })), "colored ramps");
|
||||
}
|
||||
|
||||
/// Solid colors under colored lights go in one order of faces while their facets together, with the
|
||||
/// pieces of the cuts, number at most `MAX_FACE_COMPOSITES`. Past it each solid draws whole, as one
|
||||
/// composite.
|
||||
#[test]
|
||||
fn colored_solids_past_the_face_limit_draw_as_composites() {
|
||||
let lights = json!({"lights":[{"color":"#ff0000"},{"color":"#0000ff","rotation":90}]});
|
||||
let mut base = square_node();
|
||||
base.appearance.effects.push(fx(INFLATE, lights.clone()));
|
||||
let stroke = base.appearance.items.iter().find(|i| matches!(i, AppearanceItem::Stroke(_))).cloned().unwrap();
|
||||
// The facets each solid draws under these lights. Strokes alike each build the same solid.
|
||||
let shapes = [Profile { path: profile(&base).unwrap().0, rule: FillRule::NonZero, items: solid_paints(&base), opacity: 1.0, scopes: vec![] }];
|
||||
let (parts, bounds) = solid_parts(&shapes, union_bounds(&shapes).unwrap());
|
||||
let counts: Vec<usize> = built_solids(INFLATE, &crate::merged_params(INFLATE, &lights), &parts, bounds, MAX_OBJECT_FACES)
|
||||
.map(|f| f.unwrap().map_or(0, |f| f.len()))
|
||||
.collect();
|
||||
let [fill, each] = counts[..] else { panic!("a fill's solid and a stroke's") };
|
||||
let fits = (MAX_FACE_COMPOSITES - fill) / each;
|
||||
assert!(fits >= 4, "{fill} + {fits} × {each}");
|
||||
// Under the limit; under it before the cuts but past it with their pieces; past it before them.
|
||||
let mut seen = vec![];
|
||||
for strokes in [fits / 2, fits, fits + 1] {
|
||||
let mut n = base.clone();
|
||||
n.appearance.items.extend(std::iter::repeat_n(stroke.clone(), strokes - 1));
|
||||
let uncut = fill + strokes * each;
|
||||
let cut = drawn_parts(&n, INFLATE, &lights).len();
|
||||
let one_order = cut <= MAX_FACE_COMPOSITES;
|
||||
seen.push((uncut <= MAX_FACE_COMPOSITES, one_order));
|
||||
let art = solid_art(&n).unwrap();
|
||||
let surfaces = art.children().unwrap();
|
||||
if one_order {
|
||||
assert_eq!(surfaces.len(), 1, "{uncut} faces, {cut} cut: one order");
|
||||
} else {
|
||||
assert_eq!(surfaces.len(), 1 + strokes, "{uncut} faces, {cut} cut: each solid whole");
|
||||
assert!(surfaces.iter().all(|s| s.children().is_some_and(|c| c.len() < 10)), "each solid one composite");
|
||||
}
|
||||
}
|
||||
assert_eq!(seen, [(true, true), (true, false), (false, false)], "every case");
|
||||
}
|
||||
|
||||
/// A solid-color face drawn on its own under colored lights takes the same colors as in the
|
||||
/// surface's one composite: the paint, multiplied by the same red, green and blue light ramps, and
|
||||
/// a seam of the same width.
|
||||
#[test]
|
||||
fn a_colored_solid_face_on_its_own_keeps_the_composites_colors() {
|
||||
let n = square_node();
|
||||
let p = crate::merged_params(INFLATE, &json!({"lights":[{"color":"#ff0000"},{"color":"#0000ff","rotation":90}]}));
|
||||
let (path, rule) = profile(&n).unwrap();
|
||||
let all = facets(INFLATE, &path, rule, path.bounds().unwrap(), &p).unwrap();
|
||||
let face = all
|
||||
.iter()
|
||||
.find(|f| f.rgb_gradient.is_some_and(|g| g.channels[0] != g.channels[1] || g.channels[1] != g.channels[2]))
|
||||
.expect("a facet with colored ramps")
|
||||
.clone();
|
||||
let paint = Paint::solid(RED);
|
||||
// Each node's own fill paint, and its seam stroke's width, for every node under `n`.
|
||||
let paints = |n: &Node| {
|
||||
let mut out = vec![];
|
||||
n.walk(&mut |n| {
|
||||
for item in &n.appearance.items {
|
||||
match item {
|
||||
AppearanceItem::Fill(f) => out.push((Some(f.paint.clone()), None)),
|
||||
AppearanceItem::Stroke(s) => out.push((None, Some(s.width))),
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
};
|
||||
let alone = surface(&n, vec![face.clone()], &paint, 1.0, BlendMode::Normal, true, true);
|
||||
let batch = surface(&n, vec![face.clone()], &paint, 1.0, BlendMode::Normal, true, false);
|
||||
let [single] = alone.children().unwrap().as_slice() else { panic!("one face") };
|
||||
assert!(matches!(&single.kind, NodeKind::Group { clip: true, .. }), "a clipped face");
|
||||
// The face's paint cover and its three channel ramps.
|
||||
let fills = |n: &Node| paints(n).into_iter().filter_map(|(f, _)| f).collect::<Vec<_>>();
|
||||
let one = fills(single);
|
||||
assert_eq!(one.len(), 4);
|
||||
assert_eq!(one[0], paint, "the paint");
|
||||
// The composite: its paint cover, then each channel's black backdrop and the face's ramp.
|
||||
let all_fills = fills(&batch);
|
||||
let ramps: Vec<&Paint> = all_fills.iter().filter(|p| **p != Paint::solid(Color::BLACK)).skip(1).collect();
|
||||
assert_eq!(all_fills.first(), Some(&paint));
|
||||
assert_eq!(ramps, one.iter().skip(1).collect::<Vec<_>>(), "the same light ramps");
|
||||
// The single face's clip holds its seam: the clip reaches past the facet by half the seam.
|
||||
let seam = (face.thickness() / 2.0).clamp(0.05, 0.75);
|
||||
let widths: Vec<f64> = paints(&batch).into_iter().filter_map(|(_, w)| w).filter(|w| *w > 0.0).collect();
|
||||
assert!(widths.len() == 3 && widths.iter().all(|w| (w - seam).abs() < 1e-12), "{widths:?}");
|
||||
let NodeKind::Group { children, .. } = &single.kind else { panic!("a clip group") };
|
||||
let (clip, facet) = (children[0].path_data().and_then(PathData::bounds).unwrap(), face.path().bounds().unwrap());
|
||||
assert!((clip.x0 - (facet.x0 - seam / 2.0)).abs() < 0.1 && (clip.x1 - (facet.x1 + seam / 2.0)).abs() < 0.1, "{clip:?} {facet:?}");
|
||||
}
|
||||
|
||||
/// `square_node` moved right by `dx`, with id `id` and fill `fill`.
|
||||
|
||||
@@ -419,6 +419,27 @@ pub(crate) fn appearance_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>>
|
||||
if targets_contents(p)? { leaf_targets(s, &roots) } else { Ok(roots) }
|
||||
}
|
||||
|
||||
/// The refusal of an appearance edit whose targets are all the art of graph designs drawn in graph series.
|
||||
const DESIGN_ART: &str = "the art of a graph design in a graph series is drawn again from the design: edit the design to change it";
|
||||
|
||||
/// The [`appearance_targets`] whose rows and effects a command edits: the art of graph designs drawn in graph series
|
||||
/// ([`super::graph::is_design_art`]) is left out, as the graph draws it again from the design. A command whose targets
|
||||
/// are all such art is refused.
|
||||
pub(crate) fn edit_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let ids = appearance_targets(s, p)?;
|
||||
without_design_art(&s.doc()?.doc, ids, "appearance")
|
||||
}
|
||||
|
||||
/// `ids` without the art of graph designs drawn in graph series; `cmd` is refused when `ids` held nothing else.
|
||||
pub(crate) fn without_design_art(d: &Document, mut ids: Vec<NodeId>, cmd: &str) -> Result<Vec<NodeId>> {
|
||||
let given = ids.len();
|
||||
ids.retain(|id| !super::graph::is_design_art(d, *id));
|
||||
if given > 0 && ids.is_empty() {
|
||||
return Err(bad(cmd, DESIGN_ART));
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// `ids` with each graph series group that has no fill or stroke row of its own replaced by the paths directly inside
|
||||
/// it ([`super::graph::series_group_marks`]). A series group with rows, as a document saved earlier can hold, stays:
|
||||
/// the Appearance panel lists those rows and edits them by index.
|
||||
@@ -453,17 +474,17 @@ pub(crate) fn look_holder<'a>(d: &'a Document, n: &'a Node) -> &'a Node {
|
||||
look_holders(d, n.id).last().and_then(|id| d.node(*id)).unwrap_or(n)
|
||||
}
|
||||
|
||||
/// Objects whose fill and stroke rows a command edits: the [`appearance_targets`], with a graph series group standing
|
||||
/// for the paths directly inside it ([`rowless_series_marks`]), so the graph can store the edit.
|
||||
/// Objects whose fill and stroke rows a command edits: the [`edit_targets`], with a graph series group standing for the
|
||||
/// paths directly inside it ([`rowless_series_marks`]), so the graph can store the edit.
|
||||
pub(crate) fn row_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let ids = appearance_targets(s, p)?;
|
||||
let ids = edit_targets(s, p)?;
|
||||
Ok(rowless_series_marks(&s.doc()?.doc, &ids))
|
||||
}
|
||||
|
||||
/// Objects whose whole appearance a command edits: the [`row_targets`], then each graph series group they stand for,
|
||||
/// which can hold effects and a graphic style link of its own.
|
||||
pub(crate) fn whole_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
let own = appearance_targets(s, p)?;
|
||||
let own = edit_targets(s, p)?;
|
||||
let mut ids = rowless_series_marks(&s.doc()?.doc, &own);
|
||||
let groups = stood_for(&own, &ids);
|
||||
ids.extend(groups);
|
||||
@@ -869,6 +890,11 @@ fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, "`source` and `target` are the same object"));
|
||||
}
|
||||
let copy = switch_or(p, "copy", false, C)?;
|
||||
// The art of a graph design in a series is read as a source, but neither takes an appearance nor gives one up.
|
||||
without_design_art(&s.doc()?.doc, vec![target], C)?;
|
||||
if !copy {
|
||||
without_design_art(&s.doc()?.doc, vec![source], C)?;
|
||||
}
|
||||
// A graph series group stands for the paths directly inside it: as the source, the topmost of them is read and a
|
||||
// move clears them all; as the target, each of them other than a source takes the appearance.
|
||||
let sources = look_holders(&s.doc()?.doc, source);
|
||||
@@ -1245,7 +1271,7 @@ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let aligned = aligned(p, C)?;
|
||||
if p.get("from").and_then(Value::as_str) == Some("contents") {
|
||||
// A graph series group's own Contents row, not its paths, which have none.
|
||||
let ids = appearance_targets(s, p)?;
|
||||
let ids = edit_targets(s, p)?;
|
||||
if ids.is_empty() {
|
||||
return Err(bad(C, "select objects or give ids"));
|
||||
}
|
||||
@@ -1447,6 +1473,7 @@ fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(Some(clicked), leaf_targets(s, &selected)?)
|
||||
};
|
||||
targets.retain(|id| Some(*id) != source);
|
||||
let mut targets = without_design_art(&s.doc()?.doc, targets, C)?;
|
||||
let node = match source {
|
||||
Some(id) => Arc::new(s.doc()?.doc.node(id).ok_or(EngineError::NoNode(id))?.clone()),
|
||||
None => s.eyedropper_sample.clone().ok_or_else(|| bad(C, "select the object to copy from"))?,
|
||||
|
||||
@@ -536,6 +536,80 @@ fn a_document_replaced_in_the_back_is_measured_when_the_front_one_closes() {
|
||||
assert_eq!(actual.cached_bounds, Some(expected));
|
||||
}
|
||||
|
||||
/// The type of document `index` with id `id`, wherever its tab is.
|
||||
fn text_in(s: &Session, index: usize, id: u64) -> vectorcraft_doc::TextObject {
|
||||
match &s.documents()[index].doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
_ => panic!("not text"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A document replaced while in the back has its type measured in its own composite fonts at once,
|
||||
/// while the front document stays in front with its own definition registered; coming to the front
|
||||
/// does not measure that type again.
|
||||
#[test]
|
||||
fn a_document_replaced_in_the_back_is_measured_before_it_comes_to_the_front() {
|
||||
let (bytes, id, width) = full_roman_file("CF Pane");
|
||||
let mut s = session();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Pane")]})).unwrap();
|
||||
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
|
||||
assert_eq!(s.active_index(), Some(1));
|
||||
let front = vectorcraft_text::FontDb::global().composite_font("CF Pane").unwrap();
|
||||
assert_eq!(front.parts.get(vectorcraft_doc::CharClass::Roman).size, 50.0);
|
||||
let measured = text_in(&s, 0, id);
|
||||
assert!((measured.cached_bounds.unwrap().width() - width).abs() < 1e-6);
|
||||
let node = s.documents()[0].doc.node(NodeId(id)).unwrap().geometric_bounds().unwrap();
|
||||
assert!((node.width() - width).abs() < 1e-6);
|
||||
let doc = std::sync::Arc::as_ptr(&s.documents()[0].doc);
|
||||
assert!(s.set_active(0));
|
||||
assert!(std::ptr::eq(doc, std::sync::Arc::as_ptr(&s.documents()[0].doc)));
|
||||
assert_eq!(text(&s, id).cached_bounds, measured.cached_bounds);
|
||||
}
|
||||
|
||||
/// Type a document replaced in the back sets in a composite font that only the front document
|
||||
/// defines is measured in that font while the front one is registered, and again, as missing, when
|
||||
/// the replaced document comes to the front.
|
||||
#[test]
|
||||
fn a_document_replaced_in_the_back_measures_a_font_it_lacks_again_in_front() {
|
||||
let mut s = session();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Lacked"})).unwrap()["id"].as_u64().unwrap();
|
||||
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Lacked")]})).unwrap();
|
||||
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
|
||||
let back = text_in(&s, 0, id);
|
||||
let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &back).bounds;
|
||||
assert_eq!(back.cached_bounds, Some(expected));
|
||||
assert!(s.set_active(0));
|
||||
assert!(vectorcraft_text::FontDb::global().composite_font("CF Lacked").is_none());
|
||||
let actual = text(&s, id);
|
||||
let expected = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &actual).bounds;
|
||||
assert_eq!(actual.cached_bounds, Some(expected));
|
||||
}
|
||||
|
||||
/// Text holding an inline graphic whose symbol's art is type in a composite font, in a document
|
||||
/// replaced in the back, is measured with the graphic at the size the document's own definition
|
||||
/// gives it before it comes to the front.
|
||||
#[test]
|
||||
fn a_document_replaced_in_the_back_measures_inline_graphics_in_its_own_definition() {
|
||||
let mut s = session();
|
||||
let mut full = font("CF Back Inline");
|
||||
full["parts"]["roman"]["size"] = json!(100);
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [full]})).unwrap();
|
||||
let art =
|
||||
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "Ab12", "size": 20, "font": "CF Back Inline"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "CF Back Inline Mark", "ids": [art]})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 150, "text": "x", "size": 20})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.insertInline", &json!({"id": id, "at": 0, "symbol": "CF Back Inline Mark"})).unwrap();
|
||||
let width = text(&s, id).cached_bounds.unwrap().width();
|
||||
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("type.compositeFonts.set", &json!({"fonts": [font("CF Back Inline")]})).unwrap();
|
||||
assert!(s.replace_document(0, vectorcraft_format::load(&bytes).unwrap()));
|
||||
assert!((text_in(&s, 0, id).cached_bounds.unwrap().width() - width).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// A failed batch takes back the composite fonts it set, in the font database too.
|
||||
#[test]
|
||||
fn a_failed_batch_takes_back_its_composite_fonts() {
|
||||
|
||||
@@ -13,7 +13,7 @@ use vectorcraft_doc::{Document, Effect, Node, NodeKind, StrokeLayer};
|
||||
use vectorcraft_geom::{FillRule, PathData};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::appearance::{ItemTarget, aligned, appearance_targets, index_param, item_indices, item_target, item_target_at};
|
||||
use super::appearance::{ItemTarget, aligned, appearance_targets, edit_targets, index_param, item_indices, item_target, item_target_at};
|
||||
use super::expand::has_seeded;
|
||||
use super::rasterfx;
|
||||
use super::{CommandSpec, EngineError, NodeId, Result, Session, always, bad, check_switches, cmd, fileio, has_doc, str_param, switch_or};
|
||||
@@ -49,7 +49,7 @@ fn effect_specs() -> Vec<CommandSpec> {
|
||||
"Apply Effect",
|
||||
[],
|
||||
None,
|
||||
"{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.<id>\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step) → {ids, index, item, grouped?}",
|
||||
"{effect: id (see effect.list, e.g. \"stylize.dropShadow\", \"distort.roughen\", \"warp.arc\", or \"plugin.<id>\" for an installed effect plug-in), params?: {…} (missing keys take the dialog defaults), item?: appearance item index|null (apply to that fill/stroke only; omitted: the Appearance panel's active item, else the whole object), ids?|id?: [..] (layers too), target?: \"object\"|\"contents\" (contents: the objects inside groups and layers)} append a live effect to each selected object's appearance (a group's or layer's apply to its members as one piece: one combined shadow; a Pathfinder effect, which combines a group's contents, groups several loose selected objects first, in the same undo step); the art of a graph design in a graph series is left out, and objects that are all such art are an error (docs/mcp.md) → {ids, index, item, grouped?}",
|
||||
has_doc,
|
||||
apply
|
||||
),
|
||||
@@ -298,7 +298,7 @@ fn ids_json(ids: &[NodeId]) -> Value {
|
||||
/// edits its equal item, or its equal object-level effect, each target matched on its own whatever
|
||||
/// the other targets have; in a target without them, `item` and `index` stand for themselves.
|
||||
pub(crate) fn effect_targets(s: &Session, p: &Value, item: ItemTarget, index: usize, cmd: &str) -> Result<Vec<(NodeId, Option<usize>, usize)>> {
|
||||
let roots = appearance_targets(s, p)?;
|
||||
let roots = edit_targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let per = item.per_target(s, &roots);
|
||||
let first = roots.first().and_then(|f| d.node(*f));
|
||||
@@ -453,7 +453,7 @@ pub(crate) fn apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let item = item_target(s, p, C)?;
|
||||
if effects::is_three_d(id) {
|
||||
let targets = appearance_targets(s, p)?;
|
||||
let targets = edit_targets(s, p)?;
|
||||
for (target, at) in targets.iter().copied().zip(item.per_target(s, &targets)) {
|
||||
let d = &s.doc()?.doc;
|
||||
let n = d.node(target).ok_or(EngineError::NoNode(target))?;
|
||||
@@ -492,8 +492,9 @@ fn loose_for_pathfinder(s: &Session, p: &Value, id: &str) -> Result<Option<Vec<N
|
||||
if !effects::is_pathfinder(id) || ["ids", "id", "item", "target"].iter().any(|k| p.get(k).is_some()) {
|
||||
return Ok(None);
|
||||
}
|
||||
let roots = super::appearance::subject_roots(s)?;
|
||||
let d = &s.doc()?.doc;
|
||||
// The art of a graph design in a series stays where the graph draws it.
|
||||
let roots = super::appearance::without_design_art(d, super::appearance::subject_roots(s)?, "appearance")?;
|
||||
let grouped = roots.iter().any(|r| d.node(*r).is_some_and(|n| matches!(n.kind, NodeKind::Group { clip: false, .. } | NodeKind::Layer { .. })));
|
||||
Ok((roots.len() >= 2 && !grouped).then_some(roots))
|
||||
}
|
||||
@@ -606,7 +607,7 @@ fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let src = item_target_at(s, p, "fromItem", C)?;
|
||||
let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src };
|
||||
let copy = switch_or(p, "copy", false, C)?;
|
||||
let roots = appearance_targets(s, p)?;
|
||||
let roots = edit_targets(s, p)?;
|
||||
// Where an aligned effect would go in each of several different stacks isn't one place.
|
||||
if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &roots) {
|
||||
return Err(bad(C, "effects of objects whose appearances differ can't be moved together"));
|
||||
|
||||
@@ -7,7 +7,7 @@ use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{Effect, Node};
|
||||
use vectorcraft_render::effects;
|
||||
|
||||
use super::super::appearance::{appearance_targets, index_param, item_target};
|
||||
use super::super::appearance::{edit_targets, index_param, item_target};
|
||||
use super::super::brushsym::{normalize, selection_art, store_symbol};
|
||||
use super::super::{CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, has_doc, has_selection, str_param};
|
||||
use super::{effect_targets, ids_json};
|
||||
@@ -95,7 +95,7 @@ fn map_graphic(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
effect_targets(s, p, item, index, C)?
|
||||
} else {
|
||||
let mut out = vec![];
|
||||
for id in appearance_targets(s, p)? {
|
||||
for id in edit_targets(s, p)? {
|
||||
let (item, index) = d.node(id).and_then(first_three_d).ok_or_else(|| bad(C, format!("object {} needs a 3D effect", id.0)))?;
|
||||
out.push((id, item, index));
|
||||
}
|
||||
|
||||
@@ -123,7 +123,7 @@ mod formats;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::list_dir;
|
||||
pub use access::{write_file_with, write_save_file, write_save_file_with};
|
||||
pub use access::{check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests_readonly;
|
||||
|
||||
@@ -121,6 +121,24 @@ pub(crate) fn naming_in_message(msg: &str, path: &str, name: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// The error for an SVG of a document that links a JavaScript file outside the read roots.
|
||||
pub(crate) const SCRIPT_OUTSIDE: &str = "a linked JavaScript file is outside the read roots";
|
||||
|
||||
/// `cmd` may write `st`'s document in format `format` (a format id): any format but SVG and SVGZ,
|
||||
/// and those too unless read roots are in force and the document links a JavaScript file outside
|
||||
/// them (`svg_scripts`, a relative path taken from the document's folder; a URL is not checked),
|
||||
/// which the file's `<script>` element would name. The error names no file or folder.
|
||||
pub fn check_linked_scripts(cmd: &str, format: &str, st: &crate::DocState) -> Result<()> {
|
||||
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
let doc_path = st.path.as_deref();
|
||||
if st.doc.svg_scripts.iter().any(|f| crate::cmd::links::script_hidden(f, doc_path)) {
|
||||
return Err(bad(cmd, SCRIPT_OUTSIDE));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `path` checked for writing against the automation roots in force.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn may_write(path: &str) -> Result<()> {
|
||||
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Serialize Document",
|
||||
[],
|
||||
None,
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it",
|
||||
"{format?: vectorcraft (default)|template|svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd (ait, a .ait template, is written by file.saveAsTemplate), …the format's options (see document.formats; SVG ones also as svg: {…}), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own)} → {text, warnings} for svg (plus dataBase64, the file, when its encoding isn't UTF-8), else {dataBase64, warnings}; an SVG of several artboards also gives files: [{name, text}], linked images linked: [{name, dataBase64}]. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz are refused while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)",
|
||||
has_doc,
|
||||
export::serialize
|
||||
),
|
||||
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditabilit
Line truncated
|
||||
"{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin.<plug-in id>, which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as <stem>.html / <stem>.map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the visible art), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), maxEditabilit
Line truncated
|
||||
has_doc,
|
||||
export::export
|
||||
),
|
||||
@@ -45,7 +45,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export Selection…",
|
||||
["File"],
|
||||
None,
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it",
|
||||
"{path?, format?: png|jpg|webp|svg|svgz|pdf|ai|gif|png8|tiff|bmp|tga|psd|txt|dxf|eps|emf|wmf|hpgl|vectorcraft|template (default: from the extension, else png), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), …the format's options} the selected objects (template layers left out), each in the layers and groups that hold it, whose clipping paths, opacity masks, effects, opacity and blend modes apply as on the canvas (an object of a blend, envelope, repeat or intertwine on its own; txt: the selected type alone), cropped to the bounds the renderer measures for that art (a clip group by its clip) → {path, format, bytes, warnings, bounds} (no path → {dataBase64, format, bytes, warnings, bounds}); warnings say what the format approximated or left out, as for document.export. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz are refused while the document links a JavaScript file outside them, as document.export refuses them",
|
||||
has_selection,
|
||||
export::export_selection
|
||||
),
|
||||
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export for Screens",
|
||||
["File", "Export"],
|
||||
None,
|
||||
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused",
|
||||
"{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with <filename> for the document, <name> for the artboard, asset, layer or object, <index> from 1, #### for the counter zero-padded to the run of #, <format>, <scale>, <suffix> (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, <date>, <time>, <YYYY>, <MM>, <DD>, <hh>, <mm> and <ss>; a trailing .ext is dropped, as in `COMPANY-Logo-<filename>-####-YYYYMMDD`; different files it names alike get -2, -3…), counterStart?: 1, counterPer?: item (every file of an item has its number)|file, date?: YYYY-MM-DD (the date the pattern uses; default today, UTC), preset?: mobile (PNG 1x, 2x, 3x) | density (PNG 0.75x–4x in ldpi…xxxhdpi sub-folders) instead of formats (turns subfolders on), formats?: [{format: png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft, scale?: 1 | \"2x\" | \"100w\" | \"100h\" | \"72ppi\", width?: px | height?: px | ppi? (raster only; width, then height, then ppi win over scale), suffix?: (raster default: @2x, @100w, @100h, none at 1x; vector formats drop size suffixes), folder?: (its sub-folder), quality?: (jpg 0–100), …the format's options (antiAlias, background, preset (pdf)…)}], settings?: {png|png8|jpg|webp|gif|tiff|bmp|tga|psd|svg|svgz|pdf|eps|ai|vectorcraft: {…options for every row of that format}} (rows' own options win), prefix?, antiAlias?: none|art|type (raster rows without their own), openLocation?: (remembered; the app shows the files after exporting)} one file per artboard and format (a PDF holds its artboard alone; artboards with the same name, in any case, get -2, -3…; an unnamed one is Artboard-N; a row whose file would take a name another row's file has, in any case, gets -2, -3… too, and identical rows write one file; row folders that differ only in case are one folder, spelled as the first row spells it) → {files: [path…]} (into the folder of exportPreset, outside the automation read roots: no ZIP path, and files relative to that folder); no folder → {files: [{name, dataBase64}]} (names include sub-folders: 2x/Icon@2x.png); every reply has warnings: [the encoders' warnings for the files, each once: an image that couldn't be decoded, type written in the fallback font…]. eps, ai and vectorcraft rows write a document of the item alone (its one artboard). The params (but zip and assets) are remembered in the document (document.exportSettings; not an undo step). A key it doesn't take, a key no format takes in a format row or in settings, settings for a format it doesn't write, and an unknown key inside a PDF, EPS or SVG option's object, are refused. Under automation read roots, an svg or svgz row is refused, before the folder is made or any file is written, while the document links a JavaScript file outside them, as document.export refuses it",
|
||||
has_doc,
|
||||
screens::export_for_screens
|
||||
),
|
||||
|
||||
@@ -12,7 +12,8 @@ use crate::DocState;
|
||||
use super::super::{Result, Session, bad, check_switches, edit, number_or, switch_or, text_param};
|
||||
use super::encode::single_artboard;
|
||||
use super::{
|
||||
ARTBOARD_PARAMS, Format, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded, write_or_return,
|
||||
ARTBOARD_PARAMS, Format, check_linked_scripts, default_name, encode_all, encode_with_warnings, merge, with_black_output, writable, write_encoded,
|
||||
write_or_return,
|
||||
};
|
||||
|
||||
/// The keys the export commands take for every format, beside the path, the format and the
|
||||
@@ -53,6 +54,7 @@ pub fn unused_option_notes(cmd: &str, f: &Format, p: &Value) -> Vec<String> {
|
||||
|
||||
pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let f = writable("document.serialize", Some(text_param(p, "format", "document.serialize")?.unwrap_or("vectorcraft")), None)?;
|
||||
check_linked_scripts("document.serialize", f.id, s.doc()?)?;
|
||||
let unused = unused_option_notes("document.serialize", f, p);
|
||||
let expanded = expand_presets(s, "document.serialize", p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
@@ -96,6 +98,7 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::check_not_lossy_overwrite(s.doc()?, path, p, "document.export")?;
|
||||
}
|
||||
let f = writable("document.export", text_param(p, "format", "document.export")?, path)?;
|
||||
check_linked_scripts("document.export", f.id, s.doc()?)?;
|
||||
let unused = unused_option_notes("document.export", f, p);
|
||||
let expanded = expand_presets(s, "document.export", p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
@@ -355,6 +358,7 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
super::check_not_lossy_overwrite(s.doc()?, path, p, C)?;
|
||||
}
|
||||
let f = writable(C, text_param(p, "format", C)?, path)?;
|
||||
check_linked_scripts(C, f.id, s.doc()?)?;
|
||||
let unused = unused_option_notes(C, f, p);
|
||||
let expanded = expand_presets(s, C, p)?;
|
||||
let p = with_black_output(s, &expanded);
|
||||
|
||||
@@ -822,6 +822,7 @@ pub(crate) fn job_for(s: &Session, st: &DocState, plan: SavePlan) -> Result<Save
|
||||
|
||||
fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i64>) -> Result<SaveJob> {
|
||||
let cmd = plan.mode.command();
|
||||
super::check_linked_scripts(cmd, plan.format.id, st)?;
|
||||
let mut own = doc_to_save(st, plan.format);
|
||||
// The file the document is saved as (else its own) titles it if New's name is all it has.
|
||||
let file = plan.path.as_deref().filter(|_| plan.retargets()).or(st.path.as_deref());
|
||||
@@ -1238,7 +1239,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Save Document",
|
||||
[],
|
||||
None,
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings say when the format doesn't read compress, version, preview or precision given flat, or a key given in options), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Save, p)
|
||||
),
|
||||
|
||||
@@ -1030,6 +1030,10 @@ pub(crate) fn export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
o.one_source()?;
|
||||
// `<filename>`: the document's file, as Save names it, or its title before it is saved.
|
||||
let st = s.doc()?;
|
||||
// Before the folder is made or any row is written.
|
||||
for r in &rows {
|
||||
super::check_linked_scripts(C, r.format.id, st)?;
|
||||
}
|
||||
let naming = Naming::of(&o, st.path.as_deref().unwrap_or(&st.doc.title))?;
|
||||
let selection = o.selection_mode()?;
|
||||
let selected = if selection.is_some() { selected_artwork(s)? } else { vec![] };
|
||||
|
||||
@@ -46,8 +46,9 @@ use generate::generate;
|
||||
use series::default_series_color;
|
||||
pub(crate) use series::{
|
||||
LabelTextChange, capture_label_anti_alias, capture_label_object_opacity, capture_label_paragraphs, capture_label_rows, capture_label_styles,
|
||||
capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, label_object_opacity_differs,
|
||||
paint_targets, series_group_marks, series_group_marks_where, series_marks_in, series_object_opacity_differs, shown_paint,
|
||||
capture_label_text, capture_series_object_opacity, capture_series_opacity, capture_series_top_paints, is_design_art,
|
||||
label_object_opacity_differs, paint_targets, series_group_marks, series_group_marks_where, series_marks_in, series_object_opacity_differs,
|
||||
shown_paint,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -131,7 +131,7 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for id in ids {
|
||||
// The series' own marks: the art of a marker design inside it keeps the design's paint (painting it would
|
||||
// The series' own marks: the art of a graph design inside it keeps the design's paint (painting it would
|
||||
// last only until the graph is drawn again), so edit the design to change it.
|
||||
match members.get(id) {
|
||||
Some(r) if r.group == *id => {
|
||||
@@ -139,7 +139,7 @@ pub(crate) fn paint_targets(doc: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
out.extend(group.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id));
|
||||
}
|
||||
}
|
||||
Some(r) if doc.parent_of(*id) != Some(r.group) => {}
|
||||
Some(r) if doc.parent_of(*id) != Some(r.group) || doc.node(*id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. })) => {}
|
||||
_ => out.push(*id),
|
||||
}
|
||||
}
|
||||
@@ -157,18 +157,11 @@ pub(crate) fn series_group_marks(doc: &Document, ids: &[NodeId]) -> Vec<NodeId>
|
||||
|
||||
/// [`series_group_marks`] for the series groups `stands` accepts; the others pass through.
|
||||
pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: impl Fn(&Node) -> bool) -> Vec<NodeId> {
|
||||
// A series group is a child of a graph with one of the graph's series indexes ([`series_members`]). Each id is
|
||||
// looked up through its parent, with no pass over the document: the panels call this while they draw.
|
||||
let is_series_group = |n: &Node| {
|
||||
let Some(index) = n.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false };
|
||||
let graph = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref());
|
||||
graph.is_some_and(|spec| index < series_count(spec))
|
||||
};
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut out = Vec::new();
|
||||
for id in ids {
|
||||
match doc.node(*id) {
|
||||
Some(group) if is_series_group(group) && stands(group) => {
|
||||
Some(group) if is_series_group(doc, group) && stands(group) => {
|
||||
let marks: Vec<NodeId> =
|
||||
group.children().into_iter().flatten().filter(|m| matches!(m.kind, NodeKind::Path { .. })).map(|m| m.id).collect();
|
||||
if marks.is_empty() { out.push(*id) } else { out.extend(marks) }
|
||||
@@ -180,6 +173,26 @@ pub(crate) fn series_group_marks_where(doc: &Document, ids: &[NodeId], stands: i
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `n` is a graph series group: a child of a graph with one of the graph's series indexes ([`series_members`]).
|
||||
/// It is looked up through its parent, with no pass over the document: the panels call this while they draw.
|
||||
fn is_series_group(doc: &Document, n: &Node) -> bool {
|
||||
let Some(index) = n.extras().series_index.and_then(|i| usize::try_from(i).ok()) else { return false };
|
||||
let graph = doc.parent_of(n.id).and_then(|parent| doc.node(parent)).and_then(|parent| parent.extras().graph.as_deref());
|
||||
graph.is_some_and(|spec| index < series_count(spec))
|
||||
}
|
||||
|
||||
/// Whether `id` is the art of a graph design drawn in a graph series (Object › Graph › Column or Marker): an object
|
||||
/// inside a series group other than a path directly in it. The graph draws that art again from the design.
|
||||
pub(crate) fn is_design_art(doc: &Document, id: NodeId) -> bool {
|
||||
let Some(chain) = doc.ancestry(id) else { return false };
|
||||
let Some(at) = chain.iter().position(|a| doc.node(*a).is_some_and(|n| is_series_group(doc, n))) else { return false };
|
||||
match chain.len() - at {
|
||||
1 => false,
|
||||
2 => doc.node(id).is_some_and(|n| !matches!(n.kind, NodeKind::Path { .. })),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The paint of the topmost visible fill (`true`) or stroke (`false`) of `node`, and a stroke's weight (0 without paint).
|
||||
/// With no such row: no paint.
|
||||
pub(crate) fn shown_paint(node: &Node, fill: bool) -> (Paint, f64) {
|
||||
|
||||
@@ -373,8 +373,8 @@ fn removing_a_series_marks_fill_forgets_its_kept_opacity() {
|
||||
assert_eq!(spec(&s, id).series_paints[0].fill_opacity, None);
|
||||
}
|
||||
|
||||
/// An opacity set on a row added to a graph design's copy inside a series is not kept for the series: the graph draws
|
||||
/// the design again from the design itself.
|
||||
/// A row or a row opacity is not given to a graph design's copy inside a series, and the graph keeps no opacity for the
|
||||
/// series: the graph draws the design again from the design itself.
|
||||
#[test]
|
||||
fn an_opacity_on_a_design_copy_in_a_series_is_not_kept() {
|
||||
let mut s = Session::new();
|
||||
@@ -384,11 +384,143 @@ fn an_opacity_on_a_design_copy_in_a_series_is_not_kept() {
|
||||
s.execute("graph.column", &json!({"id": id.0, "design": "Square"})).unwrap();
|
||||
let copy = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].clone();
|
||||
assert!(matches!(copy.kind, NodeKind::Group { .. }));
|
||||
s.execute("appearance.addFill", &json!({"ids": [copy.id.0]})).unwrap();
|
||||
s.execute("transparency.set", &json!({"ids": [copy.id.0], "item": 0, "opacity": 40})).unwrap();
|
||||
assert!(s.execute("appearance.addFill", &json!({"ids": [copy.id.0]})).is_err());
|
||||
assert!(s.execute("transparency.set", &json!({"ids": [copy.id.0], "item": 0, "opacity": 40})).is_err());
|
||||
assert!(spec(&s, id).series_paints.first().is_none_or(|p| p.fill_opacity.is_none()));
|
||||
}
|
||||
|
||||
/// A column graph whose series 0 draws the design "Square": the graph, series 0's first copy of the design, a path
|
||||
/// inside that copy, and the first mark of series 1, drawn plain.
|
||||
fn design_art() -> (Session, NodeId, NodeId, NodeId, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let id = graph(&mut s, "column");
|
||||
save_design(&mut s, "Square");
|
||||
s.execute("graph.column", &json!({"id": id.0, "seriesIndexes": [0], "design": "Square"})).unwrap();
|
||||
let n = s.doc().unwrap().doc.node(id).unwrap().clone();
|
||||
let copy = series(&n, 0).children().unwrap()[0].clone();
|
||||
assert!(matches!(copy.kind, NodeKind::Group { .. }));
|
||||
let mut art = vec![];
|
||||
copy.walk(&mut |m| {
|
||||
if matches!(m.kind, NodeKind::Path { .. }) {
|
||||
art.push(m.id);
|
||||
}
|
||||
});
|
||||
let mark = series(&n, 1).children().unwrap()[0].clone();
|
||||
assert!(matches!(mark.kind, NodeKind::Path { .. }));
|
||||
(s, id, copy.id, art[0], mark.id)
|
||||
}
|
||||
|
||||
/// `cmd` with `p` is refused as an edit of graph design art, and the document keeps its undo history.
|
||||
fn refused_on_design_art(s: &mut Session, cmd: &str, p: serde_json::Value) {
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let e = s.execute(cmd, &p).unwrap_err().to_string();
|
||||
assert!(e.contains("drawn again from the design"), "{cmd}: {e}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{cmd}");
|
||||
}
|
||||
|
||||
/// The commands that give rows, effects or graphic styles refuse the art of a graph design inside a series, given by
|
||||
/// id (the design's copy or a path inside it) or selected: the graph draws that art again from the design.
|
||||
#[test]
|
||||
fn appearance_commands_refuse_a_graph_designs_art_in_a_series() {
|
||||
let (mut s, _, copy, art, _) = design_art();
|
||||
let (rect, _) = blue_style(&mut s, "Blue", false);
|
||||
let graphic = s.execute("shape.rectangle", &json!({"x": 700, "y": 700, "width": 10, "height": 10})).unwrap()["id"].clone();
|
||||
s.execute("threeD.addGraphic", &json!({"name": "Mark", "ids": [graphic]})).unwrap();
|
||||
let fill = top_row(&s, art, true);
|
||||
for ids in [json!([copy.0]), json!([art.0])] {
|
||||
refused_on_design_art(
|
||||
&mut s,
|
||||
"graphicStyle.addFromLibrary",
|
||||
json!({"library": "painted-sketched", "name": "Wet Ink", "apply": true, "ids": ids}),
|
||||
);
|
||||
for cmd in ["appearance.addFill", "appearance.addStroke", "appearance.clear", "appearance.reduceToBasic", "appearance.showAllHidden"] {
|
||||
refused_on_design_art(&mut s, cmd, json!({"ids": ids}));
|
||||
}
|
||||
refused_on_design_art(&mut s, "appearance.moveItem", json!({"ids": ids, "from": "contents", "to": 0}));
|
||||
refused_on_design_art(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "ids": ids}));
|
||||
refused_on_design_art(&mut s, "appearance.addEffect", json!({"effect": "stylize.dropShadow", "ids": ids}));
|
||||
refused_on_design_art(&mut s, "effect.apply", json!({"effect": "threeD.extrude", "item": null, "ids": ids}));
|
||||
refused_on_design_art(&mut s, "effect.move", json!({"ids": ids, "from": 0, "to": 0}));
|
||||
refused_on_design_art(&mut s, "effect.remove", json!({"ids": ids, "index": 0}));
|
||||
refused_on_design_art(&mut s, "threeD.mapGraphic", json!({"ids": ids, "symbol": "Mark"}));
|
||||
refused_on_design_art(&mut s, "graphicStyle.apply", json!({"name": "Blue", "ids": ids}));
|
||||
}
|
||||
for cmd in ["appearance.removeItem", "appearance.duplicateItem"] {
|
||||
refused_on_design_art(&mut s, cmd, json!({"ids": [art.0], "index": fill}));
|
||||
}
|
||||
refused_on_design_art(&mut s, "appearance.setItem", json!({"ids": [art.0], "index": fill, "color": "#00ff00"}));
|
||||
refused_on_design_art(&mut s, "appearance.moveItem", json!({"ids": [art.0], "from": fill, "to": 0}));
|
||||
refused_on_design_art(&mut s, "transparency.set", json!({"ids": [art.0], "item": fill, "opacity": 40}));
|
||||
refused_on_design_art(&mut s, "appearance.copyFrom", json!({"source": rect.0, "ids": [art.0]}));
|
||||
refused_on_design_art(&mut s, "appearance.transfer", json!({"source": rect.0, "target": art.0, "copy": true}));
|
||||
refused_on_design_art(&mut s, "appearance.transfer", json!({"source": art.0, "target": rect.0}));
|
||||
// Selected, and through the contents of the design's copy.
|
||||
s.execute("select.set", &json!({"ids": [art.0]})).unwrap();
|
||||
refused_on_design_art(&mut s, "appearance.addFill", json!({}));
|
||||
refused_on_design_art(&mut s, "graphicStyle.addFromLibrary", json!({"library": "painted-sketched", "name": "Wet Ink", "apply": true}));
|
||||
refused_on_design_art(&mut s, "appearance.addStroke", json!({"ids": [copy.0], "target": "contents"}));
|
||||
// A Pathfinder effect does not group the selected paths of the design's copy.
|
||||
let mut paths = vec![];
|
||||
s.doc().unwrap().doc.node(copy).unwrap().walk(&mut |m| {
|
||||
if matches!(m.kind, NodeKind::Path { .. }) {
|
||||
paths.push(m.id.0);
|
||||
}
|
||||
});
|
||||
assert_eq!(paths.len(), 2);
|
||||
s.execute("select.set", &json!({"ids": paths})).unwrap();
|
||||
refused_on_design_art(&mut s, "effect.apply", json!({"effect": "pathfinder.add"}));
|
||||
// Read as a source, the art gives its look.
|
||||
s.execute("appearance.transfer", &json!({"source": art.0, "target": rect.0, "copy": true})).unwrap();
|
||||
}
|
||||
|
||||
/// Given the art of a graph design in a series with other objects, the commands edit the other objects only.
|
||||
#[test]
|
||||
fn appearance_commands_edit_the_objects_given_with_a_graph_designs_art() {
|
||||
let (mut s, id, copy, art, mark) = design_art();
|
||||
let (rect, _) = blue_style(&mut s, "Blue", false);
|
||||
let rows = |s: &Session, id: NodeId| s.doc().unwrap().doc.node(id).unwrap().appearance.clone();
|
||||
let (copy_was, art_was, mark_was) = (rows(&s, copy), rows(&s, art), rows(&s, mark));
|
||||
s.execute("appearance.addFill", &json!({"ids": [copy.0, mark.0]})).unwrap();
|
||||
assert_eq!((rows(&s, copy), rows(&s, art)), (copy_was.clone(), art_was.clone()));
|
||||
assert_eq!(rows(&s, mark).items.len(), mark_was.items.len() + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect": "stylize.dropShadow", "ids": [art.0, mark.0]})).unwrap();
|
||||
assert_eq!(rows(&s, art), art_was);
|
||||
assert_eq!(rows(&s, mark).effects.len(), 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("appearance.copyFrom", &json!({"source": rect.0, "ids": [art.0, mark.0]})).unwrap();
|
||||
assert_eq!(rows(&s, art), art_was);
|
||||
assert_ne!(rows(&s, mark), mark_was);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
// The graph's contents: series 1's marks take the fill, the design's art does not.
|
||||
s.execute("appearance.addFill", &json!({"ids": [id.0], "target": "contents"})).unwrap();
|
||||
assert_eq!((rows(&s, copy), rows(&s, art)), (copy_was, art_was));
|
||||
assert_eq!(rows(&s, mark).items.len(), mark_was.items.len() + 1);
|
||||
}
|
||||
|
||||
/// The paint commands leave the art of a graph design in a series out, a copy of the design given by id with an item
|
||||
/// included.
|
||||
#[test]
|
||||
fn paint_targets_leave_a_graph_designs_copy_out() {
|
||||
let (s, _, copy, art, mark) = design_art();
|
||||
let d = &s.doc().unwrap().doc;
|
||||
assert_eq!(super::paint_targets(d, &[copy, art, mark]), [mark]);
|
||||
}
|
||||
|
||||
/// The art of a marker design in a series is refused too.
|
||||
#[test]
|
||||
fn effect_commands_refuse_a_marker_designs_art() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
save_design(&mut s, "Pill");
|
||||
let id = graph(&mut s, "line");
|
||||
s.execute("graph.marker", &json!({"id": id.0, "seriesIndexes": [1], "design": "Pill"})).unwrap();
|
||||
let marker = series(s.doc().unwrap().doc.node(id).unwrap(), 1).children().unwrap()[1].clone();
|
||||
assert!(matches!(marker.kind, NodeKind::Group { .. }), "the design's art");
|
||||
refused_on_design_art(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "ids": [marker.id.0]}));
|
||||
}
|
||||
|
||||
/// A series' kept opacity goes on its generated marks only: a column design made of one path keeps its own opacity.
|
||||
#[test]
|
||||
fn a_column_design_keeps_its_own_opacity_under_a_series_opacity() {
|
||||
@@ -1745,8 +1877,8 @@ fn a_paint_on_a_design_copy_or_the_other_kind_of_row_is_not_kept() {
|
||||
s.execute("graph.column", &json!({"id": id.0, "design": "Square"})).unwrap();
|
||||
let copy = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].clone();
|
||||
assert!(matches!(copy.kind, NodeKind::Group { .. }));
|
||||
s.execute("appearance.addFill", &json!({"ids": [copy.id.0]})).unwrap();
|
||||
s.execute("appearance.setItem", &json!({"ids": [copy.id.0], "index": 0, "color": "#0000ff"})).unwrap();
|
||||
assert!(s.execute("appearance.addFill", &json!({"ids": [copy.id.0]})).is_err());
|
||||
assert!(s.execute("appearance.setItem", &json!({"ids": [copy.id.0], "index": 0, "color": "#0000ff"})).is_err());
|
||||
assert!(spec(&s, id).series_paints.first().is_none_or(|p| p.fill.is_none()));
|
||||
// A path inside the design's copy is a member of the series too, and its paint is not kept either.
|
||||
let copy = series(s.doc().unwrap().doc.node(id).unwrap(), 0).children().unwrap()[0].clone();
|
||||
@@ -1757,7 +1889,7 @@ fn a_paint_on_a_design_copy_or_the_other_kind_of_row_is_not_kept() {
|
||||
}
|
||||
});
|
||||
let art = paths[0];
|
||||
s.execute("appearance.setItem", &json!({"ids": [art.0], "index": top_row(&s, art, true), "color": "#00ff00"})).unwrap();
|
||||
assert!(s.execute("appearance.setItem", &json!({"ids": [art.0], "index": top_row(&s, art, true), "color": "#00ff00"})).is_err());
|
||||
assert!(spec(&s, id).series_paints.first().is_none_or(|p| p.fill.is_none()));
|
||||
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -332,7 +332,7 @@ fn style_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let i = style_index(&s.doc()?.doc, name)?;
|
||||
let add = bool_or(p, "add", false);
|
||||
let chars = s.prefs.override_char_color;
|
||||
let own = super::appearance::appearance_targets(s, p)?;
|
||||
let own = super::appearance::edit_targets(s, p)?;
|
||||
let ids = super::appearance::rowless_series_marks(&s.doc()?.doc, &own);
|
||||
// The series groups their paths stand for: a style that replaces the appearance clears what they hold themselves,
|
||||
// and a style added on top unlinks them.
|
||||
|
||||
@@ -161,11 +161,13 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "graphicStyle.addFromLibrary";
|
||||
let (info, lib) = library_param(s, p, C)?;
|
||||
let (apply, add) = (switch_or(p, "apply", false, C)?, switch_or(p, "add", false, C)?);
|
||||
if p.get("ids").is_some_and(|v| !v.is_null()) {
|
||||
let ids_given = p.get("ids").is_some_and(|v| !v.is_null());
|
||||
if ids_given {
|
||||
checked_ids_param(s, p, "ids", C)?;
|
||||
} else if apply {
|
||||
// A selection that can't take a style is refused before any style is added.
|
||||
super::appearance::appearance_targets(s, &json!({}))?;
|
||||
}
|
||||
if apply {
|
||||
// Objects that can't take a style are refused before any style is added.
|
||||
super::appearance::edit_targets(s, &if ids_given { json!({"ids": p["ids"]}) } else { json!({}) })?;
|
||||
}
|
||||
let mut names = names_param(p, C)?;
|
||||
names.extend(text_param(p, "name", C)?.map(str::to_string));
|
||||
|
||||
@@ -128,6 +128,11 @@ pub struct DocState {
|
||||
empty_artboards: std::cell::RefCell<EmptyArtboards>,
|
||||
/// What [`DocState::any_art_to_fit`] last measured. Not saved.
|
||||
art_to_fit: std::cell::RefCell<Option<ArtToFit>>,
|
||||
/// The document as [`crate::Session::replace_document`] left it in a tab in the back, with its
|
||||
/// type measured in its own composite fonts, and the lowercased names of those fonts. When the
|
||||
/// same document comes to the front, its type set in them is not measured again. While this
|
||||
/// reference lasts, its allocation holds no other document. Not saved.
|
||||
pub(crate) measured_in_own: Option<(std::sync::Weak<Document>, std::collections::HashSet<String>)>,
|
||||
}
|
||||
|
||||
/// Whether a document has an artboard for Delete Empty Artboards to delete, with the document that
|
||||
@@ -345,6 +350,7 @@ impl DocState {
|
||||
empty_artboards: Default::default(),
|
||||
plugin_effects: Default::default(),
|
||||
art_to_fit: Default::default(),
|
||||
measured_in_own: None,
|
||||
}
|
||||
}
|
||||
/// `measure`'s answer for the document now. `measure` runs once for each version of the document,
|
||||
|
||||
@@ -241,10 +241,18 @@ impl Session {
|
||||
/// Register the composite fonts of the document now in front ([`cmd::compositefonts::sync`]),
|
||||
/// after a switch or a close brought it there. Its type set in a composite font that differs
|
||||
/// from the one of that name before (added, changed or removed) is measured again, and type not
|
||||
/// measured yet (in a document replaced while in the back) is measured now.
|
||||
/// measured yet is measured now. Type that [`Session::replace_document`] measured in the
|
||||
/// document's own composite fonts while it was in the back is not measured again when the
|
||||
/// document is unchanged since.
|
||||
fn sync_front_composite_fonts(&mut self) {
|
||||
let changed: HashSet<String> = cmd::compositefonts::sync(self).into_iter().collect();
|
||||
let mut changed: HashSet<String> = cmd::compositefonts::sync(self).into_iter().collect();
|
||||
let Some(index) = self.active else { return };
|
||||
if let Some(st) = self.docs.get_mut(index)
|
||||
&& let Some((doc, own)) = st.measured_in_own.take()
|
||||
&& std::ptr::eq(doc.as_ptr(), Arc::as_ptr(&st.doc))
|
||||
{
|
||||
changed.retain(|n| !own.contains(n));
|
||||
}
|
||||
self.refresh_document_text_bounds(index, |t| t.cached_bounds.is_none() || sets_in_any(t, &changed));
|
||||
}
|
||||
|
||||
@@ -347,14 +355,10 @@ impl Session {
|
||||
doc.resolve_inline_art();
|
||||
doc.guides_into_nodes();
|
||||
cmd::dimension::conform(&mut doc);
|
||||
// In the back, type set in a font named like a composite font is measured when the document
|
||||
// comes to the front and its own composite fonts are registered, not in the front
|
||||
// document's.
|
||||
let mut back_names = None;
|
||||
if self.active == Some(index) {
|
||||
// Pending tool work (typing, a drag) belongs to the content being thrown away.
|
||||
self.reset_tool_for_doc_switch();
|
||||
} else {
|
||||
// In the back, type set in a font named like a composite font is measured again below, in
|
||||
// the document's own composite fonts, not in the front document's.
|
||||
let back = self.active != Some(index);
|
||||
if back {
|
||||
let mut names = cmd::compositefonts::names_in_use(self);
|
||||
names.extend(doc.composite_fonts.iter().map(|f| f.name.to_lowercase()));
|
||||
for tree in text_trees_mut(&mut doc) {
|
||||
@@ -363,7 +367,9 @@ impl Session {
|
||||
t.cached_baselines.clear();
|
||||
});
|
||||
}
|
||||
back_names = Some(names);
|
||||
} else {
|
||||
// Pending tool work (typing, a drag) belongs to the content being thrown away.
|
||||
self.reset_tool_for_doc_switch();
|
||||
}
|
||||
let old = &self.docs[index];
|
||||
let mut st = DocState::new(doc, old.path.clone());
|
||||
@@ -396,16 +402,36 @@ impl Session {
|
||||
if let Some(stash) = &mut self.batch_stash {
|
||||
stash.push(old);
|
||||
}
|
||||
match back_names {
|
||||
Some(names) => self.refresh_document_text_bounds(index, |t| t.cached_bounds.is_none() && !sets_in_any(t, &names)),
|
||||
None => {
|
||||
self.sync_opened_composite_fonts(index);
|
||||
self.sync_front_profiles();
|
||||
}
|
||||
if back {
|
||||
self.measure_back_document(index);
|
||||
} else {
|
||||
self.sync_opened_composite_fonts(index);
|
||||
self.sync_front_profiles();
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Measure the type not measured yet in open document `index`, which is in the back, in its own
|
||||
/// composite fonts, lent for the measuring, so its type has the bounds it will have when the
|
||||
/// document comes to the front. The front document stays the one whose composite fonts are
|
||||
/// registered. The names of the document's composite fonts its type was measured in are kept,
|
||||
/// so its coming to the front does not measure that type again.
|
||||
fn measure_back_document(&mut self, index: usize) {
|
||||
let Some(st) = self.docs.get(index) else { return };
|
||||
let fonts = st.doc.composite_fonts.clone();
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let lent = db.lend_composite_fonts(&fonts);
|
||||
// A name another loan holds with a different definition is not lent: type set in it is
|
||||
// measured again when the document comes to the front.
|
||||
let own: HashSet<String> =
|
||||
fonts.iter().filter(|f| db.composite_font(&f.name).is_some_and(|have| *have == **f)).map(|f| f.name.to_lowercase()).collect();
|
||||
self.refresh_document_text_bounds(index, |t| t.cached_bounds.is_none());
|
||||
drop(lent);
|
||||
if let Some(st) = self.docs.get_mut(index) {
|
||||
st.measured_in_own = Some((Arc::downgrade(&st.doc), own));
|
||||
}
|
||||
}
|
||||
|
||||
/// Close the document in tab `index` (`file.close`). Closing a tab other than the current one
|
||||
/// keeps the current document current, and its tool keeps its state: no document is switched
|
||||
/// to. Closing the current document makes the tab now at `index` current, or the last tab when
|
||||
|
||||
@@ -253,3 +253,91 @@ fn events_and_files_survive_a_native_round_trip_and_reach_svg() {
|
||||
assert!(svg.contains(" onclick=\"show("menu") && x < 1\""), "{svg}");
|
||||
assert!(svg.contains("<script xlink:href=\"menu.js\"/>"), "{svg}");
|
||||
}
|
||||
|
||||
/// A caller confined to read roots: every SVG and SVGZ output of a document that links a
|
||||
/// JavaScript file outside them is refused before a file or folder is written, with an error that
|
||||
/// names no file or folder, and the document keeps the link.
|
||||
#[test]
|
||||
fn confined_svg_output_refuses_a_linked_javascript_file_outside_the_read_roots() {
|
||||
let away = crate::tests_links::Folder::new("svg-script-away");
|
||||
let home = crate::tests_links::Folder::new("svg-script-home");
|
||||
let script = away.file("menu.js");
|
||||
let mut s = session();
|
||||
let a = rect(&mut s, 10.0);
|
||||
run(&mut s, "svgInteractivity.addFile", json!({"file": script}));
|
||||
run(&mut s, "assets.add", json!({"ids": [a.0]}));
|
||||
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap();
|
||||
let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned(), "menu.js".to_string()];
|
||||
let refused = |s: &mut Session, cmd: &str, p: Value| {
|
||||
let e = crate::file_access::confine(Some(&roots), || s.execute(cmd, &p)).expect_err(cmd).to_string();
|
||||
assert!(e.contains("a linked JavaScript file is outside the read roots"), "{cmd} {p}: {e}");
|
||||
for h in &hidden {
|
||||
assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}");
|
||||
}
|
||||
};
|
||||
let out = home.file("out");
|
||||
for format in ["svg", "svgz"] {
|
||||
let file = |name: &str| home.file(&format!("{name}.{format}"));
|
||||
refused(&mut s, "document.serialize", json!({"format": format}));
|
||||
refused(&mut s, "document.export", json!({"format": format}));
|
||||
refused(&mut s, "document.export", json!({"format": format, "path": file("export")}));
|
||||
refused(&mut s, "document.export", json!({"format": format, "selectedOnly": true}));
|
||||
refused(&mut s, "document.exportSelection", json!({"format": format, "path": file("selection")}));
|
||||
refused(&mut s, "document.save", json!({"path": file("save")}));
|
||||
refused(&mut s, "file.saveAs", json!({"format": format, "path": file("save-as")}));
|
||||
refused(&mut s, "file.saveCopy", json!({"format": format, "path": file("copy")}));
|
||||
refused(&mut s, "document.exportForScreens", json!({"folder": out, "formats": [{"format": "png"}, {"format": format}]}));
|
||||
refused(&mut s, "document.exportForScreens", json!({"zip": true, "formats": [{"format": format}]}));
|
||||
refused(&mut s, "assets.export", json!({"folder": out, "formats": [{"format": format}]}));
|
||||
}
|
||||
// A document saved as SVG saves as SVG again without a path: its file is left as it was.
|
||||
let own = home.file("own.svg");
|
||||
run(&mut s, "file.saveAs", json!({"path": own}));
|
||||
let before = std::fs::read(&own).unwrap();
|
||||
rect(&mut s, 50.0);
|
||||
refused(&mut s, "document.save", json!({}));
|
||||
assert_eq!(std::fs::read(&own).unwrap(), before);
|
||||
let written: Vec<_> = std::fs::read_dir(&home.0).unwrap().map(|e| e.unwrap().file_name()).collect();
|
||||
assert_eq!(written, ["own.svg"]);
|
||||
assert_eq!(s.doc().unwrap().doc.svg_scripts, [script]);
|
||||
}
|
||||
|
||||
/// A confined caller's SVG keeps every linked JavaScript file it may read, as stored: a file inside
|
||||
/// the read roots, a path relative to the document's folder that leads inside them, and a URL. A
|
||||
/// caller without roots writes a file outside them too.
|
||||
#[test]
|
||||
fn svg_output_keeps_linked_javascript_files_a_caller_may_read() {
|
||||
let away = crate::tests_links::Folder::new("svg-script-kept-away");
|
||||
let home = crate::tests_links::Folder::new("svg-script-kept-home");
|
||||
let inside = home.file("menu.js");
|
||||
let url = "https://example.com/scripts/menu.js";
|
||||
let mut s = session();
|
||||
rect(&mut s, 10.0);
|
||||
for file in [inside.as_str(), "lib/tools.js", url] {
|
||||
run(&mut s, "svgInteractivity.addFile", json!({"file": file}));
|
||||
}
|
||||
run(&mut s, "file.saveAs", json!({"path": home.file("doc.vectorcraft")}));
|
||||
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap();
|
||||
let svg = |s: &mut Session, format: &str| {
|
||||
let r = crate::file_access::confine(Some(&roots), || s.execute("document.serialize", &json!({"format": format}))).unwrap();
|
||||
match r["text"].as_str() {
|
||||
Some(text) => text.to_string(),
|
||||
None => {
|
||||
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
|
||||
assert!(vectorcraft_svg::is_svgz(&bytes), "gzip magic");
|
||||
vectorcraft_svg::text_of(&bytes).unwrap().into_owned()
|
||||
}
|
||||
}
|
||||
};
|
||||
for format in ["svg", "svgz"] {
|
||||
let text = svg(&mut s, format);
|
||||
for file in [inside.as_str(), "lib/tools.js", url] {
|
||||
assert!(text.contains(&format!("<script xlink:href=\"{file}\"/>")), "{format} {file}: {text}");
|
||||
}
|
||||
}
|
||||
// Without roots, a file outside them is written as stored.
|
||||
let outside = away.file("menu.js");
|
||||
run(&mut s, "svgInteractivity.addFile", json!({"file": outside}));
|
||||
let text = run(&mut s, "document.serialize", json!({"format": "svg"}))["text"].as_str().unwrap().to_string();
|
||||
assert!(text.contains(&format!("<script xlink:href=\"{outside}\"/>")), "{text}");
|
||||
}
|
||||
@@ -502,3 +502,80 @@ fn batched_colored_inflate_preserves_compound_holes_and_surface_opacity() {
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
assert_eq!(image.pixels, render(doc(&s)).pixels);
|
||||
}
|
||||
|
||||
/// Under colored lights, an Inflate fill and stroke in solid colors draw each face on its own, in
|
||||
/// one depth order: zoomed in, the fill's faces show the colors the one composite of the surface
|
||||
/// shows (drawn when the stroke is translucent), with no seam between faces; at 1x, where a pixel
|
||||
/// holds several faces, all but a few pixels show the average of the zoomed-in colors; and the art
|
||||
/// keeps its colors through SVG export and Expand Appearance.
|
||||
#[test]
|
||||
fn colored_solid_inflate_faces_in_one_order_keep_the_composites_colors_and_seams() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width":400,"height":400})).unwrap();
|
||||
s.execute("path.create", &json!({"d":"M100 100H300V300H100Z"})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color":"#e0c080"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color":"#204060","width":4})).unwrap();
|
||||
s.execute(
|
||||
"effect.apply",
|
||||
&json!({"effect":"threeD.inflate","item":null,"params":{
|
||||
"rotationX":0,"rotationY":0,"rotationZ":0,"lights":[{"color":"#ff4040"},{"color":"#4040ff","rotation":120}]
|
||||
}}),
|
||||
)
|
||||
.unwrap();
|
||||
let at = |d: &Document, scale: f64| {
|
||||
vectorcraft_render::Renderer::new().render(
|
||||
d,
|
||||
400,
|
||||
400,
|
||||
kurbo::Affine::scale(scale) * kurbo::Affine::translate((-140.0, -140.0)),
|
||||
&vectorcraft_render::RenderOptions { background: None, artboards: false, ..Default::default() },
|
||||
)
|
||||
};
|
||||
let ordered = doc(&s).clone();
|
||||
s.execute("transparency.set", &json!({"item":1,"opacity":99})).unwrap();
|
||||
let whole = doc(&s).clone();
|
||||
// The fill's puff, inside the stroke's: 150 to 250 pt across, 10 to 110 px at 1x.
|
||||
let (near, near_whole, far) = (at(&ordered, 3.0), at(&whole, 3.0), at(&ordered, 1.0));
|
||||
let (mut off, mut open) = (0, 0);
|
||||
for y in 10..110u32 {
|
||||
for x in 10..110u32 {
|
||||
// At 3x each 1x pixel is nine pixels: the faces against the composite, pixel by pixel.
|
||||
let mut sum = [0u32; 4];
|
||||
for (dx, dy) in (0..9).map(|k| (k % 3, k / 3)) {
|
||||
let (p, q) = (near.pixel(x * 3 + dx, y * 3 + dy), near_whole.pixel(x * 3 + dx, y * 3 + dy));
|
||||
assert!(p[3] >= 254, "no seam at ({}, {}) at 3x: {p:?}", x * 3 + dx, y * 3 + dy);
|
||||
assert!(
|
||||
p.into_iter().zip(q).all(|(p, q)| p.abs_diff(q) <= 1),
|
||||
"({}, {}) at 3x: {p:?} vs the composite's {q:?}",
|
||||
x * 3 + dx,
|
||||
y * 3 + dy
|
||||
);
|
||||
for (s, v) in sum.iter_mut().zip(p) {
|
||||
*s += u32::from(v);
|
||||
}
|
||||
}
|
||||
// At 1x, where a pixel holds several faces, a pixel has about the average of its nine:
|
||||
// a few pixels where thin faces meet are off by more than 3 or let a little through.
|
||||
let p = far.pixel(x, y);
|
||||
assert!(p[3] >= 240, "a seam at ({x},{y}) at 1x: {p:?}");
|
||||
open += usize::from(p[3] < 255);
|
||||
off += usize::from(p.into_iter().zip(sum).any(|(p, s)| u32::from(p).abs_diff(s / 9) > 3));
|
||||
}
|
||||
}
|
||||
assert!(open <= 500, "{open} of 10,000 pixels at 1x let the background through");
|
||||
assert!(off <= 300, "{off} of 10,000 pixels at 1x are off the zoomed-in colors");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(doc(&s), &ordered);
|
||||
let live = render(doc(&s));
|
||||
let svg = s.execute("document.serialize", &json!({"format":"svg"})).unwrap()["text"].as_str().unwrap().to_owned();
|
||||
assert!(!svg.contains("<image"));
|
||||
let roundtrip = render(&vectorcraft_svg::import(&svg).unwrap());
|
||||
for y in (110..290).step_by(9) {
|
||||
for x in (110..290).step_by(9) {
|
||||
let (a, b) = (live.pixel(x, y), roundtrip.pixel(x, y));
|
||||
assert!(a.into_iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 6), "SVG ({x},{y}): {a:?} vs {b:?}");
|
||||
}
|
||||
}
|
||||
s.execute("effect.expandAppearance", &json!({})).unwrap();
|
||||
assert_eq!(render(doc(&s)).pixels, live.pixels);
|
||||
}
|
||||
@@ -9793,3 +9793,233 @@ fn envelopes_document() -> Document {
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
// ---------- text wrap ----------
|
||||
|
||||
/// `n` with text wrap options `offset` and `invert`.
|
||||
fn wrapped(mut n: Node, offset: f64, invert: bool) -> Node {
|
||||
n.extras_mut().wrap = Some(vectorcraft_doc::TextWrap { offset, invert });
|
||||
n
|
||||
}
|
||||
|
||||
/// The text wrap options of `nodes` and of the objects they hold, in order, each with its object's
|
||||
/// name.
|
||||
fn wraps(nodes: &[Arc<Node>]) -> Vec<(Option<String>, f64, bool)> {
|
||||
let mut out = vec![];
|
||||
for n in nodes {
|
||||
n.walk(&mut |m| {
|
||||
if let Some(w) = m.extras().wrap {
|
||||
out.push((m.name.clone(), w.offset, w.invert));
|
||||
}
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `got` and `want` name the same objects with the same Invert Wrap, and offsets within `1e-6`.
|
||||
fn same_wraps(got: &[(Option<String>, f64, bool)], want: &[(Option<String>, f64, bool)]) {
|
||||
let close = got.len() == want.len() && got.iter().zip(want).all(|(g, w)| g.0 == w.0 && g.2 == w.2 && (g.1 - w.1).abs() < 1e-6);
|
||||
assert!(close, "{got:?}\n{want:?}");
|
||||
}
|
||||
|
||||
/// The dictionary entries of text wrap options `offset` (as written) and `invert`.
|
||||
fn wrap_entries(offset: &str, invert: bool) -> String {
|
||||
format!("%_{offset} /Real (AI11TextWrapOffset) ,\n%_{} /Bool (AI11TextWrapInvert) ,\n", u8::from(invert))
|
||||
}
|
||||
|
||||
/// Text wrap options are written in each object's dictionary and read back: a positive and a
|
||||
/// negative offset, Invert Wrap on and off, the default options, an object without them, a named
|
||||
/// object with an opacity mask, a group, a compound path and a clipping group's clipping path. An
|
||||
/// offset that isn't finite is written as the default 6 pt, and one past the -1000 to 1000 pt the
|
||||
/// reader keeps as the nearer end of that range.
|
||||
#[test]
|
||||
fn text_wrap_options_are_written_and_read_back() {
|
||||
let mut doc = Document::new(400.0, 200.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let plain = |doc: &mut Document, x: f64| square(doc, Rect::new(x, 10.0, x + 20.0, 30.0), Color::gray(0.5));
|
||||
let a = wrapped(plain(&mut doc, 10.0), 12.5, false);
|
||||
let b = wrapped(plain(&mut doc, 40.0), -4.25, true);
|
||||
let c = wrapped(plain(&mut doc, 70.0), 6.0, false);
|
||||
let d = plain(&mut doc, 100.0);
|
||||
let mut e = named(wrapped(plain(&mut doc, 130.0), 3.0, true), "Badge");
|
||||
let mask_art = plain(&mut doc, 130.0);
|
||||
e.extras_mut().mask = Some(Box::new(OpacityMask::new(mask_art, false)));
|
||||
let members = vec![plain(&mut doc, 160.0), plain(&mut doc, 190.0)];
|
||||
let f = wrapped(group(&mut doc, members, false), -2.0, false);
|
||||
let outer = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(220.0, 10.0, 260.0, 50.0)), Appearance::default());
|
||||
let inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(230.0, 20.0, 250.0, 40.0)), Appearance::default());
|
||||
let mut ring = Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd });
|
||||
ring.appearance = Appearance::basic(solid(Color::gray(0.5)), Paint::None, 0.0).into();
|
||||
let g = wrapped(ring, 7.0, true);
|
||||
let clip = wrapped(clipping(&mut doc, shapes::rectangle(Rect::new(280.0, 10.0, 320.0, 50.0))), 5.0, false);
|
||||
let clipped = plain(&mut doc, 290.0);
|
||||
let h = group(&mut doc, vec![clip, clipped], true);
|
||||
for n in [a, b, c, d, e, f, g, h] {
|
||||
doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
}
|
||||
assert_eq!(doc.layers[0].children().unwrap()[2].extras().wrap, Some(vectorcraft_doc::TextWrap::default()));
|
||||
let text = program(&doc);
|
||||
for entries in
|
||||
[wrap_entries("12.5", false), wrap_entries("-4.25", true), wrap_entries("6", false), wrap_entries("-2", false), wrap_entries("7", true)]
|
||||
{
|
||||
assert!(text.contains(&entries), "{entries}\n{text}");
|
||||
}
|
||||
assert_eq!(text.matches("(AI11TextWrapOffset)").count(), 7, "{text}");
|
||||
assert!(!text.contains("AI11TextWrapPath"), "{text}");
|
||||
let back = read_back(&doc);
|
||||
same_wraps(&wraps(back.layers[0].children().unwrap()), &wraps(doc.layers[0].children().unwrap()));
|
||||
let kept: Vec<_> = back.layers[0].children().unwrap().iter().map(|n| (n.extras().wrap, n.extras().mask.is_some())).collect();
|
||||
let want: Vec<_> = doc.layers[0].children().unwrap().iter().map(|n| (n.extras().wrap, n.extras().mask.is_some())).collect();
|
||||
assert_eq!(kept, want);
|
||||
|
||||
// An offset that isn't finite, and offsets past the range the reader keeps.
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let odd = wrapped(plain(&mut doc, 10.0), f64::NAN, true);
|
||||
let far = wrapped(plain(&mut doc, 40.0), 1e300, false);
|
||||
let far_in = wrapped(plain(&mut doc, 70.0), -1000.5, false);
|
||||
let layer = doc.layers[0].id;
|
||||
for n in [odd, far, far_in] {
|
||||
doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
}
|
||||
let text = program(&doc);
|
||||
for entries in [wrap_entries("6", true), wrap_entries("1000", false), wrap_entries("-1000", false)] {
|
||||
assert!(text.contains(&entries), "{entries}\n{text}");
|
||||
}
|
||||
same_wraps(&wraps(read_back(&doc).layers[0].children().unwrap()), &[(None, 6.0, true), (None, 1000.0, false), (None, -1000.0, false)]);
|
||||
}
|
||||
|
||||
/// The art drawn for an object (a blend's steps, a stained symbol instance's art) is written
|
||||
/// without the text wrap options of the objects it is made from, which wrap no type; the object
|
||||
/// keeps its own. A symbol's art and a live instance keep theirs.
|
||||
#[test]
|
||||
fn drawn_art_keeps_only_its_objects_text_wrap() {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let keys = vec![
|
||||
Arc::new(wrapped(square(&mut doc, Rect::new(10.0, 10.0, 12.0, 12.0), Color::gray(0.5)), 2.0, true)),
|
||||
Arc::new(wrapped(square(&mut doc, Rect::new(30.0, 10.0, 32.0, 12.0), Color::gray(0.5)), 2.0, true)),
|
||||
];
|
||||
let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(10.0), ..Default::default() };
|
||||
let blend = wrapped(Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) }), 8.0, false);
|
||||
let art = wrapped(square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF), 4.0, true);
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) });
|
||||
let mut stained = instance(&mut doc, "Leaf", Affine::translate((50.0, 10.0)));
|
||||
stained.appearance = Appearance::basic(solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0).into();
|
||||
let live = wrapped(instance(&mut doc, "Leaf", Affine::translate((80.0, 10.0))), -3.0, false);
|
||||
for n in [blend, stained, live] {
|
||||
doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
}
|
||||
let back = read_back(&doc);
|
||||
same_wraps(&wraps(back.layers[0].children().unwrap()), &[(None, 8.0, false), (None, -3.0, false)]);
|
||||
assert!(matches!(back.layers[0].children().unwrap()[2].kind, NodeKind::SymbolInstance { .. }));
|
||||
same_wraps(&wraps(&[back.symbols[0].art.clone()]), &[(None, 4.0, true)]);
|
||||
|
||||
// An object kept with an art style: its options go with the object, not its drawn look.
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let shadow = fx("stylize.dropShadow", serde_json::json!({"x": 6.0, "y": 4.0, "blur": 8.0}));
|
||||
let shadowed = styled_rect(&mut doc, "Shadowed", Rect::new(10.0, 10.0, 60.0, 50.0), solid(Color::gray(0.5)), Paint::None, vec![shadow]);
|
||||
doc.insert(Some(layer), usize::MAX, wrapped(shadowed, 9.0, true)).unwrap();
|
||||
let text = program(&doc);
|
||||
assert!(text.contains("(Anon 1) XW") && text.matches("(AI11TextWrapOffset)").count() == 1, "{text}");
|
||||
let back = read_back(&doc);
|
||||
same_wraps(&wraps(back.layers[0].children().unwrap()), &[(Some("Shadowed".into()), 9.0, true)]);
|
||||
}
|
||||
|
||||
/// On a large canvas the offsets are written at the art's scale (1/10) and read back at their size,
|
||||
/// an instance written as its art keeps its own options, and a symbol's art, defined at its own
|
||||
/// size, keeps its offset as it is.
|
||||
#[test]
|
||||
fn text_wrap_offsets_on_a_large_canvas_come_back_at_their_size() {
|
||||
let mut doc = Document::new(20_000.0, 20_000.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let a = wrapped(square(&mut doc, Rect::new(1000.0, 1000.0, 1200.0, 1200.0), Color::gray(0.5)), -12.34, true);
|
||||
let b = wrapped(square(&mut doc, Rect::new(1400.0, 1000.0, 1600.0, 1200.0), Color::gray(0.5)), 250.0, false);
|
||||
let art = wrapped(square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), LEAF), 4.0, true);
|
||||
doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) });
|
||||
let one = wrapped(instance(&mut doc, "Leaf", Affine::translate((2000.0, 1000.0))), -3.0, false);
|
||||
for n in [a, b, one] {
|
||||
doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
}
|
||||
let text = program(&doc);
|
||||
for entries in [wrap_entries("-1.234", true), wrap_entries("25", false), wrap_entries("-0.3", false), wrap_entries("4", true)] {
|
||||
assert!(text.contains(&entries), "{entries}\n{text}");
|
||||
}
|
||||
let want = [(None, -12.34, true), (None, 250.0, false), (None, -3.0, false)];
|
||||
let symbol = [(None, 4.0, true)];
|
||||
// From the editing data alone.
|
||||
let back = read_back(&doc);
|
||||
same_wraps(&wraps(back.layers[0].children().unwrap()), &want);
|
||||
same_wraps(&wraps(&[back.symbols[0].art.clone()]), &symbol);
|
||||
// Beside a page of the artboard's size in points.
|
||||
let (p, _) = private_data(&doc, &opts()).unwrap();
|
||||
let (read, notes, layers) = crate::layered_ai(&p.data, Document::new(20_000.0, 20_000.0), vec![], false, true, 1.389);
|
||||
assert!(layers, "{notes:?}");
|
||||
same_wraps(&wraps(read.layers[0].children().unwrap()), &want);
|
||||
same_wraps(&wraps(&[read.symbols[0].art.clone()]), &symbol);
|
||||
}
|
||||
|
||||
/// Type and envelopes keep their own text wrap options: point type, each frame of threaded area
|
||||
/// type (one with options, one without, in either order) and an envelope kept live.
|
||||
#[test]
|
||||
fn text_wrap_options_of_type_and_envelopes_are_read_back() {
|
||||
use vectorcraft_doc::{TextKind, TextObject, TextRun};
|
||||
for first_wraps in [true, false] {
|
||||
let mut doc = Document::new(300.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let st = style(10.0, Color::BLACK);
|
||||
let mut first = TextObject::point(vectorcraft_geom::Point::ZERO, "", st.clone());
|
||||
first.runs = vec![TextRun::new("One two three ", st.clone())];
|
||||
first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(10.0, 10.0, 90.0, 40.0)) };
|
||||
first.xf = Affine::IDENTITY;
|
||||
let mut second = first.clone();
|
||||
second.runs = vec![TextRun::new("four five", st.clone())];
|
||||
second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(110.0, 10.0, 190.0, 40.0)) };
|
||||
let (mut first, mut second) = (named(text_node(&mut doc, first), "First"), named(text_node(&mut doc, second), "Second"));
|
||||
let frame = if first_wraps { &mut first } else { &mut second };
|
||||
frame.extras_mut().wrap = Some(vectorcraft_doc::TextWrap { offset: 3.5, invert: true });
|
||||
doc.text_threads.push(vec![first.id, second.id]);
|
||||
let label = TextObject::point(vectorcraft_geom::Point::new(210.0, 30.0), "Label", st);
|
||||
let label = wrapped(named(text_node(&mut doc, label), "Label"), -1.5, false);
|
||||
for n in [first, second, label] {
|
||||
doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
}
|
||||
let back = read_back(&doc);
|
||||
assert_eq!(back.text_threads.len(), 1, "the frames stay type");
|
||||
let frame = if first_wraps { "First" } else { "Second" };
|
||||
same_wraps(&wraps(back.layers[0].children().unwrap()), &[(Some(frame.into()), 3.5, true), (Some("Label".into()), -1.5, false)]);
|
||||
}
|
||||
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let kinds = live_envelope_kinds();
|
||||
let (_, arc) = kinds.iter().find(|(n, _)| *n == "arc").unwrap();
|
||||
let bent = wrapped(envelope_node(&mut doc, arc.clone(), 50.0, false, vectorcraft_doc::live::EnvelopeOptions::NEW), 2.5, true);
|
||||
doc.insert(Some(layer), usize::MAX, bent).unwrap();
|
||||
let back = read_back(&doc);
|
||||
let top = back.layers[0].children().unwrap();
|
||||
assert!(matches!(top[0].kind, NodeKind::Envelope { .. }));
|
||||
same_wraps(&wraps(top), &[(Some("Bent".into()), 2.5, true)]);
|
||||
}
|
||||
|
||||
/// A clipping path inside art cut to a clipping object is written as its fills and its strokes,
|
||||
/// two objects: its text wrap options are written once, whether it has both or only strokes.
|
||||
#[test]
|
||||
fn a_clipping_path_written_as_its_paint_keeps_one_text_wrap() {
|
||||
for fill in [solid(Color::gray(0.5)), Paint::None] {
|
||||
let mut doc = Document::new(200.0, 100.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let mut cutter = clipping(&mut doc, shapes::rectangle(Rect::new(20.0, 20.0, 80.0, 80.0)));
|
||||
cutter.appearance = Appearance::basic(fill, solid(Color::BLACK), 2.0).into();
|
||||
let cutter = wrapped(cutter, 5.0, true);
|
||||
let member = square(&mut doc, Rect::new(30.0, 30.0, 120.0, 60.0), Color::rgb(1.0, 0.0, 0.0));
|
||||
let inner = group(&mut doc, vec![cutter, member], true);
|
||||
let frame = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::gray(0.9));
|
||||
let frame = group(&mut doc, vec![frame], false);
|
||||
let outer = group(&mut doc, vec![frame, inner], true);
|
||||
doc.insert(Some(layer), usize::MAX, outer).unwrap();
|
||||
let text = program(&doc);
|
||||
assert_eq!(text.matches("(AI11TextWrapOffset)").count(), 1, "{text}");
|
||||
same_wraps(&wraps(read_back(&doc).layers[0].children().unwrap()), &[(None, 5.0, true)]);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ use std::sync::Arc;
|
||||
use vectorcraft_color::cms::Cms;
|
||||
use vectorcraft_color::swatch::{REGISTRATION, Swatch};
|
||||
use vectorcraft_color::{BlendMode, Color, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, Document, FillLayer, Knockout, LayerColor, Node, NodeId, NodeKind, OpacityMask, StrokeLayer};
|
||||
use vectorcraft_doc::{AppearanceItem, Document, FillLayer, Knockout, LayerColor, Node, NodeId, NodeKind, OpacityMask, StrokeLayer, TextWrap};
|
||||
use vectorcraft_effects::stroke;
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Shape, SubPath};
|
||||
use vectorcraft_pathops::BoolOp;
|
||||
@@ -263,6 +263,10 @@ pub(super) struct Writer<'a> {
|
||||
/// An object's drawn look is being written: no object in it is written with a style, and its
|
||||
/// effects are the style's.
|
||||
in_look: bool,
|
||||
/// How many parts of art drawn for an object (a live object's art, a symbol instance's art, a
|
||||
/// brushed stroke's pieces) the art being written is in. Text wrap options are written only
|
||||
/// outside them, since only the document's own objects wrap type.
|
||||
drawn: u32,
|
||||
/// The brushes written ([`brushes`]).
|
||||
brush_set: brushes::Brushes,
|
||||
/// Brushes may be written; false on a large canvas, where they are left out.
|
||||
@@ -329,6 +333,7 @@ impl<'a> Writer<'a> {
|
||||
styled: HashMap::new(),
|
||||
styles: styles::Styles::default(),
|
||||
in_look: false,
|
||||
drawn: 0,
|
||||
brush_set: brushes::Brushes::default(),
|
||||
brushes_live: true,
|
||||
deform: false,
|
||||
@@ -700,7 +705,9 @@ impl<'a> Writer<'a> {
|
||||
art.locked = false;
|
||||
art.name = None;
|
||||
self.nest += 1;
|
||||
self.drawn += 1;
|
||||
self.node(&art);
|
||||
self.drawn -= 1;
|
||||
self.nest -= 1;
|
||||
} else {
|
||||
self.warn(SYMBOL_LIMIT);
|
||||
@@ -744,9 +751,11 @@ impl<'a> Writer<'a> {
|
||||
if self.nest < MAX_NEST {
|
||||
let g = vectorcraft_effects::expand_live_deep(Some(self.doc), n);
|
||||
self.nest += 1;
|
||||
self.drawn += 1;
|
||||
for c in g.children().map(Vec::as_slice).unwrap_or_default() {
|
||||
self.node(c);
|
||||
}
|
||||
self.drawn -= 1;
|
||||
self.nest -= 1;
|
||||
}
|
||||
self.end_group("U", xy);
|
||||
@@ -754,10 +763,12 @@ impl<'a> Writer<'a> {
|
||||
|
||||
/// `n`'s `/ArtDictionary`, after it, when it has a name (`AI10_ArtUID`, see [`Self::take_id`]),
|
||||
/// is bound to variables ([`Self::bound_variables`]; without a name, it gets an XML id and an
|
||||
/// empty `AIArtName`), has an opacity mask (`AI9_Mask`, see [`Self::mask`]), or is a symbol's
|
||||
/// art (its symbol's entries first, see [`Self::define_symbol`]).
|
||||
/// empty `AIArtName`), has text wrap options ([`Self::text_wrap`]), has an opacity mask
|
||||
/// (`AI9_Mask`, see [`Self::mask`]), or is a symbol's art (its symbol's entries first, see
|
||||
/// [`Self::define_symbol`]).
|
||||
fn dictionary(&mut self, n: &Node) {
|
||||
let name = n.name.as_deref().filter(|s| !s.is_empty());
|
||||
let wrap = n.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look);
|
||||
let placed = std::mem::take(&mut self.placed);
|
||||
let typed = std::mem::take(&mut self.typed);
|
||||
let bound = self.bound_variables(n, placed, typed);
|
||||
@@ -771,7 +782,7 @@ impl<'a> Writer<'a> {
|
||||
Some((id, _)) if *id == n.id => self.root_entries.take().map(|(_, e)| e),
|
||||
_ => None,
|
||||
};
|
||||
if name.is_none() && mask.is_none() && bound.is_empty() && entries.is_none() {
|
||||
if name.is_none() && mask.is_none() && bound.is_empty() && entries.is_none() && wrap.is_none() {
|
||||
return;
|
||||
}
|
||||
let start = self.body.len();
|
||||
@@ -792,17 +803,32 @@ impl<'a> Writer<'a> {
|
||||
self.bound.push((n.id, id, bound));
|
||||
}
|
||||
}
|
||||
if let Some(w) = wrap {
|
||||
self.text_wrap(w);
|
||||
}
|
||||
// A mask whose art doesn't fit is left out, and with nothing else in it the dictionary too.
|
||||
if let Some(m) = mask
|
||||
&& !self.mask(m)
|
||||
&& !has_id
|
||||
&& !has_entries
|
||||
&& wrap.is_none()
|
||||
{
|
||||
return self.body.truncate(start);
|
||||
}
|
||||
self.body.push_str("%_;\n%_\n");
|
||||
}
|
||||
|
||||
/// Text wrap options, as entries of their object's dictionary: the offset in art space's points
|
||||
/// (`AI11TextWrapOffset`, `/Real`; a value that isn't finite is written as the default 6 pt,
|
||||
/// and one past the -1000 to 1000 pt the reader keeps as the nearer end of that range) and
|
||||
/// Invert Wrap (`AI11TextWrapInvert`, `/Bool`, 1 or 0), as the reader reads them back.
|
||||
fn text_wrap(&mut self, w: TextWrap) {
|
||||
let offset = if w.offset.is_finite() { w.offset.clamp(-1000.0, 1000.0) } else { TextWrap::default().offset };
|
||||
self.body.push_str("%_");
|
||||
ps::push_num(&mut self.body, offset);
|
||||
let _ = writeln!(self.body, " /Real (AI11TextWrapOffset) ,\n%_{} /Bool (AI11TextWrapInvert) ,", u8::from(w.invert));
|
||||
}
|
||||
|
||||
/// An `/ArtDictionary` whose `AI10_ArtUID` is `name` as an XML id.
|
||||
fn xml_id(&mut self, name: &str) {
|
||||
let id = self.take_id(name);
|
||||
@@ -1006,12 +1032,18 @@ impl<'a> Writer<'a> {
|
||||
}
|
||||
|
||||
/// A container's members, the first one's outline cutting the others: its fills painted
|
||||
/// behind them (cut to the region outside too), its strokes over them, not cut by it.
|
||||
/// behind them (cut to the region outside too), its strokes over them, not cut by it. Its text
|
||||
/// wrap options are written once: with its fills, or without fills with its strokes.
|
||||
fn clip_contents(&mut self, children: &[Arc<Node>]) {
|
||||
let Some((first, rest)) = children.split_first() else { return };
|
||||
// Nothing to clip by hides the clipped art.
|
||||
let Some((outline, rule)) = vectorcraft_effects::clip_outline(first) else { return };
|
||||
let paint = first.clip_paint();
|
||||
let mut paint = first.clip_paint();
|
||||
if let (Some(_), Some(stroke)) = (&paint.fill, &mut paint.stroke)
|
||||
&& stroke.extras().wrap.is_some()
|
||||
{
|
||||
stroke.extras_mut().wrap = None;
|
||||
}
|
||||
let outer = self.clip.clone();
|
||||
let region = self.cut(&PathData::from_bezpath(&outline), rule);
|
||||
self.clip = Some(region);
|
||||
@@ -1101,9 +1133,11 @@ impl<'a> Writer<'a> {
|
||||
return true;
|
||||
}
|
||||
self.nest += 1;
|
||||
self.drawn += 1;
|
||||
for piece in &art {
|
||||
self.node(piece);
|
||||
}
|
||||
self.drawn -= 1;
|
||||
if let Some((locked, hidden)) = state {
|
||||
self.state(locked, hidden);
|
||||
}
|
||||
@@ -1148,9 +1182,11 @@ impl<'a> Writer<'a> {
|
||||
let region = self.cut(path, rule);
|
||||
self.clip = Some(region);
|
||||
self.nest += 1;
|
||||
self.drawn += 1;
|
||||
for t in &tiles {
|
||||
self.node(t);
|
||||
}
|
||||
self.drawn -= 1;
|
||||
if let Some((locked, hidden)) = state {
|
||||
self.state(locked, hidden);
|
||||
}
|
||||
@@ -1343,7 +1379,9 @@ impl<'a> Writer<'a> {
|
||||
art_node.transform(t.xf * ig.xf * doc.symbol_natural_xf(&art.symbol), true);
|
||||
(art_node.visible, art_node.locked, art_node.name) = (true, false, None);
|
||||
self.nest += 1;
|
||||
self.drawn += 1;
|
||||
self.node(&art_node);
|
||||
self.drawn -= 1;
|
||||
self.nest -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,8 +204,10 @@ impl Writer<'_> {
|
||||
if sym.dynamic || doc.symbol_export_type(name) != SymbolExportType::default() || doc.symbol_nine_slice(name).is_some() {
|
||||
self.warn(SYMBOL_OPTIONS);
|
||||
}
|
||||
// The art's effects are its own, not those of a drawn look that first places it.
|
||||
// The art's effects are its own, not those of a drawn look that first places it, and its
|
||||
// text wrap options are its own, not left out with the drawn art that first places it.
|
||||
let in_look = std::mem::take(&mut self.in_look);
|
||||
let drawn = std::mem::take(&mut self.drawn);
|
||||
self.defining_symbols.push(name.to_string());
|
||||
// The objects of this definition and of those it defines first.
|
||||
let before = self.charges();
|
||||
@@ -222,7 +224,7 @@ impl Writer<'_> {
|
||||
self.defining_symbols.pop();
|
||||
self.keep_since(before);
|
||||
self.warn(SYMBOL_COUNT);
|
||||
self.in_look = in_look;
|
||||
(self.in_look, self.drawn) = (in_look, drawn);
|
||||
return false;
|
||||
}
|
||||
// The group that holds the art is an object of the definition ([`Self::take_objects`]);
|
||||
@@ -308,7 +310,7 @@ impl Writer<'_> {
|
||||
(self.wrote_fixed, self.inner_scale),
|
||||
) = saved;
|
||||
self.doc = page_doc;
|
||||
self.in_look = in_look;
|
||||
(self.in_look, self.drawn) = (in_look, drawn);
|
||||
let art = std::mem::replace(&mut self.body, art);
|
||||
self.defining_symbols.pop();
|
||||
if self.left_out_since(art_start) {
|
||||
|
||||
@@ -3,8 +3,11 @@
|
||||
//! type runs along, `TP`), the modal character and paragraph attributes
|
||||
//! (`Tr Tf Ts Tz Tt TA Tl Ta Ti`, and §15.4.7 and §22's letter and word spacing `TC TW`, hanging
|
||||
//! punctuation `Tq`, hyphenation `Th` and tab stops `Xb Xe XB`, and §15.3.4's writing direction `TV`,
|
||||
//! Roman character rotation `Tv`, Kumi blocks `Ty TY` and binding punctuation `Tg`), the paint
|
||||
//! style, and the characters (`Tx`, `Tj`, overflow `TX`; `\r` ends a paragraph). Type set in rendering modes 4 to 7 is a mask (§5.7): the
|
||||
//! Roman character rotation `Tv`, Kumi blocks `Ty TY` and binding punctuation `Tg`, and §22.6's
|
||||
//! hyphenation language `XL`), the paint style, the characters (`Tx`, `Tj`, overflow `TX`; `\r` ends
|
||||
//! a paragraph), manual kerning pairs (`Tk`, overflow `TK`) and discretionary hyphens (`T+`, `T-`,
|
||||
//! read as soft hyphens). The line breaking value `TG` and the Japanese layout rules `Xu` (`Tu`) are
|
||||
//! not kept: a visible text object read while one is set gives a warning. Type set in rendering modes 4 to 7 is a mask (§5.7): the
|
||||
//! text object clips the objects of its clipping group. Final-form operators (the
|
||||
//! computed positions, §15.1) are skipped: the type is laid out again. Strings are decoded by the
|
||||
//! encoding pairs of the current font's `TZ`, then by the file's `TE` encoding unless that `TZ`'s
|
||||
@@ -59,6 +62,14 @@ const MASK_NOT_CLIPPED: &str = "type used as a mask in linked areas, wraparound
|
||||
/// The warning when `TV` changes after a text object's first character: the object keeps the
|
||||
/// direction of that character.
|
||||
const DIRECTION_CHANGE_LEFT_OUT: &str = "type that changes writing direction inside a text object opens in the direction of its first character";
|
||||
/// The warning when a visible text object is read while a line breaking value (`TG`) is set.
|
||||
const LINE_BREAKING_LEFT_OUT: &str = "the Line Breaking setting of legacy type was left out";
|
||||
/// The warning when a visible text object is read while Japanese layout rules (`Xu`, `Tu`) are set.
|
||||
const JAPANESE_LAYOUT_LEFT_OUT: &str = "the Japanese layout rules of legacy type were left out";
|
||||
/// The manual kerning range `text.setRangeStyle` takes, in 1/1000 em.
|
||||
const KERNING_RANGE: (f64, f64) = (-1000.0, 10_000.0);
|
||||
/// The soft hyphen a discretionary hyphen (`T+`, `T-`) is read as.
|
||||
const SOFT_HYPHEN: char = '\u{ad}';
|
||||
|
||||
/// A text path (`Tp` … `TP`).
|
||||
#[derive(Debug, Default)]
|
||||
@@ -124,6 +135,9 @@ pub(super) struct LegacyText {
|
||||
vertical: bool,
|
||||
/// A later character was set in the other direction.
|
||||
direction_changed: bool,
|
||||
/// A manual kerning value (`Tk`, `TK`) read at the start of a line, in 1/1000 em: the space
|
||||
/// before the next character, which starts the line.
|
||||
kern_before: Option<f64>,
|
||||
/// The state when it began (lock, visibility), and whether it began on a `%_` line.
|
||||
gs: GState,
|
||||
hidden: bool,
|
||||
@@ -148,6 +162,40 @@ impl LegacyText {
|
||||
}
|
||||
}
|
||||
|
||||
/// Add `text` in `style` to `runs`: to the last run when it has that style, else as a new run.
|
||||
fn push_run(runs: &mut Vec<TextRun>, text: String, style: CharStyle) {
|
||||
if text.is_empty() {
|
||||
return;
|
||||
}
|
||||
match runs.last_mut() {
|
||||
Some(last) if last.inline.is_none() && last.style == style => last.text.push_str(&text),
|
||||
_ => runs.push(TextRun::new(text, style)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Give the last character of `runs` the manual kerning `kerning` (None: automatic), in a run of
|
||||
/// its own unless its run has one character, which joins the run before it when their styles
|
||||
/// match. False when there is no character or the last one ends a paragraph: the kerning is at
|
||||
/// the start of a line.
|
||||
fn set_last_kerning(runs: &mut Vec<TextRun>, kerning: Option<f64>) -> bool {
|
||||
let Some(last) = runs.last_mut().filter(|r| r.inline.is_none()) else { return false };
|
||||
let Some(c) = last.text.chars().next_back().filter(|&c| c != '\n') else { return false };
|
||||
if last.style.kerning == kerning {
|
||||
return true;
|
||||
}
|
||||
if last.text.len() > c.len_utf8() {
|
||||
last.text.pop();
|
||||
let style = CharStyle { kerning, ..last.style.clone() };
|
||||
runs.push(TextRun::new(c.to_string(), style));
|
||||
return true;
|
||||
}
|
||||
last.style.kerning = kerning;
|
||||
if let Some(one) = runs.pop() {
|
||||
push_run(runs, one.text, one.style);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// Are `a` and `b` the same, leaving their tab stops out?
|
||||
fn same_but_tabs(a: &mut ParaStyle, b: &mut ParaStyle) -> bool {
|
||||
let (a_tabs, b_tabs) = (std::mem::take(&mut a.tabs), std::mem::take(&mut b.tabs));
|
||||
@@ -203,6 +251,10 @@ pub(super) struct TypeState {
|
||||
vertical: bool,
|
||||
/// `TY`: a Kumi block recorded for later use, which horizontal type keeps as its mark.
|
||||
kumi_recorded: bool,
|
||||
/// A line breaking value (`TG`) was read: VectorCraft has no setting for it.
|
||||
line_breaking: bool,
|
||||
/// Japanese layout rules (`Xu`, `Tu`) were read: VectorCraft has no setting for them.
|
||||
japanese_layout: bool,
|
||||
/// The encoding strings are in, by code (`TE`); None where it says nothing.
|
||||
encoding: Vec<Option<char>>,
|
||||
/// Re-encoded fonts' original names (`%AI3_BeginEncoding: _new old`, or `TZ`'s).
|
||||
@@ -232,6 +284,8 @@ impl Default for TypeState {
|
||||
render: 0,
|
||||
vertical: false,
|
||||
kumi_recorded: false,
|
||||
line_breaking: false,
|
||||
japanese_layout: false,
|
||||
encoding: vec![None; 256],
|
||||
fonts: vec![],
|
||||
font_encodings: vec![],
|
||||
@@ -684,6 +738,23 @@ impl Reader<'_> {
|
||||
st.tabs_version = st.tabs_version.wrapping_add(1);
|
||||
}
|
||||
}
|
||||
// `languageID XL` (§22.6), the hyphenation language: 0 U.S. English (the default
|
||||
// language, none), then U.K. English, French, German, Spanish, Dutch, Italian, Swedish,
|
||||
// Norwegian, Finnish, Danish and Hungarian, as the Character panel's language tags.
|
||||
"XL" => {
|
||||
const TAGS: [&str; 11] = ["en-GB", "fr", "de", "es", "nl", "it", "sv", "nb", "fi", "da", "hu"];
|
||||
match n0 {
|
||||
Some(0.0) => st.style.language = None,
|
||||
Some(id) if id.fract() == 0.0 && (1.0..=11.0).contains(&id) => {
|
||||
st.style.language = TAGS.get(id as usize - 1).map(|t| t.to_string());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// `linebreak TG` and `prop cjkLayout cjkRoman cjkCjk Xu` (`Tu` the same, §22.6). Either
|
||||
// one is set only when its operands are numbers.
|
||||
"TG" => st.line_breaking |= n0.is_some(),
|
||||
"Xu" | "Tu" => st.japanese_layout |= nums::<4>(vals).is_some(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -691,14 +762,59 @@ impl Reader<'_> {
|
||||
/// `(…) Tx` (`Tj`, overflow `TX`): characters in the current style and paint.
|
||||
pub(super) fn text_body(&mut self, w: &str, vals: &[V]) {
|
||||
let Some(bytes) = vals.iter().rev().find_map(|v| if let V::Str(s) = v { Some(s.clone()) } else { None }) else { return };
|
||||
if self.text.is_none() {
|
||||
return;
|
||||
}
|
||||
let decoded = self.type_state.decode(&bytes);
|
||||
self.add_chars(w == "TX", decoded);
|
||||
}
|
||||
|
||||
/// `autoKern kernValue Tk` (`TK` in overflow text): the space between the character before it
|
||||
/// and the character after it. With `autoKern` 0 the pair takes `kernValue` in 1/1000 em as
|
||||
/// manual kerning, kept to the range `text.setRangeStyle` takes; with 1 the pair takes the
|
||||
/// automatic kerning. The value is the kerning after the character before it; at the start of
|
||||
/// a line it is the space before the character after it. Operands that are missing, are not
|
||||
/// numbers, or a flag other than 0 and 1 leave the type as it was, and so does a `Tk` outside a
|
||||
/// text object.
|
||||
pub(super) fn text_kern(&mut self, vals: &[V]) {
|
||||
let Some([auto, value]) = nums::<2>(vals) else { return };
|
||||
let Some(auto) = flag(auto) else { return };
|
||||
let Some(t) = self.text.as_mut() else { return };
|
||||
let kerning = (!auto).then(|| value.clamp(KERNING_RANGE.0, KERNING_RANGE.1));
|
||||
let line_start = t.pending_break.is_some() || !set_last_kerning(&mut t.runs, kerning);
|
||||
if line_start {
|
||||
t.kern_before = kerning;
|
||||
}
|
||||
}
|
||||
|
||||
/// `T+` (a discretionary hyphen that doesn't print) or `T-` (`printed`: the character before it
|
||||
/// is a discretionary hyphen that prints, §15.4.10.1): a soft hyphen, which shows as a hyphen
|
||||
/// only where a line breaks at it. A printed hyphen character (`-` or U+2010) before `T-`
|
||||
/// becomes the soft hyphen; else one is added.
|
||||
pub(super) fn discretionary_hyphen(&mut self, printed: bool) {
|
||||
let Some(t) = self.text.as_mut() else { return };
|
||||
if printed
|
||||
&& t.pending_break.is_none()
|
||||
&& let Some(last) = t.runs.last_mut()
|
||||
&& last.inline.is_none()
|
||||
&& last.text.ends_with(['-', '\u{2010}'])
|
||||
{
|
||||
last.text.pop();
|
||||
last.text.push(SOFT_HYPHEN);
|
||||
return;
|
||||
}
|
||||
self.add_chars(false, SOFT_HYPHEN.to_string());
|
||||
}
|
||||
|
||||
/// Characters in the current style and paint (`overflow`: read by `TX`).
|
||||
fn add_chars(&mut self, overflow: bool, decoded: String) {
|
||||
let st = &mut self.type_state;
|
||||
let Some(t) = self.text.as_mut() else { return };
|
||||
let decoded = st.decode(&bytes);
|
||||
if decoded.is_empty() {
|
||||
return;
|
||||
}
|
||||
// Overflow text ending the story with a paragraph break (`(\r) TX`) adds no paragraph.
|
||||
if w == "TX" && decoded == "\n" {
|
||||
if overflow && decoded == "\n" {
|
||||
if t.pending_break.is_none() {
|
||||
let para = (!t.para_taken).then(|| (st.para.clone(), st.tabs_version));
|
||||
t.pending_break = Some(PendingBreak { vertical: st.vertical, para });
|
||||
@@ -744,6 +860,8 @@ impl Reader<'_> {
|
||||
text.push('\n');
|
||||
t.para_taken = false;
|
||||
}
|
||||
// Where the characters start in `text`, after a break read before them.
|
||||
let at = text.len();
|
||||
for c in decoded.chars() {
|
||||
if c != '\n' && !t.para_taken {
|
||||
t.begin_para(&mut st.para, st.tabs_version);
|
||||
@@ -757,10 +875,19 @@ impl Reader<'_> {
|
||||
t.para_taken = false;
|
||||
}
|
||||
}
|
||||
match t.runs.last_mut() {
|
||||
Some(last) if last.style == style => last.text.push_str(&text),
|
||||
_ => t.runs.push(TextRun::new(text, style)),
|
||||
// Kerning read at the start of the line is the space before its first character; a
|
||||
// paragraph break there leaves no character for it.
|
||||
let first = decoded.chars().next().filter(|&c| c != '\n');
|
||||
if let (Some(k), Some(c)) = (t.kern_before.take(), first) {
|
||||
let end = at + c.len_utf8();
|
||||
let (rest, after) = (text.split_off(end), CharStyle { kerning_before: k, ..style.clone() });
|
||||
let own = text.split_off(at);
|
||||
push_run(&mut t.runs, text, style.clone());
|
||||
push_run(&mut t.runs, own, after);
|
||||
push_run(&mut t.runs, rest, style);
|
||||
return;
|
||||
}
|
||||
push_run(&mut t.runs, text, style);
|
||||
}
|
||||
|
||||
/// `TO`: the text object ends. Area type with several linked areas becomes one frame for each
|
||||
@@ -792,6 +919,15 @@ impl Reader<'_> {
|
||||
if t.direction_changed {
|
||||
self.warn(DIRECTION_CHANGE_LEFT_OUT);
|
||||
}
|
||||
// A copy on `%_` lines is not the type the document shows.
|
||||
if !(t.hidden || hidden) {
|
||||
if self.type_state.line_breaking {
|
||||
self.warn(LINE_BREAKING_LEFT_OUT);
|
||||
}
|
||||
if self.type_state.japanese_layout {
|
||||
self.warn(JAPANESE_LAYOUT_LEFT_OUT);
|
||||
}
|
||||
}
|
||||
let mut paras = std::mem::take(&mut t.paras);
|
||||
if paras.is_empty() {
|
||||
paras.push(ParaRun { style: self.type_state.para.clone(), count: 1, tabs_version: 0 });
|
||||
|
||||
@@ -383,17 +383,20 @@ impl<'a> Reader<'a> {
|
||||
// `(text) justified TS`, special characters (§22.6): the reader adds its characters like `Tx`.
|
||||
"Tx" | "Tj" | "TX" | "TS" => self.text_body(w, &vals),
|
||||
"Tr" | "Tf" | "Ts" | "Tz" | "Tt" | "TA" | "Tl" | "Ta" | "Ti" | "TC" | "TW" | "Tq" | "Th" | "TV" | "Tv" | "Ty" | "TY" | "Tg" | "Xb"
|
||||
| "Xe" | "XB" => {
|
||||
| "Xe" | "XB" | "XL" | "TG" | "Xu" | "Tu" => {
|
||||
self.text_attr(w, &vals);
|
||||
}
|
||||
// Attributes the reader doesn't keep (kerning pairs, line breaking and Japanese layout
|
||||
// rules) and final-form positions (§15.3).
|
||||
"Tk" | "TK" | "Tc" | "Tw" | "Tm" | "Td" | "T*" | "TR" | "T+" | "T-" | "TG" | "Tu" | "Xu" => {}
|
||||
// A kerning pair (`Tk`, `TK` in overflow text, §15.4.6.1) and discretionary hyphens
|
||||
// (`T+`, `T-`, §15.4.10.1).
|
||||
"Tk" | "TK" => self.text_kern(&vals),
|
||||
"T+" => self.discretionary_hyphen(false),
|
||||
"T-" => self.discretionary_hyphen(true),
|
||||
// Final-form positions (§15.4.7: `Tc Tw Tm Td T* TR`, printing only), which the type's
|
||||
// layout computes again.
|
||||
"Tc" | "Tw" | "Tm" | "Td" | "T*" | "TR" => {}
|
||||
// `TM` (pop text matrix) and `Te` (end render), listed in §22.6, keep nothing either; the
|
||||
// reader takes `Te` with any number of operands.
|
||||
"TM" | "Te" => {}
|
||||
// The hyphenation language (`XL`), which the reader doesn't keep either (§22).
|
||||
"XL" => {}
|
||||
"TE" => self.te(&vals),
|
||||
"TZ" => self.tz(&vals),
|
||||
// An image whose samples follow in comment lines (read at `%AI5_EndRaster`).
|
||||
|
||||
@@ -4284,6 +4284,119 @@ fn legacy_end_render_and_text_matrix_pop_read() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The text, manual kerning and space before each run of a legacy-format file's first text object.
|
||||
fn legacy_kerning(art: &str) -> Vec<(String, Option<f64>, f64)> {
|
||||
legacy_texts(art)[0].runs.iter().map(|r| (r.text.clone(), r.style.kerning, r.style.kerning_before)).collect()
|
||||
}
|
||||
|
||||
/// `autoKern kernValue Tk` (§15.4.6.1) spaces the character before it from the one after it: with
|
||||
/// `autoKern` 0 by `kernValue` (1/1000 em, kept to -1000 to 10,000) as the manual kerning after the
|
||||
/// character before it, with 1 by the automatic kerning; `TK` does the same in overflow text. At
|
||||
/// the start of a line it is the space before the line's first character.
|
||||
#[test]
|
||||
fn legacy_manual_pair_kerning_is_kept() {
|
||||
let s = |x: &str| x.to_string();
|
||||
let runs = legacy_kerning(&point_type("0 TA\n(A) Tx\n0 -80 Tk", "V"));
|
||||
assert_eq!(runs, [(s("A"), Some(-80.0), 0.0), (s("V"), Some(0.0), 0.0)]);
|
||||
// Inside a run, the character before it takes the value alone.
|
||||
let runs = legacy_kerning(&point_type("(WAVE) Tx\n0 50 Tk", "S"));
|
||||
assert_eq!(runs, [(s("WAV"), None, 0.0), (s("E"), Some(50.0), 0.0), (s("S"), None, 0.0)]);
|
||||
// `autoKern` 1 gives the pair the automatic kerning, whatever its value.
|
||||
let runs = legacy_kerning(&point_type("0 TA\n(AV) Tx\n1 -50 Tk", "A"));
|
||||
assert_eq!(runs, [(s("A"), Some(0.0), 0.0), (s("V"), None, 0.0), (s("A"), Some(0.0), 0.0)]);
|
||||
// Pairs with the same value in a row stay one run.
|
||||
let runs = legacy_kerning(&point_type("0 TA\n(A) Tx\n0 50 Tk\n(B) Tx\n0 50 Tk", "C"));
|
||||
assert_eq!(runs, [(s("AB"), Some(50.0), 0.0), (s("C"), Some(0.0), 0.0)]);
|
||||
// At the start of the text and of a paragraph, the space before the line's first character.
|
||||
let runs = legacy_kerning(&point_type("0 -30 Tk", "Hi"));
|
||||
assert_eq!(runs, [(s("H"), None, -30.0), (s("i"), None, 0.0)]);
|
||||
let runs = legacy_kerning(&point_type("(a\\r) Tx\n0 40 Tk", "b"));
|
||||
assert_eq!(runs, [(s("a\n"), None, 0.0), (s("b"), None, 40.0)]);
|
||||
let runs = legacy_kerning(&point_type("(a) Tx\n(\\r) TX\n0 40 TK", "b"));
|
||||
assert_eq!(runs, [(s("a\n"), None, 0.0), (s("b"), None, 40.0)]);
|
||||
// In overflow text.
|
||||
let runs = legacy_kerning(&point_type("(ab) Tx\n0 25 TK", "c").replace("(c) Tx", "(c) TX"));
|
||||
assert_eq!(runs, [(s("a"), None, 0.0), (s("b"), Some(25.0), 0.0), (s("c"), None, 0.0)]);
|
||||
// Kept to the range `text.setRangeStyle` takes.
|
||||
let runs = legacy_kerning(&point_type("(a) Tx\n0 -5000 Tk\n(b) Tx\n0 20000 Tk", "c"));
|
||||
assert_eq!(runs, [(s("a"), Some(-1000.0), 0.0), (s("b"), Some(10_000.0), 0.0), (s("c"), None, 0.0)]);
|
||||
// The pair is spaced as the kerning says.
|
||||
let x = |art: &str| legacy_origins(&legacy_texts(art)[0])[1].0;
|
||||
let (plain, kerned) = (x(&point_type("0 TA\n(A) Tx", "V")), x(&point_type("0 TA\n(A) Tx\n0 -80 Tk", "V")));
|
||||
assert!((plain - kerned - 0.96).abs() < 1e-6, "{plain} {kerned}");
|
||||
}
|
||||
|
||||
/// A `Tk` whose operands are missing or are not numbers, or whose flag is not 0 or 1, and a `Tk`
|
||||
/// outside a text object leave the type as it was.
|
||||
#[test]
|
||||
fn legacy_pair_kerning_with_bad_operands_leaves_the_type_as_it_was() {
|
||||
let want = legacy_kerning(&point_type("(H) Tx", "i"));
|
||||
for bad in ["0 Tk", "Tk", "/x 50 Tk", "0 /x Tk", "2 50 Tk", "0.5 50 Tk", "(0) 50 Tk"] {
|
||||
assert_eq!(legacy_kerning(&point_type(&format!("(H) Tx\n{bad}"), "i")), want, "{bad}");
|
||||
}
|
||||
let outside = legacy_kerning(&format!("0 50 Tk\n{}", point_type("(H) Tx", "i")));
|
||||
assert_eq!(outside, want);
|
||||
}
|
||||
|
||||
/// `T+` (a discretionary hyphen, §15.4.10.1) is a soft hyphen where it stands, in overflow text
|
||||
/// too; `T-` makes the printed hyphen before it a soft hyphen, or adds one. Outside a text object
|
||||
/// they add nothing.
|
||||
#[test]
|
||||
fn legacy_discretionary_hyphens_are_soft_hyphens() {
|
||||
for (art, text) in [
|
||||
(point_type("(co) Tx\nT+", "operate"), "co\u{ad}operate"),
|
||||
(point_type("(co-) Tx\nT-", "operate"), "co\u{ad}operate"),
|
||||
(point_type("(co) Tx\nT-", "operate"), "co\u{ad}operate"),
|
||||
(point_type("(co) Tx\nT+", "operate").replace("(operate) Tx", "(operate) TX"), "co\u{ad}operate"),
|
||||
(format!("T+\nT-\n{}", point_type("", "co")), "co"),
|
||||
] {
|
||||
let texts = legacy_texts(&art);
|
||||
assert_eq!(texts[0].plain_text(), text, "{art}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `languageID XL` (§22.6) is the characters' language, 0 (U.S. English) the default; it lasts into
|
||||
/// the next text object, and an ID that is not 0 to 11 leaves the language as it was.
|
||||
#[test]
|
||||
fn legacy_hyphenation_language_is_kept() {
|
||||
let lang = |t: &vectorcraft_doc::TextObject| t.runs.iter().map(|r| r.style.language.clone()).collect::<Vec<_>>();
|
||||
let texts = legacy_texts(&format!("{}{}", point_type("%_ 3 XL\n(a) Tx\n%_ 0 XL\n(b) Tx\n%_ 8 XL", "c"), point_type("", "d")));
|
||||
assert_eq!(lang(&texts[0]), [Some("de".to_string()), None, Some("nb".to_string())]);
|
||||
assert_eq!(lang(&texts[1]), [Some("nb".to_string())]);
|
||||
for bad in ["12 XL", "-1 XL", "1.5 XL", "/x XL", "XL"] {
|
||||
let texts = legacy_texts(&point_type(&format!("2 XL\n{bad}"), "a"));
|
||||
assert_eq!(lang(&texts[0]), [Some("fr".to_string())], "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The line breaking value (`TG`) and the Japanese layout rules (`Xu`, `Tu`, §22.6) are not kept:
|
||||
/// a visible text object read while one is set gives a warning, once for each in a file. A copy of
|
||||
/// a text object on `%_` lines gives none, and the final-form positions (§15.4.7) give none.
|
||||
#[test]
|
||||
fn legacy_line_breaking_and_japanese_layout_rules_are_warned_once() {
|
||||
const LINE_BREAKING: &str = "the Line Breaking setting of legacy type was left out";
|
||||
const JAPANESE_LAYOUT: &str = "the Japanese layout rules of legacy type were left out";
|
||||
let r = legacy_read(&format!("{}{}", point_type("50 TG\n0 1 120 150 Xu", "a"), point_type("60 TG", "b")));
|
||||
assert_eq!(r.warnings, [LINE_BREAKING, JAPANESE_LAYOUT]);
|
||||
assert_eq!(legacy_read(&point_type("0 1 120 150 Tu", "a")).warnings, [JAPANESE_LAYOUT]);
|
||||
let hidden: String = point_type("50 TG", "a").lines().map(|l| format!("%_{l}\n")).collect();
|
||||
assert_eq!(legacy_read(&hidden).warnings, Vec::<String>::new());
|
||||
let final_form = point_type("1 0 0 1 10 50 Tm\n0 0 Td\nT*\n0 Tc\n0 Tw\n1 0 0 1 0 0 TR\nTe\nTM", "Hi");
|
||||
let r = legacy_read(&final_form);
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
assert_eq!(art_texts(&r.doc)[0].plain_text(), "Hi");
|
||||
}
|
||||
|
||||
/// `TG`, `Xu` and `Tu` with missing or non-numeric operands set nothing, so they give no warning.
|
||||
#[test]
|
||||
fn legacy_line_breaking_and_japanese_layout_rules_with_bad_operands_are_not_warned() {
|
||||
for attrs in ["TG", "(a) TG", "1 120 150 Xu", "0 1 (a) 150 Xu", "Tu", "0 1 120 (a) Tu"] {
|
||||
let r = legacy_read(&point_type(attrs, "a"));
|
||||
assert!(r.warnings.is_empty(), "{attrs}: {:?}", r.warnings);
|
||||
assert_eq!(art_texts(&r.doc)[0].plain_text(), "a", "{attrs}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Spacing is kept to the ranges the Justification options take, a Minimum, Desired and Maximum
|
||||
/// out of order go back to their defaults, and hyphenation's letter counts and limit to the ranges
|
||||
/// `text.setFormat` takes.
|
||||
|
||||
@@ -208,15 +208,15 @@ fn a_postscript_ai_with_a_multi_layer_mask_opens_with_its_layers() {
|
||||
assert!(r.warnings.iter().any(|w| w.contains("clipping group in each layer")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
/// A `.ai` in PostScript form (read through its layers) whose text carries hyphenation and
|
||||
/// tab-ruler attributes: `XL` (hyphenation language), `Xb`/`Xe`/`XB` (a tab definition) and `Th`
|
||||
/// (hyphen control). The reader drops `XL` and keeps the tab definition as the paragraph's tab
|
||||
/// stops rather than failing the file the way it did before (the symptom seen on Illustrator 6/8
|
||||
/// EPS files whose `Adobe_level2_AI5` program can't be run).
|
||||
/// A `.ai` in PostScript form (read through its layers) whose text carries hyphenation, tab-ruler
|
||||
/// and kerning attributes: `XL` (hyphenation language), `Xb`/`Xe`/`XB` (a tab definition), `Th`
|
||||
/// (hyphen control), `Tk` (a manual kerning pair) and `T+` (a discretionary hyphen). The reader
|
||||
/// keeps the language, the tab definition as the paragraph's tab stops, the pair's kerning and the
|
||||
/// soft hyphen.
|
||||
#[test]
|
||||
fn text_with_hyphenation_and_tab_attributes_opens_instead_of_failing() {
|
||||
let text = "0 To\n1 0 0 1 10 50 0 Tp\nTP\n0 Tr\n0 0 0 1 k\n/_Helvetica 9 Tf\n\
|
||||
%_ 0 XL\n36 1 Xb\n0 0 3 72 Xe\nXB\n0 1 2 2 99 Th\n0 Ta\n(hi) Tx\nTO\n";
|
||||
%_ 3 XL\n36 1 Xb\n0 0 3 72 Xe\nXB\n0 1 2 2 99 Th\n0 Ta\n(h) Tx\n0 -40 Tk\n(i) Tx\nT+\n(ho) Tx\nTO\n";
|
||||
// The operators sit on a visible layer (so they'd be reported as unknown, not quietly skipped
|
||||
// on a hidden one), beside the square so the layer is never empty.
|
||||
let src = NAMED_PROLOG.replace("S\nLB\n%AI5_EndLayer--\n%AI5_BeginLayer", &format!("S\n{text}LB\n%AI5_EndLayer--\n%AI5_BeginLayer"));
|
||||
@@ -228,10 +228,14 @@ fn text_with_hyphenation_and_tab_attributes_opens_instead_of_failing() {
|
||||
let mut texts = vec![];
|
||||
r.document.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
texts.push(t.para_at(0).clone());
|
||||
texts.push((**t).clone());
|
||||
}
|
||||
});
|
||||
let [p] = texts.as_slice() else { panic!("{texts:?}") };
|
||||
let [t] = texts.as_slice() else { panic!("{texts:?}") };
|
||||
assert_eq!(t.plain_text(), "hi\u{ad}ho");
|
||||
let runs: Vec<_> = t.runs.iter().map(|r| (r.text.as_str(), r.style.kerning, r.style.language.as_deref())).collect();
|
||||
assert_eq!(runs, [("h", Some(-40.0), Some("de")), ("i\u{ad}ho", None, Some("de"))]);
|
||||
let p = t.para_at(0);
|
||||
assert!(!p.hyphenate);
|
||||
assert_eq!((p.hyphenation.after_first, p.hyphenation.before_last, p.hyphenation.hyphen_limit), (2, 2, 25));
|
||||
let tabs: Vec<_> = p.tabs.iter().map(|t| (t.position, t.align)).collect();
|
||||
|
||||
@@ -33,7 +33,9 @@
|
||||
//! - Type (§15): point type, area type and type on a path as text objects, `type To`, `a b c d tx
|
||||
//! ty startPt Tp` (the text matrix; the frame or path in art space between it and `TP`), each
|
||||
//! run's paint style, `Tr` (fill, stroke, both or neither), `/_font size ascent descent Tf`,
|
||||
//! `Ts Tz Tt TA Tl Ta Ti` and its characters `(…) Tx` (`\r` ends a paragraph), `TO`. Standard
|
||||
//! `Ts Tz Tt TA Tl Ta Ti` and its characters `(…) Tx` (`\r` ends a paragraph), with manual
|
||||
//! kerning as `0 value Tk` after each character that has it and before a paragraph's first
|
||||
//! character that has space before it (§15.4.6.1) and soft hyphens as `T+` (§15.4.10.1), `TO`. Standard
|
||||
//! Vertical Roman Alignment is written as `1 Tv` and `0 Tv`, and Tate-chu-yoko in horizontal
|
||||
//! type as a Kumi block recorded for later use, `1 TY` … `0 TY` (§15.3.4); neither operator is
|
||||
//! written for type that has neither mark. Only the
|
||||
@@ -99,7 +101,7 @@ const HEX_LINE: usize = 60;
|
||||
pub const SUBLAYERS: &str = "sublayers are written as groups in their top-level layer (legacy .ai files have no sublayers)";
|
||||
pub const TYPE: &str = "type a legacy .ai can't hold as text (characters outside Windows Latin-1, vertical type, ruby, inline graphics, gradient or pattern fills) is written as outlines";
|
||||
pub const ROTATED_TYPE: &str = "type with rotated characters is written as outlines, which keep the rotation, and is no longer editable text (legacy .ai text can't rotate characters)";
|
||||
pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, manual kerning, optical kerning, small caps, superscript and subscript, OpenType features, Variable Font settings, optical margin alignment, System Layout, fractional widths off, area type options, type on a path's effect, alignment and spacing, an end bracket short of the path's end, subpaths after the first in an area type frame or a type path, space after paragraphs, tabs, bulleted and numbered lists) are left out";
|
||||
pub const TYPE_ATTRIBUTES: &str = "type attributes legacy .ai files don't have (underline, strikethrough, optical kerning, small caps, superscript and subscript, OpenType features, Variable Font settings, optical margin alignment, System Layout, fractional widths off, area type options, type on a path's effect, alignment and spacing, an end bracket short of the path's end, subpaths after the first in an area type frame or a type path, space after paragraphs, tabs, bulleted and numbered lists) are left out";
|
||||
pub const DYNAMIC_TEXT: &str = "Dynamic Text is written as the sizes the type is drawn at (legacy .ai files don't have it)";
|
||||
pub const HIDDEN: &str = "hidden objects are left out (hidden layers are kept, hidden)";
|
||||
pub const HIDDEN_LAYER: &str = "hidden objects are moved to a hidden layer above their own (legacy .ai files can hide only layers)";
|
||||
|
||||
@@ -120,7 +120,6 @@ pub(super) fn lost_attributes(t: &TextObject) -> bool {
|
||||
let run_lost = |s: &CharStyle| {
|
||||
s.underline
|
||||
|| s.strikethrough
|
||||
|| s.kerning.is_some_and(|k| k != 0.0)
|
||||
|| s.optical_kerning
|
||||
|| s.small_caps.is_some()
|
||||
|| s.position != CharPosition::Normal
|
||||
|
||||
@@ -107,6 +107,7 @@ VCLegacy begin
|
||||
/To {pop} bd /Tp {7 {pop} repeat} bd /TP {} bd /TO {} bd
|
||||
/Tr {pop} bd /Tf {pop pop pop pop} bd /Ts {pop} bd /Tz {pop pop} bd /Tt {pop} bd /TA {pop} bd
|
||||
/Tl {pop pop} bd /Ta {pop} bd /Ti {pop pop pop} bd /Tx {pop} bd /Tv {pop} bd /TY {pop} bd
|
||||
/Tk {pop pop} bd /T+ {} bd
|
||||
% The page trailer (3): annotatepage marks nothing.
|
||||
/annotatepage {} bd
|
||||
end
|
||||
|
||||
@@ -1494,12 +1494,12 @@ fn type_on_a_path_alignment_and_end_bracket_are_warned_as_left_out() {
|
||||
assert!(warned(&|t| t.kind = TextKind::OnPath { path: two(false), start: 0.25, end: None }));
|
||||
}
|
||||
|
||||
/// Kerning other than Auto or 0, optical kerning, Optical Margin Alignment, System Layout,
|
||||
/// fractional widths off and an area type frame with a second subpath are not held by a legacy
|
||||
/// `.ai` text object: type with any of them is written as text, with the warning that they are
|
||||
/// left out.
|
||||
/// Optical kerning, Optical Margin Alignment, System Layout, fractional widths off and an area
|
||||
/// type frame with a second subpath are not held by a legacy `.ai` text object: type with any of
|
||||
/// them is written as text, with the warning that they are left out. Manual kerning is held
|
||||
/// (`Tk`), with no warning.
|
||||
#[test]
|
||||
fn kerning_margins_widths_and_extra_frames_are_warned_as_left_out() {
|
||||
fn optical_kerning_margins_widths_and_extra_frames_are_warned_as_left_out() {
|
||||
use vectorcraft_doc::{TextKind, TextObject};
|
||||
let warned = |edit: &dyn Fn(&mut TextObject)| {
|
||||
let mut doc = typed();
|
||||
@@ -1513,7 +1513,8 @@ fn kerning_margins_widths_and_extra_frames_are_warned_as_left_out() {
|
||||
};
|
||||
assert!(!warned(&|_| {}));
|
||||
assert!(!warned(&|t| t.runs[0].style.kerning = Some(0.0)));
|
||||
assert!(warned(&|t| t.runs[0].style.kerning = Some(50.0)));
|
||||
assert!(!warned(&|t| t.runs[0].style.kerning = Some(50.0)));
|
||||
assert!(!warned(&|t| t.runs[0].style.kerning_before = 50.0));
|
||||
assert!(warned(&|t| t.runs[0].style.optical_kerning = true));
|
||||
assert!(warned(&|t| t.optical_margin = true));
|
||||
assert!(warned(&|t| t.system_layout = true));
|
||||
@@ -1526,6 +1527,67 @@ fn kerning_margins_widths_and_extra_frames_are_warned_as_left_out() {
|
||||
assert!(warned(&|t| t.kind = TextKind::Area { frame: PathData::new(vec![square(10.0), square(120.0)]) }));
|
||||
}
|
||||
|
||||
/// Manual kerning is written as `0 value Tk` after each character that has it, the space before a
|
||||
/// paragraph's first character as `Tk` before it, and a soft hyphen as a discretionary hyphen
|
||||
/// (`T+`, §15.4.6.1 and §15.4.10.1); each reads back on the same characters.
|
||||
#[test]
|
||||
fn manual_kerning_and_soft_hyphens_are_written_and_read_back() {
|
||||
use vectorcraft_doc::{CharStyle, TextObject, TextRun};
|
||||
let plain = style(12.0, Paint::solid(Color::BLACK));
|
||||
let kerned = CharStyle { kerning: Some(-80.0), ..plain.clone() };
|
||||
let before = CharStyle { kerning_before: 40.0, ..plain.clone() };
|
||||
let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "AV", kerned.clone());
|
||||
for (text, st) in [("A co\u{ad}op\n", &plain), ("W", &before), ("ord", &plain), ("d\u{ad}", &kerned)] {
|
||||
t.runs.push(TextRun::new(text, st.clone()));
|
||||
}
|
||||
let mut doc = Document::new(300.0, 200.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let out = write(&doc);
|
||||
assert!(!out.warnings.iter().any(|w| w == TYPE || w == TYPE_ATTRIBUTES), "{:?}", out.warnings);
|
||||
let text = String::from_utf8(out.bytes.clone()).unwrap();
|
||||
assert!(text.contains("(A) Tx\n0 -80 Tk\n(V) Tx\n0 -80 Tk\n"), "{text}");
|
||||
assert!(text.contains("(A co) Tx\nT+\n(op\\r) Tx\n"), "{text}");
|
||||
assert!(text.contains("0 40 Tk\n(W) Tx\n"), "{text}");
|
||||
// A soft hyphen with manual kerning keeps it too.
|
||||
assert!(text.contains("(d) Tx\n0 -80 Tk\nT+\n0 -80 Tk\n"), "{text}");
|
||||
let read = texts(&crate::import(&out.bytes).unwrap().document);
|
||||
let runs: Vec<(String, Option<f64>, f64)> = read[0].1.runs.iter().map(|r| (r.text.clone(), r.style.kerning, r.style.kerning_before)).collect();
|
||||
let s = |x: &str| x.to_string();
|
||||
assert_eq!(
|
||||
runs,
|
||||
[
|
||||
(s("AV"), Some(-80.0), 0.0),
|
||||
(s("A co\u{ad}op\n"), None, 0.0),
|
||||
(s("W"), None, 40.0),
|
||||
(s("ord"), None, 0.0),
|
||||
(s("d\u{ad}"), Some(-80.0), 0.0)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// Manual kerning of 0 is written as `0 0 Tk` and reads back as manual kerning, not as the
|
||||
/// automatic kerning of a pair with no `Tk`.
|
||||
#[test]
|
||||
fn manual_kerning_of_zero_is_written_and_read_back() {
|
||||
use vectorcraft_doc::{CharStyle, TextObject, TextRun};
|
||||
let plain = style(12.0, Paint::solid(Color::BLACK));
|
||||
let zero = CharStyle { kerning: Some(0.0), ..plain.clone() };
|
||||
let mut t = TextObject::point(vectorcraft_geom::Point::new(20.0, 40.0), "AV", zero);
|
||||
t.runs.push(TextRun::new("To", plain));
|
||||
let mut doc = Document::new(300.0, 200.0);
|
||||
let layer = doc.layers[0].id;
|
||||
let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
|
||||
doc.insert(Some(layer), usize::MAX, n).unwrap();
|
||||
let out = write(&doc);
|
||||
let text = String::from_utf8(out.bytes.clone()).unwrap();
|
||||
assert!(text.contains("(A) Tx\n0 0 Tk\n(V) Tx\n0 0 Tk\n"), "{text}");
|
||||
let read = texts(&crate::import(&out.bytes).unwrap().document);
|
||||
let runs: Vec<(String, Option<f64>)> = read[0].1.runs.iter().map(|r| (r.text.clone(), r.style.kerning)).collect();
|
||||
assert_eq!(runs, [("AV".to_string(), Some(0.0)), ("To".to_string(), None)]);
|
||||
}
|
||||
|
||||
/// Type whose font size measures the cap height is written at the em size it is drawn at, with
|
||||
/// no warning: 14 pt measuring a 0.7 em cap height reads back as 20 pt type.
|
||||
#[test]
|
||||
|
||||
@@ -843,6 +843,8 @@ impl<'a> Writer<'a> {
|
||||
self.line("TP");
|
||||
let mut para = 0usize;
|
||||
let mut para_start = true;
|
||||
// No character of the current paragraph has been written.
|
||||
let mut line_start = true;
|
||||
for run in &t.runs {
|
||||
let text = if run.style.all_caps { run.text.to_uppercase() } else { run.text.clone() };
|
||||
let mut pieces = text.split('\n').peekable();
|
||||
@@ -856,14 +858,38 @@ impl<'a> Writer<'a> {
|
||||
para_start = false;
|
||||
}
|
||||
self.char_style(&run.style, t.para_at(para));
|
||||
let mut bytes: Vec<u8> = piece.chars().filter_map(latin::encode).collect();
|
||||
// The space before a line's first character, kerning before it (§15.4.6.1).
|
||||
if line_start && !piece.is_empty() && run.style.kerning_before != 0.0 {
|
||||
self.kern(run.style.kerning_before);
|
||||
}
|
||||
line_start = false;
|
||||
// Manual kerning after each character (0 included, which differs from automatic
|
||||
// kerning), a soft hyphen as a discretionary hyphen (§15.4.10.1).
|
||||
let kerning = run.style.kerning;
|
||||
let mut bytes = vec![];
|
||||
for c in piece.chars() {
|
||||
if c == '\u{ad}' {
|
||||
self.text_string(&mut bytes);
|
||||
self.line("T+");
|
||||
if let Some(k) = kerning {
|
||||
self.kern(k);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(b) = latin::encode(c) else { continue };
|
||||
bytes.push(b);
|
||||
if let Some(k) = kerning {
|
||||
self.text_string(&mut bytes);
|
||||
self.kern(k);
|
||||
}
|
||||
}
|
||||
if ends_paragraph {
|
||||
bytes.push(b'\r');
|
||||
para += 1;
|
||||
para_start = true;
|
||||
line_start = true;
|
||||
}
|
||||
self.body.push_str(&ps::bytes(&bytes));
|
||||
self.line(" Tx");
|
||||
self.text_string(&mut bytes);
|
||||
}
|
||||
}
|
||||
if self.kumi {
|
||||
@@ -873,6 +899,22 @@ impl<'a> Writer<'a> {
|
||||
self.line("TO");
|
||||
}
|
||||
|
||||
/// `bytes` as a string of characters, `(…) Tx`, when there are any; `bytes` is left empty.
|
||||
fn text_string(&mut self, bytes: &mut Vec<u8>) {
|
||||
if !bytes.is_empty() {
|
||||
self.body.push_str(&ps::bytes(bytes));
|
||||
self.line(" Tx");
|
||||
bytes.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Manual kerning of `k` 1/1000 em between the characters before and after it: `0 k Tk`.
|
||||
fn kern(&mut self, k: f64) {
|
||||
self.body.push_str("0 ");
|
||||
ps::push_num(&mut self.body, finite(k, 0.0));
|
||||
self.line(" Tk");
|
||||
}
|
||||
|
||||
/// A paragraph's attributes: alignment `Ta` and indents `Ti` (first line's, left, right).
|
||||
fn paragraph(&mut self, p: &ParaStyle) {
|
||||
let align = match p.justify {
|
||||
|
||||
@@ -1330,7 +1330,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"file.exportAs",
|
||||
"Export As…",
|
||||
"",
|
||||
"{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}",
|
||||
"{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}; under automation read roots, an SVG or SVGZ is refused while the document links a JavaScript file outside them, as document.export refuses it",
|
||||
),
|
||||
(
|
||||
"ui.fileInfoDialog",
|
||||
|
||||
@@ -203,18 +203,78 @@ const MAX_EDGE_PAIRS: usize = 1 << 14;
|
||||
/// within the band and its x range there.
|
||||
type Slant = (Point, Point, (f64, f64), (f64, f64));
|
||||
|
||||
/// The line through two points.
|
||||
type Line = (Point, Point);
|
||||
|
||||
/// The x of the line through `p` and `q` (not horizontal) at `y`.
|
||||
fn line_x(p: Point, q: Point, y: f64) -> f64 {
|
||||
p.x + (y - p.y) / (q.y - p.y) * (q.x - p.x)
|
||||
}
|
||||
|
||||
/// The x ranges within a band at which the edges `slants` bound the frame. Edges that lie along one
|
||||
/// line and overlap there (contours that meet along an edge, however each one divides it) count by
|
||||
/// parity: a stretch of the line that an even number of them cover has the frame on both sides.
|
||||
/// At most [`MAX_EDGE_PAIRS`] pairs are compared; edges left unpaired still count as boundaries,
|
||||
/// which can make a line shorter at a seam but never puts it outside the frame. The flag is false
|
||||
/// when the limit left edges unpaired.
|
||||
fn slant_boundaries(slants: &mut [Slant]) -> (Vec<(f64, f64)>, bool) {
|
||||
/// `a + b` as its rounded value and the rounding error, which sum to it exactly.
|
||||
fn two_sum(a: f64, b: f64) -> (f64, f64) {
|
||||
let s = a + b;
|
||||
let v = s - a;
|
||||
(s, (a - (s - v)) + (b - v))
|
||||
}
|
||||
|
||||
/// `a * b` as its rounded value and the rounding error, which sum to it exactly (unless the error
|
||||
/// is too small for a normal f64).
|
||||
fn two_product(a: f64, b: f64) -> (f64, f64) {
|
||||
let p = a * b;
|
||||
(p, a.mul_add(b, -p))
|
||||
}
|
||||
|
||||
/// Does `r` lie exactly on the line through `p` and `q`? The cross product `(q - p) × (r - p)` is
|
||||
/// summed without rounding: two points apart by a single unit in the last place are never on one
|
||||
/// line.
|
||||
fn on_line_exactly(p: Point, q: Point, r: Point) -> bool {
|
||||
let left = (q.x - p.x) * (r.y - p.y);
|
||||
let right = (q.y - p.y) * (r.x - p.x);
|
||||
// Rounding moves the product difference by less than this, so a larger one is not zero.
|
||||
if (left - right).abs() > 4.0 * f64::EPSILON * (left.abs() + right.abs()) {
|
||||
return false;
|
||||
}
|
||||
let (dx, dy, ex, ey) = (two_sum(q.x, -p.x), two_sum(q.y, -p.y), two_sum(r.x, -p.x), two_sum(r.y, -p.y));
|
||||
let mut terms = [0.0; 16];
|
||||
for (k, (a, b)) in [dx.0, dx.1].into_iter().flat_map(|a| [ey.0, ey.1].map(|b| (a, b))).enumerate() {
|
||||
(terms[2 * k], terms[2 * k + 1]) = two_product(a, b);
|
||||
}
|
||||
for (k, (a, b)) in [dy.0, dy.1].into_iter().flat_map(|a| [ex.0, ex.1].map(|b| (a, b))).enumerate() {
|
||||
(terms[8 + 2 * k], terms[9 + 2 * k]) = two_product(-a, b);
|
||||
}
|
||||
// The terms added into an expansion: parts of increasing size that don't overlap, whose sum is
|
||||
// the exact sum of the terms and which keeps no zero part, so it is empty only when that sum is
|
||||
// zero.
|
||||
let (mut parts, mut len) = ([0.0; 16], 0);
|
||||
for t in terms {
|
||||
let (mut sum, mut kept) = (t, 0);
|
||||
for i in 0..len {
|
||||
let (s, err) = two_sum(sum, parts[i]);
|
||||
if err != 0.0 {
|
||||
parts[kept] = err;
|
||||
kept += 1;
|
||||
}
|
||||
sum = s;
|
||||
}
|
||||
if sum != 0.0 {
|
||||
parts[kept] = sum;
|
||||
kept += 1;
|
||||
}
|
||||
len = kept;
|
||||
}
|
||||
len == 0
|
||||
}
|
||||
|
||||
/// The x ranges within a band at which the edges `slants` bound the frame, and the line each edge
|
||||
/// lies along (the same two points for every edge it is paired with). Edges that lie exactly along
|
||||
/// one line and overlap there (contours that meet along an edge, however each one divides it) count
|
||||
/// by parity: a stretch of the line that an even number of them cover has the frame on both sides.
|
||||
/// Edges that are parallel but apart, however little, are not paired. At most [`MAX_EDGE_PAIRS`]
|
||||
/// pairs are compared; edges left unpaired still count as boundaries, which can make a line shorter
|
||||
/// at a seam but never puts it outside the frame. The flag is false when the limit left edges
|
||||
/// unpaired. `slants` is reordered, and the lines follow its new order.
|
||||
fn slant_boundaries(slants: &mut [Slant]) -> (Vec<(f64, f64)>, bool, Vec<Line>) {
|
||||
fn root(parent: &mut [usize], mut i: usize) -> usize {
|
||||
while parent[i] != i {
|
||||
parent[i] = parent[parent[i]];
|
||||
@@ -227,17 +287,16 @@ fn slant_boundaries(slants: &mut [Slant]) -> (Vec<(f64, f64)>, bool) {
|
||||
let mut parent: Vec<usize> = (0..slants.len()).collect();
|
||||
let mut pairs = 0;
|
||||
'edges: for (i, &(p, q, _, (_, x1))) in slants.iter().enumerate() {
|
||||
// Ends on the line up to rounding (a few units in the last place of the coordinates)
|
||||
// count as on it.
|
||||
// The x ranges of edges along one line, each found from its own ends, can differ by
|
||||
// rounding (a few units in the last place of the coordinates).
|
||||
let scale = p.x.abs().max(p.y.abs()).max(q.x.abs()).max(q.y.abs()).max(1.0);
|
||||
let (d, tol) = (q - p, 4.0 * f64::EPSILON * scale);
|
||||
let on_line = |r: Point| d.cross(r - p).abs() <= tol * d.hypot();
|
||||
let tol = 4.0 * f64::EPSILON * scale;
|
||||
for (j, &(r, s, ..)) in slants.iter().enumerate().skip(i + 1).take_while(|(_, o)| o.3.0 <= x1 + tol) {
|
||||
pairs += 1;
|
||||
if pairs > MAX_EDGE_PAIRS {
|
||||
break 'edges;
|
||||
}
|
||||
if on_line(r) && on_line(s) {
|
||||
if on_line_exactly(p, q, r) && on_line_exactly(p, q, s) {
|
||||
let (a, b) = (root(&mut parent, i), root(&mut parent, j));
|
||||
parent[a] = b;
|
||||
}
|
||||
@@ -246,6 +305,7 @@ fn slant_boundaries(slants: &mut [Slant]) -> (Vec<(f64, f64)>, bool) {
|
||||
let mut groups: Vec<(usize, usize)> = (0..slants.len()).map(|i| (root(&mut parent, i), i)).collect();
|
||||
groups.sort_unstable();
|
||||
let mut out = Vec::new();
|
||||
let mut lines: Vec<Line> = slants.iter().map(|s| (s.0, s.1)).collect();
|
||||
for run in groups.chunk_by(|a, b| a.0 == b.0) {
|
||||
if let [(_, i)] = run {
|
||||
out.push(slants[*i].3);
|
||||
@@ -253,6 +313,9 @@ fn slant_boundaries(slants: &mut [Slant]) -> (Vec<(f64, f64)>, bool) {
|
||||
}
|
||||
// The stretches an odd number of the edges cover: pairs of their sorted y ends.
|
||||
let (p, q, ..) = slants[run[0].1];
|
||||
for &(_, i) in run {
|
||||
lines[i] = (p, q);
|
||||
}
|
||||
let mut ys: Vec<f64> = run.iter().flat_map(|&(_, i)| [slants[i].2.0, slants[i].2.1]).collect();
|
||||
ys.sort_by(f64::total_cmp);
|
||||
for c in ys.as_chunks::<2>().0.iter().filter(|c| c[1] > c[0]) {
|
||||
@@ -260,7 +323,7 @@ fn slant_boundaries(slants: &mut [Slant]) -> (Vec<(f64, f64)>, bool) {
|
||||
out.push((s.min(t), s.max(t)));
|
||||
}
|
||||
}
|
||||
(out, pairs <= MAX_EDGE_PAIRS)
|
||||
(out, pairs <= MAX_EDGE_PAIRS, lines)
|
||||
}
|
||||
|
||||
/// The most pieces a line's band is cut into to keep it inside an Invert Wrap shape grown by its
|
||||
@@ -301,29 +364,21 @@ fn band_edges(polys: &[Vec<Point>], top: f64, bottom: f64) -> (Vec<(f64, f64, f6
|
||||
/// of edges cover).
|
||||
fn band_intervals(polys: &[Vec<Point>], top: f64, bottom: f64) -> Vec<(f64, f64)> {
|
||||
let (top, bottom) = (top.min(bottom), top.max(bottom));
|
||||
// Contours that meet along an edge cross the middle of the band at the same x, up to a few
|
||||
// units of rounding: the intervals on either side of it join (an edge that bounds the
|
||||
// shape there is still subtracted below). A vertical edge crosses the middle at its own x with
|
||||
// no rounding, so a gap at one is never taken for a seam.
|
||||
let y = (top + bottom) * 0.5;
|
||||
let mut upright: Vec<f64> = polys
|
||||
.iter()
|
||||
.flat_map(|poly| poly.iter().zip(poly.iter().cycle().skip(1)))
|
||||
.filter(|(a, b)| a.x == b.x && (a.y <= y) != (b.y <= y))
|
||||
.map(|(a, _)| a.x)
|
||||
.collect();
|
||||
upright.sort_by(f64::total_cmp);
|
||||
let upright = |x: f64| upright.binary_search_by(|v| v.total_cmp(&x)).is_ok();
|
||||
let mut mid = poly_intervals(polys, y);
|
||||
let (edges, _, mut xs) = band_boundaries(polys, top, bottom);
|
||||
// The edges of contours that meet along an edge cross the middle of the band at the same x,
|
||||
// since each is crossed on the line through the same two points: the intervals on either side
|
||||
// join there (an edge that bounds the shape there is still subtracted). Intervals with any gap
|
||||
// between them stay apart.
|
||||
xs.sort_by(f64::total_cmp);
|
||||
let mut mid: Vec<(f64, f64)> = xs.as_chunks::<2>().0.iter().map(|c| (c[0], c[1])).collect();
|
||||
mid.dedup_by(|next, prev| {
|
||||
let gap = next.0 - prev.1;
|
||||
let seam = gap <= 8.0 * f64::EPSILON * prev.1.abs().max(next.0.abs()).max(1.0) && (gap <= 0.0 || !(upright(prev.1) || upright(next.0)));
|
||||
let seam = next.0 <= prev.1;
|
||||
if seam {
|
||||
prev.1 = prev.1.max(next.1);
|
||||
}
|
||||
seam
|
||||
});
|
||||
subtract_intervals(&mid, &band_boundaries(polys, top, bottom).0)
|
||||
subtract_intervals(&mid, &edges)
|
||||
}
|
||||
|
||||
/// The x at which `polys` (even-odd) is inside somewhere in the band `top..bottom`, sorted and
|
||||
@@ -336,7 +391,7 @@ fn band_intervals(polys: &[Vec<Point>], top: f64, bottom: f64) -> Vec<(f64, f64)
|
||||
fn band_cover(polys: &[Vec<Point>], top: f64, bottom: f64, admit: bool) -> Vec<(f64, f64)> {
|
||||
let (top, bottom) = (top.min(bottom), top.max(bottom));
|
||||
let mut iv = poly_intervals(polys, (top + bottom) * 0.5);
|
||||
let (edges, paired) = band_boundaries(polys, top, bottom);
|
||||
let (edges, paired, _) = band_boundaries(polys, top, bottom);
|
||||
if paired || !admit {
|
||||
iv.extend(edges);
|
||||
}
|
||||
@@ -366,10 +421,20 @@ fn band_cover_closed(polys: &[Vec<Point>], top: f64, bottom: f64) -> Vec<(f64, f
|
||||
/// Every x at which an edge of `polys` bounds the shape within the band `top..bottom`
|
||||
/// (`top <= bottom`), sorted and disjoint, leaving out edges that only touch the top or bottom of
|
||||
/// the band, stretches of edges that an even number of edges cover, and vertical edges. The flag is
|
||||
/// false when [`MAX_EDGE_PAIRS`] left edges unpaired, which can only add to the result.
|
||||
fn band_boundaries(polys: &[Vec<Point>], top: f64, bottom: f64) -> (Vec<(f64, f64)>, bool) {
|
||||
/// false when [`MAX_EDGE_PAIRS`] left edges unpaired, which can only add to the result. Last, the x
|
||||
/// at which the edges cross the middle of the band (even-odd, as [`poly_intervals`] finds them),
|
||||
/// unsorted, each found along the line [`slant_boundaries`] gives its edge.
|
||||
fn band_boundaries(polys: &[Vec<Point>], top: f64, bottom: f64) -> (Vec<(f64, f64)>, bool, Vec<f64>) {
|
||||
let (mut flats, mut slants) = band_edges(polys, top, bottom);
|
||||
let (mut edges, paired) = slant_boundaries(&mut slants);
|
||||
let (mut edges, paired, lines) = slant_boundaries(&mut slants);
|
||||
let y = (top + bottom) * 0.5;
|
||||
let mut xs: Vec<f64> = slants.iter().zip(&lines).filter(|((p, q, ..), _)| p.y <= y && y < q.y).map(|(_, &(p, q))| line_x(p, q, y)).collect();
|
||||
// When the middle is the band's bottom (a band of no height), the edges that start there cross
|
||||
// it but are not in the band: they cross it at their lower end.
|
||||
if y == bottom {
|
||||
let starts = polys.iter().flat_map(|poly| poly.iter().zip(poly.iter().cycle().skip(1)));
|
||||
xs.extend(starts.filter(|(a, b)| a.y != b.y && a.y.min(b.y) == y).map(|(a, b)| if a.y < b.y { a.x } else { b.x }));
|
||||
}
|
||||
// The x covered by an odd number of the horizontal edges at one height: pairs of their
|
||||
// sorted ends.
|
||||
flats.sort_by(|p, q| p.0.total_cmp(&q.0));
|
||||
@@ -381,7 +446,7 @@ fn band_boundaries(polys: &[Vec<Point>], top: f64, bottom: f64) -> (Vec<(f64, f6
|
||||
// A vertical edge covers a single x: where it bounds the shape, the band's middle already
|
||||
// ends at it or an edge of some width meets it, so it is left out (vertical seams join).
|
||||
edges.retain(|e| e.1 > e.0);
|
||||
(union_intervals(edges), paired)
|
||||
(union_intervals(edges), paired, xs)
|
||||
}
|
||||
|
||||
/// The largest magnitude a text wrap offset may have (points), the bound the Text Wrap commands
|
||||
@@ -895,6 +960,72 @@ fn lines_cross_an_edge_two_contours_share() {
|
||||
assert_spans(&cells[0].spans(40.0, 60.0), &[(x, x + 50.0), (x + 50.0 + 1e-7, x + 100.0)]);
|
||||
}
|
||||
|
||||
/// Slanted edges of two contours four units in the last place apart, or one, near the edge of the
|
||||
/// canvas are not one edge: the line stops at each and keeps the gap between them.
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn separate_slanted_contours_keep_a_four_ulp_gap_near_canvas_limit() {
|
||||
let x = 3_999_000.0;
|
||||
let ulp = 2f64.powi(-31);
|
||||
assert_eq!((x + ulp).to_bits(), x.to_bits() + 1);
|
||||
for gap in [4.0 * ulp, ulp] {
|
||||
let frame = closed(&[
|
||||
&[(x - 100.0, 0.0), (x, 0.0), (x + 10.0, 10.0), (x - 90.0, 10.0)],
|
||||
&[(x + gap, 0.0), (x + 100.0 + gap, 0.0), (x + 110.0 + gap, 10.0), (x + 10.0 + gap, 10.0)],
|
||||
]);
|
||||
let cells = Region::cells(&frame, &LayoutOptions::default(), &[]);
|
||||
let spans = cells[0].spans(1.0, 9.0);
|
||||
assert_spans(&spans, &[(x - 91.0, x + 1.0), (x + 9.0 + gap, x + 101.0 + gap)]);
|
||||
assert!(spans[0].1 < spans[1].0, "gap {gap}: {spans:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Contours that share a slanted edge near the edge of the canvas, whole or divided by an anchor
|
||||
/// exactly on it, hold lines across it. So do contours whose shared edge is divided where the
|
||||
/// crossing found from the divided edge's own ends rounds to another x than the whole edge's.
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn shared_slanted_edge_still_joins_near_canvas_limit() {
|
||||
let x = 3_999_000.0;
|
||||
let left: &[(f64, f64)] = &[(x - 100.0, 0.0), (x, 0.0), (x + 10.0, 10.0), (x - 90.0, 10.0)];
|
||||
let whole: &[(f64, f64)] = &[(x, 0.0), (x + 100.0, 0.0), (x + 110.0, 10.0), (x + 10.0, 10.0)];
|
||||
let divided: &[(f64, f64)] = &[(x, 0.0), (x + 100.0, 0.0), (x + 110.0, 10.0), (x + 10.0, 10.0), (x + 2.5, 2.5)];
|
||||
for right in [whole, divided] {
|
||||
let cells = Region::cells(&closed(&[left, right]), &LayoutOptions::default(), &[]);
|
||||
assert_spans(&cells[0].spans(1.0, 9.0), &[(x - 91.0, x + 101.0)]);
|
||||
}
|
||||
// (0.75, 1.75) lies exactly on the edge from (0, 0) to (3, 7).
|
||||
let left: &[(f64, f64)] = &[(-100.0, 0.0), (0.0, 0.0), (3.0, 7.0), (-97.0, 7.0)];
|
||||
let right: &[(f64, f64)] = &[(0.0, 0.0), (100.0, 0.0), (103.0, 7.0), (3.0, 7.0), (0.75, 1.75)];
|
||||
let (top, bottom) = (1.404, 2.404);
|
||||
let y = (top + bottom) * 0.5;
|
||||
assert_ne!(line_x(Point::new(0.0, 0.0), Point::new(3.0, 7.0), y), line_x(Point::new(0.75, 1.75), Point::new(3.0, 7.0), y));
|
||||
let cells = Region::cells(&closed(&[left, right]), &LayoutOptions::default(), &[]);
|
||||
assert_spans(&cells[0].spans(top, bottom), &[(-100.0 + 3.0 * bottom / 7.0, 100.0 + 3.0 * top / 7.0)]);
|
||||
}
|
||||
|
||||
/// Area type in two slanted contours four units in the last place apart near the edge of the canvas
|
||||
/// sets no line across the gap between them.
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn area_type_sets_no_line_across_a_four_ulp_gap_between_slanted_contours() {
|
||||
let x = 3_999_000.0;
|
||||
let gap = 4.0 * 2f64.powi(-31);
|
||||
let frame = closed(&[
|
||||
&[(x - 200.0, 0.0), (x, 0.0), (x + 100.0, 100.0), (x - 100.0, 100.0)],
|
||||
&[(x + gap, 0.0), (x + 200.0 + gap, 0.0), (x + 300.0 + gap, 100.0), (x + 100.0 + gap, 100.0)],
|
||||
]);
|
||||
let style = vectorcraft_doc::CharStyle { size: 10.0, ..vectorcraft_doc::CharStyle::default() };
|
||||
let mut t = crate::TextObject::point(Point::ZERO, &"word ".repeat(400), style);
|
||||
t.kind = vectorcraft_doc::TextKind::Area { frame: PathData::from_bezpath(&frame) };
|
||||
let laid = crate::layout(crate::FontDb::global(), &t);
|
||||
assert!(!laid.lines.is_empty());
|
||||
// Each contour is 200 pt wide at any height; the two together are twice that.
|
||||
for line in &laid.lines {
|
||||
assert!(line.x1 - line.x0 < 200.0, "{} to {}", line.x0, line.x1);
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame of 200 thin slanted strips, whose edges in the band overlap in x far more than
|
||||
/// [`MAX_EDGE_PAIRS`] times, holds no line in the band (no strip holds a vertical line across it).
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -152,16 +152,18 @@ pub(super) fn color_palette(used: &[Used], params: &TraceParams) -> Vec<[f64; 3]
|
||||
// Full Tone: split until no colour box is wider than 96 (few colours) … 8 (many) levels per
|
||||
// channel, which is one histogram bin.
|
||||
let full_tone = || refine(used, centers(&median_cut(used, FULL_TONE_MAX, 96.0 - 88.0 * detail)));
|
||||
// A Limited palette of 9 to 16 colors keeps a nearly flat dark ground in one color (see [`kmeans_rgb`]).
|
||||
let limited = || kmeans_rgb(used, k, if FEW_COLORS.contains(&k) { LEAST_APART } else { 0.0 });
|
||||
match params.palette {
|
||||
Palette::Limited => kmeans_rgb(used, k),
|
||||
Palette::Limited => limited(),
|
||||
Palette::FullTone => full_tone(),
|
||||
Palette::Automatic => match flat_colors(used, detail) {
|
||||
Some(n) => kmeans_rgb(used, n),
|
||||
Some(n) => kmeans_rgb(used, n, 0.0),
|
||||
None => full_tone(),
|
||||
},
|
||||
Palette::DocumentLibrary if !params.swatches.is_empty() => library_colors(used, ¶ms.swatches, k),
|
||||
// No library colours to use: as Limited.
|
||||
Palette::DocumentLibrary => kmeans_rgb(used, k),
|
||||
Palette::DocumentLibrary => limited(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,9 +230,25 @@ pub(super) fn centers(boxes: &[ColorBox]) -> Vec<[f64; 3]> {
|
||||
boxes.iter().map(|b| b.mean).collect()
|
||||
}
|
||||
|
||||
/// Median cut to `k` colours, then weighted k-means refinement over histogram bins.
|
||||
fn kmeans_rgb(used: &[Used], k: usize) -> Vec<[f64; 3]> {
|
||||
refine(used, centers(&median_cut(used, k, 0.0)))
|
||||
/// How far apart (Oklab × 100) the two sides of a cut must be to look different: below about 3
|
||||
/// they look alike (see [`oklab`]).
|
||||
const LEAST_APART: f64 = 3.0;
|
||||
|
||||
/// The color counts of a Limited palette whose cuts are weighed by [`LEAST_APART`].
|
||||
const FEW_COLORS: std::ops::RangeInclusive<usize> = 9..=16;
|
||||
|
||||
/// The darkest colors (Oklab lightness × 100 below this) are the ones whose cuts are weighed.
|
||||
const DARK: f64 = 30.0;
|
||||
|
||||
/// The grayest colors (Oklab chroma × 100 below this) are the ones whose cuts are weighed.
|
||||
const GRAY: f64 = 3.0;
|
||||
|
||||
/// Median cut to `k` colors, then weighted k-means refinement over histogram bins. With `apart`
|
||||
/// above 0, a cut whose two sides are dark grays less than `apart` apart has its gain scaled down
|
||||
/// (see [`median_cut_apart`]). A large, nearly flat dark ground then keeps one color, and the
|
||||
/// color it would have taken goes to another cut.
|
||||
fn kmeans_rgb(used: &[Used], k: usize, apart: f64) -> Vec<[f64; 3]> {
|
||||
refine(used, centers(&median_cut_apart(used, k, 0.0, apart)))
|
||||
}
|
||||
|
||||
/// Divisive clustering in the manner of median cut, but each box is cut where that leaves its two
|
||||
@@ -240,6 +258,13 @@ fn kmeans_rgb(used: &[Used], k: usize) -> Vec<[f64; 3]> {
|
||||
/// and leaves two smaller colours in one box. Boxes are cut while there are fewer than `k` and
|
||||
/// some box spans more than `spread` levels of a channel.
|
||||
pub(super) fn median_cut(used: &[Used], k: usize, spread: f64) -> Vec<ColorBox> {
|
||||
median_cut_apart(used, k, spread, 0.0)
|
||||
}
|
||||
|
||||
/// [`median_cut`], except when both sides of a cut have a dark gray mean color (see [`DARK`] and
|
||||
/// [`GRAY`]) and the two means lie `d` (Oklab × 100) apart with `d` < `apart`: then the cut's gain
|
||||
/// is scaled by (`d` / `apart`)². With `apart` 0 it is [`median_cut`].
|
||||
fn median_cut_apart(used: &[Used], k: usize, spread: f64, apart: f64) -> Vec<ColorBox> {
|
||||
if used.is_empty() {
|
||||
return vec![ColorBox { mean: [255.0; 3], weight: 0.0, peak: 0.0 }];
|
||||
}
|
||||
@@ -248,6 +273,16 @@ pub(super) fn median_cut(used: &[Used], k: usize, spread: f64) -> Vec<ColorBox>
|
||||
bins: Vec<usize>,
|
||||
best: Option<(f64, Vec<usize>, usize)>,
|
||||
}
|
||||
// How much of a cut's gain counts when its sides' mean colors are `a` and `b`: all of it when
|
||||
// they look different or either is not a dark gray, less as two dark grays look more alike.
|
||||
let dark_gray = |c: [f64; 3]| c[0] < DARK && c[1].hypot(c[2]) < GRAY;
|
||||
let seen = |a: [f64; 3], b: [f64; 3]| {
|
||||
let (a, b) = (oklab(a), oklab(b));
|
||||
if !dark_gray(a) || !dark_gray(b) {
|
||||
return 1.0;
|
||||
}
|
||||
((0..3).map(|q| (a[q] - b[q]).powi(2)).sum::<f64>() / (apart * apart)).min(1.0)
|
||||
};
|
||||
let plan = |bins: Vec<usize>| {
|
||||
let mut best: Option<(f64, Vec<usize>, usize)> = None;
|
||||
let widest = (0..3)
|
||||
@@ -261,14 +296,27 @@ pub(super) fn median_cut(used: &[Used], k: usize, spread: f64) -> Vec<ColorBox>
|
||||
let mut sorted = bins.clone();
|
||||
sorted.sort_by(|x, y| used[*x].1[ch].total_cmp(&used[*y].1[ch]));
|
||||
let (total, sum): (f64, f64) = sorted.iter().fold((0.0, 0.0), |a, &i| (a.0 + used[i].2, a.1 + used[i].1[ch] * used[i].2));
|
||||
let (mut w, mut s) = (0.0, 0.0);
|
||||
// The sums of each side's colors are kept only when cuts are weighed by `apart`.
|
||||
let weigh = apart > 0.0;
|
||||
let all = if weigh { sorted.iter().fold([0.0; 3], |a, &i| [0, 1, 2].map(|q| a[q] + used[i].1[q] * used[i].2)) } else { [0.0; 3] };
|
||||
let (mut w, mut s, mut side) = (0.0, 0.0, [0.0; 3]);
|
||||
let mut cut: Option<(f64, usize)> = None;
|
||||
for (j, &i) in sorted.iter().enumerate().take(sorted.len() - 1) {
|
||||
w += used[i].2;
|
||||
s += used[i].1[ch] * used[i].2;
|
||||
if weigh {
|
||||
for (acc, v) in side.iter_mut().zip(used[i].1) {
|
||||
*acc += v * used[i].2;
|
||||
}
|
||||
}
|
||||
let rest = total - w;
|
||||
if w > 0.0 && rest > 0.0 {
|
||||
let gain = w * rest / total * (s / w - (sum - s) / rest).powi(2);
|
||||
let mut gain = w * rest / total * (s / w - (sum - s) / rest).powi(2);
|
||||
// A scaled gain is never more than the full one, so only a cut that gains more
|
||||
// than the best so far, on this channel and the ones before it, is scaled.
|
||||
if weigh && gain > cut.map_or(f64::NEG_INFINITY, |c| c.0).max(best.as_ref().map_or(f64::NEG_INFINITY, |b| b.0)) {
|
||||
gain *= seen(side.map(|v| v / w), [0, 1, 2].map(|q| (all[q] - side[q]) / rest));
|
||||
}
|
||||
if cut.is_none_or(|c| gain > c.0) {
|
||||
cut = Some((gain, j + 1));
|
||||
}
|
||||
@@ -340,3 +388,69 @@ fn refine(used: &[Used], mut centers: Vec<[f64; 3]>) -> Vec<[f64; 3]> {
|
||||
}
|
||||
centers
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A large ground of three near-black grays (too close to tell apart) and a ramp of 120 colors.
|
||||
fn ground_and_ramp() -> Vec<Used> {
|
||||
let ground = [5.0, 7.0, 9.0].map(|g| [g; 3]).into_iter().map(|c| (c, 14_400.0));
|
||||
let ramp = (0..120).map(|i| f64::from(i) * 255.0 / 119.0).map(|t| ([t, 255.0 - t, t / 2.0], 120.0));
|
||||
ground.chain(ramp).enumerate().map(|(i, (c, n))| (i, c, n)).collect()
|
||||
}
|
||||
|
||||
/// The same ground, six far-apart colors and a small pair of colors 60 levels apart: eight
|
||||
/// boxes, so the ninth color goes to the ground or to the pair.
|
||||
fn ground_and_pair() -> Vec<Used> {
|
||||
let ground = [5.0, 7.0, 9.0].map(|g| ([g; 3], 14_400.0));
|
||||
let far = [[255.0, 0.0, 0.0], [0.0, 255.0, 0.0], [0.0, 0.0, 255.0], [255.0, 255.0, 0.0], [0.0, 255.0, 255.0], [255.0; 3]].map(|c| (c, 120.0));
|
||||
let pair = [([128.0, 64.0, 0.0], 30.0), ([128.0, 64.0, 60.0], 30.0)];
|
||||
ground.into_iter().chain(far).chain(pair).enumerate().map(|(i, (c, n))| (i, c, n)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_limited_palette_of_nine_to_sixteen_colors_weighs_alike_sides() {
|
||||
let used = ground_and_ramp();
|
||||
let plain = |k: usize| refine(&used, centers(&median_cut(&used, k, 0.0)));
|
||||
let palette = |palette: Palette, colors: u32| color_palette(&used, &TraceParams { palette, colors, ..TraceParams::default() });
|
||||
// At 9 to 16 colors the ground keeps one color, so the palette differs from a plain median cut.
|
||||
assert_ne!(palette(Palette::Limited, 16), plain(16));
|
||||
assert_ne!(palette(Palette::DocumentLibrary, 16), plain(16));
|
||||
// At 9 colors, the pair takes the ninth color instead of the ground.
|
||||
let pair = ground_and_pair();
|
||||
let plain_pair = refine(&pair, centers(&median_cut(&pair, 9, 0.0)));
|
||||
for limited in [Palette::Limited, Palette::DocumentLibrary] {
|
||||
let ninth = color_palette(&pair, &TraceParams { palette: limited, colors: 9, ..TraceParams::default() });
|
||||
assert_ne!(ninth, plain_pair, "{limited:?}");
|
||||
}
|
||||
// Below 9 and above 16 colors, and for Full Tone and Automatic, the palette is a plain median cut's.
|
||||
for colors in [2, 3, 6, 8, 17, 24, 32, 64, 256] {
|
||||
assert_eq!(palette(Palette::Limited, colors), plain(colors as usize), "{colors} colors");
|
||||
assert_eq!(palette(Palette::DocumentLibrary, colors), plain(colors as usize), "{colors} colors");
|
||||
}
|
||||
let detail = (TraceParams::default().color_detail / 100.0).clamp(0.0, 1.0);
|
||||
assert_eq!(palette(Palette::FullTone, 16), refine(&used, centers(&median_cut(&used, FULL_TONE_MAX, 96.0 - 88.0 * detail))));
|
||||
let automatic = match flat_colors(&used, detail) {
|
||||
Some(n) => plain(n),
|
||||
None => refine(&used, centers(&median_cut(&used, FULL_TONE_MAX, 96.0 - 88.0 * detail))),
|
||||
};
|
||||
assert_eq!(palette(Palette::Automatic, 16), automatic);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dark_colored_figure_on_a_nearly_flat_dark_ground_keeps_its_color() {
|
||||
// Dark navy text (a few pixels) on the near-black ground: only cuts between two dark grays
|
||||
// are weighed, so the navy still gets a color of its own.
|
||||
let navy = [10.0, 20.0, 70.0];
|
||||
let mut used = ground_and_ramp();
|
||||
used.push((used.len(), navy, 400.0));
|
||||
let palette = color_palette(&used, &TraceParams { palette: Palette::Limited, colors: 16, ..TraceParams::default() });
|
||||
let near = |c: [f64; 3]| {
|
||||
let (a, b) = (oklab(c), oklab(navy));
|
||||
(0..3).map(|q| (a[q] - b[q]).powi(2)).sum::<f64>().sqrt()
|
||||
};
|
||||
let nearest = palette.iter().map(|&c| near(c)).fold(f64::INFINITY, f64::min);
|
||||
assert!(nearest < LEAST_APART, "nearest {nearest} in {palette:?}");
|
||||
}
|
||||
}
|
||||
@@ -1908,6 +1908,31 @@ fn the_bands_of_a_gradient_stay_apart() {
|
||||
assert!(quantize(&noisy, &sixteen_colors()).palette.len() >= 12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nearly_flat_dark_ground_keeps_one_color() {
|
||||
// A ground of three near-black grays in patches (too close to tell apart) around a gradient
|
||||
// figure: the ground holds three quarters of the pixels, but splitting it would show nothing.
|
||||
let img = Raster::from_fn(240, 240, |x, y| {
|
||||
if (60..180).contains(&x) && (60..180).contains(&y) {
|
||||
let t = ((x - 60) * 255 / 119) as u8;
|
||||
[t, 255 - t, t / 2, 255]
|
||||
} else {
|
||||
let g = [5, 7, 9][((jitter(x / 30, y / 30, 0) + 1.0) * 1.5).clamp(0.0, 2.0) as usize];
|
||||
[g, g, g, 255]
|
||||
}
|
||||
});
|
||||
let q = quantize(&img, &sixteen_colors());
|
||||
let in_figure = |i: usize| (60..180).contains(&(i % 240)) && (60..180).contains(&(i / 240));
|
||||
let labels = |figure: bool| -> std::collections::BTreeSet<u16> {
|
||||
q.labels.iter().enumerate().filter(|(i, _)| in_figure(*i) == figure).map(|(_, &l)| l).collect()
|
||||
};
|
||||
let ground = labels(false);
|
||||
assert_eq!(ground.len(), 1, "ground colors {:?} of {:?}", ground, q.palette);
|
||||
// The color the ground does not take goes to the figure.
|
||||
let figure = labels(true);
|
||||
assert_eq!(figure.len(), 15, "figure colors {:?} of {:?}", figure, q.palette);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_noisy_gradient_keeps_its_tones_without_specks() {
|
||||
// Tones 0–255 across with noise larger than High Fidelity Photo's 64 steps are apart.
|
||||
|
||||
@@ -134,6 +134,7 @@ impl VectorcraftApp {
|
||||
hover_doc: None,
|
||||
titlebar_from_env: false,
|
||||
custom_titlebar: false,
|
||||
caption_layout: Default::default(),
|
||||
desktop_frame: false,
|
||||
last_window_title: String::new(),
|
||||
fullscreen_for_mode: false,
|
||||
|
||||
@@ -45,7 +45,8 @@ const WIDGET_H: f32 = 22.0;
|
||||
|
||||
/// The application bar: brand mark, Home, menus, then Discord, search and the workspace switcher
|
||||
/// at the right. With [`VectorcraftApp::custom_titlebar`] it is also the window's title bar
|
||||
/// ([`titlebar`]): the caption buttons take the right end and the rest of the bar drags the window.
|
||||
/// ([`titlebar`]): the caption buttons take the ends [`VectorcraftApp::caption_layout`] names and the
|
||||
/// rest of the bar drags the window.
|
||||
/// On macOS, under the system's transparent title bar, its empty space drags and zooms the window
|
||||
/// too ([`titlebar::drag_area`]). With the system title bar (Windows and Linux, `system_title_bar`) the OS draws its own icon and
|
||||
/// title, so the in-app bar shows Home, menus and workspace controls only: no brand mark.
|
||||
@@ -54,7 +55,10 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let custom = app.custom_titlebar;
|
||||
let system = system_title_bar(app);
|
||||
let left = app.titlebar_inset.clamp(8.0, f32::from(i8::MAX)) as i8;
|
||||
let frame = egui::Frame::NONE.fill(t.app_bar).inner_margin(egui::Margin { left, right: if custom { 0 } else { 14 }, top: 0, bottom: 0 });
|
||||
// The room the caption buttons take at each end of the bar.
|
||||
let (captions_left, captions_right) = if custom { (app.caption_layout.left_width(), app.caption_layout.right_width()) } else { (0.0, 0.0) };
|
||||
let right_margin = if captions_right > 0.0 { 0 } else { 14 };
|
||||
let frame = egui::Frame::NONE.fill(t.app_bar).inner_margin(egui::Margin { left, right: right_margin, top: 0, bottom: 0 });
|
||||
let bar = egui::Panel::top("app_bar").exact_size(APP_BAR_HEIGHT).frame(frame.stroke(Stroke::new(1.0, t.border))).show(ui, |ui| {
|
||||
// macOS draws the bar under its transparent title bar, so the bar gets the title bar's
|
||||
// clicks: without this a double-click there zooms nothing (#1932).
|
||||
@@ -62,6 +66,9 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
titlebar::drag_area(ui, ui.max_rect());
|
||||
}
|
||||
ui.horizontal_centered(|ui| {
|
||||
if captions_left > 0.0 {
|
||||
ui.add_space(captions_left);
|
||||
}
|
||||
// With the system title bar the OS draws its own icon: no in-app brand mark.
|
||||
if !system {
|
||||
let (r, _) = ui.allocate_exact_size(vec2(MARK, MARK), Sense::hover());
|
||||
@@ -80,7 +87,7 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
// Window › Learn), then the search icon (the palette stays under its shortcut), then
|
||||
// the workspace switcher narrows.
|
||||
let full = ui.max_rect();
|
||||
let right_edge = if custom { full.right() - titlebar::WIDTH - 10.0 } else { full.right() };
|
||||
let right_edge = if captions_right > 0.0 { full.right() - captions_right - 10.0 } else { full.right() };
|
||||
let right = egui::Rect::from_min_max(egui::pos2(menus_end + 8.0, full.top()), egui::pos2(right_edge, full.bottom()));
|
||||
// In Safe Mode, a label that stays in the bar whatever document is open, and opens
|
||||
// Help › Safe Mode; the other controls fit in the room it leaves, and the workspace
|
||||
|
||||
@@ -272,12 +272,16 @@ fn code_view(app: &VectorcraftApp, ui: &mut egui::Ui, d: &Dialog) {
|
||||
}
|
||||
// One cached text, replaced when the document or the options change.
|
||||
let key = egui::Id::unique("svg-code");
|
||||
let sig = egui::Id::unique((st.uid, st.revision, opts.to_string())).value();
|
||||
// The read roots in force and the document's folder decide whether the text may be shown.
|
||||
let roots = vectorcraft_engine::file_access::current().map(|r| r.describe());
|
||||
let sig = egui::Id::unique((st.uid, st.revision, opts.to_string(), roots, st.path.as_deref())).value();
|
||||
let code: Arc<String> = match ui.ctx().data(|m| m.get_temp::<(u64, Arc<String>)>(key)).filter(|(s, _)| *s == sig) {
|
||||
Some((_, c)) => c,
|
||||
None => {
|
||||
const MAX: usize = 200_000;
|
||||
let mut text = match vectorcraft_engine::cmd::fileio::encode_all(&st.doc, "svg", &json!({ "svg": opts })) {
|
||||
let encoded = vectorcraft_engine::cmd::fileio::check_linked_scripts("document.export", "svg", st)
|
||||
.and_then(|()| vectorcraft_engine::cmd::fileio::encode_all(&st.doc, "svg", &json!({ "svg": opts })));
|
||||
let mut text = match encoded {
|
||||
// Shown as text whatever the file's encoding.
|
||||
Ok(enc) => enc
|
||||
.files
|
||||
@@ -383,6 +387,38 @@ mod tests {
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().f64("decimals", 0.0), 1.0);
|
||||
}
|
||||
|
||||
/// Show Code under read roots draws no SVG of a document that links a JavaScript file outside
|
||||
/// them: it shows the error, which names no file or folder. Without roots it shows the link.
|
||||
#[test]
|
||||
fn show_code_leaves_out_a_linked_javascript_file_outside_the_read_roots() {
|
||||
let tmp = std::env::temp_dir();
|
||||
let root = tmp.join(format!("vc-svg-code-root-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let script = tmp.join(format!("vc-svg-code-away-{}", std::process::id())).join("menu.js").to_string_lossy().into_owned();
|
||||
let (mut app, _) = app("/tmp/code.svg");
|
||||
app.run("svgInteractivity.addFile", json!({"file": script})).unwrap();
|
||||
app.run("file.export.svg", Value::Null).unwrap();
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert("showCode".into(), json!(true));
|
||||
let roots = vectorcraft_engine::file_access::AutomationRoots::new(&[&root], &[]).unwrap().unwrap();
|
||||
// The text the code view shows after two frames in one context, with `roots` in force.
|
||||
let code = |app: &mut VectorcraftApp, roots: Option<&Arc<vectorcraft_engine::file_access::AutomationRoots>>| {
|
||||
let ctx = egui::Context::default();
|
||||
theme::install_fonts(&ctx);
|
||||
for _ in 0..2 {
|
||||
let mut out =
|
||||
vectorcraft_engine::file_access::confine(roots, || ctx.run_ui(Default::default(), |ui| super::super::show(app, ui.ctx())));
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
ctx.data(|m| m.get_temp::<(u64, Arc<String>)>(egui::Id::unique("svg-code"))).map(|(_, c)| c.to_string()).unwrap_or_default()
|
||||
};
|
||||
let confined = code(&mut app, Some(&roots));
|
||||
assert!(confined.contains("a linked JavaScript file is outside the read roots"), "{confined}");
|
||||
assert!(!confined.contains("menu.js") && !confined.contains("vc-svg-code"), "{confined}");
|
||||
let shown = code(&mut app, None);
|
||||
assert!(shown.contains(&format!("<script xlink:href=\"{script}\"/>")), "{shown}");
|
||||
let _ = std::fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
/// A dialog a save panel opened carries the dialog layer's own `__` fields; the save is given
|
||||
/// only the SVG options, so it is not refused for an unknown key.
|
||||
#[test]
|
||||
|
||||
@@ -4861,6 +4861,8 @@ axis Both И двете
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers вградено изображение от {_1} × {_2} пиксела беше намалено до {_3} × {_4} пиксела, за да се запазят слоевете
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel свързаните картини показват записания във файла предварителен преглед с ниска резолюция, докато файловете им бъдат намерени: презакачете ги в панела „Връзки“
|
||||
@msg linked type areas past VectorCraft's limits were left out свързаните текстови области извън ограниченията на VectorCraft бяха пропуснати
|
||||
@msg the Line Breaking setting of legacy type was left out настройката за прекъсване на редовете на текста в стария формат беше пропусната
|
||||
@msg the Japanese layout rules of legacy type were left out японските правила за оформление на текста в стария формат бяха пропуснати
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character текст, който сменя посоката на писане в рамките на текстов обект, се отваря в посоката на първия си знак
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip текст, използван като маска в свързани области, обтичащ текст или съставен път, не изрязва
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel свързаните картини без предварителен преглед във файла показват заместител, докато файловете им бъдат намерени: презакачете ги в панела „Връзки“
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -5259,6 +5259,8 @@ imageTrace Outline Obris
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers ugrađena slika od {_1} × {_2} piksela smanjena je na {_3} × {_4} piksela kako bi se zadržali slojevi
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel povezane slike prikazuju pregled niske rezolucije sačuvan u datoteci dok se njihove datoteke ne pronađu: ponovo ih povežite u panelu Veze
|
||||
@msg linked type areas past VectorCraft's limits were left out povezana područja teksta izvan ograničenja programa VectorCraft su izostavljena
|
||||
@msg the Line Breaking setting of legacy type was left out postavka prijeloma redova teksta u starom formatu je izostavljena
|
||||
@msg the Japanese layout rules of legacy type were left out japanska pravila rasporeda teksta u starom formatu su izostavljena
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character tekst koji mijenja smjer pisanja unutar tekstualnog objekta otvara se u smjeru svog prvog znaka
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip tekst korišten kao maska u povezanim područjima, omotanom tekstu ili složenoj putanji ne odsijeca
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel povezane slike bez pregleda u datoteci prikazuju čuvar mjesta dok se njihove datoteke ne pronađu: ponovo ih povežite u panelu Veze
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -5606,6 +5606,7 @@ digits Malayalam Malaiàlam
|
||||
@msgplural Discarded {n} recovered document|Discarded {n} recovered documents S’ha descartat {n} document recuperat|S’han descartat {n} documents recuperats
|
||||
@msg divide into 1 to {MAX_PIECES} slices divideix en 1 a {MAX_PIECES} talls
|
||||
@msg Divide Objects Below: select a path Divideix els objectes de sota: seleccioneu un traçat
|
||||
@msg select a path seleccioneu un traçat
|
||||
@msg Divide Objects Below: select exactly one path Divideix els objectes de sota: seleccioneu exactament un traçat
|
||||
@msg docking action contains an unknown panel or an excessive split path l’acció d’acoblament conté un panell desconegut o un camí de divisió excessiu
|
||||
@msg Downloaded {what} S’ha baixat {what}
|
||||
@@ -5732,6 +5733,8 @@ digits Malayalam Malaiàlam
|
||||
@msg library panel `{given}` isn't open el panell de biblioteca `{given}` no està obert
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel les imatges enllaçades mostren la previsualització de baixa resolució desada al fitxer fins que es trobin els seus fitxers: torneu-les a enllaçar al panell Enllaços
|
||||
@msg linked type areas past VectorCraft's limits were left out s’han omès les àrees de text enllaçades que superen els límits de VectorCraft
|
||||
@msg the Line Breaking setting of legacy type was left out s’ha omès l’ajust de salt de línia del text en format antic
|
||||
@msg the Japanese layout rules of legacy type were left out s’han omès les regles de composició japonesa del text en format antic
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character el text que canvia de direcció d’escriptura dins d’un objecte de text s’obre en la direcció del seu primer caràcter
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip el text usat com a màscara en àrees enllaçades, en text ajustat o en un traçat compost no retalla
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel les imatges enllaçades sense previsualització al fitxer mostren un marcador de posició fins que es trobin els seus fitxers: torneu-les a enllaçar al panell Enllaços
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4704,6 +4704,7 @@ imageTrace Outline Obrys
|
||||
@msg Plug-ins can't be loaded from {path}: {e} Zásuvné moduly nelze načíst z {path}: {e}
|
||||
@msg direct-select anchor points to cut at (not the end points of open paths) nástrojem Přímý výběr vyberte kotevní body, kde se má cesta rozdělit (ne koncové body otevřených cest)
|
||||
@msg Divide Objects Below: select a path Rozdělit objekty pod: vyberte cestu
|
||||
@msg select a path vyberte cestu
|
||||
@msg Divide Objects Below: select exactly one path Rozdělit objekty pod: vyberte právě jednu cestu
|
||||
@msg Downloaded {what} Staženo: {what}
|
||||
@msg Expand Appearance: the selection has a basic appearance Rozložit vzhled: výběr má základní vzhled
|
||||
@@ -5461,6 +5462,8 @@ imageTrace Outline Obrys
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers vložený obrázek o rozměrech {_1} × {_2} pixelů byl zmenšen na {_3} × {_4} pixelů, aby se zachovaly vrstvy
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel propojené obrázky se zobrazují jako náhled v nízkém rozlišení uložený v souboru, dokud se nenajdou jejich soubory: znovu je propojte v panelu Propojení
|
||||
@msg linked type areas past VectorCraft's limits were left out propojené textové oblasti nad limity aplikace VectorCraft byly vynechány
|
||||
@msg the Line Breaking setting of legacy type was left out nastavení zalamování řádků textu ve starém formátu bylo vynecháno
|
||||
@msg the Japanese layout rules of legacy type were left out japonská pravidla sazby textu ve starém formátu byla vynechána
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character text, který mění směr psaní uvnitř textového objektu, se otevře ve směru svého prvního znaku
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip text použitý jako maska v propojených oblastech, obtékaném textu nebo složené cestě neořezává
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel propojené obrázky bez náhledu v souboru se zobrazují jako zástupný symbol, dokud se nenajdou jejich soubory: znovu je propojte v panelu Propojení
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4946,6 +4946,8 @@ imageTrace Outline Kontur
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers et indlejret billede på {_1} × {_2} pixel blev formindsket til {_3} × {_4} pixel for at bevare lagene
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel linkede billeder viser den gemte forhåndsvisning i lav opløsning, indtil deres filer findes: link dem igen i Links-panelet
|
||||
@msg linked type areas past VectorCraft's limits were left out sammenkædede tekstområder ud over VectorCrafts grænser blev udeladt
|
||||
@msg the Line Breaking setting of legacy type was left out indstillingen for linjeskift i tekst i det gamle format blev udeladt
|
||||
@msg the Japanese layout rules of legacy type were left out de japanske layoutregler for tekst i det gamle format blev udeladt
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character tekst, der skifter skriveretning inde i et tekstobjekt, åbnes i retningen for sit første tegn
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip tekst brugt som maske i sammenkædede områder, ombrudt tekst eller en sammensat kurve beskærer ikke
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel linkede billeder uden forhåndsvisning i filen viser en pladsholder, indtil deres filer findes: link dem igen i Links-panelet
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4317,6 +4317,7 @@ theme Appearance Erscheinungsbild
|
||||
@msg Plug-ins can't be loaded from {path}: {e} Aus {path} können keine Plug-ins geladen werden: {e}
|
||||
@msg direct-select anchor points to cut at (not the end points of open paths) wählen Sie mit der Direktauswahl die Ankerpunkte aus, an denen geschnitten werden soll (nicht die Endpunkte offener Pfade)
|
||||
@msg Divide Objects Below: select a path Darunterliegende Objekte aufteilen: Wählen Sie einen Pfad aus
|
||||
@msg select a path Wählen Sie einen Pfad aus
|
||||
@msg Divide Objects Below: select exactly one path Darunterliegende Objekte aufteilen: Wählen Sie genau einen Pfad aus
|
||||
@msg Downloaded {what} {what} heruntergeladen
|
||||
@msg Expand Appearance: the selection has a basic appearance Aussehen umwandeln: Die Auswahl hat ein einfaches Aussehen
|
||||
@@ -5077,6 +5078,8 @@ theme Appearance Erscheinungsbild
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers ein eingebettetes Bild mit {_1} × {_2} Pixeln wurde auf {_3} × {_4} Pixel verkleinert, damit die Ebenen erhalten bleiben
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel verknüpfte Bilder zeigen die in der Datei gespeicherte Vorschau in niedriger Auflösung, bis ihre Dateien gefunden werden: Verknüpfen Sie sie im Bedienfeld „Verknüpfungen“ neu
|
||||
@msg linked type areas past VectorCraft's limits were left out verkettete Textbereiche jenseits der Grenzen von VectorCraft wurden ausgelassen
|
||||
@msg the Line Breaking setting of legacy type was left out die Einstellung für den Zeilenumbruch von Text im alten Format wurde ausgelassen
|
||||
@msg the Japanese layout rules of legacy type were left out die japanischen Satzregeln von Text im alten Format wurden ausgelassen
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character Text, der innerhalb eines Textobjekts die Schreibrichtung wechselt, wird in der Richtung seines ersten Zeichens geöffnet
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip als Maske verwendeter Text in verketteten Bereichen, umfließendem Text oder einem zusammengesetzten Pfad beschneidet nicht
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel verknüpfte Bilder ohne Vorschau in der Datei zeigen einen Platzhalter, bis ihre Dateien gefunden werden: Verknüpfen Sie sie im Bedienfeld „Verknüpfungen“ neu
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2464,6 +2464,7 @@ axis Both Και τα δύο
|
||||
@msg Plug-ins can't be loaded from {path}: {e} Δεν είναι δυνατή η φόρτωση πρόσθετων από το {path}: {e}
|
||||
@msg direct-select anchor points to cut at (not the end points of open paths) Επιλέξτε άμεσα τα σημεία αγκύρωσης όπου θα γίνει η αποκοπή (όχι τα τελικά σημεία ανοιχτών διαδρομών)
|
||||
@msg Divide Objects Below: select a path Διαίρεση αντικειμένων από κάτω: επιλέξτε μια διαδρομή
|
||||
@msg select a path επιλέξτε μια διαδρομή
|
||||
@msg Divide Objects Below: select exactly one path Διαίρεση αντικειμένων από κάτω: επιλέξτε ακριβώς μία διαδρομή
|
||||
@msg Downloaded {what} Έγινε λήψη του {what}
|
||||
@msg Expand Appearance: the selection has a basic appearance Επέκταση εμφάνισης: η επιλογή έχει βασική εμφάνιση
|
||||
@@ -5102,6 +5103,8 @@ digits Malayalam Μαλαγιάλαμ
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers μια ενσωματωμένη εικόνα {_1} × {_2} pixel μειώθηκε σε {_3} × {_4} pixel για να διατηρηθούν τα επίπεδα
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel οι συνδεδεμένες εικόνες εμφανίζουν την προεπισκόπηση χαμηλής ανάλυσης που έχει αποθηκευτεί, μέχρι να βρεθούν τα αρχεία τους: επανασυνδέστε τις στον πίνακα Σύνδεσμοι
|
||||
@msg linked type areas past VectorCraft's limits were left out οι συνδεδεμένες περιοχές κειμένου πέρα από τα όρια του VectorCraft παραλείφθηκαν
|
||||
@msg the Line Breaking setting of legacy type was left out η ρύθμιση αλλαγής γραμμής του κειμένου παλιάς μορφής παραλείφθηκε
|
||||
@msg the Japanese layout rules of legacy type were left out οι ιαπωνικοί κανόνες διάταξης του κειμένου παλιάς μορφής παραλείφθηκαν
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character το κείμενο που αλλάζει κατεύθυνση γραφής μέσα σε ένα αντικείμενο κειμένου ανοίγει με την κατεύθυνση του πρώτου χαρακτήρα του
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip το κείμενο που χρησιμοποιείται ως μάσκα σε συνδεδεμένες περιοχές, σε κείμενο με αναδίπλωση ή σε σύνθετη διαδρομή δεν αποκόπτει
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel οι συνδεδεμένες εικόνες χωρίς προεπισκόπηση στο αρχείο εμφανίζουν ένα σύμβολο κράτησης θέσης, μέχρι να βρεθούν τα αρχεία τους: επανασυνδέστε τις στον πίνακα Σύνδεσμοι
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4394,6 +4394,7 @@ axis Both Ambos
|
||||
@msg Plug-ins can't be loaded from {path}: {e} No se pueden cargar plugins desde {path}: {e}
|
||||
@msg direct-select anchor points to cut at (not the end points of open paths) selecciona con Selección directa los puntos de ancla en los que cortar (no los puntos finales de trazados abiertos)
|
||||
@msg Divide Objects Below: select a path Dividir objetos inferiores: selecciona un trazado
|
||||
@msg select a path selecciona un trazado
|
||||
@msg Divide Objects Below: select exactly one path Dividir objetos inferiores: selecciona exactamente un trazado
|
||||
@msg Downloaded {what} Se descargó {what}
|
||||
@msg Expand Appearance: the selection has a basic appearance Expandir apariencia: la selección tiene una apariencia básica
|
||||
@@ -5153,6 +5154,8 @@ axis Both Ambos
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers una imagen incrustada de {_1} × {_2} píxeles se redujo a {_3} × {_4} píxeles para conservar las capas
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel las imágenes vinculadas muestran la vista previa de baja resolución guardada en el archivo hasta que se encuentren sus archivos: vuelva a vincularlas en el panel Vínculos
|
||||
@msg linked type areas past VectorCraft's limits were left out se omitieron las áreas de texto enlazadas que superan los límites de VectorCraft
|
||||
@msg the Line Breaking setting of legacy type was left out se omitió el ajuste de salto de línea del texto en formato antiguo
|
||||
@msg the Japanese layout rules of legacy type were left out se omitieron las reglas de composición japonesa del texto en formato antiguo
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character el texto que cambia de dirección de escritura dentro de un objeto de texto se abre en la dirección de su primer carácter
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip el texto usado como máscara en áreas enlazadas, texto ceñido o un trazado compuesto no recorta
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel las imágenes vinculadas sin vista previa en el archivo muestran un marcador de posición hasta que se encuentren sus archivos: vuelva a vincularlas en el panel Vínculos
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4618,6 +4618,7 @@ imageTrace Outline Ääriviiva
|
||||
@msg Plug-ins can't be loaded from {path}: {e} Laajennuksia ei voi ladata kansiosta {path}: {e}
|
||||
@msg direct-select anchor points to cut at (not the end points of open paths) valitse suoravalinnalla ankkuripisteet, joista leikataan (ei avoimien polkujen päätepisteitä)
|
||||
@msg Divide Objects Below: select a path Jaa alla olevat objektit: valitse polku
|
||||
@msg select a path valitse polku
|
||||
@msg Divide Objects Below: select exactly one path Jaa alla olevat objektit: valitse tasan yksi polku
|
||||
@msg Downloaded {what} Ladattiin {what}
|
||||
@msg Expand Appearance: the selection has a basic appearance Laajenna ulkoasu: valinnalla on perusulkoasu
|
||||
@@ -5360,6 +5361,8 @@ imageTrace Outline Ääriviiva
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers upotettu {_1} × {_2} kuvapisteen kuva pienennettiin kokoon {_3} × {_4} kuvapistettä, jotta tasot säilyvät
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel linkitetyt kuvat näyttävät tiedostoon tallennetun matalan tarkkuuden esikatselun, kunnes niiden tiedostot löytyvät: linkitä ne uudelleen Linkit-paneelissa
|
||||
@msg linked type areas past VectorCraft's limits were left out VectorCraftin rajat ylittävät linkitetyt tekstialueet jätettiin pois
|
||||
@msg the Line Breaking setting of legacy type was left out vanhan muodon tekstin rivinvaihtoasetus jätettiin pois
|
||||
@msg the Japanese layout rules of legacy type were left out vanhan muodon tekstin japanilaiset asettelusäännöt jätettiin pois
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character tekstiobjektin sisällä kirjoitussuuntaa vaihtava teksti avautuu ensimmäisen merkkinsä suuntaan
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip maskina käytetty teksti linkitetyissä alueissa, rivitetyssä tekstissä tai yhdistelmäpolussa ei rajaa
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel linkitetyt kuvat, joilla ei ole esikatselua tiedostossa, näkyvät paikkamerkkinä, kunnes niiden tiedostot löytyvät: linkitä ne uudelleen Linkit-paneelissa
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4383,6 +4383,7 @@ axis Both Les deux
|
||||
@msg Plug-ins can't be loaded from {path}: {e} Impossible de charger les plug-ins depuis {path} ({e})
|
||||
@msg direct-select anchor points to cut at (not the end points of open paths) sélectionnez avec l’outil Sélection directe les points d’ancrage où couper (pas les extrémités des tracés ouverts)
|
||||
@msg Divide Objects Below: select a path Diviser les objets inférieurs : sélectionnez un tracé
|
||||
@msg select a path sélectionnez un tracé
|
||||
@msg Divide Objects Below: select exactly one path Diviser les objets inférieurs : sélectionnez exactement un tracé
|
||||
@msg Downloaded {what} {what} téléchargé
|
||||
@msg Expand Appearance: the selection has a basic appearance Décomposer l’aspect : la sélection a un aspect de base
|
||||
@@ -5140,6 +5141,8 @@ axis Both Les deux
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers une image incorporée de {_1} × {_2} pixels a été réduite à {_3} × {_4} pixels pour conserver les calques
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel les images liées affichent l’aperçu basse résolution enregistré dans le fichier tant que leurs fichiers ne sont pas trouvés : liez-les à nouveau dans le panneau Liens
|
||||
@msg linked type areas past VectorCraft's limits were left out les zones de texte liées au-delà des limites de VectorCraft ont été omises
|
||||
@msg the Line Breaking setting of legacy type was left out le réglage de coupure de ligne du texte à l’ancien format a été omis
|
||||
@msg the Japanese layout rules of legacy type were left out les règles de composition japonaise du texte à l’ancien format ont été omises
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character le texte qui change de sens d’écriture dans un objet texte s’ouvre dans le sens de son premier caractère
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip le texte utilisé comme masque dans des zones liées, un habillage de texte ou un tracé transparent ne découpe pas
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel les images liées sans aperçu dans le fichier affichent un espace réservé tant que leurs fichiers ne sont pas trouvés : liez-les à nouveau dans le panneau Liens
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -8376,6 +8376,8 @@ antiAlias Sharp शार्प
|
||||
@msg type dimension must be finite टाइप का आयाम परिमित होना चाहिए
|
||||
@msg type must be static or dynamic, not {v} type static या dynamic होना चाहिए, {v} नहीं
|
||||
@msg type objects can't be isolated टाइप ऑब्जेक्ट्स को आइसोलेट नहीं किया जा सकता
|
||||
@msg the Line Breaking setting of legacy type was left out पुराने प्रारूप के टेक्स्ट की लाइन ब्रेकिंग सेटिंग छोड़ दी गई
|
||||
@msg the Japanese layout rules of legacy type were left out पुराने प्रारूप के टेक्स्ट के जापानी लेआउट नियम छोड़ दिए गए
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character टेक्स्ट ऑब्जेक्ट के भीतर लेखन दिशा बदलने वाला टेक्स्ट अपने पहले वर्ण की दिशा में खुलता है
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip लिंक्ड एरिया, रैपअराउंड टेक्स्ट या कंपाउंड पाथ में मास्क के रूप में इस्तेमाल किया गया टाइप क्लिप नहीं करता
|
||||
@msg Unembedded to {_1} एम्बेड हटाकर {_1} में रखा गया
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4999,6 +4999,8 @@ imageTrace Outline Körvonal
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers egy {_1} × {_2} képpontos beágyazott kép {_3} × {_4} képpontosra lett kicsinyítve, hogy a rétegek megmaradjanak
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel a csatolt képek a fájlban mentett kis felbontású előnézetet mutatják, amíg a fájljaik elő nem kerülnek: csatold őket újra a Csatolások panelen
|
||||
@msg linked type areas past VectorCraft's limits were left out a VectorCraft korlátain túli csatolt szövegterületek kimaradtak
|
||||
@msg the Line Breaking setting of legacy type was left out a régi formátumú szöveg sortörési beállítása kimaradt
|
||||
@msg the Japanese layout rules of legacy type were left out a régi formátumú szöveg japán tördelési szabályai kimaradtak
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character a szövegobjektumon belül írásirányt váltó szöveg az első karakterének irányában nyílik meg
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip a csatolt területeken, körbefuttatott szövegben vagy összetett útvonalban maszkként használt szöveg nem vág ki
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel a fájlban előnézet nélküli csatolt képek helyőrzőt mutatnak, amíg a fájljaik elő nem kerülnek: csatold őket újra a Csatolások panelen
|
||||
@@ -5210,6 +5212,7 @@ imageTrace Outline Körvonal
|
||||
@msgplural Discarded {n} recovered document|Discarded {n} recovered documents Elvetett helyreállított dokumentumok: {n}
|
||||
@msg divide into 1 to {MAX_PIECES} slices a felosztás 1 és {MAX_PIECES} közötti szeletre lehetséges
|
||||
@msg Divide Objects Below: select a path Alatta lévő objektumok felosztása: jelölj ki egy útvonalat
|
||||
@msg select a path jelölj ki egy útvonalat
|
||||
@msg Divide Objects Below: select exactly one path Alatta lévő objektumok felosztása: pontosan egy útvonalat jelölj ki
|
||||
@msg docking action contains an unknown panel or an excessive split path a dokkolási művelet ismeretlen panelt vagy túl hosszú felosztási útvonalat tartalmaz
|
||||
@msg Downloaded {what} Letöltve: {what}
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4946,6 +4946,8 @@ imageTrace Outline Kontur
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers gambar tersemat berukuran {_1} × {_2} piksel diperkecil menjadi {_3} × {_4} piksel agar lapisannya tetap terjaga
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel gambar tertaut menampilkan pratinjau resolusi rendah yang tersimpan dalam berkas sampai berkasnya ditemukan: tautkan ulang di panel Tautan
|
||||
@msg linked type areas past VectorCraft's limits were left out area teks tertaut di luar batas VectorCraft dihilangkan
|
||||
@msg the Line Breaking setting of legacy type was left out pengaturan pemisah baris teks format lama dihilangkan
|
||||
@msg the Japanese layout rules of legacy type were left out aturan tata letak Jepang teks format lama dihilangkan
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character teks yang mengubah arah penulisan di dalam objek teks dibuka dengan arah karakter pertamanya
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip teks yang digunakan sebagai masker di area tertaut, teks terbungkus, atau jalur majemuk tidak memotong
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel gambar tertaut tanpa pratinjau dalam berkas menampilkan penanda tempat sampai berkasnya ditemukan: tautkan ulang di panel Tautan
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2429 and column 5.
|
@@ -4446,6 +4446,7 @@ axis Both Entrambi
|
||||
@msg Plug-ins can't be loaded from {path}: {e} Impossibile caricare plug-in da {path}: {e}
|
||||
@msg direct-select anchor points to cut at (not the end points of open paths) seleziona con Selezione diretta i punti di ancoraggio in cui tagliare (non i punti finali dei tracciati aperti)
|
||||
@msg Divide Objects Below: select a path Dividi oggetti sottostanti: seleziona un tracciato
|
||||
@msg select a path seleziona un tracciato
|
||||
@msg Divide Objects Below: select exactly one path Dividi oggetti sottostanti: seleziona esattamente un tracciato
|
||||
@msg Downloaded {what} Scaricato {what}
|
||||
@msg Expand Appearance: the selection has a basic appearance Espandi aspetto: la selezione ha un aspetto di base
|
||||
@@ -5205,6 +5206,8 @@ axis Both Entrambi
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers un'immagine incorporata di {_1} × {_2} pixel è stata ridotta a {_3} × {_4} pixel per mantenere i livelli
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel le immagini collegate mostrano l'anteprima a bassa risoluzione salvata nel file finché i loro file non vengono trovati: ricollegale nel pannello Collegamenti
|
||||
@msg linked type areas past VectorCraft's limits were left out le aree di testo concatenate oltre i limiti di VectorCraft sono state omesse
|
||||
@msg the Line Breaking setting of legacy type was left out l’impostazione di interruzione di riga del testo in formato precedente è stata omessa
|
||||
@msg the Japanese layout rules of legacy type were left out le regole di composizione giapponese del testo in formato precedente sono state omesse
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character il testo che cambia direzione di scrittura all’interno di un oggetto di testo si apre nella direzione del suo primo carattere
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip il testo usato come maschera in aree concatenate, testo attorno o un tracciato composto non ritaglia
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel le immagini collegate senza anteprima nel file mostrano un segnaposto finché i loro file non vengono trovati: ricollegale nel pannello Collegamenti
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4595,6 +4595,7 @@ swatch Bright Violet ビビッドバイオレット
|
||||
@msg direct-select anchor points to cut at (not the end points of open paths) ダイレクト選択ツールで、カットする位置のアンカーポイントを選択してください (オープンパスの端点を除く)
|
||||
@msg select paths or anchor points パスまたはアンカーポイントを選択してください
|
||||
@msg Divide Objects Below: select a path 背面のオブジェクトで型抜き: パスを選択してください
|
||||
@msg select a path パスを選択してください
|
||||
@msg Divide Objects Below: select exactly one path 背面のオブジェクトで型抜き: パスを 1 つだけ選択してください
|
||||
@msg Offset Path: select paths パスのオフセット: パスを選択してください
|
||||
@msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) パスのオフセット: オフセットすると選択したパスが何も残りません (内側へのオフセットがシェイプより大きい)
|
||||
@@ -4738,6 +4739,8 @@ swatch Bright Violet ビビッドバイオレット
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers レイヤーを保持するため、{_1} × {_2} ピクセルの埋め込み画像を {_3} × {_4} ピクセルに縮小しました
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel リンク画像は、元のファイルが見つかるまで、ファイルに保存された低解像度のプレビューで表示されます:リンクパネルで再リンクしてください
|
||||
@msg linked type areas past VectorCraft's limits were left out VectorCraft の上限を超えるリンクされたテキストエリアは省略されました
|
||||
@msg the Line Breaking setting of legacy type was left out 旧形式のテキストの行分割の設定は読み込まれませんでした
|
||||
@msg the Japanese layout rules of legacy type were left out 旧形式のテキストの日本語組版ルールは読み込まれませんでした
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character テキストオブジェクト内で書字方向が変わる文字は、最初の文字の方向で開きます
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip リンクされたエリア、テキストの回り込み、複合パス内でマスクとして使われた文字はクリップしません
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel ファイルにプレビューのないリンク画像は、元のファイルが見つかるまでプレースホルダーで表示されます:リンクパネルで再リンクしてください
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4098,6 +4098,7 @@ font-technology Variable ცვლადი
|
||||
@msg Plug-ins can't be loaded from {path}: {e} პლაგინების ჩატვირთვა ვერ ხერხდება აქედან: {path}: {e}
|
||||
@msg direct-select anchor points to cut at (not the end points of open paths) პირდაპირი მონიშვნით მონიშნეთ საყრდენი წერტილები, სადაც გაიჭრება (არა ღია ტრაექტორიების ბოლო წერტილები)
|
||||
@msg Divide Objects Below: select a path ქვედა ობიექტების დაყოფა: მონიშნეთ ტრაექტორია
|
||||
@msg select a path მონიშნეთ ტრაექტორია
|
||||
@msg Divide Objects Below: select exactly one path ქვედა ობიექტების დაყოფა: მონიშნეთ ზუსტად ერთი ტრაექტორია
|
||||
@msg Downloaded {what} ჩამოტვირთულია: {what}
|
||||
@msg Expand Appearance: the selection has a basic appearance იერსახის გაშლა: მონიშნულს საბაზისო იერსახე აქვს
|
||||
@@ -5185,6 +5186,8 @@ font-technology Variable ცვლადი
|
||||
Stacked დასტად
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel დაკავშირებული გამოსახულებები ფაილში შენახულ დაბალი გარჩევადობის მინიატურას აჩვენებს, სანამ მათი ფაილები არ მოიძებნება: დაუკავშირეთ ისინი ხელახლა ბმულების პანელში
|
||||
@msg linked type areas past VectorCraft's limits were left out VectorCraft-ის ლიმიტების მიღმა დაკავშირებული ტექსტის არეები გამოტოვებულია
|
||||
@msg the Line Breaking setting of legacy type was left out ძველი ფორმატის ტექსტის სტრიქონის გადატანის პარამეტრი გამოტოვებულია
|
||||
@msg the Japanese layout rules of legacy type were left out ძველი ფორმატის ტექსტის იაპონური განლაგების წესები გამოტოვებულია
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character ტექსტი, რომელიც ტექსტური ობიექტის შიგნით ცვლის წერის მიმართულებას, იხსნება მისი პირველი სიმბოლოს მიმართულებით
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip დაკავშირებულ არეებში, გარსშემოვლებულ ტექსტში ან შედგენილ ტრაექტორიაში ნიღბად გამოყენებული ტექსტი არ ჭრის
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel დაკავშირებული გამოსახულებები, რომელთა მინიატურაც ფაილში არ არის, ადგილის შემნახველს აჩვენებს, სანამ მათი ფაილები არ მოიძებნება: დაუკავშირეთ ისინი ხელახლა ბმულების პანელში
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4522,6 +4522,7 @@ theme Appearance 외관
|
||||
@msg direct-select anchor points to cut at (not the end points of open paths) 자를 앵커 포인트를 직접 선택하세요(열린 패스의 끝점 제외)
|
||||
@msg select paths or anchor points 패스 또는 앵커 포인트를 선택하세요
|
||||
@msg Divide Objects Below: select a path 아래 개체 분할: 패스를 선택하세요
|
||||
@msg select a path 패스를 선택하세요
|
||||
@msg Divide Objects Below: select exactly one path 아래 개체 분할: 패스를 하나만 선택하세요
|
||||
@msg Offset Path: select paths 패스 오프셋: 패스를 선택하세요
|
||||
@msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) 패스 오프셋: 오프셋을 적용하면 선택한 패스가 남지 않습니다(안쪽 오프셋이 모양보다 큼)
|
||||
@@ -4665,6 +4666,8 @@ theme Appearance 외관
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers 레이어를 유지하기 위해 {_1} × {_2} 픽셀의 포함된 이미지를 {_3} × {_4} 픽셀로 줄였습니다
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel 연결된 그림은 해당 파일을 찾을 때까지 파일에 저장된 저해상도 미리 보기로 표시됩니다: 링크 패널에서 다시 연결하세요
|
||||
@msg linked type areas past VectorCraft's limits were left out VectorCraft 한도를 넘는 연결된 문자 영역은 제외되었습니다
|
||||
@msg the Line Breaking setting of legacy type was left out 이전 형식 문자의 줄 바꿈 설정이 생략되었습니다
|
||||
@msg the Japanese layout rules of legacy type were left out 이전 형식 문자의 일본어 조판 규칙이 생략되었습니다
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character 문자 개체 안에서 쓰기 방향이 바뀌는 문자는 첫 글자의 방향으로 열립니다
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip 연결된 영역, 문자 감싸기 또는 컴파운드 패스에서 마스크로 사용된 문자는 클리핑하지 않습니다
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel 파일에 미리 보기가 없는 연결된 그림은 해당 파일을 찾을 때까지 자리 표시자로 표시됩니다: 링크 패널에서 다시 연결하세요
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4814,6 +4814,7 @@ imageTrace Outline Contour
|
||||
@msg Data Recovery has nowhere to keep copies: set Preferences → File Handling → Data Recovery → Folder (recoveryFolder) Gegevensherstel heeft nergens ruimte om kopieën te bewaren: stel Voorkeuren → Bestandsafhandeling → Gegevensherstel → Map (recoveryFolder) in
|
||||
@msg direct-select anchor points to cut at (not the end points of open paths) selecteer met directe selectie ankerpunten om te knippen (niet de eindpunten van open paden)
|
||||
@msg Divide Objects Below: select a path Objecten eronder verdelen: selecteer een pad
|
||||
@msg select a path selecteer een pad
|
||||
@msg Divide Objects Below: select exactly one path Objecten eronder verdelen: selecteer precies één pad
|
||||
@msg Downloaded {what} {what} gedownload
|
||||
@msg Expand Appearance: the selection has a basic appearance Vormgeving uitbreiden: de selectie heeft een basisvormgeving
|
||||
@@ -5462,6 +5463,8 @@ imageTrace Outline Contour
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers een ingesloten afbeelding van {_1} × {_2} pixels is verkleind tot {_3} × {_4} pixels om de lagen te behouden
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel gekoppelde afbeeldingen tonen het in het bestand opgeslagen voorbeeld met lage resolutie totdat hun bestanden zijn gevonden: koppel ze opnieuw in het paneel Koppelingen
|
||||
@msg linked type areas past VectorCraft's limits were left out gekoppelde tekstvlakken buiten de limieten van VectorCraft zijn weggelaten
|
||||
@msg the Line Breaking setting of legacy type was left out de instelling voor regelafbreking van tekst in de oude indeling is weggelaten
|
||||
@msg the Japanese layout rules of legacy type were left out de Japanse opmaakregels van tekst in de oude indeling zijn weggelaten
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character tekst die binnen een tekstobject van schrijfrichting verandert, wordt geopend in de richting van het eerste teken
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip tekst die als masker wordt gebruikt in gekoppelde vlakken, tekstomloop of een samengesteld pad knipt niet uit
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel gekoppelde afbeeldingen zonder voorbeeld in het bestand tonen een tijdelijke aanduiding totdat hun bestanden zijn gevonden: koppel ze opnieuw in het paneel Koppelingen
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -4528,6 +4528,7 @@ imageTrace Outline Kontur
|
||||
@msg Plug-ins can't be loaded from {path}: {e} Nie można wczytać wtyczek z {path}: {e}
|
||||
@msg direct-select anchor points to cut at (not the end points of open paths) zaznacz bezpośrednio punkty kontrolne, w których ma nastąpić cięcie (nie punkty końcowe otwartych ścieżek)
|
||||
@msg Divide Objects Below: select a path Podziel obiekty poniżej: zaznacz ścieżkę
|
||||
@msg select a path zaznacz ścieżkę
|
||||
@msg Divide Objects Below: select exactly one path Podziel obiekty poniżej: zaznacz dokładnie jedną ścieżkę
|
||||
@msg Downloaded {what} Pobrano {what}
|
||||
@msg Expand Appearance: the selection has a basic appearance Rozszerz wygląd: zaznaczenie ma wygląd podstawowy
|
||||
@@ -5288,6 +5289,8 @@ imageTrace Outline Kontur
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers osadzony obraz o wymiarach {_1} × {_2} pikseli zmniejszono do {_3} × {_4} pikseli, aby zachować warstwy
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel połączone obrazy pokazują zapisany w pliku podgląd niskiej rozdzielczości, dopóki ich pliki nie zostaną znalezione: połącz je ponownie w panelu Łącza
|
||||
@msg linked type areas past VectorCraft's limits were left out połączone obszary tekstu poza limitami VectorCraft zostały pominięte
|
||||
@msg the Line Breaking setting of legacy type was left out pominięto ustawienie łamania wierszy tekstu w starym formacie
|
||||
@msg the Japanese layout rules of legacy type were left out pominięto japońskie reguły składu tekstu w starym formacie
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character tekst zmieniający kierunek pisania wewnątrz obiektu tekstowego otwiera się w kierunku swojego pierwszego znaku
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip tekst użyty jako maska w połączonych obszarach, oblewanym tekście lub ścieżce złożonej nie przycina
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel połączone obrazy bez podglądu w pliku pokazują symbol zastępczy, dopóki ich pliki nie zostaną znalezione: połącz je ponownie w panelu Łącza
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -3858,6 +3858,7 @@ axis Both Ambos
|
||||
@msg Plug-ins can't be loaded from {path}: {e} Não é possível carregar plug-ins de {path}: {e}
|
||||
@msg direct-select anchor points to cut at (not the end points of open paths) selecione diretamente os pontos de ancoragem onde cortar (não as extremidades de traçados abertos)
|
||||
@msg Divide Objects Below: select a path Dividir objetos abaixo: selecione um traçado
|
||||
@msg select a path selecione um traçado
|
||||
@msg Divide Objects Below: select exactly one path Dividir objetos abaixo: selecione exatamente um traçado
|
||||
@msg Downloaded {what} {what} baixado
|
||||
@msg Expand Appearance: the selection has a basic appearance Expandir aparência: a seleção tem uma aparência básica
|
||||
@@ -5408,6 +5409,8 @@ axis Both Ambos
|
||||
@msg {path}: not a file {path}: não é um arquivo
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel as imagens vinculadas mostram a visualização de baixa resolução salva no arquivo até que seus arquivos sejam encontrados: revincule-as no painel Links
|
||||
@msg linked type areas past VectorCraft's limits were left out as áreas de texto encadeadas além dos limites do VectorCraft foram omitidas
|
||||
@msg the Line Breaking setting of legacy type was left out a configuração de quebra de linha do texto no formato antigo foi omitida
|
||||
@msg the Japanese layout rules of legacy type were left out as regras de composição japonesa do texto no formato antigo foram omitidas
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character o texto que muda de direção de escrita dentro de um objeto de texto abre na direção do primeiro caractere
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip o texto usado como máscara em áreas encadeadas, texto com quebra ou um caminho composto não recorta
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel as imagens vinculadas sem visualização no arquivo mostram um espaço reservado até que seus arquivos sejam encontrados: revincule-as no painel Links
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -4431,6 +4431,7 @@ axis Both Оба
|
||||
@msg Plug-ins can't be loaded from {path}: {e} Не удается загрузить модули из {path}: {e}
|
||||
@msg direct-select anchor points to cut at (not the end points of open paths) выделите прямым выделением опорные точки для разреза (не конечные точки открытых контуров)
|
||||
@msg Divide Objects Below: select a path Разделение объектов ниже: выделите контур
|
||||
@msg select a path выделите контур
|
||||
@msg Divide Objects Below: select exactly one path Разделение объектов ниже: выделите ровно один контур
|
||||
@msg Downloaded {what} Скачано: {what}
|
||||
@msg Expand Appearance: the selection has a basic appearance Разбор оформления: у выделения основное оформление
|
||||
@@ -5190,6 +5191,8 @@ axis Both Оба
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers встроенное изображение {_1} × {_2} пикселей уменьшено до {_3} × {_4} пикселей, чтобы сохранить слои
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel связанные изображения показываются как сохранённый в файле просмотр низкого разрешения, пока их файлы не найдены: восстановите связи на панели «Связи»
|
||||
@msg linked type areas past VectorCraft's limits were left out связанные текстовые области за пределами ограничений VectorCraft пропущены
|
||||
@msg the Line Breaking setting of legacy type was left out настройка разрыва строк текста старого формата пропущена
|
||||
@msg the Japanese layout rules of legacy type were left out японские правила вёрстки текста старого формата пропущены
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character текст, меняющий направление письма внутри текстового объекта, открывается в направлении своего первого символа
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip текст, используемый как маска в связанных областях, обтекающем тексте или составном контуре, не обрезает
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel связанные изображения без просмотра в файле показываются как заполнитель, пока их файлы не найдены: восстановите связи на панели «Связи»
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -5047,6 +5047,8 @@ axis Both Båda
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers en inbäddad bild på {_1} × {_2} pixlar förminskades till {_3} × {_4} pixlar för att behålla lagren
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel länkade bilder visar förhandsgranskningen med låg upplösning som sparats i filen tills deras filer hittas: länka om dem i panelen Länkar
|
||||
@msg linked type areas past VectorCraft's limits were left out länkade textområden utöver VectorCrafts gränser utelämnades
|
||||
@msg the Line Breaking setting of legacy type was left out inställningen för radbrytning i text i det gamla formatet utelämnades
|
||||
@msg the Japanese layout rules of legacy type were left out de japanska layoutreglerna för text i det gamla formatet utelämnades
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character text som byter skrivriktning inuti ett textobjekt öppnas i riktningen för sitt första tecken
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip text som används som mask i länkade områden, ombruten text eller en sammansatt bana beskär inte
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel länkade bilder utan förhandsgranskning i filen visar en platshållare tills deras filer hittas: länka om dem i panelen Länkar
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -2774,6 +2774,37 @@ fn plugin_limit_errors_are_translated() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The reason Object › Path's commands are unavailable while the selection holds no path has its
|
||||
/// own row in every language that translates every message, and shows translated both alone and
|
||||
/// inside the error a disabled command returns.
|
||||
#[test]
|
||||
fn selected_path_reason_is_translated() {
|
||||
use serde_json::json;
|
||||
use vectorcraft_engine::EngineError;
|
||||
let reason = "select a path";
|
||||
assert!(message_literals().contains(reason));
|
||||
let mut s = vectorcraft_engine::Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("text.create", &json!({"x": 10, "y": 10, "text": "Type"})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
let error = match s.execute("path.reverse", &json!({})) {
|
||||
Err(e @ EngineError::Disabled(..)) => e.to_string(),
|
||||
other => panic!("a selection of type alone: {other:?}"),
|
||||
};
|
||||
assert_eq!(error, "command `path.reverse` is not available right now: select a path");
|
||||
assert_eq!(message(Lang::EN, &error), error);
|
||||
for code in COMPLETE_MESSAGES {
|
||||
let lang = Lang::from_code(code).expect("registered");
|
||||
let (entries, _) = parse_entries(lang.0.source);
|
||||
let row = entries.iter().find(|(ctx, src, _)| ctx == "@msg" && src == reason).map(|(_, _, tr)| tr.as_str());
|
||||
let Some(row) = row else { panic!("{code}: no `@msg` row for {reason:?}") };
|
||||
assert_ne!(row, reason, "{code}");
|
||||
assert_eq!(message(lang, reason), row, "{code}");
|
||||
let shown = message(lang, &error);
|
||||
assert!(shown.contains(row) && !shown.contains(reason) && shown.contains("`path.reverse`"), "{code}: {shown}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The errors a script's `File` and `Folder` objects, `vc.run` and `$.evalFile` raise are
|
||||
/// translated in every language of [`COMPLETE_MESSAGES`], and so is the status bar's line for a run
|
||||
/// that ends with one: the script's name, its place, the command ids and what the script itself
|
||||
|
||||
@@ -4159,6 +4159,7 @@ axis Both Her İkisi
|
||||
@msg Plug-ins can't be loaded from {path}: {e} Eklentiler {path} konumundan yüklenemiyor: {e}
|
||||
@msg direct-select anchor points to cut at (not the end points of open paths) kesilecek bağlantı noktalarını doğrudan seçin (açık yolların bitiş noktalarını değil)
|
||||
@msg Divide Objects Below: select a path Aşağıdaki Nesneleri Böl: bir yol seçin
|
||||
@msg select a path bir yol seçin
|
||||
@msg Divide Objects Below: select exactly one path Aşağıdaki Nesneleri Böl: tam olarak bir yol seçin
|
||||
@msg Downloaded {what} {what} indirildi
|
||||
@msg Expand Appearance: the selection has a basic appearance Görünümü Genişlet: seçimin temel bir görünümü vardır
|
||||
@@ -4857,6 +4858,8 @@ axis Both Her İkisi
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers katmanları korumak için {_1} × {_2} piksellik gömülü bir resim {_3} × {_4} piksele küçültüldü
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel bağlantılı resimler, dosyaları bulunana kadar dosyaya kaydedilen düşük çözünürlüklü önizlemeyi gösterir: bunları Bağlantılar panelinde yeniden bağlayın
|
||||
@msg linked type areas past VectorCraft's limits were left out VectorCraft sınırlarını aşan bağlantılı metin alanları dışarıda bırakıldı
|
||||
@msg the Line Breaking setting of legacy type was left out eski biçimdeki metnin satır kesme ayarı atlandı
|
||||
@msg the Japanese layout rules of legacy type were left out eski biçimdeki metnin Japonca dizgi kuralları atlandı
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character bir metin nesnesi içinde yazı yönünü değiştiren metin, ilk karakterinin yönünde açılır
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip bağlantılı alanlarda, kaydırılan metinde veya bileşik yolda maske olarak kullanılan metin kırpmaz
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel dosyada önizlemesi olmayan bağlantılı resimler, dosyaları bulunana kadar bir yer tutucu gösterir: bunları Bağlantılar panelinde yeniden bağlayın
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 5 and column 25.
|
@@ -4430,6 +4430,7 @@ axis Both Обидві
|
||||
@msg Plug-ins can't be loaded from {path}: {e} Не вдається завантажити модулі з {path}: {e}
|
||||
@msg direct-select anchor points to cut at (not the end points of open paths) виділіть прямим виділенням опорні точки для розрізу (не кінцеві точки відкритих контурів)
|
||||
@msg Divide Objects Below: select a path Поділ об’єктів нижче: виділіть контур
|
||||
@msg select a path виділіть контур
|
||||
@msg Divide Objects Below: select exactly one path Поділ об’єктів нижче: виділіть рівно один контур
|
||||
@msg Downloaded {what} Завантажено: {what}
|
||||
@msg Expand Appearance: the selection has a basic appearance Розбір оформлення: виділення основне оформлення
|
||||
@@ -5189,6 +5190,8 @@ axis Both Обидві
|
||||
@msg an embedded image of {_1} × {_2} pixels was reduced to {_3} × {_4} pixels to keep the layers вбудоване зображення {_1} × {_2} пікселів зменшено до {_3} × {_4} пікселів, щоб зберегти шари
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel пов’язані зображення показуються як збережений у файлі перегляд низької роздільності, доки їхні файли не знайдено: відновіть зв’язки на панелі «Зв’язки»
|
||||
@msg linked type areas past VectorCraft's limits were left out пов’язані текстові області понад обмеження VectorCraft пропущено
|
||||
@msg the Line Breaking setting of legacy type was left out налаштування розриву рядків тексту старого формату пропущено
|
||||
@msg the Japanese layout rules of legacy type were left out японські правила верстки тексту старого формату пропущено
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character текст, що змінює напрямок письма всередині текстового об’єкта, відкривається в напрямку свого першого символу
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip текст, використаний як маска у пов’язаних областях, тексті з обтіканням або складеному контурі, не обрізає
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel пов’язані зображення без перегляду у файлі показуються як заповнювач, доки їхні файли не знайдено: відновіть зв’язки на панелі «Зв’язки»
|
||||
|
||||
|
Can't render this file because it is too large.
|
@@ -4866,6 +4866,7 @@ theme Appearance Giao diện
|
||||
@msgplural Discarded {n} recovered document|Discarded {n} recovered documents Đã loại bỏ {n} tài liệu đã phục hồi
|
||||
@msg divide into 1 to {MAX_PIECES} slices chia thành 1 đến {MAX_PIECES} lát cắt
|
||||
@msg Divide Objects Below: select a path Chia đối tượng bên dưới: hãy chọn một đường dẫn
|
||||
@msg select a path hãy chọn một đường dẫn
|
||||
@msg Divide Objects Below: select exactly one path Chia đối tượng bên dưới: chọn đúng một đường dẫn
|
||||
@msg docking action contains an unknown panel or an excessive split path hành động neo chứa bảng không xác định hoặc đường dẫn tách quá dài
|
||||
@msg Downloaded {what} Đã tải xuống {what}
|
||||
@@ -4976,6 +4977,8 @@ theme Appearance Giao diện
|
||||
@msg line {line}: value for `{var}` is longer than {MAX_GRAPH_CSV} bytes dòng {line}: giá trị của `{var}` dài hơn {MAX_GRAPH_CSV} byte
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel ảnh liên kết hiển thị bản xem trước độ phân giải thấp đã lưu trong tệp cho đến khi tìm thấy tệp gốc: liên kết lại trong bảng Liên kết
|
||||
@msg linked type areas past VectorCraft's limits were left out các vùng chữ liên kết vượt quá giới hạn của VectorCraft đã bị bỏ qua
|
||||
@msg the Line Breaking setting of legacy type was left out thiết lập ngắt dòng của chữ định dạng cũ đã bị bỏ qua
|
||||
@msg the Japanese layout rules of legacy type were left out các quy tắc dàn trang tiếng Nhật của chữ định dạng cũ đã bị bỏ qua
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character chữ đổi hướng viết bên trong một đối tượng văn bản sẽ mở theo hướng của ký tự đầu tiên
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip chữ dùng làm mặt nạ trong các vùng liên kết, chữ bao quanh hoặc đường dẫn phức không cắt xén
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel ảnh liên kết không có bản xem trước trong tệp hiển thị ô giữ chỗ cho đến khi tìm thấy tệp gốc: liên kết lại trong bảng Liên kết
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 204 and column 5.
|
@@ -3736,6 +3736,8 @@ digits Malayalam 马拉雅拉姆数字
|
||||
@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? 有 {n} 个链接图像已在磁盘上更改。要显示新版本吗?
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel 链接的图片在找到其文件之前显示文件中存储的低分辨率预览:请在“链接”面板中重新链接
|
||||
@msg linked type areas past VectorCraft's limits were left out 超出 VectorCraft 限制的串接文字区域已省略
|
||||
@msg the Line Breaking setting of legacy type was left out 旧格式文字的换行设置已省略
|
||||
@msg the Japanese layout rules of legacy type were left out 旧格式文字的日文排版规则已省略
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character 在文字对象内更改书写方向的文字按其第一个字符的方向打开
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip 在串接区域、绕排文字或复合路径中用作蒙版的文字不会剪切
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel 文件中没有预览的链接图片在找到其文件之前显示占位符:请在“链接”面板中重新链接
|
||||
@@ -4293,6 +4295,7 @@ imageTrace Outline 轮廓
|
||||
@msg direct-select anchor points to cut at (not the end points of open paths) 请直接选择要在其处切割的锚点 (不能是开放路径的端点)
|
||||
@msg select paths or anchor points 请选择路径或锚点
|
||||
@msg Divide Objects Below: select a path 分割下方对象:请选择一条路径
|
||||
@msg select a path 请选择一条路径
|
||||
@msg Divide Objects Below: select exactly one path 分割下方对象:请只选择一条路径
|
||||
@msg Offset Path: select paths 偏移路径:请选择路径
|
||||
@msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) 偏移路径:偏移后所选路径不剩任何部分 (内缩量大于形状)
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -2006,6 +2006,7 @@ file-filter Templates 範本
|
||||
@msg direct-select anchor points to cut at (not the end points of open paths) 請直接選取要剪開的錨點 (不能是開放路徑的端點)
|
||||
@msg select paths or anchor points 請選取路徑或錨點
|
||||
@msg Divide Objects Below: select a path 分割下方物件:請選取路徑
|
||||
@msg select a path 請選取路徑
|
||||
@msg Divide Objects Below: select exactly one path 分割下方物件:請只選取一條路徑
|
||||
@msg Offset Path: select paths 位移複製:請選取路徑
|
||||
@msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) 位移複製:位移後所選路徑不留任何部分 (內縮量大於形狀)
|
||||
@@ -4993,6 +4994,8 @@ digits Malayalam 馬來亞拉姆數字
|
||||
@plural {n} linked image changed on disk. Show the new version?|{n} linked images changed on disk. Show the new versions? 有 {n} 個連結影像已在磁碟上變更。要顯示新版本嗎?
|
||||
@msg linked pictures show the low-resolution preview saved in the file until their files are found: relink them in the Links panel 連結的圖片在找到其檔案之前顯示檔案中儲存的低解析度預覽:請在「連結」面板中重新連結
|
||||
@msg linked type areas past VectorCraft's limits were left out 超出 VectorCraft 限制的串連文字區域已略過
|
||||
@msg the Line Breaking setting of legacy type was left out 已略過舊格式文字的換行設定
|
||||
@msg the Japanese layout rules of legacy type were left out 已略過舊格式文字的日文排版規則
|
||||
@msg type that changes writing direction inside a text object opens in the direction of its first character 在文字物件內變更書寫方向的文字會依其第一個字元的方向開啟
|
||||
@msg type used as a mask in linked areas, wraparound text or a compound path doesn't clip 在串連區域、繞圖文字或複合路徑中用作遮色片的文字不會剪裁
|
||||
@msg linked pictures with no preview in the file show a placeholder until their files are found: relink them in the Links panel 檔案中沒有預覽的連結圖片在找到其檔案之前顯示預留位置:請在「連結」面板中重新連結
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -41,6 +41,7 @@ pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option<Strin
|
||||
// A `.ai` file names the view's active artboard.
|
||||
remember_active_artboard(app);
|
||||
let st = app.session.active().ok_or("no document")?;
|
||||
fileio::check_linked_scripts("file.exportAs", f.id, st).map_err(|e| e.to_string())?;
|
||||
let doc = match fileio::export_doc(st, f, params).map_err(|e| e.to_string())? {
|
||||
std::borrow::Cow::Borrowed(_) => st.doc.clone(),
|
||||
std::borrow::Cow::Owned(d) => std::sync::Arc::new(d),
|
||||
|
||||
@@ -227,6 +227,10 @@ pub struct VectorcraftApp {
|
||||
/// Windows and Linux: the window has no OS decorations, so the app bar is the title bar (drag,
|
||||
/// double-click to maximize, caption buttons) and invisible edge zones resize the window.
|
||||
pub custom_titlebar: bool,
|
||||
/// Where the caption buttons go on the app bar while [`Self::custom_titlebar`] is on: the
|
||||
/// desktop's window-button layout on Linux and the BSDs where the desktop leaves the frame to the
|
||||
/// app, all three at the right otherwise.
|
||||
pub caption_layout: titlebar::CaptionLayout,
|
||||
/// The window has the desktop's own title bar: the OS or the window manager draws its frame,
|
||||
/// icon and title. Set by the desktop app when it opens the window; `false` for embedders
|
||||
/// without a window of their own.
|
||||
|
||||
@@ -1331,7 +1331,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"file.exportAs",
|
||||
"Export As…",
|
||||
"",
|
||||
"{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}",
|
||||
"{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}; under automation read roots, an SVG or SVGZ is refused while the document links a JavaScript file outside them, as document.export refuses it",
|
||||
),
|
||||
(
|
||||
"ui.fileInfoDialog",
|
||||
|
||||
@@ -242,6 +242,36 @@ fn control_export_refuses_an_option_no_format_takes() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `app.export`, and `file.exportAs` run as a command, write no SVG of a document that links a
|
||||
/// JavaScript file outside the read root, and the error names no file or folder; the person at the
|
||||
/// keyboard exports it with the link as stored.
|
||||
#[test]
|
||||
fn control_svg_export_refuses_a_linked_javascript_file_outside_the_read_root() {
|
||||
let (mut app, tx, base) = confined("svg-script");
|
||||
app.run("file.new", json!({"width": 100, "height": 50})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
|
||||
let script = s(base.join("outside/menu.js"));
|
||||
app.run("svgInteractivity.addFile", json!({"file": script})).unwrap();
|
||||
let path = s(base.join("out/a.svg"));
|
||||
for (method, params) in [
|
||||
("app.export", json!({"path": path, "format": "svg", "wait": true})),
|
||||
("app.export", json!({"path": s(base.join("out/a.svgz")), "wait": true})),
|
||||
("app.export", json!({"format": "svg"})),
|
||||
("engine.execute", json!({"command": "file.exportAs", "params": {"path": path, "format": "svg"}})),
|
||||
] {
|
||||
let r = request(&mut app, &tx, method, params.clone());
|
||||
let e = r["error"].as_str().unwrap_or_default();
|
||||
assert!(e.contains("a linked JavaScript file is outside the read roots"), "{method} {params}: {r}");
|
||||
assert!(!e.contains("menu.js") && !e.contains(&s(base.clone())), "{method} {params}: {r}");
|
||||
}
|
||||
assert_eq!(std::fs::read_dir(base.join("out")).unwrap().count(), 0, "nothing written");
|
||||
// The person at the keyboard isn't confined.
|
||||
app.run("file.exportAs", json!({"path": path, "format": "svg"})).unwrap();
|
||||
let svg = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(svg.contains(&format!("<script xlink:href=\"{script}\"/>")), "{svg}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// `app.export` with a path writes the file when given an option only another format reads, and
|
||||
/// its warnings name that option, as `document.export`'s do without a path. `file.exportAs` run
|
||||
/// as a command does the same; an export that automation did not ask for gets no such note.
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! The window's own title bar on Windows and Linux, where the window has no OS decorations
|
||||
//! ([`VectorcraftApp::custom_titlebar`]): empty space in the app bar drags the window and a
|
||||
//! double-click there maximizes it, caption buttons at the far right minimize, maximize/restore and
|
||||
//! close, and thin invisible zones along the window's edges resize it. On macOS the app bar sits
|
||||
//! under the system's transparent title bar and only its [`drag_area`] is used.
|
||||
//! double-click there maximizes it, caption buttons at the ends that [`CaptionLayout`] names (all three
|
||||
//! at the far right by default) minimize, maximize/restore and close, and thin invisible zones along
|
||||
//! the window's edges resize it. On macOS the app bar sits under the system's transparent title bar
|
||||
//! and only its [`drag_area`] is used.
|
||||
|
||||
use egui::{CursorIcon, Id, LayerId, Order, PointerButton, Rect, ResizeDirection, Sense, Stroke, Ui, ViewportCommand, pos2, vec2};
|
||||
use serde_json::json;
|
||||
@@ -18,16 +19,44 @@ pub const WIDTH: f32 = 3.0 * BUTTON_WIDTH;
|
||||
const EDGE: f32 = 5.0;
|
||||
const CORNER: f32 = 12.0;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
enum Caption {
|
||||
/// A caption button.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum Caption {
|
||||
Minimize,
|
||||
Maximize,
|
||||
Close,
|
||||
}
|
||||
|
||||
/// Left to right.
|
||||
/// The default order, left to right.
|
||||
const CAPTIONS: [Caption; 3] = [Caption::Minimize, Caption::Maximize, Caption::Close];
|
||||
|
||||
/// Which caption buttons the app bar draws at its left end and at its right end, each list left to
|
||||
/// right. The desktop app sets it from the desktop's window-button layout on Linux and the BSDs
|
||||
/// ([`VectorcraftApp::caption_layout`]). The default has Minimize, Maximize and Close at the right.
|
||||
#[derive(Clone, PartialEq, Eq, Debug)]
|
||||
pub struct CaptionLayout {
|
||||
pub left: Vec<Caption>,
|
||||
pub right: Vec<Caption>,
|
||||
}
|
||||
|
||||
impl Default for CaptionLayout {
|
||||
fn default() -> Self {
|
||||
Self { left: Vec::new(), right: CAPTIONS.to_vec() }
|
||||
}
|
||||
}
|
||||
|
||||
impl CaptionLayout {
|
||||
/// The width the buttons at the left end take.
|
||||
pub fn left_width(&self) -> f32 {
|
||||
self.left.len() as f32 * BUTTON_WIDTH
|
||||
}
|
||||
|
||||
/// The width the buttons at the right end take.
|
||||
pub fn right_width(&self) -> f32 {
|
||||
self.right.len() as f32 * BUTTON_WIDTH
|
||||
}
|
||||
}
|
||||
|
||||
/// Caption button ids (stable, so tests and agents can find them).
|
||||
fn caption_id(c: Caption) -> Id {
|
||||
Id::unique(("titlebar-caption", c as u8))
|
||||
@@ -70,15 +99,21 @@ fn handed_to_os(ctx: &egui::Context) {
|
||||
ctx.input_mut(|i| i.pointer = Default::default());
|
||||
}
|
||||
|
||||
/// Minimize, Maximize/Restore and Close at the right end of `bar` (the app bar's outer rect), full
|
||||
/// bar height down to its bottom border, flush with the window's edge so a maximized window's
|
||||
/// corner hits Close. Close runs `app.quit`, which asks about unsaved documents first.
|
||||
/// The buttons of [`VectorcraftApp::caption_layout`] at the left and right ends of `bar` (the app
|
||||
/// bar's outer rect), full bar height down to its bottom border, flush with the window's edges so a
|
||||
/// maximized window's corner hits the outermost button. Close runs `app.quit`, which asks about
|
||||
/// unsaved documents first.
|
||||
pub fn caption_buttons(app: &mut VectorcraftApp, ui: &mut Ui, bar: Rect) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let max = maximized(ui.ctx());
|
||||
let mut clicked = None;
|
||||
for (i, c) in CAPTIONS.into_iter().enumerate() {
|
||||
let r = Rect::from_min_size(pos2(bar.right() - WIDTH + i as f32 * BUTTON_WIDTH, bar.top()), vec2(BUTTON_WIDTH, bar.height() - 1.0));
|
||||
let layout = &app.caption_layout;
|
||||
let left = layout.left.iter().enumerate().map(|(i, c)| (*c, bar.left() + i as f32 * BUTTON_WIDTH));
|
||||
let right_start = bar.right() - layout.right_width();
|
||||
let right = layout.right.iter().enumerate().map(|(i, c)| (*c, right_start + i as f32 * BUTTON_WIDTH));
|
||||
let placed: Vec<(Caption, f32)> = left.chain(right).collect();
|
||||
for (c, x) in placed {
|
||||
let r = Rect::from_min_size(pos2(x, bar.top()), vec2(BUTTON_WIDTH, bar.height() - 1.0));
|
||||
let resp = ui.interact(r, caption_id(c), Sense::click());
|
||||
let close = c == Caption::Close;
|
||||
let fill = match (resp.is_pointer_button_down_on(), resp.hovered()) {
|
||||
@@ -296,6 +331,43 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The caption layout decides which buttons the bar draws and at which end, each end in its
|
||||
/// listed order: Close alone at the right, all three at the left with Close outermost, and a
|
||||
/// split. The bar's other controls stay between the two groups, and Close works at either end.
|
||||
#[test]
|
||||
fn caption_buttons_follow_the_caption_layout() {
|
||||
use Caption::*;
|
||||
let width = 1100.0;
|
||||
for (left, right) in [(vec![], vec![Close]), (vec![Close, Minimize, Maximize], vec![]), (vec![Close], vec![Minimize, Maximize])] {
|
||||
let label = format!("{left:?} : {right:?}");
|
||||
let mut w = Win::new(width);
|
||||
w.app.caption_layout = CaptionLayout { left: left.clone(), right: right.clone() };
|
||||
w.frame(vec![]);
|
||||
w.frame(vec![]);
|
||||
for (i, c) in left.iter().enumerate() {
|
||||
let r = w.caption(*c);
|
||||
assert_eq!((r.left(), r.top(), r.width()), (i as f32 * BUTTON_WIDTH, 0.0, BUTTON_WIDTH), "{c:?} in {label}");
|
||||
}
|
||||
for (i, c) in right.iter().enumerate() {
|
||||
let r = w.caption(*c);
|
||||
let right_edge = width - (right.len() - 1 - i) as f32 * BUTTON_WIDTH;
|
||||
assert_eq!((r.right(), r.top(), r.width()), (right_edge, 0.0, BUTTON_WIDTH), "{c:?} in {label}");
|
||||
}
|
||||
for c in CAPTIONS.into_iter().filter(|c| !left.contains(c) && !right.contains(c)) {
|
||||
assert_eq!(w.caption(c), Rect::NOTHING, "{c:?} is not drawn in {label}");
|
||||
}
|
||||
let (start, end) = (left.len() as f32 * BUTTON_WIDTH, width - right.len() as f32 * BUTTON_WIDTH);
|
||||
let widgets = w.bar_widgets();
|
||||
assert!(widgets.len() >= 11, "home, eight menus, workspace switcher, search in {label}: {widgets:?}");
|
||||
for r in &widgets {
|
||||
assert!(r.left() >= start + 8.0 && r.right() <= end - 8.0, "{r:?} runs into the caption buttons in {label}");
|
||||
}
|
||||
let close = w.caption(Close).center();
|
||||
w.click(close);
|
||||
assert_eq!(w.app.ui.status, "quit", "Close in {label}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_runs_the_quit_flow_instead_of_closing_the_window() {
|
||||
let mut w = Win::new(1000.0);
|
||||
|
||||
@@ -346,9 +346,16 @@ Tile Edge Color: Object → Pattern → Tile Edge Color… (`ui.tileEdgeColor`)
|
||||
A `color` with an alpha part (`#rrggbbaa` or `#rgba`) is an error, and the preference does not change.
|
||||
|
||||
Window title bar: on Windows and Linux the window has no OS decorations and the app bar is the title bar. Its
|
||||
caption buttons (Minimize, Maximize/Restore, Close) sit at the bar's right end, 46 pt each; they are window chrome,
|
||||
not commands, so drive them with `ui.click` if needed. Close runs `app.quit` (the same `saveChanges` questions for
|
||||
modified documents), and empty bar space and the 5 pt window edges move and resize the window. Preferences › User
|
||||
caption buttons (Minimize, Maximize/Restore, Close) are 46 pt each. By default all three sit at the bar's right end.
|
||||
On Linux and the BSDs, when the desktop leaves the window's frame to the app (a Wayland session without server-side
|
||||
decorations, such as GNOME), the window is not opened through XWayland and `VECTORCRAFT_TITLEBAR` is unset, they
|
||||
follow the `button-layout` key of `org.gnome.desktop.wm.preferences`, read when the app starts: each button the key
|
||||
names goes to the end it is listed on, in the listed order (the first one leftmost), and the buttons it does not name
|
||||
are not drawn. When `gsettings` is missing or fails, or the key names none of `minimize`, `maximize` and `close`, all
|
||||
three stay at the right end. An app frame turned on by `VECTORCRAFT_TITLEBAR=app` or by VectorCraft Title Bar on Every
|
||||
Desktop also keeps all three at the right end. The buttons are window chrome, not commands, so drive them with
|
||||
`ui.click` if needed. Close runs `app.quit` (the same `saveChanges` questions for modified documents), and empty bar
|
||||
space and the 5 pt window edges move and resize the window. Preferences › User
|
||||
Interface › System Title Bar (`systemTitleBar`, read when the app starts) gives the window its OS decorations back
|
||||
instead: the OS title then shows the active document (`*name — VectorCraft` with unsaved changes) and the app bar
|
||||
drops its brand mark. On Linux the app bar also drops its brand mark whenever the desktop draws the window's frame, with
|
||||
|
||||
@@ -22,7 +22,7 @@ Ordinary File > Save offers Save As when its own location refuses writes with a
|
||||
| | Illustrator | VectorCraft | Notes |
|
||||
|---|---:|---:|---|
|
||||
| Formats opened or placed | ~30 | 31 | missing: FreeHand, CorelDRAW, DWG, PS |
|
||||
| Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, gradients, patterns, images, type, symbols, artboards, transparency, opacity masks, clipping) or as legacy version 7 (layers and groups, one artboard per file) |
|
||||
| Formats saved (Save As) | 6 (AI, AIT, PDF, EPS, SVG, SVGZ) | 6 + native | `.ai` written PDF-compatible (with an editing copy of the art: layers, groups, paths, colors, gradients, patterns, images, type, symbols, artboards, transparency, opacity masks, clipping, text wrap options) or as legacy version 7 (layers and groups, one artboard per file) |
|
||||
| Formats exported | ~16 | 18 | missing: DWG; extra: GIF/PNG-8 palette export, DXF up to 2018, layered PSD |
|
||||
| **Overall (weighted by use)** | | **~75%** | `.ai` and PDF dominate the weighting |
|
||||
|
||||
@@ -196,6 +196,11 @@ private editing data. VectorCraft:
|
||||
as that art, with one note that counts them. Type stays live without a comparison when the saved art paints
|
||||
nothing or draws type of its own, in frames of threaded type, when a text variable binds it, and when its text
|
||||
object doesn't come in as one text object.
|
||||
Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`: the kerning after the character before the
|
||||
pair, or at a line's start the space before its first character), its discretionary hyphens (`T+`, `T-`) as
|
||||
soft hyphens and its hyphenation language (`XL`); a line breaking value (`TG`) and Japanese layout rules
|
||||
(`Xu`, `Tu`) are not kept, with a warning. Legacy `.ai` saves write manual kerning as `Tk` and soft hyphens
|
||||
as `T+`.
|
||||
Legacy `.ai` type keeps its paragraphs' letter and word spacing (`TC`, `TW`), hanging punctuation (`Tq`) and
|
||||
hyphenation (`Th`); its tab definitions (`Xb` … `XB`) set its paragraphs' tab stops. Paragraphs in a row with
|
||||
the same attributes share one copy of them while the text object is read, and those copies hold at most
|
||||
|
||||
+20
-1
@@ -234,6 +234,14 @@ the suite) keep the agent to the folders you give it:
|
||||
file outside the read roots by its file name alone in `files`, as `document.json` does, and `removeFile` takes that
|
||||
name for it (see SVG interactivity). In a frame a request drives, the JavaScript Files dialog lists such a file by
|
||||
its file name, and `ui_inspect` gives the file selected in the dialog the same way.
|
||||
- An SVG or SVGZ of a document that links a JavaScript file outside the read roots (SVG Interactivity's files: a
|
||||
path, a `file:` URL, or a relative path taken from the document's folder) is refused with "a linked JavaScript
|
||||
file is outside the read roots", which names no file or folder: `document.serialize`, `document.export` (MCP's
|
||||
`export`), `document.exportSelection`, `document.exportForScreens` and `assets.export` (before the folder is
|
||||
made or any row is written), `document.save`, `file.save`, `file.saveAs` and `file.saveCopy` (also a save
|
||||
without a path of a document whose own format is SVG or SVGZ), `file.exportAs`, and the SVG Options dialog's
|
||||
Show Code. A file given as another URL (`https://…`) is not checked. The document keeps the link, and the
|
||||
person at the keyboard exports it as stored.
|
||||
- `plugin.list`, `plugin.safeMode`, `file.recovery.*` and `ui_inspect`'s `scriptReport` leave out the paths
|
||||
outside the read roots, also those the person or an earlier request put there. In `plugin.list`, the plug-in
|
||||
folder last loaded is `null` in `folder.folder`, and a failed file in `folder.failed` and a plug-in's `source`
|
||||
@@ -795,6 +803,16 @@ The other commands given a series group's id edit the group itself, and the grap
|
||||
`appearance.addEffect`, and the paint, stroke and gradient commands with a fill or stroke `item`, which is a row of the
|
||||
group's own stack. The Appearance panel and `appearance.setActiveItem` read the selected group's own rows.
|
||||
|
||||
The graph draws the art of a column or marker design in a series again from the design, so the commands that add,
|
||||
change, move or remove fill and stroke rows, effects or graphic styles leave that art out: the `appearance.*` commands
|
||||
listed above, `effect.apply`, `appearance.addEffect` and the other `effect.*` commands that edit, move or remove an
|
||||
effect, `graphicStyle.apply` (and `graphicStyle.addFromLibrary` with `apply`), `transparency.set` with a fill or stroke
|
||||
`item`, and `appearance.copyFrom` as the target. The art is any object inside a series group other than a path directly
|
||||
in it, whether given by id, selected, or reached through `target: "contents"`. The commands edit the other objects they
|
||||
are given, and a command whose objects are all design art is an error. `appearance.transfer` with design art as its
|
||||
`target`, or as its `source` without `copy`, is an error. The paint commands leave the art out as well, without an
|
||||
error. To change the art, edit the design with `graph.design`.
|
||||
|
||||
The graph also stores a paint or stroke weight that one of these commands changes on the topmost visible fill or stroke
|
||||
of a path directly in a series: a weight set with `stroke.set`, `stroke.weightUp` or `stroke.weightDown`; a gradient
|
||||
made, placed or edited with `paint.editGradient`, `paint.setGradientGeom`, `paint.freeform.addPoint`,
|
||||
@@ -4979,7 +4997,8 @@ more than one linked file (two such files, or such a file and a file linked as t
|
||||
error and unlinks nothing. `ui.javascriptFilesDialog {}`
|
||||
opens the JavaScript Files dialog, whose Choose… puts a picked file in as a `file:///` URL. SVG export writes each event
|
||||
as an event attribute on the object's element (`onclick="…"`; with the SVG Tiny 1.2 profile it leaves them out with a
|
||||
warning) and each file as `<script xlink:href>`. SVG import reads the event attributes the panel lists and the
|
||||
warning) and each file as `<script xlink:href>`, as stored; for a caller with automation read roots, an SVG or SVGZ
|
||||
of a document that links a file outside them is refused (see the read roots above). SVG import reads the event attributes the panel lists and the
|
||||
`<script>` links back as text; it never reads a script file or runs a script, and leaves inline scripts and the links
|
||||
after the first 64 out with a warning. An unnamed `<g>` with event attributes of its own stays a group, apart from the object in
|
||||
it. The native format keeps the events and the files.
|
||||
|
||||
@@ -250,9 +250,9 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de
|
||||
| Image Trace, graphs, image tools | 3 | 75% | graph Column designs, Image Trace Create Strokes depth (Create Object Mosaic is done; junction-returning piece survival has source-generated regressions in `image-trace-quality.md`; large images trace with a warning; Auto Color keeps rare distinct colours) | 5–8 | estimated (raised from 72%); quick presets reveal adjustment controls, Properties reopens them |
|
||||
| Layers, artboards, document setup | 5 | 78% | Selected-artboard deletion is consistent across panel actions (all-selected retains artboard 1); history prunes removed indices while preserving valid multiselection; remaining: 30.0's artboard locking and colours and managing artboards from the canvas, Layers row menu commands beyond Collect for Export and menus on guide and blend spine rows (click-to-fit objects is done, #1227) | 5–8 | estimated (lowered from 82%: target moved); Artboard deletion keys keep artwork and the first of an all-selected set; Artboard Options' Show Center Mark and Show Cross Hairs draw on the canvas only (exports and print leave them out), regression-tested; Artboard Options' Show Video Safe Areas and Video Ruler Pixel Aspect Ratio (per artboard, native format) are done ([video display options](#evidence-what-ships-today-by-area)), score unchanged |
|
||||
| View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged); cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission (regression evidence below) |
|
||||
| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. |
|
||||
| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. |
|
||||
| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. |
|
||||
| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), no writing of Illustrator's editing data (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); DXF export's Include Placed Images and Include Fill Hatches options, off in CNC / CAM (`images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`; score, gaps and hours unchanged); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`; the distance from the path under Align to Path is measured from the top of each character's em box, half the height of the top of its H or the bottom of its font's bounding box (`tests_native::aligned_type_lies_as_far_from_its_path_as_the_file_lays_it_out`), and the fit under Gravity does not reproduce the file's layout), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. |
|
||||
| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, textures, map art and shading in 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. |
|
||||
| File formats | 6 | 75% | `.ai` files open with a flattened or wrong layer structure in real cases (#951), a saved `.ai`'s editing copy without live effects on objects other than paths, compound paths and groups that qualify (at most a fill and a stroke, a non-zero fill rule when filled, no large canvas) and whose appearance and effects the art-style writer supports, and with live objects as their art (#868), FreeHand/CorelDRAW/DWG/HEIC import, 3D export; see [file-format-parity.md](file-format-parity.md); EPS legacy mesh/opacity-mask and raster comparison follow-up verified PDF marked-text batching covered by M4 evidence (#6309); cross-line/style ActualText layout (#6165) and styled-cluster limits remain.| 10–20 | estimated (lowered from 85%: open issues); DXF control-point SPLINE import closure regression-tested (#1299 follow-up after #1320); PDF writer metadata, reader streaming and immutable backend checks in `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/reader_streaming.rs` and `xtask/src/pdf_deps.rs`; PDF Place and clipboard paste retain live text (synthetic regressions); SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; EPS ordinary Save retains the page frame and editable document (2026-10-26); `.ai`/EPS editing data checked against a user's files (2026-10-30): case setting (`ate::tests`, `tests_native::type_from_the_text_document_keeps_its_case_setting`), placed-file placements (`tests_native::a_small_placed_file_goes_where_it_draws_closer_to_the_page`), pages cropped to the art (`tests_native::type_on_the_copies_of_a_page_cropped_to_the_art_is_read_once`), mesh corner weights and state (`ai::mesh::tests::corners_with_handle_weights_of_zero_are_read`, `ai::tests::a_gradient_mesh_takes_the_transparency_written_after_it`), type on a path spacing (`tests_native::type_round_a_circle_is_spaced_as_the_file_lays_it_out`), blend state (`ai::tests::a_blends_transparency_follows_its_record`); scores and estimates unchanged. PDF ActualText preserved in editable import (#6165; bounded synthetic coverage below); score/hours unchanged. Save refusal continuation (#6146): `READ_ONLY_LOCATION`, Save As on ordinary UI Save only; regression execution pending; score/hours unchanged. Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), discretionary hyphens (`T+`, `T-`) and hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`); score, gaps and hours unchanged. |
|
||||
| View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged); document-tab artwork hover/copy and lossless transfer tested (2026-10-22; score/hours unchanged); cached canvas reprojection preserves scale during resize, rotation and DPI changes (regression and contributor original-file evidence below; scores/hours unchanged) |
|
||||
| View & navigation | 3 | 70% | multiple windows and the rest of Arrange (Cascade, Float in Window, Float All in Windows) | 9–14 | estimated; Window › Arrange › Tile and Consolidate All Windows done (score/hours unchanged) |
|
||||
| Guides, grids, smart guides, snapping, rulers | 3 | 80% | "intersect" smart guides for a moved selection's anchors (drawn points and dragged anchors snap to intersections, #1658) | 4–7 | estimated (lowered from 85%: target moved); Control bar snapping quick access includes Snap to Glyph and Alignment Guides (#6164); new ruler-guide Alt orientation implemented; global/artboard ruler modes (`view.globalRulers`) and video rulers (View › Rulers › Show Video Rulers, #2849) done; status-bar X/Y uses the active ruler origin and General units; score unchanged |
|
||||
@@ -515,7 +515,7 @@ about 1–1.5 agent-hours each, so the other rows (estimated on the older scale)
|
||||
| Layers, artboards, document setup | 5 | 82% | Layers panel: a confirmation before deleting layers that hold art, row menu commands beyond Collect for Export (now on every layer, sublayer, group and object row), menus on guide and blend spine rows, the Layer Options dialog for several rows with mixed values, Paste Remembers Layers for sublayers; artboard preset polish (artboard escape routing and document setup modal handoff done; Move Artwork for artboard X/Y edits, Rearrange All Artboards, Document Setup, New Document and the rest of the Layers panel are done) | 4–7 |
|
||||
| View & navigation | 3 | 70% | New View/Edit Views, multiple windows/arrange, Snap to Pixel/Glyph (print tiling is done) | 9–14 |
|
||||
| Guides, grids, smart guides, snapping, rulers | 3 | 85% | global/video rulers, Spacing Guides' distance readouts and spacing for resized or drawn art, Alt swapping a ruler guide's orientation, ruler guides selected together with art (marquee, Shift-click), ruler guides as Layers rows with their own lock and hide (#451: Lock Guides locks them all; Make Guides paths are Layers rows already) (dragging existing guides is done, #414; new guides snapping to side midpoints and artboards, and artboard guides, #451; the drawing tools snapping, with Construction Guides, #506; Spacing Guides for moves, #394; moves snapping to the grid, #740; ruler guides pulling drawn points with Smart Guides on, and "center" and "anchor" labels while hovering with the Selection tool, #812; distance and angle labels while drawing, #2983) | 2–4; status-bar X/Y uses the active ruler origin and General units |
|
||||
| File formats | 6 | 85% | PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); Explicit editing-data oversized single-artboard import fixed (#6865); scores and estimates unchanged. Affinity export, and the rest of Affinity import (adjustments, blur and bevel effects, brushes, live symbol instances, text threading), DWG (no open spec: DXF instead), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), legacy `.ai` files saved without the prolog that defines their operators (their own operator set isn't read yet), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) |
|
||||
| File formats | 6 | 85% | PDF import: glyphs inside a marked-content span with an empty `ActualText` come in as outlines in their fill and stroke, adding no text (#6971; scores and estimates unchanged); Explicit editing-data oversized single-artboard import fixed (#6865); scores and estimates unchanged. Legacy `.ai` files that name but omit their prolog open with their layers, or with their art on one layer when the format has no layers; graph data and settings in these files still come in only as drawn art. Affinity export, and the rest of Affinity import (adjustments, blur and bevel effects, brushes, live symbol instances, text threading), DWG (no open spec: DXF instead), PSD placement as layers (Photoshop Import Options; the merged image is done), EPS checked against more real files users send (Inkscape files open as vectors; other generators' constructs are tested with programs written from the PostScript Language Reference only; CID-keyed CJK type and `CCITTFaxDecode` images not read), the rest of Illustrator's editing data (appearances and live effects, symbols, pattern fills, brushes, placed files: #637), the remaining fidelity polish; EPS, DXF, EMF/WMF, TIFF, BMP, Targa, PSD export, SVGZ, PDF security, PDF/X, PDF layers, presets and Affinity import are done | 6–10 (existing scope; Affinity export unestimated) |
|
||||
| Export for Screens, Asset Export, slices, Save for Web | 3 | 85% | polish only (all four are done) | 2–4 |
|
||||
| Print, colour management, separations, flattener | 3 | 80% | print preview fidelity (flattener presets in PDF and print, overprint in PDF and composite print, Print dialog, presets, PostScript, marks, separations, Print Tiling, print overprint/flattener/bitmap options and printer profile are done, as are the Japanese papers in its Media list: JIS B4/B5/B6, はがき, 往復はがき, 封筒 長形3号/長形4号/角形2号/角形3号 and 四六判, beside the ISO B4/B5 that settings saved before them keep) | 1–2 |
|
||||
| Automation | 3 | 65% | scripting surface, batch (MCP drops malformed app replies without replay; Variables: text/visibility variables bound to objects, an object may carry several, dataset rows applied in one undo step, panel and Window › Variables with dialogs; image/graph kinds and dataset import/export open) | 6–10 |
|
||||
@@ -711,6 +711,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- **Dragging a document tab out and a document window back (G7):** a document tab dragged more than 24 pt above or below the tab strip floats its document in a window under the pointer, and a document window dragged onto the tab strip goes back under the tabs ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). A window inside the app's window is dragged by its title bar; an OS window by the document's tab at its top, and the window follows the pointer. The 24 pt distance and the tab at the top of an OS window are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`.
|
||||
- **Reordering document tabs (G7, #5663):** a document tab dragged along the tab strip moves its document among the others ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)); a line marks the gap it goes in. The current document stays current, each document keeps its own zoom, centre and artboard, the views Window › New Window opened move with their document, and Window › Next/Previous Document follow the new order. `document.move` (`{from?, to}`) does the same from MCP, the control channel and recordings. `crates/ui-egui/src/tests/tab_reorder.rs`, `crates/engine/src/tests/document_move.rs`.
|
||||
- **Closing a background document tab:** closing a tab other than the current one (`file.close {index}`) keeps the current document current, and its tool keeps its state; closing the current tab still makes its neighbor current. `crates/engine/src/tests/document_close.rs`.
|
||||
- **Replacing a background document's content:** `Session::replace_document` on a tab other than the current one (the replacement File › Revert makes for the current tab) measures the new content's type in that document's own composite fonts at once, so that type has its measured bounds while the document is in the back. When that document becomes the current one unchanged, its type in those fonts is not measured again. `crates/engine/src/cmd/compositefonts/tests.rs`.
|
||||
- **Export and Import Preferences (#6435):** an optional VectorCraft feature. The Preferences dialog's Export Preferences… saves the applied preferences to a JSON file (`prefs.export`; the web build downloads it), and Import Preferences… applies such a file (`prefs.import`). The file leaves out the folder preferences. The import checks every value first and changes nothing on an error; it keeps the open document's units and records no undo step. The file format is VectorCraft's own. Tests: `crates/engine/src/tests/prefs_file.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`.
|
||||
- **Preferences › User Interface › Open Documents As Tabs (G7, #394):** checked by default, documents open under tabs in one document window ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/workspace-overview.html)). With the box cleared, each document opened or created afterwards opens in a floating window of its own, at the next cascade place, as Float in Window floats it; documents already open stay where they are, and checking the box again leaves floating documents in their windows. Tests: `crates/ui-egui/src/doc_windows/tests.rs`.
|
||||
- **Preferences search:** a Search Preferences field above the category list has the keyboard focus when the dialog opens, and Cmd/Ctrl+F gives it back; typing lists the settings it finds, and choosing one shows its category, as the [help page](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/set-app-preferences.html) describes. VectorCraft's own rules: the field matches a setting's label, section or category, ignoring case, in the interface language or in English; the list replaces the categories while the field has text and shows every match, or "No settings found"; the chosen setting's row is highlighted and scrolled into view; Escape in the field with text clears it, and Escape in the empty field closes the dialog. The dialog's `__search` field (`ui.dialog.set`) holds the text. Tests: `crates/ui-egui/src/prefs_dialog/tests.rs`.
|
||||
@@ -815,6 +816,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- `ui.inspect` under `--automation-read-root`: the documents still opening, the recent files, library panels' files and folder preferences (saved, and in an open Preferences dialog) outside the read roots are left out of the reply, a library loaded from outside them shows by its file name in `ui.inspect` and `ui.docking`, and the app's state is not changed. `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_leaves_out_paths_outside_the_read_root`).
|
||||
- Link replies under `--automation-read-root`: `links.list`, `links.check`, `links.info` and `document.open`'s link rows leave out the path, found path and folder of a linked file outside the read roots, and the stored size and date of it in `links.info`; each row keeps its id, file name and status, and the document's links are not changed. `crates/engine/src/tests/linkspanel.rs` (`link_paths_outside_the_read_roots_are_left_out`), `crates/engine/src/tests/placed_document.rs` (`link_info_leaves_out_a_placed_documents_path_outside_the_read_roots`).
|
||||
- Document replies under `--automation-read-root`: `document.inspect` gives `path` as null for a document file outside the read roots, and `document.json` names a linked image or placed file outside them by its file name alone, without its relative path, size or date, brush art included, leaves out a relative path that leads outside them and a stored brush entry that does not read as a brush, names a data set's image value outside them by its file name, and leaves an Export for Screens folder outside them out of `export_settings`; the document is not changed. `crates/engine/src/tests/placed_document.rs` (`document_replies_leave_out_paths_outside_the_read_roots`, `document_json_checks_brush_art_and_relative_paths_against_the_read_roots`).
|
||||
- SVG output under `--automation-read-root`: `document.serialize`, `document.export`, `document.exportSelection`, `document.exportForScreens`, `assets.export`, the SVG and SVGZ saves, `file.exportAs` and the SVG Options dialog's Show Code refuse an SVG or SVGZ of a document that links a JavaScript file outside the read roots, before any file or folder is written, with an error that names no file or folder; a URL, a file inside the roots and a relative path that leads inside them are written as stored, and the person at the keyboard exports every link as stored. `crates/engine/src/tests/interactivity.rs` (`confined_svg_output_refuses_a_linked_javascript_file_outside_the_read_roots`, `svg_output_keeps_linked_javascript_files_a_caller_may_read`), `crates/ui-egui/src/tests/automation.rs` (`control_svg_export_refuses_a_linked_javascript_file_outside_the_read_root`), `crates/ui-egui/src/dialogs/svg_options.rs` (`show_code_leaves_out_a_linked_javascript_file_outside_the_read_roots`).
|
||||
- Linked-file and font-file searches under `--automation-read-root`: `links.findFiles` and `text.findFontFiles` replies, also later polls and stops of a search another client started, leave out the files found, a link's saved path and the folder searched outside the caller's read roots, and a failed search gives its reason without the path; `image.info` gives `link: null` for a linked file outside them; `text.addFontFiles` gives `folder: null` and the copies' file names when the Fonts folder is outside them. `crates/engine/src/tests/linkfiles.rs`, `crates/engine/src/tests/fontfiles.rs`, `crates/engine/tests/font_folder.rs`.
|
||||
- Swatch, brush, symbol and graphic style library lists under `--automation-read-root`: every library stays listed, the paths of library files and the user library folder outside the read roots are `null`, a library loaded from outside them is listed and found as `loaded/<file name>` and keeps that id for the session unless a library loaded later without a file shows that id itself, which moves it to the next free `loaded/<file name> (N)`, and the app's own list is not changed. `crates/engine/src/tests/library_roots.rs`.
|
||||
- Preferences commands under `--automation-read-root`: `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show folder preferences outside the read roots as `null` and leave out an export preset's folder outside them, and the preferences are not changed. `crates/engine/src/tests/prefs_roots.rs`.
|
||||
@@ -999,6 +1001,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Shortcut sets other apps save as text (`.kys`) open in Import Shortcut Set from File › Open, from Edit › Keyboard Shortcuts › Import… in the desktop app, or from a drop on the window. It matches each entry to a tool, command or panel by name and decodes the file's key and modifier codes where VectorCraft's default shortcuts agree on them; the user answers the rest, and Apply fills the Keyboard Shortcuts dialog's working set. The answers are kept with the preferences for the next import (`shortcutSet.read`, `importMatches.*`).
|
||||
- Edit › Keyboard Shortcuts › Export Text… saves the set shown in the dialog as a UTF-8 text file, as the reference app's [Export keyboard shortcuts list as a text document](https://helpx.adobe.com/illustrator/desktop/get-started/preferences-and-settings/export-keyboard-shortcuts-list.html) page describes (`shortcuts.exportText {path?}`). The layout is VectorCraft's own: the set's name, then the Tools and Menu Commands rows in the dialog's order, each with its name, a tab and its shortcuts as the dialog shows them, and nothing after the tab for a row with no shortcut. Tests `shortcut_editor::tests::export_text_*` and `tests::picks::keyboard_shortcuts_export_text_writes_the_working_set_as_text`.
|
||||
- On Windows and Linux the app bar is the window's title bar (its own minimize, maximize and close buttons, drag to move, edges to resize), with the dragon app icon as the brand mark; dialogs and menus size to their content. As on a native menu bar, once one menu is open, moving the pointer onto another title opens that one.
|
||||
- On Linux and the BSDs, when the desktop leaves the window's frame to the app (a Wayland session without server-side decorations, such as GNOME) and the window is not opened through XWayland, the app bar's window buttons follow the `button-layout` key of `org.gnome.desktop.wm.preferences` ([schema](https://gitlab.gnome.org/GNOME/gsettings-desktop-schemas/-/blob/master/schemas/org.gnome.desktop.wm.preferences.gschema.xml.in)): Close alone at the right, all three at the left, or split between the ends, in the listed order with the first one leftmost. When the key cannot be read or names no window button, and for an app frame turned on by `VECTORCRAFT_TITLEBAR=app` or VectorCraft Title Bar on Every Desktop, all three stay at the right. Tests `titlebar::tests::caption_buttons_follow_the_caption_layout`, `tests::the_caption_buttons_follow_the_frame_layout` and `tests::the_start_frame_applies_the_app_title_bar_preference`.
|
||||
- On Linux and the BSDs, Preferences › User Interface › VectorCraft Title Bar on Every Desktop (off by default) uses the app bar as the title bar from the next start in the sessions where the desktop would draw the window's frame (X11, Wayland compositors with server-side decorations such as KDE Plasma, a window opened through XWayland). System Title Bar and `VECTORCRAFT_TITLEBAR` take precedence over it, and `VECTORCRAFT_TITLEBAR` also takes precedence over System Title Bar for the run it is set in. Only the values `app`, `system` and `desktop` take precedence (case-sensitive, surrounding spaces ignored); any other value, such as `unknown`, is ignored and does not override System Title Bar.
|
||||
- Edit › Keyboard Shortcuts lists items of the menu bar and panel menus, as the reference app's [Customize keyboard shortcuts](https://web.archive.org/web/20221205131209id_/https://helpx.adobe.com/illustrator/using/customizing-keyboard-shortcuts.html) page describes for its Menu Commands. A menu command with no default shortcut that needs a value a key press does not give, such as File › Document Setup › Units (`document.setUnits {units}`), is listed only while the user has changed its shortcut. A command stays listed when a menu bar item runs it without a value or when it opens a dialog run without one, as the Variables panel's commands do.
|
||||
- No two rows of Edit › Keyboard Shortcuts have the same English name (VectorCraft's own rule). A command that an item of the menu bar runs is listed under that item's menu path (Window › Swatch Libraries › Other Library…), a command whose id extends another command's id is listed under that command's label (Character Style Options › Reset Panel), and the rows that still share a name show their id after it, except the one row an item of the menu bar runs (File › New… and File › New… (file.new)). The search finds a row by the id it shows, and a message about a shortcut already in use names the other row with its group. Test `shortcut_editor::tests::no_two_entries_have_the_same_name`.
|
||||
@@ -1098,8 +1101,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- **Blend spine Anchor Point tool (#2544):** on a selected blend, dragging a spine corner makes symmetric Smooth handles; the tool displays and picks existing spine handles when switched to, drags one independently or retracts it on click, and clicking a point with handles retracts both. The spine is edited live without moving its key objects. Windows native canvas checks and screenshots reviewed: symmetric and independent handles, corner/retraction, Shift constraints and perpendicular reshaping, tool switching, key preservation, Undo/Redo, save/reopen, hidden handles and overlapping Path/Blend priority (PR #2643). Behaviour reference: [public path-editing documentation](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html).
|
||||
- **Blend steps of brushed strokes:** the steps interpolate the pen pressure, tilt, bearing and rotation recorded with the Paintbrush, so a Calligraphic, Scatter or Art brush that varies with the pen changes gradually from one key to the next. A key without a recording counts as half pressure, half tilt and 0°, as brushes read it, and angles turn the shorter way round. When the blend starts a key's path at another anchor (an open path run from its end, a closed one turned to another start), the key's recordings, width profile and arrowheads turn with the path. Different brushes still switch halfway (VectorCraft's own rule; strokes blend their options, as [Blended objects overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blended-objects-overview.html) describes; `crates/doc/src/blend.rs`, `pen_pressure_tilt_and_angles_interpolate_for_brushes`, `stroke_profiles_turn_with_a_key_path_started_elsewhere`).
|
||||
- **Path editing (#494):** the handles shown are the handles that drag: Direct Selection drags those of a path selected as a whole (as the Pen leaves it), the Anchor Point tool and Pen+Alt no longer grab handles that Show handles when multiple anchors are selected hides, a handle shorter than the tolerance leaves its anchor to be picked, and the anchor tools pick within Selection & Anchor Display › Tolerance. A dragged segment keeps a smooth anchor at either end smooth. With Direct Selection, the Pen, the Curvature and the anchor tools, a path selected as a whole shows all its anchors selected, and the Control bar and the Properties panel offer Convert (corner, smooth) for them too; Remove and Cut wait for anchors direct-selected (#504). A handle drag gathers its snap targets once per drag (it took 21 ms per pointer move on a 20,000-path document, now 1 ms; `vectorcraft-cli perf` measures handle and segment drags on a 5,000-anchor path). Join merges the selected anchor points that lie on one another, as after Average, into one anchor (#1582, fixes #1533), and removes the merged anchors in one pass over the path, so a long run of them no longer moves the anchors after it once per merge (`cmd::path::tests::a_long_run_before_many_other_anchors_merges_in_one_pass`); Object › Path › Average & Join… (`path.averageJoin`, Cmd+Alt+Shift+J, the "Create corner or smooth join" shortcut of [Default keyboard shortcuts](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html)) moves two open path ends to their midpoint and joins them there, a corner or smooth point as its dialog's Points choice asks, in one undo step.
|
||||
- **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command or a graphic style (each given a mark or its series picked with Group Selection), the Eyedropper, Default Fill and Stroke or Swap Fill and Stroke, the paint or stroke weight a stroke weight, gradient or recolor command changes there, and a mark's object opacity and blend mode, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo; a kept gradient takes the same place on each mark's own box. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph, Appearance, Transparency or Graphic Styles controls or the Eyedropper, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again, the paint, weight, opacity and blend mode of a label's topmost visible fill and stroke rows and its object opacity and blend mode included. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485).
|
||||
A series that draws Filled Lines bands keeps no stroke paint or weight: its bands are drawn again with their 0.25 pt black outline.
|
||||
- **Graphs:** Column, Stacked Column, Bar, Stacked Bar, Line, Area, Scatter, Pie and Radar graph tools with Graph Data and Graph Type. A series starts in greyscale; Group Selection's fill and stroke, the paint, weight, opacity and blend mode of a mark's top visible fill or stroke row after an Appearance command or a graphic style (each given a mark or its series picked with Group Selection), the Eyedropper, Default Fill and Stroke or Swap Fill and Stroke, the paint or stroke weight a stroke weight, gradient or recolor command changes there, and a mark's object opacity and blend mode, are kept separately on the graph and reapplied when its data, type or size changes, and through save, open and undo; a kept gradient takes the same place on each mark's own box. A series that draws Filled Lines bands keeps no stroke paint or weight: its bands are drawn again with their 0.25 pt black outline. Graph Type's Override Calculated Values (both `axisMin` and `axisMax`) uses exactly that value-axis range, split into the tick count (5 when automatic). Line graphs take Edge-to-Edge Lines (off by default: the points sit at the centres of their categories; graphs saved before the option keep their edge-to-edge lines), and radar graphs follow Mark Data Points and Connect Data Points. Blank cells (an empty CSV cell or `null`) are values left out, not zeros: columns, bars and stacked segments skip them, lines and scatter lines break around them and the value axis ignores them, while area, pie and radar draw them as 0; a number in straight quotes is a label, and the data window writes it back quoted. Graph types combine: Graph Type on series picked with Group Selection (or `series` indexes) draws them as their own type, with column, stacked column, line and area mixing on the vertical value axis and bar and stacked bar on the horizontal one; stacked columns take one slot of the cluster, lines draw in front of columns and areas behind. The value axis goes on the left, the right or both sides (column, stacked column, line, area and scatter graphs; bar graphs keep theirs along the bottom), and Separate Scales gives the series assigned to the right axis a scale of their own with its own tick values. Each value axis takes tick marks of no, short or full (across the plot) length and a count per division, and a prefix and suffix for its numbers; the category axis takes tick marks too (none by default), at or between its labels. Graph designs: Object › Graph › Design lists the designs with a preview of the selected one, and New Design (the selected art), Rename, Delete Design, Paste Design (a copy back to edit) and Select Unused, and Marker draws the data points and legend swatches of line, scatter and radar series with a design, scaled so its backmost object fills the default marker's square. The Appearance, effect and graphic style commands do not edit a design's art inside a series, which the graph draws again from the design. Graph Data transposes rows and columns and switches a scatter graph's x and y, and a `|` in a category or series label starts a new line. Pie graphs take Legends in Wedges, Position (Even, Ratio sized by area, Stacked on one centre) and Sort (None, All, First). Graph Type takes column and cluster widths up to 1000% (overlapping past 100%) with First Row and First Column in Front (First Row orders each series' categories; across series the series order decides, so series stay one group each for Group Selection), draws filled lines, adds drop shadows behind columns, bars, lines and wedges, and puts the legend in rows across the top. Text formatted with the Character, Paragraph, Appearance, Transparency or Graphic Styles controls or the Eyedropper, on the whole graph or on labels picked with Group Selection, is kept per kind of label (value axis numbers, category labels, legend labels) through the graph being drawn again, the paint, weight, opacity and blend mode of a label's topmost visible fill and stroke rows and its object opacity and blend mode included. Object › Graph › Data opens a worksheet: cells picked with a click and edited above the sheet (Tab moves right, Enter down, the arrows between cells), Import Data from a tab-separated text file, Transpose, Switch x/y, Cell Style (decimals shown, column width), Revert and Apply. `graph.setData` returns and takes the data as CSV with each value written exactly, not rounded to two decimals, so applying the returned CSV changes nothing (#1485).
|
||||
An Eyedropper pick that includes transparency and leaves a mark's top fill or stroke row without paint, or removes that row when the source has no row of that kind, where that row had paint before, also replaces the opacity and blend mode the graph keeps for that kind of row in the series; a row that had no paint before the pick leaves them as they are.
|
||||
What Global Edit gives a mark from another match (in an isolated graph) is kept on the graph the same way, and so is the object opacity, with its blend mode, that Randomize Opacity and Sort Objects change on marks.
|
||||
- **Graph column designs:** Object › Graph › Column (`graph.column`) draws the columns, bars or stacked segments and the legend swatch of the series picked with Group Selection with a graph design: Vertically Scaled stretches it to each column's length, Uniformly Scaled scales it both ways and centers it, Repeating stacks a copy for each Each Design Represents value and chops or scales the last one (For Fractions), and Sliding keeps the part above the design's guide line in proportion and stretches the part below. The dialog lists the designs with a preview; the choice is saved with the graph and follows the design's rename and delete.
|
||||
@@ -1229,6 +1231,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- A 3D effect on one fill or stroke ([the help page](https://helpx.adobe.com/illustrator/using/effects.html)) leaves the object's other fills and strokes drawn with the path's or compound path's fill rule, so an even-odd compound path keeps its holes in them; this holds for Extrude & Bevel, Inflate, Rotate and Revolve, and for the Classic Extrude & Bevel, Rotate and Revolve. Tests: `solids::tests::a_fill_or_stroke_without_the_effect_keeps_the_even_odd_hole`, `revolve::tests::a_fill_without_the_revolve_keeps_the_even_odd_hole`.
|
||||
- With caps and opaque paint, Extrude & Bevel (both kinds) and Inflate draw each side face of the fill's solid before the faces of the same object's strokes that overlap it (strokes on closed paths without dashes, a width profile or a brush, in a solid color or an opaque gradient), so the stroke's walls cover the fill's walls at concave corners instead of showing stripes of the fill. Tests: `solids::tests::a_fills_walls_are_drawn_before_the_stroke_faces_over_them`, `solids::tests::the_draw_order_moves_a_fill_wall_before_the_stroke_faces_it_overlaps`, `solid::tests::facets_tell_the_sides_from_the_ends_and_the_faces_turned_away`.
|
||||
- When the fill and strokes are at full opacity with Normal blending, under a stroke that leaves parts of the fill's edge uncovered (dashed, with a width profile or a brush, on an open subpath, or in a paint that may show through), Extrude & Bevel (both kinds) and Inflate cut each stroke face that passes through a face of the fill's solid, or of another of the shape's strokes, where their depths meet, and draw the faces of the shape's fill and strokes that overlap in the order of their depths where they overlap, instead of by the depths of their centers. Inflate orders a plain stroke the same way, since its fill can rise in front of the stroke. The fill no longer paints over a nearer dash, and a dash's end no longer covers the fill wall in front of it; a fill wall in a gap between dashes stays visible. The same order applies inside a group member's own opacity mask or blending mode, to a gradient with transparent stops under a colored light with graphics on its caps, and to Inflate in gradients under a colored light. Tests: `solids::tests::fill_walls_and_strokes_that_leave_gaps_draw_in_the_order_of_their_depths_where_they_overlap`, `solids::tests::local_order_puts_overlapping_fill_walls_and_stroke_faces_in_depth_order`, `solids::tests::a_stroke_face_through_a_fill_wall_is_cut_where_their_depths_meet`, `solids::tests::a_masked_members_fill_and_stroke_faces_go_in_one_order`, `solids::tests::a_colored_inflate_in_gradients_draws_its_faces_in_one_order`, `solids::tests::a_depth_cycle_keeps_the_cap_last`, `solids::graphics::tests::a_transparent_gradient_with_a_graphic_keeps_the_shared_face_order`.
|
||||
- Under a colored light, an Inflate fill and strokes in solid colors, opaque with Normal blending, also draw their faces in that one order, inside a group member's own opacity mask too, instead of each solid as one composite with the stroke's faces over every fill face. Each face keeps the composite's paint, light ramps and seam width; a lone solid, the solids of an object with a translucent or blended fill or stroke, and such solids holding more than 30,720 faces together (VectorCraft's own limit) are still drawn as one composite each. Tests: `solids::tests::colored_solid_fills_and_strokes_share_face_depth_order`, `solids::tests::a_colored_solid_face_on_its_own_keeps_the_composites_colors`, `solids::tests::colored_solid_inflate_batches_channels_and_clips_once_per_surface`, `solids::tests::colored_solids_past_the_face_limit_draw_as_composites`.
|
||||
- Without a twist, a tapered Extrude & Bevel wall (and each bevel band) is one flat face; only a twist cuts walls into slices, so no seam between slices paints a light tick or a light line on a tapered, untwisted wall (#7019). Test: `solid::tests::a_tapered_wall_is_one_flat_face_and_a_twisted_one_is_sliced`.
|
||||
- Extrude & Bevel, Inflate and Rotate apply to type: it makes a solid of its glyph outlines, painted with its own fills and strokes or, when it has none, its characters' colour (the first run's), and stays type, so editing the text reshapes the solid (#4715).
|
||||
- Extrude & Bevel, Inflate and Rotate (Effect › 3D and Materials): live effects in the `three-d` crate with depth, twist, taper, solid or hollow caps, five original bevel shapes (width, height, repeat, spacing, inside, both sides), Inflate's volume, both sides, twist, taper and cap, Rotate's turned fills and strokes, Position presets, the rotation and light gizmos, SVG/PDF vector output and Expand Appearance; one 3D effect per object; covered by geometry, effect, canvas-versus-export, command and dialog tests ([three-d.md](three-d.md)).
|
||||
@@ -1286,6 +1289,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
The Every-line Composer composes a paragraph whose characters differ in line metrics (type size, font, leading or vertical scale, or an inline graphic taller than the text) in area type of any shape, rows, columns and text wrap included. In a frame that is not a rectangle, or with text wrap, each line it tries is measured where the lines above it put it, across the line's own height, so a taller line gets the room of the narrower part of the frame, or of the span beside a wrap object, that it reaches. Such a paragraph is broken with the Single-line Composer when the frame has no room for all of it or when the search passes VectorCraft's own limits. Behavior reference: [the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/set-hyphenation-and-line-breaks.html).
|
||||
A text wrap object's Offset may be negative as well as positive ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=307)). A negative Offset (to -1000 pt) shrinks the wrap object by that distance, measured from each edge itself and from the edges of its holes, so lines beside it, above it and below it run that far into it, and an object narrower than twice the distance no longer moves text aside. With Invert Wrap, a negative Offset keeps the text that far inside the object. These are VectorCraft's own rules for the shape of the shrunk object. Text Wrap Options, `object.textWrap.make` and `object.textWrap.options` and the MCP `text_wrap` tool take the negative value, and layout uses it (`crates/text/src/layout/region.rs` tests, `cmd::textwrap::tests::text_wrap_options_negative_offset_reflows_and_round_trips`).
|
||||
In area type of a shape other than a rectangle, each line's whole band, ascent to descent, stays inside the frame: where an edge pinches in within the band, the line ends at the narrowest point, and a line runs beside a hole that starts and ends within its band, not across it. In area type of any shape, a line also stays clear of a text wrap object that reaches into any part of its band, and inside an Invert Wrap object over its whole band (`crates/text/src/layout/region.rs` tests).
|
||||
In area type whose frame has several contours, a line runs across an edge two contours share only when their edges lie exactly on one line, so a gap between contours keeps lines from crossing it, even a gap one unit in the last place wide near the edge of the canvas; an edge divided by an anchor exactly on it still lets lines cross (`layout::region::separate_slanted_contours_keep_a_four_ulp_gap_near_canvas_limit`, `shared_slanted_edge_still_joins_near_canvas_limit`, `area_type_sets_no_line_across_a_four_ulp_gap_between_slanted_contours`).
|
||||
With Invert Wrap, the spans a line keeps inside a wrap shape of many parts (a comb of 500 teeth) are found by stepping through the line's spans and the shape's spans once for each piece of the band, so the work grows with the number of spans, not with its square (`crates/text/src/layout/region.rs` tests).
|
||||
The Character panel's Small Caps, Superscript and Subscript buttons and the panel menu's items of the same names turn small caps and the superscript or subscript position on and off for the selected type, or for the text the Type tool has selected (`text.setFormat` or `text.setRangeStyle` `{smallCaps, position}`), in Document Setup's proportions. Turning Superscript on turns Subscript off, and turning Subscript on turns Superscript off. A button or item shows as on when the first selected character (at a caret, the character before it) has its attribute.
|
||||
The Character panel's Anti-aliasing Method dropdown, under Character Rotation, sets how the edges of the selected type objects are drawn as pixels (`text.setFormat {antiAlias}`), for the whole object, with each frame of a thread keeping its own method and graph labels keeping it when the graph is drawn again, on the canvas, in raster exports and when the type is rasterized. VectorCraft defines the methods: Sharp, the default, draws edges as before; None paints a pixel only where the type covers at least half of it; Crisp shows a pixel covered by a share c at `2c - 0.5`, and Strong shows it at `2c`, each kept between 0 and 1. SVG, PDF and EPS export are unchanged. Scores and hours unchanged.
|
||||
@@ -1377,6 +1381,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- **Image Trace, Document Library colors:** with Document Swatches, traced fills and strokes use the displayed colors of process, global, spot and tint swatches without links, so editing a swatch leaves the trace unchanged; swatch-library colors are also unlinked; code-drawn tests in `crates/engine`.
|
||||
- **Image Trace, flattened slivers:** in a Color, Grayscale or Black and White trace with Fills, a traced region whose outline straightens onto one line (a single pixel, or a one-pixel row along an edge, its pieces shared with the regions beside it) is left out instead of becoming a selectable path with no area, which paints nothing. Snap Curves To Lines straightens more outlines, so it leaves out more of these. Without Fills, the region's 1 px stroke draws it, and it is kept. Code-drawn tests in `crates/trace`.
|
||||
- **Image Trace, Auto Color rare colours:** the Automatic palette keeps colours too rare for its area count when they are distinct (Oklab) and drawn as coherent regions, at most six, protected from mixed-colour merging and Noise; code-drawn stem, highlight, low-contrast and scattered-noise tests (see [quality notes](image-trace-quality.md#auto-color-keeps-rare-colours)).
|
||||
- **Image Trace, nearly flat dark grounds:** with a Limited palette of 9 to 16 colors (16 Colors, and Document Library without swatches), by VectorCraft's own rule, a cut whose two sides both have a dark gray mean (Oklab lightness under 0.30, chroma under 0.03) and lie less than 0.03 apart in Oklab has its gain scaled by (distance / 0.03)². A near-black ground with faint noise then traces in one color, and the color it would have taken goes to another cut. Code-drawn tests `a_nearly_flat_dark_ground_keeps_one_color`, `only_a_limited_palette_of_nine_to_sixteen_colors_weighs_alike_sides` and `a_dark_colored_figure_on_a_nearly_flat_dark_ground_keeps_its_color` in `crates/trace`.
|
||||
- **Image Trace, Document Library keeps neutral tones neutral:** each pixel takes the library color nearest in Oklab with differences in hue and chroma counted three times, so a gray or a muted brown traces as a neutral library color instead of a saturated one of similar lightness; a code-drawn test of gray and brown patches with a black, light and blue library in `crates/trace`.
|
||||
- **Image Trace, source image on hold:** while the eye button next to the Image Trace panel's View is held down, the canvas shows the selected Image Trace objects' source image whatever their View, and shows their View again on release, with no change to the document or the undo history.
|
||||
- **Image Trace, large images:** images over 1500 px on a side trace with a warning in the result and the status bar; the anchor limit is 8,000,000 (2,000,000 on the web), measured at about 90 bytes an anchor (see [quality notes](image-trace-quality.md#large-images)).
|
||||
@@ -1621,6 +1626,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
The same holds for the objects of an opacity mask's art, a mask inside another mask's art and a hidden art root included, so a mask whose art has Offset Path opens drawing the image it masks as it did, with the effect live; geometry effects that no art style holds on a mask's art, such as Roughen, are written applied to the art, which opens drawing what it drew (`a_masked_image_with_live_offset_path_round_trips`, `hidden_and_nested_mask_art_keep_live_offset_path` and `a_masks_art_with_an_effect_no_style_holds_is_written_as_it_draws` in `crates/eps/src/ai_editing/tests.rs`).
|
||||
A PDF-compatible `.ai` saved with Include Editing Data for Other Apps writes point type, area type and type on a path as type in its editing copy, and objects next to it keep their own transparency (`crates/eps/src/ai_editing/tests.rs`, `cmd::fileio::tests_pdfedit::type_comes_back_from_the_editing_copy`; [file-format-parity.md](file-format-parity.md) lists what is written as outlines).
|
||||
A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps the document's variables, data sets and the bindings of objects to variables in its editing copy, in the form the variable library reader above reads, so they come back when the file is opened. Bindings to layers, to type written as outlines, to graphs and to linked images written as other objects, data set values of graphs, and variables, data sets, bindings and values past the writer's limits are left out with a warning (#6024; `crates/eps/src/ai_editing/tests.rs` `variables_data_sets_and_bindings_are_read_back`; `crates/eps/src/ai_editing/writer/variables.rs` lists what is left out).
|
||||
A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps each wrap object's Text Wrap Options in its editing copy: the Offset, positive or negative, and Invert Wrap ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/wrap-or-unwrap-text-around-objects.html)), in the form the `.ai` reader reads them (`text_wrap` in `crates/eps/src/import/ai/read/document.rs`), so they come back when the file is opened. An offset past the -1000 to 1000 pt the reader keeps is written as the nearer end of that range. On a large canvas the offset is written at the art's scale and comes back at its size. Art the writer draws for an object, such as a blend's steps or a symbol instance written as its art, has only that object's options, and a clipping path written as its fills and its strokes has its options once (`crates/eps/src/ai_editing/tests.rs` `text_wrap_options_are_written_and_read_back`, `drawn_art_keeps_only_its_objects_text_wrap`, `text_wrap_offsets_on_a_large_canvas_come_back_at_their_size`, `text_wrap_options_of_type_and_envelopes_are_read_back`, `a_clipping_path_written_as_its_paint_keeps_one_text_wrap`).
|
||||
In a `.ai` or EPS opened from its editing data, type has its text object's opacity, blend mode and knockout shape flag, whether it is made from the file's text document or taken from the page, and type made from the text document takes its text object's lock. Where such type has transparency and comes in with other art (the rest of its look, or page type and strokes that go with it), a group of them has it. Where the page draws its type, or the strokes around it, with transparency that is neither its text object's nor its text object's combined with that of the objects around it, the page's type and strokes keep their own instead (`crates/eps/src/import/tests_native.rs`). Where the page draws type of no text object over text objects made from the text document, with their words in any case, that type is theirs as the page draws it and is left out; the page's other type of no text object goes only to text objects whose type the text document can't make, or else is left out with a warning.
|
||||
`.ai` editing-data import restores the document's listed graphic styles in panel order and links objects that use a listed style; unsupported appearances keep their drawn look (`crates/eps/src/import/ai/tests.rs`).
|
||||
A `.ai` or EPS graphic style library, whose editing data holds the styles and their list but no layers, opens with those styles in list order. Other Library… loads another document's graphic styles ([Apply graphic styles](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/apply-graphic-styles.html)) and lists such a library's styles in a library panel. A `.ai` or EPS read as its PDF part or page because its layers can't be used also gets the styles of its list in place of the default ones (`crates/eps/src/import/tests_native.rs`, `cmd::fileio::tests_aiimport::a_graphic_style_library_in_a_ai_file_without_layers_loads_its_styles`).
|
||||
@@ -1630,6 +1636,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
To find those characters, SVG export lays a type object out a second time only when the second layout can differ from the first: point type with Line-end Punctuation Half Width and no Japanese punctuation or letters, the setting new type gets, is laid out once. Exporting 5,000 such objects takes a median of 109.4 ms instead of 171.5 ms on Windows 11, with the same SVG (`crates/svg/src/export/text/tests.rs`).
|
||||
SVG export (live text), legacy `.ai` saves (text objects), DXF export (`TEXT` entities) and the CSS Properties panel write area type that Shrink Text to Fit scales down at the size it draws at, and scale its tracking, kerning, leading and baseline shifts the same way where the format holds them.
|
||||
Legacy `.ai` saves (version 7) write type with rotated characters (Character Rotation, Touch Type turns) as its outlines, with a warning that it is no longer editable text (unless `outlineText` already asks for every type object as outlines): a version 7 text object has no character rotation ([Adobe Illustrator File Format Specification 7.0](https://www.nationalarchives.gov.uk/PRONOM/fmt/423), §15), and the outlines keep each character's rotation, baseline shift and scale (`legacy_ai::tests::type_with_rotated_characters_is_outlines_that_keep_the_rotation`).
|
||||
Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), its discretionary hyphens (`T+`, `T-`) as soft hyphens and its hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` ([file format specification, version 7](https://web.archive.org/web/20050126105313/https://partners.adobe.com/public/developer/en/illustrator/sdk/AI7FileFormat.pdf), §15.4.6.1, §15.4.10.1 and §22.6). A file whose type sets a line breaking value (`TG`) or Japanese layout rules (`Xu`, `Tu`), which VectorCraft doesn't keep, opens with a warning for each (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_line_breaking_and_japanese_layout_rules_are_warned_once`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`).
|
||||
A PDF saved with Illustrator's editing data opens through it as a PDF-compatible `.ai` does, with its layers and groups and with art reaching past its page unclipped; such a PDF holds the data in `AIPDFPrivateData` streams (part of #868). A shape a PDF or `.ai` paints with a gradient (a clip path round a shading) opens as one path filled with the gradient, not a clip group round a rectangle, so Shape Builder, Live Paint and Pathfinder work on its outline (#1304).
|
||||
In a `.ai` opened from its editing data, a text object on a layer that shows and doesn't print stays on that layer, made from the file's text document, even where the page doesn't draw it (`crates/eps/src/import/tests_native.rs`). Such a `.ai` opens without the PDF part's warnings that text was kept as outlines when no outlined glyphs come in, and a warning counts the text objects that hold the page's type next to glyphs the page has only as outlines, which don't come in (`crates/engine/src/cmd/fileio/tests_aiimport.rs`). Where the art of a `.ai` or EPS opened from its editing data differs a little from the file's page, the warning gives the share of the page that differs away from type. When that share is 0.2% or less, the warning names the type and gives the share of the page that differs where the type is; when all the type is made from the text document, the type's share has a warning of its own beside the art's (`crates/eps/src/import/tests_native.rs`).
|
||||
In a `.ai` or EPS opened from its editing data, where a layer's or group's drawn look (an effect can be attached to a group or a layer, [Vector and raster effects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/vector-and-raster-effects.html)) draws a copy of art with type, the import puts the page's type that lies over the copy's other art into the copy's group, instead of giving it to other text objects by painting order. Type beside the copy's art, and every copy's type in a file past the import's text-object limits, still goes by painting order. Without a page, such a copy has no type, and no warning counts it as left out. How the page's type is matched with a copy is VectorCraft's own rule (`crates/eps/src/import/tests_native.rs`).
|
||||
|
||||
+9
-7
@@ -102,7 +102,7 @@ middle.
|
||||
| Volume | 0–100 %. The surface is a membrane under even pressure, held along the outline (and around holes): it rises vertically from the edge and rounds smoothly inside, without creases along the shape's middle. At 50 % a circle becomes a half sphere; 100 % puffs twice as high, 0 % is flat. |
|
||||
| Both sides | The back puffs out too; otherwise it is flat. |
|
||||
|
||||
The surface starts with a grid of 48 cells across the larger side, halved or quartered where it rises steeply near the outline. White-light Inflate retains the existing clipped polygon cells, shading and paint composition. With colored lights, simple cells are triangulated with shared border samples, and lighting interpolates shared membrane normals through ordinary RGB vector gradients, including on a puffed back. Solid fills batch those triangles into three channel groups and one coverage clip for the whole surface. Source gradients retain per-facet vector composition and apply transparent coverage once. Seam widths retain the 0.05 to 0.75 pt bounds, and every facet's seam has round joins ([Seams](#seams)). Shading is automatic, with no additional dialog option.
|
||||
The surface starts with a grid of 48 cells across the larger side, halved or quartered where it rises steeply near the outline. White-light Inflate retains the existing clipped polygon cells, shading and paint composition. With colored lights, simple cells are triangulated with shared border samples, and lighting interpolates shared membrane normals through ordinary RGB vector gradients, including on a puffed back. A solid fill or stroke drawn alone, or drawn whole because a fill or stroke of the object is translucent or blended, batches those triangles into three channel groups and one coverage clip for the whole surface; when its faces share one depth order with another solid's, each triangle has its own clip and channel ramps. Source gradients retain per-facet vector composition and apply transparent coverage once. Seam widths retain the 0.05 to 0.75 pt bounds, and every facet's seam has round joins ([Seams](#seams)). Shading is automatic, with no additional dialog option.
|
||||
|
||||
## Seams
|
||||
|
||||
@@ -115,9 +115,10 @@ How a facet carries its seam depends on the lights and the paint:
|
||||
- Extrude & Bevel, Inflate and Rotate, when no light is colored (one white light or several): a path filled with
|
||||
the facet's shading and stroked with its seam. With a colored light, Extrude & Bevel and Rotate (planar shading)
|
||||
are drawn the same way.
|
||||
- Inflate with a colored light and shading on: a solid-color fill draws each facet's light ramps with its seam in three channel
|
||||
groups clipped to the union of its facets, so no seam reaches past the surface; a gradient fill fills each facet's
|
||||
ramps through a clip of the facet and its seam, outlined with round joins.
|
||||
- Inflate with a colored light and shading on: a solid-color fill or stroke drawn as one composite draws each facet's light ramps with its seam in three channel
|
||||
groups clipped to the union of its facets, so no seam reaches past the surface; a gradient fill, and a solid-color
|
||||
fill or stroke whose faces share one depth order with another solid's, fills each facet's ramps through a clip of
|
||||
the facet and its seam, outlined with round joins.
|
||||
- Extrude & Bevel (Classic), Rotate (Classic) and Revolve (Classic): a path and a seam for every face; gradient and
|
||||
pattern faces seam only the base paint, and the shading and highlight layers cover the face alone. The Wireframe
|
||||
surface draws edges only, with no seam.
|
||||
@@ -128,7 +129,7 @@ How a facet carries its seam depends on the lights and the paint:
|
||||
A facet seen almost edge-on is a sliver, and a seam with mitered joins would reach past the solid as a thorn; a round
|
||||
one reaches no more than half its width past its facet. So where a facet has no neighbor (Rotate's plane, every
|
||||
silhouette corner) its convex corners are drawn rounded by up to 0.375 pt (half the largest seam), except a
|
||||
solid-color Inflate under a colored light, whose clip keeps its corners sharp.
|
||||
solid-color Inflate surface under a colored light drawn as one composite, whose clip keeps its corners sharp.
|
||||
|
||||
## Fills and strokes
|
||||
|
||||
@@ -155,8 +156,9 @@ The rest is our reading:
|
||||
this order, in runs that each carry the mask, and so do its graphics. A member of a 3D group with its own opacity
|
||||
mask or blending mode draws its fill's and strokes' faces in this order inside that mask or blending mode when
|
||||
they are opaque with Normal blending. Otherwise each solid is drawn on its own with its opacity and blending, the
|
||||
lower item's first. With a light that is not white, each solid is also drawn on its own when one of them is a
|
||||
puffed, shaded Inflate surface in a solid color (drawn as one composite).
|
||||
lower item's first. With a light that is not white, a puffed, shaded Inflate surface in a solid color takes its
|
||||
place in this order too, each of its faces drawn with its own light ramps; a lone solid of that kind is still
|
||||
drawn as one composite, and so is each such solid when they hold more than 30,720 faces together.
|
||||
- The solids turn, twist and taper about the center of the bounds of all their shapes, Inflate's grid covers
|
||||
those bounds, and with Perspective one eye sees every solid. A stroke too narrow to hold a point of Inflate's
|
||||
grid stays flat.
|
||||
|
||||
Reference in new issue
Block a user