Merge main into fix/tracing-mask-art

This commit is contained in:
dotCooCoo committed 2026-12-04 02:55:17 -08:00
commit 7304910e7b
109 files changed
+5779 -247

No files matched your search

+1 -1
View File
@@ -76,7 +76,7 @@ VectorCraft is an open-source, Rust-native vector illustration app (Illustrator-
For the crates you changed: `cargo fmt`, `cargo clippy -p <crate> --all-targets`, `cargo xtask test` or `cargo nextest run -p <crate>`. Repository-wide steps when they apply: `cargo xtask assets`, `cargo xtask brands`, `cargo xtask layers`, `cargo xtask wasm`. `cargo xtask ci` runs all of them. Workspace lints (`unsafe_code = "deny"`, no `unwrap`/`expect`/`panic!` outside tests) are in `Cargo.toml`.
### Paths and conventions
- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`.
- `unsafe`: the workspace denies it. The desktop app's platform modules in `apps/vectorcraft/src/` call OS APIs that have no safe binding and allow it with a scoped `#[allow(unsafe_code)]`: the `mac_*.rs` and `windows_*.rs` files, `caps_lock.rs`, `clipboard.rs`, `cursor_theme.rs`, `display_profile.rs`, `host_services.rs`, `open_documents.rs`, `portal_save.rs` and `system_fonts.rs`. Doc tests are built without the workspace lints, so every library root carries `#![doc(test(attr(forbid(unsafe_code))))]` (`deny` in a crate without `#![forbid(unsafe_code)]`), and `cargo xtask layers` reports a root without it.
- Attribution file: [`ASSETS.md`](ASSETS.md) (a row for every asset); licence texts next to the assets, summarised in `NOTICE`. Code-drawn defaults are preferred for swatches, brushes, symbols and patterns.
- Fonts: [storytold/craft-fonts](https://github.com/storytold/craft-fonts) through the optional `CRAFT_FONTS_DIR` build option, read by `crates/text/build.rs`; everything builds with it empty.
- Crash handling: `vectorcraft_engine::guard` wraps every entry point. Hostile-input tests: `crates/engine/tests/{import_fuzz,command_sweep}.rs`, `crates/format/tests/prop_format.rs`, `crates/mcp/tests/protocol_props.rs`.
+5 -1
View File
@@ -1 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#fff" stroke-width="3"/><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" fill="#000" stroke="#000" stroke-width="1"/><path d="M2.78 3.84L6.85 11.24L5.29 11.9Z" fill="#fff"/><circle cx="6.62" cy="12.86" r="1.7" fill="#fff"/><path d="M15 20L18 14L21 20" stroke="#fff" stroke-width="3"/><path d="M15 20L18 14L21 20" stroke="#000" stroke-width="1.2" fill="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round">
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z M2.78 3.84L6.86 11.18A1.7 1.7 0 1 1 5.24 11.87Z" fill="#000" fill-rule="evenodd"/>
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#000" stroke-width="1"/>
<path d="M15 20L18 14L21 20" stroke="#000" stroke-width="1.2" fill="none"/>
</svg>

Before

Width:  |  Height:  |  Size: 585 B

After

Width:  |  Height:  |  Size: 465 B

+5 -1
View File
@@ -1 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#fff" stroke-width="3"/><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" fill="#000" stroke="#000" stroke-width="1"/><path d="M2.78 3.84L6.85 11.24L5.29 11.9Z" fill="#fff"/><circle cx="6.62" cy="12.86" r="1.7" fill="#fff"/><path d="M16 21A6 6 0 0 1 22 15" stroke="#fff" stroke-width="3"/><path d="M16 21A6 6 0 0 1 22 15" stroke="#000" stroke-width="1.2" fill="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round">
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z M2.78 3.84L6.86 11.18A1.7 1.7 0 1 1 5.24 11.87Z" fill="#000" fill-rule="evenodd"/>
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#000" stroke-width="1"/>
<path d="M16 21A6 6 0 0 1 22 15" stroke="#000" stroke-width="1.2" fill="none"/>
</svg>

Before

Width:  |  Height:  |  Size: 593 B

After

Width:  |  Height:  |  Size: 469 B

+6 -1
View File
@@ -1 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#fff" stroke-width="3"/><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" fill="#000" stroke="#000" stroke-width="1"/><path d="M2.78 3.84L6.85 11.24L5.29 11.9Z" fill="#fff"/><circle cx="6.62" cy="12.86" r="1.7" fill="#fff"/><path d="M15 20L18.5 16.5" stroke="#fff" stroke-width="3"/><path d="M15 20L18.5 16.5" stroke="#000" stroke-width="1.2" fill="none"/><path d="M18 13h4v4h-4Z" stroke="#fff" stroke-width="3"/><path d="M18 13h4v4h-4Z" fill="#000" stroke="#000" stroke-width="1"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round">
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z M2.78 3.84L6.86 11.18A1.7 1.7 0 1 1 5.24 11.87Z" fill="#000" fill-rule="evenodd"/>
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#000" stroke-width="1"/>
<path d="M15 20L18.5 16.5" stroke="#000" stroke-width="1.2" fill="none"/>
<path d="M18 13h4v4h-4Z" fill="#000" stroke="#000" stroke-width="1"/>
</svg>

Before

Width:  |  Height:  |  Size: 707 B

After

Width:  |  Height:  |  Size: 535 B

+8 -1
View File
@@ -1 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round"><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#fff" stroke-width="3"/><path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" fill="#000" stroke="#000" stroke-width="1"/><path d="M2.78 3.84L6.85 11.24L5.29 11.9Z" fill="#fff"/><circle cx="6.62" cy="12.86" r="1.7" fill="#fff"/><path d="M15.6 14.6L20.4 19.4" stroke="#fff" stroke-width="3"/><path d="M20.4 14.6L15.6 19.4" stroke="#fff" stroke-width="3"/><path d="M18 14V20" stroke="#fff" stroke-width="3"/><path d="M15 17H21" stroke="#fff" stroke-width="3"/><path d="M15.6 14.6L20.4 19.4" stroke="#000" stroke-width="1.2" fill="none"/><path d="M20.4 14.6L15.6 19.4" stroke="#000" stroke-width="1.2" fill="none"/><path d="M18 14V20" stroke="#000" stroke-width="1.2" fill="none"/><path d="M15 17H21" stroke="#000" stroke-width="1.2" fill="none"/></svg>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round">
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z M2.78 3.84L6.86 11.18A1.7 1.7 0 1 1 5.24 11.87Z" fill="#000" fill-rule="evenodd"/>
<path d="M2 2L11.91 9.2L10.83 15.09L5.3 17.44L0.31 14.13Z" stroke="#000" stroke-width="1"/>
<path d="M15.6 14.6L20.4 19.4" stroke="#000" stroke-width="1.2" fill="none"/>
<path d="M20.4 14.6L15.6 19.4" stroke="#000" stroke-width="1.2" fill="none"/>
<path d="M18 14V20" stroke="#000" stroke-width="1.2" fill="none"/>
<path d="M15 17H21" stroke="#000" stroke-width="1.2" fill="none"/>
</svg>

Before

Width:  |  Height:  |  Size: 965 B

After

Width:  |  Height:  |  Size: 685 B

+1
View File
@@ -1,6 +1,7 @@
//! The Affinity reader is `craft-affinity` (storytold/craft-libs). This crate keeps its name so
//! the corpus tests and fuzz targets under it, and the CI job that runs them, still build.
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub use craft_affinity::*;
+1
View File
@@ -18,6 +18,7 @@
//!
//! The crate knows no command and depends on no other VectorCraft crate.
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
use std::fmt;
+1
View File
@@ -9,6 +9,7 @@
//! [`stroke_pieces`] is the single source of brush geometry: the renderer paints the pieces it
//! returns (caching them per node) and `object.expandBrush` inserts them as real objects.
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
mod calli;
mod colorize;
+1
View File
@@ -21,6 +21,7 @@
//! - `scene`: the document walk that turns objects into entities.
//! - `import`: the reader, entities to art, blocks to symbols.
//! - `hpgl`: the HP-GL reader, the pen's moves to paths, and the writer, paths to pen moves.
#![doc(test(attr(deny(unsafe_code))))]
mod aci;
#[cfg(test)]
+1
View File
@@ -3,6 +3,7 @@
//! Colours keep the model the user picked them in (RGB, CMYK, Gray, Lab; HSB is a UI view of RGB),
//! so documents don't drift when converting back and forth. Rendering asks for [`Color::to_rgba`].
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
pub mod blend;
pub mod cms;
+1
View File
@@ -4,6 +4,7 @@
//! [`Document::node_mut`], which clones only the nodes on the path from the root to the edited node.
//! Keeping the previous `Document` value around is therefore a cheap undo snapshot.
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
pub mod appearance;
pub mod assets;
+1
View File
@@ -33,6 +33,7 @@
//! noise (`seed` parameter, default 0); the random Pixelate filters hash their pattern's cells,
//! anchored at the object's centre.
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
pub mod addons;
mod adjust;
+2 -2
View File
@@ -903,7 +903,7 @@ pub struct SymbolOptions {
impl SymbolOptions {
/// The options `d` keeps for symbol `name`.
fn of(d: &Document, name: &str) -> Self {
pub(in crate::cmd) fn of(d: &Document, name: &str) -> Self {
Self {
size: stored_natural_size(d, name),
registration: d.symbol_registration(name),
@@ -914,7 +914,7 @@ impl SymbolOptions {
}
/// Make them the options of `d`'s symbol `name`.
fn give(&self, d: &mut Document, name: &str) {
pub(in crate::cmd) fn give(&self, d: &mut Document, name: &str) {
set_natural_size(d, name, self.size);
d.set_symbol_registration(name, self.registration);
d.set_symbol_export_type(name, self.export_type);
+164 -1
View File
@@ -10,9 +10,12 @@
//! custom character sets:
//! <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=348>.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use serde_json::{Map, Value, json};
use vectorcraft_doc::text::{COMPOSITE_FONTS_MAX, COMPOSITE_NAME_MAX, CUSTOM_CHARS_MAX, CUSTOM_SETS_MAX};
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet};
use vectorcraft_doc::{CharClass, CompositeFont, CompositePart, CompositeParts, CustomCharSet, Document, Node, NodeKind};
use vectorcraft_text::FontDb;
use super::fileio::{read_file_head, write_file};
@@ -77,6 +80,166 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// Every stored family name, including regeneration settings and retained style defaults.
/// Planning reads a private clone so gathering names never changes the destination.
fn family_names(d: &Document) -> Result<BTreeSet<String>> {
let mut view = d.clone();
let mut names = BTreeSet::new();
let mut note = |family: &mut String| {
names.insert(family.to_lowercase());
};
super::textstyles::each_text_mut(&mut view, &mut |text| {
for run in &mut text.runs {
note(&mut run.style.font_family);
}
Ok(())
})?;
for style in view.char_styles.iter_mut().chain(view.para_styles.iter_mut()) {
if let Some(Value::String(family)) = style.attrs.get_mut("font_family") {
note(family);
}
}
let mut graphs = Vec::new();
view.visit_stored(|node, _| {
if node.extras().graph.is_some() {
graphs.push(node.id);
}
});
for id in graphs {
if let Some(node) = view.stored_node_mut(id) {
graph_families(node, &mut note);
}
}
fn brush_graphs(node: &mut Node, note: &mut impl FnMut(&mut String)) {
graph_families(node, note);
if let Some(mask) = node.extras_if_any().and_then(|extras| extras.mask.as_mut()) {
brush_graphs(Arc::make_mut(&mut mask.art), note);
}
for child in node.children_mut().into_iter().flatten() {
brush_graphs(Arc::make_mut(child), note);
}
}
for art in vectorcraft_brush::library(&view).iter_mut().flat_map(|brush| brush.art_mut()) {
brush_graphs(art, &mut note);
}
Ok(names)
}
fn graph_families(node: &mut Node, visit: &mut impl FnMut(&mut String)) {
if let Some(graph) = node.extras_if_any().and_then(|extras| extras.graph.as_deref_mut()) {
let labels = &mut graph.label_styles;
for style in [&mut labels.values, &mut labels.categories, &mut labels.legend].into_iter().flatten() {
visit(&mut style.font_family);
}
}
}
/// Family fields held directly by one node; the adoption walker owns tree/resource traversal.
pub(super) fn node_families(node: &mut Node, visit: &mut impl FnMut(&mut String)) {
if let NodeKind::Text(text) = &mut node.kind {
for run in &mut text.runs {
visit(&mut run.style.font_family);
}
}
graph_families(node, visit);
}
/// A fully checked incoming-only rename map and the destination's prospective definitions.
pub(super) struct CompositeImport {
names: BTreeMap<String, String>,
pub(super) combined: Vec<CompositeFont>,
}
impl CompositeImport {
pub(super) fn rename(&self, family: &mut String) -> bool {
if let Some(name) = self.names.get(&family.to_lowercase()) {
let changed = family.as_str() != name.as_str();
*family = name.clone();
changed
} else {
false
}
}
}
fn composite_alias(base: &str, reserved: &BTreeSet<String>, cmd: &str) -> Result<String> {
let db = FontDb::global();
let mut number = 2_u64;
loop {
let suffix = format!(" {number}");
let stem: String = base.chars().take(COMPOSITE_NAME_MAX.saturating_sub(suffix.chars().count())).collect();
let name = format!("{}{suffix}", stem.trim_end());
if CompositeFont::clean_name(&name).as_deref() == Some(name.as_str())
&& !reserved.contains(&name.to_lowercase())
&& !db.has_installed_family(&name)
{
return Ok(name);
}
number = number.checked_add(1).ok_or_else(|| bad(cmd, "no free name for a placed composite font"))?;
}
}
/// Plan used incoming definitions before changing either document or the font database.
/// Keep existing meanings even for an uninstalled family that destination art still names.
pub(super) fn plan_import(source: Vec<CompositeFont>, source_families: BTreeSet<String>, target: &Document, cmd: &str) -> Result<CompositeImport> {
if source.len() > COMPOSITE_FONTS_MAX || target.composite_fonts.len() > COMPOSITE_FONTS_MAX {
return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
}
let mut source_names = BTreeSet::new();
for font in &source {
font.check().map_err(|why| bad(cmd, why))?;
if !source_names.insert(font.name.to_lowercase()) {
return Err(bad(cmd, format!("two incoming composite fonts are named `{}`", font.name)));
}
}
let target_families = family_names(target)?;
let mut target_taken = target_families.clone();
for font in target.composite_fonts.iter() {
target_taken.insert(font.name.to_lowercase());
target_taken.extend(font.part_fonts().map(str::to_lowercase));
}
let mut reserved = source_families;
reserved.extend(target_families);
for font in source.iter().chain(target.composite_fonts.iter()) {
reserved.insert(font.name.to_lowercase());
reserved.extend(font.part_fonts().map(str::to_lowercase));
}
let db = FontDb::global();
let mut names = BTreeMap::new();
let mut combined = target.composite_fonts.to_vec();
for font in source {
let equivalent = |other: &&CompositeFont| other.parts == font.parts && other.custom == font.custom;
let mut reused = CompositeFont::named(&target.composite_fonts, &font.name).filter(equivalent);
let needs_alias = reused.is_none() && (target_taken.contains(&font.name.to_lowercase()) || db.has_installed_family(&font.name));
if needs_alias {
// A repeated import reuses its already-installed equal alias.
reused = target.composite_fonts.iter().find(equivalent);
}
let name = match reused {
Some(other) => other.name.clone(),
None if needs_alias => composite_alias(&font.name, &reserved, cmd)?,
None => font.name.clone(),
};
reserved.insert(name.to_lowercase());
names.insert(font.name.to_lowercase(), name.clone());
if reused.is_none() {
combined.push(CompositeFont { name, ..font });
}
}
// A source document may currently lend fonts to the database. Validate the prospective
// document, not composite names temporarily registered by a different document.
if combined.len() > COMPOSITE_FONTS_MAX {
return Err(bad(cmd, format!("a document keeps at most {COMPOSITE_FONTS_MAX} composite fonts")));
}
if let Some(font) = combined.iter().find(|font| db.has_installed_family(&font.name)) {
return Err(bad(cmd, format!("`{}` is the name of an installed font", font.name)));
}
if CompositeFont::usable(&combined).is_some() {
return Err(bad(cmd, "the composite fonts in the placed art and document cannot stand together"));
}
Ok(CompositeImport { names, combined })
}
/// Register the active document's composite fonts in the font database, and remove the ones the
/// other open documents (or an earlier active document) defined. Run after each command and when
/// another document takes the front, so an undo, a revert, an opened or closed file or a document
+50 -7
View File
@@ -5,6 +5,7 @@
//! own stacks, groups and layers included (layers through `ids`), or with `target: "contents"`
//! the objects inside them (see `appearance`).
use std::collections::HashSet;
use std::sync::Arc;
use serde_json::{Value, json};
@@ -115,7 +116,7 @@ fn effect_specs() -> Vec<CommandSpec> {
"Move Effect",
[],
None,
"{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (refused when the targets' appearances differ, or differ from that of a graph design's art given first)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}",
"{from: int|[int] (position in the source list; a list moves several effects of that list, which keep their order and land together), to: int (the position of the (first) moved effect in the destination list afterwards), fromItem?: appearance item index|null (the source list: that fill/stroke's effects, null the object's; omitted: the active item, else the object's), toItem?: item index|null (the destination list; default: the source list), copy?: bool (copy instead of move, as Alt-dragging the row), ids?|id?: [..], target?: \"object\"|\"contents\", aligned?: bool (different appearances allow only a reorder within the same shared fill or stroke, or within identical object effect lists; a graph design's art given first still requires equal appearances)} reorder an effect or move it between the object and its fills/strokes, as one undo step → {ids, index, item}",
has_doc,
move_effect
),
@@ -678,6 +679,35 @@ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "ids": ids_json(&ids) }))
}
impl Session {
/// Can the Appearance panel reorder shared effects on the exact subjects it displays?
/// A generated graph design or a selection normalized to different objects has no matching row.
pub fn can_reorder_selected_effects(&self) -> bool {
let Ok(st) = self.doc() else { return false };
let Ok(roots) = edit_targets(self, &Value::Null, "effect.move") else { return false };
let selected: HashSet<_> = st.selection.subjects().iter().copied().collect();
roots.len() == selected.len() && roots.iter().all(|id| selected.contains(id) && st.doc.is_editable(*id))
}
}
/// Resolves a same-list reorder for objects whose appearances differ. Every object must share the
/// complete ordered object effect list or the same fill/stroke row, with its effects, before editing.
fn shared_reorder_slots(d: &Document, ids: &[NodeId], source: ItemTarget, anchor: usize) -> Option<Vec<Option<usize>>> {
let mut seen = HashSet::with_capacity(ids.len());
let mut appearances: Vec<&vectorcraft_doc::Appearance> =
ids.iter().map(|id| d.node(*id).filter(|_| seen.insert(*id) && d.is_editable(*id)).map(|n| &*n.appearance)).collect::<Option<_>>()?;
let first = *appearances.get(anchor)?;
if source == ItemTarget::Top {
return appearances.iter().all(|ap| ap.effects == first.effects).then(|| vec![None; appearances.len()]);
}
let item = source.effects_item(first, "effect.move").ok()??;
appearances.swap(0, anchor);
let shared = SharedStack::of(&appearances);
let mut slots = (0..appearances.len()).map(|k| shared.item_in(item, k).map(Some)).collect::<Option<Vec<_>>>()?;
slots.swap(0, anchor);
Some(slots)
}
/// `effect.move`: moves (with `copy`: copies) effect `from`, or the effects `from` lists as one block in their order, to `to` in its own list or in `toItem`'s.
fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "effect.move";
@@ -694,17 +724,30 @@ fn move_effect(s: &mut Session, p: &Value) -> Result<Value> {
let dst = if p.get("toItem").is_some() { item_target_at(s, p, "toItem", C)? } else { src };
let copy = switch_or(p, "copy", false, C)?;
let roots = edit_targets(s, p, C)?;
// Where an aligned effect would go in each of several different stacks isn't one place.
if aligned(p, C)? && super::appearance::appearances_differ(&s.doc()?.doc, &with_reference(design_reference(s, p, C)?, &roots)) {
return Err(bad(C, "effects of objects whose appearances differ can't be moved together"));
}
let reference = design_reference(s, p, C)?;
let d = &s.doc()?.doc;
let slots = if aligned(p, C)? && super::appearance::appearances_differ(d, &with_reference(reference, &roots)) {
// An omitted item and a numbered item can use different anchors and still name the same row.
let shared = (!copy && reference.is_none())
.then(|| {
shared_reorder_slots(d, &roots, src, src.anchor(s, &roots))
.filter(|source| src == dst || shared_reorder_slots(d, &roots, dst, dst.anchor(s, &roots)).as_ref() == Some(source))
})
.flatten();
Some(shared.ok_or_else(|| bad(C, "effects of objects whose appearances differ can't be moved together"))?)
} else {
None
};
// Where the effect landed in each object it moved in, in the order of `ids`.
let mut landed = vec![];
let ids = s.edit(if copy { "Duplicate Effect" } else { "Move Effect" }, |d, _| {
let mut done = vec![];
for id in &roots {
for (k, id) in roots.iter().enumerate() {
let Some(n) = d.node_mut(*id) else { continue };
let (si, di) = (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?);
let (si, di) = match &slots {
Some(slots) => (slots[k], slots[k]),
None => (src.effects_item(&n.appearance, C)?, dst.effects_item(&n.appearance, C)?),
};
let Some(fx) = n.appearance.effects_mut(si).filter(|fx| from.iter().all(|i| *i < fx.len())) else { continue };
// Taken out from the top down, so the lower positions stay valid; put back in order.
let mut taken: Vec<Effect> = from.iter().rev().filter_map(|&i| if copy { fx.get(i).cloned() } else { Some(fx.remove(i)) }).collect();
+78 -14
View File
@@ -578,7 +578,7 @@ fn art_of<'a>(nodes: impl Iterator<Item = &'a Arc<Node>>) -> Vec<Node> {
}
/// The art as one object of `d` (its resources added), at its natural size and position.
fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node {
fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Result<Node> {
let mut node = match l.art {
Art::Image(img, clip) => {
let (sx, sy) = pt_per_px(img.ppi);
@@ -613,7 +613,7 @@ fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node {
Art::Text(t) => Node::new(d.alloc_id(), NodeKind::Text(Box::new(text::area_text(t, l.natural, &d.setup)))),
Art::Document(s, link, bounding) => document::node(d, &s, link, bounding),
Art::Vector { src, mut nodes, clip } => {
adopt::adopt(d, &src, &mut nodes);
adopt::adopt(d, &src, &mut nodes, PLACE)?;
let mut children: Vec<Arc<Node>> = nodes.iter().map(|n| Arc::new(d.reid(n))).collect();
if let Some(r) = clip {
children.insert(0, Arc::new(clip_path(d.alloc_id(), r)));
@@ -622,7 +622,7 @@ fn build(d: &mut Document, l: Loaded, link: Option<LinkInfo>) -> Node {
}
};
node.name = Some(l.name);
node
Ok(node)
}
/// `node` moved and scaled by `m` as a whole: strokes, effects and pattern tiles go along.
@@ -817,22 +817,86 @@ impl Session {
if self.doc()?.uid != read.job.doc {
return Err(bad(PLACE, NOT_ACTIVE));
}
let params = read.job.params.clone();
if let Some(old) = read.job.old {
let st = self.doc()?;
// Deleted, changed, or another object with its id: an undo that removes the object frees
// its id for the next object made.
if st.doc.node(old) != read.job.replaced.as_ref() {
// Keep the asynchronous target check against the drawing currently on show.
if self.doc()?.doc.node(old) != read.job.replaced.as_ref() {
return Err(bad(PLACE, "replace: the object to replace was changed or deleted"));
}
}
let params = read.job.params.clone();
// Provisional reselection and placement are one outside command. Deferring their
// notifications must not make an asynchronous handoff part of an unrelated tool drag.
if self.depth == 0 && !self.previewing && !self.in_tool_actions {
self.command_with_settled_warnings(|s| s.outside_interaction(PLACE, &params, |s| s.place_read_handoff(read, &params)))
} else {
self.place_read_handoff(read, &params)
}
}
fn place_read_handoff(&mut self, read: PlaceRead, params: &Value) -> Result<Value> {
let mut rollback = None;
let mut reselect = None;
if let Some(old) = read.job.old {
let st = self.doc()?;
if st.selection.objects != [old] || st.selection.symbol_part.is_some() {
self.execute("select.set", &json!({ "ids": [old.0] }))?;
// Adoption may now fail. Its provisional selection must not escape that error.
rollback = Some((
self.active,
st.clone(),
self.paint.clone(),
self.fill_active,
self.pending_paint.clone(),
self.active_appearance_item.clone(),
self.batch_paint_docs.clone(),
self.journal.len(),
self.journal.held(),
));
self.journal.hold(Some(self.journal.first_kept()));
reselect = Some(old);
}
}
self.place_hand_off = Some(read);
let r = self.execute(PLACE, &params);
let outer_tool_actions = self.in_tool_actions;
if reselect.is_some() {
self.in_tool_actions = true;
}
let result = (|| {
if let Some(old) = reselect {
self.execute("select.set", &json!({ "ids": [old.0] }))?;
}
self.place_hand_off = Some(read);
self.execute(PLACE, params)
})();
self.place_hand_off = None;
r
if let Some((active, before, paint, fill_active, pending, appearance, paint_docs, journal, held)) = rollback {
if result.is_err() {
if let Some(st) = self.docs.iter_mut().find(|st| st.uid == before.uid) {
let revision = st.revision.max(before.revision);
*st = before;
st.revision = revision + 1;
}
self.active = active;
self.paint = paint;
self.fill_active = fill_active;
self.pending_paint = pending;
self.active_appearance_item = appearance;
self.batch_paint_docs = paint_docs;
self.journal.truncate(journal);
for group in self.docs.iter_mut().filter_map(|st| st.undo_group.as_mut()) {
group.journal.retain(|&(n, _)| n < journal);
group.steps.retain(|&(n, _)| n < journal);
}
self.clear_deferred_overlay_cache();
self.decoded_images.empty();
self.sync_front_profiles();
super::compositefonts::sync(self);
}
self.journal.hold(held);
}
if reselect.is_some() {
self.in_tool_actions = outer_tool_actions;
self.after_command(result.is_ok().then_some(PLACE));
}
result
}
}
@@ -998,7 +1062,7 @@ fn apply(s: &mut Session, read: PlaceRead) -> Result<Value> {
n => warnings.push(format!("{n} slices would lie outside the canvas and were left out")),
}
let (id, size, slice_ids) = s.edit("Place", |d, sel| {
let mut node = transformed(build(d, loaded, link), m);
let mut node = transformed(build(d, loaded, link)?, m);
if let Some((old_image, (_, q, _))) = distorted {
node = with_corners(node, q).ok_or_else(|| super::xform::distorted_image_error(PLACE, old_image))?;
}
@@ -1266,7 +1330,7 @@ fn thumbnail_png(l: Loaded, px: f64) -> Result<String> {
let natural = l.natural;
let mut d = Document::new(natural.width().max(1.0), natural.height().max(1.0));
let layer = d.layers.first().map(|l| l.id);
let node = build(&mut d, l, None);
let node = build(&mut d, l, None)?;
d.insert(layer, 0, node)?;
let k = px.clamp(1.0, MAX_THUMBNAIL) / natural.width().max(natural.height()).max(1e-9);
let png = vectorcraft_render::Renderer::new().render_region(&d, natural, k, false).to_png().map_err(EngineError::Other)?;
+368 -23
View File
@@ -5,13 +5,16 @@
//! defines differently keeps its colour, unlinked. Text styles are left as they are: the art carries
//! its own formatting.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use vectorcraft_brush::{Brush, BrushKind};
use vectorcraft_color::Paint;
use vectorcraft_doc::{AppearanceItem, Document, Node, NodeKind, PatternDef, Symbol};
use super::super::Result;
use super::super::clipboard::SymbolOptions;
use super::super::compositefonts::{CompositeImport, node_families, plan_import};
use super::unique_name;
/// Visit `n` and every descendant (children and opacity-mask art) mutably.
@@ -52,9 +55,56 @@ fn paint_refs(p: &mut Paint, f: &mut impl FnMut(Ref)) {
});
}
/// Visit only the records the shared reader accepted, in their original order. Consuming
/// each accepted record once also leaves ignored duplicate surfaces and capped records alone.
fn accepted_graphic_refs<T: PartialEq>(
list: &mut serde_json::Value,
accepted: Vec<T>,
parse: impl Fn(&serde_json::Value) -> Option<T>,
f: &mut impl FnMut(Ref),
) {
let Some(list) = list.as_array_mut() else { return };
let mut accepted = accepted.into_iter().peekable();
for value in list {
let Some(next) = accepted.peek() else { break };
if parse(value).as_ref() != Some(next) {
continue;
}
let _ = accepted.next();
if let Some(serde_json::Value::String(symbol)) = value.get_mut("symbol") {
f(Ref::Symbol(symbol));
}
}
}
/// Symbol references in accepted Graphics and Map Art records, including fill/stroke effects.
/// Each stored name is visited once, so a rename cannot feed a second rename in the same map.
fn appearance_graphic_refs(appearance: &mut vectorcraft_doc::Appearance, f: &mut impl FnMut(Ref)) {
use vectorcraft_render::effects as fx;
if fx::appearance_graphic_symbols(appearance).is_empty() {
return;
}
let (effects, items) = (&mut appearance.effects, &mut appearance.items);
for effect in effects.iter_mut().chain(items.iter_mut().flat_map(|item| item.effects_mut())) {
if fx::takes_graphics(&effect.id) {
let accepted = fx::mapped_graphics(&effect.params);
if let Some(list) = effect.params.get_mut(fx::GRAPHICS) {
accepted_graphic_refs(list, accepted, |value| fx::MappedGraphic::from_value(value).ok(), f);
}
} else if fx::takes_map_art(&effect.id) {
let accepted = fx::surface_maps(&effect.params);
if let Some(list) = effect.params.get_mut(fx::MAP_ART) {
accepted_graphic_refs(list, accepted, |value| fx::SurfaceMap::from_value(value).ok(), f);
}
}
}
}
/// Every resource reference in `n` and its descendants.
fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
each_mut(n, &mut |n| {
appearance_graphic_refs(&mut n.appearance, f);
for it in &mut n.appearance.items {
match it {
AppearanceItem::Fill(fl) => paint_refs(&mut fl.paint, f),
@@ -71,6 +121,9 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
for r in &mut t.runs {
paint_refs(&mut r.style.fill, f);
paint_refs(&mut r.style.stroke, f);
if let Some(inline) = &mut r.inline {
f(Ref::Symbol(&mut inline.symbol));
}
}
if let Some(fonts) = &mut t.file_fonts {
fonts.map_keys(|key| f(Ref::Image(key)));
@@ -81,6 +134,14 @@ fn refs(n: &mut Node, f: &mut impl FnMut(Ref)) {
NodeKind::SymbolInstance { symbol, .. } => f(Ref::Symbol(symbol)),
_ => {}
}
if let Some(extras) = n.extras_if_any() {
extras
.symbol_overrides
.iter_mut()
.flat_map(|override_| [&mut override_.fill, &mut override_.stroke])
.flatten()
.for_each(|paint| paint_refs(paint, f));
}
// A color-masked image's masked pixels come along, and the key they were made from
// follows the image's.
if let Some(cm) = n.extras_if_any().and_then(|e| e.color_mask.as_deref_mut()) {
@@ -162,7 +223,16 @@ fn canon(dst: &Document, n: &Node) -> Node {
own.images.insert(k.clone(), blob.clone());
}
}
own.reid(n)
let mut canonical = own.reid(n);
// Derived layout caches do not define the stored art's resource identity.
each_mut(&mut canonical, &mut |node| {
if let NodeKind::Text(text) = &mut node.kind {
text.cached_bounds = None;
text.cached_baselines.clear();
text.cached_ink = None;
}
});
canonical
}
/// Do symbols `a` and `b` draw the same, whatever ids their art has ([`canon`])?
@@ -220,12 +290,273 @@ fn brush_art(b: &mut Brush) -> Vec<&mut Node> {
}
}
/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point
/// `nodes` at the names they got.
pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
/// Apply the final resource-name plan to one incoming reference.
fn rename_ref(r: Ref<'_>, maps: [&Renames; 5]) {
let (map, key) = match r {
Ref::Image(key) => (maps[0], key),
Ref::Symbol(key) => (maps[1], key),
Ref::Pattern(key) => (maps[2], key),
Ref::Brush(key) => (maps[3], key),
Ref::Swatch(link) => {
if let Some((new, _)) = link.as_deref().and_then(|key| maps[4].get(key)) {
*link = new.clone();
}
return;
}
};
if let Some((Some(new), _)) = map.get(key.as_str()) {
*key = new.clone();
}
}
#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
enum ResourceKind {
Symbol,
Pattern,
Brush,
}
type ResourceKey = (ResourceKind, String);
/// A source definition's dependencies whose planned names have not been finalized yet.
fn pending_dependencies(key: &ResourceKey, src: &Document, brushes: &[Brush], pending: &BTreeSet<ResourceKey>) -> BTreeSet<ResourceKey> {
let mut dependencies = BTreeSet::new();
let mut note = |r: Ref<'_>| {
let key = match r {
Ref::Symbol(name) => (ResourceKind::Symbol, name.clone()),
Ref::Pattern(name) => (ResourceKind::Pattern, name.clone()),
Ref::Brush(name) => (ResourceKind::Brush, name.clone()),
Ref::Image(_) | Ref::Swatch(_) => return,
};
if pending.contains(&key) {
dependencies.insert(key);
}
};
match key.0 {
ResourceKind::Symbol => {
if let Some(symbol) = src.symbols.iter().find(|symbol| symbol.name == key.1) {
refs(&mut (*symbol.art).clone(), &mut note);
}
}
ResourceKind::Pattern => {
if let Some(pattern) = src.pattern(&key.1) {
for art in &pattern.art {
refs(&mut (**art).clone(), &mut note);
}
}
}
ResourceKind::Brush => {
if let Some(mut brush) = brushes.iter().find(|brush| brush.name == key.1).cloned() {
for art in brush_art(&mut brush) {
refs(art, &mut note);
}
}
}
}
dependencies
}
/// Prefer the original name, then only canonical numbered variants from `unique_name`.
/// A free original name keeps its planned copy; another incoming name is never stolen.
fn matching_name<T>(base: &str, definitions: &[T], used: &[String], name: impl Fn(&T) -> &str, same: impl Fn(&T) -> bool) -> Option<String> {
let original = definitions.iter().find(|definition| name(definition) == base)?;
if same(original) {
return Some(base.to_string());
}
let prefix = format!("{base} ");
let mut seen = BTreeSet::new();
let mut aliases: Vec<_> = definitions
.iter()
.filter_map(|definition| {
let candidate = name(definition);
// Match the first definition, as the document name lookups do.
if !seen.insert(candidate.to_string()) {
return None;
}
let suffix = candidate.strip_prefix(&prefix)?;
if suffix.starts_with('0') || !suffix.bytes().all(|byte| byte.is_ascii_digit()) {
return None;
}
let number = suffix.parse::<u64>().ok()?;
(number >= 2 && !used.iter().any(|used| used == candidate)).then_some((number, definition))
})
.collect();
aliases.sort_unstable_by_key(|(number, _)| *number);
aliases.into_iter().find_map(|(_, definition)| same(definition).then(|| name(definition).to_string()))
}
/// Compare final incoming content, not the original references or destination's resource name.
fn reusable_name(
key: &ResourceKey,
dst: &Document,
src: &Document,
src_brushes: &[Brush],
dst_brushes: &[Brush],
used: &Used,
maps: [&Renames; 5],
) -> Option<String> {
match key.0 {
ResourceKind::Symbol => {
let source = src.symbols.iter().find(|symbol| symbol.name == key.1)?;
let mut incoming = source.clone();
refs(Arc::make_mut(&mut incoming.art), &mut |r| rename_ref(r, maps));
matching_name(
&key.1,
&dst.symbols,
&used.symbols,
|symbol| &symbol.name,
|candidate| {
let mut normalized = candidate.clone();
normalized.name = incoming.name.clone();
same_symbol(dst, &normalized, &incoming) && SymbolOptions::of(dst, &candidate.name) == SymbolOptions::of(src, &source.name)
},
)
}
ResourceKind::Pattern => {
let mut incoming = src.pattern(&key.1)?.clone();
for art in &mut incoming.art {
refs(Arc::make_mut(art), &mut |r| rename_ref(r, maps));
}
matching_name(
&key.1,
&dst.patterns,
&used.patterns,
|pattern| &pattern.name,
|candidate| {
let mut normalized = candidate.clone();
normalized.name = incoming.name.clone();
same_pattern(dst, &normalized, &incoming)
},
)
}
ResourceKind::Brush => {
let mut incoming = src_brushes.iter().find(|brush| brush.name == key.1)?.clone();
for art in brush_art(&mut incoming) {
refs(art, &mut |r| rename_ref(r, maps));
*art = canon(dst, art);
}
matching_name(
&key.1,
dst_brushes,
&used.brushes,
|brush| &brush.name,
|candidate| {
let mut normalized = candidate.clone();
normalized.name = incoming.name.clone();
for art in brush_art(&mut normalized) {
*art = canon(dst, art);
}
normalized == incoming
},
)
}
}
}
/// Finalize each copied definition only after its copied dependencies. Each key/edge is
/// processed once; a cycle (and its unresolved parents) conservatively keeps the planned copies.
fn reuse_remapped_resources(
dst: &Document,
src: &Document,
src_brushes: &[Brush],
dst_brushes: &[Brush],
used: &Used,
fixed: [&Renames; 2],
changing: [&mut Renames; 3],
) {
let [symbols, patterns, brushes] = changing;
let mut pending = BTreeSet::new();
for (kind, map) in [(ResourceKind::Symbol, &*symbols), (ResourceKind::Pattern, &*patterns), (ResourceKind::Brush, &*brushes)] {
pending.extend(map.iter().filter(|(_, (_, copy))| *copy).map(|(name, _)| (kind, name.clone())));
}
let mut waiting = BTreeMap::new();
let mut parents: BTreeMap<ResourceKey, Vec<ResourceKey>> = BTreeMap::new();
let mut ready = BTreeSet::new();
for key in &pending {
let dependencies = pending_dependencies(key, src, src_brushes, &pending);
if dependencies.is_empty() {
ready.insert(key.clone());
}
waiting.insert(key.clone(), dependencies.len());
for dependency in dependencies {
parents.entry(dependency).or_default().push(key.clone());
}
}
while let Some(key) = ready.pop_first() {
let maps = [fixed[0], &*symbols, &*patterns, &*brushes, fixed[1]];
if let Some(name) = reusable_name(&key, dst, src, src_brushes, dst_brushes, used, maps) {
let map = match key.0 {
ResourceKind::Symbol => &mut *symbols,
ResourceKind::Pattern => &mut *patterns,
ResourceKind::Brush => &mut *brushes,
};
map.insert(key.1.clone(), (Some(name), false));
}
for parent in parents.remove(&key).into_iter().flatten() {
if let Some(count) = waiting.get_mut(&parent) {
*count -= 1;
if *count == 0 {
ready.insert(parent);
}
}
}
}
}
/// Remap only incoming users before resource equality decides whether to share or copy.
/// Report actual family renaming for the final copied-resource reuse phase.
fn remap_composite_families(src: &Document, nodes: &mut [Node], used: &Used, brushes: &mut [Brush], plan: &CompositeImport) -> (Document, bool) {
let mut staged = src.clone();
let mut aliased = false;
for node in nodes.iter_mut() {
each_mut(node, &mut |node| {
node_families(node, &mut |family| {
aliased |= plan.rename(family);
});
});
}
for symbol in staged.symbols.iter_mut().filter(|symbol| used.symbols.contains(&symbol.name)) {
each_mut(Arc::make_mut(&mut symbol.art), &mut |node| {
node_families(node, &mut |family| {
aliased |= plan.rename(family);
});
});
}
for pattern in staged.patterns.iter_mut().filter(|pattern| used.patterns.contains(&pattern.name)) {
for art in &mut pattern.art {
each_mut(Arc::make_mut(art), &mut |node| {
node_families(node, &mut |family| {
aliased |= plan.rename(family);
});
});
}
}
for brush in brushes.iter_mut().filter(|brush| used.brushes.contains(&brush.name)) {
for art in brush_art(brush) {
each_mut(art, &mut |node| {
node_families(node, &mut |family| {
aliased |= plan.rename(family);
});
});
}
}
(staged, aliased)
}
/// Discover the incoming resource frontier and its composite-font users before planning
/// names or changing either document. Resource order and the no-composite fast path stay shared.
fn collect_resources(src: &Document, nodes: &mut [Node]) -> (Used, Vec<Brush>, BTreeSet<String>) {
let mut used = Used::default();
let composites = !src.composite_fonts.is_empty();
let mut families = BTreeSet::new();
let mut note_family = |name: &mut String| {
families.insert(name.to_lowercase());
};
for n in nodes.iter_mut() {
refs(n, &mut |r| used.note(r));
if composites {
each_mut(n, &mut |node| node_families(node, &mut note_family));
}
}
let src_brushes = vectorcraft_brush::library(src);
// Symbol, pattern and brush art and tint swatches can use more resources (the lists grow while
@@ -254,8 +585,29 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
}
for mut a in art {
refs(&mut a, &mut |r| used.note(r));
if composites {
each_mut(&mut a, &mut |node| node_families(node, &mut note_family));
}
}
}
(used, src_brushes, families)
}
/// Bring the resources `nodes` (art from `src`) use into `dst`, renaming on conflict, and point
/// `nodes` at the names they got.
pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node], cmd: &str) -> Result<()> {
let (used, mut src_brushes, families) = collect_resources(src, nodes);
let fonts = src.composite_fonts.iter().filter(|font| families.contains(&font.name.to_lowercase())).cloned().collect::<Vec<_>>();
// All representability/validation errors precede incoming or destination mutation.
let plan = if fonts.is_empty() { None } else { Some(plan_import(fonts, families, dst, cmd)?) };
let staged;
let mut aliased = false;
let src = if let Some(plan) = &plan {
(staged, aliased) = remap_composite_families(src, nodes, &used, &mut src_brushes, plan);
&staged
} else {
src
};
let images = names(&used.images, |k| src.images.get(k), |k| dst.images.get(k), |a, b| a == b, |c| dst.images.contains_key(c));
// Symbol and pattern art copied in takes ids of `dst`, so their art is compared by what it
@@ -264,7 +616,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
&used.symbols,
|n| src.symbols.iter().find(|s| s.name == n),
|n| dst.symbols.iter().find(|s| s.name == n),
|a, b| same_symbol(dst, a, b),
|a, b| same_symbol(dst, a, b) && SymbolOptions::of(dst, &a.name) == SymbolOptions::of(src, &b.name),
|c| dst.symbols.iter().any(|s| s.name == c),
);
let mut patterns = names(&used.patterns, |n| src.pattern(n), |n| dst.pattern(n), |a, b| same_pattern(dst, a, b), |c| dst.pattern(c).is_some());
@@ -330,23 +682,14 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
unshare(&mut brushes, &bru, &used.brushes, |c| dst_brushes.iter().any(|b| b.name == c));
}
let mut rename = |r: Ref| {
let (map, k) = match r {
Ref::Image(k) => (&images, k),
Ref::Symbol(k) => (&symbols, k),
Ref::Pattern(k) => (&patterns, k),
Ref::Brush(k) => (&brushes, k),
Ref::Swatch(link) => {
if let Some((new, _)) = link.as_deref().and_then(|k| swatches.get(k)) {
*link = new.clone();
}
return;
}
};
if let Some((Some(new), _)) = map.get(k.as_str()) {
*k = new.clone();
}
};
if aliased || symbols.values().any(|(_, copy)| *copy) {
reuse_remapped_resources(dst, src, &src_brushes, &dst_brushes, &used, [&images, &swatches], [&mut symbols, &mut patterns, &mut brushes]);
}
if let Some(plan) = plan {
dst.composite_fonts = plan.combined.into();
}
let mut rename = |r: Ref| rename_ref(r, [&images, &symbols, &patterns, &brushes, &swatches]);
for n in nodes.iter_mut() {
refs(n, &mut rename);
}
@@ -375,6 +718,7 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
// The art takes ids of `dst`: those of `src` may name objects of `dst` already.
def.art = Arc::new(dst.reid(&def.art));
dst.symbols.push(def);
SymbolOptions::of(src, old).give(dst, new);
}
}
for (old, new) in copies(&patterns) {
@@ -406,4 +750,5 @@ pub(crate) fn adopt(dst: &mut Document, src: &Document, nodes: &mut [Node]) {
dst.swatches.push(w);
}
}
Ok(())
}
+5 -1
View File
@@ -178,6 +178,10 @@ fn opened_document_art(
super::super::links::resolve(&mut l.doc, super::super::links::LinkBase::file(path), false, false);
}
l.doc.drop_edit_modes();
// Measure and crop in this source's composite fonts, not those of the front document.
// The existing thread-local loan restores its caller's context on every return or unwind.
let source_fonts = l.doc.composite_fonts.clone();
let _source_fonts = vectorcraft_text::FontDb::global().lend_document_composite_fonts(&source_fonts);
// The native file does not store type's layout bounds. Measure them before cropping or
// copying the art, so the placed group keeps the positions of aligned point type.
for warning in crate::Session::refresh_text_bounds(&mut l.doc) {
@@ -544,7 +548,7 @@ pub(crate) fn expand(d: &mut Document, id: NodeId, cmd: &str) -> Result<()> {
let a = document_art(p.link.name(), &bytes, Some(&p.link.path), p.page(), p.bounding, p.page_box, cmd)?;
let m = p.art_xf(a.frame).ok_or_else(|| bad(cmd, format!("object {} has no size", id.0)))?;
let mut nodes = a.nodes;
super::adopt::adopt(d, &a.doc, &mut nodes);
super::adopt::adopt(d, &a.doc, &mut nodes, cmd)?;
let mut children: Vec<Arc<Node>> = nodes.iter().map(|n| Arc::new(d.reid(n))).collect();
if let Some(r) = a.clip {
children.insert(0, Arc::new(super::clip_path(d.alloc_id(), r)));
+1
View File
@@ -5,6 +5,7 @@
//! server all go through [`Session::execute`]. Tools (pointer gestures) are hosted here too and
//! reduce to commands, so every gesture is journaled and replayable.
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
pub mod cmd;
pub mod file_access;
+81 -6
View File
@@ -559,23 +559,92 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
/// `pathItems.removeAll()`: deletes every path of the document in one command. A hidden or locked
/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before
/// anything is deleted, as `PageItems.removeAll()` does.
/// anything is deleted, as `PageItems.removeAll()` does. So does the clipping path of a group or
/// layer that keeps other objects, or a compound path or group that clips one and would be left
/// with no visible path or visible type that lays out glyphs to clip by.
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
if super::layers::is_scoped(a, "PathItems") {
return super::layers::scoped_remove_all(h, a);
}
let doc = items_doc(h, a)?;
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| {
let ids = path_items(h, st)?;
let d = &st.doc;
if h.session.borrow().menu.guides_locked
&& let Some(id) = ids.iter().find(|id| st.doc.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })))
&& let Some(id) = ids.iter().find(|id| d.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })))
{
return Err(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0)));
}
let refused: Vec<u64> = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect();
let locks = st.doc.locked_artboards();
let refused: Vec<u64> = ids.iter().filter(|i| !editable(d, **i)).map(|i| i.0).take(20).collect();
let locks = d.locked_artboards();
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
Ok::<_, HostError>((ids, refused, on_locked))
let mut next: Vec<_> = d.layers.iter().collect();
let mut nodes = Vec::new();
while let Some(n) = next.pop() {
nodes.push(n);
next.extend(n.children().into_iter().flatten());
}
let mut going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
let mut affected: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
for n in nodes.iter().rev() {
if n.children().into_iter().flatten().any(|k| affected.contains(&k.id)) {
affected.insert(n.id);
}
}
// Type is laid out only inside a mask that loses a path; no other outline decides a refusal.
let mut in_mask = std::collections::HashSet::new();
for n in &nodes {
if n.clips()
&& let Some(mask) = n.children().and_then(|k| k.first())
&& affected.contains(&mask.id)
{
let mut stack = vec![mask];
while let Some(m) = stack.pop() {
if in_mask.insert(m.id) {
stack.extend(m.children().into_iter().flatten());
}
}
}
}
let mut geometry = std::collections::HashSet::new();
let mut masks = Vec::new();
for n in nodes.into_iter().rev() {
let kids = n.children().map_or(&[][..], Vec::as_slice);
// Clear removes compound paths emptied of direct members, but keeps empty groups.
if matches!(n.kind, NodeKind::Compound { .. })
&& !kids.is_empty()
&& kids.iter().all(|k| matches!(k.kind, NodeKind::Path { .. }) && going.contains(&k.id))
{
going.insert(n.id);
}
// A clip outline takes in visible paths and the glyphs of visible type, as
// `push_clip_shapes` does; type that lays out no glyphs (blank, or overset) gives no
// outline. A list marker is a glyph too, so whitespace-only type is laid out as well.
let shape = n.visible
&& match &n.kind {
NodeKind::Path { .. } => true,
NodeKind::Text(t) => {
in_mask.contains(&n.id) && !vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).to_bezpath().elements().is_empty()
}
_ => false,
};
// A clipping group's outline is its first member's alone.
let inner =
if n.clips() { kids.first().is_some_and(|k| geometry.contains(&k.id)) } else { kids.iter().any(|k| geometry.contains(&k.id)) };
if n.visible && ((shape && !going.contains(&n.id)) || inner) {
geometry.insert(n.id);
}
if n.clips()
&& let Some(mask) = kids.first()
&& affected.contains(&mask.id)
&& !geometry.contains(&mask.id)
&& kids.iter().skip(1).any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. }))
&& masks.len() < 20
{
masks.push(mask.id.0);
}
}
Ok::<_, HostError>((ids, refused, on_locked, masks))
})?;
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
@@ -585,6 +654,12 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
}
if !masks.is_empty() {
let list = masks.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!(
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}"
)));
}
if !ids.is_empty() {
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
}
+2
View File
@@ -661,6 +661,7 @@ impl Session {
self.pending_paint = None;
// The previous preview's Assign Profile is undone with it.
self.sync_front_profiles();
cmd::compositefonts::sync(self);
let rw = cmd::distortcmds::perspective_rewrite(self, cmd, params).or_else(|| cmd::bounds_rewrite(self, cmd, params));
let (cmd, params) = rw.as_ref().map_or((cmd, params), |(c, p)| (c.as_str(), p));
// A selected object's converted appearance must not replace the current paints while
@@ -877,6 +878,7 @@ impl Session {
deselect_hidden(&menu, &st.doc, &mut st.selection);
// A canceled preview's Assign Profile is undone with it.
self.sync_front_profiles();
cmd::compositefonts::sync(self);
// With New Art Has Basic Appearance off, new art takes the appearance of the selection as
// the document has it again, not as a preview left it. An interaction that changed only the
// defaults (`defaultsOnly: true`) leaves the defaults it began with.
+12 -3
View File
@@ -25,6 +25,12 @@ fn with_settled_warnings(mut r: Value, settled: &[String]) -> Value {
}
impl Session {
/// Run a command callback and keep warnings from every preview it settles or restores.
pub(crate) fn command_with_settled_warnings(&mut self, f: impl FnOnce(&mut Self) -> Result<Value>) -> Result<Value> {
let (r, settled) = self.collect_settled_warnings(f);
r.map(|v| with_settled_warnings(v, &settled))
}
/// `spec`'s `enabled` with `ids` selected instead of the selection, which is then put back.
fn enabled_with_selection(&mut self, spec: &CommandSpec, ids: Vec<NodeId>) -> std::result::Result<(), String> {
let Some(d) = self.active_mut() else { return (spec.enabled)(self) };
@@ -121,10 +127,9 @@ impl Session {
// A preview that a top-level command applied first (a drag with Real-time Drawing off, kept
// before Undo) reports its warning in the command's result.
let r = if self.depth == 0 {
let (r, settled) = self.collect_settled_warnings(|s| {
self.command_with_settled_warnings(|s| {
if outside { s.outside_interaction(id, params, |s| s.execute_spec(spec, id, params)) } else { s.execute_spec(spec, id, params) }
});
r.map(|v| with_settled_warnings(v, &settled))
})
} else {
self.execute_spec(spec, id, params)
};
@@ -253,6 +258,10 @@ impl Session {
// after an undone or redone Assign Profile, a failed or panicked command's documents put
// back, and a batch step, before the next step converts through them.
self.sync_front_profiles();
if self.depth != 0 {
// The next batch step can measure/outline definitions this step adopted.
cmd::compositefonts::sync(self);
}
if r.is_err() && self.depth == 0 {
self.batch_paint_docs.clear();
// A failed or panicked command's documents are put back: type is drawn in their
+38
View File
@@ -888,6 +888,44 @@ fn apply_reports_the_index_in_the_object_whose_row_it_names() {
assert_eq!((r["item"].clone(), r["index"].clone()), (json!(0), json!(1)), "a's row 0 holds two effects");
}
#[test]
fn aligned_effect_move_uses_the_shared_fill_or_stroke_in_each_target() {
let mut s = session();
let (a, b) = reversed_pair(&mut s);
for (id, item) in [(a, 1), (b, 2)] {
for effect in ["distort.twist", "distort.roughen"] {
run(&mut s, "effect.apply", json!({"ids": [id.0], "item": item, "effect": effect}));
}
}
run(&mut s, "select.set", json!({"ids": [b.0, a.0]}));
let appearances = |s: &Session| [a, b].map(|id| node(s, id).appearance.clone());
let before = appearances(&s);
for (params, reply_item) in [(json!({"from": 1, "to": 0, "aligned": true}), 2), (json!({"from": 1, "to": 0, "toItem": 1, "aligned": true}), 1)] {
run(&mut s, "appearance.setActiveItem", json!({"index": 2}));
let moved = run(&mut s, "effect.move", params);
assert_eq!(moved["item"], json!(reply_item), "the reply addresses the destination's anchor");
assert_eq!(moved["index"], json!(0));
for (appearance, item) in appearances(&s).iter().zip([1, 2]) {
let ids: Vec<_> = appearance.effects_at(Some(item)).unwrap().iter().map(|e| e.id.as_str()).collect();
assert_eq!(ids, ["distort.roughen", "distort.twist"]);
assert!(appearance.effects_at(Some(0)).unwrap().is_empty());
}
run(&mut s, "edit.undo", json!({}));
assert_eq!(appearances(&s), before);
}
run(&mut s, "appearance.setActiveItem", json!({"index": 2}));
for destination in [0, 2] {
assert!(s.execute("effect.move", &json!({"from": 1, "to": 0, "toItem":destination, "aligned":true})).is_err());
assert_eq!(appearances(&s), before, "a different or invalid destination must not change either list");
}
run(&mut s, "effect.apply", json!({"ids": [a.0], "item": 1, "effect": "stylize.feather"}));
let before = appearances(&s);
assert!(s.execute("effect.move", &json!({"ids": [b.0, a.0], "fromItem": 2, "from": 1, "to": 0, "aligned": true})).is_err());
assert_eq!(appearances(&s), before, "no effect moves if a target lacks the shared row");
}
/// `effect.move`'s reply names where the effect landed in the object whose row the active item is
/// (the first selected object), also when that object paints above the others.
#[test]
+371
View File
@@ -3684,6 +3684,377 @@ fn scoped_remove_all_refuses_a_clipping_compound_path() {
assert_eq!(undo_steps(&s), steps);
}
/// Runs the document's `pathItems.removeAll()`, then logs its error message and the number of paths.
const CAUGHT_PATHS_REMOVE_ALL: &str = "var p = app.activeDocument.pathItems, m = '';\
try { p.removeAll(); } catch (e) { m = e.message; }\
vc.log(m); vc.log(p.length);";
/// The document's `pathItems.removeAll()` refuses to delete the path that clips a group while the
/// group keeps other art, and deletes nothing, as the scoped collections do.
#[test]
fn document_path_items_remove_all_refuses_a_clipping_path() {
let (mut s, a, b) = doc();
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("object.arrange.bringToFront", &json!({})).unwrap();
run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap();
let d = &s.active().unwrap().doc;
assert_eq!(d.parent_of(a).and_then(|g| d.node(g)).and_then(|g| g.children()).map(|k| k[0].id), Some(a));
let before = s.active().unwrap().doc.clone();
let steps = undo_steps(&s);
// The script catches the error and counts the paths before the run ends, so the run's own
// rollback cannot hide a deletion.
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
let e = out[0].as_str().unwrap_or_default();
assert!(e.contains("cannot delete a clipping path"), "{out:?}");
assert!(e.contains(&a.0.to_string()), "{out:?}");
assert!(!e.contains(&b.0.to_string()), "{out:?}");
assert_eq!(out[1], json!(2));
assert_eq!(s.active().unwrap().doc, before);
assert_eq!(undo_steps(&s), steps);
}
/// The document's `pathItems.removeAll()` would empty a compound path that clips a group keeping
/// other art, so it throws and deletes nothing.
#[test]
fn document_path_items_remove_all_refuses_to_empty_a_clipping_compound_path() {
let (mut s, a, b) = doc();
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
let compound = s.active().unwrap().doc.parent_of(a).unwrap();
s.execute("select.set", &json!({"ids": [compound.0, t.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": [compound.0]})).unwrap();
s.execute("object.arrange.bringToFront", &json!({})).unwrap();
run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap();
let d = &s.active().unwrap().doc;
assert_eq!(d.parent_of(compound).and_then(|g| d.node(g)).and_then(|g| g.children()).map(|k| k[0].id), Some(compound));
let before = s.active().unwrap().doc.clone();
let steps = undo_steps(&s);
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
let e = out[0].as_str().unwrap_or_default();
assert!(e.contains("cannot delete a clipping path"), "{out:?}");
assert!(e.contains(&compound.0.to_string()), "{out:?}");
assert_eq!(out[1], json!(2));
assert_eq!(s.active().unwrap().doc, before);
assert_eq!(undo_steps(&s), steps);
}
/// A clipping mask made of a group of paths, as an imported SVG mask with several shapes is, would
/// be left empty by the document's `pathItems.removeAll()`, so it throws and deletes nothing.
#[test]
fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_of_paths() {
let (mut s, a, b) = doc();
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [mask.0, t.0]})).unwrap();
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("Clip", |d, _| {
if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) {
children.sort_by_key(|c| c.id != mask);
*clip = true;
}
Ok(())
})
.unwrap();
let d = &s.active().unwrap().doc;
assert!(d.node(outer).unwrap().clips());
assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask));
let before = s.active().unwrap().doc.clone();
let steps = undo_steps(&s);
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
let e = out[0].as_str().unwrap_or_default();
assert!(e.contains("cannot delete a clipping path"), "{out:?}");
assert!(e.contains(&mask.0.to_string()), "{out:?}");
assert_eq!(out[1], json!(2));
assert_eq!(s.active().unwrap().doc, before);
assert_eq!(undo_steps(&s), steps);
}
/// Type clips by its glyph outlines, so a clipping group that keeps type after its paths go still
/// clips, and the document's `pathItems.removeAll()` deletes every path.
#[test]
fn document_path_items_remove_all_keeps_a_clipping_group_that_holds_type() {
let (mut s, a, b) = doc();
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap();
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap();
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("Clip", |d, _| {
if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) {
children.sort_by_key(|c| c.id != mask);
*clip = true;
}
Ok(())
})
.unwrap();
let d = &s.active().unwrap().doc;
assert!(d.node(outer).unwrap().clips());
assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask));
let steps = undo_steps(&s);
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
assert_eq!(out[0], json!(""), "{out:?}");
assert_eq!(out[1], json!(0));
let d = &s.active().unwrap().doc;
assert!(d.node(a).is_none() && d.node(b).is_none());
assert!(d.node(t).is_some() && d.node(u).is_some());
assert_eq!(undo_steps(&s), steps + 1);
}
/// Type with no characters to draw gives no clip outline, so a clipping group whose paths would
/// leave only such type makes the document's `pathItems.removeAll()` throw and delete nothing.
#[test]
fn document_path_items_remove_all_refuses_when_only_blank_type_would_clip() {
let (mut s, a, _) = doc();
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap();
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap();
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("Clip", |d, _| {
if let Some(NodeKind::Text(tx)) = d.node_mut(t).map(|n| &mut n.kind) {
tx.runs.iter_mut().for_each(|r| r.text = " ".into());
}
if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) {
children.sort_by_key(|c| c.id != mask);
*clip = true;
}
Ok(())
})
.unwrap();
let before = s.active().unwrap().doc.clone();
let steps = undo_steps(&s);
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
let e = out[0].as_str().unwrap_or_default();
assert!(e.contains("cannot delete a clipping path"), "{out:?}");
assert!(e.contains(&mask.0.to_string()), "{out:?}");
assert_eq!(out[1], json!(2));
assert_eq!(s.active().unwrap().doc, before);
assert_eq!(undo_steps(&s), steps);
}
/// A clipping group nested in a clipping mask clips by its first member only, so type it clips does
/// not keep the outer mask's outline, and the document's `pathItems.removeAll()` names the outer
/// mask too.
#[test]
fn document_path_items_remove_all_ignores_type_clipped_inside_a_nested_mask() {
let (mut s, a, b) = doc();
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [b.0, t.0]})).unwrap();
let nested = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [a.0, nested.0]})).unwrap();
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap();
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("Clip", |d, _| {
for (g, first) in [(nested, b), (outer, mask)] {
if let Some(NodeKind::Group { children, clip }) = d.node_mut(g).map(|n| &mut n.kind) {
children.sort_by_key(|c| c.id != first);
*clip = true;
}
}
Ok(())
})
.unwrap();
let before = s.active().unwrap().doc.clone();
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
let e = out[0].as_str().unwrap_or_default();
assert!(e.contains("cannot delete a clipping path"), "{out:?}");
assert!(e.split(": ").last().unwrap_or_default().split(", ").any(|id| id == mask.0.to_string()), "{out:?}");
assert_eq!(out[1], json!(2));
assert_eq!(s.active().unwrap().doc, before);
}
/// A numbered paragraph whose text is a single space still draws its number, which clips, so the
/// document's `pathItems.removeAll()` deletes the paths of a clipping group that keeps it.
#[test]
fn document_path_items_remove_all_keeps_a_clipping_group_whose_type_draws_only_a_list_number() {
use vectorcraft_doc::text::{NumberStyle, ParaList};
let (mut s, a, b) = doc();
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap();
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap();
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("Clip", |d, _| {
if let Some(NodeKind::Text(tx)) = d.node_mut(t).map(|n| &mut n.kind) {
tx.runs.iter_mut().for_each(|r| r.text = " ".into());
let mut styles = tx.paragraph_styles();
styles.iter_mut().for_each(|p| p.list = Some(ParaList::numbered(NumberStyle::Arabic)));
tx.set_paragraph_styles(styles);
}
if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) {
children.sort_by_key(|c| c.id != mask);
*clip = true;
}
Ok(())
})
.unwrap();
if let Some(NodeKind::Text(tx)) = s.active().unwrap().doc.node(t).map(|n| &n.kind) {
assert!(!vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx).to_bezpath().elements().is_empty());
}
let steps = undo_steps(&s);
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
assert_eq!(out[0], json!(""), "{out:?}");
assert_eq!(out[1], json!(0));
let d = &s.active().unwrap().doc;
assert!(d.node(a).is_none() && d.node(b).is_none());
assert!(d.node(t).is_some() && d.node(u).is_some());
assert_eq!(undo_steps(&s), steps + 1);
}
/// Area type too short for its first line lays out no glyphs and gives no clip outline, so a
/// clipping group whose paths would leave only such type makes the document's
/// `pathItems.removeAll()` throw and delete nothing.
#[test]
fn document_path_items_remove_all_refuses_when_only_overset_type_would_clip() {
let (mut s, a, _) = doc();
let t = NodeId(
s.execute("text.create", &json!({"x": 10, "y": 250, "size": 12, "area": {"width": 100, "height": 1}, "text": "hi"})).unwrap()["id"]
.as_u64()
.unwrap(),
);
let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap());
if let Some(NodeKind::Text(tx)) = s.active().unwrap().doc.node(t).map(|n| &n.kind) {
assert!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), tx).to_bezpath().elements().is_empty());
}
s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap();
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap();
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("Clip", |d, _| {
if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) {
children.sort_by_key(|c| c.id != mask);
*clip = true;
}
Ok(())
})
.unwrap();
let before = s.active().unwrap().doc.clone();
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
let e = out[0].as_str().unwrap_or_default();
assert!(e.contains("cannot delete a clipping path"), "{out:?}");
assert!(e.contains(&mask.0.to_string()), "{out:?}");
assert_eq!(out[1], json!(2));
assert_eq!(s.active().unwrap().doc, before);
}
/// Hidden type does not clip, so a clipping group whose paths would leave only hidden type makes
/// the document's `pathItems.removeAll()` throw and delete nothing.
#[test]
fn document_path_items_remove_all_refuses_when_only_hidden_type_would_clip() {
let (mut s, a, _) = doc();
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
let u = NodeId(s.execute("text.create", &json!({"x": 10, "y": 300, "text": "yo"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [a.0, t.0]})).unwrap();
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [mask.0, u.0]})).unwrap();
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("Clip", |d, _| {
if let Some(n) = d.node_mut(t) {
n.visible = false;
}
if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) {
children.sort_by_key(|c| c.id != mask);
*clip = true;
}
Ok(())
})
.unwrap();
let before = s.active().unwrap().doc.clone();
let steps = undo_steps(&s);
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
let e = out[0].as_str().unwrap_or_default();
assert!(e.contains("cannot delete a clipping path"), "{out:?}");
assert!(e.contains(&mask.0.to_string()), "{out:?}");
assert_eq!(out[1], json!(2));
assert_eq!(s.active().unwrap().doc, before);
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn document_path_items_remove_all_refuses_to_empty_a_clipping_group_with_an_empty_subgroup() {
let (mut s, a, b) = doc();
let t = NodeId(s.execute("text.create", &json!({"x": 10, "y": 250, "text": "hi"})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let mask = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
let empty = NodeId(s.execute("object.newGroup", &json!({"parent": mask.0})).unwrap()["id"].as_u64().unwrap());
s.execute("select.set", &json!({"ids": [mask.0, t.0]})).unwrap();
let outer = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
s.edit("Clip", |d, _| {
if let Some(NodeKind::Group { children, clip }) = d.node_mut(outer).map(|n| &mut n.kind) {
children.sort_by_key(|c| c.id != mask);
*clip = true;
}
Ok(())
})
.unwrap();
let d = &s.active().unwrap().doc;
assert!(d.node(outer).unwrap().clips());
assert_eq!(d.node(outer).and_then(|g| g.children()).map(|k| k[0].id), Some(mask));
assert!(d.node(empty).unwrap().children().unwrap().is_empty());
let before = d.clone();
let steps = undo_steps(&s);
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
assert_eq!(
out[0],
json!(format!("cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {}", mask.0))
);
assert_eq!(out[1], json!(2));
assert_eq!(s.active().unwrap().doc, before);
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn document_path_items_remove_all_keeps_empty_groups_but_removes_empty_compounds() {
for compound in [false, true] {
let (mut s, a, b) = doc();
let c = rect(&mut s, 200.0, 100.0, 20.0, 20.0);
s.execute("select.set", &json!({"ids": [b.0, c.0]})).unwrap();
s.execute(if compound { "object.compoundPath.make" } else { "object.group" }, &json!({})).unwrap();
let sibling = s.active().unwrap().doc.parent_of(b).unwrap();
let layer = s.active().unwrap().doc.parent_of(a).unwrap();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("object.arrange.bringToFront", &json!({})).unwrap();
s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap();
let d = &s.active().unwrap().doc;
assert!(d.node(layer).unwrap().clips());
assert_eq!(d.node(layer).and_then(|n| n.children()).map(|k| k[0].id), Some(a));
let before = d.clone();
let steps = undo_steps(&s);
let out = log(&mut s, CAUGHT_PATHS_REMOVE_ALL);
if compound {
assert_eq!(out, [json!(""), json!(0)]);
let d = &s.active().unwrap().doc;
assert!(d.node(sibling).is_none());
assert!(!d.node(layer).unwrap().clips());
assert_eq!(undo_steps(&s), steps + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.active().unwrap().doc, before);
} else {
assert_eq!(
out[0],
json!(format!(
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {}",
a.0
))
);
assert_eq!(out[1], json!(3));
assert_eq!(s.active().unwrap().doc, before);
assert_eq!(undo_steps(&s), steps);
}
}
}
/// A path that leaves a compound path for a layer is drawn as it was: it takes the compound
/// path's paint and pixel alignment, as Release Compound Path gives them.
#[test]
+5 -2
View File
@@ -409,11 +409,14 @@ impl Session {
/// The selection tool a press at `p` with `mods` borrows ([`Self::lent_tool`]): none when
/// the Selection tool keeps a Cmd press on a selected object to select the object behind it
/// (Selection & Anchor Display › Command Click to Select Objects Behind), which an earlier Cmd
/// press armed ([`Self::behind_armed`]).
/// press armed ([`Self::behind_armed`]); none either when the active tool keeps the press
/// ([`vectorcraft_tools::Tool::keeps_cmd_press`]), as Direct Selection keeps one on a shown
/// direction handle to mirror the opposite handle.
fn lent_tool_at(&mut self, p: Point, mods: &Mods, view: ViewInfo) -> Option<&'static str> {
let id = self.lent_tool(self.tool.id(), mods)?;
let behind = self.tool.id() == "selection" && self.with_tool_cx(view, |_, cx| vectorcraft_tools::select::selects_behind_at(cx, p));
(!behind).then_some(id)
let kept = !behind && self.with_tool_cx(view, |t, cx| t.keeps_cmd_press(cx, p, *mods));
(!behind && !kept).then_some(id)
}
/// Is the press `ev` lent a selection tool ([`Self::lend_selection_tool`])? The frontend asks
@@ -332,6 +332,70 @@ fn direct_handle_cmd_before_press_still_lends_selection_and_returns_direct() {
assert_eq!(s.doc().unwrap().history.undo.len(), before.undo);
}
#[test]
fn direct_handle_cmd_held_before_pressing_a_handle_mirrors_instead_of_moving_the_path() {
let mut s = session();
let id = curve(&mut s, Point::new(50.0, 100.0));
let before = node(&s, id);
let undo = s.doc().unwrap().history.undo.len();
let end = Point::new(180.0, 100.0);
pointer(&mut s, PointerKind::Down, end, cmd());
assert_eq!(s.tool_id(), "directSelection", "a Cmd press on a shown handle is not lent to the Selection tool");
let q = Point::new(180.0, 160.0);
pointer(&mut s, PointerKind::Drag, q, cmd());
assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth);
assert_other_geometry(&s, id, &before);
pointer(&mut s, PointerKind::Up, q, cmd());
assert_mirrored(anchor(&s, id), q, AnchorKind::Smooth);
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1);
assert_eq!(s.tool_id(), "directSelection");
}
#[test]
fn direct_handle_cmd_shift_held_before_pressing_a_handle_constrains_and_mirrors() {
let mut s = session();
let id = curve(&mut s, Point::new(50.0, 100.0));
let before = node(&s, id);
let p = anchor(&s, id).p;
let shifted = Mods { shift: true, ..cmd() };
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), shifted);
assert_eq!(s.tool_id(), "directSelection");
let raw = Point::new(180.0, 150.0);
pointer(&mut s, PointerKind::Drag, raw, shifted);
assert_mirrored(anchor(&s, id), constrained(p, raw), AnchorKind::Smooth);
assert_other_geometry(&s, id, &before);
pointer(&mut s, PointerKind::Up, raw, shifted);
}
#[test]
fn direct_handle_cmd_press_on_a_handle_under_a_bounding_box_handle_still_lends_selection() {
let mut s = session();
let id = curve(&mut s, Point::new(50.0, 100.0));
// A second object widens the selection's bounding box so its top-middle handle lands on the
// curve's outgoing handle end at (180, 100).
let rect = run(&mut s, "path.create", json!({"anchors": [{"x": 330, "y": 150}, {"x": 340, "y": 150}, {"x": 340, "y": 200}], "closed": true}));
run(&mut s, "select.set", json!({"ids": [id.0, rect["id"]]}));
let boxed = ViewInfo { show_bbox: true, ..view() };
let end = Point::new(180.0, 100.0);
s.pointer(&PointerEvent::new(PointerKind::Down, end.x, end.y).with_mods(cmd()), boxed).unwrap();
assert_eq!(s.tool_id(), "selection", "the bounding box handle keeps the press for the lent Selection tool");
s.pointer(&PointerEvent::new(PointerKind::Up, end.x, end.y).with_mods(cmd()), boxed).unwrap();
assert_eq!(s.tool_id(), "directSelection");
}
#[test]
fn direct_handle_cmd_alt_before_pressing_a_handle_still_lends_group_selection() {
let mut s = session();
let id = curve(&mut s, Point::new(50.0, 100.0));
let a = anchor(&s, id);
let both = Mods { alt: true, ..cmd() };
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), both);
assert_eq!(s.tool_id(), "groupSelection", "Cmd+Alt keeps its Group Selection loan on a handle");
pointer(&mut s, PointerKind::Up, Point::new(180.0, 100.0), both);
assert_eq!(s.tool_id(), "directSelection");
assert_eq!(anchor(&s, id), a);
}
#[test]
fn direct_handle_cmd_that_lends_direct_selection_from_the_pen_does_not_mirror() {
let mut s = session();
@@ -490,6 +554,22 @@ fn direct_handle_pinned_blend_spine_cmd_shift_preserves_keys_and_mapping() {
assert_content(&s, &after);
}
#[test]
fn direct_handle_cmd_held_before_pressing_a_blend_spine_handle_mirrors() {
let mut s = session();
let id = blend(&mut s);
let (a, keys, _) = blend_state(&s, id);
pointer(&mut s, PointerKind::Down, a.h_out, cmd());
assert_eq!(s.tool_id(), "directSelection", "a Cmd press on a spine handle is not lent to the Selection tool");
let q = Point::new(180.0, 160.0);
pointer(&mut s, PointerKind::Drag, q, cmd());
pointer(&mut s, PointerKind::Up, q, cmd());
let (after, after_keys, _) = blend_state(&s, id);
near(after.p, a.p);
assert_mirrored(after, q, AnchorKind::Smooth);
assert_eq!(after_keys, keys, "the key objects did not move");
}
#[test]
fn direct_handle_incoming_drag_mirrors_outgoing_and_release_restores_ordinary_length() {
let mut s = session();
+72
View File
@@ -119,6 +119,78 @@ fn picked_handles_stay_picked_after_they_are_dragged() {
near(anchor(&s, id, 2).h_in, Point::new(310.0, 170.0));
}
/// With two handles picked, Cmd/Ctrl held before the press on one of them drags that handle alone
/// and mirrors its opposite handle; the other picked handle stays where it is.
#[test]
fn a_cmd_drag_of_one_of_two_picked_handles_mirrors_its_opposite_handle() {
let (mut s, id) = session();
click(&mut s, Point::new(180.0, 100.0), Mods::default());
click(&mut s, Point::new(300.0, 140.0), shift());
let cmd = Mods { cmd: true, ..Mods::default() };
drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 160.0), cmd);
assert_eq!(s.tool_id(), "directSelection");
let a = anchor(&s, id, 1);
near(a.h_out, Point::new(180.0, 160.0));
near(a.h_in, Point::new(20.0, 40.0));
assert_eq!(a.kind, AnchorKind::Smooth);
near(anchor(&s, id, 2).h_in, Point::new(300.0, 140.0));
}
/// Both handles stay picked after a Cmd/Ctrl drag of one of them: a drag of the other without
/// Cmd/Ctrl then moves both.
#[test]
fn picked_handles_stay_picked_after_a_cmd_drag_of_one_of_them() {
let (mut s, id) = session();
click(&mut s, Point::new(180.0, 100.0), Mods::default());
click(&mut s, Point::new(300.0, 140.0), shift());
let cmd = Mods { cmd: true, ..Mods::default() };
drag(&mut s, Point::new(180.0, 100.0), Point::new(180.0, 160.0), cmd);
drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default());
near(anchor(&s, id, 1).h_out, Point::new(190.0, 160.0));
near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0));
}
/// Both handles stay picked after a Cmd/Ctrl+Shift drag of one of them, and after Escape during
/// one.
#[test]
fn picked_handles_stay_picked_after_a_cmd_shift_drag_of_one_of_them() {
for escape in [false, true] {
let (mut s, id) = session();
click(&mut s, Point::new(180.0, 100.0), Mods::default());
click(&mut s, Point::new(300.0, 140.0), shift());
let cmd_shift = Mods { cmd: true, shift: true, ..Mods::default() };
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd_shift);
pointer(&mut s, PointerKind::Drag, Point::new(220.0, 100.0), cmd_shift);
if escape {
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
}
pointer(&mut s, PointerKind::Up, Point::new(220.0, 100.0), cmd_shift);
let x = if escape { 180.0 } else { 220.0 };
near(anchor(&s, id, 1).h_out, Point::new(x, 100.0));
drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default());
near(anchor(&s, id, 1).h_out, Point::new(x + 10.0, 100.0));
near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0));
}
}
/// Escape during a Cmd/Ctrl drag of one of two picked handles puts the handle back and leaves both
/// picked.
#[test]
fn escape_during_a_cmd_drag_of_a_picked_handle_keeps_both_picked() {
let (mut s, id) = session();
click(&mut s, Point::new(180.0, 100.0), Mods::default());
click(&mut s, Point::new(300.0, 140.0), shift());
let cmd = Mods { cmd: true, ..Mods::default() };
pointer(&mut s, PointerKind::Down, Point::new(180.0, 100.0), cmd);
pointer(&mut s, PointerKind::Drag, Point::new(180.0, 160.0), cmd);
s.tool_key(ToolKey::Escape, Mods::default(), view()).unwrap();
pointer(&mut s, PointerKind::Up, Point::new(180.0, 160.0), cmd);
near(anchor(&s, id, 1).h_out, Point::new(180.0, 100.0));
drag(&mut s, Point::new(300.0, 140.0), Point::new(310.0, 140.0), Mods::default());
near(anchor(&s, id, 1).h_out, Point::new(190.0, 100.0));
near(anchor(&s, id, 2).h_in, Point::new(310.0, 140.0));
}
/// A Shift-click on a picked handle takes it away, and Escape lets every picked handle go: a drag
/// then moves only the handle pressed.
#[test]
File diff suppressed because it is too large. Load diff
+162 -1
View File
@@ -8,7 +8,7 @@ use vectorcraft_doc::{
Appearance, AppearanceItem, Artboard, Dash, Document, FillLayer, ImageBlob, ImageObject, Knockout, LayerColor, LineCap, LineJoin, Node, NodeKind,
OpacityMask, StrokeLayer, Symbol,
};
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, shapes};
use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Shape, shapes};
use super::*;
@@ -1020,6 +1020,167 @@ fn hidden_layers_open_hidden() {
assert!(text.contains("%AI5_NumLayers: 3\n%AI5_OpenViewLayers: 776\n"), "{text}");
}
fn dash_painted_nodes(nodes: &[Arc<Node>], out: &mut Vec<Node>) {
for n in nodes {
match &n.kind {
NodeKind::Path { .. } | NodeKind::Compound { .. } => out.push((**n).clone()),
_ => {
if let Some(children) = n.children() {
dash_painted_nodes(children, out);
}
}
}
}
}
/// Original synthetic rectangle, independent of the artwork in #10476.
fn dash_compat_document(pattern: Vec<f64>) -> Document {
let mut doc = Document::new(200.0, 100.0);
let mut stroke = StrokeLayer::new(solid(Color::BLACK), 4.0);
stroke.dash = Some(Dash { pattern, offset: 2.5, align_corners: false });
stroke.overprint = true;
let ap = Appearance {
items: vec![AppearanceItem::Fill(FillLayer::new(solid(Color::rgb(0.0, 1.0, 0.0)))), AppearanceItem::Stroke(stroke)],
..Appearance::default()
};
let n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 180.0, 80.0)), ap);
doc.insert(Some(doc.layers[0].id), usize::MAX, n).unwrap();
doc
}
fn ai_dash_outputs(doc: &Document) -> Vec<(String, Vec<String>, Document)> {
let out = export_ai_editing(doc, &opts()).unwrap();
let legacy = crate::export_legacy_ai(doc, &crate::LegacyAiOptions::default()).unwrap();
let legacy_back = crate::import(&legacy.bytes).unwrap().document;
vec![
(String::from_utf8(out.program).unwrap().replace("\r\n", "\n"), out.warnings, read_back(doc)),
(String::from_utf8(legacy.bytes).unwrap().replace("\r\n", "\n"), legacy.warnings, legacy_back),
]
}
#[test]
fn ai_dash_lists_reduce_repetitions_and_keep_small_patterns_editable() {
for (pattern, emitted) in [
(vec![33.5673; 5], "[33.5673] 2.5 d"),
(vec![33.5673; 10], "[33.5673] 2.5 d"),
(vec![3.0, 2.0, 1.0, 3.0, 2.0, 1.0, 3.0, 2.0, 1.0], "[3 2 1] 2.5 d"),
(vec![0.25], "[0.25] 2.5 d"),
(vec![0.25, 0.5], "[0.25 0.5] 2.5 d"),
(vec![3.0, 2.0, 1.0], "[3 2 1] 2.5 d"),
(vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0], "[3 2 1 2 3 4] 2.5 d"),
] {
let doc = dash_compat_document(pattern.clone());
for (text, warnings, back) in ai_dash_outputs(&doc) {
assert!(text.contains(emitted), "{pattern:?}: missing {emitted}: {text}");
assert!(warnings.is_empty(), "{pattern:?}: {warnings:?}");
let mut art = vec![];
dash_painted_nodes(&back.layers, &mut art);
assert_eq!(art.len(), 1);
let st = art[0].appearance.stroke().unwrap();
assert_eq!(st.width, 4.0);
assert!(st.overprint);
assert_eq!(st.dash.as_ref().unwrap().offset, 2.5);
let got = &st.dash.as_ref().unwrap().pattern;
for i in 0..pattern.len() * got.len() * 2 {
assert_eq!(pattern[i % pattern.len()], got[i % got.len()]);
}
assert!(art[0].appearance.fill().is_some());
}
assert_eq!(doc.layers[0].children().unwrap()[0].appearance.stroke().unwrap().dash.as_ref().unwrap().pattern, pattern);
}
}
#[test]
fn ai_dash_lists_that_exceed_six_effective_lengths_are_outlined_with_a_warning() {
for pattern in [vec![3.0, 2.0, 1.0, 2.0, 3.0], vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0], vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]] {
let doc = dash_compat_document(pattern);
let original = &doc.layers[0].children().unwrap()[0];
let path = original.path_data().unwrap();
let expected = vectorcraft_effects::stroke::outline_region(path, FillRule::NonZero, original.appearance.stroke().unwrap()).to_bezpath();
for (text, warnings, back) in ai_dash_outputs(&doc) {
assert!(warnings.iter().any(|w| w.contains("filled outlines")), "{warnings:?}");
assert!(
!text.lines().filter(|l| l.ends_with(" d")).any(|l| {
let array = l.rsplit_once('[').unwrap().1.split(']').next().unwrap();
let n = array.split_whitespace().count();
n > 6 || (n % 2 == 1 && n * 2 > 6)
}),
"{text}"
);
let mut art = vec![];
dash_painted_nodes(&back.layers, &mut art);
assert!(art.iter().all(|n| n.appearance.stroke().is_none()), "{art:?}");
assert_eq!(art.len(), 2, "fill and outlined stroke keep their paint order");
assert_eq!(art[0].appearance.fill().unwrap().paint, solid(Color::rgb(0.0, 1.0, 0.0)));
let fill = art[1].appearance.fill().unwrap();
assert_eq!(fill.paint, solid(Color::BLACK));
assert!(fill.overprint);
let got = art[1].stroke_path().unwrap();
for y in 5..85 {
for x in 5..185 {
let p = vectorcraft_geom::Point::new(f64::from(x) + 0.123, f64::from(y) + 0.123);
assert_eq!(got.winding(p) != 0, expected.winding(p) != 0, "at {p:?}");
}
}
}
}
}
#[test]
fn ai_dash_lists_in_linked_styles_also_respect_the_reader_limit() {
for (pattern, live) in [(vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], false), (vec![33.5673; 5], true)] {
let mut doc = dash_compat_document(pattern);
let n = Arc::make_mut(&mut Arc::make_mut(&mut doc.layers[0]).children_mut().unwrap()[0]);
n.appearance.stroke_mut().unwrap().overprint = false;
n.extras_mut().graphic_style = Some(7);
let mut style = vectorcraft_doc::GraphicStyle::new("Dashed", (*n.appearance).clone());
style.id = 7;
doc.graphic_styles.push(style);
let out = export_ai_editing(&doc, &opts()).unwrap();
let text = String::from_utf8(out.program).unwrap();
assert!(!text.contains("[3 2 1 2 3 4 5 6]"), "a style dictionary must not keep an incompatible dash list");
if live {
assert!(out.warnings.is_empty(), "{:?}", out.warnings);
assert!(text.contains("1 (Dashed) XW"), "an equivalent dash representation keeps the style link");
assert!(text.contains("[33.5673] 2.5 d"));
} else {
assert!(out.warnings.iter().any(|w| w.contains("filled outlines")), "{:?}", out.warnings);
}
}
}
#[test]
fn ai_dash_lists_in_legacy_text_reduce_or_outline_without_becoming_solid() {
use vectorcraft_doc::{CharStyle, TextObject};
use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font};
// Existing licensed test face, with original single-letter artwork.
vectorcraft_text::FontDb::global().add_font(height_font(true).unwrap());
for (pattern, live) in [(vec![33.5673; 5], true), (vec![3.0, 2.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0], false)] {
let mut doc = Document::new(200.0, 100.0);
let st = CharStyle {
font_family: HEIGHT_FAMILY.into(),
size: 48.0,
fill: solid(Color::rgb(0.0, 1.0, 0.0)),
stroke: solid(Color::BLACK),
stroke_width: 2.0,
stroke_dash: Some(Dash { pattern, offset: 2.5, align_corners: false }),
..CharStyle::default()
};
let t = TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "T", st);
let n = Node::new(doc.alloc_id(), NodeKind::Text(Box::new(t)));
doc.insert(Some(doc.layers[0].id), usize::MAX, n).unwrap();
let out = crate::export_legacy_ai(&doc, &crate::LegacyAiOptions::default()).unwrap();
let text = String::from_utf8(out.bytes).unwrap().replace("\r\n", "\n");
assert_eq!(text.contains("0 To\n"), live, "irreducible type strokes must take the outline fallback");
if live {
assert!(text.contains("[33.5673] 2.5 d"));
} else {
assert!(out.warnings.iter().any(|w| w.contains("filled outlines")), "{:?}", out.warnings);
assert!(text.matches("\nf\n").count() >= 2, "the glyph's fill and dashed stroke are both painted");
}
}
}
/// A 200 × 100 document of a gradient fill, a compound path, an image and a symbol instance, and
/// what the data holds as plain paths: type.
fn unsupported() -> Document {
+1 -1
View File
@@ -71,7 +71,7 @@ pub(super) const LIVE: &str =
"repeats, placed documents, intertwines and distorted images are written as their art in the editing data for other apps";
pub(super) const DEEP_DISTORTED: &str = "images changed by Perspective Distort or Free Distort nested 8 deep in opacity masks, symbols, live objects and pattern tiles are written as the nearest parallelogram in the editing data for other apps";
pub(super) const GRAPHS: &str = "graphs are written as their art, without their data or settings, in the editing data for other apps";
pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps";
pub(super) const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, complex dash patterns, dots, dashes fitted to corners, gradients, patterns, arrowheads) are written as filled outlines, and brushed strokes as their brush's art, in the editing data for other apps";
pub(super) const ITEM_TRANSPARENCY: &str =
"the opacity and blending modes of single fills and strokes are left out of the editing data for other apps";
pub(super) const LAYER_MASKS: &str = "opacity masks on layers are left out of the editing data for other apps";
+1 -1
View File
@@ -364,7 +364,7 @@ fn plain_key(k: &Node) -> bool {
&& i.effects().is_empty()
&& i.opacity() >= 1.0
&& i.blend() == BlendMode::Normal
&& !matches!(i, AppearanceItem::Stroke(s) if !vectorcraft_effects::stroke::is_plain(s) || !dash_read_back(s))
&& !matches!(i, AppearanceItem::Stroke(s) if !crate::ai_ops::plain_stroke(s) || !dash_read_back(s))
});
plain &= kind && fills <= 1 && strokes <= 1 && order && quiet && n.appearance.effects.is_empty() && n.extras().mask.is_none();
});
+2 -2
View File
@@ -258,7 +258,7 @@ fn plain_within(art: &Node, masks: u32) -> bool {
&& i.opacity() >= 1.0
&& i.blend() == BlendMode::Normal
&& matches!(i.paint(), Paint::Solid { .. } | Paint::None)
&& !matches!(i, AppearanceItem::Stroke(s) if !vectorcraft_effects::stroke::is_plain(s))
&& !matches!(i, AppearanceItem::Stroke(s) if !crate::ai_ops::plain_stroke(s))
});
// A group's own fills and strokes aren't written.
let group_paint = matches!(n.kind, NodeKind::Group { .. }) && items.iter().any(|i| !i.paint().is_none());
@@ -519,7 +519,7 @@ impl Writer<'_> {
let name = st.brush.as_deref()?;
self.brush_set();
let (plugin, kind) = self.live_brush(name).map(|b| (b.plugin, b.brush.kind.clone()))?;
if !matches!(st.paint, Paint::Solid { .. }) || st.overprint {
if !matches!(st.paint, Paint::Solid { .. }) || st.overprint || !ai_ops::dash_fits(st) {
return None;
}
let ops = self.color_ops(&st.paint, true);
+1 -2
View File
@@ -8,7 +8,6 @@ use vectorcraft_color::gradient::GradientGeom;
use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_color::{Color, Gradient, GradientKind, GradientPaint, GradientStop, Paint};
use vectorcraft_doc::{AppearanceItem, FillLayer, PatternDef, StrokeLayer, TileType};
use vectorcraft_effects::stroke;
use vectorcraft_geom::{Affine, BezPath, Rect, Shape, Vec2};
use super::{MAX_NEST, Writer, Xy};
@@ -367,7 +366,7 @@ impl Writer<'_> {
/// Does a plain line of `s`'s paint draw it ([`Self::direct`], and the line style operators can
/// write it)?
pub(super) fn direct_stroke(&self, s: &StrokeLayer) -> bool {
self.direct(&s.paint) && stroke::is_plain(s)
self.direct(&s.paint) && crate::ai_ops::plain_stroke(s)
}
/// `n`'s paint `items` as one path object paints: no paint, a fill, a plain line, or both, the
+11 -1
View File
@@ -404,7 +404,7 @@ impl Writer<'_> {
if st.brush.is_some() {
return self.brush_filter(s, st, visible);
}
if !matches!(st.paint, Paint::Solid { .. }) || st.overprint {
if !matches!(st.paint, Paint::Solid { .. }) || st.overprint || !ai_ops::dash_fits(st) {
return None;
}
let ops = self.color_ops(&st.paint, true);
@@ -1077,6 +1077,16 @@ pub(in crate::ai_editing) fn same_appearance(a: &Appearance, b: &Appearance) ->
let below = ap.items.iter().take(ci).filter(|i| !i.paint().is_none()).count();
ap.items.retain(|i| !i.paint().is_none());
ap.contents_index = (below > 0).then_some(below);
// The writer shortens repeated dash lists without changing their painted period.
// Compare those representations equally so a linked style can stay live.
for i in &mut ap.items {
if let AppearanceItem::Stroke(st) = i
&& let Some(d) = st.dash.as_mut().filter(|d| d.is_dashed())
&& let Some(pattern) = ai_ops::dash_pattern(&d.pattern)
{
d.pattern = pattern.to_vec();
}
}
for e in ap.effects.iter_mut().chain(ap.items.iter_mut().flat_map(|i| i.effects_mut().iter_mut())) {
e.params = normalized_params(e);
}
+2 -2
View File
@@ -425,8 +425,8 @@ fn plain_wrap_art(n: &Node, styled: &HashMap<NodeId, Arc<Node>>) -> bool {
let painted = || match super::visible_items(n).as_slice() {
[] => true,
[AppearanceItem::Fill(f)] => solid(&f.paint),
[AppearanceItem::Stroke(s)] => solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s),
[AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] => solid(&f.paint) && solid(&s.paint) && vectorcraft_effects::stroke::is_plain(s),
[AppearanceItem::Stroke(s)] => solid(&s.paint) && crate::ai_ops::plain_stroke(s),
[AppearanceItem::Fill(f), AppearanceItem::Stroke(s)] => solid(&f.paint) && solid(&s.paint) && crate::ai_ops::plain_stroke(s),
_ => false,
};
let whole = |p: &PathData| p.subpaths.iter().all(|sp| sp.anchors.len() >= 2);
+23 -2
View File
@@ -179,7 +179,28 @@ pub(crate) fn window_samples(samples: &[u8], w: u32, channels: usize, [x0, y0, x
out
}
/// The stroke's width, cap, join, miter limit and dashes: `w J j M d`.
/// The shortest equivalent dash list the AI reader can hold. Odd lists repeat twice before
/// dash/gap parity repeats. Keep at most six effective lengths: longer lists can make the
/// reader reject the entire file (#10476). Compare exactly, so no dash or gap changes length.
pub(crate) fn dash_pattern(pattern: &[f64]) -> Option<&[f64]> {
(1..=pattern.len().min(6))
.filter(|n| n % 2 == 0 || *n <= 3)
.find(|n| pattern.len().is_multiple_of(*n) && pattern.iter().enumerate().all(|(i, v)| *v == pattern[i % n]))
.map(|n| &pattern[..n])
}
/// Invalid or empty dashes already draw solid; valid dashes need an exact short representation.
pub(crate) fn dash_fits(st: &StrokeLayer) -> bool {
st.dash.as_ref().filter(|d| d.is_dashed()).is_none_or(|d| dash_pattern(&d.pattern).is_some())
}
/// A plain AI stroke, including the reader's dash-list limit. Other strokes use filled outlines.
pub(crate) fn plain_stroke(st: &StrokeLayer) -> bool {
vectorcraft_effects::stroke::is_plain(st) && dash_fits(st)
}
/// The stroke's width, cap, join, miter limit and dashes: `w J j M d`. Callers check
/// [`dash_fits`] first; irreducible longer patterns belong in their outline fallback.
pub(crate) fn line_style(s: &mut String, st: &StrokeLayer) {
let cap = match st.cap {
LineCap::Butt => ps::LineCap::Butt,
@@ -191,6 +212,6 @@ pub(crate) fn line_style(s: &mut String, st: &StrokeLayer) {
LineJoin::Round => ps::LineJoin::Round,
LineJoin::Bevel => ps::LineJoin::Bevel,
};
let dash = st.dash.as_ref().filter(|d| d.is_dashed()).map(|d| (d.pattern.as_slice(), d.offset));
let dash = st.dash.as_ref().filter(|d| d.is_dashed()).and_then(|d| dash_pattern(&d.pattern).map(|p| (p, d.offset)));
ps::push_line_style(s, st.width, cap, join, st.miter_limit, dash);
}
+1 -2
View File
@@ -125,8 +125,7 @@ const HUE_STOPS: &str = "gradients mixed around the hue wheel are written in pro
const PERCEPTUAL_STOPS: &str = "Perceptual gradients are written in process colors, with the colors between their stops as stops of their own (at most 256; legacy .ai gradients mix their stops' colors directly)";
/// Wedges a conic gradient is written as: one a degree.
const CONIC_WEDGES: usize = 360;
const STROKES: &str =
"strokes a plain line can't draw (inside or outside the path, variable width, gradients, brushes, arrowheads) are written as filled outlines";
const STROKES: &str = "strokes a plain line can't draw (inside or outside the path, variable width, complex dash patterns, gradients, brushes, arrowheads) are written as filled outlines";
const IMAGE_ALPHA: &str = "transparent image pixels are written over white";
const LIVE: &str = "symbols, blends, envelopes, meshes, repeats, placed documents, intertwines and distorted images are written as their art";
const DEEP_DISTORTED: &str =
+5 -2
View File
@@ -1,7 +1,7 @@
use super::writer::Writer;
use super::{
Affine, AreaOptions, BezPath, CharPosition, CharStyle, CompositeFont, Document, Gradient, GradientKind, Paint, ParaStyle, PathAlign, PathEffect,
StrokeLayer, TextKind, TextObject, Write, latin, ps, stroke,
StrokeLayer, TextKind, TextObject, Write, latin, ps,
};
/// A gradient definition: `%AI5_BeginGradient: (name)`, `(name) type stops Bd`, `[`, the stops
@@ -111,6 +111,9 @@ pub(super) fn holds_as_text(t: &TextObject) -> bool {
r.inline.is_none()
&& solid(&r.style.fill)
&& solid(&r.style.stroke)
// Long dash lists can reject the entire AI file. Keep their glyph paint by
// taking the existing type-outline path instead of writing a solid stroke.
&& (!r.style.has_stroke() || crate::ai_ops::dash_fits(&r.style.stroke_layer()))
&& (if r.style.all_caps { r.text.to_uppercase() } else { r.text.clone() }).chars().all(|c| latin::encode(c).is_some())
})
}
@@ -221,5 +224,5 @@ pub(super) fn direct_fill(p: &Paint) -> bool {
/// Can stroke `s` be written as the stroke of a path object (a plain line of a colour)?
pub(super) fn direct_stroke(s: &StrokeLayer) -> bool {
matches!(s.paint, Paint::Solid { .. }) && stroke::is_plain(s)
matches!(s.paint, Paint::Solid { .. }) && crate::ai_ops::plain_stroke(s)
}
+1
View File
@@ -34,6 +34,7 @@
//! - `ai_graph`: the records of a live graph those two write around its group.
//! - `gradient_key`: the key those two find gradient definitions by.
//! - [`dcs`]: DCS files, an EPS file with one program per printing plate, read for placing.
#![doc(test(attr(deny(unsafe_code))))]
mod ai_editing;
mod ai_graph;
+1
View File
@@ -37,6 +37,7 @@
//! already; [`save_with`] writes a version 1 document with them negated back for an older file
//! version ([`vectorcraft_doc::twist`]).
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
#[cfg(not(target_arch = "wasm32"))]
mod atomic;
+89 -4
View File
@@ -2,7 +2,7 @@
use std::borrow::Cow;
use kurbo::{BezPath, ParamCurveNearest, PathEl, Point, Rect, Shape};
use kurbo::{BezPath, ParamCurveNearest, PathEl, PathSeg, Point, Rect, Shape};
use crate::path::{FillRule, PathData};
@@ -104,13 +104,51 @@ fn closed(path: &BezPath) -> Cow<'_, BezPath> {
/// Distance from `p` to the nearest point on the path outline.
pub fn distance_to_outline(path: &BezPath, p: Point) -> f64 {
path.segments().map(|s| s.nearest(p, 1e-9).distance_sq).fold(f64::INFINITY, f64::min).sqrt()
path.segments().map(|s| nearest_distance_sq(s, p)).fold(f64::INFINITY, f64::min).sqrt()
}
/// Is `p` within `tol` of the path's stroke of width `width`?
pub fn stroke_contains(path: &BezPath, width: f64, tol: f64, p: Point) -> bool {
let quick = path.bounding_box().inflate(width / 2.0 + tol, width / 2.0 + tol);
quick.contains(p) && distance_to_outline(path, p) <= width / 2.0 + tol
let radius = width / 2.0 + tol;
if !path.bounding_box().inflate(radius, radius).contains(p) {
return false;
}
if !radius.is_finite() {
return distance_to_outline(path, p) <= radius;
}
// Keep candidates whose squared distance could underflow near a zero radius.
let search_radius = radius.max(f64::MIN_POSITIVE.sqrt());
path.segments().any(|segment| !curve_outside_reach(segment, p, search_radius) && nearest_distance_sq(segment, p).sqrt() <= radius)
}
// A Bézier stays inside the bounds of its control points. A line projection is
// already cheap, so only check the bounds before running a curve solver.
fn curve_outside_reach(segment: PathSeg, p: Point, radius: f64) -> bool {
let bounds = match segment {
PathSeg::Line(_) => return false,
PathSeg::Quad(q) => Rect::from_points(q.p0, q.p1).union_pt(q.p2),
PathSeg::Cubic(c) => Rect::from_points(c.p0, c.p1).union_pt(c.p2).union_pt(c.p3),
};
outside_axis(p.x, radius, bounds.x0, bounds.x1) || outside_axis(p.y, radius, bounds.y0, bounds.y1)
}
fn outside_axis(p: f64, radius: f64, low: f64, high: f64) -> bool {
// Leave room for rounding in the curve evaluation and the distance comparison.
let scale = p.abs().max(low.abs()).max(high.abs()).max(radius);
let padded = radius + 8.0 * f64::EPSILON * scale;
p < low - padded || p > high + padded
}
fn nearest_distance_sq(segment: PathSeg, p: Point) -> f64 {
#[cfg(test)]
OUTLINE_NEAREST_CALLS.with(|count| count.set(count.get() + 1));
segment.nearest(p, 1e-9).distance_sq
}
#[cfg(test)]
thread_local! {
static OUTLINE_NEAREST_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Does the path touch the rect: an anchor inside it, or a segment crossing its edges? Used for
@@ -185,6 +223,53 @@ mod tests {
assert!(!stroke_contains(&p, 2.0, 0.0, Point::new(12.0, 5.0)));
}
#[test]
fn stroke_hit_skips_distant_curves_without_changing_results() {
let mut path = BezPath::new();
for i in 0..96 {
let x = f64::from(i) * 16.0;
path.move_to((x, 0.0));
path.curve_to((x + 1.0, 4.0), (x + 2.0, -4.0), (x + 3.0, 0.0));
}
path.move_to((512.0, 0.0));
path.quad_to((513.0, 4.0), (514.0, 0.0));
for (point, expected_hit, expected_calls) in [(Point::new(512.0, 0.0), true, 1), (Point::new(520.0, 0.0), false, 0)] {
assert_eq!(distance_to_outline(&path, point) <= 0.5, expected_hit);
assert!(path.bounding_box().contains(point));
OUTLINE_NEAREST_CALLS.with(|count| count.set(0));
assert_eq!(stroke_contains(&path, 0.0, 0.5, point), expected_hit);
assert_eq!(OUTLINE_NEAREST_CALLS.with(std::cell::Cell::get), expected_calls);
}
assert_stroke_hits_at_cutoff();
}
fn assert_stroke_hits_at_cutoff() {
let mut path = BezPath::new();
path.move_to((0.0, 0.0));
path.line_to((0.0, 0.0));
path.quad_to((4.0, 8.0), (8.0, 0.0));
path.curve_to((12.0, 8.0), (16.0, -4.0), (20.0, 0.0));
path.close_path();
path.move_to((2.0, -3.0));
path.line_to((2.0, -3.0));
for transform in [kurbo::Affine::IDENTITY, kurbo::Affine::new([-2.0, 1.0, 0.0, 1.0, 10.0, 1e8])] {
let transformed = transform * path.clone();
for x in -2..23 {
for y in -5..9 {
let point = transform * Point::new(f64::from(x), f64::from(y));
let distance = distance_to_outline(&transformed, point);
for radius in [distance.next_down(), distance, distance.next_up(), 0.0, 1.5] {
let inside = transformed.bounding_box().inflate(radius, radius).contains(point);
assert_eq!(stroke_contains(&transformed, 0.0, radius, point), inside && distance <= radius, "{point:?}, {radius}");
}
}
}
}
}
#[test]
fn evenodd_hole() {
let mut outer = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));
+1
View File
@@ -6,6 +6,7 @@
//!
//! Coordinates are document points (1/72 in), y pointing down.
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
pub mod anchors;
pub mod arc;
+1
View File
@@ -131,6 +131,7 @@
//! `await` (ECMA-262 2017 section 25.5, <https://262.ecma-international.org/8.0/#sec-async-function-objects>).
//! An `await` suspends its function's frame until the value settles, and a promise job resumes it.
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
pub mod ast;
mod builtins;
+1
View File
@@ -13,6 +13,7 @@
//!
//! Entry points: [`Server::serve`] (stdio loop) and [`Server::handle_line`] (one message).
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
mod backend;
mod headless;
+1
View File
@@ -26,6 +26,7 @@
//! formats.
//!
//! The app walks its document and maps its drawing operations to the shared writers.
#![doc(test(attr(deny(unsafe_code))))]
#[cfg(test)]
mod bytes;
+1
View File
@@ -5,6 +5,7 @@
//! Béziers, and the pieces it splits curves into are refitted afterwards so results carry few
//! anchors. See the crate README for the API overview.
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
pub mod addons;
mod boolean;
+42 -2
View File
@@ -1,5 +1,7 @@
use std::collections::HashMap;
use vectorcraft_geom::Vec2;
use super::exporter::{UNDECODED, address, blend, color, constant_mask, cover, in_range, norm, rects_overlap, rule, to_path, writable, xf};
use super::{
Affine, AppearanceItem, BezPath, BlendMode, Document, Exporter, Fill, FillRule, GradientKind, LineCap, LineJoin, Mark, Node, NodeKind,
@@ -19,6 +21,37 @@ fn brushed(b: Option<Rect>, reach: f64) -> Option<Rect> {
if reach > 0.0 { b.map(|b| b.inflate(reach, reach)) } else { b }
}
/// Can the patch shade its own outline without folding across it? The differences of adjacent
/// tensor control points bound each directional derivative in a convex cone. If every pair of
/// derivatives has the same strict orientation, averaging them along any segment keeps them
/// independent, so distinct parameter points cannot map to the same point.
fn unfolded_patch(points: [(f32, f32); 12]) -> bool {
let p = points.map(|(x, y)| Vec2::new(f64::from(x), f64::from(y)));
let top = [p[0], p[11], p[10], p[9]];
let bottom = [p[3], p[4], p[5], p[6]];
let left = [p[0], p[1], p[2], p[3]];
let right = [p[9], p[8], p[7], p[6]];
// Raise the linear blending terms of the Coons surface to cubic degree in each direction.
let net: [[Vec2; 4]; 4] = std::array::from_fn(|row| {
let v = row as f64 / 3.0;
std::array::from_fn(|col| {
let u = col as f64 / 3.0;
let bilinear = (p[0] * (1.0 - u) + p[9] * u) * (1.0 - v) + (p[3] * (1.0 - u) + p[6] * u) * v;
top[col] * (1.0 - v) + bottom[col] * v + left[row] * (1.0 - u) + right[row] * u - bilinear
})
});
let du: [[Vec2; 3]; 4] = std::array::from_fn(|row| std::array::from_fn(|col| net[row][col + 1] - net[row][col]));
let dv: [[Vec2; 4]; 3] = std::array::from_fn(|row| std::array::from_fn(|col| net[row + 1][col] - net[row][col]));
let orientation = du[0][0].cross(dv[0][0]).signum();
du.into_iter().flatten().all(|u| {
dv.iter().flatten().all(|v| {
let cross = u.cross(*v) * orientation;
// Keep near-parallel directions on the existing clipped path through PDF quantization.
cross > 0.0 && cross * cross > 1e-12 * u.hypot2() * v.hypot2()
})
})
}
#[cfg(test)]
std::thread_local! {
/// The objects this thread has measured for the walk and for the links (tests).
@@ -542,7 +575,7 @@ impl Exporter<'_> {
}
}
/// Gradient mesh `m` as one PDF Type 6 (Coons patch) shading filling its outline (ISO 32000-1,
/// Gradient mesh `m` as one PDF Type 6 (Coons patch) shading (ISO 32000-1,
/// 8.7.4.5.7): each patch blends its corner colours bilinearly, as the canvas draws it, and
/// the viewer or RIP does so smoothly at its own resolution. Cutting the mesh into flat quads
/// instead banded, left seams between them, and made files with many meshes very large.
@@ -560,7 +593,6 @@ impl Exporter<'_> {
if !writable(s, Affine::IDENTITY, bounds) {
return false;
}
let Some(path) = to_path(s, &m.outline().to_bezpath()) else { return false };
let page: Vec<vectorcraft_color::Color> = m.points.iter().map(|p| self.page_color(&p.color)).collect();
let mixed = page.windows(2).any(|w| w[0].model() != w[1].model());
let rgb = page.iter().any(|c| matches!(c, vectorcraft_color::Color::Rgb { .. } | vectorcraft_color::Color::Lab { .. }));
@@ -584,6 +616,14 @@ impl Exporter<'_> {
patches.push(krilla::paint::MeshPatch { points, colors, opacities: [NormalizedF32::ONE; 4] });
}
}
// An unfolded single patch shades its own outline. Filling that exact outline makes some
// readers antialias it twice and leave seams where patches touch. Keep the outline for
// folded geometry and for meshes with more than one patch, which can overlap themselves.
let bounds_path = match patches.as_slice() {
[patch] if unfolded_patch(patch.points) => to_path(s, &bounds.inflate(1.0, 1.0).to_path(0.1)),
_ => None,
};
let Some(path) = bounds_path.or_else(|| to_path(s, &m.outline().to_bezpath())) else { return false };
let mesh = krilla::paint::MeshGradient { patches, transform: xf(Affine::IDENTITY), anti_alias: false };
s.set_stroke(None);
s.set_fill(Some(Fill { paint: mesh.into(), opacity: NormalizedF32::ONE, rule: krilla::paint::FillRule::NonZero }));
+1
View File
@@ -42,6 +42,7 @@
//! security handler, the algorithm following the compatibility ([`Encryption`]); either password
//! opens an encrypted file.
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
mod editing;
mod encrypt;
+74
View File
@@ -2,12 +2,16 @@
//! viewer blends each patch's corner colours smoothly, instead of the mesh being cut into small
//! flat-coloured paths that band, show seams and make the file large.
use craft::pdf::syntax::content::{TypedIter, ops::TypedInstruction};
use craft::pdf::syntax::object::{Name, Object};
use vectorcraft_color::Color;
use vectorcraft_doc::live::{GradientMesh, MeshAppearance};
use vectorcraft_doc::{ColorMode, Document, Node, NodeKind};
use vectorcraft_geom::{Rect, shapes};
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with};
use vectorcraft_testkit::raster::{assert_similar, render_artboard};
use super::import_fidelity::stream;
use crate::*;
/// A 200 × 200 pt document with a 2 × 2 mesh over (20, 20)–(180, 180), its nine points coloured
@@ -44,6 +48,76 @@ fn kinds(d: &Document) -> (usize, usize) {
(meshes, paths)
}
fn import_patches(boundaries: &[[(u8, u8); 12]]) -> Document {
use std::fmt::Write as _;
let mut data = String::new();
for boundary in boundaries {
data.push_str("00"); // Every patch supplies all its vertices.
for (x, y) in boundary {
write!(data, "{x:02X}{y:02X}").unwrap();
}
data.push_str(&"28465A".repeat(4));
}
data.push('>');
let shading = stream(
"/ShadingType 6 /ColorSpace /DeviceRGB /BitsPerCoordinate 8 /BitsPerComponent 8 /BitsPerFlag 8 \
/Decode [0 255 0 255 0 1 0 1 0 1] /Filter /ASCIIHexDecode",
&data,
);
let page = PdfPage {
resources: format!("/Shading << /Mesh {} 0 R >>", first_extra(1)),
..PdfPage::new(100.0, 100.0, "q 0.8 0 0 0.8 10 10 cm /Mesh sh Q")
};
let imported = import(&pdf_with(&[page], &[&shading], None)).unwrap();
assert_eq!(kinds(&imported).0, boundaries.len());
imported
}
fn has_curved_outline(bytes: &[u8]) -> bool {
let output = crate::pages::open(bytes, None).unwrap();
let pages = output.pages();
let has_curve = |content: &[u8]| {
let mut ops = TypedIter::new(content);
while let Some(op) = ops.next() {
if matches!(op, TypedInstruction::CubicTo(_) | TypedInstruction::CubicStartTo(_) | TypedInstruction::CubicEndTo(_)) {
return true;
}
}
false
};
if has_curve(pages.iter().next().unwrap().page_stream().unwrap()) {
return true;
}
output.objects().into_iter().any(|object| match object {
Object::Stream(form) if form.dict().get::<Name<'_>>(b"Subtype").is_some_and(|name| name.as_ref() == b"Form") => {
has_curve(&form.decoded().unwrap())
}
_ => false,
})
}
#[test]
fn joined_opaque_pdf_meshes_keep_their_shading_edges_on_export() {
// The same cubic, in opposite directions, is the two patches' inner edge.
let imported = import_patches(&[
[(10, 95), (10, 65), (10, 35), (10, 5), (25, 5), (40, 5), (55, 5), (61, 30), (41, 70), (45, 95), (35, 95), (22, 95)],
[(45, 95), (41, 70), (61, 30), (55, 5), (68, 5), (82, 5), (90, 5), (90, 35), (90, 65), (90, 95), (75, 95), (60, 95)],
]);
let bytes = export(&imported, &PdfOptions::default()).unwrap();
assert!(!has_curved_outline(&bytes), "the writer must leave the shared curved edge to the shading itself");
let reimported = import(&bytes).unwrap();
assert_eq!(kinds(&reimported).0, 2, "both patches still export as vector shadings");
assert_similar(&render_artboard(&imported), &render_artboard(&reimported), 6.0, 0.01);
}
#[test]
fn folded_pdf_mesh_still_uses_its_outline() {
let imported =
import_patches(&[[(10, 95), (92, 65), (93, 35), (10, 5), (25, 5), (40, 5), (90, 5), (4, 30), (3, 70), (90, 95), (65, 95), (42, 95)]]);
let bytes = export(&imported, &PdfOptions::default()).unwrap();
assert!(has_curved_outline(&bytes), "a rectangle would expose folded paint outside the intended outline");
}
#[test]
fn a_gradient_mesh_is_written_as_a_smooth_patch_shading() {
let d = doc(rgb, 1.0);
+1
View File
@@ -42,6 +42,7 @@
//! `"runtime": "js"` and names a `.js` file, which runs in a fresh `vectorcraft-js` realm for each
//! run, with the same input, output, permissions and budgets.
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
pub mod deferred;
pub mod dialog;
+1
View File
@@ -5,6 +5,7 @@
//! (multiple fills/strokes, opacity, blend modes, stroke alignment, dashes), clip groups,
//! gradients, images and text (via `vectorcraft-text` glyph outlines).
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
pub mod addons;
mod brush_fx;
+1
View File
@@ -22,6 +22,7 @@
//! keeps open brackets and the levels of an XML literal on capped stacks. Its work is linear in the
//! input's size, and no input can overflow the stack.
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
mod analyze;
mod catalog;
+1
View File
@@ -100,6 +100,7 @@
//! letter and word spacing become character attributes (line breaks, kerning, baseline shift,
//! rotation and style names).
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
use craft_svg::tree::usvg;
mod css;
+1
View File
@@ -22,6 +22,7 @@
// apply here.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
pub mod ai;
pub mod ase;
+6 -3
View File
@@ -171,10 +171,13 @@ mod tests {
let expected: Vec<_> =
["Noto Sans Arabic", "Noto Sans Thai", "Noto Sans Georgian"].into_iter().filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)).collect();
assert_eq!(startup, expected);
// Korean and Devanagari faces are fetched only on demand, never at startup or in the
// background queue every session runs.
// Korean, Devanagari and Gujarati faces are fetched only on demand, never at startup or in
// the background queue every session runs.
let demand: Vec<_> = WEB_FONTS.iter().filter(|w| w.demand).map(|w| w.family).collect();
let expected: Vec<_> = ["NanumGothic", "Noto Sans Devanagari"].into_iter().filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)).collect();
let expected: Vec<_> = ["NanumGothic", "Noto Sans Devanagari", "Noto Sans Gujarati"]
.into_iter()
.filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n))
.collect();
assert_eq!(demand, expected);
assert!(WEB_FONTS.iter().all(|w| !(w.startup && w.demand)));
}
+1
View File
@@ -9,6 +9,7 @@
//!
//! Frames (`TextKind::Area`) and paths (`TextKind::OnPath`) are interpreted in text space.
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
mod bitmap;
mod colr;
+2 -1
View File
@@ -3,10 +3,11 @@
# startup = fetched before the app starts (fallbacks the first frame needs)
# background = fetched after the app starts (fonts users pick by name)
# demand = fetched only when the interface language or the interface's own text needs one of
# the face's scripts (Korean, Hindi)
# the face's scripts (Korean, Hindi, Gujarati)
# Read by build.rs (the WEB_FONTS table) and `cargo xtask web-fonts` (copies the files, a Trunk hook).
startup | Noto Sans Arabic | Regular
startup | Noto Sans Thai | Regular
startup | Noto Sans Georgian | Regular
demand | NanumGothic | Regular
demand | Noto Sans Devanagari | Regular
demand | Noto Sans Gujarati | Regular
+1
View File
@@ -7,6 +7,7 @@
//!
//! [`fold`] finds the panels and hinges of a flat packaging blank from its fold lines.
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
pub mod fold;
mod solid;
+56 -11
View File
@@ -110,6 +110,8 @@ struct HandlePress {
moved: bool,
/// The picked handles when the press began.
picked: PickedHandles,
/// A mirroring Cmd/Ctrl press on one of several picked handles: they stay picked after its drag.
keeps_picks: bool,
}
#[derive(Clone, Debug)]
@@ -1046,6 +1048,33 @@ impl Tool for DirectSelectionTool {
self.lent_cmd = value.as_bool().unwrap_or(false);
}
}
/// A Cmd/Ctrl press without Alt on the end of a shown direction handle (a path's, type on a
/// path's or a selected blend spine anchor's) stays with Direct Selection, so the drag mirrors
/// the opposite handle ([`DirectSelectionTool::mirrors`]). A press on a handle of the bounding
/// box the lent Selection tool shows still goes to that tool, and so does a press anywhere else,
/// including one that a press of the tool gives to something it checks before the handles (a
/// corner widget, a bracket of type on a path, a gradient mesh point).
fn keeps_cmd_press(&self, cx: &ToolContext, p: Point, mods: Mods) -> bool {
if self.group || mods.alt || crate::select::bbox_handle_at(cx, p) {
return false;
}
let point = cx.point_tol();
// The order of the checks is the order `pointer` tries them in on a press.
let ev = PointerEvent::new(PointerKind::Down, p.x, p.y).with_mods(mods);
if CornerDrag::hit(cx, &ev, true).is_some_and(|c| !(c.on_unpicked() && c.widget_center().is_some_and(|w| yields_to_point(cx, p, w)))) {
return false;
}
if !over_path_type_anchor(cx, p) && BracketDrag::hit_any(cx, &ev).is_some() {
return false;
}
if self.spine.filter(|(id, _)| cx.selection.contains(*id)).and_then(|sel| hit_spine_handle(cx, sel, p, point)).is_some() {
return true;
}
if self.mesh.hit(cx, &cx.selection.objects, p).is_some() {
return false;
}
hit_handle(cx, p, point).is_some()
}
/// Escape during a drag (anchors, handles, segments, objects, type areas, blend spines, mesh
/// points, corner widgets, the brackets of type on a path, a marquee) cancels it: what it moved
/// goes back and the tool waits for the next press (#1743).
@@ -1087,13 +1116,16 @@ impl Tool for DirectSelectionTool {
self.mesh.cancel();
// The frame anchors or handles a cancelled drag held stay selected.
let frame = matches!(self.state, State::TypeArea { .. }) && !self.frame.is_empty();
let handles = matches!(self.state, State::Handles { .. });
let kept = self.handle_press.take().filter(|press| press.keeps_picks && matches!(self.state, State::Handle { .. }));
let handles = matches!(self.state, State::Handles { .. }) || kept.is_some();
if let Some(press) = kept {
self.handles = press.picked;
}
self.state = State::Idle;
self.guides.clear();
(self.anchor_snap, self.copy_snap, self.move_snap) = (None, None, None);
self.last_location = None;
(self.click, self.click_segment, self.click_group, self.frame_click) = (None, None, None, None);
self.handle_press = None;
match (frame, handles) {
(true, _) => vec![Action::Cancel, Action::Notify(FRAME_PICKED.into())],
(_, true) => vec![Action::Cancel, Action::Notify(HANDLES_PICKED.into())],
@@ -1896,9 +1928,11 @@ impl DirectSelectionTool {
self.state = State::Handle { id, si, ai, out, drag: Some(drag) };
vec![Action::Preview("path.setHandle".into(), params)]
}
/// A press on the end of the direction handle `(id, si, ai, out)`. Without Shift on one of two or
/// more picked handles (`picks`, as they were before the press), a drag moves them all; any
/// other press drags that handle alone, as before handles could be picked.
/// A press on the end of the direction handle `(id, si, ai, out)`. Without Shift or a mirroring
/// Cmd/Ctrl ([`Self::mirrors`]) on one of two or more picked handles (`picks`, as they were
/// before the press), a drag moves them all; any other press drags that handle alone, as before
/// handles could be picked, so a Cmd/Ctrl drag mirrors its opposite handle. The picked handles
/// stay picked after such a Cmd/Ctrl or Cmd/Ctrl+Shift drag of one of them.
fn press_handle(
&mut self,
cx: &ToolContext,
@@ -1931,8 +1965,11 @@ impl DirectSelectionTool {
};
let handle = (id, (si, ai, out));
let on = picks.get(&id).is_some_and(|set| set.contains(&handle.1));
let several = on && !ev.mods.shift && picks.values().map(BTreeSet::len).sum::<usize>() > 1;
let begin = if several {
let one_of_several = on && picks.values().map(BTreeSet::len).sum::<usize>() > 1;
let among_several = one_of_several && !ev.mods.shift;
// A mirroring drag keeps the picks with Shift held too.
let keeps_picks = one_of_several && self.mirrors(ev);
let begin = if among_several && !keeps_picks {
let items = picks.iter().flat_map(|(id, set)| set.iter().map(|h| (*id, *h))).collect();
self.state = State::Handles { handle, from, start: p, items, began: false };
self.handles = picks.clone();
@@ -1942,7 +1979,7 @@ impl DirectSelectionTool {
self.state = State::Handle { id, si, ai, out, drag };
vec![Action::Begin("Reshape".into())]
};
self.handle_press = Some(HandlePress { handle, at: p, shift: ev.mods.shift, moved: false, picked: picks });
self.handle_press = Some(HandlePress { handle, at: p, shift: ev.mods.shift, moved: false, picked: picks, keeps_picks });
begin
}
/// The release of a press on one of several picked handles: a drag commits, and the picked
@@ -1957,10 +1994,18 @@ impl DirectSelectionTool {
self.handles = BTreeMap::from([(handle.0, BTreeSet::from([handle.1]))]);
vec![Action::Notify(HANDLES_PICKED.into())]
}
/// After the release of a press on a handle that did not drag: a click picks the handle alone,
/// and a Shift-click adds it to the picked handles or takes it away.
/// After the release of a press on a handle: a click picks the handle alone, and a Shift-click
/// adds it to the picked handles or takes it away. A mirroring drag of one of several picked
/// handles leaves them all picked.
fn pick_clicked_handle(&mut self) -> Option<Action> {
let press = self.handle_press.take().filter(|press| !press.moved)?;
let press = self.handle_press.take()?;
if press.moved {
if !press.keeps_picks {
return None;
}
self.handles = press.picked;
return Some(Action::Notify(HANDLES_PICKED.into()));
}
let (id, h) = press.handle;
let mut picked = if press.shift { press.picked } else { BTreeMap::new() };
let set = picked.entry(id).or_default();
+7
View File
@@ -6,6 +6,7 @@
//! and journal entry. One-shot `Exec` actions run immediately. This makes every gesture replayable
//! by the control channel and MCP, and keeps tools testable without a UI.
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
pub mod addons;
pub mod bbox;
@@ -278,6 +279,12 @@ pub trait Tool: Send {
fn hover_object(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Option<NodeId> {
None
}
/// Does a press at `p` with Cmd/Ctrl and `mods` held stay with the tool, instead of going to
/// the selection tool the session lends for Cmd/Ctrl? Direct Selection keeps a press on a shown
/// direction handle, where Cmd/Ctrl mirrors the opposite handle.
fn keeps_cmd_press(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> bool {
false
}
/// What the Info panel shows for the tool as it is now: the drag in progress (a move of the
/// selection, a gradient vector, a handle the Pen pulls out, a Scale, Rotate, Reflect or Shear
/// tool drag), or the Paintbrush's brush. None for a tool with nothing of its own to show.
+1
View File
@@ -46,6 +46,7 @@
//! it, so each enclosed outline is fitted once. An area that holds a transparent pixel or a color
//! left out stays a hole.
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
mod centerline;
mod contour;
+7 -4
View File
@@ -11,7 +11,7 @@ use craft::ui::docking::IconGroupSeparator;
use craft::ui::list::{CommandHighlight, ThumbRows};
use craft::ui::menu::{MenuTitleLook, MenuTitlePad};
use craft::ui::patterns::form_dialogs::PresetCardLook;
use craft::ui::runtime::env::{AltCodeKeys, RootEnv, Scale, ScrubDrags, WindowKey};
use craft::ui::runtime::env::{AltCodeKeys, RootEnv, Scale, ScrubDrags, WindowKey, WordsOverride, with_env};
use craft::ui::runtime::frame::{FrameInput, FrameOutput};
use craft::ui::runtime::toast::{self, Toast};
use craft::ui::runtime::windows::WindowHost;
@@ -771,7 +771,7 @@ impl VectorcraftApp {
let mut control_bar_place = chrome::control_bar_place(&self.ui);
// PLAN: assumed `chrome::window_title(&VectorcraftApp) -> String` (shell-01 A1 names the call, no row gives its signature; shell-w9).
let window_title = chrome::window_title(self);
let shown = AppShell::new(WindowKey::main())
let shell = AppShell::new(WindowKey::main())
.title_bar_if(true, |_| None, chrome::app_bar)
.options_bar(
self.ui.control_bar,
@@ -801,8 +801,11 @@ impl VectorcraftApp {
.body(|ui, cx, app: &mut VectorcraftApp| {
panel_docking::show(app, ui, cx.shell().is_some_and(|shell| shell.panels_hidden()));
crate::place::window_files(app, ui);
})
.show(ui, self);
});
// The shell shows the window's dialogs under these words. Temporary: removed once the craft-libs pin includes
// storytold/craft-libs#4891 (`dialogs::print::title_words`).
let words = dialogs::print::title_words(self).map(WordsOverride::Overlay);
let shown = with_env(ui, |env| env.words = words, |ui| shell.show(ui, self));
chrome::set_control_bar_place(&mut self.ui, control_bar_place);
if shown.screen_mode != given {
self.ui.follow_screen_mode(shown.screen_mode);
+22 -5
View File
@@ -1,12 +1,13 @@
use craft::behavior::{ColumnWidth, IconId};
use craft::i18n::WordSet as _;
use craft::ui::buttons::{Link, LinkLook};
use craft::ui::contract::{Bind, Gap, Pad, Props as _, Show as _, ShowContainer as _, clicked};
use craft::ui::display::Text;
use craft::ui::layout::CellAlign;
use craft::ui::layout_components::{Grid, Stack};
use craft::ui::runtime::env::{Env, Overrides, with_env};
use craft::ui::runtime::env::{Env, Overrides, WordRows, WordsOverride, with_env};
use craft::ui::sections::Section;
use craft::ui::shell::{RecentFile, StartAction, StartLayout, StartLink, StartPlace, StartScreen, Template};
use craft::ui::shell::{RecentFile, ShellWords, StartAction, StartLayout, StartLink, StartPlace, StartScreen, Template};
use craft::ui::style::{SurfaceKind, TypeRole};
use super::{Ui, VectorcraftApp, json};
@@ -45,9 +46,14 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
}
let mut pressed = None;
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect).layout(egui::Layout::top_down(egui::Align::Min)));
// Production's community links read in the accent alone, with no underline.
let plain_links = |overrides: &mut Overrides| {
let words = recent_words(app.ui_language());
// Production's community links read in the accent alone, with no underline, and the recent files are headed
// "Recent Files".
let set_env = |overrides: &mut Overrides| {
overrides.values.set(LinkLook::Plain);
if let Some(words) = words {
overrides.words = Some(WordsOverride::Overlay(words));
}
};
// Learn follows the presets, which stand right under New and Open as in production 0.24.1.
let start = StartScreen::new(Bind::bound(&mut app.ui.home_view), Bind::bound(&mut app.ui.home_sort), &recent)
@@ -62,7 +68,7 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
.links(&links)
.links_title(tl!("Community"))
.section(StartPlace::AfterSections, |ui, _| learn(ui, &mut pressed));
let out = with_env(&mut child, plain_links, |ui| start.show(ui));
let out = with_env(&mut child, set_env, |ui| start.show(ui));
for action in out.actions {
run_action(app, action);
}
@@ -73,6 +79,17 @@ pub(super) fn home(app: &mut VectorcraftApp, ui: &mut Ui, rect: egui::Rect) {
}
}
/// VectorCraft's heading for the Home screen's recent files, "Recent Files", over the framework's "Recent". Outside
/// English, a language whose catalog does not translate it keeps the framework's translation.
// Workaround for craft-libs#4890: once the craft-libs pin includes it, the start screen's `recent_title` heads the
// list, and this word row is removed.
fn recent_words(lang: crate::i18n::Lang) -> Option<WordRows> {
const ENGLISH: &str = "Recent Files";
let shown = crate::i18n::tr(lang, ENGLISH);
let word = ShellWords::word("startScreen.recent")?;
(lang == crate::i18n::Lang::EN || shown != ENGLISH).then(|| WordRows::new().row(word, shown))
}
/// What the start screen's user did. A command that fails says why in the status bar (#6160).
fn run_action(app: &mut VectorcraftApp, action: StartAction) {
fn run(app: &mut VectorcraftApp, id: &str, params: serde_json::Value) {
+460 -26
View File
@@ -8,15 +8,15 @@ use std::hash::{Hash, Hasher};
use std::sync::{Arc, Weak};
use craft::behavior::Input;
use craft::behavior::Metrics;
use craft::behavior::{CanvasView, Metrics};
use craft::draw::ui::{
AnchorsShown, BezierOverlay, BezierTool, EditPath, EditSubpath, HandleStyle, HandlesShown, Knot, KnotRef, PathOptionsSettings, PathSelection,
AnchorsShown, EditPath, EditSubpath, HandleSide, HandleStyle, HandlesShown, Knot, KnotRef, MAX_ANCHORS, PathOptionsSettings, PathSelection,
SegmentMark,
};
use craft::theme::Srgba;
use craft::ui::canvas::{CanvasSpace, canvas_space};
use craft::ui::canvas_controls::{HoverOutline, HoverShape, SelectionOutline};
use craft::ui::contract::{Access, Bind, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _};
use craft::ui::canvas_controls::{HoverOutline, HoverShape, SelectionOutline, path_runs};
use craft::ui::contract::{Access, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _, Styled as _};
use craft::ui::style::{ComponentStyle, DataColor, StyleCx};
use egui::{Color32, Rect, Response, Shape, Stroke, StrokeKind, vec2};
use vectorcraft_doc::{Document, NodeId, NodeKind};
@@ -622,6 +622,457 @@ impl Component for SelectionDots<'_> {
}
}
// TEMPORARY: craft-libs#4900 and craft-libs#4928. `BezierOverlay` at the pinned craft-libs lays out its scene and
// flattens and strokes every outline on every paint, and the canvas cloned the paths for it each frame, so a large
// selection stalled every frame. `AnchorMarks` draws what the overlay draws under `BezierTool::Anchors`, from the
// kept marks, and keeps it as one mesh while the marks, the view and the look stay the same. When the craft-libs pin
// includes both pull requests, remove `AnchorMarks` and this section and go back to
// `BezierOverlay::display(...).revision(marks.key)`.
/// The marks' look, resolved from the theme: the colors and widths `BezierOverlay` paints anchors, handles and
/// outlines with.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
struct AnchorMarksStyle {
#[style(metrics)]
metrics: Metrics,
/// The outline of a path without a color of its own, and the fill of a selected anchor.
line: craft::ui::style::StyleColor,
/// The fill of a hollow anchor and of a handle's end, per state.
fill: craft::ui::style::Stateful<craft::ui::style::StyleColor>,
/// The edge of an anchor or a handle's end, for a path without a color of its own.
edge: craft::ui::style::StyleColor,
/// An anchor's side.
anchor: f32,
/// A handle end's side with Large handles.
large: f32,
thin: f32,
medium: f32,
thick: f32,
/// How far outside the canvas an anchor or a handle's end is still drawn.
reach: f32,
}
/// [`AnchorMarksStyle`] for one paint, with the fill resolved: what the kept mesh is built from besides the marks.
#[derive(Clone, Copy, Debug, PartialEq)]
struct MarkLook {
line: Color32,
fill: Color32,
edge: Color32,
anchor: f32,
large: f32,
thin: f32,
medium: f32,
thick: f32,
reach: f32,
}
/// Everything the kept mesh of the anchor marks depends on.
#[derive(Clone, Copy, Debug, PartialEq)]
struct MeshKey {
/// [`marks_key`] of the marks.
marks: u64,
view: CanvasView,
rect: Rect,
clip: Rect,
pixels_per_point: f32,
options: egui::epaint::TessellationOptions,
look: MarkLook,
}
/// The anchor marks tessellated as one mesh, and what they were tessellated from.
pub(crate) struct KeptMesh {
key: MeshKey,
mesh: Arc<egui::Mesh>,
}
/// One set of anchors as `BezierOverlay` took it: the paths, which anchors are selected and how they show.
struct MarkSet<'a> {
paths: &'a [EditPath],
selection: &'a PathSelection,
handles: HandlesShown,
shown: AnchorsShown,
segment_mark: SegmentMark,
options: &'a PathOptionsSettings,
}
/// The two sets the canvas shows: the paths whose handles the tools drag, then the paths whose anchors show selected
/// without handles.
fn mark_sets(anchors: &Anchors) -> [MarkSet<'_>; 2] {
[
MarkSet {
paths: &anchors.paths,
selection: &anchors.selection,
handles: anchors.handles,
shown: anchors.shown,
segment_mark: anchors.segment_mark,
options: &anchors.options,
},
MarkSet {
paths: &anchors.plain,
selection: &anchors.plain_selection,
handles: HandlesShown::OneAnchor,
shown: anchors.shown,
segment_mark: SegmentMark::default(),
options: &anchors.options,
},
]
}
/// The anchors, handles and outlines of the selection, painted over the canvas as one kept mesh: no pointer, key or
/// accessibility node, as `BezierOverlay` under `BezierTool::Anchors` has none.
#[derive(craft::ui::contract::Component, craft::ui::contract::Props)]
#[component(canvas_control, content_painter)]
struct AnchorMarks<'a> {
#[common]
common: Common,
anchors: &'a Anchors,
/// [`marks_key`] of `anchors`.
key: u64,
kept: &'a std::cell::RefCell<Option<KeptMesh>>,
}
impl Component for AnchorMarks<'_> {
const ROLE: Role = Role::GRAPHICS_OBJECT;
const ALT_ROLES: &'static [Role] = &[Role::None];
const INPUT: Input = Input::Display;
const PARTS: bool = false;
const STOPS: bool = false;
const OVERLAYS: bool = false;
type Style = AnchorMarksStyle;
type Output = Response;
fn style(cx: &StyleCx<'_>, _: AnchorMarksStyleKey) -> AnchorMarksStyle {
let tokens = cx.tokens;
let handle = cx.handle();
AnchorMarksStyle {
metrics: Metrics::new(),
line: cx.color(tokens.color.overlay.line),
fill: handle.fill,
edge: handle.stroke,
anchor: tokens.size.handle.sm,
large: handle.side,
thin: tokens.stroke.thin,
medium: tokens.stroke.medium,
thick: tokens.stroke.thick,
reach: tokens.size.hit.target,
}
}
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> egui::Vec2 {
egui::Vec2::ZERO
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let Some(space) = canvas_space(&cx.env) else { return };
let style = &cx.style;
let look = MarkLook {
line: style.line.egui(),
fill: cx.resolve(&style.fill).egui(),
edge: style.edge.egui(),
anchor: style.anchor,
large: style.large,
thin: style.thin,
medium: style.medium,
thick: style.thick,
reach: style.reach,
};
let painter = ui.content_painter(cx);
let key = MeshKey {
marks: self.key,
view: space.view,
rect: cx.rect,
clip: painter.painter.clip_rect(),
pixels_per_point: painter.pixels_per_point(),
options: painter.painter.ctx().tessellation_options(|options| *options),
look,
};
let shapes = || {
let mut shapes = Vec::new();
for set in mark_sets(self.anchors) {
mark_shapes(&mut shapes, &set, &space.view, cx.rect, &look);
}
shapes
};
#[cfg(test)]
if tests::RAW_MARKS.with(std::cell::Cell::get) {
painter.painter.extend(shapes());
return;
}
let mut kept = self.kept.borrow_mut();
let mesh = match kept.as_ref().filter(|kept| kept.key == key) {
Some(kept) => Arc::clone(&kept.mesh),
None => {
let shapes = shapes();
let mesh = Arc::new(tessellate(shapes, &key));
*kept = Some(KeptMesh { key, mesh: Arc::clone(&mesh) });
mesh
}
};
if !mesh.is_empty() {
painter.painter.add(Shape::Mesh(mesh));
}
}
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
access.role(Role::None);
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
/// `shapes` as one mesh, tessellated as the frame would tessellate them, except that a small filled circle is a
/// polygon rather than a disc from the font atlas, so a later change to the atlas cannot leave the mesh wrong.
fn tessellate(shapes: Vec<Shape>, key: &MeshKey) -> egui::Mesh {
#[cfg(test)]
tests::MESHES_BUILT.with(|built| built.set(built.get() + 1));
let mut tessellator = egui::epaint::Tessellator::new(key.pixels_per_point, key.options, [1, 1], Vec::new());
tessellator.set_clip_rect(key.clip);
let mut mesh = egui::Mesh::default();
for shape in shapes {
tessellator.tessellate_shape(shape, &mut mesh);
}
mesh
}
/// Shows the selection's anchors, handles and outlines from `marks`.
fn paint_anchor_marks(ui: &mut egui::Ui, rect: Rect, marks: &SelectionMarks) {
let anchors = &marks.anchors;
if anchors.paths.is_empty() && anchors.plain.is_empty() {
return;
}
#[cfg(test)]
if tests::OVERLAY_MARKS.with(std::cell::Cell::get) {
tests::paint_with_overlay(ui, rect, anchors);
return;
}
AnchorMarks { common: Common::new(), anchors, key: marks.key, kept: &marks.mesh }.label("Anchors").show_at(ui, rect);
}
/// The fill of an anchor or a handle's end.
#[derive(Clone, Copy)]
enum MarkFill {
/// The look's fill.
Look,
/// The path's color, or the look's line without one: a selected anchor.
Path,
}
/// The egui shapes `BezierOverlay` paints for `set` under `BezierTool::Anchors`, in its order: every outline, the
/// selected segment, then the anchors and handles near `rect`, then the handles of the other paths' selected anchors.
fn mark_shapes(out: &mut Vec<Shape>, set: &MarkSet<'_>, view: &CanvasView, rect: Rect, look: &MarkLook) {
let options = set.options;
let option_color = options.color.map(|[r, g, b]| Color32::from(Srgba::rgb(f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0)));
let path_color = |path: &EditPath| path.color.map(Color32::from);
let anchor_side = options.anchor_size.unwrap_or(look.anchor);
let handle_side = if options.handles == HandleStyle::Large { look.large } else { look.anchor };
let circles = set.shown == AnchorsShown::Curvature;
let line = |out: &mut Vec<Shape>, points: Vec<egui::Pos2>, closed: bool, segment: bool, color: Option<Color32>| {
let named = if segment { look.thick } else { look.medium };
let ink = color.unwrap_or(look.line);
match options.thickness {
Some(thickness) => {
if segment {
stroke_line(out, points.clone(), closed, Stroke::new(thickness, ink));
stroke_line(out, points, closed, Stroke::new(named, ink));
} else {
stroke_line(out, points, closed, Stroke::new(thickness, ink));
}
}
None => stroke_line(out, points, closed, Stroke::new(named, ink)),
}
};
for path in set.paths {
let color = path.color.map(Color32::from).or(option_color);
for sub in &path.subpaths {
for (points, closed) in path_runs(view, &sub.bez_path()) {
line(out, points, closed, false, color);
}
}
if set.segment_mark == SegmentMark::Line
&& let Some(s) = set.selection.segment.filter(|_| set.selection.path == Some(path.key))
&& let Some(curve) = path.subpaths.get(s.subpath).and_then(|sub| sub.segment(s.knot))
{
let mut segment = BezPath::new();
segment.move_to(curve.p0);
segment.curve_to(curve.p1, curve.p2, curve.p3);
for (points, closed) in path_runs(view, &segment) {
line(out, points, closed, true, color);
}
}
}
let total: usize = set.paths.iter().map(EditPath::anchor_count).sum();
if set.shown == AnchorsShown::Hidden || total > MAX_ANCHORS {
return;
}
let mark = |out: &mut Vec<Shape>, at: egui::Pos2, side: f32, circle: bool, fill: MarkFill, color: Option<Color32>| {
let fill = match fill {
MarkFill::Look => look.fill,
MarkFill::Path => color.unwrap_or(look.line),
};
let edge = Stroke::new(look.thin, color.unwrap_or(look.edge));
if circle {
let radius = side / 2.0;
out.push(Shape::Circle(egui::epaint::CircleShape { center: at, radius, fill, stroke: Stroke::NONE }));
out.push(Shape::Circle(egui::epaint::CircleShape { center: at, radius, fill: Color32::TRANSPARENT, stroke: edge }));
} else {
let square = Rect::from_center_size(at, egui::Vec2::splat(side));
out.push(Shape::Rect(egui::epaint::RectShape::new(square, 0.0, fill, Stroke::NONE, StrokeKind::Inside)));
out.push(Shape::Rect(egui::epaint::RectShape::new(square, 0.0, Color32::TRANSPARENT, edge, StrokeKind::Inside)));
}
};
// A direction handle: its line from the anchor, then its end.
let handle = |out: &mut Vec<Shape>, path: &EditPath, knot: KnotRef, end: egui::Pos2| {
let color = path_color(path);
if let Some(knot) = path.knot(knot) {
out.push(Shape::line(vec![view.to_screen(knot.anchor), end], Stroke::new(look.thin, color.unwrap_or(look.line))));
}
mark(out, end, handle_side, true, MarkFill::Look, color);
};
let selected = Selected::of(set.selection);
let near = rect.expand(look.reach);
let shown = if circles { Vec::new() } else { shown_handles(set.paths, set.selection, &selected, set.handles, view) };
let mut handles = shown.iter().peekable();
for (at, path) in set.paths.iter().enumerate() {
for knot_ref in path.knot_refs() {
let Some(knot) = path.knot(knot_ref) else { continue };
let anchor = view.to_screen(knot.anchor);
if near.contains(anchor) && set.selection.shows(path.key, knot_ref.subpath) {
let fill = if selected.draws_selected(path.key, knot_ref) { MarkFill::Path } else { MarkFill::Look };
mark(out, anchor, anchor_side, circles, fill, path_color(path));
}
while let Some(&(_, _, end)) = handles.next_if(|(p, k, _)| *p == at && *k == knot_ref) {
if near.contains(end) {
handle(out, path, knot_ref, end);
}
}
}
}
if circles || set.handles == HandlesShown::All {
return;
}
// The handles of anchors selected in paths other than the edited one.
let edited = set.selection.path.map_or(0, |_| set.selection.anchors.len());
for path in set.paths {
if set.selection.path == Some(path.key) || !selected.listed.contains(&path.key) {
continue;
}
let own = PathSelection::new(Some(path.key), Vec::new(), None);
let listed = |key: u64, knot: KnotRef| selected.others.contains(&(key, knot));
for (_, knot, end) in handles_of(std::slice::from_ref(path), &own, listed, selected.others_len + edited, set.handles, view) {
handle(out, path, knot, end);
}
}
}
/// Strokes the run `points`, closed or open, on its centre line.
fn stroke_line(out: &mut Vec<Shape>, points: Vec<egui::Pos2>, closed: bool, stroke: Stroke) {
if closed {
if stroke.is_empty() {
return;
}
let mut line = egui::epaint::PathStroke::from(stroke);
line.kind = StrokeKind::Middle;
out.push(Shape::closed_line(points, line));
} else {
out.push(Shape::line(points, stroke));
}
}
/// The anchors a [`PathSelection`] selects, gathered into sets once.
struct Selected {
path: Option<u64>,
anchors: std::collections::HashSet<KnotRef>,
others: std::collections::HashSet<(u64, KnotRef)>,
listed: std::collections::HashSet<u64>,
others_len: usize,
}
impl Selected {
fn of(sel: &PathSelection) -> Self {
Self {
path: sel.path,
anchors: sel.anchors.iter().copied().collect(),
others: sel.others.iter().flat_map(|(key, knots)| knots.iter().map(|knot| (*key, *knot))).collect(),
listed: sel.others.iter().map(|(key, _)| *key).collect(),
others_len: sel.others.iter().map(|(_, knots)| knots.len()).sum(),
}
}
/// Whether `knot` of `path` is a selected anchor of the edited path.
fn has_anchor(&self, path: u64, knot: KnotRef) -> bool {
self.path == Some(path) && self.anchors.contains(&knot)
}
/// Whether `knot` of `path` draws selected.
fn draws_selected(&self, path: u64, knot: KnotRef) -> bool {
self.has_anchor(path, knot) || self.others.contains(&(path, knot))
}
}
/// The handles that show for `sel`, in path order, in then out: each path's index, the knot and the end on screen.
fn shown_handles(
paths: &[EditPath],
sel: &PathSelection,
selected: &Selected,
shown: HandlesShown,
view: &CanvasView,
) -> Vec<(usize, KnotRef, egui::Pos2)> {
handles_of(paths, sel, |path, knot| selected.has_anchor(path, knot), sel.selected_len(), shown, view)
}
/// The handles that show, with `has_anchor` answering whether a knot is a selected anchor and `count` the number of
/// selected anchors `HandlesShown::OneAnchor` counts. A retracted handle and the handles of a subpath the selection
/// does not show are left out.
fn handles_of(
paths: &[EditPath],
sel: &PathSelection,
has_anchor: impl Fn(u64, KnotRef) -> bool,
count: usize,
shown: HandlesShown,
view: &CanvasView,
) -> Vec<(usize, KnotRef, egui::Pos2)> {
let mut out = Vec::new();
for (index, path) in paths.iter().enumerate() {
let segment_ends = sel.segment.filter(|_| sel.path == Some(path.key)).and_then(|s| {
let (a, b) = path.subpaths.get(s.subpath)?.segment_ends(s.knot)?;
Some((KnotRef::new(s.subpath, a), KnotRef::new(s.subpath, b)))
});
for knot_ref in path.knot_refs().filter(|k| sel.shows(path.key, k.subpath)) {
let Some(knot) = path.knot(knot_ref) else { continue };
for side in [HandleSide::In, HandleSide::Out] {
let of_selection = || {
has_anchor(path.key, knot_ref)
|| next_to_selected(path, &has_anchor, knot_ref, side)
|| segment_ends.is_some_and(|(a, b)| (side == HandleSide::Out && a == knot_ref) || (side == HandleSide::In && b == knot_ref))
};
let wanted = match shown {
HandlesShown::All => true,
HandlesShown::OneAnchor => count == 1 && of_selection(),
_ => of_selection(),
};
if wanted && !knot.retracted(side) {
out.push((index, knot_ref, view.to_screen(knot.handle(side))));
}
}
}
}
out
}
/// Whether `side` of `knot` is the handle of a segment that a selected anchor ends: the previous anchor's out handle
/// or the next anchor's in handle, across a closed subpath's seam too.
fn next_to_selected(path: &EditPath, has_anchor: &impl Fn(u64, KnotRef) -> bool, knot: KnotRef, side: HandleSide) -> bool {
let Some(sub) = path.subpaths.get(knot.subpath) else { return false };
let count = sub.knots.len();
if side == HandleSide::Out {
return sub.segment_ends(knot.knot).is_some_and(|(_, next)| has_anchor(path.key, KnotRef::new(knot.subpath, next)));
}
let previous = (knot.knot + count.saturating_sub(1)) % count.max(1);
sub.segment_ends(previous).is_some_and(|(previous, _)| has_anchor(path.key, KnotRef::new(knot.subpath, previous)))
}
/// Whether the active tool draws its own points over the paths: the Curvature tool while it has a draft.
fn tool_draws_points(app: &mut VectorcraftApp) -> bool {
if app.session.tool_id() != "curvature" {
@@ -675,27 +1126,7 @@ pub(super) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, space: &CanvasSp
}
outline.show_at(ui, rect);
}
let anchors = &marks.anchors;
if !anchors.paths.is_empty() {
let mut paths = anchors.paths.clone();
// The marks only show the selection: the tools make the edits.
let _ = BezierOverlay::new("Anchors", Bind::bound(&mut paths), &anchors.selection)
.tool(BezierTool::Anchors)
.handles(anchors.handles)
.anchors(anchors.shown)
.segment_mark(anchors.segment_mark)
.path_options(&anchors.options)
.show_at(ui, rect);
}
if !anchors.plain.is_empty() {
let mut paths = anchors.plain.clone();
let _ = BezierOverlay::new("Selected anchors", Bind::bound(&mut paths), &anchors.plain_selection)
.tool(BezierTool::Anchors)
.handles(HandlesShown::OneAnchor)
.anchors(anchors.shown)
.path_options(&anchors.options)
.show_at(ui, rect);
}
paint_anchor_marks(ui, rect, &marks);
let dots = &marks.dots;
if !(dots.centers.is_empty() && dots.origins.is_empty() && dots.key_anchor.is_none()) {
SelectionDots { common: Common::new(), dots }.label("Selection dots").show_at(ui, rect);
@@ -722,6 +1153,8 @@ pub(crate) struct SelectionMarks {
outlines: Vec<Outlined>,
anchors: Anchors,
dots: Dots,
/// The anchor marks as one mesh, from the last paint ([`AnchorMarks`]).
mesh: std::cell::RefCell<Option<KeptMesh>>,
}
impl SelectionMarks {
@@ -738,6 +1171,7 @@ impl SelectionMarks {
outlines: outlines(app, st),
anchors: anchors(app, st, tool, tool_points),
dots: dots(app, st),
mesh: std::cell::RefCell::new(None),
}
}
@@ -803,4 +1237,4 @@ fn view_key(app: &VectorcraftApp, st: &DocState, tool: &str, tool_points: bool)
}
#[cfg(test)]
mod tests;
pub(super) mod tests;
@@ -942,6 +942,217 @@ fn grouping_selected_anchors_by_path_compares_each_path_a_bounded_number_of_time
assert!(compared.get() < 2 * 2001, "{} comparisons for 2,001 entries", compared.get());
}
thread_local! {
/// Whether `show` draws the anchor marks with `BezierOverlay`, as it did before [`AnchorMarks`].
pub(super) static OVERLAY_MARKS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// Whether [`AnchorMarks`] paints its shapes one by one instead of as a mesh.
pub(in crate::canvas) static RAW_MARKS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
/// How many meshes [`AnchorMarks`] tessellated.
pub(super) static MESHES_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The anchor marks as `show` drew them before [`AnchorMarks`]: two `BezierOverlay`s under `BezierTool::Anchors`.
pub(super) fn paint_with_overlay(ui: &mut egui::Ui, rect: Rect, anchors: &Anchors) {
use craft::draw::ui::{BezierOverlay, BezierTool};
use craft::ui::contract::Bind;
if !anchors.paths.is_empty() {
let mut paths = anchors.paths.clone();
let _ = BezierOverlay::new("Anchors", Bind::bound(&mut paths), &anchors.selection)
.tool(BezierTool::Anchors)
.handles(anchors.handles)
.anchors(anchors.shown)
.segment_mark(anchors.segment_mark)
.path_options(&anchors.options)
.show_at(ui, rect);
}
if !anchors.plain.is_empty() {
let mut paths = anchors.plain.clone();
let _ = BezierOverlay::new("Selected anchors", Bind::bound(&mut paths), &anchors.plain_selection)
.tool(BezierTool::Anchors)
.handles(HandlesShown::OneAnchor)
.anchors(anchors.shown)
.path_options(&anchors.options)
.show_at(ui, rect);
}
}
/// One frame of the canvas alone with `events`.
fn canvas_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> egui::FullOutput {
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0));
let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), events, ..Default::default() }, |ui| super::super::show(app, ui));
out.textures_delta.clear();
out
}
/// The shapes a canvas frame paints, with the anchor marks drawn by `BezierOverlay` (`overlay`) or by
/// [`AnchorMarks`] one shape at a time.
fn canvas_shapes(app: &mut VectorcraftApp, ctx: &egui::Context, overlay: bool) -> Vec<egui::Shape> {
OVERLAY_MARKS.with(|on| on.set(overlay));
RAW_MARKS.with(|on| on.set(!overlay));
canvas_frame(app, ctx, vec![]);
let out = canvas_frame(app, ctx, vec![]);
OVERLAY_MARKS.with(|on| on.set(false));
RAW_MARKS.with(|on| on.set(false));
crate::tests::labels::flat_painted_shapes(&out.shapes)
}
/// A canvas app with one curve, the task bar off and every frame drawn on this thread.
fn canvas_app() -> (VectorcraftApp, NodeId) {
let mut app = blank();
app.ui.task_bar = false;
app.canvas.worker_started = true;
let curve = id_of(&app.run("path.create", json!({"d": "M40 40 C60 10 90 10 110 40 S160 70 180 40 L180 90"})).unwrap());
(app, curve)
}
// The anchor marks paint the shapes `BezierOverlay` paints for the same marks: under the Selection tool, Direct
// Selection with a partial selection, a selected segment and the Curvature tool, with handles shown for one anchor or
// for every selected anchor, each handle style, and the Path Options color and thickness on paths without a color.
#[test]
fn the_anchor_marks_paint_what_the_bezier_overlay_paints() {
let (mut app, curve) = scene();
let ctx = crate::testing::ui_context();
let compare = |app: &mut VectorcraftApp, case: &str, change: &dyn Fn(&mut Anchors)| {
canvas_frame(app, &ctx, vec![]);
if let Some(marks) = app.canvas.selection_marks.as_mut() {
change(&mut marks.anchors);
}
let overlay = canvas_shapes(app, &ctx, true);
let marks = canvas_shapes(app, &ctx, false);
assert!(overlay.len() > 20, "{case}: the overlay painted the marks ({} shapes)", overlay.len());
let differs = overlay.iter().zip(&marks).position(|(a, b)| a != b);
assert!(
overlay == marks,
"{case}: {} shapes from the overlay, {} from the marks, first difference at {differs:?}",
overlay.len(),
marks.len()
);
};
let same = |_: &mut Anchors| {};
app.select_tool("selection");
compare(&mut app, "the Selection tool", &same);
for (multiple, style) in [(true, "solid"), (false, "hollow"), (true, "large")] {
app.session.prefs.show_handles_multiple_anchors = multiple;
app.session.prefs.handle_style = style.into();
app.session.prefs.anchor_size = 5;
app.select_tool("directSelection");
app.run("select.anchors", json!({"id": curve.0, "anchors": [[0, 1], [0, 2]], "mode": "set"})).unwrap();
compare(&mut app, &format!("Direct Selection, multiple {multiple}, {style}"), &same);
app.run("select.anchors", json!({"id": curve.0, "anchors": [[0, 2]], "mode": "set"})).unwrap();
compare(&mut app, &format!("one anchor, multiple {multiple}, {style}"), &same);
}
// A segment selected in place keeps the revision, so the kept marks are dropped to build them again.
let pick_segment = |app: &mut VectorcraftApp| {
app.session.active_mut().unwrap().selection.segments.insert(curve, [(0, 1)].into_iter().collect());
app.canvas.selection_marks = None;
};
pick_segment(&mut app);
compare(&mut app, "a selected segment", &|anchors| assert!(anchors.selection.segment.is_some(), "a segment is selected"));
app.session.active_mut().unwrap().selection.segments.clear();
app.run("select.all", json!({})).unwrap();
compare(&mut app, "every handle", &|anchors| anchors.handles = HandlesShown::All);
let options = |anchors: &mut Anchors| {
anchors.options.color = Some([10, 200, 30]);
anchors.options.thickness = Some(3.0);
for path in anchors.paths.iter_mut().chain(&mut anchors.plain) {
path.color = None;
}
};
compare(&mut app, "the Path Options color and thickness", &options);
app.run("select.set", json!({"ids": [curve.0]})).unwrap();
app.select_tool("directSelection");
pick_segment(&mut app);
compare(&mut app, "a selected segment with a thickness", &options);
compare(&mut app, "paths without a color", &|anchors| {
for path in anchors.paths.iter_mut().chain(&mut anchors.plain) {
path.color = None;
}
});
app.session.active_mut().unwrap().selection.segments.clear();
app.run("select.set", json!({"ids": [curve.0]})).unwrap();
app.select_tool("curvature");
compare(&mut app, "the Curvature tool", &same);
}
// The canvas tessellates the anchor marks once and paints the kept mesh while nothing they show changes: frames that
// change nothing tessellate none, and a new selection, a scroll of the view and a new zoom each tessellate them once.
#[test]
fn an_idle_frame_tessellates_no_anchor_marks() {
let (mut app, curve) = canvas_app();
app.select_tool("directSelection");
app.run("select.set", json!({"ids": [curve.0]})).unwrap();
let ctx = crate::testing::ui_context();
let frames = |app: &mut VectorcraftApp, n: usize| {
let before = MESHES_BUILT.with(std::cell::Cell::get);
for _ in 0..n {
canvas_frame(app, &ctx, vec![]);
}
MESHES_BUILT.with(std::cell::Cell::get) - before
};
assert_eq!(frames(&mut app, 3), 1, "the first frame tessellates the marks");
assert_eq!(frames(&mut app, 10), 0, "frames that change nothing");
app.run("select.anchors", json!({"id": curve.0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
assert_eq!(frames(&mut app, 5), 1, "a new selection");
app.view_mut().unwrap().center.x += 40.0;
assert_eq!(frames(&mut app, 5), 1, "a scroll");
app.view_mut().unwrap().zoom *= 2.0;
assert_eq!(frames(&mut app, 5), 1, "a new zoom");
app.run("select.none", json!({})).unwrap();
assert_eq!(frames(&mut app, 5), 0, "nothing selected, nothing to tessellate");
}
/// What a press-drag and Tab presses did: the curve's bounds, its selected anchors, and the focused accessibility node
/// after each Tab.
type Reached = (vectorcraft_geom::Rect, Vec<(usize, usize)>, Vec<Option<String>>);
/// What the canvas does with a press-drag from the curve's third anchor under `tool`, then Tab presses.
fn press_and_tab(tool: &str, overlay: bool) -> Reached {
OVERLAY_MARKS.with(|on| on.set(overlay));
let (mut app, curve) = canvas_app();
app.select_tool(tool);
app.run("select.set", json!({"ids": [curve.0]})).unwrap();
let ctx = crate::testing::ui_context();
ctx.enable_accesskit();
canvas_frame(&mut app, &ctx, vec![]);
let xf = app.canvas_view().unwrap();
// The curve's third anchor, and a drag away from it.
let (from, to) = (xf.to_screen(Point::new(110.0, 40.0)), xf.to_screen(Point::new(130.0, 60.0)));
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
canvas_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from)]);
canvas_frame(&mut app, &ctx, vec![button(from, true)]);
for i in 1..=5 {
canvas_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(from + (to - from) * (i as f32 / 5.0))]);
}
canvas_frame(&mut app, &ctx, vec![button(to, false)]);
let tab = egui::Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
let focused = (0..4)
.map(|_| {
let out = canvas_frame(&mut app, &ctx, vec![tab.clone()]);
let update = out.platform_output.accesskit_update.as_ref().expect("an accessibility tree");
update.nodes.iter().find(|(id, _)| *id == update.focus).and_then(|(_, node)| node.label().map(str::to_owned))
})
.collect();
OVERLAY_MARKS.with(|on| on.set(false));
let st = app.session.active().unwrap();
let bounds = st.doc.bounds_of(&[curve], false).unwrap();
let mut chosen: Vec<(usize, usize)> = st.selection.partial(curve).map(|set| set.iter().copied().collect()).unwrap_or_default();
chosen.sort_unstable();
(bounds, chosen, focused)
}
// A press on a shown anchor reaches the tool and Tab from the canvas goes where it went with `BezierOverlay`: the
// Selection tool drags the whole path, Direct Selection drags the anchor, and Tab keeps the focus on the canvas.
#[test]
fn a_press_on_an_anchor_and_tab_reach_what_they_reached_with_the_overlay() {
for tool in ["selection", "directSelection"] {
let overlay = press_and_tab(tool, true);
let marks = press_and_tab(tool, false);
assert_eq!(marks, overlay, "{tool}");
let (bounds, ..) = &marks;
assert!((bounds.x0 - 40.0).abs() > 1.0 || (bounds.x1 - 180.0).abs() > 1.0, "{tool}: the drag edited the curve: {bounds:?}");
}
}
thread_local! {
/// How many times the canvas built the selection's marks ([`SelectionMarks::build`]).
pub(super) static MARKS_BUILT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
+3 -1
View File
@@ -267,10 +267,12 @@ fn the_shown_tool_follows_the_pointer_in_the_frame_it_moves() {
}
/// One headless canvas frame with `events` → the points it paints: the centres of circles and rectangles and the
/// points of lines and paths.
/// points of lines and paths. The selection's anchor marks paint as the shapes their mesh is made of.
fn painted_points(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Vec<Pos2> {
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0))), events, ..Default::default() };
super::selection::tests::RAW_MARKS.with(|on| on.set(true));
let mut out = ctx.run_ui(raw, |ui| show(app, ui));
super::selection::tests::RAW_MARKS.with(|on| on.set(false));
out.textures_delta.clear();
let mut points = vec![];
for shape in flat_shapes(out.shapes) {
+37
View File
@@ -45,3 +45,40 @@ fn every_cursor_icon_the_app_names_is_in_its_set() {
}
}
}
/// Painted cursors use the SVG's alpha as ink. Drawing the vent in white makes it solid ink.
#[test]
fn the_painted_pen_nibs_keep_their_breather_holes() {
use craft::ui::primitives::{painted_image, register_app_icons};
use craft::ui::runtime::env::Env;
use craft::ui::style::rgba_color;
register_app_icons(&crate::icons::APP_ICONS);
register_app_icons(&CURSOR_ICONS);
crate::testing::ui_context()
.run_ui(Default::default(), |ui| {
let env = Env::of(ui);
let tokens = env.tokens.tokens();
let ink = rgba_color(tokens.color.overlay.cursor);
let is_ink = |px: &[u8]| px[3] >= 240 && [ink.r(), ink.g(), ink.b()].iter().zip(px).all(|(want, got)| want.abs_diff(*got) <= 8);
let scale = 4.0;
let from_art_units = tokens.size.icon.md * scale / 24.0;
for c in [Cursor::Pen, Cursor::PenConvert, Cursor::PenJoin, Cursor::Curvature] {
let cb::Cursor::Painted(painted @ PaintedCursor::Tool { hotspot, .. }) = tool_cursor(c) else {
panic!("{c:?} must have painted tool art");
};
let image = painted_image(&env, &painted, scale).expect("the cursor fits in its bitmap");
let [hx, hy] = image.hotspot.map(f32::from);
let pixel = |x: f32, y: f32| {
let x = (hx + (x - hotspot.x) * from_art_units).round() as usize;
let y = (hy + (y - hotspot.y) * from_art_units).round() as usize;
let i = (y * usize::from(image.size[0]) + x) * 4;
&image.rgba[i..i + 4]
};
assert!(is_ink(pixel(9.5, 13.2)), "{c:?}: the nib body is ink");
assert!(!is_ink(pixel(6.62, 12.86)), "{c:?}: the vent must break up the ink");
}
})
.textures_delta
.clear();
}
+10 -1
View File
@@ -33,7 +33,7 @@ use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamKi
use craft::ui::patterns::presets::{NamedPresetEvent, PresetError, PresetRow};
use craft::ui::pickers::{Anchor9, ReferencePoint, ReferencePointLook};
use craft::ui::primitives::IconSpec;
use craft::ui::runtime::env::{LengthUnits, UnitKind};
use craft::ui::runtime::env::{LengthUnits, UnitKind, WordRows};
use craft::ui::shell::WindowDialogs;
use craft::ui::text::{LinkMode, LinkedFields, NumberField, SelectableText};
use serde_json::{Map, Value, json};
@@ -518,6 +518,15 @@ pub(super) fn settings(fields: &DialogFields) -> Value {
Value::Object(nested(p))
}
/// The words that title File › Print "Print" while the Print dialog is open in Print mode, for the window's shell to
/// show its dialogs under. The framework titles a dialog in sections "Print Settings". Temporary: this is removed, and
/// the dialog is titled with `HostedPrint::title`, once the craft-libs pin includes storytold/craft-libs#4891.
pub(crate) fn title_words(app: &VectorcraftApp) -> Option<WordRows> {
app.print_dialog.open.as_ref().filter(|open| open.mode == PrintMode::Print)?;
let title = craft::i18n::Word::keyed("printDialog.title", "Print Settings");
Some(WordRows::new().row(title, tl!("Print")))
}
/// The work of the open dialog, once per frame: the printer list, Setup…, the preview, the placement the preview was
/// dragged to, the presets and OK.
pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
+36
View File
@@ -143,6 +143,42 @@ fn pages(pdf: &[u8]) -> usize {
vectorcraft_pdf::info(pdf, None).unwrap().pages.len()
}
/// The texts the whole window paints, with where each is drawn, once the open dialog has faded in (each frame is a
/// quarter second on).
fn window_texts(app: &mut VectorcraftApp) -> Vec<(String, egui::Rect)> {
let ctx = ctx(app);
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 1000.0));
let mut texts = vec![];
for k in 0..4 {
let raw = egui::RawInput { screen_rect: Some(screen), time: Some(f64::from(k) * 0.25), ..Default::default() };
let out = crate::testing::app_frame(app, &ctx, raw);
texts = crate::tests_labels::text_shapes(&out)
.into_iter()
.map(|(t, transform)| (t.galley.text().to_string(), transform * t.galley.rect.translate(t.pos.to_vec2())))
.collect();
}
texts
}
#[test]
fn the_print_dialog_is_titled_print_and_the_preset_editor_keeps_its_title() {
let (mut printing, _) = app();
printing.run("file.print", json!({})).unwrap();
let texts = window_texts(&mut printing);
let painted = |texts: &[(String, egui::Rect)], text: &str| texts.iter().filter(|(t, _)| t == text).map(|(_, r)| *r).collect::<Vec<_>>();
assert!(painted(&texts, "Print Settings").is_empty(), "the Print dialog is not titled Print Settings: {texts:?}");
let preset_row = painted(&texts, "Print Preset");
let preset_row = preset_row.first().expect("the Print Preset row is shown");
// The title sits above the dialog's first row; the Print button sits below it.
assert!(painted(&texts, "Print").iter().any(|title| title.bottom() <= preset_row.top()), "the dialog is titled Print: {texts:?}");
// The preset editor keeps the framework's title.
let (mut editing, _) = app();
editing.run("ui.printPresetDialog", json!({"preset": vectorcraft_engine::cmd::printpresets::DEFAULT_PRESET})).unwrap();
let texts = window_texts(&mut editing);
assert!(!painted(&texts, "Print Settings").is_empty(), "the preset editor is titled Print Settings: {texts:?}");
}
#[test]
fn print_sends_every_page_to_the_chosen_printer_and_keeps_the_settings() {
let (mut app, jobs) = app();
+89 -1
View File
@@ -40,12 +40,26 @@ pub(crate) fn panel_body(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) {
{
// These panels lay out forms. Collection panels own their scrolling viewport
// and reserve their own footer outside it.
Stack::new().id_salt(id).fill().scroll(Scroll::vertical()).show(ui, |ui, _| memoized(app, ui, id, icon_panel_body));
let scroll = if empty_state_only(app, id) { Scroll::vertical().overlay().at_rest() } else { Scroll::vertical() };
Stack::new().id_salt(id).fill().scroll(scroll).show(ui, |ui, _| memoized(app, ui, id, icon_panel_body));
}
None => memoized(app, ui, id, icon_panel_body),
}
}
/// Whether panel `id` is the Character or Paragraph panel showing only its empty state. Its body then scrolls with an
/// overlay bar, which leaves the message its full width: a scroll body measures its content beside the bar's lane, and a
/// message that wraps onto one more line there kept a bar it did not need. This case is temporary: the craft-libs pin
/// bump that includes craft-libs#4898, which fixes the measuring run, removes it and the two `shows_only_empty_state`
/// helpers.
fn empty_state_only(app: &VectorcraftApp, id: &str) -> bool {
match id {
"character" => panels::character::shows_only_empty_state(app),
"paragraph" => panels::paragraph::shows_only_empty_state(app),
_ => false,
}
}
/// The Layers panel's body.
fn layers_body(p: &mut BodyProps<'_>, ui: &mut Ui) {
#[cfg(test)]
@@ -180,6 +194,8 @@ mod tests {
static DIRECT: Cell<bool> = const { Cell::new(false) };
/// The panel [`draw`] shows.
static SHOWN: RefCell<&'static str> = const { RefCell::new("") };
/// The height of the body [`draw_unscrolled`] drew last.
static UNSCROLLED_HEIGHT: Cell<f32> = const { Cell::new(0.0) };
}
pub(super) fn count_run() {
@@ -202,6 +218,9 @@ mod tests {
fn panel(id: &'static str) -> Panel {
SHOWN.with(|s| *s.borrow_mut() = id);
let mut app = VectorcraftApp::new(Session::new(), Default::default());
// The scan of the installed fonts, which the app starts, changes the fonts' generation when it ends, and the
// bodies' inputs hold that generation: wait for it, or an idle frame that it ends in runs the body.
vectorcraft_text::FontDb::global().family_list();
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap();
let mut panel = Panel::new(app, draw);
@@ -356,6 +375,75 @@ mod tests {
assert!(panel.shows_value_with(|v| v.starts_with('7')), "the panel shows the 7 pt weight: {:?}", panel.values());
}
/// The Character or Paragraph empty state, drawn without a scroll body; [`UNSCROLLED_HEIGHT`] holds its height.
fn draw_unscrolled(app: &mut VectorcraftApp, ui: &mut Ui) {
let top = ui.min_rect().top();
crate::panels::show_icon_panel(app, ui, SHOWN.with(|s| *s.borrow()));
UNSCROLLED_HEIGHT.with(|h| h.set(ui.min_rect().bottom() - top));
}
/// Panel `id` drawn by `draw` over a document with nothing selected, in `room`.
fn empty_panel(id: &'static str, draw: fn(&mut VectorcraftApp, &mut Ui), room: egui::Vec2) -> Panel {
SHOWN.with(|s| *s.borrow_mut() = id);
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 200, "height": 200})).unwrap();
let mut panel = Panel::new(app, draw);
panel.room(room);
panel.frame();
panel.frame();
panel
}
/// The empty state's texts as `panel` paints them, in paint order.
fn empty_state_texts(panel: &Panel, message: &str) -> Vec<(String, egui::Rect)> {
panel.texts().into_iter().filter(|(text, _)| text == "No text selected" || text == message).collect()
}
/// In a dock group tall enough for the Character or Paragraph empty state at the group's full width, the dock body
/// lays the message out as an unscrolled body does, and the wheel does not move it: the body shows no scroll bar
/// and keeps no room for one. The groups are a little wider than the widths at which the message wraps onto one
/// line fewer, so beside a bar's lane it would take one more line, and from the empty state's own height to about
/// one line more.
#[test]
fn an_empty_state_that_fits_its_group_does_not_scroll() {
let cases = [
("character", "Select a text object to edit its character attributes."),
("paragraph", "Select a text object to edit its paragraph attributes."),
];
for (id, message) in cases {
let height_at = |width: f32| {
let tall = empty_panel(id, draw_unscrolled, egui::vec2(width, 1600.0));
assert_eq!(empty_state_texts(&tall, message).len(), 2, "{id} shows its empty state: {:?}", tall.texts());
UNSCROLLED_HEIGHT.with(Cell::get).ceil()
};
let mut widths = Vec::new();
let mut last = height_at(120.0);
for step in 1..=50 {
let width = 120.0 + 4.0 * step as f32;
let height = height_at(width);
if height < last {
widths.extend([width, width + 2.0]);
}
last = height;
}
assert!(widths.len() >= 4, "{id}: the message wraps onto fewer lines as the group widens");
for width in widths {
let height = height_at(width);
for extra in [0.0, 4.0, 8.0, 12.0] {
let room = egui::vec2(width, height + extra);
let unscrolled = empty_panel(id, draw_unscrolled, room);
let mut docked = empty_panel(id, draw, room);
docked.scroll_at(egui::pos2(width / 2.0, room.y / 2.0), -120.0);
assert_eq!(
empty_state_texts(&docked, message),
empty_state_texts(&unscrolled, message),
"{id} at {room:?}: the docked empty state is laid out and stays where the unscrolled one is"
);
}
}
}
}
/// The texts `id`'s body paints after idle frames, shown in its `MemoView` or, with `direct`, directly.
fn texts(id: &'static str, direct: bool) -> Vec<(String, egui::Rect)> {
DIRECT.with(|d| d.set(direct));
+19 -3
View File
@@ -74,17 +74,33 @@ static EMBEDDED: &Embedded = &[
/// The codes of [`EMBEDDED`] the interface offers. Browsers cannot use the native installed-font
/// fallback, so on the web a language whose text would be missing-glyph boxes (Gujarati without a
/// bundled Gujarati face) is not offered, including when restoring a preference. Arabic is kept
/// unavailable to users until the shared catalog in `storytold/craft-i18n` is consumed.
/// Gujarati face, see [`has_gujarati_face`]) is not offered, including when restoring a preference.
/// Arabic is kept unavailable to users until the shared catalog in `storytold/craft-i18n` is consumed.
fn offered_codes(web: bool, gujarati_font: bool) -> Vec<&'static str> {
EMBEDDED.iter().map(|(code, ..)| *code).filter(|code| *code != "ar" && (*code != "gu" || !web || gujarati_font)).collect()
}
/// Whether the interface has a Gujarati face: an embedded craft-fonts face, or on the web a face
/// the interface font stack serves (`SERVED_FONTS`, the `startup` and `demand` lines of
/// `crates/text/web-fonts.txt`) and fetches when Gujarati text needs it.
fn has_gujarati_face() -> bool {
#[cfg(target_arch = "wasm32")]
let served = vectorcraft_text::SERVED_FONTS.iter().map(|f| f.scripts);
#[cfg(not(target_arch = "wasm32"))]
let served = std::iter::empty();
has_gujarati_face_in(vectorcraft_text::CRAFT_FONTS, served)
}
/// [`has_gujarati_face`] for the given embedded faces and the scripts of each served face.
fn has_gujarati_face_in<'a>(embedded: &[vectorcraft_text::EmbeddedFace], mut served: impl Iterator<Item = &'a [&'a str]>) -> bool {
embedded.iter().any(|f| f.has_script("Gujr")) || served.any(|scripts| scripts.contains(&"Gujr"))
}
/// The one catalog set of the process, built on first use.
fn shared_cell() -> &'static Arc<I18n> {
static SHARED: OnceLock<Arc<I18n>> = OnceLock::new();
SHARED.get_or_init(|| {
let offered = offered_codes(cfg!(target_arch = "wasm32"), vectorcraft_text::CRAFT_FONTS.iter().any(|f| f.has_script("Gujr")));
let offered = offered_codes(cfg!(target_arch = "wasm32"), has_gujarati_face());
let (i18n, problems) = I18n::new(EMBEDDED, &offered);
for problem in problems {
log::warn!("vectorcraft: interface language catalog: {problem}");
+17
View File
@@ -159,6 +159,23 @@ fn gujarati_web_selection_requires_a_bundled_interface_font() {
assert!(codes(true, false).contains(&"hi".to_string()));
}
/// The web build embeds no Gujarati face, but serves Noto Sans Gujarati on demand: the web's
/// served faces are the `startup` and `demand` lines of `crates/text/web-fonts.txt`, so the web
/// offers Gujarati. Checked where the craft-fonts checkout has the face.
#[test]
fn web_offers_gujarati_with_the_served_gujarati_face() {
if !vectorcraft_text::CRAFT_FONTS.iter().any(|f| f.has_script("Gujr")) {
eprintln!("skipped: built without craft-fonts, or one without a Gujarati face");
return;
}
let served = || vectorcraft_text::WEB_FONTS.iter().filter(|w| w.startup || w.demand).map(|w| w.scripts);
let web_embedded: Vec<_> = vectorcraft_text::CRAFT_FONTS.iter().filter(|f| !f.has_script("Gujr")).copied().collect();
let font = has_gujarati_face_in(&web_embedded, served());
assert!(font, "a served Gujarati face counts on the web");
assert!(offered_codes(true, font).contains(&"gu"));
assert!(!has_gujarati_face_in(&web_embedded, std::iter::empty()), "without it, nothing draws Gujarati on the web");
}
/// A numbered built-in name shows its name before the number translated and the number as it
/// is; a name with a row of its own uses that row, and any other name comes back unchanged.
#[test]
+1
View File
@@ -4,6 +4,7 @@
//! (view/window) here and everything else to the engine. The same entry point serves menus,
//! shortcuts, the command palette ([`palette`], Help › Search Commands…) and the control channel ([`control`]).
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
/// VectorCraft as craft-update knows it, with its 128 px icon and accent colour: the update
/// prompt shows both, and an AppImage's menu entry gets the icon.
+4 -1
View File
@@ -252,7 +252,10 @@ fn artboard_items(app: &VectorcraftApp) -> Vec<Node> {
.collect();
let unlock: Vec<Node> =
[entry("Unlock Selected", sel.clone(), false), entry("Unlock All", (0..n).collect(), false)].into_iter().flatten().collect();
for (label, items) in [("Lock Artboards", lock), ("Unlock Artboards", unlock)] {
for (label, mut items) in [("Lock Artboards", lock), ("Unlock Artboards", unlock)] {
// The selected and unselected targets are disjoint. If All matches a narrower row, it
// is adjacent to it after empty rows are removed. Keep the narrower row for that command key.
items.dedup_by(|a, b| matches!((a, b), (Node::Item(a), Node::Item(b)) if a.command == b.command));
if !items.is_empty() {
v.push(sub(label, items));
}
+4 -1
View File
@@ -477,7 +477,10 @@ fn build_catalog(app: &VectorcraftApp, listed: &Listed, plays: &[(String, craft:
Ok(catalog) => {
// While a text field has the keys no shortcut runs, as in production; the text-editing chords still edit it,
// and the Type tool's commands run while it types.
let catalog = catalog.typing_rule(TypingRule::AllWait);
// The document canvas also defaults to Cmd+0, but its Fit on Screen stops at actual size.
// Leave that chord to VectorCraft's Fit Artboard in Window.
let fit_on_screen = CommandRef::from(craft::ui::canvas::ViewCommands::FitOnScreen);
let catalog = catalog.typing_rule(TypingRule::AllWait).replace_defaults(fit_on_screen.id, Vec::new());
let catalog = linked_keys.into_iter().fold(catalog, |catalog, (id, keys)| catalog.replace_defaults(id, keys));
let catalog = UNROUTED.iter().fold(catalog, |catalog, id| catalog.replace_defaults(id.as_str(), Vec::new()));
Some(type_keys.into_iter().fold(catalog, |catalog, (id, keys)| catalog.replace_defaults(id, keys)))
+29 -1
View File
@@ -21,6 +21,7 @@ use std::sync::Arc;
use craft::behavior::{Axis, DockSide, IconId};
use craft::ui::buttons::IconButton;
use craft::ui::contract::{Bind, BodyCx, PlainData, Props as _, Show as _, SizeLimits, Tracked};
use craft::ui::dialog::DialogId;
use craft::ui::docking::{
ColumnCards, DockCommands, DockConfig, DockEvent, DockGrid, DockPanels, DockScene, DockSizes, DockTo, DragUnit, FloatSpace, GroupAt, HidePanels,
PanelKey, PanelSpec, PanelSpecs, actions as command_actions, move_actions, request_actions,
@@ -73,6 +74,9 @@ pub(crate) struct Runtime {
/// A panel just floated out of a tool rail, whose window takes over the held press on the next
/// pass, with the pointer at this point inside it ([`continue_move`]).
hand_over: Option<(String, egui::Vec2)>,
/// The dialogs a panel in the open flyout opened, by id and opening serial: while one is open, Auto-Collapse Iconic
/// Panels leaves the flyout open ([`show`]).
flyout_dialogs: Vec<(DialogId, u64)>,
}
/// `ui.docking`: the layout in use, the hidden panels, the open flyout, the focused panel, the
@@ -1344,6 +1348,16 @@ fn raise(app: &VectorcraftApp, ctx: &egui::Context, panel: &str) {
}
}
/// The open dialogs of the main window, by id and opening serial: a dialog closed and opened again has a new serial.
fn open_dialogs(app: &VectorcraftApp) -> Vec<(DialogId, u64)> {
app.dialogs().map_or_else(Vec::new, |dialogs| {
dialogs.with(|host| {
let host = &*host;
host.stack().ids().filter_map(|id| Some((id, host.open_serial(id)?))).collect()
})
})
}
/// The floating window holding `panel` takes over the held primary press on the next pass, with the
/// pointer at `grab` inside it: a panel floated out of a tool rail mid-drag follows the pointer and
/// docks where the release lands.
@@ -1369,7 +1383,15 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, keeps_tools: boo
let presenting = app.ui.screen_mode >= 3;
// Shift+Tab, from its key, a menu or automation, closes a panel popped out of the icon column.
let mut flyout = flyout_before.clone().filter(|_| !keeps_tools);
let auto_collapse = app.session.prefs.auto_collapse_icon_panels;
let dialogs_before = open_dialogs(app);
if flyout_before.is_some() {
app.dock_rt.flyout_dialogs.retain(|dialog| dialogs_before.contains(dialog));
} else {
app.dock_rt.flyout_dialogs.clear();
}
// A dialog a panel of the flyout opened (the Gradient panel's stop popover) is a layer of the window's dialog host,
// outside the flyout's: while one is open, a press in it or the focus moving into it leaves the flyout open.
let auto_collapse = app.session.prefs.auto_collapse_icon_panels && app.dock_rt.flyout_dialogs.is_empty();
// The specs and rails leave the app for the pass, which lends the app to the panel bodies.
let specs = std::mem::take(&mut app.dock_rt.specs);
let rails = std::mem::take(&mut app.dock_rt.rails);
@@ -1415,6 +1437,12 @@ pub(crate) fn show(app: &mut VectorcraftApp, ui: &mut egui::Ui, keeps_tools: boo
if app.ui.open_panel == flyout_before {
app.ui.open_panel = flyout;
}
if app.ui.open_panel.is_some() {
let opened: Vec<_> = open_dialogs(app).into_iter().filter(|dialog| !dialogs_before.contains(dialog)).collect();
app.dock_rt.flyout_dialogs.extend(opened);
} else {
app.dock_rt.flyout_dialogs.clear();
}
if output.error.is_some() {
Arc::make_mut(&mut app.ui.dock_workspace).replace(default_workspace(&[]));
app.status(tl!("Invalid panel layout; restored the default dock").to_string());
+37
View File
@@ -1349,3 +1349,40 @@ fn a_tab_menus_stock_items_start_at_the_panel_items_check_column() {
let within = find(&shown, "Float").1;
assert!(within < stock.1 - 0.5, "\"Float\" starts {within} into its row with no rows before it, as far as {} after them", stock.1);
}
/// With Auto-Collapse Iconic Panels on, the popover the Gradient panel's stop chip opens from the panel's flyout leaves
/// the flyout open while it shows; once it closes, a click away from the flyout still closes it.
#[test]
fn a_popover_opened_from_an_auto_collapsing_flyout_leaves_the_flyout_open() {
let mut h = Harness::new();
h.app.session.prefs.auto_collapse_icon_panels = true;
h.app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 120, "height": 100})).unwrap();
let stops = json!([{"offset": 0, "color": "#2468ac"}, {"offset": 1, "color": "#e09020"}]);
h.app.run("paint.setFill", json!({"keepModel": true, "gradient": {"kind": "linear", "stops": stops}})).unwrap();
h.app.run("paint.setStroke", json!({"none": true, "focus": false})).unwrap();
h.app.select_tool("directSelection");
h.app.run("gradient.selectStop", json!({"index": 0})).unwrap();
h.app.run("window.panel", json!({"panel": "gradient"})).unwrap();
h.frames(3);
let flyout = h.app.ui.open_panel.clone();
assert!(flyout.is_some(), "the Gradient panel opens in its icon column's flyout");
let popover = craft::ui::dialog::dialog_id(crate::dialogs::gradient_stop::KIND);
let popover_open = |h: &Harness| h.app.dialogs().unwrap().with(|host| host.stack().contains(popover));
let chip = h
.nodes
.iter()
.filter(|(_, node)| node.label() == Some("Edit the stop"))
.find_map(|(_, node)| node.bounds())
.map(|b| Rect::from_min_max(pos2(b.x0 as f32, b.y0 as f32), pos2(b.x1 as f32, b.y1 as f32)))
.expect("the flyout's stop chip");
h.click(chip.center());
h.frames(3);
assert!(popover_open(&h), "the chip opens the stop popover");
assert_eq!(h.app.ui.open_panel, flyout, "the flyout stays open while its panel's popover shows");
h.press(egui::Key::Escape, Default::default());
h.frames(2);
assert!(!popover_open(&h), "Escape closes the popover");
assert_eq!(h.app.ui.open_panel, flyout, "closing the popover leaves the flyout open");
h.click(h.canvas().center());
assert_eq!(h.app.ui.open_panel, None, "a click away from the flyout still closes it");
}
+65 -12
View File
@@ -474,7 +474,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let pass = pass.into_inner();
if let Some(list) = shown.inner {
let opener = list.response.clone();
apply_list(app, node.as_deref(), &order, selection, list);
apply_list(app, node.as_deref(), &order, mix, selection, list);
if let (Some(key), Some(n)) = (app.ui.appearance_panel.menu, node.as_deref()) {
row_menu(app, ui, &opener, n, key);
}
@@ -530,8 +530,7 @@ fn object_row_label(app: &VectorcraftApp, summary: Option<&Summary>, mixed: bool
}
}
/// The list over `rows` (`order` their keys), bound to `selection`. A mixed selection's rows don't
/// drag: where one would go in each of the different stacks isn't one place.
/// The list over `rows` (`order` their keys), bound to `selection`.
fn show_list(
ui: &mut Ui,
cx: &RowCx<'_>,
@@ -555,10 +554,11 @@ fn show_list(
.deletable(true)
.selection(Bind::bound(selection))
.can_drag(|key: &RowKey| key.drags());
if let Some(n) = cx.node.filter(|_| cx.mix.is_none()) {
if let Some(n) = cx.node {
let mix = cx.mix;
list = list
.reorder(ReorderRule::new().copy_with(CopyKeys::Alt).into_groups())
.accepts(move |drag: &ListDrag<RowKey>, over: Option<&RowKey>, insert: usize| accepts(n, order, drag, over, insert, copy));
.accepts(move |drag: &ListDrag<RowKey>, over: Option<&RowKey>, insert: usize| accepts(n, order, mix, drag, over, insert, copy));
}
list.show_items(ui, rows, &mut |key, item| build_row(cx, *key, item))
}
@@ -569,6 +569,7 @@ fn apply_list(
app: &mut VectorcraftApp,
node: Option<&Node>,
order: &[RowKey],
mix: Option<&Mixed>,
selection: Selection<RowKey>,
list: CollectionResponse<RowKey, RowEvent>,
) {
@@ -610,7 +611,7 @@ fn apply_list(
delete_selected(app, node, sel).ok();
}
if let Some(mv) = moved {
reorder(app, n, order, &mv);
reorder(app, n, order, mix, &mv);
}
}
@@ -1192,7 +1193,14 @@ fn mixed(app: &VectorcraftApp) -> Option<Mixed> {
}
let aps: Vec<&vectorcraft_doc::Appearance> = nodes.iter().map(|n| &*n.appearance).collect();
let fills_differ = rest.iter().any(|n| n.appearance.fill_paint() != first.appearance.fill_paint());
Some(Mixed { shared: vectorcraft_doc::appearance::SharedStack::of(&aps), transparency, fills_differ })
let object_effects_match = rest.iter().all(|n| n.appearance.effects == first.appearance.effects);
Some(Mixed {
shared: vectorcraft_doc::appearance::SharedStack::of(&aps),
transparency,
fills_differ,
object_effects_match,
effect_targets_match: app.session.can_reorder_selected_effects(),
})
}
/// A mixed selection as the panel lists it ([`mixed`]).
@@ -1203,6 +1211,10 @@ struct Mixed {
transparency: bool,
/// Their topmost fills differ: the object row shows no fill chip.
fills_differ: bool,
/// All objects have the same complete, ordered object effect list.
object_effects_match: bool,
/// The command edits the same subjects whose rows the panel shows.
effect_targets_match: bool,
}
/// The selection's [`object_label`] and [`mixed`] summary for the active document as of one
@@ -1673,17 +1685,40 @@ fn delete_selected(app: &mut VectorcraftApp, node: Option<&Node>, sel: Sel) -> R
/// Whether the rows of `drag` may land before position `insert` of `order` (`over`: the row under
/// the pointer, which takes them when it holds rows): a drop that moves or copies them
/// ([`reorder_command`]).
fn accepts(n: &Node, order: &[RowKey], drag: &ListDrag<RowKey>, over: Option<&RowKey>, insert: usize, copy: bool) -> bool {
fn accepts(n: &Node, order: &[RowKey], mix: Option<&Mixed>, drag: &ListDrag<RowKey>, over: Option<&RowKey>, insert: usize, copy: bool) -> bool {
let before = order.get(..insert).map_or(0, |rows| rows.iter().filter(|key| drag.keys.contains(key)).count());
let mv = ReorderMove::new(drag.grabbed, drag.keys.clone(), insert.saturating_sub(before), copy);
let into = over.copied().filter(|key| key.has_children()).map(|key| mv.clone().in_group(Some(key)));
reorder_command(n, order, &mv).is_some() || into.is_some_and(|mv| reorder_command(n, order, &mv).is_some())
reorder_for_selection(n, order, mix, &mv).is_some() || into.is_some_and(|mv| reorder_for_selection(n, order, mix, &mv).is_some())
}
/// A mixed selection has an unambiguous destination only within a list that all its objects share.
fn reorder_for_selection(n: &Node, order: &[RowKey], mix: Option<&Mixed>, mv: &ReorderMove<RowKey>) -> Option<(&'static str, Value)> {
let (cmd, params) = reorder_command(n, order, mv)?;
let Some(mix) = mix else { return Some((cmd, params)) };
let (item, _) = mv.key.effect()?;
let shared = item.map_or(mix.object_effects_match, |i| mix.shared.has_item(i));
(cmd == "effect.move" && !mv.copy && mix.effect_targets_match && shared && params["fromItem"] == params["toItem"]).then_some((cmd, params))
}
/// Runs the reorder `mv` of the rows `order` of `n` and picks the moved rows (the copies), the
/// grabbed one the lead; a moved Contents row keeps its selection.
fn reorder(app: &mut VectorcraftApp, n: &Node, order: &[RowKey], mv: &ReorderMove<RowKey>) {
let Some((cmd, params)) = reorder_command(n, order, mv) else { return };
fn reorder(app: &mut VectorcraftApp, n: &Node, order: &[RowKey], mix: Option<&Mixed>, mv: &ReorderMove<RowKey>) {
let Some((cmd, mut params)) = reorder_for_selection(n, order, mix, mv) else { return };
if mix.is_some() {
if let Some((Some(item), _)) = mv.key.effect() {
// The panel shows the first selected object's rows. The engine's implicit active
// item uses that same anchor, even when another target paints first.
if app.session.appearance_item() != Some(item) && app.run("appearance.setActiveItem", json!({"index": item})).is_err() {
return;
}
if let Some(fields) = params.as_object_mut() {
fields.remove("fromItem");
fields.remove("toItem");
}
}
params = aligned(app, params);
}
let Ok(result) = app.run(cmd, params.clone()) else { return };
let Some((kind, grabbed)) = mv.key.sel().rows() else { return };
let mut set: Vec<usize> = mv.keys.iter().filter_map(|key| key.sel().rows().map(|(_, k)| k)).collect();
@@ -1808,6 +1843,20 @@ fn items_move(
Some(("appearance.moveItem", params))
}
/// An edge between rows in an expanded fill or stroke can report that item as its parent.
/// A drop immediately after the item header still means append to its effects.
fn item_effect_gap(remaining: &[RowKey], gap: usize, item: usize) -> Option<usize> {
let above = gap.checked_sub(1).and_then(|at| remaining.get(at)).copied();
if above == Some(RowKey::Item(item)) {
return None;
}
let index = |key: Option<RowKey>| match key {
Some(RowKey::ItemEffect(row, index)) if row == item => Some(index),
_ => None,
};
index(remaining.get(gap).copied()).or_else(|| index(above).map(|at| at + 1))
}
/// The effects `set` (ascending) of list `from_item` moved or copied to `gap` of `remaining`.
fn effects_move(
n: &Node,
@@ -1818,7 +1867,11 @@ fn effects_move(
mv: &ReorderMove<RowKey>,
) -> Option<(&'static str, Value)> {
let (item, pos) = match mv.parent {
Some(RowKey::Item(i)) => (Some(i), n.appearance.effects_at(Some(i))?.len()),
Some(RowKey::Item(i)) => {
let end = n.appearance.effects_at(Some(i))?.len();
let pos = if from_item == Some(i) && !mv.copy { item_effect_gap(remaining, gap, i).unwrap_or(end) } else { end };
(Some(i), pos)
}
Some(key) => key.effect()?,
None => {
let above = gap.checked_sub(1).and_then(|at| remaining.get(at)).copied();
+73 -3
View File
@@ -353,6 +353,8 @@ fn drops_pick_the_command() {
(mv(&[item(1)], 3, false, None), None),
(mv(&[item(1)], 3, false, Some(ItemEffect(1, 0))), None),
(mv(&[ItemEffect(1, 0)], 5, false, None), effects(json!({"from": 0, "fromItem": 1, "to": 1, "toItem": 1, "copy": false}))),
(mv(&[ItemEffect(1, 1)], 4, false, Some(item(1))), effects(json!({"from": 1, "fromItem": 1, "to": 0, "toItem": 1, "copy": false}))),
(mv(&[ItemEffect(1, 0)], 3, false, Some(item(1))), effects(json!({"from": 0, "fromItem": 1, "to": 1, "toItem": 1, "copy": false}))),
(mv(&[ItemEffect(1, 0)], 4, false, None), None),
(mv(&[ItemEffect(1, 1)], 5, true, Some(item(0))), effects(json!({"from": 1, "fromItem": 1, "to": 0, "toItem": 0, "copy": true}))),
(mv(&[ItemEffect(1, 1)], 7, false, None), effects(json!({"from": 1, "fromItem": 1, "to": 1, "toItem": null, "copy": false}))),
@@ -362,8 +364,8 @@ fn drops_pick_the_command() {
assert_eq!(reorder_command(&path, &order, &moved), want, "{moved:?}");
}
let drag = |keys: &[RowKey]| ListDrag::new(egui::Id::NULL, keys.to_vec(), keys[0]);
assert!(accepts(&path, &order, &drag(&[effect(0)]), Some(&item(0)), 2, false), "into a fill's row");
assert!(!accepts(&path, &order, &drag(&[effect(0)]), Some(&Object), 1, false), "where it is");
assert!(accepts(&path, &order, None, &drag(&[effect(0)]), Some(&item(0)), 2, false), "into a fill's row");
assert!(!accepts(&path, &order, None, &drag(&[effect(0)]), Some(&Object), 1, false), "where it is");
// A group listed top-down S3, FA*, Contents, S1*, F0 (paint order F0 S1 FA S3, Contents above
// two), FA and S1 dragged together.
@@ -419,7 +421,7 @@ fn drops_pick_the_command() {
] {
assert_eq!(reorder_command(&group, &order, &moved), want, "{moved:?}");
}
assert!(!accepts(&group, &order, &drag(&[Contents]), Some(&Contents), 3, false), "where it is");
assert!(!accepts(&group, &order, None, &drag(&[Contents]), Some(&Contents), 3, false), "where it is");
}
#[test]
@@ -604,6 +606,74 @@ fn a_mixed_selection_lists_what_its_objects_share() {
assert!(panel.shows("Mixed Objects"));
}
#[test]
fn a_mixed_selection_reorders_its_identical_object_effect_lists() {
let mut app = app_with_a_selected_rectangle();
let a = node(&app).id;
let b = app.run("shape.rectangle", json!({"x": 50, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("paint.setFill", json!({"ids": [b], "color": "#ff0000"})).unwrap();
app.run("select.set", json!({"ids": [a.0, b]})).unwrap();
for effect in ["distort.twist", "distort.roughen"] {
app.run("effect.apply", json!({"effect": effect, "item": null})).unwrap();
}
let steps = |app: &VectorcraftApp| app.session.active().unwrap().history.undo.len();
let order = |app: &VectorcraftApp| {
[a, NodeId(b)]
.map(|id| app.session.active().unwrap().doc.node(id).unwrap().appearance.effects.iter().map(|e| e.id.clone()).collect::<Vec<_>>())
};
let before = order(&app);
let undo = steps(&app);
let mut panel = Panel::new(app, show);
assert!(panel.shows("Mixed Appearances"));
let drag = |panel: &mut Panel| {
let from = crate::panels::tests_appearance::row_spot(panel, &effect_row_label("distort.roughen"));
let above = panel.rect(&effect_row_label("distort.twist"));
panel.drag_between(from, egui::pos2(from.x, above.top() + 1.0), egui::Modifiers::NONE);
};
drag(&mut panel);
{
let mut app = panel.app();
assert_eq!(order(&app), [vec!["distort.roughen", "distort.twist"], vec!["distort.roughen", "distort.twist"]]);
assert_eq!(steps(&app), undo + 1);
app.run("edit.undo", json!({})).unwrap();
assert_eq!(order(&app), before);
app.run("effect.apply", json!({"ids": [b], "effect": "stylize.feather", "item": null})).unwrap();
}
let before = order(&panel.app());
drag(&mut panel);
assert_eq!(order(&panel.app()), before, "a common prefix does not make both lists reorderable");
}
#[test]
fn a_mixed_selection_reorders_shared_stroke_effects_at_different_item_indices() {
let mut app = app_with_a_selected_rectangle();
let a = node(&app).id;
let b = app.run("shape.rectangle", json!({"x": 50, "y": 0, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [b]})).unwrap();
app.run("appearance.addFill", json!({})).unwrap();
app.run("appearance.moveItem", json!({"from": 2, "to": 0})).unwrap();
app.run("appearance.setItem", json!({"index": 0, "color": "#ff0000"})).unwrap();
for (id, item) in [(a.0, 1), (b, 2)] {
for effect in ["distort.twist", "distort.roughen"] {
app.run("effect.apply", json!({"ids": [id], "item": item, "effect": effect})).unwrap();
}
}
app.run("select.set", json!({"ids": [b, a.0]})).unwrap();
app.ui.appearance_panel.open.insert(RowKey::Item(2));
let mut panel = Panel::new(app, show);
let from = crate::panels::tests_appearance::row_spot(&mut panel, &effect_row_label("distort.roughen"));
let above = panel.rect(&effect_row_label("distort.twist"));
panel.drag_between(from, egui::pos2(from.x, above.top() + 1.0), egui::Modifiers::NONE);
let app = panel.app();
let doc = &app.session.active().unwrap().doc;
for (id, item) in [(a, 1), (NodeId(b), 2)] {
let effects = doc.node(id).unwrap().appearance.effects_at(Some(item)).unwrap();
assert_eq!(effects.iter().map(|effect| effect.id.as_str()).collect::<Vec<_>>(), ["distort.roughen", "distort.twist"]);
}
assert_eq!(app.ui.appearance_panel.selection.lead, Some(RowKey::ItemEffect(2, 0)));
}
/// The [`summary`] the canvas cache holds for the active document, checked field by field against
/// what [`object_label`] and [`mixed`] work out from scratch.
fn fresh_summary(app: &mut VectorcraftApp) -> Arc<Summary> {
+2 -2
View File
@@ -1244,8 +1244,8 @@ fn the_artboard_tools_lock_entries_have_something_to_change() {
Some(sub) => menu_labels(children_of(sub)),
None => vec![],
};
assert_eq!(subs("Lock Artboards"), ["Lock All Except Selected", "Lock All"], "the selected artboard is locked already");
assert_eq!(subs("Unlock Artboards"), ["Unlock Selected", "Unlock All"]);
assert_eq!(subs("Lock Artboards"), ["Lock All Except Selected"], "only the unselected artboard can be locked");
assert_eq!(subs("Unlock Artboards"), ["Unlock Selected"], "only the selected artboard can be unlocked");
}
/// A right-click on an artboard that isn't selected selects it alone; on a selected one the selection
+5
View File
@@ -1262,6 +1262,11 @@ pub(crate) fn controls(app: &mut VectorcraftApp, ui: &mut Ui, rows: CharacterRow
}
}
/// Whether [`show`] draws only the empty state: no type is selected and the Snap to Glyph options are hidden.
pub(crate) fn shows_only_empty_state(app: &VectorcraftApp) -> bool {
text_style(app).is_none() && !app.ui.snap_to_glyph_options
}
/// The Character panel: the controls over the selected type (an empty state without any), then the
/// Snap to Glyph options while they are shown, which need no type.
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
+11 -12
View File
@@ -6,7 +6,7 @@
//!
//! The mode follows the colour's own model: the last mode picked comes back for colours in its model
//! and the defaults for new art, and the app keeps it between sessions. Alt on the spectrum, a chip
//! or a recent colour targets the inactive proxy (the framework's `PanelTarget::Background`);
//! or a recent colour targets the inactive proxy;
//! Cmd/Ctrl-clicking the spectrum recolours (Complement, with Shift Invert).
//!
//! `ui.colorPanel` picks a mode, shows or hides the options and checks or unchecks Show Recent
@@ -432,12 +432,11 @@ fn recolor(app: &mut VectorcraftApp, tgt: &Target, invert: bool, behind: bool) {
}
}
/// Run what the panel reported this pass on the document: the edits (the inactive proxy for a
/// `Background` target), the Tint row, None, a recolour click and the proxy's own events. The
/// Run the panel's edits, Tint row, None, recolour clicks and proxy events on the document. The
/// gradient stop popover, which embeds the panel, hands its output here too.
pub(crate) fn apply_output(app: &mut VectorcraftApp, out: &ColorPanelOutput) {
let tgt = target_now(app);
apply_with(app, &tgt, out);
apply_with(app, &tgt, PanelTarget::Foreground, out);
}
/// [`target`] with the "?" state of [`mixed_now`], for callers without the panel's pass.
@@ -445,9 +444,9 @@ pub(crate) fn target_now(app: &VectorcraftApp) -> Target {
target_with(app, mixed_now(app))
}
fn apply_with(app: &mut VectorcraftApp, tgt: &Target, out: &ColorPanelOutput) {
fn apply_with(app: &mut VectorcraftApp, tgt: &Target, active: PanelTarget, out: &ColorPanelOutput) {
for (which, event) in &out.edits {
let behind = matches!(which, PanelTarget::Background);
let behind = *which != active;
apply_event(app, event, &EditPath::Preview, &mut |app, picked: &PickedColor, phase| {
choose(app, tgt, picked_color(picked), phase, behind);
});
@@ -462,7 +461,7 @@ fn apply_with(app: &mut VectorcraftApp, tgt: &Target, out: &ColorPanelOutput) {
});
}
if let Some(which) = out.none {
let cmd = super::proxy_cmd(app, matches!(which, PanelTarget::Background));
let cmd = super::proxy_cmd(app, which != active);
app.run(cmd, json!({"none": true})).ok();
}
if let Some(r) = out.recolor {
@@ -549,16 +548,16 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let (fill, stroke) = super::current_paints(app);
let (fill_well, fill_color) = well(tl!("Fill"), &fill, fill_mixed);
let (stroke_well, stroke_color) = well(tl!("Stroke"), &stroke, stroke_mixed);
let fill_active = app.session.fill_active;
let colors = if fill_active { [fill_color, stroke_color] } else { [stroke_color, fill_color] };
let active = if fill_active { Well::Primary } else { Well::Secondary };
// The shared panel uses fixed slots for both the displayed colors and its edit targets.
let (active, active_target) =
if app.session.fill_active { (Well::Primary, PanelTarget::Foreground) } else { (Well::Secondary, PanelTarget::Background) };
let edited = tgt.color().map(|c| PickedColor::in_model(srgba(&c), model_values(&c)));
let rows = shown(app, &tgt);
let printable = gamut(app);
let stored: Vec<Color> = app.session.recent_colors.to_vec();
let chips: Vec<Srgba> = stored.iter().map(srgba).collect();
let before = app.ui.color_panel;
let out = ColorPanel::new(Bind::bound(&mut app.ui.color_panel), colors)
let out = ColorPanel::new(Bind::bound(&mut app.ui.color_panel), [fill_color, stroke_color])
.layout(LAYOUT)
.wells([fill_well, stroke_well], Bind::given(active))
.edited(edited)
@@ -570,7 +569,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
.working_rgb(&WorkingRgb)
.show(ui);
// PLAN: a click on a recent chip reports only its sRGB, so a CMYK recent colour paints as RGB; co.K18 needs the edit to name the chip.
apply_with(app, &tgt, &out);
apply_with(app, &tgt, active_target, &out);
let now = app.ui.color_panel.mode;
// Shift-click on the spectrum cycles the mode inside the panel; the colour follows it here.
if now != before.mode && picked_mode(now).is_some() {
+33
View File
@@ -429,3 +429,36 @@ fn the_wells_show_a_gradient_and_none_as_the_tools_proxy_does() {
assert!(color.shows_value(well), "the Color panel shows a well that reads as {well:?}");
}
}
#[test]
fn the_color_panel_edits_the_selected_stroke_well_without_changing_fill() {
use crate::tests::panel_harness::Panel;
let mut app = app();
app.run("paint.setFill", json!({"color": "#224466"})).unwrap();
app.run("paint.setStroke", json!({"color": "#aa5522"})).unwrap();
app.run("paint.toggleActive", json!({"fill": true})).unwrap();
let mut panel = Panel::new(app, show);
let (fill, stroke) = paints_hex(&panel.app());
let fill_well = panel.rect("Fill");
let stroke_well = panel.rect("Stroke");
let stroke_hit = egui::pos2(stroke_well.center().x, (fill_well.bottom() + stroke_well.bottom()) / 2.0);
assert!(stroke_well.contains(stroke_hit) && !fill_well.contains(stroke_hit), "click the exposed part of Stroke");
panel.click_at(stroke_hit);
assert!(!panel.app().session.fill_active, "the Color panel made Stroke active");
panel.click("Black");
assert_eq!(paints_hex(&panel.app()), (fill.clone(), "#000000".into()));
assert_ne!(stroke, "#000000");
panel.click_with("White", egui::Modifiers::ALT);
assert_eq!(paints_hex(&panel.app()), ("#ffffff".into(), "#000000".into()));
assert!(!panel.app().session.fill_active, "Alt edits Fill without activating it");
panel.click("None");
assert_eq!(paints_hex(&panel.app()), ("#ffffff".into(), String::new()));
panel.click("Fill");
assert!(panel.app().session.fill_active);
panel.click("Black");
assert_eq!(paints_hex(&panel.app()), ("#000000".into(), String::new()));
}
+11 -2
View File
@@ -299,9 +299,18 @@ pub(crate) fn split_row(app: &mut VectorcraftApp, ui: &mut Ui) {
let Some(split) = selected_split(app) else { return };
// The canvas sets the divider to a ten-thousandth: a hundredth of a percent.
let pct = (split * 10_000.0).round() / 100.0;
// Workaround until the craft-libs pin includes craft-libs#5024: keying the field on the selection drops a value
// typed for one object when another is selected. The pin bump replaces this with `edit_target`.
let target = crate::panels::selection_target(app);
let edit = Field::new(tl!("Divider"))
.show(ui, |ui, _| {
SliderField::new(tl!("Divider"), Bind::given(pct), 0.0..=100.0).layout(SliderFieldLayout::Inline).step(1.0).unit("%").show(ui).edit
SliderField::new(tl!("Divider"), Bind::given(pct), 0.0..=100.0)
.layout(SliderFieldLayout::Inline)
.step(1.0)
.unit("%")
.id_salt(("divider", &target))
.show(ui)
.edit
})
.inner;
let Some(edit) = edit else { return };
@@ -1031,7 +1040,7 @@ fn show_settings(app: &mut VectorcraftApp, ui: &mut Ui, st: &mut TraceUi, list:
}
split_row(app, ui);
let data = RowsData::of(app);
let data = RowsData::of_selection(app);
let sampler = Sampler { enabled: t.is_trace || t.is_image, armed: app.ui.trace_ignore_sampler.is_some() };
let (main, advanced) = rows::settings_group(ui, |ui| {
let main = rows::main_rows(ui, &mut st.params, &data, RowsHost::Panel);
+21 -8
View File
@@ -22,7 +22,7 @@ use vectorcraft_engine::cmd::swatchlib::DOCUMENT_SWATCHES;
use super::{MODES, PALETTES, ignore_color, palette_label};
use crate::VectorcraftApp;
use crate::panels::swatches;
use crate::panels::{SelectionTarget, selection_target, swatches};
/// Where the rows are shown.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -40,13 +40,21 @@ pub(crate) struct RowsData {
pub(crate) libraries: Vec<Entry<String>>,
/// The active document's colour group names.
pub(crate) groups: Vec<String>,
/// The selection whose settings the rows show, for a host that follows the selection (the panel). A slider's
/// unfinished value is dropped when it changes.
pub(crate) target: Option<SelectionTarget>,
}
impl RowsData {
/// The lists for the active document.
pub(crate) fn of(app: &VectorcraftApp) -> Self {
// PLAN: assumed `swatches::library_entries(app: &VectorcraftApp) -> Vec<Entry<String>>` (color-w10).
RowsData { libraries: swatches::library_entries(app), groups: swatch_groups(app) }
RowsData { libraries: swatches::library_entries(app), groups: swatch_groups(app), target: None }
}
/// The lists for the active document, for rows that show the selection's settings.
pub(crate) fn of_selection(app: &VectorcraftApp) -> Self {
RowsData { target: Some(selection_target(app)), ..Self::of(app) }
}
}
@@ -151,13 +159,18 @@ fn slider(key: &'static str, label: &'static str, range: RangeInclusive<f64>, un
Slider { key, label, range, unit, default: 0.0 }
}
fn slider_row(ui: &mut Ui, params: &mut Value, spec: Slider, enabled: bool, out: &mut RowsOutput) {
fn slider_row(ui: &mut Ui, params: &mut Value, data: &RowsData, spec: Slider, enabled: bool, out: &mut RowsOutput) {
let Slider { key, label, range, unit, default } = spec;
let value = params[key].as_f64().unwrap_or(default);
let events = Field::new(label)
.enabled(enabled)
.show(ui, |ui, _| {
let mut field = SliderField::new(label, Bind::given(value), range.clone()).layout(SliderFieldLayout::Inline).step(1.0).enabled(enabled);
// Workaround until the craft-libs pin includes craft-libs#5024: keying the field on the selection drops a
// value typed for one object when another is selected. The pin bump replaces this with `edit_target`.
if let Some(target) = &data.target {
field = field.id_salt((key, target));
}
if let Some(unit) = unit {
field = field.unit(unit);
}
@@ -234,14 +247,14 @@ pub(crate) fn main_rows(ui: &mut Ui, params: &mut Value, data: &RowsData, host:
_ if matches!(palette.as_str(), "fullTone" | "automatic") => slider("colorDetail", tl!("Colors"), 0.0..=100.0, Some("%")),
_ => slider("colors", tl!("Colors"), 2.0..=256.0, None),
};
slider_row(ui, params, count, true, &mut out);
slider_row(ui, params, data, count, true, &mut out);
out
}
/// The Advanced settings: fidelity, method, Create, snapping, shapes, grouping, gradients and Ignore Color, with an
/// eyedropper for Ignore Color when the host passes a `sampler`. `_data` and `_host` are the arguments of
/// eyedropper for Ignore Color when the host passes a `sampler`. `data` and `_host` are the arguments of
/// [`main_rows`], so a host passes the same set to both.
pub(crate) fn advanced_rows(ui: &mut Ui, params: &mut Value, _data: &RowsData, _host: RowsHost, sampler: Option<Sampler>) -> RowsOutput {
pub(crate) fn advanced_rows(ui: &mut Ui, params: &mut Value, data: &RowsData, _host: RowsHost, sampler: Option<Sampler>) -> RowsOutput {
let mut out = RowsOutput::default();
let mode = text(params, "mode", "blackAndWhite");
for spec in [
@@ -249,7 +262,7 @@ pub(crate) fn advanced_rows(ui: &mut Ui, params: &mut Value, _data: &RowsData, _
slider("corners", tl!("Corners"), 0.0..=100.0, Some("%")),
slider("noise", tl!("Noise"), 1.0..=100.0, Some("px")),
] {
slider_row(ui, params, spec, true, &mut out);
slider_row(ui, params, data, spec, true, &mut out);
}
// Flat Logo always paints biggest shapes first with a hair of overlap, so there is no choice.
if mode != "logo" {
@@ -282,7 +295,7 @@ pub(crate) fn advanced_rows(ui: &mut Ui, params: &mut Value, _data: &RowsData, _
params[key] = json!(!create(params, key));
out.picked();
}
slider_row(ui, params, Slider { default: 10.0, ..slider("strokeWidth", tl!("Stroke"), 1.0..=100.0, Some("px")) }, strokes, &mut out);
slider_row(ui, params, data, Slider { default: 10.0, ..slider("strokeWidth", tl!("Stroke"), 1.0..=100.0, Some("px")) }, strokes, &mut out);
}
// (Black and White has one colour and Flat Logo flat ones: no gradients to find.)
let gradients = mode == "grayscale" || mode == "color";
@@ -599,6 +599,64 @@ fn the_divider_slider_keeps_an_exact_divider_and_a_drag_is_one_undo_step() {
assert_eq!(undo(&panel.app()), steps + 1, "one undo step for the edit");
}
/// Two traced objects with the same settings, the first one selected: the app, the first and the second object.
fn two_traced_objects(app: VectorcraftApp) -> (VectorcraftApp, NodeId, NodeId) {
let mut app = app;
let a = first_selected(&app).unwrap().id;
app.run("edit.duplicate", json!({})).unwrap();
let b = first_selected(&app).unwrap().id;
assert_ne!(a, b);
app.run("select.set", json!({"ids": [a.0]})).unwrap();
(app, a, b)
}
/// Types `text` into the number box of the slider row `name` without finishing the edit.
fn type_unfinished(panel: &mut Panel, name: &str, text: &str) {
panel.click_role(name, craft::ui::contract::Role::SPIN_BUTTON);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text(text);
}
/// A value typed into a settings slider for one Image Trace object, and not finished, is dropped when another
/// object is selected: Enter afterwards changes neither object.
#[test]
fn an_unfinished_slider_value_is_dropped_when_another_object_is_selected() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let (app, a, b) = two_traced_objects(traced_app());
let mut panel = panel_over(app);
panel.frame();
let threshold = param(&panel.app(), "threshold");
let steps = undo(&panel.app());
type_unfinished(&mut panel, "Threshold", "3");
select(&mut panel, b);
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
assert_eq!(param(&panel.app(), "threshold"), threshold, "B keeps its threshold");
assert_eq!(undo(&panel.app()), steps, "nothing was traced");
select(&mut panel, a);
assert_eq!(param(&panel.app(), "threshold"), threshold, "A keeps its threshold");
}
/// A value typed into the Divider for one Image Trace object, and not finished, is dropped when another object is
/// selected: Enter afterwards moves neither divider.
#[test]
fn an_unfinished_divider_value_is_dropped_when_another_object_is_selected() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut app = traced_app();
app.run("imageTrace.setView", json!({"view": "split", "split": 0.4})).unwrap();
let (app, a, b) = two_traced_objects(app);
let mut panel = panel_over(app);
panel.frame();
let steps = undo(&panel.app());
type_unfinished(&mut panel, "Divider", "8");
select(&mut panel, b);
assert_eq!(first_selected(&panel.app()).unwrap().trace_split(), 0.4, "B has the same divider");
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
assert_eq!(first_selected(&panel.app()).unwrap().trace_split(), 0.4, "B keeps its divider");
assert_eq!(undo(&panel.app()), steps, "no undo step");
select(&mut panel, a);
assert_eq!(first_selected(&panel.app()).unwrap().trace_split(), 0.4, "A keeps its divider");
}
/// Properties shows the Divider slider of the selected Image Trace object in the Split view only,
/// with its name and value for screen readers.
#[test]
+5
View File
@@ -848,6 +848,11 @@ fn localized_control_words() -> WordRows {
.fold(WordRows::new(), |rows, (word, translated)| rows.row(word, translated))
}
/// Whether [`show`] draws only the empty state: no type is selected.
pub(crate) fn shows_only_empty_state(app: &VectorcraftApp) -> bool {
text_style(app).is_none()
}
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let Some((_, para)) = text_style(app) else {
super::empty_state(ui, "pilcrow", tl!("No text selected"), tl!("Select a text object to edit its paragraph attributes."));
+40 -12
View File
@@ -7,15 +7,17 @@
//! list stays after the selection changes, so choosing a font in it sets that font on the live text
//! selected then, as the font menus do. The sample field sets the text the samples show, and the
//! panel menu sets their size; Reset Retype Panel clears the list. `retype.find`, `retype.list`,
//! `retype.preview` and `retype.reset` do the same.
//! `retype.preview` and `retype.reset` do the same. A font's menu (a secondary click on its row, or
//! Shift+F10 on the focused row) selects the row and holds Apply Font, which sets that font as a
//! click does, then the panel menu's sample sizes and Reset Retype Panel.
use craft::behavior::{EditEvent, Mixed, keyed};
use craft::keymap::CommandRef;
use craft::ui::buttons::{Button, Link};
use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _};
use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::display::{Divider, Shade, Text};
use craft::ui::list::{List, ListRow, ThumbAspect, ThumbSize};
use craft::ui::menu::PanelRow;
use craft::ui::menu::{Menu, MenuItem, PanelRow};
use craft::ui::primitives::ContentPainterCx;
use craft::ui::runtime::commands::{CommandState, CommandStates};
use craft::ui::style::Variant;
@@ -50,7 +52,7 @@ const SIZES: [(Size, &str, ThumbSize); 3] =
[(Size::Small, "small", ThumbSize::Small), (Size::Medium, "medium", ThumbSize::Medium), (Size::Large, "large", ThumbSize::Large)];
/// One font in the list.
#[derive(Clone, Debug, PartialEq, Eq)]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Found {
pub family: String,
pub style: String,
@@ -114,21 +116,47 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let on_white = app.session.prefs.font_samples_on_white;
let indexed: Vec<(usize, &Found)> = view.fonts.iter().enumerate().collect();
let source = keyed(&indexed, |(at, _)| *at);
// A click activates a row, so the same row chosen again sets its font again.
let list = List::<usize>::new(tl!("Matching fonts")).select(SelectMode::Single).activate(ActivateOn::Click).show_items(
ui,
&source,
&mut |key, _| {
// The rows are keyed by place, so a list with other fonts, or another document, is another
// list: a row's menu closes rather than act on the font that took its place.
let document = app.session.active().map(|st| st.uid);
// A click activates a row, so the same row chosen again sets its font again. A secondary
// click selects its row and asks for the row's menu; it does not activate the row.
let list = List::<usize>::new(tl!("Matching fonts"))
.id(ui.scope_id().with(("matching-fonts", document, &view.fonts)))
.select(SelectMode::Single)
.activate(ActivateOn::Click)
.row_menu()
.show_items(ui, &source, &mut |key, _| {
let (family, style) = indexed.get(*key).map_or(("", ""), |(_, f)| (f.family.as_str(), f.style.as_str()));
ListRow::new(format!("{family} {style}")).thumb_aspect(size, ThumbAspect::new(8, 1), move |cx: &ContentPainterCx, rect: Rect| {
crate::font_menu::paint_family_sample(cx, rect, family, style, sample, on_white);
})
},
);
let chosen = list.events.iter().find_map(|e| match e {
});
let mut chosen = list.events.iter().find_map(|e| match e {
CollectionEvent::Activate(at) => view.fonts.get(*at),
_ => None,
});
if let Some(request) = list.menu
&& let Some(f) = view.fonts.get(request.key)
{
// Apply Font is off while choosing the font would set it on nothing.
let live = live_text_selected(app);
Menu::context(format!("{} {}", f.family, f.style), &list.response).show(ui, |ui, _| {
if MenuItem::new(tl!("Apply Font")).enabled(live).show(ui).ran {
chosen = Some(f);
}
Divider::horizontal().show(ui);
for (size, name, _) in SIZES {
if MenuItem::new(size_label(size)).check(view.size == size).show(ui).ran {
run = Some(("retype.preview", json!({ "size": name })));
}
}
Divider::horizontal().show(ui);
if MenuItem::new(tl!("Reset Retype Panel")).show(ui).ran {
run = Some(("retype.reset", json!({})));
}
});
}
if let Some(f) = chosen
&& live_text_selected(app)
{
+122
View File
@@ -232,3 +232,125 @@ fn choosing_a_listed_font_sets_it_on_the_selected_live_text() {
click(&mut app, &ctx, "Source Serif 4 Regular");
assert!(app.session.active().unwrap().doc == before);
}
/// Live text in Source Sans 3, selected, and a list of two fonts → the app and the text's id.
fn listed_with_live_text() -> (VectorcraftApp, u64) {
let mut app = app();
let font = |family: &str, style: &str| super::Found { family: family.into(), style: style.into(), matched: 1 };
app.ui.retype.searched = true;
app.ui.retype.fonts = vec![font("Source Sans 3", "Bold"), font("Source Serif 4", "Regular")];
let t = app.session.execute("text.create", &json!({"x": 10, "y": 300, "text": "live", "font": "Source Sans 3"})).unwrap()["id"].as_u64().unwrap();
select(&mut app, &[t]);
(app, t)
}
fn family_of(app: &VectorcraftApp, id: u64) -> String {
let NodeKind::Text(text) = &app.session.active().unwrap().doc.node(NodeId(id)).unwrap().kind else { panic!("text") };
text.first_style().font_family.clone()
}
fn undo_len(app: &VectorcraftApp) -> usize {
app.session.doc().unwrap().history.undo.len()
}
const SERIF: &str = "Source Serif 4 Regular";
const SANS: &str = "Source Sans 3 Bold";
#[test]
fn a_fonts_menu_selects_its_row_without_setting_the_font() {
use craft::ui::contract::Role;
let (app, t) = listed_with_live_text();
let mut panel = Panel::new(app, show);
let undo = undo_len(&panel.app());
panel.secondary_click(SERIF);
assert!(panel.menu_item_enabled("Apply Font"), "live text is selected");
assert_eq!(family_of(&panel.app(), t), "Source Sans 3", "the secondary click sets no font");
assert_eq!(undo_len(&panel.app()), undo);
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
panel.frame();
assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM));
assert!(panel.selected(SERIF), "the row the menu opened on is selected");
assert!(!panel.selected(SANS));
assert_eq!(family_of(&panel.app(), t), "Source Sans 3");
}
#[test]
fn apply_font_sets_the_rows_font_on_the_live_text_in_one_undo_step() {
let (app, t) = listed_with_live_text();
let mut panel = Panel::new(app, show);
let undo = undo_len(&panel.app());
// A menu opened on another row first, then closed: the menu acts on the row it opened on last.
panel.secondary_click(SANS);
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
panel.secondary_click(SERIF);
panel.click_menu_item("Apply Font");
assert_eq!(family_of(&panel.app(), t), "Source Serif 4", "the font of the row the menu opened on");
assert_eq!(undo_len(&panel.app()), undo + 1);
}
#[test]
fn apply_font_is_off_without_live_text() {
let (mut app, t) = listed_with_live_text();
select(&mut app, &[]);
let mut panel = Panel::new(app, show);
panel.secondary_click(SERIF);
assert!(!panel.menu_item_enabled("Apply Font"));
assert!(panel.menu_item_enabled("Reset Retype Panel"), "the panel's own items stay on");
assert_eq!(family_of(&panel.app(), t), "Source Sans 3", "text that is not selected keeps its font");
}
#[test]
fn the_fonts_menu_sets_the_sample_size_and_resets_the_panel() {
use craft::behavior::Mixed;
use craft::ui::contract::Role;
let (app, _) = listed_with_live_text();
let mut panel = Panel::new(app, show);
let before = panel.app().ui.retype.size;
let (other, label) = if before == Size::Large { (Size::Small, "Small") } else { (Size::Large, "Large") };
panel.secondary_click(SERIF);
panel.click_role(label, Role::MENU_ITEM_CHECK_BOX);
assert_eq!(panel.app().ui.retype.size, other, "the size changed to the one chosen");
panel.secondary_click(SERIF);
assert_eq!(panel.toggled(label), Some(Mixed::Same(true)), "the size chosen is checked");
panel.click_menu_item("Reset Retype Panel");
assert!(!panel.app().ui.retype.searched, "the list is cleared");
assert_eq!(panel.app().ui.retype.size, other, "the size stays");
}
#[test]
fn keyboard_opens_the_fonts_menu_and_escape_returns_focus() {
use craft::ui::contract::Role;
let (app, t) = listed_with_live_text();
let mut panel = Panel::new(app, show);
panel.focus(SERIF);
panel.key(egui::Key::F10, egui::Modifiers::SHIFT);
panel.frame();
assert!(panel.menu_item_enabled("Apply Font"));
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
panel.frame();
assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM));
assert!(panel.focused(SERIF));
assert_eq!(family_of(&panel.app(), t), "Source Sans 3", "opening and closing the menu sets no font");
}
#[test]
fn the_fonts_menu_closes_when_the_list_or_the_document_changes() {
use craft::ui::contract::Role;
let (app, _) = listed_with_live_text();
let mut panel = Panel::new(app, show);
panel.secondary_click(SERIF);
assert!(panel.shows_role("Apply Font", Role::MENU_ITEM));
// Another search puts another font in the row's place.
panel.app().ui.retype.fonts.reverse();
panel.frame();
assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM));
panel.secondary_click(SERIF);
assert!(panel.shows_role("Apply Font", Role::MENU_ITEM));
panel.app().run("file.new", json!({"width": 300, "height": 200})).unwrap();
panel.frame();
assert!(!panel.shows_role("Apply Font", Role::MENU_ITEM));
}
+23 -6
View File
@@ -14,15 +14,15 @@ use serde_json::{Value, json};
use vectorcraft_engine::script::console::{Console, ConsoleLine, Ending, Entry};
// PLAN: assumed paths of the framework items below, re-exported by craft-ui (behavior, theme and keymap types)
use craft::behavior::{DisplayOrder, IconId, ItemSource};
use craft::behavior::{DisplayOrder, IconId, ItemSource, Selection};
use craft::keymap::CommandRef;
use craft::theme::variant::Tone;
use craft::ui::buttons::Button;
use craft::ui::contract::{Bind, LeastWidth, Props as _, ScrollAnchor, Show, ShowCollection, ShowContainer, Sizing, clicked};
use craft::ui::contract::{Bind, CollectionEvent, LeastWidth, Props as _, ScrollAnchor, Show, ShowCollection, ShowContainer, Sizing, clicked};
use craft::ui::layout::RowAlign;
use craft::ui::layout_components::{Row, Stack};
use craft::ui::list::{List, ListRow, RowInk};
use craft::ui::menu::PanelRow;
use craft::ui::menu::{Menu, MenuItem, PanelRow};
use craft::ui::notices::Notice;
use craft::ui::primitives::IconSpec;
use craft::ui::runtime::commands::{CommandState, CommandStates};
@@ -209,11 +209,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
selection.anchor = selection.anchor.take().filter(held);
let buttons = buttons(count > 0, !selection.items.is_empty());
let mut picked = None;
let mut menu_command = None;
Stack::new().fill().footer(|ui, _| picked = footer(ui, buttons).or(picked)).show(ui, |ui, _| {
if let Some(n) = notice(c) {
Notice::new(Tone::Info, n).show(ui);
}
List::<u64>::new(tl!("Script Console"))
let out = List::<u64>::new(tl!("Script Console"))
.id(ui.scope_id().with("console-lines"))
.row_menu()
.sizing(Sizing::Fill)
.scroll_anchor(ScrollAnchor::End)
.selection(Bind::bound(&mut *selection))
@@ -227,9 +230,23 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
Entry::Output(_) | Entry::Log(_) => row,
}
});
if let Some(line) = out.menu.map(|request| request.key).filter(held) {
// The row's More button can open the menu without a selection gesture.
if out.events.iter().any(|event| matches!(event, CollectionEvent::ContextMenu(_))) && !selection.items.contains(&line) {
*selection = Selection::single(line);
}
Menu::context(tl!("Script Console"), &out.response).show(ui, |ui, _| {
if MenuItem::new(tl!("Copy Line")).show(ui).ran {
menu_command = Some((COMMANDS[2], json!({"first": line, "last": line})));
}
if MenuItem::new(tl!("Copy Selected")).enabled(!selection.items.is_empty()).show(ui).ran {
menu_command = Some((COMMANDS[1], json!({})));
}
});
}
});
if let Some(id) = picked {
run_ui(app, id, json!({}));
if let Some((id, params)) = menu_command.or_else(|| picked.map(|id| (id, json!({})))) {
run_ui(app, id, params);
}
}
+192 -17
View File
@@ -4,6 +4,9 @@
//! objects' events, and a click on one picks it to edit. Remove Selected Entry
//! (`svgInteractivity.removeEvent`) and the panel menu's Clear Events (`svgInteractivity.clearEvents`)
//! remove them; Link JavaScript Files… opens the JavaScript Files dialog (`ui.javascriptFilesDialog`).
//! A right-click on an event row (or Shift+F10 on the focused row) picks that event and opens its
//! menu: Remove Event, Clear Events and Link JavaScript Files…, the same commands as the footer and
//! the panel menu.
//! Everything reads `svgInteractivity.info`.
use std::hash::{DefaultHasher, Hash, Hasher};
@@ -17,7 +20,7 @@ use craft::ui::display::{Shade, Text};
use craft::ui::form::Field;
use craft::ui::layout_components::Stack;
use craft::ui::list::{List, ListRow};
use craft::ui::menu::PanelRow;
use craft::ui::menu::{Menu, MenuItem, PanelRow};
use craft::ui::pickers::Select;
use craft::ui::primitives::SubmitKey;
use craft::ui::runtime::commands::{CommandState, CommandStates};
@@ -35,6 +38,13 @@ pub const ID: &str = "svgInteractivity";
/// The engine command of the panel menu's one row.
const CLEAR_EVENTS: &str = "svgInteractivity.clearEvents";
/// What the footer or a row's menu picked, run once the list is drawn.
#[derive(Clone, Copy)]
enum RowAction {
Clear,
LinkFiles,
}
/// The SVG Interactivity panel's own state, kept while the app runs.
#[derive(Clone, Debug, Default)]
pub(crate) struct SvgInteractivityPanel {
@@ -51,8 +61,8 @@ pub(crate) struct Info {
script_target: Option<egui::IdSalt>,
}
/// What [`info`] was read for: drawing (uid and File Revert count), revision, and selection size and ends.
pub(crate) type SelKey = ((u64, u64), u64, usize, Option<NodeId>, Option<NodeId>);
/// What [`info`] was read for: drawing (uid and File Revert count), revision, and selected objects.
pub(crate) type SelKey = ((u64, u64), u64, Vec<NodeId>);
/// A side label's text without its colon: the label draws the colon itself
/// (`CommonWords::caption`), so the catalog's "Event:" keeps its translation here.
@@ -61,16 +71,11 @@ pub(crate) fn caption(label: &'static str) -> &'static str {
crate::i18n::t(label).trim_end_matches(':')
}
fn sel_key(app: &VectorcraftApp) -> Option<SelKey> {
let st = app.session.active()?;
let sel = &st.selection.objects;
Some(((st.uid, st.reverts), st.revision, sel.len(), sel.first().copied(), sel.last().copied()))
}
/// The memoized [`Info`] when it was read for the current document and selection.
fn cached(app: &VectorcraftApp) -> Option<&Info> {
let key = sel_key(app)?;
app.canvas.svg_info.as_ref().filter(|(k, _)| *k == key).map(|(_, v)| v)
let st = app.session.active()?;
let (((uid, reverts), revision, selection), info) = app.canvas.svg_info.as_ref()?;
(*uid == st.uid && *reverts == st.reverts && *revision == st.revision && selection == &st.selection.objects).then_some(info)
}
/// `svgInteractivity.info`, read again only when the document or the selection changes.
@@ -78,7 +83,8 @@ pub(crate) fn info(app: &mut VectorcraftApp) -> Info {
if let Some(v) = cached(app) {
return v.clone();
}
let Some(key) = sel_key(app) else { return Info::default() };
let Some(st) = app.session.active() else { return Info::default() };
let key = ((st.uid, st.reverts), st.revision, st.selection.objects.clone());
let r = app.session.execute("svgInteractivity.info", &json!({})).unwrap_or_default();
let events = r["events"]
.as_array()
@@ -134,7 +140,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let rows_stamp = stamp.finish();
let mut remove = None;
let mut footer_pick = None;
let has_doc = app.session.active().is_some();
let mut row_action = None;
let document = app.session.active().map(|st| st.uid);
let has_doc = document.is_some();
let can_clear = clearable(&info);
let listed = events.iter().any(|(e, _)| e == event);
Stack::new()
.fill()
@@ -155,9 +164,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
let selection = if listed { Selection::single(event.to_string()) } else { Default::default() };
let mut list = List::<String>::new(tl!("Events"))
// Keep each row menu with the drawing and artwork it was opened for.
.id(ui.scope_id().with(("svg-events", document, info.script_target)))
.select(SelectMode::Single)
.arrows_select(true)
.deletable(true)
.row_menu()
.rows_stamp(rows_stamp)
.selection(Bind::given(selection))
.sizing(Sizing::Fill);
@@ -180,12 +192,29 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
CollectionEvent::Activate(key) => pick = Some(key),
// The menu acts on the row it opened on, so that row becomes the picked event.
CollectionEvent::ContextMenu(request) => pick = Some(request.key),
CollectionEvent::Delete(_) => {
remove = pick.as_deref().or(listed.then_some(event)).map(str::to_owned);
}
_ => {}
}
}
// `list.menu` is `None` once its row leaves the list.
if let Some(request) = list.menu {
let key = request.key.clone();
Menu::context(request.key, &list.response).show(ui, |ui, _| {
if MenuItem::new(tl!("Remove Event")).show(ui).ran {
remove = Some(key.clone());
}
if MenuItem::new(tl!("Clear Events")).enabled(can_clear).show(ui).ran {
row_action = Some(RowAction::Clear);
}
if MenuItem::new(tl!("Link JavaScript Files…")).enabled(has_doc).show(ui).ran {
row_action = Some(RowAction::LinkFiles);
}
});
}
});
if let Some(e) = pick {
let state = &mut app.ui.svg_interactivity_panel;
@@ -200,10 +229,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
match footer_pick {
Some(0) => remove = Some(event.to_string()),
Some(1) => {
Some(1) => row_action = Some(RowAction::LinkFiles),
_ => {}
}
match row_action {
Some(RowAction::Clear) => {
app.run(CLEAR_EVENTS, json!({})).ok();
}
Some(RowAction::LinkFiles) => {
crate::menus::invoke(app, "ui.javascriptFilesDialog", json!({}));
}
_ => {}
None => {}
}
if let Some(event) = remove
&& app.run("svgInteractivity.removeEvent", json!({ "event": event })).is_ok_and(|out| out["changed"].as_u64().unwrap_or(0) > 0)
@@ -221,11 +257,16 @@ pub(crate) fn menu_rows(_app: &VectorcraftApp) -> Vec<PanelRow> {
/// Clear Events is on while the objects have events. The panel reads the events each frame it shows; a
/// panel that is not shown leaves the row off.
pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
// (Where the objects' events differ, some of them have events.)
let any = cached(app).is_some_and(|info| info.has && info.events.as_ref().is_none_or(|l| !l.is_empty()));
let any = cached(app).is_some_and(clearable);
states.set(CommandRef::new(CLEAR_EVENTS), CommandState::new().enabled(any));
}
/// Clear Events has something to clear: the objects have events. (Where their events differ, some
/// of them have events.)
fn clearable(info: &Info) -> bool {
info.has && info.events.as_ref().is_none_or(|l| !l.is_empty())
}
/// The panel's own `ui.svgInteractivity.*` commands: it has none, because its menu row is the engine
/// command `svgInteractivity.clearEvents`.
pub(crate) fn run(_app: &mut VectorcraftApp, _id: &str, _params: &Value) -> Option<Result<Value, String>> {
@@ -481,4 +522,138 @@ mod tests {
assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some(script.as_str()));
assert!(panel.in_view(&last), "the picker scrolls the selected event into view");
}
/// A rectangle with two events, `onclick: 1;` and `onmouseover: 2;`, in the panel.
fn two_events() -> Panel {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}));
run(&mut app, "svgInteractivity.setEvent", json!({"event": "onclick", "script": "1;"}));
run(&mut app, "svgInteractivity.setEvent", json!({"event": "onmouseover", "script": "2;"}));
Panel::new(app, show)
}
fn undo_len(panel: &Panel) -> usize {
panel.app().session.active().unwrap().history.undo.len()
}
#[test]
fn row_menu_picks_its_row_and_removes_that_event_in_one_undo_step() {
let mut panel = two_events();
panel.click("onclick: 1;");
assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("1;"));
panel.secondary_click("onmouseover: 2;");
assert_eq!(panel.value(caption("JavaScript:")).as_deref(), Some("2;"), "the right-clicked row is picked");
let undo = undo_len(&panel);
panel.click_menu_item(tl!("Remove Event"));
panel.frame();
assert!(!panel.shows("onmouseover: 2;"), "the right-clicked event is removed");
assert!(panel.shows("onclick: 1;"), "the event picked before the right-click stays");
assert_eq!(undo_len(&panel), undo + 1);
panel.app().run("edit.undo", json!({})).unwrap();
panel.frame();
assert!(panel.shows("onmouseover: 2;"), "one undo brings it back");
}
#[test]
fn row_menu_offers_the_panel_menu_and_footer_commands() {
let mut panel = two_events();
panel.secondary_click("onclick: 1;");
let mut states = CommandStates::default();
menu_states(&panel.app(), &mut states);
let panel_menu_clear = states.remove(&CommandRef::new(CLEAR_EVENTS)).is_some_and(|s| s.is_enabled());
assert_eq!(panel.menu_item_enabled(tl!("Clear Events")), panel_menu_clear, "Clear Events follows the panel menu");
assert!(panel.menu_item_enabled(tl!("Link JavaScript Files…")), "a document is open");
let undo = undo_len(&panel);
panel.click_menu_item(tl!("Clear Events"));
panel.frame();
assert!(!panel.shows("onclick: 1;") && !panel.shows("onmouseover: 2;"));
assert_eq!(undo_len(&panel), undo + 1);
}
#[test]
fn keyboard_row_menu_opens_on_the_focused_row_and_escape_returns_focus() {
let mut panel = two_events();
panel.click("onclick: 1;");
panel.key(egui::Key::ArrowDown, egui::Modifiers::NONE);
panel.key(egui::Key::F10, egui::Modifiers::SHIFT);
panel.frame();
assert!(panel.menu_item_enabled(tl!("Remove Event")));
panel.key(egui::Key::Escape, egui::Modifiers::NONE);
panel.frame();
assert!(!panel.shows_role(tl!("Remove Event"), craft::ui::contract::Role::MENU_ITEM));
assert!(panel.focused("onmouseover: 2;"), "Escape gives focus back to the row");
// Enter runs the menu's first row, Remove Event, announced in that frame like the footer's.
panel.key(egui::Key::F10, egui::Modifiers::SHIFT);
panel.frame();
let enter =
|pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE };
panel.frame_with(vec![enter(true)]);
let removed = crate::i18n::fmt(tl!("Removed SVG event {event}"), &[("event", "onmouseover")]);
let announced = panel.announces(&removed);
panel.frame_with(vec![enter(false)]);
panel.frame();
assert!(announced, "the removal is announced like the footer's");
assert!(!panel.shows("onmouseover: 2;"));
assert!(panel.shows("onclick: 1;"));
}
#[test]
fn row_menu_closes_when_artwork_selection_changes_in_the_same_document() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
let ids = [0, 20, 40, 60].map(|x| run(&mut app, "shape.rectangle", json!({"x": x, "y": 0, "width": 10, "height": 10}))["id"].clone());
run(&mut app, "svgInteractivity.setEvent", json!({"ids": ids, "event": "onclick", "script": "1;"}));
let first = json!({"ids": [ids[0], ids[1], ids[3]]});
let second = json!({"ids": [ids[0], ids[2], ids[3]]});
run(&mut app, "select.set", first.clone());
let mut panel = Panel::new(app, show);
let item = tl!("Remove Event");
let role = craft::ui::contract::Role::MENU_ITEM;
panel.secondary_click("onclick: 1;");
assert!(panel.menu_item_enabled(item));
// Only the middle object changes, and both selections display the exact same row.
run(&mut panel.app(), "select.set", second);
panel.frame();
assert!(panel.shows("onclick: 1;"));
assert!(!panel.shows_role(item, role));
run(&mut panel.app(), "select.set", first);
panel.frame();
assert!(!panel.shows_role(item, role), "the old menu stays closed on return");
panel.secondary_click("onclick: 1;");
assert!(panel.menu_item_enabled(item), "the row can open a fresh menu");
}
#[test]
fn row_menu_closes_when_its_row_disappears_or_the_document_changes() {
let mut panel = two_events();
panel.secondary_click("onmouseover: 2;");
assert!(panel.menu_item_enabled(tl!("Remove Event")));
run(&mut panel.app(), "svgInteractivity.removeEvent", json!({"event": "onmouseover"}));
panel.frame();
assert!(!panel.shows_role(tl!("Remove Event"), craft::ui::contract::Role::MENU_ITEM));
// A second document whose object has the same event: switching to it shows a row of the same
// name, which the menu must not carry over to.
{
let mut app = panel.app();
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}));
run(&mut app, "svgInteractivity.setEvent", json!({"event": "onclick", "script": "1;"}));
app.run("window.nextDocument", json!({})).unwrap();
}
panel.frame();
panel.secondary_click("onclick: 1;");
assert!(panel.menu_item_enabled(tl!("Remove Event")));
panel.app().run("window.nextDocument", json!({})).unwrap();
panel.frame();
assert!(panel.shows("onclick: 1;"), "the other document lists the same event");
assert!(!panel.shows_role(tl!("Remove Event"), craft::ui::contract::Role::MENU_ITEM));
}
}
+23 -3
View File
@@ -344,6 +344,21 @@ fn shown_paragraph(app: &VectorcraftApp, t: &TextObject) -> usize {
super::character::text_editing(app).map_or(0, |(_, a, _)| t.paragraphs_in(a, a).start)
}
/// The edit target of the panel's fields for text `n`: the active document and its reverts, the
/// selected objects, the Type tool's range and whether Select All took the threaded story, and the
/// text and paragraph whose stops the panel shows.
/// A value typed in a field is dropped when this changes before it is entered, so it does not set
/// the stops of other text, even text whose stop holds the same values.
fn edited_paragraph(app: &VectorcraftApp, n: &Node) -> egui::IdSalt {
let para = match &n.kind {
NodeKind::Text(t) => shown_paragraph(app, t),
_ => 0,
};
let document = app.session.active().map(|st| (st.uid, st.reverts, &st.selection.objects));
let typed = (super::character::text_editing(app), super::character::text_story(app));
egui::IdSalt::new((document, typed, n.id, para))
}
/// [`above_text`], then note the active document and text `n`. A floating panel is
/// at least [`crate::panel_docking::PANEL_MIN_WIDTH`] wide, so for narrow text at a low zoom the
/// panel comes out wider than asked; the ruler then draws text `n` at [`screen_scale`] and runs
@@ -722,6 +737,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
return;
};
let vertical = matches!(&node.kind, NodeKind::Text(text) if text.vertical);
let edited = edited_paragraph(app, &node);
let targets = indent_targets(app, &node);
let mixed_left = targets.iter().any(|p| p.left != para.left_indent);
let panel = &mut app.ui.tabs_panel;
@@ -763,7 +779,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let label = if vertical { tl!("Y:") } else { tl!("X:") };
let x = marker.map_or_else(|| stops.get(stop).map(|s| s.position), |item| picked_position(item, &para, span));
let typed = Field::new(label)
.show(ui, |ui, _| NumberField::length(label, Bind::given(x), lengths).range(0.0..=MAX_STOP).show(ui))
.show(ui, |ui, _| NumberField::length(label, Bind::given(x), lengths).range(0.0..=MAX_STOP).edit_target((edited, stop, marker)).show(ui))
.inner
.and_then(|out| out.edit.events.committed().copied().flatten());
if let Some(value) = typed {
@@ -773,7 +789,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let on_stop = marker.is_none() && stop < stops.len();
let leader = stops.get(stop).filter(|_| marker.is_none()).map(|s| s.leader.clone()).unwrap_or_default();
let typed = Field::new(tl!("Leader:"))
.show(ui, |ui, _| TextField::new(tl!("Leader:"), Bind::given(leader.clone())).limit(8_usize).enabled(on_stop).show(ui))
.show(ui, |ui, _| {
TextField::new(tl!("Leader:"), Bind::given(leader.clone())).limit(8_usize).enabled(on_stop).edit_target((edited, stop)).show(ui)
})
.inner
.and_then(|out| out.events.committed().cloned());
if let (Some(leader), Some(s)) = (typed, stops.get_mut(stop)) {
@@ -784,7 +802,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let decimal = marker.is_none() && stops.get(stop).is_some_and(|s| s.align == TabAlign::Decimal);
let on = stops.get(stop).map_or_else(|| ".".to_string(), |s| s.align_on.to_string());
let typed = Field::new(tl!("Align On:"))
.show(ui, |ui, _| TextField::new(tl!("Align On:"), Bind::given(on.clone())).limit(1_usize).enabled(decimal).show(ui))
.show(ui, |ui, _| {
TextField::new(tl!("Align On:"), Bind::given(on.clone())).limit(1_usize).enabled(decimal).edit_target((edited, stop)).show(ui)
})
.inner
.and_then(|out| out.events.committed().and_then(|text| text.chars().next()));
if let (Some(c), Some(s)) = (typed, stops.get_mut(stop)) {
+240
View File
@@ -1094,3 +1094,243 @@ fn above_text_puts_the_panel_at_the_top_when_below_the_text_does_not_fit() {
assert_eq!(top, 0.0, "view centered at y {center_y}: panel top {top}, canvas {canvas:?}");
}
}
/// An app with area texts that each have decimal stops, aligned on a period with no leader, at
/// `positions`, and the first text selected. → the app and the texts' ids.
fn decimal_stops_app(texts: usize, positions: &[f64]) -> (VectorcraftApp, Vec<u64>) {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({})).unwrap();
let stops: Vec<_> = positions.iter().map(|p| json!({"position": p, "align": "decimal"})).collect();
let ids: Vec<u64> = (0..texts)
.map(|i| {
let y = 20.0 + 80.0 * i as f64;
let id = app.run("text.create", json!({"x": 10, "y": y, "text": "a\t1.5", "area": {"width": 300, "height": 60}})).unwrap();
let id = id["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
app.run("text.tabs.set", json!({"stops": stops})).unwrap();
id
})
.collect();
app.run("select.set", json!({"ids": [ids[0]]})).unwrap();
(app, ids)
}
/// The stops of the first paragraph of text `id` as (position, leader, align on).
fn stops_of(app: &VectorcraftApp, id: u64) -> Vec<(f64, String, char)> {
text_of(app, id).para_at(0).tabs.iter().map(|s| (s.position, s.leader.clone(), s.align_on)).collect()
}
/// Selects all of the focused field's text, types `text` and leaves it unentered.
fn draft(panel: &mut crate::tests::panel_harness::Panel, label: &str, role: craft::ui::contract::Role, text: &str) {
panel.click_role(label, role);
panel.key(egui::Key::A, egui::Modifiers::COMMAND);
panel.type_text(text);
}
/// A value typed in the X, Leader or Align On field and not yet entered is dropped when the
/// selection moves to another text whose stop holds the same values: Enter then leaves both texts'
/// stops as they were. A value typed for the newly selected text still sets its stop.
#[test]
fn a_field_value_typed_before_the_selection_changes_does_not_reach_the_new_text() {
use craft::ui::contract::Role;
for (label, role, typed) in [("X:", Role::SPIN_BUTTON, "70"), ("Leader:", Role::TEXT_INPUT, "-"), ("Align On:", Role::TEXT_INPUT, ",")] {
let (app, ids) = decimal_stops_app(2, &[40.0]);
let (a, b) = (ids[0], ids[1]);
let before = stops_of(&app, a);
let mut panel = crate::tests::panel_harness::Panel::new(app, show);
draft(&mut panel, label, role, typed);
panel.app().run("select.set", json!({"ids": [b]})).unwrap();
panel.frame();
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
for id in [a, b] {
assert_eq!(stops_of(&panel.app(), id), before, "{label} {typed:?} typed for text {a}, entered after selecting text {b}: text {id}");
}
draft(&mut panel, label, role, typed);
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
assert_eq!(stops_of(&panel.app(), a), before, "{label} {typed:?} typed for text {b}: text {a}");
assert_ne!(stops_of(&panel.app(), b), before, "{label} {typed:?} typed for text {b} sets its stop");
}
}
/// A Leader value typed with two texts selected and not yet entered is dropped when the selection
/// changes to the first text and a third one: the panel still shows the first text, but Enter
/// would set every selected text's stops.
#[test]
fn a_field_value_typed_before_other_texts_join_the_selection_does_not_reach_them() {
let (app, ids) = decimal_stops_app(3, &[40.0]);
let before = stops_of(&app, ids[0]);
let mut panel = crate::tests::panel_harness::Panel::new(app, show);
panel.app().run("select.set", json!({"ids": [ids[0], ids[1]]})).unwrap();
draft(&mut panel, "Leader:", craft::ui::contract::Role::TEXT_INPUT, "-");
panel.app().run("select.set", json!({"ids": [ids[0], ids[2]]})).unwrap();
panel.frame();
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
for &id in &ids {
assert_eq!(
stops_of(&panel.app(), id),
before,
"Leader typed for texts {} and {}, entered after selecting {} and {}: text {id}",
ids[0],
ids[1],
ids[0],
ids[2]
);
}
}
/// A Leader or Align On value typed for one stop and not yet entered is dropped when the ruler
/// picks another stop of the paragraph with the same leader and alignment character.
#[test]
fn a_field_value_typed_before_another_stop_is_picked_does_not_reach_that_stop() {
use craft::ui::contract::Role;
for (label, typed) in [("Leader:", "-"), ("Align On:", ",")] {
let (app, ids) = decimal_stops_app(1, &[30.0, 60.0]);
let before = stops_of(&app, ids[0]);
let mut panel = crate::tests::panel_harness::Panel::new(app, show);
panel.app().ui.tabs_panel.stop = 0;
draft(&mut panel, label, Role::TEXT_INPUT, typed);
panel.app().ui.tabs_panel.stop = 1;
panel.frame();
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
assert_eq!(stops_of(&panel.app(), ids[0]), before, "{label} {typed:?} typed for the first stop, entered after picking the second");
}
}
/// An X value typed in one document and not yet entered is dropped when another document becomes
/// active, also when the text selected there has the same id and the same stops.
#[test]
fn an_x_value_typed_before_another_document_is_activated_does_not_reach_it() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let ids: Vec<u64> = (0..2)
.map(|_| {
app.run("file.new", json!({})).unwrap();
let id = app.run("text.create", json!({"x": 10, "y": 20, "text": "a\t1.5", "area": {"width": 300, "height": 60}})).unwrap();
let id = id["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
app.run("text.tabs.set", json!({"stops": [{"position": 40, "align": "decimal"}]})).unwrap();
id
})
.collect();
assert_eq!(ids[0], ids[1], "the two documents' texts have the same id");
let id = ids[0];
let before = stops_of(&app, id);
let mut panel = crate::tests::panel_harness::Panel::new(app, show);
draft(&mut panel, "X:", craft::ui::contract::Role::SPIN_BUTTON, "70");
panel.app().run("document.activate", json!({"index": 0})).unwrap();
panel.frame();
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
for index in [0, 1] {
panel.app().run("document.activate", json!({"index": index})).unwrap();
assert_eq!(stops_of(&panel.app(), id), before, "X typed in the second document, entered after activating the first: document {index}");
}
}
/// The stops of every paragraph of text `id` as (position, leader, align on).
fn paragraph_stops(app: &VectorcraftApp, id: u64) -> Vec<Vec<(f64, String, char)>> {
let t = text_of(app, id);
(0..t.paragraph_count()).map(|i| t.para_at(i).tabs.iter().map(|s| (s.position, s.leader.clone(), s.align_on)).collect()).collect()
}
/// An X value typed with the Type tool's insertion point in the first paragraph and not yet
/// entered is dropped when the insertion point moves to the second paragraph, or the selection
/// grows over both, though both paragraphs hold the same stops.
#[test]
fn an_x_value_typed_before_the_type_tool_selection_changes_does_not_reach_other_paragraphs() {
for (anchor, caret) in [(6, 6), (0, 9)] {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({})).unwrap();
let id = app.run("text.create", json!({"x": 10, "y": 20, "text": "a\t1.5\nb\t2.5", "area": {"width": 300, "height": 80}})).unwrap();
let id = id["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
app.run("text.tabs.set", json!({"stops": [{"position": 40, "align": "decimal"}]})).unwrap();
let before = paragraph_stops(&app, id);
assert_eq!(before.len(), 2);
assert_eq!(before[0], before[1], "both paragraphs hold the same stops");
app.session.select_tool("type", Default::default()).unwrap();
app.session.set_tool_option("textSelection", &json!({"editing": id, "anchor": 0, "caret": 0}));
let mut panel = crate::tests::panel_harness::Panel::new(app, show);
draft(&mut panel, "X:", craft::ui::contract::Role::SPIN_BUTTON, "70");
panel.app().session.set_tool_option("textSelection", &json!({"editing": id, "anchor": anchor, "caret": caret}));
panel.frame();
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
assert_eq!(
paragraph_stops(&panel.app(), id),
before,
"X typed at the start of the text, entered with the Type tool's selection at {anchor}..{caret}"
);
}
}
/// An X value typed for the first-line marker and not yet entered is dropped when the ruler picks
/// the left indent's box at the same position.
#[test]
fn an_x_value_typed_before_another_indent_marker_is_picked_does_not_move_it() {
let mut app = indent_app(0.0, 0.0);
app.ui.tabs_panel.marker = Some(RulerItem::FirstLine);
let mut panel = crate::tests::panel_harness::Panel::new(app, show);
draft(&mut panel, "X:", craft::ui::contract::Role::SPIN_BUTTON, "20");
panel.app().ui.tabs_panel.marker = Some(RulerItem::LeftBox);
panel.frame();
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
assert_eq!(indent_values(&panel.app(), 0), (0.0, 0.0), "X typed for the first-line marker, entered after picking the left indent's box");
}
/// An X value typed and not yet entered is dropped when File › Revert restores the document, also
/// when the restored text is selected again and holds the same stops.
#[test]
fn an_x_value_typed_before_file_revert_does_not_reach_the_restored_text() {
struct SavedFile(std::path::PathBuf);
impl Drop for SavedFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
let (mut app, ids) = decimal_stops_app(1, &[40.0]);
let id = ids[0];
app.services.read = Some(Box::new(|path| std::fs::read(path).map_err(|e| e.to_string())));
app.services.write = Some(Box::new(|path, bytes| std::fs::write(path, bytes).map_err(|e| e.to_string())));
let path = SavedFile(std::env::temp_dir().join(format!("vc-ui-tabs-draft-revert-{}.vectorcraft", std::process::id())));
app.run("file.saveAs", json!({"path": path.0})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 200, "width": 40, "height": 40})).unwrap();
app.run("select.set", json!({"ids": [id]})).unwrap();
let before = stops_of(&app, id);
let mut panel = crate::tests::panel_harness::Panel::new(app, show);
draft(&mut panel, "X:", craft::ui::contract::Role::SPIN_BUTTON, "70");
panel.app().run("file.revert", json!({"confirmed": true})).unwrap();
panel.app().run("select.set", json!({"ids": [id]})).unwrap();
panel.frame();
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
assert_eq!(stops_of(&panel.app(), id), before, "X typed before File › Revert, entered after selecting the restored text");
}
/// A Leader value typed with the Type tool's selection over all of a threaded frame's text and not
/// yet entered is dropped when Select All takes the whole story, though the frame's range stays
/// the same: Enter would set the stops of every frame of the story.
#[test]
fn a_field_value_typed_before_select_all_takes_the_story_does_not_reach_it() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({})).unwrap();
let story = (1..=8).map(|i| format!("{i}\t1.5")).collect::<Vec<_>>().join("\n");
let a = app.run("text.create", json!({"x": 10, "y": 20, "text": story, "area": {"width": 300, "height": 50}})).unwrap()["id"].as_u64().unwrap();
app.run("select.set", json!({"ids": [a]})).unwrap();
app.run("text.tabs.set", json!({"stops": [{"position": 40, "align": "decimal"}]})).unwrap();
let b = app.run("text.thread.add", json!({"from": a, "rect": [10, 300, 300, 200]})).unwrap()["id"].as_u64().unwrap();
assert!(!text_of(&app, a).plain_text().is_empty() && !text_of(&app, b).plain_text().is_empty(), "the story runs through both frames");
let before = (paragraph_stops(&app, a), paragraph_stops(&app, b));
let len = text_of(&app, a).plain_text().len();
app.run("select.set", json!({"ids": [a]})).unwrap();
app.session.select_tool("type", Default::default()).unwrap();
app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 0, "caret": len}));
let range = super::super::character::text_editing(&app);
let mut panel = crate::tests::panel_harness::Panel::new(app, show);
draft(&mut panel, "Leader:", craft::ui::contract::Role::TEXT_INPUT, "-");
panel.app().run("select.all", json!({})).unwrap();
assert_eq!(super::super::character::text_editing(&panel.app()), range, "Select All leaves the frame's range as it was");
assert!(super::super::character::text_story(&panel.app()).is_some(), "Select All takes the story");
panel.frame();
panel.key(egui::Key::Enter, egui::Modifiers::NONE);
let after_a = paragraph_stops(&panel.app(), a);
let after_b = paragraph_stops(&panel.app(), b);
assert_eq!((after_a, after_b), before, "Leader typed for frame {a}'s text, entered after Select All took the story");
}
@@ -77,6 +77,70 @@ fn the_console_footer_buttons_run_their_commands_at_minimum_width() {
assert!(!panel.enabled("Copy All"));
}
#[test]
fn the_row_menu_copies_its_line_or_the_selected_range_while_output_arrives() {
let mut app = app();
run(&mut app, "$.writeln('one'); $.writeln('two'); $.writeln('three')");
let mut panel = Panel::new(app, show);
panel.click("#1 c.js: one");
panel.click_with("#1 c.js: three", egui::Modifiers::SHIFT);
panel.secondary_click("#1 c.js: two");
run(&mut panel.app(), "$.writeln('later')");
panel.frame();
panel.click_menu_item("Copy Line");
assert_eq!(panel.app().clipboard_out.take().as_deref(), Some("#1 c.js: two"));
panel.secondary_click("#1 c.js: two");
panel.click_menu_item("Copy Selected");
assert_eq!(panel.app().clipboard_out.take().as_deref(), Some("#1 c.js: one\n#1 c.js: two\n#1 c.js: three"));
panel.secondary_click("#2 c.js: later");
panel.click_menu_item("Copy Selected");
assert_eq!(panel.app().clipboard_out.take().as_deref(), Some("#2 c.js: later"));
panel.secondary_click("#1 c.js: two");
panel.app().run("script.console.clear", json!({})).unwrap();
run(&mut panel.app(), "$.writeln('replacement')");
panel.frame();
assert!(!panel.shows("Copy Line"), "a replacement at the same row cannot inherit the menu");
}
#[test]
fn copy_line_follows_its_number_when_older_output_is_dropped() {
let mut app = app();
run(&mut app, "$.writeln('first'); $.writeln('target'); $.writeln('next')");
let mut panel = Panel::new(app, show);
panel.secondary_click("#1 c.js: target");
// Fill the console and evict its first line while the menu is open.
let free = vectorcraft_engine::script::console::MAX_CONSOLE_LINES - panel.app().session.script_console().lines().len();
// Each run also writes a start, an end and a report.
run(&mut panel.app(), &format!("for (var i = 0; i < {}; i++) $.writeln(i)", free - 2));
assert_eq!(panel.app().session.script_console().first_number(), 1);
panel.frame();
panel.click_menu_item("Copy Line");
assert_eq!(panel.app().clipboard_out.take().as_deref(), Some("#1 c.js: target"));
}
#[test]
fn the_focused_console_row_opens_its_menu_from_the_keyboard() {
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
let mut app = app();
run(&mut app, "$.writeln('one')");
let mut panel = Panel::new(app, show);
panel.click("#1 c.js: one");
let list_focus = panel.ctx().memory(|memory| memory.focused()).expect("the console list has focus");
panel.key(Key::F10, Modifiers::SHIFT);
assert!(panel.menu_item_enabled("Copy Line"));
assert!(panel.menu_item_enabled("Copy Selected"));
panel.key(Key::Escape, Modifiers::NONE);
assert!(!panel.shows_role("Copy Line", Role::MENU_ITEM));
assert_eq!(panel.ctx().memory(|memory| memory.focused()), Some(list_focus));
}
#[test]
fn clear_works_during_a_run_and_the_run_goes_on_writing() {
let mut app = app();
+27
View File
@@ -80,6 +80,33 @@ fn idle(app: &mut VectorcraftApp, ctx: &egui::Context, n: usize) {
}
}
/// A focused document canvas must use the app's artboard fit, whose zoom may exceed 100%.
#[test]
fn command_zero_fits_the_active_artboard_when_the_canvas_has_focus() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.session.execute("file.new", &json!({"width": 120, "height": 80, "artboards": 2})).unwrap();
app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap();
let ctx = ready(&mut app);
app.view_mut().unwrap().artboard = 1;
app.run("view.fitArtboard", json!({})).unwrap();
idle(&mut app, &ctx, 12);
let fitted = app.view().unwrap();
let (zoom, center) = (fitted.zoom, fitted.center);
assert!(zoom > 1.0, "this artboard has room to grow past actual size: {zoom}");
app.run("view.setZoom", json!({"zoom": 50})).unwrap();
idle(&mut app, &ctx, 12);
focus_canvas(&mut app, &ctx);
assert!(app.view().unwrap().zoom < 1.0);
key_frame(&mut app, &ctx, tap(Key::Num0, cmd()));
idle(&mut app, &ctx, 12);
let fitted = app.view().unwrap();
assert!((fitted.zoom - zoom).abs() < 1e-6, "shortcut zoom {} should match the menu fit {zoom}", fitted.zoom);
assert_eq!(fitted.center, center, "fit the active artboard, not the whole document");
}
/// An app with a 200 × 200 document whose window has drawn its first frame, which builds the keymap the shortcut
/// commands edit.
fn new_app() -> VectorcraftApp {
+27
View File
@@ -614,12 +614,17 @@ fn every_context_label_is_a_menu_string() {
app.ui.context_spelling = None;
// The Lock Artboards and Unlock Artboards submenus of the Artboard tool.
app.run("artboard.new", json!({"x": 400, "y": 0, "width": 100, "height": 80})).unwrap();
app.run("artboard.new", json!({"x": 520, "y": 0, "width": 100, "height": 80})).unwrap();
app.run("artboard.setProps", json!({"index": 0, "locked": true})).unwrap();
app.select_tool("artboard");
shown.extend(labels(&app));
// Lock Selected with the artboard that isn't locked active.
crate::panels::artboards::select(&mut app, 1);
shown.extend(labels(&app));
// Unlock All has its own target when another locked artboard is outside the selection.
app.run("artboard.setProps", json!({"index": 2, "locked": true})).unwrap();
crate::panels::artboards::select(&mut app, 0);
shown.extend(labels(&app));
let missing: Vec<_> = shown.iter().filter(|l| !strings.contains(l.as_str())).collect();
assert!(missing.is_empty(), "context menu labels missing from menu_strings: {missing:?}");
for label in menus::CONTEXT_LABELS {
@@ -681,6 +686,28 @@ impl CanvasMenu {
}
}
#[test]
fn single_artboard_lock_submenus_open_and_apply_the_available_action() {
let mut app = app();
app.select_tool("artboard");
let mut canvas = CanvasMenu::new(app);
for (submenu, action, equivalent, locked) in
[("Lock Artboards", "Lock Selected", "Lock All", true), ("Unlock Artboards", "Unlock Selected", "Unlock All", false)]
{
canvas.right_click(100.0, 100.0);
let row = canvas.fixture.by_label(submenu).expect("the canvas offers the artboard submenu");
canvas.frame(vec![Event::PointerMoved(row.center())]);
canvas.fixture.advance(1.0);
canvas.frame(vec![]);
let row = canvas.fixture.by_label(action).expect("the submenu shows the action for the selected artboard");
assert!(canvas.fixture.by_label(equivalent).is_none(), "the same action has only one row");
canvas.fixture.click(&row);
canvas.frame(vec![]);
assert_eq!(canvas.app.borrow().session.active().unwrap().doc.artboards[0].locked, locked);
}
}
#[test]
fn create_outlines_from_the_canvas_menu_converts_selected_text_in_one_undo_step() {
let mut app = app();
+21
View File
@@ -164,6 +164,27 @@ fn home_lists_recent_files_and_a_click_opens_one() {
assert!(!app.ui.status.is_empty(), "a file that can't be opened says so");
}
/// The Home screen heads its recent files "Recent Files", in the interface language where the catalog translates it.
#[test]
fn home_heads_the_recent_files_recent_files() {
use crate::i18n::LangExt as _;
let shown = |lang: &str| {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
app.session.prefs.interface_language = lang.into();
app.ui.recent_files = vec![std::env::temp_dir().join("vectorcraft-home-heading").join("Drawing.svg").to_string_lossy().into_owned()];
home_screen(app)
};
let home = shown("en");
assert!(home.shows("Recent Files"), "the recent files are headed Recent Files");
assert!(!home.shows("Recent"), "not Recent alone");
let home = shown("de");
let de = crate::i18n::Lang::from_code("de").expect("German is registered");
let german = crate::i18n::tr(de, "Recent Files");
// Without a German row for Recent Files, the framework's heading stays.
let heading = if german == "Recent Files" { crate::i18n::tr_id(de, "startScreen.recent", "Recent") } else { german };
assert!(home.shows(heading), "German shows {heading}");
}
/// The Home screen has a Learn section: every tutorial of the Learn panel under its skill. A
/// tutorial shows the Learn panel at its steps and no document is opened; the Quick skill guide
/// shows its list of skills.
@@ -510,6 +510,11 @@ impl Panel {
self.fixture.tree().focused_key() == self.look(name).node
}
/// Whether the row or item named `name` reports itself selected.
pub(crate) fn selected(&self, name: &str) -> bool {
self.fixture.tree().selected_of(self.look(name).node).unwrap_or(false)
}
/// Whether the zero-based control of `role` has focus, including rows with identical names.
pub(crate) fn focused_nth(&self, role: craft::ui::contract::Role, index: usize) -> bool {
self.fixture.tree().focused_key() == self.look_nth(role, index).node
+22
View File
@@ -44,6 +44,28 @@ mod tests {
assert_covers(&ui_fonts().stack(), [Sample::new("hi", "hindi", HINDI)]);
}
/// The face the web serves for Gujarati (a `demand` line of `crates/text/web-fonts.txt`) draws
/// every Gujarati character of the Gujarati catalog on its own, as on the web, which has no
/// other Gujarati face.
#[test]
fn web_gujarati_face_covers_the_gujarati_catalog() {
if !embeds("Gujr") {
eprintln!("skipped: built without craft-fonts, or one without a Gujarati face");
return;
}
let served: Vec<_> = vectorcraft_text::CRAFT_FONTS
.iter()
.filter(|f| {
vectorcraft_text::WEB_FONTS.iter().any(|w| w.demand && w.scripts.contains(&"Gujr") && w.family == f.family && w.style == f.style)
})
.copied()
.collect();
assert!(!served.is_empty(), "the web serves a Gujarati face (a `demand` line of web-fonts.txt)");
let gujarati: String = include_str!("i18n/gu.tsv").chars().filter(|c| ('\u{0A80}'..='\u{0AFF}').contains(c)).collect();
assert!(!gujarati.is_empty());
assert_covers(&UiFonts::new(&I18nScripts).craft_faces(&served).stack(), [Sample::new("gu", "gu.tsv", &gujarati)]);
}
#[test]
fn japanese_renders_with_the_craft_fonts_without_installed_fonts() {
if !embeds("Jpan") {
@@ -1155,7 +1155,9 @@ fn review_596866_owned_release_then_press(coalesced: bool) {
let history = (app.session.active().unwrap().history.undo.len(), app.session.active().unwrap().history.redo.len());
if coalesced {
frame_at(&mut app, &ctx, start + step, vec![review_596866_button(at, false), review_596866_button(at, true)]);
assert!(frame_input(&ctx, |i| i.pointer.primary_released() && i.pointer.primary_pressed() && i.pointer.primary_down()));
// The press's Down comes in a second pass of this frame when another part of the UI asks for a rerun, and in the
// next frame otherwise. The coalesced release and press are read from the frame whose first pass took them.
assert!(frame_event(&ctx, |i| i.pointer.primary_released() && i.pointer.primary_pressed() && i.pointer.primary_down()));
} else {
review_gesture_release(&mut app, &ctx, at, start + step);
assert_eq!(app.session.active().unwrap().selection.objects, Vec::<NodeId>::new(), "CONTROL: the owned Up remains consumed");
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff. Show more