mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 17:15:56 +00:00
Merge main into feat/weed-box-and-lines
This commit is contained in:
@@ -520,7 +520,7 @@ pub(crate) fn levels(w: usize, h: usize, px: &dyn Fn(usize) -> [u16; 4], setting
|
||||
/// the tolerance plus the softness on, and in proportion between them.
|
||||
fn level(c: [u16; 3], refs: &[[u16; 3]], settings: &Settings) -> u8 {
|
||||
let Settings { tolerance, softness, measure, .. } = *settings;
|
||||
let d = refs.iter().map(|r| apart(c, *r, measure)).fold(f64::INFINITY, f64::min);
|
||||
let d = percent(refs.iter().map(|r| gap(c, *r, measure)).fold(f64::INFINITY, f64::min), measure);
|
||||
if d <= tolerance {
|
||||
0
|
||||
} else if d >= tolerance + softness {
|
||||
@@ -530,16 +530,22 @@ fn level(c: [u16; 3], refs: &[[u16; 3]], settings: &Settings) -> u8 {
|
||||
}
|
||||
}
|
||||
|
||||
/// How far apart `a` and `b` are, as a percentage, measured as `measure` says: the RGB distance of
|
||||
/// the largest one (black to white), or the largest difference on one channel of the channel's range.
|
||||
/// A difference of `k` 8-bit steps on one channel is exactly `k / 255 × 100` with channels.
|
||||
fn apart(a: [u16; 3], b: [u16; 3], measure: Match) -> f64 {
|
||||
/// How far apart `a` and `b` are, measured as `measure` says, before `percent` converts it: the
|
||||
/// squared RGB distance, or the largest difference on one channel.
|
||||
fn gap(a: [u16; 3], b: [u16; 3], measure: Match) -> f64 {
|
||||
match measure {
|
||||
Match::Distance => {
|
||||
let sq: f64 = a.iter().zip(b).map(|(x, y)| (f64::from(*x) - f64::from(y)).powi(2)).sum();
|
||||
sq.sqrt() / (65_535.0 * 3f64.sqrt()) * 100.0
|
||||
}
|
||||
Match::Channels => f64::from(a.iter().zip(b).map(|(x, y)| x.abs_diff(y)).max().unwrap_or(0)) / 65_535.0 * 100.0,
|
||||
Match::Distance => a.iter().zip(b).map(|(x, y)| (f64::from(*x) - f64::from(y)).powi(2)).sum(),
|
||||
Match::Channels => f64::from(a.iter().zip(b).map(|(x, y)| x.abs_diff(y)).max().unwrap_or(0)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A `gap` as a percentage: of the largest RGB distance (black to white) with distance, or of the
|
||||
/// channel's range with channels. A difference of `k` 8-bit steps on one channel is exactly
|
||||
/// `k / 255 × 100` with channels.
|
||||
fn percent(gap: f64, measure: Match) -> f64 {
|
||||
match measure {
|
||||
Match::Distance => gap.sqrt() / (65_535.0 * 3f64.sqrt()) * 100.0,
|
||||
Match::Channels => gap / 65_535.0 * 100.0,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ use super::super::menucmds::whole_or;
|
||||
use super::super::object::choice;
|
||||
use super::super::textedit::{CharChange, text_mut, text_ref, type_ranges};
|
||||
use super::super::typecmd::refresh_bounds;
|
||||
use super::super::typemenu::text_ids;
|
||||
use super::super::typemenu::{bake_dynamic_text, text_ids};
|
||||
use super::super::{CommandSpec, bad, cmd, has_selection, number_or, switch_or, targets};
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
@@ -61,7 +61,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Release Type on a Path…",
|
||||
["Object", "Plug-ins", "Type Tools"],
|
||||
None,
|
||||
"{mode?: \"both\" (point type and the path) | \"path\" (the path only) | \"text\" (point type only) (\"both\"), keepOriginal?: false (true: the type on a path stays and the released objects go just above it), ids?: [id…], id? (instead of ids; neither: the selection)} split each type on a path among the objects (inside groups too) into point type and the path it was set on. The point type holds the same text with the same character and paragraph attributes, on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options (effect, align to path, spacing, flip, brackets) don't apply to point type and are dropped. The path keeps its exact shape (open or closed, anchors and handles, the object's transform) and comes out with no fill and no stroke, in the type's layer and place in the stacking order. Other objects are left alone, and with no type on a path among them nothing changes and no undo step is made. One undo step; the released objects are selected → {ids (released, bottom to top), paths, texts}",
|
||||
"{mode?: \"both\" (point type and the path) | \"path\" (the path only) | \"text\" (point type only) (\"both\"), keepOriginal?: false (true: the type on a path stays and the released objects go just above it), ids?: [id…], id? (instead of ids; neither: the selection)} split each type on a path among the objects (inside groups too) into point type and the path it was set on. The point type holds the same text with the same character and paragraph attributes, on one straight line whose baseline starts where the first character sat on the path; Type on a Path Options (effect, align to path, spacing, flip, brackets) don't apply to point type and are dropped; type with Dynamic Text on (type.dynamicText) comes out with it off, at the sizes it was drawn at. The path keeps its exact shape (open or closed, anchors and handles, the object's transform) and comes out with no fill and no stroke, in the type's layer and place in the stacking order. Other objects are left alone, and with no type on a path among them nothing changes and no undo step is made. One undo step; the released objects are selected → {ids (released, bottom to top), paths, texts}",
|
||||
has_selection,
|
||||
release_path
|
||||
),
|
||||
@@ -230,8 +230,9 @@ fn first_pen(lay: &vectorcraft_text::TextLayout) -> Option<Point> {
|
||||
|
||||
/// `t`, type on a path, as point type on one straight line: the same runs and character and
|
||||
/// paragraph attributes, its baseline starting where its first character sat on the path (in the
|
||||
/// object's own text space, so its transform stays). Type on a Path Options are dropped. None for
|
||||
/// other type, or when it can't be placed.
|
||||
/// object's own text space, so its transform stays). Type on a Path Options are dropped, and
|
||||
/// Dynamic Text is turned off at the sizes it draws the text at. None for other type, or when it
|
||||
/// can't be placed.
|
||||
fn released_text(t: &TextObject) -> Option<TextObject> {
|
||||
let TextKind::OnPath { path, .. } = &t.kind else { return None };
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
@@ -244,6 +245,8 @@ fn released_text(t: &TextObject) -> Option<TextObject> {
|
||||
(p.x.is_finite() && p.y.is_finite()).then_some(p)
|
||||
})?;
|
||||
let mut out = t.clone();
|
||||
// Point type has no brackets to fit: it keeps the sizes the path drew it at.
|
||||
bake_dynamic_text(&mut out);
|
||||
out.kind = TextKind::Point;
|
||||
out.path_effect = Default::default();
|
||||
out.path_align = Default::default();
|
||||
|
||||
@@ -32,8 +32,8 @@ use super::opacitymask::percent;
|
||||
use super::paint::paint_from;
|
||||
use super::{AppearanceAttrs, EyedropperAttrs, FillAttrs, StrokeAttrs};
|
||||
use super::{
|
||||
CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_doc, has_selection, id_param, ids_param, index, leaf_targets,
|
||||
ok, paint_targets, str_param, switch_or, targets,
|
||||
CommandSpec, NodeId, Result, Session, bad, check_numbers, check_switches, cmd, has_doc, has_selection, ids_param, index, leaf_targets,
|
||||
object_param, ok, paint_targets, str_param, switch_or, targets,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
@@ -726,8 +726,8 @@ fn clear(n: &mut Node) {
|
||||
|
||||
fn transfer(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "appearance.transfer";
|
||||
let source = id_param(p, "source").ok_or_else(|| bad(C, "missing `source` id"))?;
|
||||
let target = id_param(p, "target").ok_or_else(|| bad(C, "missing `target` id"))?;
|
||||
let source = object_param(p, "source", C)?.ok_or_else(|| bad(C, "missing `source` id"))?;
|
||||
let target = object_param(p, "target", C)?.ok_or_else(|| bad(C, "missing `target` id"))?;
|
||||
if source == target {
|
||||
return Err(bad(C, "`source` and `target` are the same object"));
|
||||
}
|
||||
@@ -1201,7 +1201,7 @@ fn target_contents(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// Sample enabled attributes with transform-aware character dimensions and atomic validation.
|
||||
fn copy_from(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "appearance.copyFrom";
|
||||
let clicked = id_param(p, "source").ok_or_else(|| bad(C, "missing `source` id"))?;
|
||||
let clicked = object_param(p, "source", C)?.ok_or_else(|| bad(C, "missing `source` id"))?;
|
||||
let (reverse, append) = (switch_or(p, "reverse", false, C)?, switch_or(p, "append", false, C)?);
|
||||
let defaults_only = switch_or(p, "defaultsOnly", false, C)?;
|
||||
if defaults_only && (reverse || append || p.get("ids").is_some()) {
|
||||
@@ -1512,6 +1512,9 @@ impl Picked {
|
||||
stroke_width: st.stroke_width,
|
||||
overprint_fill: st.overprint_fill,
|
||||
overprint_stroke: st.overprint_stroke,
|
||||
// The space before a line's first character belongs to where the character is,
|
||||
// not to how it looks: a sample from one doesn't move the target's (#5111).
|
||||
kerning_before: st.kerning_before,
|
||||
..cs.clone()
|
||||
};
|
||||
}
|
||||
|
||||
@@ -11,7 +11,9 @@ use std::collections::HashSet;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_brush::{self as brush, ArtBrush, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter, Variation};
|
||||
use vectorcraft_brush::{
|
||||
self as brush, ArtBrush, Bristle, BristleShape, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter, Variation,
|
||||
};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, PatternDef, Symbol};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect, SubPath, shapes};
|
||||
@@ -169,6 +171,7 @@ pub struct BuiltinBrushLibrary {
|
||||
pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons },
|
||||
BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs },
|
||||
BuiltinBrushLibrary { id: "bristle-brushes", name: "Bristle Brushes", make: bristle_brushes },
|
||||
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
|
||||
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
|
||||
BuiltinBrushLibrary { id: "game-trails", name: "Game Trails", make: game_trails },
|
||||
@@ -290,6 +293,31 @@ fn calligraphic_nibs() -> BrushLibrary {
|
||||
built("Calligraphic Nibs", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
/// A bristle brush: `shape`, then size (pt), bristle length, density, thickness, paint opacity
|
||||
/// and stiffness (%).
|
||||
fn bristle(name: &str, shape: BristleShape, [size, length, density, thickness, opacity, stiffness]: [f64; 6]) -> Brush {
|
||||
Brush { name: name.into(), kind: BrushKind::Bristle(Bristle { shape, size, length, density, thickness, opacity, stiffness }) }
|
||||
}
|
||||
|
||||
/// Bristle Brushes: one bristle brush for each tip shape, from a fine liner to wide fans for
|
||||
/// blending and texture.
|
||||
fn bristle_brushes() -> BrushLibrary {
|
||||
use BristleShape::*;
|
||||
let brushes = vec![
|
||||
bristle("Fine Liner", RoundPoint, [2.0, 140.0, 30.0, 30.0, 90.0, 75.0]),
|
||||
bristle("Pointed Flat", FlatPoint, [5.0, 120.0, 55.0, 35.0, 80.0, 60.0]),
|
||||
bristle("Stubby Round", RoundBlunt, [8.0, 60.0, 70.0, 50.0, 85.0, 80.0]),
|
||||
bristle("Dry Scrub", FlatBlunt, [10.0, 40.0, 25.0, 60.0, 60.0, 95.0]),
|
||||
bristle("Soft Dome", RoundCurve, [12.0, 160.0, 85.0, 20.0, 45.0, 25.0]),
|
||||
bristle("Filbert", FlatCurve, [9.0, 110.0, 65.0, 40.0, 70.0, 45.0]),
|
||||
bristle("Angled Round", RoundAngle, [7.0, 130.0, 50.0, 35.0, 75.0, 55.0]),
|
||||
bristle("Angled Flat", FlatAngle, [11.0, 100.0, 60.0, 45.0, 80.0, 65.0]),
|
||||
bristle("Fan Blender", RoundFan, [16.0, 220.0, 40.0, 15.0, 35.0, 20.0]),
|
||||
bristle("Grass Fan", FlatFan, [20.0, 260.0, 15.0, 25.0, 65.0, 35.0]),
|
||||
];
|
||||
built("Bristle Brushes", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
fn border(name: &str, side: Node, corner: Option<Node>, fit: PatternFit) -> Brush {
|
||||
let kind = BrushKind::Pattern(PatternBrush { side, outer_corner: corner.clone(), inner_corner: corner, fit, ..Default::default() });
|
||||
Brush { name: name.into(), kind }
|
||||
|
||||
@@ -33,10 +33,10 @@ mod symbols;
|
||||
|
||||
pub(crate) use brushes::{apply_brush, brush_targets, stroke_paint};
|
||||
use brushes::{
|
||||
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_remove,
|
||||
brush_selection_art, brush_set_current, brush_unused, expand_brush,
|
||||
brush_apply, brush_delete, brush_duplicate, brush_freehand, brush_get, brush_list, brush_move, brush_new, brush_options, brush_place_art,
|
||||
brush_remove, brush_replace_art, brush_selection_art, brush_set_current, brush_unused, expand_brush,
|
||||
};
|
||||
pub(crate) use dynamic::{edit_part, part_only, selected_part};
|
||||
pub(crate) use dynamic::{edit_part, fit_parts, part_only, selected_part};
|
||||
use dynamic::{symbol_instance_reset, symbol_instance_select_part, symbol_instance_set_appearance};
|
||||
use symbols::selected_instances;
|
||||
pub(crate) use symbols::{
|
||||
@@ -67,6 +67,24 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
brush_selection_art
|
||||
),
|
||||
cmd!(
|
||||
"brush.placeArt",
|
||||
"Place Brush Art",
|
||||
[],
|
||||
None,
|
||||
"{name, x?, y?} place a copy of the art a scatter, art or pattern brush is made of, centered on (x, y) (default: the center of the first artboard), and select it, as dragging the brush from the Brushes panel onto an empty part of the canvas does; a pattern brush places its tiles left to right (side, outer corner, inner corner, start, end; the ones it has art for) 10 pt apart, each in a group named Side Tile, Outer Corner Tile, Inner Corner Tile, Start Tile or End Tile, with an unpainted rectangle at the back of a tile that has a repeat frame marking that frame; a calligraphic or bristle brush is refused → {id}",
|
||||
has_doc,
|
||||
brush_place_art
|
||||
),
|
||||
cmd!(
|
||||
"brush.replaceArt",
|
||||
"Replace Brush Art",
|
||||
[],
|
||||
None,
|
||||
"{name, ids?|id?, applyToStrokes?: true} make the selected art (several objects become one group, as in brush.new) the art of a scatter, art or pattern brush, keeping its other options, as Alt-dragging (Option-dragging on macOS) art onto the brush in the Brushes panel does; a pattern brush takes a group named for one of its tiles, or a group of such groups (as brush.placeArt places them), tile by tile (of two named for one tile, the frontmost), each with the repeat frame an unpainted rectangle at its back marks (other tiles stay as they are), and other art as its side tile; when strokes use the brush and applyToStrokes is false, the brush and its strokes stay as they were and a copy of the brush with the new art, named `<name> copy`, goes after it and becomes the current brush; otherwise the strokes redraw with the new art; one undo step; refused for a calligraphic or bristle brush, with nothing selected, and for art (or a tile) with no width → {name: the brush that has the new art}",
|
||||
has_doc,
|
||||
brush_replace_art
|
||||
),
|
||||
cmd!(
|
||||
"brush.apply",
|
||||
"Apply Brush",
|
||||
|
||||
@@ -239,7 +239,7 @@ pub(super) fn brush_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
&& v.get(k).is_none()
|
||||
{
|
||||
let art = selection_art(s, p)?.ok_or_else(|| bad(C, format!("{ty} brushes need selected art (or params.{k})")))?;
|
||||
if art.geometric_bounds().is_none_or(|b| b.width() <= 1e-6) {
|
||||
if !has_width(&art, &s.doc()?.doc.symbol_boxes()) {
|
||||
return Err(bad(C, "the selected art has no width"));
|
||||
}
|
||||
v[k] = serde_json::to_value(&art).unwrap_or_default();
|
||||
@@ -249,6 +249,12 @@ pub(super) fn brush_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "name": name }))
|
||||
}
|
||||
|
||||
/// Whether art `n` has width for a brush to be made of, with symbol instances measured by their
|
||||
/// symbols' art in `symbols`.
|
||||
fn has_width(n: &Node, symbols: &vectorcraft_doc::SymbolBoxes) -> bool {
|
||||
n.geometric_bounds_with(symbols).is_some_and(|b| b.width() > 1e-6)
|
||||
}
|
||||
|
||||
/// Refuses `name` for a bristle brush when it has more than [`Bristle::MAX_NAME_CHARS`] characters.
|
||||
fn bristle_name_fits(cmd: &str, name: &str) -> Result<()> {
|
||||
let (count, max) = (name.chars().count(), Bristle::MAX_NAME_CHARS);
|
||||
@@ -367,6 +373,12 @@ fn art_brushes(n: &Node, out: &mut Vec<String>) {
|
||||
pub(super) fn brush_unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let d = &s.doc()?.doc;
|
||||
let lib = brush::library(d);
|
||||
let names = brush_unused_in(d, &lib);
|
||||
Ok(json!({ "names": names }))
|
||||
}
|
||||
|
||||
/// The brushes of `lib` no stroke in `d` paints with, in library order ([`brush_unused`]).
|
||||
fn brush_unused_in(d: &Document, lib: &[Brush]) -> Vec<String> {
|
||||
let mut todo = vec![];
|
||||
let trees = d.layers.iter().chain(d.symbols.iter().map(|s| &s.art)).chain(d.graph_designs.iter().map(|g| &g.art));
|
||||
let patterns = d.patterns.iter().chain(d.pattern_edit.iter().filter_map(|pe| pe.original.as_ref()));
|
||||
@@ -379,8 +391,7 @@ pub(super) fn brush_unused(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
used.insert(name);
|
||||
}
|
||||
}
|
||||
let names: Vec<&str> = lib.iter().map(|b| b.name.as_str()).filter(|n| !used.contains(*n)).collect();
|
||||
Ok(json!({ "names": names }))
|
||||
lib.iter().map(|b| b.name.clone()).filter(|n| !used.contains(n)).collect()
|
||||
}
|
||||
|
||||
pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -483,6 +494,217 @@ pub(super) fn brush_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "name": out }))
|
||||
}
|
||||
|
||||
/// The name `brush.placeArt` gives each pattern brush tile it places, by tile, in the order it
|
||||
/// places them; `brush.replaceArt` reads a group of that name as that tile.
|
||||
const TILE_NAMES: [&str; 5] = ["Side Tile", "Outer Corner Tile", "Inner Corner Tile", "Start Tile", "End Tile"];
|
||||
|
||||
/// The space between the pattern brush tiles `brush.placeArt` places, in points.
|
||||
const TILE_GAP: f64 = 10.0;
|
||||
|
||||
/// The message for a brush that is not made of art.
|
||||
fn no_art(name: &str) -> String {
|
||||
format!("`{name}` has no art (only scatter, art and pattern brushes do)")
|
||||
}
|
||||
|
||||
/// Tile `i` of `p` ([`TILE_NAMES`] order): its art and its repeat frame, when it has art.
|
||||
fn tile(p: &brush::PatternBrush, i: usize) -> Option<(&Node, Option<vectorcraft_geom::Rect>)> {
|
||||
match i {
|
||||
0 => Some((&p.side, p.side_frame)),
|
||||
1 => p.outer_corner.as_ref().map(|n| (n, p.outer_corner_frame)),
|
||||
2 => p.inner_corner.as_ref().map(|n| (n, p.inner_corner_frame)),
|
||||
3 => p.start.as_ref().map(|n| (n, p.start_frame)),
|
||||
_ => p.end.as_ref().map(|n| (n, p.end_frame)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives tile `i` of `p` ([`TILE_NAMES`] order) the art `art` and the repeat frame `frame`. The tile
|
||||
/// no longer comes from a pattern swatch, and a corner draws its own art.
|
||||
fn set_tile(p: &mut brush::PatternBrush, i: usize, art: Node, frame: Option<vectorcraft_geom::Rect>) {
|
||||
match i {
|
||||
0 => (p.side, p.side_frame, p.side_swatch) = (art, frame, None),
|
||||
1 => (p.outer_corner, p.outer_corner_frame, p.outer_corner_swatch, p.outer_source) = (Some(art), frame, None, None),
|
||||
2 => (p.inner_corner, p.inner_corner_frame, p.inner_corner_swatch, p.inner_source) = (Some(art), frame, None, None),
|
||||
3 => (p.start, p.start_frame, p.start_swatch) = (Some(art), frame, None),
|
||||
_ => (p.end, p.end_frame, p.end_swatch) = (Some(art), frame, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The art `brush.placeArt` places for brush `b`, in the brush's own coordinates: a scatter or art
|
||||
/// brush's art, or a pattern brush's tiles in a row, each in a group named for its tile
|
||||
/// ([`TILE_NAMES`]), with an unpainted rectangle at the back of a tile that has a repeat frame
|
||||
/// marking that frame. `None` for a brush that is not made of art. Symbol instances in the art are
|
||||
/// measured by their symbols' art in `symbols`.
|
||||
fn placed_art(b: &Brush, symbols: &vectorcraft_doc::SymbolBoxes) -> Option<Node> {
|
||||
match &b.kind {
|
||||
BrushKind::Scatter(sc) => Some(sc.art.clone()),
|
||||
BrushKind::Art(a) => Some(a.art.clone()),
|
||||
BrushKind::Pattern(pb) => {
|
||||
let mut tiles = vec![];
|
||||
let mut x = 0.0;
|
||||
for (i, tile_name) in TILE_NAMES.iter().enumerate() {
|
||||
let Some((art, frame)) = tile(pb, i) else { continue };
|
||||
let mut children = vec![];
|
||||
if let Some(f) = frame {
|
||||
let marker = Node::path(
|
||||
NodeId(0),
|
||||
vectorcraft_geom::shapes::rectangle(f),
|
||||
vectorcraft_doc::Appearance::basic(Paint::None, Paint::None, 1.0),
|
||||
);
|
||||
children.push(Arc::new(marker));
|
||||
}
|
||||
children.push(Arc::new(art.clone()));
|
||||
let mut g = Node::group(NodeId(0), children);
|
||||
g.name = Some((*tile_name).to_string());
|
||||
let Some(r) = g.geometric_bounds_with(symbols) else { continue };
|
||||
// Each tile sits right of the one before it, centered on the line y = 0.
|
||||
g.transform(vectorcraft_geom::Affine::translate((x - r.x0, -r.center().y)), false);
|
||||
x += r.width() + TILE_GAP;
|
||||
tiles.push(Arc::new(g));
|
||||
}
|
||||
Some(Node::group(NodeId(0), tiles))
|
||||
}
|
||||
BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `brush.placeArt`: a copy of the art brush `name` is made of, centered on (`x`, `y`) (default: the
|
||||
/// center of the first artboard) in the layer new art goes into, and selected, as one undo step.
|
||||
/// Scatter and art brushes place their art; pattern brushes place their tiles ([`placed_art`]).
|
||||
pub(super) fn brush_place_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.placeArt";
|
||||
let name = name_param(p, C)?.to_string();
|
||||
let d = &s.doc()?.doc;
|
||||
let center = d.artboards.first().map(|a| a.rect.center()).unwrap_or(super::Point::ZERO);
|
||||
let at = super::Point::new(super::number_or(p, "x", center.x, C)?, super::number_or(p, "y", center.y, C)?);
|
||||
let b = brush::find(d, &name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?;
|
||||
let symbols = d.symbol_boxes();
|
||||
let mut art = placed_art(&b, &symbols).ok_or_else(|| bad(C, no_art(&name)))?;
|
||||
if let Some(r) = art.geometric_bounds_with(&symbols) {
|
||||
art.transform(vectorcraft_geom::Affine::translate(at - r.center()), false);
|
||||
}
|
||||
let parent = s.doc()?.target_parent()?;
|
||||
let id = s.edit("Place Brush Art", |d, sel| {
|
||||
let art = d.reid(&art);
|
||||
let id = art.id;
|
||||
d.insert(parent, usize::MAX, art)?;
|
||||
sel.set([id]);
|
||||
Ok(id)
|
||||
})?;
|
||||
Ok(json!({ "id": id.0 }))
|
||||
}
|
||||
|
||||
/// The repeat frame an unpainted rectangle at the back of a tile group marks ([`placed_art`]): the
|
||||
/// rectangle's bounds, when `n` is a path of one closed subpath through the four corners of its
|
||||
/// bounds, without curves, whose fills and strokes paint nothing and that has no other appearance.
|
||||
fn frame_marker(n: &Node) -> Option<vectorcraft_geom::Rect> {
|
||||
let NodeKind::Path { path, guide: false, clipping: false, .. } = &n.kind else { return None };
|
||||
let unpainted = n.appearance.effects.is_empty()
|
||||
&& n.appearance.items.iter().all(|i| match i {
|
||||
AppearanceItem::Fill(f) => f.paint.is_none(),
|
||||
AppearanceItem::Stroke(st) => st.paint.is_none(),
|
||||
});
|
||||
let [sp] = path.subpaths.as_slice() else { return None };
|
||||
let r = n.geometric_bounds()?;
|
||||
let corners = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)];
|
||||
let at_corners = sp.anchors.len() == 4
|
||||
&& sp.anchors.iter().all(|a| a.h_in == a.p && a.h_out == a.p)
|
||||
&& corners.iter().all(|c| sp.anchors.iter().any(|a| (a.p.x, a.p.y) == *c));
|
||||
(unpainted && sp.closed && at_corners && r.width() > 1e-9 && r.height() > 1e-9).then_some(r)
|
||||
}
|
||||
|
||||
/// The tiles in `art` for a pattern brush, by tile ([`TILE_NAMES`] order), with their repeat frames:
|
||||
/// a group named for a tile, as `brush.placeArt` places them, is the art of its tile (an unpainted
|
||||
/// rectangle at its back marks the tile's frame, [`frame_marker`], and is left out of the art; a
|
||||
/// group left with one member gives that member), and so is each member of a group whose members
|
||||
/// are all such groups; any other art is the side tile.
|
||||
fn tiles_of(art: Node) -> Vec<(usize, Node, Option<vectorcraft_geom::Rect>)> {
|
||||
let named = |c: &Node| matches!(c.kind, NodeKind::Group { clip: false, .. }) && c.name.as_deref().is_some_and(|n| TILE_NAMES.contains(&n));
|
||||
let tiles = match &art.kind {
|
||||
_ if named(&art) => vec![Arc::new(art)],
|
||||
NodeKind::Group { children, clip: false } if !children.is_empty() && children.iter().all(|c| named(c)) => children.clone(),
|
||||
_ => return vec![(0, art, None)],
|
||||
};
|
||||
let mut out: Vec<(usize, Node, Option<vectorcraft_geom::Rect>)> = vec![];
|
||||
for t in tiles {
|
||||
let Some(i) = t.name.as_deref().and_then(|n| TILE_NAMES.iter().position(|x| *x == n)) else { continue };
|
||||
let mut g = (*t).clone();
|
||||
let mut frame = None;
|
||||
if let NodeKind::Group { children, .. } = &mut g.kind
|
||||
&& let Some(f) = children.first().and_then(|c| frame_marker(c))
|
||||
{
|
||||
frame = Some(f);
|
||||
children.remove(0);
|
||||
}
|
||||
g.name = None;
|
||||
// The group `brush.placeArt` put around the tile's art: the art itself goes back, so a
|
||||
// tile does not gain a group each time it goes out and back.
|
||||
if let NodeKind::Group { children, clip: false } = &g.kind
|
||||
&& let [only] = children.as_slice()
|
||||
&& g == Node::group(g.id, children.clone())
|
||||
{
|
||||
g = (**only).clone();
|
||||
}
|
||||
// A tile named twice: the frontmost one counts.
|
||||
out.retain(|(j, ..)| *j != i);
|
||||
out.push((i, g, frame));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `brush.replaceArt`: the selected art (or `ids`/`id`; several objects become one group, as in
|
||||
/// `brush.new`) becomes the art of scatter, art or pattern brush `name`, keeping its other options,
|
||||
/// as one undo step. A pattern brush takes the tiles `brush.placeArt` places by their names
|
||||
/// ([`tiles_of`]) and other art as its side tile. When strokes use the brush and `applyToStrokes` is
|
||||
/// false, the brush and its strokes stay as they were and a copy of the brush with the new art is
|
||||
/// added after it and becomes the current brush; otherwise the strokes redraw with the new art.
|
||||
pub(super) fn brush_replace_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.replaceArt";
|
||||
let name = name_param(p, C)?.to_string();
|
||||
let apply = super::switch_or(p, "applyToStrokes", true, C)?;
|
||||
let mut lib = brush::library(&s.doc()?.doc);
|
||||
let i = lib.iter().position(|b| b.name == name).ok_or_else(|| bad(C, format!("no brush named `{name}`")))?;
|
||||
if lib[i].art().is_empty() {
|
||||
return Err(bad(C, no_art(&name)));
|
||||
}
|
||||
let art = selection_art(s, p)?.ok_or_else(|| bad(C, "nothing selected"))?;
|
||||
let d = &s.doc()?.doc;
|
||||
let symbols = d.symbol_boxes();
|
||||
let check = |n: &Node| if has_width(n, &symbols) { Ok(()) } else { Err(bad(C, "the selected art has no width")) };
|
||||
let mut b = lib[i].clone();
|
||||
match &mut b.kind {
|
||||
BrushKind::Scatter(sc) => {
|
||||
check(&art)?;
|
||||
sc.art = art;
|
||||
}
|
||||
BrushKind::Art(a) => {
|
||||
check(&art)?;
|
||||
a.art = art;
|
||||
}
|
||||
BrushKind::Pattern(pb) => {
|
||||
for (t, art, frame) in tiles_of(art) {
|
||||
check(&art)?;
|
||||
set_tile(pb, t, art, frame);
|
||||
}
|
||||
}
|
||||
BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => return Err(bad(C, no_art(&name))),
|
||||
}
|
||||
let used = !brush_unused_in(d, &lib).contains(&name);
|
||||
if apply || !used {
|
||||
lib[i] = b;
|
||||
save_library(s, "Replace Brush Art", lib, &[])?;
|
||||
return Ok(json!({ "name": name }));
|
||||
}
|
||||
b.name = brush::unique_name(&lib, &format!("{} copy", name.trim()));
|
||||
let copy = b.name.clone();
|
||||
lib.insert(i + 1, b);
|
||||
s.edit("Replace Brush Art", |d, _| {
|
||||
d.unknown.insert(brush::CURRENT_KEY.into(), json!(copy));
|
||||
brush::store(d, &lib);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "name": copy }))
|
||||
}
|
||||
|
||||
pub(super) fn expand_brush(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?);
|
||||
let ids: Vec<NodeId> = ids.into_iter().filter(|id| s.doc().ok().and_then(|st| st.doc.node(*id)).is_some_and(brush::has_brush)).collect();
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! appearance of objects in the symbol's art and stays linked to the symbol
|
||||
//! (`symbol.instance.setAppearance`, `symbol.instance.reset`). The changes live on the instance
|
||||
//! ([`vectorcraft_doc::symbol_overrides`]); editing the symbol keeps those whose object is still
|
||||
//! there ([`fit_overrides`]).
|
||||
//! there and draws them ([`fit_overrides`]).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -27,7 +27,7 @@ pub(super) fn type_id(dynamic: bool) -> &'static str {
|
||||
}
|
||||
|
||||
/// Fit the appearance changes of instances `ids` to their symbols: an instance of a static (or
|
||||
/// missing) symbol keeps none, an instance of a dynamic one those naming an object of its art.
|
||||
/// missing) symbol keeps none, an instance of a dynamic one those its art still draws ([`fit_parts`]).
|
||||
pub(super) fn fit_overrides(d: &mut Document, ids: &[NodeId]) {
|
||||
for id in ids {
|
||||
let art = match d.node(*id) {
|
||||
@@ -40,7 +40,7 @@ pub(super) fn fit_overrides(d: &mut Document, ids: &[NodeId]) {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
let mut e = n.extras_mut();
|
||||
match art {
|
||||
Some(art) => symbol_overrides::retain_parts(&mut e.symbol_overrides, &art),
|
||||
Some(art) => fit_parts(&mut e.symbol_overrides, &art),
|
||||
None => e.symbol_overrides.clear(),
|
||||
}
|
||||
}
|
||||
@@ -177,17 +177,42 @@ fn check_paint_kinds(p: &Value, art: &Node, path: &[u32], cmd: &str) -> Result<(
|
||||
fn solid_fill_check(p: &Value, art: &Node, path: &[u32], fill: Option<&vectorcraft_color::Paint>, cmd: &str) -> Result<()> {
|
||||
let asked = p.get("fill").is_some_and(|v| !v.is_null());
|
||||
let is_instance = symbol_overrides::part(art, path).is_some_and(|n| matches!(n.kind, NodeKind::SymbolInstance { .. }));
|
||||
let draws_nothing = |f: &vectorcraft_color::Paint| match f {
|
||||
vectorcraft_color::Paint::Gradient(_) => true,
|
||||
vectorcraft_color::Paint::Pattern { .. } => true,
|
||||
vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. } => false,
|
||||
};
|
||||
if asked && is_instance && fill.is_some_and(draws_nothing) {
|
||||
if asked && is_instance && fill.is_some_and(|f| !stains(f)) {
|
||||
return Err(bad(cmd, "fill on a symbol instance must be a solid color or none"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Can a symbol instance's fill be `f`? An instance stains its art with a solid fill only.
|
||||
fn stains(f: &vectorcraft_color::Paint) -> bool {
|
||||
match f {
|
||||
vectorcraft_color::Paint::Gradient(_) => false,
|
||||
vectorcraft_color::Paint::Pattern { .. } => false,
|
||||
vectorcraft_color::Paint::None | vectorcraft_color::Paint::Solid { .. } => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the appearance changes `overrides` that name an object of `art` (a symbol's new art), each
|
||||
/// without a fill or stroke that object does not draw ([`paint_refusal`], [`stains`]); a change
|
||||
/// left with nothing in it is dropped.
|
||||
pub(crate) fn fit_parts(overrides: &mut Vec<SymbolOverride>, art: &Node) {
|
||||
symbol_overrides::retain_parts(overrides, art);
|
||||
for o in overrides.iter_mut() {
|
||||
let Some(n) = symbol_overrides::part(art, &o.path) else { continue };
|
||||
let instance = matches!(n.kind, NodeKind::SymbolInstance { .. });
|
||||
if paint_refusal(n, "fill", FIT).is_some() || (instance && o.fill.as_ref().is_some_and(|f| !stains(f))) {
|
||||
o.fill = None;
|
||||
}
|
||||
if paint_refusal(n, "stroke", FIT).is_some() {
|
||||
o.stroke = None;
|
||||
}
|
||||
}
|
||||
overrides.retain(|o| !o.is_empty());
|
||||
}
|
||||
|
||||
/// The command name [`fit_parts`] gives [`paint_refusal`], whose refusal it does not show.
|
||||
const FIT: &str = "symbol.update";
|
||||
|
||||
/// `fill` or `stroke` of `p` for override `o`: absent leaves it, null clears it, a colour string or
|
||||
/// an object of `paint.setFill`'s paint params sets it.
|
||||
fn paint_change(s: &Session, p: &Value, key: &str, cmd: &str) -> Result<Option<Option<vectorcraft_color::Paint>>> {
|
||||
|
||||
@@ -29,8 +29,8 @@ use super::edit::{outermost, selected_roots};
|
||||
use super::paint::paint_from;
|
||||
use super::pathops::{Beside, shape_node};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_value, f64_or, finite_numbers, has_doc, id_param, named_ids,
|
||||
number_or, point_param, str_param, switch_or,
|
||||
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_value, f64_or, finite_numbers, has_doc, named_ids, number_or,
|
||||
object_param, point_param, str_param, switch_or,
|
||||
};
|
||||
|
||||
mod live_paint;
|
||||
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Live Paint Bucket",
|
||||
[],
|
||||
None,
|
||||
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}",
|
||||
"{group?: id | ids?|id?: [id…] (paths to make live first, as livePaint.make does), point: [x,y], points?: [[x,y]…] (a drag polyline starting at point; 1 to 4096 finite canvas points; fills every crossed face of the same group), continuation?: [[[x,y]…]…] (further path chunks of 1 to 4096 finite canvas points each; each starts at the preceding chunk's last point; requires points), color?|swatch?|gradient?|none? (default: current fill; a color in #rrggbbaa or #rgba is refused), tint?: 0..100, keepModel?: bool (both as paint.setFill)} fill the face containing point, skipping hidden faces → {group, face}",
|
||||
has_doc,
|
||||
lp_fill
|
||||
),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::{
|
||||
Appearance, Arc, Beside, Document, EDGE_NAME, EngineError, FACE_NAME, GapOptions, GapSize, LIVE_PAINT_NAME, Node, NodeId, Paint, PathData, Point,
|
||||
Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, id_param, ids_json,
|
||||
is_live_paint, json, number_or, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, switch_or,
|
||||
Rect, Result, SOURCES_NAME, Selection, Session, SubPath, Value, b, bad, build_children, edge_near, face_at, finite, ids_json, is_live_paint,
|
||||
json, number_or, object_param, paint_from, po, point_param, repaint_from, replace_roots, root_ids, source_nodes, source_shapes, switch_or,
|
||||
};
|
||||
|
||||
/// `options` as stored on a Live Paint group: none for the defaults.
|
||||
@@ -272,9 +272,38 @@ pub(super) fn lp_gap_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "livePaint.fill";
|
||||
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
|
||||
let parse_chunk = |input: &Value, start: Point| -> Result<Vec<Point>> {
|
||||
let values = input
|
||||
.as_array()
|
||||
.filter(|points| !points.is_empty() && points.len() <= b::LP_FILL_CHUNK_POINTS)
|
||||
.ok_or_else(|| bad(C, "each path chunk must contain 1 to 4096 points"))?;
|
||||
let points: Vec<_> = values
|
||||
.iter()
|
||||
.map(|point| {
|
||||
let pair = point.as_array().filter(|pair| pair.len() == 2).ok_or_else(|| bad(C, "points must be [x,y] pairs"))?;
|
||||
let x = pair.first().and_then(Value::as_f64).ok_or_else(|| bad(C, "point x must be a number"))?;
|
||||
let y = pair.get(1).and_then(Value::as_f64).ok_or_else(|| bad(C, "point y must be a number"))?;
|
||||
let point = Point::new(x, y);
|
||||
if !finite(point) {
|
||||
return Err(bad(C, "points must be finite canvas points"));
|
||||
}
|
||||
Ok(point)
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
if points.first() != Some(&start) {
|
||||
return Err(bad(C, "path chunks must share their boundary point"));
|
||||
}
|
||||
Ok(points)
|
||||
};
|
||||
let points = p.get("points");
|
||||
let continuation = match p.get("continuation") {
|
||||
None => &[][..],
|
||||
Some(input) if points.is_some() => input.as_array().ok_or_else(|| bad(C, "continuation must be an array of path chunks"))?.as_slice(),
|
||||
Some(_) => return Err(bad(C, "continuation requires points")),
|
||||
};
|
||||
crate::cmd::paint::check_keep_model(p, C)?;
|
||||
let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.fill.clone());
|
||||
let group = id_param(p, "group");
|
||||
let group = object_param(p, "group", C)?;
|
||||
let roots = if group.is_none() { root_ids(s, p)? } else { vec![] };
|
||||
let (g, face) = s.edit("Live Paint Bucket", |d, sel| {
|
||||
let gid = match group {
|
||||
@@ -302,7 +331,33 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.and_then(|n| b::visible_face_at(n, pt))
|
||||
.map(|f| f.id)
|
||||
.ok_or_else(|| EngineError::Other("no Live Paint face at that point".into()))?;
|
||||
d.node_mut(fid).ok_or(EngineError::NoNode(fid))?.appearance.set_fill(paint.clone());
|
||||
let mut targets = std::collections::BTreeSet::from([fid]);
|
||||
if let Some(points) = points {
|
||||
let n = d.node(gid).ok_or(EngineError::NoNode(gid))?;
|
||||
// Use the existing region-crossing probes, so even a face narrower than the distance
|
||||
// between pointer events is filled. Reversing matches visible_face_at's front first.
|
||||
let faces: Vec<_> = b::faces(n).into_iter().rev().filter(|f| f.visible).collect();
|
||||
let mut face_ids = vec![];
|
||||
let mut regions = vec![];
|
||||
for f in faces {
|
||||
if let Some(path) = f.path_data()
|
||||
&& let Some(bounds) = path.bounds()
|
||||
{
|
||||
face_ids.push(f.id);
|
||||
regions.push((po::Region { path: path.clone(), sources: vec![] }, path.to_bezpath(), bounds));
|
||||
}
|
||||
}
|
||||
let map = b::BuilderMap { regions, ..Default::default() };
|
||||
let mut last = pt;
|
||||
for input in std::iter::once(points).chain(continuation) {
|
||||
let chunk = parse_chunk(input, last)?;
|
||||
last = chunk.last().copied().unwrap_or(last);
|
||||
targets.extend(map.hits_along(&chunk, None).regions.iter().filter_map(|i| face_ids.get(*i).copied()));
|
||||
}
|
||||
}
|
||||
for target in targets {
|
||||
d.node_mut(target).ok_or(EngineError::NoNode(target))?.appearance.set_fill(paint.clone());
|
||||
}
|
||||
Ok((gid, fid))
|
||||
})?;
|
||||
s.remember_paint(&paint);
|
||||
@@ -312,7 +367,7 @@ pub(super) fn lp_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "livePaint.strokeEdge";
|
||||
let pt = point_param(p, "point").filter(|q| finite(*q)).ok_or_else(|| bad(C, "missing point [x,y]"))?;
|
||||
let g = id_param(p, "group").ok_or_else(|| bad(C, "missing group"))?;
|
||||
let g = object_param(p, "group", C)?.ok_or_else(|| bad(C, "missing group"))?;
|
||||
crate::cmd::paint::check_keep_model(p, C)?;
|
||||
let paint = paint_from(s, p)?.unwrap_or_else(|| s.paint.stroke.clone());
|
||||
let width = number_or(p, "width", s.paint.stroke_width.max(0.0), C)?;
|
||||
@@ -335,7 +390,10 @@ pub(super) fn lp_stroke_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
pub(super) fn lp_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let g = id_param(p, "group").or_else(|| id_param(p, "id")).ok_or_else(|| bad("livePaint.info", "missing group"))?;
|
||||
let g = match object_param(p, "group", "livePaint.info")? {
|
||||
Some(g) => g,
|
||||
None => object_param(p, "id", "livePaint.info")?.ok_or_else(|| bad("livePaint.info", "missing group"))?,
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
let n = d.node(g).filter(|n| is_live_paint(n)).ok_or_else(|| bad("livePaint.info", format!("{g} is not a Live Paint group")))?;
|
||||
let faces: Vec<Value> = b::faces(n)
|
||||
|
||||
@@ -783,12 +783,14 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// The paragraph attributes new type gets (the Type tools, `text.create`): aligned to the start of
|
||||
/// each paragraph's direction (left, right for Hebrew and Arabic), Japanese punctuation composed
|
||||
/// with Line-end Punctuation Half Width and Standard burasagari. Imported text keeps its own.
|
||||
/// with Line-end Punctuation Half Width and Standard burasagari, and Korean words kept whole
|
||||
/// (Korean Line Break Anywhere off). Imported text keeps its own.
|
||||
pub(crate) fn new_type_para() -> vectorcraft_doc::ParaStyle {
|
||||
vectorcraft_doc::ParaStyle {
|
||||
justify: vectorcraft_doc::Justify::Auto,
|
||||
mojikumi: vectorcraft_doc::Mojikumi::LineEndHalf,
|
||||
burasagari: vectorcraft_doc::Burasagari::Standard,
|
||||
korean_line_break_anywhere: false,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,8 +15,8 @@ use vectorcraft_tools::distort::{PinSet, arap, collect_points, mesh_for, project
|
||||
|
||||
use super::edit::{duplicate_in, outermost, refuse_symbol_part, selected_roots};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, id_param,
|
||||
matrix_param, named_id, named_ids, number_or, ok, point_indices, point_param, str_param, switch_or, targets,
|
||||
CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, matrix_param,
|
||||
named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
@@ -305,7 +305,7 @@ fn same_points(a: Option<&WidthProfile>, b: Option<&WidthProfile>) -> bool {
|
||||
|
||||
fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "stroke.widthPoint.set";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let t = f64_req(p, "t", C)?.clamp(0.0, 1.0);
|
||||
let (left, right) = (f64_req(p, "left", C)?, f64_req(p, "right", C)?);
|
||||
if !(left.is_finite() && right.is_finite()) || left < 0.0 || right < 0.0 || left.max(right) > 1.0e5 {
|
||||
@@ -362,7 +362,7 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn width_point_copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "stroke.widthPoint.copy";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let t = f64_req(p, "t", C)?.clamp(0.0, 1.0);
|
||||
// When the profile comes out as it was (the copy replaces a side of a discontinuous point that has
|
||||
// its widths already), the document and its undo history stay as they are.
|
||||
@@ -382,7 +382,7 @@ fn width_point_copy(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn width_point_remove(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "stroke.widthPoint.remove";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let indices = match (p.get("indices"), p.get("index")) {
|
||||
(Some(a), _) => point_indices(a),
|
||||
(None, Some(i)) => point_indices(&json!([i])),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Document Info panel data, its categories and the text report (Document Info › Save…, File →
|
||||
//! Package), and Object → Make Pixel Perfect.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet, HashSet};
|
||||
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::Paint;
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Document Info",
|
||||
["Window", "Document Info"],
|
||||
None,
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}",
|
||||
"{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}. An image linked to a file outside the automation read roots has link null, and its Linked Images row names the file alone",
|
||||
has_doc,
|
||||
info
|
||||
),
|
||||
@@ -358,6 +358,16 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut fonts = BTreeSet::new();
|
||||
let mut images: BTreeMap<String, Value> = BTreeMap::new();
|
||||
let mut image_rows: Vec<ImageRow> = vec![];
|
||||
// Whether the request being served may read each linked file (a relative path read from the
|
||||
// document's folder), checked once per file.
|
||||
let mut readable: HashMap<String, bool> = HashMap::new();
|
||||
let link_doc = super::links::LinkBase::of(st).doc;
|
||||
let mut may_read = |stored: &str| {
|
||||
*readable.entry(stored.to_string()).or_insert_with(|| {
|
||||
let resolved = super::fileio::document_path(stored, link_doc).ok();
|
||||
crate::file_access::check_read(resolved.as_deref().unwrap_or(stored)).is_ok()
|
||||
})
|
||||
};
|
||||
let mut patterns = BTreeSet::new();
|
||||
let mut symbols = BTreeSet::new();
|
||||
let mut spot = BTreeSet::new();
|
||||
@@ -411,12 +421,15 @@ fn info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Some("textObjects")
|
||||
}
|
||||
NodeKind::Image(im) => {
|
||||
// A linked file outside a confined request's read roots: `link` is null, and the row
|
||||
// names the file alone.
|
||||
let link = im.link.as_ref().map(|l| (l, may_read(&l.path)));
|
||||
images.insert(
|
||||
im.key.clone(),
|
||||
json!({ "width": im.width, "height": im.height, "linked": im.link.is_some(), "link": im.link.as_ref().map(|l| &l.path) }),
|
||||
json!({ "width": im.width, "height": im.height, "linked": im.link.is_some(), "link": link.and_then(|(l, ok)| ok.then_some(&l.path)) }),
|
||||
);
|
||||
let name = im.link.as_ref().map_or_else(|| n.display_name(), |l| l.name().to_string());
|
||||
image_rows.push((name, im.width, im.height, im.link.as_ref().map(|l| l.path.clone())));
|
||||
image_rows.push((name, im.width, im.height, link.map(|(l, ok)| if ok { l.path.clone() } else { l.name().to_string() })));
|
||||
Some("images")
|
||||
}
|
||||
NodeKind::SymbolInstance { symbol, .. } => {
|
||||
|
||||
@@ -18,8 +18,8 @@ use super::create::{add_look, insert_look};
|
||||
use super::newart::NewArt;
|
||||
use super::pathops::{Beside, remove_each};
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, check_numbers, cmd, f64_or, has_anchors, has_doc, has_selection, id_param, index, number_or, ok, str_param,
|
||||
switch_or,
|
||||
CommandSpec, Result, Session, bad, check_numbers, cmd, f64_or, has_anchors, has_doc, has_selection, index, number_or, object_param, ok,
|
||||
str_param, switch_or,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::common::{MAX_INPUT, path_kind, path_mut, point_entry, usize_opt, usize_req, within_input_bound};
|
||||
use super::{
|
||||
Anchor, BTreeSet, Beside, Color, Document, EngineError, Node, NodeId, NodeKind, Paint, PathData, Point, Result, Selection, Session, Value, Vec2,
|
||||
add_look, bad, check_numbers, f64_or, id_param, json, number_or, ok, po, str_param, switch_or,
|
||||
add_look, bad, check_numbers, f64_or, json, number_or, object_param, ok, po, str_param, switch_or,
|
||||
};
|
||||
|
||||
// ---------- Curvature ----------
|
||||
@@ -41,7 +41,7 @@ enum CurvatureOp {
|
||||
pub(super) fn curvature_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
use vectorcraft_tools::draw2::{EndCurve, curvature_close, curvature_extend, curvature_insert, curvature_move};
|
||||
const C: &str = "path.curvatureEdit";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
check_numbers(p, &["x", "y", "t"], C)?;
|
||||
let at = match (p.get("x").and_then(Value::as_f64), p.get("y").and_then(Value::as_f64)) {
|
||||
@@ -106,7 +106,7 @@ pub(super) fn curvature_edit(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
pub(super) fn remove_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.removeAnchor";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
let ai = usize_req(p, "anchor", C)?;
|
||||
let curvature = switch_or(p, "curvature", false, C)?;
|
||||
@@ -220,7 +220,7 @@ fn remove_anchors_of(
|
||||
|
||||
pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.convertAnchor";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
let ai = usize_req(p, "anchor", C)?;
|
||||
let smooth = str_param(p, "to") == Some("smooth");
|
||||
@@ -257,7 +257,7 @@ pub(super) fn convert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
pub(super) fn reshape_segment(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.reshapeSegment";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
let seg = usize_req(p, "segment", C)?;
|
||||
let t = number_or(p, "t", 0.5, C)?.clamp(0.05, 0.95);
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::common::{
|
||||
};
|
||||
use super::{
|
||||
Anchor, AnchorKind, Beside, BezPath, BoolOp, Cap, EngineError, FillRule, Join, NodeId, ParamCurve, PathData, Point, Result, Session, SubPath,
|
||||
Value, bad, eraser_area, eraser_tip, f64_or, fill_contains, id_param, json, number_or, po,
|
||||
Value, bad, eraser_area, eraser_tip, f64_or, fill_contains, json, number_or, object_param, po,
|
||||
};
|
||||
|
||||
/// Split a filled path into connected pieces (each outer contour with its holes).
|
||||
@@ -170,7 +170,7 @@ pub(in super::super) fn erase_outline(pd: &PathData, step: f64, remove: &dyn Fn(
|
||||
|
||||
pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "path.split";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
let anchor = usize_opt(p, "anchor", C)?;
|
||||
let seg = usize_opt(p, "segment", C)?;
|
||||
|
||||
@@ -4,7 +4,8 @@ use super::common::{
|
||||
};
|
||||
use super::{
|
||||
Anchor, Appearance, BTreeSet, BoolOp, Cap, Color, Document, EngineError, FillRule, Join, NewArt, Node, NodeId, NodeKind, Paint, PathData, Point,
|
||||
Result, Selection, Session, SimplifyOptions, SubPath, Value, bad, id_param, insert_look, json, number_or, po, remove_each, str_param, switch_or,
|
||||
Result, Selection, Session, SimplifyOptions, SubPath, Value, bad, insert_look, json, number_or, object_param, po, remove_each, str_param,
|
||||
switch_or,
|
||||
};
|
||||
|
||||
// ---------- Pencil / Paintbrush ----------
|
||||
@@ -158,7 +159,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let keep_selected = switch_or(p, "keepSelected", true, C)?;
|
||||
let filled = switch_or(p, "fill", false, C)?;
|
||||
if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) {
|
||||
let id = id_param(ext, "id").ok_or_else(|| bad(C, "extend needs id"))?;
|
||||
let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?;
|
||||
let at_start = str_param(ext, "end") == Some("start");
|
||||
let (pd, _) = path_of(&s.doc()?.doc, id)?;
|
||||
let si = pd.subpaths.iter().rposition(|s| !s.closed && !s.anchors.is_empty()).ok_or_else(|| bad(C, "path has no open end"))?;
|
||||
@@ -179,7 +180,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// open subpath, that subpath starting at the end the stroke ends on, it ends at its end).
|
||||
let connect = match p.get("connect").filter(|v| !v.is_null()) {
|
||||
Some(cn) => {
|
||||
let other = id_param(cn, "id").ok_or_else(|| bad(C, "connect needs id"))?;
|
||||
let other = object_param(cn, "id", C)?.ok_or_else(|| bad(C, "connect needs id"))?;
|
||||
if other == id {
|
||||
return Err(bad(C, "connect needs a path other than the one extended"));
|
||||
}
|
||||
@@ -299,7 +300,7 @@ pub(super) fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(json!({ "id": id.0 }));
|
||||
}
|
||||
if let Some(rd) = p.get("redraw").filter(|v| !v.is_null()) {
|
||||
let id = id_param(rd, "id").ok_or_else(|| bad(C, "redraw needs id"))?;
|
||||
let id = object_param(rd, "id", C)?.ok_or_else(|| bad(C, "redraw needs id"))?;
|
||||
let within = number_or(rd, "within", 12.0, C)?;
|
||||
if !within.is_finite() || within < 0.0 {
|
||||
return Err(bad(C, "redraw within must be a finite distance of 0 or more"));
|
||||
|
||||
@@ -10,8 +10,8 @@ use vectorcraft_geom::{Affine, Point, Vec2};
|
||||
use super::clipboard::SwatchChoices;
|
||||
use super::{
|
||||
CommandSpec, Result, Session, always, bad, can_clear_history, can_redo, can_undo, check_numbers, checked_ids_param, clock_date, cmd, date_param,
|
||||
f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, id_param, index,
|
||||
number_or, ok, point_param, str_param, switch_or,
|
||||
f64_req, finite_numbers, has_clipboard, has_doc, has_selection, has_selection_guides_or_artboard_tool, has_selection_or_guides, index, number_or,
|
||||
object_param, ok, point_param, str_param, switch_or,
|
||||
};
|
||||
use crate::{Clipboard, EngineError, inspect};
|
||||
|
||||
@@ -267,7 +267,7 @@ fn doc_move(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn doc_node(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad("document.node", "missing id"))?;
|
||||
let id = object_param(p, "id", "document.node")?.ok_or_else(|| bad("document.node", "missing id"))?;
|
||||
let mut opts = slice_opts(p, "document.node")?;
|
||||
let summary = switch_or(p, "summary", false, "document.node")?;
|
||||
if !summary && (opts.depth.is_some() || opts.child_limit.is_some()) {
|
||||
|
||||
@@ -78,7 +78,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"3D Lighting Preset",
|
||||
[],
|
||||
None,
|
||||
"{index: int, preset: standard|diffuse|topLeft|right, item?: appearance item index|null (omitted: the active item, else the object's), ids?|id?: [..], target?: object|contents, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} replace an applied 3D effect's light rig and ambient with an original lighting preset; preserve shading, geometry and view; all targets must have a 3D effect at index other than Extrude & Bevel (Classic), which has no lighting presets; one undo step → {ids}",
|
||||
"{index: int, preset: standard|diffuse|topLeft|right, item?: appearance item index|null (omitted: the active item, else the object's), ids?|id?: [..], target?: object|contents, aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection)} replace an applied 3D effect's light rig and ambient with an original lighting preset; preserve shading, geometry and view; all targets must have a 3D effect at index other than Extrude & Bevel (Classic), Revolve (Classic) or Rotate (Classic), which have no lighting presets; one undo step → {ids}",
|
||||
has_doc,
|
||||
lighting_preset
|
||||
),
|
||||
@@ -123,7 +123,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Refresh Deferred Effects",
|
||||
["Effect"],
|
||||
None,
|
||||
"{ids?: [object id] (objects of the document; `id` names one; default: every object with a deferred stage)} run the deferred live-effect plug-in stages of those objects again (effect.deferredStatus), sharing a fresh 2,000 ms budget; a stage that gives a result is drawn with it; not an undo step. Enabled when a stage is deferred → {refreshed, stillDeferred (left out for want of time again, or not reached because the object, or a group or layer holding it, is hidden, or with a part of its input too small for the refresh's drawing), failed (timed out, failed or has no plug-in)}",
|
||||
"{ids?|id?: [object id] (objects of the document, also in the art of a symbol, pattern, brush or opacity mask; an object without a deferred stage adds nothing; an id of no object is an error; `id` names one; default: every object with a deferred stage)} run the deferred live-effect plug-in stages of those objects again (effect.deferredStatus), sharing a fresh 2,000 ms budget; a stage that gives a result is drawn with it; not an undo step. Enabled when a stage is deferred → {refreshed, stillDeferred (left out for want of time again, or not reached because the object, or a group or layer holding it, is hidden, or with a part of its input too small for the refresh's drawing), failed (timed out, failed or has no plug-in)}",
|
||||
has_deferred,
|
||||
refresh_deferred
|
||||
),
|
||||
@@ -150,16 +150,27 @@ fn stage_objects(d: &Document, fx: &vectorcraft_plugins::deferred::Deferrals) ->
|
||||
None => rest.push(object),
|
||||
}
|
||||
}
|
||||
if rest.is_empty() {
|
||||
for (id, n) in definition_objects(d, &rest) {
|
||||
out.entry(id).or_insert((n, false));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The objects of `ids` found in the art `d` draws from outside its layers: the art of its
|
||||
/// symbols, patterns and brushes, and opacity masks (in that art or in the layers).
|
||||
fn definition_objects(d: &Document, ids: &[u64]) -> std::collections::HashMap<u64, Arc<Node>> {
|
||||
let mut out = std::collections::HashMap::new();
|
||||
if ids.is_empty() {
|
||||
return out;
|
||||
}
|
||||
let ids: std::collections::HashSet<u64> = ids.iter().copied().collect();
|
||||
let brushes = vectorcraft_brush::library(d);
|
||||
let symbols = d.symbols.iter().map(|s| &*s.art);
|
||||
let patterns = d.patterns.iter().flat_map(|p| p.art.iter().map(|a| &**a));
|
||||
let layers = d.layers.iter().map(|a| &**a);
|
||||
let mut look = |n: &Node| {
|
||||
if rest.contains(&n.id.0) {
|
||||
out.entry(n.id.0).or_insert_with(|| (Arc::new(n.clone()), false));
|
||||
if ids.contains(&n.id.0) {
|
||||
out.entry(n.id.0).or_insert_with(|| Arc::new(n.clone()));
|
||||
}
|
||||
};
|
||||
for a in symbols.chain(patterns).chain(brushes.iter().flat_map(|b| b.art())).chain(layers) {
|
||||
@@ -231,10 +242,19 @@ fn refresh_deferred(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (doc, fx) = (st.doc.clone(), st.plugin_effects.clone());
|
||||
let ids = super::named_ids(p)?;
|
||||
let objects = prune(&doc, &fx);
|
||||
if let Some(id) = ids.iter().flatten().find(|id| doc.node(**id).is_none() && !objects.contains_key(&id.0)) {
|
||||
return Err(EngineError::NoNode(*id));
|
||||
// An object of the art drawn outside the layers is valid whether or not it has a stage.
|
||||
let elsewhere: Vec<u64> = ids.iter().flatten().filter(|id| doc.node(**id).is_none() && !objects.contains_key(&id.0)).map(|id| id.0).collect();
|
||||
let found = definition_objects(&doc, &elsewhere);
|
||||
if let Some(id) = elsewhere.iter().find(|id| !found.contains_key(id)) {
|
||||
return Err(EngineError::NoNode(NodeId(*id)));
|
||||
}
|
||||
let ids: Option<Vec<u64>> = ids.map(|ids| ids.iter().map(|id| id.0).collect());
|
||||
// Only the objects with a stage have anything to refresh.
|
||||
let ids: Option<Vec<u64>> = ids.map(|ids| {
|
||||
let mut ids: Vec<u64> = ids.iter().map(|id| id.0).filter(|id| objects.contains_key(id)).collect();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
ids
|
||||
});
|
||||
let counts = fx.refresh(ids.as_deref(), |targets| {
|
||||
let mut renderer = vectorcraft_render::Renderer::new();
|
||||
let mut whole = Vec::new();
|
||||
@@ -656,12 +676,10 @@ fn lighting_preset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if !effect.is_some_and(|e| effects::is_three_d(&e.id)) {
|
||||
return Err(bad(C, format!("object {} needs a 3D effect at index {index}", id.0)));
|
||||
}
|
||||
// Extrude & Bevel (Classic) has no lighting presets; its lights are set in its own options.
|
||||
if effect.is_some_and(|e| e.id == effects::CLASSIC_EXTRUDE) {
|
||||
return Err(bad(
|
||||
C,
|
||||
format!("object {}: Extrude & Bevel (Classic) at index {index} has no lighting presets; set its lights with effect.setParams", id.0),
|
||||
));
|
||||
// The classic 3D effects have no lighting presets; their lights are set in their own options.
|
||||
if let Some(e) = effect.filter(|e| effects::is_classic_three_d(&e.id)) {
|
||||
let name = effects::effect_info(&e.id).map_or("This effect", |info| info.label.trim_end_matches('…'));
|
||||
return Err(bad(C, format!("object {}: {name} at index {index} has no lighting presets; set its lights with effect.setParams", id.0)));
|
||||
}
|
||||
}
|
||||
let mut options = p.clone();
|
||||
|
||||
@@ -115,3 +115,32 @@ fn lighting_presets_refuse_extrude_and_bevel_classic_and_leave_a_mixed_selection
|
||||
let params = &s.doc().unwrap().doc.node(NodeId(classic)).unwrap().appearance.effects[0].params;
|
||||
assert_eq!((params["lightRotation"].as_f64(), params["lightHeight"].as_f64()), (Some(135.0), Some(45.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lighting_presets_refuse_revolve_classic() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = s.execute("path.create", &json!({"d":"M100 40 L130 60 L130 140 L100 160"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("paint.setFill", &json!({"color":"#3366cc"})).unwrap();
|
||||
s.execute("effect.apply", &json!({"effect":"threeD.classicRevolve","item":null,"params":{"surface":"diffuse"}})).unwrap();
|
||||
s.doc_mut().unwrap().mark_saved();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let err = s.execute("effect.lightingPreset", &json!({"ids":[id],"index":0,"item":null,"preset":"topLeft"})).unwrap_err().to_string();
|
||||
assert!(err.contains(&format!("object {id}: Revolve (Classic) at index 0 has no lighting presets")), "{err}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lighting_presets_refuse_rotate_classic() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = s.execute("shape.rectangle", &json!({"x":100,"y":100,"width":80,"height":60})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("effect.apply", &json!({"effect":"threeD.classicRotate","item":null,"params":{"lightRotation":40}})).unwrap();
|
||||
s.doc_mut().unwrap().mark_saved();
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let err = s.execute("effect.lightingPreset", &json!({"ids":[id],"index":0,"item":null,"preset":"diffuse"})).unwrap_err().to_string();
|
||||
assert!(err.contains(&format!("object {id}: Rotate (Classic) at index 0 has no lighting presets")), "{err}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
assert!(!s.doc().unwrap().is_dirty());
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ use vectorcraft_doc::{NodeId, NodeKind};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
const TYPES: [&str; 5] = ["threeD.extrude", "threeD.classicExtrude", "threeD.inflate", "threeD.rotate", "threeD.revolve"];
|
||||
const TYPES: [&str; 6] = ["threeD.extrude", "threeD.classicExtrude", "threeD.inflate", "threeD.rotate", "threeD.classicRotate", "threeD.revolve"];
|
||||
|
||||
fn id_of(v: &Value) -> NodeId {
|
||||
NodeId(v["id"].as_u64().unwrap())
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! File → File Info (`file.info`): the document title and its descriptive metadata (author,
|
||||
//! description, keywords, rating, copyright), with the read-only created and modified dates. The
|
||||
//! SVG (with `metadata`), PDF and PNG writers carry it, and a PDF or `.ai` opens with the File Info
|
||||
//! it gives ([`read_pdf`]).
|
||||
//! title is the one the file the document was opened from gave itself ([`DocMetadata::title`]),
|
||||
//! else the document's name. The SVG (with `metadata`), PDF and PNG writers carry it, and a PDF or
|
||||
//! `.ai` opens with the File Info it gives ([`read_pdf`]).
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::metadata::{MAX_RATING, iso8601};
|
||||
@@ -22,7 +23,7 @@ const READ_ONLY: [&str; 6] = ["created", "modified", "colorMode", "units", "artb
|
||||
pub(crate) fn info_json(d: &Document) -> Value {
|
||||
let m = &d.metadata;
|
||||
json!({
|
||||
"title": d.title,
|
||||
"title": d.info_title(),
|
||||
"author": m.author,
|
||||
"authorTitle": m.author_title,
|
||||
"description": m.description,
|
||||
@@ -48,14 +49,22 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
_ => return Err(bad(C, "params must be an object")),
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
let (mut title, mut m) = (d.title.clone(), d.metadata.clone());
|
||||
let (mut title, mut m) = (d.info_title().to_string(), d.metadata.clone());
|
||||
for (k, v) in o {
|
||||
apply(&mut title, &mut m, k, v)?;
|
||||
}
|
||||
let d = &s.doc()?.doc;
|
||||
if title != d.title || m != d.metadata {
|
||||
// A title File Info changes becomes the document's own, as it always has (the tab and Save As
|
||||
// offer it where the document has no file), and replaces the one its file gave.
|
||||
let retitled = title != d.info_title();
|
||||
if retitled {
|
||||
m.title = None;
|
||||
}
|
||||
if retitled || m != d.metadata {
|
||||
s.edit("File Info", |d, _| {
|
||||
d.title = title;
|
||||
if retitled {
|
||||
d.title = title;
|
||||
}
|
||||
d.metadata = m;
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -64,8 +73,8 @@ pub(crate) fn file_info(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
/// The File Info a PDF or PDF-compatible `.ai` gives ([`vectorcraft_pdf::file_info`]) into `m`: each
|
||||
/// field that `file.info` would take (a value it refuses is left out), and the created and
|
||||
/// modified dates.
|
||||
/// field that `file.info` would take (a value it refuses is left out), its title ([`imported_title`])
|
||||
/// as the File Info title, and the created and modified dates.
|
||||
pub(crate) fn read_pdf(m: &mut DocMetadata, f: vectorcraft_pdf::FileInfo) {
|
||||
let status = f.copyrighted.map(|c| if c { CopyrightStatus::Copyrighted } else { CopyrightStatus::PublicDomain });
|
||||
let fields = [
|
||||
@@ -83,6 +92,7 @@ pub(crate) fn read_pdf(m: &mut DocMetadata, f: vectorcraft_pdf::FileInfo) {
|
||||
let _ = apply(&mut title, m, k, &v);
|
||||
}
|
||||
}
|
||||
m.title = f.title.as_deref().and_then(imported_title);
|
||||
m.created = f.created.or(m.created);
|
||||
m.modified = f.modified.or(m.modified);
|
||||
}
|
||||
@@ -141,6 +151,18 @@ fn text(k: &str, v: &Value, multiline: bool) -> Result<String> {
|
||||
Ok(s.to_string())
|
||||
}
|
||||
|
||||
/// The File Info title `raw`, read from a file, makes: runs of white space (line breaks too)
|
||||
/// become single spaces, other control characters are dropped, at most [`MAX_TEXT`] characters
|
||||
/// are kept, as `file.info` takes a title. `None` when nothing is left, or when it is the
|
||||
/// Untitled-N name New gives (what a document that never had a title writes to its files).
|
||||
pub(crate) fn imported_title(raw: &str) -> Option<String> {
|
||||
let words: Vec<String> =
|
||||
raw.split_whitespace().map(|w| w.chars().filter(|c| !c.is_control()).collect::<String>()).filter(|w| !w.is_empty()).collect();
|
||||
let title: String = words.join(" ").chars().take(MAX_TEXT).collect();
|
||||
let title = title.trim_end();
|
||||
super::fileio::is_own_title(title).then(|| title.to_string())
|
||||
}
|
||||
|
||||
/// Keywords from a list or a comma- or semicolon-separated string: trimmed, each once (ignoring
|
||||
/// case), empty ones dropped.
|
||||
fn keywords(v: &Value) -> Result<Vec<String>> {
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
//! - `eps`: EPS export options (flattened transparency, previews, the embedded document), `document.exportEps`.
|
||||
//! - `dxfimport`: the DXF options `document.open` and Place read, `document.dxfInfo`.
|
||||
//! - `metafile`: EMF and WMF export, open and place.
|
||||
//! - `hpgl`: HP-GL export options and plots.
|
||||
//! - `importer`: files that importer plug-ins open (`document.open {importer}`, and extensions no
|
||||
//! built-in format reads).
|
||||
//! - `mesh3d`: 3D assets as OBJ, glTF, USDA and USDZ mesh files (`assets.export3D`).
|
||||
@@ -40,6 +41,7 @@ mod load;
|
||||
mod mesh3d;
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, size_note};
|
||||
mod heifread;
|
||||
mod hpgl;
|
||||
mod jp2read;
|
||||
mod metafile;
|
||||
mod naming;
|
||||
@@ -90,9 +92,9 @@ pub use pdfimport::{LoadOptions, page_document};
|
||||
pub(crate) use save::job_for;
|
||||
pub(crate) use save::save as save_document;
|
||||
pub use save::{
|
||||
SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, export_folder, reads_option as save_reads_option,
|
||||
remembered_save_options, save_filters, save_format, save_job, save_plan, save_with, stamp_save_dates, template_filters, templates_dialog_folder,
|
||||
templates_folder,
|
||||
SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, export_folder, leave_out_unreadable_save_paths,
|
||||
reads_option as save_reads_option, remembered_save_options, save_filters, save_format, save_job, save_plan, save_with, stamp_save_dates,
|
||||
template_filters, templates_dialog_folder, templates_folder,
|
||||
};
|
||||
pub(crate) use screens::{
|
||||
PARAM_KEYS as SCREEN_PARAM_KEYS, ROW_KEYS as SCREEN_ROW_KEYS, UNWRITTEN_FORMATS as SCREEN_UNWRITTEN_FORMATS,
|
||||
@@ -124,7 +126,9 @@ pub(crate) use access::list_dir;
|
||||
pub use access::write_file_with;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) use access::{Placed, copy_new, file_metadata};
|
||||
pub(crate) use access::{absolute_path, create_dir, document_path, file_created, file_stamp, read_file, read_file_head, write_file, write_new_file};
|
||||
pub(crate) use access::{
|
||||
absolute_path, create_dir, document_path, file_created, file_stamp, read_file, read_file_head, shown_link, shown_path, write_file, write_new_file,
|
||||
};
|
||||
#[cfg(all(test, windows))]
|
||||
pub(crate) use access::{document_path_on, document_path_with};
|
||||
#[cfg(test)]
|
||||
@@ -139,6 +143,7 @@ pub(crate) use export_names::{
|
||||
artboard_file_names_keeping_dots, default_name, merge, unique_file_names_keeping_dots, with_black_output, write_or_return,
|
||||
};
|
||||
use export_names::{distinct_names_by, write_encoded};
|
||||
pub(crate) use formats::is_own_title;
|
||||
use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, import_name, writable};
|
||||
pub use formats::{
|
||||
DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, builtin_open_filters,
|
||||
|
||||
@@ -42,6 +42,29 @@ pub(crate) fn touched<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
|
||||
(out, seen)
|
||||
}
|
||||
|
||||
/// May a reply to the request being served name `path`, a file or folder the client did not give?
|
||||
/// Always without roots in force; with them, only inside the read roots ([`crate::file_access::check_read`]).
|
||||
pub(crate) fn shown(path: &str) -> bool {
|
||||
crate::file_access::check_read(path).is_ok()
|
||||
}
|
||||
|
||||
/// `path` as a reply to the request being served names it: whole when [`shown`], else its file name,
|
||||
/// after the last `/` or `\` whichever platform wrote it (empty for a path that ends in no name, such
|
||||
/// as `..` or a folder ending in a separator).
|
||||
pub(crate) fn shown_path(path: &str) -> std::borrow::Cow<'_, str> {
|
||||
shown_link(path, None)
|
||||
}
|
||||
|
||||
/// A link's `stored` path as a reply to the request being served names it: whole when the file it
|
||||
/// names (`resolved`, else `stored` itself) is [`shown`], else its file name as [`shown_path`] gives it.
|
||||
pub(crate) fn shown_link<'a>(stored: &'a str, resolved: Option<&str>) -> std::borrow::Cow<'a, str> {
|
||||
if shown(resolved.unwrap_or(stored)) {
|
||||
return std::borrow::Cow::Borrowed(stored);
|
||||
}
|
||||
let name = stored.rsplit(vectorcraft_doc::links::path_separators(stored)).next().unwrap_or_default();
|
||||
std::borrow::Cow::Borrowed(if matches!(name, "." | "..") { "" } else { name })
|
||||
}
|
||||
|
||||
/// `path` checked for writing against the automation roots in force.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn may_write(path: &str) -> Result<()> {
|
||||
|
||||
@@ -536,6 +536,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def
|
||||
| "dxf"
|
||||
| "emf"
|
||||
| "wmf"
|
||||
| "hpgl"
|
||||
| "ai"
|
||||
)
|
||||
};
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Export DXF",
|
||||
[],
|
||||
None,
|
||||
"{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused",
|
||||
"{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; includeImages and includeHatches false, so fills are their outlines and no image files are written; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), includeImages?: true (false: placed images and their files are left out), includeHatches?: true (false: fills are their outlines, without solid hatches), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused",
|
||||
has_doc,
|
||||
export_dxf
|
||||
)]
|
||||
@@ -37,7 +37,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
|
||||
name: "dxfPreset",
|
||||
ty: "string",
|
||||
default: "\"custom\"",
|
||||
description: "custom, or cnc (CNC / CAM: version 2000, mm, 256 colors, editability, type as outlines, PNG images); the options given override it",
|
||||
description: "custom, or cnc (CNC / CAM: version 2000, mm, 256 colors, editability, type as outlines, no images, no fill hatches); the options given override it",
|
||||
},
|
||||
FormatOption { name: "version", ty: "string", default: "\"2018\"", description: "R12, R13, R14, 2000, 2004, 2007, 2010, 2013 or 2018" },
|
||||
FormatOption {
|
||||
@@ -60,6 +60,18 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
|
||||
default: "\"png\"",
|
||||
description: "png or jpeg: the files placed images are written to, next to the drawing",
|
||||
},
|
||||
FormatOption {
|
||||
name: "includeImages",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "placed images are written, linked to their files; false leaves them and their files out",
|
||||
},
|
||||
FormatOption {
|
||||
name: "includeHatches",
|
||||
ty: "boolean",
|
||||
default: "true",
|
||||
description: "filled areas get a solid hatch after their outlines; false writes the outlines alone",
|
||||
},
|
||||
FormatOption {
|
||||
name: "preserve",
|
||||
ty: "string",
|
||||
@@ -133,6 +145,8 @@ struct Params {
|
||||
scale_lineweights: Option<bool>,
|
||||
colors: Option<Value>,
|
||||
raster_format: Option<String>,
|
||||
include_images: Option<bool>,
|
||||
include_hatches: Option<bool>,
|
||||
preserve: Option<String>,
|
||||
alter_paths: Option<bool>,
|
||||
outline_text: Option<bool>,
|
||||
@@ -176,6 +190,8 @@ fn parse(p: &Value) -> Result<(DxfOptions, ArtboardPick)> {
|
||||
scale_lineweights: q.scale_lineweights.unwrap_or(d.scale_lineweights),
|
||||
colors: choice("colors", q.colors.as_ref().map(text), ColorDepth::from_id, d.colors, "8, 16, 256 or true")?,
|
||||
raster: choice("rasterFormat", q.raster_format, RasterFormat::from_id, d.raster, "png or jpeg")?,
|
||||
include_images: q.include_images.unwrap_or(d.include_images),
|
||||
include_hatches: q.include_hatches.unwrap_or(d.include_hatches),
|
||||
preserve: choice("preserve", q.preserve, Preserve::from_id, d.preserve, "appearance or editability")?,
|
||||
alter_paths: q.alter_paths.unwrap_or(d.alter_paths),
|
||||
outline_text: q.outline_text.unwrap_or(d.outline_text),
|
||||
|
||||
@@ -464,7 +464,7 @@ fn encode_all_of(doc: &Document, format: &str, p: &Value) -> Result<Encoded> {
|
||||
}
|
||||
// Formats that draw type: missing fonts come out in the fallback font (PDF and SVG say so
|
||||
// themselves: SVG only when it outlines or embeds fonts).
|
||||
if (f.raster || matches!(f.id, "eps" | "emf" | "wmf"))
|
||||
if (f.raster || matches!(f.id, "eps" | "emf" | "wmf" | "hpgl"))
|
||||
&& let Some(w) = crate::cmd::fonts::substitution_warning(doc)
|
||||
{
|
||||
enc.warnings.push(w);
|
||||
@@ -503,7 +503,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
let doc = &*doc.without_edit_modes();
|
||||
let n = doc.artboards.len();
|
||||
// SVG reads its own `useArtboards` (an SVG option).
|
||||
let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf") { use_artboards(p)? } else { None };
|
||||
let use_artboards = if f.raster || matches!(f.id, "pdf" | "ai" | "dxf" | "emf" | "wmf" | "hpgl") { use_artboards(p)? } else { None };
|
||||
// `rect`: that area of the page, as if it were the only artboard (the document is not changed).
|
||||
if let Some(rect) = page_rect(f, p)? {
|
||||
let mut q = super::export::without_artboards(p);
|
||||
@@ -536,6 +536,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
"eps" => return super::eps::encode(doc, p),
|
||||
"emf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Emf),
|
||||
"wmf" => return super::metafile::encode(doc, p, use_artboards, vectorcraft_metafile::Kind::Wmf),
|
||||
"hpgl" => return super::hpgl::encode(doc, p, use_artboards),
|
||||
"ai" => return super::save::encode_ai(C, f, doc, p),
|
||||
"pdf" => {
|
||||
let (bytes, warnings) = super::pdf::encode(C, doc, p)?;
|
||||
@@ -591,7 +592,7 @@ fn encode_files(doc: &Document, f: &Format, p: &Value) -> Result<Encoded> {
|
||||
let bytes = renderer.export_region(doc, region, format, &settings).map_err(EngineError::Other)?;
|
||||
// File Info as PNG text chunks.
|
||||
let bytes = if matches!(format, RasterFormat::Png | RasterFormat::Png8) {
|
||||
vectorcraft_render::encode::png::with_text(bytes, &doc.metadata.png_text(&doc.title))
|
||||
vectorcraft_render::encode::png::with_text(bytes, &doc.metadata.png_text(doc.info_title()))
|
||||
} else {
|
||||
bytes
|
||||
};
|
||||
|
||||
@@ -48,7 +48,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
|
||||
name: "useArtboards",
|
||||
ty: "boolean",
|
||||
default: "null",
|
||||
description: "true: one file per chosen artboard (default all), <file>_<artboard>.eps, and with two or more a central <file>.eps of the whole document (none when no art shows); absent: the same when artboard, artboards or range names artboards, else one file of the visible art; false: one file of the visible art, even when artboards are named",
|
||||
description: "true: one file per chosen artboard (default all), <file>_<artboard>.eps, and with two or more a central <file>.eps of the whole document (when no art shows, Export writes none and Save writes it on the first artboard); absent: the same when artboard, artboards or range names artboards, else one file of the visible art; false: one file of the visible art, even when artboards are named (Save: the first artboard when no art shows)",
|
||||
},
|
||||
FormatOption { name: "level", ty: "integer", default: "3", description: "PostScript language level, 2 or 3" },
|
||||
FormatOption {
|
||||
@@ -203,10 +203,15 @@ fn expanded(cmd: &str, p: &Value, saved: &[super::super::FlattenerPreset]) -> Re
|
||||
}
|
||||
}
|
||||
|
||||
/// One file to write: its artboard, region and origin.
|
||||
type Page = (Option<usize>, Rect, Point);
|
||||
|
||||
/// The files to write: `(artboard, region, origin)` each — every chosen artboard with its corner
|
||||
/// as the origin, or the visible art's bounds with the first artboard's corner. With two or more
|
||||
/// chosen artboards, a central file of the visible art comes first (none when no art shows).
|
||||
fn pages(doc: &Document, set: &Settings) -> Result<Vec<(Option<usize>, Rect, Point)>> {
|
||||
/// `saving`: Save always writes the file it names, so with no visible art that file's region is
|
||||
/// the first artboard, and the second value is true.
|
||||
fn pages(doc: &Document, set: &Settings, saving: bool) -> Result<(Vec<Page>, bool)> {
|
||||
let n = doc.artboards.len();
|
||||
let named = set.boards.resolve(n).map_err(|e| bad(C, e))?;
|
||||
let boards = match (set.use_artboards, named) {
|
||||
@@ -217,17 +222,25 @@ fn pages(doc: &Document, set: &Settings) -> Result<Vec<(Option<usize>, Rect, Poi
|
||||
};
|
||||
let corner = |r: Rect| Point::new(r.x0, r.y1);
|
||||
let art = |art: Rect| (None, art, doc.artboards.first().map_or(corner(art), |a| corner(a.rect)));
|
||||
// The visible art's bounds; for Save with no visible art, the first artboard (true).
|
||||
let visible = || match vectorcraft_render::encode::art_bounds(doc) {
|
||||
Some(bounds) => Some((bounds, false)),
|
||||
None if saving => doc.artboards.first().map(|a| (a.rect, true)),
|
||||
None => None,
|
||||
};
|
||||
match boards {
|
||||
Some(boards) => {
|
||||
let central = (boards.len() > 1).then(|| vectorcraft_render::encode::art_bounds(doc).map(art)).flatten();
|
||||
let central = (boards.len() > 1).then(visible).flatten();
|
||||
let each = boards
|
||||
.into_iter()
|
||||
.map(|b| doc.artboards.get(b).map(|a| (Some(b), a.rect, corner(a.rect))).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))));
|
||||
central.map(Ok).into_iter().chain(each).collect()
|
||||
let pages = central.map(|(bounds, _)| Ok(art(bounds))).into_iter().chain(each).collect::<Result<_>>()?;
|
||||
Ok((pages, central.is_some_and(|(_, blank)| blank)))
|
||||
}
|
||||
None => {
|
||||
let bounds = vectorcraft_render::encode::art_bounds(doc).ok_or_else(|| bad(C, "nothing to export: the document has no visible art"))?;
|
||||
Ok(vec![art(bounds)])
|
||||
let missing = if saving { "the document has no artboard" } else { "nothing to export: the document has no visible art" };
|
||||
let (bounds, blank) = visible().ok_or_else(|| bad(C, missing))?;
|
||||
Ok((vec![art(bounds)], blank))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -293,16 +306,17 @@ pub(super) fn encode(doc: &Document, p: &Value) -> Result<Encoded> {
|
||||
encode_document(doc, p, false)
|
||||
}
|
||||
|
||||
/// Save keeps a single page's original frame and all native editing data, unlike Export's
|
||||
/// optional art-bound crop or separate file per artboard. Existing EPS loss warnings still apply.
|
||||
/// Save writes the pages Export does (the visible art's bounds, or with Use Artboards the chosen
|
||||
/// artboards), with a smaller preview. A single file, the one the document becomes, carries all
|
||||
/// the native editing data; with no visible art its page is the first artboard.
|
||||
pub(super) fn encode_save(doc: &Document, p: &Value) -> Result<Encoded> {
|
||||
encode_document(doc, p, true)
|
||||
}
|
||||
|
||||
fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> {
|
||||
let set = parse(p)?;
|
||||
if saving && (set.use_artboards == Some(false) || bool_or(p, "selectedOnly", false)) {
|
||||
return Err(bad(C, "EPS Save retains the artboard and all artwork: use document.export for cropped or selected-only EPS"));
|
||||
if saving && bool_or(p, "selectedOnly", false) {
|
||||
return Err(bad(C, "EPS Save writes all artwork: use document.export for selected-only EPS"));
|
||||
}
|
||||
let original = doc;
|
||||
let (full, warnings) = crate::cmd::place::document::full_documents(doc);
|
||||
@@ -315,18 +329,16 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> {
|
||||
} else {
|
||||
Cow::Borrowed(original)
|
||||
};
|
||||
let pages = if saving {
|
||||
let board = set.boards.one(doc.artboards.len()).map_err(|e| bad(C, e))?;
|
||||
let rect = doc.artboards.get(board).ok_or_else(|| bad(C, "the document has no artboard"))?.rect;
|
||||
vec![(Some(board), rect, Point::new(rect.x0, rect.y1))]
|
||||
} else {
|
||||
pages(doc, &set)?
|
||||
};
|
||||
let (pages, blank) = pages(doc, &set, saving)?;
|
||||
if pages.is_empty() {
|
||||
return Err(bad(C, "the document has no artboard"));
|
||||
}
|
||||
// The artboards' background colors, behind the art (the editing data keeps them as colors).
|
||||
let filled = super::export::with_artboard_fills(doc, p, pages.iter().filter_map(|(b, ..)| *b)).map_err(|e| bad(C, e))?;
|
||||
// The file Save writes alone becomes the document's own, so it carries every artboard.
|
||||
let whole = saving && pages.len() == 1;
|
||||
// The artboards' background colors, behind the art (the editing data keeps them as colors);
|
||||
// a page on the first artboard because no art shows has that artboard's color.
|
||||
let fills = pages.iter().filter_map(|(b, ..)| *b).chain(blank.then_some(0));
|
||||
let filled = super::export::with_artboard_fills(doc, p, fills).map_err(|e| bad(C, e))?;
|
||||
let doc = &*filled;
|
||||
let regions: Vec<Rect> = pages.iter().map(|(_, region, _)| *region).collect();
|
||||
let expanded = expand_transparent_tile_images(doc, &set.flatten)?;
|
||||
@@ -358,9 +370,9 @@ fn encode_document(doc: &Document, p: &Value, saving: bool) -> Result<Encoded> {
|
||||
let o = EpsOptions {
|
||||
region,
|
||||
origin,
|
||||
title: doc.title.clone(),
|
||||
title: doc.info_title().to_owned(),
|
||||
created,
|
||||
native: Some(native(&editing, if saving { None } else { board }, set.include_linked)),
|
||||
native: Some(native(&editing, if whole { None } else { board }, set.include_linked)),
|
||||
..set.eps.clone()
|
||||
};
|
||||
let out = vectorcraft_eps::export(drawn, &o, preview.as_ref(), thumbnail.as_ref()).map_err(|e| bad(C, e))?;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::super::unique_name;
|
||||
use super::{
|
||||
Result, Session, TEMPLATE_FORMATS, UNSUPPORTED, Unsupported, Value, bad, dxf, eps, json, metafile, native, pdf, screens, svg, text, unsupported,
|
||||
Result, Session, TEMPLATE_FORMATS, UNSUPPORTED, Unsupported, Value, bad, dxf, eps, hpgl, json, metafile, native, pdf, screens, svg, text,
|
||||
unsupported,
|
||||
};
|
||||
|
||||
/// One option a format's encoder reads from the export params.
|
||||
@@ -479,8 +480,17 @@ pub const FORMATS: &[Format] = &[
|
||||
},
|
||||
Format { id: "emf", label: "EMF", extensions: &["emf"], mime: "image/emf", read: true, write: true, raster: false, options: metafile::OPTIONS },
|
||||
Format { id: "wmf", label: "WMF", extensions: &["wmf"], mime: "image/wmf", read: true, write: true, raster: false, options: metafile::OPTIONS },
|
||||
// HP-GL/2 plot files, read by `vectorcraft_cad::hpgl` into paths; exports don't write them.
|
||||
reader("hpgl", "HP-GL", &["plt", "hpgl", "hgl", "hpg"], "application/vnd.hp-hpgl", false),
|
||||
// HP-GL/2 plot files, read by `vectorcraft_cad::hpgl` into paths and written as pen moves.
|
||||
Format {
|
||||
id: "hpgl",
|
||||
label: "HP-GL",
|
||||
extensions: &["plt", "hpgl", "hgl", "hpg"],
|
||||
mime: "application/vnd.hp-hpgl",
|
||||
read: true,
|
||||
write: true,
|
||||
raster: false,
|
||||
options: hpgl::OPTIONS,
|
||||
},
|
||||
Format {
|
||||
id: "tga",
|
||||
label: "Targa",
|
||||
@@ -920,13 +930,20 @@ pub(crate) fn import_name(base: &str, taken: impl Fn(&str) -> bool) -> String {
|
||||
/// (the title PDF, PNG and SVG metadata carry). A title of its own stays, and native files keep
|
||||
/// the stored title.
|
||||
pub fn has_own_title(doc: &vectorcraft_doc::Document) -> bool {
|
||||
!doc.title.trim().is_empty() && !doc.title.strip_prefix("Untitled-").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
|
||||
is_own_title(doc.info_title())
|
||||
}
|
||||
|
||||
/// Is `title` one a person or a file gave, not blank and not the Untitled-N name New gives?
|
||||
pub(crate) fn is_own_title(title: &str) -> bool {
|
||||
!title.trim().is_empty() && !title.strip_prefix("Untitled-").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
|
||||
}
|
||||
|
||||
pub fn titled_for_export(doc: &vectorcraft_doc::Document, path: Option<&str>, format: &str) -> Option<vectorcraft_doc::Document> {
|
||||
let path = path.filter(|_| !has_own_title(doc) && !matches!(format, "vectorcraft" | "template" | "ai"))?;
|
||||
let mut d = doc.clone();
|
||||
d.title = file_stem(path);
|
||||
// A File Info title that is no title of its own (blank, or an Untitled-N name) would hide it.
|
||||
d.metadata.title = None;
|
||||
Some(d)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//! HP-GL for every path that writes plot files (`vectorcraft_cad::hpgl`): `document.export {format:
|
||||
//! hpgl}` and Export As (one plot of an artboard, or one per artboard with Use Artboards), with the
|
||||
//! options parsed from the params.
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_cad::hpgl::write::{DEFAULT_TOLERANCE, MAX_PENS, TOLERANCE_RANGE};
|
||||
use vectorcraft_cad::hpgl::{HpglOptions, Origin, Version};
|
||||
use vectorcraft_doc::Document;
|
||||
|
||||
use super::super::{Result, bad, number_or, switch_or, text_param};
|
||||
use super::{ArtboardPick, Encoded, FormatOption};
|
||||
|
||||
const C: &str = "document.export";
|
||||
|
||||
/// The options `document.formats` lists for HP-GL.
|
||||
pub(super) const OPTIONS: &[FormatOption] = &[
|
||||
super::ARTBOARD,
|
||||
super::ARTBOARDS,
|
||||
super::RANGE,
|
||||
super::USE_ARTBOARDS,
|
||||
FormatOption {
|
||||
name: "hpglVersion",
|
||||
ty: "string",
|
||||
default: "\"hpgl\"",
|
||||
description: "hpgl (IN, SP, PU and PD only; a coordinate outside -32,768 to 32,767 gets a warning) or hpgl2 (also the pens' colors, NP and PC, and each pen's paths as one encoded polyline, PE)",
|
||||
},
|
||||
FormatOption {
|
||||
name: "curveTolerance",
|
||||
ty: "number",
|
||||
default: "0.1",
|
||||
description: "how far the straight moves a curve becomes may lie from it, in points (0.01 to 10)",
|
||||
},
|
||||
FormatOption {
|
||||
name: "pens",
|
||||
ty: "array",
|
||||
default: "null",
|
||||
description: "the pen table, pen 1's color first: up to 255 \"#rrggbb\" colors, each path drawn with the pen of the nearest color; null: a pen for each color in the order the art first draws in it, numbered alike in every file of one export",
|
||||
},
|
||||
FormatOption {
|
||||
name: "origin",
|
||||
ty: "string",
|
||||
default: "\"bottomLeft\"",
|
||||
description: "bottomLeft or center: where (0, 0) lies on the artboard (or the art's bounds)",
|
||||
},
|
||||
FormatOption {
|
||||
name: "sortPaths",
|
||||
ty: "boolean",
|
||||
default: "false",
|
||||
description: "draw each pen's next path from the end nearest where the pen stopped, instead of in paint order",
|
||||
},
|
||||
FormatOption {
|
||||
name: "insideFirst",
|
||||
ty: "boolean",
|
||||
default: "false",
|
||||
description: "draw a path only after the pen's paths that lie inside it (a letter's counter before the letter, a hole before the part), the paths otherwise in paint order; with sortPaths, the nearest of the paths free to draw comes next",
|
||||
},
|
||||
];
|
||||
|
||||
/// The HP-GL options in `p` (the region is set per plot).
|
||||
fn parse(p: &Value) -> Result<HpglOptions> {
|
||||
let mut o = HpglOptions::default();
|
||||
if let Some(s) = text_param(p, "hpglVersion", C)? {
|
||||
let key = "hpglVersion";
|
||||
o.version = Version::from_id(s).ok_or_else(|| bad(C, format!("`{key}` must be one of {}", Version::ALL.map(Version::id).join(", "))))?;
|
||||
}
|
||||
let x = number_or(p, "curveTolerance", DEFAULT_TOLERANCE, C)?;
|
||||
if !TOLERANCE_RANGE.contains(&x) {
|
||||
let (key, min, max) = ("curveTolerance", TOLERANCE_RANGE.start(), TOLERANCE_RANGE.end());
|
||||
return Err(bad(C, format!("`{key}` must be between {min} and {max} (got {x})")));
|
||||
}
|
||||
o.tolerance = x;
|
||||
match p.get("pens") {
|
||||
None | Some(Value::Null) => {}
|
||||
Some(v) => {
|
||||
let colors: Option<Vec<[u8; 3]>> = v.as_array().filter(|a| (1..=MAX_PENS).contains(&a.len())).and_then(|a| a.iter().map(hex).collect());
|
||||
o.pens = colors.ok_or_else(|| bad(C, "`pens` must be an array of 1 to 255 #rrggbb colors"))?;
|
||||
}
|
||||
}
|
||||
if let Some(s) = text_param(p, "origin", C)? {
|
||||
let key = "origin";
|
||||
o.origin = Origin::from_id(s).ok_or_else(|| bad(C, format!("`{key}` must be one of {}", Origin::ALL.map(Origin::id).join(", "))))?;
|
||||
}
|
||||
o.sort = switch_or(p, "sortPaths", false, C)?;
|
||||
o.inside_first = switch_or(p, "insideFirst", false, C)?;
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
/// A `#rrggbb` color.
|
||||
fn hex(v: &Value) -> Option<[u8; 3]> {
|
||||
let s = v.as_str()?.strip_prefix('#').filter(|s| s.len() == 6 && s.bytes().all(|b| b.is_ascii_hexdigit()))?;
|
||||
let byte = |i: usize| s.get(i..i + 2).and_then(|h| u8::from_str_radix(h, 16).ok());
|
||||
Some([byte(0)?, byte(2)?, byte(4)?])
|
||||
}
|
||||
|
||||
/// Encode `doc` as HP-GL: a plot of the chosen artboard (default the first), or with
|
||||
/// `use_artboards` one plot per chosen artboard (default all), with one pen numbering for them all.
|
||||
pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) -> Result<Encoded> {
|
||||
let opts = parse(p)?;
|
||||
let f = super::format("hpgl").ok_or_else(|| bad(C, "no HP-GL format"))?;
|
||||
let pick: ArtboardPick = super::encode::options(f, p)?;
|
||||
let n = doc.artboards.len();
|
||||
let boards = match use_artboards {
|
||||
Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()),
|
||||
_ => vec![pick.one(n).map_err(|e| bad(C, e))?],
|
||||
};
|
||||
let regions = boards
|
||||
.iter()
|
||||
.map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1))))
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let plots = vectorcraft_cad::hpgl::export_regions(doc, &opts, ®ions).map_err(|e| bad(C, e))?;
|
||||
let mut enc = Encoded::default();
|
||||
for (b, out) in boards.into_iter().zip(plots) {
|
||||
enc.files.push((Some(b), out.bytes));
|
||||
for w in out.warnings {
|
||||
if !enc.warnings.contains(&w) {
|
||||
enc.warnings.push(w);
|
||||
}
|
||||
}
|
||||
}
|
||||
if enc.files.is_empty() {
|
||||
return Err(bad(C, "the document has no artboard"));
|
||||
}
|
||||
let regions: Vec<vectorcraft_geom::Rect> = enc.files.iter().filter_map(|(b, _)| b.and_then(|b| doc.artboards.get(b))).map(|a| a.rect).collect();
|
||||
enc.warnings.extend(crate::cmd::fonts::export_overflow_warning(doc, &doc.layers, Some(®ions)));
|
||||
Ok(enc)
|
||||
}
|
||||
@@ -145,7 +145,7 @@ pub(super) fn encode(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Result
|
||||
}
|
||||
}
|
||||
}
|
||||
let o = vectorcraft_eps::LegacyAiOptions { title: doc.title.clone(), created, hidden, outline_text };
|
||||
let o = vectorcraft_eps::LegacyAiOptions { title: doc.info_title().to_owned(), created, hidden, outline_text };
|
||||
let out = vectorcraft_eps::export_legacy_ai(&d, &o).map_err(|e| bad(cmd, e))?;
|
||||
for w in placed.iter().chain(&out.warnings) {
|
||||
note(&mut enc.warnings, w);
|
||||
|
||||
@@ -7,6 +7,7 @@ use vectorcraft_doc::{Document, ImageBlob, ImageObject, Node, NodeKind};
|
||||
use vectorcraft_geom::Affine;
|
||||
use vectorcraft_render::effects::pixel::LoadedTexture;
|
||||
|
||||
use super::super::fileinfo::imported_title;
|
||||
use super::super::{Result, Session, bad, bool_or, clipboard, parse_range, str_param};
|
||||
use super::pdfimport::LoadOptions;
|
||||
use super::{Format, SAVE_FORMATS, absolute_path, file_stamp, format, jxlread, psdread, read_file, readable_format_for_name};
|
||||
@@ -550,6 +551,15 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
if let Some(mode) = opts.color_mode.filter(|m| *m != doc.color_mode) {
|
||||
super::super::colormgmt::set_color_mode(&mut doc, mode, true, None, opts.grays);
|
||||
}
|
||||
// The title the file gives itself (an SVG's `<title>`, a PDF's, `.ai`'s or `.ait`'s XMP `dc:title`
|
||||
// or Info `Title`, which the readers put in File Info) is separate from the document's name.
|
||||
// Restored File Info is preserved exactly; newly imported SVG candidates and a restored
|
||||
// document's legacy name fallback are cleaned as imported text. The name stays the file's (#3626).
|
||||
if !restored && matches!(format.id, "svg" | "svgz") {
|
||||
doc.metadata.title = doc.metadata.title.as_deref().and_then(imported_title);
|
||||
}
|
||||
let held = restored.then_some(doc.title.as_str()).filter(|t| *t != title);
|
||||
doc.metadata.title = doc.metadata.title.or_else(|| held.and_then(imported_title));
|
||||
// Imports are named after the file; a native document keeps its own title (the tab shows the
|
||||
// file name once it has a path).
|
||||
if !matches!(format.id, "vectorcraft" | "template") || doc.title.is_empty() {
|
||||
@@ -678,6 +688,7 @@ fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option<St
|
||||
if template {
|
||||
doc.template = false;
|
||||
doc.title = s.next_untitled();
|
||||
doc.metadata.title = None;
|
||||
}
|
||||
// A .ai (or .ait) another app wrote carries no open Layers rows we read: all of them start
|
||||
// closed, its top-level layers as its groups (#1475). Ours carry their own.
|
||||
@@ -711,7 +722,7 @@ fn open_loaded(s: &mut Session, loaded: Loaded, links: Resolved, path: Option<St
|
||||
st.import_losses = losses;
|
||||
st.links_from = read_from;
|
||||
let opened = &s.documents()[index];
|
||||
let (title, file_info_title) = (opened.title(), opened.doc.title.clone());
|
||||
let (title, file_info_title) = (opened.title(), opened.doc.info_title().to_string());
|
||||
Ok(super::merge(
|
||||
json!({ "index": index, "title": title, "fileInfoTitle": file_info_title, "format": format.id, "warnings": warnings, "restored": restored }),
|
||||
links.to_json(),
|
||||
|
||||
@@ -731,7 +731,7 @@ pub(super) fn encode_ai(cmd: &str, f: &Format, doc: &Document, p: &Value) -> Res
|
||||
// With the artboards' background colors, as the pages draw them.
|
||||
let art = super::export::with_artboard_fills(art, ¶ms, 0..art.artboards.len()).map_err(|e| bad(cmd, e))?;
|
||||
let o = vectorcraft_eps::AiEditingOptions {
|
||||
title: doc.title.clone(),
|
||||
title: doc.info_title().to_owned(),
|
||||
created: doc.metadata.created.or_else(vectorcraft_doc::metadata::output_time),
|
||||
};
|
||||
let (data, lost) = vectorcraft_eps::ai_private_data(&art, &o).map_err(|e| bad(cmd, e))?;
|
||||
@@ -870,8 +870,10 @@ impl SaveJob {
|
||||
_ => encode_all(doc, f.id, &self.params),
|
||||
}
|
||||
.map_err(|e| named_for_save(cmd, e))?;
|
||||
// A legacy .ai file per artboard.
|
||||
let per_artboard = f.id == "ai" && super::legacy_ai::wanted(cmd, f, &self.params)?;
|
||||
// A legacy .ai file per artboard, or the files the EPS encoder writes: one, or with Use
|
||||
// Artboards and two or more artboards the central file at the path and a file per
|
||||
// artboard beside it.
|
||||
let per_artboard = f.id == "eps" || (f.id == "ai" && super::legacy_ai::wanted(cmd, f, &self.params)?);
|
||||
if enc.files.len() != 1 && !per_artboard {
|
||||
return Err(bad(cmd, "Save writes one artboard: name one, or export several with document.export"));
|
||||
}
|
||||
@@ -883,7 +885,13 @@ impl SaveJob {
|
||||
/// folder?, warnings, files?: [{name, dataBase64}] (every file, when there are several),
|
||||
/// linked?: [{name, dataBase64}]}`; with one → `{path, format, bytes, warnings, files?:
|
||||
/// [path…], linked?: [path…]}`.
|
||||
pub fn write(&self, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
pub fn write(&self, write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
self.write_unless(|_| None, write)
|
||||
}
|
||||
|
||||
/// [`SaveJob::write`], once `stop` has seen the paths of every file it writes to a path, in
|
||||
/// order: when `stop` returns a value, nothing is written and that value is returned.
|
||||
pub fn write_unless(&self, stop: impl FnOnce(&[&str]) -> Option<Value>, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
|
||||
let (plan, doc) = (&self.plan, &*self.doc);
|
||||
let mut enc = self.encode()?;
|
||||
let warnings = std::mem::take(&mut enc.warnings);
|
||||
@@ -897,6 +905,9 @@ impl SaveJob {
|
||||
return Ok(out);
|
||||
};
|
||||
let files = enc.named(doc, path);
|
||||
if let Some(stopped) = stop(&files.iter().map(|(p, _)| p.as_str()).collect::<Vec<_>>()) {
|
||||
return Ok(stopped);
|
||||
}
|
||||
for (p, bytes) in &files {
|
||||
write(p, bytes)?;
|
||||
}
|
||||
@@ -1032,11 +1043,47 @@ pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result<Value>
|
||||
let plan = save_plan(s, mode, p)?;
|
||||
let job = save_job(s, plan)?;
|
||||
let uid = s.doc()?.uid;
|
||||
let out = job.write_streamed(&mut super::write_file_with)?;
|
||||
let mut out = job.write_streamed(&mut super::write_file_with)?;
|
||||
job.complete(s, uid);
|
||||
leave_out_unreadable_save_paths(&mut out, str_param(p, "path"));
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The reply `out` of a save with the `path` param `given`, as the request being served may see it
|
||||
/// ([`super::access::shown`]). A save without a path writes the document's own file: its `path` is
|
||||
/// left out, and the `files` and `linked` written beside it are named by their file names, when they
|
||||
/// are outside the read roots. The suggested `folder` of a reply without a path is left out when it
|
||||
/// is outside them. Without roots in force `out` is unchanged.
|
||||
pub fn leave_out_unreadable_save_paths(out: &mut Value, given: Option<&str>) {
|
||||
use super::access::{shown, shown_path};
|
||||
|
||||
if crate::file_access::current().is_none() {
|
||||
return;
|
||||
}
|
||||
let Some(o) = out.as_object_mut() else { return };
|
||||
if o.get("folder").and_then(Value::as_str).is_some_and(|f| !shown(f)) {
|
||||
o.remove("folder");
|
||||
}
|
||||
// Every path the reply names then is the one the client gave, or beside it.
|
||||
if given.is_some_and(|g| !g.is_empty()) {
|
||||
return;
|
||||
}
|
||||
if o.get("path").and_then(Value::as_str).is_some_and(|p| !shown(p)) {
|
||||
o.remove("path");
|
||||
}
|
||||
for key in ["files", "linked"] {
|
||||
if let Some(Value::Array(rows)) = o.get_mut(key) {
|
||||
for row in rows {
|
||||
if let Value::String(p) = row
|
||||
&& !shown(p)
|
||||
{
|
||||
*row = json!(shown_path(p));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn can_revert(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
match (&st.path, st.is_dirty()) {
|
||||
@@ -1092,6 +1139,25 @@ fn format_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
}
|
||||
}
|
||||
// An EPS save that named artboards without Use Artboards, or with it on, had it on (the
|
||||
// encoder reads them so): it shows on, with those artboards as the range.
|
||||
if f.id == "eps"
|
||||
&& let Some(m) = &saved
|
||||
&& m.get("useArtboards").and_then(Value::as_bool) != Some(false)
|
||||
{
|
||||
let range = m.get("range").and_then(Value::as_str).filter(|r| !r.trim().is_empty());
|
||||
let boards = m
|
||||
.get("artboards")
|
||||
.and_then(|a| serde_json::from_value::<Vec<usize>>(a.clone()).ok())
|
||||
.or_else(|| m.get("artboard").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).map(|i| vec![i]))
|
||||
.filter(|b| !b.is_empty());
|
||||
if range.is_some() || boards.is_some() {
|
||||
v["options"]["useArtboards"]["value"] = json!(true);
|
||||
if let (None, Some(boards)) = (range, boards) {
|
||||
v["options"]["range"]["value"] = json!(range_text(&boards));
|
||||
}
|
||||
}
|
||||
}
|
||||
v["saveFormats"] =
|
||||
SAVE_FORMATS.iter().filter_map(|id| format(id)).map(|f| json!({"id": f.id, "label": f.label, "extensions": f.extensions})).collect();
|
||||
Ok(v)
|
||||
@@ -1104,7 +1170,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: 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 saves the chosen artboard (first by default), retaining its page margins and the whole editable document; 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. 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",
|
||||
"{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",
|
||||
has_doc,
|
||||
|s, p| save(s, SaveMode::Save, p)
|
||||
),
|
||||
@@ -1158,7 +1224,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
|
||||
"Format Options",
|
||||
[],
|
||||
None,
|
||||
"{format?: a writable format id or ait (default: the document's own)} → {id, label, extensions, mime, read, write, raster, options: {name: {type, default, description, value}}, saveFormats: [{id, label, extensions}]}; value = the document's option as last saved in that format, else (native, for a document not yet saved as one) as the last native save used it, else the default",
|
||||
"{format?: a writable format id or ait (default: the document's own)} → {id, label, extensions, mime, read, write, raster, options: {name: {type, default, description, value}}, saveFormats: [{id, label, extensions}]}; value = the document's option as last saved in that format, else (native, for a document not yet saved as one) as the last native save used it, else the default (EPS: useArtboards is true when the last save named artboards without it, and range then names them)",
|
||||
always,
|
||||
format_options
|
||||
),
|
||||
|
||||
@@ -196,7 +196,7 @@ pub(super) fn name_without_device(name: &str) -> String {
|
||||
pub(crate) const ROW_KEYS: [&str; 7] = ["format", "scale", "ppi", "width", "height", "suffix", "folder"];
|
||||
|
||||
/// The writable formats a format row can't name.
|
||||
pub(crate) const UNWRITTEN_FORMATS: [&str; 5] = ["template", "txt", "dxf", "emf", "wmf"];
|
||||
pub(crate) const UNWRITTEN_FORMATS: [&str; 6] = ["template", "txt", "dxf", "emf", "wmf", "hpgl"];
|
||||
|
||||
/// One format row: what to write, at which size, with which suffix, into which sub-folder.
|
||||
struct Row {
|
||||
@@ -644,12 +644,86 @@ impl Output {
|
||||
/// File → Export for Screens: [`export`] (over the settings of `exportPreset`, when given), with
|
||||
/// the params remembered in the document (`document.exportSettings`).
|
||||
pub(super) fn export_for_screens(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// A folder the client gave, as against the one its `exportPreset` keeps.
|
||||
let given = p.get("folder").is_some();
|
||||
let p = with_preset(s, p)?;
|
||||
let r = export(s, &p)?;
|
||||
let hidden = if given { None } else { str_param(&p, "folder").filter(|f| !f.is_empty() && !super::access::shown(f)) };
|
||||
let mut r = export(s, &p).map_err(|e| match hidden {
|
||||
Some(folder) => leave_out_folder_from_error(e, folder),
|
||||
None => e,
|
||||
})?;
|
||||
remember(s, &p);
|
||||
if !given && let Some(folder) = str_param(&p, "folder").filter(|f| !f.is_empty()) {
|
||||
leave_out_unreadable_folder(&mut r, folder);
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
/// An error of an export into `folder`, a folder outside the read roots that the client did not
|
||||
/// give: `folder` as the path the error is about names it by its own name
|
||||
/// ([`super::access::shown_path`]), and the rest of the message stays.
|
||||
fn leave_out_folder_from_error(e: EngineError, folder: &str) -> EngineError {
|
||||
let name = super::access::shown_path(folder);
|
||||
match e {
|
||||
EngineError::Other(msg) => EngineError::Other(leave_out_folder_from_message(&msg, folder, &name)),
|
||||
EngineError::BadParams { cmd, msg } => EngineError::BadParams { cmd, msg: leave_out_folder_from_message(&msg, folder, &name) },
|
||||
e => e,
|
||||
}
|
||||
}
|
||||
|
||||
/// `msg` with `folder` given as `name` where it begins a path the message is about: at the start
|
||||
/// of `msg` (`<path>: <reason>`), after a `: ` (`... outside the write root <root>: <path>`) or
|
||||
/// after `cannot resolve `, followed by the end, a separator, a `:` or a space. A root the message
|
||||
/// names stays whole, even one inside `folder`.
|
||||
fn leave_out_folder_from_message(msg: &str, folder: &str, name: &str) -> String {
|
||||
const BEFORE: [&str; 2] = [": ", "cannot resolve "];
|
||||
let mut out = String::with_capacity(msg.len());
|
||||
let mut rest = msg;
|
||||
loop {
|
||||
if let Some(after) = rest.strip_prefix(folder)
|
||||
&& after.chars().next().is_none_or(|c| matches!(c, '/' | '\\' | ':' | ' '))
|
||||
{
|
||||
out.push_str(name);
|
||||
rest = after;
|
||||
}
|
||||
let Some((i, len)) = BEFORE.iter().filter_map(|b| rest.find(b).map(|i| (i, b.len()))).min() else { break };
|
||||
out.push_str(&rest[..i + len]);
|
||||
rest = &rest[i + len..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// The reply `r` of an export into `folder`, a folder the client did not give, as the request being
|
||||
/// served may see it: when `folder` is outside the read roots ([`super::access::shown`]), the ZIP's
|
||||
/// `path` is left out and `files` names each file written relative to `folder` (`2x/Logo@2x.png`),
|
||||
/// as the reply of an export to a ZIP names them.
|
||||
fn leave_out_unreadable_folder(r: &mut Value, folder: &str) {
|
||||
if super::access::shown(folder) {
|
||||
return;
|
||||
}
|
||||
let Some(o) = r.as_object_mut() else { return };
|
||||
o.remove("path");
|
||||
let inside = format!("{folder}/");
|
||||
if let Some(Value::Array(files)) = o.get_mut("files") {
|
||||
for file in files {
|
||||
// A ZIP's files are named relative to it already.
|
||||
if let Some(name) = file.as_str().and_then(|path| path.strip_prefix(&inside)) {
|
||||
*file = json!(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Export settings kept in the document or a preset, as the request being served may see them: a
|
||||
/// `folder` outside the read roots ([`super::access::shown`]) is left out.
|
||||
fn leave_out_unreadable_settings_folder(mut settings: Map<String, Value>) -> Map<String, Value> {
|
||||
if settings.get("folder").and_then(Value::as_str).is_some_and(|f| !f.is_empty() && !super::access::shown(f)) {
|
||||
settings.remove("folder");
|
||||
}
|
||||
settings
|
||||
}
|
||||
|
||||
// ---------- export presets ----------
|
||||
|
||||
/// A saved batch export: what to write and how to name and sort it, to use again
|
||||
@@ -727,7 +801,13 @@ pub fn preset_list(saved: &[ScreenExportPreset]) -> Value {
|
||||
}
|
||||
|
||||
pub(super) fn presets_list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "presets": preset_list(&s.prefs.screen_export_presets) }))
|
||||
let saved: Vec<ScreenExportPreset> = s
|
||||
.prefs
|
||||
.screen_export_presets
|
||||
.iter()
|
||||
.map(|p| ScreenExportPreset { name: p.name.clone(), settings: leave_out_unreadable_settings_folder(p.settings.clone()) })
|
||||
.collect();
|
||||
Ok(json!({ "presets": preset_list(&saved) }))
|
||||
}
|
||||
|
||||
/// The [`PRESET_KEYS`] of `given`, refused as an error of command `cmd` when an export would
|
||||
@@ -831,6 +911,8 @@ pub(super) fn presets_export(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(too_many());
|
||||
}
|
||||
let count = presets.len();
|
||||
let presets: Vec<ScreenExportPreset> =
|
||||
presets.into_iter().map(|p| ScreenExportPreset { settings: leave_out_unreadable_settings_folder(p.settings), ..p }).collect();
|
||||
let text = serde_json::to_string_pretty(&PresetFile { format: PRESET_FILE_FORMAT.into(), presets }).map_err(|e| bad(EXPORT, e.to_string()))?;
|
||||
if text.len() > MAX_PRESET_FILE_BYTES {
|
||||
return Err(bad(EXPORT, format!("export presets file is larger than {MAX_PRESET_FILE_BYTES} bytes")));
|
||||
@@ -1388,12 +1470,31 @@ pub(crate) fn store_settings(s: &mut Session, mut settings: Map<String, Value>)
|
||||
|
||||
/// `document.exportSettings`: the Export for Screens settings the document last exported with.
|
||||
pub(super) fn export_settings(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({ "settings": s.doc()?.doc.export_settings }))
|
||||
Ok(json!({ "settings": leave_out_unreadable_settings_folder(s.doc()?.doc.export_settings.clone()) }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{Output, ScreenSize, safe_file_name};
|
||||
use super::{Output, ScreenSize, leave_out_folder_from_message, safe_file_name};
|
||||
|
||||
/// A hidden export folder is named by its name where a message is about it, and a root that
|
||||
/// starts with the same text, or a longer path, stays whole.
|
||||
#[test]
|
||||
fn a_hidden_folder_is_named_by_its_name_in_a_message() {
|
||||
let f = "/work/out";
|
||||
let cases = [
|
||||
(
|
||||
"automation path rejected: outside the write root /work/out/in: /work/out",
|
||||
"automation path rejected: outside the write root /work/out/in: out",
|
||||
),
|
||||
("automation path rejected: cannot resolve /work/out: denied", "automation path rejected: cannot resolve out: denied"),
|
||||
("/work/out/2x/a.png: disk full", "out/2x/a.png: disk full"),
|
||||
("automation path rejected: outside the write root /a: /work/outer", "automation path rejected: outside the write root /a: /work/outer"),
|
||||
];
|
||||
for (msg, want) in cases {
|
||||
assert_eq!(leave_out_folder_from_message(msg, f, "out"), want, "{msg}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Files given one name are numbered in turn, each numbering going on from the last one (so
|
||||
/// thousands of them don't each try every number used before), and a file asking again for
|
||||
|
||||
@@ -48,6 +48,19 @@ fn image_of(s: &Session) -> vectorcraft_doc::ImageObject {
|
||||
}
|
||||
}
|
||||
|
||||
/// A path outside a confined request's read roots shows as its file name, after the last `/` or `\`
|
||||
/// on every platform; one that ends in no name shows as nothing. Without roots it shows whole.
|
||||
#[test]
|
||||
fn a_hidden_path_shows_as_its_file_name_on_every_platform() {
|
||||
let windows = "C:\\Users\\someone\\art\\red.png";
|
||||
crate::file_access::confine(Some(&crate::file_access::AutomationRoots::none()), || {
|
||||
for (path, name) in [("/home/someone/art/red.png", "red.png"), (windows, "red.png"), ("/home/someone/..", ""), ("C:\\Users\\someone\\", "")] {
|
||||
assert_eq!(shown_path(path), name, "{path}");
|
||||
}
|
||||
});
|
||||
assert_eq!(shown_path(windows), windows);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opens_every_readable_format() {
|
||||
let mut s = session(200.0, 100.0, 1);
|
||||
@@ -418,6 +431,7 @@ fn export_extensions_name_every_writable_format() {
|
||||
"eps",
|
||||
"emf",
|
||||
"wmf",
|
||||
"plt",
|
||||
"tga",
|
||||
"psd"
|
||||
]
|
||||
@@ -453,6 +467,7 @@ fn formats_query_lists_readers_writers_and_options() {
|
||||
"eps",
|
||||
"emf",
|
||||
"wmf",
|
||||
"hpgl",
|
||||
"tga",
|
||||
"psd"
|
||||
]
|
||||
|
||||
@@ -109,23 +109,25 @@ fn the_ai_editing_copy_for_other_apps_draws_the_color_as_the_pages_do() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Does PostScript `t` paint the only red the document has, the first artboard's color? RGB, or
|
||||
/// CMYK PostScript's (its values depend on the color conversion the platform offers, so only its
|
||||
/// hue is checked).
|
||||
fn red(t: &str) -> bool {
|
||||
t.lines().any(|l| {
|
||||
let mut w: Vec<&str> = l.split_whitespace().collect();
|
||||
let Some(op) = w.pop() else { return false };
|
||||
let v: Vec<f64> = w.iter().filter_map(|n| n.parse().ok()).collect();
|
||||
match (op, v.as_slice()) {
|
||||
("rg" | "setrgbcolor", [r, g, b]) => *r > 0.9 && *g < 0.1 && *b < 0.1,
|
||||
("k" | "setcmykcolor", [c, m, y, k]) => *c < 0.1 && *m > 0.8 && *y > 0.8 && *k < 0.1,
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eps_and_postscript_print_draw_the_color() {
|
||||
let mut s = session();
|
||||
// The only red the document has, the first artboard's color: RGB, or CMYK PostScript's (its
|
||||
// values depend on the color conversion the platform offers, so only its hue is checked).
|
||||
let red = |t: &str| {
|
||||
t.lines().any(|l| {
|
||||
let mut w: Vec<&str> = l.split_whitespace().collect();
|
||||
let Some(op) = w.pop() else { return false };
|
||||
let v: Vec<f64> = w.iter().filter_map(|n| n.parse().ok()).collect();
|
||||
match (op, v.as_slice()) {
|
||||
("rg" | "setrgbcolor", [r, g, b]) => *r > 0.9 && *g < 0.1 && *b < 0.1,
|
||||
("k" | "setcmykcolor", [c, m, y, k]) => *c < 0.1 && *m > 0.8 && *y > 0.8 && *k < 0.1,
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
};
|
||||
let eps = |s: &mut Session, more: Value| {
|
||||
String::from_utf8_lossy(&file(s, with(json!({"format": "eps", "useArtboards": true, "artboard": 0}), &more))).into_owned()
|
||||
};
|
||||
@@ -138,6 +140,22 @@ fn eps_and_postscript_print_draw_the_color() {
|
||||
assert!(!red(&ps(&mut s, json!({"includeArtboardFill": false}))), "print without it");
|
||||
}
|
||||
|
||||
/// EPS Save draws the color on an artboard's page: with Use Artboards, or on the first artboard
|
||||
/// when no art shows. The box of the visible art, as Export's, has none.
|
||||
#[test]
|
||||
fn eps_save_draws_the_color_on_an_artboard_page() {
|
||||
let mut s = session();
|
||||
let save = |s: &mut Session, more: Value| {
|
||||
let options = with(json!({"previewFormat": "none", "thumbnails": false}), &more);
|
||||
String::from_utf8_lossy(&b64(&s.execute("document.save", &json!({"format": "eps", "options": options})).unwrap())).into_owned()
|
||||
};
|
||||
assert!(!red(&save(&mut s, json!({}))), "the art's box");
|
||||
assert!(red(&save(&mut s, json!({"useArtboards": true, "range": "1"}))), "the artboard's page");
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.execute("edit.clear", &json!({})).unwrap();
|
||||
assert!(red(&save(&mut s, json!({}))), "the first artboard when no art shows");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_for_screens_includes_the_fill_unless_unchecked() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -84,6 +84,11 @@ fn the_cnc_preset_sets_the_options_that_are_not_given() {
|
||||
true
|
||||
)
|
||||
);
|
||||
assert_eq!((o.include_images, o.include_hatches), (false, false), "CNC / CAM leaves out images and fill hatches");
|
||||
let given = dxf::options(&json!({"dxfPreset": "cnc", "includeImages": true, "includeHatches": true})).unwrap();
|
||||
assert_eq!((given.include_images, given.include_hatches), (true, true), "the options given override it");
|
||||
let custom = dxf::options(&json!({})).unwrap();
|
||||
assert_eq!((custom.include_images, custom.include_hatches), (true, true), "Custom keeps both");
|
||||
assert_eq!(dxf::options(&json!({})).unwrap().version, vectorcraft_cad::DxfVersion::R2018, "custom by default");
|
||||
let e = s.execute("document.exportDxf", &json!({"dxfPreset": "laser"})).unwrap_err().to_string();
|
||||
assert!(e.contains("custom or cnc"), "{e}");
|
||||
@@ -151,6 +156,44 @@ fn placed_images_come_back_as_linked_files() {
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// `includeImages` and `includeHatches` leave out placed images (with their files) and fill
|
||||
/// hatches, each on its own, through both commands, with and without a path; CNC / CAM leaves
|
||||
/// out both, and the options given override it.
|
||||
#[test]
|
||||
fn placed_images_and_fill_hatches_can_be_left_out() {
|
||||
let mut s = super::tests_svg::image_session();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap();
|
||||
let counts = |r: &Value| {
|
||||
let e = entities(&text(r));
|
||||
let n = |k: &str| e.iter().filter(|x| *x == k).count();
|
||||
(n("LWPOLYLINE"), n("HATCH"), n("IMAGE"), r.get("linked").and_then(Value::as_array).map_or(0, Vec::len))
|
||||
};
|
||||
let warned = |r: &Value, w: &str| r["warnings"].as_array().unwrap().iter().any(|x| x.as_str().is_some_and(|x| x.starts_with(w)));
|
||||
let all = s.execute("document.export", &json!({"format": "dxf"})).unwrap();
|
||||
assert_eq!(counts(&all), (1, 1, 1, 1));
|
||||
let r = s.execute("document.export", &json!({"format": "dxf", "includeImages": false})).unwrap();
|
||||
assert_eq!(counts(&r), (1, 1, 0, 0));
|
||||
assert!(warned(&r, "placed images are left out") && !warned(&r, "fill hatches"), "{r}");
|
||||
let r = s.execute("document.exportDxf", &json!({"includeHatches": false})).unwrap();
|
||||
assert_eq!(counts(&r), (1, 0, 1, 1));
|
||||
assert!(warned(&r, "fill hatches are left out") && !warned(&r, "placed images"), "{r}");
|
||||
let r = s.execute("document.exportDxf", &json!({"dxfPreset": "cnc"})).unwrap();
|
||||
assert_eq!(counts(&r), (1, 0, 0, 0));
|
||||
let r = s.execute("document.export", &json!({"format": "dxf", "dxfPreset": "cnc", "includeImages": true})).unwrap();
|
||||
assert_eq!(counts(&r), (1, 0, 1, 1));
|
||||
// With a path, no image file is written next to the drawing.
|
||||
let dir = std::env::temp_dir().join(format!("vc-dxf-out-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("cut.dxf").to_string_lossy().to_string();
|
||||
let r = s.execute("document.exportDxf", &json!({"path": path, "dxfPreset": "cnc"})).unwrap();
|
||||
assert!(r.get("linked").is_none(), "{r}");
|
||||
let files: Vec<String> = std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).map(|e| e.file_name().to_string_lossy().to_string()).collect();
|
||||
assert_eq!(files, ["cut.dxf"]);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Two placed images whose pixel data can't be decoded are left out of the drawing and get no
|
||||
/// linked file, and `warnings` holds the note raster exports give, once, without naming either
|
||||
/// image's key.
|
||||
@@ -181,6 +224,8 @@ fn bad_dxf_options_are_refused() {
|
||||
json!({"rasterFormat": "gif"}),
|
||||
json!({"preserve": "both"}),
|
||||
json!({"alterPaths": "yes"}),
|
||||
json!({"includeImages": "no"}),
|
||||
json!({"includeHatches": 0}),
|
||||
] {
|
||||
let e = s.execute("document.exportDxf", &p).unwrap_err().to_string();
|
||||
assert!(e.contains("DXF"), "{p}: {e}");
|
||||
@@ -203,6 +248,8 @@ fn formats_list_dxf_and_what_can_not_be_written() {
|
||||
"scaleLineweights",
|
||||
"colors",
|
||||
"rasterFormat",
|
||||
"includeImages",
|
||||
"includeHatches",
|
||||
"preserve",
|
||||
"alterPaths",
|
||||
"outlineText",
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! HP-GL plotter files through the commands: `document.open` by extension or by content, File ›
|
||||
//! Place as one group of paths, the dialogs' filters and the format list, and files that aren't
|
||||
//! HP-GL refused with a message.
|
||||
//! Place as one group of paths, the dialogs' filters and the format list, files that aren't
|
||||
//! HP-GL refused with a message, and `document.export` of one artboard, each or the art, with its
|
||||
//! options checked.
|
||||
|
||||
use serde_json::json;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeKind;
|
||||
|
||||
use super::*;
|
||||
@@ -100,5 +101,131 @@ fn the_dialogs_and_the_format_list_name_hpgl() {
|
||||
assert!(open_filters().any(|f| f == filter) && place_filters().any(|f| f == filter));
|
||||
let r = Session::new().execute("document.formats", &json!({})).unwrap();
|
||||
let f = r["formats"].as_array().unwrap().iter().find(|f| f["id"] == "hpgl").unwrap().clone();
|
||||
assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(false), Some(false)));
|
||||
assert_eq!((f["read"].as_bool(), f["write"].as_bool(), f["raster"].as_bool()), (Some(true), Some(true), Some(false)));
|
||||
for o in ["useArtboards", "hpglVersion", "curveTolerance", "pens", "origin", "sortPaths", "insideFirst"] {
|
||||
assert!(f["options"].get(o).is_some(), "{o}: {f}");
|
||||
}
|
||||
assert_eq!(writable_format(None, Some("x/part.plt")).unwrap().id, "hpgl");
|
||||
assert_eq!(writable_format(None, Some("x/part.hpgl")).unwrap().id, "hpgl");
|
||||
}
|
||||
|
||||
fn bytes(v: &Value) -> Vec<u8> {
|
||||
vectorcraft_format::base64_decode(v["dataBase64"].as_str().expect("dataBase64")).unwrap()
|
||||
}
|
||||
|
||||
/// Two 100 pt artboards side by side, a 30 pt square on each, the second one red.
|
||||
fn two_boards() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100, "artboards": 2})).unwrap();
|
||||
let second = s.doc().unwrap().doc.artboards[1].rect.x0;
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap();
|
||||
let red = s.execute("shape.rectangle", &json!({"x": second + 10.0, "y": 10, "width": 30, "height": 30})).unwrap()["id"].clone();
|
||||
s.execute("paint.setStroke", &json!({"ids": [red], "color": "#ff0000"})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_writes_a_plot_of_one_artboard_or_each() {
|
||||
let mut s = two_boards();
|
||||
let r = s.execute("document.export", &json!({"format": "hpgl"})).unwrap();
|
||||
assert_eq!(r["format"], "hpgl");
|
||||
// The first artboard's square, 1016 units to the inch from its bottom-left corner.
|
||||
assert_eq!(String::from_utf8(bytes(&r)).unwrap(), "IN;PU;SP1;PU141,1270;PD564,1270,564,847,141,847,141,1270;PU;SP0;");
|
||||
let second = String::from_utf8(bytes(&s.execute("document.export", &json!({"format": "hpgl", "artboard": 1})).unwrap())).unwrap();
|
||||
assert_eq!(second, "IN;PU;SP1;PU141,1270;PD564,1270,564,847,141,847,141,1270;PU;SP0;", "its own square, its own pen 1");
|
||||
assert_eq!(bytes(&s.execute("document.serialize", &json!({"format": "hpgl"})).unwrap()), bytes(&r));
|
||||
let r = s.execute("document.export", &json!({"format": "hpgl", "useArtboards": true})).unwrap();
|
||||
let files = r["files"].as_array().unwrap();
|
||||
assert_eq!(files.len(), 2);
|
||||
assert!(files[1]["name"].as_str().unwrap().ends_with("-Artboard-2.plt"), "{files:?}");
|
||||
// One pen numbering for every file: the red square is pen 2 in the second.
|
||||
assert_eq!(String::from_utf8(bytes(&files[1])).unwrap(), "IN;PU;SP2;PU141,1270;PD564,1270,564,847,141,847,141,1270;PU;SP0;");
|
||||
// The bounds of the art: both squares, the second pen red, read back as two paths.
|
||||
let art = bytes(&s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false, "hpglVersion": "hpgl2"})).unwrap());
|
||||
assert!(art.starts_with(b"IN;NP4;PC1,0,0,0;PC2,255,0,0;"), "{:?}", String::from_utf8_lossy(&art));
|
||||
let back = Session::new().execute("document.open", &json!({"name": "art.plt", "dataBase64": b64(&art)})).unwrap();
|
||||
assert_eq!(back["format"], "hpgl", "{back}");
|
||||
// One file holds one artboard.
|
||||
assert!(s.execute("document.export", &json!({"format": "hpgl", "artboards": [0, 1]})).is_err());
|
||||
}
|
||||
|
||||
/// A plot read back opens with the same squares: as wide as the art drew them, a point at most
|
||||
/// apart from the 30 pt sides plus the 0.35 mm pen.
|
||||
#[test]
|
||||
fn a_plot_reads_back_as_its_art() {
|
||||
let mut s = two_boards();
|
||||
let plot = bytes(&s.execute("document.export", &json!({"format": "hpgl", "useArtboards": false})).unwrap());
|
||||
let mut back = Session::new();
|
||||
back.execute("document.open", &json!({"name": "art.plt", "dataBase64": b64(&plot)})).unwrap();
|
||||
let doc = &back.doc().unwrap().doc;
|
||||
let mut paths = 0;
|
||||
doc.walk(|n| paths += usize::from(matches!(n.kind, NodeKind::Path { .. })));
|
||||
assert_eq!(paths, 2);
|
||||
let board = doc.artboards[0].rect;
|
||||
let second = s.doc().unwrap().doc.artboards[1].rect.x0;
|
||||
let pen = 0.35 * 72.0 / 25.4;
|
||||
assert!((board.width() - (second + 30.0 + pen)).abs() < 0.1, "{board:?}");
|
||||
assert!((board.height() - (30.0 + pen)).abs() < 0.1, "{board:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_options_are_checked() {
|
||||
let mut s = two_boards();
|
||||
let refused = |s: &mut Session, p: Value| s.execute("document.export", &p).expect_err("refused").to_string();
|
||||
let cases = [
|
||||
(json!({"format": "hpgl", "hpglVersion": "hpgl3"}), "`hpglVersion` must be one of hpgl, hpgl2"),
|
||||
(json!({"format": "hpgl", "hpglVersion": 2}), "`hpglVersion` must be a string"),
|
||||
(json!({"format": "hpgl", "curveTolerance": 0}), "`curveTolerance` must be between 0.01 and 10 (got 0)"),
|
||||
(json!({"format": "hpgl", "curveTolerance": "fine"}), "`curveTolerance` must be a number"),
|
||||
(json!({"format": "hpgl", "pens": []}), "`pens` must be an array of 1 to 255 #rrggbb colors"),
|
||||
(json!({"format": "hpgl", "pens": ["#ff0000", "red"]}), "`pens` must be an array of 1 to 255 #rrggbb colors"),
|
||||
(json!({"format": "hpgl", "pens": "#ff0000"}), "`pens` must be an array of 1 to 255 #rrggbb colors"),
|
||||
(json!({"format": "hpgl", "origin": "top"}), "`origin` must be one of bottomLeft, center"),
|
||||
(json!({"format": "hpgl", "sortPaths": "yes"}), "`sortPaths` must be true or false"),
|
||||
(json!({"format": "hpgl", "insideFirst": 1}), "`insideFirst` must be true or false"),
|
||||
];
|
||||
for (p, want) in cases {
|
||||
let e = refused(&mut s, p.clone());
|
||||
assert!(e.contains(want), "{p}: {e}");
|
||||
}
|
||||
let many: Vec<String> = (0..256).map(|i| format!("#{:02x}0000", i % 256)).collect();
|
||||
assert!(refused(&mut s, json!({"format": "hpgl", "pens": many})).contains("`pens`"));
|
||||
// Given options take effect: the center as the origin, a pen table (black is pen 2), and the
|
||||
// square starting at its corner nearest the origin.
|
||||
let p = json!({"format": "hpgl", "origin": "CENTER", "pens": ["#ff0000", "#000000"], "curveTolerance": 10, "sortPaths": true});
|
||||
let plot = String::from_utf8(bytes(&s.execute("document.export", &p).unwrap())).unwrap();
|
||||
assert_eq!(plot, "IN;PU;SP2;PU-141,141;PD-564,141,-564,564,-141,564,-141,141;PU;SP0;");
|
||||
}
|
||||
|
||||
/// `insideFirst` draws the square inside the other one first, though it was made last.
|
||||
#[test]
|
||||
fn inside_first_draws_the_inner_square_first() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
s.execute("paint.setStroke", &json!({"color": "#000000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 80, "height": 80})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 30, "y": 30, "width": 20, "height": 20})).unwrap();
|
||||
let starts = |s: &mut Session, p: Value| {
|
||||
let plot = String::from_utf8(bytes(&s.execute("document.export", &p).unwrap())).unwrap();
|
||||
(plot.find("PU141,1270;").unwrap(), plot.find("PU423,988;").unwrap())
|
||||
};
|
||||
let (outer, inner) = starts(&mut s, json!({"format": "hpgl"}));
|
||||
assert!(outer < inner);
|
||||
let (outer, inner) = starts(&mut s, json!({"format": "hpgl", "insideFirst": true}));
|
||||
assert!(inner < outer);
|
||||
}
|
||||
|
||||
/// Export Selection plots the selected square alone (the red one, made last), from the
|
||||
/// bottom-left corner of its bounds.
|
||||
#[test]
|
||||
fn export_selection_writes_a_plot_of_the_selection() {
|
||||
let mut s = two_boards();
|
||||
let r = s.execute("document.exportSelection", &json!({"format": "hpgl"})).unwrap();
|
||||
assert_eq!(r["format"], "hpgl");
|
||||
let plot = String::from_utf8(bytes(&r)).unwrap();
|
||||
assert_eq!(plot.matches("PD").count(), 1, "{plot}");
|
||||
assert!(plot.starts_with("IN;PU;SP1;PU7,430;PD"), "{plot}");
|
||||
}
|
||||
|
||||
@@ -667,6 +667,118 @@ fn a_numbered_file_is_written_into_the_first_rows_folder() {
|
||||
assert_eq!(std::fs::read_dir(dir).unwrap().count(), 1, "one sub-folder");
|
||||
}
|
||||
|
||||
/// An export into the folder an export preset keeps, for a client whose read roots don't hold that
|
||||
/// folder: the reply leaves out the ZIP's path and names the files relative to the folder. A folder
|
||||
/// inside the read roots, and one the client gives, stay whole.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_presets_folder_outside_the_read_root_is_left_out_of_the_reply() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let mut s = session(1);
|
||||
let tmp = Folder::new("preset-roots");
|
||||
let (inside, out) = (tmp.0.join("in"), tmp.0.join("out"));
|
||||
for f in [&inside, &out] {
|
||||
std::fs::create_dir_all(f).unwrap();
|
||||
}
|
||||
let folder = out.to_string_lossy().replace('\\', "/");
|
||||
let settings = json!({"formats": [{"format": "png", "folder": "1x"}], "subfolders": true, "folder": folder});
|
||||
s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap();
|
||||
let write_only = AutomationRoots::new(&[inside.as_path()], &[out.as_path()]).unwrap();
|
||||
let both = AutomationRoots::new(&[inside.as_path(), out.as_path()], &[out.as_path()]).unwrap();
|
||||
let run = |s: &mut Session, roots: &Option<std::sync::Arc<AutomationRoots>>, p: Value| confine(roots.as_ref(), || export(s, p));
|
||||
|
||||
let r = run(&mut s, &write_only, json!({"exportPreset": "Kept"}));
|
||||
assert_eq!(r["files"], json!(["1x/Artboard-1.png"]), "{r}");
|
||||
assert!(out.join("1x/Artboard-1.png").is_file());
|
||||
let r = run(&mut s, &write_only, json!({"exportPreset": "Kept", "zip": true}));
|
||||
assert_eq!((r.get("path"), &r["files"]), (None, &json!(["1x/Artboard-1.png"])), "{r}");
|
||||
assert!(!r.to_string().contains(&folder), "{r}");
|
||||
// Inside the read roots, or given by the client: whole.
|
||||
assert_eq!(run(&mut s, &both, json!({"exportPreset": "Kept"}))["files"], json!([format!("{folder}/1x/Artboard-1.png")]));
|
||||
let r = run(&mut s, &write_only, json!({"exportPreset": "Kept", "folder": folder, "zip": true}));
|
||||
assert!(r["path"].as_str().is_some_and(|p| p.starts_with(&format!("{folder}/")) && p.ends_with(".zip")), "{r}");
|
||||
}
|
||||
|
||||
/// An export into the folder an export preset keeps, refused because that folder is outside the
|
||||
/// client's read and write roots: the error names the folder by its name only. A folder the client
|
||||
/// gives stays whole in the error.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_refused_export_into_a_presets_folder_outside_the_read_root_names_it_by_its_name() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let mut s = session(1);
|
||||
let tmp = Folder::new("preset-refused");
|
||||
let (inside, out) = (tmp.0.join("in"), tmp.0.join("kept-out"));
|
||||
for f in [&inside, &out] {
|
||||
std::fs::create_dir_all(f).unwrap();
|
||||
}
|
||||
let folder = out.to_string_lossy().replace('\\', "/");
|
||||
let settings = json!({"formats": [{"format": "png"}], "folder": folder});
|
||||
s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap();
|
||||
let confined = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap();
|
||||
let mut run = |p: Value| confine(confined.as_ref(), || s.execute("document.exportForScreens", &p)).unwrap_err().to_string();
|
||||
|
||||
let e = run(json!({"exportPreset": "Kept"}));
|
||||
assert!(e.contains("outside the write root") && e.contains("kept-out") && !e.contains(&folder), "{e}");
|
||||
let e = run(json!({"exportPreset": "Kept", "folder": folder}));
|
||||
assert!(e.contains(&folder), "{e}");
|
||||
assert_eq!(std::fs::read_dir(&out).unwrap().count(), 0, "nothing written");
|
||||
// A preset folder that holds the write root: the root stays whole in the error.
|
||||
let parent = tmp.0.to_string_lossy().replace('\\', "/");
|
||||
let settings = json!({"formats": [{"format": "png"}], "folder": parent});
|
||||
s.execute("document.exportPresets.save", &json!({"name": "Parent", "settings": settings})).unwrap();
|
||||
let e = confine(confined.as_ref(), || s.execute("document.exportForScreens", &json!({"exportPreset": "Parent"}))).unwrap_err().to_string();
|
||||
let root = inside.display().to_string();
|
||||
let name = tmp.0.file_name().unwrap().to_string_lossy().into_owned();
|
||||
assert!(e.contains(&format!("root {root}: {name}")), "{e}");
|
||||
}
|
||||
|
||||
/// The export settings the document keeps and the saved presets, read by a client whose read roots
|
||||
/// don't hold their folder: `document.exportSettings`, `document.exportPresets.list` and
|
||||
/// `document.exportPresets.export` (as data and as a file) leave out that folder and keep the rest.
|
||||
/// Inside the read roots the folder stays.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn kept_settings_leave_out_a_folder_outside_the_read_root() {
|
||||
use crate::file_access::{AutomationRoots, confine};
|
||||
|
||||
let mut s = session(1);
|
||||
let tmp = Folder::new("settings-roots");
|
||||
let (inside, out) = (tmp.0.join("in"), tmp.0.join("out"));
|
||||
for f in [&inside, &out] {
|
||||
std::fs::create_dir_all(f).unwrap();
|
||||
}
|
||||
let folder = out.to_string_lossy().replace('\\', "/");
|
||||
let settings = json!({"formats": [{"format": "svg"}], "folder": folder});
|
||||
s.execute("document.exportPresets.save", &json!({"name": "Kept", "settings": settings})).unwrap();
|
||||
export(&mut s, json!({"exportPreset": "Kept"}));
|
||||
let confined = AutomationRoots::new(&[inside.as_path()], &[inside.as_path()]).unwrap();
|
||||
let both = AutomationRoots::new(&[inside.as_path(), out.as_path()], &[inside.as_path()]).unwrap();
|
||||
let ask = |s: &mut Session, roots: &Option<std::sync::Arc<AutomationRoots>>, cmd: &str, p: Value| {
|
||||
confine(roots.as_ref(), || s.execute(cmd, &p).unwrap())
|
||||
};
|
||||
let saved = |list: &Value| list["presets"].as_array().unwrap().iter().find(|p| p["name"] == "Kept").unwrap()["settings"].clone();
|
||||
|
||||
let r = ask(&mut s, &confined, "document.exportSettings", json!({}));
|
||||
assert_eq!((r["settings"].get("folder"), &r["settings"]["formats"]), (None, &json!([{"format": "svg"}])), "{r}");
|
||||
let r = ask(&mut s, &confined, "document.exportPresets.list", json!({}));
|
||||
assert_eq!(saved(&r), json!({"formats": [{"format": "svg"}]}), "{r}");
|
||||
let r = ask(&mut s, &confined, "document.exportPresets.export", json!({"names": ["Kept"]}));
|
||||
let data = r["data"].as_str().unwrap();
|
||||
assert!(!data.contains(&folder) && data.contains("svg"), "{data}");
|
||||
let file = inside.join("kept.vcexportpresets");
|
||||
let path = file.to_string_lossy().replace('\\', "/");
|
||||
ask(&mut s, &confined, "document.exportPresets.export", json!({"names": ["Kept"], "path": path}));
|
||||
assert!(!std::fs::read_to_string(&file).unwrap().contains(&folder));
|
||||
|
||||
// Inside the read roots: whole.
|
||||
assert_eq!(ask(&mut s, &both, "document.exportSettings", json!({}))["settings"]["folder"], json!(folder));
|
||||
assert_eq!(saved(&ask(&mut s, &both, "document.exportPresets.list", json!({})))["folder"], json!(folder));
|
||||
assert!(ask(&mut s, &both, "document.exportPresets.export", json!({"names": ["Kept"]}))["data"].as_str().unwrap().contains(&folder));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn format_settings_apply_to_their_rows_and_rows_win() {
|
||||
let mut s = session(1);
|
||||
|
||||
@@ -109,6 +109,40 @@ fn unlinked(g: &Gradient) -> Gradient {
|
||||
g
|
||||
}
|
||||
|
||||
/// Give each saved preset in `saved` a name no built-in preset or earlier saved one has (any case):
|
||||
/// a clash becomes the first free "<name> N", N from 2. Returns the renames as (old, new).
|
||||
pub(crate) fn rename_clashing_presets(saved: &mut [GradientPreset]) -> Vec<(String, String)> {
|
||||
if saved.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
let builtin: std::collections::HashSet<String> = builtin_presets().map(|e| e.name.to_ascii_lowercase()).collect();
|
||||
let mut taken: std::collections::HashSet<String> =
|
||||
builtin.iter().cloned().chain(saved.iter().map(|p| p.name.trim().to_ascii_lowercase())).collect();
|
||||
let mut kept = std::collections::HashSet::new();
|
||||
// The next suffix to try for each name, so many presets with one name take linear time.
|
||||
let mut next: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
|
||||
let mut renamed = vec![];
|
||||
for p in saved {
|
||||
let key = p.name.trim().to_ascii_lowercase();
|
||||
if !builtin.contains(&key) && kept.insert(key.clone()) {
|
||||
continue;
|
||||
}
|
||||
let base = p.name.trim();
|
||||
let n = next.entry(key).or_insert(2);
|
||||
let name = loop {
|
||||
let candidate = format!("{base} {n}");
|
||||
*n += 1;
|
||||
if !taken.contains(&candidate.to_ascii_lowercase()) {
|
||||
break candidate;
|
||||
}
|
||||
};
|
||||
taken.insert(name.to_ascii_lowercase());
|
||||
kept.insert(name.to_ascii_lowercase());
|
||||
renamed.push((std::mem::replace(&mut p.name, name.clone()), name));
|
||||
}
|
||||
renamed
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The Gradient panel's presets: the built-in ones by library, then the saved ones.
|
||||
pub fn gradient_presets(&self) -> Vec<GradientPresetEntry> {
|
||||
|
||||
@@ -15,7 +15,7 @@ use vectorcraft_geom::{Affine, Rect};
|
||||
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, bool_or, check_numbers, check_switches, checked_id, checked_ids_param, cmd, color_value, f64_or, has_doc,
|
||||
has_selection, id_param, ids_param, index, ok, str_param, switch_or,
|
||||
has_selection, ids_param, index, object_param, ok, str_param, switch_or,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
@@ -426,7 +426,7 @@ fn paste_remembers_layers(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// The Layers panel's target circle.
|
||||
fn target(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "layer.target";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let st = s.doc()?;
|
||||
let n = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
if !st.doc.is_editable(id) {
|
||||
@@ -594,7 +594,7 @@ fn duplicate_rows(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn set_current(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "layer.setCurrent";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let st = s.doc_mut()?;
|
||||
let layer = st.doc.layer_containing(id).ok_or(EngineError::NoNode(id))?;
|
||||
st.active_layer = Some(layer);
|
||||
@@ -700,7 +700,7 @@ fn in_isolation(doc: &Document, isolation: Option<NodeId>, id: NodeId) -> bool {
|
||||
/// The selection column: select a row's art.
|
||||
fn select_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "layer.selectAll";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let add = switch_or(p, "add", false, C)?;
|
||||
let st = s.doc()?;
|
||||
let n = st.doc.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
@@ -747,9 +747,12 @@ enum Place {
|
||||
/// Drag rows in the Layers panel.
|
||||
fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "layer.move";
|
||||
let mut ids = ids_param(p, "ids", C)?.or_else(|| id_param(p, "id").map(|i| vec![i])).ok_or_else(|| bad(C, "missing ids"))?;
|
||||
let mut ids = match ids_param(p, "ids", C)? {
|
||||
Some(ids) => ids,
|
||||
None => vec![object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing ids"))?],
|
||||
};
|
||||
ids.truncate(MAX_ROWS);
|
||||
let target = id_param(p, "target").ok_or_else(|| bad(C, "missing target"))?;
|
||||
let target = object_param(p, "target", C)?.ok_or_else(|| bad(C, "missing target"))?;
|
||||
let place = match str_param(p, "place").unwrap_or("inside") {
|
||||
"above" => Place::Above,
|
||||
"below" => Place::Below,
|
||||
@@ -831,8 +834,8 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "node.move";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let parent = id_param(p, "parent");
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let parent = object_param(p, "parent", C)?;
|
||||
let index = p.get("index").and_then(Value::as_u64).map_or(usize::MAX, index);
|
||||
let d = &s.doc()?.doc;
|
||||
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
|
||||
|
||||
@@ -21,7 +21,7 @@ use super::expand::gradient_sampler;
|
||||
use super::pathops::Beside;
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, always, bad, check_numbers, cmd, color_param, f64_or, f64_req, finite_numbers, has_doc, has_multi,
|
||||
has_selection, id_param, named_ids, number_or, ok, str_param, switch_or, text_param,
|
||||
has_selection, named_ids, number_or, object_param, ok, str_param, switch_or, text_param,
|
||||
};
|
||||
|
||||
mod blend;
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use vectorcraft_doc::live::BlendSpineMode;
|
||||
|
||||
use super::common::{
|
||||
DEFAULT_DISTANCE, DEFAULT_STEPS, ease_param, fix_ids, ids_json, is_blend, orientation_param, percent_param, roots_param, selected_of,
|
||||
spacing_param, starts_param, wrap,
|
||||
@@ -61,6 +63,19 @@ fn extend_spine(spec: &mut BlendSpec, old: &[Arc<Node>], old_spec: &BlendSpec, k
|
||||
spec.spine = Some(path);
|
||||
}
|
||||
|
||||
/// Does `p` set easing (`easingType` or `ramp`)? Easing needs a spine.
|
||||
fn gives_easing(p: &Value) -> bool {
|
||||
["easingType", "ramp"].iter().any(|key| p.get(*key).is_some_and(|v| !v.is_null()))
|
||||
}
|
||||
|
||||
/// The Create Spine mode `p` gives as `key`, or `current` when it is omitted or null.
|
||||
fn spine_mode_param(p: &Value, cmd: &str, key: &str, current: BlendSpineMode) -> Result<BlendSpineMode> {
|
||||
match p.get(key).filter(|v| !v.is_null()) {
|
||||
None => Ok(current),
|
||||
Some(v) => v.as_str().and_then(BlendSpineMode::from_id).ok_or_else(|| bad(cmd, format!("`{key}` must be one of auto, always, never"))),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.blend.make";
|
||||
let roots = roots_param(s, p)?;
|
||||
@@ -69,16 +84,22 @@ pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let starts = starts_param(p, &roots)?;
|
||||
let base = first_blend(&s.doc()?.doc, &roots);
|
||||
let defaults = s.prefs.blend_options.unwrap_or_default();
|
||||
// Create Spine applies to a new blend; one taking more keys keeps whether it has a spine.
|
||||
let create_spine = spine_mode_param(p, C, "createSpine", defaults.create_spine)?;
|
||||
let cur = match base.as_ref().map(|n| &n.kind) {
|
||||
Some(NodeKind::Blend { spec, .. }) => BlendDefaults { spacing: spec.spacing, orientation: spec.orientation },
|
||||
_ => s.prefs.blend_options.unwrap_or_default(),
|
||||
Some(NodeKind::Blend { spec, .. }) => BlendDefaults { spacing: spec.spacing, orientation: spec.orientation, ..defaults },
|
||||
_ => defaults,
|
||||
};
|
||||
let spacing = spacing_param(p, C, cur.spacing)?;
|
||||
let orientation = orientation_param(p, cur.orientation);
|
||||
let (ease0, color0) = match base.as_ref().map(|n| &n.kind) {
|
||||
Some(NodeKind::Blend { spec, .. }) => (spec.ease, spec.color_shift),
|
||||
_ => Default::default(),
|
||||
let (ease0, color0, no_spine) = match base.as_ref().map(|n| &n.kind) {
|
||||
Some(NodeKind::Blend { spec, .. }) => (spec.ease, spec.color_shift, spec.no_spine),
|
||||
_ => (Default::default(), 0.0, !create_spine.creates_spine()),
|
||||
};
|
||||
if no_spine && gives_easing(p) {
|
||||
return Err(bad(C, "the blend has no spine"));
|
||||
}
|
||||
let ease = ease_param(p, C, ease0)?;
|
||||
let color_shift = percent_param(p, C, "colorShift", color0, -100.0)?;
|
||||
let id = s.edit("Make Blend", |d, sel| {
|
||||
@@ -91,7 +112,7 @@ pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
n.knockout = vectorcraft_doc::Knockout::On;
|
||||
n
|
||||
});
|
||||
let mut spec = BlendSpec { spacing, orientation, ease, color_shift, starts, ..Default::default() };
|
||||
let mut spec = BlendSpec { spacing, orientation, ease, color_shift, starts, no_spine, ..Default::default() };
|
||||
if let NodeKind::Blend { children: old, spec: old_spec } = &n.kind {
|
||||
extend_spine(&mut spec, old, old_spec, &children);
|
||||
}
|
||||
@@ -303,7 +324,11 @@ pub(super) fn spine_remove_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if anchors.contains(&index) {
|
||||
return Err(bad(C, "a key object sits on that point"));
|
||||
}
|
||||
if sp.anchors.len() <= 2 {
|
||||
// A closed spine pinned open keeps a copy of its first point at its end (#6809), so the
|
||||
// points left must be two apart, not only two in number.
|
||||
let mut rest = sp.anchors.iter().enumerate().filter(|(i, _)| *i != index).map(|(_, a)| a.p);
|
||||
let first = rest.next();
|
||||
if sp.anchors.len() <= 2 || first.is_none_or(|f| rest.all(|q| q.distance(f) < 0.01)) {
|
||||
return Err(bad(C, "a spine keeps at least two points"));
|
||||
}
|
||||
sp.anchors.remove(index);
|
||||
@@ -346,9 +371,12 @@ pub(super) fn blend_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Nothing to set them on: the options new blends start with (easing is per blend).
|
||||
let d = s.prefs.blend_options.unwrap_or_default();
|
||||
let spacing = spacing_param(p, C, d.spacing)?;
|
||||
s.prefs.blend_options = Some(BlendDefaults { spacing, orientation: orientation_param(p, d.orientation) });
|
||||
s.prefs.blend_options = Some(BlendDefaults { spacing, orientation: orientation_param(p, d.orientation), ..d });
|
||||
return Ok(json!({ "defaults": true }));
|
||||
};
|
||||
if gives_easing(p) && any_without_spine(s) {
|
||||
return Err(bad(C, "the blend has no spine"));
|
||||
}
|
||||
let spacing = spacing_param(p, C, cur.spacing)?;
|
||||
let orientation = orientation_param(p, cur.orientation);
|
||||
let ease = ease_param(p, C, cur.ease)?;
|
||||
@@ -384,6 +412,7 @@ pub(super) fn blend_info(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
v["colorShift"] = json!(spec.color_shift);
|
||||
v["starts"] = json!((0..keys.len()).map(|i| spec.start(i)).collect::<Vec<_>>());
|
||||
v["keys"] = json!(keys.iter().map(|k| k.0).collect::<Vec<_>>());
|
||||
v["hasSpine"] = json!(!spec.no_spine);
|
||||
if let Some(NodeKind::Blend { children, .. }) = s.doc()?.doc.node(id).map(|n| &n.kind)
|
||||
&& let Some((path, anchors)) = live::blend_spine(children, &spec)
|
||||
&& let Some(sp) = path.subpaths.first()
|
||||
@@ -403,6 +432,19 @@ pub(super) fn blend_info(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The Blend panel's Create Spine: with `mode`, sets whether new blends get a spine; without, reads
|
||||
/// it. A tool setting kept with the preferences, not an undo step; blends already made keep theirs.
|
||||
pub(super) fn blend_create_spine(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.blend.createSpine";
|
||||
let mut d = s.prefs.blend_options.unwrap_or_default();
|
||||
let mode = spine_mode_param(p, C, "mode", d.create_spine)?;
|
||||
if mode != d.create_spine {
|
||||
d.create_spine = mode;
|
||||
s.prefs.blend_options = Some(d);
|
||||
}
|
||||
Ok(json!({ "mode": mode.id() }))
|
||||
}
|
||||
|
||||
pub(super) fn blend_expand(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let blends = selected_of(s, is_blend);
|
||||
let ids = s.edit("Expand Blend", |d, sel| {
|
||||
@@ -507,6 +549,8 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let spine = d.node(path).and_then(|n| n.path_data().cloned()).ok_or(EngineError::NoNode(path))?;
|
||||
d.remove(path)?;
|
||||
if let Some(NodeKind::Blend { children, spec }) = d.node_mut(b).map(|n| &mut n.kind) {
|
||||
// A blend made without a spine gets this one.
|
||||
spec.no_spine = false;
|
||||
spec.spine = Some(spine);
|
||||
spec.key_anchors.clear();
|
||||
keys_to_spine(children, spec);
|
||||
@@ -517,7 +561,16 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Is any selected blend one made without a spine?
|
||||
fn any_without_spine(s: &Session) -> bool {
|
||||
let Ok(st) = s.doc() else { return false };
|
||||
selected_of(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine))
|
||||
}
|
||||
|
||||
pub(super) fn blend_reverse_spine(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
if any_without_spine(s) {
|
||||
return Err(bad("object.blend.reverseSpine", "the blend has no spine"));
|
||||
}
|
||||
edit_blends(s, "Reverse Spine", |children, spec| {
|
||||
if spec.spine.is_some() && pin(children, spec) {
|
||||
// The keys keep their anchors, which now count from the other end.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::blend::{
|
||||
blend_expand, blend_info, blend_make, blend_options, blend_release, blend_replace_spine, blend_reverse_spine, blend_reverse_stack,
|
||||
spine_add_anchor, spine_convert_anchor, spine_move_anchor, spine_remove_anchor, spine_reshape_segment,
|
||||
blend_create_spine, blend_expand, blend_info, blend_make, blend_options, blend_release, blend_replace_spine, blend_reverse_spine,
|
||||
blend_reverse_stack, spine_add_anchor, spine_convert_anchor, spine_move_anchor, spine_remove_anchor, spine_reshape_segment,
|
||||
};
|
||||
use super::common::{has_blend, has_envelope, has_mesh};
|
||||
use super::envelope::{
|
||||
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Blend"],
|
||||
Some("Cmd+Alt+B"),
|
||||
"{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name and transparency) instead of nesting → {id}",
|
||||
"{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even), createSpine?: auto|always|never (default: the mode object.blend.createSpine sets; never: a blend without a spine, which takes no easing)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name, transparency and whether it has a spine) instead of nesting → {id}",
|
||||
has_doc,
|
||||
blend_make
|
||||
),
|
||||
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Release",
|
||||
["Object", "Blend"],
|
||||
Some("Cmd+Alt+Shift+B"),
|
||||
"{} release the selected blends: the key objects come back and the spine stays as a path with no fill or stroke, below them; a blend with a name, opacity, blend mode, isolation, opacity mask or appearance of its own comes back as a group keeping them (and its knockout) → {ids (the keys), spines: [ids], groups: [ids]}",
|
||||
"{} release the selected blends: the key objects come back and the spine (if the blend has one) stays as a path with no fill or stroke, below them; a blend with a name, opacity, blend mode, isolation, opacity mask or appearance of its own comes back as a group keeping them (and its knockout) → {ids (the keys), spines: [ids], groups: [ids]}",
|
||||
has_blend,
|
||||
blend_release
|
||||
),
|
||||
@@ -40,6 +40,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
blend_options
|
||||
),
|
||||
cmd!(
|
||||
"object.blend.createSpine",
|
||||
"Create Spine",
|
||||
[],
|
||||
None,
|
||||
"{mode?: auto|always|never} the Blend panel's Create Spine: whether new blends get a spine (auto and always: the straight lines between the key centers, as before; never: no spine to show, edit, reverse or release, and no easing, until Replace Spine gives one); with no `mode`, reads it; blends already made keep theirs (a tool setting kept with the preferences, not an undo step) → {mode}",
|
||||
always,
|
||||
blend_create_spine
|
||||
),
|
||||
cmd!(
|
||||
"object.blend.expand",
|
||||
"Expand",
|
||||
@@ -54,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Replace Spine",
|
||||
["Object", "Blend"],
|
||||
None,
|
||||
"{} use the selected path as the spine of the selected blend (the path is consumed)",
|
||||
"{} use the selected path as the spine of the selected blend (the path is consumed); a blend made without a spine gets this one",
|
||||
has_blend,
|
||||
blend_replace_spine
|
||||
),
|
||||
@@ -63,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reverse Spine",
|
||||
["Object", "Blend"],
|
||||
None,
|
||||
"{} reverse the order of the key objects along the spine",
|
||||
"{} reverse the order of the key objects along the spine; an error when a selected blend has no spine",
|
||||
has_blend,
|
||||
blend_reverse_spine
|
||||
),
|
||||
@@ -72,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Blend Info",
|
||||
[],
|
||||
None,
|
||||
"{} the options of the first selected blend, else those new blends start with → {target: blend|defaults, id?, spacing: smooth|steps|distance, steps, distance, orientation: page|path, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct, keys?: [ids], starts?: [anchor|null], spine?: {anchors: [{x, y, in: [x, y], out: [x, y]}], closed, keyAnchors: [anchor each key sits on] | null (keys spread evenly: a spine from Replace Spine), explicit: false for the straight lines between the key centres}}",
|
||||
"{} the options of the first selected blend, else those new blends start with → {target: blend|defaults, id?, spacing: smooth|steps|distance, steps, distance, orientation: page|path, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct, keys?: [ids], starts?: [anchor|null], hasSpine?: false for a blend made without a spine (no `spine` then), spine?: {anchors: [{x, y, in: [x, y], out: [x, y]}], closed, keyAnchors: [anchor each key sits on] | null (keys spread evenly: a spine from Replace Spine), explicit: false for the straight lines between the key centres}}",
|
||||
always,
|
||||
blend_info
|
||||
),
|
||||
|
||||
@@ -3,7 +3,7 @@ use super::common::{fix_ids, ids_json, is_envelope, roots_param, selected_of, wr
|
||||
use super::mesh::{handle_param, index_param, whole};
|
||||
use super::{
|
||||
Affine, Appearance, Arc, Beside, Color, Document, EngineError, EnvelopeKind, EnvelopeMap, EnvelopeOptions, Node, NodeId, NodeKind, Paint,
|
||||
PathData, Point, PreserveShape, Result, Session, Value, bad, check_numbers, f64_or, f64_req, id_param, json, live, ok, switch_or, text_param,
|
||||
PathData, Point, PreserveShape, Result, Session, Value, bad, check_numbers, f64_or, f64_req, json, live, object_param, ok, switch_or, text_param,
|
||||
};
|
||||
|
||||
// ---------- Envelope ----------
|
||||
@@ -419,7 +419,7 @@ pub(super) fn env_edit_contents(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
pub(super) fn env_set_mesh_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.envelope.setMeshPoint";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
let index = index_param(p, "index", C)?;
|
||||
let q = Point::new(f64_req(p, "x", C)?, f64_req(p, "y", C)?);
|
||||
let handle = handle_param(p, C)?;
|
||||
|
||||
@@ -4,7 +4,7 @@ use super::common::{fix_ids, ids_json, is_mesh, replace_with, roots_param, selec
|
||||
use super::envelope::{outline_of, rows_cols};
|
||||
use super::{
|
||||
Color, Document, EngineError, EnvelopeKind, GradientMesh, MeshAppearance, Node, NodeId, NodeKind, Paint, Point, Result, Session, Value, bad,
|
||||
check_numbers, color_param, f64_or, f64_req, finite_numbers, gradient_sampler, id_param, json, live, ok, str_param,
|
||||
check_numbers, color_param, f64_or, f64_req, finite_numbers, gradient_sampler, json, live, object_param, ok, str_param,
|
||||
};
|
||||
|
||||
// ---------- Gradient mesh ----------
|
||||
@@ -115,7 +115,7 @@ fn image_mesh(d: &Document, im: &vectorcraft_doc::ImageObject, rows: u32, cols:
|
||||
/// Run `f` on the gradient mesh `p.id` (one undo step `label`); with `envelopes`, a mesh
|
||||
/// envelope's grid too (see [`edit_grid`]).
|
||||
fn with_mesh<T>(s: &mut Session, p: &Value, cmd: &str, label: &str, envelopes: bool, f: impl FnOnce(&mut GradientMesh) -> Result<T>) -> Result<T> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(cmd, "missing `id`"))?;
|
||||
let id = object_param(p, "id", cmd)?.ok_or_else(|| bad(cmd, "missing `id`"))?;
|
||||
s.edit(label, move |d, _| edit_grid(d, id, cmd, envelopes, f))
|
||||
}
|
||||
|
||||
@@ -147,7 +147,7 @@ const MAX_POINTS: usize = 1 << 20;
|
||||
/// points}…]}`. Each mesh comes once, with its points in order and without repeats.
|
||||
fn point_items(p: &Value, cmd: &str) -> Result<Vec<(NodeId, BTreeSet<usize>)>> {
|
||||
let one = |q: &Value| -> Result<(NodeId, BTreeSet<usize>)> {
|
||||
let id = id_param(q, "id").ok_or_else(|| bad(cmd, "missing `id`"))?;
|
||||
let id = object_param(q, "id", cmd)?.ok_or_else(|| bad(cmd, "missing `id`"))?;
|
||||
let points = match q.get("points") {
|
||||
None | Some(Value::Null) => BTreeSet::from([index_param(q, "index", cmd)?]),
|
||||
Some(Value::Array(v)) if v.len() <= MAX_POINTS => v
|
||||
|
||||
@@ -1306,13 +1306,16 @@ fn convert_to_artboards(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let symbols = d.symbol_boxes();
|
||||
let boxes: Vec<(NodeId, Rect)> = roots.iter().filter_map(|id| Some((*id, d.node(*id)?.geometric_bounds_with(&symbols)?))).collect();
|
||||
let mut converted = vec![];
|
||||
// The highest artboard id the document has, kept up to date as artboards are added.
|
||||
let mut top = d.artboards.iter().map(|a| a.id).max();
|
||||
for (id, b) in boxes {
|
||||
if b.width() <= 0.0 || b.height() <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
// Named one past the highest artboard id the document has, whatever id it is given.
|
||||
let number = d.artboards.iter().map(|a| a.id).max().map_or(1, |m| m.saturating_add(1));
|
||||
let aid = d.next_artboard_id();
|
||||
let number = top.map_or(1, |m| m.saturating_add(1));
|
||||
let aid = d.next_artboard_id_above(top);
|
||||
top = top.max(Some(aid));
|
||||
d.artboards.push(vectorcraft_doc::Artboard {
|
||||
id: aid,
|
||||
name: format!("Artboard {number}"),
|
||||
|
||||
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reflect…",
|
||||
["Object", "Transform"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg, origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
"{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg (the mirror line, counter-clockwise from horizontal; 0: horizontal; omitted: vertical), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
|
||||
has_selection,
|
||||
reflect
|
||||
),
|
||||
|
||||
@@ -12,7 +12,7 @@ use vectorcraft_doc::{Document, LinkInfo};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::fileio::{create_dir, write_file};
|
||||
use super::fileio::{create_dir, document_path, shown_link, shown_path, write_file};
|
||||
use super::links::LinkBase;
|
||||
use super::{CommandSpec, Result, Session, bad, cmd, has_doc, switch_or, text_param, unique_name};
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Package",
|
||||
[],
|
||||
None,
|
||||
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder",
|
||||
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name",
|
||||
has_doc,
|
||||
package
|
||||
)]
|
||||
@@ -178,8 +178,10 @@ impl<'a> Collector<'a> {
|
||||
|
||||
/// Warns when a file that placed `.ai` file `source` links (`name`) was copied as `copy`: the
|
||||
/// copy of `source` finds it only by its name, beside it.
|
||||
/// `path` is the link's path as the warning names it.
|
||||
fn renamed(&mut self, lines: &mut Vec<String>, source: &str, path: &str, name: &str, copy: &str) {
|
||||
if Path::new(copy).file_name().and_then(std::ffi::OsStr::to_str) != Some(name) {
|
||||
let source = shown_path(source);
|
||||
let message = format!(
|
||||
"{path}: copied as {copy}; the copy of {source} looks for it as {name} and shows the file of that name, if any, else its preview"
|
||||
);
|
||||
@@ -207,11 +209,13 @@ impl<'a> Collector<'a> {
|
||||
let section = self.sections.len();
|
||||
self.sections.push(vec![]);
|
||||
let mut lines = vec![];
|
||||
// The packaged document's sections read as before; a placed document's name its file.
|
||||
// The packaged document's sections read as before; a placed document's name its file. The
|
||||
// report and the warnings name a file outside a confined request's read roots by its name.
|
||||
let shown_source = shown_path(source);
|
||||
let heading = |lines: &mut Vec<String>, title: &str| {
|
||||
lines.push(title.into());
|
||||
if depth > 0 {
|
||||
lines.push(format!("Document: {source}"));
|
||||
lines.push(format!("Document: {shown_source}"));
|
||||
}
|
||||
};
|
||||
// A file's saved path is only meaningful inside its own document.
|
||||
@@ -243,17 +247,21 @@ impl<'a> Collector<'a> {
|
||||
heading(&mut lines, "LINKED FILES");
|
||||
for file in linked_files(doc) {
|
||||
let found_path = file.found_path.as_deref().unwrap_or(&file.path);
|
||||
// The stored path, whole when the place it names (read from this document's folder) is
|
||||
// inside the read roots. A file found elsewhere does not show a stored path outside them.
|
||||
let resolved = document_path(&file.path, Some(source)).ok();
|
||||
let shown = shown_link(&file.path, resolved.as_deref()).into_owned();
|
||||
if let Some(ancestor) = self.visiting.get(found_path).cloned() {
|
||||
// The ancestor is already included (possibly the root document). A
|
||||
// cyclic reference cannot have a final content hash until both files
|
||||
// have been written, so leave its size/hash unspecified, not stale.
|
||||
self.warn(&mut lines, format!("{}: circular placed-document link to {ancestor}; stopped following the cycle", file.path));
|
||||
self.warn(&mut lines, format!("{shown}: circular placed-document link to {ancestor}; stopped following the cycle"));
|
||||
local.insert(file.path.clone(), Copied { name: ancestor, size: None, hash: None });
|
||||
continue;
|
||||
}
|
||||
if let Some(existing) = self.copies.get(found_path).cloned() {
|
||||
if by_name {
|
||||
self.renamed(&mut lines, source, &file.path, &file.name, &existing.name);
|
||||
self.renamed(&mut lines, source, &shown, &file.name, &existing.name);
|
||||
}
|
||||
// Another document may place other pages of a PDF copied already.
|
||||
if self.opts.copy_fonts
|
||||
@@ -265,8 +273,8 @@ impl<'a> Collector<'a> {
|
||||
continue;
|
||||
}
|
||||
let Some(mut bytes) = file.bytes else {
|
||||
lines.push(format!("{}: not found ({}), not copied", file.name, file.path));
|
||||
self.missing.push(if depth == 0 { file.name.clone() } else { format!("{} ({source})", file.name) });
|
||||
lines.push(format!("{}: not found ({shown}), not copied", file.name));
|
||||
self.missing.push(if depth == 0 { file.name.clone() } else { format!("{} ({shown_source})", file.name) });
|
||||
continue;
|
||||
};
|
||||
if self.copies.len() >= 10_000 {
|
||||
@@ -277,7 +285,7 @@ impl<'a> Collector<'a> {
|
||||
let unique = free_name(&name, if self.opts.links_folder { &mut self.link_names } else { &mut self.taken });
|
||||
let destination_file = format!("{dir}{unique}");
|
||||
if by_name {
|
||||
self.renamed(&mut lines, source, &file.path, &file.name, &destination_file);
|
||||
self.renamed(&mut lines, source, &shown, &file.name, &destination_file);
|
||||
}
|
||||
// A placed PDF or .ai file is copied as it is, as an image is; the files a .ai file
|
||||
// read from its editing data links are copied beside it.
|
||||
@@ -285,7 +293,7 @@ impl<'a> Collector<'a> {
|
||||
let placed_file = pages.is_some();
|
||||
if placed_file && let Some(mut art) = super::place::document::editing_data(&file.name, &bytes) {
|
||||
if depth >= vectorcraft_doc::placed_document::MAX_DEPTH {
|
||||
self.warn(&mut lines, format!("{}: nesting limit reached; copied unchanged without collecting its own links", file.path));
|
||||
self.warn(&mut lines, format!("{shown}: nesting limit reached; copied unchanged without collecting its own links"));
|
||||
} else {
|
||||
self.collect(&mut art, found_path, &destination_file, depth + 1, true, None)?;
|
||||
}
|
||||
@@ -296,7 +304,7 @@ impl<'a> Collector<'a> {
|
||||
}
|
||||
if placed_file && super::place::document::is_native(&file.name, &bytes) {
|
||||
if depth >= vectorcraft_doc::placed_document::MAX_DEPTH {
|
||||
self.warn(&mut lines, format!("{}: nesting limit reached; copied unchanged without collecting its own links", file.path));
|
||||
self.warn(&mut lines, format!("{shown}: nesting limit reached; copied unchanged without collecting its own links"));
|
||||
} else {
|
||||
match vectorcraft_format::load_file(&bytes) {
|
||||
Ok(saved) => {
|
||||
@@ -320,8 +328,7 @@ impl<'a> Collector<'a> {
|
||||
Err(e) => self.warn(
|
||||
&mut lines,
|
||||
format!(
|
||||
"{}: could not rewrite linked document ({e}); copied unchanged, its own links were not relinked",
|
||||
file.path
|
||||
"{shown}: could not rewrite linked document ({e}); copied unchanged, its own links were not relinked"
|
||||
),
|
||||
),
|
||||
}
|
||||
@@ -329,7 +336,7 @@ impl<'a> Collector<'a> {
|
||||
}
|
||||
Err(e) => self.warn(
|
||||
&mut lines,
|
||||
format!("{}: unreadable linked document ({e}); copied unchanged, its own links were not collected", file.path),
|
||||
format!("{shown}: unreadable linked document ({e}); copied unchanged, its own links were not collected"),
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -337,7 +344,7 @@ impl<'a> Collector<'a> {
|
||||
let copy = Copied { name: destination_file.clone(), size: Some(bytes.len() as u64), hash: Some(hash_bytes(&bytes)) };
|
||||
self.copies.insert(found_path.to_string(), copy.clone());
|
||||
local.insert(file.path.clone(), copy);
|
||||
lines.push(format!("{} → {destination_file}", file.path));
|
||||
lines.push(format!("{shown} → {destination_file}"));
|
||||
self.entries.push((destination_file, bytes));
|
||||
}
|
||||
lines.push(String::new());
|
||||
@@ -518,7 +525,7 @@ fn collect_and_write(package: Package, write: &mut dyn FnMut(&str, &[u8]) -> Res
|
||||
// The report.
|
||||
if let Some(info) = info {
|
||||
let report_name = free_name(&format!("{stem} Report.txt"), &mut taken);
|
||||
let mut text = format!("Package: {doc_name}\nFrom: {doc_path}\n\n");
|
||||
let mut text = format!("Package: {doc_name}\nFrom: {}\n\n", shown_path(&doc_path));
|
||||
lines.iter().for_each(|l| text.push_str(&format!("{l}\n")));
|
||||
text.push_str(&info);
|
||||
entries.push((report_name, text.into_bytes()));
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -12,7 +12,7 @@ use super::draw2::usize_opt;
|
||||
use super::pathops::Beside;
|
||||
use super::{
|
||||
CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_anchors, has_doc, has_selected_path,
|
||||
has_selection, id_param, ids_param, index, number_or, ok, str_param, switch_or, targets,
|
||||
has_selection, ids_param, index, number_or, object_param, ok, str_param, switch_or, targets,
|
||||
};
|
||||
use crate::EngineError;
|
||||
|
||||
@@ -168,7 +168,7 @@ pub(super) fn path_mut(d: &mut vectorcraft_doc::Document, id: NodeId) -> Result<
|
||||
}
|
||||
|
||||
fn append_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad("path.appendAnchor", "missing id"))?;
|
||||
let id = object_param(p, "id", "path.appendAnchor")?.ok_or_else(|| bad("path.appendAnchor", "missing id"))?;
|
||||
let a = anchor_from_json(p, "path.appendAnchor")?;
|
||||
let subpath = p.get("subpath").and_then(Value::as_u64).map(|u| u as usize);
|
||||
s.edit("Pen", |d, sel| {
|
||||
@@ -206,7 +206,7 @@ fn append_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// incoming handle moves as Move Direction Handle moves it: the outgoing handle turns with it only
|
||||
/// on a smooth anchor, so the first segment of a path that starts at a corner keeps its shape.
|
||||
fn close(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad("path.close", "missing id"))?;
|
||||
let id = object_param(p, "id", "path.close")?.ok_or_else(|| bad("path.close", "missing id"))?;
|
||||
let subpath = p.get("subpath").and_then(Value::as_u64).map(|u| u as usize);
|
||||
let handle = |key: &str| match p.get(key).filter(|h| !h.is_null()) {
|
||||
None => Ok(None),
|
||||
@@ -303,7 +303,7 @@ pub(crate) fn transform_anchors(s: &mut Session, label: &str, xf: vectorcraft_ge
|
||||
}
|
||||
|
||||
fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad("path.setHandle", "missing id"))?;
|
||||
let id = object_param(p, "id", "path.setHandle")?.ok_or_else(|| bad("path.setHandle", "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", "path.setHandle")?.unwrap_or(0);
|
||||
let ai = p.get("anchor").and_then(Value::as_u64).map(index).ok_or_else(|| bad("path.setHandle", "missing anchor"))?;
|
||||
let out = str_param(p, "which") != Some("in");
|
||||
@@ -321,7 +321,7 @@ fn set_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
/// `path.moveAnchor`: one anchor to (x, y), its handles keeping their offsets (the Anchor Point
|
||||
/// tool's Shift-drag).
|
||||
fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad("path.moveAnchor", "missing id"))?;
|
||||
let id = object_param(p, "id", "path.moveAnchor")?.ok_or_else(|| bad("path.moveAnchor", "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", "path.moveAnchor")?.unwrap_or(0);
|
||||
let ai = p.get("anchor").and_then(Value::as_u64).map(index).ok_or_else(|| bad("path.moveAnchor", "missing anchor"))?;
|
||||
let pos = Point::new(f64_req(p, "x", "path.moveAnchor")?, f64_req(p, "y", "path.moveAnchor")?);
|
||||
@@ -341,7 +341,7 @@ fn move_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn set_anchors(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad("path.setAnchors", "missing id"))?;
|
||||
let id = object_param(p, "id", "path.setAnchors")?.ok_or_else(|| bad("path.setAnchors", "missing id"))?;
|
||||
let subs = p.get("subpaths").and_then(Value::as_array).ok_or_else(|| bad("path.setAnchors", "missing subpaths"))?;
|
||||
let data = PathData::new(
|
||||
subs.iter()
|
||||
@@ -1562,7 +1562,7 @@ fn renumber_after_insert(sel: &mut Selection, id: NodeId, si: usize, added: usiz
|
||||
}
|
||||
|
||||
fn reshape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad("path.reshape", "missing id"))?;
|
||||
let id = object_param(p, "id", "path.reshape")?.ok_or_else(|| bad("path.reshape", "missing id"))?;
|
||||
let at = Point::new(f64_req(p, "x", "path.reshape")?, f64_req(p, "y", "path.reshape")?);
|
||||
check_numbers(p, &["dx", "dy", "tol", "radius"], "path.reshape")?;
|
||||
let delta = Vec2::new(f64_or(p, "dx", 0.0), f64_or(p, "dy", 0.0));
|
||||
@@ -1684,7 +1684,7 @@ fn reshape(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn insert_anchor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad("path.insertAnchor", "missing id"))?;
|
||||
let id = object_param(p, "id", "path.insertAnchor")?.ok_or_else(|| bad("path.insertAnchor", "missing id"))?;
|
||||
let si = usize_opt(p, "subpath", "path.insertAnchor")?.unwrap_or(0);
|
||||
let seg = p.get("segment").and_then(Value::as_u64).map(index).ok_or_else(|| bad("path.insertAnchor", "missing segment"))?;
|
||||
let t = number_or(p, "t", 0.5, "path.insertAnchor")?.clamp(0.0, 1.0);
|
||||
|
||||
@@ -23,8 +23,10 @@ pub struct BuiltinPatternLibrary {
|
||||
}
|
||||
|
||||
/// The built-in pattern libraries (Window → Swatch Libraries → Patterns), in menu order.
|
||||
pub const PATTERN_LIBRARIES: &[BuiltinPatternLibrary] =
|
||||
&[BuiltinPatternLibrary { id: "geometric-patterns", name: "Geometric Patterns", make: geometric_patterns }];
|
||||
pub const PATTERN_LIBRARIES: &[BuiltinPatternLibrary] = &[
|
||||
BuiltinPatternLibrary { id: "geometric-patterns", name: "Geometric Patterns", make: geometric_patterns },
|
||||
BuiltinPatternLibrary { id: "grit-textures", name: "Grit Textures", make: grit_textures },
|
||||
];
|
||||
|
||||
/// The library category of the built-in pattern libraries.
|
||||
pub const CATEGORY: &str = "patterns";
|
||||
@@ -154,6 +156,106 @@ fn geometric_patterns(d: &mut Document) {
|
||||
add(d, "Zigzag", 10.0, 8.0, TileType::Grid, vec![polygon(&[(0.0, 5.0), (5.0, 1.0), (10.0, 5.0), (10.0, 7.0), (5.0, 3.0), (0.0, 7.0)])]);
|
||||
}
|
||||
|
||||
/// SplitMix64, a small generator with a fixed seed per pattern, so a grit pattern draws the same
|
||||
/// marks every time it is made.
|
||||
struct SplitMix64(u64);
|
||||
|
||||
impl SplitMix64 {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
/// A number from `lo` up to, but not including, `hi`.
|
||||
fn range(&mut self, lo: f64, hi: f64) -> f64 {
|
||||
lo + (self.next() >> 11) as f64 / (1u64 << 53) as f64 * (hi - lo)
|
||||
}
|
||||
}
|
||||
|
||||
/// A round dot of radius `r` at (`x`, `y`).
|
||||
fn dot(x: f64, y: f64, r: f64) -> PathData {
|
||||
shapes::ellipse(Rect::new(x - r, y - r, x + r, y + r))
|
||||
}
|
||||
|
||||
/// An irregular fleck of four to seven corners about (`x`, `y`), at most `r` from it.
|
||||
fn fleck(rng: &mut SplitMix64, x: f64, y: f64, r: f64) -> PathData {
|
||||
use std::f64::consts::TAU;
|
||||
let n = 4 + (rng.next() % 4) as usize;
|
||||
let turn = rng.range(0.0, TAU);
|
||||
let points: Vec<(f64, f64)> = (0..n)
|
||||
.map(|k| {
|
||||
let a = turn + TAU * (k as f64 + rng.range(-0.3, 0.3)) / n as f64;
|
||||
let reach = r * rng.range(0.55, 1.0);
|
||||
(x + reach * a.cos(), y + reach * a.sin())
|
||||
})
|
||||
.collect();
|
||||
polygon(&points)
|
||||
}
|
||||
|
||||
/// A thin straight scratch `len` long and `width` wide, centered on (`x`, `y`) at a random angle.
|
||||
fn scratch(rng: &mut SplitMix64, x: f64, y: f64, len: f64, width: f64) -> PathData {
|
||||
let (s, c) = rng.range(0.0, std::f64::consts::PI).sin_cos();
|
||||
let (hx, hy, wx, wy) = (c * len / 2.0, s * len / 2.0, -s * width / 2.0, c * width / 2.0);
|
||||
polygon(&[(x - hx - wx, y - hy - wy), (x + hx - wx, y + hy - wy), (x + hx + wx, y + hy + wy), (x - hx + wx, y - hy + wy)])
|
||||
}
|
||||
|
||||
/// A grit pattern of `count` marks scattered over a square grid tile of side `size`, drawn from
|
||||
/// `seed` (`mark` draws one at a point). A mark that reaches past an edge is kept whole: the tiling
|
||||
/// draws the part outside the tile on the next tile, so the tiles join without a seam.
|
||||
fn grit(d: &mut Document, name: &str, size: f64, seed: u64, count: usize, mark: impl Fn(&mut SplitMix64, f64, f64) -> PathData) {
|
||||
let mut rng = SplitMix64(seed);
|
||||
let marks = (0..count)
|
||||
.map(|_| {
|
||||
let (x, y) = (rng.range(0.0, size), rng.range(0.0, size));
|
||||
mark(&mut rng, x, y)
|
||||
})
|
||||
.collect();
|
||||
add(d, name, size, size, TileType::Grid, marks);
|
||||
}
|
||||
|
||||
/// Grit Textures: seamless black grain, grit, sand, speckle, stipple, scratch and fleck textures on
|
||||
/// a clear background, each drawn from its own fixed seed.
|
||||
fn grit_textures(d: &mut Document) {
|
||||
grit(d, "Fine Grain", 24.0, 1, 320, |rng, x, y| dot(x, y, rng.range(0.15, 0.35)));
|
||||
grit(d, "Coarse Grit", 30.0, 2, 150, |rng, x, y| {
|
||||
let r = rng.range(0.45, 1.1);
|
||||
fleck(rng, x, y, r)
|
||||
});
|
||||
grit(d, "Sand", 24.0, 3, 280, |rng, x, y| {
|
||||
let r = rng.range(0.2, 0.45);
|
||||
fleck(rng, x, y, r)
|
||||
});
|
||||
grit(d, "Speckle", 30.0, 4, 90, |rng, x, y| dot(x, y, rng.range(0.3, 0.9)));
|
||||
// Stipple: one dot in each cell of a 12 × 12 grid, moved a little off the cell's center.
|
||||
let mut rng = SplitMix64(5);
|
||||
let (size, cells) = (24.0, 12);
|
||||
let step = size / f64::from(cells);
|
||||
let dots = (0..cells)
|
||||
.flat_map(|row| (0..cells).map(move |col| (col, row)))
|
||||
.map(|(col, row)| {
|
||||
let x = (f64::from(col) + 0.5) * step + rng.range(-0.3, 0.3) * step;
|
||||
let y = (f64::from(row) + 0.5) * step + rng.range(-0.3, 0.3) * step;
|
||||
dot(x, y, rng.range(0.3, 0.45))
|
||||
})
|
||||
.collect();
|
||||
add(d, "Stipple", size, size, TileType::Grid, dots);
|
||||
grit(d, "Scratches", 36.0, 6, 45, |rng, x, y| {
|
||||
let (len, width) = (rng.range(2.0, 7.0), rng.range(0.15, 0.35));
|
||||
scratch(rng, x, y, len, width)
|
||||
});
|
||||
grit(d, "Sparse Flecks", 36.0, 7, 32, |rng, x, y| {
|
||||
let r = rng.range(0.35, 0.8);
|
||||
fleck(rng, x, y, r)
|
||||
});
|
||||
grit(d, "Dense Flecks", 18.0, 8, 220, |rng, x, y| {
|
||||
let r = rng.range(0.2, 0.5);
|
||||
fleck(rng, x, y, r)
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -168,4 +270,60 @@ mod tests {
|
||||
assert_eq!(existing_pattern(&d, &lib, "Dots").as_deref(), expected, "{other}");
|
||||
}
|
||||
}
|
||||
|
||||
fn grit_doc() -> Document {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
grit_textures(&mut d);
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grit_textures_draw_the_same_marks_every_time() {
|
||||
let (a, b) = (grit_doc(), grit_doc());
|
||||
assert_eq!(a.patterns.len(), 8);
|
||||
assert_eq!(a.patterns, b.patterns);
|
||||
}
|
||||
|
||||
/// Every grit tile is 18 to 36 pt with at most 600 marks, each with an area, touching the tile
|
||||
/// and near it. Marks reach past the edges, and the tiling draws a tile's art on the next tile
|
||||
/// across each edge a mark crosses. No mark is another mark moved by a whole tile, which the tiling would draw
|
||||
/// twice in one place.
|
||||
#[test]
|
||||
fn grit_tiles_join_without_a_seam() {
|
||||
let mut crossing = 0;
|
||||
for p in &grit_doc().patterns {
|
||||
let (w, h) = (p.width(), p.height());
|
||||
assert!((18.0..=36.0).contains(&w) && w == h && p.tile.x0 == 0.0 && p.tile.y0 == 0.0, "{}", p.name);
|
||||
assert!(!p.art.is_empty() && p.art.len() <= 600, "{}: {} marks", p.name, p.art.len());
|
||||
let bounds: Vec<Rect> = p
|
||||
.art
|
||||
.iter()
|
||||
.map(|n| match &n.kind {
|
||||
vectorcraft_doc::NodeKind::Path { path, .. } => path.bounds().unwrap_or_else(|| panic!("{}: an empty mark", p.name)),
|
||||
_ => panic!("{}: a mark that is not a path", p.name),
|
||||
})
|
||||
.collect();
|
||||
let near = |a: &Rect, b: Rect| {
|
||||
(a.x0 - b.x0).abs() < 1e-9 && (a.y0 - b.y0).abs() < 1e-9 && (a.x1 - b.x1).abs() < 1e-9 && (a.y1 - b.y1).abs() < 1e-9
|
||||
};
|
||||
let band = p.tile.inflate(w / 4.0, h / 4.0);
|
||||
for b in &bounds {
|
||||
assert!(b.width() > 0.0 && b.height() > 0.0, "{}: {b:?}", p.name);
|
||||
assert!(b.x1 > 0.0 && b.y1 > 0.0 && b.x0 < w && b.y0 < h, "{}: {b:?} does not touch the tile", p.name);
|
||||
assert!(b.x0 >= band.x0 && b.y0 >= band.y0 && b.x1 <= band.x1 && b.y1 <= band.y1, "{}: {b:?} is too far out", p.name);
|
||||
// The tile past each edge the mark crosses draws this tile's art.
|
||||
let (dx, dy) = (f64::from(i8::from(b.x1 > w) - i8::from(b.x0 < 0.0)), f64::from(i8::from(b.y1 > h) - i8::from(b.y0 < 0.0)));
|
||||
for (x, y) in [(dx, 0.0), (0.0, dy), (dx, dy)] {
|
||||
let next = p.tile + kurbo::Vec2::new(x * w, y * h);
|
||||
assert!(p.offsets_covering(next).contains(&kurbo::Vec2::ZERO), "{}: {b:?} is cut off at {next:?}", p.name);
|
||||
}
|
||||
crossing += usize::from(dx != 0.0 || dy != 0.0);
|
||||
for (dx, dy) in [(w, 0.0), (-w, 0.0), (0.0, h), (0.0, -h), (w, h), (w, -h), (-w, h), (-w, -h)] {
|
||||
let moved = *b + kurbo::Vec2::new(dx, dy);
|
||||
assert!(!bounds.iter().any(|o| near(o, moved)), "{}: {b:?} is drawn twice by the tiling", p.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(crossing > 0, "no mark reaches past an edge");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -760,14 +760,16 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// When the write failed, the old stored module stays in the folder and needs its grant at
|
||||
// the next launch. A grant that can't be removed still approves the old bytes, so the store
|
||||
// gets the module it held back. When that module can't be read or written back, or there
|
||||
// was none, no module goes with the grant, and the grant stops counting for this session. A
|
||||
// grants file that is too large or doesn't hold a list approves nothing, and the new module
|
||||
// stays; one that can't be opened or read may approve the old bytes once it reads again.
|
||||
// was none, no module goes with the grant, and the grant stops counting for every session in
|
||||
// the process attached to the folder. A grants file that is too large or doesn't hold a list
|
||||
// approves nothing, and the new module stays; one that can't be opened or read may approve
|
||||
// the old bytes once it reads again.
|
||||
let writes = s.grant_writes();
|
||||
if stored && !s.store_grant(&m.id, None) && s.holds_plugin_grant(&m.id) {
|
||||
let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(plugin.id(), held.as_deref()));
|
||||
stored = !back && holds_new(s);
|
||||
if !back || matches!(previous, Ok(None)) {
|
||||
s.ignore_stored_grant(&m.id);
|
||||
s.ignore_stored_grant(&m.id, writes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,7 +110,9 @@ pub(super) const ALLOWED: &[&str] = &[
|
||||
"brush.move",
|
||||
"brush.new",
|
||||
"brush.options",
|
||||
"brush.placeArt",
|
||||
"brush.remove",
|
||||
"brush.replaceArt",
|
||||
"brush.selectionArt",
|
||||
"brush.setCurrent",
|
||||
"brush.unused",
|
||||
@@ -678,6 +680,7 @@ pub(super) const DENIED: &[&str] = &[
|
||||
"addon.pen.nextSegment",
|
||||
"effect.refreshDeferred",
|
||||
"graphicStyle.setOptions",
|
||||
"object.blend.createSpine",
|
||||
"object.blend.options",
|
||||
"object.liquify",
|
||||
"object.pathfinder.options",
|
||||
|
||||
@@ -687,6 +687,10 @@ impl Session {
|
||||
for e in self.prefs.keep_folders(&mut p) {
|
||||
log::warn!("{e}");
|
||||
}
|
||||
// Saved gradient presets get names no built-in preset or other saved one has.
|
||||
for (old, new) in super::gradpresets::rename_clashing_presets(&mut p.gradient_presets) {
|
||||
log::warn!("saved gradient preset {old} is listed as {new}: another preset has its name");
|
||||
}
|
||||
// The edit the active tool computes on another thread is applied first (the Preferences
|
||||
// dialog applies its settings here, outside a command). A failure to apply it was the
|
||||
// edit's own, and the preferences apply all the same.
|
||||
@@ -765,7 +769,7 @@ impl Session {
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(query "prefs.get", "Get Preferences", [], None, "{key?} → the value of one preference (or preference group: eyedropper), or {prefs: {…all…}}", always, get),
|
||||
cmd!(query "prefs.get", "Get Preferences", [], None, "{key?} → the value of one preference (or preference group: eyedropper), or {prefs: {…all…}}; under automation read roots a folder preference outside them is null, and an export preset's folder outside them is left out", always, get),
|
||||
cmd!(
|
||||
query "prefs.set",
|
||||
"Set Preference",
|
||||
@@ -776,7 +780,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
set
|
||||
),
|
||||
cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?} reset one category (or everything) to defaults", always, reset),
|
||||
cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference", always, list),
|
||||
cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference; under automation read roots a folder preference's value outside them is null", always, list),
|
||||
cmd!(
|
||||
query "prefs.export",
|
||||
"Export Preferences",
|
||||
@@ -882,8 +886,42 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "imported": values.len() }))
|
||||
}
|
||||
|
||||
/// The preferences that name a folder: the [`FOLDER_PREFS`] and the scratch disks.
|
||||
const PATH_PREFS: [&str; 6] = ["fontsFolder", "pluginsFolder", "scratchPrimary", "scratchSecondary", "recoveryFolder", "templatesFolder"];
|
||||
|
||||
/// The scratch disk choices that are not folders.
|
||||
const SCRATCH_CHOICES: [&str; 2] = ["Startup", "None"];
|
||||
|
||||
/// The preferences as `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show them to the
|
||||
/// request being served. Under automation read roots, a folder preference ([`PATH_PREFS`]) outside
|
||||
/// them is `null`, as `ui.inspect` leaves it out, and an export preset's `folder` outside them is
|
||||
/// left out. An empty value (the default folder) and a scratch
|
||||
/// disk choice ([`SCRATCH_CHOICES`]) are shown. Without roots the preferences are shown as they are.
|
||||
fn shown_prefs(prefs: &Prefs) -> Value {
|
||||
let mut all = prefs.to_json();
|
||||
if crate::file_access::current().is_none() {
|
||||
return all;
|
||||
}
|
||||
// The app trims a folder before it uses it.
|
||||
let hidden = |path: &str| !path.trim().is_empty() && crate::file_access::check_read(path.trim()).is_err();
|
||||
for key in PATH_PREFS {
|
||||
let Some(path) = all[key].as_str() else { continue };
|
||||
if hidden(path) && !(key.starts_with("scratch") && SCRATCH_CHOICES.contains(&path.trim())) {
|
||||
all[key] = Value::Null;
|
||||
}
|
||||
}
|
||||
if let Some(presets) = all.get_mut("screenExportPresets").and_then(Value::as_array_mut) {
|
||||
for settings in presets.iter_mut().filter_map(|p| p.get_mut("settings").and_then(Value::as_object_mut)) {
|
||||
if settings.get("folder").and_then(Value::as_str).is_some_and(hidden) {
|
||||
settings.remove("folder");
|
||||
}
|
||||
}
|
||||
}
|
||||
all
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let all = s.prefs.to_json();
|
||||
let all = shown_prefs(&s.prefs);
|
||||
match str_param(p, "key") {
|
||||
Some(k) if spec(k).is_some() || PREF_GROUPS.contains(&k) => Ok(all[k].clone()),
|
||||
Some(k) => Err(bad("prefs.get", format!("unknown preference `{k}`"))),
|
||||
@@ -911,7 +949,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if document_units && values.contains_key("unitsGeneral") && s.active().is_some() {
|
||||
s.set_document_units(s.default_units())?;
|
||||
}
|
||||
let all = s.prefs.to_json();
|
||||
let all = shown_prefs(&s.prefs);
|
||||
Ok(Value::Object(values.keys().map(|k| (k.clone(), all[k.as_str()].clone())).collect()))
|
||||
}
|
||||
|
||||
@@ -925,11 +963,11 @@ fn reset(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let mut next = s.prefs.clone();
|
||||
next.reset(cat);
|
||||
s.apply_prefs(next);
|
||||
Ok(json!({ "prefs": s.prefs.to_json() }))
|
||||
Ok(json!({ "prefs": shown_prefs(&s.prefs) }))
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let all = s.prefs.to_json();
|
||||
let all = shown_prefs(&s.prefs);
|
||||
Ok(Value::Array(
|
||||
PREF_SPECS
|
||||
.iter()
|
||||
|
||||
@@ -17,7 +17,11 @@
|
||||
//! store can, an announcement that lasts as long as the app ([`RecoveryStore::announce`]: the
|
||||
//! browser's Web Locks). Only areas nobody holds any more (their app is gone) are offered, and
|
||||
//! while their copies are restored or discarded the area is held, so two apps launched together
|
||||
//! never both take it.
|
||||
//! never both take it. An area's lock file or folder can be removed while its app runs, so each
|
||||
//! recovery save and heartbeat checks that the lock still holds the area, and locks it again or
|
||||
//! takes a new area. The copies it had in the old area stay there until it has written them again
|
||||
//! in the new one, and an entry `<new area>/keeps-<old area>` ([`mark_left`]) tells other apps
|
||||
//! that those copies belong to a running app, so none of them offers or discards them meanwhile.
|
||||
//!
|
||||
//! A heartbeat alone can't tell a gone app from one whose timers stopped (a background tab), so
|
||||
//! when unsure an area counts as held, and its app repairs what another app did meanwhile: each
|
||||
@@ -59,6 +63,9 @@ const BLOB_EXT: &str = ".blob";
|
||||
/// The heartbeat entry of an area in a store without locks: when its app last said it runs (Unix
|
||||
/// seconds, as text).
|
||||
const BEAT: &str = "heartbeat";
|
||||
/// The start of an entry `<area>/keeps-<left area>`: the app holding `<area>` still keeps the copies
|
||||
/// it left in `<left area>` ([`mark_left`]).
|
||||
const KEEPS: &str = "keeps-";
|
||||
/// The least time without a heartbeat after which an area's app counts as gone (seconds); else
|
||||
/// three Data Recovery intervals.
|
||||
const MIN_STALE: i64 = 180;
|
||||
@@ -100,6 +107,12 @@ pub trait RecoveryStore: Send + Sync {
|
||||
fn lock(&self, _area: &str) -> std::result::Result<Lock, String> {
|
||||
Ok(Lock::Unsupported)
|
||||
}
|
||||
/// Does `hold`, which [`RecoveryStore::lock`] gave for area `area`, still hold it? A lock on a
|
||||
/// file or folder that was removed or replaced since holds nothing; when that can't be told now,
|
||||
/// it does (default: it does).
|
||||
fn still_held(&self, _area: &str, _hold: &(dyn std::any::Any + Send + Sync)) -> bool {
|
||||
true
|
||||
}
|
||||
/// Stores without locks: also hold area `area` in a way other apps can see that lasts exactly as
|
||||
/// long as this app runs, if the store has one (the browser's Web Locks) → it, until dropped.
|
||||
fn announce(&self, _area: &str) -> Option<Hold> {
|
||||
@@ -266,7 +279,60 @@ impl FolderStore {
|
||||
builder.recursive(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
|
||||
builder.create(dir).map_err(|e| format!("{}: {e}", dir.display()))
|
||||
builder.create(dir).map_err(|e| Self::folder_error(dir, &e, true))
|
||||
}
|
||||
|
||||
/// The first folder on the way to `dir` (`dir` included), from the top down, that is not a
|
||||
/// folder (`true`) or is missing (`false`). None when every one of them is a folder or one of
|
||||
/// them can't be checked.
|
||||
fn in_the_way(dir: &std::path::Path) -> Option<(&std::path::Path, bool)> {
|
||||
let mut way: Vec<&std::path::Path> = dir.ancestors().filter(|p| !p.as_os_str().is_empty()).collect();
|
||||
way.reverse();
|
||||
for p in way {
|
||||
match std::fs::metadata(p) {
|
||||
Ok(m) if m.is_dir() => {}
|
||||
Ok(_) => return Some((p, true)),
|
||||
Err(m) if m.kind() == std::io::ErrorKind::NotFound => return Some((p, false)),
|
||||
Err(_) => return None,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The message for error `e` on folder `dir`, which was being made (`making`) or read. It
|
||||
/// names the first folder on the way to `dir` that is not a folder, or is missing (when
|
||||
/// `making`, the one that couldn't be made), and otherwise `dir`.
|
||||
fn folder_error(dir: &std::path::Path, e: &std::io::Error, making: bool) -> String {
|
||||
match Self::in_the_way(dir) {
|
||||
Some((p, true)) => format!("{} is not a folder: {e}", p.display()),
|
||||
Some((p, false)) if making => format!("couldn't make {}: {e}", p.display()),
|
||||
Some((p, false)) if p != dir => format!("{} is missing", p.display()),
|
||||
_ => format!("{}: {e}", dir.display()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The message for error `e` on file `f`. It names the first folder on the way to `f` that is
|
||||
/// not a folder or is missing, and otherwise `f`.
|
||||
fn file_error(f: &std::path::Path, e: &std::io::Error) -> String {
|
||||
match f.parent().and_then(Self::in_the_way) {
|
||||
Some((p, true)) => format!("{} is not a folder: {e}", p.display()),
|
||||
Some((p, false)) => format!("{} is missing", p.display()),
|
||||
None => format!("{}: {e}", f.display()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The outcome `r` of removing file `f`. A file that is not there counts as removed, unless a
|
||||
/// file is on the way to it: Windows reports that as a missing file, and it is named as for a
|
||||
/// listing.
|
||||
pub(crate) fn removed(f: &std::path::Path, r: std::io::Result<()>) -> std::result::Result<(), String> {
|
||||
match r {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => match f.parent().and_then(Self::in_the_way) {
|
||||
Some((p, true)) => Err(format!("{} is not a folder: {e}", p.display())),
|
||||
_ => Ok(()),
|
||||
},
|
||||
Err(e) => Err(Self::file_error(f, &e)),
|
||||
Ok(()) => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Refuse area folder `dir` unless it is a folder itself, not a link to one, and (on Unix)
|
||||
@@ -274,7 +340,7 @@ impl FolderStore {
|
||||
/// linked to a folder of its own in a shared recovery folder looked free, and claiming it
|
||||
/// wrote the copies through the link.
|
||||
fn own_area(dir: &std::path::Path) -> std::result::Result<(), String> {
|
||||
let m = std::fs::symlink_metadata(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
|
||||
let m = std::fs::symlink_metadata(dir).map_err(|e| Self::folder_error(dir, &e, false))?;
|
||||
if !m.file_type().is_dir() {
|
||||
return Err(format!("{}: not a folder of its own", dir.display()));
|
||||
}
|
||||
@@ -286,11 +352,17 @@ impl FolderStore {
|
||||
}
|
||||
|
||||
/// The plain names of the files (or, `dirs`, folders) in `dir`; none when it doesn't exist.
|
||||
/// A file on the way to `dir` is an error: Windows reports such a folder as missing.
|
||||
fn names(dir: &std::path::Path, dirs: bool) -> std::result::Result<Vec<String>, String> {
|
||||
let entries = match std::fs::read_dir(dir) {
|
||||
Ok(e) => e,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(vec![]),
|
||||
Err(e) => return Err(format!("{}: {e}", dir.display())),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
return match Self::in_the_way(dir) {
|
||||
Some((p, true)) => Err(format!("{} is not a folder: {e}", p.display())),
|
||||
_ => Ok(vec![]),
|
||||
};
|
||||
}
|
||||
Err(e) => return Err(Self::folder_error(dir, &e, false)),
|
||||
};
|
||||
Ok(entries
|
||||
.filter_map(|e| e.ok())
|
||||
@@ -325,7 +397,7 @@ impl FolderStore {
|
||||
match e.kind() {
|
||||
std::io::ErrorKind::NotFound => Ok(Lock::Busy),
|
||||
std::io::ErrorKind::PermissionDenied if std::fs::symlink_metadata(path).is_ok() => Ok(Lock::Busy),
|
||||
_ => Err(format!("{}: {e}", path.display())),
|
||||
_ => Err(Self::file_error(path, &e)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -337,7 +409,7 @@ impl FolderStore {
|
||||
Ok(()) | Err(std::fs::TryLockError::WouldBlock) => Ok(Lock::Busy),
|
||||
// The lock file was removed meanwhile, and locking it failed instead.
|
||||
Err(std::fs::TryLockError::Error(_)) if !Self::still_named(&file, path) => Ok(Lock::Busy),
|
||||
Err(std::fs::TryLockError::Error(e)) => Err(format!("{}: {e}", path.display())),
|
||||
Err(std::fs::TryLockError::Error(e)) => Err(Self::file_error(path, &e)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -385,10 +457,10 @@ impl RecoveryStore for FolderStore {
|
||||
if let Some(dir) = f.parent() {
|
||||
Self::own_area(dir)?;
|
||||
}
|
||||
if !std::fs::symlink_metadata(&f).map_err(|e| format!("{}: {e}", f.display()))?.file_type().is_file() {
|
||||
if !std::fs::symlink_metadata(&f).map_err(|e| Self::file_error(&f, &e))?.file_type().is_file() {
|
||||
return Err(format!("{}: not a plain file", f.display()));
|
||||
}
|
||||
std::fs::read(&f).map_err(|e| format!("{}: {e}", f.display()))
|
||||
std::fs::read(&f).map_err(|e| Self::file_error(&f, &e))
|
||||
}
|
||||
fn write(&self, name: &str, bytes: &[u8]) -> std::result::Result<(), String> {
|
||||
let f = self.file(name)?;
|
||||
@@ -396,14 +468,11 @@ impl RecoveryStore for FolderStore {
|
||||
Self::create_area(dir)?;
|
||||
Self::own_area(dir)?;
|
||||
}
|
||||
vectorcraft_format::write_atomic(&f, bytes).map_err(|e| format!("{}: {e}", f.display()))
|
||||
vectorcraft_format::write_atomic(&f, bytes).map_err(|e| Self::file_error(&f, &e))
|
||||
}
|
||||
fn remove(&self, name: &str) -> std::result::Result<(), String> {
|
||||
let f = self.file(name)?;
|
||||
match std::fs::remove_file(&f) {
|
||||
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(format!("{}: {e}", f.display())),
|
||||
_ => Ok(()),
|
||||
}
|
||||
Self::removed(&f, std::fs::remove_file(&f))
|
||||
}
|
||||
fn location(&self) -> String {
|
||||
self.0.to_string_lossy().into_owned()
|
||||
@@ -416,6 +485,16 @@ impl RecoveryStore for FolderStore {
|
||||
Self::create_area(&dir)?;
|
||||
Self::lock_area(&dir)
|
||||
}
|
||||
fn still_held(&self, area: &str, hold: &(dyn std::any::Any + Send + Sync)) -> bool {
|
||||
let (Some(file), Ok(dir)) = (hold.downcast_ref::<std::fs::File>(), self.area(area)) else { return true };
|
||||
let path = dir.join(LOCK_FILE);
|
||||
// Only a lock file or folder that is gone, or another one in its place, ends the hold. One
|
||||
// that can't be read now (a network folder that doesn't answer) still counts as held.
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Ok(_) => Self::own_area(&dir).is_ok() && Self::still_named(file, &path),
|
||||
Err(e) => e.kind() != std::io::ErrorKind::NotFound,
|
||||
}
|
||||
}
|
||||
fn remove_area(&self, area: &str) {
|
||||
// Best effort: whatever is left is tidied at a later launch. A folder that isn't empty
|
||||
// (copies came back meanwhile) stays. The caller still holds the lock here.
|
||||
@@ -457,6 +536,12 @@ pub struct Recovery {
|
||||
/// heartbeat it wrote there: that one doesn't make them look running, a newer one does (their
|
||||
/// app was only paused and came back).
|
||||
adopted: BTreeMap<String, i64>,
|
||||
/// Copies in an area this session had to leave (`keep_hold`), by document uid, with their
|
||||
/// store: each stays until its document has a copy in the new area, or needs none. They are
|
||||
/// still this session's: never offered or discarded as a crash's here.
|
||||
left: BTreeMap<u64, (Arc<dyn RecoveryStore>, String)>,
|
||||
/// The `<own area>/keeps-<left area>` entries this session wrote in its area ([`mark_left`]).
|
||||
marked: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl Recovery {
|
||||
@@ -526,14 +611,120 @@ fn beating(store: &dyn RecoveryStore, area: &str, stale: i64, mine: Option<i64>)
|
||||
|
||||
/// Refresh this session's hold on its area (the app does this every [`HEARTBEAT_EVERY`] seconds,
|
||||
/// so also on its first frame after its timers were paused): its heartbeat in a store without
|
||||
/// locks, and its copies ([`repair`]) → the documents whose copies went missing (write them now).
|
||||
/// Best effort: a missed beat only lets another app offer the copies once three intervals have
|
||||
/// passed.
|
||||
/// locks, and its copies ([`repair`]) → the documents whose copies went missing (write them now),
|
||||
/// and those whose only copy is in an area the session left (`keep_hold`). Best effort: a missed
|
||||
/// beat only lets another app offer the copies once three intervals have passed.
|
||||
pub fn heartbeat(s: &mut Session) -> Vec<u64> {
|
||||
let mut lost = keep_hold(s);
|
||||
// An entry that couldn't be written before, or that was removed since (by the user, a
|
||||
// cleaner), is written now.
|
||||
if let Some(own) = &s.recovery.own
|
||||
&& !s.recovery.marked.is_empty()
|
||||
&& let Ok(names) = own.store.list()
|
||||
{
|
||||
s.recovery.marked.retain(|n| names.contains(n));
|
||||
}
|
||||
mark_left(s);
|
||||
if let Some(own) = s.recovery.own.as_ref().filter(|o| o.beats) {
|
||||
let _ = beat(own.store.as_ref(), &own.area);
|
||||
}
|
||||
repair(s)
|
||||
// A copy that was being written when the session left its area finished there. A document
|
||||
// that gets no copy now (a complex one) keeps the copy it has.
|
||||
lost.extend(
|
||||
s.recovery
|
||||
.left
|
||||
.keys()
|
||||
.filter(|&&uid| s.documents().iter().any(|d| d.uid == uid && d.recovery.is_none() && skip_reason(s, d).is_none()))
|
||||
.copied(),
|
||||
);
|
||||
lost.extend(repair(s));
|
||||
lost.sort_unstable();
|
||||
lost.dedup();
|
||||
lost
|
||||
}
|
||||
|
||||
/// Check that this session's lock still holds its area (stores with locks). The area's lock file,
|
||||
/// or the whole area, can be removed while the app runs (by the user, a cleaner, another program),
|
||||
/// and then another app can lock the area and offer or delete this session's copies as a crash's.
|
||||
/// The area is locked again, made again first if it went (its copies are then written again).
|
||||
/// When another app holds it now, the session takes a new area, and each copy left in the old one
|
||||
/// stays until its document has a copy in the new one. → the documents whose copies must be
|
||||
/// written again.
|
||||
fn keep_hold(s: &mut Session) -> Vec<u64> {
|
||||
drop_left_done(s);
|
||||
let Some(own) = &mut s.recovery.own else { return vec![] };
|
||||
if own.beats || own.hold.as_deref().is_none_or(|h| own.store.still_held(&own.area, h)) {
|
||||
return vec![];
|
||||
}
|
||||
let (store, area) = (own.store.clone(), own.area.clone());
|
||||
// The lock held is on a file the area no longer has, so it holds nothing: it goes first (a
|
||||
// removed file this app still has open can keep a new lock file from being made).
|
||||
own.hold = None;
|
||||
if let Ok(Lock::Held(h)) = store.lock(&area) {
|
||||
own.hold = Some(h);
|
||||
return repair(s);
|
||||
}
|
||||
let mut lost = vec![];
|
||||
for st in &mut s.docs {
|
||||
if let Some(c) = st.recovery.take() {
|
||||
s.recovery.left.insert(st.uid, (store.clone(), c.file));
|
||||
lost.push(st.uid);
|
||||
}
|
||||
}
|
||||
s.recovery.own = None;
|
||||
// Best effort: when no area can be taken now, the next recovery save says why.
|
||||
let _ = claim(s, &store);
|
||||
lost
|
||||
}
|
||||
|
||||
/// The copies left in an area this session left whose documents were saved, reverted or closed
|
||||
/// since go.
|
||||
fn drop_left_done(s: &mut Session) {
|
||||
let done: Vec<u64> = s.recovery.left.keys().filter(|&&uid| !s.documents().iter().any(|d| d.uid == uid && d.is_dirty())).copied().collect();
|
||||
for uid in done {
|
||||
drop_left(s, uid);
|
||||
}
|
||||
}
|
||||
|
||||
/// Document `uid`'s copy in an area this session left goes. A copy that can't be removed now stays
|
||||
/// this session's, and a later heartbeat removes it.
|
||||
fn drop_left(s: &mut Session, uid: u64) {
|
||||
let Some((store, file)) = s.recovery.left.get(&uid) else { return };
|
||||
let doc = store.remove(&format!("{file}{DOC_EXT}"));
|
||||
let meta = store.remove(&format!("{file}{META_EXT}"));
|
||||
if doc.is_ok() && meta.is_ok() {
|
||||
s.recovery.left.remove(&uid);
|
||||
mark_left(s);
|
||||
}
|
||||
}
|
||||
|
||||
/// Record in this session's area each area it left that still holds copies of its documents: an
|
||||
/// entry `<own area>/keeps-<left area>`, so another app leaves those copies alone while this one
|
||||
/// runs ([`keeper`]). The entries of areas that hold none of its copies any more go. Best effort:
|
||||
/// an entry not written or removed now is written or removed at the next heartbeat.
|
||||
fn mark_left(s: &mut Session) {
|
||||
let Some(own) = &s.recovery.own else { return };
|
||||
let (store, area) = (own.store.clone(), own.area.clone());
|
||||
let want: BTreeSet<String> = s
|
||||
.recovery
|
||||
.left
|
||||
.values()
|
||||
.filter(|(st, _)| st.location() == store.location())
|
||||
.filter_map(|(_, f)| f.split_once('/').map(|(a, _)| a))
|
||||
.filter(|a| *a != area)
|
||||
.map(|a| format!("{area}/{KEEPS}{a}"))
|
||||
.collect();
|
||||
let gone: Vec<String> = s.recovery.marked.difference(&want).cloned().collect();
|
||||
for n in gone {
|
||||
if store.remove(&n).is_ok() {
|
||||
s.recovery.marked.remove(&n);
|
||||
}
|
||||
}
|
||||
for n in want {
|
||||
if !s.recovery.marked.contains(&n) && store.write(&n, b"").is_ok() {
|
||||
s.recovery.marked.insert(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Forget this session's copies that are missing from its area, so the next recovery save writes
|
||||
@@ -555,10 +746,13 @@ pub fn repair(s: &mut Session) -> Vec<u64> {
|
||||
/// This session's area in `store`, taken now if it has none there yet: a fresh area, held for the
|
||||
/// session's lifetime (locked, or with a heartbeat and an announcement where the store has them).
|
||||
pub fn claim(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<String> {
|
||||
if let Some(own) = &s.recovery.own {
|
||||
if own.store.location() == store.location() {
|
||||
if s.recovery.own.as_ref().is_some_and(|o| o.store.location() == store.location()) {
|
||||
// Documents whose copies went are left without one, so the caller writes them again.
|
||||
keep_hold(s);
|
||||
if let Some(own) = &s.recovery.own {
|
||||
return Ok(own.area.clone());
|
||||
}
|
||||
} else if s.recovery.own.is_some() {
|
||||
// The store moved (the preference names another folder): copies start again there.
|
||||
release(s);
|
||||
}
|
||||
@@ -578,6 +772,9 @@ pub fn claim(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<String>
|
||||
}
|
||||
};
|
||||
s.recovery.own = Some(Own { store: store.clone(), area: area.clone(), hold, beats });
|
||||
// The entries written before are in the area this session had (released or left).
|
||||
s.recovery.marked.clear();
|
||||
mark_left(s);
|
||||
return Ok(area);
|
||||
}
|
||||
Err(EngineError::Other("no free recovery area".into()))
|
||||
@@ -588,7 +785,14 @@ pub fn release(s: &mut Session) {
|
||||
for st in &mut s.docs {
|
||||
st.recovery = None;
|
||||
}
|
||||
// Copies left in an area this session had to leave go too.
|
||||
let left: Vec<u64> = s.recovery.left.keys().copied().collect();
|
||||
for uid in left {
|
||||
drop_left(s, uid);
|
||||
}
|
||||
let Some(Own { store, area, hold, .. }) = s.recovery.own.take() else { return };
|
||||
// Its `keeps-` entries go with the area's other entries.
|
||||
s.recovery.marked.clear();
|
||||
let mine = |n: &String| n.split_once('/').is_some_and(|(a, _)| a == area);
|
||||
for name in store.list().unwrap_or_default().iter().filter(|n| mine(n)) {
|
||||
let _ = store.remove(name);
|
||||
@@ -750,12 +954,16 @@ pub struct RecoveryJob {
|
||||
pub title: String,
|
||||
meta: Meta,
|
||||
save: SaveJob,
|
||||
/// The store the copy goes to (the preference can name another folder before it is finished).
|
||||
store: Arc<dyn RecoveryStore>,
|
||||
}
|
||||
|
||||
impl RecoveryJob {
|
||||
/// Encode the snapshot and store it with its details and the images the area doesn't have
|
||||
/// yet → `{file, title, bytes (the document's), imageBytes (images written now)}`.
|
||||
pub fn write(&self, store: &dyn RecoveryStore) -> std::result::Result<Value, String> {
|
||||
/// yet, in the store the job was made for → `{file, title, bytes (the document's), imageBytes
|
||||
/// (images written now)}`.
|
||||
pub fn write(&self) -> std::result::Result<Value, String> {
|
||||
let store = self.store.as_ref();
|
||||
let doc = self.save.doc();
|
||||
// A linked image keeps its preview, as a save writes it.
|
||||
let linked = doc.linked_only_images();
|
||||
@@ -808,13 +1016,36 @@ impl RecoveryJob {
|
||||
|
||||
/// Once stored: the document (if still open) remembers the copy, so it isn't written again
|
||||
/// while unchanged and goes when the document is saved or closed. A document saved or closed
|
||||
/// meanwhile has nothing left to recover: its copy goes at once.
|
||||
/// meanwhile has nothing left to recover: its copy goes at once. So does a copy written in an
|
||||
/// area the session left meanwhile (`keep_hold`), and its document gets a new one.
|
||||
pub fn finish(self, s: &mut Session) {
|
||||
let snapshot = self.save.snapshot().clone();
|
||||
let copy = RecoveryCopy { file: self.file.clone(), doc: snapshot };
|
||||
let area = self.file.split_once('/').map(|(a, _)| a);
|
||||
let current = s.recovery.own.as_ref().is_some_and(|o| o.store.location() == self.store.location() && Some(o.area.as_str()) == area);
|
||||
match s.document_mut(self.uid).filter(|st| st.is_dirty()) {
|
||||
Some(st) => st.recovery = Some(copy),
|
||||
None => remove_copy(s, &self.file),
|
||||
Some(st) if current => {
|
||||
st.recovery = Some(copy);
|
||||
drop_left(s, self.uid);
|
||||
}
|
||||
// Written in an area left meanwhile: kept, in place of the copy left there before,
|
||||
// until the document has a copy in the new area.
|
||||
Some(st) if st.recovery.is_none() => {
|
||||
let before = s.recovery.left.insert(self.uid, (self.store.clone(), self.file.clone()));
|
||||
// The copy left there before, unless this one was written over it. Best effort,
|
||||
// as in `remove_copy`.
|
||||
if let Some((store, file)) = before.filter(|(old, f)| old.location() != self.store.location() || *f != self.file) {
|
||||
let _ = store.remove(&format!("{file}{DOC_EXT}"));
|
||||
let _ = store.remove(&format!("{file}{META_EXT}"));
|
||||
}
|
||||
mark_left(s);
|
||||
}
|
||||
// Best effort, as in `remove_copy`.
|
||||
_ => {
|
||||
let _ = self.store.remove(&format!("{}{DOC_EXT}", self.file));
|
||||
let _ = self.store.remove(&format!("{}{META_EXT}", self.file));
|
||||
drop_left(s, self.uid);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -867,6 +1098,11 @@ fn fresh_name(area: &str, stem: &str, taken: &[String]) -> String {
|
||||
/// when it has none and a copy is needed) → (jobs, skipped: `[{title, reason}]` for modified
|
||||
/// documents that get none).
|
||||
pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<RecoveryJob>, Vec<Value>)> {
|
||||
// A lost lock is taken again first: copies that go with it are written again, even of
|
||||
// documents unchanged since.
|
||||
if s.recovery.own.as_ref().is_some_and(|o| o.store.location() == store.location()) {
|
||||
keep_hold(s);
|
||||
}
|
||||
// Copies another app removed are written again.
|
||||
repair(s);
|
||||
let skipped: Vec<Value> = s
|
||||
@@ -923,7 +1159,7 @@ pub fn jobs(s: &mut Session, store: &Arc<dyn RecoveryStore>) -> Result<(Vec<Reco
|
||||
// Filled in as the copy is written.
|
||||
images: BTreeMap::new(),
|
||||
};
|
||||
out.push(RecoveryJob { uid: st.uid, file, title, meta, save });
|
||||
out.push(RecoveryJob { uid: st.uid, file, title, meta, save, store: store.clone() });
|
||||
}
|
||||
Ok((out, skipped))
|
||||
}
|
||||
@@ -954,7 +1190,7 @@ pub(crate) fn save_copies(s: &mut Session) -> Result<()> {
|
||||
return Err(EngineError::Other("a document with unsaved changes has no recovery copy".into()));
|
||||
}
|
||||
for j in jobs {
|
||||
j.write(store.as_ref()).map_err(EngineError::Other)?;
|
||||
j.write().map_err(EngineError::Other)?;
|
||||
j.finish(s);
|
||||
}
|
||||
Ok(())
|
||||
@@ -966,6 +1202,8 @@ pub fn forget(s: &mut Session, uid: u64) {
|
||||
if s.script_in_run {
|
||||
return;
|
||||
}
|
||||
// So does a copy of it left in an area this session left.
|
||||
drop_left(s, uid);
|
||||
let Some(copy) = s.document_mut(uid).and_then(|st| st.recovery.take()) else { return };
|
||||
remove_copy(s, ©.file);
|
||||
}
|
||||
@@ -975,12 +1213,16 @@ pub fn forget_all(s: &mut Session) {
|
||||
release(s);
|
||||
}
|
||||
|
||||
/// The copies of documents with no unsaved changes left (undone back to the saved state) go.
|
||||
/// The copies of documents with no unsaved changes left (undone back to the saved state) go, and
|
||||
/// the copies left in an area this session left of documents closed since.
|
||||
pub fn forget_clean(s: &mut Session) {
|
||||
let uids: Vec<u64> = s.documents().iter().filter(|d| !d.is_dirty() && d.recovery.is_some()).map(|d| d.uid).collect();
|
||||
for uid in uids {
|
||||
forget(s, uid);
|
||||
}
|
||||
if !s.script_in_run {
|
||||
drop_left_done(s);
|
||||
}
|
||||
}
|
||||
|
||||
fn save(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
@@ -988,7 +1230,7 @@ fn save(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let (jobs, skipped) = jobs(s, &store)?;
|
||||
let mut saved = vec![];
|
||||
for j in jobs {
|
||||
saved.push(j.write(store.as_ref()).map_err(EngineError::Other)?);
|
||||
saved.push(j.write().map_err(EngineError::Other)?);
|
||||
j.finish(s);
|
||||
}
|
||||
forget_clean(s);
|
||||
@@ -1018,6 +1260,10 @@ fn owner(s: &mut Session, store: &dyn RecoveryStore, area: &str, hold: &mut Vec<
|
||||
}
|
||||
match store.lock(area) {
|
||||
Ok(Lock::Held(h)) => {
|
||||
// Copies an app left here when it had to leave the area stay its own while it runs.
|
||||
if let Some(who) = keeper(s, store, area) {
|
||||
return who;
|
||||
}
|
||||
hold.push(h);
|
||||
Owner::Gone
|
||||
}
|
||||
@@ -1026,6 +1272,9 @@ fn owner(s: &mut Session, store: &dyn RecoveryStore, area: &str, hold: &mut Vec<
|
||||
if store.announced(area).unwrap_or(false) || beating(store, area, stale_after(s), s.recovery.adopted.get(area).copied()) {
|
||||
return Owner::Running;
|
||||
}
|
||||
if let Some(who) = keeper(s, store, area) {
|
||||
return who;
|
||||
}
|
||||
// Best effort: without it another app might offer the copies too, which loses nothing.
|
||||
if take && let Ok(t) = beat(store, area) {
|
||||
s.recovery.adopted.insert(area.to_string(), t);
|
||||
@@ -1035,6 +1284,42 @@ fn owner(s: &mut Session, store: &dyn RecoveryStore, area: &str, hold: &mut Vec<
|
||||
}
|
||||
}
|
||||
|
||||
/// Who keeps the copies left in `area` by an app that had to leave it, from the entries
|
||||
/// `<its area>/keeps-<area>` ([`mark_left`]): this session, or another app that is running. `None`:
|
||||
/// no app that runs keeps them. An entry counts only in an area this account can lock or tell is
|
||||
/// held ([`holder`]), so an entry in a folder of another account, or in one whose lock can't be
|
||||
/// checked, keeps nothing. A store that can't be listed now keeps them (a copy kept loses nothing).
|
||||
fn keeper(s: &Session, store: &dyn RecoveryStore, area: &str) -> Option<Owner> {
|
||||
let Ok(names) = store.list() else { return Some(Owner::Running) };
|
||||
let mark = format!("/{KEEPS}{area}");
|
||||
let mut who = None;
|
||||
for k in names.iter().filter_map(|n| n.strip_suffix(mark.as_str())).filter(|k| *k != area) {
|
||||
match holder(s, store, k) {
|
||||
Owner::Mine => return Some(Owner::Mine),
|
||||
Owner::Running => who = Some(Owner::Running),
|
||||
Owner::Gone => {}
|
||||
}
|
||||
}
|
||||
who
|
||||
}
|
||||
|
||||
/// Whose area `area` is, without taking it over: this session's, a running app's, or nobody's (a
|
||||
/// lock taken to tell goes at once). An area whose lock fails (not a recovery area of this
|
||||
/// account, a lock file that can't be opened) is nobody's.
|
||||
fn holder(s: &Session, store: &dyn RecoveryStore, area: &str) -> Owner {
|
||||
if s.recovery.own.as_ref().is_some_and(|o| o.area == area && o.store.location() == store.location()) {
|
||||
return Owner::Mine;
|
||||
}
|
||||
match store.lock(area) {
|
||||
Ok(Lock::Held(_)) | Err(_) => Owner::Gone,
|
||||
Ok(Lock::Busy) => Owner::Running,
|
||||
Ok(Lock::Unsupported) => {
|
||||
let runs = store.announced(area).unwrap_or(false) || beating(store, area, stale_after(s), s.recovery.adopted.get(area).copied());
|
||||
if runs { Owner::Running } else { Owner::Gone }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Tidy away a gone app's area `area` once no copies are left in it, then let it go (`hold`). The
|
||||
/// area is removed while it is still held, so an app taking a new area of that name meanwhile
|
||||
/// finds it held or gone and takes the next name.
|
||||
@@ -1057,9 +1342,15 @@ fn open_copies(s: &Session) -> Vec<String> {
|
||||
s.documents().iter().filter_map(|d| d.recovery.as_ref()).map(|c| c.file.clone()).collect()
|
||||
}
|
||||
|
||||
/// The copies of documents open now in this session that are in an area it left, in `store`.
|
||||
fn left_copies(s: &Session, store: &dyn RecoveryStore) -> Vec<String> {
|
||||
s.recovery.left.values().filter(|(st, _)| st.location() == store.location()).map(|(_, f)| f.clone()).collect()
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let store = need_store(s, "file.recovery.list")?;
|
||||
let open = open_copies(s);
|
||||
let left = left_copies(s, store.as_ref());
|
||||
let copies = copies_in(&store.list().map_err(EngineError::Other)?);
|
||||
let mut rows = vec![];
|
||||
for area in store.areas().map_err(EngineError::Other)? {
|
||||
@@ -1071,7 +1362,7 @@ fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let title = if meta.title.is_empty() { f.rsplit('/').next().unwrap_or(f).to_string() } else { meta.title };
|
||||
rows.push(json!({
|
||||
"file": f, "title": title, "path": meta.path, "format": meta.format, "saved": meta.saved,
|
||||
"open": who == Owner::Mine && open.contains(f), "running": who == Owner::Running,
|
||||
"open": (who == Owner::Mine && open.contains(f)) || left.contains(f), "running": who == Owner::Running,
|
||||
}));
|
||||
}
|
||||
// A gone app's empty area is tidied away.
|
||||
@@ -1095,7 +1386,14 @@ fn targets(s: &mut Session, store: &dyn RecoveryStore, cmd: &str, p: &Value) ->
|
||||
{
|
||||
return Err(bad(cmd, format!("no recovery copy `{f}` (see file.recovery.list)")));
|
||||
}
|
||||
let picked = |c: &str| file.is_none_or(|f| f == c);
|
||||
// A copy this session left in an area it had to leave is still its own.
|
||||
let left = left_copies(s, store);
|
||||
if let Some(f) = file
|
||||
&& left.iter().any(|c| c == f)
|
||||
{
|
||||
return Err(bad(cmd, format!("`{f}` is the copy of a document open now")));
|
||||
}
|
||||
let picked = |c: &str| file.is_none_or(|f| f == c) && !left.iter().any(|l| l == c);
|
||||
let areas: BTreeSet<&str> = copies.iter().filter(|(_, c)| picked(c)).map(|(a, _)| a.as_str()).collect();
|
||||
let mut out = vec![];
|
||||
for area in areas {
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -13,8 +13,8 @@ use vectorcraft_doc::{Appearance, CellAlign, CellVAlign, Document, Node, NodeKin
|
||||
use vectorcraft_geom::{Rect, shapes};
|
||||
|
||||
use super::{
|
||||
CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, f64_req, has_doc, has_selection, id_param, ids_param, index, number_or, switch_or,
|
||||
targets,
|
||||
CommandSpec, EngineError, NodeId, Result, Session, bad, cmd, f64_req, has_doc, has_selection, ids_param, index, number_or, object_param,
|
||||
switch_or, targets,
|
||||
};
|
||||
|
||||
/// The most slices one Divide Slices makes.
|
||||
@@ -680,7 +680,7 @@ fn create(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn set_rect(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "object.slice.setRect";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
let r = rect_param(p, C)?;
|
||||
let d = &s.doc()?.doc;
|
||||
if d.slice(id).is_none() {
|
||||
|
||||
@@ -206,11 +206,31 @@ fn no_targets(ids: &[vectorcraft_doc::NodeId], p: &Value) -> bool {
|
||||
ids.is_empty() && p.get("ids").is_none() && p.get("id").is_none()
|
||||
}
|
||||
|
||||
/// The objects `stroke.set` edits with no `item`: a selected group or layer with a stroke row of
|
||||
/// its own edits that row, as the Stroke panel does with the group targeted (#6739); the other
|
||||
/// targets reach their painted leaves, as before.
|
||||
fn own_stroke_or_leaves(s: &Session, p: &Value) -> Result<Vec<vectorcraft_doc::NodeId>> {
|
||||
let picked = super::targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
let own = |id: &vectorcraft_doc::NodeId| {
|
||||
d.node(*id).is_some_and(|n| {
|
||||
matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape() && n.appearance.stroke().is_some()
|
||||
})
|
||||
};
|
||||
let (mut out, rest): (Vec<_>, Vec<_>) = picked.into_iter().partition(own);
|
||||
for id in super::leaf_targets(s, &rest)? {
|
||||
if !out.contains(&id) {
|
||||
out.push(id);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "stroke.set";
|
||||
let change = StrokeChange::parse(p, C)?;
|
||||
let item = item_target(s, p, C)?.of_kind(s, false);
|
||||
let mut ids = item.targets(s, p)?;
|
||||
let mut ids = if item == ItemTarget::Top { own_stroke_or_leaves(s, p)? } else { item.targets(s, p)? };
|
||||
let new_art = no_targets(&ids, p);
|
||||
if item == ItemTarget::Top {
|
||||
// Images and symbol instances take no stroke from the panel.
|
||||
@@ -261,7 +281,11 @@ fn stroke_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Ok(());
|
||||
}
|
||||
if index.is_none() && n.appearance.stroke().is_none() {
|
||||
n.appearance.set_stroke(Paint::solid(Color::BLACK));
|
||||
// Options alone (cap, join, miter limit, dashes, alignment) don't make a stroke
|
||||
// visible: the row made for them has no paint. A weight, an arrowhead or a profile
|
||||
// still gives the object the black stroke the panel draws (#6739).
|
||||
let visible = change.weight.is_some() || sa.is_some() || ea.is_some() || profile.is_some();
|
||||
n.appearance.set_stroke(if visible { Paint::solid(Color::BLACK) } else { Paint::None });
|
||||
}
|
||||
if let Some(st) = n.appearance.stroke_at_mut(index) {
|
||||
set(st);
|
||||
|
||||
@@ -19,7 +19,7 @@ use vectorcraft_doc::symbol_overrides::SymbolOverride;
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind, Selection, SymbolEdit, SymbolRegistration};
|
||||
use vectorcraft_geom::{Affine, Point};
|
||||
|
||||
use super::brushsym::{natural_size, place_xf};
|
||||
use super::brushsym::{fit_parts, natural_size, place_xf};
|
||||
use super::{EngineError, Result, Session, bad, number_or, object_param, ok, str_param};
|
||||
|
||||
/// The name of the undo step that enters symbol editing mode.
|
||||
@@ -425,8 +425,8 @@ fn each_changed_instance(n: &mut Node, name: &str, f: &mut dyn FnMut(&mut Vec<Sy
|
||||
}
|
||||
|
||||
/// Each instance's appearance changes to objects of symbol `name`'s art follow those objects
|
||||
/// through an edit of the editing layer (see [`follow_paths`]), and keep only the changes to
|
||||
/// objects the art still has. That covers the instances on the layers and in the art of the
|
||||
/// through an edit of the editing layer (see [`follow_paths`]), and keep only the changes the art
|
||||
/// still draws ([`fit_parts`]). That covers the instances on the layers and in the art of the
|
||||
/// document's other symbols, graph designs, pattern tiles (the tiles pattern editing's Cancel puts
|
||||
/// back included) and brushes, opacity-mask art included. The editing layer holds no instance of
|
||||
/// the symbol, since [`sync`] refuses one.
|
||||
@@ -435,7 +435,7 @@ fn follow_objects(d: &mut Document, name: &str, old: (&[Arc<Node>], bool), new:
|
||||
let mut follow = |o: &mut Vec<SymbolOverride>| {
|
||||
follow_paths(o, old, new);
|
||||
match &art {
|
||||
Some(art) => vectorcraft_doc::symbol_overrides::retain_parts(o, art),
|
||||
Some(art) => fit_parts(o, art),
|
||||
None => o.clear(),
|
||||
}
|
||||
};
|
||||
|
||||
@@ -13,7 +13,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Set Tab Stops",
|
||||
["Window", "Tabs"],
|
||||
None,
|
||||
"{stops: [{position: pt, align?: left|center|right|decimal, leader?: \". \", alignOn?: \".\"}], ids?|id?, start?: byte, end?: byte} replace the tab stops of the selected text (with a range: of the paragraphs it touches); supplied align, leader and alignOn must be strings, and alignOn cannot be empty",
|
||||
"{stops: [{position: pt, align?: left|center|right|decimal, leader?: \". \", alignOn?: \".\"}], ids?|id?, start?: byte, end?: byte} replace the tab stops of the selected text (with a range: of the paragraphs it touches); at most 256 stops, or no more than each targeted paragraph already holds, positions 0..=100000 pt; supplied align, leader and alignOn must be strings, a leader has at most 8 characters and alignOn exactly one; stops are sorted by position, and of stops at one position the first given is kept",
|
||||
has_selection,
|
||||
set
|
||||
),
|
||||
@@ -41,7 +41,7 @@ fn parse_stops(p: &Value) -> Result<Vec<TabStop>> {
|
||||
let mut stops = vec![];
|
||||
for s in arr {
|
||||
let position = s.get("position").and_then(Value::as_f64).ok_or_else(|| bad(C, "each stop needs a position"))?;
|
||||
if !(0.0..=100_000.0).contains(&position) {
|
||||
if !(0.0..=TabStop::MAX_POSITION).contains(&position) {
|
||||
return Err(bad(C, "positions must be between 0 and 100000 pt"));
|
||||
}
|
||||
let align = match s.get("align") {
|
||||
@@ -60,16 +60,25 @@ fn parse_stops(p: &Value) -> Result<Vec<TabStop>> {
|
||||
None | Some(Value::Null) => "",
|
||||
Some(Value::String(value)) => value.as_str(),
|
||||
Some(_) => return Err(bad(C, "`leader` must be a string")),
|
||||
};
|
||||
let (label, max) = ("`leader`", TabStop::MAX_LEADER);
|
||||
if leader.chars().count() > max {
|
||||
return Err(bad(C, format!("{label} must be at most {max} characters")));
|
||||
}
|
||||
.chars()
|
||||
.take(8)
|
||||
.collect();
|
||||
let align_on = match s.get("alignOn") {
|
||||
None | Some(Value::Null) => '.',
|
||||
Some(Value::String(value)) => value.chars().next().ok_or_else(|| bad(C, "`alignOn` cannot be empty"))?,
|
||||
Some(Value::String(value)) => {
|
||||
let mut chars = value.chars();
|
||||
let c = chars.next().ok_or_else(|| bad(C, "`alignOn` cannot be empty"))?;
|
||||
if chars.next().is_some() {
|
||||
let label = "`alignOn`";
|
||||
return Err(bad(C, format!("{label} must be one character")));
|
||||
}
|
||||
c
|
||||
}
|
||||
Some(_) => return Err(bad(C, "`alignOn` must be a string")),
|
||||
};
|
||||
stops.push(TabStop { position, align, leader, align_on });
|
||||
stops.push(TabStop { position, align, leader: leader.to_string(), align_on });
|
||||
}
|
||||
stops.sort_by(|a, b| a.position.total_cmp(&b.position));
|
||||
stops.dedup_by(|a, b| (a.position - b.position).abs() < 1e-6);
|
||||
@@ -77,10 +86,39 @@ fn parse_stops(p: &Value) -> Result<Vec<TabStop>> {
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// More than the limit is taken only when every targeted paragraph already holds at least as
|
||||
// many stops, so a paragraph that holds more can still lose them one at a time. The supplied
|
||||
// list is counted before it is read.
|
||||
let max = TabStop::MAX_STOPS;
|
||||
let supplied = p.get("stops").and_then(Value::as_array).map_or(0, Vec::len);
|
||||
if supplied > max && supplied > fewest_held(s, p)? {
|
||||
return Err(bad("text.tabs.set", format!("at most {max} tab stops")));
|
||||
}
|
||||
let stops = parse_stops(p)?;
|
||||
apply(s, p, stops, "Tab Stops")
|
||||
}
|
||||
|
||||
/// The fewest tab stops a paragraph that `text.tabs.set` with `p` targets holds (0 with none).
|
||||
fn fewest_held(s: &Session, p: &Value) -> Result<usize> {
|
||||
let ids = text_targets(s, p, "text.tabs.set")?;
|
||||
let range = TextRange::parse(p, "text.tabs.set")?;
|
||||
let doc = &s.doc()?.doc;
|
||||
let mut fewest: Option<usize> = None;
|
||||
for id in &ids {
|
||||
if let Some(NodeKind::Text(t)) = doc.node(*id).map(|node| &node.kind) {
|
||||
let held = match para_span(range, t) {
|
||||
None => t.para_styles().map(|pa| pa.tabs.len()).min(),
|
||||
Some(r) => r.map(|i| t.para_at(i).tabs.len()).min(),
|
||||
};
|
||||
fewest = match (fewest, held) {
|
||||
(Some(a), Some(b)) => Some(a.min(b)),
|
||||
(a, b) => a.or(b),
|
||||
};
|
||||
}
|
||||
}
|
||||
Ok(fewest.unwrap_or(0))
|
||||
}
|
||||
|
||||
fn apply(s: &mut Session, p: &Value, stops: Vec<TabStop>, label: &str) -> Result<Value> {
|
||||
let ids = text_targets(s, p, "text.tabs.set")?;
|
||||
let range = TextRange::parse(p, "text.tabs.set")?;
|
||||
@@ -128,7 +166,7 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
@@ -139,6 +177,59 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A leader of more than eight characters, an `alignOn` of more than one character and a list
|
||||
/// of more than 256 stops are errors, not cut short.
|
||||
#[test]
|
||||
fn long_leaders_long_align_on_and_too_many_stops_are_errors() {
|
||||
let err = |stops: Value| super::parse_stops(&json!({ "stops": stops })).unwrap_err().to_string();
|
||||
assert!(err(json!([{"position": 40, "leader": "123456789"}])).contains("`leader` must be at most 8 characters"));
|
||||
assert!(err(json!([{"position": 40, "alignOn": ",."}])).contains("`alignOn` must be one character"));
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute("text.create", &json!({"x": 10, "y": 20, "text": "a\tb"})).unwrap();
|
||||
let many: Vec<Value> = (0..257).map(|i| json!({"position": i})).collect();
|
||||
let e = s.execute("text.tabs.set", &json!({ "stops": many.clone() })).unwrap_err().to_string();
|
||||
assert!(e.contains("at most 256 tab stops"), "{e}");
|
||||
// The supplied list is counted, not the stops left once those at one position merge.
|
||||
let same: Vec<Value> = (0..257).map(|_| json!({"position": 5})).collect();
|
||||
assert!(s.execute("text.tabs.set", &json!({ "stops": same })).unwrap_err().to_string().contains("at most 256 tab stops"));
|
||||
assert_eq!(s.execute("text.tabs.set", &json!({ "stops": &many[..256] })).unwrap()["stops"], json!(256));
|
||||
let ok = super::parse_stops(&json!({"stops": [{"position": 0, "leader": "12345678", "alignOn": "€"}]})).unwrap();
|
||||
assert_eq!((ok[0].leader.as_str(), ok[0].align_on), ("12345678", '€'));
|
||||
}
|
||||
|
||||
/// A paragraph that already holds more than 256 stops (from a file) can lose them one at a
|
||||
/// time: a list no longer than every targeted paragraph's own is taken, a longer one is not, and
|
||||
/// a paragraph with fewer stops targeted beside it keeps the limit.
|
||||
#[test]
|
||||
fn stops_can_be_removed_from_a_paragraph_holding_more_than_the_limit() {
|
||||
use vectorcraft_doc::{NodeId, NodeKind, TabAlign, TabStop};
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
let id = NodeId(s.execute("text.create", &json!({"x": 10, "y": 20, "text": "a\tb\nc\td"})).unwrap()["id"].as_u64().unwrap());
|
||||
let held: Vec<TabStop> =
|
||||
(0..300).map(|i| TabStop { position: f64::from(i), align: TabAlign::Left, leader: String::new(), align_on: '.' }).collect();
|
||||
s.edit("Load", |d, _| {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) {
|
||||
t.edit_paras(None, |pa| pa.tabs = held.clone());
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let list = |n: i32| json!({ "stops": (0..n).map(|i| json!({"position": i})).collect::<Vec<_>>() });
|
||||
assert!(s.execute("text.tabs.set", &list(301)).unwrap_err().to_string().contains("at most 256 tab stops"));
|
||||
assert_eq!(s.execute("text.tabs.set", &list(299)).unwrap()["stops"], json!(299));
|
||||
assert_eq!(s.execute("text.tabs.get", &json!({})).unwrap()["stops"].as_array().unwrap().len(), 299);
|
||||
// The second paragraph (bytes 4 on) now holds 2 stops: 298 for both paragraphs is refused,
|
||||
// and 298 for the first alone is taken.
|
||||
s.execute("text.tabs.set", &json!({"stops": [{"position": 1}, {"position": 2}], "start": 4, "end": 4})).unwrap();
|
||||
let mut both = list(298);
|
||||
assert!(s.execute("text.tabs.set", &both).is_err());
|
||||
both["start"] = json!(0);
|
||||
both["end"] = json!(0);
|
||||
assert_eq!(s.execute("text.tabs.set", &both).unwrap()["stops"], json!(298));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_get_clear_tabs() {
|
||||
let mut s = Session::new();
|
||||
|
||||
@@ -11,8 +11,8 @@ use super::menucmds::whole_or;
|
||||
use super::stroke::StrokeChange;
|
||||
use super::typecmd::refresh_bounds;
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, has_selection, id_param,
|
||||
index, number_or, point_param, str_param, switch_or, targets, text_param,
|
||||
CommandSpec, EngineError, Result, Session, bad, bool_or, check_numbers, check_switches, cmd, color_value, has_doc, has_selection, index,
|
||||
number_or, object_param, point_param, str_param, switch_or, targets, text_param,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -40,7 +40,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character",
|
||||
[],
|
||||
None,
|
||||
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\", baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
|
||||
"{id? (default: the one selected type object), start?: byte, end?: byte (default: all text), story?: bool = false (all the text of every frame of the threaded story `id` is a frame of, in one undo step; no `start` or `end`), font?, style?, size?: pt, leading?: pt|\"auto\", tracking?, kerning?: 1/1000 em|\"auto\"|\"optical\" (the space after each character), kerningBefore?: 1/1000 em -1000..10000 (the space before a character that starts a line by itself: the first character of the text, of a paragraph or after a forced line break; no effect elsewhere; 0 by default), baselineShift?: pt, hScale?: %, vScale?: %, rotation?: deg counter-clockwise (0: upright), fill?: colour|\"none\", stroke?: colour|\"none\" (#rrggbbaa and #rgba are refused in both), keepModel?: bool (fill and stroke, as paint.setFill), strokeWidth?: pt, strokeOptions?: {weight?, cap?, join?, miterLimit?, align?, dash?, dashOffset?, alignDashes?} (as stroke.set: the character stroke), underline?, strikethrough?, allCaps?: bool, smallCaps?: bool, position?: \"normal\"|\"superscript\"|\"subscript\" (sizes from Document Setup), features?: [\"dlig\", \"-liga\", …], featureChanges?: [\"tnum\", \"-onum\", …] (OpenType features turned on, or with - off, on top of each character's own; its other features are kept), charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\", proportionalMetrics?: bool (full-width glyphs on the font's proportional widths: `palt` in horizontal type, `vpal` in vertical type), tateChuYoko?: bool (Character panel menu › Tate-chu-yoko, with Show East Asian Options: in vertical type those characters stand side by side across one em of the column; kept on the characters and ignored in horizontal type), tcyUpDown?, tcyLeftRight?: pt -1296..1296 (Character panel menu › Tate-chu-yoko Settings: in vertical type a block of tate-chu-yoko characters moves up by a positive Up/Down and down by a negative one, right by a positive Left/Right and left by a negative one, as one piece with the values of its first character; on a vertical path a positive Up/Down moves it toward the path's start and a positive Left/Right to the path's left; 0 by default; automatic digit blocks and horizontal type do not move; neither turns tateChuYoko on), standardVerticalRoman?: bool (Character panel menu › Standard Vertical Roman Alignment, with Show East Asian Options: in vertical type those half-width characters, such as Latin letters and digits, stand upright one below the other instead of being rotated; spaces and tate-chu-yoko blocks are not changed; kept on the characters and ignored in horizontal type; off by default), noBreak?: bool (Character panel menu › No Break: these characters stay on one line, including across a space inside the run), kashidas?: bool (Character panel menu › Kashidas: selected characters allow insertion only when both joined neighbors have it on; on by default), charDirection?: \"default\"|\"leftToRight\"|\"rightToLeft\" (Character panel menu › Character Direction: the characters are set left to right or right to left inside their paragraph, as a Unicode bidi embedding; default: as the bidi algorithm sets them), digits?: \"default\"|\"arabic\"|\"hindi\"|\"farsi\"|\"devanagari\"|\"bengali\"|\"gurmukhi\"|\"gujarati\"|\"odia\"|\"tamil\"|\"telugu\"|\"kannada\"|\"malayalam\" (Character panel menu › Digits: the numeral system every digit is drawn in, whatever was typed: Western, Arabic-Indic (hindi), Eastern Arabic-Indic (farsi) or an Indic script's own digits), fontHeightReference?: \"emBox\"|\"capHeight\"|\"xHeight\"|\"icfBox\" (Character panel › Set Font Height Reference: the height of the font that size measures, the em box by default; with a font that has no such height, or one outside 0.1 to 2 em, the em box), language?: name|tag (Character panel › Language: one of Document Setup's languages by name or BCP 47 tag, case-insensitive, such as \"Turkish\" or \"tr\"; the characters are shaped in it, so the font uses that language's forms (OpenType `locl`); saved as the tag, English: USA, the default, as none; new type takes the document's language), fontAxes?: {\"wght\": 650, …} (Character panel › Variable Font: the setting of each variation axis named, in the axis's units and clamped to its range; null: back to the style's own setting; other axes keep theirs; tags the font has no axis for are left out; a font or style change clears them; text.fontList {family, style} lists the axes)} style a character range (size/leading/baselineShift are document points and hScale includes the object transform; runs are split at the range ends) → {id, runs, warning?: text (the font or style set isn't available: its type is drawn in the fallback font or the family's closest style)}",
|
||||
has_doc,
|
||||
set_range_style
|
||||
),
|
||||
@@ -103,7 +103,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Step Type",
|
||||
[],
|
||||
None,
|
||||
"{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the character before it, leading its paragraph), else every selected type object → {ids}",
|
||||
"{attribute: \"size\"|\"leading\"|\"tracking\"|\"kerning\"|\"baselineShift\", by?: steps (1; negative steps down), id?, start?: byte, end?: byte, ids?: [id…] (instead of id)} step type by the Preferences › Type increments (size and leading: typeSizeIncrement, pt; tracking and kerning: trackingIncrement, 1/1000 em; baseline shift: baselineShiftIncrement, pt), what the Type tool's Alt+arrows do (Cmd/Ctrl too: five steps; horizontal: ←/→ kerning at the caret or tracking of the selection, ↑/↓ leading, Shift+↑/↓ baseline shift; vertical: ↓/↑ with or without Shift kerning or tracking, ←/→ leading, Shift+→/← baseline shift; mixed selected text objects use the horizontal mapping). The range of `id`, else the type objects in `ids`, else the text the Type tool has selected (at a caret: kerning steps the space after the character before it, or at the start of a line (of the text, a paragraph, or after a forced line break) the space before the character after it (kerningBefore, as text.setRangeStyle), and nothing at an empty line's start; leading its paragraph), else every selected type object → {ids}",
|
||||
has_doc,
|
||||
type_step
|
||||
),
|
||||
@@ -148,7 +148,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Reset Tracking and Kerning",
|
||||
[],
|
||||
Some("Cmd+Alt+Q"),
|
||||
"{ids?: [id…]} set tracking to 0 and clear manual kerning without changing the automatic method in all the text of the type objects in `ids`, else in the text the Type tool has selected (at a caret: only the kerning of the character before it), else in every selected type object, as one undo step → {ids}",
|
||||
"{ids?: [id…]} set tracking to 0 and clear manual kerning (kerning and kerningBefore) without changing the automatic method in all the text of the type objects in `ids`, else in the text the Type tool has selected (at a caret: only the kerning there, as type.step steps it), else in every selected type object, as one undo step → {ids}",
|
||||
has_selection,
|
||||
reset_tracking
|
||||
),
|
||||
@@ -272,7 +272,7 @@ fn range_of(p: &Value, len: usize, cmd: &str) -> Result<(usize, usize)> {
|
||||
|
||||
fn edit_range(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.editRange";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
let t = text_ref(s, id)?;
|
||||
let len = edit::runs_len(&t.runs);
|
||||
let (a, b) = range_of(p, len, C)?;
|
||||
@@ -337,7 +337,7 @@ fn clear_param(s: &Session, p: &Value, id: NodeId, c: &str) -> Result<Vec<NodeId
|
||||
|
||||
fn start_list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.startList";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
let t = text_ref(s, id)?;
|
||||
let len = edit::runs_len(&t.runs);
|
||||
let at = offset_or(p, "at", len, C)?.min(len);
|
||||
@@ -365,7 +365,7 @@ fn start_list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
|
||||
fn get_range(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad("text.getRange", "missing `id`"))?;
|
||||
let id = object_param(p, "id", "text.getRange")?.ok_or_else(|| bad("text.getRange", "missing `id`"))?;
|
||||
if switch_or(p, "story", false, "text.getRange")? {
|
||||
return get_story(s, p, id);
|
||||
}
|
||||
@@ -430,6 +430,8 @@ pub(crate) struct CharChange {
|
||||
leading: Option<Option<f64>>,
|
||||
tracking: Option<f64>,
|
||||
kerning: Option<Option<f64>>,
|
||||
/// The space before a character that starts a line by itself (`kerningBefore`).
|
||||
kerning_before: Option<f64>,
|
||||
optical_kerning: Option<bool>,
|
||||
baseline_shift: Option<f64>,
|
||||
h_scale: Option<f64>,
|
||||
@@ -691,7 +693,7 @@ fn auto_or_num(p: &Value, k: &str, cmd: &str) -> Result<Option<Option<f64>>> {
|
||||
impl CharChange {
|
||||
/// `setup` gives the superscript, subscript and small caps proportions.
|
||||
pub(crate) fn parse(p: &Value, cmd: &str, setup: &vectorcraft_doc::DocSetup) -> Result<Self> {
|
||||
check_numbers(p, &["size", "tracking", "baselineShift", "hScale", "vScale", "rotation", "strokeWidth"], cmd)?;
|
||||
check_numbers(p, &["size", "tracking", "kerningBefore", "baselineShift", "hScale", "vScale", "rotation", "strokeWidth"], cmd)?;
|
||||
check_switches(
|
||||
p,
|
||||
&["underline", "strikethrough", "allCaps", "proportionalMetrics", "tateChuYoko", "standardVerticalRoman", "noBreak", "kashidas"],
|
||||
@@ -720,6 +722,7 @@ impl CharChange {
|
||||
Some(Value::String(v)) if v.eq_ignore_ascii_case("optical") || v.eq_ignore_ascii_case("auto") => Some(None),
|
||||
Some(v) => Some(Some(v.as_f64().ok_or_else(|| bad(cmd, "kerning must be a number, \"auto\", or \"optical\""))?)),
|
||||
},
|
||||
kerning_before: num("kerningBefore"),
|
||||
optical_kerning: match p.get("kerning") {
|
||||
Some(Value::String(v)) if v.eq_ignore_ascii_case("optical") => Some(true),
|
||||
Some(Value::String(v)) if v.eq_ignore_ascii_case("auto") => Some(false),
|
||||
@@ -777,6 +780,7 @@ impl CharChange {
|
||||
&& self.leading.is_none()
|
||||
&& self.tracking.is_none()
|
||||
&& self.kerning.is_none()
|
||||
&& self.kerning_before.is_none()
|
||||
&& self.optical_kerning.is_none()
|
||||
&& self.baseline_shift.is_none()
|
||||
&& self.h_scale.is_none()
|
||||
@@ -883,6 +887,9 @@ impl CharChange {
|
||||
if let Some(v) = self.kerning {
|
||||
st.kerning = v.map(|k| k.clamp(-1000.0, 10000.0));
|
||||
}
|
||||
if let Some(v) = self.kerning_before {
|
||||
st.kerning_before = v.clamp(-1000.0, 10000.0);
|
||||
}
|
||||
if let Some(v) = self.optical_kerning {
|
||||
st.optical_kerning = v;
|
||||
}
|
||||
@@ -1254,7 +1261,7 @@ fn drawn_glyph(
|
||||
|
||||
fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.setGlyphAlternate";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
let gid = match p.get("gid") {
|
||||
None => return Err(bad(C, "missing `gid` (a glyph id, or null for the default glyph)")),
|
||||
Some(Value::Null) => None,
|
||||
@@ -1344,7 +1351,7 @@ fn set_glyph_alternate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn glyph_alternates(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.glyphAlternates";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
let t = text_ref(s, id)?;
|
||||
let (ch, bytes, face) = glyph_target(&t, p, C)?;
|
||||
let default = face.glyph_for(ch);
|
||||
@@ -1359,7 +1366,7 @@ fn glyph_alternates(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.touchType";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
check_numbers(p, &["start"], C)?;
|
||||
let start = byte_param(p, "start").ok_or_else(|| bad(C, "missing `start` (the byte offset of a character)"))?;
|
||||
if !["dx", "dy", "hScale", "vScale", "rotation"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) {
|
||||
@@ -1585,7 +1592,7 @@ fn touch_type(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn create_in_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.createInPath";
|
||||
let pid = id_param(p, "path").ok_or_else(|| bad(C, "missing `path` (a path object id)"))?;
|
||||
let pid = object_param(p, "path", C)?.ok_or_else(|| bad(C, "missing `path` (a path object id)"))?;
|
||||
let on_path = match str_param(p, "mode").unwrap_or("area") {
|
||||
"area" => false,
|
||||
"onPath" | "path" => true,
|
||||
@@ -1694,17 +1701,16 @@ pub(crate) fn editing_story(s: &Session) -> Vec<NodeId> {
|
||||
s.active().map(|st| super::threads::story_of(&st.doc, id)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A text range a type shortcut changes: its type object, its bytes, and the caret's byte when it
|
||||
/// came from a caret ([`type_ranges`]).
|
||||
pub(crate) type TypeRange = (NodeId, usize, usize, Option<usize>);
|
||||
|
||||
/// The text ranges a type shortcut changes: the range of `id`, else all the text of the type
|
||||
/// objects in `ids`, else the text the Type tool has selected (all the text of every frame of the
|
||||
/// story after Select All in threaded text, [`editing_story`]), else all the text of every selected
|
||||
/// type object. At a caret, `at_caret` gives the range from the plain text and the caret's byte
|
||||
/// (None: nothing changes there). Each range comes with whether it came from a caret.
|
||||
pub(crate) fn type_ranges(
|
||||
s: &mut Session,
|
||||
p: &Value,
|
||||
c: &str,
|
||||
at_caret: impl Fn(&str, usize) -> Option<(usize, usize)>,
|
||||
) -> Result<Vec<(NodeId, usize, usize, bool)>> {
|
||||
/// (None: nothing changes there). Each range comes with the caret's byte when it came from a caret.
|
||||
pub(crate) fn type_ranges(s: &mut Session, p: &Value, c: &str, at_caret: impl Fn(&str, usize) -> Option<(usize, usize)>) -> Result<Vec<TypeRange>> {
|
||||
// (text, its range; None: all of it).
|
||||
let targets: Vec<(NodeId, Option<(usize, usize)>)> = match super::object_param(p, "id", c)? {
|
||||
// An object that isn't type is refused as `ids` of it is.
|
||||
@@ -1728,10 +1734,10 @@ pub(crate) fn type_ranges(
|
||||
let text = text_ref(s, id)?.plain_text();
|
||||
let (a, b) = range.map_or((0, text.len()), |(a, b)| (a.min(text.len()), b.min(text.len())));
|
||||
let (a, b, caret) = if a < b {
|
||||
(a, b, false)
|
||||
(a, b, None)
|
||||
} else {
|
||||
match at_caret(&text, a) {
|
||||
Some((a, b)) => (a, b, true),
|
||||
Some((x, y)) => (x, y, Some(a)),
|
||||
None => continue,
|
||||
}
|
||||
};
|
||||
@@ -1763,24 +1769,31 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Step::Tracking | Step::Kerning => prefs.tracking_increment,
|
||||
Step::BaselineShift => prefs.baseline_shift_increment,
|
||||
};
|
||||
// The ranges stepped. At a caret: kerning is the space after the character before it, leading
|
||||
// the paragraph's; the rest wait for a selection.
|
||||
// The ranges stepped. At a caret: kerning is the space after the character before it, or at
|
||||
// the start of a line the space before the character after it (#5111), leading the
|
||||
// paragraph's; the rest wait for a selection.
|
||||
let ranges = type_ranges(s, p, C, |text, a| match step {
|
||||
Step::Kerning => Some((edit::prev_char(text, a), a)),
|
||||
Step::Kerning => edit::caret_kerning_target(text, a).map(|(r, _)| (r.start, r.end)),
|
||||
Step::Leading => {
|
||||
let para = edit::paragraph_at(text, a);
|
||||
Some((para.start, para.end))
|
||||
}
|
||||
_ => None,
|
||||
})?;
|
||||
// At a caret, the kerning stepped: (whether it is the space before the character, its value).
|
||||
let mut caret_kerning = Vec::with_capacity(ranges.len());
|
||||
for &(id, a, b, caret) in &ranges {
|
||||
let value = if matches!(step, Step::Kerning) && caret {
|
||||
let t = text_ref(s, id)?;
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
|
||||
Some(effective_kerning(vectorcraft_text::FontDb::global(), &t, &lay, a, b))
|
||||
} else {
|
||||
None
|
||||
let value = match caret {
|
||||
Some(c) if matches!(step, Step::Kerning) => {
|
||||
let t = text_ref(s, id)?;
|
||||
if edit::caret_kerning_target(&t.plain_text(), c).is_some_and(|(_, before)| before) {
|
||||
Some((true, edit::style_at(&t.runs, a + 1).kerning_before))
|
||||
} else {
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
|
||||
Some((false, effective_kerning(vectorcraft_text::FontDb::global(), &t, &lay, a, b)))
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
caret_kerning.push(value);
|
||||
}
|
||||
@@ -1829,10 +1842,13 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.leading = Some(super::typecmd::local_type_value(t, leading * points + inc, (0.1, 5000.0), false, C)?);
|
||||
}
|
||||
Step::Tracking => st.tracking = (st.tracking + inc).clamp(-1000.0, 10000.0),
|
||||
Step::Kerning => {
|
||||
let current = caret_kerning.get(range_index).copied().flatten().unwrap_or_else(|| st.kerning.unwrap_or(0.0));
|
||||
st.kerning = Some((current + inc).clamp(-1000.0, 10000.0));
|
||||
}
|
||||
Step::Kerning => match caret_kerning.get(range_index).copied().flatten() {
|
||||
Some((true, current)) => st.kerning_before = (current + inc).clamp(-1000.0, 10000.0),
|
||||
caret => {
|
||||
let current = caret.map_or_else(|| st.kerning.unwrap_or(0.0), |(_, v)| v);
|
||||
st.kerning = Some((current + inc).clamp(-1000.0, 10000.0));
|
||||
}
|
||||
},
|
||||
Step::BaselineShift => {
|
||||
st.baseline_shift = super::typecmd::local_type_value(t, st.baseline_shift * points + inc, (-1296.0, 1296.0), false, C)?;
|
||||
}
|
||||
@@ -1849,17 +1865,22 @@ fn type_step(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
/// Cmd/Ctrl+Alt+Q: tracking 0 and manual kerning cleared in the type objects in
|
||||
/// `ids`, else in the Type tool's selected text, else in every selected type object. At a caret,
|
||||
/// only the kerning of the character before it changes, as Alt+←/→ in horizontal type or Alt+↓/↑ in vertical type kerns there.
|
||||
/// The automatic method remains selected.
|
||||
/// only the kerning there changes, as Alt+←/→ in horizontal type or Alt+↓/↑ in vertical type kerns
|
||||
/// there: of the character before it, or at the start of a line the space before the character
|
||||
/// after it ([`edit::caret_kerning_target`]). The automatic method remains selected.
|
||||
fn reset_tracking(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let ranges = type_ranges(s, p, "type.resetTracking", |text, a| Some((edit::prev_char(text, a), a)))?;
|
||||
let ranges = type_ranges(s, p, "type.resetTracking", |text, a| edit::caret_kerning_target(text, a).map(|(r, _)| (r.start, r.end)))?;
|
||||
if !ranges.is_empty() {
|
||||
s.edit("Reset Tracking and Kerning", |d, _| {
|
||||
for &(id, a, b, caret) in &ranges {
|
||||
let t = text_mut(d, id).ok_or(EngineError::NoNode(id))?;
|
||||
edit::style_range(&mut t.runs, a, b, |st| {
|
||||
st.kerning = None;
|
||||
if !caret {
|
||||
let before = caret.and_then(|c| edit::caret_kerning_target(&t.plain_text(), c)).map(|(_, before)| before);
|
||||
edit::style_range(&mut t.runs, a, b, |st| match before {
|
||||
Some(true) => st.kerning_before = 0.0,
|
||||
Some(false) => st.kerning = None,
|
||||
None => {
|
||||
st.kerning = None;
|
||||
st.kerning_before = 0.0;
|
||||
st.tracking = 0.0;
|
||||
}
|
||||
});
|
||||
@@ -1975,7 +1996,7 @@ fn fit_headline(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn discard_empty(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.discardEmpty";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing `id`"))?;
|
||||
if edit::runs_len(&text_ref(s, id)?.runs) > 0 {
|
||||
return Ok(json!({"removed": false}));
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind, ParaStyle, TextStyleDef};
|
||||
use vectorcraft_doc::{CharStyle, Document, Node, NodeId, NodeKind, ParaStyle, TabStop, TextStyleDef};
|
||||
|
||||
use super::clipboard::resources::import_text_styles;
|
||||
use super::typecmd::{refresh_bounds, text_targets};
|
||||
@@ -125,7 +125,7 @@ macro_rules! style_cmds {
|
||||
}
|
||||
|
||||
/// The params of `charStyle.load`, `paraStyle.load` and `textStyle.loadAll`.
|
||||
const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind";
|
||||
const LOAD_PARAMS: &str = "{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} copy the styles of this kind (textStyle.loadAll: character and paragraph styles) from a document VectorCraft opens (see document.formats) into this one, after its own, in one undo step, with the swatches and patterns they paint with, the symbols and brushes those patterns use, and the styles of either kind that type in those patterns and symbols is set in, as Paste brings those of pasted type (a global or spot color whose name this document gives another color is this document's). A style that is the same as the style here of its name, or of its name with a number (`Body 2`), isn't added again; any other is added under a free name (`Body 2`). The file's Normal styles aren't loaded, and a style whose attributes don't read or are out of the range charStyle.new or paraStyle.new takes, or whose name is empty, is skipped → {added: [names here], existing: [names already here], skipped: [names in the file]} (textStyle.loadAll: {charStyles: {…}, paraStyles: {…}}); charStyle.load and paraStyle.load list only the styles of their own kind";
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
let mut v = style_cmds!(
|
||||
@@ -148,13 +148,13 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"paraStyle",
|
||||
"Paragraph Styles",
|
||||
"Paragraph",
|
||||
"; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; tab positions 0..=100000 pt"
|
||||
"; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; changed tabs: at most 256 stops, each changed stop's position 0..=100000 pt and leader at most 8 characters, sorted by position keeping the first of stops at one position"
|
||||
));
|
||||
v.push(spec(
|
||||
"paraStyle.edit",
|
||||
"Edit Paragraph Style",
|
||||
&[],
|
||||
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; tab positions 0..=100000 pt",
|
||||
"{name, to, attrs: {…}} replace name and sparse attributes in one undo step; users keep local overrides; changed numeric attrs: indents, space_before and space_after -1296..=1296 pt; hyphenation words_longer_than 1..=25, after_first and before_last 1..=15, hyphen_limit 0..=25, zone 0..=1296 pt; justification word_spacing 0..=1000%, letter_spacing -100..=500%, glyph_scaling 50..=200% (each [min, desired, max] in order), auto_leading 0..=500%; changed tabs: at most 256 stops, each changed stop's position 0..=100000 pt and leader at most 8 characters, sorted by position keeping the first of stops at one position",
|
||||
|s, p| edit_style(s, p, Kind::Para),
|
||||
true,
|
||||
));
|
||||
@@ -188,8 +188,10 @@ fn to_attrs<T: Serialize>(v: &T) -> Map<String, Value> {
|
||||
/// from a style instead leaves the text's own value alone.
|
||||
pub fn char_attrs(v: &CharStyle) -> Map<String, Value> {
|
||||
let mut m = to_attrs(v);
|
||||
// A chosen glyph belongs to one character, not to a reusable character style.
|
||||
// A chosen glyph belongs to one character, and the space before a line's first character to
|
||||
// where it stands (#5111), not to a reusable character style.
|
||||
m.remove("glyphAlternate");
|
||||
m.remove("kerningBefore");
|
||||
for (k, x) in [
|
||||
("font_version", json!(v.font_version)),
|
||||
("fontAxes", json!(v.font_axes)),
|
||||
@@ -243,6 +245,7 @@ pub fn para_attrs(v: &ParaStyle) -> Map<String, Value> {
|
||||
("kinsoku_type", json!(v.kinsoku_type)),
|
||||
("roman_hanging", json!(v.roman_hanging)),
|
||||
("kashida", json!(v.kashida)),
|
||||
("korean_line_break_anywhere", json!(v.korean_line_break_anywhere)),
|
||||
] {
|
||||
m.insert(k.into(), x);
|
||||
}
|
||||
@@ -530,6 +533,12 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
if m.contains_key("glyphAlternate") {
|
||||
return Err(bad(&c, "`glyphAlternate` belongs to one character, not to a character style (text.setGlyphAlternate sets it)"));
|
||||
}
|
||||
if m.contains_key("kerningBefore") {
|
||||
return Err(bad(
|
||||
&c,
|
||||
"`kerningBefore` belongs to a line's first character, not to a character style (text.setRangeStyle sets it)",
|
||||
));
|
||||
}
|
||||
let mut st = with_attrs(&CharStyle::default(), m, &c)?;
|
||||
let changed = |key: &str| m.contains_key(key) && kept.and_then(|k| k.get(key)) != m.get(key);
|
||||
for (key, value, lo, hi) in
|
||||
@@ -569,8 +578,9 @@ fn attrs_param(d: &Document, p: &Value, kind: Kind, verb: &str, kept: Option<&Ma
|
||||
char_attrs(&st)
|
||||
}
|
||||
Kind::Para => {
|
||||
let st = with_attrs(&ParaStyle::default(), m, &c)?;
|
||||
let mut st = with_attrs(&ParaStyle::default(), m, &c)?;
|
||||
para_ranges(&st, m, kept, &c)?;
|
||||
sort_tabs(&mut st, m, kept);
|
||||
para_attrs(&st)
|
||||
}
|
||||
};
|
||||
@@ -587,7 +597,8 @@ const PARA_DISTANCE: f64 = 1296.0;
|
||||
/// Check the paragraph attributes of `st` (read from `attrs`) that differ from `kept` against the
|
||||
/// ranges `text.setFormat` keeps them to: the indents and the space before and after, each
|
||||
/// Hyphenation option, each Justification option (Minimum, Desired and Maximum in order, as
|
||||
/// `attrs` gives them) and the position of each tab stop. A value `kept` has is not checked.
|
||||
/// `attrs` gives them), and the number of tab stops with the position and leader of each stop
|
||||
/// `kept` does not hold. A value `kept` has is not checked.
|
||||
fn para_ranges(st: &ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>, c: &str) -> Result<()> {
|
||||
let within = |key: &str, value: f64, lo: f64, hi: f64| {
|
||||
if (lo..=hi).contains(&value) { Ok(()) } else { Err(bad(c, format!("`{key}` must be from {lo} to {hi}"))) }
|
||||
@@ -644,18 +655,37 @@ fn para_ranges(st: &ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<Str
|
||||
}
|
||||
}
|
||||
if changed("tabs") {
|
||||
let kept_tabs: Vec<f64> = kept
|
||||
.and_then(|k| k.get("tabs"))
|
||||
.and_then(Value::as_array)
|
||||
.map(|stops| stops.iter().filter_map(|s| s.get("position").and_then(Value::as_f64)).collect())
|
||||
.unwrap_or_default();
|
||||
for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(&stop.position)) {
|
||||
within("tabs.position", stop.position, 0.0, 100_000.0)?;
|
||||
let kept_tabs = kept_tab_stops(kept);
|
||||
let max = TabStop::MAX_STOPS;
|
||||
if st.tabs.len() > max.max(kept_tabs.len()) {
|
||||
return Err(bad(c, format!("at most {max} tab stops")));
|
||||
}
|
||||
for stop in st.tabs.iter().filter(|stop| !kept_tabs.contains(stop)) {
|
||||
within("tabs.position", stop.position, 0.0, TabStop::MAX_POSITION)?;
|
||||
let (label, max) = ("`tabs.leader`", TabStop::MAX_LEADER);
|
||||
if stop.leader.chars().count() > max {
|
||||
return Err(bad(c, format!("{label} must be at most {max} characters")));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The tab stops `kept` holds, each as it reads (a stop that does not read is left out).
|
||||
fn kept_tab_stops(kept: Option<&Map<String, Value>>) -> Vec<TabStop> {
|
||||
let stops = kept.and_then(|k| k.get("tabs")).and_then(Value::as_array);
|
||||
stops.into_iter().flatten().filter_map(|s| serde_json::from_value(s.clone()).ok()).collect()
|
||||
}
|
||||
|
||||
/// `st`'s tab stops sorted by position, keeping the first of stops within 1e-6 pt of each other,
|
||||
/// as `text.tabs.set` keeps them, when `attrs` changes them from `kept`.
|
||||
fn sort_tabs(st: &mut ParaStyle, attrs: &Map<String, Value>, kept: Option<&Map<String, Value>>) {
|
||||
if attrs.contains_key("tabs") && kept.and_then(|k| k.get("tabs")) != attrs.get("tabs") {
|
||||
st.tabs.sort_by(|a, b| a.position.total_cmp(&b.position));
|
||||
st.tabs.dedup_by(|a, b| (a.position - b.position).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
/// Check a character style's `fill` or `stroke` (`key`): each solid color and gradient stop has a
|
||||
/// tint from 0 to 1, and a link to a global swatch of `d`, whose color at that tint it takes.
|
||||
fn style_paint(d: &Document, paint: &mut vectorcraft_color::Paint, key: &str, c: &str) -> Result<()> {
|
||||
@@ -1011,10 +1041,29 @@ fn unused(s: &mut Session, kind: Kind) -> Result<Value> {
|
||||
|
||||
/// The styles of `kind` in `src` that load, with their source names so that art in the file keeps
|
||||
/// referring to them: not the Normal style, and not one whose attributes don't read, whose sizes,
|
||||
/// scales, leading, shifts or stroke width are out of the range `charStyle.new` takes, or whose name
|
||||
/// is empty, which are skipped. → (the styles, the names in `src` of those skipped)
|
||||
/// scales, leading, shifts or stroke width are out of the range `charStyle.new` takes, whose
|
||||
/// indents, spacing, Hyphenation or Justification options or tab stops are out of the range
|
||||
/// `paraStyle.new` takes, or whose name is empty, which are skipped. → (the styles, the names in
|
||||
/// `src` of those skipped)
|
||||
fn loadable(src: &Document, kind: Kind) -> (Vec<TextStyleDef>, Vec<String>) {
|
||||
const RANGED: [&str; 8] = ["size", "h_scale", "v_scale", "leading", "baseline_shift", "tcyUpDown", "tcyLeftRight", "stroke_width"];
|
||||
const RANGED: [&str; 16] = [
|
||||
"size",
|
||||
"h_scale",
|
||||
"v_scale",
|
||||
"leading",
|
||||
"baseline_shift",
|
||||
"tcyUpDown",
|
||||
"tcyLeftRight",
|
||||
"stroke_width",
|
||||
"left_indent",
|
||||
"right_indent",
|
||||
"first_line_indent",
|
||||
"space_before",
|
||||
"space_after",
|
||||
"hyphenation",
|
||||
"justification",
|
||||
"tabs",
|
||||
];
|
||||
let (mut defs, mut skipped) = (vec![], vec![]);
|
||||
for def in kind.defs(src) {
|
||||
let name = def.name.as_str();
|
||||
|
||||
@@ -1336,7 +1336,8 @@ fn para_style_redefined_to_the_defaults_updates_its_paragraphs() {
|
||||
|
||||
/// The same for character styles: Auto kerning and the Roman baseline alignment, which the
|
||||
/// run's JSON leaves out, are captured and reach the style's users. A glyph choice belongs to
|
||||
/// one character, so it is not a reusable style attribute.
|
||||
/// one character, and the space before a line's first character to where it stands (#5111), so
|
||||
/// neither is a reusable style attribute.
|
||||
#[test]
|
||||
fn char_style_redefined_to_the_defaults_updates_its_text() {
|
||||
use vectorcraft_doc::CharAlign;
|
||||
@@ -1356,6 +1357,7 @@ fn char_style_redefined_to_the_defaults_updates_its_text() {
|
||||
assert_eq!((kerning(&s), aligns(&s)), ([None, None, Some(60.0)], [CharAlign::RomanBaseline; 3]));
|
||||
let mut reusable = settable::<CharStyle>();
|
||||
reusable.remove("glyphAlternate");
|
||||
reusable.remove("kerningBefore");
|
||||
assert_eq!(defined(&s, 0), reusable, "Redefine captures every reusable attribute");
|
||||
s.execute("charStyle.new", &json!({"name": "Copy", "id": local})).unwrap();
|
||||
assert_eq!(defined(&s, 1), reusable, "New captures every reusable attribute");
|
||||
@@ -1729,3 +1731,77 @@ fn paragraph_style_attributes_are_checked_before_a_definition_changes() {
|
||||
assert!(error.contains(&format!("`{key}`")), "{attrs}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A paragraph style's changed tab stops are checked stop by stop: a stop the style holds is kept
|
||||
/// as it is, and a stop at a held position with another alignment is a changed stop. A changed
|
||||
/// stop's leader has at most eight characters and its Align On one character, a changed list has
|
||||
/// at most 256 stops (or as many as the style holds, here 300), and the stops are stored sorted by position,
|
||||
/// keeping the first of stops at one position.
|
||||
#[test]
|
||||
fn paragraph_style_tab_stops_are_checked_by_stop_and_sorted() {
|
||||
let (mut s, _) = session_with_text("Text");
|
||||
s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {}})).unwrap();
|
||||
let def = |s: &Session| s.doc().unwrap().doc.para_styles.iter().find(|d| d.name == "Body").unwrap().attrs.clone();
|
||||
let doc = std::sync::Arc::make_mut(&mut s.doc_mut().unwrap().doc);
|
||||
let held: Vec<Value> =
|
||||
(0..300).map(|i| json!({"position": 200000.0 + f64::from(i), "align": "left", "leader": "123456789", "alignOn": "."})).collect();
|
||||
doc.para_styles.iter_mut().find(|d| d.name == "Body").unwrap().attrs.insert("tabs".into(), Value::from(held.clone()));
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let mut moved = held.clone();
|
||||
moved[0]["align"] = json!("right");
|
||||
for (stops, why) in [
|
||||
(Value::from(moved), "`tabs.position`"),
|
||||
(json!([{"position": 36.0, "leader": "123456789"}]), "`tabs.leader` must be at most 8 characters"),
|
||||
(Value::from((0..301).map(|i| json!({"position": f64::from(i)})).collect::<Vec<_>>()), "at most 256 tab stops"),
|
||||
(json!([{"position": 36.0, "alignOn": ",."}]), "expected a character"),
|
||||
] {
|
||||
for cmd in ["paraStyle.edit", "paraStyle.setAttrs"] {
|
||||
let params = match cmd {
|
||||
"paraStyle.edit" => json!({"name": "Body", "to": "Body", "attrs": {"tabs": stops}}),
|
||||
_ => json!({"name": "Body", "attrs": {"tabs": stops}}),
|
||||
};
|
||||
let error = s.execute(cmd, ¶ms).unwrap_err().to_string();
|
||||
assert!(error.contains(why), "{cmd}: {error}");
|
||||
}
|
||||
}
|
||||
let many = Value::from((0..257).map(|i| json!({"position": f64::from(i)})).collect::<Vec<_>>());
|
||||
let error = s.execute("paraStyle.new", &json!({"name": "Other", "attrs": {"tabs": many}})).unwrap_err().to_string();
|
||||
assert!(error.contains("at most 256 tab stops"), "{error}");
|
||||
assert_eq!(s.doc().unwrap().doc, before);
|
||||
// The held stops stay while one is dropped and another attribute changes.
|
||||
s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"tabs": &held[1..], "left_indent": 4.0}})).unwrap();
|
||||
assert_eq!(def(&s)["tabs"].as_array().map(Vec::len), Some(299));
|
||||
let stops = json!([{"position": 72.0, "align": "right"}, {"position": 36.0}, {"position": 36.0000001, "align": "center"}, {"position": 0.0, "leader": "12345678"}]);
|
||||
s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"tabs": stops}})).unwrap();
|
||||
assert_eq!(
|
||||
def(&s)["tabs"],
|
||||
json!([{"position": 0.0, "align": "left", "leader": "12345678", "alignOn": "."}, {"position": 36.0, "align": "left", "alignOn": "."},
|
||||
{"position": 72.0, "align": "right", "alignOn": "."}])
|
||||
);
|
||||
s.execute("paraStyle.setAttrs", &json!({"name": "Body", "attrs": {"tabs": []}})).unwrap();
|
||||
assert_eq!(def(&s)["tabs"], json!([]), "an empty list stays set");
|
||||
}
|
||||
|
||||
/// Load Paragraph Styles and Load All Styles skip a paragraph style whose indents, spacing,
|
||||
/// Hyphenation or Justification options or tab stops are out of the range `paraStyle.new` takes,
|
||||
/// and load the others with their stops.
|
||||
#[test]
|
||||
fn loading_skips_paragraph_styles_out_of_range() {
|
||||
let file = [
|
||||
("Good", json!({"left_indent": 6.0, "tabs": [{"position": 36.0, "align": "decimal", "alignOn": ","}]})),
|
||||
("Indent", json!({"left_indent": 2000.0})),
|
||||
("Space", json!({"space_after": -1300.0})),
|
||||
("Hyphens", json!({"hyphenation": {"words_longer_than": 40}})),
|
||||
("Spacing", json!({"justification": {"word_spacing": [120.0, 100.0, 133.0]}})),
|
||||
("Leader", json!({"tabs": [{"position": 10.0, "leader": "123456789"}]})),
|
||||
];
|
||||
let data = styles_file(&[], &file);
|
||||
for cmd in ["paraStyle.load", "textStyle.loadAll"] {
|
||||
let (mut s, _) = session_with_text("Title");
|
||||
let r = s.execute(cmd, &json!({"dataBase64": data, "name": "Other.vectorcraft"})).unwrap();
|
||||
let r = if cmd == "textStyle.loadAll" { r["paraStyles"].clone() } else { r };
|
||||
assert_eq!(r, json!({"added": ["Good"], "existing": [], "skipped": ["Indent", "Space", "Hyphens", "Spacing", "Leader"]}), "{cmd}");
|
||||
let good = super::style_attrs(&s.doc().unwrap().doc, true, "Good").unwrap();
|
||||
assert_eq!(good["tabs"], json!([{"position": 36.0, "align": "decimal", "alignOn": ","}]), "{cmd}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,8 +10,8 @@ use vectorcraft_geom::{Affine, PathData, Vec2};
|
||||
use super::edit::selected_roots;
|
||||
use super::pathops::{length_given, number_given, shape_node};
|
||||
use super::{
|
||||
CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, id_param, index, number_or, ok,
|
||||
str_param, switch_or, targets, text_param,
|
||||
CommandSpec, EngineError, Result, Session, bad, check_numbers, cmd, color_value, f64_req, has_doc, has_selection, index, number_or, object_param,
|
||||
ok, str_param, switch_or, targets, text_param,
|
||||
};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -1273,7 +1273,7 @@ fn reshape_area(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
};
|
||||
let mut items = Vec::with_capacity(raw.len());
|
||||
for it in raw {
|
||||
let id = id_param(it, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(it, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let mut refs = super::select::checked_refs(it.get("anchors"), C)?;
|
||||
refs.sort_unstable();
|
||||
refs.dedup();
|
||||
@@ -1304,7 +1304,7 @@ fn reshape_area(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn reshape_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.reshapePath";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let mut refs = super::select::checked_refs(p.get("anchors"), C)?;
|
||||
refs.sort_unstable();
|
||||
refs.dedup();
|
||||
@@ -1335,7 +1335,7 @@ fn reshape_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
fn set_path_handle(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.setPathHandle";
|
||||
let id = id_param(p, "id").ok_or_else(|| bad(C, "missing id"))?;
|
||||
let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?;
|
||||
let si = super::draw2::usize_opt(p, "subpath", C)?.unwrap_or(0);
|
||||
let ai = p.get("anchor").and_then(Value::as_u64).map(index).ok_or_else(|| bad(C, "missing anchor"))?;
|
||||
let out = super::object::choice(p, C, "which", &["in", "out"])? != Some("in");
|
||||
|
||||
@@ -397,6 +397,49 @@ fn roman_hanging_punctuation_is_set_per_paragraph_and_saved_only_when_on() {
|
||||
assert!(text(&s).para_at(1).roman_hanging);
|
||||
}
|
||||
|
||||
/// Paragraph panel menu › Korean Line Break Anywhere: new type has it off and saves that;
|
||||
/// `text.setFormat {koreanLineBreakAnywhere}` sets it per paragraph in one undo step and refuses a
|
||||
/// value that is not true or false, a paragraph saved before the option opens with it on, and
|
||||
/// paragraph styles carry it. `text.setRangeStyle`, a character command, does not take it.
|
||||
#[test]
|
||||
fn korean_line_break_anywhere_is_set_per_paragraph_and_saved_only_when_off() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 10, "size": 20, "text": "가나다\n라마"})).unwrap()["id"].as_u64().unwrap();
|
||||
let text = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
assert!(!text(&s).para_at(0).korean_line_break_anywhere, "new type has it off");
|
||||
assert_eq!(serde_json::to_value(text(&s).para_at(0)).unwrap()["korean_line_break_anywhere"], false);
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
// Only the first paragraph (the caret's range).
|
||||
s.execute("text.setFormat", &json!({"koreanLineBreakAnywhere": true, "start": 0, "end": 0})).unwrap();
|
||||
assert!(text(&s).para_at(0).korean_line_break_anywhere && !text(&s).para_at(1).korean_line_break_anywhere);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
assert!(serde_json::to_value(text(&s).para_at(0)).unwrap().get("korean_line_break_anywhere").is_none());
|
||||
let back: vectorcraft_doc::ParaStyle = serde_json::from_value(serde_json::to_value(text(&s).para_at(0)).unwrap()).unwrap();
|
||||
assert!(back.korean_line_break_anywhere);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert!(!text(&s).para_at(0).korean_line_break_anywhere);
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert!(text(&s).para_at(0).korean_line_break_anywhere);
|
||||
// Saved before the option: on, the line breaks it was laid out with.
|
||||
let old: vectorcraft_doc::ParaStyle = serde_json::from_value(json!({"justify": "Left"})).unwrap();
|
||||
assert!(old.korean_line_break_anywhere);
|
||||
assert!(s.execute("text.setFormat", &json!({"ids": [id], "koreanLineBreakAnywhere": "yes"})).is_err());
|
||||
assert!(s.execute("text.setRangeStyle", &json!({"id": id, "koreanLineBreakAnywhere": false})).is_err());
|
||||
assert!(text(&s).para_at(0).korean_line_break_anywhere, "a refused call changes nothing");
|
||||
// A paragraph style carries it.
|
||||
s.execute("paraStyle.new", &json!({"name": "Anywhere", "attrs": {"korean_line_break_anywhere": true}})).unwrap();
|
||||
s.execute("paraStyle.apply", &json!({"name": "Anywhere", "id": id})).unwrap();
|
||||
assert!(text(&s).para_at(1).korean_line_break_anywhere);
|
||||
s.execute("paraStyle.new", &json!({"name": "Words", "attrs": {"korean_line_break_anywhere": false}})).unwrap();
|
||||
s.execute("paraStyle.apply", &json!({"name": "Words", "id": id})).unwrap();
|
||||
assert!(!text(&s).para_at(0).korean_line_break_anywhere && !text(&s).para_at(1).korean_line_break_anywhere);
|
||||
}
|
||||
|
||||
/// Paragraph panel › Insert Kashidas: `text.setFormat {kashida}` sets it per paragraph in one
|
||||
/// undo step, the paragraph is saved with it only when it is not None and opens with it, an
|
||||
/// unknown value changes nothing, and paragraph styles carry it.
|
||||
|
||||
@@ -140,6 +140,35 @@ fn block_turns_off_keeping_its_sizes_and_records_nothing_when_nothing_changes()
|
||||
assert_eq!(undo_len(&s), n + 2, "already off: no undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_to_point_type_turns_block_off_keeping_its_sizes() {
|
||||
let mut s = session();
|
||||
let id = area(&mut s, 300.0, 400.0, "BIG\na much longer second line");
|
||||
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
|
||||
let sizes = |t: &TextObject| t.runs.iter().map(|r| (r.text.clone(), r.style.size, r.style.leading)).collect::<Vec<_>>();
|
||||
let fitted = sizes(&text(&s, id));
|
||||
let n = undo_len(&s);
|
||||
s.execute("type.convertToPointType", &json!({})).unwrap();
|
||||
assert_eq!(undo_len(&s), n + 1, "one undo step");
|
||||
let t = text(&s, id);
|
||||
assert!(matches!(t.kind, TextKind::Point));
|
||||
assert!(!t.dynamic_text, "point type has Dynamic Text off");
|
||||
assert_eq!(sizes(&t), fitted, "point type keeps the sizes Block set");
|
||||
assert!(serde_json::to_value(&t).unwrap().get("dynamicText").is_none(), "saved without dynamicText");
|
||||
// Back to area type, the frame is not refitted: Block stays off.
|
||||
s.execute("type.convertToAreaType", &json!({})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!(matches!(t.kind, TextKind::Area { .. }));
|
||||
assert!(!t.dynamic_text, "Block does not come on again");
|
||||
assert_eq!(sizes(&t), fitted);
|
||||
// Undo gives the Block frame back.
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let t = text(&s, id);
|
||||
assert!(t.dynamic_text && matches!(t.kind, TextKind::Area { .. }));
|
||||
assert_eq!(sizes(&t), fitted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_params_and_other_type_are_refused() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Convert To Point Type",
|
||||
["Type"],
|
||||
None,
|
||||
"{ids?|id?} area type → point type; soft line wraps become line breaks, and a frame of threaded text leaves its thread with the text it holds → {ids}",
|
||||
"{ids?|id?} area type → point type; soft line wraps become line breaks, a frame of threaded text leaves its thread with the text it holds, and Dynamic Text (Block) is turned off, keeping the sizes it set → {ids}",
|
||||
has_selection,
|
||||
to_point
|
||||
),
|
||||
@@ -311,7 +311,10 @@ fn to_area(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
continue;
|
||||
}
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
let mut b = if lay.bounds.area() > 0.0 { lay.bounds } else { t.estimate_bounds() };
|
||||
// The frame is worked out in line space, where the lines are; vertical type turns it
|
||||
// into text space with the lines.
|
||||
let text_bounds = if lay.bounds.area() > 0.0 { lay.bounds } else { t.estimate_bounds() };
|
||||
let mut b = lay.line_xf.inverse().transform_rect_bbox(text_bounds);
|
||||
// Across, the frame spans the lines as they are aligned: from their starts to their ends
|
||||
// without the tracking after their last characters (`LineInfo::trailing`), not to the
|
||||
// ink, which tracking can pull past an advance. Area type aligns them alike.
|
||||
@@ -332,7 +335,7 @@ fn to_area(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Justify::Auto if lay.lines.first().is_some_and(|l| l.rtl) => (slack, 0.0),
|
||||
_ => (0.0, slack),
|
||||
};
|
||||
let frame = Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0));
|
||||
let frame = lay.line_xf.transform_rect_bbox(Rect::new(b.x0 - sl, top, b.x1 + sr, b.y1.max(top + 1.0)));
|
||||
t.kind = TextKind::Area { frame: shapes::rectangle(frame) };
|
||||
refresh_bounds(t);
|
||||
}
|
||||
@@ -368,6 +371,8 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Point type is in no thread: its first paragraph starts in it.
|
||||
t.first_para_continues = false;
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
// The lines are in line space; the frame's bounds are taken there too.
|
||||
let fb = lay.line_xf.inverse().transform_rect_bbox(fb);
|
||||
let plain = t.plain_text();
|
||||
let baseline = lay.lines.first().map(|l| l.baseline).unwrap_or(fb.y0 + t.first_style().size * 0.8);
|
||||
// Soft wraps → explicit breaks (replace the space before the wrap when there is one).
|
||||
@@ -410,8 +415,14 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Justify::Auto if lay.lines.first().is_some_and(|l| l.rtl) => x1,
|
||||
_ => x0,
|
||||
};
|
||||
// Point type has no Dynamic Text: Block is turned off, keeping the sizes it set, so
|
||||
// converting back to area type does not turn it on again.
|
||||
t.dynamic_text = false;
|
||||
t.kind = TextKind::Point;
|
||||
t.xf *= Affine::translate((ox, baseline));
|
||||
// The origin is in the area type's line space; point type's line space puts its own
|
||||
// origin there (vertical point type turns its lines about a different point).
|
||||
let point_xf = if lay.vertical { vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).line_xf } else { Affine::IDENTITY };
|
||||
t.xf *= lay.line_xf * Affine::translate((ox, baseline)) * point_xf.inverse();
|
||||
refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
|
||||
@@ -8,7 +8,7 @@ use vectorcraft_color::Paint;
|
||||
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
|
||||
|
||||
use super::select::selectable_ids;
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, id_param, str_param};
|
||||
use super::{CommandSpec, EngineError, Result, Session, always, bad, bool_or, cmd, has_doc, object_param, str_param};
|
||||
|
||||
/// Magic Wand panel settings. Tolerances: colours as 0–255 RGB distance, stroke weight in
|
||||
/// points, opacity in percent.
|
||||
@@ -152,7 +152,7 @@ fn paintable(doc: &Document) -> Vec<NodeId> {
|
||||
}
|
||||
|
||||
fn magic_wand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let id = id_param(p, "id").ok_or_else(|| bad("select.magicWand", "missing id"))?;
|
||||
let id = object_param(p, "id", "select.magicWand")?.ok_or_else(|| bad("select.magicWand", "missing id"))?;
|
||||
let st = s.doc()?;
|
||||
let reference = st.doc.node(id).ok_or(EngineError::NoNode(id))?.clone();
|
||||
let w = s.menu.wand.clone();
|
||||
|
||||
@@ -645,7 +645,7 @@ fn flatten(rgba: &[u8], matte: [u8; 3]) -> impl Iterator<Item = [u8; 3]> + '_ {
|
||||
|
||||
/// The File Info text `s.metadata` lets into the files: `(keyword, text)`.
|
||||
fn metadata(doc: &Document, s: &WebSettings) -> Vec<(&'static str, String)> {
|
||||
doc.metadata.png_text(&doc.title).into_iter().filter(|(k, _)| s.metadata.keeps(k)).map(|(k, v)| (k, v.into_owned())).collect()
|
||||
doc.metadata.png_text(doc.info_title()).into_iter().filter(|(k, _)| s.metadata.keeps(k)).map(|(k, v)| (k, v.into_owned())).collect()
|
||||
}
|
||||
|
||||
/// Encode straight RGBA pixels (`w`×`h`) as `s` says; `doc` gives the metadata.
|
||||
|
||||
Reference in New Issue
Block a user