mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-20 01:14:23 +01:00
Merge main into fix/image-cache-follows-memory
This commit is contained in:
commit
8404fa4223
153 files changed
+11038
-655
No files matched your search
Generated
+1
@@ -6214,6 +6214,7 @@ dependencies = [
|
||||
"image",
|
||||
"jpeg-encoder",
|
||||
"log",
|
||||
"png 0.18.1",
|
||||
"proptest",
|
||||
"psd",
|
||||
"serde_json",
|
||||
|
||||
@@ -32,10 +32,11 @@ log = { workspace = true }
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
winsafe = { version = "0.0.29", default-features = false, features = ["kernel", "psapi"] }
|
||||
|
||||
# DirectWrite's system font collection (the desktop app's src/system_fonts.rs, shared): fonts that
|
||||
# font services such as Adobe Fonts load in place (#579). MIT OR Apache-2.0.
|
||||
# DirectWrite's system font collection and GDI's font list (the desktop app's src/system_fonts.rs,
|
||||
# shared): fonts that font services such as Adobe Fonts load in place (#579, #1258). MIT OR
|
||||
# Apache-2.0.
|
||||
[target.'cfg(all(windows, not(target_vendor = "win7")))'.dependencies]
|
||||
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite"] }
|
||||
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi"] }
|
||||
|
||||
# CoreText's font manager (the desktop app's src/mac_fonts.rs, shared): fonts that apps and font
|
||||
# managers register from their own folders (#579). Zlib OR Apache-2.0 OR MIT.
|
||||
|
||||
@@ -50,13 +50,14 @@ clipboard-win = { workspace = true }
|
||||
# Win32 (MIT); the `user` feature is User32.dll only. Only the wgpu renderer chooses an adapter.
|
||||
winsafe = { version = "0.0.29", default-features = false, features = ["user"], optional = true }
|
||||
|
||||
# DirectWrite's system font collection (src/system_fonts.rs): fonts that font services such as
|
||||
# Adobe Fonts load in place (#579). MIT OR Apache-2.0, already in the build through accesskit.
|
||||
# DirectWrite's system font collection and GDI's font list (src/system_fonts.rs): fonts that font
|
||||
# services such as Adobe Fonts load in place (#579, #1258). MIT OR Apache-2.0, already in the build
|
||||
# through accesskit.
|
||||
# Win32_UI_WindowsAndMessaging has `MSG` and `WM_POINTERDOWN`, which src/windows_stylus.rs uses to
|
||||
# read a pen's barrel button from its pointer messages. Win32_UI_Input_Pointer has
|
||||
# `GetPointerPenInfo`, which it uses to read the pen's pressure and which end of the pen is down.
|
||||
[target.'cfg(all(windows, not(target_vendor = "win7")))'.dependencies]
|
||||
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
|
||||
windows = { version = "0.62", features = ["Win32_Graphics_DirectWrite", "Win32_Graphics_Gdi", "Win32_UI_Input_Pointer", "Win32_UI_WindowsAndMessaging"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# The macOS menu bar (src/mac_menu.rs): Tauri's menu crate, AppKit menus behind a safe API (no GTK
|
||||
|
||||
@@ -1070,13 +1070,15 @@ fn main() -> std::process::ExitCode {
|
||||
}
|
||||
// Linux may not map the window before the first frames, so a saved maximize is retried then (#3635).
|
||||
let pending_maximize = cfg!(target_os = "linux") && app.ui.window.as_ref().is_some_and(|g| g.maximized);
|
||||
// User Defined swatch, graphic style and symbol libraries live next to the preferences.
|
||||
// User Defined swatch, graphic style, symbol and brush libraries live next to the preferences.
|
||||
let swatches = prefs_path().and_then(|p| Some(p.parent()?.join("Swatches").to_string_lossy().to_string()));
|
||||
app.session.swatch_libraries.set_user_dir(swatches);
|
||||
let styles = prefs_path().and_then(|p| Some(p.parent()?.join("Graphic Styles").to_string_lossy().to_string()));
|
||||
app.session.style_libraries.set_user_dir(styles);
|
||||
let symbols = prefs_path().and_then(|p| Some(p.parent()?.join("Symbols").to_string_lossy().to_string()));
|
||||
app.session.symbol_libraries.set_user_dir(symbols);
|
||||
let brushes = prefs_path().and_then(|p| Some(p.parent()?.join("Brushes").to_string_lossy().to_string()));
|
||||
app.session.brush_libraries.set_user_dir(brushes);
|
||||
// With the User Defined libraries listed, the persistent library panels reopen.
|
||||
vectorcraft_ui_egui::panels::library_panel::restore(&mut app);
|
||||
// So do the Libraries panel's libraries; runs without preferences (agents' test
|
||||
|
||||
@@ -1,39 +1,56 @@
|
||||
//! Windows: the font files in DirectWrite's system font collection, scanned with the font folders
|
||||
//! (`vectorcraft_text::set_platform_font_files`). The desktop app and `vectorcraft-cli` (exports,
|
||||
//! MCP) both install it; the CLI shares this file.
|
||||
//! Windows: the font files in DirectWrite's system font collection and those of the fonts GDI has
|
||||
//! loaded, scanned with the font folders (`vectorcraft_text::set_platform_font_files`). The desktop
|
||||
//! app and `vectorcraft-cli` (exports, MCP) both install it; the CLI shares this file.
|
||||
//!
|
||||
//! Font services such as Adobe Fonts load their fonts with GDI at run time, from files in their
|
||||
//! own folders, without installing them: the font folders and the registry don't list them. Since
|
||||
//! Windows 10 (version 1607) DirectWrite's system font collection holds them too
|
||||
//! Windows 10 (version 1607) DirectWrite's system font collection is meant to hold them too
|
||||
//! (<https://learn.microsoft.com/windows/win32/directwrite/what-s-new-in-directwrite-for-windows-8-consumer-preview>,
|
||||
//! "Support for Adobe Typekit and other font-service clients"), so VectorCraft lists them as other
|
||||
//! apps do, reading the files in place (#579).
|
||||
//! apps do, reading the files in place (#579). It doesn't always: on some machines the fonts
|
||||
//! Creative Cloud loads are in GDI's font list (Word and the font dialogs show them) but not in
|
||||
//! the collection (#1258). So the families GDI lists that the collection doesn't name are asked
|
||||
//! for one by one: a GDI font selected into a device context gives the DirectWrite font face
|
||||
//! GDI uses (`IDWriteGdiInterop::CreateFontFaceFromHdc`), and that face its files.
|
||||
//!
|
||||
//! DirectWrite is COM, which has no safe API, hence the scoped `unsafe_code` allowance.
|
||||
//! DirectWrite is COM and GDI a C API, neither with a safe API, hence the scoped `unsafe_code`
|
||||
//! allowance.
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use windows::Win32::Foundation::LPARAM;
|
||||
use windows::Win32::Graphics::DirectWrite::{
|
||||
DWRITE_FACTORY_TYPE_SHARED, DWriteCreateFactory, IDWriteFactory3, IDWriteFontSet, IDWriteLocalFontFileLoader,
|
||||
DWRITE_FACTORY_TYPE_SHARED, DWRITE_FONT_PROPERTY_ID_WIN32_FAMILY_NAME, DWriteCreateFactory, IDWriteFactory3, IDWriteFontFile, IDWriteFontSet,
|
||||
IDWriteGdiInterop, IDWriteLocalFontFileLoader, IDWriteStringList,
|
||||
};
|
||||
use windows::Win32::Graphics::Gdi::{
|
||||
CreateCompatibleDC, CreateFontIndirectW, DEFAULT_CHARSET, DeleteDC, DeleteObject, EnumFontFamiliesExW, HDC, HGDIOBJ, LOGFONTW, RASTER_FONTTYPE,
|
||||
SelectObject, TEXTMETRICW,
|
||||
};
|
||||
use windows::core::Interface;
|
||||
|
||||
/// The most fonts read from the collection (a system has a few thousand).
|
||||
const MAX_FONTS: u32 = 1 << 16;
|
||||
/// The most families and faces taken from GDI's font list.
|
||||
const MAX_GDI_FONTS: usize = 1 << 16;
|
||||
/// The most files one font face is made of (one, but for a few Type 1 fonts).
|
||||
const MAX_FACE_FILES: u32 = 8;
|
||||
/// The longest file path taken, in UTF-16 units (Windows' own limit).
|
||||
const MAX_PATH: u32 = 32_767;
|
||||
|
||||
/// Have the font scans read the font files DirectWrite lists.
|
||||
/// Have the font scans read the font files DirectWrite and GDI list.
|
||||
pub fn install() {
|
||||
vectorcraft_text::set_platform_font_files(font_files);
|
||||
}
|
||||
|
||||
/// The local files of the fonts in DirectWrite's system font collection as it is now (fonts
|
||||
/// loaded since the last call included). None before Windows 10, or when DirectWrite fails: the
|
||||
/// font folders and the registry still list the installed fonts.
|
||||
/// loaded since the last call included), with those of the fonts GDI lists that the collection
|
||||
/// leaves out. None before Windows 10, or when DirectWrite fails: the font folders and the
|
||||
/// registry still list the installed fonts.
|
||||
fn font_files() -> Vec<String> {
|
||||
match collection_files() {
|
||||
match listed_files() {
|
||||
Ok(files) => files.into_iter().collect(),
|
||||
Err(e) => {
|
||||
log::debug!("DirectWrite's system fonts aren't listed: {e}");
|
||||
@@ -42,30 +59,48 @@ fn font_files() -> Vec<String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn collection_files() -> windows::core::Result<BTreeSet<String>> {
|
||||
fn listed_files() -> windows::core::Result<BTreeSet<String>> {
|
||||
// SAFETY: plain DirectWrite calls on interfaces it returned, each checked for failure; the
|
||||
// collection is asked to check for fonts loaded since the factory last looked.
|
||||
let set = unsafe {
|
||||
let (factory, set) = unsafe {
|
||||
let factory: IDWriteFactory3 = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)?;
|
||||
let mut collection = None;
|
||||
factory.GetSystemFontCollection(false, &mut collection, true)?;
|
||||
let Some(collection) = collection else { return Ok(BTreeSet::new()) };
|
||||
collection.GetFontSet()?
|
||||
(factory, collection.map(|c| c.GetFontSet()).transpose()?)
|
||||
};
|
||||
let mut files = set.as_ref().map(collection_files).unwrap_or_default();
|
||||
// GDI's own names for the collection's families, the names GDI lists them by.
|
||||
// SAFETY: a list DirectWrite returns, read by `strings`.
|
||||
let named = set.as_ref().and_then(|s| unsafe { s.GetPropertyValues(DWRITE_FONT_PROPERTY_ID_WIN32_FAMILY_NAME) }.ok());
|
||||
let named: BTreeSet<String> = named.as_ref().map(strings).unwrap_or_default().iter().map(|n| n.to_lowercase()).collect();
|
||||
match gdi_files(&factory, &named) {
|
||||
Ok(more) => files.extend(more),
|
||||
Err(e) => log::debug!("GDI's fonts aren't listed: {e}"),
|
||||
}
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
fn collection_files(set: &IDWriteFontSet) -> BTreeSet<String> {
|
||||
// SAFETY: a count of the set's fonts.
|
||||
let count = unsafe { set.GetFontCount() }.min(MAX_FONTS);
|
||||
// Faces of one file (a collection's, a variable font's instances) name it once.
|
||||
Ok((0..count).filter_map(|i| local_path(&set, i)).collect())
|
||||
(0..count).filter_map(|i| local_path(set, i)).collect()
|
||||
}
|
||||
|
||||
/// The path of the file holding font `i` of `set`, when it is a local file (not a downloadable
|
||||
/// font, nor one in memory).
|
||||
fn local_path(set: &IDWriteFontSet, i: u32) -> Option<String> {
|
||||
// SAFETY: `i` is below the set's count; the key DirectWrite hands back stays valid while
|
||||
// `file` (which owns it) lives, and is passed back with its own size; the path buffer is
|
||||
// sized from DirectWrite's answer plus the terminating NUL.
|
||||
// SAFETY: `i` is below the set's count.
|
||||
let file = unsafe { set.GetFontFaceReference(i).ok()?.GetFontFile().ok()? };
|
||||
file_path(&file)
|
||||
}
|
||||
|
||||
/// The path of `file`, when it is a local file.
|
||||
fn file_path(file: &IDWriteFontFile) -> Option<String> {
|
||||
// SAFETY: the key DirectWrite hands back stays valid while `file` (which owns it) lives, and is
|
||||
// passed back with its own size; the path buffer is sized from DirectWrite's answer plus the
|
||||
// terminating NUL.
|
||||
unsafe {
|
||||
let file = set.GetFontFaceReference(i).ok()?.GetFontFile().ok()?;
|
||||
let loader: IDWriteLocalFontFileLoader = file.GetLoader().ok()?.cast().ok()?;
|
||||
let (mut key, mut size) = (std::ptr::null_mut(), 0u32);
|
||||
file.GetReferenceKey(&mut key, &mut size).ok()?;
|
||||
@@ -79,6 +114,159 @@ fn local_path(set: &IDWriteFontSet, i: u32) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The strings of `list`.
|
||||
fn strings(list: &IDWriteStringList) -> Vec<String> {
|
||||
// SAFETY: indices below the list's count; each buffer is sized from DirectWrite's answer plus
|
||||
// the terminating NUL.
|
||||
let count = unsafe { list.GetCount() }.min(MAX_FONTS);
|
||||
(0..count)
|
||||
.filter_map(|i| unsafe {
|
||||
let len = list.GetStringLength(i).ok()?;
|
||||
if len > MAX_PATH {
|
||||
return None;
|
||||
}
|
||||
let mut s = vec![0u16; len as usize + 1];
|
||||
list.GetString(i, &mut s).ok()?;
|
||||
Some(String::from_utf16_lossy(s.get(..len as usize)?))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A memory device context, deleted when dropped.
|
||||
struct MemoryDc(HDC);
|
||||
|
||||
impl MemoryDc {
|
||||
fn new() -> windows::core::Result<Self> {
|
||||
// SAFETY: a device context compatible with the screen, owned by the guard.
|
||||
let dc = unsafe { CreateCompatibleDC(None) };
|
||||
if dc.is_invalid() { Err(windows::core::Error::from_thread()) } else { Ok(Self(dc)) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MemoryDc {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the guard's own device context, with its first font back in it.
|
||||
// Failing to delete it leaks a handle, which there's nothing to do about.
|
||||
let _ = unsafe { DeleteDC(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
/// The files of the faces of the font families GDI lists that DirectWrite's collection doesn't
|
||||
/// name (`named`, lower case).
|
||||
fn gdi_files(factory: &IDWriteFactory3, named: &BTreeSet<String>) -> windows::core::Result<BTreeSet<String>> {
|
||||
// SAFETY: a DirectWrite call checked for failure.
|
||||
let interop = unsafe { factory.GetGdiInterop()? };
|
||||
let dc = MemoryDc::new()?;
|
||||
let mut families = BTreeSet::new();
|
||||
enum_fonts(&dc, [0; 32], add_family, &mut families);
|
||||
let mut faces = Vec::new();
|
||||
for family in families.iter().filter(|f| !named.contains(&face_name(f).to_lowercase())) {
|
||||
enum_fonts(&dc, *family, add_face, &mut faces);
|
||||
}
|
||||
// A face listed once for each of its character sets is read once.
|
||||
faces.sort_by_key(face_key);
|
||||
faces.dedup_by_key(|f| face_key(f));
|
||||
// Asking for a face's files takes about a third of a millisecond, and the fonts are looked at
|
||||
// every few seconds (#2576): the faces still listed keep the files they had while those exist.
|
||||
// A face no longer listed is forgotten, so one activated again is asked for anew, and one
|
||||
// whose files couldn't be read (GDI or DirectWrite failed, or it has no local file) is asked
|
||||
// again at the next look.
|
||||
let mut known = KNOWN_FACES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut now = BTreeMap::new();
|
||||
for f in &faces {
|
||||
let key = face_key(f);
|
||||
let files = match known.remove(&key) {
|
||||
Some(files) if !files.is_empty() && files.iter().all(|p| std::path::Path::new(p).is_file()) => files,
|
||||
_ => face_files(&interop, &dc, f),
|
||||
};
|
||||
now.insert(key, files);
|
||||
}
|
||||
*known = now;
|
||||
Ok(known.values().flatten().cloned().collect())
|
||||
}
|
||||
|
||||
/// A GDI face: its name (NUL-padded), weight and whether it's italic.
|
||||
type FaceKey = ([u16; 32], i32, u8);
|
||||
|
||||
fn face_key(f: &LOGFONTW) -> FaceKey {
|
||||
(f.lfFaceName, f.lfWeight, f.lfItalic)
|
||||
}
|
||||
|
||||
/// The files of the faces GDI listed at the last look ([`gdi_files`]).
|
||||
static KNOWN_FACES: Mutex<BTreeMap<FaceKey, Vec<String>>> = Mutex::new(BTreeMap::new());
|
||||
|
||||
/// Have GDI call `add` with `out` for each font of the family named `family` (NUL-padded), or for
|
||||
/// one font of each family when it's empty.
|
||||
fn enum_fonts<T>(
|
||||
dc: &MemoryDc,
|
||||
family: [u16; 32],
|
||||
add: unsafe extern "system" fn(*const LOGFONTW, *const TEXTMETRICW, u32, LPARAM) -> i32,
|
||||
out: &mut T,
|
||||
) {
|
||||
let query = LOGFONTW { lfCharSet: DEFAULT_CHARSET, lfFaceName: family, ..Default::default() };
|
||||
// SAFETY: `add` reads the fonts GDI passes and casts the LPARAM back to the `T` it is, which
|
||||
// outlives the call (GDI calls back before returning). Its answer is the last callback's.
|
||||
let _ = unsafe { EnumFontFamiliesExW(dc.0, &query, Some(add), LPARAM(std::ptr::from_mut(out) as isize), 0) };
|
||||
}
|
||||
|
||||
/// A GDI font list callback adding the font's family name to the `BTreeSet<[u16; 32]>` in `out`.
|
||||
unsafe extern "system" fn add_family(font: *const LOGFONTW, _: *const TEXTMETRICW, kind: u32, out: LPARAM) -> i32 {
|
||||
// SAFETY: GDI passes a valid font, and `out` is the set `enum_fonts` was given.
|
||||
let (Some(font), Some(out)) = (unsafe { font.as_ref() }, unsafe { (out.0 as *mut BTreeSet<[u16; 32]>).as_mut() }) else {
|
||||
return 0;
|
||||
};
|
||||
// Bitmap fonts have no file DirectWrite reads; `@` names are vertical writing's copies.
|
||||
if kind & RASTER_FONTTYPE == 0 && font.lfFaceName.first().is_some_and(|&c| c != 0 && c != u16::from(b'@')) {
|
||||
out.insert(font.lfFaceName);
|
||||
}
|
||||
i32::from(out.len() < MAX_GDI_FONTS)
|
||||
}
|
||||
|
||||
/// A GDI font list callback adding the font to the `Vec<LOGFONTW>` in `out`.
|
||||
unsafe extern "system" fn add_face(font: *const LOGFONTW, _: *const TEXTMETRICW, kind: u32, out: LPARAM) -> i32 {
|
||||
// SAFETY: GDI passes a valid font, and `out` is the list `enum_fonts` was given.
|
||||
let (Some(font), Some(out)) = (unsafe { font.as_ref() }, unsafe { (out.0 as *mut Vec<LOGFONTW>).as_mut() }) else {
|
||||
return 0;
|
||||
};
|
||||
if kind & RASTER_FONTTYPE == 0 {
|
||||
out.push(*font);
|
||||
}
|
||||
i32::from(out.len() < MAX_GDI_FONTS)
|
||||
}
|
||||
|
||||
/// `name`, NUL-padded, as a string.
|
||||
fn face_name(name: &[u16; 32]) -> String {
|
||||
String::from_utf16_lossy(name.split(|&c| c == 0).next().unwrap_or_default())
|
||||
}
|
||||
|
||||
/// The local files of the DirectWrite font face GDI uses for `font`.
|
||||
fn face_files(interop: &IDWriteGdiInterop, dc: &MemoryDc, font: &LOGFONTW) -> Vec<String> {
|
||||
// SAFETY: the font is selected into the guard's device context only while DirectWrite reads
|
||||
// it, then the context's own font goes back and the font is deleted; the files array is
|
||||
// sized from DirectWrite's count.
|
||||
unsafe {
|
||||
let gdi_font = CreateFontIndirectW(font);
|
||||
if gdi_font.is_invalid() {
|
||||
return Vec::new();
|
||||
}
|
||||
let first = SelectObject(dc.0, HGDIOBJ::from(gdi_font));
|
||||
let face = interop.CreateFontFaceFromHdc(dc.0);
|
||||
SelectObject(dc.0, first);
|
||||
// Failing to delete it leaks a handle, which there's nothing to do about.
|
||||
let _ = DeleteObject(HGDIOBJ::from(gdi_font));
|
||||
let Ok(face) = face else { return Vec::new() };
|
||||
let mut count = 0;
|
||||
if face.GetFiles(&mut count, None).is_err() || count == 0 || count > MAX_FACE_FILES {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut files = vec![None; count as usize];
|
||||
if face.GetFiles(&mut count, Some(files.as_mut_ptr())).is_err() {
|
||||
return Vec::new();
|
||||
}
|
||||
files.iter().flatten().filter_map(file_path).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// DirectWrite lists the installed fonts, by their files' full paths.
|
||||
@@ -89,4 +277,34 @@ mod tests {
|
||||
let fonts = std::path::Path::new(&std::env::var("WINDIR").unwrap()).join("Fonts").to_string_lossy().to_lowercase();
|
||||
assert!(files.iter().any(|f| f.to_lowercase().starts_with(&fonts)), "{} files, {:?}", files.len(), files.first());
|
||||
}
|
||||
|
||||
/// A font loaded with GDI from a file without an extension outside the font folders, as
|
||||
/// Creative Cloud loads Adobe Fonts, is listed by its file even though DirectWrite's collection
|
||||
/// doesn't hold it (#1258): fonts loaded for one process never are.
|
||||
#[test]
|
||||
fn fonts_only_gdi_has_loaded_are_listed_by_their_files() {
|
||||
use windows::Win32::Graphics::Gdi::{AddFontResourceExW, FR_PRIVATE, RemoveFontResourceExW};
|
||||
let dir = std::env::temp_dir().join(format!("vc-gdi-fonts-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("29457");
|
||||
let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/SourceSans3-Regular.ttf");
|
||||
let mut data = std::fs::read(source).unwrap();
|
||||
// Renamed (to a name as long) so no installed Source Sans 3 stands in for it.
|
||||
let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
|
||||
for (from, to) in [(utf16("Source Sans 3"), utf16("GdiOnly Sans3")), (b"Source Sans 3".to_vec(), b"GdiOnly Sans3".to_vec())] {
|
||||
let mut i = 0;
|
||||
while let Some(at) = data[i..].windows(from.len()).position(|w| w == from) {
|
||||
data[i + at..i + at + to.len()].copy_from_slice(&to);
|
||||
i += at + to.len();
|
||||
}
|
||||
}
|
||||
std::fs::write(&file, data).unwrap();
|
||||
let path = windows::core::HSTRING::from(file.as_os_str());
|
||||
assert_eq!(unsafe { AddFontResourceExW(&path, FR_PRIVATE, None) }, 1);
|
||||
let files = super::font_files();
|
||||
let _ = unsafe { RemoveFontResourceExW(&path, FR_PRIVATE.0, None) };
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let wanted = file.to_string_lossy().to_lowercase();
|
||||
assert!(files.iter().any(|f| f.to_lowercase() == wanted), "{wanted} not in {} files", files.len());
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,22 @@
|
||||
//! `vectorcraft --help` prints the usage and exits before the app starts (#2110): run from a
|
||||
//! terminal, SSH or an agent's shell it used to open the window (or hang without a display).
|
||||
|
||||
use std::io::Read;
|
||||
use std::process::{Command, Output, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const BIN: &str = env!("CARGO_BIN_EXE_vectorcraft");
|
||||
|
||||
/// Runs the desktop binary without a display, so a regression fails instead of opening a window.
|
||||
/// Runs the desktop binary without a display and with a control port it cannot parse, so a
|
||||
/// regression exits with that error instead of opening a window.
|
||||
fn run(args: &[&str], env: &[(&str, &str)]) -> Output {
|
||||
let mut child = Command::new(BIN)
|
||||
.args(args)
|
||||
.env_remove("DISPLAY")
|
||||
.env_remove("WAYLAND_DISPLAY")
|
||||
.env_remove("WAYLAND_SOCKET")
|
||||
.env_remove("VECTORCRAFT_CONTROL_PORT")
|
||||
.env("VECTORCRAFT_CONTROL_PORT", "not-a-port")
|
||||
.env("VECTORCRAFT_NO_PREFS", "1")
|
||||
.envs(env.iter().copied())
|
||||
.stdin(Stdio::null())
|
||||
@@ -21,15 +24,28 @@ fn run(args: &[&str], env: &[(&str, &str)]) -> Output {
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while child.try_wait().unwrap().is_none() {
|
||||
if Instant::now() >= deadline {
|
||||
child.kill().unwrap();
|
||||
panic!("{args:?}: the app started instead of printing its usage");
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
child.wait_with_output().unwrap()
|
||||
// Both pipes end when the binary exits, however long a loaded machine takes to start it. The
|
||||
// deadline only stops a binary that is still running.
|
||||
let deadline = Instant::now() + Duration::from_secs(120);
|
||||
let stdout = read_to_end(child.stdout.take().unwrap());
|
||||
let stderr = read_to_end(child.stderr.take().unwrap());
|
||||
let recv = |rx: &mpsc::Receiver<Vec<u8>>| rx.recv_timeout(deadline.saturating_duration_since(Instant::now()));
|
||||
let (Ok(stdout), Ok(stderr)) = (recv(&stdout), recv(&stderr)) else {
|
||||
child.kill().unwrap();
|
||||
panic!("{args:?}: the app started instead of printing its usage");
|
||||
};
|
||||
Output { status: child.wait().unwrap(), stdout, stderr }
|
||||
}
|
||||
|
||||
/// Reads `pipe` to its end on another thread.
|
||||
fn read_to_end(mut pipe: impl Read + Send + 'static) -> mpsc::Receiver<Vec<u8>> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let mut buf = Vec::new();
|
||||
let _ = pipe.read_to_end(&mut buf);
|
||||
let _ = tx.send(buf);
|
||||
});
|
||||
rx
|
||||
}
|
||||
|
||||
fn prints_usage(args: &[&str], env: &[(&str, &str)]) {
|
||||
|
||||
@@ -159,3 +159,13 @@ display_name = "Aditya Sisodiya"
|
||||
real_name = "Angelo Bernardini"
|
||||
display_name = "Angelo Bernardini"
|
||||
sync_github_name = false
|
||||
|
||||
[people.DCaioP]
|
||||
real_name = "Caio Pontes Magalhães"
|
||||
display_name = "Caio Pontes"
|
||||
sync_github_name = false
|
||||
|
||||
[people.xbirks]
|
||||
real_name = "Andrés Ortega Montoya"
|
||||
display_name = "Andrés Ortega Montoya"
|
||||
sync_github_name = false
|
||||
@@ -476,6 +476,18 @@ impl Brush {
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Brush::art`], to change (relink the resources it uses).
|
||||
pub fn art_mut(&mut self) -> Vec<&mut Node> {
|
||||
match &mut self.kind {
|
||||
BrushKind::Scatter(s) => vec![&mut s.art],
|
||||
BrushKind::Art(a) => vec![&mut a.art],
|
||||
BrushKind::Pattern(p) => std::iter::once(&mut p.side)
|
||||
.chain([&mut p.outer_corner, &mut p.inner_corner, &mut p.start, &mut p.end].into_iter().flatten())
|
||||
.collect(),
|
||||
BrushKind::Calligraphic(_) | BrushKind::Bristle(_) => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// A brush definition from JSON (a stored library entry or a command's params), its values
|
||||
/// kept within their ranges ([`Brush::sanitize`]). A Hue Shift colorization without a `key`
|
||||
/// takes the color the art's fills and strokes use most (the first of [`art_colors`]), or
|
||||
|
||||
+80
-1
@@ -621,6 +621,29 @@ pub struct SavedView {
|
||||
pub rotation: f64,
|
||||
}
|
||||
|
||||
impl SavedView {
|
||||
/// Most views a document keeps (the View menu lists every one).
|
||||
pub const MAX: usize = 25;
|
||||
/// Longest name, in characters.
|
||||
pub const MAX_NAME: usize = 255;
|
||||
|
||||
/// `name` trimmed and cut to [`Self::MAX_NAME`] characters (`None` when blank).
|
||||
pub fn clean_name(name: &str) -> Option<String> {
|
||||
let name: String = name.trim().chars().take(Self::MAX_NAME).collect();
|
||||
(!name.is_empty()).then_some(name)
|
||||
}
|
||||
|
||||
/// The first "View N" none of `saved` is named.
|
||||
pub fn default_name(saved: &[SavedView]) -> String {
|
||||
(1..=saved.len() + 1).map(|i| format!("View {i}")).find(|n| !saved.iter().any(|x| &x.name == n)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Can the canvas show this view: a finite centre and a finite, positive zoom.
|
||||
pub fn is_usable(&self) -> bool {
|
||||
self.center.x.is_finite() && self.center.y.is_finite() && self.zoom.is_finite() && self.zoom > 0.0
|
||||
}
|
||||
}
|
||||
|
||||
/// A saved selection (Select → Save Selection…): the objects that were selected, listed by name at
|
||||
/// the bottom of the Select menu.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -851,7 +874,7 @@ pub struct Document {
|
||||
pub graph_designs: Vec<GraphDesign>,
|
||||
#[serde(default)]
|
||||
pub guides: Vec<Guide>,
|
||||
/// View → New View… (up to 25, like Illustrator).
|
||||
/// View → New View… (at most [`SavedView::MAX`]); saved with the document.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub views: Vec<SavedView>,
|
||||
/// Select → Save Selection… (at most [`SavedSelection::MAX`]); saved with the document.
|
||||
@@ -1843,6 +1866,40 @@ impl Document {
|
||||
}
|
||||
art
|
||||
}
|
||||
/// Does any artwork lie on `rect` (an artboard)? Artwork is any object under the layers,
|
||||
/// hidden and locked ones and those on template layers included, whose visual bounds (symbol
|
||||
/// instances measured by their art) meet `rect`; touching its edge counts. A group (not a clip
|
||||
/// group) counts by its members, so one whose members sit on two other artboards leaves the one
|
||||
/// between them empty. A clip group or clipping layer counts by its members inside its clip (and
|
||||
/// by its clipping path where that paints). Guides (paths made into guides too) aren't artwork
|
||||
/// (Delete Empty Artboards).
|
||||
pub fn artboard_has_art(&self, rect: Rect) -> bool {
|
||||
// As in `art_on_artboard`: a millionth of a point covers rounding at the edges.
|
||||
let rect = rect.inflate(1e-6, 1e-6);
|
||||
fn meets(b: Option<Rect>, r: Rect) -> bool {
|
||||
b.is_some_and(|b| b.x0 <= r.x1 && r.x0 <= b.x1 && b.y0 <= r.y1 && r.y0 <= b.y1)
|
||||
}
|
||||
fn has(c: &Node, s: &SymbolBoxes, rect: Rect) -> bool {
|
||||
match &c.kind {
|
||||
NodeKind::Group { children, clip: true } | NodeKind::Layer { children, clip: true, .. } => {
|
||||
let Some((clip, rest)) = children.split_first() else { return false };
|
||||
let paint = clip.clip_paint();
|
||||
if (paint.fill.is_some() || paint.stroke.is_some()) && meets(clip.visual_bounds_with(s), rect) {
|
||||
return true;
|
||||
}
|
||||
// The members show only inside the clip's box.
|
||||
let Some(b) = c.visual_bounds_with(s).filter(|b| meets(Some(*b), rect)) else { return false };
|
||||
let inside = Rect::new(b.x0.max(rect.x0), b.y0.max(rect.y0), b.x1.min(rect.x1), b.y1.min(rect.y1));
|
||||
rest.iter().any(|m| has(m, s, inside))
|
||||
}
|
||||
NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().any(|m| has(m, s, rect)),
|
||||
NodeKind::Path { guide: true, .. } => false,
|
||||
_ => meets(c.visual_bounds_with(s), rect),
|
||||
}
|
||||
}
|
||||
let symbols = self.symbol_boxes();
|
||||
self.layers.iter().any(|l| has(l, &symbols, rect))
|
||||
}
|
||||
/// The art that moves, scales or is cut with artboard `index`: [`Document::art_on_artboard`]
|
||||
/// without the objects on another locked artboard, which stay unless `locked_and_hidden`, as
|
||||
/// locked art does.
|
||||
@@ -2100,6 +2157,28 @@ impl Document {
|
||||
self.saved_selections = kept.into();
|
||||
}
|
||||
|
||||
/// Saved views as a file gives them, made safe to list and go to: at most [`SavedView::MAX`],
|
||||
/// each with a clean, unique name, a finite centre and a finite, positive zoom (a rotation
|
||||
/// that isn't finite becomes 0°).
|
||||
pub fn tidy_views(&mut self) {
|
||||
if self.views.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut kept: Vec<SavedView> = vec![];
|
||||
for v in std::mem::take(&mut self.views) {
|
||||
if kept.len() >= SavedView::MAX {
|
||||
break;
|
||||
}
|
||||
let Some(name) = SavedView::clean_name(&v.name) else { continue };
|
||||
if !v.is_usable() || kept.iter().any(|k| k.name == name) {
|
||||
continue;
|
||||
}
|
||||
let rotation = if v.rotation.is_finite() { v.rotation } else { 0.0 };
|
||||
kept.push(SavedView { name, rotation, ..v });
|
||||
}
|
||||
self.views = kept;
|
||||
}
|
||||
|
||||
/// Leave opacity-mask editing: drop the temporary editing layer, a working copy of art the
|
||||
/// mask already holds (the engine syncs it after every edit).
|
||||
pub fn drop_edit_modes(&mut self) {
|
||||
|
||||
@@ -0,0 +1,502 @@
|
||||
//! Brush libraries (Window → Brush Libraries, the Brushes panel's library button): read-only sets
|
||||
//! of brushes the library panel shows. A library is a document holding the brushes with the
|
||||
//! resources their art uses (patterns, symbols, swatches, graphic styles, images); saved, it is a
|
||||
//! native `.vectorcraft` file, which File › Open also opens. The built-in libraries are generated
|
||||
//! here ([`BUILTIN`]); User Defined ones are the `.vectorcraft` files in the user library folder
|
||||
//! ([`Libraries`]), and Other Library… loads the brushes of any document VectorCraft opens.
|
||||
//! `brush.addFromLibrary` copies brushes into the document; `brush.saveLibrary` writes the
|
||||
//! document's.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::{Arc, LazyLock};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_brush::{self as brush, ArtBrush, Brush, BrushKind, Calligraphic, Colorization, PatternBrush, PatternFit, Scatter, Variation};
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeId, NodeKind, PatternDef, Symbol};
|
||||
use vectorcraft_geom::{Affine, FillRule, PathData, Point, Rect, SubPath, shapes};
|
||||
|
||||
use super::brushsym::{apply_brush, brush_targets, roots, stroke_paint};
|
||||
use super::clipboard::Clipboard;
|
||||
use super::clipboard::resources::SwatchChoices;
|
||||
use super::patterncmds::add_pattern;
|
||||
use super::swatch::str_list;
|
||||
use super::swatchlib::{FileData, LibraryFile, LibraryInfo, stem};
|
||||
use super::*;
|
||||
|
||||
/// The extension of saved brush libraries: native documents.
|
||||
pub const BRUSHES_EXT: &str = vectorcraft_format::EXTENSION;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
query "brush.libraries",
|
||||
"Brush Libraries",
|
||||
[],
|
||||
None,
|
||||
"{} → {libraries: [{id, name, category: \"builtIn\"|\"user\" (User Defined: the .vectorcraft files in the user library folder, rescanned now)|\"loaded\" (brush.loadLibrary), count, path?}], userFolder} every brush library the library panel opens, in menu order",
|
||||
always,
|
||||
list
|
||||
),
|
||||
cmd!(
|
||||
query "brush.library",
|
||||
"Brush Library",
|
||||
[],
|
||||
None,
|
||||
"{library: id or name} → {id, name, category, brushes: [{name, type}] (as brush.list)}",
|
||||
always,
|
||||
get
|
||||
),
|
||||
cmd!(
|
||||
"brush.addFromLibrary",
|
||||
"Add to Brushes",
|
||||
["Window", "Brush Libraries"],
|
||||
None,
|
||||
"{library: id or name, name? | names?: [brush names in the library] (default: all of it), apply?: false (also apply the first one to paths, as brush.apply does), ids?|id? (the paths apply takes; default the selected ones), swatchConflict? (as edit.paste)} copy library brushes into the document's Brushes as one undo step (with the apply; named Apply Brush when no brush is added and it only applies one), with the resources their art uses (patterns, symbols, swatches, graphic styles, images). A brush the document already has (same name and definition) isn't added again; a name another brush has gets a number (\"Ribbon 2\"). The first one becomes the current brush → {library, names: [each brush's name in the document], added: [names added], existing: [names already there], applied: [ids of the paths it was applied to]}",
|
||||
has_doc,
|
||||
add
|
||||
),
|
||||
cmd!(
|
||||
"brush.saveLibrary",
|
||||
"Save Brush Library…",
|
||||
["Window", "Brushes"],
|
||||
None,
|
||||
"{path?, names?: [brush names] (default: all), name?: library name (default: the document's), user?: false (save into the user library folder, listed under User Defined)} save the document's brushes, with the resources their art uses, as a brush library: a .vectorcraft document holding only them → {path, count, library?: id when saved to the user folder}; without path or user → {dataBase64: the file's bytes, count}",
|
||||
has_doc,
|
||||
save
|
||||
),
|
||||
cmd!(
|
||||
"brush.loadLibrary",
|
||||
"Other Library…",
|
||||
["Window", "Brush Libraries"],
|
||||
None,
|
||||
"{path? | data?: file text | dataBase64?, name?: file name (default: the path's)} load the brushes of any document VectorCraft opens (see document.formats; one without brushes of its own has the default ones), a saved brush library included, for the library panel (Window → Brush Libraries lists it until the app quits; a file of the user library folder, or a file with the same bytes as one there, opens as that User Defined library) → {library: id, name, count}",
|
||||
always,
|
||||
load
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// A brush library: its name, its brushes (in panel order) and a document holding them with the
|
||||
/// resources their art uses; the document has no art of its own.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct BrushLibrary {
|
||||
pub name: String,
|
||||
pub brushes: Vec<Brush>,
|
||||
pub doc: Document,
|
||||
}
|
||||
|
||||
impl Default for BrushLibrary {
|
||||
fn default() -> Self {
|
||||
Self { name: String::new(), brushes: vec![], doc: Document::new(100.0, 100.0) }
|
||||
}
|
||||
}
|
||||
|
||||
impl BrushLibrary {
|
||||
pub fn len(&self) -> usize {
|
||||
self.brushes.len()
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.brushes.is_empty()
|
||||
}
|
||||
pub fn brush(&self, name: &str) -> Option<&Brush> {
|
||||
self.brushes.iter().find(|b| b.name == name)
|
||||
}
|
||||
|
||||
/// Document `src`'s brushes `names` (empty: all of them, in panel order) as a library named
|
||||
/// `name`: the brushes and every resource their art uses.
|
||||
pub fn from_document(src: &Document, names: &[String], name: String) -> std::result::Result<Self, String> {
|
||||
let all = brush::library(src);
|
||||
if let Some(n) = names.iter().find(|n| !all.iter().any(|b| b.name == **n)) {
|
||||
return Err(format!("no brush `{n}`"));
|
||||
}
|
||||
let picked = all.iter().filter(|b| names.is_empty() || names.contains(&b.name));
|
||||
let clip = Clipboard::gather(src, picked.map(|b| stroke(&b.name)).collect());
|
||||
let mut doc = clip.to_document();
|
||||
for l in &mut doc.layers {
|
||||
if let Some(ch) = Arc::make_mut(l).children_mut() {
|
||||
ch.clear();
|
||||
}
|
||||
}
|
||||
// The brushes picked and those their art paints with, in the panel order of the document
|
||||
// they came from.
|
||||
let brushes: Vec<Brush> = all.into_iter().filter(|b| clip.brushes.iter().any(|c| c.name == b.name)).collect();
|
||||
brush::store(&mut doc, &brushes);
|
||||
doc.title = name.clone();
|
||||
Ok(Self { name, brushes, doc })
|
||||
}
|
||||
}
|
||||
|
||||
impl LibraryFile for BrushLibrary {
|
||||
const EXTS: &'static [&'static str] = &[BRUSHES_EXT];
|
||||
fn read(bytes: &[u8], stem: &str) -> std::result::Result<Self, String> {
|
||||
let doc = vectorcraft_format::load(bytes).map_err(|e| e.to_string())?;
|
||||
BrushLibrary::from_document(&doc, &[], stem.to_string())
|
||||
}
|
||||
fn name(&self) -> &str {
|
||||
&self.name
|
||||
}
|
||||
}
|
||||
|
||||
/// User Defined and loaded brush libraries.
|
||||
pub type Libraries = super::swatchlib::Libraries<BrushLibrary>;
|
||||
|
||||
/// A path stroked with brush `name` (what the resource gathering follows).
|
||||
fn stroke(name: &str) -> Node {
|
||||
let mut ap = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
if let Some(st) = ap.stroke_mut() {
|
||||
st.brush = Some(name.into());
|
||||
}
|
||||
let line = SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(100.0, 0.0)], false);
|
||||
Node::path(NodeId(0), PathData::single(line), ap)
|
||||
}
|
||||
|
||||
// ---------- built-in libraries ----------
|
||||
|
||||
/// A library generated in code.
|
||||
pub struct BuiltinBrushLibrary {
|
||||
pub id: &'static str,
|
||||
pub name: &'static str,
|
||||
make: fn() -> BrushLibrary,
|
||||
}
|
||||
|
||||
/// The built-in brush libraries, in menu order: original brushes generated in code, one library
|
||||
/// per kind of brush.
|
||||
pub const BUILTIN: &[BuiltinBrushLibrary] = &[
|
||||
BuiltinBrushLibrary { id: "art-ribbons", name: "Art Ribbons", make: art_ribbons },
|
||||
BuiltinBrushLibrary { id: "calligraphic-nibs", name: "Calligraphic Nibs", make: calligraphic_nibs },
|
||||
BuiltinBrushLibrary { id: "pattern-borders", name: "Pattern Borders", make: pattern_borders },
|
||||
BuiltinBrushLibrary { id: "scatter-shapes", name: "Scatter Shapes", make: scatter_shapes },
|
||||
];
|
||||
|
||||
/// Built-in library `id`, made once.
|
||||
fn builtin_library(id: &str) -> Option<Arc<BrushLibrary>> {
|
||||
static MADE: LazyLock<Vec<Arc<BrushLibrary>>> = LazyLock::new(|| BUILTIN.iter().map(|b| Arc::new((b.make)())).collect());
|
||||
BUILTIN.iter().position(|b| b.id == id).and_then(|i| MADE.get(i).cloned())
|
||||
}
|
||||
|
||||
/// Library `name` of `brushes`, `doc` holding the resources their art uses.
|
||||
fn built(name: &str, mut doc: Document, brushes: Vec<Brush>) -> BrushLibrary {
|
||||
brush::store(&mut doc, &brushes);
|
||||
doc.title = name.into();
|
||||
BrushLibrary { name: name.into(), brushes, doc }
|
||||
}
|
||||
|
||||
fn filled(p: PathData, paint: Paint) -> Node {
|
||||
Node::path(NodeId(0), p, Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(paint))], ..Default::default() })
|
||||
}
|
||||
|
||||
fn black(p: PathData) -> Node {
|
||||
filled(p, Paint::solid(Color::BLACK))
|
||||
}
|
||||
|
||||
fn group(children: Vec<Node>) -> Node {
|
||||
Node::group(NodeId(0), children.into_iter().map(Arc::new).collect())
|
||||
}
|
||||
|
||||
fn polygon(pts: &[(f64, f64)]) -> PathData {
|
||||
let pts: Vec<Point> = pts.iter().map(|&(x, y)| Point::new(x, y)).collect();
|
||||
PathData::single(SubPath::polyline(&pts, true))
|
||||
}
|
||||
|
||||
/// A band along y = `f(x)` for x in 0..`len`, `thick` pt thick, in `n` steps.
|
||||
fn band(len: f64, thick: f64, n: usize, f: impl Fn(f64) -> f64) -> PathData {
|
||||
let xs: Vec<f64> = (0..=n).map(|i| len * i as f64 / n as f64).collect();
|
||||
let mut pts: Vec<Point> = xs.iter().map(|&x| Point::new(x, f(x) - thick / 2.0)).collect();
|
||||
pts.extend(xs.iter().rev().map(|&x| Point::new(x, f(x) + thick / 2.0)));
|
||||
PathData::single(SubPath::polyline(&pts, true))
|
||||
}
|
||||
|
||||
/// An even-odd ring of radii `outer` and `inner` around `c`.
|
||||
fn ring(c: Point, outer: f64, inner: f64) -> Node {
|
||||
let disc = |r: f64| shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r));
|
||||
let children = [disc(outer), disc(inner)].into_iter().map(|p| Arc::new(Node::path(NodeId(0), p, Appearance::default()))).collect();
|
||||
let mut n = Node::new(NodeId(0), NodeKind::Compound { children, rule: FillRule::EvenOdd });
|
||||
n.appearance = Appearance { items: vec![AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::BLACK)))], ..Default::default() }.into();
|
||||
n
|
||||
}
|
||||
|
||||
fn art(name: &str, art: Node, colorization: Colorization) -> Brush {
|
||||
Brush { name: name.into(), kind: BrushKind::Art(ArtBrush { art, colorization, ..Default::default() }) }
|
||||
}
|
||||
|
||||
/// Art Ribbons: art brushes, 100 pt long, drawn here; Striped Ribbon is filled with the library's
|
||||
/// own pattern, Pinstripes.
|
||||
fn art_ribbons() -> BrushLibrary {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
let stripe = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 6.0, 1.5)), {
|
||||
let mut a = Appearance::default();
|
||||
a.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(Color::from_hex("#2f80c9").unwrap_or(Color::BLACK)))));
|
||||
a
|
||||
});
|
||||
add_pattern(&mut doc, PatternDef { tile: Rect::new(0.0, 0.0, 6.0, 3.0), ..PatternDef::new("Pinstripes", vec![Arc::new(stripe)]) });
|
||||
let notched = polygon(&[(0.0, -3.0), (100.0, -3.0), (95.0, 0.0), (100.0, 3.0), (0.0, 3.0), (5.0, 0.0)]);
|
||||
let double = group(vec![black(shapes::rectangle(Rect::new(0.0, -2.5, 100.0, -1.5))), black(shapes::rectangle(Rect::new(0.0, 1.5, 100.0, 2.5)))]);
|
||||
let wave = band(100.0, 1.6, 64, |x| 2.5 * (x / 100.0 * 4.0 * std::f64::consts::TAU).sin());
|
||||
// Round and thick at the start, tapering to a point.
|
||||
let teardrop = {
|
||||
let n = 48;
|
||||
let half = |x: f64| 3.5 * (1.0 - x / 100.0).powf(0.8) * (x / 4.0).min(1.0).sqrt();
|
||||
let xs = |i: usize| 100.0 * i as f64 / n as f64;
|
||||
let mut pts: Vec<Point> = (0..=n).map(xs).map(|x| Point::new(x, -half(x))).collect();
|
||||
pts.extend((0..n).rev().map(xs).map(|x| Point::new(x, half(x))));
|
||||
PathData::single(SubPath::polyline(&pts, true))
|
||||
};
|
||||
let striped = {
|
||||
let mut n =
|
||||
filled(shapes::rectangle(Rect::new(0.0, -4.0, 100.0, 4.0)), Paint::Pattern { pattern: "Pinstripes".into(), xf: Default::default() });
|
||||
n.appearance.set_stroke(Paint::solid(Color::from_hex("#1d4f7c").unwrap_or(Color::BLACK)));
|
||||
n
|
||||
};
|
||||
let brushes = vec![
|
||||
art("Notched Ribbon", black(notched), Colorization::Tints),
|
||||
art("Double Line", double, Colorization::Tints),
|
||||
art("Wave", black(wave), Colorization::Tints),
|
||||
art("Teardrop", black(teardrop), Colorization::Tints),
|
||||
art("Striped Ribbon", striped, Colorization::None),
|
||||
];
|
||||
built("Art Ribbons", doc, brushes)
|
||||
}
|
||||
|
||||
fn nib(name: &str, angle: f64, roundness: f64, size: f64) -> Brush {
|
||||
Brush { name: name.into(), kind: BrushKind::Calligraphic(Calligraphic { angle, roundness, size, ..Default::default() }) }
|
||||
}
|
||||
|
||||
/// Calligraphic Nibs: pen nibs of several shapes; Pressure Pen's size follows the pen pressure.
|
||||
fn calligraphic_nibs() -> BrushLibrary {
|
||||
let pressure = Brush {
|
||||
name: "Pressure Pen".into(),
|
||||
kind: BrushKind::Calligraphic(Calligraphic {
|
||||
angle: 30.0,
|
||||
roundness: 60.0,
|
||||
size: 5.0,
|
||||
variation: [0.0, 0.0, 4.0],
|
||||
modes: Some([Variation::Fixed, Variation::Fixed, Variation::Pressure]),
|
||||
}),
|
||||
};
|
||||
let brushes = vec![
|
||||
nib("Fine Nib", 45.0, 25.0, 2.0),
|
||||
nib("Broad Nib", 45.0, 15.0, 9.0),
|
||||
nib("Chisel", 0.0, 8.0, 6.0),
|
||||
nib("Round Pen", 0.0, 100.0, 4.0),
|
||||
pressure,
|
||||
];
|
||||
built("Calligraphic Nibs", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
fn border(name: &str, side: Node, corner: Option<Node>, fit: PatternFit) -> Brush {
|
||||
let kind = BrushKind::Pattern(PatternBrush { side, outer_corner: corner.clone(), inner_corner: corner, fit, ..Default::default() });
|
||||
Brush { name: name.into(), kind }
|
||||
}
|
||||
|
||||
/// An invisible rectangle that fixes a tile's width.
|
||||
fn spacer(r: Rect) -> Node {
|
||||
Node::path(NodeId(0), shapes::rectangle(r), Appearance::default())
|
||||
}
|
||||
|
||||
/// Pattern Borders: pattern brushes of tiles drawn here; Beads has corner tiles.
|
||||
fn pattern_borders() -> BrushLibrary {
|
||||
let zigzag = black(polygon(&[(0.0, 1.4), (5.0, -2.6), (10.0, 1.4), (10.0, 2.6), (5.0, -1.4), (0.0, 2.6)]));
|
||||
let beads = group(vec![black(shapes::rectangle(Rect::new(0.0, -0.3, 8.0, 0.3))), black(shapes::ellipse(Rect::new(1.5, -2.5, 6.5, 2.5)))]);
|
||||
let dash_dot = group(vec![
|
||||
spacer(Rect::new(0.0, -1.0, 12.0, 1.0)),
|
||||
black(shapes::rounded_rectangle(Rect::new(0.5, -0.75, 6.5, 0.75), 0.75)),
|
||||
black(shapes::ellipse(Rect::new(8.5, -1.0, 10.5, 1.0))),
|
||||
]);
|
||||
let scallops = black(band(10.0, 1.0, 20, |x| -3.0 * (x / 10.0 * std::f64::consts::PI).sin()));
|
||||
let brushes = vec![
|
||||
border("Zigzag", zigzag, None, PatternFit::Stretch),
|
||||
border("Beads", beads, Some(ring(Point::ZERO, 3.5, 1.5)), PatternFit::Stretch),
|
||||
border("Dash Dot", dash_dot, None, PatternFit::AddSpace),
|
||||
border("Scallops", scallops, None, PatternFit::Stretch),
|
||||
];
|
||||
built("Pattern Borders", Document::new(100.0, 100.0), brushes)
|
||||
}
|
||||
|
||||
fn scatter(name: &str, art: Node, s: Scatter) -> Brush {
|
||||
Brush { name: name.into(), kind: BrushKind::Scatter(Scatter { art, ..s }) }
|
||||
}
|
||||
|
||||
/// Scatter Shapes: scatter brushes of shapes drawn here; Sparkles scatters the library's own
|
||||
/// symbol, Sparkle.
|
||||
fn scatter_shapes() -> BrushLibrary {
|
||||
let mut doc = Document::new(100.0, 100.0);
|
||||
// A four-pointed gold sparkle in the ±10 pt box symbol instances assume.
|
||||
let points: Vec<Point> = (0..8)
|
||||
.map(|i| {
|
||||
let r = if i % 2 == 0 { 10.0 } else { 2.5 };
|
||||
let a = std::f64::consts::FRAC_PI_4 * i as f64;
|
||||
Point::new(r * a.cos(), r * a.sin())
|
||||
})
|
||||
.collect();
|
||||
let gold = Color::from_hex("#e0a526").unwrap_or(Color::BLACK);
|
||||
let sparkle = Node::path(doc.alloc_id(), PathData::single(SubPath::polyline(&points, true)), {
|
||||
let mut a = Appearance::default();
|
||||
a.items.push(AppearanceItem::Fill(FillLayer::new(Paint::solid(gold))));
|
||||
a
|
||||
});
|
||||
doc.symbols.push(Symbol { name: "Sparkle".into(), art: Arc::new(sparkle) });
|
||||
let instance = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Sparkle".into(), xf: Affine::scale(0.3) });
|
||||
let random = |a: f64, b: f64| (a, b);
|
||||
let base = Scatter { colorization: Colorization::Tints, ..Default::default() };
|
||||
let brushes = vec![
|
||||
scatter(
|
||||
"Stars",
|
||||
black(shapes::star(Point::ZERO, 4.0, 1.7, 5, 0.0)),
|
||||
Scatter {
|
||||
size: random(70.0, 130.0),
|
||||
spacing: random(150.0, 220.0),
|
||||
scatter: random(-80.0, 80.0),
|
||||
rotation: random(-180.0, 180.0),
|
||||
..base.clone()
|
||||
},
|
||||
),
|
||||
scatter("Rings", ring(Point::ZERO, 2.5, 1.5), Scatter { spacing: (140.0, 140.0), ..base.clone() }),
|
||||
scatter(
|
||||
"Triangles",
|
||||
black(shapes::polygon(Point::ZERO, 3.0, 3, 0.0)),
|
||||
Scatter { spacing: (120.0, 120.0), rotation: (90.0, 90.0), rotation_relative_to_path: true, ..base.clone() },
|
||||
),
|
||||
scatter(
|
||||
"Sparkles",
|
||||
instance,
|
||||
Scatter {
|
||||
size: random(60.0, 140.0),
|
||||
spacing: random(110.0, 180.0),
|
||||
scatter: random(-60.0, 60.0),
|
||||
rotation: random(-45.0, 45.0),
|
||||
colorization: Colorization::None,
|
||||
..base
|
||||
},
|
||||
),
|
||||
];
|
||||
built("Scatter Shapes", doc, brushes)
|
||||
}
|
||||
|
||||
// ---------- commands ----------
|
||||
|
||||
fn builtin_info(b: &BuiltinBrushLibrary) -> LibraryInfo {
|
||||
LibraryInfo { id: b.id.into(), name: b.name.into(), category: "builtIn" }
|
||||
}
|
||||
|
||||
/// Every brush library, in menu order: built-in, User Defined, loaded.
|
||||
pub fn libraries(s: &Session) -> Vec<LibraryInfo> {
|
||||
BUILTIN.iter().map(builtin_info).chain(s.brush_libraries.infos().cloned()).collect()
|
||||
}
|
||||
|
||||
/// Library `key` (an id, or a name in any case) with its info.
|
||||
pub fn library(s: &Session, key: &str) -> Option<(LibraryInfo, Arc<BrushLibrary>)> {
|
||||
if let Some(found) = s.brush_libraries.get(key) {
|
||||
return Some(found);
|
||||
}
|
||||
if let Some(b) = BUILTIN.iter().find(|b| b.id == key) {
|
||||
return Some((builtin_info(b), builtin_library(key)?));
|
||||
}
|
||||
let id = libraries(s).into_iter().find(|l| l.name.eq_ignore_ascii_case(key))?.id;
|
||||
library(s, &id)
|
||||
}
|
||||
|
||||
fn library_param(s: &Session, p: &Value, cmd: &str) -> Result<(LibraryInfo, Arc<BrushLibrary>)> {
|
||||
let key = str_param(p, "library").ok_or_else(|| bad(cmd, "missing `library` (see brush.libraries)"))?;
|
||||
library(s, key).ok_or_else(|| bad(cmd, format!("no brush library `{key}` (see brush.libraries)")))
|
||||
}
|
||||
|
||||
fn list(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
s.brush_libraries.rescan();
|
||||
let libs: Vec<Value> = libraries(s)
|
||||
.into_iter()
|
||||
.map(|l| {
|
||||
let count = library(s, &l.id).map_or(0, |(_, lib)| lib.len());
|
||||
json!({"id": l.id, "name": l.name, "category": l.category, "count": count, "path": s.brush_libraries.path(&l.id)})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({ "libraries": libs, "userFolder": s.brush_libraries.user_dir() }))
|
||||
}
|
||||
|
||||
fn get(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (info, lib) = library_param(s, p, "brush.library")?;
|
||||
let brushes: Vec<Value> = lib.brushes.iter().map(|b| json!({"name": b.name, "type": b.kind.type_id()})).collect();
|
||||
Ok(json!({"id": info.id, "name": info.name, "category": info.category, "brushes": brushes}))
|
||||
}
|
||||
|
||||
fn add(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.addFromLibrary";
|
||||
let (info, lib) = library_param(s, p, C)?;
|
||||
let mut names = str_list(p, "names");
|
||||
names.extend(str_param(p, "name").map(str::to_string));
|
||||
if let Some(n) = names.iter().find(|n| lib.brush(n).is_none()) {
|
||||
return Err(bad(C, format!("no brush `{n}` in `{}`", lib.name)));
|
||||
}
|
||||
let mut picked: Vec<String> = if names.is_empty() { lib.brushes.iter().map(|b| b.name.clone()).collect() } else { names };
|
||||
// Each once, in the order asked for.
|
||||
let mut seen = HashSet::new();
|
||||
picked.retain(|n| seen.insert(n.clone()));
|
||||
let apply = bool_or(p, "apply", false);
|
||||
if apply && picked.is_empty() {
|
||||
return Err(bad(C, format!("`{}` has no brushes to apply", lib.name)));
|
||||
}
|
||||
let choices = SwatchChoices::parse(C, p)?;
|
||||
let clip = Clipboard::gather(&lib.doc, picked.iter().map(|n| stroke(n)).collect());
|
||||
// The typing `s.edit` would settle first is settled before the probe below, so the document
|
||||
// the edit installs is the one it starts from.
|
||||
if !s.previewing && super::typing_in_progress(s) {
|
||||
super::settle_interaction(s)?;
|
||||
}
|
||||
let st = s.doc()?;
|
||||
let before: HashSet<String> = brush::library(&st.doc).into_iter().map(|b| b.name).collect();
|
||||
// A library brush's name in the document: its own, or the one the import gave it.
|
||||
let target = |renamed: &[Value], n: &str| -> String {
|
||||
let to = renamed.iter().find(|r| r["kind"] == "brush" && r["from"] == n).and_then(|r| r["to"].as_str());
|
||||
to.unwrap_or(n).to_string()
|
||||
};
|
||||
// Where the brushes land, worked out on a copy that the edit then installs: nothing to add and
|
||||
// nothing to apply is no edit, and a click that only applies brushes the document has is
|
||||
// named for that.
|
||||
let mut probe = (*st.doc).clone();
|
||||
let imported = clip.import_into(&mut probe, &choices, false);
|
||||
let doc_names: Vec<String> = picked.iter().map(|n| target(&imported.renamed, n)).collect();
|
||||
let paths = if apply { brush_targets(&st.doc, &roots(s, p)?) } else { vec![] };
|
||||
let paint = stroke_paint(s);
|
||||
if imported.added > 0 || !paths.is_empty() {
|
||||
let label = if imported.added > 0 { "Add to Brushes" } else { "Apply Brush" };
|
||||
s.edit(label, |d, _| {
|
||||
*d = probe;
|
||||
if let Some(first) = doc_names.first() {
|
||||
d.unknown.insert(brush::CURRENT_KEY.into(), json!(first));
|
||||
apply_brush(d, &paths, first, &paint);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
} else if let Some(first) = doc_names.first() {
|
||||
s.execute("brush.setCurrent", &json!({ "name": first }))?;
|
||||
}
|
||||
let (added, existing): (Vec<&String>, Vec<&String>) = doc_names.iter().partition(|n| !before.contains(*n));
|
||||
let applied: Vec<u64> = paths.iter().map(|id| id.0).collect();
|
||||
Ok(json!({"library": info.id, "names": doc_names, "added": added, "existing": existing, "applied": applied}))
|
||||
}
|
||||
|
||||
fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.saveLibrary";
|
||||
let st = s.doc()?;
|
||||
let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).map_or_else(|| stem(&st.title()).to_string(), str::to_string);
|
||||
let lib = BrushLibrary::from_document(&st.doc, &str_list(p, "names"), name).map_err(|e| bad(C, e))?;
|
||||
if lib.is_empty() {
|
||||
return Err(bad(C, "the document has no brushes to save"));
|
||||
}
|
||||
let mut out = json!({ "count": lib.len() });
|
||||
let bytes = vectorcraft_format::save_file(&lib.doc);
|
||||
s.brush_libraries.write(p, &lib.name, BRUSHES_EXT, FileData::Binary(bytes), &mut out, C)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn load(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.loadLibrary";
|
||||
let (info, lib) = s.brush_libraries.load(p, C, |bytes, file| {
|
||||
let loaded = super::fileio::load(file, bytes).map_err(|e| bad(C, e.to_string()))?;
|
||||
if loaded.preview_only {
|
||||
return Err(bad(C, "only this Affinity file's embedded preview could be read; use File › Open to see it with its warning"));
|
||||
}
|
||||
BrushLibrary::from_document(&loaded.doc, &[], stem(file).to_string()).map_err(|e| bad(C, e))
|
||||
})?;
|
||||
Ok(json!({"library": info.id, "name": info.name, "count": lib.len()}))
|
||||
}
|
||||
@@ -249,7 +249,7 @@ fn ids_json(ids: &[NodeId]) -> Value {
|
||||
Value::Array(ids.iter().map(|i| Value::from(i.0)).collect())
|
||||
}
|
||||
|
||||
fn roots(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
pub(crate) fn roots(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
match ids_param(p, "ids").or_else(|| id_param(p, "id").map(|i| vec![i])) {
|
||||
Some(mut v) => {
|
||||
// Explicit ids: only existing, non-layer objects, none inside another of them.
|
||||
@@ -269,7 +269,7 @@ fn name_param<'a>(p: &'a Value, cmd: &str) -> Result<&'a str> {
|
||||
// ---------- brushes ----------
|
||||
|
||||
/// Brushable nodes (paths and compound paths) under `ids`.
|
||||
fn brush_targets(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
pub(crate) fn brush_targets(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
let Some(n) = d.node(*id) else { continue };
|
||||
@@ -302,6 +302,27 @@ fn brush_selection_art(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "art": art.map(|n| serde_json::to_value(&n).unwrap_or_default()) }))
|
||||
}
|
||||
|
||||
/// The stroke paint a brush gives paths without one: the current stroke colour, else black.
|
||||
pub(crate) fn stroke_paint(s: &Session) -> Paint {
|
||||
if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() }
|
||||
}
|
||||
|
||||
/// Paint paths `ids` of `d` with brush `name` (a path without a stroke takes `stroke`).
|
||||
pub(crate) fn apply_brush(d: &mut Document, ids: &[NodeId], name: &str, stroke: &Paint) {
|
||||
for id in ids {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
if n.appearance.stroke().is_none_or(|st| st.paint.is_none()) {
|
||||
n.appearance.set_stroke(stroke.clone());
|
||||
}
|
||||
if let Some(st) = n.appearance.stroke_mut() {
|
||||
if st.width <= 0.0 {
|
||||
st.width = 1.0;
|
||||
}
|
||||
st.brush = Some(name.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn brush_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "brush.apply";
|
||||
let name = name_param(p, C)?.to_string();
|
||||
@@ -309,21 +330,10 @@ fn brush_apply(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return Err(bad(C, format!("no brush named `{name}`")));
|
||||
}
|
||||
let ids = brush_targets(&s.doc()?.doc, &roots(s, p)?);
|
||||
let stroke = if s.paint.stroke.is_none() { Paint::solid(Color::BLACK) } else { s.paint.stroke.clone() };
|
||||
let stroke = stroke_paint(s);
|
||||
s.edit("Apply Brush", |d, _| {
|
||||
d.unknown.insert(brush::CURRENT_KEY.into(), json!(name));
|
||||
for id in &ids {
|
||||
let Some(n) = d.node_mut(*id) else { continue };
|
||||
if n.appearance.stroke().is_none_or(|st| st.paint.is_none()) {
|
||||
n.appearance.set_stroke(stroke.clone());
|
||||
}
|
||||
if let Some(st) = n.appearance.stroke_mut() {
|
||||
if st.width <= 0.0 {
|
||||
st.width = 1.0;
|
||||
}
|
||||
st.brush = Some(name.clone());
|
||||
}
|
||||
}
|
||||
apply_brush(d, &ids, &name, &stroke);
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&ids) }))
|
||||
|
||||
@@ -23,6 +23,7 @@ use vectorcraft_geom::Rect;
|
||||
|
||||
pub use flavours::{AI, BITMAP, EMF, EPS, FILE_HEAD, Flavour, PASTE_ORDER, PDF, PNG, SVG, TEXT, file_flavour, is_address, names_a_picture};
|
||||
pub(crate) use resources::SwatchChoices;
|
||||
pub use resources::{ArtResources, art_resources};
|
||||
|
||||
use super::*;
|
||||
use crate::DocState;
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//!
|
||||
//! Objects refer to resources by name (image blobs, symbols, patterns, swatches, character and
|
||||
//! paragraph styles, brushes) and to graphic styles by id. Copy follows those references, also
|
||||
//! through the symbols, patterns and styles it finds, and keeps what they lead to.
|
||||
//! through the symbols, patterns, styles and brush art it finds, and keeps what they lead to.
|
||||
//!
|
||||
//! Pasting matches each resource by name: an identical one in the document is used, a missing one
|
||||
//! is added, and a different one of the same name is added under a free name, which the pasted
|
||||
@@ -13,6 +13,7 @@
|
||||
//! the document's Spot Colors option says. Pasting back into the document the objects came from
|
||||
//! uses its resources as they are now.
|
||||
|
||||
use std::cell::OnceCell;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -147,10 +148,28 @@ struct Defs<'a> {
|
||||
styles: &'a [GraphicStyle],
|
||||
char_styles: &'a [TextStyleDef],
|
||||
para_styles: &'a [TextStyleDef],
|
||||
brushes: Brushes<'a>,
|
||||
}
|
||||
|
||||
/// The brushes references lead to: a document's library, read the first time a brush is used
|
||||
/// (`vectorcraft_brush::library` parses it), or the clipboard's own.
|
||||
enum Brushes<'a> {
|
||||
Lazy(&'a Document, &'a OnceCell<Vec<Brush>>),
|
||||
Ready(&'a [Brush]),
|
||||
}
|
||||
|
||||
impl<'a> Brushes<'a> {
|
||||
fn get(&self) -> &'a [Brush] {
|
||||
match *self {
|
||||
Brushes::Lazy(d, cell) => cell.get_or_init(|| vectorcraft_brush::library(d)),
|
||||
Brushes::Ready(list) => list,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Defs<'a> {
|
||||
fn of(d: &'a Document) -> Self {
|
||||
/// `d`'s definitions; `brushes` holds its brush library once a brush is used.
|
||||
fn of(d: &'a Document, brushes: &'a OnceCell<Vec<Brush>>) -> Self {
|
||||
Self {
|
||||
swatches: d.swatches_iter().collect(),
|
||||
symbols: &d.symbols,
|
||||
@@ -158,6 +177,7 @@ impl<'a> Defs<'a> {
|
||||
styles: &d.graphic_styles,
|
||||
char_styles: &d.char_styles,
|
||||
para_styles: &d.para_styles,
|
||||
brushes: Brushes::Lazy(d, brushes),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -180,9 +200,9 @@ pub(super) struct Used {
|
||||
}
|
||||
|
||||
impl Used {
|
||||
fn of<'a>(defs: &Defs<'a>, nodes: &'a [Node]) -> Self {
|
||||
fn of<'a>(defs: &Defs<'a>, nodes: impl IntoIterator<Item = &'a Node>) -> Self {
|
||||
let mut used = Used::default();
|
||||
let mut todo: Vec<Source<'a>> = nodes.iter().map(Source::Node).collect();
|
||||
let mut todo: Vec<Source<'a>> = nodes.into_iter().map(Source::Node).collect();
|
||||
while let Some(src) = todo.pop() {
|
||||
let mut found = |r: Ref<'_>| used.note(defs, r, &mut todo);
|
||||
match src {
|
||||
@@ -224,6 +244,8 @@ impl Used {
|
||||
Res::Pattern => todo.extend(defs.patterns.iter().filter(|p| p.name == name).flat_map(|p| p.art.iter().map(|a| Source::Node(a)))),
|
||||
Res::CharStyle => todo.extend(defs.char_styles.iter().filter(|s| s.name == name).map(|s| Source::Attrs(&s.attrs))),
|
||||
Res::ParaStyle => todo.extend(defs.para_styles.iter().filter(|s| s.name == name).map(|s| Source::Attrs(&s.attrs))),
|
||||
// A scatter or art brush's art, a pattern brush's tiles.
|
||||
Res::Brush => todo.extend(defs.brushes.get().iter().filter(|b| b.name == name).flat_map(|b| b.art().into_iter().map(Source::Node))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -242,6 +264,80 @@ impl Used {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a preview of some art shows besides the art itself ([`art_resources`]).
|
||||
pub struct ArtResources {
|
||||
/// Changes when any resource the art uses changes, and only then.
|
||||
pub key: u64,
|
||||
/// The art and image bytes counted in `key` by their address, held weakly: their allocations
|
||||
/// stay theirs (no other art can take an address) for as long as the key is kept.
|
||||
_kept: (Vec<std::sync::Weak<Node>>, Vec<std::sync::Weak<Vec<u8>>>),
|
||||
}
|
||||
|
||||
/// The resources `art` uses in `doc`, through the definitions they lead to as Copy follows them
|
||||
/// ([`Used`]): images, symbols, patterns (tile type, overlap and spacing too), swatches (linked
|
||||
/// colours, tints, gradient swatches; colour groups' included), character and paragraph styles,
|
||||
/// brushes and graphic styles, and the document's Spot Colors option. Art and image bytes count
|
||||
/// by identity, the other definitions by their saved form: working the key out walks `art` and
|
||||
/// the definitions it leads to, and never reads an image's bytes.
|
||||
pub fn art_resources<'a>(doc: &'a Document, art: impl IntoIterator<Item = &'a Node>) -> ArtResources {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let library = OnceCell::new();
|
||||
let defs = Defs::of(doc, &library);
|
||||
// The art's references shortened to the brush library's life.
|
||||
let mut nodes: Vec<&Node> = vec![];
|
||||
for n in art {
|
||||
nodes.push(n);
|
||||
}
|
||||
let used = Used::of(&defs, nodes);
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
let mut kept = (vec![], vec![]);
|
||||
fn saved(h: &mut impl Hasher, v: &impl serde::Serialize) {
|
||||
serde_json::to_vec(v).unwrap_or_default().hash(h);
|
||||
}
|
||||
fn node(h: &mut impl Hasher, kept: &mut Vec<std::sync::Weak<Node>>, a: &Arc<Node>) {
|
||||
(Arc::as_ptr(a) as usize).hash(h);
|
||||
kept.push(Arc::downgrade(a));
|
||||
}
|
||||
for (res, names) in &used.names {
|
||||
for name in names {
|
||||
(*res as u8, name).hash(&mut h);
|
||||
match res {
|
||||
Res::Image => {
|
||||
if let Some(b) = doc.images.get(name) {
|
||||
b.mime.hash(&mut h);
|
||||
for bytes in std::iter::once(&b.bytes).chain(&b.proxy) {
|
||||
(Arc::as_ptr(bytes) as usize).hash(&mut h);
|
||||
kept.1.push(Arc::downgrade(bytes));
|
||||
}
|
||||
}
|
||||
}
|
||||
Res::Symbol => doc.symbols.iter().filter(|s| s.name == *name).for_each(|s| node(&mut h, &mut kept.0, &s.art)),
|
||||
Res::Pattern => {
|
||||
for p in doc.patterns.iter().filter(|p| p.name == *name) {
|
||||
saved(&mut h, &PatternDef { art: vec![], ..p.clone() });
|
||||
p.art.iter().for_each(|a| node(&mut h, &mut kept.0, a));
|
||||
}
|
||||
}
|
||||
Res::CharStyle => doc.char_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)),
|
||||
Res::ParaStyle => doc.para_styles.iter().filter(|s| s.name == *name).for_each(|s| saved(&mut h, s)),
|
||||
Res::Brush => defs.brushes.get().iter().filter(|b| b.name == *name).for_each(|b| saved(&mut h, b)),
|
||||
// Swatches below (tints count too); graphic styles go by id.
|
||||
Res::Swatch | Res::GraphicStyle => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
for w in doc.swatches_iter().filter(|w| used.carries(w) || used.has(Res::Swatch, &w.name)) {
|
||||
saved(&mut h, w);
|
||||
}
|
||||
for g in doc.graphic_styles.iter().filter(|g| g.id != 0 && used.styles.contains(&g.id)) {
|
||||
saved(&mut h, g);
|
||||
}
|
||||
if used.names.contains_key(&Res::Swatch) {
|
||||
doc.spot_use_lab.hash(&mut h);
|
||||
}
|
||||
ArtResources { key: h.finish(), _kept: kept }
|
||||
}
|
||||
|
||||
/// A resource list entry known by its name.
|
||||
trait Named: Clone {
|
||||
fn name(&self) -> &str;
|
||||
@@ -469,6 +565,26 @@ fn same_art(r: &Relink, ours: &[Arc<Node>], theirs: &[Arc<Node>]) -> bool {
|
||||
ours.len() == theirs.len() && ours.iter().zip(theirs).all(|(a, b)| relinked(&unlinked, a) == relinked(r, b))
|
||||
}
|
||||
|
||||
/// Is `ours` (a document brush) brush `theirs` (a pasted one) once the art of that is relinked by
|
||||
/// `r`? Graphic style links don't count, as in [`same_art`].
|
||||
fn same_brush(r: &Relink, ours: &Brush, theirs: &Brush) -> bool {
|
||||
let relinked = |r: &Relink, b: &Brush| {
|
||||
let mut b = b.clone();
|
||||
b.art_mut().into_iter().for_each(|a| r.node(a));
|
||||
b
|
||||
};
|
||||
relinked(&Relink::default(), ours) == relinked(r, theirs)
|
||||
}
|
||||
|
||||
/// Does brush `b`'s art show symbols or patterns?
|
||||
fn shows_definitions(b: &Brush) -> bool {
|
||||
let mut found = false;
|
||||
for a in b.art() {
|
||||
node_refs(a, &mut |r| found |= matches!(r, Ref::Name(Res::Symbol | Res::Pattern, _)));
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// What pasting did to the document's resources (part of the paste result).
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Imported {
|
||||
@@ -501,11 +617,13 @@ impl Imported {
|
||||
impl Clipboard {
|
||||
/// `nodes` (from `src`) and the resources of `src` they use.
|
||||
pub(crate) fn gather(src: &Document, nodes: Vec<Node>) -> Self {
|
||||
let used = Used::of(&Defs::of(src), &nodes);
|
||||
let library = OnceCell::new();
|
||||
let used = Used::of(&Defs::of(src, &library), &nodes);
|
||||
let pick = |r: Res, list: &[TextStyleDef]| list.iter().filter(|s| used.has(r, &s.name)).cloned().collect::<Vec<_>>();
|
||||
let brushes = match used.names.get(&Res::Brush) {
|
||||
Some(names) => vectorcraft_brush::library(src).into_iter().filter(|b| names.contains(&b.name)).collect(),
|
||||
None => vec![],
|
||||
// Read when a brush was used.
|
||||
let brushes = match (used.names.get(&Res::Brush), library.get()) {
|
||||
(Some(names), Some(library)) => library.iter().filter(|b| names.contains(&b.name)).cloned().collect(),
|
||||
_ => vec![],
|
||||
};
|
||||
Self {
|
||||
images: src.images.iter().filter(|(k, _)| used.has(Res::Image, k)).map(|(k, b)| (k.clone(), b.clone())).collect(),
|
||||
@@ -530,6 +648,7 @@ impl Clipboard {
|
||||
styles: &self.graphic_styles,
|
||||
char_styles: &self.char_styles,
|
||||
para_styles: &self.para_styles,
|
||||
brushes: Brushes::Ready(&self.brushes),
|
||||
};
|
||||
Used::of(&defs, &self.nodes)
|
||||
}
|
||||
@@ -549,8 +668,10 @@ impl Clipboard {
|
||||
let used = self.used();
|
||||
let mut out = Imported::default();
|
||||
self.import_images(d, &used, same_doc, &mut out);
|
||||
self.import_brushes(d, &used, same_doc, &mut out);
|
||||
self.import_swatches(d, &used, choices, same_doc, &mut out);
|
||||
// Brushes whose art shows no symbols or patterns, before the symbols and patterns whose art
|
||||
// they may brush; the others once those are in.
|
||||
let mut added_brushes = self.import_brushes(d, &used, same_doc, false, &mut out);
|
||||
// Character and paragraph styles (their colours relinked first).
|
||||
for (r, mine, theirs) in [(Res::CharStyle, &self.char_styles, &mut d.char_styles), (Res::ParaStyle, &self.para_styles, &mut d.para_styles)] {
|
||||
for def in mine.iter().filter(|s| used.has(r, &s.name)) {
|
||||
@@ -583,6 +704,7 @@ impl Clipboard {
|
||||
added_patterns.extend(p.new_name(&def.name));
|
||||
out.placed(Res::Pattern, &def.name, &p);
|
||||
}
|
||||
added_brushes.extend(self.import_brushes(d, &used, same_doc, true, &mut out));
|
||||
self.import_graphic_styles(d, &used, same_doc, &mut out);
|
||||
for s in d.symbols.iter_mut().filter(|s| added_symbols.contains(&s.name)) {
|
||||
out.relink.node(Arc::make_mut(&mut s.art));
|
||||
@@ -592,6 +714,13 @@ impl Clipboard {
|
||||
out.relink.node(Arc::make_mut(a));
|
||||
}
|
||||
}
|
||||
if !added_brushes.is_empty() {
|
||||
let mut lib = vectorcraft_brush::library(d);
|
||||
for b in lib.iter_mut().filter(|b| added_brushes.contains(&b.name)) {
|
||||
b.art_mut().into_iter().for_each(|a| out.relink.node(a));
|
||||
}
|
||||
vectorcraft_brush::store(d, &lib);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -607,20 +736,26 @@ impl Clipboard {
|
||||
}
|
||||
}
|
||||
|
||||
fn import_brushes(&self, d: &mut Document, used: &Used, same_doc: bool, out: &mut Imported) {
|
||||
let brushes: Vec<&Brush> = self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name)).collect();
|
||||
/// The brushes whose art shows symbols or patterns (`late`), or the others: each one the
|
||||
/// document has (its art compared once relinked) is used, the others are added. → the names of
|
||||
/// those added, whose art is relinked at the end.
|
||||
fn import_brushes(&self, d: &mut Document, used: &Used, same_doc: bool, late: bool, out: &mut Imported) -> Vec<String> {
|
||||
let brushes: Vec<&Brush> = self.brushes.iter().filter(|b| used.has(Res::Brush, &b.name) && shows_definitions(b) == late).collect();
|
||||
if brushes.is_empty() {
|
||||
return;
|
||||
return vec![];
|
||||
}
|
||||
let mut lib = vectorcraft_brush::library(d);
|
||||
let before = lib.len();
|
||||
let mut added = vec![];
|
||||
for b in brushes {
|
||||
let p = place(&mut lib, b, same_doc, PartialEq::eq);
|
||||
let r = &out.relink;
|
||||
let p = place(&mut lib, b, same_doc, |ours, theirs| same_brush(r, ours, theirs));
|
||||
added.extend(p.new_name(&b.name));
|
||||
out.placed(Res::Brush, &b.name, &p);
|
||||
}
|
||||
if lib.len() != before {
|
||||
if !added.is_empty() {
|
||||
vectorcraft_brush::store(d, &lib);
|
||||
}
|
||||
added
|
||||
}
|
||||
|
||||
/// Global and spot colours (a name conflict merges or adds as `choices` say), then the tint
|
||||
|
||||
@@ -82,7 +82,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Create Text",
|
||||
[],
|
||||
None,
|
||||
"{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style?, color?, keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
"{x, y, text, rotation?: deg (about x, y), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color?, keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
|
||||
has_doc,
|
||||
text_create
|
||||
),
|
||||
@@ -794,6 +794,9 @@ pub(crate) fn new_type_style(s: &Session, p: &Value) -> CharStyle {
|
||||
}
|
||||
if let Some(f) = str_param(p, "style") {
|
||||
style.font_style = f.to_string();
|
||||
} else if str_param(p, "font").is_some() {
|
||||
// A family without a Regular (#4128): its closest style, as text.setRangeStyle takes.
|
||||
super::textedit::fit_font_style(&mut style);
|
||||
}
|
||||
style.fill = match p.get("color").and_then(color_value) {
|
||||
Some(c) => vectorcraft_color::Paint::solid(super::paint::new_color(s, p, c)),
|
||||
|
||||
@@ -843,10 +843,13 @@ fn freehand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if let Some((si, sp)) = redraw_section(&pd, &pts, fit_tol, within) {
|
||||
s.edit(if brush { "Paintbrush" } else { "Pencil" }, |d, sel| {
|
||||
*path_mut(d, id)?.subpaths.get_mut(si).ok_or_else(|| bad(C, "no such subpath"))? = sp;
|
||||
// A member path of a compound path is redrawn in it: the compound path is what is
|
||||
// selected.
|
||||
let whole = d.parent_of(id).filter(|p| d.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id);
|
||||
if keep_selected {
|
||||
sel.set([id]);
|
||||
sel.set([whole]);
|
||||
} else {
|
||||
sel.remove(id);
|
||||
sel.remove(whole);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
@@ -1494,6 +1497,7 @@ fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
.map_or(0.0, |x| x.0)
|
||||
};
|
||||
let (first_pt, last_pt) = (pts.first().copied(), pts.last().copied());
|
||||
let mut ends: Vec<(f64, NodeId, usize, bool, Point)> = vec![];
|
||||
for id in target_paths(&st.doc, &st.selection, poly_bounds(&pts, tol)) {
|
||||
let (pd, _) = path_of(&st.doc, id)?;
|
||||
@@ -1502,9 +1506,20 @@ fn join_scrub(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
continue;
|
||||
}
|
||||
for (start, a) in [(true, sp.anchors[0].p), (false, sp.anchors[sp.anchors.len() - 1].p)] {
|
||||
if dist_to_polyline(&pts, a) <= tol {
|
||||
ends.push((order(a), id, si, start, a));
|
||||
let on_scrub = dist_to_polyline(&pts, a) <= tol;
|
||||
let near_start = first_pt.is_some_and(|p| a.distance(p) <= tol);
|
||||
let near_end = last_pt.is_some_and(|p| a.distance(p) <= tol);
|
||||
if !on_scrub && !near_start && !near_end {
|
||||
continue;
|
||||
}
|
||||
let ord = if on_scrub {
|
||||
order(a)
|
||||
} else if near_start && (!near_end || first_pt.is_some_and(|p| a.distance(p) <= a.distance(last_pt.unwrap_or(p)))) {
|
||||
-1.0
|
||||
} else {
|
||||
1e30
|
||||
};
|
||||
ends.push((ord, id, si, start, a));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -335,7 +335,7 @@ pub fn load_with(name: &str, bytes: &[u8], opts: &LoadOptions) -> Result<Loaded>
|
||||
if !matches!(format.id, "vectorcraft" | "template") || doc.title.is_empty() {
|
||||
doc.title = title;
|
||||
}
|
||||
warnings.extend(doc.images.values().filter_map(|b| too_large_note(&b.bytes)));
|
||||
warnings.extend(doc.images.values().filter_map(|b| size_note(&b.bytes)));
|
||||
Ok(Loaded { doc, format, warnings, restored, converted, preview_only, editing_data })
|
||||
}
|
||||
|
||||
@@ -515,8 +515,8 @@ pub(crate) use vectorcraft_doc::MAX_RASTER_ALLOC;
|
||||
|
||||
/// What to say of encoded image `bytes` that need more than [`MAX_RASTER_ALLOC`] to decode,
|
||||
/// counted as RGBA (4 bytes a pixel) or as the decoder gives them when that is more (its header
|
||||
/// says so; the pixels aren't read): Open, Place and the Links panel say it (#1479). `None` for
|
||||
/// images within the allowance, and for bytes that aren't an image.
|
||||
/// says so; the pixels aren't read): Open, Place and the Links panel say it ([`size_note`], #1479).
|
||||
/// `None` for images within the allowance, and for bytes that aren't an image.
|
||||
pub(crate) fn too_large_note(bytes: &[u8]) -> Option<String> {
|
||||
use image::ImageDecoder as _;
|
||||
if let Some((w, h)) = vectorcraft_doc::cmyk::oversized_tiff(bytes) {
|
||||
@@ -530,6 +530,17 @@ pub(crate) fn too_large_note(bytes: &[u8]) -> Option<String> {
|
||||
(rgba_over || d.total_bytes() > MAX_RASTER_ALLOC).then(|| format!("an image of {w} × {h} pixels is too large to draw"))
|
||||
}
|
||||
|
||||
/// What Open, Place and the Links panel say of encoded image `bytes` that [`too_large_note`] is
|
||||
/// said of: that the image is shown at reduced size when the renderer decodes it smaller
|
||||
/// ([`vectorcraft_render::reduced_size`]), nothing when the renderer reads it at its own size a
|
||||
/// row at a time, otherwise that note. Returns `None` when [`too_large_note`] returns `None`.
|
||||
pub(crate) fn size_note(bytes: &[u8]) -> Option<String> {
|
||||
let note = too_large_note(bytes)?;
|
||||
let Some(drawn) = vectorcraft_render::reduced_size(bytes) else { return Some(note) };
|
||||
let (w, h) = image::ImageReader::new(Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()?;
|
||||
(drawn != (w, h)).then(|| format!("an image of {w} × {h} pixels is shown at reduced size"))
|
||||
}
|
||||
|
||||
/// Decode an image's header (and, for formats stored as PNG, its pixels). CMYK TIFFs are kept as
|
||||
/// they are, with their ink amounts ([`ImageBlob::cmyk`]), except that ones storing one plane per
|
||||
/// ink are written again with their inks together ([`vectorcraft_doc::cmyk::stored_cmyk_tiff`]);
|
||||
|
||||
@@ -32,7 +32,7 @@ mod export;
|
||||
pub(crate) mod imagemap;
|
||||
mod legacy_ai;
|
||||
mod load;
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, too_large_note};
|
||||
pub(crate) use load::{MAX_RASTER_ALLOC, size_note};
|
||||
mod metafile;
|
||||
mod naming;
|
||||
mod native;
|
||||
@@ -74,7 +74,7 @@ pub use native::with_compression_pref;
|
||||
pub use pdfimport::{LoadOptions, page_document};
|
||||
pub(crate) use save::job_for;
|
||||
pub use save::{
|
||||
SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, export_folder, reads_option as save_reads_option,
|
||||
SAVE_FORMATS, SaveJob, SaveMode, SavePlan, StreamWrite, TEMPLATE_FORMATS, dialog_folder, export_folder, reads_option as save_reads_option,
|
||||
remembered_save_options, save_filters, save_format, save_job, save_plan, save_with, stamp_save_dates, template_filters, templates_dialog_folder,
|
||||
templates_folder,
|
||||
};
|
||||
|
||||
@@ -185,6 +185,14 @@ fn parent_folder(path: &str) -> Option<String> {
|
||||
std::path::Path::new(path).parent().map(|p| p.to_string_lossy().to_string()).filter(|p| !p.is_empty())
|
||||
}
|
||||
|
||||
/// A file dialog's starting folder for a path on disk (#4122): the path's parent when it is a
|
||||
/// folder, else the nearest ancestor directory that exists.
|
||||
pub fn dialog_folder(path: &str) -> Option<String> {
|
||||
let folder = parent_folder(path)?;
|
||||
let path = std::path::PathBuf::from(folder);
|
||||
path.ancestors().find(|a| a.is_dir()).map(|a| a.to_string_lossy().into_owned())
|
||||
}
|
||||
|
||||
/// A save format by id or extension, or why it isn't one.
|
||||
fn save_format_of(f: &str) -> std::result::Result<&'static Format, String> {
|
||||
match format(f) {
|
||||
@@ -300,7 +308,7 @@ fn disagreeing_option(p: &Value, svg: bool) -> std::result::Result<Option<(Strin
|
||||
.as_object()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|(k, v)| !v.is_null() && !matches!(k.as_str(), "path" | "format" | "options") && !(svg && k.as_str() == "svg"))
|
||||
.filter(|(k, v)| !(v.is_null() || matches!(k.as_str(), "path" | "format" | "options") || svg && k.as_str() == "svg"))
|
||||
.map(|(k, v)| (k.clone(), v.clone()))
|
||||
.collect();
|
||||
if svg {
|
||||
@@ -1020,6 +1028,20 @@ mod tests_folders {
|
||||
assert_eq!(super::xdg_documents("XDG_MUSIC_DIR=\"$HOME/Musica\"", home), None);
|
||||
}
|
||||
|
||||
/// #4122: File → Open starts in the folder of the last opened file.
|
||||
#[test]
|
||||
fn dialog_folder_is_the_nearest_existing_parent() {
|
||||
let base = std::env::temp_dir().join(format!("vc-open-folder-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(&base).unwrap();
|
||||
let file = base.join("poster.svg");
|
||||
assert_eq!(super::dialog_folder(&file.to_string_lossy()).map(PathBuf::from), Some(base.clone()));
|
||||
let missing = base.join("gone").join("card.ai");
|
||||
assert_eq!(super::dialog_folder(&missing.to_string_lossy()).map(PathBuf::from), Some(base.clone()));
|
||||
assert!(super::dialog_folder("poster.svg").is_none());
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
}
|
||||
|
||||
/// #703: the Templates folder a dialog starts in exists: made when missing, else the nearest
|
||||
/// folder above it.
|
||||
#[test]
|
||||
|
||||
@@ -185,7 +185,7 @@ fn planar_tiffs_with_more_strips_than_can_be_counted_are_too_large() {
|
||||
file[102..106].copy_from_slice(&1u32.to_le_bytes());
|
||||
let e = raster_image(&file).err().expect("refused");
|
||||
assert!(e.to_string().contains("an image of 3 × 2147483649 pixels is too large to draw"), "{e}");
|
||||
assert!(too_large_note(&file).is_some());
|
||||
assert!(load::too_large_note(&file).is_some());
|
||||
assert_eq!(vectorcraft_doc::cmyk::oversized_tiff(&file), Some((3, 1 << 31 | 1)));
|
||||
}
|
||||
|
||||
|
||||
@@ -138,6 +138,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
artboard_delete
|
||||
),
|
||||
cmd!(
|
||||
"artboard.deleteEmpty",
|
||||
"Delete Empty Artboards",
|
||||
["Window", "Artboards"],
|
||||
None,
|
||||
"{} delete every artboard with no artwork on it (no object, hidden, locked and template art included, whose visual bounds meet or touch it, clip groups and clipping layers by their members inside the clip; guides don't count), with its guides, in one step; locked artboards stay; when every artboard is empty and none is locked, artboard 1 stays (with a locked one left, artboard 1 can go) → {deleted: [index…]} (the indices before deleting)",
|
||||
has_empty_artboards,
|
||||
artboard_delete_empty
|
||||
),
|
||||
cmd!(
|
||||
"artboard.setProps",
|
||||
"Artboard Options…",
|
||||
@@ -863,21 +872,49 @@ fn artboard_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fn artboard_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let indices = super::panelcmds::artboard_indices(&s.doc()?.doc, p, "artboard.delete")?;
|
||||
super::panelcmds::refuse_locked(&s.doc()?.doc, &indices)?;
|
||||
s.edit("Delete Artboard", |d, sel| {
|
||||
if indices.len() >= d.artboards.len() {
|
||||
return Err(EngineError::Other("a document needs at least one artboard".into()));
|
||||
}
|
||||
// The last first, so the others keep their places; their guides go with them.
|
||||
for &i in indices.iter().rev() {
|
||||
let id = d.artboards.remove(i).id;
|
||||
d.retire_artboard_id(id);
|
||||
d.retain_guides(sel, |_, g| g.artboard != Some(id));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
s.edit("Delete Artboard", |d, sel| remove_artboards(d, sel, &indices))?;
|
||||
ok()
|
||||
}
|
||||
|
||||
/// Delete artboards `indices` (sorted) of `d` with their guides; at least one must be left.
|
||||
fn remove_artboards(d: &mut Document, sel: &mut vectorcraft_doc::Selection, indices: &[usize]) -> Result<()> {
|
||||
if indices.len() >= d.artboards.len() {
|
||||
return Err(EngineError::Other("a document needs at least one artboard".into()));
|
||||
}
|
||||
// The last first, so the others keep their places; their guides go with them.
|
||||
for &i in indices.iter().rev() {
|
||||
let id = d.artboards.remove(i).id;
|
||||
d.retire_artboard_id(id);
|
||||
d.retain_guides(sel, |_, g| g.artboard != Some(id));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The artboards Delete Empty Artboards deletes: those with no artwork
|
||||
/// ([`Document::artboard_has_art`]) that aren't locked, but artboard 1 when every artboard is one
|
||||
/// of them (a document keeps one, as Delete Artboards keeps artboard 1).
|
||||
pub(crate) fn empty_artboards(d: &Document) -> Vec<usize> {
|
||||
let mut empty: Vec<usize> = d.artboards.iter().enumerate().filter(|(_, a)| !a.locked && !d.artboard_has_art(a.rect)).map(|(i, _)| i).collect();
|
||||
if empty.len() == d.artboards.len() {
|
||||
empty.retain(|&i| i != 0);
|
||||
}
|
||||
empty
|
||||
}
|
||||
|
||||
fn has_empty_artboards(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
if empty_artboards(&st.doc).is_empty() { Err("no empty artboards to delete".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
fn artboard_delete_empty(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let indices = empty_artboards(&s.doc()?.doc);
|
||||
if indices.is_empty() {
|
||||
return Err(EngineError::Other("no empty artboards to delete".into()));
|
||||
}
|
||||
s.edit("Delete Empty Artboards", |d, sel| remove_artboards(d, sel, &indices))?;
|
||||
Ok(json!({ "deleted": indices }))
|
||||
}
|
||||
|
||||
/// One artboard's part of `artboard.setProps`: its index, new rectangle, name, color, lock,
|
||||
/// display marks (Show Center Mark, Show Cross Hairs, Show Video Safe Areas) and Video Ruler Pixel
|
||||
/// Aspect Ratio, how far it moved, whether it was resized, the map its art and guides take when
|
||||
|
||||
@@ -76,7 +76,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Links",
|
||||
[],
|
||||
None,
|
||||
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first} every image object and placed document in the layers, as the Links panel lists them → {links: [{id, name, linked, status: ok|modified|missing|embedded, format, pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image too large to draw, document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels)}], missing, modified, embedded}",
|
||||
"{show?: all (default)|missing|modified|embedded, sort?: name|kind (file format)|status (missing, modified, ok, embedded); default: stacking order; top first} every image object and placed document in the layers, as the Links panel lists them → {links: [{id, name, linked, status: ok|modified|missing|embedded, format, pixelWidth, pixelHeight, path?, found?: path (found away from its path), page?, preview?: true (showing the saved preview), note?: said of an image past the decode allowance (shown at reduced size, or too large to draw), document?: true (a placed document: pageWidth and pageHeight in pt instead of pixels)}], missing, modified, embedded}",
|
||||
has_doc,
|
||||
list
|
||||
),
|
||||
@@ -1128,7 +1128,7 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
// Only an image that could be past the decode allowance (at 16 bytes a pixel, the
|
||||
// most a decoder gives) has its header read for this.
|
||||
let large = im.width as u64 * im.height as u64 > fileio::MAX_RASTER_ALLOC / 16;
|
||||
if let Some(note) = st.doc.images.get(&im.key).filter(|_| large).and_then(|b| fileio::too_large_note(&b.bytes)) {
|
||||
if let Some(note) = st.doc.images.get(&im.key).filter(|_| large).and_then(|b| fileio::size_note(&b.bytes)) {
|
||||
row["note"] = json!(note);
|
||||
}
|
||||
(im.link.as_ref(), row)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
pub(crate) mod appearance;
|
||||
mod assets;
|
||||
mod attributes;
|
||||
pub mod brushlib;
|
||||
mod brushsym;
|
||||
mod buildcmds;
|
||||
pub mod clipboard;
|
||||
@@ -271,6 +272,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(flatten::specs());
|
||||
v.extend(stylelib::specs());
|
||||
v.extend(symbollib::specs());
|
||||
v.extend(brushlib::specs());
|
||||
v.extend(library::specs());
|
||||
v.extend(expand::specs());
|
||||
v.extend(attributes::specs());
|
||||
@@ -564,6 +566,9 @@ pub use opacitymask::TransparencyInfo;
|
||||
/// Eyedropper Options (`Prefs::eyedropper`).
|
||||
pub use xform::{AppearanceAttrs, EyedropperAttrs, EyedropperOptions, FillAttrs, StrokeAttrs};
|
||||
|
||||
/// Pathfinder Options (`Prefs::pathfinder`).
|
||||
pub use pathops::{PATHFINDER_PRECISION_RANGE, PathfinderOptions};
|
||||
|
||||
/// The Attributes panel's state ([`Session::attributes_info`]).
|
||||
pub use overprint::AttributesInfo;
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! Character/Paragraph attributes.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Composer, JustificationOptions, NodeKind, Scaling, SingleWordJustify};
|
||||
use vectorcraft_doc::{Composer, JustificationOptions, NodeKind, Scaling, SingleWordJustify, TextRun};
|
||||
use vectorcraft_geom::{Rect, Vec2};
|
||||
|
||||
use super::*;
|
||||
@@ -47,6 +47,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_doc,
|
||||
set_format
|
||||
),
|
||||
cmd!(
|
||||
"text.convertListToText",
|
||||
"Convert to Text",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, start?: byte, end?: byte} (Type › Bullets and Numbering › Convert to Text: the paragraphs of the selected type, or of `ids`, or those a start/end range touches) the marker of each list paragraph becomes characters of its text: the bullet, or the number and its period as the paragraph showed it, then a tab, at the start of the paragraph in the marker's font, size and color; the list is turned off. When the marker's tab went to the left indent, the paragraph gets a left-aligned tab stop without a leader there, in place of any stop there, which keeps the text after the tab where it started; when it went to a tab stop and a stop there or past it has a leader or is not left-aligned, or a right, center or decimal stop lies between the marker and that place, the paragraph gets a left-aligned stop without a leader where the marker's tab ended, in place of any stop there and of those right, center and decimal stops before it (past the left indent only in a paragraph with no tab of its own). In threaded type the numbers are those counted through the story's frames, and a paragraph that continues into a later frame is converted where its text starts. An empty list paragraph has no marker and only leaves the list. A paragraph with no direction set gets the direction it ran in when the characters would change it (a letter or roman numeral before right-to-left text). With the Every-line Composer, a paragraph with a tab is broken line by line, so a converted paragraph can break its lines at other places. While the Type tool edits, its typing ends first and its anchor and caret move past the characters inserted at or before them; in threaded type, when the caret's character moved to another frame, the tool edits that frame, which becomes the selection when it was not selected. One undo step → {ids, converted: paragraphs, inserted: [{id, at: byte before the change, length: bytes}]}",
|
||||
has_doc,
|
||||
convert_list_to_text
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -642,3 +651,355 @@ fn set_format(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})?;
|
||||
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>() }))
|
||||
}
|
||||
|
||||
/// The part of a story paragraph in one frame, as [`convert_list_to_text`] reads it: the frame,
|
||||
/// the frame's paragraph, its bytes there, its list, the marker the frame's layout draws for it
|
||||
/// and the numbered paragraphs the frame counts before it.
|
||||
struct ParagraphPart {
|
||||
frame: usize,
|
||||
index: usize,
|
||||
bytes: std::ops::Range<usize>,
|
||||
list: Option<vectorcraft_doc::text::ParaList>,
|
||||
marker: Option<String>,
|
||||
count: u32,
|
||||
}
|
||||
|
||||
/// A paragraph of a story: its parts in thread order (a later frame's first paragraph goes on
|
||||
/// with the paragraph the frame before it ends in, which may be an empty part after a paragraph
|
||||
/// break), and whether the call converts it (a part of it is in a paragraph the call names).
|
||||
struct StoryParagraph {
|
||||
parts: Vec<ParagraphPart>,
|
||||
converts: bool,
|
||||
}
|
||||
|
||||
impl StoryParagraph {
|
||||
/// The part whose style a re-flowed thread gives the whole paragraph
|
||||
/// (`vectorcraft_text::thread::story_paras`) and whose marker the layout draws: the first part
|
||||
/// with text, else the last part.
|
||||
fn main_part(&self) -> Option<&ParagraphPart> {
|
||||
self.parts.iter().find(|p| !p.bytes.is_empty()).or(self.parts.last())
|
||||
}
|
||||
}
|
||||
|
||||
/// The style of the character at byte `b` of `t`, as the layout reads it: the run that holds `b`,
|
||||
/// else the one before it, else the first.
|
||||
fn char_style_at(t: &vectorcraft_doc::TextObject, b: usize) -> vectorcraft_doc::CharStyle {
|
||||
let mut runs = vec![];
|
||||
let mut off = 0;
|
||||
for r in &t.runs {
|
||||
runs.push((off..off + r.text.len(), &r.style));
|
||||
off += r.text.len();
|
||||
}
|
||||
let find = |b: usize| runs.iter().find(|(r, _)| r.contains(&b)).map(|(_, s)| (*s).clone());
|
||||
find(b).or_else(|| b.checked_sub(1).and_then(find)).unwrap_or_else(|| t.first_style())
|
||||
}
|
||||
|
||||
/// The list marker that `lay` (the layout of `t`) draws before paragraph `index` (bytes `bytes`):
|
||||
/// the width of its characters and the width of the tab after them. A paragraph the layout leaves
|
||||
/// out (overset text) is laid out on its own, as a paragraph that starts there, numbered on from
|
||||
/// `count`.
|
||||
fn marker_extent(
|
||||
t: &vectorcraft_doc::TextObject,
|
||||
lay: &vectorcraft_text::TextLayout,
|
||||
index: usize,
|
||||
bytes: std::ops::Range<usize>,
|
||||
count: u32,
|
||||
) -> (f64, f64) {
|
||||
let width = |lay: &vectorcraft_text::TextLayout, start: usize| {
|
||||
lay.markers.iter().find(|m| lay.glyphs.get(m.glyphs.start).is_some_and(|g| g.byte == start)).map(|m| {
|
||||
let advance = |g: usize| lay.glyphs.get(g).map_or(0.0, |g| g.advance);
|
||||
(m.glyphs.clone().filter(|&g| g != m.tab).map(advance).sum::<f64>(), advance(m.tab))
|
||||
})
|
||||
};
|
||||
width(lay, bytes.start).unwrap_or_else(|| {
|
||||
let mut probe = t.clone();
|
||||
probe.kind = vectorcraft_doc::TextKind::Point;
|
||||
probe.runs = vectorcraft_text::edit::slice_runs(&t.runs, bytes.start, bytes.end);
|
||||
probe.ruby.clear();
|
||||
probe.set_all_paras(t.para_at(index).clone());
|
||||
probe.list_count = count;
|
||||
probe.first_para_continues = false;
|
||||
width(&vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &probe), 0).unwrap_or((0.0, 0.0))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether tab stop `tab` is at position `x`.
|
||||
fn stop_at(tab: &vectorcraft_doc::TabStop, x: f64) -> bool {
|
||||
(tab.position - x).abs() <= 1e-6
|
||||
}
|
||||
|
||||
/// Whether `tabs` hold one stop at position `x`, left-aligned and without a leader.
|
||||
fn plain_stop_at(tabs: &[vectorcraft_doc::TabStop], x: f64) -> bool {
|
||||
let there: Vec<&vectorcraft_doc::TabStop> = tabs.iter().filter(|tab| stop_at(tab, x)).collect();
|
||||
matches!(there.as_slice(), [only] if only.align == vectorcraft_doc::TabAlign::Left && only.leader.is_empty())
|
||||
}
|
||||
|
||||
/// Whether tab stop `tab` lies between positions `from` and `x` and is not left-aligned.
|
||||
fn aligned_between(tab: &vectorcraft_doc::TabStop, from: f64, x: f64) -> bool {
|
||||
tab.align != vectorcraft_doc::TabAlign::Left && tab.position > from + 1e-6 && tab.position < x - 1e-6
|
||||
}
|
||||
|
||||
/// The frames of the story that type object `id` belongs to (its thread in thread order, else `id`
|
||||
/// alone), each with the length of its text in bytes.
|
||||
fn story_frames(s: &Session, id: NodeId) -> Vec<(NodeId, usize)> {
|
||||
let Some(st) = s.active() else { return vec![] };
|
||||
let d = &st.doc;
|
||||
let frames = d.text_threads.iter().find(|thread| thread.contains(&id)).cloned().unwrap_or_else(|| vec![id]);
|
||||
frames
|
||||
.into_iter()
|
||||
.filter_map(|f| match d.node(f).map(|n| &n.kind) {
|
||||
Some(NodeKind::Text(t)) => Some((f, t.plain_text().len())),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// After Convert to Text inserted `inserted` (each a frame, the byte it went in at and its length),
|
||||
/// the Type tool's anchor and caret in frame `id` (`editing`, read before the call, in a story
|
||||
/// whose frames had the lengths `before`) move past the characters inserted at or before them in
|
||||
/// the story. In threaded type the caret stays in the frame it was in while its place is still
|
||||
/// there, and else goes to the frame its character moved to, with the anchor in that frame; that
|
||||
/// frame becomes the selection when it was not selected.
|
||||
fn move_editing_selection(
|
||||
s: &mut Session,
|
||||
(id, anchor, caret): (NodeId, usize, usize),
|
||||
before: &[(NodeId, usize)],
|
||||
inserted: &[(NodeId, usize, usize)],
|
||||
) -> Result<()> {
|
||||
// Story positions: the bytes of the frames before a frame, then the byte in it.
|
||||
let start_of = |frames: &[(NodeId, usize)], f: NodeId| frames.iter().take_while(|(g, _)| *g != f).map(|(_, n)| n).sum::<usize>();
|
||||
let len_of = |frames: &[(NodeId, usize)], f: NodeId| frames.iter().find(|(g, _)| *g == f).map_or(0, |(_, n)| *n);
|
||||
let inserted: Vec<(usize, usize)> =
|
||||
inserted.iter().filter(|(f, _, _)| before.iter().any(|(g, _)| g == f)).map(|&(f, at, n)| (start_of(before, f) + at, n)).collect();
|
||||
if inserted.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let story = |at: usize| {
|
||||
let at = start_of(before, id) + at.min(len_of(before, id));
|
||||
at + inserted.iter().filter(|(b, _)| *b <= at).map(|(_, n)| n).sum::<usize>()
|
||||
};
|
||||
let (anchor, caret) = (story(anchor), story(caret));
|
||||
let after = story_frames(s, id);
|
||||
let fits = |f: NodeId| (start_of(&after, f)..=start_of(&after, f) + len_of(&after, f)).contains(&caret);
|
||||
let frame = if fits(id) { Some(id) } else { after.iter().map(|(f, _)| *f).find(|f| fits(*f)) };
|
||||
let Some(frame) = frame else { return Ok(()) };
|
||||
let (start, len) = (start_of(&after, frame), len_of(&after, frame));
|
||||
let local = |at: usize| at.saturating_sub(start).min(len);
|
||||
if frame == id {
|
||||
s.set_tool_option("select", &json!({"start": local(anchor), "end": local(caret)}));
|
||||
return Ok(());
|
||||
}
|
||||
s.set_tool_option("textSelection", &json!({"editing": frame.0, "anchor": local(anchor), "caret": local(caret)}));
|
||||
// The Type tool ends editing after a command when the frame it edits is not selected, itself
|
||||
// or through a selected group, so that frame becomes the selection, as a click in it does.
|
||||
let selected = s.active().is_some_and(|st| {
|
||||
let mut cur = Some(frame);
|
||||
while let Some(c) = cur {
|
||||
if st.selection.contains(c) {
|
||||
return true;
|
||||
}
|
||||
cur = st.doc.parent_of(c);
|
||||
}
|
||||
false
|
||||
});
|
||||
if !selected {
|
||||
s.select(|_, sel| sel.set([frame]))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Type › Bullets and Numbering › Convert to Text (`text.convertListToText`): the markers of the
|
||||
/// list paragraphs the call names become characters of the text, and the lists are turned off.
|
||||
/// While the Type tool edits, its typing ends first and its anchor and caret move past the
|
||||
/// characters inserted at or before them ([`move_editing_selection`]).
|
||||
fn convert_list_to_text(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.convertListToText";
|
||||
use vectorcraft_doc::text::ParaList;
|
||||
let ids = super::typecmd::text_targets(s, p, C)?;
|
||||
let range = super::typecmd::TextRange::parse(p, C)?;
|
||||
let editing = match super::textedit::editing_range(s)? {
|
||||
Some((id, _, _)) => {
|
||||
let options = s.tool_options();
|
||||
let at = |k: &str| options.get(k).and_then(Value::as_u64).and_then(|v| usize::try_from(v).ok());
|
||||
at("anchor").zip(at("caret")).map(|(anchor, caret)| (id, anchor, caret))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let story_before = editing.map(|(id, _, _)| story_frames(s, id)).unwrap_or_default();
|
||||
let d = &s.doc()?.doc;
|
||||
let text = |id: NodeId| match d.node(id).map(|n| &n.kind) {
|
||||
Some(NodeKind::Text(t)) => Some(t.as_ref()),
|
||||
_ => None,
|
||||
};
|
||||
// Each story once: the frames of a thread in thread order, or one type object.
|
||||
let mut stories: Vec<Vec<NodeId>> = vec![];
|
||||
for id in &ids {
|
||||
if stories.iter().any(|story| story.contains(id)) {
|
||||
continue;
|
||||
}
|
||||
let thread = d.text_threads.iter().find(|thread| thread.contains(id));
|
||||
stories.push(thread.map_or_else(|| vec![*id], |thread| thread.iter().copied().filter(|f| text(*f).is_some()).collect()));
|
||||
}
|
||||
// Per frame: the paragraphs whose list goes (with the style each gets) and the characters that
|
||||
// go in at a byte.
|
||||
type Stops = Vec<(usize, vectorcraft_doc::ParaStyle)>;
|
||||
type Inserts = Vec<(usize, TextRun)>;
|
||||
let mut edits: Vec<(NodeId, Stops, Inserts)> = vec![];
|
||||
let mut converted = 0;
|
||||
for story in &stories {
|
||||
let frames: Vec<&vectorcraft_doc::TextObject> = story.iter().filter_map(|id| text(*id)).collect();
|
||||
let mut paras: Vec<StoryParagraph> = vec![];
|
||||
let mut named_parts = vec![];
|
||||
let plains: Vec<String> = frames.iter().map(|t| t.plain_text()).collect();
|
||||
for (f, ((id, t), plain)) in story.iter().zip(&frames).zip(&plains).enumerate() {
|
||||
let named = if ids.contains(id) { range.map_or(0..t.paragraph_count(), |r| r.paras(t)) } else { 0..0 };
|
||||
let mut count = t.list_count;
|
||||
let mut start = 0;
|
||||
for (k, piece) in plain.split('\n').enumerate() {
|
||||
let bytes = start..start + piece.len();
|
||||
start = bytes.end + 1;
|
||||
let before = count;
|
||||
let list = t.para_at(k).list;
|
||||
let marker = ParaList::next_marker(list, piece.is_empty(), &mut count);
|
||||
// A later frame's first paragraph goes on with the one the frame before it ends in.
|
||||
if !(k == 0 && f > 0) || paras.is_empty() {
|
||||
paras.push(StoryParagraph { parts: vec![], converts: false });
|
||||
}
|
||||
if let Some(para) = paras.last_mut() {
|
||||
para.parts.push(ParagraphPart { frame: f, index: k, bytes, list, marker, count: before });
|
||||
named_parts.push((paras.len() - 1, named.contains(&k)));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i, named) in named_parts {
|
||||
if let Some(para) = paras.get_mut(i) {
|
||||
let listed = para.main_part().is_some_and(|p| p.list.is_some());
|
||||
para.converts |= named && listed;
|
||||
}
|
||||
}
|
||||
// Each converted paragraph's main part, whether the paragraph holds a tab of its own, and
|
||||
// the paragraph.
|
||||
let main_parts: Vec<(&ParagraphPart, bool, &StoryParagraph)> = paras
|
||||
.iter()
|
||||
.filter(|p| p.converts)
|
||||
.filter_map(|p| {
|
||||
let tabs = p.parts.iter().any(|q| plains.get(q.frame).and_then(|s| s.get(q.bytes.clone())).is_some_and(|s| s.contains('\t')));
|
||||
p.main_part().map(|m| (m, tabs, p))
|
||||
})
|
||||
.collect();
|
||||
let layouts: Vec<Option<vectorcraft_text::TextLayout>> = frames
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(f, t)| {
|
||||
main_parts
|
||||
.iter()
|
||||
.any(|(p, _, _)| p.marker.is_some() && p.frame == f)
|
||||
.then(|| vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t))
|
||||
})
|
||||
.collect();
|
||||
let mut frame_edits: Vec<(Stops, Inserts)> = vec![(vec![], vec![]); frames.len()];
|
||||
for (para, own_tabs, story_para) in main_parts {
|
||||
converted += 1;
|
||||
let mut stop = None;
|
||||
let mut direction = None;
|
||||
if let (Some(marker), Some(t), Some(Some(lay))) = (¶.marker, frames.get(para.frame), layouts.get(para.frame)) {
|
||||
// The marker's tab went to the left indent when it was ahead of the marker and no
|
||||
// explicit stop came first, as the layout sets it; otherwise to the next tab stop,
|
||||
// without the stop's leader, and for a right, center or decimal stop measured with
|
||||
// the whole paragraph after it, where a converted tab measures the rest of its line.
|
||||
// A plain left stop where the marker's tab ended takes the converted tab there: one
|
||||
// at the left indent in the first case, and in the second, where a stop there or
|
||||
// past it has a leader or is not left-aligned, or a right, center or decimal stop
|
||||
// lies between the marker and that place. Those right, center and decimal stops
|
||||
// between the marker and that place are removed. No other tab reaches a stop before
|
||||
// the left indent, nor one past it in a paragraph with no tab of its own.
|
||||
let style = t.para_at(para.index);
|
||||
let (width, gap) = marker_extent(t, lay, para.index, para.bytes.clone(), para.count);
|
||||
let pen = style.left_indent + style.first_line_indent + width;
|
||||
let indent = style.left_indent;
|
||||
let before = style.tabs.iter().any(|tab| tab.position > pen + 1e-6 && tab.position < indent - 1e-6);
|
||||
let end = pen + gap;
|
||||
let needed = |x: f64| !plain_stop_at(&style.tabs, x) || style.tabs.iter().any(|tab| aligned_between(tab, pen, x));
|
||||
if indent - pen > 1e-6 && !before {
|
||||
stop = Some((pen, indent)).filter(|&(_, x)| needed(x));
|
||||
} else if (end < indent - 1e-6 || !own_tabs)
|
||||
&& style.tabs.iter().any(|tab| {
|
||||
let past = tab.position > end - 1e-6 && (!tab.leader.is_empty() || tab.align != vectorcraft_doc::TabAlign::Left);
|
||||
past || aligned_between(tab, pen, end)
|
||||
})
|
||||
{
|
||||
stop = Some((pen, end)).filter(|&(_, x)| needed(x));
|
||||
}
|
||||
// A paragraph with no direction set runs the way its first strong character does.
|
||||
// When the marker's characters would change that (a letter or a roman numeral
|
||||
// before right-to-left text), the paragraph gets the direction it ran in.
|
||||
if style.direction.is_none() {
|
||||
let body = plains.get(para.frame).and_then(|s| s.get(para.bytes.clone())).unwrap_or_default();
|
||||
let was = vectorcraft_text::paragraph_is_rtl(body, None);
|
||||
if vectorcraft_text::paragraph_is_rtl(&format!("{marker}\t{body}"), None) != was {
|
||||
direction = Some(if was { vectorcraft_doc::ParaDirection::RightToLeft } else { vectorcraft_doc::ParaDirection::LeftToRight });
|
||||
}
|
||||
}
|
||||
let run = TextRun { text: format!("{marker}\t"), style: ParaList::marker_style(&char_style_at(t, para.bytes.start)), inline: None };
|
||||
if let Some((_, inserts)) = frame_edits.get_mut(para.frame) {
|
||||
inserts.push((para.bytes.start, run));
|
||||
}
|
||||
}
|
||||
// A paragraph in several frames is changed in its main part and in its empty parts:
|
||||
// re-flowing the thread gives the other parts with text the main part's style.
|
||||
let Some(mut style) = frames.get(para.frame).map(|t| t.para_at(para.index).clone()) else { continue };
|
||||
style.list = None;
|
||||
if direction.is_some() {
|
||||
style.direction = direction;
|
||||
}
|
||||
// A plain left stop at `x`, in place of any stop there and of the right, center and
|
||||
// decimal stops between the marker's end `from` and `x`.
|
||||
if let Some((from, x)) = stop {
|
||||
style.tabs.retain(|tab| !stop_at(tab, x) && !aligned_between(tab, from, x));
|
||||
let i = style.tabs.iter().position(|tab| tab.position > x).unwrap_or(style.tabs.len());
|
||||
let tab = vectorcraft_doc::TabStop { position: x, align: vectorcraft_doc::TabAlign::Left, leader: String::new(), align_on: '.' };
|
||||
style.tabs.insert(i, tab);
|
||||
}
|
||||
for part in story_para.parts.iter().filter(|q| std::ptr::eq(*q, para) || q.bytes.is_empty()) {
|
||||
if let Some((stops, _)) = frame_edits.get_mut(part.frame) {
|
||||
stops.push((part.index, style.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (id, (stops, inserts)) in story.iter().zip(frame_edits) {
|
||||
if !stops.is_empty() {
|
||||
edits.push((*id, stops, inserts));
|
||||
}
|
||||
}
|
||||
}
|
||||
let changed: Vec<u64> = edits.iter().map(|(id, _, _)| id.0).collect();
|
||||
let inserted: Vec<Value> = edits
|
||||
.iter()
|
||||
.flat_map(|(id, _, inserts)| inserts.iter().map(move |(at, run)| json!({"id": id.0, "at": at, "length": run.text.len()})))
|
||||
.collect();
|
||||
let insertions: Vec<(NodeId, usize, usize)> =
|
||||
edits.iter().flat_map(|(id, _, inserts)| inserts.iter().map(move |(at, run)| (*id, *at, run.text.len()))).collect();
|
||||
if !edits.is_empty() {
|
||||
s.edit("Convert to Text", |d, _| {
|
||||
for (id, stops, mut inserts) in edits {
|
||||
let Some(NodeKind::Text(t)) = d.node_mut(id).map(|n| &mut n.kind) else { continue };
|
||||
for (k, style) in stops {
|
||||
t.edit_paras(Some(k..k + 1), |para| *para = style.clone());
|
||||
}
|
||||
// From the last paragraph to the first, so that each byte still names its place.
|
||||
inserts.sort_by_key(|(at, _)| std::cmp::Reverse(*at));
|
||||
for (at, run) in inserts {
|
||||
let len = run.text.len();
|
||||
vectorcraft_text::edit::replace_range_styled(&mut t.runs, at, at, &[run]);
|
||||
t.ruby_after_replace(at, at, len);
|
||||
}
|
||||
super::typecmd::refresh_bounds(t);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
if let Some(editing) = editing {
|
||||
move_editing_selection(s, editing, &story_before, &insertions)?;
|
||||
}
|
||||
}
|
||||
Ok(json!({ "ids": changed, "converted": converted, "inserted": inserted }))
|
||||
}
|
||||
@@ -23,90 +23,90 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Unite",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
has_selection,
|
||||
|s, _| run_pf(s, PathfinderOp::Unite)
|
||||
|s, p| run_pf(s, p, PathfinderOp::Unite)
|
||||
),
|
||||
cmd!(
|
||||
"object.pathfinder.minusFront",
|
||||
"Minus Front",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
has_selection,
|
||||
|s, _| run_pf(s, PathfinderOp::MinusFront)
|
||||
|s, p| run_pf(s, p, PathfinderOp::MinusFront)
|
||||
),
|
||||
cmd!(
|
||||
"object.pathfinder.intersect",
|
||||
"Intersect",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
has_selection,
|
||||
|s, _| run_pf(s, PathfinderOp::Intersect)
|
||||
|s, p| run_pf(s, p, PathfinderOp::Intersect)
|
||||
),
|
||||
cmd!(
|
||||
"object.pathfinder.exclude",
|
||||
"Exclude",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
has_selection,
|
||||
|s, _| run_pf(s, PathfinderOp::Exclude)
|
||||
|s, p| run_pf(s, p, PathfinderOp::Exclude)
|
||||
),
|
||||
cmd!(
|
||||
"object.pathfinder.divide",
|
||||
"Divide",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
has_selection,
|
||||
|s, _| run_pf(s, PathfinderOp::Divide)
|
||||
|s, p| run_pf(s, p, PathfinderOp::Divide)
|
||||
),
|
||||
cmd!(
|
||||
"object.pathfinder.trim",
|
||||
"Trim",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
has_selection,
|
||||
|s, _| run_pf(s, PathfinderOp::Trim)
|
||||
|s, p| run_pf(s, p, PathfinderOp::Trim)
|
||||
),
|
||||
cmd!(
|
||||
"object.pathfinder.merge",
|
||||
"Merge",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
has_selection,
|
||||
|s, _| run_pf(s, PathfinderOp::Merge)
|
||||
|s, p| run_pf(s, p, PathfinderOp::Merge)
|
||||
),
|
||||
cmd!(
|
||||
"object.pathfinder.crop",
|
||||
"Crop",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
has_multi,
|
||||
|s, _| run_pf(s, PathfinderOp::Crop)
|
||||
|s, p| run_pf(s, p, PathfinderOp::Crop)
|
||||
),
|
||||
cmd!(
|
||||
"object.pathfinder.outline",
|
||||
"Outline",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
has_selection,
|
||||
|s, _| run_pf(s, PathfinderOp::Outline)
|
||||
|s, p| run_pf(s, p, PathfinderOp::Outline)
|
||||
),
|
||||
cmd!(
|
||||
"object.pathfinder.minusBack",
|
||||
"Minus Back",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{ids?: [id…] (selected first; default: the selection)} operate on the selected objects (back → front) → {ids}",
|
||||
"{ids?: [id…] (selected first; default: the selection), precision?: pt 0.001..10, removeRedundantPoints?: bool, removeUnpainted?: bool (default: the Pathfinder Options, see object.pathfinder.options; the values used join the journal entry)} operate on the selected objects (back → front) → {ids}",
|
||||
has_selection,
|
||||
|s, _| run_pf(s, PathfinderOp::MinusBack)
|
||||
|s, p| run_pf(s, p, PathfinderOp::MinusBack)
|
||||
),
|
||||
cmd!(
|
||||
"object.pathfinder.trap",
|
||||
@@ -117,6 +117,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_selection,
|
||||
trap
|
||||
),
|
||||
cmd!(
|
||||
"object.pathfinder.options",
|
||||
"Pathfinder Options…",
|
||||
["Window", "Pathfinder"],
|
||||
None,
|
||||
"{precision?: pt 0.001..10 (0.01; how closely the Pathfinder operations follow the paths: results are refit to within it and pieces thinner than it are dropped), removeRedundantPoints?: bool (false; the results lose the anchors that don't change their shape), removeUnpainted?: bool (false; Divide and Outline leave out the pieces of objects with no fill)} Pathfinder Options, kept in the preferences and used by every later Shape Mode and Pathfinder operation (not Trap); {} reads them → the options",
|
||||
always,
|
||||
pathfinder_options
|
||||
),
|
||||
cmd!(
|
||||
"object.path.outlineStroke",
|
||||
"Outline Stroke",
|
||||
@@ -379,6 +388,82 @@ pub(crate) fn remove_each(d: &mut Document, ids: &[NodeId]) -> Result<()> {
|
||||
|
||||
// ---------- Pathfinder ----------
|
||||
|
||||
/// Pathfinder panel › Pathfinder Options (`object.pathfinder.options`, the `pathfinder` preference
|
||||
/// group), which every Shape Mode and Pathfinder operation of the panel uses. The defaults leave
|
||||
/// the results as they were before the options existed.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct PathfinderOptions {
|
||||
/// How closely results follow the paths (pt): they are refit to within it and pieces thinner
|
||||
/// than it are dropped ([`po::pathfinder_with`]).
|
||||
pub precision: f64,
|
||||
/// Results lose the anchors that don't change their shape (to within `precision`).
|
||||
pub remove_redundant_points: bool,
|
||||
/// Divide and Outline leave out the pieces of objects with no fill.
|
||||
pub remove_unpainted: bool,
|
||||
}
|
||||
|
||||
impl Default for PathfinderOptions {
|
||||
fn default() -> Self {
|
||||
Self { precision: po::DEFAULT_PRECISION, remove_redundant_points: false, remove_unpainted: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// The range of Pathfinder Options › Precision (pt).
|
||||
pub const PATHFINDER_PRECISION_RANGE: std::ops::RangeInclusive<f64> = 0.001..=10.0;
|
||||
|
||||
impl PathfinderOptions {
|
||||
/// These options with those `p` names (`precision` in pt or a string with a unit), or why `p`
|
||||
/// can't set them.
|
||||
pub(crate) fn merged(&self, p: &Value) -> std::result::Result<Self, String> {
|
||||
let given = match p {
|
||||
Value::Null => return Ok(*self),
|
||||
Value::Object(given) => given,
|
||||
_ => return Err("`pathfinder` must be an object".into()),
|
||||
};
|
||||
let mut o = *self;
|
||||
for (key, v) in given {
|
||||
let flag = || v.as_bool().ok_or_else(|| format!("`{key}` must be true or false"));
|
||||
match key.as_str() {
|
||||
"precision" => {
|
||||
o.precision =
|
||||
len_param(p, key).filter(|v| PATHFINDER_PRECISION_RANGE.contains(v)).ok_or("precision must be from 0.001 to 10 pt")?;
|
||||
}
|
||||
"removeRedundantPoints" => o.remove_redundant_points = flag()?,
|
||||
"removeUnpainted" => o.remove_unpainted = flag()?,
|
||||
k => {
|
||||
let path = "pathfinder";
|
||||
return Err(format!("unknown option `{path}.{k}`"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(o)
|
||||
}
|
||||
}
|
||||
|
||||
fn pathfinder_options(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.prefs.pathfinder = s.prefs.pathfinder.merged(p).map_err(|e| bad("object.pathfinder.options", e))?;
|
||||
Ok(json!(s.prefs.pathfinder))
|
||||
}
|
||||
|
||||
/// The last part of the id of `op`'s command (`object.pathfinder.…`).
|
||||
fn pf_id(op: PathfinderOp) -> &'static str {
|
||||
match op {
|
||||
PathfinderOp::Unite => "unite",
|
||||
PathfinderOp::MinusFront => "minusFront",
|
||||
PathfinderOp::Intersect => "intersect",
|
||||
PathfinderOp::Exclude => "exclude",
|
||||
PathfinderOp::Divide => "divide",
|
||||
PathfinderOp::Trim => "trim",
|
||||
PathfinderOp::Merge => "merge",
|
||||
PathfinderOp::Crop => "crop",
|
||||
PathfinderOp::Outline => "outline",
|
||||
PathfinderOp::MinusBack => "minusBack",
|
||||
PathfinderOp::HardMix => "hardMix",
|
||||
PathfinderOp::SoftMix => "softMix",
|
||||
}
|
||||
}
|
||||
|
||||
fn pf_label(op: PathfinderOp) -> &'static str {
|
||||
match op {
|
||||
PathfinderOp::Unite => "Unite",
|
||||
@@ -396,7 +481,25 @@ fn pf_label(op: PathfinderOp) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
fn run_pf(s: &mut Session, op: PathfinderOp) -> Result<Value> {
|
||||
/// The Pathfinder Options an operation uses: those `p` gives, else the preferences'. They join the
|
||||
/// command's journal entry, so replaying it gives the same result whatever the preferences are then.
|
||||
fn pf_options(s: &mut Session, p: &Value, id: &str) -> Result<PathfinderOptions> {
|
||||
let mut stored = s.prefs.pathfinder;
|
||||
if !PATHFINDER_PRECISION_RANGE.contains(&stored.precision) {
|
||||
// A preferences file edited by hand: the default, rather than refitting everything away.
|
||||
stored.precision = po::DEFAULT_PRECISION;
|
||||
}
|
||||
let keys = ["precision", "removeRedundantPoints", "removeUnpainted"];
|
||||
let given: serde_json::Map<String, Value> =
|
||||
p.as_object().into_iter().flatten().filter(|(k, _)| keys.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
|
||||
let options = stored.merged(&Value::Object(given)).map_err(|e| bad(id, e))?;
|
||||
s.note_journal("precision", json!(options.precision));
|
||||
s.note_journal("removeRedundantPoints", json!(options.remove_redundant_points));
|
||||
s.note_journal("removeUnpainted", json!(options.remove_unpainted));
|
||||
Ok(options)
|
||||
}
|
||||
|
||||
fn run_pf(s: &mut Session, p: &Value, op: PathfinderOp) -> Result<Value> {
|
||||
let roots = selected_roots(s)?;
|
||||
if roots.is_empty() {
|
||||
return Err(EngineError::Other("nothing selected".into()));
|
||||
@@ -404,6 +507,7 @@ fn run_pf(s: &mut Session, op: PathfinderOp) -> Result<Value> {
|
||||
let shape_mode =
|
||||
matches!(op, PathfinderOp::Unite | PathfinderOp::MinusFront | PathfinderOp::Intersect | PathfinderOp::Exclude | PathfinderOp::MinusBack);
|
||||
let label = pf_label(op);
|
||||
let options = pf_options(s, p, &format!("object.pathfinder.{}", pf_id(op)))?;
|
||||
let ids = s.edit(label, |d, sel| {
|
||||
// Build the stack (back → front); names are separate from paint/style identity.
|
||||
let mut styles: Vec<Style> = vec![];
|
||||
@@ -452,7 +556,12 @@ fn run_pf(s: &mut Session, op: PathfinderOp) -> Result<Value> {
|
||||
let parts: Vec<(PathData, FillRule)> = lv.iter().filter_map(node_path).collect();
|
||||
let refs: Vec<(&PathData, FillRule)> = parts.iter().map(|(p, r)| (p, *r)).collect();
|
||||
let name = n.name.clone().or_else(|| lv.iter().find_map(|l| l.name.clone()));
|
||||
push(po::try_unite_all(&refs).map_err(|e| EngineError::Other(e.to_string()))?, FillRule::NonZero, style_of(top), name);
|
||||
push(
|
||||
po::try_unite_all_with(&refs, options.precision).map_err(|e| EngineError::Other(e.to_string()))?,
|
||||
FillRule::NonZero,
|
||||
style_of(top),
|
||||
name,
|
||||
);
|
||||
} else {
|
||||
for l in &lv {
|
||||
if let Some((p, r)) = node_path(l) {
|
||||
@@ -467,7 +576,18 @@ fn run_pf(s: &mut Session, op: PathfinderOp) -> Result<Value> {
|
||||
if shapes.iter().any(|s| s.path.subpaths.iter().any(|sp| sp.anchors.iter().any(|a| !(a.p.x.is_finite() && a.p.y.is_finite())))) {
|
||||
return Err(EngineError::Other("paths contain invalid coordinates".into()));
|
||||
}
|
||||
let results = po::pathfinder(op, &shapes);
|
||||
let mut results = po::pathfinder_with(op, &shapes, options.precision);
|
||||
if options.remove_unpainted && matches!(op, PathfinderOp::Divide | PathfinderOp::Outline) {
|
||||
// Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork: the pieces
|
||||
// of objects with no fill (or only hidden ones) go.
|
||||
let filled = |st: &Style| st.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Fill(f) if f.visible && !f.paint.is_none()));
|
||||
results.retain(|r| styles.get(r.key as usize).is_some_and(filled));
|
||||
}
|
||||
if options.remove_redundant_points {
|
||||
for r in &mut results {
|
||||
r.path = po::remove_redundant_points(&r.path, options.precision);
|
||||
}
|
||||
}
|
||||
if results.iter().all(|r| r.path.is_empty()) {
|
||||
return Err(EngineError::Other(format!("{label} produced an empty result")));
|
||||
}
|
||||
|
||||
@@ -208,7 +208,7 @@ fn load(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool) -> Result<Loa
|
||||
let (sx, sy) = pt_per_px(img.ppi);
|
||||
let natural = Rect::new(0.0, 0.0, img.width as f64 * sx, img.height as f64 * sy);
|
||||
let link = src.path.map(|path| super::links::link_info(path, &src.bytes));
|
||||
let warnings = fileio::too_large_note(&img.blob.bytes).into_iter().collect();
|
||||
let warnings = fileio::size_note(&img.blob.bytes).into_iter().collect();
|
||||
return Ok(Loaded { name, format, art: Art::Image(img), natural, warnings, link, board: None });
|
||||
}
|
||||
if pdf {
|
||||
|
||||
@@ -384,11 +384,11 @@ pub fn spec(key: &str) -> Option<&'static PrefSpec> {
|
||||
}
|
||||
|
||||
/// Preferences kept as one object with a command of their own instead of [`PREF_SPECS`] rows (they
|
||||
/// aren't in the Preferences dialog): the Eyedropper Options (`eyedropper.setOptions`) and the
|
||||
/// Perspective Grid Options (`perspective.widget.options`). `prefs.get`
|
||||
/// and `prefs.set` take them by key (a partial object updates what it names) and `prefs.reset`
|
||||
/// without a category resets them.
|
||||
pub const PREF_GROUPS: &[&str] = &["eyedropper", "perspectiveWidget"];
|
||||
/// aren't in the Preferences dialog): the Eyedropper Options (`eyedropper.setOptions`), the
|
||||
/// Perspective Grid Options (`perspective.widget.options`) and the Pathfinder Options
|
||||
/// (`object.pathfinder.options`). `prefs.get` and `prefs.set` take them by key (a partial object
|
||||
/// updates what it names) and `prefs.reset` without a category resets them.
|
||||
pub const PREF_GROUPS: &[&str] = &["eyedropper", "perspectiveWidget", "pathfinder"];
|
||||
|
||||
/// Validate a value for preference group `key` against `current`.
|
||||
fn validate_group(key: &str, current: &Value, v: &Value) -> std::result::Result<Value, String> {
|
||||
@@ -397,6 +397,10 @@ fn validate_group(key: &str, current: &Value, v: &Value) -> std::result::Result<
|
||||
let cur: super::EyedropperOptions = serde_json::from_value(current.clone()).unwrap_or_default();
|
||||
cur.merged(v).map(|o| json!(o))
|
||||
}
|
||||
"pathfinder" => {
|
||||
let cur: super::PathfinderOptions = serde_json::from_value(current.clone()).unwrap_or_default();
|
||||
cur.merged(v).map(|o| json!(o))
|
||||
}
|
||||
"perspectiveWidget" => {
|
||||
let mut merged = current.clone();
|
||||
if let (Some(o), Some(p)) = (merged.as_object_mut(), v.as_object()) {
|
||||
|
||||
@@ -274,6 +274,20 @@ fn get_range(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({"text": text, "runs": runs, "length": len}))
|
||||
}
|
||||
|
||||
/// Keep `st`'s font style when its family has it, else take the family's closest one: a family
|
||||
/// whose styles are numbered (W3, W6) has no Regular (#4128). A family that isn't installed keeps
|
||||
/// the style as it is.
|
||||
pub(crate) fn fit_font_style(st: &mut CharStyle) {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let styles = db.styles(&st.font_family);
|
||||
if !styles.is_empty()
|
||||
&& !styles.iter().any(|s| s.eq_ignore_ascii_case(&st.font_style))
|
||||
&& let Some(face) = db.face(&st.font_family, &st.font_style)
|
||||
{
|
||||
st.font_style = face.style.clone();
|
||||
}
|
||||
}
|
||||
|
||||
/// Character attribute changes parsed from params (shared by range and whole-object styling).
|
||||
#[derive(Default)]
|
||||
pub(crate) struct CharChange {
|
||||
@@ -540,13 +554,7 @@ impl CharChange {
|
||||
st.font_family = f.clone();
|
||||
// Keep the style when the new family has it, else its closest match.
|
||||
if self.style.is_none() {
|
||||
let styles = vectorcraft_text::FontDb::global().styles(f);
|
||||
if !styles.is_empty()
|
||||
&& !styles.iter().any(|s| s.eq_ignore_ascii_case(&st.font_style))
|
||||
&& let Some(face) = vectorcraft_text::FontDb::global().face(f, &st.font_style)
|
||||
{
|
||||
st.font_style = face.style.clone();
|
||||
}
|
||||
fit_font_style(st);
|
||||
}
|
||||
}
|
||||
if let Some(v) = &self.style {
|
||||
|
||||
@@ -50,6 +50,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
has_thread_selection,
|
||||
remove
|
||||
),
|
||||
cmd!(
|
||||
"text.thread.break",
|
||||
"Break Thread",
|
||||
[],
|
||||
None,
|
||||
"{id, port: \"in\"|\"out\"} break the thread of area type or type on a path `id` before it (its in port) or after it (its out port), as a double-click on that port does: the story flows into the frames before the break, and the frames after it are left empty (still threaded with each other when two or more)",
|
||||
has_doc,
|
||||
break_thread
|
||||
),
|
||||
cmd!(query "text.thread.info", "Threads", [], None, "{} → [[id…]] every thread in order", has_doc, |s, _| {
|
||||
Ok(json!(s.doc()?.doc.text_threads.iter().map(|t| t.iter().map(|i| i.0).collect::<Vec<_>>()).collect::<Vec<_>>()))
|
||||
}),
|
||||
@@ -648,6 +657,56 @@ fn remove(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
ok()
|
||||
}
|
||||
|
||||
/// `text.thread.break`: a double-click on a threaded port. The thread is split there; the whole
|
||||
/// story moves into the frames before the split, and the frames after it are emptied, staying
|
||||
/// threaded with each other when two or more remain.
|
||||
fn break_thread(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "text.thread.break";
|
||||
let id = checked_id(s, p.get("id").unwrap_or(&Value::Null), C)?;
|
||||
let before = match p.get("port").and_then(Value::as_str) {
|
||||
Some("in") => true,
|
||||
Some("out") => false,
|
||||
_ => return Err(bad(C, "`port` must be \"in\" or \"out\"")),
|
||||
};
|
||||
let d = &s.doc()?.doc;
|
||||
let thread = d.text_threads.iter().find(|t| t.contains(&id)).cloned().unwrap_or_default();
|
||||
let at = thread.iter().position(|x| *x == id).map(|i| if before { i } else { i + 1 });
|
||||
let Some(at) = at.filter(|at| *at > 0 && *at < thread.len()) else {
|
||||
return Err(bad(C, if before { "no frame comes before `id` in a thread" } else { "no frame comes after `id` in a thread" }));
|
||||
};
|
||||
let (head, tail) = (thread[..at].to_vec(), thread[at..].to_vec());
|
||||
s.edit("Break Thread", |d, _| {
|
||||
let sources: Vec<TextObject> = thread.iter().filter_map(|id| text_of(d, *id).cloned()).collect();
|
||||
let mut story: Vec<TextRun> = sources.iter().flat_map(|t| t.runs.iter().cloned()).collect();
|
||||
let paras = vectorcraft_text::thread::story_paras(&sources.iter().collect::<Vec<_>>(), &[]);
|
||||
let end_style = story.last().map(|r| r.style.clone()).unwrap_or_default();
|
||||
let last_para = paras.last().cloned().unwrap_or_default();
|
||||
// Every frame but the first holds nothing, for the re-flow to share the story out among
|
||||
// the first part's frames once.
|
||||
for id in head.iter().skip(1).chain(&tail) {
|
||||
if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) {
|
||||
t.runs = vec![TextRun { text: String::new(), style: end_style.clone(), inline: None }];
|
||||
t.set_all_paras(last_para.clone());
|
||||
t.first_para_continues = false;
|
||||
refresh_bounds(t);
|
||||
}
|
||||
}
|
||||
if let Some(NodeKind::Text(t)) = head.first().and_then(|id| d.node_mut(*id)).map(|n| &mut n.kind) {
|
||||
vectorcraft_text::edit::normalize(&mut story);
|
||||
t.runs = story;
|
||||
t.set_paragraph_styles(paras);
|
||||
t.first_para_continues = false;
|
||||
refresh_bounds(t);
|
||||
}
|
||||
if let Some(i) = d.text_threads.iter().position(|t| *t == thread) {
|
||||
d.text_threads.splice(i..=i, [head, tail]);
|
||||
}
|
||||
d.text_threads.retain(|t| t.len() >= 2);
|
||||
Ok(())
|
||||
})?;
|
||||
ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -1056,6 +1115,68 @@ mod tests {
|
||||
(s, [a, b, c])
|
||||
}
|
||||
|
||||
fn continues(s: &Session, id: u64) -> bool {
|
||||
text_of(&s.doc().unwrap().doc, NodeId(id)).is_some_and(|t| t.first_para_continues)
|
||||
}
|
||||
|
||||
/// A double-click on a threaded port breaks the thread there: the story flows into the frames
|
||||
/// before the break and the frames after it are left empty, still threaded with each other
|
||||
/// when two or more. One undo step restores the thread and its text.
|
||||
#[test]
|
||||
fn break_splits_the_thread_and_the_story_flows_into_the_first_part() {
|
||||
let story = TEXT.repeat(12);
|
||||
let (mut s, [a, b, c]) = three_frames(&story, 40.0);
|
||||
let d = new_id(s.execute("text.create", &json!({"x": 200, "y": 100, "text": "", "area": {"width": 150, "height": 100}})).unwrap());
|
||||
s.execute("text.thread.add", &json!({"from": c, "to": d})).unwrap();
|
||||
let all = [a, b, c, d];
|
||||
let shown: Vec<String> = all.iter().map(|id| text(&s, *id)).collect();
|
||||
assert!(shown.iter().all(|t| !t.is_empty()), "each frame shows part of the story");
|
||||
let joined = |s: &Session, ids: &[u64]| ids.iter().map(|id| text(s, *id)).collect::<String>();
|
||||
// (frame, port, threads after, the frames that hold the story, the frames left empty)
|
||||
let cases = [
|
||||
(a, "out", vec![vec![b, c, d]], vec![a], vec![b, c, d]),
|
||||
(b, "in", vec![vec![b, c, d]], vec![a], vec![b, c, d]),
|
||||
(b, "out", vec![vec![a, b], vec![c, d]], vec![a, b], vec![c, d]),
|
||||
(d, "in", vec![vec![a, b, c]], vec![a, b, c], vec![d]),
|
||||
(c, "out", vec![vec![a, b, c]], vec![a, b, c], vec![d]),
|
||||
];
|
||||
for (id, port, after, full, empty) in cases {
|
||||
let case = format!("{port} port of {id}");
|
||||
s.execute("text.thread.break", &json!({"id": id, "port": port})).unwrap();
|
||||
assert_eq!(threads(&s), after, "{case}");
|
||||
assert_eq!(joined(&s, &full), story, "{case}: the story flows into the first part");
|
||||
assert!(empty.iter().all(|id| text(&s, *id).is_empty()), "{case}: the frames after the break are empty");
|
||||
assert!(!continues(&s, empty[0]), "{case}: the first frame after the break starts a paragraph");
|
||||
assert!(!continues(&s, a), "{case}: the first frame starts the story");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(threads(&s), [all.to_vec()], "{case}: undo");
|
||||
assert_eq!(all.iter().map(|id| text(&s, *id)).collect::<Vec<_>>(), shown, "{case}: undo");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn break_refuses_a_port_with_no_thread_and_bad_params() {
|
||||
let (mut s, [a, b, c]) = three_frames(&TEXT.repeat(4), 200.0);
|
||||
let lone = new_id(s.execute("text.create", &json!({"x": 400, "y": 10, "text": "Alone.", "area": {"width": 100, "height": 100}})).unwrap());
|
||||
let ids = [a, b, c, lone];
|
||||
let shown: Vec<String> = ids.iter().map(|id| text(&s, *id)).collect();
|
||||
let before = threads(&s);
|
||||
for params in [
|
||||
json!({"id": a, "port": "in"}),
|
||||
json!({"id": c, "port": "out"}),
|
||||
json!({"id": lone, "port": "out"}),
|
||||
json!({"id": lone, "port": "in"}),
|
||||
json!({"id": a, "port": "up"}),
|
||||
json!({"id": a}),
|
||||
json!({"port": "out"}),
|
||||
json!({"id": 9999, "port": "out"}),
|
||||
] {
|
||||
assert!(s.execute("text.thread.break", ¶ms).is_err(), "{params}");
|
||||
}
|
||||
assert_eq!(threads(&s), before);
|
||||
assert_eq!(ids.iter().map(|id| text(&s, *id)).collect::<Vec<_>>(), shown);
|
||||
}
|
||||
|
||||
/// Whether the document holds area type or type on a path `id`.
|
||||
fn is_frame(s: &Session, id: u64) -> bool {
|
||||
text_of(&s.doc().unwrap().doc, NodeId(id)).is_some()
|
||||
|
||||
@@ -120,7 +120,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Character",
|
||||
[],
|
||||
None,
|
||||
"{ids?|id?, font?, style?, size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour, keepModel?: bool (as paint.setFill), features?: [\"dlig\", \"-liga\", …] OpenType, start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits)}",
|
||||
"{ids?|id?, font?, style? (font alone: the style is kept when the new family has it, else its closest), size?: pt, leading?: pt|\"auto\", tracking?: 1/1000 em, justify?: \"auto\" (the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\", fill?: colour, keepModel?: bool (as paint.setFill), features?: [\"dlig\", \"-liga\", …] OpenType, start?: byte, end?: byte} (size/leading are document points after object scaling; with a range: the character attributes style that range and justify the paragraphs it touches; without: all the text) → {ids, overflow?: [id…] (area type and type on a path whose text no longer fits; left out when all fits)}",
|
||||
has_doc,
|
||||
set_style
|
||||
),
|
||||
@@ -811,6 +811,10 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
style_chars(t, range, |st| {
|
||||
if let Some(f) = &font {
|
||||
st.font_family = f.clone();
|
||||
// Keep the style when the new family has it, else its closest match (#4128).
|
||||
if style.is_none() {
|
||||
super::textedit::fit_font_style(st);
|
||||
}
|
||||
}
|
||||
if let Some(f) = &style {
|
||||
st.font_style = f.clone();
|
||||
@@ -853,6 +857,9 @@ fn set_style(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
st.font_family = f.clone();
|
||||
st.font_version = None;
|
||||
st.font_axes.clear();
|
||||
if style.is_none() {
|
||||
super::textedit::fit_font_style(st);
|
||||
}
|
||||
}
|
||||
if let Some(f) = &style {
|
||||
st.font_style = f.clone();
|
||||
@@ -1650,6 +1657,369 @@ mod area_tests {
|
||||
assert_eq!((list(&s, 0), list(&s, 1), list(&s, 2)), (None, None, None));
|
||||
}
|
||||
|
||||
/// The glyphs the layout of type `id` draws, each with its glyph, where it is drawn and the
|
||||
/// transform it is drawn with (in thousandths), from the top line down and left to right.
|
||||
fn drawn_glyphs(s: &Session, id: u64) -> Vec<(u32, i64, i64, [i64; 6])> {
|
||||
let Some(NodeKind::Text(t)) = s.doc().unwrap().doc.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") };
|
||||
let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
|
||||
let milli = |v: f64| (v * 1000.0).round() as i64;
|
||||
let mut v: Vec<(u32, i64, i64, [i64; 6])> = lay
|
||||
.glyphs
|
||||
.iter()
|
||||
.filter(|g| !g.outline.elements().is_empty())
|
||||
.map(|g| (g.gid, milli(g.origin.x), milli(g.origin.y), g.xf.as_coeffs().map(milli)))
|
||||
.collect();
|
||||
v.sort_by_key(|&(_, x, y, _)| (y, x));
|
||||
v
|
||||
}
|
||||
|
||||
/// Type › Bullets and Numbering › Convert to Text: `text.convertListToText` writes each list
|
||||
/// paragraph's marker before its text as characters in the marker's style, followed by a tab,
|
||||
/// turns the list off, and gives the paragraph a plain left tab stop at the left indent where
|
||||
/// the marker's tab went to it, so every glyph is drawn where it was: bullets in area type (a
|
||||
/// wrapped item, an empty item, a right-aligned stop at the indent and a stop before it, both
|
||||
/// with leaders), numbers narrower and wider than the hanging indent (one reaching a stop with
|
||||
/// a leader past it), and point and vertical type. A paragraph with a tab of its own keeps its
|
||||
/// stops past the indent. The characters can be styled and deleted, and one undo brings the
|
||||
/// lists back.
|
||||
#[test]
|
||||
fn convert_to_text_writes_the_markers_where_they_were_drawn() {
|
||||
use vectorcraft_doc::text::{Bullet, ParaList};
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
let text = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => (**t).clone(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
let markers = |s: &Session, id: u64| vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text(s, id)).markers.len();
|
||||
let tabs =
|
||||
|s: &Session, id: u64, k: usize| text(s, id).para_at(k).tabs.iter().map(|t| (t.position, t.align, t.leader.clone())).collect::<Vec<_>>();
|
||||
let long = "The quick brown fox jumps over the lazy dog and runs far away into the woods beyond the hill";
|
||||
let id = s
|
||||
.execute("text.create", &json!({"x": 10, "y": 10, "text": format!("One\n{long}\n\nFour\nFive"), "area": {"width": 200, "height": 400}}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let (four, five) = (long.len() + 6, long.len() + 11);
|
||||
s.execute("text.setFormat", &json!({"ids": [id], "list": "bullet"})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [id], "bullet": "square", "start": four, "end": four})).unwrap();
|
||||
// A right-aligned stop with a leader at the fourth item's left indent, and a stop with a
|
||||
// leader before the fifth item's: the bullets' tabs go to the indent and to that stop and
|
||||
// draw no leader.
|
||||
s.execute("text.tabs.set", &json!({"ids": [id], "start": four, "end": four, "stops": [{"position": 18, "align": "right", "leader": "."}]}))
|
||||
.unwrap();
|
||||
s.execute("text.tabs.set", &json!({"ids": [id], "start": five, "end": five, "stops": [{"position": 10, "leader": "."}]})).unwrap();
|
||||
// The first character larger, raised and underlined: the bullet takes its size alone. The
|
||||
// fourth item's first character is larger than the break before it.
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 1, "size": 20, "baselineShift": 4, "underline": true})).unwrap();
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": four, "end": four + 1, "size": 20})).unwrap();
|
||||
let listed = text(&s, id);
|
||||
let before = drawn_glyphs(&s, id);
|
||||
assert_eq!(markers(&s, id), 4, "the empty item has no bullet");
|
||||
let reply = s.execute("text.convertListToText", &json!({"ids": [id]})).unwrap();
|
||||
let inserted = |at: usize| json!({"id": id, "at": at, "length": 4});
|
||||
assert_eq!(reply, json!({"ids": [id], "converted": 5, "inserted": [inserted(0), inserted(4), inserted(four), inserted(five)]}));
|
||||
assert_eq!(drawn_glyphs(&s, id), before, "every glyph is drawn where it was");
|
||||
let t = text(&s, id);
|
||||
assert_eq!(t.plain_text(), format!("\u{2022}\tOne\n\u{2022}\t{long}\n\n\u{25AA}\tFour\n\u{2022}\tFive"));
|
||||
assert!((0..5).all(|k| t.para_at(k).list.is_none()), "no paragraph is in a list");
|
||||
assert_eq!(markers(&s, id), 0);
|
||||
let left = vectorcraft_doc::TabAlign::Left;
|
||||
let plain_stop = |position| vec![(position, left, String::new())];
|
||||
assert_eq!(
|
||||
(tabs(&s, id, 0), tabs(&s, id, 1), tabs(&s, id, 2), tabs(&s, id, 3), tabs(&s, id, 4)),
|
||||
(plain_stop(18.0), plain_stop(18.0), vec![], plain_stop(18.0), plain_stop(10.0)),
|
||||
"a plain left stop at the left indent (in place of the right-aligned one), none in the empty item, and the stop the \
|
||||
fifth item's tab went to without its leader"
|
||||
);
|
||||
let bullet = &t.runs[0];
|
||||
assert_eq!(
|
||||
(bullet.text.as_str(), bullet.style.size, bullet.style.baseline_shift, bullet.style.underline),
|
||||
("\u{2022}\t", 20.0, 0.0, false),
|
||||
"the bullet has the first character's size without its baseline shift and underline"
|
||||
);
|
||||
// The characters are text: they take a style and can be deleted.
|
||||
s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 3, "size": 30})).unwrap();
|
||||
assert_eq!(text(&s, id).runs[0].style.size, 30.0);
|
||||
s.execute("text.editRange", &json!({"id": id, "start": 0, "end": 4, "insert": ""})).unwrap();
|
||||
assert!(text(&s, id).plain_text().starts_with("One\n\u{2022}\t"));
|
||||
for _ in 0..3 {
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
}
|
||||
let back = text(&s, id);
|
||||
assert_eq!(back.para_at(3).list, Some(ParaList::bulleted(Bullet::Square)));
|
||||
assert_eq!((back.runs, back.para, back.paras), (listed.runs, listed.para, listed.paras), "one undo step");
|
||||
assert_eq!(drawn_glyphs(&s, id), before);
|
||||
// Numbers 1 to 9 at 20 pt are narrower than the hanging indent, 10 is wider and takes the
|
||||
// text to the next default stop, and 11 to its stop at 72 pt, whose leader the number's tab
|
||||
// draws neither before nor after.
|
||||
let items = (1..=11).map(|i| format!("Item {i}")).collect::<Vec<_>>().join("\n");
|
||||
let id =
|
||||
s.execute("text.create", &json!({"x": 300, "y": 10, "size": 20, "text": items, "area": {"width": 300, "height": 600}})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [id], "list": "number"})).unwrap();
|
||||
let eleven = 9 * 7 + 8;
|
||||
s.execute("text.tabs.set", &json!({"ids": [id], "start": eleven, "end": eleven, "stops": [{"position": 72, "leader": "."}]})).unwrap();
|
||||
let before = drawn_glyphs(&s, id);
|
||||
s.execute("text.convertListToText", &json!({"ids": [id]})).unwrap();
|
||||
assert_eq!(drawn_glyphs(&s, id), before, "numbers");
|
||||
let expected = (1..=11).map(|i| format!("{i}.\tItem {i}")).collect::<Vec<_>>().join("\n");
|
||||
assert_eq!(text(&s, id).plain_text(), expected);
|
||||
assert_eq!((tabs(&s, id, 0), tabs(&s, id, 9), tabs(&s, id, 10)), (plain_stop(18.0), vec![], plain_stop(72.0)));
|
||||
// A paragraph with a tab of its own keeps its stops past the left indent, which that tab
|
||||
// can reach.
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 650, "size": 30, "text": "Item\tvalue"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [id], "list": "number"})).unwrap();
|
||||
s.execute("text.tabs.set", &json!({"ids": [id], "stops": [{"position": 72, "leader": "."}, {"position": 200}]})).unwrap();
|
||||
s.execute("text.convertListToText", &json!({"ids": [id]})).unwrap();
|
||||
assert_eq!(text(&s, id).plain_text(), "1.\tItem\tvalue");
|
||||
assert_eq!(tabs(&s, id, 0), [(72.0, left, ".".to_string()), (200.0, left, String::new())]);
|
||||
// A 30 pt number's tab to a right-aligned stop aligns the whole paragraph there, trailing
|
||||
// space included, and a converted tab aligns the rest of its line: a plain left stop where
|
||||
// the number's tab ended keeps the text in place. A right-aligned stop before the left stop
|
||||
// the number's tab reached, which the wrapped paragraph's width kept the number's tab from,
|
||||
// would catch the converted tab, which measures only the first line: it goes. The lines are
|
||||
// compared with the Single-line Composer, as a paragraph with a tab is broken line by line.
|
||||
let right = vectorcraft_doc::TabAlign::Right;
|
||||
for (text_in, width, stops, kept) in [
|
||||
("One ", 300, json!([{"position": 200, "align": "right"}]), vec![(200.0, right, String::new())]),
|
||||
("The quick brown fox jumps over the lazy dog", 230, json!([{"position": 100, "align": "right"}, {"position": 150}]), vec![]),
|
||||
] {
|
||||
let id = s
|
||||
.execute("text.create", &json!({"x": 10, "y": 600, "size": 30, "text": text_in, "area": {"width": width, "height": 300}}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [id], "list": "number", "composer": "singleLine"})).unwrap();
|
||||
s.execute("text.tabs.set", &json!({"ids": [id], "stops": stops})).unwrap();
|
||||
let before = drawn_glyphs(&s, id);
|
||||
s.execute("text.convertListToText", &json!({"ids": [id]})).unwrap();
|
||||
assert_eq!(drawn_glyphs(&s, id), before, "{text_in:?}");
|
||||
let after = tabs(&s, id, 0);
|
||||
assert_eq!(
|
||||
(after.first().map(|t| (t.1, t.2.as_str())), after.get(1..).map(<[_]>::to_vec)),
|
||||
(Some((left, "")), Some(kept)),
|
||||
"{text_in:?}"
|
||||
);
|
||||
}
|
||||
// Overset items, which the layout leaves out, get the stop by the same rule: a 30 pt number is
|
||||
// wider than the hanging indent, a 12 pt bullet is not.
|
||||
for (size, list, text_after, stop) in
|
||||
[(30, "number", "1.\tOne\n2.\tTwo", vec![]), (12, "bullet", "\u{2022}\tOne\n\u{2022}\tTwo", plain_stop(18.0))]
|
||||
{
|
||||
let id = s
|
||||
.execute("text.create", &json!({"x": 10, "y": 500, "size": size, "text": "One\nTwo", "area": {"width": 200, "height": size + 10}}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [id], "list": list})).unwrap();
|
||||
assert_eq!(markers(&s, id), 1, "the second item is overset");
|
||||
s.execute("text.convertListToText", &json!({"ids": [id]})).unwrap();
|
||||
assert_eq!((text(&s, id).plain_text().as_str(), tabs(&s, id, 1)), (text_after, stop), "{size} pt");
|
||||
}
|
||||
// Point type and vertical type.
|
||||
for vertical in [false, true] {
|
||||
let id =
|
||||
s.execute("text.create", &json!({"x": 400, "y": 700, "vertical": vertical, "text": "One\nTwo"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [id], "list": "number"})).unwrap();
|
||||
let before = drawn_glyphs(&s, id);
|
||||
s.execute("text.convertListToText", &json!({"ids": [id]})).unwrap();
|
||||
assert_eq!(drawn_glyphs(&s, id), before, "vertical {vertical}");
|
||||
assert_eq!(text(&s, id).plain_text(), "1.\tOne\n2.\tTwo");
|
||||
}
|
||||
// Type with no list paragraph: nothing to convert and no undo step.
|
||||
let plain = s.execute("text.create", &json!({"x": 10, "y": 700, "text": "Plain"})).unwrap()["id"].as_u64().unwrap();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
assert_eq!(s.execute("text.convertListToText", &json!({"ids": [plain]})).unwrap(), json!({"ids": [], "converted": 0, "inserted": []}));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps);
|
||||
}
|
||||
|
||||
/// A right-to-left list paragraph converted to text starts with the number, its period and a
|
||||
/// tab, which are read first: the line draws its glyphs in the order it drew them with the
|
||||
/// marker, the number at the right with its period at its left. Letters and roman numerals
|
||||
/// would make the paragraph run left to right, so the paragraph gets the direction it ran in;
|
||||
/// digits leave the direction unset.
|
||||
#[test]
|
||||
fn a_right_to_left_list_paragraph_converts_to_text_read_first() {
|
||||
use vectorcraft_doc::ParaDirection;
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
|
||||
for (number, text, direction) in [
|
||||
("arabic", "1.\tשלום\n2.\tעולם", None),
|
||||
("upperLetters", "A.\tשלום\nB.\tעולם", Some(ParaDirection::RightToLeft)),
|
||||
("upperRoman", "I.\tשלום\nII.\tעולם", Some(ParaDirection::RightToLeft)),
|
||||
] {
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "שלום\nעולם", "area": {"width": 200, "height": 200}})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [id], "number": number})).unwrap();
|
||||
// `drawn_glyphs` lists the first line first, from left to right.
|
||||
let order = |s: &Session| {
|
||||
let glyphs = drawn_glyphs(s, id);
|
||||
let top = glyphs.first().map_or(0, |g| g.2);
|
||||
glyphs.into_iter().filter(|g| g.2 == top).map(|g| g.0).collect::<Vec<_>>()
|
||||
};
|
||||
let before = order(&s);
|
||||
s.execute("text.convertListToText", &json!({"ids": [id]})).unwrap();
|
||||
let Some(NodeKind::Text(t)) = s.doc().unwrap().doc.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") };
|
||||
assert_eq!(t.plain_text(), text);
|
||||
assert!(t.para_at(0).list.is_none() && t.para_at(1).list.is_none());
|
||||
let directions = (t.para_at(0).direction, t.para_at(1).direction);
|
||||
assert_eq!(order(&s), before, "{number}: the first line's glyphs from left to right");
|
||||
assert_eq!(directions, (direction, direction), "{number}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert to Text in threaded type writes the numbers the story counted through its frames,
|
||||
/// and both frames draw every glyph where it was. A paragraph that continues into the next
|
||||
/// frame gets its number once, where it starts, also when only the later frame is named, and
|
||||
/// empty frames after a converted paragraph leave its list with it.
|
||||
#[test]
|
||||
fn threaded_numbers_convert_to_text_as_the_story_counted_them() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap();
|
||||
let plain = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.plain_text(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
let numbers = |s: &Session, id: u64| {
|
||||
let Some(NodeKind::Text(t)) = s.doc().unwrap().doc.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") };
|
||||
vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).markers.iter().map(|m| m.text.clone()).collect::<Vec<_>>()
|
||||
};
|
||||
let thread = |s: &mut Session, text: &str| {
|
||||
let a = s.execute("text.create", &json!({"x": 10, "y": 10, "text": text, "area": {"width": 150, "height": 60}})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [a, b], "list": "number"})).unwrap();
|
||||
(a, b)
|
||||
};
|
||||
// Whole paragraphs: the first frame ends with a paragraph break.
|
||||
let (a, b) = thread(&mut s, &(1..=10).map(|i| format!("Item {i}")).collect::<Vec<_>>().join("\n"));
|
||||
let first = numbers(&s, a).len();
|
||||
assert!((2..10).contains(&first) && plain(&s, a).ends_with('\n'), "both frames hold items: {first}");
|
||||
let before = (drawn_glyphs(&s, a), drawn_glyphs(&s, b));
|
||||
let reply = s.execute("text.convertListToText", &json!({"ids": [a, b]})).unwrap();
|
||||
assert_eq!(reply["converted"], 10, "each paragraph once");
|
||||
assert_eq!((drawn_glyphs(&s, a), drawn_glyphs(&s, b)), before, "both frames");
|
||||
let story = (1..=10).map(|i| format!("{i}.\tItem {i}")).collect::<Vec<_>>().join("\n");
|
||||
assert_eq!(plain(&s, a) + &plain(&s, b), story);
|
||||
assert!(plain(&s, b).starts_with(&format!("{n}.\tItem {n}", n = first + 1)));
|
||||
// The empty part after the first frame's last break and the second frame's first item are
|
||||
// one paragraph: a caret at the end of the first frame converts that item.
|
||||
let (a, b) = thread(&mut s, &(1..=10).map(|i| format!("Item {i}")).collect::<Vec<_>>().join("\n"));
|
||||
let end = plain(&s, a).len();
|
||||
let reply = s.execute("text.convertListToText", &json!({"ids": [a], "start": end, "end": end})).unwrap();
|
||||
assert_eq!(reply["converted"], 1);
|
||||
assert!(plain(&s, b).starts_with(&format!("{n}.\tItem {n}\nItem", n = first + 1)), "{}", plain(&s, b));
|
||||
// A paragraph split between the frames, with only the second frame named.
|
||||
let long = "The quick brown fox jumps over the lazy dog. ".repeat(4);
|
||||
let (a, b) = thread(&mut s, &format!("One\nTwo\n{long}\nFour"));
|
||||
assert!(!plain(&s, a).ends_with('\n'), "the third paragraph goes on in the second frame");
|
||||
// A paragraph with a tab is broken line by line, so the lines are compared with the
|
||||
// Single-line Composer, which breaks the listed paragraph the same way.
|
||||
s.execute("text.setFormat", &json!({"ids": [a, b], "composer": "singleLine"})).unwrap();
|
||||
let before = (drawn_glyphs(&s, a), drawn_glyphs(&s, b));
|
||||
s.execute("text.convertListToText", &json!({"ids": [b]})).unwrap();
|
||||
assert_eq!((drawn_glyphs(&s, a), drawn_glyphs(&s, b)), before, "both frames, with the paragraph split between them");
|
||||
assert_eq!(plain(&s, a) + &plain(&s, b), format!("One\nTwo\n3.\t{long}\n4.\tFour"));
|
||||
assert_eq!(numbers(&s, a), ["1.", "2."], "the paragraphs of the first frame alone stay in the list");
|
||||
let Some(NodeKind::Text(second)) = s.doc().unwrap().doc.node(NodeId(b)).map(|n| &n.kind) else { panic!("text") };
|
||||
assert!(second.para_at(0).list.is_none(), "the third paragraph's part in the second frame leaves the list too");
|
||||
// One item that fits in the first of three frames: the two empty frames after it leave the
|
||||
// list too, so the re-flowed thread draws no number before the converted one.
|
||||
let a = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "Item", "area": {"width": 150, "height": 60}})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 60})).unwrap()["id"].as_u64().unwrap();
|
||||
let c = s.execute("shape.rectangle", &json!({"x": 400, "y": 10, "width": 150, "height": 60})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b, c]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [a, b, c], "list": "number"})).unwrap();
|
||||
assert_eq!((plain(&s, b), plain(&s, c), numbers(&s, a)), (String::new(), String::new(), vec!["1.".to_string()]));
|
||||
assert_eq!(s.execute("text.convertListToText", &json!({"ids": [a]})).unwrap()["converted"], 1);
|
||||
assert_eq!(plain(&s, a), "1.\tItem");
|
||||
assert_eq!(numbers(&s, a), Vec::<String>::new(), "no number drawn before the converted one");
|
||||
for id in [a, b, c] {
|
||||
let Some(NodeKind::Text(t)) = s.doc().unwrap().doc.node(NodeId(id)).map(|n| &n.kind) else { panic!("text") };
|
||||
assert!(t.para_at(0).list.is_none(), "frame {id} leaves the list");
|
||||
}
|
||||
// An overset 30 pt number, wider than the hanging indent, in a last frame that starts
|
||||
// inside a paragraph: its tab goes to the next stop, so it gets no stop at the left indent.
|
||||
let a = s
|
||||
.execute("text.create", &json!({"x": 10, "y": 10, "size": 30, "text": format!("{long}\nTwo"), "area": {"width": 150, "height": 80}}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 80})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [a, b], "list": "number"})).unwrap();
|
||||
let Some(NodeKind::Text(second)) = s.doc().unwrap().doc.node(NodeId(b)).map(|n| &n.kind) else { panic!("text") };
|
||||
assert!(second.first_para_continues && second.plain_text().ends_with("\nTwo"), "{:?}", second.plain_text());
|
||||
assert_eq!(numbers(&s, b).len(), 0, "the second item is overset");
|
||||
s.execute("text.convertListToText", &json!({"ids": [b]})).unwrap();
|
||||
let Some(NodeKind::Text(second)) = s.doc().unwrap().doc.node(NodeId(b)).map(|n| &n.kind) else { panic!("text") };
|
||||
assert!(second.plain_text().ends_with("\n2.\tTwo"), "{:?}", second.plain_text());
|
||||
assert!(second.para_at(1).tabs.is_empty(), "no stop at the left indent: {:?}", second.para_at(1).tabs);
|
||||
}
|
||||
|
||||
/// `text.convertListToText` sent while the Type tool edits (as from MCP or the control channel)
|
||||
/// moves the tool's anchor and caret past the characters it inserts at or before them, so that
|
||||
/// neither lands inside a bullet. In threaded type, when the text before the caret moves to the
|
||||
/// frame before, the caret goes with its character into that frame, which becomes the
|
||||
/// selection.
|
||||
#[test]
|
||||
fn convert_to_text_moves_the_type_tools_selection() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 600, "height": 300})).unwrap();
|
||||
let plain = |s: &Session, id: u64| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind {
|
||||
NodeKind::Text(t) => t.plain_text(),
|
||||
_ => panic!("text"),
|
||||
};
|
||||
let selection = |s: &Session| {
|
||||
let o = s.tool_options();
|
||||
(o["editing"].as_u64(), o["anchor"].as_u64(), o["caret"].as_u64())
|
||||
};
|
||||
let id = s.execute("text.create", &json!({"x": 10, "y": 50, "text": "One\nTwo"})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [id], "list": "bullet"})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [id]})).unwrap();
|
||||
s.select_tool("type", Default::default()).unwrap();
|
||||
// From after the O of One to after the T of Two.
|
||||
s.set_tool_option("textSelection", &json!({"editing": id, "anchor": 1, "caret": 5}));
|
||||
s.execute("text.convertListToText", &json!({})).unwrap();
|
||||
let text = plain(&s, id);
|
||||
assert_eq!(text, "\u{2022}\tOne\n\u{2022}\tTwo");
|
||||
assert_eq!(selection(&s), (Some(id), Some(5), Some(13)), "the anchor after the O, the caret after the T");
|
||||
assert!(text.is_char_boundary(5) && text.is_char_boundary(13));
|
||||
|
||||
let long = "The quick brown fox jumps over the lazy dog. ".repeat(4);
|
||||
let a = s
|
||||
.execute("text.create", &json!({"x": 10, "y": 10, "text": format!("One\nTwo\n{long}\nFour"), "area": {"width": 150, "height": 60}}))
|
||||
.unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
let b = s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 150, "height": 200})).unwrap()["id"].as_u64().unwrap();
|
||||
s.select_tool("selection", Default::default()).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
|
||||
s.execute("text.thread.create", &json!({})).unwrap();
|
||||
s.execute("text.setFormat", &json!({"ids": [a, b], "list": "number"})).unwrap();
|
||||
assert!(plain(&s, b).starts_with("dog. "), "the second frame starts with the dog: {:?}", plain(&s, b));
|
||||
s.execute("select.set", &json!({"ids": [b]})).unwrap();
|
||||
s.select_tool("type", Default::default()).unwrap();
|
||||
// The caret after the d of dog, at the start of the second frame.
|
||||
s.set_tool_option("textSelection", &json!({"editing": b, "anchor": 1, "caret": 1}));
|
||||
s.execute("text.convertListToText", &json!({"ids": [b]})).unwrap();
|
||||
let first = plain(&s, a);
|
||||
assert!(first.ends_with("lazy dog. "), "the dog moved to the first frame: {first:?}");
|
||||
let after_d = (first.len() - "og. ".len()) as u64;
|
||||
assert_eq!(selection(&s), (Some(a), Some(after_d), Some(after_d)), "the caret is after the d of dog in the first frame");
|
||||
assert_eq!(s.active().unwrap().selection.objects, vec![NodeId(a)], "the first frame is selected");
|
||||
}
|
||||
|
||||
/// Type › Create Outlines makes a path of a list item's bullet as well as of its characters.
|
||||
#[test]
|
||||
fn create_outlines_makes_a_path_of_the_bullet() {
|
||||
|
||||
+138
-26
@@ -7,9 +7,6 @@ use vectorcraft_geom::Point;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Illustrator keeps up to 25 views per document.
|
||||
pub const MAX_VIEWS: usize = 25;
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
@@ -17,7 +14,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New View…",
|
||||
["View"],
|
||||
None,
|
||||
"{name?, center: [x, y], zoom: (1 = 100%), rotation?: deg} save a view (the app fills in the current one) → {name, index}",
|
||||
"{name?, center: [x, y], zoom: (1 = 100%), rotation?: deg} save a view in the document (the app fills in the current one; default \"View N\"; at most 25, names up to 255 characters, each name once) → {name, index}",
|
||||
has_doc,
|
||||
new_view
|
||||
),
|
||||
@@ -26,8 +23,8 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit Views…",
|
||||
["View"],
|
||||
None,
|
||||
"{name, newName?, delete?: bool} rename or delete a saved view; no params → {views}",
|
||||
has_doc,
|
||||
"{name, newName?: rename, delete?: bool} | {edits: [{name, newName?, delete?}…]} rename or delete saved views, all in one undo step; names are those before the edit and must stay unique; no params → {views}",
|
||||
has_views,
|
||||
edit_views
|
||||
),
|
||||
cmd!(query "view.saved.list", "Saved Views", [], None, "{} → {views: [{name, center, zoom, rotation}]}", has_doc, list_views),
|
||||
@@ -66,12 +63,12 @@ fn new_view(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
None => 0.0,
|
||||
};
|
||||
let st = s.doc()?;
|
||||
if st.doc.views.len() >= MAX_VIEWS {
|
||||
return Err(bad(C, format!("a document keeps at most {MAX_VIEWS} views")));
|
||||
if st.doc.views.len() >= SavedView::MAX {
|
||||
return Err(bad(C, format!("a document keeps at most {} views", SavedView::MAX)));
|
||||
}
|
||||
let name = match str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()) {
|
||||
Some(n) => n.to_string(),
|
||||
None => (1..).map(|i| format!("View {i}")).find(|n| !st.doc.views.iter().any(|v| &v.name == n)).unwrap_or_default(),
|
||||
let name = match str_param(p, "name").and_then(SavedView::clean_name) {
|
||||
Some(n) => n,
|
||||
None => SavedView::default_name(&st.doc.views),
|
||||
};
|
||||
if st.doc.views.iter().any(|v| v.name == name) {
|
||||
return Err(bad(C, format!("a view named `{name}` exists")));
|
||||
@@ -84,26 +81,60 @@ fn new_view(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "name": name, "index": index }))
|
||||
}
|
||||
|
||||
/// Edit Views… needs a document with at least one saved view.
|
||||
fn has_views(s: &Session) -> std::result::Result<(), String> {
|
||||
let st = s.active().ok_or("no document open")?;
|
||||
if st.doc.views.is_empty() { Err("no saved views".into()) } else { Ok(()) }
|
||||
}
|
||||
|
||||
fn edit_views(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "view.saved.edit";
|
||||
let Some(name) = str_param(p, "name") else { return list_views(s, p) };
|
||||
let i = s.doc()?.doc.views.iter().position(|v| v.name == name).ok_or_else(|| bad(C, format!("no view named `{name}`")))?;
|
||||
if bool_or(p, "delete", false) {
|
||||
s.edit("Delete View", |d, _| {
|
||||
d.views.remove(i);
|
||||
let (edits, one) = match p.get("edits").and_then(Value::as_array) {
|
||||
Some(list) => (list.as_slice(), false),
|
||||
None if str_param(p, "name").is_some() => (std::slice::from_ref(p), true),
|
||||
None => return list_views(s, p),
|
||||
};
|
||||
let before = s.doc()?.doc.views.clone();
|
||||
// Edits name the views as they are now, so they don't depend on each other's order.
|
||||
let mut after: Vec<Option<SavedView>> = before.iter().cloned().map(Some).collect();
|
||||
for e in edits {
|
||||
let name = str_param(e, "name").ok_or_else(|| bad(C, "missing name"))?;
|
||||
let i = before.iter().position(|v| v.name == name).ok_or_else(|| bad(C, format!("no view named `{name}`")))?;
|
||||
let Some(slot) = after.get_mut(i) else { continue };
|
||||
if bool_or(e, "delete", false) {
|
||||
*slot = None;
|
||||
} else if let Some(v) = slot {
|
||||
v.name = str_param(e, "newName").and_then(SavedView::clean_name).ok_or_else(|| bad(C, "give newName or delete"))?;
|
||||
}
|
||||
}
|
||||
let after: Vec<SavedView> = after.into_iter().flatten().collect();
|
||||
let mut names = std::collections::HashSet::with_capacity(after.len());
|
||||
for v in &after {
|
||||
if !names.insert(v.name.as_str()) {
|
||||
return Err(bad(C, format!("a view named `{}` exists", v.name)));
|
||||
}
|
||||
}
|
||||
// One rename or delete keeps the name of its step; several are one Edit Views step.
|
||||
let deleted = after.len() < before.len();
|
||||
let label = if !one {
|
||||
"Edit Views"
|
||||
} else if deleted {
|
||||
"Delete View"
|
||||
} else {
|
||||
"Rename View"
|
||||
};
|
||||
let result = match (one, deleted) {
|
||||
(true, true) => json!({ "deleted": str_param(p, "name") }),
|
||||
(true, false) => json!({ "name": str_param(p, "newName").and_then(SavedView::clean_name) }),
|
||||
(false, _) => json!({ "views": after }),
|
||||
};
|
||||
if before != after {
|
||||
s.edit(label, |d, _| {
|
||||
d.views = after;
|
||||
Ok(())
|
||||
})?;
|
||||
return Ok(json!({ "deleted": name }));
|
||||
}
|
||||
let new = str_param(p, "newName").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(C, "give newName or delete"))?.to_string();
|
||||
if s.doc()?.doc.views.iter().any(|v| v.name == new) {
|
||||
return Err(bad(C, format!("a view named `{new}` exists")));
|
||||
}
|
||||
s.edit("Rename View", |d, _| {
|
||||
d.views[i].name = new.clone();
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "name": new }))
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -154,4 +185,85 @@ mod tests {
|
||||
let bytes = vectorcraft_format::save_file(&s.doc().unwrap().doc);
|
||||
assert_eq!(vectorcraft_format::load(&bytes).unwrap().views[0].name, "Overview");
|
||||
}
|
||||
|
||||
fn names(s: &mut Session) -> Vec<String> {
|
||||
s.doc().unwrap().doc.views.iter().map(|v| v.name.clone()).collect()
|
||||
}
|
||||
|
||||
fn session_with_views(names: &[&str]) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
for (i, n) in names.iter().enumerate() {
|
||||
s.execute("view.saved.new", &json!({"name": n, "center": [i, i], "zoom": 1 + i})).unwrap();
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Two named views go out with the file and come back with their names, centres, zooms and
|
||||
/// rotations, in order.
|
||||
#[test]
|
||||
fn saved_views_reopen_with_their_names_and_viewports() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({})).unwrap();
|
||||
s.execute("view.saved.new", &json!({"name": "Overview", "center": [306, 396], "zoom": 0.5})).unwrap();
|
||||
s.execute("view.saved.new", &json!({"name": "Logo detail", "center": [40.25, -12.5], "zoom": 8, "rotation": -30})).unwrap();
|
||||
let saved = s.doc().unwrap().doc.views.clone();
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save_file(&s.doc().unwrap().doc)).unwrap();
|
||||
assert_eq!(back.views, saved);
|
||||
assert_eq!((back.views[1].center.x, back.views[1].center.y, back.views[1].zoom, back.views[1].rotation), (40.25, -12.5, 8.0, -30.0));
|
||||
}
|
||||
|
||||
/// Edit Views… applies its renames and deletes together, as one undo step, by the names the
|
||||
/// views had before (so two can swap names); a shared or unknown name changes nothing.
|
||||
#[test]
|
||||
fn edit_views_applies_several_edits_as_one_step() {
|
||||
let mut s = session_with_views(&["A", "B", "C"]);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let edits = json!({"edits": [
|
||||
{"name": "A", "newName": "B"},
|
||||
{"name": "B", "newName": " A "},
|
||||
{"name": "C", "delete": true},
|
||||
]});
|
||||
let r = s.execute("view.saved.edit", &edits).unwrap();
|
||||
assert_eq!(r["views"].as_array().map(Vec::len), Some(2));
|
||||
assert_eq!(names(&mut s), ["B", "A"]);
|
||||
// The views keep their viewports under their new names.
|
||||
assert_eq!(s.doc().unwrap().doc.views[0].zoom, 1.0);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(names(&mut s), ["A", "B", "C"]);
|
||||
for bad in [
|
||||
json!({"edits": [{"name": "A", "newName": "C"}]}),
|
||||
json!({"edits": [{"name": "A", "newName": "X"}, {"name": "B", "newName": "X"}]}),
|
||||
json!({"edits": [{"name": "A", "delete": true}, {"name": "Nope", "delete": true}]}),
|
||||
json!({"edits": [{"name": "A", "newName": " "}]}),
|
||||
] {
|
||||
assert!(s.execute("view.saved.edit", &bad).is_err(), "accepted {bad}");
|
||||
assert_eq!(names(&mut s), ["A", "B", "C"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A document keeps at most 25 views; unnamed ones take the first free "View N", and names are
|
||||
/// capped like other names the user gives.
|
||||
#[test]
|
||||
fn a_document_keeps_at_most_25_views() {
|
||||
let all: Vec<String> = (0..25).map(|i| format!("V{i}")).collect();
|
||||
let mut s = session_with_views(&all.iter().map(String::as_str).collect::<Vec<_>>());
|
||||
assert!(s.execute("view.saved.new", &json!({"name": "One too many", "center": [0, 0], "zoom": 1})).is_err());
|
||||
assert_eq!(s.doc().unwrap().doc.views.len(), 25);
|
||||
s.execute("view.saved.edit", &json!({"name": "V0", "delete": true})).unwrap();
|
||||
assert_eq!(s.execute("view.saved.new", &json!({"center": [0, 0], "zoom": 1})).unwrap()["name"], "View 1");
|
||||
s.execute("view.saved.edit", &json!({"name": "V1", "delete": true})).unwrap();
|
||||
let long = "x".repeat(1000);
|
||||
assert_eq!(s.execute("view.saved.new", &json!({"name": long, "center": [0, 0], "zoom": 1})).unwrap()["name"], "x".repeat(255));
|
||||
}
|
||||
|
||||
/// Edit Views… is off until the document has a view.
|
||||
#[test]
|
||||
fn edit_views_needs_a_saved_view() {
|
||||
let mut s = session_with_views(&[]);
|
||||
assert!(s.execute("view.saved.edit", &json!({})).is_err());
|
||||
s.execute("view.saved.new", &json!({"name": "Only", "center": [0, 0], "zoom": 1})).unwrap();
|
||||
assert_eq!(s.execute("view.saved.edit", &json!({})).unwrap()["views"][0]["name"], "Only");
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,6 @@ use vectorcraft_doc::{Document, NodeId, NodeKind, Selection};
|
||||
use vectorcraft_geom::Affine;
|
||||
use vectorcraft_tools::{PaintDefaults, Tool};
|
||||
|
||||
pub use cmd::EyedropperOptions;
|
||||
pub use cmd::clipboard::Clipboard;
|
||||
pub use cmd::create::constrain_click;
|
||||
pub use cmd::distortcmds::perspective_click;
|
||||
@@ -33,6 +32,7 @@ pub use cmd::params::{check_keys, check_params};
|
||||
pub use cmd::pathops::auto_simplify_level;
|
||||
pub use cmd::rasterfx::{export_pdf, flatten_raster_effects};
|
||||
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
|
||||
pub use cmd::{EyedropperOptions, PathfinderOptions};
|
||||
pub use journal::Journal;
|
||||
pub use tooling::{UiRequest, ViewInfo};
|
||||
pub use vectorcraft_doc as doc;
|
||||
@@ -1112,6 +1112,9 @@ pub struct Prefs {
|
||||
/// Eyedropper Options (`eyedropper.setOptions`; a preference group, see
|
||||
/// [`cmd::prefscmds::PREF_GROUPS`]).
|
||||
pub eyedropper: EyedropperOptions,
|
||||
/// Pathfinder panel › Pathfinder Options (`object.pathfinder.options`; a preference group, see
|
||||
/// [`cmd::prefscmds::PREF_GROUPS`]).
|
||||
pub pathfinder: PathfinderOptions,
|
||||
/// Edit → Transparency Flattener Presets: the user's presets (the built-in ones aren't stored).
|
||||
/// Not a `prefs.set` key or group (resetting the preferences keeps them): `flattener.presets.*`
|
||||
/// edit it.
|
||||
@@ -1337,6 +1340,7 @@ impl Default for Prefs {
|
||||
Color::rgb8(r, g, b).to_hex()
|
||||
},
|
||||
eyedropper: Default::default(),
|
||||
pathfinder: Default::default(),
|
||||
flattener_presets: vec![],
|
||||
width_profiles: vec![],
|
||||
japanese_crop_marks: false,
|
||||
@@ -1429,6 +1433,8 @@ pub struct Session {
|
||||
pub style_libraries: cmd::stylelib::Libraries,
|
||||
/// User Defined and loaded symbol libraries (Window → Symbol Libraries); not saved.
|
||||
pub symbol_libraries: cmd::symbollib::Libraries,
|
||||
/// User Defined and loaded brush libraries (Window → Brush Libraries); not saved.
|
||||
pub brush_libraries: cmd::brushlib::Libraries,
|
||||
/// The Libraries panel's libraries of graphics, colours and text styles (`library.*`).
|
||||
pub libraries: cmd::library::Libraries,
|
||||
/// Where the saved PDF presets are kept, one file each; `None`: only for the session
|
||||
@@ -1588,6 +1594,7 @@ impl Session {
|
||||
freeform_point: None,
|
||||
style_libraries: Default::default(),
|
||||
symbol_libraries: Default::default(),
|
||||
brush_libraries: Default::default(),
|
||||
libraries: Default::default(),
|
||||
pdf_preset_dir: None,
|
||||
profile_dir: None,
|
||||
@@ -2513,7 +2520,7 @@ impl Session {
|
||||
/// closes it. A scope that joined an open group leaves the group open; with `cancel`, it puts the
|
||||
/// document and its selection back as they were when the scope began and cuts the journal back to
|
||||
/// where the scope began (only while the group's step is still the newest one), and an undo step
|
||||
/// that the scope's first edit recorded goes too.
|
||||
/// that the scope's first edit recorded goes too. The open undo groups drop the cut entries.
|
||||
pub fn end_undo_scope(&mut self, scope: UndoScope, cancel: bool) {
|
||||
let Some((doc, selection, first)) = scope.joined else {
|
||||
self.end_document_undo_group(scope.uid, cancel);
|
||||
@@ -2542,6 +2549,11 @@ impl Session {
|
||||
st.history.recost_last(&st.doc);
|
||||
st.revision += 1;
|
||||
self.journal.truncate(scope.journal);
|
||||
// The next commands take the cut entries' numbers, so no open undo group keeps them.
|
||||
for g in self.docs.iter_mut().filter_map(|st| st.undo_group.as_mut()) {
|
||||
g.journal.retain(|&(n, _)| n < scope.journal);
|
||||
g.steps.retain(|&(n, _)| n < scope.journal);
|
||||
}
|
||||
}
|
||||
|
||||
/// Commands with enablement (for menus, palette, MCP `list_commands`).
|
||||
@@ -2605,6 +2617,8 @@ mod tests_blendopts;
|
||||
#[cfg(test)]
|
||||
mod tests_blendspine;
|
||||
#[cfg(test)]
|
||||
mod tests_brushlib;
|
||||
#[cfg(test)]
|
||||
mod tests_brushsym;
|
||||
#[cfg(test)]
|
||||
mod tests_build;
|
||||
|
||||
@@ -0,0 +1,327 @@
|
||||
//! Brush libraries: the built-in libraries, saving a document's brushes as a library (User
|
||||
//! Defined, or a file), reopening it and adding its brushes to another document (the patterns and
|
||||
//! symbols their art uses along, one undo step, deduped, renamed on a clash, applied), other
|
||||
//! documents' brushes, and files that can't be read.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_brush::BrushKind;
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn session() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
s
|
||||
}
|
||||
|
||||
fn run(s: &mut Session, id: &str, p: Value) -> Value {
|
||||
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
|
||||
}
|
||||
|
||||
fn doc(s: &Session) -> &vectorcraft_doc::Document {
|
||||
&s.doc().unwrap().doc
|
||||
}
|
||||
|
||||
fn undo_len(s: &Session) -> usize {
|
||||
s.doc().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
fn brushes(s: &Session) -> Vec<String> {
|
||||
vectorcraft_brush::library(doc(s)).into_iter().map(|b| b.name).collect()
|
||||
}
|
||||
|
||||
fn brush(s: &Session, name: &str) -> vectorcraft_brush::Brush {
|
||||
vectorcraft_brush::find(doc(s), name).unwrap_or_else(|| panic!("no brush {name}"))
|
||||
}
|
||||
|
||||
fn strs(v: &Value) -> Vec<&str> {
|
||||
v.as_array().unwrap().iter().map(|n| n.as_str().unwrap()).collect()
|
||||
}
|
||||
|
||||
/// The patterns a brush's art fills with.
|
||||
fn art_patterns(b: &vectorcraft_brush::Brush) -> Vec<String> {
|
||||
let mut out = vec![];
|
||||
for a in b.art() {
|
||||
a.walk(&mut |n| {
|
||||
for it in &n.appearance.items {
|
||||
if let vectorcraft_color::Paint::Pattern { pattern, .. } = it.paint() {
|
||||
out.push(pattern.clone());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A folder of its own under the temp folder, emptied.
|
||||
fn folder(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("vc-brushlib-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
/// Pattern `name` (a 4 pt dot of `color` in a 10 pt tile) with its swatch, as one step.
|
||||
fn add_pattern(s: &mut Session, name: &str, color: &str) {
|
||||
let color = vectorcraft_color::Color::from_hex(color).unwrap();
|
||||
s.edit("Pattern", |d, _| {
|
||||
let dot = vectorcraft_doc::Node::path(
|
||||
d.alloc_id(),
|
||||
vectorcraft_geom::shapes::ellipse(vectorcraft_geom::Rect::new(0.0, 0.0, 4.0, 4.0)),
|
||||
vectorcraft_doc::Appearance::basic(vectorcraft_color::Paint::solid(color), vectorcraft_color::Paint::None, 0.0),
|
||||
);
|
||||
let def = vectorcraft_doc::PatternDef {
|
||||
tile: vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0),
|
||||
..vectorcraft_doc::PatternDef::new(name, vec![std::sync::Arc::new(dot)])
|
||||
};
|
||||
d.swatches.push(vectorcraft_color::Swatch {
|
||||
name: name.into(),
|
||||
paint: vectorcraft_color::Paint::Pattern { pattern: name.into(), xf: Default::default() },
|
||||
global: false,
|
||||
spot: false,
|
||||
});
|
||||
d.patterns.push(def);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// A document with brushes of its own: "My Nib" (calligraphic) and "Dotted Band" (an art brush
|
||||
/// whose art is filled with pattern "Dots").
|
||||
fn kit() -> Session {
|
||||
let mut s = session();
|
||||
run(&mut s, "brush.new", json!({"type": "calligraphic", "name": "My Nib", "params": {"angle": 20, "roundness": 40, "size": 7}}));
|
||||
add_pattern(&mut s, "Dots", "#ff0000");
|
||||
let band = run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 100, "height": 8}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "paint.setFill", json!({"swatch": "Dots"}));
|
||||
run(&mut s, "brush.new", json!({"type": "art", "name": "Dotted Band", "ids": [band]}));
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_builtin_libraries_are_original_brushes_generated_in_code() {
|
||||
let mut s = Session::new();
|
||||
let list = run(&mut s, "brush.libraries", json!({}));
|
||||
let libs = list["libraries"].as_array().unwrap();
|
||||
let ids: Vec<&str> = libs.iter().map(|l| l["id"].as_str().unwrap()).collect();
|
||||
assert_eq!(ids, ["art-ribbons", "calligraphic-nibs", "pattern-borders", "scatter-shapes"]);
|
||||
assert!(libs.iter().all(|l| l["category"] == "builtIn"));
|
||||
let lib = run(&mut s, "brush.library", json!({"library": "art ribbons"}));
|
||||
assert_eq!(
|
||||
lib["brushes"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect::<Vec<_>>(),
|
||||
["Notched Ribbon", "Double Line", "Wave", "Teardrop", "Striped Ribbon"]
|
||||
);
|
||||
assert_eq!(libs[0]["count"].as_u64(), Some(5));
|
||||
// One kind of brush per library, every brush drawing something.
|
||||
for (id, kind) in [("art-ribbons", "art"), ("calligraphic-nibs", "calligraphic"), ("pattern-borders", "pattern"), ("scatter-shapes", "scatter")] {
|
||||
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
|
||||
assert!(lib.len() >= 4, "{id}");
|
||||
for b in &lib.brushes {
|
||||
assert_eq!(b.kind.type_id(), kind, "{}", b.name);
|
||||
let mut line = vectorcraft_geom::BezPath::new();
|
||||
line.move_to((0.0, 0.0));
|
||||
line.curve_to((60.0, -40.0), (140.0, 40.0), (200.0, 0.0));
|
||||
let stroke = vectorcraft_doc::StrokeLayer::new(vectorcraft_color::Paint::solid(vectorcraft_color::Color::BLACK), 1.0);
|
||||
assert!(!vectorcraft_brush::stroke_pieces(&lib.doc, b, &line, &stroke).is_empty(), "{} draws nothing", b.name);
|
||||
}
|
||||
}
|
||||
// The resources their art uses come with them: Striped Ribbon's pattern, Sparkles' symbol.
|
||||
let (_, ribbons) = cmd::brushlib::library(&s, "art-ribbons").unwrap();
|
||||
assert_eq!(art_patterns(ribbons.brush("Striped Ribbon").unwrap()), ["Pinstripes"]);
|
||||
assert!(ribbons.doc.pattern("Pinstripes").is_some());
|
||||
let (_, shapes) = cmd::brushlib::library(&s, "scatter-shapes").unwrap();
|
||||
let BrushKind::Scatter(sparkles) = &shapes.brush("Sparkles").unwrap().kind else { panic!("not a scatter brush") };
|
||||
assert!(matches!(&sparkles.art.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Sparkle"));
|
||||
assert!(shapes.doc.symbols.iter().any(|x| x.name == "Sparkle"));
|
||||
// None of them is a default brush.
|
||||
let defaults: Vec<&str> = vectorcraft_brush::defaults().iter().map(|b| b.name.as_str()).collect();
|
||||
for id in ids {
|
||||
let (_, lib) = cmd::brushlib::library(&s, id).unwrap();
|
||||
assert!(lib.brushes.iter().all(|b| !defaults.contains(&b.name.as_str())), "{id}");
|
||||
}
|
||||
assert!(s.execute("brush.library", &json!({"library": "nope"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_library_reopens_and_its_brushes_join_another_document_in_one_step() {
|
||||
let dir = folder("user");
|
||||
let mut s = kit();
|
||||
s.brush_libraries.set_user_dir(Some(dir.to_string_lossy().to_string()));
|
||||
let r = run(&mut s, "brush.saveLibrary", json!({"user": true, "name": "Inks", "names": ["My Nib", "Dotted Band"]}));
|
||||
assert_eq!((r["library"].as_str(), r["count"].as_u64()), (Some("user/Inks.vectorcraft"), Some(2)));
|
||||
let path = r["path"].as_str().unwrap().to_string();
|
||||
let list = run(&mut s, "brush.libraries", json!({}));
|
||||
let user: Vec<&Value> = list["libraries"].as_array().unwrap().iter().filter(|l| l["category"] == "user").collect();
|
||||
assert_eq!(user.len(), 1);
|
||||
assert_eq!((user[0]["name"].as_str(), user[0]["count"].as_u64()), (Some("Inks"), Some(2)));
|
||||
// The file is a document: the two brushes and the pattern their art uses, no art.
|
||||
let saved = vectorcraft_format::load(&std::fs::read(&path).unwrap()).unwrap();
|
||||
let names: Vec<String> = vectorcraft_brush::library(&saved).into_iter().map(|b| b.name).collect();
|
||||
assert_eq!(names, ["My Nib", "Dotted Band"]);
|
||||
assert_eq!(saved.patterns.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["Dots"]);
|
||||
assert!(saved.layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())));
|
||||
// Loading the file gives that User Defined library.
|
||||
let r = run(&mut s, "brush.loadLibrary", json!({ "path": path }));
|
||||
assert_eq!((r["library"].as_str(), r["name"].as_str()), (Some("user/Inks.vectorcraft"), Some("Inks")));
|
||||
|
||||
// Into a new document: Dotted Band and its pattern, as one step.
|
||||
run(&mut s, "file.new", json!({"width": 100, "height": 100}));
|
||||
let defaults = brushes(&s);
|
||||
let before = undo_len(&s);
|
||||
let r = run(&mut s, "brush.addFromLibrary", json!({"library": "Inks", "name": "Dotted Band"}));
|
||||
assert_eq!((strs(&r["names"]), strs(&r["added"]), strs(&r["existing"])), (vec!["Dotted Band"], vec!["Dotted Band"], vec![]));
|
||||
assert_eq!(undo_len(&s), before + 1);
|
||||
assert_eq!(s.doc().unwrap().history.undo.last().unwrap().label, "Add to Brushes");
|
||||
assert_eq!(brushes(&s), [defaults.clone(), vec!["Dotted Band".to_string()]].concat());
|
||||
let (_, lib) = cmd::brushlib::library(&s, "Inks").unwrap();
|
||||
assert_eq!(&brush(&s, "Dotted Band"), lib.brush("Dotted Band").unwrap());
|
||||
assert!(doc(&s).pattern("Dots").is_some() && doc(&s).swatch("Dots").is_some(), "the pattern its art fills with");
|
||||
assert_eq!(run(&mut s, "brush.list", json!({}))["current"], "Dotted Band");
|
||||
// Undo takes it all back.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(brushes(&s), defaults);
|
||||
assert!(doc(&s).pattern("Dots").is_none());
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
// Again: already there, so no step and no copy.
|
||||
let before = undo_len(&s);
|
||||
let r = run(&mut s, "brush.addFromLibrary", json!({"library": "user/Inks.vectorcraft", "names": ["Dotted Band", "My Nib", "Dotted Band"]}));
|
||||
assert_eq!((strs(&r["names"]), strs(&r["existing"]), strs(&r["added"])), (vec!["Dotted Band", "My Nib"], vec!["Dotted Band"], vec!["My Nib"]));
|
||||
assert_eq!(undo_len(&s), before + 1, "My Nib was new");
|
||||
let before = undo_len(&s);
|
||||
let r = run(&mut s, "brush.addFromLibrary", json!({"library": "Inks"}));
|
||||
assert_eq!((strs(&r["existing"]).len(), undo_len(&s)), (2, before));
|
||||
assert_eq!(brushes(&s).len(), defaults.len() + 2);
|
||||
assert_eq!(doc(&s).patterns.len(), 1);
|
||||
assert_eq!(run(&mut s, "brush.list", json!({}))["current"], "My Nib", "the library's first brush");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn library_brushes_bring_their_patterns_and_symbols_rename_clashes_and_apply() {
|
||||
let mut s = session();
|
||||
// The document has a pattern "Pinstripes" and a brush "Wave" of its own.
|
||||
add_pattern(&mut s, "Pinstripes", "#00ff00");
|
||||
let mine = doc(&s).pattern("Pinstripes").unwrap().clone();
|
||||
run(&mut s, "brush.new", json!({"type": "calligraphic", "name": "Wave"}));
|
||||
let my_wave = brush(&s, "Wave");
|
||||
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 10, "x2": 150, "y2": 60}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "select.set", json!({"ids": [path]}));
|
||||
let before = undo_len(&s);
|
||||
let r = run(&mut s, "brush.addFromLibrary", json!({"library": "art-ribbons", "names": ["Striped Ribbon", "Wave"], "apply": true}));
|
||||
assert_eq!(undo_len(&s), before + 1, "adding and applying are one step");
|
||||
assert_eq!(strs(&r["names"]), ["Striped Ribbon", "Wave 2"]);
|
||||
assert_eq!(r["applied"], json!([path]));
|
||||
assert_eq!(brush(&s, "Wave"), my_wave, "the document's own Wave stays");
|
||||
// The library's Pinstripes comes in under a free name, and the brush's art follows it.
|
||||
assert_eq!(doc(&s).pattern("Pinstripes").unwrap(), &mine);
|
||||
assert!(doc(&s).pattern("Pinstripes 2").is_some() && doc(&s).swatch("Pinstripes 2").is_some());
|
||||
assert_eq!(art_patterns(&brush(&s, "Striped Ribbon")), ["Pinstripes 2"]);
|
||||
// The first one is applied to the selected path and is the current brush.
|
||||
let n = doc(&s).node(NodeId(path)).unwrap();
|
||||
assert_eq!(n.appearance.stroke().and_then(|st| st.brush.clone()).as_deref(), Some("Striped Ribbon"));
|
||||
assert_eq!(run(&mut s, "brush.list", json!({}))["current"], "Striped Ribbon");
|
||||
// Adding it again finds it, its pattern renamed, and adds nothing.
|
||||
let before = undo_len(&s);
|
||||
let r = run(&mut s, "brush.addFromLibrary", json!({"library": "art-ribbons", "names": ["Striped Ribbon", "Wave"]}));
|
||||
assert_eq!((strs(&r["names"]), strs(&r["existing"])), (vec!["Striped Ribbon", "Wave 2"], vec!["Striped Ribbon", "Wave 2"]));
|
||||
assert_eq!(undo_len(&s), before);
|
||||
assert!(doc(&s).pattern("Pinstripes 3").is_none() && vectorcraft_brush::find(doc(&s), "Striped Ribbon 2").is_none());
|
||||
// Undo of the first add takes the brushes, the pattern and the brush stroke back.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!(vectorcraft_brush::find(doc(&s), "Striped Ribbon").is_none() && doc(&s).pattern("Pinstripes 2").is_none());
|
||||
assert!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().is_none_or(|st| st.brush.is_none()));
|
||||
// A scatter brush brings the symbol it scatters.
|
||||
let r = run(&mut s, "brush.addFromLibrary", json!({"library": "Scatter Shapes", "name": "Sparkles"}));
|
||||
assert_eq!(strs(&r["added"]), ["Sparkles"]);
|
||||
assert_eq!(doc(&s).symbols.iter().map(|x| x.name.as_str()).collect::<Vec<_>>(), ["Sparkle"]);
|
||||
// Applying a brush the document has still applies (one step) to the paths given, without
|
||||
// adding it again.
|
||||
run(&mut s, "select.none", json!({}));
|
||||
let before = undo_len(&s);
|
||||
let r = run(&mut s, "brush.addFromLibrary", json!({"library": "scatter-shapes", "name": "Sparkles", "apply": true, "ids": [path]}));
|
||||
assert_eq!((undo_len(&s), strs(&r["existing"]), r["applied"].clone()), (before + 1, vec!["Sparkles"], json!([path])));
|
||||
assert_eq!(doc(&s).node(NodeId(path)).unwrap().appearance.stroke().and_then(|st| st.brush.clone()).as_deref(), Some("Sparkles"));
|
||||
assert_eq!(doc(&s).symbols.len(), 1);
|
||||
assert!(s.execute("brush.addFromLibrary", &json!({"library": "art-ribbons", "name": "Nope"})).is_err());
|
||||
assert!(s.execute("brush.addFromLibrary", &json!({"name": "Wave"})).is_err());
|
||||
}
|
||||
|
||||
/// The undo step is Add to Brushes when a brush comes in (applied or not), and Apply Brush when
|
||||
/// the brushes are all there and the click only applies one; undo and redo of either restore the
|
||||
/// document as it was and as the step left it.
|
||||
#[test]
|
||||
fn adding_library_brushes_is_add_to_brushes_and_only_applying_one_is_apply_brush() {
|
||||
let mut s = session();
|
||||
let path = run(&mut s, "shape.line", json!({"x1": 10, "y1": 10, "x2": 150, "y2": 60}))["id"].as_u64().unwrap();
|
||||
let label = |s: &Session| s.doc().unwrap().history.undo.last().unwrap().label.clone();
|
||||
let stroke_brush = |s: &Session| doc(s).node(NodeId(path)).unwrap().appearance.stroke().and_then(|st| st.brush.clone());
|
||||
run(&mut s, "brush.addFromLibrary", json!({"library": "art-ribbons", "name": "Wave", "apply": true, "ids": [path]}));
|
||||
assert_eq!((label(&s), stroke_brush(&s).as_deref()), ("Add to Brushes".to_string(), Some("Wave")));
|
||||
run(&mut s, "brush.addFromLibrary", json!({"library": "art-ribbons", "name": "Teardrop"}));
|
||||
assert_eq!(label(&s), "Add to Brushes");
|
||||
let (before, brushes_before) = (undo_len(&s), brushes(&s));
|
||||
let r = run(&mut s, "brush.addFromLibrary", json!({"library": "art-ribbons", "name": "Teardrop", "apply": true, "ids": [path]}));
|
||||
assert_eq!((strs(&r["added"]), strs(&r["existing"])), (vec![], vec!["Teardrop"]));
|
||||
assert_eq!((undo_len(&s), label(&s), brushes(&s)), (before + 1, "Apply Brush".to_string(), brushes_before.clone()));
|
||||
assert_eq!(stroke_brush(&s).as_deref(), Some("Teardrop"));
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!((stroke_brush(&s).as_deref(), brushes(&s)), (Some("Wave"), brushes_before.clone()));
|
||||
run(&mut s, "edit.redo", json!({}));
|
||||
assert_eq!((stroke_brush(&s).as_deref(), label(&s)), (Some("Teardrop"), "Apply Brush".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pasted_brushed_art_brings_the_patterns_its_brush_art_uses() {
|
||||
let mut s = kit();
|
||||
let line = run(&mut s, "shape.line", json!({"x1": 10, "y1": 100, "x2": 150, "y2": 120}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "brush.apply", json!({"name": "Dotted Band", "ids": [line]}));
|
||||
run(&mut s, "select.set", json!({"ids": [line]}));
|
||||
run(&mut s, "edit.copy", json!({}));
|
||||
run(&mut s, "file.new", json!({"width": 200, "height": 200}));
|
||||
run(&mut s, "edit.paste", json!({}));
|
||||
assert!(vectorcraft_brush::find(doc(&s), "Dotted Band").is_some());
|
||||
assert!(doc(&s).pattern("Dots").is_some(), "the brush's art is filled with it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_documents_brushes_load_and_unreadable_files_are_errors() {
|
||||
let mut s = kit();
|
||||
// Another document's brushes load as a library, without its art.
|
||||
let b64 = run(&mut s, "document.serialize", json!({}))["dataBase64"].as_str().unwrap().to_string();
|
||||
let count = brushes(&s).len();
|
||||
let r = run(&mut s, "brush.loadLibrary", json!({"dataBase64": b64, "name": "Poster.vectorcraft"}));
|
||||
assert_eq!((r["name"].as_str(), r["count"].as_u64()), (Some("Poster"), Some(count as u64)));
|
||||
let (_, lib) = cmd::brushlib::library(&s, r["library"].as_str().unwrap()).unwrap();
|
||||
assert!(lib.doc.layers.iter().all(|l| l.children().is_none_or(|c| c.is_empty())));
|
||||
assert!(lib.brush("Dotted Band").is_some() && lib.doc.pattern("Dots").is_some());
|
||||
// An SVG has the default brushes, as it does opened.
|
||||
let svg = r##"<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><rect width="10" height="10"/></svg>"##;
|
||||
let r = run(&mut s, "brush.loadLibrary", json!({"data": svg, "name": "Box.svg"}));
|
||||
assert_eq!(r["count"].as_u64(), Some(vectorcraft_brush::defaults().len() as u64), "{r}");
|
||||
// Files that aren't documents, missing files and damaged native files are errors.
|
||||
assert!(s.execute("brush.loadLibrary", &json!({"data": "hello", "name": "x.txt"})).is_err());
|
||||
assert!(s.execute("brush.loadLibrary", &json!({"path": "/no/such/Library.vectorcraft"})).is_err());
|
||||
let dir = folder("bad");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let bad = dir.join("Broken.vectorcraft");
|
||||
std::fs::write(&bad, b"{\"format\": \"vectorcraft\", \"doc\": 7").unwrap();
|
||||
assert!(s.execute("brush.loadLibrary", &json!({"path": bad.to_string_lossy()})).is_err());
|
||||
// A damaged file in the user folder isn't listed.
|
||||
s.brush_libraries.set_user_dir(Some(dir.to_string_lossy().to_string()));
|
||||
let list = run(&mut s, "brush.libraries", json!({}));
|
||||
assert!(list["libraries"].as_array().unwrap().iter().all(|l| l["category"] != "user"));
|
||||
s.brush_libraries.set_user_dir(None);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
// No such brush, or a headless session's user folder, is an error.
|
||||
assert!(s.execute("brush.saveLibrary", &json!({"names": ["Nope"]})).is_err());
|
||||
assert!(s.execute("brush.saveLibrary", &json!({"user": true})).is_err());
|
||||
// A document whose brushes were all deleted has none to save.
|
||||
let all = brushes(&s);
|
||||
run(&mut s, "brush.delete", json!({ "names": all }));
|
||||
assert!(s.execute("brush.saveLibrary", &json!({})).is_err());
|
||||
// Without a path the library comes back as the file's bytes.
|
||||
let mut s = kit();
|
||||
let r = run(&mut s, "brush.saveLibrary", json!({"names": ["My Nib"]}));
|
||||
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(vectorcraft_brush::library(&vectorcraft_format::load(&bytes).unwrap()).len(), 1);
|
||||
}
|
||||
@@ -944,6 +944,21 @@ fn join_tool_joins_two_lines() {
|
||||
assert_eq!(p.subpaths[0].anchors[2].p, Point::new(300.0, 150.0));
|
||||
}
|
||||
|
||||
/// #2899: a scrub from one open end toward the other joins them when the line passes near the
|
||||
/// endpoints, not only when it crosses them.
|
||||
#[test]
|
||||
fn join_tool_joins_endpoints_near_the_scrub_ends() {
|
||||
let mut s = session();
|
||||
let a = line(&mut s, 100.0, 100.0, 200.0, 100.0);
|
||||
line(&mut s, 205.0, 100.0, 300.0, 150.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
drag(&mut s, "join", &[(198.0, 92.0), (207.0, 92.0)], Mods::default());
|
||||
assert_eq!(paths(&s).len(), 1);
|
||||
let p = path(&s, a);
|
||||
assert_eq!(p.anchor_count(), 3);
|
||||
assert_eq!(p.subpaths[0].anchors[1].p, Point::new(202.5, 100.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn line_family_tools_draw_and_click_asks_dialog() {
|
||||
let mut s = session();
|
||||
@@ -2722,3 +2737,78 @@ fn pencil_option_takes_a_hundredth_and_smooth_keeps_its_floor() {
|
||||
assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(if tool == "smooth" { 0.05 } else { 0.02 }), "{tool}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A selected compound path (a shape with a hole) is overdrawn as its paths are: a Pencil stroke
|
||||
/// starting and ending on its outer path, or on its hole, redraws that member path, draws no new
|
||||
/// path, and leaves the compound path selected, so the next stroke redraws it too.
|
||||
#[test]
|
||||
fn pencil_redraws_a_selected_compound_path() {
|
||||
let mut s = session();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let ring = |cx: f64, rx: f64, ry: f64| -> Vec<serde_json::Value> {
|
||||
(0..72)
|
||||
.map(|i| {
|
||||
let a = f64::from(i * 5).to_radians();
|
||||
json!([cx + rx * a.cos(), 300.0 + ry * a.sin()])
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let outer = s.execute("path.freehand", &json!({"points": ring(400.0, 150.0, 90.0), "closed": true})).unwrap()["id"].as_u64().unwrap();
|
||||
let hole = s.execute("path.freehand", &json!({"points": ring(380.0, 60.0, 30.0), "closed": true})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("select.set", &json!({"ids": [outer, hole]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let compound = s.doc().unwrap().selection.objects.clone();
|
||||
assert_eq!(compound.len(), 1);
|
||||
let members = |s: &Session| -> Vec<PathData> {
|
||||
s.doc().unwrap().doc.node(compound[0]).unwrap().children().unwrap().iter().map(|c| c.path_data().unwrap().clone()).collect()
|
||||
};
|
||||
let before = members(&s);
|
||||
let v = view();
|
||||
s.select_tool("pencil", v).unwrap();
|
||||
let count = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len());
|
||||
let stroke = |s: &mut Session, pts: &[(f64, f64)]| {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1), v).unwrap();
|
||||
for &(x, y) in &pts[1..] {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap();
|
||||
}
|
||||
let l = pts[pts.len() - 1];
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, l.0, l.1), v).unwrap();
|
||||
};
|
||||
// Over the outer path's right side, bowing outward: from (550, 300) round to (520, 360).
|
||||
stroke(&mut s, &[(550.0, 300.0), (575.0, 315.0), (580.0, 335.0), (560.0, 355.0), (520.0, 360.0)]);
|
||||
assert_eq!(count(&s), 1, "no new path");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, compound, "the compound path stays selected");
|
||||
let after = members(&s);
|
||||
assert!(after[0] != before[0] && after[1] == before[1], "the outer path is redrawn, the hole left alone");
|
||||
// Then over the hole's left side: the compound path is still the one redrawn.
|
||||
stroke(&mut s, &[(320.0, 300.0), (310.0, 290.0), (312.0, 280.0), (330.0, 274.0)]);
|
||||
assert_eq!(count(&s), 1, "no new path");
|
||||
assert_eq!(s.doc().unwrap().selection.objects, compound);
|
||||
assert!(members(&s)[1] != before[1], "the hole is redrawn");
|
||||
}
|
||||
|
||||
/// With the Pencil's Live preview off, nothing is added to the document while a filled stroke is
|
||||
/// drawn; the release draws the path with its fill, as one undo step.
|
||||
#[test]
|
||||
fn pencil_with_live_preview_off_draws_the_filled_path_on_release() {
|
||||
let mut s = session();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.set_tool_option_cmd(&json!({"tool": "pencil", "values": {"livePreview": false, "fill": true}})).unwrap();
|
||||
assert_eq!(s.tool_options_of("pencil")["livePreview"], json!(false));
|
||||
let v = view();
|
||||
s.select_tool("pencil", v).unwrap();
|
||||
let count = |s: &Session| s.doc().unwrap().doc.layers[0].children().map_or(0, |c| c.len());
|
||||
let (before, undo) = (count(&s), s.doc().unwrap().history.undo.len());
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
|
||||
for (x, y) in [(160.0, 110.0), (190.0, 170.0), (120.0, 190.0), (105.0, 120.0)] {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap();
|
||||
assert_eq!(count(&s), before, "nothing drawn while the stroke is drawn");
|
||||
}
|
||||
s.pointer(&PointerEvent::new(PointerKind::Up, 105.0, 120.0), v).unwrap();
|
||||
assert_eq!(count(&s), before + 1, "the release draws the path");
|
||||
let doc = &s.doc().unwrap().doc;
|
||||
let n = doc.layers[0].children().unwrap().last().unwrap();
|
||||
assert!(n.path_data().is_some() && !n.appearance.fill_paint().is_none(), "{:?}", n.appearance);
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
|
||||
}
|
||||
@@ -780,6 +780,34 @@ fn an_undo_scope_in_an_open_group_takes_back_only_its_own_edits() {
|
||||
assert_eq!(objects(&s), 0, "one undo takes back the group's edits");
|
||||
}
|
||||
|
||||
/// A canceled undo scope that joined an open group forgets the journal entries it cut: when a command
|
||||
/// in another document takes the same entry number, a later cancel of the group keeps that entry, and
|
||||
/// the journal replays to the same documents.
|
||||
#[test]
|
||||
fn a_canceled_undo_scope_leaves_its_cut_entries_out_of_the_group() {
|
||||
let mut s = Session::new();
|
||||
let rect = json!({"x": 10, "y": 10, "width": 100, "height": 50});
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
s.execute("document.activate", &json!({"index": 0})).unwrap();
|
||||
s.begin_undo_group();
|
||||
s.execute("shape.rectangle", &rect).unwrap();
|
||||
let scope = s.begin_undo_scope().unwrap();
|
||||
s.execute("shape.rectangle", &rect).unwrap();
|
||||
s.end_undo_scope(scope, true);
|
||||
let journal = s.journal.len();
|
||||
// The switch takes the entry number the scope's edit had, and the rectangle in the second document follows it.
|
||||
s.execute("document.activate", &json!({"index": 1})).unwrap();
|
||||
s.execute("shape.rectangle", &rect).unwrap();
|
||||
s.end_undo_group(true);
|
||||
let objects = s.documents().iter().map(|d| d.doc.layers[0].children().map_or(0, |c| c.len())).collect::<Vec<_>>();
|
||||
assert_eq!(objects, [0, 1]);
|
||||
assert_eq!(s.journal.len(), journal + 1, "only the group's own edit leaves the journal");
|
||||
let r = replayed(&s);
|
||||
assert_eq!(documents(&r), documents(&s));
|
||||
assert_eq!(r.active_index(), s.active_index());
|
||||
}
|
||||
|
||||
/// A move drag is named for what its last preview did: Alt pressed or released during the drag
|
||||
/// turns it into a copy or back (the Selection and Direct Selection tools).
|
||||
#[test]
|
||||
|
||||
@@ -20,8 +20,14 @@ fn place_embedded(s: &mut Session, path: &str) -> NodeId {
|
||||
/// A PNG that says it is `w` × `h` 1-bit grey pixels (its header and no rows, which is all that
|
||||
/// placing and listing read).
|
||||
pub(crate) fn png_header(w: u32, h: u32) -> Vec<u8> {
|
||||
png_header_as(w, h, [1, 0, 0, 0, 0])
|
||||
}
|
||||
|
||||
/// A PNG that says it is `w` × `h` pixels of the bit depth, color type, compression, filter and
|
||||
/// interlace method `kind` gives (its header and no rows).
|
||||
fn png_header_as(w: u32, h: u32, kind: [u8; 5]) -> Vec<u8> {
|
||||
let mut out = b"\x89PNG\r\n\x1a\n".to_vec();
|
||||
let ihdr: Vec<u8> = [&b"IHDR"[..], &w.to_be_bytes(), &h.to_be_bytes(), &[1, 0, 0, 0, 0]].concat();
|
||||
let ihdr: Vec<u8> = [&b"IHDR"[..], &w.to_be_bytes(), &h.to_be_bytes(), &kind].concat();
|
||||
for chunk in [&ihdr[..], b"IDAT\x78\x9c", b"IEND"] {
|
||||
out.extend((chunk.len() as u32 - 4).to_be_bytes());
|
||||
out.extend(chunk);
|
||||
@@ -30,32 +36,42 @@ pub(crate) fn png_header(w: u32, h: u32) -> Vec<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
/// An image past what a decode may take isn't drawn: Place and Open say so and the Links panel's
|
||||
/// row carries the note, where the image used to be blank with no word (#1479).
|
||||
/// An image past what a decode may take is drawn at reduced size: Place and Open say so and the
|
||||
/// Links panel's row carries the note. One the renderer can't read at reduced size (an interlaced
|
||||
/// RGBA PNG past the allowance as decoded, or an image of more pixels than the allowance has
|
||||
/// bytes) isn't drawn, and the note says it is too large to draw (#1479).
|
||||
#[test]
|
||||
fn an_image_too_large_to_draw_is_reported() {
|
||||
const NOTE: &str = "an image of 200000 × 200000 pixels is too large to draw";
|
||||
const NOTE: &str = "an image of 40000 × 40000 pixels is shown at reduced size";
|
||||
const UNDRAWN: &str = "an image of 30000 × 30000 pixels is too large to draw";
|
||||
let dir = Folder::new("huge");
|
||||
let (big, small) = (dir.file("wall.png"), dir.file("small.png"));
|
||||
write(&big, &png_header(200_000, 200_000));
|
||||
let (big, small, laced) = (dir.file("wall.png"), dir.file("small.png"), dir.file("laced.png"));
|
||||
write(&big, &png_header(40_000, 40_000));
|
||||
write(&small, &png(40, 20, BLUE));
|
||||
write(&laced, &png_header_as(30_000, 30_000, [8, 6, 0, 0, 1]));
|
||||
let mut s = session();
|
||||
assert_eq!(run(&mut s, "file.place", json!({"path": big, "at": [200, 150], "link": false}))["warnings"], json!([NOTE]));
|
||||
assert_eq!(run(&mut s, "file.place", json!({"path": small, "at": [20, 20], "link": false}))["warnings"], json!([]));
|
||||
assert_eq!(run(&mut s, "file.place", json!({"path": laced, "at": [20, 20], "link": false}))["warnings"], json!([UNDRAWN]));
|
||||
let l = run(&mut s, "links.list", json!({}));
|
||||
let notes: Vec<&Value> = l["links"].as_array().unwrap().iter().map(|r| &r["note"]).collect();
|
||||
assert_eq!(notes, [&Value::Null, &json!(NOTE)], "top first: the small image has nothing to say");
|
||||
assert_eq!(notes, [&json!(UNDRAWN), &Value::Null, &json!(NOTE)], "top first: the small image has nothing to say");
|
||||
// Opened as a document: said too. An image that decodes (16,000 px square) has no note.
|
||||
assert_eq!(crate::cmd::fileio::load("wall.png", &png_header(200_000, 200_000)).unwrap().warnings, [NOTE]);
|
||||
assert_eq!(crate::cmd::fileio::load("wall.png", &png_header(40_000, 40_000)).unwrap().warnings, [NOTE]);
|
||||
let more = crate::cmd::fileio::load("more.png", &png_header(200_000, 200_000)).unwrap().warnings;
|
||||
assert_eq!(more, ["an image of 200000 × 200000 pixels is too large to draw"], "more pixels than the allowance has bytes");
|
||||
assert!(crate::cmd::fileio::load("fine.png", &png_header(16_000, 16_000)).unwrap().warnings.is_empty());
|
||||
// 20,000 px square at 16 bits a sample is 3.2 GB decoded and 1.6 GB as RGBA: read a row at a
|
||||
// time at its own size, so nothing is said of it.
|
||||
assert!(crate::cmd::fileio::load("deep.png", &png_header_as(20_000, 20_000, [16, 6, 0, 0, 0])).unwrap().warnings.is_empty());
|
||||
}
|
||||
|
||||
/// A gray image is counted as RGBA, 4 bytes a pixel: 23,171 × 23,170 1-bit pixels decode to 537 MB
|
||||
/// of gray and are 2,147,488,280 bytes as RGBA, past the 2 GiB allowance; 23,170 × 23,170 are
|
||||
/// 2,147,395,600 bytes, within it.
|
||||
/// of gray and are 2,147,488,280 bytes as RGBA, past the 2 GiB allowance (shown at reduced size);
|
||||
/// 23,170 × 23,170 are 2,147,395,600 bytes, within it.
|
||||
#[test]
|
||||
fn a_gray_image_too_large_as_rgba_is_reported_on_place() {
|
||||
const NOTE: &str = "an image of 23171 × 23170 pixels is too large to draw";
|
||||
const NOTE: &str = "an image of 23171 × 23170 pixels is shown at reduced size";
|
||||
let dir = Folder::new("huge-gray-place");
|
||||
let (over, within) = (dir.file("over.png"), dir.file("within.png"));
|
||||
write(&over, &png_header(23_171, 23_170));
|
||||
@@ -76,7 +92,7 @@ fn a_gray_image_too_large_as_rgba_is_reported_on_open() {
|
||||
write(&over, &png_header(23_171, 23_170));
|
||||
write(&within, &png_header(23_170, 23_170));
|
||||
let mut s = session();
|
||||
assert_eq!(open(&mut s, &over)["warnings"], json!(["an image of 23171 × 23170 pixels is too large to draw"]));
|
||||
assert_eq!(open(&mut s, &over)["warnings"], json!(["an image of 23171 × 23170 pixels is shown at reduced size"]));
|
||||
assert_eq!(open(&mut s, &within)["warnings"], json!([]));
|
||||
}
|
||||
fn close(a: f64, b: f64) -> bool {
|
||||
|
||||
@@ -1144,3 +1144,122 @@ fn stroke_advanced_scale_swap_flip() {
|
||||
assert!(s.execute("stroke.setAdvanced", &json!({})).is_err());
|
||||
assert!(s.execute("stroke.setAdvanced", &json!({"flipProfile": "sideways"})).is_err());
|
||||
}
|
||||
|
||||
/// A document of `n` 200 × 150 artboards in a row, 400 pt apart (`x` = 400·i), each with a
|
||||
/// guide of its own.
|
||||
fn row_of_artboards(n: usize) -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 150})).unwrap();
|
||||
for i in 1..n {
|
||||
s.execute("artboard.new", &json!({"x": 400 * i, "y": 0, "width": 200, "height": 150})).unwrap();
|
||||
}
|
||||
for i in 0..n {
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 400 * i + 50, "artboard": i})).unwrap();
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn box_at(s: &mut Session, x: f64, w: f64) -> NodeId {
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": 10, "width": w, "height": 20})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
fn artboard_names(s: &Session) -> Vec<String> {
|
||||
s.doc().unwrap().doc.artboards.iter().map(|a| a.name.clone()).collect()
|
||||
}
|
||||
|
||||
/// Artboards panel › Delete Empty Artboards: with art only on artboard 2, artboards 1 and 3 go
|
||||
/// with their guides in one undo step, the art and its ids untouched; Undo brings them back.
|
||||
#[test]
|
||||
fn delete_empty_artboards_deletes_those_with_no_art_in_one_step() {
|
||||
let mut s = row_of_artboards(3);
|
||||
let art = box_at(&mut s, 450.0, 20.0);
|
||||
let before = s.doc().unwrap().doc.clone();
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
assert_eq!(s.execute("artboard.deleteEmpty", &json!({})).unwrap(), json!({"deleted": [0, 2]}));
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(artboard_names(&s), ["Artboard 2"]);
|
||||
assert_eq!(st.doc.guides.len(), 1, "the deleted artboards' guides go with them");
|
||||
assert_eq!(st.doc.node(art).map(|n| n.geometric_bounds()), before.node(art).map(|n| n.geometric_bounds()), "the art stays");
|
||||
assert_eq!(st.history.undo.len(), steps + 1);
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(artboard_names(&s), ["Artboard 1", "Artboard 2", "Artboard 3"]);
|
||||
assert_eq!(s.doc().unwrap().doc.guides.len(), 3);
|
||||
}
|
||||
|
||||
/// What counts as art: hidden and locked objects, an object straddling two artboards and one
|
||||
/// that only touches an artboard's edge; a group counts by its members, not by its box.
|
||||
#[test]
|
||||
fn delete_empty_artboards_keeps_artboards_with_hidden_locked_or_shared_art() {
|
||||
let mut s = row_of_artboards(5);
|
||||
// Hidden art on 1, locked art on 2.
|
||||
box_at(&mut s, 10.0, 20.0);
|
||||
s.execute("object.hide", &json!({})).unwrap();
|
||||
box_at(&mut s, 410.0, 20.0);
|
||||
s.execute("object.lock", &json!({})).unwrap();
|
||||
// Straddling 3 (x 800–1000) and 4 (x 1200–1400).
|
||||
box_at(&mut s, 900.0, 350.0);
|
||||
// A group of a box on 3 and one whose right edge touches 6's left edge (x 2000): its box spans
|
||||
// 5 (x 1600–1800), which stays empty, and 6 has art only by the touch.
|
||||
s.execute("artboard.new", &json!({"x": 2000, "y": 0, "width": 200, "height": 150})).unwrap();
|
||||
let a = box_at(&mut s, 850.0, 20.0);
|
||||
let b = box_at(&mut s, 1980.0, 20.0);
|
||||
// No stroke, so its visual box ends at x 2000.
|
||||
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("artboard.deleteEmpty", &json!({})).unwrap(), json!({"deleted": [4]}));
|
||||
assert_eq!(artboard_names(&s), ["Artboard 1", "Artboard 2", "Artboard 3", "Artboard 4", "Artboard 6"]);
|
||||
}
|
||||
|
||||
/// A locked empty artboard stays; with every artboard empty artboard 1 stays; with none empty
|
||||
/// the command is disabled, refuses and adds no undo step.
|
||||
#[test]
|
||||
fn delete_empty_artboards_leaves_locked_ones_and_artboard_1() {
|
||||
let mut s = row_of_artboards(3);
|
||||
s.execute("artboard.setProps", &json!({"index": 1, "locked": true})).unwrap();
|
||||
assert_eq!(s.execute("artboard.deleteEmpty", &json!({})).unwrap(), json!({"deleted": [0, 2]}), "all empty, one locked");
|
||||
assert_eq!(artboard_names(&s), ["Artboard 2"]);
|
||||
|
||||
let mut s = row_of_artboards(3);
|
||||
assert_eq!(s.execute("artboard.deleteEmpty", &json!({})).unwrap(), json!({"deleted": [1, 2]}), "all empty: artboard 1 stays");
|
||||
assert_eq!(artboard_names(&s), ["Artboard 1"]);
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let spec = crate::cmd::command_specs().iter().find(|c| c.id == "artboard.deleteEmpty").unwrap();
|
||||
assert!((spec.enabled)(&s).is_err(), "one artboard left: nothing to delete");
|
||||
assert!(s.execute("artboard.deleteEmpty", &json!({})).is_err());
|
||||
box_at(&mut s, 10.0, 20.0);
|
||||
let steps_with_art = s.doc().unwrap().history.undo.len();
|
||||
assert!(s.execute("artboard.deleteEmpty", &json!({})).is_err(), "nothing empty");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps_with_art);
|
||||
assert!(steps_with_art > steps);
|
||||
}
|
||||
|
||||
/// Art outside a clip shows nowhere: a clip group or a clipping layer has art only where its
|
||||
/// members show inside the clip, so an artboard that only the clipped-away part of a member
|
||||
/// covers is empty.
|
||||
#[test]
|
||||
fn delete_empty_artboards_measures_clipped_art_through_the_clip() {
|
||||
// Clip group: the clip on 1, a member running on to 2. Clipping layer: the clip on 3, a member
|
||||
// running on to 4. Nothing else.
|
||||
let mut s = row_of_artboards(4);
|
||||
let long = box_at(&mut s, 50.0, 400.0);
|
||||
let clip = box_at(&mut s, 10.0, 100.0);
|
||||
// The front object clips (drawn after the member).
|
||||
s.execute("select.set", &json!({"ids": [long.0, clip.0]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
s.execute("layer.new", &json!({"name": "Clipped"})).unwrap();
|
||||
box_at(&mut s, 850.0, 400.0);
|
||||
// The layer's top object becomes its clipping path.
|
||||
let layer_clip = box_at(&mut s, 810.0, 100.0);
|
||||
let layer_of =
|
||||
|s: &Session| s.doc().unwrap().doc.layers.iter().find(|l| l.children().unwrap().iter().any(|c| c.id == layer_clip)).unwrap().clone();
|
||||
let layer = layer_of(&s);
|
||||
assert_eq!(layer.children().unwrap().len(), 2, "both in their own layer");
|
||||
s.execute("layer.clippingMask.toggle", &json!({"id": layer.id.0})).unwrap();
|
||||
let layer = layer_of(&s);
|
||||
assert!(matches!(layer.kind, vectorcraft_doc::NodeKind::Layer { clip: true, .. }));
|
||||
let first = layer.children().unwrap()[0].id;
|
||||
assert_eq!(first, layer_clip, "the layer's first object clips the rest");
|
||||
assert_eq!(s.execute("artboard.deleteEmpty", &json!({})).unwrap(), json!({"deleted": [1, 3]}));
|
||||
assert_eq!(artboard_names(&s), ["Artboard 1", "Artboard 3"]);
|
||||
}
|
||||
@@ -1098,3 +1098,187 @@ fn create_outlines_turns_colr_glyphs_into_layer_groups() {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
assert!(nodes.iter().all(|(id, ..)| d.node(*id).is_some() && seen.insert(*id)), "ids of the document's, each once");
|
||||
}
|
||||
|
||||
/// Pathfinder panel › Pathfinder Options: `object.pathfinder.options` reads and sets the options
|
||||
/// (kept in the preferences as the `pathfinder` group) and refuses values out of range or of the
|
||||
/// wrong type, changing nothing.
|
||||
#[test]
|
||||
fn pathfinder_options_round_trip_and_refuse_bad_values() {
|
||||
let mut s = session();
|
||||
let defaults = json!({"precision": 0.01, "removeRedundantPoints": false, "removeUnpainted": false});
|
||||
assert_eq!(s.execute("object.pathfinder.options", &json!({})).unwrap(), defaults);
|
||||
let set = json!({"precision": 0.5, "removeRedundantPoints": true, "removeUnpainted": true});
|
||||
assert_eq!(s.execute("object.pathfinder.options", &set).unwrap(), set);
|
||||
assert_eq!(s.execute("prefs.get", &json!({"key": "pathfinder"})).unwrap(), set);
|
||||
let mm = s.execute("object.pathfinder.options", &json!({"precision": "1 mm"})).unwrap()["precision"].as_f64().unwrap();
|
||||
assert!((mm - 72.0 / 25.4).abs() < 1e-9, "a length with a unit: {mm}");
|
||||
s.execute("object.pathfinder.options", &json!({"precision": 0.5})).unwrap();
|
||||
for bad in [
|
||||
json!({"precision": 0}),
|
||||
json!({"precision": 11}),
|
||||
json!({"precision": "x"}),
|
||||
json!({"precision": -1}),
|
||||
json!({"removeRedundantPoints": "yes"}),
|
||||
json!({"removeUnpainted": 1}),
|
||||
json!({"tolerance": 1}),
|
||||
] {
|
||||
assert!(s.execute("object.pathfinder.options", &bad).is_err(), "{bad}");
|
||||
assert!(s.execute("prefs.set", &json!({"key": "pathfinder", "value": bad})).is_err(), "prefs.set {bad}");
|
||||
assert_eq!(s.execute("object.pathfinder.options", &json!({})).unwrap(), set, "{bad} changes nothing");
|
||||
}
|
||||
s.execute("prefs.set", &json!({"key": "pathfinder", "value": {"removeUnpainted": false}})).unwrap();
|
||||
assert!(!s.prefs.pathfinder.remove_unpainted);
|
||||
assert!(s.prefs.pathfinder.remove_redundant_points, "a partial object keeps the rest");
|
||||
s.execute("prefs.reset", &json!({})).unwrap();
|
||||
assert_eq!(s.execute("object.pathfinder.options", &json!({})).unwrap(), defaults);
|
||||
}
|
||||
|
||||
/// A filled square and, crossing it, a rectangle with no fill, selected.
|
||||
fn filled_and_unfilled(s: &mut Session) {
|
||||
let a = rect(s, 0.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(s, 50.0, 25.0, 100.0, 50.0);
|
||||
set_fill(s, a, Color::rgb(1.0, 0.0, 0.0));
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(b).unwrap().appearance.set_fill(Paint::None);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
}
|
||||
|
||||
/// The fill of each piece of the group `op` makes from [`filled_and_unfilled`], and of each
|
||||
/// piece's stroke.
|
||||
fn pieces(s: &mut Session, op: &str) -> Vec<(Paint, Paint)> {
|
||||
let r = ids(&s.execute(op, &json!({})).unwrap());
|
||||
node(s, r[0]).children().unwrap().iter().map(|c| (c.appearance.fill_paint(), c.appearance.stroke_paint())).collect()
|
||||
}
|
||||
|
||||
/// Pathfinder Options › Divide and Outline Will Remove Unpainted Artwork: off, Divide and Outline
|
||||
/// keep the pieces of an object with no fill; on, they leave them out.
|
||||
#[test]
|
||||
fn divide_and_outline_remove_unpainted_artwork_when_asked() {
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
for on in [false, true] {
|
||||
let mut s = session();
|
||||
s.execute("object.pathfinder.options", &json!({"removeUnpainted": on})).unwrap();
|
||||
filled_and_unfilled(&mut s);
|
||||
let divided = pieces(&mut s, "object.pathfinder.divide");
|
||||
let unfilled = divided.iter().filter(|(fill, _)| fill.is_none()).count();
|
||||
// The overlap takes the paint of the rectangle in front, so it has no fill either.
|
||||
assert_eq!(unfilled, if on { 0 } else { 2 }, "Divide, option {on}: {divided:?}");
|
||||
assert_eq!(divided.len() - unfilled, 1, "the square's piece stays");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let outlined = pieces(&mut s, "object.pathfinder.outline");
|
||||
let from_unfilled = outlined.iter().filter(|(_, stroke)| *stroke != red).count();
|
||||
assert_eq!(from_unfilled > 0, !on, "Outline, option {on}: {outlined:?}");
|
||||
assert!(outlined.iter().any(|(_, stroke)| *stroke == red), "the square's edges stay");
|
||||
}
|
||||
}
|
||||
|
||||
/// Pathfinder Options › Remove Redundant Points: Unite of a square with an anchor in the middle of
|
||||
/// its top edge and a square inside it keeps the extra anchor unless the option is on.
|
||||
#[test]
|
||||
fn remove_redundant_points_drops_anchors_that_shape_nothing() {
|
||||
for on in [false, true] {
|
||||
let mut s = session();
|
||||
s.execute("object.pathfinder.options", &json!({"removeRedundantPoints": on})).unwrap();
|
||||
let pts = [(0.0, 0.0), (50.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)];
|
||||
let anchors: Vec<Value> = pts.iter().map(|(x, y)| json!({"x": x, "y": y})).collect();
|
||||
let a = NodeId(s.execute("path.create", &json!({"anchors": anchors, "closed": true})).unwrap()["id"].as_u64().unwrap());
|
||||
let b = rect(&mut s, 20.0, 20.0, 60.0, 60.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let r = ids(&s.execute("object.pathfinder.unite", &json!({})).unwrap());
|
||||
let anchors = path_of(&s, r[0]).0.anchor_count();
|
||||
if on {
|
||||
assert_eq!(anchors, 4, "option on");
|
||||
} else {
|
||||
assert!(anchors > 4, "option off keeps the anchor: {anchors}");
|
||||
}
|
||||
assert!((area_of(&s, r[0]) - 10_000.0).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
/// Pathfinder Options › Precision: Divide drops a 0.5 pt overlap at a precision of 1 pt and keeps
|
||||
/// it at the default.
|
||||
#[test]
|
||||
fn precision_decides_whether_a_thin_overlap_is_a_piece() {
|
||||
for (precision, faces) in [(None, 3), (Some(1.0), 2)] {
|
||||
let mut s = session();
|
||||
if let Some(p) = precision {
|
||||
s.execute("object.pathfinder.options", &json!({"precision": p})).unwrap();
|
||||
}
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 0.0, 99.5, 100.0, 100.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let r = ids(&s.execute("object.pathfinder.divide", &json!({})).unwrap());
|
||||
assert_eq!(node(&s, r[0]).children().unwrap().len(), faces, "precision {precision:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A hidden fill paints nothing: with Divide and Outline Will Remove Unpainted Artwork on, the
|
||||
/// pieces of an object whose only fill is hidden go too.
|
||||
#[test]
|
||||
fn remove_unpainted_counts_a_hidden_fill_as_unpainted() {
|
||||
let mut s = session();
|
||||
s.execute("object.pathfinder.options", &json!({"removeUnpainted": true})).unwrap();
|
||||
let a = rect(&mut s, 0.0, 0.0, 100.0, 100.0);
|
||||
let b = rect(&mut s, 50.0, 25.0, 100.0, 50.0);
|
||||
set_fill(&mut s, a, Color::rgb(1.0, 0.0, 0.0));
|
||||
set_fill(&mut s, b, Color::rgb(0.0, 0.0, 1.0));
|
||||
s.edit("t", |d, _| {
|
||||
d.node_mut(b).unwrap().appearance.fill_mut().unwrap().visible = false;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
let divided = pieces(&mut s, "object.pathfinder.divide");
|
||||
let red = Paint::solid(Color::rgb(1.0, 0.0, 0.0));
|
||||
assert_eq!(divided.len(), 1, "only the red square's piece: {divided:?}");
|
||||
assert_eq!(divided[0].0, red);
|
||||
}
|
||||
|
||||
/// Shape Modes unite a group selected with other objects first: at a fine precision a group
|
||||
/// member thinner than the default precision (0.005 pt) is kept there too.
|
||||
#[test]
|
||||
fn a_thin_group_member_survives_the_group_union_at_a_fine_precision() {
|
||||
for (precision, subpaths) in [(None, 2), (Some(0.001), 3)] {
|
||||
let mut s = session();
|
||||
if let Some(p) = precision {
|
||||
s.execute("object.pathfinder.options", &json!({"precision": p})).unwrap();
|
||||
}
|
||||
let (a, thin) = (rect(&mut s, 0.0, 0.0, 50.0, 50.0), rect(&mut s, 0.0, 100.0, 100.0, 0.005));
|
||||
s.execute("select.set", &json!({"ids": [a.0, thin.0]})).unwrap();
|
||||
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
|
||||
let other = rect(&mut s, 200.0, 0.0, 50.0, 50.0);
|
||||
s.execute("select.set", &json!({"ids": [g, other.0]})).unwrap();
|
||||
let r = ids(&s.execute("object.pathfinder.unite", &json!({})).unwrap());
|
||||
assert_eq!(path_of(&s, r[0]).0.subpaths.len(), subpaths, "precision {precision:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A Pathfinder operation records the options it used in its journal entry, so replaying the
|
||||
/// journal with other preferences gives the same art.
|
||||
#[test]
|
||||
fn pathfinder_journal_entries_replay_with_the_options_they_used() {
|
||||
let mut s = session();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 0, "y": 99.5, "width": 100, "height": 50})).unwrap();
|
||||
s.execute("paint.setFill", &json!({"none": true})).unwrap();
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.prefs.pathfinder = PathfinderOptions { precision: 1.0, remove_redundant_points: true, remove_unpainted: true };
|
||||
let r = ids(&s.execute("object.pathfinder.divide", &json!({})).unwrap());
|
||||
assert_eq!(node(&s, r[0]).children().unwrap().len(), 1, "the thin overlap and the unfilled piece go");
|
||||
let (id, p) = s.journal.last().unwrap().clone();
|
||||
assert_eq!(id, "object.pathfinder.divide");
|
||||
assert_eq!((&p["precision"], &p["removeRedundantPoints"], &p["removeUnpainted"]), (&json!(1.0), &json!(true), &json!(true)));
|
||||
let mut replay = Session::new();
|
||||
for (id, p) in &s.journal {
|
||||
replay.execute(id, p).unwrap();
|
||||
}
|
||||
assert_eq!(replay.prefs.pathfinder, PathfinderOptions::default());
|
||||
let doc = |s: &Session| serde_json::to_value(&*s.doc().unwrap().doc).unwrap();
|
||||
assert_eq!(doc(&replay), doc(&s));
|
||||
// Options given as params are checked as object.pathfinder.options checks them.
|
||||
assert!(s.execute("object.pathfinder.divide", &json!({"precision": 20})).is_err());
|
||||
}
|
||||
@@ -1427,3 +1427,32 @@ fn clicking_the_in_port_then_the_canvas_threads_a_new_frame_before_it() {
|
||||
let strokes = s.overlays(v).iter().filter(|o| matches!(o, vectorcraft_tools::Overlay::Line { .. })).count();
|
||||
assert_eq!(strokes, 6, "both frames selected: the first one's out port and the second one's in port show arrows");
|
||||
}
|
||||
|
||||
/// Given a family without a style, text.create, text.createInPath and text.setStyle keep the style
|
||||
/// when the family has it, else take the family's closest one, as text.setRangeStyle does: a family
|
||||
/// whose styles are numbered has no Regular to store (#4128). A style given is kept as given.
|
||||
#[test]
|
||||
fn a_family_without_its_style_takes_its_closest_style() {
|
||||
use vectorcraft_text::test_fonts::{NUMBERED_FAMILY as FAMILY, numbered_font};
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
db.add_font(numbered_font("W3").unwrap());
|
||||
db.add_font(numbered_font("W6").unwrap());
|
||||
let numbered = ["W3", "W6"];
|
||||
let style = |s: &Session, id: NodeId| obj(s, id).runs[0].style.font_style.clone();
|
||||
let create = |s: &mut Session, p: Value| NodeId(s.execute("text.create", &p).unwrap()["id"].as_u64().unwrap());
|
||||
let mut s = session();
|
||||
let created = create(&mut s, json!({"x": 10, "y": 50, "text": "a", "font": FAMILY}));
|
||||
assert!(numbered.contains(&style(&s, created).as_str()), "text.create: {}", style(&s, created));
|
||||
let pid = s.execute("path.create", &json!({"d": "M100 400 L400 100"})).unwrap()["id"].as_u64().unwrap();
|
||||
let on_path = s.execute("text.createInPath", &json!({"path": pid, "mode": "onPath", "text": "a", "font": FAMILY})).unwrap();
|
||||
let on_path = NodeId(on_path["id"].as_u64().unwrap());
|
||||
assert!(numbered.contains(&style(&s, on_path).as_str()), "text.createInPath: {}", style(&s, on_path));
|
||||
let given = create(&mut s, json!({"x": 10, "y": 90, "text": "a", "font": FAMILY, "style": "Medium"}));
|
||||
assert_eq!(style(&s, given), "Medium", "a style given is kept");
|
||||
let set = text(&mut s, "a");
|
||||
s.execute("text.setStyle", &json!({"ids": [set.0], "font": FAMILY})).unwrap();
|
||||
assert!(numbered.contains(&style(&s, set).as_str()), "text.setStyle: {}", style(&s, set));
|
||||
s.execute("text.setStyle", &json!({"ids": [set.0], "style": "W6"})).unwrap();
|
||||
s.execute("text.setStyle", &json!({"ids": [set.0], "font": FAMILY})).unwrap();
|
||||
assert_eq!(style(&s, set), "W6", "a style the family has is kept");
|
||||
}
|
||||
@@ -415,6 +415,12 @@ impl Session {
|
||||
self.tool.wants_ticks()
|
||||
}
|
||||
|
||||
/// Does the active tool build a stroke from every position the pointer passed
|
||||
/// ([`vectorcraft_tools::Tool::wants_samples`])?
|
||||
pub fn tool_wants_samples(&self) -> bool {
|
||||
self.tool.wants_samples()
|
||||
}
|
||||
|
||||
/// Is the active tool waiting for work it runs on another thread ([`Tool::waiting`])?
|
||||
pub fn tool_waiting(&self) -> bool {
|
||||
self.tool.waiting()
|
||||
|
||||
@@ -2991,6 +2991,17 @@ fn arb_ai_token() -> impl Strategy<Value = String> {
|
||||
"[1 0 0 1 0 0 10 10 12 10 1 8 10 1] /N X#",
|
||||
"[1e308 -1e308 0] /N X#",
|
||||
"0 /E X#",
|
||||
"[2 2] /Size X#",
|
||||
"/Cartesian /Type X#",
|
||||
"[1 1] /P X#",
|
||||
"(Adobe Path Blends) 1 0 92 XP",
|
||||
"(Adobe Path Blends) 1 0 999999 XP",
|
||||
"\n%44434241010000000000000000000000\n",
|
||||
"\n%0200000041000000000000000000000000000000\n",
|
||||
"\n%4G\n",
|
||||
"%_/ArtDictionary :\n%_(A) /String (ShapeBlendPathID) ,\n%_(K) /String (ShapeBlendPathType) ,\n%_;\n",
|
||||
"%_/ArtDictionary :\n%_(S) /String (ShapeBlendPathType) ,\n%_;\n",
|
||||
"9 () XW",
|
||||
"\n%AI9_BeginArtStyles\n",
|
||||
"\n%AI9_EndArtStyles\n",
|
||||
"/KnownStyle :",
|
||||
@@ -4254,3 +4265,80 @@ fn a_long_thin_shape_with_a_shadow_renders_and_exports() {
|
||||
let doc = vectorcraft_engine::cmd::fileio::load("long.af", &bytes).unwrap().doc;
|
||||
survive("long shape", || Some(doc)).unwrap();
|
||||
}
|
||||
|
||||
/// A blend in `.ai` editing data, written by hand: two keys (10 pt squares, red on the left, blue on
|
||||
/// the right) on a straight spine, `steps` steps drawn between them as the blend lays them out, and
|
||||
/// the record (`DCBA`, version 1, two keys `A` and `B`, see `vectorcraft_eps`' AI blend reader).
|
||||
fn blend_text(steps: usize) -> String {
|
||||
use std::fmt::Write;
|
||||
let square = |x: f64, hidden: bool, t: f64| {
|
||||
let p = if hidden { "%_" } else { "" };
|
||||
format!("{p}0 0 0 0 {} 0 {} Xa\n{p}{x} 40 m\n{p}{x} 50 L\n{p}{} 50 L\n{p}{} 40 L\n{p}f\n", 1.0 - t, t, x + 10.0, x + 10.0)
|
||||
};
|
||||
let part = |kind: &str, id: Option<&str>| {
|
||||
let id = id.map(|i| format!("%_({i}) /String (ShapeBlendPathID) ,\n")).unwrap_or_default();
|
||||
format!("%_/ArtDictionary :\n{id}%_({kind}) /String (ShapeBlendPathType) ,\n%_;\n")
|
||||
};
|
||||
let span = 10.0 * (steps as f64 + 1.0);
|
||||
let mut s = String::from("%_0 Ae\n%_u\n");
|
||||
s += &square(0.0, true, 0.0);
|
||||
s += &part("K", Some("A"));
|
||||
s += &square(span, true, 1.0);
|
||||
s += &part("K", Some("B"));
|
||||
let _ = write!(s, "%_5 45 m\n%_{} 45 L\n%_N\n", span + 5.0);
|
||||
s += &part("S", None);
|
||||
s += "%_U\n%_9 () XW\nu\n";
|
||||
for i in 0..steps + 2 {
|
||||
let t = i as f64 / (steps as f64 + 1.0);
|
||||
s += &square(t * span, false, t);
|
||||
}
|
||||
s += "U\n9 () XW\n0 Ae\n";
|
||||
let mut words: Vec<u32> = vec![u32::from_le_bytes(*b"DCBA"), 1, 0, 0, 0, 0, 0, 0, 0, 0, 2];
|
||||
for id in ['A', 'B'] {
|
||||
words.extend([id as u32, 0, 0, 0, 0, 0]);
|
||||
}
|
||||
let hex: String = words.iter().flat_map(|w| w.to_le_bytes()).map(|b| format!("{b:02X}")).collect();
|
||||
let _ = write!(s, "(Adobe Path Blends) 1 0 {} XP\n%{hex}\n", hex.len() / 2);
|
||||
s
|
||||
}
|
||||
|
||||
/// `.ai` editing data holding `layer_art` on one layer, compressed as the private data is.
|
||||
fn ai_private(layer_art: &str) -> Vec<u8> {
|
||||
use vectorcraft_testkit::ai;
|
||||
let data = ai::editing_data(4000.0, 200.0, &ai::layer("L", layer_art));
|
||||
[b"%AI24_ZStandard_Data".as_slice(), &zstd(&data)].concat()
|
||||
}
|
||||
|
||||
/// A blend of many steps doesn't stall the import: one within the limits (a thousand steps between
|
||||
/// two keys) is checked and made live quickly, one past them keeps its drawn steps without being
|
||||
/// laid out.
|
||||
#[test]
|
||||
fn large_ai_blends_import_in_bounded_time() {
|
||||
for (steps, live) in [(3, true), (998, true), (1_500, false)] {
|
||||
let private = ai_private(&blend_text(steps));
|
||||
let started = std::time::Instant::now();
|
||||
let (doc, notes, read) = vectorcraft_eps::layered_ai(&private, Document::new(4000.0, 200.0), vec![], false, true, 1.0);
|
||||
assert!(read, "{steps} steps: read from the layers ({notes:?})");
|
||||
let took = started.elapsed();
|
||||
assert!(took < std::time::Duration::from_secs(30), "{steps} steps took {took:?}");
|
||||
let mut blends = 0;
|
||||
doc.walk(|n| blends += usize::from(matches!(n.kind, vectorcraft_doc::NodeKind::Blend { .. })));
|
||||
assert_eq!(blends == 1, live, "{steps} steps: live {live}");
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(config())]
|
||||
|
||||
/// A `.ai` blend whose record, parts or drawn steps are damaged or hostile: read live, as its
|
||||
/// drawn steps, or not at all, never panicking.
|
||||
#[test]
|
||||
fn ai_blend_never_panics(steps in 1usize..6, cut in 0usize..2_500, edits in prop::collection::vec((0usize..2_500, prop::sample::select(vec!['0', '9', '-', '.', ' ', '\n', '(', ')', '/', ':', ';', '%', '_', 'K', 'S', 'A', 'B', 'u', 'U', 'F', 'X'])), 0..12)) {
|
||||
let text = mutate_text(&blend_text(steps), cut, &edits);
|
||||
let private = ai_private(&text);
|
||||
// Far-out coordinates: the check's grid saturates instead of overflowing.
|
||||
let far = ai_private(&blend_text(steps).replace(" 40 m\n", " 1e300 m\n").replace(" 50 L\n", " -1e300 L\n"));
|
||||
survive("a .ai blend far out", || Some(vectorcraft_eps::layered_ai(&far, Document::new(100.0, 100.0), vec![], false, true, 1.0).0))?;
|
||||
survive("mutated .ai blend", || Some(vectorcraft_eps::layered_ai(&private, Document::new(100.0, 100.0), vec![], false, true, 1.0).0))?;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
//! Blends from the editing data (`(Adobe Path Blends) 1 0 n XP`), read as live blends.
|
||||
//!
|
||||
//! What a blend is and does is Illustrator's public documentation: key objects, the spine the
|
||||
//! steps follow, Blend Options' Spacing (Smooth Color, Specified Steps, Specified Distance) and
|
||||
//! Orientation (Align to Page, Align to Path), Replace Spine and Reverse Spine
|
||||
//! (<https://helpx.adobe.com/illustrator/using/blending-objects.html>).
|
||||
//!
|
||||
//! How the editing data writes one isn't documented. As written in files users sent (used
|
||||
//! locally, never committed): the blend's own art on `%_` lines, a group holding the key objects
|
||||
//! and the spine, each object's `/ArtDictionary` naming its part (`ShapeBlendPathType`: `K` a key,
|
||||
//! `S` the spine) and a key's id (`ShapeBlendPathID`); then the steps drawn, a group on plain
|
||||
//! lines; then `(Adobe Path Blends) 1 0 n XP` and `n` bytes as hex on `%` lines. Those bytes
|
||||
//! start `DCBA`, version 1; word 10 (little endian) is the number of keys, and the words after it
|
||||
//! a record per key that starts with the key's id. What the other words mean isn't known, so the
|
||||
//! spacing and orientation are taken from the steps drawn instead: as many steps as they have
|
||||
//! between two keys, and whichever orientation lays the blend out as they are drawn. A blend whose
|
||||
//! parts don't agree, or that doesn't come out as drawn, keeps its drawn steps.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::blend::blend_expand;
|
||||
use vectorcraft_doc::live::{BlendOrientation, BlendSpacing, BlendSpec};
|
||||
use vectorcraft_doc::{AppearanceItem, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{PathData, Point};
|
||||
|
||||
/// The plugin that writes blends.
|
||||
pub(super) const PLUGIN: &str = "Adobe Path Blends"; // brand-ok: the plugin name the files use
|
||||
/// The most bytes of a blend's record read.
|
||||
pub(super) const MAX_RECORD: usize = 4096;
|
||||
/// The most keys read from one blend.
|
||||
const MAX_KEYS: usize = 64;
|
||||
/// The most steps between two keys (Blend Options' limit).
|
||||
const MAX_STEPS: usize = 1000;
|
||||
/// The most objects (keys and steps) one blend may lay out to be read live; more keep their
|
||||
/// drawn steps.
|
||||
pub(super) const MAX_BLEND_OBJECTS: usize = 5_000;
|
||||
/// How far (pt) a step laid out here may be from where the file draws it.
|
||||
const PLACE_TOLERANCE: f64 = 0.5;
|
||||
/// How far a step's colour (each channel, 0 to 1) may be from the drawn one.
|
||||
const COLOR_TOLERANCE: f32 = 0.02;
|
||||
/// The note for a blend that keeps its drawn steps.
|
||||
pub(super) const DRAWN: &str = "a blend VectorCraft couldn't read as a live blend comes in as its drawn steps";
|
||||
|
||||
/// A blend part an object's dictionary names: its type (`K`, `S`) and its id.
|
||||
pub(super) type Roles = HashMap<NodeId, (String, Option<String>)>;
|
||||
|
||||
/// The bytes of hex digits `hex`, or `None` when they aren't pairs of hex digits.
|
||||
pub(super) fn hex_bytes(hex: &[u8]) -> Option<Vec<u8>> {
|
||||
if !hex.len().is_multiple_of(2) {
|
||||
return None;
|
||||
}
|
||||
let digit = |b: u8| (b as char).to_digit(16).map(|d| d as u8);
|
||||
hex.as_chunks::<2>().0.iter().map(|&[a, b]| Some(digit(a)? << 4 | digit(b)?)).collect()
|
||||
}
|
||||
|
||||
/// The keys' ids in a blend's record, in its order; `None` for a record that isn't one.
|
||||
pub(super) fn record_ids(bytes: &[u8]) -> Option<Vec<String>> {
|
||||
if bytes.get(..4)? != b"DCBA" || bytes.len() > MAX_RECORD {
|
||||
return None;
|
||||
}
|
||||
let words: Vec<u32> = bytes.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c)).collect();
|
||||
if words.get(1) != Some(&1) {
|
||||
return None;
|
||||
}
|
||||
let count = usize::try_from(*words.get(10)?).ok().filter(|c| (2..=MAX_KEYS).contains(c))?;
|
||||
let rest = words.len().checked_sub(11)?;
|
||||
if rest == 0 || !rest.is_multiple_of(count) {
|
||||
return None;
|
||||
}
|
||||
let size = rest / count;
|
||||
(0..count)
|
||||
.map(|i| {
|
||||
let w = *words.get(11 + i * size)?;
|
||||
let c = char::from_u32(w).filter(char::is_ascii_alphanumeric)?;
|
||||
Some(c.to_string())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The blend `edit` (its key objects and spine, as their dictionaries name them in `roles`) and
|
||||
/// `drawn` (its steps as the file draws them) make, with the keys of the record `ids`: one live
|
||||
/// blend, or `None` when they don't agree or it doesn't come out as drawn.
|
||||
///
|
||||
/// `budget`: how many more objects blends may lay out in this import; a blend that would lay out
|
||||
/// more isn't made live (each blend is laid out twice, once per orientation, and checked against
|
||||
/// its drawn steps, so a file of huge blends mustn't stall the import). What it lays out is taken
|
||||
/// from it.
|
||||
pub(super) fn live_blend(edit: &Node, drawn: &Node, ids: &[String], roles: &Roles, budget: &mut usize) -> Option<NodeKind> {
|
||||
let parts = edit.children()?;
|
||||
let role = |n: &Arc<Node>| roles.get(&n.id);
|
||||
let keys: Vec<Arc<Node>> = parts.iter().filter(|n| role(n).is_some_and(|(t, _)| t == "K")).cloned().collect();
|
||||
let spine = parts.iter().filter(|n| role(n).is_some_and(|(t, _)| t == "S")).find_map(|n| match &n.kind {
|
||||
NodeKind::Path { path, .. } => Some(path.clone()),
|
||||
_ => None,
|
||||
});
|
||||
// Each key named once, and the record's keys the same.
|
||||
let mut named: Vec<&str> = keys.iter().filter_map(|k| role(k).and_then(|(_, id)| id.as_deref())).collect();
|
||||
if keys.len() < 2 || named.len() != keys.len() || ids.len() != keys.len() {
|
||||
return None;
|
||||
}
|
||||
named.sort_unstable();
|
||||
let mut listed: Vec<&str> = ids.iter().map(String::as_str).collect();
|
||||
listed.sort_unstable();
|
||||
if named != listed || named.windows(2).any(|w| w.first() == w.get(1)) {
|
||||
return None;
|
||||
}
|
||||
// The steps between two keys: the drawn objects that aren't keys, shared out.
|
||||
let drawn: Vec<&Arc<Node>> = drawn.children()?.iter().collect();
|
||||
let between = (drawn.len().checked_sub(keys.len())?).checked_div(keys.len() - 1)?;
|
||||
if between == 0 || between > MAX_STEPS || drawn.len() != keys.len() + between * (keys.len() - 1) || drawn.len() > MAX_BLEND_OBJECTS {
|
||||
return None;
|
||||
}
|
||||
// Both orientations are laid out.
|
||||
let cost = drawn.len().saturating_mul(2);
|
||||
if cost > *budget {
|
||||
return None;
|
||||
}
|
||||
*budget -= cost;
|
||||
// The drawn steps' centres and paints, once.
|
||||
let drawn: Vec<(Point, Fill)> = drawn.iter().map(|d| Some((centre(d)?, fill(d)))).collect::<Option<_>>()?;
|
||||
let keys: Vec<Arc<Node>> = keys
|
||||
.into_iter()
|
||||
.map(|k| {
|
||||
let mut k = (*k).clone();
|
||||
k.visible = true;
|
||||
Arc::new(k)
|
||||
})
|
||||
.collect();
|
||||
let spine = spine?;
|
||||
let key_anchors = on_spine(&keys, &spine)?;
|
||||
let spacing = BlendSpacing::Steps(u32::try_from(between).ok()?);
|
||||
// The orientation that lays the steps out as drawn, the closest when both do.
|
||||
[BlendOrientation::AlignToPage, BlendOrientation::AlignToPath]
|
||||
.into_iter()
|
||||
.filter_map(|orientation| {
|
||||
let spec = BlendSpec { spacing, orientation, spine: Some(spine.clone()), key_anchors: key_anchors.clone(), ..BlendSpec::default() };
|
||||
let laid = blend_expand(&keys, &spec);
|
||||
let off = how_far(&laid, &drawn)?;
|
||||
Some((off, spec))
|
||||
})
|
||||
.min_by(|a, b| a.0.total_cmp(&b.0))
|
||||
.map(|(_, spec)| NodeKind::Blend { children: keys, spec: Box::new(spec) })
|
||||
}
|
||||
|
||||
/// The anchor of `spine`'s first subpath each key's centre sits on (within a point), each a
|
||||
/// different one.
|
||||
fn on_spine(keys: &[Arc<Node>], spine: &PathData) -> Option<Vec<u32>> {
|
||||
let anchors = &spine.subpaths.first()?.anchors;
|
||||
let mut out: Vec<u32> = vec![];
|
||||
for k in keys {
|
||||
let c = centre(k)?;
|
||||
let (i, d) = anchors.iter().enumerate().map(|(i, a)| (i, (a.p - c).hypot())).min_by(|a, b| a.1.total_cmp(&b.1))?;
|
||||
let i = u32::try_from(i).ok()?;
|
||||
if d > 1.0 || out.contains(&i) {
|
||||
return None;
|
||||
}
|
||||
out.push(i);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn centre(n: &Node) -> Option<Point> {
|
||||
n.geometric_bounds().map(|b| b.center()).filter(|p| p.x.is_finite() && p.y.is_finite())
|
||||
}
|
||||
|
||||
/// An object's fill, as far as the check compares it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Fill {
|
||||
/// No fill.
|
||||
None,
|
||||
/// A solid colour, as RGB.
|
||||
Solid([f32; 3]),
|
||||
/// A fill this can't compare (a gradient, a pattern): the blend isn't made live.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// An object's first fill.
|
||||
fn fill(n: &Node) -> Fill {
|
||||
n.appearance
|
||||
.items
|
||||
.iter()
|
||||
.find_map(|i| match i {
|
||||
AppearanceItem::Fill(f) => Some(match &f.paint {
|
||||
Paint::None => Fill::None,
|
||||
Paint::Solid { color, .. } => Fill::Solid(Color::to_rgb(color)),
|
||||
_ => Fill::Other,
|
||||
}),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(Fill::None)
|
||||
}
|
||||
|
||||
/// Do two fills match: both none, or solid colours within the tolerance?
|
||||
fn same_fill(a: Fill, b: Fill) -> bool {
|
||||
match (a, b) {
|
||||
(Fill::None, Fill::None) => true,
|
||||
(Fill::Solid(a), Fill::Solid(b)) => a.iter().zip(b).all(|(x, y)| (x - y).abs() <= COLOR_TOLERANCE),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// How far the objects `laid` are from the drawn ones (`drawn`: their centres and fills): the
|
||||
/// farthest, each drawn object matched to a laid one of its own within the tolerance (each laid
|
||||
/// one matches one drawn one: the nearest still free; through a grid of cells the tolerance wide,
|
||||
/// so each finds its neighbours without looking at them all), when they are as many and each
|
||||
/// matches in place and fill; else `None` (also when that matching leaves one out).
|
||||
fn how_far(laid: &[Node], drawn: &[(Point, Fill)]) -> Option<f64> {
|
||||
if laid.len() != drawn.len() {
|
||||
return None;
|
||||
}
|
||||
let cell = |p: Point| ((p.x / PLACE_TOLERANCE).floor() as i64, (p.y / PLACE_TOLERANCE).floor() as i64);
|
||||
let laid: Vec<(Point, Fill)> = laid.iter().map(|l| Some((centre(l)?, fill(l)))).collect::<Option<_>>()?;
|
||||
let mut grid: HashMap<(i64, i64), Vec<usize>> = HashMap::with_capacity(laid.len());
|
||||
for (i, (p, _)) in laid.iter().enumerate() {
|
||||
grid.entry(cell(*p)).or_default().push(i);
|
||||
}
|
||||
let mut used = vec![false; laid.len()];
|
||||
let mut worst: f64 = 0.0;
|
||||
for &(c, f) in drawn {
|
||||
let (cx, cy) = cell(c);
|
||||
// Coordinates far out saturate the cells: the neighbours' keys saturate too.
|
||||
let (i, near) = (-1i64..=1)
|
||||
.flat_map(|dx| (-1i64..=1).map(move |dy| (cx.saturating_add(dx), cy.saturating_add(dy))))
|
||||
.filter_map(|k| grid.get(&k))
|
||||
.flatten()
|
||||
.filter(|&&i| !used.get(i).copied().unwrap_or(true))
|
||||
.filter_map(|&i| laid.get(i).map(|l| (i, l)))
|
||||
.filter(|(_, (p, lf))| (*p - c).hypot() <= PLACE_TOLERANCE && same_fill(*lf, f))
|
||||
.map(|(i, (p, _))| (i, (*p - c).hypot()))
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))?;
|
||||
if let Some(u) = used.get_mut(i) {
|
||||
*u = true;
|
||||
}
|
||||
worst = worst.max(near);
|
||||
}
|
||||
Some(worst)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Records that aren't one: too short, another magic, another version, key counts out of
|
||||
/// range or not dividing the rest, ids that aren't letters or digits, and hex digits that
|
||||
/// don't pair up. None of them panics.
|
||||
#[test]
|
||||
fn records_are_checked() {
|
||||
let words = |w: &[u32]| w.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>();
|
||||
let magic = u32::from_le_bytes(*b"DCBA");
|
||||
let good = words(&[magic, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 'A' as u32, 0, 0, 0, 0, 0, 'B' as u32, 0, 0, 0, 0, 0]);
|
||||
assert_eq!(record_ids(&good), Some(vec!["A".to_string(), "B".to_string()]));
|
||||
for bad in [
|
||||
vec![],
|
||||
b"DCB".to_vec(),
|
||||
words(&[0x41424344, 1]),
|
||||
words(&[magic, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 65, 0, 66, 0]),
|
||||
words(&[magic, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 65]),
|
||||
words(&[magic, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1000, 65]),
|
||||
words(&[magic, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 65, 0, 66]),
|
||||
words(&[magic, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0x20, 0, 66, 0]),
|
||||
words(&[magic, 1, 0, 0, 0, 0, 0, 0, 0, 0, u32::MAX]),
|
||||
] {
|
||||
assert_eq!(record_ids(&bad), None, "{bad:?}");
|
||||
}
|
||||
assert_eq!(hex_bytes(b"4A4"), None);
|
||||
assert_eq!(hex_bytes(b"4G"), None);
|
||||
assert_eq!(hex_bytes(b"4a4B"), Some(vec![0x4a, 0x4b]));
|
||||
}
|
||||
|
||||
/// A blend that would lay out more than the import's budget has left isn't made live, and
|
||||
/// takes nothing from it.
|
||||
#[test]
|
||||
fn a_blend_past_the_budget_isnt_made_live() {
|
||||
let edit = Node::new(NodeId(1), NodeKind::Group { children: vec![], clip: false });
|
||||
let drawn = Node::new(NodeId(2), NodeKind::Group { children: vec![], clip: false });
|
||||
let mut budget = 1;
|
||||
assert!(live_blend(&edit, &drawn, &["A".into(), "B".into()], &Roles::new(), &mut budget).is_none());
|
||||
assert_eq!(budget, 1);
|
||||
}
|
||||
|
||||
/// Two drawn steps on one laid object don't both match it: each laid object matches one drawn
|
||||
/// one, so a drawing the blend doesn't lay out isn't taken for it.
|
||||
#[test]
|
||||
fn each_laid_step_matches_one_drawn_step() {
|
||||
let square = |x: f64| {
|
||||
let path = vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(x, 0.0, x + 10.0, 10.0));
|
||||
Node::path(NodeId(0), path, Default::default())
|
||||
};
|
||||
let laid = [square(0.0), square(50.0)];
|
||||
let c = |x: f64| (Point::new(x + 5.0, 5.0), Fill::None);
|
||||
assert!(how_far(&laid, &[c(0.0), c(50.0)]).is_some());
|
||||
assert!(how_far(&laid, &[c(0.0), c(0.1)]).is_none(), "both drawn steps near the first laid one");
|
||||
// Coordinates far out don't overflow the grid.
|
||||
let far = [square(1e300), square(-1e300)];
|
||||
let _ = how_far(&far, &[c(1e300), c(-1e300)]);
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
//! objects and points. Anything it doesn't read is an error: the caller opens the file the way it
|
||||
//! did before (the printed page, or the PDF), with a warning saying why.
|
||||
|
||||
mod blend;
|
||||
mod frames;
|
||||
mod lex;
|
||||
mod mesh;
|
||||
|
||||
@@ -422,6 +422,18 @@ mod tests {
|
||||
assert_eq!((geom.start, geom.end), (Point::new(10.0, 10.0), Point::new(50.0, 10.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_stops_beyond_the_cap_are_ignored() {
|
||||
let mut d = GradientDef::begin(&[V::Str(b"H".to_vec()), V::Num(0.0)]).unwrap();
|
||||
let mut spots = vec![];
|
||||
for i in 0..257 {
|
||||
let ramp = i as f64 / 256.0 * 100.0;
|
||||
d.stop(&nums(&[0.2, 0.4, 0.6, 0.0, 1.0, 1.0, 6.0, 50.0, ramp]), &mut spots);
|
||||
}
|
||||
let (_, g) = d.finish().unwrap();
|
||||
assert_eq!(g.stops.len(), MAX_STOPS);
|
||||
}
|
||||
|
||||
/// A linear gradient of three stops as newer files place it: `Bg` with numbers that aren't in
|
||||
/// art space, `Xm` for the whole ramp and a `Bm` for each pair of stops.
|
||||
#[test]
|
||||
|
||||
@@ -75,6 +75,9 @@ const MAX_DEPTH: usize = 256;
|
||||
const MAX_STACK: usize = 1 << 20;
|
||||
/// Most objects read.
|
||||
const MAX_NODES: usize = 4_000_000;
|
||||
/// The most objects all the blends of one import may lay out to be checked (each twice) and made
|
||||
/// live; past it, blends keep their drawn steps.
|
||||
const BLEND_BUDGET: usize = 50_000;
|
||||
/// Most points in one path.
|
||||
const MAX_POINTS: usize = 4_000_000;
|
||||
/// Largest image read (pixels).
|
||||
@@ -505,6 +508,12 @@ struct Reader<'a> {
|
||||
drawn_looks: usize,
|
||||
/// Nodes read from `%_` lines.
|
||||
hidden_ids: HashSet<NodeId>,
|
||||
/// The blend part each object's dictionary names (`ShapeBlendPathType`, `ShapeBlendPathID`).
|
||||
blend_roles: super::blend::Roles,
|
||||
/// A blend's record being read from the `%` lines after its `XP`: its length and hex digits.
|
||||
blend_record: Option<(usize, Vec<u8>)>,
|
||||
/// How many more objects blends may lay out in this import ([`super::blend::live_blend`]).
|
||||
blend_budget: usize,
|
||||
/// A group just ended, its state (`Xy`, `Xd`, `XW`) not yet read.
|
||||
group_ended: bool,
|
||||
/// A layer's own state (`Xy` after its art, before `LB`), until something says the art moves on.
|
||||
@@ -667,6 +676,9 @@ impl<'a> Reader<'a> {
|
||||
warnings: Vec::new(),
|
||||
drawn_looks: 0,
|
||||
hidden_ids: HashSet::new(),
|
||||
blend_roles: HashMap::new(),
|
||||
blend_record: None,
|
||||
blend_budget: BLEND_BUDGET,
|
||||
clip_fills: HashSet::new(),
|
||||
looks: HashSet::new(),
|
||||
compound_groups: HashSet::new(),
|
||||
@@ -745,6 +757,19 @@ impl<'a> Reader<'a> {
|
||||
fn comment(&mut self, c: &[u8]) -> Result<(), String> {
|
||||
let line = String::from_utf8_lossy(c);
|
||||
let line = line.trim_end();
|
||||
if let Some((len, hex)) = self.blend_record.as_mut() {
|
||||
if !line.is_empty() && line.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||
// As many digits as the record says it has, no more.
|
||||
let wanted = len.saturating_mul(2);
|
||||
let take = wanted.saturating_sub(hex.len()).min(line.len());
|
||||
hex.extend_from_slice(line.as_bytes().get(..take).unwrap_or_default());
|
||||
if hex.len() >= wanted {
|
||||
self.end_blend();
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
self.end_blend();
|
||||
}
|
||||
if let Some(r) = self.raster.as_mut()
|
||||
&& r.operands.is_some()
|
||||
&& !line.is_empty()
|
||||
@@ -1129,6 +1154,9 @@ impl<'a> Reader<'a> {
|
||||
// ---- operators -------------------------------------------------------------------------
|
||||
|
||||
fn op(&mut self, w: &str, hidden: bool) -> Result<(), String> {
|
||||
if self.blend_record.is_some() {
|
||||
self.end_blend();
|
||||
}
|
||||
match w {
|
||||
// The writer's placeholder for a number the object doesn't have (a radial gradient's
|
||||
// highlight `-- -- angle length Bh`): a NaN keeps the other operands where they are.
|
||||
@@ -1398,6 +1426,14 @@ impl<'a> Reader<'a> {
|
||||
r.operands = Some(vals);
|
||||
}
|
||||
}
|
||||
// A plugin group ends; a blend's record follows on `%` lines.
|
||||
"XP" => {
|
||||
let name = vals.iter().find_map(V::text).unwrap_or_default();
|
||||
let len = Self::nums(&vals).last().copied().unwrap_or(0.0);
|
||||
if name == super::blend::PLUGIN && len.is_finite() && len > 0.0 && len <= super::blend::MAX_RECORD as f64 {
|
||||
self.blend_record = Some((len as usize, vec![]));
|
||||
}
|
||||
}
|
||||
_ if IGNORED.contains(&w) => {}
|
||||
// Before the art, the setup runs procedures of the printing format.
|
||||
_ if self.frames.is_empty() => {}
|
||||
@@ -1646,9 +1682,59 @@ impl<'a> Reader<'a> {
|
||||
self.frames.iter().all(|f| !matches!(&f.kind, Kind::Layer(a) if !a.visible))
|
||||
}
|
||||
|
||||
/// A blend's record read: the blend's own art (the group of its key objects and spine, on `%_`
|
||||
/// lines) and its drawn steps (the group after it) become one live blend, or, where they can't,
|
||||
/// the drawn steps stay, without the blend's own art drawn over them (see [`super::blend`]).
|
||||
fn end_blend(&mut self) {
|
||||
let Some((_, hex)) = self.blend_record.take() else { return };
|
||||
let ids = super::blend::hex_bytes(&hex).as_deref().and_then(super::blend::record_ids);
|
||||
let roles = &self.blend_roles;
|
||||
let Some(f) = self.frames.last_mut() else { return };
|
||||
let n = f.children.len();
|
||||
let (Some(at), Some(drawn)) = (n.checked_sub(2), n.checked_sub(1)) else { return };
|
||||
let part_of_blend = |node: &Node| node.children().is_some_and(|c| c.iter().any(|k| roles.contains_key(&k.id)));
|
||||
let (Some(edit), Some(steps)) = (f.children.get(at), f.children.get(drawn)) else { return };
|
||||
if !part_of_blend(edit) {
|
||||
return;
|
||||
}
|
||||
if !matches!(steps.kind, NodeKind::Group { clip: false, .. }) {
|
||||
// The steps aren't a group of drawn steps: the blend's own art goes all the same, so
|
||||
// its keys and spine aren't drawn over what the file draws.
|
||||
f.children.remove(at);
|
||||
self.warn(super::blend::DRAWN);
|
||||
return;
|
||||
}
|
||||
let mut budget = self.blend_budget;
|
||||
let live = ids.and_then(|ids| super::blend::live_blend(edit, steps, &ids, roles, &mut budget));
|
||||
self.blend_budget = budget;
|
||||
let Some(mut steps) = f.children.pop() else { return };
|
||||
let Some(_edit) = f.children.pop() else { return };
|
||||
match live {
|
||||
Some(kind) => {
|
||||
// The steps the blend lays out count as the objects they draw, as its drawn steps
|
||||
// did (they were counted as read).
|
||||
let mut blend = Node::new(self.doc.alloc_id(), kind);
|
||||
(blend.name, blend.visible, blend.locked) = (steps.name.take(), steps.visible, steps.locked);
|
||||
(blend.opacity, blend.blend, blend.isolate, blend.knockout) = (steps.opacity, steps.blend, steps.isolate, steps.knockout);
|
||||
f.children.push(blend);
|
||||
}
|
||||
None => {
|
||||
f.children.push(steps);
|
||||
self.warn(super::blend::DRAWN);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An object's dictionary: its name (`AIArtName`, or the XML id `AI10_ArtUID`), and the
|
||||
/// opacity mask it may carry.
|
||||
fn art_dictionary(&mut self, o: &Obj) {
|
||||
// A blend's key object or spine.
|
||||
if let Some(kind) = o.text("ShapeBlendPathType")
|
||||
&& let Some(id) = self.last_object().map(|n| n.id)
|
||||
&& self.blend_roles.len() < 100_000
|
||||
{
|
||||
self.blend_roles.insert(id, (kind, o.text("ShapeBlendPathID")));
|
||||
}
|
||||
// An envelope (a distortion, `AIDeformStyle` / `DeformValue`) is written on `%_` lines as
|
||||
// a group holding the mesh that shapes it; the distorted art the file's PDF part draws
|
||||
// follows on plain lines. That mesh isn't art, so it goes (#2405).
|
||||
|
||||
@@ -764,6 +764,20 @@ mod tests {
|
||||
assert_eq!(feather.params["radius"].as_f64(), Some(5.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_styles_clear_operands_beyond_the_cap() {
|
||||
let mut data = Vec::from(
|
||||
b"/KnownStyle :\n(Soft) /Name ,\n/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n",
|
||||
);
|
||||
for _ in 0..80 {
|
||||
data.extend_from_slice(b"1 ");
|
||||
}
|
||||
data.extend_from_slice(b"/Dictionary : /NotRecorded ,\n; /Dict ;\n /Part ,\n;\n");
|
||||
let styles = art_styles(&data);
|
||||
let [feather] = styles["Soft"].effects.as_slice() else { panic!() };
|
||||
assert_eq!(feather.params["radius"].as_f64(), Some(5.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn art_styles_ignore_filters_beyond_the_cap() {
|
||||
const UNIT: &[u8] = b"/BasicFilter :\n(Adobe Feather) 1 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n; /Dict ;\n /Part ,\n";
|
||||
@@ -781,14 +795,80 @@ mod tests {
|
||||
fn hostile_dash_offsets_and_width_profiles_are_tamed() {
|
||||
let mut f = Filter::default();
|
||||
paint_op(&mut f, "d", &[V::Arr(vec![V::Num(5.0)]), V::Num(f64::NAN)]);
|
||||
assert_eq!(f.dash.map(|d| d.offset), Some(0.0));
|
||||
assert_eq!(f.dash.as_ref().map(|d| d.offset), Some(0.0));
|
||||
// Positions outside 0..=1 and out of order, a negative width, a non-finite one.
|
||||
let arrays = HashMap::from([
|
||||
("BSVariableWidthTValuesArray".to_string(), vec![1.5, -0.2, 0.5, 0.7]),
|
||||
("BSCenteredWidthsArray".to_string(), vec![-1.0, 2.0, 0.5, f64::INFINITY]),
|
||||
]);
|
||||
assert_eq!(width_profile(&arrays).map(|p| p.points), Some(vec![(0.0, 2.0, 2.0), (0.5, 0.5, 0.5), (1.0, 0.0, 0.0)]));
|
||||
let ok = (0..64).map(|_| V::Num(2.0)).collect::<Vec<_>>();
|
||||
paint_op(&mut f, "d", &[V::Arr(ok), V::Num(0.0)]);
|
||||
assert_eq!(f.dash.as_ref().map(|d| d.pattern.len()), Some(64));
|
||||
let huge = (0..65).map(|_| V::Num(1.0)).collect::<Vec<_>>();
|
||||
paint_op(&mut f, "d", &[V::Arr(huge), V::Num(0.0)]);
|
||||
assert_eq!(f.dash, None);
|
||||
let long = (0..1025).map(|i| i as f64 / 1024.0).collect::<Vec<_>>();
|
||||
let wide = vec![1.0; 1025];
|
||||
let huge = HashMap::from([("BSVariableWidthTValuesArray".to_string(), long), ("BSCenteredWidthsArray".to_string(), wide)]);
|
||||
assert_eq!(width_profile(&huge), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_stroke_widths_are_sanitized() {
|
||||
let mut f = Filter::default();
|
||||
paint_op(&mut f, "w", &[V::Num(12.0)]);
|
||||
assert_eq!(f.width, 12.0);
|
||||
paint_op(&mut f, "w", &[V::Num(-1.0)]);
|
||||
assert_eq!(f.width, 12.0);
|
||||
paint_op(&mut f, "w", &[V::Num(f64::INFINITY)]);
|
||||
assert_eq!(f.width, 12.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_stroke_paint_flags_ignore_short_operands() {
|
||||
let mut f = Filter { paints: (true, true), ..Filter::default() };
|
||||
paint_op(&mut f, "Xd", &[V::Num(1.0)]);
|
||||
assert_eq!(f.paints, (true, true));
|
||||
paint_op(&mut f, "Xd", &[V::Num(0.0), V::Num(1.0)]);
|
||||
assert_eq!(f.paints, (false, true));
|
||||
paint_op(&mut f, "Xd", &[V::Num(2.0), V::Num(0.0)]);
|
||||
assert_eq!(f.paints, (true, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_stroke_miter_limits_are_capped() {
|
||||
let mut f = Filter::default();
|
||||
paint_op(&mut f, "M", &[V::Num(900.0)]);
|
||||
assert_eq!(f.miter, 500.0);
|
||||
paint_op(&mut f, "M", &[V::Num(0.5)]);
|
||||
assert_eq!(f.miter, 500.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_stroke_caps_and_joins_ignore_invalid_values() {
|
||||
let mut f = Filter::default();
|
||||
paint_op(&mut f, "J", &[V::Num(99.0)]);
|
||||
assert_eq!(f.cap, LineCap::Butt);
|
||||
paint_op(&mut f, "J", &[V::Num(2.0)]);
|
||||
assert_eq!(f.cap, LineCap::Square);
|
||||
paint_op(&mut f, "j", &[V::Num(99.0)]);
|
||||
assert_eq!(f.join, LineJoin::Miter);
|
||||
paint_op(&mut f, "j", &[V::Num(1.0)]);
|
||||
assert_eq!(f.join, LineJoin::Round);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_blend_opacities_are_clamped() {
|
||||
let mut f = Filter::default();
|
||||
paint_op(&mut f, "Xy", &[V::Num(3.0), V::Num(1.5)]);
|
||||
assert_eq!(f.xy, Some((3, 1.0)));
|
||||
paint_op(&mut f, "Xy", &[V::Num(-1.0), V::Num(0.25)]);
|
||||
assert_eq!(f.xy, Some((0, 0.25)));
|
||||
paint_op(&mut f, "Xy", &[V::Num(0.0), V::Num(f64::NAN)]);
|
||||
assert_eq!(f.xy, Some((0, 0.25)));
|
||||
}
|
||||
|
||||
/// A basic filter `name` whose dictionary holds `body`.
|
||||
fn basic(name: &str, body: &str) -> String {
|
||||
format!("/BasicFilter :\n({name}) 0 0 /Filter ,\n1 /Visible ,\n/Dictionary : /NotRecorded ,\n{body}; /Dict ;\n /Part ,\n")
|
||||
|
||||
@@ -1569,3 +1569,194 @@ fn stroked_path_guides_from_the_star_operator() {
|
||||
assert_eq!(n.appearance.items.len(), 1);
|
||||
assert!(matches!(n.appearance.items[0], AppearanceItem::Stroke(_)));
|
||||
}
|
||||
|
||||
/// A blend's record as the editing data writes it after `(Adobe Path Blends) 1 0 n XP`: `DCBA`,
|
||||
/// version 1, then (as far as the reader reads it) the number of keys at word 10 and a record of
|
||||
/// six words per key starting with its id. Hand-written; the other words are zero.
|
||||
fn blend_record(ids: &[char]) -> String {
|
||||
let mut words: Vec<u32> = vec![u32::from_le_bytes(*b"DCBA"), 1, 0, 0, 0, 0, 0, 0, 0, 0, ids.len() as u32];
|
||||
for id in ids {
|
||||
words.extend([*id as u32, 0, 0, 0, 0, 0]);
|
||||
}
|
||||
let hex: String = words.iter().flat_map(|w| w.to_le_bytes()).map(|b| format!("{b:02X}")).collect();
|
||||
let lines: Vec<String> = hex.as_bytes().chunks(60).map(|c| format!("%{}", String::from_utf8_lossy(c))).collect();
|
||||
format!("(Adobe Path Blends) 1 0 {} XP\n{}\n", hex.len() / 2, lines.join("\n"))
|
||||
}
|
||||
|
||||
/// A square `s` wide with its lower left at (x, y), filled with RGB `rgb`, as `%_` lines when
|
||||
/// `hidden`.
|
||||
fn square(x: f64, y: f64, s: f64, rgb: [f64; 3], hidden: bool) -> String {
|
||||
let p = if hidden { "%_" } else { "" };
|
||||
format!("{p}0 0 0 0 {} {} {} Xa\n{p}{x} {y} m\n{p}{x} {} L\n{p}{} {} L\n{p}{} {y} L\n{p}f\n", rgb[0], rgb[1], rgb[2], y + s, x + s, y + s, x + s)
|
||||
}
|
||||
|
||||
/// The dictionary naming a blend part: type `kind` (`K`, `S`) and, for a key, `id`.
|
||||
fn blend_part(kind: &str, id: Option<&str>) -> String {
|
||||
let id = id.map(|i| format!("%_({i}) /String (ShapeBlendPathID) ,\n")).unwrap_or_default();
|
||||
format!("%_/ArtDictionary :\n{id}%_({kind}) /String (ShapeBlendPathType) ,\n%_;\n")
|
||||
}
|
||||
|
||||
/// A blend of two 20 pt squares, red on the left (key `A`) and blue on the right (`B`), along
|
||||
/// `spine` (path operators, `%_` lines), with its drawn steps (three between the keys) and the
|
||||
/// record `record`.
|
||||
fn blend_file(spine: &str, ids: [Option<&str>; 2], record: &str) -> String {
|
||||
let (red, blue) = ([1.0, 0.0, 0.0], [0.0, 0.0, 1.0]);
|
||||
let mut art = String::from("%_0 Ae\n%_u\n");
|
||||
art += &square(0.0, 40.0, 20.0, red, true);
|
||||
art += &blend_part("K", ids[0]);
|
||||
art += &square(100.0, 40.0, 20.0, blue, true);
|
||||
art += &blend_part("K", ids[1]);
|
||||
art += spine;
|
||||
art += "%_N\n";
|
||||
art += &blend_part("S", None);
|
||||
art += "%_U\n%_9 () XW\nu\n";
|
||||
for i in 0..5 {
|
||||
let t = i as f64 / 4.0;
|
||||
art += &square(t * 100.0, 40.0, 20.0, [1.0 - t, 0.0, t], false);
|
||||
}
|
||||
art += "U\n9 () XW\n0 Ae\n";
|
||||
art += record;
|
||||
art
|
||||
}
|
||||
|
||||
/// The blend read from `body`: the first object of the layer.
|
||||
fn read_blend(body: &str) -> (Arc<Node>, Vec<String>) {
|
||||
let s = read_ok(&layer(body));
|
||||
let first = art(&s.doc).into_iter().next().expect("an object");
|
||||
(first, s.warnings)
|
||||
}
|
||||
|
||||
/// Two keys, a straight spine and a record: one live blend of the two keys, three steps between
|
||||
/// them (as drawn), its colours running from red to blue, the drawn steps and the blend's own art
|
||||
/// gone.
|
||||
#[test]
|
||||
fn a_blend_comes_in_as_a_live_blend() {
|
||||
let body = blend_file("%_10 50 m\n%_110 50 L\n", [Some("A"), Some("B")], &blend_record(&['A', 'B']));
|
||||
let s = read_ok(&layer(&body));
|
||||
let objects = art(&s.doc);
|
||||
assert_eq!(objects.len(), 1, "one object: {objects:?}");
|
||||
let NodeKind::Blend { children, spec } = &objects[0].kind else { panic!("not a blend: {:?}", objects[0].kind) };
|
||||
assert_eq!(children.len(), 2);
|
||||
assert_eq!(spec.spacing, vectorcraft_doc::live::BlendSpacing::Steps(3));
|
||||
let laid = vectorcraft_doc::blend::blend_expand(children, spec);
|
||||
assert_eq!(laid.len(), 5);
|
||||
let middle = laid.iter().find(|n| n.geometric_bounds().is_some_and(|b| (b.center().x - 60.0).abs() < 0.5)).expect("the middle step");
|
||||
let Paint::Solid { color, .. } = fill(middle) else { panic!("solid") };
|
||||
let [r, _, b] = color.to_rgb();
|
||||
assert!((r - 0.5).abs() < 0.02 && (b - 0.5).abs() < 0.02, "{r} {b}");
|
||||
assert!(!s.warnings.iter().any(|w| w == super::blend::DRAWN), "{:?}", s.warnings);
|
||||
}
|
||||
|
||||
/// A spine written from the right key to the left one keeps the keys in their order on it (the
|
||||
/// red key first), sitting on its last and first anchors.
|
||||
#[test]
|
||||
fn a_blends_spine_written_backwards_keeps_its_keys_order() {
|
||||
let (blend, warnings) = read_blend(&blend_file("%_110 50 m\n%_10 50 L\n", [Some("A"), Some("B")], &blend_record(&['A', 'B'])));
|
||||
let NodeKind::Blend { children, spec } = &blend.kind else { panic!("a live blend: {:?} {warnings:?}", blend.kind) };
|
||||
assert!(matches!(fill(&children[0]), Paint::Solid { color, .. } if color.to_rgb()[0] > 0.9), "the first key is the red one");
|
||||
assert_eq!(spec.key_anchors, vec![1, 0], "the red key on the spine's end, the blue one on its start");
|
||||
}
|
||||
|
||||
/// A curved spine (a line, a curve and a line) is read with its points exactly; a blend whose drawn
|
||||
/// steps don't follow it (they are drawn on a straight line here) keeps its drawn steps.
|
||||
#[test]
|
||||
fn a_curved_spine_keeps_its_points() {
|
||||
let spine = "%_110 50 m\n%_95 45 l\n%_80 20 40 20 25 45 c\n%_10 50 L\n";
|
||||
let s = read_ok(&layer(&format!("%_u\n{spine}%_N\n%_U\n")));
|
||||
let mut found = None;
|
||||
for n in art(&s.doc) {
|
||||
n.walk(&mut |c| {
|
||||
if let NodeKind::Path { path, .. } = &c.kind {
|
||||
found = Some(path.clone());
|
||||
}
|
||||
});
|
||||
}
|
||||
let path = found.expect("the spine is read");
|
||||
let a = &path.subpaths[0].anchors;
|
||||
assert_eq!(a.len(), 4);
|
||||
assert!((a[1].h_out.x - 80.0).abs() < 1e-9 && (a[2].h_in.x - 40.0).abs() < 1e-9 && (a[2].p.x - 25.0).abs() < 1e-9, "{a:?}");
|
||||
let (blend, warnings) = read_blend(&blend_file(spine, [Some("A"), Some("B")], &blend_record(&['A', 'B'])));
|
||||
assert!(!matches!(blend.kind, NodeKind::Blend { .. }), "steps drawn off the spine aren't made live");
|
||||
assert_eq!(blend.children().map(|c| c.len()), Some(5));
|
||||
assert!(warnings.iter().any(|w| w == super::blend::DRAWN));
|
||||
}
|
||||
|
||||
/// Steps with a gradient fill can't be compared: the blend keeps its drawn steps.
|
||||
#[test]
|
||||
fn a_blend_whose_steps_it_cant_compare_keeps_its_drawn_steps() {
|
||||
let body = blend_file("%_10 50 m\n%_110 50 L\n", [Some("A"), Some("B")], &blend_record(&['A', 'B']));
|
||||
// The drawn squares' fill made a gradient's.
|
||||
let gradient = "%AI5_BeginGradient: (g)\n(g) 0 2 Bd\n[\n1 0 0 0 1 %_Bs\n0 0 0 1 0 %_Bs\nBD\n%AI5_EndGradient\n";
|
||||
let drawn_from = body.find("\nu\n").expect("the drawn group") + 1;
|
||||
let (head, tail) = body.split_at(drawn_from);
|
||||
let tail = tail.replacen("Xa\n", "Xa\n0 1 0 0 1 0 0 1 0 0 Bb\n(g) 0 0 0 1 1 0 0 1 0 0 Bg\n", 5).replace("\nf\n", "\nf\n0 BB\n");
|
||||
let (blend, _) = read_blend(&format!("{gradient}{head}{tail}"));
|
||||
assert!(!matches!(blend.kind, NodeKind::Blend { .. }), "{:?}", blend.kind);
|
||||
}
|
||||
|
||||
/// The blend's own art (its keys and spine) isn't left drawn when what follows it isn't a group of
|
||||
/// drawn steps.
|
||||
#[test]
|
||||
fn a_blends_own_art_goes_when_its_steps_arent_a_group() {
|
||||
let body = blend_file("%_10 50 m\n%_110 50 L\n", [Some("A"), Some("B")], &blend_record(&['A', 'B']));
|
||||
// The drawn steps as one square, not a group.
|
||||
let at = body.find("\nu\n").expect("the drawn group") + 1;
|
||||
let end = body.find("U\n9 () XW\n0 Ae\n").expect("its end");
|
||||
let body = format!("{}{}{}", &body[..at], square(0.0, 40.0, 20.0, [1.0, 0.0, 0.0], false), &body[end + 2..]);
|
||||
let s = read_ok(&layer(&body));
|
||||
let objects = art(&s.doc);
|
||||
assert_eq!(objects.len(), 1, "the drawn square alone: {objects:?}");
|
||||
assert!(matches!(objects[0].kind, NodeKind::Path { .. }));
|
||||
assert!(s.warnings.iter().any(|w| w == super::blend::DRAWN));
|
||||
}
|
||||
|
||||
/// A record that isn't one, a key with no id, or ids the record doesn't list: the drawn steps
|
||||
/// stay (with a note), without the blend's own art drawn over them.
|
||||
#[test]
|
||||
fn a_blend_it_cant_read_keeps_its_drawn_steps() {
|
||||
let straight = "%_10 50 m\n%_110 50 L\n";
|
||||
let garbled = "(Adobe Path Blends) 1 0 16 XP\n%00112233445566778899AABBCCDDEEFF\n";
|
||||
let short = "(Adobe Path Blends) 1 0 92 XP\n%44434241\n";
|
||||
for body in [
|
||||
blend_file(straight, [Some("A"), Some("B")], garbled),
|
||||
blend_file(straight, [Some("A"), Some("B")], short),
|
||||
blend_file(straight, [Some("A"), None], &blend_record(&['A', 'B'])),
|
||||
blend_file(straight, [Some("A"), Some("B")], &blend_record(&['X', 'Y'])),
|
||||
] {
|
||||
let s = read_ok(&layer(&body));
|
||||
let objects = art(&s.doc);
|
||||
assert_eq!(objects.len(), 1, "only the drawn steps: {objects:?}");
|
||||
assert_eq!(objects[0].children().map(|c| c.len()), Some(5), "the five drawn squares");
|
||||
assert!(s.warnings.iter().any(|w| w == super::blend::DRAWN), "{:?}", s.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
/// The blend is live: moving a key moves the steps between it and the other key with it.
|
||||
#[test]
|
||||
fn moving_a_blends_key_moves_its_steps() {
|
||||
let body = blend_file("%_10 50 m\n%_110 50 L\n", [Some("A"), Some("B")], &blend_record(&['A', 'B']));
|
||||
let (blend, _) = read_blend(&body);
|
||||
let NodeKind::Blend { children, spec } = &blend.kind else { panic!("a blend") };
|
||||
let middle = |keys: &[Arc<Node>]| {
|
||||
let laid = vectorcraft_doc::blend::blend_expand(keys, spec);
|
||||
let xs: Vec<f64> = laid.iter().filter_map(|n| n.geometric_bounds()).map(|b| b.center().y).collect();
|
||||
xs.iter().sum::<f64>() / xs.len() as f64
|
||||
};
|
||||
let before = middle(children);
|
||||
let mut keys = children.clone();
|
||||
let mut moved = (*keys[1]).clone();
|
||||
moved.transform(vectorcraft_geom::Affine::translate((0.0, 40.0)), true);
|
||||
keys[1] = Arc::new(moved);
|
||||
let after = middle(&keys);
|
||||
assert!((after - before - 20.0).abs() < 1.0, "the steps follow: {before} -> {after}");
|
||||
}
|
||||
|
||||
/// A record line longer than the record says is read only as far as its length: the digits after
|
||||
/// it don't spoil it.
|
||||
#[test]
|
||||
fn a_blend_record_is_read_to_its_length() {
|
||||
let record = blend_record(&['A', 'B']);
|
||||
let longer = record.trim_end().to_string() + "DEADBEEF\n";
|
||||
let (blend, warnings) = read_blend(&blend_file("%_10 50 m\n%_110 50 L\n", [Some("A"), Some("B")], &longer));
|
||||
assert!(matches!(blend.kind, NodeKind::Blend { .. }), "{warnings:?}");
|
||||
}
|
||||
@@ -19,6 +19,174 @@ pub(super) fn read(body: &str) -> crate::Imported {
|
||||
import(&eps(body)).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_roll_negative_count_is_refused() {
|
||||
let err = import(&eps("-1 1 roll")).unwrap_err();
|
||||
assert!(err.contains("rangecheck") && err.contains("count"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_putinterval_negative_index_is_refused() {
|
||||
let err = import(&eps("(abcd) -1 (x) putinterval pop")).unwrap_err();
|
||||
assert!(err.contains("rangecheck") && err.contains("count"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_negative_string_count_is_refused() {
|
||||
let err = import(&eps("-1 string pop")).unwrap_err();
|
||||
assert!(err.contains("rangecheck") && err.contains("count"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_negative_repeat_count_is_refused() {
|
||||
let err = import(&eps("-1 { } repeat pop")).unwrap_err();
|
||||
assert!(err.contains("rangecheck"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_put_negative_index_is_refused() {
|
||||
let err = import(&eps("/a [0] def a -1 1 put pop")).unwrap_err();
|
||||
assert!(err.contains("rangecheck") && err.contains("index"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_negative_packedarray_count_is_refused() {
|
||||
let err = import(&eps("-1 packedarray pop")).unwrap_err();
|
||||
assert!(err.contains("rangecheck") && err.contains("count"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_get_negative_index_is_refused() {
|
||||
let err = import(&eps("/a [0] def a -1 get pop")).unwrap_err();
|
||||
assert!(err.contains("rangecheck") && err.contains("index"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_negative_dict_count_is_refused() {
|
||||
let err = import(&eps("-1 dict pop")).unwrap_err();
|
||||
assert!(err.contains("rangecheck") && err.contains("count"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_negative_array_count_is_refused() {
|
||||
let err = import(&eps("-1 array pop")).unwrap_err();
|
||||
assert!(err.contains("rangecheck") && err.contains("count"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_index_negative_count_is_refused() {
|
||||
let err = import(&eps("1 -1 index pop")).unwrap_err();
|
||||
assert!(err.contains("rangecheck") && err.contains("count"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_getinterval_negative_count_is_refused() {
|
||||
let err = import(&eps("(a) 1 -1 getinterval pop")).unwrap_err();
|
||||
assert!(err.contains("rangecheck") && err.contains("count"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_getinterval_negative_at_is_refused() {
|
||||
let err = import(&eps("(a) -1 1 getinterval pop")).unwrap_err();
|
||||
assert!(err.contains("rangecheck") && err.contains("count"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_copy_negative_count_is_refused() {
|
||||
let err = import(&eps("1 -1 copy pop")).unwrap_err();
|
||||
assert!(err.contains("rangecheck"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_srand_non_integer_operand_is_refused() {
|
||||
let err = import(&eps("1.5 srand")).unwrap_err();
|
||||
assert!(err.contains("typecheck") && err.contains("srand"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_roll_non_integer_count_is_refused() {
|
||||
let err = import(&eps("1.5 1 roll")).unwrap_err();
|
||||
assert!(err.contains("typecheck"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_roll_non_integer_displacement_is_refused() {
|
||||
let err = import(&eps("1 1.5 roll")).unwrap_err();
|
||||
assert!(err.contains("typecheck"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_repeat_non_procedure_operand_is_refused() {
|
||||
let err = import(&eps("1 1 repeat")).unwrap_err();
|
||||
assert!(err.contains("typecheck") && err.contains("repeat"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_repeat_non_integer_count_is_refused() {
|
||||
let err = import(&eps("1.5 { pop } repeat")).unwrap_err();
|
||||
assert!(err.contains("typecheck"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_mod_non_integer_operand_is_refused() {
|
||||
let err = import(&eps("1.5 2 mod")).unwrap_err();
|
||||
assert!(err.contains("typecheck") && err.contains("mod"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_loop_non_procedure_operand_is_refused() {
|
||||
let err = import(&eps("1 loop")).unwrap_err();
|
||||
assert!(err.contains("typecheck") && err.contains("loop"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_index_non_integer_count_is_refused() {
|
||||
let err = import(&eps("1 1.5 index pop")).unwrap_err();
|
||||
assert!(err.contains("typecheck"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_ifelse_non_procedure_branch_is_refused() {
|
||||
let err = import(&eps("true { pop } 1 ifelse")).unwrap_err();
|
||||
assert!(err.contains("typecheck") && err.contains("ifelse"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_ifelse_non_boolean_condition_is_refused() {
|
||||
let err = import(&eps("1 { pop } { pop } ifelse")).unwrap_err();
|
||||
assert!(err.contains("typecheck") && err.contains("ifelse"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_if_non_procedure_body_is_refused() {
|
||||
let err = import(&eps("true 1 if")).unwrap_err();
|
||||
assert!(err.contains("typecheck") && err.contains("if"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_if_non_boolean_condition_is_refused() {
|
||||
let err = import(&eps("1 { pop } if")).unwrap_err();
|
||||
assert!(err.contains("typecheck") && err.contains("if"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_idiv_non_integer_operand_is_refused() {
|
||||
let err = import(&eps("1.5 2 idiv")).unwrap_err();
|
||||
assert!(err.contains("typecheck") && err.contains("idiv"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_for_non_procedure_operand_is_refused() {
|
||||
let err = import(&eps("1 1 10 1 for")).unwrap_err();
|
||||
assert!(err.contains("typecheck") && err.contains("for"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn postscript_copy_non_integer_operand_count_is_refused() {
|
||||
let err = import(&eps("1 1.5 copy pop")).unwrap_err();
|
||||
assert!(err.contains("typecheck") && err.contains("copy"));
|
||||
}
|
||||
|
||||
/// #1714: arrays and dictionaries a program links into themselves or each other are freed with
|
||||
/// the interpreter, also the ones it no longer reaches and when it stops on an error.
|
||||
#[test]
|
||||
|
||||
@@ -597,6 +597,8 @@ pub fn load_file(bytes: &[u8]) -> Result<NativeFile, FormatError> {
|
||||
doc.setup.keep_in_range();
|
||||
// Untrusted: capped, named and pointing at objects the file has.
|
||||
doc.tidy_saved_selections();
|
||||
// Untrusted: capped, named and with a zoom and centre the canvas can show.
|
||||
doc.tidy_views();
|
||||
doc.tidy_graph_designs();
|
||||
doc.raster_effects.add_around = doc.raster_effects.add_around.clamp(0.0, vectorcraft_doc::rastersettings::MAX_ADD_AROUND);
|
||||
let mut depth_notes = vec![];
|
||||
|
||||
@@ -260,3 +260,43 @@ fn saved_selections_from_a_file_are_tidied() {
|
||||
v["document"]["saved_selections"] = json!([{"name": 5, "objects": "x"}]);
|
||||
assert!(load(&serde_json::to_vec(&v).unwrap()).is_err());
|
||||
}
|
||||
|
||||
/// Saved views (View → New View…) travel with the file, names and viewports intact; older files
|
||||
/// have none, and a hostile one is cut down to what the View menu can list, with names that fit
|
||||
/// and a zoom the canvas can show.
|
||||
#[test]
|
||||
fn saved_views_round_trip_and_from_a_file_are_tidied() {
|
||||
use vectorcraft_doc::SavedView;
|
||||
use vectorcraft_geom::Point;
|
||||
let mut d = rich_doc();
|
||||
let mut v: Value = serde_json::from_slice(&save(&d, false)).unwrap();
|
||||
assert!(v["document"].get("views").is_none(), "nothing written when there are none");
|
||||
assert!(load(&serde_json::to_vec(&v).unwrap()).unwrap().views.is_empty(), "a file from before views opens");
|
||||
d.views = vec![
|
||||
SavedView { name: "Overview".into(), center: Point::new(306.0, 396.0), zoom: 0.5, rotation: 0.0 },
|
||||
SavedView { name: "Logo detail".into(), center: Point::new(40.25, -12.5), zoom: 8.0, rotation: -30.0 },
|
||||
];
|
||||
assert_eq!(load(&save(&d, false)).unwrap().views, d.views);
|
||||
let mut list = vec![
|
||||
json!({"name": format!(" {} ", "x".repeat(1000)), "center": {"x": 1, "y": 2}, "zoom": 2}),
|
||||
json!({"name": " ", "center": {"x": 0, "y": 0}, "zoom": 1}),
|
||||
json!({"name": "Zero", "center": {"x": 0, "y": 0}, "zoom": 0}),
|
||||
json!({"name": "Negative", "center": {"x": 0, "y": 0}, "zoom": -3}),
|
||||
json!({"name": "Dup", "center": {"x": 5, "y": 6}, "zoom": 3, "rotation": 10}),
|
||||
json!({"name": "Dup", "center": {"x": 0, "y": 0}, "zoom": 1}),
|
||||
];
|
||||
list.extend((0..100).map(|i| json!({"name": format!("V{i}"), "center": {"x": i, "y": i}, "zoom": 1})));
|
||||
v["document"]["views"] = json!(list);
|
||||
let back = load(&serde_json::to_vec(&v).unwrap()).unwrap();
|
||||
let views = &back.views;
|
||||
assert_eq!(views.len(), SavedView::MAX);
|
||||
assert_eq!(views[0].name, "x".repeat(SavedView::MAX_NAME));
|
||||
assert_eq!((views[1].name.as_str(), views[1].zoom, views[1].rotation), ("Dup", 3.0, 10.0), "the first of a name stays");
|
||||
assert_eq!(views[2].name, "V0", "blank names, a zero or negative zoom and a repeated name go");
|
||||
assert!(views.iter().all(SavedView::is_usable));
|
||||
// What loads saves and loads again unchanged.
|
||||
assert_eq!(&load(&save(&back, false)).unwrap().views, views);
|
||||
// Junk in the member is a format error, not a crash.
|
||||
v["document"]["views"] = json!([{"name": 5, "center": "x", "zoom": "big"}]);
|
||||
assert!(load(&serde_json::to_vec(&v).unwrap()).is_err());
|
||||
}
|
||||
@@ -687,6 +687,11 @@ pub fn boolean_n(paths: &[(&PathData, FillRule)], pred: impl Fn(&[bool]) -> bool
|
||||
/// [`unite_all`] that reports a refused input instead of leaving it out of the union or returning
|
||||
/// an empty path.
|
||||
pub fn try_unite_all(paths: &[(&PathData, FillRule)]) -> Result<PathData, PathOpsError> {
|
||||
try_unite_all_with(paths, DEFAULT_PRECISION)
|
||||
}
|
||||
|
||||
/// [`try_unite_all`] refit to `precision`, dropping slivers thinner than it.
|
||||
pub fn try_unite_all_with(paths: &[(&PathData, FillRule)], precision: f64) -> Result<PathData, PathOpsError> {
|
||||
let mut all = BezPath::new();
|
||||
for (p, r) in paths {
|
||||
let bp = fill_bezpath(p);
|
||||
@@ -700,13 +705,18 @@ pub fn try_unite_all(paths: &[(&PathData, FillRule)]) -> Result<PathData, PathOp
|
||||
if all.elements().is_empty() {
|
||||
return Ok(PathData::default());
|
||||
}
|
||||
let tidy = Tidy::keeping(DEFAULT_PRECISION, paths.iter().map(|(p, _)| fill_bezpath(p)).collect::<Vec<_>>().iter());
|
||||
let tidy = Tidy::keeping(precision, paths.iter().map(|(p, _)| fill_bezpath(p)).collect::<Vec<_>>().iter());
|
||||
Ok(all_contours_to_path(&normalize_bez(&all, FillRule::NonZero)?, &tidy))
|
||||
}
|
||||
|
||||
/// Union of many filled paths. Each input is first normalised on its own, then all are swept
|
||||
/// together with a single integer winding number, which keeps this fast for thousands of shapes.
|
||||
pub fn unite_all(paths: &[(&PathData, FillRule)]) -> PathData {
|
||||
unite_all_with(paths, DEFAULT_PRECISION)
|
||||
}
|
||||
|
||||
/// [`unite_all`] refit to `precision`, dropping slivers thinner than it.
|
||||
pub fn unite_all_with(paths: &[(&PathData, FillRule)], precision: f64) -> PathData {
|
||||
let mut all = BezPath::new();
|
||||
for (p, r) in paths {
|
||||
let bp = fill_bezpath(p);
|
||||
@@ -721,7 +731,7 @@ pub fn unite_all(paths: &[(&PathData, FillRule)]) -> PathData {
|
||||
if all.elements().is_empty() {
|
||||
return PathData::default();
|
||||
}
|
||||
let tidy = Tidy::keeping(DEFAULT_PRECISION, paths.iter().map(|(p, _)| fill_bezpath(p)).collect::<Vec<_>>().iter());
|
||||
let tidy = Tidy::keeping(precision, paths.iter().map(|(p, _)| fill_bezpath(p)).collect::<Vec<_>>().iter());
|
||||
match normalize_bez(&all, FillRule::NonZero) {
|
||||
Ok(c) => all_contours_to_path(&c, &tidy),
|
||||
Err(_) => PathData::default(),
|
||||
|
||||
@@ -15,14 +15,18 @@ pub const MAX_SEGMENT_PAIRS: usize = 1 << 22;
|
||||
/// Fenwick tree of counts over its slots.
|
||||
struct Counts(Vec<isize>);
|
||||
|
||||
// `isolate_lowest_one` is still unstable in Rust 1.96, and the workspace builds on 1.95 (rust-version).
|
||||
#[allow(clippy::manual_isolate_lowest_one)]
|
||||
#[inline]
|
||||
fn fenwick_step(i: usize) -> usize {
|
||||
// Same as `i.isolate_lowest_one()`; that API is still unstable on the workspace MSRV.
|
||||
1 << i.trailing_zeros()
|
||||
}
|
||||
|
||||
impl Counts {
|
||||
fn add(&mut self, slot: usize, d: isize) {
|
||||
let mut i = slot + 1;
|
||||
while let Some(c) = self.0.get_mut(i) {
|
||||
*c += d;
|
||||
i += i & i.wrapping_neg();
|
||||
i += fenwick_step(i);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +35,7 @@ impl Counts {
|
||||
let (mut i, mut s) = (end.min(self.0.len().saturating_sub(1)), 0);
|
||||
while i > 0 {
|
||||
s += self.0.get(i).copied().unwrap_or(0);
|
||||
i -= i & i.wrapping_neg();
|
||||
i -= fenwick_step(i);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
@@ -16,14 +16,15 @@ mod planar;
|
||||
mod trap;
|
||||
|
||||
pub use boolean::{
|
||||
BoolOp, DEFAULT_PRECISION, area, boolean, boolean_n, normalize, try_area, try_boolean, try_boolean_n, try_normalize, try_unite_all, unite_all,
|
||||
BoolOp, DEFAULT_PRECISION, area, boolean, boolean_n, normalize, try_area, try_boolean, try_boolean_n, try_normalize, try_unite_all,
|
||||
try_unite_all_with, unite_all, unite_all_with,
|
||||
};
|
||||
pub use edit::{
|
||||
AverageAxis, SIMPLIFY_LEVEL, SimplifiedPart, SimplifyOptions, add_anchor_points, auto_simplify_level, average, join, remove_anchor,
|
||||
remove_redundant_points, simplify, simplify_level_tolerance, simplify_part, simplify_with, smooth, split_into_grid,
|
||||
};
|
||||
pub use offset::{Cap, Join, offset_path, outline_stroke, stroke_region};
|
||||
pub use pathfinder::{FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, region_at, regions};
|
||||
pub use pathfinder::{FaceMerger, PathfinderOp, Region, Shape, merge_regions, pathfinder, pathfinder_with, region_at, regions};
|
||||
pub use planar::{
|
||||
BuilderArrangement, SHAPE_BUILDER_MAX_GAP, SHAPE_BUILDER_MAX_SEGMENTS, cut_out, encloses_area, find_gaps, has_open_path, interior_point,
|
||||
live_paint, live_paint_with_gaps, run_around, shape_builder, shape_builder_with_gap,
|
||||
|
||||
@@ -8,7 +8,8 @@ use linesweeper::topology::ContourIdx;
|
||||
use vectorcraft_geom::{FillRule, PathData};
|
||||
|
||||
use crate::boolean::{
|
||||
Arrangement, Multi, Seg, Tidy, all_contours_to_path, contours_to_path, eps_for, fill_bezpath, normalize_bez, segs_to_subpath, to_seg, unite_all,
|
||||
Arrangement, DEFAULT_PRECISION, Multi, Seg, Tidy, all_contours_to_path, contours_to_path, eps_for, fill_bezpath, normalize_bez, segs_to_subpath,
|
||||
to_seg, unite_all, unite_all_with,
|
||||
};
|
||||
|
||||
/// A filled shape in a Pathfinder stack. `key` identifies its paint (e.g. a hashed fill colour);
|
||||
@@ -78,9 +79,12 @@ impl Region {
|
||||
}
|
||||
}
|
||||
|
||||
fn arrangement(shapes: &[Shape]) -> Option<Arrangement> {
|
||||
/// The arrangement of `shapes`, its faces refit to `precision` and its slivers thinner than it dropped.
|
||||
fn arrangement(shapes: &[Shape], precision: f64) -> Option<Arrangement> {
|
||||
let bps: Vec<(BezPath, FillRule)> = shapes.iter().map(|s| (fill_bezpath(&s.path), s.rule)).collect();
|
||||
Arrangement::new(bps).ok()
|
||||
let mut arr = Arrangement::new(bps).ok()?;
|
||||
arr.tidy.precision = precision;
|
||||
Some(arr)
|
||||
}
|
||||
|
||||
/// The one item of `it`, if it has exactly one.
|
||||
@@ -95,6 +99,14 @@ fn one(path: PathData, key: u64) -> Vec<Shape> {
|
||||
|
||||
/// Run a Pathfinder operation over `shapes` (back → front).
|
||||
pub fn pathfinder(op: PathfinderOp, shapes: &[Shape]) -> Vec<Shape> {
|
||||
pathfinder_with(op, shapes, DEFAULT_PRECISION)
|
||||
}
|
||||
|
||||
/// [`pathfinder`] at Pathfinder Options › Precision: results are refit to within `precision`
|
||||
/// (document units) and pieces thinner than it are dropped. A smaller value follows the inputs more
|
||||
/// closely. A value that isn't positive and finite is [`DEFAULT_PRECISION`].
|
||||
pub fn pathfinder_with(op: PathfinderOp, shapes: &[Shape], precision: f64) -> Vec<Shape> {
|
||||
let precision = if precision.is_finite() && precision > 0.0 { precision } else { DEFAULT_PRECISION };
|
||||
let n = shapes.len();
|
||||
if n == 0 {
|
||||
return Vec::new();
|
||||
@@ -102,7 +114,7 @@ pub fn pathfinder(op: PathfinderOp, shapes: &[Shape]) -> Vec<Shape> {
|
||||
let front_key = shapes[n - 1].key;
|
||||
let unite = || {
|
||||
let v: Vec<(&PathData, FillRule)> = shapes.iter().map(|s| (&s.path, s.rule)).collect();
|
||||
one(unite_all(&v), front_key)
|
||||
one(unite_all_with(&v, precision), front_key)
|
||||
};
|
||||
// Unite doesn't need the arrangement.
|
||||
if op == PathfinderOp::Unite {
|
||||
@@ -111,7 +123,7 @@ pub fn pathfinder(op: PathfinderOp, shapes: &[Shape]) -> Vec<Shape> {
|
||||
// Open paths are cutting edges for Divide; the filled-only operations keep their
|
||||
// implicit closure. Reuse Shape Builder's bounded planar map and its fallback.
|
||||
if op == PathfinderOp::Divide && crate::has_open_path(shapes) {
|
||||
return crate::shape_builder(shapes, false)
|
||||
return crate::planar::builder(shapes, false, 0.0, precision)
|
||||
.regions
|
||||
.into_iter()
|
||||
.filter_map(|r| {
|
||||
@@ -120,7 +132,7 @@ pub fn pathfinder(op: PathfinderOp, shapes: &[Shape]) -> Vec<Shape> {
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
let Some(arr) = arrangement(shapes) else { return Vec::new() };
|
||||
let Some(arr) = arrangement(shapes, precision) else { return Vec::new() };
|
||||
let p = &arr.tidy;
|
||||
match op {
|
||||
PathfinderOp::Unite => unite(),
|
||||
@@ -307,7 +319,12 @@ fn vertex_key(p: Point) -> (u64, u64) {
|
||||
/// All faces of the planar arrangement of `shapes` (every area covered by at least one shape,
|
||||
/// split wherever coverage changes).
|
||||
pub fn regions(shapes: &[Shape]) -> Vec<Region> {
|
||||
arrangement(shapes).map(|a| regions_of(&a)).unwrap_or_default()
|
||||
regions_with(shapes, DEFAULT_PRECISION)
|
||||
}
|
||||
|
||||
/// [`regions`] refit to `precision`.
|
||||
pub(crate) fn regions_with(shapes: &[Shape], precision: f64) -> Vec<Region> {
|
||||
arrangement(shapes, precision).map(|a| regions_of(&a)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The face under `point`, if any (Shape Builder hover/click).
|
||||
@@ -348,7 +365,12 @@ impl FaceMerger {
|
||||
// The Shape Builder's faces come from the planar map only up to its cap.
|
||||
let segments: usize = shapes.iter().flat_map(|s| &s.path.subpaths).map(|sp| sp.segment_count()).sum();
|
||||
let lines = (segments <= crate::SHAPE_BUILDER_MAX_SEGMENTS).then(|| (shapes.to_vec(), std::cell::OnceCell::new()));
|
||||
Self { arr: if has_open { None } else { arrangement(shapes) }, shapes: shapes.len(), lines, snap: std::cell::OnceCell::new() }
|
||||
Self {
|
||||
arr: if has_open { None } else { arrangement(shapes, DEFAULT_PRECISION) },
|
||||
shapes: shapes.len(),
|
||||
lines,
|
||||
snap: std::cell::OnceCell::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Merge faces found with Gap Detection using the same temporary bridges as Live Paint.
|
||||
@@ -851,7 +873,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn same_as_one_mask_at_a_time(shapes: &[Shape]) {
|
||||
let arr = arrangement(shapes).expect("arrangement");
|
||||
let arr = arrangement(shapes, DEFAULT_PRECISION).expect("arrangement");
|
||||
assert_eq!(regions_of(&arr), regions_one_mask_at_a_time(&arr));
|
||||
}
|
||||
|
||||
@@ -859,6 +881,54 @@ mod tests {
|
||||
shapes::rectangle(Rect::new(x0, y0, x1, y1))
|
||||
}
|
||||
|
||||
/// Pathfinder Options › Precision: pieces thinner than the precision are dropped, so a 0.5 pt
|
||||
/// strip that the default keeps goes at a precision of 1 pt, whether the Pathfinder works on
|
||||
/// the arrangement (Divide), the planar map (Divide with an open path) or the union (Unite).
|
||||
#[test]
|
||||
fn precision_drops_pieces_thinner_than_it() {
|
||||
let overlapping =
|
||||
[Shape::new(rect(0.0, 0.0, 100.0, 100.0), FillRule::NonZero, 1), Shape::new(rect(0.0, 99.5, 100.0, 200.0), FillRule::NonZero, 2)];
|
||||
let line = PathData::single(SubPath::polyline(&[Point::new(-10.0, 99.5), Point::new(110.0, 99.5)], false));
|
||||
let cut = [Shape::new(rect(0.0, 0.0, 100.0, 100.0), FillRule::NonZero, 1), Shape::new(line, FillRule::NonZero, 2)];
|
||||
let apart =
|
||||
[Shape::new(rect(0.0, 0.0, 100.0, 100.0), FillRule::NonZero, 1), Shape::new(rect(0.0, 150.0, 100.0, 150.5), FillRule::NonZero, 2)];
|
||||
for (what, op, shapes, kept) in [
|
||||
("Divide", PathfinderOp::Divide, &overlapping, 3),
|
||||
("Divide with an open path", PathfinderOp::Divide, &cut, 2),
|
||||
("Unite", PathfinderOp::Unite, &apart, 2),
|
||||
] {
|
||||
let count = |r: Vec<Shape>| r.iter().map(|s| s.path.subpaths.len()).sum::<usize>();
|
||||
assert_eq!(pathfinder_with(op, shapes, DEFAULT_PRECISION), pathfinder(op, shapes), "{what}: the default is the plain Pathfinder");
|
||||
assert_eq!(count(pathfinder(op, shapes)), kept, "{what}: the default keeps the strip");
|
||||
assert_eq!(count(pathfinder_with(op, shapes, 1.0)), kept - 1, "{what}: 1 pt drops it");
|
||||
assert_eq!(pathfinder_with(op, shapes, f64::NAN), pathfinder(op, shapes), "{what}: an invalid precision is the default");
|
||||
}
|
||||
}
|
||||
|
||||
/// The planar map that Divide with an open path uses merges two edges between the same points
|
||||
/// only when they are closer than the precision: a lens 0.005 pt thick between two curves is a
|
||||
/// piece at a precision of 0.001 pt, and not at the default.
|
||||
#[test]
|
||||
fn open_path_divide_keeps_a_lens_thicker_than_the_precision() {
|
||||
// Curves monotonic in x and y, so the sweep keeps each one whole between the shared ends;
|
||||
// their middles are 0.005 pt apart.
|
||||
let shift = 0.005 / 0.75 / std::f64::consts::SQRT_2;
|
||||
let curve = |d: f64| [Point::new(0.0, 0.0), Point::new(d, 50.0 - d), Point::new(50.0 + d, 100.0 - d), Point::new(100.0, 100.0)];
|
||||
let (top, bottom) = (curve(0.0), curve(shift));
|
||||
let mut bp = kurbo::BezPath::new();
|
||||
bp.move_to(top[0]);
|
||||
bp.curve_to(top[1], top[2], top[3]);
|
||||
bp.curve_to(bottom[2], bottom[1], bottom[0]);
|
||||
bp.close_path();
|
||||
let lens = Shape::new(PathData::from_bezpath(&bp), FillRule::NonZero, 1);
|
||||
let line = PathData::single(SubPath::polyline(&[Point::new(200.0, 0.0), Point::new(300.0, 0.0)], false));
|
||||
let shapes = [lens, Shape::new(line, FillRule::NonZero, 2)];
|
||||
let area = |r: &[Shape]| r.iter().map(|s| crate::area(&s.path, FillRule::NonZero)).sum::<f64>();
|
||||
let fine = pathfinder_with(PathfinderOp::Divide, &shapes, 0.001);
|
||||
assert!(area(&fine) > 0.1, "the lens is a piece: {} pt²", area(&fine));
|
||||
assert_eq!(area(&pathfinder(PathfinderOp::Divide, &shapes)), 0.0, "thinner than the default precision");
|
||||
}
|
||||
|
||||
/// Shapes on a coarse grid, so that edges and corners coincide: rectangles, rectangles with
|
||||
/// a hole, ellipses and polygons that may cross themselves, under either fill rule.
|
||||
fn arb_shape() -> impl Strategy<Value = Shape> {
|
||||
|
||||
@@ -465,7 +465,7 @@ fn find(parent: &mut [usize], mut v: usize) -> usize {
|
||||
/// wherever they meet another path, keyed by the input they came from (the front-most where
|
||||
/// inputs share one). Empty when the paths can't be swept (non-finite or too degenerate).
|
||||
pub fn live_paint(shapes: &[Shape]) -> (Vec<Region>, Vec<Shape>) {
|
||||
build(shapes).unwrap_or_default()
|
||||
build(shapes, DEFAULT_PRECISION).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// [`live_paint`] with Gap Detection: the faces are those of `shapes` with a line across each gap
|
||||
@@ -809,22 +809,27 @@ pub(crate) fn gap_inputs(shapes: &[Shape], gap: f64) -> Vec<Shape> {
|
||||
/// found. A `gap` of 0 is [`shape_builder`]. The bridges are in no region's sources and in no piece
|
||||
/// of `lines` or `edges`.
|
||||
pub fn shape_builder_with_gap(shapes: &[Shape], edges: bool, gap: f64) -> BuilderArrangement {
|
||||
builder(shapes, edges, gap, DEFAULT_PRECISION)
|
||||
}
|
||||
|
||||
/// [`shape_builder_with_gap`] refitting its results to `precision` (Pathfinder Options › Precision).
|
||||
pub(crate) fn builder(shapes: &[Shape], edges: bool, gap: f64, precision: f64) -> BuilderArrangement {
|
||||
let has_open = has_open_path(shapes);
|
||||
let segments: usize = shapes.iter().flat_map(|s| &s.path.subpaths).map(|sp| sp.segment_count()).sum();
|
||||
let planar = (segments <= SHAPE_BUILDER_MAX_SEGMENTS)
|
||||
.then(|| {
|
||||
let keyed: Vec<Shape> = shapes.iter().enumerate().map(|(i, s)| Shape::new(s.path.clone(), s.rule, i as u64)).collect();
|
||||
if has_open && gap.is_finite() && gap > 0.0 {
|
||||
let (faces, pieces) = live_paint(&gap_inputs(&keyed, gap));
|
||||
let (faces, pieces) = build(&gap_inputs(&keyed, gap), precision).unwrap_or_default();
|
||||
// Gap targets split original outlines too, but the bridges themselves aren't art.
|
||||
(faces, pieces.into_iter().filter(|p| p.key < shapes.len() as u64).collect())
|
||||
} else {
|
||||
live_paint(&keyed)
|
||||
build(&keyed, precision).unwrap_or_default()
|
||||
}
|
||||
})
|
||||
.filter(|(faces, pieces)| !faces.is_empty() || !pieces.is_empty());
|
||||
let Some((faces, pieces)) = planar else {
|
||||
return BuilderArrangement { regions: filled_regions(shapes), ..Default::default() };
|
||||
return BuilderArrangement { regions: filled_regions(shapes, precision), ..Default::default() };
|
||||
};
|
||||
let is_line = |i: u64| shapes.get(i as usize).is_some_and(|s| !s.path.subpaths.iter().any(|sp| sp.closed));
|
||||
let (lines, outline): (Vec<Shape>, Vec<Shape>) = pieces.into_iter().partition(|e| is_line(e.key));
|
||||
@@ -832,7 +837,7 @@ pub fn shape_builder_with_gap(shapes: &[Shape], edges: bool, gap: f64) -> Builde
|
||||
faces
|
||||
} else {
|
||||
// The filled areas from their arrangement, whose faces merge exactly, then the gaps.
|
||||
let mut regions = crate::regions(shapes);
|
||||
let mut regions = crate::pathfinder::regions_with(shapes, precision);
|
||||
regions.extend(faces.into_iter().filter(|f| f.sources.is_empty()));
|
||||
regions
|
||||
};
|
||||
@@ -842,14 +847,14 @@ pub fn shape_builder_with_gap(shapes: &[Shape], edges: bool, gap: f64) -> Builde
|
||||
/// The regions of the shapes' filled areas. A shape that fills nothing (open paths that enclose no
|
||||
/// area, such as cutting lines) is left out, so a flood of them cannot push the arrangement past its
|
||||
/// size budget and take the filled shapes down with it; the regions keep the original indices.
|
||||
fn filled_regions(shapes: &[Shape]) -> Vec<crate::Region> {
|
||||
fn filled_regions(shapes: &[Shape], precision: f64) -> Vec<crate::Region> {
|
||||
let fills = |s: &Shape| s.path.subpaths.iter().any(|sp| sp.closed || encloses_area(sp));
|
||||
let keep: Vec<usize> = (0..shapes.len()).filter(|&i| shapes.get(i).is_some_and(fills)).collect();
|
||||
if keep.len() == shapes.len() {
|
||||
return crate::regions(shapes);
|
||||
return crate::pathfinder::regions_with(shapes, precision);
|
||||
}
|
||||
let kept: Vec<Shape> = keep.iter().filter_map(|&i| shapes.get(i).cloned()).collect();
|
||||
crate::regions(&kept)
|
||||
crate::pathfinder::regions_with(&kept, precision)
|
||||
.into_iter()
|
||||
.map(|mut r| {
|
||||
r.sources = r.sources.iter().filter_map(|&s| keep.get(s).copied()).collect();
|
||||
@@ -1080,6 +1085,11 @@ pub(crate) struct Map {
|
||||
/// With `cover`, also finds which inputs cover each sliver, which only [`Map::merge`] reads;
|
||||
/// without it the slivers' lists of inputs stay empty.
|
||||
pub(crate) fn map(shapes: &[Shape], cover: bool) -> Option<Map> {
|
||||
map_with(shapes, cover, DEFAULT_PRECISION)
|
||||
}
|
||||
|
||||
/// [`map`] whose faces and pieces are refit to `precision`, and whose slivers thinner than it are dropped.
|
||||
fn map_with(shapes: &[Shape], cover: bool, precision: f64) -> Option<Map> {
|
||||
let mut inputs: Vec<(BezPath, usize)> = Vec::new();
|
||||
for (i, s) in shapes.iter().enumerate() {
|
||||
let mut bp = BezPath::new();
|
||||
@@ -1110,7 +1120,7 @@ pub(crate) fn map(shapes: &[Shape], cover: bool) -> Option<Map> {
|
||||
let sweep =
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Topology::<Crossings>::from_paths(inputs.iter().map(|(p, i)| (p, *i)), eps)));
|
||||
let top = sweep.ok()?.ok()?;
|
||||
let tidy = Tidy::keeping(DEFAULT_PRECISION, inputs.iter().map(|p| &p.0));
|
||||
let tidy = Tidy::keeping(precision, inputs.iter().map(|p| &p.0));
|
||||
|
||||
// The planar graph: vertices are the sweep's points, edges its segments. Points closer than
|
||||
// the sweep's tolerance are one vertex (it can put a corner that lies on another path's edge
|
||||
@@ -1229,7 +1239,7 @@ pub(crate) fn map(shapes: &[Shape], cover: bool) -> Option<Map> {
|
||||
let twin_of = between.get(&key).and_then(|v| {
|
||||
v.iter().copied().find(|&e| {
|
||||
let other = edges.get(e).and_then(|e| mid(&e.segs));
|
||||
matches!((here, other), (Some(a), Some(b)) if a.distance(b) < DEFAULT_PRECISION)
|
||||
matches!((here, other), (Some(a), Some(b)) if a.distance(b) < precision)
|
||||
})
|
||||
});
|
||||
if let Some(e) = twin_of {
|
||||
@@ -1448,8 +1458,8 @@ impl Map {
|
||||
}
|
||||
}
|
||||
|
||||
fn build(shapes: &[Shape]) -> Option<(Vec<Region>, Vec<Shape>)> {
|
||||
let m = map(shapes, false)?;
|
||||
fn build(shapes: &[Shape], precision: f64) -> Option<(Vec<Region>, Vec<Shape>)> {
|
||||
let m = map_with(shapes, false, precision)?;
|
||||
let Map { edges, around, faces, holes, face_holes, tidy, anchors, snap, .. } = &m;
|
||||
let snap = *snap;
|
||||
let fills: Vec<Fill> = shapes.iter().map(Fill::new).collect();
|
||||
@@ -1465,7 +1475,11 @@ fn build(shapes: &[Shape]) -> Option<(Vec<Region>, Vec<Shape>)> {
|
||||
subpaths.extend(hs.iter().filter_map(|&k| holes.get(k)).filter_map(|(c, _)| subpath(c)));
|
||||
let path = unshear(PathData::new(subpaths), anchors, snap);
|
||||
let sources =
|
||||
interior_point(&path).map(|p| fills.iter().enumerate().filter(|(_, f)| f.contains(p)).map(|(i, _)| i).collect()).unwrap_or_default();
|
||||
// A face finer than the default precision can need a finer outline to find a point in.
|
||||
interior_point(&path)
|
||||
.or_else(|| (precision < DEFAULT_PRECISION).then(|| interior_point_within(&path, precision / 4.0)).flatten())
|
||||
.map(|p| fills.iter().enumerate().filter(|(_, f)| f.contains(p)).map(|(i, _)| i).collect())
|
||||
.unwrap_or_default();
|
||||
Some(Region { path, sources })
|
||||
})
|
||||
.collect();
|
||||
@@ -1530,11 +1544,17 @@ fn build(shapes: &[Shape]) -> Option<(Vec<Region>, Vec<Shape>)> {
|
||||
/// A point strictly inside a filled path, well away from its edges where it can be (for re-finding
|
||||
/// a Live Paint face after a rebuild).
|
||||
pub fn interior_point(path: &PathData) -> Option<Point> {
|
||||
let bb = path.bounds()?;
|
||||
interior_point_within(path, (bb.width().max(bb.height()) * 1e-3).max(1e-4))
|
||||
}
|
||||
|
||||
/// [`interior_point`] with the path's curves flattened to within `tolerance`.
|
||||
fn interior_point_within(path: &PathData, tolerance: f64) -> Option<Point> {
|
||||
let bb = path.bounds()?;
|
||||
let bp = path.to_bezpath();
|
||||
let mut edges: Vec<(Point, Point)> = vec![];
|
||||
let (mut first, mut last) = (Point::ZERO, Point::ZERO);
|
||||
kurbo::flatten(bp.iter(), (bb.width().max(bb.height()) * 1e-3).max(1e-4), |el| match el {
|
||||
kurbo::flatten(bp.iter(), tolerance, |el| match el {
|
||||
kurbo::PathEl::MoveTo(p) => {
|
||||
if last != first {
|
||||
edges.push((last, first));
|
||||
|
||||
+76
-16
@@ -21,8 +21,8 @@ use vectorcraft_color::{BlendMode, Color, GradientKind, Paint};
|
||||
use vectorcraft_doc::{AppearanceItem, Document, LineCap, LineJoin, Node, NodeKind, StrokeAlign, StrokeLayer, SymbolBoxes, TextObject};
|
||||
use vectorcraft_effects::stroke::{self, WrittenShape};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, Rect};
|
||||
use vectorcraft_text::TextLayout;
|
||||
use vectorcraft_text::embed::Embedding;
|
||||
use vectorcraft_text::{ListMarker, TextLayout};
|
||||
|
||||
use crate::forms::Mark;
|
||||
use crate::lab_spot::{find, rfind};
|
||||
@@ -694,8 +694,11 @@ struct GlyphLine {
|
||||
/// The glyph space (krilla's, y down, at `size`) → text space, at the line's start.
|
||||
frame: Affine,
|
||||
/// Glyph id, pen position and advance along the line (in glyph space), and the characters it
|
||||
/// stands for (bytes of the plain text).
|
||||
/// stands for (bytes of the plain text, or of the list marker's text).
|
||||
glyphs: Vec<(u32, f64, f64, std::ops::Range<usize>)>,
|
||||
/// The list marker the glyphs belong to, by its first glyph's index in the layout
|
||||
/// ([`TextLayout::marker_of`]); `None` for glyphs of the plain text.
|
||||
marker: Option<usize>,
|
||||
}
|
||||
|
||||
/// Most pixels along a side of a freeform gradient's image (its colour field is smooth).
|
||||
@@ -1780,7 +1783,9 @@ impl Exporter<'_> {
|
||||
/// COLR, SVG), with `images`, are written as text too, which draws their images or layers; the
|
||||
/// indices of those it can't write or draw (SVG glyphs) are returned with the outlines. The
|
||||
/// hyphen the layout adds where it breaks a line inside a word ([`break_hyphen`]) is written
|
||||
/// as the character its glyph stands for, on its own after the glyphs before it.
|
||||
/// as the character its glyph stands for, on its own after the glyphs before it. The glyphs of
|
||||
/// a list marker are written as the marker's characters ([`marker_chars`]), apart from the
|
||||
/// plain text's glyphs; a marker glyph that stands for none of them is drawn as a path.
|
||||
///
|
||||
/// `bent`: `Some(false)` writes the glyphs bent along a path ([`vectorcraft_text::GlyphBend`])
|
||||
/// as outlines, not text (text is set straight); `Some(true)` writes only those, as text where
|
||||
@@ -1802,6 +1807,11 @@ impl Exporter<'_> {
|
||||
// stand for no character of it, the characters a line-break hyphen can stand for.
|
||||
let written: Cow<str> =
|
||||
if layout.glyphs.iter().any(|g| g.run == run && g.len == 0) { Cow::Owned(format!("{text}{BREAK_HYPHENS}")) } else { Cow::Borrowed(text) };
|
||||
let written_text: &str = &written;
|
||||
// The text a line's glyphs stand for: `written`, or its list marker's characters.
|
||||
let text_of = |l: &GlyphLine| l.marker.and_then(|m| layout.marker_of(m)).map_or(written_text, |m| m.text.as_str());
|
||||
// The characters of the list marker being written that each of its glyphs stands for.
|
||||
let mut marker: Option<(usize, Vec<Option<std::ops::Range<usize>>>)> = None;
|
||||
for (gi, g) in layout.glyphs.iter().enumerate().filter(|(_, g)| g.run == run) {
|
||||
let coloured = g.image.is_some() || g.colour.is_some();
|
||||
if coloured && !images {
|
||||
@@ -1815,11 +1825,27 @@ impl Exporter<'_> {
|
||||
(Some(true), false) => continue,
|
||||
_ => {}
|
||||
}
|
||||
// A list marker's glyphs stand for no character of the text either; they are not
|
||||
// line-break hyphens, whatever the marker.
|
||||
let hyphen = if layout.marker_of(gi).is_some() { None } else { break_hyphen(g) };
|
||||
let range = hyphen.clone().map_or(g.byte..g.byte + g.len, |h| text.len() + h.start..text.len() + h.end);
|
||||
let ch = written.get(range.clone()).and_then(|t| t.chars().next());
|
||||
// Of the glyphs with no length, only a list marker's and line-break hyphens are written
|
||||
// as text; the others, such as kashidas, are drawn as paths. A list marker's glyphs are
|
||||
// not line-break hyphens, whatever the marker.
|
||||
let in_marker = (g.len == 0).then(|| layout.marker_of(gi)).flatten();
|
||||
let hyphen = if in_marker.is_some() { None } else { break_hyphen(g) };
|
||||
let (range, ch) = match in_marker {
|
||||
Some(m) => {
|
||||
if marker.as_ref().is_none_or(|(start, _)| *start != m.glyphs.start) {
|
||||
marker = Some((m.glyphs.start, marker_chars(layout, m)));
|
||||
}
|
||||
let range = marker.as_ref().and_then(|(start, chars)| chars.get(gi.checked_sub(*start)?).cloned().flatten());
|
||||
let ch = range.clone().and_then(|r| m.text.get(r)).and_then(|t| t.chars().next());
|
||||
(range.unwrap_or(0..0), ch)
|
||||
}
|
||||
None => {
|
||||
let range = hyphen.clone().map_or(g.byte..g.byte + g.len, |h| text.len() + h.start..text.len() + h.end);
|
||||
let ch = written.get(range.clone()).and_then(|t| t.chars().next());
|
||||
(range, ch)
|
||||
}
|
||||
};
|
||||
let marker_at = in_marker.map(|m| m.glyphs.start);
|
||||
// Spaces are written too (text extraction needs them); control characters and soft
|
||||
// hyphens draw nothing.
|
||||
let blank = g.outline.elements().is_empty() && !coloured;
|
||||
@@ -1852,18 +1878,22 @@ impl Exporter<'_> {
|
||||
let frame = g.xf * Affine::scale(1.0 / sy);
|
||||
// Its pen position along the frame's baseline, when it continues the line (a
|
||||
// line-break hyphen never does).
|
||||
let x = line.as_ref().filter(|l| hyphen.is_none() && l.face == g.font_id && (l.size - size).abs() < 1e-6).and_then(|l| {
|
||||
let [a, b, c, d, e, f] = (l.frame.inverse() * frame).as_coeffs();
|
||||
let same = (a - 1.0).abs() < 1e-6 && b.abs() < 1e-6 && c.abs() < 1e-6 && (d - 1.0).abs() < 1e-6 && f.abs() < 1e-4;
|
||||
same.then_some(e)
|
||||
});
|
||||
let x = line
|
||||
.as_ref()
|
||||
.filter(|l| hyphen.is_none() && l.face == g.font_id && (l.size - size).abs() < 1e-6 && l.marker == marker_at)
|
||||
.and_then(|l| {
|
||||
let [a, b, c, d, e, f] = (l.frame.inverse() * frame).as_coeffs();
|
||||
let same = (a - 1.0).abs() < 1e-6 && b.abs() < 1e-6 && c.abs() < 1e-6 && (d - 1.0).abs() < 1e-6 && f.abs() < 1e-4;
|
||||
same.then_some(e)
|
||||
});
|
||||
let x = match x {
|
||||
Some(x) => x,
|
||||
None => {
|
||||
if let Some(l) = line.take() {
|
||||
self.draw_glyph_line(s, l, &written, fill, layout.bounds);
|
||||
let text = text_of(&l);
|
||||
self.draw_glyph_line(s, l, text, fill, layout.bounds);
|
||||
}
|
||||
line = Some(GlyphLine { face: g.font_id, font, size, frame, glyphs: vec![] });
|
||||
line = Some(GlyphLine { face: g.font_id, font, size, frame, glyphs: vec![], marker: marker_at });
|
||||
0.0
|
||||
}
|
||||
};
|
||||
@@ -1880,7 +1910,8 @@ impl Exporter<'_> {
|
||||
}
|
||||
}
|
||||
if let Some(l) = line {
|
||||
self.draw_glyph_line(s, l, &written, fill, layout.bounds);
|
||||
let text = text_of(&l);
|
||||
self.draw_glyph_line(s, l, text, fill, layout.bounds);
|
||||
}
|
||||
(rest, unwritten)
|
||||
}
|
||||
@@ -2129,6 +2160,35 @@ fn break_hyphen(g: &vectorcraft_text::PositionedGlyph) -> Option<std::ops::Range
|
||||
BREAK_HYPHENS.char_indices().find(|&(_, c)| face.glyph_for(c) == g.gid).map(|(i, c)| i..i + c.len_utf8())
|
||||
}
|
||||
|
||||
/// The characters of list marker `m` of `layout` that each of its glyphs stands for, as bytes of
|
||||
/// the marker's text, in the order of [`ListMarker::glyphs`]: `None` for its tab and for a glyph
|
||||
/// that stands for none of them. A glyph stands for the first character left that the glyph's
|
||||
/// font maps to that glyph in its character map. When the glyphs that no character maps to (an
|
||||
/// OpenType feature such as oldstyle figures replaced them) are as many as the characters left,
|
||||
/// they stand for those characters, in order.
|
||||
fn marker_chars(layout: &TextLayout, m: &ListMarker) -> Vec<Option<std::ops::Range<usize>>> {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let mut left: Vec<(std::ops::Range<usize>, char)> = m.text.char_indices().map(|(i, c)| (i..i + c.len_utf8(), c)).collect();
|
||||
let mut chars = vec![None; m.glyphs.len()];
|
||||
let mut unmapped = vec![];
|
||||
for (k, gi) in m.glyphs.clone().enumerate() {
|
||||
let Some(g) = layout.glyphs.get(gi).filter(|g| gi != m.tab && g.gid != 0) else { continue };
|
||||
let face = db.face_by_id(g.font_id);
|
||||
match (left.iter().position(|(_, c)| face.as_ref().is_some_and(|f| f.glyph_for(*c) == g.gid)), chars.get_mut(k)) {
|
||||
(Some(at), Some(slot)) => *slot = Some(left.remove(at).0),
|
||||
_ => unmapped.push(k),
|
||||
}
|
||||
}
|
||||
if unmapped.len() == left.len() {
|
||||
for (k, (range, _)) in unmapped.into_iter().zip(left) {
|
||||
if let Some(slot) = chars.get_mut(k) {
|
||||
*slot = Some(range);
|
||||
}
|
||||
}
|
||||
}
|
||||
chars
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -153,6 +153,10 @@ fn block(nodes: &[Arc<Node>], lines: &HashMap<NodeId, LineFacts>) -> (usize, Opt
|
||||
/// the file's widths are rounded, or it moved a glyph a hair (`TJ`).
|
||||
const EVEN_TRACKING: f64 = 10.0;
|
||||
|
||||
/// How far the tracking of a wrapped line's spaces may stray (thousandths of an em, a fiftieth of
|
||||
/// an em) and still be one value: each space the file draws beside a wider gap is tracked apart.
|
||||
const SPACE_TRACKING_TOLERANCE: f64 = 20.0;
|
||||
|
||||
/// A line's spacing: the tracking after its letters, and how much more its spaces take (word
|
||||
/// spacing, `Tw`; `None` when it has none). `None` when its letters are tracked apart (set by
|
||||
/// hand), or its spaces more than `slack` apart.
|
||||
@@ -194,7 +198,7 @@ fn area_type(nodes: &[Arc<Node>], lines: &HashMap<NodeId, LineFacts>, b: &Block)
|
||||
// type's own.
|
||||
// A wrapped line's spaces may each be tracked apart, within a fiftieth of an em of each other.
|
||||
let spacings: Vec<(f64, Option<f64>)> =
|
||||
texts.iter().map(|(t, f)| line_spacing(t, if f.wraps { 20.0 } else { EVEN_TRACKING })).collect::<Option<_>>()?;
|
||||
texts.iter().map(|(t, f)| line_spacing(t, if f.wraps { SPACE_TRACKING_TOLERANCE } else { EVEN_TRACKING })).collect::<Option<_>>()?;
|
||||
let trackings: Vec<f64> = spacings.iter().map(|(t, _)| *t).collect();
|
||||
let words: Vec<Option<f64>> = spacings.iter().map(|(_, w)| *w).collect();
|
||||
let wrapped: Vec<f64> = texts.iter().filter(|(_, f)| f.wraps).map(|(_, f)| f.length).collect();
|
||||
|
||||
@@ -276,7 +276,7 @@ impl TextLine {
|
||||
self.column = true;
|
||||
// Letter-spaced Japanese is common: a gap reads as a space only when a whole em is left
|
||||
// out (the tracking set in `finish` keeps narrower gaps).
|
||||
if step > size * 0.9 && !run.ends_with(' ') && !text.starts_with(' ') {
|
||||
if step > size * 0.9 && !run.ends_with(is_space) && !text.starts_with(is_space) {
|
||||
run.push(' ');
|
||||
}
|
||||
if last.takes(look) {
|
||||
@@ -334,15 +334,16 @@ impl TextLine {
|
||||
if !on_line && !on_curve {
|
||||
return false;
|
||||
}
|
||||
if !run.ends_with(' ') && !text.starts_with(' ') {
|
||||
if !run.ends_with(is_space) && !text.starts_with(is_space) {
|
||||
self.gaps.push(Gap { at: bytes, width: gap, em: self.last_size.min(at.size), on_line });
|
||||
}
|
||||
// A space the file draws between two glyphs spans the gaps on both sides of it.
|
||||
let drawn = self.drawn_space.take();
|
||||
if on_line {
|
||||
if text == " " && !run.ends_with(' ') {
|
||||
let mut chars = text.chars();
|
||||
if chars.next().is_some_and(is_space) && chars.next().is_none() && !run.ends_with(is_space) {
|
||||
self.drawn_space = Some((bytes, gap + advance));
|
||||
} else if let Some((b, before)) = drawn.filter(|_| !text.starts_with(' ')) {
|
||||
} else if let Some((b, before)) = drawn.filter(|_| !text.starts_with(is_space)) {
|
||||
self.drawn_spaces.push((b, before + gap));
|
||||
}
|
||||
}
|
||||
@@ -904,12 +905,13 @@ fn tracked(runs: Vec<TextRun>, tracking: f64, spaces: &[(usize, f64)]) -> Vec<Te
|
||||
let mut from = 0;
|
||||
for &(b, own) in spaces.iter().filter(|(b, _)| (off..end).contains(b)) {
|
||||
let at = b - off;
|
||||
let (Some(before), Some(space)) = (r.text.get(from..at), r.text.get(at..at + 1)) else { continue };
|
||||
let len = r.text.get(at..).and_then(|t| t.chars().next()).map_or(1, char::len_utf8);
|
||||
let (Some(before), Some(space)) = (r.text.get(from..at), r.text.get(at..at + len)) else { continue };
|
||||
if !before.is_empty() {
|
||||
out.push(TextRun { text: before.to_string(), style: style.clone(), inline: None });
|
||||
}
|
||||
out.push(TextRun { text: space.to_string(), style: CharStyle { tracking: own, ..style.clone() }, inline: None });
|
||||
from = at + 1;
|
||||
from = at + len;
|
||||
}
|
||||
if let Some(rest) = r.text.get(from..).filter(|t| !t.is_empty()) {
|
||||
out.push(TextRun { text: rest.to_string(), style, inline: None });
|
||||
@@ -919,6 +921,12 @@ fn tracked(runs: Vec<TextRun>, tracking: f64, spaces: &[(usize, f64)]) -> Vec<Te
|
||||
out
|
||||
}
|
||||
|
||||
/// A space a file draws as a glyph: U+0020, the no-break spaces (U+00A0, U+202F) or one of the
|
||||
/// fixed-width spaces U+2000 to U+200A (en, em, thin, hair and the others).
|
||||
fn is_space(c: char) -> bool {
|
||||
matches!(c, ' ' | '\u{a0}' | '\u{2000}'..='\u{200a}' | '\u{202f}')
|
||||
}
|
||||
|
||||
fn round(v: f64) -> f64 {
|
||||
(v * 1000.0).round() / 1000.0
|
||||
}
|
||||
|
||||
@@ -37,13 +37,18 @@ fn close(a: Rect, b: Rect, tol: f64) -> bool {
|
||||
(a.x0 - b.x0).abs() < tol && (a.y0 - b.y0).abs() < tol && (a.x1 - b.x1).abs() < tol && (a.y1 - b.y1).abs() < tol
|
||||
}
|
||||
|
||||
/// `d` exported with the default options and imported back: the document a round trip through a PDF
|
||||
/// gives.
|
||||
fn roundtrip(d: &Document) -> Document {
|
||||
let bytes = export(d, &PdfOptions::default()).expect("export");
|
||||
import(&bytes).expect("import")
|
||||
}
|
||||
|
||||
/// `d` exported uncompressed, dated `created: Some(0)` rather than by the clock: two exports of one
|
||||
/// document are then the same bytes, where the clock's dates, in whole seconds, differ whenever a
|
||||
/// second ticks between them.
|
||||
fn uncompressed(d: &Document) -> String {
|
||||
let bytes = export(d, &PdfOptions::uncompressed()).expect("export");
|
||||
let bytes = export(d, &PdfOptions { created: Some(0), ..PdfOptions::uncompressed() }).expect("export");
|
||||
String::from_utf8_lossy(&bytes).into_owned()
|
||||
}
|
||||
|
||||
|
||||
@@ -226,6 +226,21 @@ fn words_set_ems_apart_beside_the_spaces_the_file_draws_keep_their_place() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn words_set_ems_apart_beside_a_drawn_no_break_or_thin_space_keep_their_place() {
|
||||
// As above, the file drawing a no-break space and a thin space alone, with a gap on each side.
|
||||
let (x1, x2) = (48.0, 84.0);
|
||||
let lines: &[(f32, f32, f32, &str)] =
|
||||
&[(20.0, 50.0, 10.0, "ab"), (36.0, 50.0, 10.0, "\u{a0}"), (x1, 50.0, 10.0, "cd"), (70.0, 50.0, 10.0, "\u{2009}"), (x2, 50.0, 10.0, "ef")];
|
||||
let t = texts(&import(&source_sans(lines)).unwrap());
|
||||
assert_eq!(t.len(), 1);
|
||||
assert_eq!(t[0].plain_text(), "ab\u{a0}cd\u{2009}ef");
|
||||
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t[0]);
|
||||
let at = |byte: usize| (t[0].xf * laid.glyphs.iter().find(|g| g.byte == byte).unwrap().origin).x;
|
||||
assert!((at(4) - f64::from(x1)).abs() < 0.05, "the second word starts where the file has it: {} vs {x1}", at(4));
|
||||
assert!((at(9) - f64::from(x2)).abs() < 0.05, "the third word starts where the file has it: {} vs {x2}", at(9));
|
||||
}
|
||||
|
||||
/// A document of area type `text` (Source Sans 3, 10 pt) `width` wide at (20, 30).
|
||||
fn area_doc(text: &str, justify: Justify, width: f64, space_before: f64) -> Document {
|
||||
let style = CharStyle { size: 10.0, fill: Paint::solid(Color::BLACK), ..Default::default() };
|
||||
|
||||
@@ -5,8 +5,9 @@ use std::sync::Arc;
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_color::{Color, Gradient, GradientPaint, Paint};
|
||||
use vectorcraft_doc::{CharStyle, Document, Effect, Node, NodeKind, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect};
|
||||
use vectorcraft_doc::text::{Bullet, NumberStyle, ParaList};
|
||||
use vectorcraft_doc::{CharStyle, Document, Effect, Node, NodeKind, ParaStyle, TextKind, TextObject, TextRun};
|
||||
use vectorcraft_geom::{Affine, BezPath, PathData, Point, Rect, shapes};
|
||||
use vectorcraft_text::{FALLBACK_FAMILY, FontDb};
|
||||
|
||||
use crate::*;
|
||||
@@ -201,7 +202,8 @@ fn line_break_hyphens_of_right_to_left_lines_are_written_as_text_where_the_canva
|
||||
|
||||
/// The kashidas of justified Arabic type (Insert Kashidas), which stand for no character either,
|
||||
/// are drawn as paths: reopened, the type holds its letters and no hyphen or tatweel. Skipped
|
||||
/// without an OpenType font that covers Arabic and the tatweel, or when the layout adds no kashida.
|
||||
/// without an OpenType font that covers Arabic and the tatweel, when the layout adds no kashida,
|
||||
/// or when PDF text import returns no strings on this platform.
|
||||
#[test]
|
||||
fn kashidas_are_not_written_as_hyphens() {
|
||||
let db = FontDb::global();
|
||||
@@ -223,10 +225,16 @@ fn kashidas_are_not_written_as_hyphens() {
|
||||
return;
|
||||
}
|
||||
let back = texts(&import_as(&pdf(&doc(vec![t]), false).bytes, TextAs::Text));
|
||||
if back.is_empty() {
|
||||
return;
|
||||
}
|
||||
assert!(!back.concat().contains(['-', '\u{2010}', '\u{0640}']), "{back:?}");
|
||||
// Every letter comes back, at least as often as the text holds it (the justified words may
|
||||
// come back as type objects of their own).
|
||||
let all = back.concat();
|
||||
if all.is_empty() {
|
||||
return;
|
||||
}
|
||||
let count = |s: &str, c: char| s.chars().filter(|&x| x == c).count();
|
||||
for c in text.chars().filter(|c| c.is_alphabetic()) {
|
||||
assert!(count(&all, c) >= count(text, c), "{c}: {back:?}");
|
||||
@@ -296,6 +304,196 @@ fn real_text_lands_within_half_a_point_of_the_outlines() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Area type 200 points wide holding `text`, its paragraphs in lists `lists`, with an 18 pt
|
||||
/// hanging indent.
|
||||
fn listed(text: &str, lists: &[Option<ParaList>]) -> TextObject {
|
||||
let mut t = TextObject::point(Point::ZERO, text, style(12.0));
|
||||
t.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(20.0, 20.0, 220.0, 280.0)) };
|
||||
t.xf = Affine::IDENTITY;
|
||||
t.para.left_indent = 18.0;
|
||||
t.para.first_line_indent = -18.0;
|
||||
let styles = lists.iter().map(|&list| ParaStyle { list, ..t.para.clone() }).collect();
|
||||
t.set_paragraph_styles(styles);
|
||||
t
|
||||
}
|
||||
|
||||
/// The origins (document space) of the glyphs of each list marker of the type objects of `d`, in
|
||||
/// the order they are drawn, the marker's tab left out.
|
||||
fn marker_origins(d: &Document) -> Vec<Vec<Point>> {
|
||||
let mut out = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), t);
|
||||
for m in &lay.markers {
|
||||
out.push(m.glyphs.clone().filter(|&i| i != m.tab).map(|i| t.xf * lay.glyphs[i].origin).collect());
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Each glyph of the type objects of `d` that stands for characters of its text: the first of
|
||||
/// them and the glyph's origin in document space.
|
||||
fn glyph_chars(d: &Document) -> Vec<(char, Point)> {
|
||||
let mut out = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
let text = t.plain_text();
|
||||
for g in vectorcraft_text::layout(FontDb::global(), t).glyphs.iter().filter(|g| g.len > 0) {
|
||||
if let Some(c) = text.get(g.byte..).and_then(|s| s.chars().next()) {
|
||||
out.push((c, t.xf * g.origin));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// Does `text` hold `a` before `b`?
|
||||
fn before(text: &str, a: &str, b: &str) -> bool {
|
||||
matches!((text.find(a), text.find(b)), (Some(x), Some(y)) if x < y)
|
||||
}
|
||||
|
||||
/// `back`, the export of `d` reopened, has glyphs of the characters `drawn` (each list marker's,
|
||||
/// in the order the canvas draws them) within `near` points of where `d` draws its markers'
|
||||
/// glyphs.
|
||||
fn assert_markers_in_place(d: &Document, back: &Document, drawn: &[&str], near: f64) {
|
||||
let want = marker_origins(d);
|
||||
assert_eq!(want.len(), drawn.len(), "{drawn:?}");
|
||||
let got = glyph_chars(back);
|
||||
for (origins, chars) in want.iter().zip(drawn) {
|
||||
assert_eq!(origins.len(), chars.chars().count(), "{chars}");
|
||||
for (p, c) in origins.iter().zip(chars.chars()) {
|
||||
assert!(got.iter().any(|(gc, gp)| *gc == c && gp.distance(*p) < near), "{c:?} at {p:?}: {got:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// List markers (Paragraph panel › Bullets and Numbered List) are written as text: reopened, the
|
||||
/// export holds each bullet and number as characters, before its paragraph's text and where the
|
||||
/// canvas draws them, and the page looks as it does with outlined type.
|
||||
#[test]
|
||||
fn list_markers_are_written_as_text_where_the_canvas_draws_them() {
|
||||
let number = Some(ParaList::numbered(NumberStyle::Arabic));
|
||||
for (bullet, character) in [(Bullet::Dot, "\u{2022}"), (Bullet::Dash, "\u{2013}"), (Bullet::Circle, "\u{25E6}"), (Bullet::Square, "\u{25AA}")] {
|
||||
let bullet = Some(ParaList::bulleted(bullet));
|
||||
let t = listed("alpha beta gamma delta epsilon zeta eta theta\nbullet\nfirst\nsecond", &[bullet, bullet, number, number]);
|
||||
let d = doc(vec![t]);
|
||||
let back = import_as(&pdf(&d, false).bytes, TextAs::Text);
|
||||
let all = texts(&back).concat();
|
||||
assert_eq!(all.matches(character).count(), 2, "{all}");
|
||||
assert!(before(&all, character, "alpha") && before(&all, "1.", "first") && before(&all, "2.", "second"), "{all}");
|
||||
assert_markers_in_place(&d, &back, &[character, character, "1.", "2."], 0.1);
|
||||
let (real, outlined) = (ink(&import_as(&pdf(&d, false).bytes, TextAs::Outlines)), ink(&import_as(&pdf(&d, true).bytes, TextAs::Outlines)));
|
||||
let off =
|
||||
[real.x0 - outlined.x0, real.y0 - outlined.y0, real.x1 - outlined.x1, real.y1 - outlined.y1].iter().fold(0.0f64, |m, v| m.max(v.abs()));
|
||||
assert!(off < 0.5, "{character}: {real:?} vs {outlined:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A right-to-left numbered paragraph's number is written as its characters where the canvas
|
||||
/// draws them (the period, then 1 and 2, from the left), and the paragraph's own text comes back
|
||||
/// as it does without a list.
|
||||
#[test]
|
||||
fn a_right_to_left_number_is_written_as_text_where_the_canvas_draws_it() {
|
||||
let hebrew = "שלום עולם";
|
||||
let mut plain = listed(hebrew, &[None]);
|
||||
plain.edit_paras(None, |p| p.justify = vectorcraft_doc::Justify::Auto);
|
||||
let mut numbered = plain.clone();
|
||||
numbered.edit_paras(None, |p| p.list = Some(ParaList::numbered(NumberStyle::Arabic)));
|
||||
numbered.list_count = 11;
|
||||
let d = doc(vec![numbered]);
|
||||
let back = import_as(&pdf(&d, false).bytes, TextAs::Text);
|
||||
// The reader tracks a reopened right-to-left line as a whole, and the gap before the number
|
||||
// comes back as a space of the Hebrew font's width, so the number may sit up to a tenth of an
|
||||
// em (1.2 pt) away; its characters keep their spacing to within 0.1 pt.
|
||||
assert_markers_in_place(&d, &back, &[".12"], 1.2);
|
||||
let drawn = marker_origins(&d).concat();
|
||||
let got = glyph_chars(&back);
|
||||
let at = |c: char| got.iter().find(|(gc, _)| *gc == c).map(|(_, p)| p.x);
|
||||
for (k, (a, b)) in [('.', '1'), ('1', '2')].into_iter().enumerate() {
|
||||
let (Some(pa), Some(pb), Some(da), Some(db)) = (at(a), at(b), drawn.get(k), drawn.get(k + 1)) else {
|
||||
panic!("{a:?} and {b:?} in {got:?}");
|
||||
};
|
||||
assert!(((pb - pa) - (db.x - da.x)).abs() < 0.1, "{a:?} to {b:?}: {} against {}", pb - pa, db.x - da.x);
|
||||
}
|
||||
let without = texts(&import_as(&pdf(&doc(vec![plain]), false).bytes, TextAs::Text)).concat();
|
||||
let all = texts(&back).concat();
|
||||
assert!(all.contains(without.trim()), "{all:?} holds {without:?}");
|
||||
}
|
||||
|
||||
/// Type on a path writes its bullet as text where the canvas draws it along the path.
|
||||
#[test]
|
||||
fn a_bullet_on_a_path_is_written_as_text_where_the_canvas_draws_it() {
|
||||
let mut t = TextObject::point(Point::ZERO, "along the arc", style(18.0));
|
||||
t.kind = TextKind::OnPath { path: arc(), start: 0.0, end: None };
|
||||
t.xf = Affine::IDENTITY;
|
||||
t.para.list = Some(ParaList::bulleted(Bullet::Dot));
|
||||
let d = doc(vec![t]);
|
||||
let back = import_as(&pdf(&d, false).bytes, TextAs::Text);
|
||||
assert!(texts(&back).concat().contains('\u{2022}'), "{:?}", texts(&back));
|
||||
assert_markers_in_place(&d, &back, &["\u{2022}"], 0.3);
|
||||
}
|
||||
|
||||
/// Threaded frames write each marker their layouts draw as text, the number of the paragraph the
|
||||
/// first frame splits included, in each frame where the canvas draws it.
|
||||
#[test]
|
||||
fn numbers_in_threaded_frames_are_written_as_text_in_each_frame() {
|
||||
let numbered =
|
||||
ParaStyle { list: Some(ParaList::numbered(NumberStyle::Arabic)), left_indent: 18.0, first_line_indent: -18.0, ..Default::default() };
|
||||
let frame = |r: Rect| {
|
||||
let mut t = TextObject::point(Point::ZERO, "", style(12.0));
|
||||
t.kind = TextKind::Area { frame: shapes::rectangle(r) };
|
||||
t.xf = Affine::IDENTITY;
|
||||
t
|
||||
};
|
||||
let (mut a, mut b) = (frame(Rect::new(20.0, 20.0, 180.0, 80.0)), frame(Rect::new(200.0, 20.0, 360.0, 280.0)));
|
||||
let text = format!("One\nTwo\n{}\nFour", "The quick brown fox jumps over the lazy dog. ".repeat(4));
|
||||
let story = vec![TextRun { text, style: style(12.0), inline: None }];
|
||||
let parts = vectorcraft_text::thread::distribute(FontDb::global(), &[&a, &b], &story, &vec![numbered; 4]);
|
||||
for (f, part) in [&mut a, &mut b].into_iter().zip(&parts) {
|
||||
f.runs = part.runs.clone();
|
||||
f.set_paragraph_styles(part.paras.clone());
|
||||
f.list_count = part.list_count;
|
||||
}
|
||||
let first = a.plain_text();
|
||||
assert!(first.contains("quick") && !first.ends_with('\n'), "the first frame splits the third paragraph: {first:?}");
|
||||
let d = doc(vec![a, b]);
|
||||
let mut drawn: Vec<String> = vec![];
|
||||
d.walk(|n| {
|
||||
if let NodeKind::Text(t) = &n.kind {
|
||||
drawn.extend(vectorcraft_text::layout(FontDb::global(), t).markers.into_iter().map(|m| m.text));
|
||||
}
|
||||
});
|
||||
assert!(drawn.contains(&"4.".to_string()), "{drawn:?}");
|
||||
let back = import_as(&pdf(&d, false).bytes, TextAs::Text);
|
||||
assert_markers_in_place(&d, &back, &drawn.iter().map(String::as_str).collect::<Vec<_>>(), 0.1);
|
||||
}
|
||||
|
||||
/// A number set in oldstyle figures (the first character's OpenType features) is written as its
|
||||
/// digits, though the character map gives the digits other glyphs. The reopened type has no
|
||||
/// OpenType features and sets lining figures, so only where each number starts is compared.
|
||||
#[test]
|
||||
fn a_number_in_oldstyle_figures_is_written_as_its_digits() {
|
||||
let number = Some(ParaList::numbered(NumberStyle::Arabic));
|
||||
let mut t = listed("first\nsecond", &[number, number]);
|
||||
for r in &mut t.runs {
|
||||
r.style.features = vec!["onum".into()];
|
||||
}
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), &t);
|
||||
let one = &lay.glyphs[lay.markers[0].glyphs.start];
|
||||
let face = FontDb::global().face_by_id(one.font_id).unwrap();
|
||||
assert_ne!(face.glyph_for('1'), one.gid, "an oldstyle 1, not the character map's");
|
||||
let d = doc(vec![t]);
|
||||
let back = import_as(&pdf(&d, false).bytes, TextAs::Text);
|
||||
let all = texts(&back).concat();
|
||||
assert!(before(&all, "1.", "first") && before(&all, "2.", "second"), "{all:?}");
|
||||
let got = glyph_chars(&back);
|
||||
for (origins, digit) in marker_origins(&d).iter().zip(['1', '2']) {
|
||||
assert!(got.iter().any(|(c, p)| *c == digit && p.distance(origins[0]) < 0.1), "{digit} at {:?}: {got:?}", origins[0]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A run shifted two billion points off its baseline is left out, as real text or outlines, and
|
||||
/// the rest of the type is written. On a page 50 points high, the page's y flip puts the shifted
|
||||
/// run's baseline at -2,147,483,648, which the PDF writer panics on in builds with overflow checks.
|
||||
|
||||
@@ -24,6 +24,8 @@ jpeg-encoder = { workspace = true }
|
||||
gif = { workspace = true }
|
||||
# TIFF LZW compression (MIT OR Apache-2.0; already used by the image crate's TIFF reader).
|
||||
weezl = "0.2"
|
||||
# PNG rows read one at a time (MIT OR Apache-2.0; already used by the image crate's PNG reader).
|
||||
png = "0.18"
|
||||
log = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
|
||||
@@ -46,9 +46,9 @@ fn shows_definitions(brush: &Brush, st: &StrokeLayer) -> bool {
|
||||
matches!(st.paint, vectorcraft_color::Paint::Pattern { .. }) || crate::fx::Reads::of_all(art.into_iter()).shows_definitions()
|
||||
}
|
||||
|
||||
/// The art of `doc`'s patterns and symbols, in order.
|
||||
fn definitions(doc: &Document) -> impl Iterator<Item = &Arc<Node>> {
|
||||
doc.patterns.iter().flat_map(|p| &p.art).chain(doc.symbols.iter().map(|s| &s.art))
|
||||
/// The names and art of `doc`'s patterns and symbols, in order.
|
||||
fn definitions(doc: &Document) -> impl Iterator<Item = (&str, &Arc<Node>)> {
|
||||
doc.patterns.iter().flat_map(|p| p.art.iter().map(|a| (p.name.as_str(), a))).chain(doc.symbols.iter().map(|s| (s.name.as_str(), &s.art)))
|
||||
}
|
||||
|
||||
/// Parsed brush library and generated brush art.
|
||||
@@ -61,9 +61,9 @@ pub(crate) struct BrushCache {
|
||||
/// (frame stamp, document address) the library was last validated for.
|
||||
checked: (u64, usize),
|
||||
lib: HashMap<String, Arc<Brush>>,
|
||||
/// The art of the document's patterns and symbols ([`definitions`]) when the library was last
|
||||
/// validated, held weakly as the pattern tiles hold theirs.
|
||||
definitions: Vec<Weak<Node>>,
|
||||
/// The names and art of the document's patterns and symbols ([`definitions`]) when the library
|
||||
/// was last validated, the art held weakly as the pattern tiles hold theirs.
|
||||
definitions: Vec<(String, Weak<Node>)>,
|
||||
/// Brush art per (node id, stroke item index, [`path_key`] of the stroked path).
|
||||
pub(crate) entries: FrameCache<(u64, usize, u64), Entry>,
|
||||
/// How many times [`Renderer::draw_brush`] made brush art.
|
||||
@@ -93,8 +93,8 @@ impl BrushCache {
|
||||
return;
|
||||
}
|
||||
self.checked = key;
|
||||
if !self.definitions.iter().map(Weak::as_ptr).eq(definitions(doc).map(Arc::as_ptr)) {
|
||||
self.definitions = definitions(doc).map(Arc::downgrade).collect();
|
||||
if !self.definitions.iter().map(|(n, a)| (n.as_str(), a.as_ptr())).eq(definitions(doc).map(|(n, a)| (n, Arc::as_ptr(a)))) {
|
||||
self.definitions = definitions(doc).map(|(n, a)| (n.to_string(), Arc::downgrade(a))).collect();
|
||||
self.entries.retain(|e| !e.definitions);
|
||||
}
|
||||
let cur = doc.unknown.get(vectorcraft_brush::DOC_KEY);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! What draws differently after an edit, so a view can draw again only there.
|
||||
//! What draws differently after an edit, or once placed documents' bitmaps are ready, so a view
|
||||
//! can draw again only there.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
use vectorcraft_doc::{Document, Node, NodeKind, SymbolBoxes};
|
||||
@@ -14,6 +16,66 @@ pub enum Changed {
|
||||
Everything,
|
||||
}
|
||||
|
||||
impl Changed {
|
||||
/// What may draw differently after this change and `other`: everything when either is,
|
||||
/// else both areas.
|
||||
pub fn and(self, other: Changed) -> Changed {
|
||||
match (self, other) {
|
||||
(Changed::Everything, _) | (_, Changed::Everything) => Changed::Everything,
|
||||
(Changed::Area(a), Changed::Area(b)) => Changed::Area(a.union(b)),
|
||||
(Changed::Area(a), Changed::Nothing) | (Changed::Nothing, Changed::Area(a)) => Changed::Area(a),
|
||||
(Changed::Nothing, Changed::Nothing) => Changed::Nothing,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What draws differently in `doc` once the bitmaps of the placed documents' `files` are ready
|
||||
/// ([`crate::placed_document::made_between`]): the bounds of everything the objects that show
|
||||
/// them paint, measured as [`changed`] measures an object that changed. Everything when the art
|
||||
/// of a symbol, a graph design, a pattern or a brush shows one of them (it draws wherever it is
|
||||
/// used), or while a pattern is edited.
|
||||
pub fn placed_area(doc: &Document, files: &HashSet<String>) -> Changed {
|
||||
if files.is_empty() {
|
||||
return Changed::Nothing;
|
||||
}
|
||||
let mut elsewhere =
|
||||
doc.symbols.iter().map(|s| &s.art).chain(doc.graph_designs.iter().map(|g| &g.art)).chain(doc.patterns.iter().flat_map(|p| &p.art));
|
||||
if doc.pattern_edit.is_some()
|
||||
|| elsewhere.any(|n| shows(n, files))
|
||||
|| vectorcraft_brush::library(doc).iter().any(|b| b.art().into_iter().any(|n| shows(n, files)))
|
||||
{
|
||||
return Changed::Everything;
|
||||
}
|
||||
let symbols = doc.symbol_boxes();
|
||||
let mut area = None;
|
||||
for layer in &doc.layers {
|
||||
add_placed(&symbols, layer, files, &mut area);
|
||||
}
|
||||
area.map_or(Changed::Nothing, Changed::Area)
|
||||
}
|
||||
|
||||
/// Does `n`, a member of it or the art of an opacity mask in it show one of `files`?
|
||||
fn shows(n: &Node, files: &HashSet<String>) -> bool {
|
||||
matches!(&n.kind, NodeKind::PlacedDocument(p) if files.contains(&p.key))
|
||||
|| n.extras().mask.as_ref().is_some_and(|m| shows(&m.art, files))
|
||||
|| n.children().is_some_and(|c| c.iter().any(|c| shows(c, files)))
|
||||
}
|
||||
|
||||
/// Add to `area` what `n` paints where it shows one of `files`: each member of a group or layer
|
||||
/// whose members draw each on their own (unless its opacity mask shows one), and any other object
|
||||
/// whole.
|
||||
fn add_placed(symbols: &SymbolBoxes, n: &Node, files: &HashSet<String>, area: &mut Option<Rect>) {
|
||||
match members(n) {
|
||||
Some(children) if !n.extras().mask.as_ref().is_some_and(|m| shows(&m.art, files)) => {
|
||||
for c in children {
|
||||
add_placed(symbols, c, files, area);
|
||||
}
|
||||
}
|
||||
_ if shows(n, files) => *area = vectorcraft_geom::union_opt(*area, crate::brush_fx::cull_bounds(symbols, n)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// What may draw differently in `new` than in `old`, the version before an edit: the bounds of
|
||||
/// everything the objects that changed paint, before and after the edit ([`crate::painted_bounds`]),
|
||||
/// or everything when more than the art in the layers changed, or while a pattern is edited (its
|
||||
|
||||
+98
-29
@@ -687,7 +687,8 @@ fn linear_key(view: Affine) -> [u64; 4] {
|
||||
}
|
||||
|
||||
/// The pan of the view a raster was cropped for, or made at a lower resolution than the view's, and
|
||||
/// the device-pixel rect of the frame it was made in ([`PixelEntry::view`], [`ShadowEntry::view`]).
|
||||
/// the device-pixel rect it was made for in that view: the frame's, or around it the margin of
|
||||
/// [`pan_margin`] ([`PixelEntry::view`], [`ShadowEntry::view`]).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct ViewCrop {
|
||||
pan: Vec2,
|
||||
@@ -701,7 +702,7 @@ impl ViewCrop {
|
||||
|
||||
/// Does the raster draw in a frame through `view` (of the same zoom and rotation) onto
|
||||
/// `screen`? When the view is panned by whole pixels and the frame's rect, panned back, lies
|
||||
/// within the one the raster was made in: the same pixels in the same places, as when a frame
|
||||
/// within the one the raster was made for: the same pixels in the same places, as when a frame
|
||||
/// is drawn again only in a part of it.
|
||||
fn serves(&self, view: Affine, screen: Rect) -> bool {
|
||||
let d = view.translation() - self.pan;
|
||||
@@ -709,6 +710,30 @@ impl ViewCrop {
|
||||
let s = screen - whole;
|
||||
(d - whole).hypot() < 1e-6 && s.x0 >= self.screen.x0 && s.y0 >= self.screen.y0 && s.x1 <= self.screen.x1 && s.y1 <= self.screen.y1
|
||||
}
|
||||
|
||||
/// The rect the raster was made for, in the device pixels of a frame through `view` that it
|
||||
/// serves ([`Self::serves`]).
|
||||
fn served(&self, view: Affine) -> Rect {
|
||||
let d = view.translation() - self.pan;
|
||||
self.screen + Vec2::new(d.x.round(), d.y.round())
|
||||
}
|
||||
}
|
||||
|
||||
/// How far (device pixels, on each side) past a `w` × `h` view a raster cropped to it, and `m`
|
||||
/// pixels around that, is made when it is made again at the same zoom and rotation, so that later
|
||||
/// pans of up to that many pixels draw it: the most that keeps the raster within `budget` pixels and
|
||||
/// `side` pixels a side, with two pixels to spare for rounding, and at most half the view's longer
|
||||
/// side. 0 when the view and the `m` pixels around it alone leave no room.
|
||||
fn pan_margin((w, h): (f64, f64), m: f64, budget: f64, side: f64) -> f64 {
|
||||
let (a, b) = (w + 2.0 * m, h + 2.0 * m);
|
||||
// The largest `e` with (a + 2e) × (b + 2e) within the budget, less two pixels for the rounding
|
||||
// of the raster's edges to whole pixels.
|
||||
let e = (((a - b).powi(2) + 4.0 * budget).sqrt() - (a + b)) / 4.0 - 2.0;
|
||||
// (Also for a view or spread that isn't a number.)
|
||||
if !e.is_finite() {
|
||||
return 0.0;
|
||||
}
|
||||
e.min((side - a.max(b)) / 2.0 - 2.0).min(w.max(h) / 2.0).floor().max(0.0)
|
||||
}
|
||||
|
||||
/// Most pixels a raster of [`Renderer::pixel_content`] or [`Renderer::with_filters`] holds while
|
||||
@@ -816,8 +841,9 @@ struct Shadow {
|
||||
mode: vectorcraft_doc::color::BlendMode,
|
||||
/// Made before its object moved ([`ShadowEntry::moved`]).
|
||||
moved: bool,
|
||||
/// Cropped to the view, or made over a raster that is ([`ShadowEntry::view`]).
|
||||
cropped: bool,
|
||||
/// For a raster cropped to the view, or made over a raster that is ([`ShadowEntry::view`]), the
|
||||
/// rect it was made for, in this frame's device pixels ([`ViewCrop::served`]).
|
||||
cropped: Option<Rect>,
|
||||
}
|
||||
|
||||
impl ShadowEntry {
|
||||
@@ -1099,9 +1125,12 @@ impl Renderer {
|
||||
/// what can show in the `screen` (device pixels): the view, and around it the blur's spread and
|
||||
/// `around` (document units: how far the shadows and glows stacked over this one look), made
|
||||
/// coarser to fit the budget where the blur hides the coarser grid. Such a raster, and one
|
||||
/// made over it (`over_cropped`), is reused only in the same view. `None` when the effect isn't
|
||||
/// a shadow/glow or the raster would still be too large (caller falls back to
|
||||
/// [`Self::draw_shadow_filter`]).
|
||||
/// made over it, is reused while a pan keeps the view inside the rect it was made for: the
|
||||
/// view, and when the raster kept for the object was made at the same zoom and rotation and no
|
||||
/// drag is on, the view with [`pan_margin`] around it, within `over` (the rect, in device
|
||||
/// pixels, that the cropped rasters of the shadows and glows it is made over were made for;
|
||||
/// `None` when it is made over none). `None` when the effect isn't a shadow/glow or the raster
|
||||
/// would still be too large (caller falls back to [`Self::draw_shadow_filter`]).
|
||||
/// While dragging on a multithreaded context, a raster that has to be made again counts as too
|
||||
/// large when it would hold more than [`DRAG_PIXEL_BUDGET`] pixels.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -1113,7 +1142,7 @@ impl Renderer {
|
||||
fx: &RasterFx,
|
||||
reach: Rect,
|
||||
owner: Option<&Arc<Node>>,
|
||||
(screen, around, over_cropped): (Rect, f64, bool),
|
||||
(screen, around, over): (Rect, f64, Option<Rect>),
|
||||
paint: &mut dyn FnMut(&mut Self, &mut RenderContext, &Frame),
|
||||
) -> Option<Shadow> {
|
||||
let (mode, opacity, dx, dy, blur, color, darkness) = match fx {
|
||||
@@ -1128,7 +1157,6 @@ impl Renderer {
|
||||
// What the silhouette reads: as the raster kept for `n` found it, else found now.
|
||||
let reads = self.shadows.get(&key).filter(|e| e.node.is(n)).map_or_else(|| Reads::of(n), |e| e.inputs.reads);
|
||||
let inputs = self.raster_inputs(f, n, reads);
|
||||
let in_view = ViewCrop::of(f.view, screen);
|
||||
let exact = |e: &ShadowEntry| {
|
||||
e.linear == linear && e.node.is(n) && e.inputs == inputs && (interacting || !e.moved) && e.view.is_none_or(|v| v.serves(f.view, screen))
|
||||
};
|
||||
@@ -1141,7 +1169,7 @@ impl Renderer {
|
||||
e.stamp = stamp;
|
||||
self.stats.moved += usize::from(e.moved);
|
||||
let p = f.view * e.anchor;
|
||||
(e.image.clone(), (p.x + e.rel.0).round(), (p.y + e.rel.1).round(), e.scale, e.moved, e.view.is_some())
|
||||
(e.image.clone(), (p.x + e.rel.0).round(), (p.y + e.rel.1).round(), e.scale, e.moved, e.view.map(|v| v.served(f.view)))
|
||||
}
|
||||
None => {
|
||||
// An Outer Glow's silhouette grows by a quarter of a pixel of the document's raster grid first.
|
||||
@@ -1162,18 +1190,23 @@ impl Renderer {
|
||||
};
|
||||
// A glow too large for the budget is made coarser, where its blur hides the coarser grid: the filter
|
||||
// layer the caller falls back to can't make its silhouette solid.
|
||||
let full = region(whole, matches!(fx, RasterFx::OuterGlow { .. }), 4.0e6).filter(|_| !over_cropped);
|
||||
let full = region(whole, matches!(fx, RasterFx::OuterGlow { .. }), 4.0e6).filter(|_| over.is_none());
|
||||
// Else it is cropped to what can show in the view, within the budget of the filter
|
||||
// layer it would otherwise be drawn through, and made coarser in the same way.
|
||||
// layer it would otherwise be drawn through, and made coarser in the same way. Made
|
||||
// again at this zoom and rotation (after a pan), it covers a margin around the view
|
||||
// too, so that later pans within the margin draw it.
|
||||
let ((x0, y0, w, h, scale), cropped) = match full {
|
||||
Some(r) => (r, false),
|
||||
Some(r) => (r, None),
|
||||
None => {
|
||||
let m = spread + around / f.px;
|
||||
let r = whole.intersect(screen.inflate(m, m));
|
||||
let again = self.shadows.get(&key).is_some_and(|e| e.linear == linear) && !f.opts.dragging;
|
||||
let e = if again { pan_margin((screen.width(), screen.height()), m, PIXEL_BUDGET, 8192.0) } else { 0.0 };
|
||||
let room = over.map_or(screen.inflate(e, e), |o| screen.inflate(e, e).intersect(o));
|
||||
let r = whole.intersect(room.inflate(m, m));
|
||||
if r.width() <= 0.0 || r.height() <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
(region(r, true, PIXEL_BUDGET)?, true)
|
||||
(region(r, true, PIXEL_BUDGET)?, Some(room))
|
||||
}
|
||||
};
|
||||
// During a drag, a larger shadow on a multithreaded context is filtered within the
|
||||
@@ -1185,7 +1218,10 @@ impl Renderer {
|
||||
// Silhouette (the object's painted alpha, and its colors under Darkness), offset by
|
||||
// the shadow distance.
|
||||
let mut off = f.offscreen_context(w, h);
|
||||
let crop = Frame { mt: false, view: Affine::scale(1.0 / scale) * Affine::translate((-x0, -y0)) * f.view, ..*f };
|
||||
let view = Affine::scale(1.0 / scale) * Affine::translate((-x0, -y0)) * f.view;
|
||||
// Art is culled against the raster's own area: members of a group outside the view cast their shadows in it.
|
||||
let visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(w), f64::from(h)));
|
||||
let crop = Frame { mt: false, view, visible, ..*f };
|
||||
let before = self.stats.moved;
|
||||
self.inside_layer(|r| paint(r, &mut off, &shifted(&crop, dx, dy)));
|
||||
// A silhouette drawn over moved rasters makes a moved shadow.
|
||||
@@ -1234,7 +1270,7 @@ impl Renderer {
|
||||
let p = f.view * anchor;
|
||||
let node = Drawn::of(n, owner);
|
||||
let rel = (x0 - p.x, y0 - p.y);
|
||||
let view = cropped.then_some(in_view);
|
||||
let view = cropped.map(|room| ViewCrop::of(f.view, room));
|
||||
self.shadows.insert(key, ShadowEntry { node, linear, anchor, rel, image: image.clone(), scale, view, made, inputs, moved, stamp });
|
||||
self.trim_fx_rasters(FX_RASTER_BUDGET);
|
||||
(image, x0, y0, scale, moved, cropped)
|
||||
@@ -1345,7 +1381,10 @@ impl Renderer {
|
||||
let anchor = reach.origin();
|
||||
let p = f.view * anchor;
|
||||
let mut off = f.offscreen_context(w, h);
|
||||
let crop = Frame { mt: false, view: Affine::scale(1.0 / scale) * Affine::translate((-(p.x + rel.0), -(p.y + rel.1))) * f.view, ..*f };
|
||||
let view = Affine::scale(1.0 / scale) * Affine::translate((-(p.x + rel.0), -(p.y + rel.1))) * f.view;
|
||||
// Culled against the raster's area, as `shadow_raster` draws the silhouette.
|
||||
let visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, f64::from(w), f64::from(h)));
|
||||
let crop = Frame { mt: false, view, visible, ..*f };
|
||||
self.inside_layer(|r| paint(r, &mut off, &shifted(&crop, dx, dy)));
|
||||
off.flush();
|
||||
let mut pm = vello_cpu::Pixmap::new(w, h);
|
||||
@@ -1684,7 +1723,8 @@ impl Renderer {
|
||||
for (i, fx) in rfx.iter().enumerate().filter(|(_, x)| x.is_below()) {
|
||||
// A raster cropped to the view covers what the shadows and glows stacked over it read.
|
||||
let around: f64 = rfx.iter().skip(i + 1).filter(|x| x.is_below()).map(looks).sum();
|
||||
let over_cropped = made.iter().any(|(_, s)| s.as_ref().is_some_and(|s| s.cropped));
|
||||
// The rect that the cropped rasters of the earlier ones (drawn into this one's silhouette) were all made for.
|
||||
let over = made.iter().filter_map(|(_, s)| s.as_ref()?.cropped).reduce(|a, b| a.intersect(b));
|
||||
let shadow = {
|
||||
let earlier = &made;
|
||||
let view = f.view;
|
||||
@@ -1701,7 +1741,7 @@ impl Renderer {
|
||||
}
|
||||
paint(r, c, fr);
|
||||
};
|
||||
let view = (screen, around, over_cropped);
|
||||
let view = (screen, around, over);
|
||||
content.cache.and_then(|slot| self.shadow_raster(f, content.node, slot + i, fx, stacked, owner.as_ref(), view, &mut art))
|
||||
};
|
||||
stacked = match fx {
|
||||
@@ -1773,9 +1813,11 @@ impl Renderer {
|
||||
/// resolution. A whole raster at full resolution is cached while the object, the
|
||||
/// zoom and what the content reads ([`Inputs`]) stay the same (panning only moves it), and
|
||||
/// while interacting after the content only moved ([`Self::move_pixel_content`]). A cropped or
|
||||
/// lower-resolution raster is cached while the object, the view (its pan included) and what the
|
||||
/// content reads stay the same ([`PixelEntry::view`]); a lower-resolution one is kept resampled to
|
||||
/// the view's pixels ([`Self::resampled`]).
|
||||
/// lower-resolution raster is cached while the object, the zoom and what the content reads stay
|
||||
/// the same and a pan keeps the view inside the rect it was made for ([`PixelEntry::view`]): the
|
||||
/// view, and for a raster cropped to it that is made again at the same zoom and rotation, outside
|
||||
/// a drag and for content without a [`Kept`] image, the view with [`pan_margin`] around it. A
|
||||
/// lower-resolution one is kept resampled to the view's pixels ([`Self::resampled`]).
|
||||
/// While dragging, content without such a raster to draw renders within [`DRAG_PIXEL_BUDGET`]
|
||||
/// pixels and is not cached.
|
||||
fn pixel_content(
|
||||
@@ -1815,8 +1857,20 @@ impl Renderer {
|
||||
let fits = full.area() <= PIXEL_BUDGET;
|
||||
// Device pixels from a pixel to the content deciding it (`None`: anywhere).
|
||||
let margin = chain.iter().try_fold(2.0, |m, fx| looks_around(fx).map(|d| m + d / f.px));
|
||||
let linear = linear_key(f.view);
|
||||
let key = content.cache.map(|slot| (content.node as *const Node as usize, slot, f.ink));
|
||||
// Made again at this zoom and rotation (after a pan), a raster cropped to the view covers a
|
||||
// margin around the view too, so that later pans within the margin draw it.
|
||||
let again = key.and_then(|key| self.pixel_fx.get(&key)).is_some_and(|e| e.linear == linear) && content.kept.is_none() && !f.opts.dragging;
|
||||
let room = match margin {
|
||||
Some(m) if !fits && again => {
|
||||
let e = pan_margin((screen.width(), screen.height()), m, PIXEL_BUDGET, f64::from(crate::MAX_RASTER_SIDE));
|
||||
screen.inflate(e, e)
|
||||
}
|
||||
_ => screen,
|
||||
};
|
||||
let region = match margin {
|
||||
Some(m) if !fits => full.intersect(screen.inflate(m, m)),
|
||||
Some(m) if !fits => full.intersect(room.inflate(m, m)),
|
||||
_ => full,
|
||||
};
|
||||
let (x0, y0) = (region.x0.floor(), region.y0.floor());
|
||||
@@ -1825,11 +1879,10 @@ impl Renderer {
|
||||
let side = f64::from(crate::MAX_RASTER_SIDE);
|
||||
let k = (PIXEL_BUDGET / (rw * rh)).sqrt().min(side / rw).min(side / rh).min(1.0);
|
||||
let (w, h) = ((rw * k).ceil().clamp(1.0, side), (rh * k).ceil().clamp(1.0, side));
|
||||
// The cached raster: of the whole content at full size at this zoom, else of this view.
|
||||
let linear = linear_key(f.view);
|
||||
// The cached raster: of the whole content at full size at this zoom, else of this view (and
|
||||
// the margin around it).
|
||||
let whole = fits && k >= 1.0;
|
||||
let in_view = (!whole).then(|| ViewCrop::of(f.view, screen));
|
||||
let key = content.cache.map(|slot| (content.node as *const Node as usize, slot, f.ink));
|
||||
let in_view = (!whole).then(|| ViewCrop::of(f.view, room));
|
||||
let stamp = self.stamp;
|
||||
let channels = match f.ink {
|
||||
Ink::Cmy => effects::pixel::Channels::CmyPlane,
|
||||
@@ -2131,6 +2184,7 @@ impl Renderer {
|
||||
let o = f.opts;
|
||||
(doc.images, self.dim_images.map(f32::to_bits), o.smooth_images, o.image_mips, o.trace_views, o.progressive_placed).hash(&mut h);
|
||||
o.trace_source.as_deref().hash(&mut h);
|
||||
o.mark_undecoded_images.hash(&mut h);
|
||||
}
|
||||
if reads.brushes {
|
||||
self.brushes.library_key(f.doc, self.stamp).hash(&mut h);
|
||||
@@ -2413,7 +2467,7 @@ mod tests {
|
||||
use vectorcraft_doc::{Appearance, Document, Effect, Node};
|
||||
use vectorcraft_geom::{Affine, Rect, shapes};
|
||||
|
||||
use super::{DRAG_PIXEL_BUDGET, Drawn, PIXEL_BUDGET, drag_scale, filter_region, filter_region_within};
|
||||
use super::{DRAG_PIXEL_BUDGET, Drawn, PIXEL_BUDGET, drag_scale, filter_region, filter_region_within, pan_margin};
|
||||
use crate::tests_fontchange::fonts_steady;
|
||||
use crate::{RenderOptions, Rendered, Renderer};
|
||||
|
||||
@@ -2458,6 +2512,21 @@ mod tests {
|
||||
assert_eq!(filter_region_within(small, (1600, 1000), 4.0, DRAG_PIXEL_BUDGET), filter_region(small, (1600, 1000), 4.0));
|
||||
}
|
||||
|
||||
/// The margin a raster cropped to the view is made again with keeps it within the pixel budget,
|
||||
/// a pixel of rounding on each edge included, and within the side limit; it is at most half the
|
||||
/// view's longer side, and 0 when the view and its spread alone fill the budget.
|
||||
#[test]
|
||||
fn the_margin_for_pans_stays_within_the_pixel_budget() {
|
||||
for ((w, h), m, want) in [((2560.0, 1440.0), 32.0, 441.0), ((640.0, 360.0), 32.0, 320.0), ((3840.0, 2160.0), 32.0, 0.0)] {
|
||||
let e = pan_margin((w, h), m, PIXEL_BUDGET, 8192.0);
|
||||
assert_eq!(e, want, "{w} × {h}");
|
||||
let (rw, rh) = (w + 2.0 * (m + e) + 2.0, h + 2.0 * (m + e) + 2.0);
|
||||
assert!(e == 0.0 || rw * rh <= PIXEL_BUDGET, "{w} × {h}: {rw} × {rh}");
|
||||
}
|
||||
assert_eq!(pan_margin((2000.0, 10.0), 0.0, 1e9, 3000.0), 498.0, "within the side limit");
|
||||
assert_eq!(pan_margin((2000.0, 10.0), f64::NAN, PIXEL_BUDGET, 8192.0), 0.0);
|
||||
}
|
||||
|
||||
fn doc_with(r: Rect, fill: Color, effects: Vec<(&str, serde_json::Value)>) -> Document {
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let id = d.alloc_id();
|
||||
|
||||
@@ -63,7 +63,13 @@ fn physical_memory() -> Option<u64> {
|
||||
fn physical_memory() -> Option<u64> {
|
||||
let (sysctl, name) = if cfg!(target_os = "macos") { ("/usr/sbin/sysctl", "hw.memsize") } else { ("/sbin/sysctl", "hw.physmem") };
|
||||
let out = std::process::Command::new(sysctl).args(["-n", name]).output().ok().filter(|o| o.status.success())?;
|
||||
String::from_utf8(out.stdout).ok()?.trim().parse().ok()
|
||||
sysctl_bytes(&out.stdout)
|
||||
}
|
||||
|
||||
/// The byte count `sysctl -n` prints for a memory size.
|
||||
#[cfg(any(target_os = "macos", target_os = "freebsd", test))]
|
||||
fn sysctl_bytes(out: &[u8]) -> Option<u64> {
|
||||
std::str::from_utf8(out).ok()?.trim().parse().ok()
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "linux", windows, target_os = "macos", target_os = "freebsd", target_arch = "wasm32")))]
|
||||
@@ -114,6 +120,11 @@ pub(crate) struct ImageStore {
|
||||
tick: u64,
|
||||
/// [`BlobId`]s per blob byte buffer, by address (the `Weak` keeps it from being reused).
|
||||
ids: HashMap<usize, (Weak<Vec<u8>>, BlobId)>,
|
||||
/// The content keys of images whose pixels can't be decoded ([`Undecoded::Unreadable`]), so
|
||||
/// they aren't decoded again, each with whether [`newly_undecodable`] has counted it.
|
||||
///
|
||||
/// [`Undecoded::Unreadable`]: crate::paint::Undecoded::Unreadable
|
||||
undecodable: HashMap<Arc<str>, bool>,
|
||||
}
|
||||
|
||||
fn pixmap_bytes(pm: &Pixmap) -> usize {
|
||||
@@ -122,7 +133,21 @@ fn pixmap_bytes(pm: &Pixmap) -> usize {
|
||||
|
||||
impl ImageStore {
|
||||
pub(crate) fn new(budget: usize) -> Self {
|
||||
Self { entries: HashMap::new(), bytes: 0, budget, tick: 0, ids: HashMap::new() }
|
||||
Self { entries: HashMap::new(), bytes: 0, budget, tick: 0, ids: HashMap::new(), undecodable: HashMap::new() }
|
||||
}
|
||||
|
||||
/// Whether the image with content key `content` is known not to decode.
|
||||
pub(crate) fn is_undecodable(&self, content: &str) -> bool {
|
||||
self.undecodable.contains_key(content)
|
||||
}
|
||||
|
||||
/// Note that the image with content key `content` can't be decoded. Past 1024 such images the
|
||||
/// notes are dropped and those images are tried again.
|
||||
pub(crate) fn set_undecodable(&mut self, content: Arc<str>) {
|
||||
if self.undecodable.len() >= 1024 {
|
||||
self.undecodable.clear();
|
||||
}
|
||||
self.undecodable.entry(content).or_insert(false);
|
||||
}
|
||||
|
||||
/// The pixels of `key`, marked as just used.
|
||||
@@ -252,6 +277,27 @@ pub(crate) fn remember_size(blob: &ImageBlob, size: (u16, u16)) {
|
||||
store().remember_size(&blob.bytes, size);
|
||||
}
|
||||
|
||||
/// How many of `blobs` a renderer has found it can't decode (they draw nothing, or a crossed box
|
||||
/// with [`RenderOptions::mark_undecoded_images`](crate::RenderOptions::mark_undecoded_images)) that
|
||||
/// no earlier call counted: each such image is counted once in the process.
|
||||
pub fn newly_undecodable<'a>(blobs: impl IntoIterator<Item = &'a ImageBlob>) -> usize {
|
||||
let mut s = store();
|
||||
if s.undecodable.values().all(|counted| *counted) {
|
||||
return 0;
|
||||
}
|
||||
let mut n = 0;
|
||||
for blob in blobs {
|
||||
let Some(id) = s.known_id(&blob.bytes) else { continue };
|
||||
if let Some(counted) = s.undecodable.get_mut(&id.content)
|
||||
&& !*counted
|
||||
{
|
||||
*counted = true;
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
n
|
||||
}
|
||||
|
||||
/// `pm` at half the size (rounded up), each pixel the mean of the 2×2 it covers (the last row and
|
||||
/// column repeat on odd sizes).
|
||||
pub(crate) fn half(pm: &Pixmap) -> Pixmap {
|
||||
@@ -339,6 +385,13 @@ mod tests {
|
||||
assert_eq!(s.bytes(), 2 * 640 * 640 * 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sysctl_prints_the_memory_size_in_bytes() {
|
||||
assert_eq!(sysctl_bytes(b"17179869184\n"), Some(16 << 30));
|
||||
assert_eq!(sysctl_bytes(b""), None);
|
||||
assert_eq!(sysctl_bytes(b"unknown oid 'hw.memsize'\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_averages_and_rounds_up_odd_sizes() {
|
||||
let px = |v: u8| PremulRgba8 { r: v, g: v, b: v, a: 255 };
|
||||
|
||||
@@ -18,7 +18,7 @@ mod ink;
|
||||
mod live;
|
||||
mod lru;
|
||||
mod paint;
|
||||
pub use paint::decode_failures;
|
||||
pub use paint::{decode_failures, reduced_size};
|
||||
mod pattern;
|
||||
pub mod placed_document;
|
||||
pub mod proof;
|
||||
@@ -37,9 +37,9 @@ use ink::Ink;
|
||||
use lru::FrameCache;
|
||||
|
||||
pub use brush_fx::instance_art;
|
||||
pub use changed::{Changed, changed, view_pixels};
|
||||
pub use changed::{Changed, changed, placed_area, view_pixels};
|
||||
pub use effects::stroke::width_outline;
|
||||
pub use images::{IMAGE_CACHE_MAX, image_cache_bytes, set_image_cache_budget};
|
||||
pub use images::{IMAGE_CACHE_MAX, image_cache_bytes, newly_undecodable, set_image_cache_budget};
|
||||
pub use live::expand_live;
|
||||
pub use pattern::render_pattern_swatch;
|
||||
pub use vectorcraft_effects as effects;
|
||||
@@ -186,6 +186,9 @@ pub struct RenderOptions {
|
||||
/// (box-filtered from the full image, kept with the decoded images), so the full image needn't
|
||||
/// stay in memory or be sampled. Off, images always sample their full pixels (exports).
|
||||
pub image_mips: bool,
|
||||
/// Screen views: an image whose pixels can't be decoded draws as a light gray box crossed
|
||||
/// from corner to corner. Off, it draws nothing (exports, which report it instead).
|
||||
pub mark_undecoded_images: bool,
|
||||
/// Screen views while an interaction is in progress (a drag, a dialog's preview): an object
|
||||
/// whose content only moved since an earlier frame draws its cached drop shadows, outer glows
|
||||
/// and filtered content from the rasters made then, at the nearest whole pixel, without
|
||||
@@ -281,6 +284,7 @@ impl Default for RenderOptions {
|
||||
precise: false,
|
||||
supersample: false,
|
||||
image_mips: false,
|
||||
mark_undecoded_images: false,
|
||||
interacting: false,
|
||||
dragging: false,
|
||||
rich_black: false,
|
||||
@@ -539,6 +543,9 @@ pub struct Renderer {
|
||||
fx_arts: FrameCache<usize, FxArtEntry>,
|
||||
/// Symbol art as instances and inline graphics draw it (see [`Self::placed_art`]).
|
||||
placed_arts: FrameCache<PlacedKey, PlacedEntry>,
|
||||
/// The bitmap clock of [`placed_document`] when this frame first drew a placed document from
|
||||
/// a bitmap: the bitmaps drawn since then are not dropped to make room for those it asks for.
|
||||
placed_frame: Option<u64>,
|
||||
/// Layers open around the drawing point in the current context: a non-isolated group can copy
|
||||
/// its backdrop only when there are none (see [`Self::group`]).
|
||||
nested: u32,
|
||||
@@ -688,6 +695,7 @@ impl Renderer {
|
||||
shape_of: 0,
|
||||
fx_arts: FrameCache::new(lru::FX_ART_BUDGET, 256),
|
||||
placed_arts: FrameCache::new(lru::PLACED_ART_BUDGET, 256),
|
||||
placed_frame: None,
|
||||
nested: 0,
|
||||
backdrop: None,
|
||||
blends: PtrMap::default(),
|
||||
@@ -788,6 +796,7 @@ impl Renderer {
|
||||
(self.offscreen_live, self.offscreen_budget) = (0, 0);
|
||||
self.symbol_nodes = 0;
|
||||
self.twice_drawn = 0;
|
||||
self.placed_frame = None;
|
||||
}
|
||||
|
||||
/// End a frame: drop cache entries not used for a few frames (every render, thumbnails too,
|
||||
@@ -2151,6 +2160,8 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if f.opts.mark_undecoded_images && (!outline || f.doc.setup.outline_images) {
|
||||
self.draw_undecoded_mark(ctx, f, im, area);
|
||||
}
|
||||
if outline {
|
||||
let mut p = rect.to_path(0.1);
|
||||
@@ -2159,6 +2170,32 @@ impl Renderer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the mark of image `im` whose pixels can't be had ([`RenderOptions::mark_undecoded_images`]):
|
||||
/// a light gray box over its frame, crossed from corner to corner with a gray hairline, and
|
||||
/// with `area` (see [`Self::draw_image_in`]) only inside that region.
|
||||
fn draw_undecoded_mark(&mut self, ctx: &mut RenderContext, f: &Frame, im: &vectorcraft_doc::ImageObject, area: Option<&(BezPath, FillRule)>) {
|
||||
let (w, h) = (im.width as f64, im.height as f64);
|
||||
if let Some((bp, rule)) = area {
|
||||
ctx.set_transform(f.view);
|
||||
ctx.set_fill_rule(fill_rule(*rule));
|
||||
ctx.push_clip_layer(bp);
|
||||
}
|
||||
let rect = Rect::new(0.0, 0.0, w, h);
|
||||
ctx.set_transform(f.view * im.xf);
|
||||
ctx.set_paint(f.ink.fixed([128, 128, 128, 40]));
|
||||
ctx.fill_rect(&rect);
|
||||
let mut cross = rect.to_path(0.1);
|
||||
cross.move_to((0.0, 0.0));
|
||||
cross.line_to((w, h));
|
||||
cross.move_to((w, 0.0));
|
||||
cross.line_to((0.0, h));
|
||||
cross.apply_affine(im.xf);
|
||||
self.hairline(ctx, f, &cross, [128, 128, 128, 255]);
|
||||
if area.is_some() {
|
||||
ctx.pop_layer();
|
||||
}
|
||||
}
|
||||
|
||||
/// Name image `key` recoloured by `map` (its hash `hash`) as `derived` (the key the adjusted
|
||||
/// art's image takes): drawing `derived` draws the recoloured pixels, made when first drawn and
|
||||
/// kept with the decoded images. Names past a limit drop the art made with them too, so it is
|
||||
@@ -2276,16 +2313,30 @@ fn blob_key(blob: &vectorcraft_doc::ImageBlob) -> (images::ImageKey, Option<Arc<
|
||||
}
|
||||
|
||||
/// The decoded pixels of `blob` (a CMYK image's inks shown through the working CMYK profile, again
|
||||
/// when the colour settings change), from the shared store, and their key there.
|
||||
/// when the colour settings change), from the shared store, and their key there. An image whose
|
||||
/// pixels can't be decoded is noted in the store and not decoded again; each request for it counts
|
||||
/// a failure in [`decode_failures`].
|
||||
fn blob_pixmap(blob: &vectorcraft_doc::ImageBlob, touch: bool) -> Option<(images::ImageKey, Arc<Pixmap>)> {
|
||||
let (key, lut, size) = blob_key(blob);
|
||||
let pm = match lookup(&key, touch) {
|
||||
Some(pm) => pm,
|
||||
None => {
|
||||
if images::store().is_undecodable(&key.content) {
|
||||
paint::add_decode_failures(1);
|
||||
return None;
|
||||
}
|
||||
// Decoded outside the lock: other renderers carry on meanwhile.
|
||||
let pm = match lut.and_then(|lut| ink::cmyk_pixmap(blob, &lut)) {
|
||||
Some(pm) => pm,
|
||||
None => paint::decode_pixmap(&blob.bytes)?,
|
||||
None => match paint::decode_pixmap_or_why(&blob.bytes) {
|
||||
Ok(pm) => pm,
|
||||
Err(why) => {
|
||||
if why == paint::Undecoded::Unreadable {
|
||||
images::store().set_undecodable(key.content.clone());
|
||||
}
|
||||
return None;
|
||||
}
|
||||
},
|
||||
};
|
||||
images::store().insert(key.clone(), Arc::new(pm))
|
||||
}
|
||||
|
||||
+342
-24
@@ -73,6 +73,38 @@ thread_local! {
|
||||
static DECODE_FAILURES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// The decode allowance of one image on this thread in place of [`MAX_DECODE_ALLOC`], so a
|
||||
/// test can draw an image past it without decoding gigabytes.
|
||||
pub(crate) static TEST_ALLOWANCE: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
|
||||
/// The bytes [`fits_beside_pinned`] finds room for on this thread, in place of what the images
|
||||
/// paints hold in the shared store leave.
|
||||
pub(crate) static TEST_ROOM: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
|
||||
/// The images [`decode_or_reduction`] has tried to decode on this thread.
|
||||
pub(crate) static DECODE_ATTEMPTS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// The most memory decoding one image may take on this thread: [`MAX_DECODE_ALLOC`].
|
||||
fn allowance() -> u64 {
|
||||
#[cfg(test)]
|
||||
if let Some(a) = TEST_ALLOWANCE.with(std::cell::Cell::get) {
|
||||
return a;
|
||||
}
|
||||
MAX_DECODE_ALLOC
|
||||
}
|
||||
|
||||
/// Why an image has no pixels to draw ([`decode_pixmap_or_why`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Undecoded {
|
||||
/// Its pixels can't be read, at their own size or at [`reduced_size`]: decoding them again
|
||||
/// fails again.
|
||||
Unreadable,
|
||||
/// The images being painted leave no room for it within twice [`MAX_DECODE_ALLOC`]: it may
|
||||
/// be decoded once they are done.
|
||||
NoRoom,
|
||||
}
|
||||
|
||||
/// How many images have failed to decode on this thread so far: an export compares the count
|
||||
/// before and after it draws to say it left images out. Images that other threads (another export,
|
||||
/// the canvas, thumbnails) fail to decode meanwhile are not counted.
|
||||
@@ -80,36 +112,262 @@ pub fn decode_failures() -> u64 {
|
||||
DECODE_FAILURES.with(std::cell::Cell::get)
|
||||
}
|
||||
|
||||
/// `bytes` decoded within [`MAX_DECODE_ALLOC`] ([`decode_within_allowance`]); a failure is counted
|
||||
/// in [`decode_failures`].
|
||||
fn decode(bytes: &[u8]) -> Option<image::DynamicImage> {
|
||||
let img = decode_within_allowance(bytes).ok();
|
||||
if img.is_none() {
|
||||
add_decode_failures(1);
|
||||
}
|
||||
img
|
||||
/// [`decode_in_room`]'s image or error.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn decode_within_allowance(bytes: &[u8]) -> image::ImageResult<image::DynamicImage> {
|
||||
decode_in_room(bytes).map_err(|(e, _)| e)
|
||||
}
|
||||
|
||||
/// `bytes` decoded within [`MAX_DECODE_ALLOC`], counted as RGBA: the image's size is read from its
|
||||
/// header first, and an image of more than that as RGBA gets a limit error before anything is
|
||||
/// decoded (#1717).
|
||||
pub(crate) fn decode_within_allowance(bytes: &[u8]) -> image::ImageResult<image::DynamicImage> {
|
||||
/// decoded (#1717). A failure comes with why the image gave no pixels ([`room_for`]).
|
||||
fn decode_in_room(bytes: &[u8]) -> Result<image::DynamicImage, (image::ImageError, Undecoded)> {
|
||||
let allowance = allowance();
|
||||
let unreadable = |e| (e, Undecoded::Unreadable);
|
||||
let reader = || -> image::ImageResult<_> {
|
||||
let mut r = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format()?;
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(MAX_DECODE_ALLOC);
|
||||
limits.max_alloc = Some(allowance);
|
||||
r.limits(limits);
|
||||
Ok(r)
|
||||
};
|
||||
let (w, h) = reader()?.into_dimensions()?;
|
||||
let (w, h) = reader().and_then(|r| r.into_dimensions()).map_err(unreadable)?;
|
||||
let bytes = (u64::from(w) * u64::from(h)).saturating_mul(4);
|
||||
// The images paints hold can't be evicted from the cache, so a document of many images held
|
||||
// them all at once: a new one is decoded only while those and it fit twice the allowance.
|
||||
let pinned = crate::images::store().pinned_bytes() as u64;
|
||||
if bytes > MAX_DECODE_ALLOC || bytes.saturating_add(pinned) > 2 * MAX_DECODE_ALLOC {
|
||||
return Err(image::ImageError::Limits(image::error::LimitError::from_kind(image::error::LimitErrorKind::InsufficientMemory)));
|
||||
if let Err(why) = room_for(bytes, pinned) {
|
||||
return Err((image::ImageError::Limits(image::error::LimitError::from_kind(image::error::LimitErrorKind::InsufficientMemory)), why));
|
||||
}
|
||||
reader().and_then(|r| r.decode()).map_err(unreadable)
|
||||
}
|
||||
|
||||
/// Whether an image of `rgba` bytes may be decoded while the images being painted hold `pinned`
|
||||
/// bytes: within the allowance itself, and within twice [`MAX_DECODE_ALLOC`] with them. An image
|
||||
/// over the allowance may still be decoded at [`reduced_size`].
|
||||
fn room_for(rgba: u64, pinned: u64) -> Result<(), Undecoded> {
|
||||
if rgba > allowance() {
|
||||
Err(Undecoded::Unreadable)
|
||||
} else if rgba.saturating_add(pinned) > 2 * MAX_DECODE_ALLOC {
|
||||
Err(Undecoded::NoRoom)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `bytes` of decoded pixels fit beside the images paints hold, which can't be evicted from
|
||||
/// the cache: a new image is decoded only while those and it fit twice [`MAX_DECODE_ALLOC`].
|
||||
fn fits_beside_pinned(bytes: u64) -> bool {
|
||||
#[cfg(test)]
|
||||
if let Some(room) = TEST_ROOM.with(std::cell::Cell::get) {
|
||||
return bytes <= room;
|
||||
}
|
||||
let pinned = crate::images::store().pinned_bytes() as u64;
|
||||
bytes.saturating_add(pinned) <= 2 * MAX_DECODE_ALLOC
|
||||
}
|
||||
|
||||
/// The size at which [`decode_pixmap_or_why`] decodes encoded image `bytes` that take more than
|
||||
/// [`MAX_DECODE_ALLOC`] as RGBA, or whose decoded samples do (16 bits a sample): the largest that
|
||||
/// fits it as RGBA, keeping its proportions, at most the image's own size, with sides of at most
|
||||
/// `u16::MAX` pixels. `None` for an image within the allowance and for one that isn't decoded at
|
||||
/// all: an image that isn't a PNG, JPEG, GIF or WebP; an image of more pixels than the allowance
|
||||
/// has bytes (2,147,483,648 pixels, or 536,870,912 in the web app; 46,341 × 46,341 is more); and an
|
||||
/// image whose decoded samples take more than the allowance, unless it is a PNG that isn't
|
||||
/// interlaced and is at most the allowance divided by [`ROW_SCRATCH`] pixels wide (read a row at a
|
||||
/// time).
|
||||
pub fn reduced_size(bytes: &[u8]) -> Option<(u32, u32)> {
|
||||
reduction(bytes, allowance()).map(|r| r.to)
|
||||
}
|
||||
|
||||
/// How [`decode_pixmap_or_why`] reads an image past the decode allowance ([`reduced_size`]).
|
||||
struct Reduction {
|
||||
/// The image's size in pixels.
|
||||
size: (u32, u32),
|
||||
/// The size it is decoded at.
|
||||
to: (u32, u32),
|
||||
/// Read a row at a time (a PNG that isn't interlaced) rather than decoded whole first.
|
||||
rows: bool,
|
||||
/// The bytes reading the image takes besides the result: the PNG reader's row buffers, or the
|
||||
/// image decoded whole and a band of its rows as RGBA.
|
||||
scratch: u64,
|
||||
}
|
||||
|
||||
/// [`reduced_size`]'s reading of `bytes` within `allowance`.
|
||||
fn reduction(bytes: &[u8], allowance: u64) -> Option<Reduction> {
|
||||
use image::ImageDecoder as _;
|
||||
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?;
|
||||
let format = reader.format()?;
|
||||
if !matches!(format, image::ImageFormat::Png | image::ImageFormat::Jpeg | image::ImageFormat::Gif | image::ImageFormat::WebP) {
|
||||
return None;
|
||||
}
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(allowance);
|
||||
reader.limits(limits);
|
||||
let d = reader.into_decoder().ok()?;
|
||||
let (w, h) = d.dimensions();
|
||||
let pixels = u64::from(w) * u64::from(h);
|
||||
// An image of more pixels than the allowance has bytes (four times what it holds as RGBA) is
|
||||
// not read.
|
||||
if pixels == 0 || pixels > allowance || (pixels.saturating_mul(4) <= allowance && d.total_bytes() <= allowance) {
|
||||
return None;
|
||||
}
|
||||
let to = fitted_dims(w, h, allowance)?;
|
||||
// The PNG reader's row buffers take at most `ROW_SCRATCH` bytes a column, also within the allowance.
|
||||
let rows = format == image::ImageFormat::Png
|
||||
&& u64::from(w).saturating_mul(ROW_SCRATCH) <= allowance
|
||||
&& png_reader(bytes).is_some_and(|r| !r.info().interlaced);
|
||||
let scratch = if rows {
|
||||
u64::from(w) * ROW_SCRATCH
|
||||
} else {
|
||||
let band = u64::from(BAND) * u64::from(w) * (u64::from(d.color_type().bytes_per_pixel()) + 4);
|
||||
d.total_bytes().saturating_add(band)
|
||||
};
|
||||
(rows || d.total_bytes() <= allowance).then_some(Reduction { size: (w, h), to, rows, scratch })
|
||||
}
|
||||
|
||||
/// How many rows of an image decoded whole [`reduced_pixmap`] converts to RGBA at a time.
|
||||
const BAND: u32 = 16;
|
||||
|
||||
/// The most memory a column of a PNG read a row at a time takes in the reader's row buffers: the
|
||||
/// row as stored (up to 8 bytes a pixel and a filter byte), the row before it, and the row given
|
||||
/// out (up to 4 bytes a pixel).
|
||||
const ROW_SCRATCH: u64 = 32;
|
||||
|
||||
/// The largest size of at most `w`×`h` pixels, keeping their proportions, whose pixels take at most
|
||||
/// `allowance` bytes as RGBA, with sides of at most `u16::MAX` pixels.
|
||||
fn fitted_dims(w: u32, h: u32, allowance: u64) -> Option<(u32, u32)> {
|
||||
let pixels = u64::from(w) * u64::from(h);
|
||||
let s = ((allowance / 4) as f64 / pixels as f64).sqrt().min(u16::MAX as f64 / w.max(h) as f64).min(1.0);
|
||||
let side = |n: u32| ((n as f64 * s).floor() as u32).clamp(1, u16::MAX as u32);
|
||||
let (mut nw, mut nh) = (side(w), side(h));
|
||||
// Rounding can leave the product a pixel over: take a pixel off the longer side.
|
||||
while u64::from(nw) * u64::from(nh) * 4 > allowance && (nw > 1 || nh > 1) {
|
||||
if nw >= nh { nw -= 1 } else { nh -= 1 }
|
||||
}
|
||||
(u64::from(nw) * u64::from(nh) * 4 <= allowance).then_some((nw, nh))
|
||||
}
|
||||
|
||||
/// A PNG reader of `bytes` that gives 8-bit gray, gray with alpha, RGB or RGBA rows, with its
|
||||
/// header and the chunks before the pixels read.
|
||||
fn png_reader(bytes: &[u8]) -> Option<png::Reader<std::io::Cursor<&[u8]>>> {
|
||||
let mut d = png::Decoder::new(std::io::Cursor::new(bytes));
|
||||
d.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
|
||||
d.read_info().ok()
|
||||
}
|
||||
|
||||
/// `bytes` decoded at the size [`reduction`] gives. Each pixel of the result is the mean of the
|
||||
/// image's pixels it covers. [`Undecoded::Unreadable`] when they can't be read, and
|
||||
/// [`Undecoded::NoRoom`] when the result and what reading takes ([`Reduction::scratch`]) don't fit
|
||||
/// beside the images paints hold.
|
||||
fn reduced_pixmap(bytes: &[u8], r: &Reduction) -> Result<vello_cpu::Pixmap, Undecoded> {
|
||||
let (tw, th) = r.to;
|
||||
if !fits_beside_pinned((u64::from(tw) * u64::from(th) * 4).saturating_add(r.scratch)) {
|
||||
return Err(Undecoded::NoRoom);
|
||||
}
|
||||
shrunk(bytes, r).ok_or(Undecoded::Unreadable)
|
||||
}
|
||||
|
||||
/// `bytes` read and shrunk as [`reduced_pixmap`] says.
|
||||
fn shrunk(bytes: &[u8], r: &Reduction) -> Option<vello_cpu::Pixmap> {
|
||||
let mut shrink = Shrink::new(r.size, r.to);
|
||||
if r.rows {
|
||||
let mut reader = png_reader(bytes)?;
|
||||
let (color, _) = reader.output_color_type();
|
||||
while let Some(row) = reader.next_row().ok()? {
|
||||
let data = row.data();
|
||||
match color {
|
||||
png::ColorType::Grayscale => shrink.row(data.iter().map(|&g| [g, g, g, 255])),
|
||||
png::ColorType::GrayscaleAlpha => shrink.row(data.as_chunks::<2>().0.iter().map(|&[g, a]| [g, g, g, a])),
|
||||
png::ColorType::Rgb => shrink.row(data.as_chunks::<3>().0.iter().map(|&[r, g, b]| [r, g, b, 255])),
|
||||
png::ColorType::Rgba => shrink.row(data.as_chunks::<4>().0.iter().copied()),
|
||||
png::ColorType::Indexed => return None,
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?;
|
||||
let mut limits = image::Limits::default();
|
||||
limits.max_alloc = Some(allowance());
|
||||
reader.limits(limits);
|
||||
let img = reader.decode().ok()?;
|
||||
let (w, h) = (img.width(), img.height());
|
||||
for y in (0..h).step_by(BAND as usize) {
|
||||
let band = img.crop_imm(0, y, w, BAND.min(h - y)).to_rgba8();
|
||||
band.as_raw().as_chunks::<4>().0.chunks_exact(w as usize).for_each(|row| shrink.row(row.iter().copied()));
|
||||
}
|
||||
}
|
||||
shrink.finish()
|
||||
}
|
||||
|
||||
/// An image shrunk as its RGBA rows are given ([`Shrink::row`]): each pixel of the result is the
|
||||
/// mean of the image's pixels it covers, premultiplied.
|
||||
struct Shrink {
|
||||
/// The image's size.
|
||||
size: (u32, u32),
|
||||
/// The result's size.
|
||||
to: (u32, u32),
|
||||
/// The sums of the result row being made, a pixel each: red, green and blue times alpha, and
|
||||
/// alpha.
|
||||
sums: Vec<[u64; 4]>,
|
||||
/// How many of the image's pixels each pixel of that row has.
|
||||
counts: Vec<u64>,
|
||||
/// The result row being made, and the next row of the image.
|
||||
at: (u32, u32),
|
||||
/// The finished rows.
|
||||
out: Vec<vello_cpu::color::PremulRgba8>,
|
||||
}
|
||||
|
||||
impl Shrink {
|
||||
fn new(size: (u32, u32), to: (u32, u32)) -> Self {
|
||||
let n = to.0 as usize;
|
||||
Self { size, to, sums: vec![[0; 4]; n], counts: vec![0; n], at: (0, 0), out: Vec::with_capacity(n * to.1 as usize) }
|
||||
}
|
||||
|
||||
/// Add the image's next row of RGBA pixels (pixels past its width are left out).
|
||||
fn row(&mut self, rgba: impl IntoIterator<Item = [u8; 4]>) {
|
||||
if self.at.1 >= self.size.1 {
|
||||
return;
|
||||
}
|
||||
let ty = (u64::from(self.at.1) * u64::from(self.to.1) / u64::from(self.size.1)) as u32;
|
||||
if ty != self.at.0 {
|
||||
self.flush();
|
||||
self.at.0 = ty;
|
||||
}
|
||||
let (w, tw) = (u64::from(self.size.0), u64::from(self.to.0));
|
||||
for (x, p) in (0..w).zip(rgba) {
|
||||
// `tx` is the result column that the image's column `x` falls in.
|
||||
let tx = (x * tw / w) as usize;
|
||||
let a = u64::from(p[3]);
|
||||
if let Some(s) = self.sums.get_mut(tx) {
|
||||
s[0] += u64::from(p[0]) * a;
|
||||
s[1] += u64::from(p[1]) * a;
|
||||
s[2] += u64::from(p[2]) * a;
|
||||
s[3] += a;
|
||||
}
|
||||
if let Some(c) = self.counts.get_mut(tx) {
|
||||
*c += 1;
|
||||
}
|
||||
}
|
||||
self.at.1 += 1;
|
||||
}
|
||||
|
||||
/// Finish the result row being made.
|
||||
fn flush(&mut self) {
|
||||
for (s, n) in self.sums.iter_mut().zip(&mut self.counts) {
|
||||
let k = (*n).max(1);
|
||||
let mean = |v: u64, d: u64| ((v + d / 2) / d).min(255) as u8;
|
||||
self.out.push(vello_cpu::color::PremulRgba8 { r: mean(s[0], 255 * k), g: mean(s[1], 255 * k), b: mean(s[2], 255 * k), a: mean(s[3], k) });
|
||||
*s = [0; 4];
|
||||
*n = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// The shrunk image once every row of the image was given.
|
||||
fn finish(mut self) -> Option<vello_cpu::Pixmap> {
|
||||
if self.at.1 < self.size.1 {
|
||||
return None;
|
||||
}
|
||||
self.flush();
|
||||
let (w, h) = (u16::try_from(self.to.0).ok()?, u16::try_from(self.to.1).ok()?);
|
||||
(self.out.len() == w as usize * h as usize).then(|| vello_cpu::Pixmap::from_parts(self.out, w, h))
|
||||
}
|
||||
reader()?.decode()
|
||||
}
|
||||
|
||||
/// `img` shrunk, keeping its proportions, to fit a pixmap's sides (at most `u16::MAX` pixels).
|
||||
@@ -124,14 +382,59 @@ fn fit_pixmap(img: image::DynamicImage) -> image::DynamicImage {
|
||||
img.resize_exact(nw, nh, image::imageops::FilterType::Triangle)
|
||||
}
|
||||
|
||||
/// Decode encoded image bytes into a premultiplied pixmap (shrunk to fit a pixmap's sides).
|
||||
/// [`decode_pixmap_or_why`]'s pixels.
|
||||
#[cfg(test)]
|
||||
pub fn decode_pixmap(bytes: &[u8]) -> Option<vello_cpu::Pixmap> {
|
||||
pixmap_of(fit_pixmap(decode(bytes)?).to_rgba8())
|
||||
decode_pixmap_or_why(bytes).ok()
|
||||
}
|
||||
|
||||
/// [`decode_pixmap`] shrunk to `w`×`h` pixels when the image is larger (never enlarged).
|
||||
/// Decode encoded image bytes into a premultiplied pixmap (shrunk to fit a pixmap's sides), or say
|
||||
/// why there are no pixels. An image that takes more than the allowance as RGBA is decoded at
|
||||
/// [`reduced_size`] when it has one; a failure is counted in [`decode_failures`].
|
||||
pub(crate) fn decode_pixmap_or_why(bytes: &[u8]) -> Result<vello_cpu::Pixmap, Undecoded> {
|
||||
counted(match decode_or_reduction(bytes) {
|
||||
Ok(img) => pixmap_of(fit_pixmap(img).to_rgba8()).ok_or(Undecoded::Unreadable),
|
||||
Err(r) => r.and_then(|r| reduced_pixmap(bytes, &r)),
|
||||
})
|
||||
}
|
||||
|
||||
/// `bytes` decoded within the allowance ([`decode_in_room`]), or, when it refuses them for their
|
||||
/// size, how [`reduced_pixmap`] reads them past it; otherwise why there is no image.
|
||||
fn decode_or_reduction(bytes: &[u8]) -> Result<image::DynamicImage, Result<Reduction, Undecoded>> {
|
||||
#[cfg(test)]
|
||||
DECODE_ATTEMPTS.with(|n| n.set(n.get() + 1));
|
||||
match decode_in_room(bytes) {
|
||||
Ok(img) => Ok(img),
|
||||
Err((image::ImageError::Limits(_), Undecoded::Unreadable)) => Err(reduction(bytes, allowance()).ok_or(Undecoded::Unreadable)),
|
||||
Err((_, why)) => Err(Err(why)),
|
||||
}
|
||||
}
|
||||
|
||||
/// `pm`, with a failure counted in [`decode_failures`] when there is none.
|
||||
fn counted(pm: Result<vello_cpu::Pixmap, Undecoded>) -> Result<vello_cpu::Pixmap, Undecoded> {
|
||||
if pm.is_err() {
|
||||
add_decode_failures(1);
|
||||
}
|
||||
pm
|
||||
}
|
||||
|
||||
/// [`decode_pixmap_or_why`] shrunk to `w`×`h` pixels when the image is larger (never enlarged). An
|
||||
/// image past the decode allowance is decoded straight at `w`×`h` when that is no larger on either
|
||||
/// side and fits the allowance, otherwise at [`reduced_size`].
|
||||
pub fn decode_pixmap_fit(bytes: &[u8], w: u16, h: u16) -> Option<vello_cpu::Pixmap> {
|
||||
let img = decode(bytes)?;
|
||||
let img = match decode_or_reduction(bytes) {
|
||||
Ok(img) => img,
|
||||
Err(r) => {
|
||||
return counted(r.and_then(|mut r| {
|
||||
let fit = (u32::from(w).max(1), u32::from(h).max(1));
|
||||
if fit.0 <= r.to.0 && fit.1 <= r.to.1 {
|
||||
r.to = fit;
|
||||
}
|
||||
reduced_pixmap(bytes, &r)
|
||||
}))
|
||||
.ok();
|
||||
}
|
||||
};
|
||||
let img = if img.width() > w as u32 || img.height() > h as u32 {
|
||||
img.resize_exact(w as u32, h as u32, image::imageops::FilterType::Triangle)
|
||||
} else {
|
||||
@@ -140,9 +443,9 @@ pub fn decode_pixmap_fit(bytes: &[u8], w: u16, h: u16) -> Option<vello_cpu::Pixm
|
||||
pixmap_of(img.to_rgba8())
|
||||
}
|
||||
|
||||
/// Count `n` images that couldn't be decoded on this thread ([`decode_failures`]). [`decode`]
|
||||
/// counts each failure, and a raster kept in a cache counts the failures it was drawn with again
|
||||
/// each time it is drawn.
|
||||
/// Count `n` images that couldn't be decoded on this thread ([`decode_failures`]).
|
||||
/// [`decode_pixmap_or_why`] and [`decode_pixmap_fit`] count each failure, and a raster kept in a cache
|
||||
/// counts the failures it was drawn with again each time it is drawn.
|
||||
pub(crate) fn add_decode_failures(n: u64) {
|
||||
DECODE_FAILURES.with(|c| c.set(c.get() + n));
|
||||
}
|
||||
@@ -163,3 +466,18 @@ fn pixmap_of(img: image::RgbaImage) -> Option<vello_cpu::Pixmap> {
|
||||
.collect();
|
||||
Some(vello_cpu::Pixmap::from_parts(data, w as u16, h as u16))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// An image over the allowance as RGBA never fits, so it is noted as undecodable; one that only
|
||||
/// the images being painted leave no room for is not, and is tried again later.
|
||||
#[test]
|
||||
fn only_the_room_painted_images_take_is_tried_again() {
|
||||
assert_eq!(room_for(MAX_DECODE_ALLOC + 1, 0), Err(Undecoded::Unreadable));
|
||||
assert_eq!(room_for(MAX_DECODE_ALLOC + 1, 2 * MAX_DECODE_ALLOC), Err(Undecoded::Unreadable));
|
||||
assert_eq!(room_for(MAX_DECODE_ALLOC, MAX_DECODE_ALLOC + 1), Err(Undecoded::NoRoom));
|
||||
assert_eq!(room_for(MAX_DECODE_ALLOC, MAX_DECODE_ALLOC), Ok(()));
|
||||
}
|
||||
}
|
||||
@@ -8,9 +8,12 @@
|
||||
//! it shows is cached as a bitmap per file and zoom step (a power of two, in device pixels per
|
||||
//! point), shared by every object showing that file. A bitmap not made yet is made on a
|
||||
//! background worker while the frame shows another step's bitmap, or a light placeholder;
|
||||
//! [`generation`] changes when one is ready and [`busy`] says whether any is coming, so the screen
|
||||
//! can draw again. Past [`MAX_SIDE`] pixels, and in outline, proofing and ink frames, it is drawn
|
||||
//! exactly.
|
||||
//! [`generation`] changes when one is ready, [`made_between`] says for which files, and [`busy`]
|
||||
//! says whether any is coming, so the screen can draw again where those files show
|
||||
//! ([`crate::placed_area`]). Bitmaps drawn since a frame began are not dropped to make room for
|
||||
//! the ones it asks for, up to [`MAX_BYTES`], and a bitmap that can't be made is not asked for
|
||||
//! again. Past [`MAX_SIDE`] pixels, past [`MAX_BYTES`], and in outline, proofing and ink frames,
|
||||
//! it is drawn exactly.
|
||||
//!
|
||||
//! A document opened with only its placed documents' previews ([`ImageBlob::is_proxy`]) shows them
|
||||
//! up to their resolution; past it the file is read again in the background
|
||||
@@ -19,7 +22,7 @@
|
||||
//! same way, up to [`MAX_DEPTH`] deep; deeper ones show their previews.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, LazyLock, Mutex, MutexGuard, PoisonError};
|
||||
|
||||
@@ -33,8 +36,12 @@ use crate::{Frame, Renderer};
|
||||
|
||||
/// The longest side of a cached bitmap (pixels); larger steps draw exactly.
|
||||
pub const MAX_SIDE: f64 = 4096.0;
|
||||
/// The most bytes of bitmaps kept.
|
||||
/// The bytes of bitmaps kept, past which those not drawn since the frame that asks for another
|
||||
/// one began are dropped.
|
||||
const BUDGET: usize = 512 << 20;
|
||||
/// The most bytes of bitmaps kept, those drawn in the frame included: a bitmap that would take
|
||||
/// them past it is not kept, and its file draws exactly at that zoom step.
|
||||
const MAX_BYTES: usize = 4 * BUDGET;
|
||||
/// The smallest zoom step (device pixels per point).
|
||||
const MIN_STEP: f64 = 1.0 / 64.0;
|
||||
|
||||
@@ -57,7 +64,19 @@ struct Bitmaps {
|
||||
static BITMAPS: LazyLock<Mutex<Bitmaps>> = LazyLock::new(Default::default);
|
||||
/// Bitmaps being made.
|
||||
static PENDING: LazyLock<Mutex<HashSet<BitmapKey>>> = LazyLock::new(Default::default);
|
||||
/// Bitmaps that could not be made (neither the file nor a preview could be read): not asked for
|
||||
/// again.
|
||||
static FAILED: LazyLock<Mutex<HashSet<BitmapKey>>> = LazyLock::new(Default::default);
|
||||
/// Bitmaps made but not kept, past [`MAX_BYTES`]: their files draw exactly at those zoom steps.
|
||||
static UNKEPT: LazyLock<Mutex<HashSet<BitmapKey>>> = LazyLock::new(Default::default);
|
||||
static GENERATION: AtomicU64 = AtomicU64::new(0);
|
||||
/// The files of the last [`MADE_KEPT`] bitmaps made, each with the [`generation`] it gave.
|
||||
static MADE: LazyLock<Mutex<VecDeque<(u64, String)>>> = LazyLock::new(Default::default);
|
||||
/// How many bitmaps [`MADE`] keeps.
|
||||
const MADE_KEPT: usize = 256;
|
||||
/// How many bitmaps of each file were asked for (tests).
|
||||
#[cfg(test)]
|
||||
static SCHEDULED: LazyLock<Mutex<HashMap<String, usize>>> = LazyLock::new(Default::default);
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
// The caches stay whole if a holder panicked (entries are only inserted and removed).
|
||||
@@ -65,11 +84,35 @@ fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
|
||||
}
|
||||
|
||||
/// Changes whenever a bitmap made in the background is ready: a screen showing placed documents
|
||||
/// draws again when it does.
|
||||
/// draws again when it does, where [`made_between`] says.
|
||||
pub fn generation() -> u64 {
|
||||
GENERATION.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The files whose bitmaps were made after [`generation`] `from`, up to `to`: a screen drawn at
|
||||
/// `from` draws again where they show ([`crate::placed_area`]). None when they are no longer
|
||||
/// known (more than [`MADE_KEPT`] bitmaps were made since).
|
||||
pub fn made_between(from: u64, to: u64) -> Option<HashSet<String>> {
|
||||
let made = lock(&MADE);
|
||||
let oldest = made.front().map_or(u64::MAX, |(g, _)| *g);
|
||||
if to > from && oldest > from.saturating_add(1) {
|
||||
return None;
|
||||
}
|
||||
Some(made.iter().filter(|(g, _)| *g > from && *g <= to).map(|(_, key)| key.clone()).collect())
|
||||
}
|
||||
|
||||
/// A bitmap of file `key` is ready: the generation changes, and [`MADE`] records which file
|
||||
/// changed it. Both happen under [`MADE`]'s lock, so a generation read is in [`MADE`] by the time
|
||||
/// [`made_between`] reads it.
|
||||
fn made(key: &str) {
|
||||
let mut made = lock(&MADE);
|
||||
let g = GENERATION.fetch_add(1, Ordering::Relaxed).wrapping_add(1);
|
||||
made.push_back((g, key.to_owned()));
|
||||
while made.len() > MADE_KEPT {
|
||||
made.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
/// Are bitmaps being made in the background?
|
||||
pub fn busy() -> bool {
|
||||
!lock(&PENDING).is_empty()
|
||||
@@ -81,6 +124,18 @@ pub(crate) fn pending_for(key: &str) -> bool {
|
||||
lock(&PENDING).iter().any(|k| k.0 == key)
|
||||
}
|
||||
|
||||
/// How many bitmaps of file `key` were asked for.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn scheduled(key: &str) -> usize {
|
||||
lock(&SCHEDULED).get(key).copied().unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Mark the bitmap of file `key` at zoom `step` as not kept past [`MAX_BYTES`].
|
||||
#[cfg(test)]
|
||||
pub(crate) fn mark_unkept(key: &str, step: f64) {
|
||||
lock(&UNKEPT).insert((key.to_string(), step.to_bits()));
|
||||
}
|
||||
|
||||
/// The zoom step for `scale` device pixels per point: the power of two at or above it.
|
||||
pub(crate) fn step(scale: f64) -> Option<f64> {
|
||||
(scale.is_finite() && scale > 0.0).then(|| 2f64.powf(scale.log2().ceil()).max(MIN_STEP))
|
||||
@@ -104,19 +159,33 @@ impl Bitmaps {
|
||||
.map(|(_, b)| (b.pm.clone(), b.step))
|
||||
}
|
||||
|
||||
fn insert(&mut self, k: BitmapKey, pm: Pixmap, step: f64) {
|
||||
/// Keep `pm` as bitmap `k`, and past `budget` bytes drop the bitmaps drawn least recently,
|
||||
/// but not those drawn or made since clock `keep` (when the frame that asked for `k` began),
|
||||
/// which stay even past it. When the bitmaps would still be past `max` bytes, `k` is not kept:
|
||||
/// false.
|
||||
fn insert(&mut self, k: BitmapKey, pm: Pixmap, step: f64, keep: u64, (budget, max): (usize, usize)) -> bool {
|
||||
self.clock += 1;
|
||||
let size = pm.width() as usize * pm.height() as usize * 4;
|
||||
self.bytes += size;
|
||||
if let Some(old) = self.map.insert(k, Bitmap { pm: Arc::new(pm), step, used: self.clock }) {
|
||||
if let Some(old) = self.map.insert(k.clone(), Bitmap { pm: Arc::new(pm), step, used: self.clock }) {
|
||||
self.bytes = self.bytes.saturating_sub(old.pm.width() as usize * old.pm.height() as usize * 4);
|
||||
}
|
||||
while self.bytes > BUDGET && self.map.len() > 1 {
|
||||
let Some(k) = self.map.iter().min_by_key(|(_, b)| b.used).map(|(k, _)| k.clone()) else { break };
|
||||
while self.bytes > budget {
|
||||
let Some(k) = self.map.iter().filter(|(key, b)| b.used <= keep && **key != k).min_by_key(|(_, b)| b.used).map(|(key, _)| key.clone())
|
||||
else {
|
||||
break;
|
||||
};
|
||||
if let Some(b) = self.map.remove(&k) {
|
||||
self.bytes = self.bytes.saturating_sub(b.pm.width() as usize * b.pm.height() as usize * 4);
|
||||
}
|
||||
}
|
||||
if self.bytes <= max {
|
||||
return true;
|
||||
}
|
||||
if self.map.remove(&k).is_some() {
|
||||
self.bytes = self.bytes.saturating_sub(size);
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,6 +206,8 @@ struct Job {
|
||||
object: PlacedDocument,
|
||||
blob: ImageBlob,
|
||||
step: f64,
|
||||
/// The bitmap clock when the frame that asked for it began ([`Bitmaps::insert`]).
|
||||
keep: u64,
|
||||
/// The scheduler's file-access scope, which the worker runs the job in.
|
||||
scope: Option<Scoped>,
|
||||
}
|
||||
@@ -204,15 +275,24 @@ fn pixels(v: f64) -> u16 {
|
||||
v.round().clamp(1.0, MAX_SIDE) as u16
|
||||
}
|
||||
|
||||
/// Make `job`'s bitmap and keep it.
|
||||
/// Make `job`'s bitmap and keep it (or remember that it was not kept), or remember that it can't
|
||||
/// be made. The generation changes before the job stops being pending, so a screen that sees
|
||||
/// nothing pending sees the change.
|
||||
fn run(r: &mut Renderer, mut job: Job) {
|
||||
let scope = job.scope.take();
|
||||
let mut body = || {
|
||||
if let Some(pm) = make(r, &job.object, &job.blob, job.step) {
|
||||
lock(&BITMAPS).insert(job.key.clone(), pm, job.step);
|
||||
match make(r, &job.object, &job.blob, job.step) {
|
||||
Some(pm) => {
|
||||
if !lock(&BITMAPS).insert(job.key.clone(), pm, job.step, job.keep, (BUDGET, MAX_BYTES)) {
|
||||
lock(&UNKEPT).insert(job.key.clone());
|
||||
}
|
||||
made(&job.key.0);
|
||||
}
|
||||
None => {
|
||||
lock(&FAILED).insert(job.key.clone());
|
||||
}
|
||||
}
|
||||
lock(&PENDING).remove(&job.key);
|
||||
GENERATION.fetch_add(1, Ordering::Relaxed);
|
||||
};
|
||||
match scope {
|
||||
Some(scoped) => scoped(&mut body),
|
||||
@@ -241,9 +321,10 @@ mod workers {
|
||||
loop {
|
||||
let job = super::lock(&rx).recv();
|
||||
let Ok(job) = job else { break };
|
||||
// A panic loses this bitmap, not the worker.
|
||||
// A panic loses this bitmap, not the worker; it is not asked for again.
|
||||
let key = job.key.clone();
|
||||
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| super::run(&mut r, *job))).is_err() {
|
||||
super::lock(&super::FAILED).insert(key.clone());
|
||||
super::lock(&super::PENDING).remove(&key);
|
||||
}
|
||||
}
|
||||
@@ -267,6 +348,10 @@ fn schedule(job: Job) {
|
||||
if !lock(&PENDING).insert(job.key.clone()) {
|
||||
return;
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
*lock(&SCHEDULED).entry(job.key.0.clone()).or_default() += 1;
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let job = match workers::submit(Box::new(job)) {
|
||||
Ok(()) => return,
|
||||
@@ -318,8 +403,9 @@ impl Renderer {
|
||||
self.draw_arc(ctx, &inner, &e.art);
|
||||
}
|
||||
|
||||
/// Draw `p` from its bitmap at this zoom step, or (while that is made) another step's, or a
|
||||
/// placeholder. False when bitmaps don't suit (too large).
|
||||
/// Draw `p` from its bitmap at this zoom step, or (while that is made, or when it can't be)
|
||||
/// another step's, or a placeholder. False when bitmaps don't suit (too large, or not kept
|
||||
/// past [`MAX_BYTES`]).
|
||||
fn draw_placed_bitmap(&mut self, ctx: &mut RenderContext, f: &Frame, p: &PlacedDocument) -> bool {
|
||||
let m = f.view * p.xf;
|
||||
let Some(step) = step(mean_scale(m)) else { return false };
|
||||
@@ -328,16 +414,24 @@ impl Renderer {
|
||||
}
|
||||
let Some(blob) = f.doc.images.get(&p.key).cloned() else { return true };
|
||||
let key = (p.key.clone(), step.to_bits());
|
||||
let (found, nearest) = {
|
||||
// Not kept past [`MAX_BYTES`]: drawn exactly.
|
||||
if lock(&UNKEPT).contains(&key) {
|
||||
return false;
|
||||
}
|
||||
let (found, nearest, keep) = {
|
||||
let mut b = lock(&BITMAPS);
|
||||
// The clock when this frame first drew a placed document's bitmap.
|
||||
let keep = *self.placed_frame.get_or_insert(b.clock);
|
||||
let found = b.get(&key);
|
||||
let nearest = if found.is_none() { b.nearest(&p.key, step) } else { None };
|
||||
(found, nearest)
|
||||
(found, nearest, keep)
|
||||
};
|
||||
let shown = match found {
|
||||
Some(pm) => Some(pm),
|
||||
// It can't be made: another step's, or the placeholder.
|
||||
None if lock(&FAILED).contains(&key) => nearest.map(|n| n.0),
|
||||
None => {
|
||||
schedule(Job { key, object: p.clone(), blob, step, scope: SCOPE_CAPTURE.get().map(|capture| capture()) });
|
||||
schedule(Job { key, object: p.clone(), blob, step, keep, scope: SCOPE_CAPTURE.get().map(|capture| capture()) });
|
||||
// Made here and now (no threads) or meanwhile another step's.
|
||||
let mut b = lock(&BITMAPS);
|
||||
b.get(&(p.key.clone(), step.to_bits())).or(nearest.map(|n| n.0))
|
||||
@@ -354,7 +448,7 @@ impl Renderer {
|
||||
ctx.reset_paint_transform();
|
||||
}
|
||||
None => {
|
||||
// Coming: a light box where it will be.
|
||||
// Coming, or it can't be made: a light box where it shows.
|
||||
ctx.set_transform(m);
|
||||
ctx.set_paint(peniko::Color::from_rgba8(128, 128, 128, 40));
|
||||
ctx.fill_rect(&kurbo::Rect::new(rect.x0, rect.y0, rect.x1, rect.y1));
|
||||
@@ -378,4 +472,31 @@ mod tests {
|
||||
assert_eq!(step(f64::NAN), None);
|
||||
assert_eq!(step(0.0), None);
|
||||
}
|
||||
|
||||
/// Past the budget, the bitmaps drawn least recently are dropped, but not those drawn since
|
||||
/// the frame that asked for the new one began; past the most, the new one is not kept.
|
||||
#[test]
|
||||
fn bitmaps_drawn_in_the_frame_stay_up_to_the_most_kept() {
|
||||
let mut b = Bitmaps::default();
|
||||
// 400 bytes each: a budget of 1,000 bytes and at most 2,000.
|
||||
let limits = (1000, 2000);
|
||||
let key = |name: &str| (name.to_string(), 1f64.to_bits());
|
||||
for name in ["a", "b", "c"] {
|
||||
assert!(b.insert(key(name), Pixmap::new(10, 10), 1.0, 0, limits));
|
||||
}
|
||||
assert_eq!(b.bytes, 1200, "all made in the frame: kept past the budget");
|
||||
// The next frame begins and draws "a", then asks for "d".
|
||||
let frame = b.clock;
|
||||
assert!(b.get(&key("a")).is_some());
|
||||
assert!(b.insert(key("d"), Pixmap::new(10, 10), 1.0, frame, limits));
|
||||
let mut kept: Vec<&str> = b.map.keys().map(|(name, _)| name.as_str()).collect();
|
||||
kept.sort_unstable();
|
||||
assert_eq!((kept, b.bytes), (vec!["a", "d"], 800), "b and c, not drawn since, are dropped");
|
||||
for name in ["e", "f", "g"] {
|
||||
assert!(b.insert(key(name), Pixmap::new(10, 10), 1.0, frame, limits), "{name}");
|
||||
}
|
||||
assert_eq!(b.bytes, 2000);
|
||||
assert!(!b.insert(key("h"), Pixmap::new(10, 10), 1.0, frame, limits), "past the most: not kept");
|
||||
assert!(!b.map.contains_key(&key("h")) && b.bytes == 2000);
|
||||
}
|
||||
}
|
||||
+202
-1
@@ -930,7 +930,9 @@ fn tiff_header(w: u32, h: u32) -> Vec<u8> {
|
||||
|
||||
/// The decode allowance (2 GB) counts an image's pixels as RGBA, read from its header (#1717): a
|
||||
/// 1-bit gray image whose 8-bit gray pixels are within it but whose RGBA is over it is not decoded
|
||||
/// and draws nothing, counted for an export to report; one a column narrower goes on to decoding.
|
||||
/// whole, and one a column narrower goes on to decoding. `decode_pixmap` reads the larger one at
|
||||
/// reduced size; this header has no rows to read, so it draws nothing, counted for an export to
|
||||
/// report.
|
||||
#[test]
|
||||
fn an_image_too_large_as_rgba_is_not_decoded() {
|
||||
let over = paint::decode_within_allowance(&png_header(23_171, 23_170));
|
||||
@@ -946,6 +948,87 @@ fn an_image_too_large_as_rgba_is_not_decoded() {
|
||||
assert!(matches!(huge, Err(image::ImageError::Limits(_))), "{huge:?}");
|
||||
}
|
||||
|
||||
/// A PNG of `w` × `h` noisy pixels cut off halfway through its bytes: its header reads, and its
|
||||
/// pixels can't be decoded.
|
||||
fn truncated_png(w: u32, h: u32) -> Vec<u8> {
|
||||
let img = image::RgbaImage::from_fn(w, h, |x, y| {
|
||||
let v = (x * 7919 + y * 104_729).wrapping_mul(2_654_435_761).to_le_bytes();
|
||||
image::Rgba([v[0], v[1], v[2], 255])
|
||||
});
|
||||
let mut png = vec![];
|
||||
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
png.truncate(png.len() / 2);
|
||||
png
|
||||
}
|
||||
|
||||
/// An image whose pixels can't be decoded is tried once: later renders find the store's note of it,
|
||||
/// and each render counts it in `decode_failures` for an export to report. On screen
|
||||
/// (`mark_undecoded_images`) it draws as a crossed gray box; an export draws nothing there.
|
||||
#[test]
|
||||
fn an_undecodable_image_is_tried_once_and_marked_on_screen() {
|
||||
use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind};
|
||||
let png = truncated_png(61, 47);
|
||||
assert_eq!(image::ImageReader::new(std::io::Cursor::new(&png)).with_guessed_format().unwrap().into_dimensions().unwrap(), (61, 47));
|
||||
let mut d = Document::new(80.0, 60.0);
|
||||
d.images.insert("cut".into(), ImageBlob::new("image/png", png));
|
||||
let id = d.alloc_id();
|
||||
let im = ImageObject {
|
||||
key: "cut".into(),
|
||||
width: 61,
|
||||
height: 47,
|
||||
xf: Affine::translate((10.0, 5.0)),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
d.insert(Some(d.layers[0].id), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap();
|
||||
// The alpha summed over the image's frame.
|
||||
let alpha = |r: &Rendered| (10..71).flat_map(|x| (5..52).map(move |y| u64::from(r.pixel(x, y)[3]))).sum::<u64>();
|
||||
let attempts = || paint::DECODE_ATTEMPTS.with(std::cell::Cell::get);
|
||||
let (tried, failed) = (attempts(), decode_failures());
|
||||
let screen = RenderOptions { mark_undecoded_images: true, ..Default::default() };
|
||||
let mut r = Renderer::new();
|
||||
for render in 1..=2 {
|
||||
let shown = r.render(&d, 80, 60, Affine::IDENTITY, &screen);
|
||||
assert!(alpha(&shown) > 0, "render {render}: the crossed box shows");
|
||||
assert_eq!(decode_failures() - failed, render, "render {render}: counted");
|
||||
}
|
||||
assert_eq!(attempts() - tried, 1, "tried once");
|
||||
let export = Renderer::new().render(&d, 80, 60, Affine::IDENTITY, &RenderOptions::default());
|
||||
assert_eq!(alpha(&export), 0, "an export draws nothing there");
|
||||
assert_eq!((attempts() - tried, decode_failures() - failed), (1, 3), "and counts it without decoding it again");
|
||||
}
|
||||
|
||||
/// The rasters a renderer keeps of an object's raster effects are made again when
|
||||
/// `mark_undecoded_images` changes: a blurred image whose pixels can't be decoded shows its blurred
|
||||
/// mark only while the option is on.
|
||||
#[test]
|
||||
fn raster_effects_follow_the_undecoded_image_mark() {
|
||||
use vectorcraft_doc::{Effect, ImageBlob, ImageObject, NodeKind};
|
||||
let mut d = Document::new(80.0, 60.0);
|
||||
d.images.insert("cut".into(), ImageBlob::new("image/png", truncated_png(43, 31)));
|
||||
let id = d.alloc_id();
|
||||
let im = ImageObject {
|
||||
key: "cut".into(),
|
||||
width: 43,
|
||||
height: 31,
|
||||
xf: Affine::translate((15.0, 12.0)),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let mut n = Node::new(id, NodeKind::Image(Box::new(im)));
|
||||
n.appearance.effects.push(Effect { id: "blur.gaussian".into(), params: serde_json::json!({"radius": 2.0}), visible: true });
|
||||
d.insert(Some(d.layers[0].id), 0, n).unwrap();
|
||||
let alpha = |r: &Rendered| r.pixels.chunks(4).map(|p| u64::from(p[3])).sum::<u64>();
|
||||
let mut r = Renderer::new();
|
||||
for mark in [true, false, true] {
|
||||
let opts = RenderOptions { mark_undecoded_images: mark, ..Default::default() };
|
||||
let a = alpha(&r.render(&d, 80, 60, Affine::IDENTITY, &opts));
|
||||
assert_eq!(a > 0, mark, "mark_undecoded_images {mark}: alpha {a}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A gray image within the allowance draws its gray levels.
|
||||
#[test]
|
||||
fn a_gray_image_draws_its_gray_levels() {
|
||||
@@ -963,6 +1046,124 @@ fn a_gray_image_draws_its_gray_levels() {
|
||||
assert_eq!((r.pixel(5, 10), r.pixel(35, 10)), ([40, 40, 40, 255], [200, 200, 200, 255]));
|
||||
}
|
||||
|
||||
/// Runs `f` with the decode allowance of one image on this thread set to `bytes`.
|
||||
fn with_allowance<T>(bytes: u64, f: impl FnOnce() -> T) -> T {
|
||||
paint::TEST_ALLOWANCE.with(|c| c.set(Some(bytes)));
|
||||
let out = f();
|
||||
paint::TEST_ALLOWANCE.with(|c| c.set(None));
|
||||
out
|
||||
}
|
||||
|
||||
/// `img` encoded as `format`.
|
||||
fn encoded(img: image::DynamicImage, format: image::ImageFormat) -> Vec<u8> {
|
||||
let mut out = vec![];
|
||||
img.write_to(&mut std::io::Cursor::new(&mut out), format).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
/// A 16-bit PNG past the decode allowance is read a row at a time at the largest size within the
|
||||
/// allowance and draws its colors; the file's own size is kept.
|
||||
#[test]
|
||||
fn a_png_past_the_allowance_draws_at_reduced_size() {
|
||||
use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind};
|
||||
let img = image::ImageBuffer::<image::Rgba<u16>, _>::from_fn(64, 48, |x, _| {
|
||||
if x < 32 { image::Rgba([51400, 10280, 10280, 65535]) } else { image::Rgba([10280, 10280, 51400, 65535]) }
|
||||
});
|
||||
let png = encoded(image::DynamicImage::ImageRgba16(img), image::ImageFormat::Png);
|
||||
// 64 × 48 is 12,288 bytes as RGBA; 36 × 27 is the largest within 4,096.
|
||||
assert_eq!(with_allowance(4096, || paint::reduced_size(&png)), Some((36, 27)));
|
||||
assert_eq!(paint::reduced_size(&png), None, "within the 2 GB allowance");
|
||||
let mut d = Document::new(64.0, 48.0);
|
||||
d.images.insert("over".into(), ImageBlob::new("image/png", png));
|
||||
let id = d.alloc_id();
|
||||
let im = ImageObject { key: "over".into(), width: 64, height: 48, xf: Affine::IDENTITY, link: None, placement: Default::default(), pixels: None };
|
||||
d.insert(Some(d.layers[0].id), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap();
|
||||
let failed = decode_failures();
|
||||
// As on screen, where an image that can't be decoded draws as a crossed box.
|
||||
let screen = RenderOptions { smooth_images: false, mark_undecoded_images: true, ..Default::default() };
|
||||
let r = with_allowance(4096, || Renderer::new().render(&d, 64, 48, Affine::IDENTITY, &screen));
|
||||
assert_eq!(decode_failures(), failed);
|
||||
assert_eq!((r.pixel(8, 24), r.pixel(56, 24)), ([200, 40, 40, 255], [40, 40, 200, 255]));
|
||||
// 16 × 16 at 16 bits a sample is 2,048 bytes decoded and 1,024 as RGBA: past 1,500 as decoded
|
||||
// and within it as RGBA, it is read a row at a time at its own size.
|
||||
let small = image::ImageBuffer::<image::Rgba<u16>, _>::from_pixel(16, 16, image::Rgba([51400, 10280, 10280, 65535]));
|
||||
let small = encoded(image::DynamicImage::ImageRgba16(small), image::ImageFormat::Png);
|
||||
assert_eq!(with_allowance(1500, || paint::reduced_size(&small)), Some((16, 16)));
|
||||
let pm = with_allowance(1500, || paint::decode_pixmap(&small)).expect("read a row at a time");
|
||||
let c = pm.sample(3, 3);
|
||||
assert_eq!((pm.width(), pm.height(), [c.r, c.g, c.b, c.a]), (16, 16, [200, 40, 40, 255]));
|
||||
// A row is read only while the reader's row buffers, 32 bytes a column, fit the allowance:
|
||||
// 128 columns do within 4,096 bytes, and 129 columns are not decoded (their samples, 8 bytes a
|
||||
// pixel, are past it too).
|
||||
let wide = |w: u32| {
|
||||
let img = image::ImageBuffer::<image::Rgba<u16>, _>::from_pixel(w, 6, image::Rgba([51400, 10280, 10280, 65535]));
|
||||
encoded(image::DynamicImage::ImageRgba16(img), image::ImageFormat::Png)
|
||||
};
|
||||
assert_eq!(with_allowance(4096, || paint::reduced_size(&wide(128))), Some((128, 6)));
|
||||
assert_eq!(with_allowance(4096, || paint::reduced_size(&wide(129))), None);
|
||||
// An image of more pixels than the allowance has bytes is not read: 128 × 32 8-bit gray pixels
|
||||
// are drawn at 64 × 16 within 4,096 bytes, and 128 × 33 are not.
|
||||
let gray = |h: u32| encoded(image::DynamicImage::ImageLuma8(image::GrayImage::from_pixel(128, h, image::Luma([90]))), image::ImageFormat::Png);
|
||||
assert_eq!(with_allowance(4096, || paint::reduced_size(&gray(32))), Some((64, 16)));
|
||||
assert_eq!(with_allowance(4096, || paint::reduced_size(&gray(33))), None);
|
||||
}
|
||||
|
||||
/// A JPEG whose RGB samples are within the allowance but whose RGBA is past it is decoded whole
|
||||
/// and shrunk to the largest size within the allowance; an image whose decoded samples are past it
|
||||
/// and can't be read a row at a time (a GIF, 4 bytes a pixel) is still not decoded, counted, and
|
||||
/// noted as undecodable.
|
||||
#[test]
|
||||
fn a_jpeg_past_the_allowance_as_rgba_is_shrunk_and_a_gif_past_it_is_not_decoded() {
|
||||
let jpeg = encoded(image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(80, 60, image::Rgb([30, 120, 200]))), image::ImageFormat::Jpeg);
|
||||
// 14,400 bytes of RGB, 19,200 as RGBA: 73 × 54 is the largest within 16,000.
|
||||
let pm = with_allowance(16_000, || paint::decode_pixmap(&jpeg)).expect("decoded at reduced size");
|
||||
assert_eq!((pm.width(), pm.height()), (73, 54));
|
||||
let c = pm.sample(36, 27);
|
||||
assert!(c.r.abs_diff(30) <= 4 && c.g.abs_diff(120) <= 4 && c.b.abs_diff(200) <= 4 && c.a == 255, "{c:?}");
|
||||
// A placed document's preview asks for 20 × 15: decoded straight at that size.
|
||||
let pm = with_allowance(16_000, || paint::decode_pixmap_fit(&jpeg, 20, 15)).expect("decoded at the size asked for");
|
||||
assert_eq!((pm.width(), pm.height()), (20, 15));
|
||||
let gif =
|
||||
encoded(image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(80, 60, image::Rgba([30, 120, 200, 255]))), image::ImageFormat::Gif);
|
||||
assert_eq!(with_allowance(16_000, || paint::reduced_size(&gif)), None);
|
||||
let failed = decode_failures();
|
||||
let why = with_allowance(16_000, || paint::decode_pixmap_or_why(&gif)).err();
|
||||
assert_eq!(why, Some(paint::Undecoded::Unreadable), "noted as undecodable");
|
||||
assert_eq!(decode_failures(), failed + 1);
|
||||
}
|
||||
|
||||
/// An image past the allowance is decoded at reduced size only while the result and what reading
|
||||
/// it takes (the image decoded whole, or the PNG reader's row buffers) fit beside the images
|
||||
/// paints hold; when they don't, it isn't decoded and is not noted as undecodable, and it is
|
||||
/// decoded once there is room.
|
||||
#[test]
|
||||
fn a_reduced_decode_counts_what_reading_takes_beside_the_images_paints_hold() {
|
||||
/// Runs `f` with room for `bytes` beside the images paints hold.
|
||||
fn with_room<T>(bytes: u64, f: impl FnOnce() -> T) -> T {
|
||||
paint::TEST_ROOM.with(|c| c.set(Some(bytes)));
|
||||
let out = f();
|
||||
paint::TEST_ROOM.with(|c| c.set(None));
|
||||
out
|
||||
}
|
||||
// Decoded whole: 14,400 bytes of RGB and a 16-row band of 8,960 bytes, beside a 73 × 54 result
|
||||
// of 15,768 bytes.
|
||||
let jpeg = encoded(image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(80, 60, image::Rgb([30, 120, 200]))), image::ImageFormat::Jpeg);
|
||||
// Read a row at a time: 64 columns of 32 bytes in the reader's row buffers, beside a 36 × 27
|
||||
// result of 3,888 bytes.
|
||||
let png = encoded(
|
||||
image::DynamicImage::ImageRgba16(image::ImageBuffer::from_pixel(64, 48, image::Rgba([51400, 10280, 10280, 65535]))),
|
||||
image::ImageFormat::Png,
|
||||
);
|
||||
for (bytes, allowance, room, size) in [(&jpeg, 16_000, 15_768 + 14_400 + 8_960, (73, 54)), (&png, 4_096, 3_888 + 2_048, (36, 27))] {
|
||||
let failed = decode_failures();
|
||||
let none = with_allowance(allowance, || with_room(room - 1, || paint::decode_pixmap_or_why(bytes)));
|
||||
assert_eq!(none.err(), Some(paint::Undecoded::NoRoom), "not decoded with a byte too few, and tried again later");
|
||||
assert_eq!(decode_failures(), failed + 1);
|
||||
let pm = with_allowance(allowance, || with_room(room, || paint::decode_pixmap(bytes))).expect("decoded once there is room");
|
||||
assert_eq!((pm.width(), pm.height()), size);
|
||||
}
|
||||
}
|
||||
|
||||
/// Art Optimized exports are supersampled (#983): two red shapes meeting along a diagonal leave no
|
||||
/// seam of the white background between them, where shape-by-shape smoothing shows one; the outer
|
||||
/// edges stay smooth.
|
||||
|
||||
@@ -801,6 +801,68 @@ fn brush_art_draws_edits_of_the_symbols_and_patterns_it_shows() {
|
||||
}
|
||||
}
|
||||
|
||||
/// As above, with symbols `Dot` (a blue square) and `Other` (a red square with a brushed line),
|
||||
/// and patterns `Fill` (a green square) and `Spare` (a red square with a brushed line). After a
|
||||
/// frame, the next one draws as a new renderer does when two symbols or two patterns swap names,
|
||||
/// their art left as it is: the brush art's instance of `Dot` or its square painted with `Fill`
|
||||
/// then shows art that draws a brushed stroke.
|
||||
#[test]
|
||||
fn brush_art_draws_renamed_symbols_and_patterns_it_shows() {
|
||||
let _fonts = fonts_steady();
|
||||
use vectorcraft_brush::{Brush, BrushKind, Scatter};
|
||||
use vectorcraft_doc::pattern::{PatternDef, pattern_paint};
|
||||
use vectorcraft_geom::shapes::{line, rectangle};
|
||||
let square = |d: &mut Document, paint: Paint| filled(d, rectangle(Rect::new(-4.0, -4.0, 4.0, 4.0)), paint, vec![]);
|
||||
let art = |d: &mut Document, paint: Paint, brushed: bool| {
|
||||
let mut members = vec![Arc::new(square(d, paint))];
|
||||
if brushed {
|
||||
members.push(Arc::new(brushed_line(d)));
|
||||
}
|
||||
Node::group(d.alloc_id(), members)
|
||||
};
|
||||
let doc = || {
|
||||
let mut d = Document::new(200.0, 100.0);
|
||||
for (name, paint, brushed) in
|
||||
[("Dot", Paint::solid(Color::rgb(0.0, 0.0, 1.0)), false), ("Other", Paint::solid(Color::rgb(1.0, 0.0, 0.0)), true)]
|
||||
{
|
||||
let a = art(&mut d, paint, brushed);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { name: name.into(), art: Arc::new(a) });
|
||||
}
|
||||
for (name, paint, brushed) in
|
||||
[("Fill", Paint::solid(Color::rgb(0.0, 0.6, 0.0)), false), ("Spare", Paint::solid(Color::rgb(1.0, 0.0, 0.0)), true)]
|
||||
{
|
||||
let a = art(&mut d, paint, brushed);
|
||||
let mut def = PatternDef::new(name, vec![Arc::new(a)]);
|
||||
def.tile = Rect::new(-6.0, -6.0, 6.0, 6.0);
|
||||
d.patterns.push(def);
|
||||
}
|
||||
let id = d.alloc_id();
|
||||
let instance = Node::new(id, NodeKind::SymbolInstance { symbol: "Dot".into(), xf: Affine::translate((0.0, -8.0)) });
|
||||
let mut painted = square(&mut d, pattern_paint("Fill"));
|
||||
painted.transform(Affine::translate((0.0, 8.0)), true);
|
||||
let scatter = Node::group(d.alloc_id(), vec![Arc::new(instance), Arc::new(painted)]);
|
||||
let mut lib = vectorcraft_brush::library(&d);
|
||||
lib.push(Brush { name: "Dots".into(), kind: BrushKind::Scatter(Scatter { art: scatter, spacing: (150.0, 150.0), ..Default::default() }) });
|
||||
vectorcraft_brush::store(&mut d, &lib);
|
||||
let mut ap = vectorcraft_doc::Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0);
|
||||
if let Some(s) = ap.stroke_mut() {
|
||||
s.brush = Some("Dots".into());
|
||||
}
|
||||
let path = Node::path(d.alloc_id(), line((20.0, 50.0).into(), (180.0, 50.0).into()), ap);
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), usize::MAX, path).unwrap();
|
||||
d
|
||||
};
|
||||
edit_draws_as_new(doc(), |d| {
|
||||
d.symbols[0].name = "Other".into();
|
||||
d.symbols[1].name = "Dot".into();
|
||||
});
|
||||
edit_draws_as_new(doc(), |d| {
|
||||
d.patterns[0].name = "Spare".into();
|
||||
d.patterns[1].name = "Fill".into();
|
||||
});
|
||||
}
|
||||
|
||||
/// A path of the document and an instance of symbol `Wave` (a group holding another path) are
|
||||
/// stroked with scatter brush `Bent`, whose art is an arc envelope around a green band: the second
|
||||
/// frame evaluates none of the envelopes in their brush art again, and draws what the first drew
|
||||
|
||||
@@ -8,8 +8,11 @@ use vectorcraft_geom::shapes;
|
||||
use super::*;
|
||||
|
||||
/// Every file reads as a 40×20 artboard filled blue; a file whose bytes start with `loop` also
|
||||
/// places itself (the same key) in its middle.
|
||||
/// places itself (the same key) in its middle, and one whose bytes start with `bad` can't be read.
|
||||
fn blue_page(p: &PlacedDocument, bytes: &[u8]) -> Option<(Document, Node, Rect)> {
|
||||
if bytes.starts_with(b"bad") {
|
||||
return None;
|
||||
}
|
||||
let mut d = Document::new(40.0, 20.0);
|
||||
d.layers.clear();
|
||||
let blue = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0);
|
||||
@@ -27,19 +30,32 @@ fn doc_with(key: &str, bytes: &[u8]) -> Document {
|
||||
vectorcraft_doc::placed_document::set_loader(blue_page);
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
d.images.insert(key.into(), ImageBlob::new("application/json", bytes.to_vec()));
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, placed_node(50, key, 40.0, 20.0, Affine::translate((10.0, 10.0)) * Affine::scale(2.0))).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// Object `id` showing file `key` in a `width`×`height` box placed by `xf`.
|
||||
fn placed_node(id: u64, key: &str, width: f64, height: f64, xf: Affine) -> Node {
|
||||
let p = PlacedDocument {
|
||||
link: LinkInfo::new("/art/card.vectorcraft"),
|
||||
key: key.into(),
|
||||
bounding: false,
|
||||
page_box: Default::default(),
|
||||
width: 40.0,
|
||||
height: 20.0,
|
||||
xf: Affine::translate((10.0, 10.0)) * Affine::scale(2.0),
|
||||
width,
|
||||
height,
|
||||
xf,
|
||||
placement: Default::default(),
|
||||
};
|
||||
let l = d.layers[0].id;
|
||||
d.insert(Some(l), 0, Node::new(NodeId(50), NodeKind::PlacedDocument(Box::new(p)))).unwrap();
|
||||
d
|
||||
Node::new(NodeId(id), NodeKind::PlacedDocument(Box::new(p)))
|
||||
}
|
||||
|
||||
/// Held by the tests that draw placed documents from bitmaps, which share the bitmaps, their
|
||||
/// generation and the jobs being made: one test's bitmaps don't push out another's, and
|
||||
/// [`settle`] waits for its own.
|
||||
fn serial() -> std::sync::MutexGuard<'static, ()> {
|
||||
static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
fn doc(key: &str) -> Document {
|
||||
@@ -117,6 +133,7 @@ fn a_placed_document_with_a_drop_shadow_shows_its_file_once_read() {
|
||||
|
||||
#[test]
|
||||
fn on_screen_a_placed_document_shows_a_placeholder_then_its_bitmap() {
|
||||
let _serial = serial();
|
||||
let d = doc("progressive-1");
|
||||
let generation = placed_document::generation();
|
||||
let first = render(&d, true);
|
||||
@@ -135,6 +152,7 @@ fn on_screen_a_placed_document_shows_a_placeholder_then_its_bitmap() {
|
||||
|
||||
#[test]
|
||||
fn copies_of_one_placed_document_share_its_bitmap() {
|
||||
let _serial = serial();
|
||||
let mut d = doc("shared-1");
|
||||
let n = d.node(NodeId(50)).unwrap().clone();
|
||||
let l = d.layers[0].id;
|
||||
@@ -150,8 +168,126 @@ fn copies_of_one_placed_document_share_its_bitmap() {
|
||||
assert_eq!(&r.pixel(50, 75)[..3], &[0, 0, 255]);
|
||||
}
|
||||
|
||||
/// Nine files on screen, each drawn from a 4096 × 4096 bitmap (576 MiB together, past the 512 MiB
|
||||
/// the bitmaps keep): once made, the next frames draw all nine and ask for none again.
|
||||
#[test]
|
||||
fn nine_large_bitmaps_on_screen_are_not_made_again() {
|
||||
let _serial = serial();
|
||||
vectorcraft_doc::placed_document::set_loader(blue_page);
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
let l = d.layers[0].id;
|
||||
let keys: Vec<String> = (0..9).map(|i| format!("nine-{i}")).collect();
|
||||
for (i, key) in keys.iter().enumerate() {
|
||||
d.images.insert(key.clone(), ImageBlob::new("application/json", format!("{{\"doc\": \"{key}\"}}").into_bytes()));
|
||||
// A 1 × 1 point box at 4096 pixels a point: a 4096-pixel bitmap.
|
||||
d.insert(Some(l), i, placed_node(100 + i as u64, key, 1.0, 1.0, Affine::translate((i as f64 * 0.001, 0.0)))).unwrap();
|
||||
}
|
||||
let (view, opts) = (Affine::scale(4096.0), RenderOptions { progressive_placed: true, ..Default::default() });
|
||||
let mut r = Renderer::new();
|
||||
r.render(&d, 32, 32, view, &opts);
|
||||
settle();
|
||||
let asked = || keys.iter().map(|k| placed_document::scheduled(k)).collect::<Vec<_>>();
|
||||
assert_eq!(asked(), vec![1; 9], "each asked for once");
|
||||
for frame in 1..=2 {
|
||||
let shown = r.render(&d, 32, 32, view, &opts);
|
||||
assert_eq!(asked(), vec![1; 9], "frame {frame} asks for none again");
|
||||
assert_eq!(&shown.pixel(16, 16)[..3], &[0, 0, 255], "frame {frame} draws the art");
|
||||
}
|
||||
}
|
||||
|
||||
/// A bitmap that was not kept (it would have taken the bitmaps past the most they may hold) is
|
||||
/// not asked for again: its file draws exactly at that zoom step, at once.
|
||||
#[test]
|
||||
fn a_bitmap_not_kept_draws_exactly_without_being_asked_for() {
|
||||
let _serial = serial();
|
||||
let d = doc("unkept-1");
|
||||
// The box is drawn at 2 pixels a point: zoom step 2.
|
||||
placed_document::mark_unkept("unkept-1", 2.0);
|
||||
let shown = render(&d, true);
|
||||
assert_eq!(&shown.pixel(50, 30)[..3], &[0, 0, 255], "the art, drawn exactly");
|
||||
assert_eq!(placed_document::scheduled("unkept-1"), 0, "not asked for");
|
||||
}
|
||||
|
||||
/// A file that can't be read, without a preview: its bitmap is asked for once, the screen is
|
||||
/// not told to draw again, and later frames draw the placeholder without asking again.
|
||||
#[test]
|
||||
fn a_bitmap_that_cant_be_made_is_not_asked_for_again() {
|
||||
let _serial = serial();
|
||||
let d = doc_with("unreadable-1", b"bad");
|
||||
let generation = placed_document::generation();
|
||||
render(&d, true);
|
||||
settle();
|
||||
assert_eq!(placed_document::generation(), generation, "nothing new to draw");
|
||||
let later = render(&d, true);
|
||||
assert_eq!(placed_document::scheduled("unreadable-1"), 1, "asked for once");
|
||||
let shown = &later.pixel(50, 30)[..3];
|
||||
assert!(shown != [255, 255, 255] && shown != [0, 0, 255], "the placeholder: {shown:?}");
|
||||
}
|
||||
|
||||
/// Once bitmaps are ready, drawing again where [`placed_area`] says gives what drawing the whole
|
||||
/// frame again gives. The area of a file covers every object showing it (a group's member and
|
||||
/// an object with a drop shadow too) and no object showing another file; art of a brush or a
|
||||
/// symbol showing it makes it everything.
|
||||
#[test]
|
||||
fn a_ready_bitmap_draws_again_where_its_file_shows() {
|
||||
let _serial = serial();
|
||||
vectorcraft_doc::placed_document::set_loader(blue_page);
|
||||
let mut d = Document::new(100.0, 100.0);
|
||||
for key in ["area-a", "area-b"] {
|
||||
d.images.insert(key.into(), ImageBlob::new("application/json", format!("{{\"doc\": \"{key}\"}}").into_bytes()));
|
||||
}
|
||||
let l = d.layers[0].id;
|
||||
// 20 × 10 point boxes: A loose at (5, 5), with a shadow at (30, 40) and in a group at (5, 80);
|
||||
// B at (75, 5). Only the shadow reaches past x = 50, and only the group's member past y = 50.
|
||||
let at = |x: f64, y: f64| Affine::translate((x, y)) * Affine::scale(0.5);
|
||||
d.insert(Some(l), 0, placed_node(60, "area-a", 40.0, 20.0, at(5.0, 5.0))).unwrap();
|
||||
let group = NodeKind::Group { children: vec![Arc::new(placed_node(61, "area-a", 40.0, 20.0, at(5.0, 80.0)))], clip: false };
|
||||
d.insert(Some(l), 1, Node::new(NodeId(62), group)).unwrap();
|
||||
let mut shadowed = placed_node(63, "area-a", 40.0, 20.0, at(30.0, 40.0));
|
||||
let params = serde_json::json!({"x": 4, "y": 4, "blur": 1, "opacity": 100});
|
||||
shadowed.appearance.effects.push(vectorcraft_doc::Effect { id: "stylize.dropShadow".into(), params, visible: true });
|
||||
d.insert(Some(l), 2, shadowed).unwrap();
|
||||
d.insert(Some(l), 3, placed_node(64, "area-b", 40.0, 20.0, at(75.0, 5.0))).unwrap();
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), progressive_placed: true, ..Default::default() };
|
||||
let mut r = Renderer::new();
|
||||
let generation = placed_document::generation();
|
||||
let before = r.render(&d, 100, 100, Affine::IDENTITY, &opts);
|
||||
settle();
|
||||
let made = placed_document::made_between(generation, placed_document::generation()).expect("known");
|
||||
let files = |keys: &[&str]| keys.iter().map(|k| k.to_string()).collect::<std::collections::HashSet<_>>();
|
||||
assert_eq!(made, files(&["area-a", "area-b"]), "both files' bitmaps");
|
||||
let only_a = files(&["area-a"]);
|
||||
let Changed::Area(a) = placed_area(&d, &only_a) else { panic!("an area") };
|
||||
for (x, y) in [(6.0, 6.0), (24.0, 14.0), (31.0, 41.0), (53.0, 53.0), (6.0, 81.0), (24.0, 89.0)] {
|
||||
assert!(a.contains(vectorcraft_geom::Point::new(x, y)), "({x}, {y}) in {a:?}");
|
||||
}
|
||||
assert!(a.x1 < 75.0, "not B: {a:?}");
|
||||
// Drawn again only there, it is what the whole frame drawn again shows.
|
||||
let Changed::Area(area) = placed_area(&d, &made) else { panic!("an area") };
|
||||
let after = Renderer::new().render(&d, 100, 100, Affine::IDENTITY, &opts);
|
||||
let [x0, y0, x1, y1] = view_pixels(area, Affine::IDENTITY, 100, 100).expect("on screen");
|
||||
let part = r.render(&d, x1 - x0, y1 - y0, Affine::translate((-f64::from(x0), -f64::from(y0))), &opts);
|
||||
let mut patched = before.pixels.clone();
|
||||
for y in 0..y1 - y0 {
|
||||
let (from, to, n) = ((y * (x1 - x0) * 4) as usize, (((y0 + y) * 100 + x0) * 4) as usize, ((x1 - x0) * 4) as usize);
|
||||
patched[to..to + n].copy_from_slice(&part.pixels[from..from + n]);
|
||||
}
|
||||
assert!(patched == after.pixels, "drawn again in {area:?}, it differs from drawing it all");
|
||||
assert!(before.pixels != after.pixels, "the bitmaps show");
|
||||
// Other files change nothing; art of a brush or a symbol showing the file changes everything.
|
||||
assert_eq!(placed_area(&d, &files(&["area-z"])), Changed::Nothing);
|
||||
let mut brushed = d.clone();
|
||||
let scatter = vectorcraft_brush::Scatter { art: placed_node(66, "area-a", 40.0, 20.0, Affine::IDENTITY), ..Default::default() };
|
||||
let brush = vectorcraft_brush::Brush { name: "Cards".into(), kind: vectorcraft_brush::BrushKind::Scatter(scatter) };
|
||||
vectorcraft_brush::store(&mut brushed, &[brush]);
|
||||
assert_eq!(placed_area(&brushed, &only_a), Changed::Everything);
|
||||
d.symbols.push(vectorcraft_doc::Symbol { name: "Card".into(), art: Arc::new(placed_node(65, "area-a", 40.0, 20.0, Affine::IDENTITY)) });
|
||||
assert_eq!(placed_area(&d, &only_a), Changed::Everything);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_document_kept_as_its_preview_draws_the_preview() {
|
||||
let _serial = serial();
|
||||
let mut d = doc("preview-1");
|
||||
// Only the preview (a 20×10 green PNG) is there, and the file can't be read here.
|
||||
let img = image::RgbaImage::from_pixel(20, 10, image::Rgba([0, 200, 0, 255]));
|
||||
@@ -172,6 +308,7 @@ fn a_placed_document_kept_as_its_preview_draws_the_preview() {
|
||||
|
||||
#[test]
|
||||
fn a_document_that_places_itself_draws_a_few_levels_deep_then_stops() {
|
||||
let _serial = serial();
|
||||
let d = doc_with("loop-1", b"loop");
|
||||
let t = std::time::Instant::now();
|
||||
let r = render(&d, false);
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
//! Effect rasters cropped to the view, or made at a lower resolution, are kept while the view
|
||||
//! stays as it is: dragging other art over an object whose effects reach far past the view (a wide
|
||||
//! blur, or any blur zoomed in) draws its raster from the last frame.
|
||||
//! blur, or any blur zoomed in) draws its raster from the last frame. A cropped raster made again
|
||||
//! after a pan is kept while later pans stay within the margin it is made with.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId};
|
||||
use vectorcraft_doc::{Appearance, Document, Effect, ImageBlob, ImageObject, Node, NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, Rect, shapes};
|
||||
|
||||
use crate::{RenderOptions, Renderer};
|
||||
@@ -110,6 +111,209 @@ fn rasters_cropped_to_the_view_follow_a_pan_and_a_zoom() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A 6000 × 4000 pt image (300 × 200 pixels, 20 pt a pixel) under `effects`.
|
||||
fn large_image(effects: &[(&str, serde_json::Value)]) -> Document {
|
||||
let img = image::RgbaImage::from_fn(300, 200, |x, y| image::Rgba([(x * 7) as u8, (y * 13) as u8, ((x + y) * 3) as u8, 255]));
|
||||
let mut png = vec![];
|
||||
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
let mut d = Document::new(6000.0, 4000.0);
|
||||
d.images.insert("viewraster-pan".into(), ImageBlob::new("image/png", png));
|
||||
let im = ImageObject {
|
||||
key: "viewraster-pan".into(),
|
||||
width: 300,
|
||||
height: 200,
|
||||
xf: Affine::scale(20.0),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let mut n = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)));
|
||||
n.appearance.effects = effects.iter().map(|(id, p)| Effect { id: (*id).into(), params: p.clone(), visible: true }).collect();
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, n).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// At 100 %, the Drop Shadow, Gaussian Blur and Feather rasters of a large image are cropped to the view. The pan
|
||||
/// that makes one again at the same zoom makes it with a margin around the view, and later pans within the margin
|
||||
/// (by up to 259 pixels from the frame that made them, and back) draw it without making any offscreen raster: each
|
||||
/// such frame makes as many offscreen pixels as the same view drawn again, and draws as a fresh renderer draws it,
|
||||
/// within a level a channel: an image sampled into a raster that starts at another pixel rounds by up to a level, as it
|
||||
/// does in the frames of two fresh renderers whose views differ in size.
|
||||
#[test]
|
||||
fn pans_within_a_cropped_rasters_margin_draw_it_kept() {
|
||||
let size = (640, 360);
|
||||
let cases: Vec<Case> = vec![
|
||||
("Drop Shadow", vec![("stylize.dropShadow", json!({"blur": 20, "x": 7, "y": 7}))], 1.0),
|
||||
("Gaussian Blur", vec![("blur.gaussian", json!({"radius": 20}))], 1.0),
|
||||
("Feather", vec![("stylize.feather", json!({"radius": 20}))], 1.0),
|
||||
(
|
||||
"Drop Shadow over a Drop Shadow",
|
||||
vec![("stylize.dropShadow", json!({"blur": 20, "x": 7, "y": 7})), ("stylize.dropShadow", json!({"blur": 10, "x": -5, "y": 9}))],
|
||||
1.0,
|
||||
),
|
||||
];
|
||||
let counted = |r: &mut Renderer, d: &Document, xf: Affine, opts: &RenderOptions| {
|
||||
crate::OFFSCREEN_PIXELS.with(|n| n.set(0));
|
||||
let image = r.render(d, size.0, size.1, xf, opts);
|
||||
(image, crate::OFFSCREEN_PIXELS.with(|n| n.get()))
|
||||
};
|
||||
for (name, effects, zoom) in cases {
|
||||
let d = large_image(&effects);
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
let at = |dx: f64, dy: f64| Affine::translate((320.0 + dx, 180.0 + dy)) * Affine::scale(zoom) * Affine::translate((-3000.0, -2000.0));
|
||||
let mut r = Renderer::new();
|
||||
r.threads = 2;
|
||||
r.render(&d, size.0, size.1, at(0.0, 0.0), &opts);
|
||||
// The pan that makes the rasters again, and the same view drawn again.
|
||||
r.render(&d, size.0, size.1, at(37.0, 0.0), &opts);
|
||||
let (_, kept) = counted(&mut r, &d, at(37.0, 0.0), &opts);
|
||||
for (dx, dy) in [(74.0, 0.0), (74.0, -37.0), (296.0, -37.0), (0.0, 0.0), (-222.0, 37.0)] {
|
||||
let (image, made) = counted(&mut r, &d, at(dx, dy), &opts);
|
||||
assert_eq!(made, kept, "{name}: the pan to ({dx}, {dy}) drew the rasters kept");
|
||||
let mut fresh = Renderer::new();
|
||||
fresh.threads = 2;
|
||||
let still = fresh.render(&d, size.0, size.1, at(dx, dy), &opts);
|
||||
let worst = image.pixels.iter().zip(&still.pixels).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0);
|
||||
assert!(worst <= 1, "{name}: ({dx}, {dy}): a channel differs by {worst}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Scrolls by amounts that are not whole pixels, as the wheel and a trackpad give them, moved in whole pixels with the part left
|
||||
/// over carried to the next, as the canvas moves them: after the scroll that makes the Drop Shadow's cropped raster
|
||||
/// again with its margin, every later scroll draws it kept. The same scrolls moved as given make it again in every
|
||||
/// frame.
|
||||
#[test]
|
||||
fn fractional_scrolls_moved_in_whole_pixels_draw_a_cropped_raster_kept() {
|
||||
let size = (640, 360);
|
||||
let d = large_image(&[("stylize.dropShadow", json!({"blur": 20, "x": 7, "y": 7}))]);
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
let at = |dx: f64, dy: f64| Affine::translate((320.0 + dx, 180.0 + dy)) * Affine::translate((-3000.0, -2000.0));
|
||||
let counted = |r: &mut Renderer, xf: Affine| {
|
||||
crate::OFFSCREEN_PIXELS.with(|n| n.set(0));
|
||||
r.render(&d, size.0, size.1, xf, &opts);
|
||||
crate::OFFSCREEN_PIXELS.with(|n| n.get())
|
||||
};
|
||||
let scrolls = [(0.37, 1.13), (-2.71, 0.0), (0.0, 0.45), (1.9, -0.83), (0.21, 0.21), (13.6, -4.4), (-0.5, 0.5), (7.77, 2.22)];
|
||||
for whole in [true, false] {
|
||||
let mut r = Renderer::new();
|
||||
r.threads = 2;
|
||||
r.render(&d, size.0, size.1, at(0.0, 0.0), &opts);
|
||||
// The scroll that makes the raster again with its margin, and the same view drawn again.
|
||||
r.render(&d, size.0, size.1, at(37.0, 0.0), &opts);
|
||||
let kept = counted(&mut r, at(37.0, 0.0));
|
||||
let (mut given, mut moved): ((f64, f64), (f64, f64)) = ((37.0, 0.0), (37.0, 0.0));
|
||||
let mut made_again = 0;
|
||||
for (k, (x, y)) in scrolls.into_iter().enumerate() {
|
||||
given = (given.0 + x, given.1 + y);
|
||||
moved = if whole { (given.0.round(), given.1.round()) } else { given };
|
||||
let made = counted(&mut r, at(moved.0, moved.1));
|
||||
if whole {
|
||||
assert_eq!(made, kept, "scroll {k} to {moved:?} drew the raster kept");
|
||||
} else if made > kept {
|
||||
made_again += 1;
|
||||
}
|
||||
}
|
||||
assert!((moved.0 - given.0).abs() <= 0.5 && (moved.1 - given.1).abs() <= 0.5, "moved {moved:?} for {given:?}");
|
||||
if !whole {
|
||||
assert_eq!(made_again, scrolls.len(), "scrolls by amounts that are not whole pixels make the raster again");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group's shadow raster holds the shadows of the members outside the view: a pan that brings a member into view
|
||||
/// draws its shadow from the raster kept as a fresh renderer draws it, for a raster of the group's whole reach (two
|
||||
/// 100 pt squares) and for one cropped to the view and the margin a pan adds (two 3000 × 2000 pt rectangles).
|
||||
#[test]
|
||||
fn a_groups_shadow_raster_holds_the_members_outside_the_view() {
|
||||
let size = (640, 360);
|
||||
let blue = || Appearance::basic(Paint::solid(Color::rgb(0.1, 0.3, 0.9)), Paint::None, 0.0);
|
||||
// The two members, the point the view is centered on, and the pans after the first frame.
|
||||
let cases = [
|
||||
("whole", [Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(600.0, 0.0, 700.0, 100.0)], (220.0, 50.0), vec![-300.0]),
|
||||
("cropped", [Rect::new(0.0, 0.0, 3000.0, 2000.0), Rect::new(3400.0, 0.0, 6400.0, 2000.0)], (3000.0, 1000.0), vec![-37.0, -237.0]),
|
||||
];
|
||||
let mut wrong = vec![];
|
||||
for (name, members, (cx, cy), pans) in cases {
|
||||
let mut d = Document::new(6400.0, 2000.0);
|
||||
let members = members.iter().map(|r| std::sync::Arc::new(Node::path(d.alloc_id(), shapes::rectangle(*r), blue()))).collect();
|
||||
let mut group = Node::group(d.alloc_id(), members);
|
||||
group.appearance.effects.push(Effect { id: "stylize.dropShadow".into(), params: json!({"blur": 20, "x": 7, "y": 7}), visible: true });
|
||||
let layer = d.layers[0].id;
|
||||
d.insert(Some(layer), 0, group).unwrap();
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
let at = |dx: f64| Affine::translate((320.0 + dx, 180.0)) * Affine::translate((-cx, -cy));
|
||||
let mut r = Renderer::new();
|
||||
r.threads = 2;
|
||||
r.render(&d, size.0, size.1, at(0.0), &opts);
|
||||
for dx in pans {
|
||||
let image = r.render(&d, size.0, size.1, at(dx), &opts);
|
||||
let mut fresh = Renderer::new();
|
||||
fresh.threads = 2;
|
||||
if image.pixels != fresh.render(&d, size.0, size.1, at(dx), &opts).pixels {
|
||||
wrong.push(format!("{name}: panned by {dx}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(wrong.is_empty(), "{wrong:?}");
|
||||
}
|
||||
|
||||
/// While interacting, a group with a member outside the view that only moved draws its shadow from the raster of the
|
||||
/// frame before, where a fresh renderer draws it: the moved silhouette holds that member too.
|
||||
#[test]
|
||||
fn a_moved_group_with_a_member_outside_the_view_draws_its_shadow_kept() {
|
||||
let size = (640, 360);
|
||||
let blue = || Appearance::basic(Paint::solid(Color::rgb(0.1, 0.3, 0.9)), Paint::None, 0.0);
|
||||
let mut base = Document::new(700.0, 100.0);
|
||||
let members = [Rect::new(0.0, 0.0, 100.0, 100.0), Rect::new(600.0, 0.0, 700.0, 100.0)]
|
||||
.iter()
|
||||
.map(|r| std::sync::Arc::new(Node::path(base.alloc_id(), shapes::rectangle(*r), blue())))
|
||||
.collect();
|
||||
let mut group = Node::group(base.alloc_id(), members);
|
||||
group.appearance.effects.push(Effect { id: "stylize.dropShadow".into(), params: json!({"blur": 20, "x": 7, "y": 7}), visible: true });
|
||||
let (id, layer) = (group.id, base.layers[0].id);
|
||||
base.insert(Some(layer), 0, group).unwrap();
|
||||
let view = Affine::translate((100.0, 130.0));
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
let live = RenderOptions { interacting: true, ..opts.clone() };
|
||||
let mut r = Renderer::new();
|
||||
r.threads = 2;
|
||||
r.render(&base, size.0, size.1, view, &opts);
|
||||
let mut moved = base.clone();
|
||||
moved.node_mut(id).unwrap().transform(Affine::translate((3.0, 2.0)), false);
|
||||
let frame = r.render(&moved, size.0, size.1, view, &live);
|
||||
assert!(r.stats.moved > 0, "drawn from the raster of the frame before");
|
||||
let mut fresh = Renderer::new();
|
||||
fresh.threads = 2;
|
||||
assert!(frame.pixels == fresh.render(&moved, size.0, size.1, view, &opts).pixels);
|
||||
}
|
||||
|
||||
/// A shadow made over an earlier cropped shadow covers only the rect the earlier one was made for. In a 2000 × 1200
|
||||
/// view of the image's right edge, the pixel budget gives the earlier shadow, which also covers what the later one
|
||||
/// reads 60 pixels below, a margin of 548 pixels and the later one 643: a pan of 600 pixels past the first makes both
|
||||
/// again, and the frame draws as a fresh renderer draws it.
|
||||
#[test]
|
||||
fn a_shadow_over_a_cropped_shadow_keeps_to_the_earlier_ones_margin() {
|
||||
let size = (2000, 1200);
|
||||
let effects = [("stylize.dropShadow", json!({"blur": 20, "x": 7, "y": 7})), ("stylize.dropShadow", json!({"blur": 10, "x": -5, "y": -60}))];
|
||||
let d = large_image(&effects);
|
||||
let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };
|
||||
let at = |dy: f64| Affine::translate((1000.0, 600.0 + dy)) * Affine::translate((-6000.0, -2000.0));
|
||||
let mut r = Renderer::new();
|
||||
r.threads = 2;
|
||||
r.render(&d, size.0, size.1, at(0.0), &opts);
|
||||
r.render(&d, size.0, size.1, at(37.0), &opts);
|
||||
for dy in [37.0 - 600.0, 37.0 + 600.0] {
|
||||
let image = r.render(&d, size.0, size.1, at(dy), &opts);
|
||||
let mut fresh = Renderer::new();
|
||||
fresh.threads = 2;
|
||||
let still = fresh.render(&d, size.0, size.1, at(dy), &opts);
|
||||
let worst = image.pixels.iter().zip(&still.pixels).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0);
|
||||
assert_eq!(worst, 0, "panned to {dy}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Time a drag of the square over each backdrop in a 2560 × 1440 view: the first frame renders as
|
||||
/// before a drag, the next eight as a drag's frames (`interacting` and `dragging`, as the canvas
|
||||
/// renders them), then the frame after the drag. The hashes of that frame and of a fresh renderer's
|
||||
|
||||
@@ -18,7 +18,8 @@ pub(super) type XNode<'a, 'i> = roxmltree::Node<'a, 'i>;
|
||||
/// `name: value` declarations of a block or `style` attribute, with their `!important` flag. The
|
||||
/// `font` shorthand becomes its longhands, as usvg reads it for the rest of the drawing (#1557).
|
||||
pub(super) fn parse_decls(s: &str) -> Vec<(String, String, bool)> {
|
||||
s.split(';')
|
||||
split_decls(s)
|
||||
.into_iter()
|
||||
.filter_map(|d| {
|
||||
let (k, v) = d.split_once(':')?;
|
||||
let v = v.trim();
|
||||
@@ -37,6 +38,36 @@ pub(super) fn parse_decls(s: &str) -> Vec<(String, String, bool)> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Splits on the `;`s that are outside quoted strings and parentheses (`url(data:…;base64,…)`).
|
||||
fn split_decls(s: &str) -> Vec<&str> {
|
||||
let mut parts = Vec::new();
|
||||
let (mut start, mut depth, mut quote, mut escaped) = (0, 0usize, None::<char>, false);
|
||||
for (i, c) in s.char_indices() {
|
||||
if escaped {
|
||||
escaped = false;
|
||||
} else if c == '\\' {
|
||||
escaped = true;
|
||||
} else if let Some(q) = quote {
|
||||
if c == q {
|
||||
quote = None;
|
||||
}
|
||||
} else {
|
||||
match c {
|
||||
'\'' | '"' => quote = Some(c),
|
||||
'(' => depth += 1,
|
||||
')' => depth = depth.saturating_sub(1),
|
||||
';' if depth == 0 => {
|
||||
parts.push(s.get(start..i).unwrap_or_default());
|
||||
start = i + 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
parts.push(s.get(start..).unwrap_or_default());
|
||||
parts
|
||||
}
|
||||
|
||||
/// The longhands of a `font` shorthand: those it leaves out back to their initial values. None
|
||||
/// when it doesn't parse (it is then ignored, as in CSS).
|
||||
fn font_longhands(v: &str) -> Vec<(&'static str, String)> {
|
||||
@@ -467,6 +498,18 @@ mod tests {
|
||||
assert_eq!(parse_decls("fill: red !importantx"), [("fill".to_string(), "red !importantx".to_string(), false)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn semicolons_in_quotes_and_parens_do_not_split() {
|
||||
let d = |k: &str, v: &str| (k.to_string(), v.to_string(), false);
|
||||
assert_eq!(parse_decls("font-family:'A;B'; fill:red"), [d("font-family", "'A;B'"), d("fill", "red")]);
|
||||
assert_eq!(parse_decls("font-family:\"A;B\"; fill:red"), [d("font-family", "\"A;B\""), d("fill", "red")]);
|
||||
assert_eq!(
|
||||
parse_decls("fill:url(data:image/svg+xml;base64,AAA); stroke:red"),
|
||||
[d("fill", "url(data:image/svg+xml;base64,AAA)"), d("stroke", "red")]
|
||||
);
|
||||
let _ = parse_decls("font-family:'A;B; fill:red");
|
||||
}
|
||||
|
||||
fn with_doc(svg: &str, f: impl FnOnce(&roxmltree::Document, &Styles)) {
|
||||
let doc = roxmltree::Document::parse(svg).unwrap();
|
||||
let st = Styles::new(&doc);
|
||||
|
||||
@@ -408,6 +408,29 @@ pub fn twin_font(newer: bool) -> Option<Vec<u8>> {
|
||||
Some(builder.build())
|
||||
}
|
||||
|
||||
/// The family of [`numbered_font`]: styles numbered W3 and W6, and no Regular.
|
||||
pub const NUMBERED_FAMILY: &str = "Numtest Mincho";
|
||||
|
||||
/// A face of family [`NUMBERED_FAMILY`] in `style` (`W3` or `W6`; the bundled Source Sans 3
|
||||
/// Regular renamed), as families whose styles are numbered have, with no Regular among them.
|
||||
/// `None` when it can't be built.
|
||||
pub fn numbered_font(style: &str) -> Option<Vec<u8>> {
|
||||
const FACE: &[u8] = include_bytes!("../../../assets/fonts/SourceSans3-Regular.ttf");
|
||||
let font = skrifa::FontRef::new(FACE).ok()?;
|
||||
let full = format!("{NUMBERED_FAMILY} {style}");
|
||||
let postscript = format!("NumtestMincho-{style}");
|
||||
let name = name_table(&[(1, NUMBERED_FAMILY), (2, style), (4, &full), (5, "Version 1.000"), (6, &postscript)])?;
|
||||
let mut builder = FontBuilder::new();
|
||||
builder.add_raw(Tag::new(b"name"), name);
|
||||
for r in font.table_directory.table_records() {
|
||||
let tag = Tag::new(&r.tag().to_be_bytes());
|
||||
if !builder.contains(tag) {
|
||||
builder.add_raw(tag, font.table_data(r.tag())?.as_bytes());
|
||||
}
|
||||
}
|
||||
Some(builder.build())
|
||||
}
|
||||
|
||||
/// The character whose glyph [`colour_bitmap_font`] draws as a colour bitmap.
|
||||
pub const COLOUR_CHAR: char = 'E';
|
||||
|
||||
|
||||
@@ -133,7 +133,7 @@ shown_when = [
|
||||
"The Selection tool after a click on the out port or the in port of selected area type or type on a path, threaded, overflowing or not: the pointer carries that text until a click threads it into a closed path, area type or type on a path, a click on empty canvas makes a new frame of the same kind and shape there, or a drag draws the new frame; from the in port the frame placed comes before the clicked one. Escape or another tool drops it.",
|
||||
]
|
||||
hotspot = "Where the new frame's top-left corner goes (the click), or the path clicked."
|
||||
look = "A small block of text lines: the overflow text the pointer carries. Until it is drawn it borrows the I-beam (Text)."
|
||||
look = "A small block of text lines: the overflow text the pointer carries."
|
||||
|
||||
# ── Pen family ────────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -7,8 +7,9 @@
|
||||
//! 45° steps round its anchor); drag a segment → reshape the curve, a selected blend's spine's too,
|
||||
//! straight or curved (#1111; Shift: its handles at right angles to the line between its anchors,
|
||||
//! at one length). Shift held at the press on an anchor moves it instead, handles and all (Shift
|
||||
//! still held: at 45° steps from where it was). Blend spine points and handles follow the same
|
||||
//! conversions (#2544).
|
||||
//! still held: at 45° steps from where it was). Space held during a convert- or handle-drag moves
|
||||
//! the anchor, handles and all, as while drawing with the Pen. Blend spine points and handles
|
||||
//! follow the same conversions (#2544).
|
||||
//! Scissors: click a path to split it there.
|
||||
|
||||
use serde_json::json;
|
||||
@@ -83,6 +84,15 @@ enum State {
|
||||
},
|
||||
}
|
||||
|
||||
/// Gesture to resume after Space is released mid-drag (#3694).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum SpaceResume {
|
||||
Convert { id: NodeId, si: usize, ai: usize },
|
||||
Handle { id: NodeId, si: usize, ai: usize, out: bool },
|
||||
SpineConvert { id: NodeId, ai: usize },
|
||||
SpineHandle { id: NodeId, ai: usize, out: bool },
|
||||
}
|
||||
|
||||
pub struct AnchorTool {
|
||||
id: &'static str,
|
||||
state: State,
|
||||
@@ -91,6 +101,8 @@ pub struct AnchorTool {
|
||||
snap: HandleSnap,
|
||||
/// Move offset while Shift-dragging an anchor or spine point (pointer, delta).
|
||||
measure: Option<(Point, f64, f64)>,
|
||||
/// While Space is held during a convert/handle drag, the shape gesture to return to.
|
||||
space_resume: Option<SpaceResume>,
|
||||
}
|
||||
|
||||
impl AnchorTool {
|
||||
@@ -101,7 +113,11 @@ impl AnchorTool {
|
||||
"scissors" => "scissors",
|
||||
_ => "addAnchor",
|
||||
};
|
||||
Self { id, state: State::Idle, guides: vec![], snap: HandleSnap::default(), measure: None }
|
||||
Self { id, state: State::Idle, guides: vec![], snap: HandleSnap::default(), measure: None, space_resume: None }
|
||||
}
|
||||
|
||||
fn anchor_pos(cx: &ToolContext, id: NodeId, si: usize, ai: usize) -> Option<Point> {
|
||||
cx.doc.node(id).and_then(|n| n.path_data()).and_then(|pd| pd.subpaths.get(si)?.anchors.get(ai).map(|a| a.p))
|
||||
}
|
||||
|
||||
/// Nearest point of this eligible spine, in document coordinates.
|
||||
@@ -216,6 +232,49 @@ impl AnchorTool {
|
||||
}
|
||||
}
|
||||
|
||||
fn space_move_from(cx: &ToolContext, st: State, p: Point, began: bool) -> (State, Option<SpaceResume>) {
|
||||
match st {
|
||||
State::Convert { id, si, ai, .. } => match Self::anchor_pos(cx, id, si, ai) {
|
||||
Some(from) => (State::Move { id, si, ai, from, start: p, began }, Some(SpaceResume::Convert { id, si, ai })),
|
||||
None => (st, None),
|
||||
},
|
||||
State::Handle { id, si, ai, out, .. } => match Self::anchor_pos(cx, id, si, ai) {
|
||||
Some(from) => (State::Move { id, si, ai, from, start: p, began }, Some(SpaceResume::Handle { id, si, ai, out })),
|
||||
None => (st, None),
|
||||
},
|
||||
State::SpineConvert { id, ai, .. } => {
|
||||
match crate::direct::spines(cx)
|
||||
.into_iter()
|
||||
.find(|(blend, _)| *blend == id)
|
||||
.and_then(|(_, path)| path.subpaths.first()?.anchors.get(ai).map(|a| a.p))
|
||||
{
|
||||
Some(from) => (State::SpineMove { id, ai, from, start: p, began }, Some(SpaceResume::SpineConvert { id, ai })),
|
||||
None => (st, None),
|
||||
}
|
||||
}
|
||||
State::SpineHandle { id, ai, out, .. } => {
|
||||
match crate::direct::spines(cx)
|
||||
.into_iter()
|
||||
.find(|(blend, _)| *blend == id)
|
||||
.and_then(|(_, path)| path.subpaths.first()?.anchors.get(ai).map(|a| a.p))
|
||||
{
|
||||
Some(from) => (State::SpineMove { id, ai, from, start: p, began }, Some(SpaceResume::SpineHandle { id, ai, out })),
|
||||
None => (st, None),
|
||||
}
|
||||
}
|
||||
other => (other, None),
|
||||
}
|
||||
}
|
||||
|
||||
fn resume_shape(p: Point, resume: SpaceResume, began: bool) -> State {
|
||||
match resume {
|
||||
SpaceResume::Convert { id, si, ai } => State::Convert { id, si, ai, start: p, began },
|
||||
SpaceResume::Handle { id, si, ai, out } => State::Handle { id, si, ai, out, start: p, began },
|
||||
SpaceResume::SpineConvert { id, ai } => State::SpineConvert { id, ai, start: p, began },
|
||||
SpaceResume::SpineHandle { id, ai, out } => State::SpineHandle { id, ai, out, start: p, began },
|
||||
}
|
||||
}
|
||||
|
||||
/// How far a Shift-dragged anchor has gone: Shift still held keeps it at 45° steps.
|
||||
fn move_delta(cx: &ToolContext, start: Point, p: Point, shift: bool) -> vectorcraft_geom::Vec2 {
|
||||
if shift { constrain_angle_from(p - start, 45.0, cx.constrain_angle) } else { p - start }
|
||||
@@ -266,6 +325,7 @@ impl Tool for AnchorTool {
|
||||
}
|
||||
}
|
||||
("anchorPoint", PointerKind::Down) => {
|
||||
self.space_resume = None;
|
||||
self.state = Self::press_target(cx, p);
|
||||
if ev.mods.shift {
|
||||
self.state = Self::moving(cx, self.state);
|
||||
@@ -310,6 +370,27 @@ impl Tool for AnchorTool {
|
||||
*began = true;
|
||||
}
|
||||
}
|
||||
if ev.mods.space {
|
||||
if self.space_resume.is_none()
|
||||
&& matches!(self.state, State::Convert { .. } | State::Handle { .. } | State::SpineConvert { .. } | State::SpineHandle { .. })
|
||||
{
|
||||
let was_began = match self.state {
|
||||
State::Convert { began, .. }
|
||||
| State::Handle { began, .. }
|
||||
| State::SpineConvert { began, .. }
|
||||
| State::SpineHandle { began, .. } => began,
|
||||
_ => false,
|
||||
};
|
||||
let (st, resume) = Self::space_move_from(cx, self.state, p, was_began);
|
||||
if let Some(r) = resume {
|
||||
self.state = st;
|
||||
self.space_resume = Some(r);
|
||||
}
|
||||
}
|
||||
} else if let Some(resume) = self.space_resume.take() {
|
||||
let was_began = matches!(self.state, State::Move { began: true, .. } | State::SpineMove { began: true, .. });
|
||||
self.state = Self::resume_shape(p, resume, was_began);
|
||||
}
|
||||
let preview = match self.state {
|
||||
State::Idle => return out,
|
||||
State::Convert { id, si, ai, .. } => Action::Preview(
|
||||
@@ -376,6 +457,7 @@ impl Tool for AnchorTool {
|
||||
("anchorPoint", PointerKind::Up) => {
|
||||
self.guides.clear();
|
||||
self.measure = None;
|
||||
self.space_resume = None;
|
||||
let st = std::mem::replace(&mut self.state, State::Idle);
|
||||
match st {
|
||||
State::Convert { began: true, .. }
|
||||
@@ -984,6 +1066,33 @@ mod tests {
|
||||
assert!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 200.0, 300.0).with_mods(shift)).is_empty());
|
||||
}
|
||||
|
||||
/// #3694: Space held mid-drag on a convert moves the anchor, handles and all.
|
||||
#[test]
|
||||
fn anchor_point_space_mid_drag_moves_the_anchor() {
|
||||
let (mut d, _) = doc_with_rect();
|
||||
let l = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let sp = vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 300.0), Point::new(200.0, 300.0), Point::new(300.0, 300.0)], false);
|
||||
d.insert(Some(l), 1, vectorcraft_doc::Node::path(id, vectorcraft_geom::PathData::single(sp), vectorcraft_doc::Appearance::default_art()))
|
||||
.unwrap();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let space = Mods { space: true, ..Mods::default() };
|
||||
let moved = |x: f64, y: f64| Action::Preview("path.moveAnchor".into(), json!({"id": id.0, "subpath": 0, "anchor": 1, "x": x, "y": y}));
|
||||
let mut t = AnchorTool::new("anchorPoint");
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.0, 300.0));
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 230.0, 340.0));
|
||||
assert!(matches!(&a[..], [Action::Begin(_), Action::Preview(c, _)] if c == "path.convertAnchor"), "{a:?}");
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 240.0, 350.0).with_mods(space));
|
||||
assert_eq!(a, vec![moved(200.0, 300.0)]);
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 250.0, 360.0).with_mods(space));
|
||||
assert_eq!(a, vec![moved(210.0, 310.0)]);
|
||||
let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 260.0, 370.0));
|
||||
assert!(matches!(&a[..], [Action::Preview(c, _)] if c == "path.convertAnchor"), "{a:?}");
|
||||
assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 260.0, 370.0)), vec![Action::Commit]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anchor_point_shift_drag_honors_measurement_labels() {
|
||||
let (mut d, _) = doc_with_rect();
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
//! vertical line through the press point.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::NodeId;
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use super::{FEEDBACK, eraser_area, points_json, polyline};
|
||||
@@ -58,6 +58,10 @@ pub struct GestureTool {
|
||||
/// "Alt key toggles to Smooth Tool": holding Alt with the Pencil tool smooths selected paths
|
||||
/// instead of closing the path (Pencil only, off by default).
|
||||
pub alt_smooth: bool,
|
||||
/// "Live preview" (Pencil only, on by default): the stroke shows with its fill and stroke as it
|
||||
/// is drawn. Off, only a thin line follows the pen while drawing, and the path takes its fill
|
||||
/// and stroke on release.
|
||||
pub live_preview: bool,
|
||||
/// "Live curve fitting": the Pencil's preview fits the stroke while it is drawn; off, the
|
||||
/// preview shows the points joined by straight segments and the release fits them (Pencil
|
||||
/// only, on by default).
|
||||
@@ -88,6 +92,17 @@ pub struct GestureTool {
|
||||
snap: DrawSnap,
|
||||
}
|
||||
|
||||
/// The paths a stroke can redraw for selected object `id`: the path itself, or a compound path's
|
||||
/// member paths.
|
||||
fn redraw_targets(cx: &ToolContext, id: NodeId) -> Vec<NodeId> {
|
||||
let Some(n) = cx.doc.node(id) else { return vec![] };
|
||||
match &n.kind {
|
||||
NodeKind::Path { .. } => vec![id],
|
||||
NodeKind::Compound { children, .. } => children.iter().filter(|c| c.path_data().is_some()).map(|c| c.id).collect(),
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
impl GestureTool {
|
||||
pub fn new(id: &str) -> Self {
|
||||
let id: &'static str = match id {
|
||||
@@ -120,6 +135,7 @@ impl GestureTool {
|
||||
keep_selected: id != "blobBrush",
|
||||
// Off, as Pencil Tool Options ships it: Alt keeps drawing a closed path until it is on.
|
||||
alt_smooth: false,
|
||||
live_preview: true,
|
||||
live_fit: true,
|
||||
smoothing: false,
|
||||
straight: false,
|
||||
@@ -143,6 +159,12 @@ impl GestureTool {
|
||||
matches!(self.id, "pencil" | "paintbrush")
|
||||
}
|
||||
|
||||
/// Does a stroke show as the path it draws while it is drawn? Not with the Pencil's Live preview
|
||||
/// off: then the drag shows as a thin line (an overlay) until the release.
|
||||
fn previews(&self) -> bool {
|
||||
self.id != "pencil" || self.live_preview
|
||||
}
|
||||
|
||||
/// Add a stroke sample.
|
||||
fn push(&mut self, p: Point, pressure: f32) {
|
||||
let raw = self.shift_next.take();
|
||||
@@ -269,9 +291,16 @@ impl GestureTool {
|
||||
if self.edit_within <= 0.0 || !tol.is_finite() {
|
||||
return None;
|
||||
}
|
||||
// A selected compound path (a shape with a hole) redraws the member path the stroke starts
|
||||
// on, the nearest of them: a compound path has no path of its own.
|
||||
cx.selection.objects.iter().find_map(|id| {
|
||||
let pd = cx.doc.node(*id).and_then(|n| n.path_data()).filter(|_| cx.doc.is_editable(*id))?;
|
||||
pd.nearest(p).filter(|n| n.4 <= tol).map(|_| (*id, tol))
|
||||
redraw_targets(cx, *id)
|
||||
.into_iter()
|
||||
.filter(|m| cx.doc.is_editable(*m))
|
||||
.filter_map(|m| Some((m, cx.doc.node(m)?.path_data()?.nearest(p)?.4)))
|
||||
.filter(|(_, d)| *d <= tol)
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
.map(|(m, _)| (m, tol))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -451,7 +480,8 @@ impl Tool for GestureTool {
|
||||
self.began = true;
|
||||
out.push(Action::Begin(self.label().into()));
|
||||
}
|
||||
if crate::previews_at(self.points.len()) {
|
||||
// With the Pencil's Live preview off a thin line shows instead (`overlays`).
|
||||
if self.previews() && crate::previews_at(self.points.len()) {
|
||||
self.previewed = self.points.len();
|
||||
let mut v = self.freehand_params(false);
|
||||
if !self.live_fit {
|
||||
@@ -503,6 +533,11 @@ impl Tool for GestureTool {
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
/// The freehand tools build their stroke from every position the pointer passed; the Join tool
|
||||
/// only needs where its scribble crosses the ends.
|
||||
fn wants_samples(&self) -> bool {
|
||||
matches!(self.id, "pencil" | "paintbrush" | "blobBrush" | "eraser" | "knife" | "smooth" | "pathEraser")
|
||||
}
|
||||
/// `[` and `]` are the Blob Brush's and the Eraser's: their size (#1661).
|
||||
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
|
||||
matches!(key, ToolKey::BracketLeft | ToolKey::BracketRight) && matches!(self.id, "blobBrush" | "eraser")
|
||||
@@ -549,7 +584,8 @@ impl Tool for GestureTool {
|
||||
}
|
||||
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
|
||||
let mut o = self.snap.guides().to_vec();
|
||||
if !self.active || self.points.len() < 2 || self.began {
|
||||
// A path being drawn shows itself, except with the Pencil's Live preview off.
|
||||
if !self.active || self.points.len() < 2 || (self.began && self.previews()) {
|
||||
return o;
|
||||
}
|
||||
let width = match self.id {
|
||||
@@ -564,6 +600,11 @@ impl Tool for GestureTool {
|
||||
return o;
|
||||
}
|
||||
o.push(Overlay::Path { path: polyline(&self.points), color, width, dashed: self.id == "knife" });
|
||||
if cx.measurement_labels && self.id == "blobBrush" {
|
||||
let last = self.points[self.points.len() - 1];
|
||||
let length = self.points.windows(2).map(|w| w[0].distance(w[1])).sum();
|
||||
o.push(Overlay::Measure { p: last + vectorcraft_geom::Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("L: {}", cx.len(length)) });
|
||||
}
|
||||
o
|
||||
}
|
||||
fn cursor(&self, cx: &ToolContext, p: Point, m: Mods) -> Cursor {
|
||||
@@ -609,6 +650,7 @@ impl Tool for GestureTool {
|
||||
"fidelity": self.fidelity,
|
||||
"fill": self.fill,
|
||||
"altSmooth": self.alt_smooth,
|
||||
"livePreview": self.live_preview,
|
||||
"liveFit": self.live_fit,
|
||||
"keepSelected": self.keep_selected,
|
||||
"editWithin": self.edit_within,
|
||||
@@ -638,6 +680,7 @@ impl Tool for GestureTool {
|
||||
"roundness" => self.roundness = v.as_f64().unwrap_or(self.roundness).clamp(1.0, 100.0),
|
||||
"fill" => self.fill = v.as_bool().unwrap_or(self.fill),
|
||||
"altSmooth" => self.alt_smooth = v.as_bool().unwrap_or(self.alt_smooth),
|
||||
"livePreview" if self.id == "pencil" => self.live_preview = v.as_bool().unwrap_or(self.live_preview),
|
||||
"liveFit" if self.id == "pencil" => self.live_fit = v.as_bool().unwrap_or(self.live_fit),
|
||||
"keepSelected" => self.keep_selected = v.as_bool().unwrap_or(self.keep_selected),
|
||||
"mergeOnlySelection" => self.merge_only_selection = v.as_bool().unwrap_or(self.merge_only_selection),
|
||||
@@ -794,9 +837,63 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// With the Pencil's Live preview off, a stroke previews nothing while it is drawn: a thin line
|
||||
/// follows the pen (an overlay), and the release draws the path with its fill and stroke. On (the
|
||||
/// default), every step previews the path and no line is shown. The Paintbrush has no such option.
|
||||
#[test]
|
||||
fn pencil_with_live_preview_off_shows_a_thin_line_until_the_release() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let cx = cx(&d, &s, &p);
|
||||
let previews = |acts: &[Action]| acts.iter().filter(|a| matches!(a, Action::Preview(..))).count();
|
||||
let line = |t: &GestureTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Path { width, .. } if *width == 1.0));
|
||||
let pts = [(0.0, 0.0), (10.0, 5.0), (20.0, 0.0), (30.0, 5.0)];
|
||||
for live in [true, false] {
|
||||
let mut t = GestureTool::new("pencil");
|
||||
assert_eq!(t.options()["livePreview"], json!(true), "on by default");
|
||||
t.set_option("livePreview", &json!(live));
|
||||
assert_eq!(t.options()["livePreview"], json!(live));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1));
|
||||
let mut during = vec![];
|
||||
for &(x, y) in &pts[1..] {
|
||||
during.extend(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, x, y)));
|
||||
}
|
||||
assert!(matches!(during.first(), Some(Action::Begin(_))), "live {live}: {during:?}");
|
||||
assert_eq!(previews(&during), if live { 3 } else { 0 }, "live {live}: {during:?}");
|
||||
assert_eq!(line(&t), !live, "live {live}: the thin line shows only with Live preview off");
|
||||
let up = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 30.0, 5.0));
|
||||
assert!(matches!(up.as_slice(), [Action::Preview(c, _), Action::Commit] if c == "path.freehand"), "live {live}: {up:?}");
|
||||
assert!(!line(&t), "live {live}: no line after the release");
|
||||
}
|
||||
// Escape mid-stroke with Live preview off cancels the stroke it began.
|
||||
let mut t = GestureTool::new("pencil");
|
||||
t.set_option("livePreview", &json!(false));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0));
|
||||
t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 10.0, 5.0));
|
||||
assert_eq!(t.key(&cx, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);
|
||||
// The Paintbrush keeps previewing: Live preview isn't one of its options.
|
||||
let mut b = GestureTool::new("paintbrush");
|
||||
assert!(b.options().get("livePreview").is_none());
|
||||
b.set_option("livePreview", &json!(false));
|
||||
b.pointer(&cx, &PointerEvent::new(PointerKind::Down, 0.0, 0.0));
|
||||
let acts = b.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 10.0, 5.0));
|
||||
assert_eq!(previews(&acts), 1, "{acts:?}");
|
||||
}
|
||||
|
||||
/// Holding Alt shows the Paintbrush's closing cursor before the press, and the Pencil's and the
|
||||
/// Paintbrush's while drawing (before a press, Alt gives the Pencil its straight-line cursor); a release
|
||||
/// with Alt still held closes the path, and Alt let go before the release leaves it open.
|
||||
/// The freehand tools take every position the pointer passed (`wants_samples`); the Join tool
|
||||
/// doesn't need them.
|
||||
#[test]
|
||||
fn the_freehand_tools_want_every_sample() {
|
||||
for id in ["pencil", "paintbrush", "blobBrush", "eraser", "knife", "smooth", "pathEraser"] {
|
||||
assert!(GestureTool::new(id).wants_samples(), "{id}");
|
||||
}
|
||||
assert!(!GestureTool::new("join").wants_samples());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alt_shows_the_closing_cursor_and_a_release_with_alt_closes() {
|
||||
let (d, _) = doc_with_rect();
|
||||
@@ -840,6 +937,24 @@ mod tests {
|
||||
assert_eq!(t.cursor(&cx, at, Mods::default()), Cursor::Smooth, "a smoothing drag");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blob_brush_drag_shows_scrub_length_measurement_labels() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let on = ToolContext { measurement_labels: true, ..cx(&d, &s, &p) };
|
||||
let off = ToolContext { measurement_labels: false, ..cx(&d, &s, &p) };
|
||||
let mut t = GestureTool::new("blobBrush");
|
||||
t.pointer(&on, &PointerEvent::new(PointerKind::Down, 50.0, 150.0));
|
||||
t.pointer(&on, &PointerEvent::new(PointerKind::Drag, 150.0, 150.0));
|
||||
let want = format!("L: {}", on.len(100.0));
|
||||
assert!(t.overlays(&on).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == &want)));
|
||||
let mut quiet = GestureTool::new("blobBrush");
|
||||
quiet.pointer(&off, &PointerEvent::new(PointerKind::Down, 50.0, 150.0));
|
||||
quiet.pointer(&off, &PointerEvent::new(PointerKind::Drag, 150.0, 150.0));
|
||||
assert!(!quiet.overlays(&off).iter().any(|o| matches!(o, Overlay::Measure { .. })));
|
||||
}
|
||||
|
||||
/// The Blob Brush has Keep selected and Merge only with selection, both off by default, and its
|
||||
/// stroke sends both.
|
||||
#[test]
|
||||
|
||||
+11
-2
@@ -30,6 +30,7 @@ pub mod pen;
|
||||
pub mod pie;
|
||||
pub mod place;
|
||||
pub mod printtiling;
|
||||
pub mod repeat_grid;
|
||||
pub mod rulerguide;
|
||||
pub mod select;
|
||||
pub mod settings;
|
||||
@@ -741,7 +742,7 @@ impl Cursor {
|
||||
}
|
||||
|
||||
/// The cursor this one borrows until it's drawn: the generic crosshair for the
|
||||
/// tools, the I-beam for vertical type and loaded text, the Pen's add cursor for the Mesh tool and Puppet
|
||||
/// tools, the I-beam for vertical type, the Pen's add cursor for the Mesh tool and Puppet
|
||||
/// Warp, not-allowed for the Scissors away from a path. `None` for a cursor with a look of
|
||||
/// its own.
|
||||
pub fn stand_in(self) -> Option<Self> {
|
||||
@@ -770,7 +771,7 @@ impl Cursor {
|
||||
| Cursor::SymbolScreener
|
||||
| Cursor::SymbolStyler
|
||||
| Cursor::Scissors => Some(Cursor::Crosshair),
|
||||
Cursor::TypeVertical | Cursor::LoadedText => Some(Cursor::Text),
|
||||
Cursor::TypeVertical => Some(Cursor::Text),
|
||||
Cursor::MeshAdd | Cursor::PuppetPin => Some(Cursor::PenAdd),
|
||||
Cursor::ScissorsNotAllowed => Some(Cursor::NotAllowed),
|
||||
_ => None,
|
||||
@@ -923,6 +924,14 @@ pub trait Tool: Send {
|
||||
fn wants_ticks(&self) -> bool {
|
||||
false
|
||||
}
|
||||
/// Does the tool build a stroke from the drag's samples (the Pencil and the other freehand
|
||||
/// tools)? The host then hands it every position the pointer passed between two frames, not
|
||||
/// only the last, so a fast stroke keeps its curve. Every other tool gets one drag a frame, so
|
||||
/// one whose drag preview is costly (moving a large selection, Free Distort, the Width tool)
|
||||
/// doesn't redo it for each sample.
|
||||
fn wants_samples(&self) -> bool {
|
||||
false
|
||||
}
|
||||
/// Is the tool waiting for work it runs on another thread (the planar map of a large selection
|
||||
/// for the Shape Builder and the Live Paint Bucket)? It highlights no region under the pointer
|
||||
/// until the work is done. While this holds, the desktop app calls [`Tool::poll`] each frame,
|
||||
|
||||
@@ -0,0 +1,395 @@
|
||||
//! Grid Repeat's on-canvas handles (#2691): a handle below the grid adds or removes rows, one right
|
||||
//! of it columns, one past its bottom-right corner both, and a slider between the first two
|
||||
//! columns (rows) sets the horizontal (vertical) spacing, as the public "Set grid repeat options"
|
||||
//! page describes. Drawing and hit testing share the document-space geometry of
|
||||
//! [`GridHandles::of`]; a drag previews the existing Repeat Options command and commits as one undo
|
||||
//! step.
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::pattern::tile_offset;
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind, OrientedBox, RepeatKind, Selection};
|
||||
use vectorcraft_geom::{Point, Rect, Vec2};
|
||||
|
||||
use crate::bbox::Handle;
|
||||
use crate::{Action, Cursor, Mods, ToolContext};
|
||||
|
||||
/// The radius of the row, column and corner handles (screen points).
|
||||
pub const HANDLE_RADIUS: f32 = 5.0;
|
||||
|
||||
/// How far (screen points) the row, column and corner handles sit outside the bounding box, clear
|
||||
/// of its own handles and rotate zones.
|
||||
pub const HANDLE_GAP: f64 = 22.0;
|
||||
|
||||
/// Half the length of a spacing slider's bar (screen points).
|
||||
pub const SLIDER_HALF: f32 = 7.0;
|
||||
|
||||
/// How near (screen points) a press must come to a handle to take it.
|
||||
const REACH: f64 = 8.0;
|
||||
|
||||
/// The smallest tile (source size plus spacing) a spacing slider leaves, in points.
|
||||
const MIN_TILE: f64 = 0.01;
|
||||
|
||||
/// The most rows or columns a grid repeat has (as `object.repeat.options` clamps them).
|
||||
const MAX_COUNT: f64 = 500.0;
|
||||
|
||||
/// A control of [`GridHandles`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum GridPart {
|
||||
/// Below the grid: drag down for more rows, up for fewer.
|
||||
Rows,
|
||||
/// Right of the grid: drag right for more columns, left for fewer.
|
||||
Cols,
|
||||
/// Past the bottom-right corner: rows and columns together.
|
||||
Corner,
|
||||
/// Between the first two columns: the horizontal spacing.
|
||||
HSpacing,
|
||||
/// Between the first two rows: the vertical spacing.
|
||||
VSpacing,
|
||||
}
|
||||
|
||||
impl GridPart {
|
||||
/// Whether the control draws as a slider bar rather than a round handle.
|
||||
pub fn is_slider(self) -> bool {
|
||||
matches!(self, Self::HSpacing | Self::VSpacing)
|
||||
}
|
||||
|
||||
/// The bounding-box handle whose resize cursor the control shows.
|
||||
fn handle(self) -> Handle {
|
||||
match self {
|
||||
Self::Rows | Self::VSpacing => Handle::Bottom,
|
||||
Self::Cols | Self::HSpacing => Handle::Right,
|
||||
Self::Corner => Handle::BottomRight,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The controls of a selected grid repeat, in document space.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct GridHandles {
|
||||
pub id: NodeId,
|
||||
rows: u32,
|
||||
cols: u32,
|
||||
h_spacing: f64,
|
||||
v_spacing: f64,
|
||||
/// The source's bounds (the first tile).
|
||||
source: Rect,
|
||||
/// From one column to the next (x) and one row to the next (y).
|
||||
step: Vec2,
|
||||
/// How much `step` moves for each point of spacing (0.75 along a hex grid's staggered axis).
|
||||
gain: Vec2,
|
||||
pub rows_at: Point,
|
||||
pub cols_at: Point,
|
||||
pub corner_at: Point,
|
||||
/// With two columns or more.
|
||||
pub h_slider: Option<Point>,
|
||||
/// With two rows or more.
|
||||
pub v_slider: Option<Point>,
|
||||
}
|
||||
|
||||
impl GridHandles {
|
||||
/// The controls of a single editable grid repeat selected whole, placed outside `frame` (the
|
||||
/// bounding box the Selection tool shows; its geometric bounds without one) at `zoom`.
|
||||
pub fn of(doc: &Document, selection: &Selection, frame: Option<OrientedBox>, zoom: f64) -> Option<Self> {
|
||||
let [id] = selection.objects.as_slice() else { return None };
|
||||
if !selection.anchors.is_empty() || !selection.segments.is_empty() || !doc.is_editable(*id) || !zoom.is_finite() || zoom <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let n = doc.node(*id)?;
|
||||
let NodeKind::Repeat(spec) = &n.kind else { return None };
|
||||
let RepeatKind::Grid { h_spacing, v_spacing, rows, cols, grid_type, .. } = spec.kind else { return None };
|
||||
if !h_spacing.is_finite() || !v_spacing.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let source = spec.source_bounds()?;
|
||||
// As `repeat_transforms` lays the tiles out.
|
||||
let (w, h) = ((source.width() + h_spacing).max(1e-3), (source.height() + v_spacing).max(1e-3));
|
||||
let step = Vec2::new(tile_offset(grid_type, w, h, 1, 0).x, tile_offset(grid_type, w, h, 0, 1).y);
|
||||
let gain = Vec2::new(tile_offset(grid_type, 1.0, 1.0, 1, 0).x, tile_offset(grid_type, 1.0, 1.0, 0, 1).y);
|
||||
if ![step.x, step.y, gain.x, gain.y].iter().all(|v| v.is_finite() && *v > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let frame = match frame {
|
||||
Some(f) => aabb(f.corners())?,
|
||||
None => n.geometric_bounds_with(&doc.symbol_boxes())?,
|
||||
};
|
||||
let gap = HANDLE_GAP / zoom;
|
||||
let (rows, cols) = (rows.clamp(1, 500), cols.clamp(1, 500));
|
||||
let g = Self {
|
||||
id: *id,
|
||||
rows,
|
||||
cols,
|
||||
h_spacing,
|
||||
v_spacing,
|
||||
source,
|
||||
step,
|
||||
gain,
|
||||
rows_at: Point::new(frame.center().x, frame.y1 + gap),
|
||||
cols_at: Point::new(frame.x1 + gap, frame.center().y),
|
||||
corner_at: Point::new(frame.x1 + gap, frame.y1 + gap),
|
||||
// Halfway between the right edge of the first column and the left edge of the second,
|
||||
// level with the first tile; likewise between the first two rows.
|
||||
h_slider: (cols > 1).then(|| Point::new(source.x0 + (source.width() + step.x) / 2.0, source.center().y)),
|
||||
v_slider: (rows > 1).then(|| Point::new(source.center().x, source.y0 + (source.height() + step.y) / 2.0)),
|
||||
};
|
||||
g.parts().iter().all(|(_, p)| finite(*p)).then_some(g)
|
||||
}
|
||||
|
||||
/// Every control with where it is: the round handles, then the sliders there are.
|
||||
pub fn parts(&self) -> Vec<(GridPart, Point)> {
|
||||
let mut v = vec![(GridPart::Rows, self.rows_at), (GridPart::Cols, self.cols_at), (GridPart::Corner, self.corner_at)];
|
||||
v.extend(self.h_slider.map(|p| (GridPart::HSpacing, p)));
|
||||
v.extend(self.v_slider.map(|p| (GridPart::VSpacing, p)));
|
||||
v
|
||||
}
|
||||
|
||||
/// The control under `p` (the nearest within reach) and the grid's controls, unless a
|
||||
/// bounding-box handle is there, which keeps its scaling.
|
||||
fn hit(cx: &ToolContext, p: Point) -> Option<(Self, GridPart)> {
|
||||
if !cx.show_bbox || !finite(p) {
|
||||
return None;
|
||||
}
|
||||
let g = Self::of(cx.doc, cx.selection, crate::select::selection_box(cx), cx.zoom)?;
|
||||
let reach = cx.tol(REACH);
|
||||
let (part, _) =
|
||||
g.parts().into_iter().map(|(part, q)| (part, q.distance(p))).filter(|(_, d)| *d <= reach).min_by(|a, b| a.1.total_cmp(&b.1))?;
|
||||
(!crate::select::bbox_handle_at(cx, p)).then_some((g, part))
|
||||
}
|
||||
|
||||
/// The Repeat Options that dragging `part` by `d` (document points) from the press gives.
|
||||
fn options(&self, part: GridPart, d: Vec2) -> Value {
|
||||
let count = |n: u32, by: f64, step: f64| (f64::from(n) + (by / step).round()).clamp(1.0, MAX_COUNT) as u32;
|
||||
// The slider sits halfway across the gap, which widens by `gain` for each point of spacing:
|
||||
// the spacing that keeps the slider under the pointer.
|
||||
let spacing = |s: f64, by: f64, gain: f64, size: f64| ((s + 2.0 * by / gain).max(MIN_TILE - size) * 100.0).round() / 100.0;
|
||||
match part {
|
||||
GridPart::Rows => json!({ "rows": count(self.rows, d.y, self.step.y) }),
|
||||
GridPart::Cols => json!({ "cols": count(self.cols, d.x, self.step.x) }),
|
||||
GridPart::Corner => json!({ "rows": count(self.rows, d.y, self.step.y), "cols": count(self.cols, d.x, self.step.x) }),
|
||||
GridPart::HSpacing => json!({ "hSpacing": spacing(self.h_spacing, d.x, self.gain.x, self.source.width()) }),
|
||||
GridPart::VSpacing => json!({ "vSpacing": spacing(self.v_spacing, d.y, self.gain.y, self.source.height()) }),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The page-square bounds of `corners`.
|
||||
fn aabb(corners: [Point; 4]) -> Option<Rect> {
|
||||
let r = corners.iter().skip(1).fold(Rect::from_points(corners[0], corners[0]), |r, p| r.union_pt(*p));
|
||||
[r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()).then_some(r)
|
||||
}
|
||||
|
||||
fn finite(p: Point) -> bool {
|
||||
p.x.is_finite() && p.y.is_finite()
|
||||
}
|
||||
|
||||
/// The resize cursor of `part`, turned with the view.
|
||||
fn part_cursor(cx: &ToolContext, part: GridPart) -> Cursor {
|
||||
crate::select::handle_cursor(part.handle(), -cx.view_angle())
|
||||
}
|
||||
|
||||
/// The cursor over a grid repeat's control at `p`, if one is there.
|
||||
pub fn cursor(cx: &ToolContext, p: Point) -> Option<Cursor> {
|
||||
let (_, part) = GridHandles::hit(cx, p)?;
|
||||
Some(part_cursor(cx, part))
|
||||
}
|
||||
|
||||
/// A drag of one of a grid repeat's controls.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GridDrag {
|
||||
grid: GridHandles,
|
||||
part: GridPart,
|
||||
start: Point,
|
||||
/// The options the press found, and the last ones previewed.
|
||||
from: Value,
|
||||
last: Option<Value>,
|
||||
}
|
||||
|
||||
impl GridDrag {
|
||||
pub fn hit(cx: &ToolContext, p: Point, mods: Mods) -> Option<Self> {
|
||||
if mods.cmd || mods.ctrl || mods.alt {
|
||||
return None;
|
||||
}
|
||||
let (grid, part) = GridHandles::hit(cx, p)?;
|
||||
Some(Self { grid, part, start: p, from: grid.options(part, Vec2::ZERO), last: None })
|
||||
}
|
||||
|
||||
/// Whether the drag has changed the grid (and so previews it).
|
||||
pub fn adjusting(&self) -> bool {
|
||||
self.last.is_some()
|
||||
}
|
||||
|
||||
pub fn cursor(&self, cx: &ToolContext) -> Cursor {
|
||||
part_cursor(cx, self.part)
|
||||
}
|
||||
|
||||
/// Preview the options the pointer at `p` gives, when they change; the first change opens
|
||||
/// the undo step.
|
||||
pub fn drag(&mut self, p: Point) -> Vec<Action> {
|
||||
if !finite(p) {
|
||||
return vec![];
|
||||
}
|
||||
let v = self.grid.options(self.part, p - self.start);
|
||||
if self.last.as_ref().unwrap_or(&self.from) == &v {
|
||||
return vec![];
|
||||
}
|
||||
let mut out = vec![];
|
||||
if self.last.is_none() {
|
||||
out.push(Action::Begin("Repeat Options".into()));
|
||||
}
|
||||
out.push(Action::Preview("object.repeat.options".into(), v.clone()));
|
||||
self.last = Some(v);
|
||||
out
|
||||
}
|
||||
|
||||
/// Commit the drag; one that ends where it began leaves no undo step.
|
||||
pub fn finish(self) -> Vec<Action> {
|
||||
match self.last {
|
||||
Some(v) if v == self.from => vec![Action::Cancel],
|
||||
Some(_) => vec![Action::Commit],
|
||||
None => vec![],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cancel(self) -> Vec<Action> {
|
||||
if self.last.is_some() { vec![Action::Cancel] } else { vec![] }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::testutil::{cx, doc_with_rect, paint};
|
||||
use std::sync::Arc;
|
||||
use vectorcraft_doc::pattern::RepeatSpec;
|
||||
|
||||
/// [`doc_with_rect`]'s 100 × 100 square at (100, 100) as a 3 × 3 grid repeat with 20 pt of
|
||||
/// spacing, selected: tiles every 120 pt, the grid 340 pt square.
|
||||
fn grid() -> (Document, Selection) {
|
||||
let (mut doc, id) = doc_with_rect();
|
||||
let mut source = doc.node(id).unwrap().clone();
|
||||
source.id = doc.alloc_id();
|
||||
doc.node_mut(id).unwrap().kind = NodeKind::Repeat(RepeatSpec::grid(vec![Arc::new(source)], 20.0, 20.0));
|
||||
let mut selection = Selection::default();
|
||||
selection.set([id]);
|
||||
(doc, selection)
|
||||
}
|
||||
|
||||
fn preview(out: &[Action]) -> Option<&Value> {
|
||||
out.iter().find_map(|a| match a {
|
||||
Action::Preview(cmd, v) if cmd == "object.repeat.options" => Some(v),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_handles_sit_outside_the_grid_at_every_zoom() {
|
||||
let (doc, selection) = grid();
|
||||
for zoom in [0.5, 1.0, 4.0] {
|
||||
let g = GridHandles::of(&doc, &selection, None, zoom).unwrap();
|
||||
let gap = HANDLE_GAP / zoom;
|
||||
assert_eq!(g.rows_at, Point::new(270.0, 440.0 + gap), "{zoom}");
|
||||
assert_eq!(g.cols_at, Point::new(440.0 + gap, 270.0), "{zoom}");
|
||||
assert_eq!(g.corner_at, Point::new(440.0 + gap, 440.0 + gap), "{zoom}");
|
||||
// Halfway across the gaps between the first two columns and rows.
|
||||
assert_eq!(g.h_slider, Some(Point::new(210.0, 150.0)), "{zoom}");
|
||||
assert_eq!(g.v_slider, Some(Point::new(150.0, 210.0)), "{zoom}");
|
||||
}
|
||||
// Placed outside the bounding box the Selection tool shows.
|
||||
let frame = OrientedBox::aligned(Rect::new(90.0, 90.0, 450.0, 450.0));
|
||||
let g = GridHandles::of(&doc, &selection, Some(frame), 1.0).unwrap();
|
||||
assert_eq!(g.rows_at, Point::new(270.0, 450.0 + HANDLE_GAP));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_handles_without_a_single_valid_grid_repeat() {
|
||||
let (mut doc, mut selection) = grid();
|
||||
for zoom in [0.0, -1.0, f64::NAN, f64::INFINITY] {
|
||||
assert!(GridHandles::of(&doc, &selection, None, zoom).is_none(), "{zoom}");
|
||||
}
|
||||
let paint = paint();
|
||||
let mut c = cx(&doc, &selection, &paint);
|
||||
let g = GridHandles::of(&doc, &selection, None, 1.0).unwrap();
|
||||
assert!(cursor(&c, g.rows_at).is_some());
|
||||
c.show_bbox = false;
|
||||
assert!(cursor(&c, g.rows_at).is_none(), "the bounding box is hidden");
|
||||
let id = selection.objects[0];
|
||||
let other = doc.alloc_id();
|
||||
let mut second = doc.node(id).unwrap().clone();
|
||||
second.id = other;
|
||||
let layer = doc.layers[0].id;
|
||||
doc.insert(Some(layer), 1, second).unwrap();
|
||||
selection.set([id, other]);
|
||||
assert!(GridHandles::of(&doc, &selection, None, 1.0).is_none(), "two objects selected");
|
||||
selection.set([id]);
|
||||
let NodeKind::Repeat(spec) = &mut doc.node_mut(id).unwrap().kind else { panic!("a repeat") };
|
||||
spec.kind = RepeatKind::Mirror { angle: 90.0, center: Point::ZERO };
|
||||
assert!(GridHandles::of(&doc, &selection, None, 1.0).is_none(), "a mirror repeat");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_by_one_grid_has_no_spacing_sliders() {
|
||||
let (mut doc, selection) = grid();
|
||||
let NodeKind::Repeat(spec) = &mut doc.node_mut(selection.objects[0]).unwrap().kind else { panic!("a repeat") };
|
||||
let RepeatKind::Grid { rows, cols, .. } = &mut spec.kind else { panic!("a grid") };
|
||||
(*rows, *cols) = (1, 1);
|
||||
let g = GridHandles::of(&doc, &selection, None, 1.0).unwrap();
|
||||
assert_eq!((g.h_slider, g.v_slider), (None, None));
|
||||
assert_eq!(g.parts().len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dragging_the_handles_previews_rows_columns_and_spacing() {
|
||||
let (doc, selection) = grid();
|
||||
let paint = paint();
|
||||
let c = cx(&doc, &selection, &paint);
|
||||
let g = GridHandles::of(&doc, &selection, crate::select::selection_box(&c), 1.0).unwrap();
|
||||
// Two tile heights down: five rows, one undo step.
|
||||
let mut d = GridDrag::hit(&c, g.rows_at, Mods::default()).unwrap();
|
||||
assert!(d.drag(g.rows_at + Vec2::new(0.0, 30.0)).is_empty(), "less than half a tile changes nothing");
|
||||
assert!(!d.adjusting());
|
||||
let out = d.drag(g.rows_at + Vec2::new(3.0, 240.0));
|
||||
assert!(matches!(out.first(), Some(Action::Begin(l)) if l == "Repeat Options"), "{out:?}");
|
||||
assert_eq!(preview(&out), Some(&json!({"rows": 5})));
|
||||
assert!(d.drag(g.rows_at + Vec2::new(0.0, 250.0)).is_empty(), "the same count isn't previewed again");
|
||||
assert!(matches!(d.finish().as_slice(), [Action::Commit]));
|
||||
// Left past the first column: one column at least.
|
||||
let mut d = GridDrag::hit(&c, g.cols_at, Mods::default()).unwrap();
|
||||
assert_eq!(preview(&d.drag(g.cols_at - Vec2::new(900.0, 0.0))), Some(&json!({"cols": 1})));
|
||||
let mut d = GridDrag::hit(&c, g.corner_at, Mods::default()).unwrap();
|
||||
assert_eq!(preview(&d.drag(g.corner_at + Vec2::new(120.0, -120.0))), Some(&json!({"rows": 2, "cols": 4})));
|
||||
// The spacing slider stays under the pointer: 10 pt right is 20 pt more spacing.
|
||||
let mut d = GridDrag::hit(&c, g.h_slider.unwrap(), Mods::default()).unwrap();
|
||||
assert_eq!(preview(&d.drag(g.h_slider.unwrap() + Vec2::new(10.0, 4.0))), Some(&json!({"hSpacing": 40.0})));
|
||||
// Back where it began: no undo step.
|
||||
assert_eq!(preview(&d.drag(g.h_slider.unwrap())), Some(&json!({"hSpacing": 20.0})));
|
||||
assert!(matches!(d.finish().as_slice(), [Action::Cancel]));
|
||||
// Overlapping tiles keep a tile of at least 0.01 pt.
|
||||
let mut d = GridDrag::hit(&c, g.v_slider.unwrap(), Mods::default()).unwrap();
|
||||
assert_eq!(preview(&d.drag(g.v_slider.unwrap() - Vec2::new(0.0, 500.0))), Some(&json!({"vSpacing": -99.99})));
|
||||
assert!(matches!(d.cancel().as_slice(), [Action::Cancel]));
|
||||
// Alt, Cmd and Ctrl keep the Selection tool's own gestures.
|
||||
assert!(GridDrag::hit(&c, g.rows_at, Mods { alt: true, ..Mods::default() }).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bounding_box_handle_wins_where_they_overlap() {
|
||||
let (doc, selection) = grid();
|
||||
let paint = paint();
|
||||
let mut c = cx(&doc, &selection, &paint);
|
||||
// Zoomed far out (the 340 pt grid 6.8 px across), the spacing slider lies on the top-left
|
||||
// bounding-box handle, which keeps its scaling; the round handles stay clear of the box.
|
||||
c.zoom = 0.02;
|
||||
let g = GridHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap();
|
||||
let slider = g.h_slider.unwrap();
|
||||
assert!(crate::select::bbox_handle_at(&c, slider));
|
||||
assert!(GridDrag::hit(&c, slider, Mods::default()).is_none());
|
||||
assert!(cursor(&c, slider).is_none());
|
||||
assert!(!crate::select::bbox_handle_at(&c, g.rows_at));
|
||||
assert!(GridDrag::hit(&c, g.rows_at, Mods::default()).is_some());
|
||||
// The spacing slider, inside the box, is the grid's.
|
||||
c.zoom = 1.0;
|
||||
let g = GridHandles::of(&doc, &selection, crate::select::selection_box(&c), c.zoom).unwrap();
|
||||
assert!(GridDrag::hit(&c, g.h_slider.unwrap(), Mods::default()).is_some());
|
||||
assert_eq!(cursor(&c, g.h_slider.unwrap()), Some(Cursor::ResizeH));
|
||||
assert_eq!(cursor(&c, g.rows_at), Some(Cursor::ResizeV));
|
||||
assert_eq!(cursor(&c, g.corner_at), Some(Cursor::ResizeNwSe));
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,10 @@
|
||||
//! kind, shape and size at the click on empty canvas, and a drag draws a rectangle for the new
|
||||
//! frame (`text.thread.add`), which comes after the clicked one in its thread. A click on the in
|
||||
//! port does the same with the new frame put before it: the story then starts there and flows on
|
||||
//! into the clicked one. Escape drops the loaded text.
|
||||
//! into the clicked one. Escape drops the loaded text. A double-click on a port where the frame is
|
||||
//! threaded splits the thread at that port (`text.thread.break`), as the archived help section on
|
||||
//! threading describes
|
||||
//! (<https://web.archive.org/web/20220127090642/https://helpx.adobe.com/illustrator/using/creating-text.html>).
|
||||
//! With Smart Guides and Invoke Distance Guides on, Alt/Option held over another object shows how
|
||||
//! far the selection is from it, and over an empty part of an artboard how far it is from the
|
||||
//! artboard's edges ([`crate::guides::distance_guides`]).
|
||||
@@ -93,6 +96,8 @@ enum State {
|
||||
Pie(PieDrag),
|
||||
/// Move or rotate a live mirror axis.
|
||||
Mirror(crate::mirror::MirrorDrag),
|
||||
/// Drag a grid repeat's row, column or corner handle or a spacing slider.
|
||||
GridRepeat(crate::repeat_grid::GridDrag),
|
||||
/// Dragging a bracket of type on a path.
|
||||
Bracket(BracketDrag),
|
||||
/// Loaded with the text of area type or type on a path `from` by a click on its out port, or
|
||||
@@ -496,6 +501,14 @@ impl SelectionTool {
|
||||
fn loaded(&mut self, cx: &ToolContext, ev: &PointerEvent, from: NodeId, before: bool, press: Option<(Point, Point)>) -> Option<Vec<Action>> {
|
||||
let p = ev.pos;
|
||||
match (ev.kind, press) {
|
||||
// The second press of a double-click on the port that loaded the text: the text is
|
||||
// put down, and the double-click breaks the thread there.
|
||||
(PointerKind::Down, _)
|
||||
if crate::text::port_at(cx, p) == Some((from, if before { crate::text::Port::In } else { crate::text::Port::Out })) =>
|
||||
{
|
||||
self.state = State::Idle;
|
||||
return Some(vec![]);
|
||||
}
|
||||
(PointerKind::Down, _) if !cx.doc.node(from).is_some_and(is_threadable) => {
|
||||
self.state = State::Idle;
|
||||
return None;
|
||||
@@ -560,6 +573,12 @@ impl Tool for SelectionTool {
|
||||
{
|
||||
return d.cancel();
|
||||
}
|
||||
if key == ToolKey::Escape
|
||||
&& matches!(self.state, State::GridRepeat(_))
|
||||
&& let State::GridRepeat(d) = std::mem::take(&mut self.state)
|
||||
{
|
||||
return d.cancel();
|
||||
}
|
||||
if key == ToolKey::Escape && matches!(self.state, State::Loaded { .. }) {
|
||||
self.state = State::Idle;
|
||||
return vec![];
|
||||
@@ -570,7 +589,7 @@ impl Tool for SelectionTool {
|
||||
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
|
||||
match self.state {
|
||||
State::Marquee { .. } => key == ToolKey::Letter('e'),
|
||||
State::Loaded { .. } | State::Mirror(_) => key == ToolKey::Escape,
|
||||
State::Loaded { .. } | State::Mirror(_) | State::GridRepeat(_) => key == ToolKey::Escape,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -593,6 +612,7 @@ impl Tool for SelectionTool {
|
||||
State::Pie(d) => d.adjusting(),
|
||||
State::Bracket(b) => b.adjusting(),
|
||||
State::Mirror(d) => d.adjusting(),
|
||||
State::GridRepeat(d) => d.adjusting(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -606,7 +626,8 @@ impl Tool for SelectionTool {
|
||||
{
|
||||
return out;
|
||||
}
|
||||
// Mirror controls take precedence over art, bounding handles and ruler guides.
|
||||
// Mirror and grid repeat controls take precedence over art and ruler guides; the mirror
|
||||
// axis line and the grid's controls yield to the bounding-box handles they overlap.
|
||||
if let State::Mirror(mut d) = self.state.clone() {
|
||||
match ev.kind {
|
||||
PointerKind::Drag | PointerKind::Up => {
|
||||
@@ -622,6 +643,21 @@ impl Tool for SelectionTool {
|
||||
_ => return vec![],
|
||||
}
|
||||
}
|
||||
if let State::GridRepeat(mut d) = self.state.clone() {
|
||||
match ev.kind {
|
||||
PointerKind::Drag | PointerKind::Up => {
|
||||
let mut out = d.drag(ev.pos);
|
||||
if ev.kind == PointerKind::Up {
|
||||
out.extend(d.finish());
|
||||
self.state = State::Idle;
|
||||
} else {
|
||||
self.state = State::GridRepeat(d);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
_ => return vec![],
|
||||
}
|
||||
}
|
||||
if matches!(self.state, State::Idle)
|
||||
&& ev.kind == PointerKind::Down
|
||||
&& let Some(d) = crate::mirror::MirrorDrag::hit(cx, ev.pos, ev.mods)
|
||||
@@ -630,6 +666,14 @@ impl Tool for SelectionTool {
|
||||
self.hover = None;
|
||||
return vec![];
|
||||
}
|
||||
if matches!(self.state, State::Idle)
|
||||
&& ev.kind == PointerKind::Down
|
||||
&& let Some(d) = crate::repeat_grid::GridDrag::hit(cx, ev.pos, ev.mods)
|
||||
{
|
||||
self.state = State::GridRepeat(d);
|
||||
self.hover = None;
|
||||
return vec![];
|
||||
}
|
||||
if let Some(out) = self.guide.pointer(cx, ev) {
|
||||
return out;
|
||||
}
|
||||
@@ -645,6 +689,16 @@ impl Tool for SelectionTool {
|
||||
match (ev.kind, self.state.clone()) {
|
||||
(PointerKind::DoubleClick, _) => {
|
||||
self.state = State::Idle;
|
||||
// A threaded port: the thread breaks there. Any other port takes the double-click
|
||||
// too, so it neither edits the type nor isolates.
|
||||
if let Some((id, port)) = crate::text::port_at(cx, p) {
|
||||
let (input, output) = crate::text::port_states(cx.doc, id, false);
|
||||
let (state, name) = if port == crate::text::Port::In { (input, "in") } else { (output, "out") };
|
||||
if state == crate::text::PortState::Threaded {
|
||||
return vec![Action::Exec("text.thread.break".into(), json!({ "id": id.0, "port": name }))];
|
||||
}
|
||||
return vec![];
|
||||
}
|
||||
if let Some(a) = corners::double_click(cx, p, false).or_else(|| pie::double_click(cx, p)).or_else(|| typewidget::double_click(cx, p))
|
||||
{
|
||||
return vec![a];
|
||||
@@ -925,11 +979,14 @@ impl Tool for SelectionTool {
|
||||
if let State::Mirror(d) = &self.state {
|
||||
return d.cursor(cx, p);
|
||||
}
|
||||
if let State::GridRepeat(d) = &self.state {
|
||||
return d.cursor(cx);
|
||||
}
|
||||
if matches!(self.state, State::Idle)
|
||||
&& !m.cmd
|
||||
&& !m.ctrl
|
||||
&& !m.alt
|
||||
&& let Some(cursor) = crate::mirror::cursor(cx, p)
|
||||
&& let Some(cursor) = crate::mirror::cursor(cx, p).or_else(|| crate::repeat_grid::cursor(cx, p))
|
||||
{
|
||||
return cursor;
|
||||
}
|
||||
@@ -1052,7 +1109,7 @@ pub(crate) fn release_guide_at(cx: &ToolContext, p: Point, m: Mods) -> Option<Ac
|
||||
/// The resize cursor for handle `h` of a box turned by `angle` (counter-clockwise degrees): the
|
||||
/// handle that sits where `h` appears on screen, in 45° steps. In a turned view, `angle` is the
|
||||
/// box's own angle less [`ToolContext::view_angle`].
|
||||
fn handle_cursor(h: Handle, angle: f64) -> Cursor {
|
||||
pub(crate) fn handle_cursor(h: Handle, angle: f64) -> Cursor {
|
||||
let steps = if angle.is_finite() { (angle / 45.0).round() as i64 } else { 0 };
|
||||
let h = Handle::ALL.get((h as i64 - steps).rem_euclid(8) as usize).copied().unwrap_or(h);
|
||||
match h {
|
||||
@@ -2684,6 +2741,35 @@ mod tests {
|
||||
assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, corner.x, corner.y)), vec![Action::Begin("Resize Type Area".into())]);
|
||||
}
|
||||
|
||||
/// A double-click on a threaded port breaks the thread there, its in port before the frame
|
||||
/// and its out port after it; it doesn't thread the loaded text into a new frame. A
|
||||
/// double-click on a port with no thread does nothing (it doesn't switch to the Type tool).
|
||||
#[test]
|
||||
fn a_double_click_on_a_threaded_port_breaks_the_thread() {
|
||||
let (mut d, id, input, output) = fitting_area_type();
|
||||
let rect = d.children(Some(d.layers[0].id)).unwrap()[0].id;
|
||||
let mut s = Selection::default();
|
||||
s.set([id]);
|
||||
let p = paint();
|
||||
let double_click = |d: &vectorcraft_doc::Document, at: Point| {
|
||||
let cx = cx(d, &s, &p);
|
||||
let mut t = SelectionTool::default();
|
||||
let kinds = [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick];
|
||||
let out: Vec<Action> = kinds.into_iter().flat_map(|k| t.pointer(&cx, &ev(k, at.x, at.y))).collect();
|
||||
assert_ne!(t.cursor(&cx, Point::new(30.0, 420.0), Mods::default()), Cursor::LoadedText, "no text stays loaded");
|
||||
out
|
||||
};
|
||||
let breaks = |port: &str| vec![Action::Exec("text.thread.break".into(), json!({"id": id.0, "port": port}))];
|
||||
d.text_threads = vec![vec![id, rect]];
|
||||
assert_eq!(double_click(&d, output), breaks("out"));
|
||||
assert_eq!(double_click(&d, input), vec![], "no frame before it");
|
||||
d.text_threads = vec![vec![rect, id]];
|
||||
assert_eq!(double_click(&d, input), breaks("in"));
|
||||
assert_eq!(double_click(&d, output), vec![], "no frame after it");
|
||||
d.text_threads.clear();
|
||||
assert_eq!(double_click(&d, output), vec![]);
|
||||
}
|
||||
|
||||
/// The memo answers for the revision, the selected objects and Use Preview Bounds it measured
|
||||
/// for, and measures again when any of them changes.
|
||||
#[test]
|
||||
|
||||
@@ -35,9 +35,9 @@ const ROWS: &[Row] = &[
|
||||
// Line Segment Tool Options: the Length and Angle a click's dialog opens with, Fill Line.
|
||||
(&["lineSegment"], None, &["length", "angle", "fillLine"]),
|
||||
(&["pencil", "paintbrush"], None, &["fidelity", "fill", "keepSelected", "editWithin", "closeWithin"]),
|
||||
// Pencil Tool Options' Alt key toggles to Smooth Tool and Live curve fitting (the Paintbrush
|
||||
// has neither option).
|
||||
(&["pencil"], None, &["altSmooth", "liveFit"]),
|
||||
// Pencil Tool Options' Alt key toggles to Smooth Tool, Live preview and Live curve fitting (the
|
||||
// Paintbrush has none of them).
|
||||
(&["pencil"], None, &["altSmooth", "livePreview", "liveFit"]),
|
||||
(&["smooth"], None, &["fidelity"]),
|
||||
(&["blobBrush", "eraser"], None, &["size"]),
|
||||
(&["blobBrush"], None, &["keepSelected", "mergeOnlySelection"]),
|
||||
|
||||
@@ -261,6 +261,9 @@ impl Tool for BrushPaintTool {
|
||||
self.inner.set_option(key, v);
|
||||
}
|
||||
}
|
||||
fn wants_samples(&self) -> bool {
|
||||
self.inner.wants_samples()
|
||||
}
|
||||
fn busy(&self) -> bool {
|
||||
self.inner.busy()
|
||||
}
|
||||
|
||||
+608
-37
@@ -196,9 +196,9 @@ fn pen_pressure(ui: &Ui, app: &VectorcraftApp, pressed: bool) -> f32 {
|
||||
|
||||
/// The positions this frame's pointer moves passed through before its last one, each with the
|
||||
/// pen force a touch event gave just before it, or the pressure the host's feed kept for that move
|
||||
/// ([`StylusFeed::take_moves`], macOS), if any. The last move is the pointer's position. Only for
|
||||
/// pens and fingers (frames with touch events or with the feed's moves): a mouse's moves are left
|
||||
/// as they were.
|
||||
/// ([`StylusFeed::take_moves`], macOS), if any. The last move is the pointer's position. A mouse's
|
||||
/// moves count too, with no pressure: a fast mouse stroke otherwise keeps one position a frame, a
|
||||
/// sample every few pixels, too few for a low Fidelity to follow the hand (#3328).
|
||||
fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>) -> Vec<(Pos2, Option<f32>)> {
|
||||
let pressures = stylus.map(StylusFeed::take_moves).unwrap_or_default();
|
||||
ui.input(|i| {
|
||||
@@ -219,6 +219,8 @@ fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>) -> Vec<(Pos2, Option<f32>)>
|
||||
let forces = pressures.iter().rev().map(|f| (*f > 0.0).then_some(*f)).chain(std::iter::repeat(None));
|
||||
moves = points.into_iter().rev().zip(forces).collect();
|
||||
moves.reverse();
|
||||
} else {
|
||||
moves = i.events.iter().filter_map(|e| if let egui::Event::PointerMoved(p) = e { Some((*p, None)) } else { None }).collect();
|
||||
}
|
||||
moves.pop();
|
||||
// A burst of events (a stalled frame) is thinned to a bounded count.
|
||||
@@ -231,6 +233,15 @@ fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>) -> Vec<(Pos2, Option<f32>)>
|
||||
})
|
||||
}
|
||||
|
||||
/// The moves of this frame ([`frame_moves`]) the active tool gets before the pointer's position:
|
||||
/// all of them for a tool that builds a stroke from them ([`vectorcraft_engine::Session::tool_wants_samples`]), none
|
||||
/// for the others, which get one drag a frame. The moves are read either way, so the host's feed
|
||||
/// pairs the next frame's with its own.
|
||||
fn tool_frame_moves(ui: &Ui, app: &VectorcraftApp) -> Vec<(Pos2, Option<f32>)> {
|
||||
let moves = frame_moves(ui, app.services.stylus.as_ref());
|
||||
if app.session.tool_wants_samples() { moves } else { vec![] }
|
||||
}
|
||||
|
||||
pub fn mods(m: egui::Modifiers, space: bool) -> Mods {
|
||||
Mods { shift: m.shift, alt: m.alt, cmd: m.command, ctrl: m.ctrl, space }
|
||||
}
|
||||
@@ -510,6 +521,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
isolated: key.isolated.map(vectorcraft_doc::NodeId),
|
||||
// Images far smaller on screen than they are sample their mip levels (#1244).
|
||||
image_mips: true,
|
||||
// An image whose pixels can't be decoded shows as a crossed box, and the status message
|
||||
// below reports it.
|
||||
mark_undecoded_images: true,
|
||||
// During a drag or a dialog's preview, objects that only moved draw their raster
|
||||
// effects from the cached rasters of an earlier frame (#1257).
|
||||
interacting: key.interacting,
|
||||
@@ -560,6 +574,12 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
}
|
||||
// The status bar reports each image that a renderer (this thread's or the worker's) could not
|
||||
// decode, once per image in the process.
|
||||
let undecoded = vectorcraft_render::newly_undecodable(doc.images.values());
|
||||
if undecoded > 0 {
|
||||
app.status(format!("{undecoded} image(s) couldn't be decoded and show as crossed boxes"));
|
||||
}
|
||||
if let (Some(tex), Some(k)) = (&app.canvas.texture, &app.canvas.key)
|
||||
&& k.doc == key.doc
|
||||
{
|
||||
@@ -678,6 +698,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
}
|
||||
selection_overlay(app, &painter, &xf, overlays.iter().any(|o| matches!(o, Overlay::CurvePoint { .. })));
|
||||
mirror_axis_overlay(app, &painter, &xf);
|
||||
grid_repeat_overlay(app, &painter, &xf);
|
||||
if app.ui.view.text_threads {
|
||||
// Under the tools' overlays: a selected frame's own ports are drawn over its thread's.
|
||||
let mut threads = thread_overlays(app, xf.zoom);
|
||||
@@ -878,7 +899,8 @@ fn cursor_icon(c: Cursor) -> egui::CursorIcon {
|
||||
| Cursor::GroupSelection
|
||||
| Cursor::CornerRadius
|
||||
| Cursor::PathBracket
|
||||
| Cursor::TypeWidget => C::Default,
|
||||
| Cursor::TypeWidget
|
||||
| Cursor::LoadedText => C::Default,
|
||||
Cursor::SelectionCopy => C::Copy,
|
||||
Cursor::Move => C::Move,
|
||||
Cursor::Crosshair => C::Crosshair,
|
||||
@@ -942,8 +964,7 @@ fn cursor_icon(c: Cursor) -> egui::CursorIcon {
|
||||
| Cursor::Scissors
|
||||
| Cursor::ScissorsNotAllowed
|
||||
| Cursor::MeshAdd
|
||||
| Cursor::PuppetPin
|
||||
| Cursor::LoadedText => cursor_icon(c.stand_in().unwrap_or(Cursor::Crosshair)),
|
||||
| Cursor::PuppetPin => cursor_icon(c.stand_in().unwrap_or(Cursor::Crosshair)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -972,11 +993,8 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
|
||||
{
|
||||
zoom_about(vm, rect, p, vm.zoom * factor);
|
||||
}
|
||||
if scroll != egui::Vec2::ZERO
|
||||
&& let Some(vm) = app.view_mut()
|
||||
{
|
||||
let d = Xf { rect, zoom: vm.zoom, center: vm.center, rot: vm.rotation.to_radians() }.delta_to_doc(scroll);
|
||||
vm.center -= d;
|
||||
if scroll != egui::Vec2::ZERO {
|
||||
scroll_view(app, ui, scroll);
|
||||
}
|
||||
if let Some(p) = hover
|
||||
&& let Some(deg) = trackpad_turn(ui, app.session.prefs.trackpad_rotate_view)
|
||||
@@ -1133,9 +1151,10 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
|
||||
ui.data_mut(|dd| dd.insert_temp(drag_pos_id(), p));
|
||||
match d {
|
||||
Drag::Pan { start, center, .. } => {
|
||||
let d = xf.delta_to_doc(p - start);
|
||||
let ppp = ui.ctx().pixels_per_point();
|
||||
if let Some(vm) = app.view_mut() {
|
||||
vm.center = center - d;
|
||||
vm.center = center;
|
||||
pan_pixels(vm, ppp, whole_pixels(p - start, ppp));
|
||||
}
|
||||
}
|
||||
Drag::RotateView { start_angle, start_rot, snaps } => {
|
||||
@@ -1185,13 +1204,16 @@ fn handle_input(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, rect:
|
||||
ui.data_mut(|dd| dd.insert_temp(drag_id(), Drag::Art));
|
||||
}
|
||||
Drag::Tool => {
|
||||
if tool_drag_moved(ui, &xf, p, &pointer) {
|
||||
// In a frame with touch events (a pen on Windows or the web, a finger) or a
|
||||
// macOS pen's moves, every position the pen passed, not just the last: a fast
|
||||
// stroke keeps its curve (a pen reports far more often than frames come).
|
||||
// Mouse events, a pen's on X11 among them, give the last position only, with
|
||||
// the host's latest pressure.
|
||||
for (at, force) in frame_moves(ui, app.services.stylus.as_ref()) {
|
||||
// Every position the pen or mouse passed this frame, not just the last, for a
|
||||
// tool that builds a stroke from them: a fast stroke keeps its curve (a pen or a
|
||||
// mouse reports far more often than frames come). Touch events (a pen on Windows
|
||||
// or the web, a finger) and a macOS pen's moves carry their own pressure; a
|
||||
// mouse's, a pen's on X11 among them, take the host's latest. Other tools get
|
||||
// the last position only, so a costly drag preview runs once a frame.
|
||||
let moves = tool_frame_moves(ui, app);
|
||||
// A frame whose pointer ends where the last one did still moved in between.
|
||||
if tool_drag_moved(ui, &xf, p, &pointer) || !moves.is_empty() {
|
||||
for (at, force) in moves {
|
||||
let pressure = force.unwrap_or_else(|| pen_pressure(ui, app, false));
|
||||
dispatch(app, &PointerEvent { kind: PointerKind::Drag, pos: xf.to_doc(at), mods: mods(m, space), pressure }, view);
|
||||
}
|
||||
@@ -1381,6 +1403,53 @@ fn rotate_about(vm: &mut View, rect: egui::Rect, p: Pos2, degrees: f64) {
|
||||
vm.center += before - Xf::new(rect, vm).to_doc(p);
|
||||
}
|
||||
|
||||
/// Move view `vm`'s content by `(dx, dy)` device pixels along the screen's axes, at `ppp` device
|
||||
/// pixels a point: the canvas's frame moves by exactly those pixels.
|
||||
fn pan_pixels(vm: &mut View, ppp: f32, (dx, dy): (f64, f64)) {
|
||||
let (sn, cs) = vm.rotation.to_radians().sin_cos();
|
||||
let k = vm.zoom * f64::from(ppp);
|
||||
vm.center -= vectorcraft_geom::Vec2::new((dx * cs + dy * sn) / k, (-dx * sn + dy * cs) / k);
|
||||
}
|
||||
|
||||
/// Screen points `d` in the nearest whole device pixels, at `ppp` device pixels a point.
|
||||
fn whole_pixels(d: egui::Vec2, ppp: f32) -> (f64, f64) {
|
||||
((f64::from(d.x) * f64::from(ppp)).round(), (f64::from(d.y) * f64::from(ppp)).round())
|
||||
}
|
||||
|
||||
/// What the scrolls of the view have left to move ([`scroll_view`]).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
struct ScrollRest {
|
||||
/// Device pixels along the screen's axes, at most half a pixel each.
|
||||
x: f64,
|
||||
y: f64,
|
||||
/// The document, the view's center, zoom and rotation, and the device pixels a point that the
|
||||
/// last scroll left.
|
||||
after: Option<(u64, Point, f64, f64, f32)>,
|
||||
}
|
||||
|
||||
/// Scroll the active view so that its content moves `by` screen points (the wheel, a trackpad, a
|
||||
/// touch screen, a scroll bar), in whole device pixels: the part of a pixel left over is added to
|
||||
/// the next scroll. It is dropped when the view changed in between (a zoom, a turn, Fit, a pan
|
||||
/// of another kind, another document) or the device pixels a point did.
|
||||
fn scroll_view(app: &mut VectorcraftApp, ui: &Ui, by: egui::Vec2) {
|
||||
let ppp = ui.ctx().pixels_per_point();
|
||||
let Some(doc) = app.session.active().map(|st| st.uid) else { return };
|
||||
let Some(vm) = app.view_mut() else { return };
|
||||
let id = egui::Id::unique("canvas-scroll-rest");
|
||||
let rest = scroll_by(vm, doc, ppp, by, ui.data(|d| d.get_temp(id)).unwrap_or_default());
|
||||
ui.data_mut(|d| d.insert_temp(id, rest));
|
||||
}
|
||||
|
||||
/// [`scroll_view`] for view `vm` of document `doc` at `ppp` device pixels a point, after the
|
||||
/// scrolls that left `rest`: what this scroll leaves.
|
||||
fn scroll_by(vm: &mut View, doc: u64, ppp: f32, by: egui::Vec2, rest: ScrollRest) -> ScrollRest {
|
||||
let (x, y) = if rest.after == Some((doc, vm.center, vm.zoom, vm.rotation, ppp)) { (rest.x, rest.y) } else { (0.0, 0.0) };
|
||||
let (x, y) = (x + f64::from(by.x) * f64::from(ppp), y + f64::from(by.y) * f64::from(ppp));
|
||||
let (dx, dy) = (x.round(), y.round());
|
||||
pan_pixels(vm, ppp, (dx, dy));
|
||||
ScrollRest { x: x - dx, y: y - dy, after: Some((doc, vm.center, vm.zoom, vm.rotation, ppp)) }
|
||||
}
|
||||
|
||||
/// How far a trackpad rotation turns before it turns the view, in degrees.
|
||||
const ROTATE_DEAD_ZONE: f64 = 5.0;
|
||||
/// How long after its last rotation event a trackpad rotation ends, in seconds.
|
||||
@@ -1491,7 +1560,8 @@ fn scroll_bars(app: &mut VectorcraftApp, ui: &Ui, rect: egui::Rect, outer: egui:
|
||||
let painter = ui.painter();
|
||||
painter.rect_filled(egui::Rect::from_min_max(outer.max - vec2(SCROLL_BAR, SCROLL_BAR), outer.max), 0.0, t.ruler);
|
||||
let hover = ui.input(|i| i.pointer.hover_pos());
|
||||
// Screen points the view moves this frame, or the centre a dragged thumb puts it at.
|
||||
// Screen points the view moves this frame, or the center a dragged thumb's drag began at and
|
||||
// the screen points it has moved the view since.
|
||||
let mut moved = egui::Vec2::ZERO;
|
||||
let mut center = None;
|
||||
for (k, (track, span)) in scroll_tracks(rect, outer).into_iter().zip(scroll_spans(&xf, content)).enumerate() {
|
||||
@@ -1517,7 +1587,7 @@ fn scroll_bars(app: &mut VectorcraftApp, ui: &Ui, rect: egui::Rect, outer: egui:
|
||||
&& let Some(p) = resp.interact_pointer_pos()
|
||||
{
|
||||
let by = ((along(p) - d.from) * d.ratio).clamp(d.min, d.max);
|
||||
center = Some(d.center + xf.delta_to_doc(axis * by));
|
||||
center = Some((d.center, axis * by));
|
||||
}
|
||||
if !resp.dragged() || resp.drag_stopped() {
|
||||
ui.data_mut(|dd| dd.remove::<ThumbDrag>(id));
|
||||
@@ -1548,12 +1618,15 @@ fn scroll_bars(app: &mut VectorcraftApp, ui: &Ui, rect: egui::Rect, outer: egui:
|
||||
let hot = drag.is_some() || hover.is_some_and(|p| thumb.contains(p));
|
||||
painter.rect_filled(thumb, CornerRadius::same(3), if hot { t.text_dim } else { t.text_disabled });
|
||||
}
|
||||
let Some(vm) = app.view_mut() else { return };
|
||||
if let Some(c) = center {
|
||||
let ppp = ui.ctx().pixels_per_point();
|
||||
if let Some((c, by)) = center
|
||||
&& let Some(vm) = app.view_mut()
|
||||
{
|
||||
vm.center = c;
|
||||
pan_pixels(vm, ppp, whole_pixels(-by, ppp));
|
||||
}
|
||||
if moved != egui::Vec2::ZERO {
|
||||
vm.center += xf.delta_to_doc(moved);
|
||||
scroll_view(app, ui, -moved);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2479,6 +2552,12 @@ fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Response, xf: &Xf)
|
||||
widgets::PanelDrag::Brush { name, .. } => {
|
||||
("brush.apply", json!({"name": name, "ids": [vectorcraft_tools::xform::paint_owner(&st.doc, hit.leaf).0]}))
|
||||
}
|
||||
// A brush from a brush library panel: added to the document's Brushes and applied to the
|
||||
// path it lands on, in one step.
|
||||
widgets::PanelDrag::LibraryBrush { library, name } => (
|
||||
"brush.addFromLibrary",
|
||||
json!({"library": library, "name": name, "apply": true, "ids": [vectorcraft_tools::xform::paint_owner(&st.doc, hit.leaf).0]}),
|
||||
),
|
||||
// Art dragged back onto the canvas: its move was already dropped. (A symbol was placed
|
||||
// above.)
|
||||
widgets::PanelDrag::Art(_)
|
||||
@@ -2843,6 +2922,36 @@ fn mirror_axis_overlay(app: &VectorcraftApp, p: &egui::Painter, xf: &Xf) {
|
||||
p.rect_stroke(handle, 2.0, Stroke::new(2.0, t.measure_bg), StrokeKind::Outside);
|
||||
}
|
||||
|
||||
/// A selected grid repeat's row, column and corner handles and its spacing sliders (#2691), at
|
||||
/// the places the Selection tool's hit testing finds them.
|
||||
fn grid_repeat_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: &Xf) {
|
||||
use vectorcraft_tools::repeat_grid::{GridHandles, GridPart, HANDLE_RADIUS, SLIDER_HALF};
|
||||
if app.session.tool_id() != "selection" || !app.ui.view.bounding_box {
|
||||
return;
|
||||
}
|
||||
let frame = app.selection_box();
|
||||
let Some(st) = app.session.active() else { return };
|
||||
let Some(grid) = GridHandles::of(&st.doc, &st.selection, frame, xf.zoom) else { return };
|
||||
let t = Tokens::get(p.ctx());
|
||||
let half = f64::from(SLIDER_HALF) / xf.zoom;
|
||||
for (part, at) in grid.parts() {
|
||||
let c = xf.to_screen(at);
|
||||
if !c.is_finite() {
|
||||
continue;
|
||||
}
|
||||
if part.is_slider() {
|
||||
// A bar across the gap's middle, square to the spacing it sets.
|
||||
let along = if part == GridPart::HSpacing { vectorcraft_geom::Vec2::new(0.0, half) } else { vectorcraft_geom::Vec2::new(half, 0.0) };
|
||||
let ends = [xf.to_screen(at - along), xf.to_screen(at + along)];
|
||||
p.line_segment(ends, Stroke::new(6.0, t.measure_bg));
|
||||
p.line_segment(ends, Stroke::new(2.5, t.selection));
|
||||
} else {
|
||||
p.circle_filled(c, HANDLE_RADIUS, t.measure_bg);
|
||||
p.circle_stroke(c, HANDLE_RADIUS, Stroke::new(2.0, t.selection));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The radius of the Rotate View dial, in screen points.
|
||||
const DIAL_RADIUS: f32 = 40.0;
|
||||
|
||||
@@ -3524,11 +3633,12 @@ pub(crate) fn color_image(img: &vectorcraft_render::Rendered) -> egui::ColorImag
|
||||
}
|
||||
|
||||
/// The pixels of the `w`×`h` frame through `view` to render again for `doc`, when only the document
|
||||
/// changed since the frame shown (its key `key` but for the revision, and its render options
|
||||
/// `opts`), which this thread rendered, and no frame is on its way from the worker: those it
|
||||
/// changed in (`Some(None)`: none), grown to whole eighths of the frame, as long as they are at
|
||||
/// most half of it. None: render the whole frame. Frames the worker renders stay
|
||||
/// whole: its renderer keeps the rasters of the art's effects, this thread's doesn't.
|
||||
/// changed, or placed documents' bitmaps were made, since the frame shown (its key `key` but for
|
||||
/// the revision and [`CacheKey::placed`], and its render options `opts`), which this thread
|
||||
/// rendered, and no frame is on its way from the worker: those it changed in, and those the
|
||||
/// objects showing those bitmaps' files cover (`Some(None)`: none), grown to whole eighths of the
|
||||
/// frame, as long as they are at most half of it. None: render the whole frame. Frames the worker
|
||||
/// renders stay whole: its renderer keeps the rasters of the art's effects, this thread's doesn't.
|
||||
fn changed_pixels(
|
||||
app: &VectorcraftApp,
|
||||
key: &CacheKey,
|
||||
@@ -3543,11 +3653,18 @@ fn changed_pixels(
|
||||
if opts.mask_view.is_some() {
|
||||
return None;
|
||||
}
|
||||
let same_view = app.canvas.key.as_ref().is_some_and(|k| *k == CacheKey { revision: k.revision, ..key.clone() });
|
||||
let shown_key = app.canvas.key.as_ref()?;
|
||||
let same_view = *shown_key == CacheKey { revision: shown_key.revision, placed: shown_key.placed, ..key.clone() };
|
||||
if !same_view || app.canvas.texture.is_none() || app.canvas.from_worker || app.canvas.worker.as_ref().is_some_and(|w| w.pending.is_some()) {
|
||||
return None;
|
||||
}
|
||||
match vectorcraft_render::changed(shown, doc) {
|
||||
// The placed documents' files whose bitmaps were made since the frame shown.
|
||||
let placed = if shown_key.placed == key.placed {
|
||||
vectorcraft_render::Changed::Nothing
|
||||
} else {
|
||||
vectorcraft_render::placed_area(doc, &vectorcraft_render::placed_document::made_between(shown_key.placed, key.placed)?)
|
||||
};
|
||||
match vectorcraft_render::changed(shown, doc).and(placed) {
|
||||
vectorcraft_render::Changed::Nothing => Some(None),
|
||||
vectorcraft_render::Changed::Area(area) => match vectorcraft_render::view_pixels(area, view, w, h) {
|
||||
None => Some(None),
|
||||
@@ -5355,6 +5472,67 @@ mod tests {
|
||||
assert!(canvas(&app, delta).is_some_and(|(pos, _)| pos.is_none()), "a new view renders all of it");
|
||||
}
|
||||
|
||||
/// A placed document's bitmap made in the background renders the canvas again only where the
|
||||
/// objects showing its file are: both copies of the file are in the part rendered again.
|
||||
#[test]
|
||||
fn a_ready_placed_document_bitmap_renders_only_its_part_of_the_canvas() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width":400,"height":300})).unwrap();
|
||||
app.ui.task_bar = false;
|
||||
app.ui.view.rulers = false;
|
||||
app.canvas.worker_started = true; // every frame on this thread, however long it takes
|
||||
// A document of one 60 × 30 artboard with a rectangle, placed linked twice.
|
||||
let mut src = Session::new();
|
||||
src.execute("file.new", &json!({"width": 60, "height": 30})).unwrap();
|
||||
src.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 60, "height": 30})).unwrap();
|
||||
let dir = std::env::temp_dir().join(format!("vectorcraft-placed-redraw-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let path = dir.join("card.vectorcraft");
|
||||
std::fs::write(&path, vectorcraft_format::save_file(&src.active().unwrap().doc)).unwrap();
|
||||
let path = path.to_string_lossy().into_owned();
|
||||
let ids: Vec<u64> = [[60, 50], [140, 50]]
|
||||
.iter()
|
||||
.map(|at| {
|
||||
let r = app.session.execute("file.place", &json!({"path": path, "at": at})).unwrap();
|
||||
assert_eq!(r["linked"], true, "{r}");
|
||||
r["ids"][0].as_u64().unwrap()
|
||||
})
|
||||
.collect();
|
||||
app.run("shape.rectangle", json!({"x":250,"y":200,"width":40,"height":30})).unwrap();
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
// Where the canvas texture changed in a frame, and how much of it.
|
||||
let canvas = |app: &VectorcraftApp, mut delta: egui::TexturesDelta| {
|
||||
let tex = app.canvas.texture.as_ref().map(|t| t.id());
|
||||
let set = delta.set.iter().find(|(t, _)| tex == Some(**t)).and_then(|(_, d)| d.last()).map(|d| (d.pos, d.image.size()));
|
||||
delta.clear();
|
||||
set
|
||||
};
|
||||
let (_, delta) = frame_output(&mut app, &ctx);
|
||||
assert!(canvas(&app, delta).is_some_and(|(pos, _)| pos.is_none()), "the first frame renders all of it");
|
||||
let t = std::time::Instant::now();
|
||||
while vectorcraft_render::placed_document::busy() && t.elapsed().as_secs() < 20 {
|
||||
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||
}
|
||||
let (_, delta) = frame_output(&mut app, &ctx);
|
||||
let (pos, size) = canvas(&app, delta).expect("the bitmap shows");
|
||||
let [px, py] = pos.expect("a part of the canvas");
|
||||
let key = app.canvas.key.clone().unwrap();
|
||||
let view = Affine::translate((f64::from(key.w) / 2.0, f64::from(key.h) / 2.0))
|
||||
* Affine::rotate(key.rot.to_radians())
|
||||
* Affine::scale(key.zoom * f64::from(key.ppp))
|
||||
* Affine::translate((-key.cx, -key.cy));
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
for id in ids {
|
||||
let b = doc.node(vectorcraft_doc::NodeId(id)).unwrap().geometric_bounds().unwrap();
|
||||
let [x0, y0, x1, y1] = vectorcraft_render::view_pixels(b, view, key.w, key.h).unwrap();
|
||||
let inside = x0 as usize >= px && y0 as usize >= py && x1 as usize <= px + size[0] && y1 as usize <= py + size[1];
|
||||
assert!(inside, "object {id} at {:?} in the part at {:?} of size {size:?}", [x0, y0, x1, y1], [px, py]);
|
||||
}
|
||||
assert!(size[0] * size[1] * 2 <= key.w as usize * key.h as usize, "a part of it: {size:?}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// While an opacity mask is viewed, an edit renders all of the canvas: the mask view shows the
|
||||
/// mask's coverage wherever its art reaches, past its object's bounds.
|
||||
#[test]
|
||||
@@ -5653,6 +5831,55 @@ mod tests {
|
||||
assert_eq!(pink(&mut app), Some(on), "on again, as before");
|
||||
}
|
||||
|
||||
/// Images whose pixels can't be decoded draw as crossed boxes on the canvas, and the status
|
||||
/// bar reports each of them once: two such images give one message, and later frames that
|
||||
/// draw them again give none.
|
||||
#[test]
|
||||
fn undecodable_images_are_marked_and_reported_once() {
|
||||
use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind};
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
app.canvas.worker_started = true; // render on this thread
|
||||
// PNGs of noisy pixels cut off halfway: their headers read, their pixels don't decode.
|
||||
let cut = |w: u32| {
|
||||
let img = image::RgbaImage::from_fn(w, 41, |x, y| image::Rgba([(x * 37 + y * 101) as u8, (x * y) as u8, (x ^ y) as u8, 255]));
|
||||
let mut png = vec![];
|
||||
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
png.truncate(png.len() / 2);
|
||||
png
|
||||
};
|
||||
{
|
||||
let st = app.session.doc_mut().unwrap();
|
||||
let d = std::sync::Arc::make_mut(&mut st.doc);
|
||||
for (i, w) in [53u32, 59].into_iter().enumerate() {
|
||||
let key = format!("cut{i}");
|
||||
d.images.insert(key.clone(), ImageBlob::new("image/png", cut(w)));
|
||||
let im = ImageObject {
|
||||
key,
|
||||
width: w,
|
||||
height: 41,
|
||||
xf: Affine::translate((40.0 + 150.0 * i as f64, 100.0)),
|
||||
link: None,
|
||||
placement: Default::default(),
|
||||
pixels: None,
|
||||
};
|
||||
let (id, layer) = (d.alloc_id(), d.layers[0].id);
|
||||
d.insert(Some(layer), 0, Node::new(id, NodeKind::Image(Box::new(im)))).unwrap();
|
||||
}
|
||||
st.revision += 1;
|
||||
}
|
||||
let ctx = egui::Context::default();
|
||||
app.status("");
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert!(app.canvas.shown.as_ref().is_some_and(|(_, o)| o.mark_undecoded_images), "the canvas marks them");
|
||||
assert_eq!(app.ui.status, "2 image(s) couldn't be decoded and show as crossed boxes");
|
||||
app.status("");
|
||||
app.session.doc_mut().unwrap().revision += 1;
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.ui.status, "", "said once");
|
||||
}
|
||||
|
||||
/// A drag of an object with raster effects (#1257): the drag's frames render while
|
||||
/// interacting and draw the object's drop shadow and filtered content from the rasters of the
|
||||
/// frame before; the frame after the drag renders without `interacting`, on the render worker,
|
||||
@@ -6490,6 +6717,79 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A selected grid repeat draws its row handle below the grid and a slider between its first
|
||||
/// two columns (none with the bounding box hidden). Dragging the row handle down two tiles in
|
||||
/// a zoomed view makes five rows without scaling the source, as one undo step, and the slider
|
||||
/// sets the horizontal spacing (#2691).
|
||||
#[test]
|
||||
fn grid_repeat_handles_set_rows_and_spacing_in_one_undo_step_each() {
|
||||
use vectorcraft_tools::repeat_grid::{GridHandles, HANDLE_RADIUS};
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": 40, "y": 40, "width": 40, "height": 40})).unwrap();
|
||||
app.run("object.repeat.grid", json!({"hSpacing": 10, "vSpacing": 10})).unwrap();
|
||||
app.ui.task_bar = false;
|
||||
app.ui.view.rulers = false;
|
||||
let ctx = egui::Context::default();
|
||||
// The first frame fits the artboard in the window; then zoom to 1.5 px a point.
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
app.view_mut().unwrap().zoom = 1.5;
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.view().unwrap().zoom, 1.5);
|
||||
// Rows, columns, horizontal spacing and the source's bounds.
|
||||
let grid = |app: &VectorcraftApp| {
|
||||
let st = app.session.active().unwrap();
|
||||
let n = st.doc.node(st.selection.objects[0]).unwrap();
|
||||
let vectorcraft_doc::NodeKind::Repeat(spec) = &n.kind else { panic!("a repeat") };
|
||||
let vectorcraft_doc::RepeatKind::Grid { rows, cols, h_spacing, .. } = spec.kind else { panic!("a grid repeat") };
|
||||
(rows, cols, h_spacing, spec.source_bounds().unwrap())
|
||||
};
|
||||
let handles = |app: &mut VectorcraftApp| {
|
||||
let frame = app.selection_box();
|
||||
let st = app.session.active().unwrap();
|
||||
GridHandles::of(&st.doc, &st.selection, frame, app.view().unwrap().zoom).unwrap()
|
||||
};
|
||||
let before = grid(&app);
|
||||
assert_eq!((before.0, before.1, before.2), (3, 3, 10.0));
|
||||
let g = handles(&mut app);
|
||||
let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
|
||||
let drawn = shapes(&mut app, &ctx);
|
||||
let circle_at = |drawn: &[Shape], at: Pos2| {
|
||||
drawn.iter().any(|s| matches!(s, Shape::Circle(c) if c.center.distance(at) < 0.01 && c.radius == HANDLE_RADIUS))
|
||||
};
|
||||
assert!(circle_at(&drawn, xf.to_screen(g.rows_at)), "the row handle is drawn");
|
||||
assert!(circle_at(&drawn, xf.to_screen(g.corner_at)), "the corner handle is drawn");
|
||||
app.ui.view.bounding_box = false;
|
||||
assert!(!circle_at(&shapes(&mut app, &ctx), xf.to_screen(g.rows_at)), "hidden with the bounding box");
|
||||
app.ui.view.bounding_box = true;
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
let drag = |app: &mut VectorcraftApp, from: Pos2, by: egui::Vec2| {
|
||||
frame(app, &ctx, vec![egui::Event::PointerMoved(from), button(from, true)]);
|
||||
for k in 1..=4 {
|
||||
frame(app, &ctx, vec![egui::Event::PointerMoved(from + by * k as f32 / 4.0)]);
|
||||
}
|
||||
frame(app, &ctx, vec![button(from + by, false)]);
|
||||
};
|
||||
// Two tiles of 50 pt down, at 1.5 px a point.
|
||||
drag(&mut app, xf.to_screen(g.rows_at), vec2(0.0, 150.0));
|
||||
let after = grid(&app);
|
||||
assert_eq!((after.0, after.1, after.2), (5, 3, 10.0));
|
||||
assert_eq!(after.3, before.3, "the source keeps its size");
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(grid(&app).0, 3, "one undo step");
|
||||
app.run("edit.redo", json!({})).unwrap();
|
||||
assert_eq!(grid(&app).0, 5);
|
||||
// The slider between the first two columns, 6 px (4 pt) right: it stays halfway across a
|
||||
// gap 8 pt wider, 18 pt of spacing.
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let g = handles(&mut app);
|
||||
drag(&mut app, xf.to_screen(g.h_slider.unwrap()), vec2(6.0, 0.0));
|
||||
assert_eq!(grid(&app).2, 18.0);
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!((grid(&app).0, grid(&app).2), (5, 10.0), "the spacing's own undo step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn top_bounding_box_handle_scales_a_default_mirror_repeat() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
@@ -6780,11 +7080,12 @@ mod tests {
|
||||
assert_ne!(app.view().unwrap().center, before, "frame {k}: the wheel scrolls the view");
|
||||
assert_eq!(cursor(&app), Some(Cursor::Move), "frame {k}: the cursor stays while the view moves");
|
||||
}
|
||||
// The wheel's smooth scrolling runs on for some frames; then the view rests.
|
||||
// The wheel's smooth scrolling runs on for some frames; then the view rests. A frame of it
|
||||
// that scrolls less than half a device pixel leaves the view where it is.
|
||||
for _ in 0..200 {
|
||||
let before = app.view().unwrap().center;
|
||||
outlines(&mut app, vec![], 0.016);
|
||||
if app.view().unwrap().center == before {
|
||||
if app.view().unwrap().center == before && !ctx.input(|i| i.is_scrolling()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -6793,6 +7094,137 @@ mod tests {
|
||||
assert_eq!(cursor(&app), Some(Cursor::Arrow), "still again: the pointer at {:?} is past the rectangle", app.hover_doc);
|
||||
}
|
||||
|
||||
/// The wheel, a scroll bar and the Hand tool move the view by whole device pixels at 1.25
|
||||
/// device pixels a point, in a zoomed and turned view: every frame's render view is the first
|
||||
/// one's panned by whole pixels, which the renderer's cropped effect rasters need to be drawn
|
||||
/// again, and the wheel's and the scroll bar's scrolls add up to what they were given within a
|
||||
/// device pixel, as does the drag.
|
||||
#[test]
|
||||
fn scrolls_and_pans_move_the_view_by_whole_device_pixels() {
|
||||
const PPP: f32 = 1.25;
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
app.session.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 400, "height": 300})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0));
|
||||
let mut time = 0.0;
|
||||
let mut frame = |app: &mut VectorcraftApp, events: Vec<egui::Event>| {
|
||||
time += 0.016;
|
||||
let mut input = egui::RawInput { time: Some(time), screen_rect: Some(screen), events, ..Default::default() };
|
||||
input.viewports.get_mut(&egui::ViewportId::ROOT).unwrap().native_pixels_per_point = Some(PPP);
|
||||
ctx.run_ui(input, |ui| show(app, ui)).textures_delta.clear();
|
||||
};
|
||||
frame(&mut app, vec![]);
|
||||
{
|
||||
let v = app.view_mut().unwrap();
|
||||
v.zoom = 4.0;
|
||||
v.rotation = 30.0;
|
||||
v.center = Point::new(200.3, 150.7);
|
||||
}
|
||||
frame(&mut app, vec![]);
|
||||
// The pan of the canvas's render view (the translation of the view it renders through, less
|
||||
// the half of its size), in device pixels.
|
||||
let pan = |app: &VectorcraftApp| {
|
||||
let v = app.view().unwrap();
|
||||
(Affine::rotate(v.rotation.to_radians()) * Affine::scale(v.zoom * f64::from(PPP)) * Affine::translate(-v.center.to_vec2())).translation()
|
||||
};
|
||||
let wheel = |d: egui::Vec2| egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Point,
|
||||
delta: d,
|
||||
phase: egui::TouchPhase::Move,
|
||||
modifiers: Default::default(),
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
};
|
||||
let whole = |by: vectorcraft_geom::Vec2| (by - vectorcraft_geom::Vec2::new(by.x.round(), by.y.round())).hypot() < 1e-6;
|
||||
let rect = app.canvas_rect.unwrap();
|
||||
let track = scroll_tracks(rect, screen)[0].center();
|
||||
let deltas = [vec2(0.37, 11.13), vec2(-12.71, 0.0), vec2(0.0, 7.45), vec2(21.9, -3.83), vec2(0.21, 0.21)];
|
||||
for (name, at) in [("the wheel", rect.center()), ("the horizontal scroll bar", track)] {
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(at)]);
|
||||
let start = pan(&app);
|
||||
let mut given = vectorcraft_geom::Vec2::ZERO;
|
||||
for (k, d) in deltas.iter().enumerate() {
|
||||
frame(&mut app, vec![wheel(*d)]);
|
||||
// Over the scroll bar, the wheel scrolls along it.
|
||||
given += if at == track {
|
||||
vectorcraft_geom::Vec2::new(f64::from(d.x + d.y), 0.0)
|
||||
} else {
|
||||
vectorcraft_geom::Vec2::new(f64::from(d.x), f64::from(d.y))
|
||||
};
|
||||
let by = pan(&app) - start;
|
||||
assert!(whole(by), "{name}, scroll {k}: the view moved {by:?} device pixels");
|
||||
}
|
||||
// The wheel's smooth scrolling runs on for some frames.
|
||||
for k in 0..60 {
|
||||
frame(&mut app, vec![]);
|
||||
let by = pan(&app) - start;
|
||||
assert!(whole(by), "{name}, frame {k} after the scrolls: the view moved {by:?} device pixels");
|
||||
}
|
||||
let by = pan(&app) - start;
|
||||
let want = given * f64::from(PPP);
|
||||
assert!(by.hypot() > 10.0, "{name}: the view moved {by:?} device pixels");
|
||||
assert!((by.x - want.x).abs() <= 1.0 && (by.y - want.y).abs() <= 1.0, "{name}: moved {by:?} device pixels for {want:?}");
|
||||
}
|
||||
// The horizontal scroll bar's thumb dragged to points between device pixels: the view moves
|
||||
// `ratio` points for each point the thumb moves, the other way.
|
||||
let (_, span, from) = scroll_bar(&mut app, 0);
|
||||
let ratio = f64::from(span.ratio(scroll_tracks(rect, screen)[0].width()));
|
||||
assert!(ratio > 1.0, "at 400% the view moves further than the thumb: {ratio}");
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(from)]);
|
||||
let start = pan(&app);
|
||||
frame(&mut app, vec![primary(from, true)]);
|
||||
for (k, dx) in [7.37_f32, 12.81, 3.33].into_iter().enumerate() {
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(from + vec2(dx, 0.0))]);
|
||||
let by = pan(&app) - start;
|
||||
assert!(whole(by), "thumb drag {k}: the view moved {by:?} device pixels");
|
||||
let want = -f64::from(dx) * ratio * f64::from(PPP);
|
||||
assert!((by.x - want).abs() <= 1.0 && by.y.abs() <= 1.0, "thumb drag {k}: moved {by:?} device pixels for {want}");
|
||||
}
|
||||
frame(&mut app, vec![primary(from + vec2(3.33, 0.0), false)]);
|
||||
// A Hand tool drag to points between device pixels.
|
||||
app.select_tool("hand");
|
||||
let p0 = rect.center() + vec2(0.3, 0.1);
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(p0)]);
|
||||
let start = pan(&app);
|
||||
frame(&mut app, vec![primary(p0, true)]);
|
||||
for (k, d) in [vec2(13.37, -7.61), vec2(40.19, 3.33), vec2(-5.55, 22.71)].into_iter().enumerate() {
|
||||
frame(&mut app, vec![egui::Event::PointerMoved(p0 + d)]);
|
||||
let by = pan(&app) - start;
|
||||
assert!(whole(by), "drag {k}: the view moved {by:?} device pixels");
|
||||
let want = vectorcraft_geom::Vec2::new(f64::from(d.x), f64::from(d.y)) * f64::from(PPP);
|
||||
assert!((by.x - want.x).abs() <= 1.0 && (by.y - want.y).abs() <= 1.0, "drag {k}: moved {by:?} device pixels for {want:?}");
|
||||
}
|
||||
frame(&mut app, vec![primary(p0 + vec2(-5.55, 22.71), false)]);
|
||||
}
|
||||
|
||||
/// The part of a device pixel a scroll leaves is added to the next scroll of the same view, and
|
||||
/// dropped when the view was zoomed, turned or moved in between, when the next scroll is in
|
||||
/// another document, or when the device pixels a point changed.
|
||||
#[test]
|
||||
fn a_scrolls_leftover_pixel_part_carries_only_to_the_same_view() {
|
||||
let view = View { zoom: 1.0, center: Point::new(100.0, 100.0), fitted: true, rotation: 0.0, artboard: 0 };
|
||||
let mut v = view;
|
||||
let rest = scroll_by(&mut v, 1, 1.0, vec2(0.4, -0.3), ScrollRest::default());
|
||||
assert_eq!(v.center, view.center, "less than half a pixel does not move the view");
|
||||
assert!((rest.x - 0.4).abs() < 1e-6 && (rest.y + 0.3).abs() < 1e-6);
|
||||
let mut again = v;
|
||||
scroll_by(&mut again, 1, 1.0, vec2(0.4, -0.3), rest);
|
||||
assert_eq!(again.center, Point::new(99.0, 101.0), "the second scroll adds the first's part");
|
||||
let changed = [
|
||||
("zoomed", View { zoom: 2.0, ..v }, 1, 1.0),
|
||||
("turned", View { rotation: 90.0, ..v }, 1, 1.0),
|
||||
("fitted or moved", View { center: Point::new(150.0, 120.0), ..v }, 1, 1.0),
|
||||
("another document", v, 2, 1.0),
|
||||
("another display scale", v, 1, 1.25),
|
||||
];
|
||||
for (name, before, doc, ppp) in changed {
|
||||
let mut after = before;
|
||||
let left = scroll_by(&mut after, doc, ppp, vec2(0.4 / ppp, -0.3 / ppp), rest);
|
||||
assert_eq!(after.center, before.center, "{name}: the first scroll's part is dropped");
|
||||
assert!((left.x - 0.4).abs() < 1e-6 && (left.y + 0.3).abs() < 1e-6, "{name}: {left:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// View › Snap to Glyph toggles through the View menu command (#3124).
|
||||
#[test]
|
||||
fn snap_to_glyph_menu_command_toggles_the_view_flag() {
|
||||
@@ -8275,6 +8707,36 @@ mod tests {
|
||||
assert_eq!(brush(&app).as_deref(), Some("Arrow"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_library_brush_dropped_on_a_path_is_added_and_applied_in_one_step() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let id =
|
||||
app.session.execute("path.create", &json!({"anchors": [{"x": 100, "y": 150}, {"x": 300, "y": 150}]})).unwrap()["id"].as_u64().unwrap();
|
||||
app.session.execute("select.none", &json!({})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
|
||||
let drop = |app: &mut VectorcraftApp, at: Point| {
|
||||
let at = xf.to_screen(at);
|
||||
egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::LibraryBrush { library: "scatter-shapes".into(), name: "Sparkles".into() });
|
||||
let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() };
|
||||
frame(app, &ctx, vec![egui::Event::PointerMoved(at), up]);
|
||||
};
|
||||
let undo = app.session.active().unwrap().history.undo.len();
|
||||
// Off the path: nothing.
|
||||
drop(&mut app, Point::new(200.0, 250.0));
|
||||
assert!(vectorcraft_brush::find(&app.session.active().unwrap().doc, "Sparkles").is_none());
|
||||
// On it: added, with the symbol it scatters, and applied, as one step.
|
||||
drop(&mut app, Point::new(200.0, 150.0));
|
||||
let st = app.session.active().unwrap();
|
||||
assert!(vectorcraft_brush::find(&st.doc, "Sparkles").is_some() && st.doc.symbols.iter().any(|s| s.name == "Sparkle"), "{}", app.ui.status);
|
||||
let n = st.doc.node(vectorcraft_doc::NodeId(id)).unwrap();
|
||||
assert_eq!(n.appearance.stroke().and_then(|s| s.brush.clone()).as_deref(), Some("Sparkles"));
|
||||
assert_eq!(st.history.undo.len(), undo + 1);
|
||||
assert_eq!(st.history.undo.last().unwrap().label, "Add to Brushes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn middle_drag_pans_the_view_with_any_tool() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
@@ -9127,7 +9589,7 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_moves_keeps_touch_samples_and_pressure_but_leaves_mouse_unchanged() {
|
||||
fn frame_moves_keeps_touch_feed_and_mouse_samples_with_their_pressure() {
|
||||
let ctx = egui::Context::default();
|
||||
let a = pos2(10.0, 20.0);
|
||||
let b = pos2(20.0, 30.0);
|
||||
@@ -9136,7 +9598,8 @@ mod tests {
|
||||
let mut mouse = vec![];
|
||||
let mut out = ctx.run_ui(egui::RawInput { events: events.clone(), ..Default::default() }, |ui| mouse = frame_moves(ui, None));
|
||||
out.textures_delta.clear();
|
||||
assert!(mouse.is_empty());
|
||||
// A mouse keeps its moves too, without a pressure.
|
||||
assert_eq!(mouse, [(a, None), (b, None)], "the last move follows the normal pointer path");
|
||||
// A macOS pen: the feed kept a pressure for each move, the last for the last.
|
||||
let feed = StylusFeed::default();
|
||||
for p in [0.9, 0.3, 0.0, 0.5] {
|
||||
@@ -9148,7 +9611,7 @@ mod tests {
|
||||
assert_eq!(samples, [(a, Some(0.3)), (b, None)], "paired from the end; a lift's 0 is no pressure");
|
||||
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| samples = frame_moves(ui, Some(&feed)));
|
||||
out.textures_delta.clear();
|
||||
assert!(samples.is_empty(), "the moves were taken: a mouse's moves again");
|
||||
assert_eq!(samples, [(a, None), (b, None)], "the moves were taken: a mouse's moves again");
|
||||
let events = [pen(egui::TouchPhase::Move, a, 0.2), pen(egui::TouchPhase::Move, b, 0.8), pen(egui::TouchPhase::Move, c, 0.6)].concat();
|
||||
let mut samples = vec![];
|
||||
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| samples = frame_moves(ui, None));
|
||||
@@ -9546,6 +10009,84 @@ mod tests {
|
||||
assert!(!visible(&app), "the grid stays hidden");
|
||||
}
|
||||
|
||||
/// #3328: every position a mouse reports within one frame reaches the Pencil, not only the
|
||||
/// frame's last one, so a fast stroke keeps the hand's movement.
|
||||
#[test]
|
||||
fn a_mouse_stroke_keeps_every_move_of_a_frame() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
app.select_tool("pencil");
|
||||
let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
|
||||
let at = |x: f64, y: f64| xf.to_screen(Point::new(x, y));
|
||||
let button =
|
||||
|p, pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
|
||||
let start = at(100.0, 100.0);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]);
|
||||
// One frame of a fast stroke: a zigzag of 20 moves, 6 pt apart.
|
||||
let zigzag: Vec<_> = (1..=20).map(|i| at(100.0 + 6.0 * f64::from(i), if i % 2 == 0 { 100.0 } else { 112.0 })).collect();
|
||||
frame(&mut app, &ctx, zigzag.iter().map(|p| egui::Event::PointerMoved(*p)).collect());
|
||||
let end = *zigzag.last().unwrap();
|
||||
frame(&mut app, &ctx, vec![button(end, false)]);
|
||||
let (cmd, p) = app.session.journal.last().unwrap().clone();
|
||||
assert_eq!(cmd, "path.freehand");
|
||||
let pts = p["points"].as_array().unwrap();
|
||||
let expected: Vec<_> = std::iter::once(start)
|
||||
.chain(zigzag.iter().copied())
|
||||
.map(|p| {
|
||||
let p = xf.to_doc(p);
|
||||
json!([p.x, p.y])
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(pts, expected.as_slice(), "the stroke keeps every move of the frame, in order");
|
||||
}
|
||||
|
||||
/// A frame whose moves end where the last frame's did still reaches the Pencil: the stroke went
|
||||
/// out and came back in between.
|
||||
#[test]
|
||||
fn a_mouse_stroke_keeps_a_frame_that_ends_where_it_started() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
app.select_tool("pencil");
|
||||
let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
|
||||
let at = |x: f64, y: f64| xf.to_screen(Point::new(x, y));
|
||||
let button =
|
||||
|p, pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
|
||||
let (start, a) = (at(100.0, 100.0), at(160.0, 100.0));
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]);
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(a)]);
|
||||
// Out to a bump and back to `a`, all in one frame.
|
||||
let bump = [at(170.0, 80.0), at(180.0, 70.0), at(170.0, 80.0), a];
|
||||
frame(&mut app, &ctx, bump.iter().map(|p| egui::Event::PointerMoved(*p)).collect());
|
||||
frame(&mut app, &ctx, vec![button(a, false)]);
|
||||
let (_, p) = app.session.journal.last().unwrap().clone();
|
||||
let n = p["points"].as_array().unwrap().len();
|
||||
assert!(n >= 5, "the bump's moves are kept: {n} points");
|
||||
}
|
||||
|
||||
/// Only a tool that builds a stroke from the drag's samples gets every move of a frame (#4227):
|
||||
/// the Selection tool and the other tools get one drag a frame, at the pointer's position, so a
|
||||
/// costly drag preview runs once.
|
||||
#[test]
|
||||
fn only_the_freehand_tools_get_every_move_of_a_frame() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.session.execute("file.new", &json!({"width": 800, "height": 600})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let events: Vec<_> = (0..20).map(|i| egui::Event::PointerMoved(pos2(100.0 + i as f32 * 5.0, 100.0))).collect();
|
||||
for (tool, every) in
|
||||
[("pencil", true), ("paintbrush", true), ("blobBrush", true), ("selection", false), ("directSelection", false), ("width", false)]
|
||||
{
|
||||
app.select_tool(tool);
|
||||
let mut moves = vec![];
|
||||
let mut out = ctx.run_ui(egui::RawInput { events: events.clone(), ..Default::default() }, |ui| moves = tool_frame_moves(ui, &app));
|
||||
out.textures_delta.clear();
|
||||
assert_eq!(moves.len(), if every { 19 } else { 0 }, "{tool}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #491: a pen tap whose press and lift come in one frame selects what it tapped, and the
|
||||
/// lift (the pointer gone with it) doesn't drag the selection to the canvas's centre.
|
||||
#[test]
|
||||
@@ -10554,6 +11095,36 @@ mod tests {
|
||||
assert!(thread_overlays(&app, zoom).is_empty());
|
||||
}
|
||||
|
||||
/// A double-click with the Selection tool on the out port of a threaded frame breaks the
|
||||
/// thread there: no new frame is threaded on, and the story flows back into the first frame.
|
||||
#[test]
|
||||
fn a_double_click_on_a_threaded_out_port_breaks_the_thread() {
|
||||
use vectorcraft_tools::text::{Port, port_centre};
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 600, "height": 400})).unwrap();
|
||||
let text = "Words that fill more than the frame holds. ".repeat(10);
|
||||
let a =
|
||||
app.run("text.create", json!({"x": 20, "y": 20, "text": text, "area": {"width": 150, "height": 60}})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("text.thread.add", json!({"from": a, "at": [300, 200]})).unwrap();
|
||||
app.run("select.set", json!({"ids": [a]})).unwrap();
|
||||
app.select_tool("selection");
|
||||
let doc = |app: &VectorcraftApp| app.session.active().unwrap().doc.clone();
|
||||
let before = doc(&app);
|
||||
let NodeKind::Text(t) = &before.node(vectorcraft_doc::NodeId(a)).unwrap().kind else { panic!("not text") };
|
||||
let view = app.view_info();
|
||||
let at = port_centre(t, Port::Out, 1.0 / view.zoom).unwrap();
|
||||
let count = doc(&app).layers[0].children().map_or(0, |c| c.len());
|
||||
for kind in [PointerKind::Down, PointerKind::Up, PointerKind::Down, PointerKind::Up, PointerKind::DoubleClick] {
|
||||
crate::canvas::dispatch(&mut app, &PointerEvent::new(kind, at.x, at.y), view);
|
||||
}
|
||||
let d = doc(&app);
|
||||
assert!(d.text_threads.is_empty(), "the thread is broken");
|
||||
assert_eq!(d.layers[0].children().map_or(0, |c| c.len()), count, "no new frame");
|
||||
let NodeKind::Text(t) = &d.node(vectorcraft_doc::NodeId(a)).unwrap().kind else { panic!("not text") };
|
||||
assert_eq!(t.plain_text(), text, "the story flows into the first frame");
|
||||
assert_eq!(app.session.tool_id(), "selection");
|
||||
}
|
||||
|
||||
/// With more than `PORTS_MAX` type objects selected the tools draw no ports, and Show Text
|
||||
/// Threads draws only its lines, no port boxes.
|
||||
#[test]
|
||||
|
||||
@@ -512,7 +512,9 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
x += w;
|
||||
}
|
||||
crate::document_drag::finish_tabs(ui.ctx(), hovering_art);
|
||||
// The » button: every open document, the active one checked.
|
||||
// The » button: every open document, the active one checked. The list scrolls once it
|
||||
// reaches the bottom of the window, so every document of a large session stays reachable
|
||||
// (#4017).
|
||||
if overflow {
|
||||
let more = egui::Rect::from_min_max(egui::pos2(strip.right() - MORE, strip.top()), egui::pos2(strip.right(), strip.bottom() - 1.0));
|
||||
let resp = ui.interact(more, ui.scope_id().with("tabs-more"), Sense::click());
|
||||
@@ -520,12 +522,14 @@ pub fn doc_tabs(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
icons::paint(ui, "chevrons-right", egui::Rect::from_center_size(more.center(), vec2(14.0, 14.0)), t.text);
|
||||
let resp = resp.on_hover_text(tl!("Show all open documents"));
|
||||
egui::Popup::menu(&resp).show(|ui| {
|
||||
for (i, (title, _)) in tabs.iter().enumerate() {
|
||||
if widgets::menu_item_name(ui, title, true, Some(i) == active) {
|
||||
activate = Some(i);
|
||||
ui.close();
|
||||
widgets::menu_scroll(ui, |ui| {
|
||||
for (i, (title, _)) in tabs.iter().enumerate() {
|
||||
if widgets::menu_item_name(ui, title, true, Some(i) == active) {
|
||||
activate = Some(i);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
if let Some(i) = close {
|
||||
|
||||
@@ -586,7 +586,7 @@ pub(crate) fn save_screenshot_with_limit(
|
||||
// A data-only reply has no second way to deliver the image, so refuse an oversized one before
|
||||
// allocating its working set. A request that named a path still writes that file: only the
|
||||
// inline copy is downgraded.
|
||||
if data && path.is_none() && !screenshot_rgba_bytes(w, h).is_some_and(|bytes| bytes <= max_reply_bytes) {
|
||||
if data && path.is_none() && screenshot_rgba_bytes(w, h).is_none_or(|bytes| bytes > max_reply_bytes) {
|
||||
return json!({"ok": false, "error": format!(
|
||||
"a PNG reply of this {w}×{h} screenshot would exceed the {max_reply_bytes}-byte reply-encoding limit; write it to a path instead"
|
||||
)});
|
||||
|
||||
@@ -294,6 +294,18 @@ fn type_widget(p: &mut Ink, o: Pos2) {
|
||||
line(p, b + vec2(4.0, 0.0), b + vec2(4.0, 9.0));
|
||||
}
|
||||
|
||||
/// Overflow text the Selection tool carries after a click on the red out port: a small block of
|
||||
/// lines at the hotspot (where a new frame's top-left would go).
|
||||
fn loaded_text(p: &mut Ink, o: Pos2) {
|
||||
let tl = o;
|
||||
let br = o + vec2(14.0, 11.0);
|
||||
let frame = vec![tl, pos2(br.x, tl.y), br, pos2(tl.x, br.y)];
|
||||
poly(p, frame, HALO, INK);
|
||||
for y in [3.0, 6.5, 10.0] {
|
||||
line(p, tl + vec2(2.0, y), tl + vec2(12.0, y));
|
||||
}
|
||||
}
|
||||
|
||||
/// The gradient annotator's stop cursors: the arrow with a plus (add a stop) or minus (delete it)
|
||||
/// badge.
|
||||
fn stop_badge(p: &mut Ink, o: Pos2, add: bool) {
|
||||
@@ -593,6 +605,7 @@ fn glyph(c: Cursor, p: Pos2) -> Option<Vec<Shape>> {
|
||||
Cursor::Blend | Cursor::BlendObject | Cursor::BlendAnchor => blend(ink, p, c),
|
||||
Cursor::PathBracket => path_bracket(ink, p),
|
||||
Cursor::TypeWidget => type_widget(ink, p),
|
||||
Cursor::LoadedText => loaded_text(ink, p),
|
||||
Cursor::ShapeBuilder => shape_builder(ink, p, false),
|
||||
Cursor::ShapeBuilderErase => shape_builder(ink, p, true),
|
||||
Cursor::Hand => hand(ink, p, false),
|
||||
@@ -825,6 +838,17 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Loaded text after a click on the overflow out port is a text-block glyph, not the I-beam.
|
||||
#[test]
|
||||
fn loaded_text_cursor_is_not_the_text_i_beam() {
|
||||
assert!(Cursor::LoadedText.stand_in().is_none());
|
||||
let loaded = rasterize(Cursor::LoadedText, 2.0).expect("loaded text bitmap");
|
||||
let ibeam = rasterize(Cursor::Text, 2.0).expect("text bitmap");
|
||||
assert_ne!(loaded.rgba, ibeam.rgba);
|
||||
let [hx, hy] = loaded.hotspot.map(usize::from);
|
||||
assert!(pixel(&loaded, hx, hy)[3] > 200, "hotspot lies on the drawn frame");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_glyph_becomes_a_bitmap_with_its_hotspot_inside() {
|
||||
for ppp in [1.0, 1.25, 1.5, 2.0, 3.0] {
|
||||
|
||||
@@ -225,7 +225,7 @@ pub(super) fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog)
|
||||
ui.add_space(10.0);
|
||||
// The brush as OK would make it, on a sample stroke.
|
||||
let ty = d.str("__type");
|
||||
stroke_preview(ui, &ty, edited_def(d), vec2(PREVIEW_W, 64.0));
|
||||
stroke_preview(app, ui, &ty, edited_def(d), vec2(PREVIEW_W, 64.0));
|
||||
}
|
||||
|
||||
/// The brush definition as OK would make it: `__def` with the fields' params.
|
||||
|
||||
@@ -241,18 +241,18 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
ui.add_space(10.0);
|
||||
match d.str("__type").as_str() {
|
||||
"bristle" => bristle_body(app, ui, d),
|
||||
"calligraphic" => calligraphic_body(ui, d),
|
||||
"calligraphic" => calligraphic_body(app, ui, d),
|
||||
_ => brush_art_options::body(app, ui, d),
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn calligraphic_body(ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
fn calligraphic_body(app: &VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
let c = calligraphic(d);
|
||||
ui.horizontal(|ui| {
|
||||
nib_preview(ui, &c, vec2(NIB_W, 84.0));
|
||||
ui.add_space(8.0);
|
||||
stroke_preview(ui, "calligraphic", serde_json::to_value(&c).unwrap_or_default(), vec2(STROKE_W - NIB_W - 8.0, 84.0));
|
||||
stroke_preview(app, ui, "calligraphic", serde_json::to_value(&c).unwrap_or_default(), vec2(STROKE_W - NIB_W - 8.0, 84.0));
|
||||
});
|
||||
ui.add_space(12.0);
|
||||
egui::Grid::new("brush-options-calli").num_columns(5).spacing([8.0, 8.0]).show(ui, |ui| {
|
||||
@@ -290,11 +290,12 @@ fn bristle_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) {
|
||||
}
|
||||
ui.add_space(8.0);
|
||||
let p = params(d);
|
||||
stroke_preview(ui, "bristle", p, vec2(STROKE_W, 64.0));
|
||||
stroke_preview(app, ui, "bristle", p, vec2(STROKE_W, 64.0));
|
||||
}
|
||||
|
||||
/// A stroke painted with the brush the fields describe (type `ty`, definition fields `def`).
|
||||
pub(super) fn stroke_preview(ui: &mut egui::Ui, ty: &str, def: Value, size: egui::Vec2) {
|
||||
/// A stroke painted with the brush the fields describe (type `ty`, definition fields `def`), with
|
||||
/// the active document's resources (the patterns, symbols… its art uses).
|
||||
pub(super) fn stroke_preview(app: &VectorcraftApp, ui: &mut egui::Ui, ty: &str, def: Value, size: egui::Vec2) {
|
||||
let mut def = match def {
|
||||
Value::Object(o) => o,
|
||||
_ => Map::new(),
|
||||
@@ -302,7 +303,7 @@ pub(super) fn stroke_preview(ui: &mut egui::Ui, ty: &str, def: Value, size: egui
|
||||
def.insert("name".into(), json!("preview"));
|
||||
def.insert("type".into(), json!(ty));
|
||||
let (r, _) = ui.allocate_exact_size(size, Sense::hover());
|
||||
crate::panels::brushes::chip(ui, r, &Value::Object(def));
|
||||
crate::panels::brushes::definition_chip(ui, r, app.session.active(), &Value::Object(def));
|
||||
ui.painter().rect_stroke(r, 0.0, Stroke::new(1.0, Tokens::get(ui.ctx()).input_border), egui::StrokeKind::Inside);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
//! View → Edit Views…: the document's saved views in a list, with the chosen one's name to edit
|
||||
//! and Delete. Nothing changes until OK, which applies every rename and delete as one undo step
|
||||
//! (`view.saved.edit` `edits`); Cancel leaves them as they were.
|
||||
//!
|
||||
//! Fields: `count` and, for each saved view `i`, `orig<i>` (its name when the dialog opened),
|
||||
//! `name<i>` (as edited) and `deleted<i>`; `selected` (the row picked).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::doc::SavedView;
|
||||
|
||||
use super::{DialogSpec, form};
|
||||
use crate::state::Dialog;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
|
||||
/// The dialog kind of Edit Views.
|
||||
pub const KIND: &str = "editViews";
|
||||
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Edit Views").into(), body, confirm, min_width: 420.0, ..DialogSpec::FORM };
|
||||
|
||||
/// Open Edit Views on the active document's saved views.
|
||||
pub fn open(app: &mut VectorcraftApp) -> Result<Value, String> {
|
||||
let names: Vec<String> = app.session.active().map(|d| d.doc.views.iter().map(|v| v.name.clone()).collect()).unwrap_or_default();
|
||||
if names.is_empty() {
|
||||
return Err("No saved views (View → New View…)".into());
|
||||
}
|
||||
let mut fields = json!({ "count": names.len(), "selected": 0 });
|
||||
for (i, n) in names.iter().enumerate() {
|
||||
fields[format!("orig{i}")] = json!(n);
|
||||
fields[format!("name{i}")] = json!(n);
|
||||
fields[format!("deleted{i}")] = json!(false);
|
||||
}
|
||||
app.ui.dialog = Some(Dialog::new(KIND, fields));
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn count(d: &Dialog) -> usize {
|
||||
d.fields.get("count").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()).unwrap_or(0).min(SavedView::MAX)
|
||||
}
|
||||
|
||||
/// The rows still in the list (not deleted).
|
||||
fn rows(d: &Dialog) -> Vec<usize> {
|
||||
(0..count(d)).filter(|i| !d.bool(&format!("deleted{i}"))).collect()
|
||||
}
|
||||
|
||||
fn selected(d: &Dialog, rows: &[usize]) -> Option<usize> {
|
||||
let want = d.fields.get("selected").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok());
|
||||
want.filter(|w| rows.contains(w)).or_else(|| rows.first().copied())
|
||||
}
|
||||
|
||||
fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let rows = rows(d);
|
||||
let current = selected(d, &rows);
|
||||
let mut pick = None;
|
||||
let mut delete = false;
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(200.0);
|
||||
widgets::dim_label(ui, tl!("Saved Views"));
|
||||
widgets::list_box(ui, |ui| {
|
||||
egui::ScrollArea::vertical().id_salt("saved-views").min_scrolled_height(180.0).max_height(180.0).show(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.set_min_height(180.0);
|
||||
for &i in &rows {
|
||||
if ui.selectable_label(Some(i) == current, d.str(&format!("name{i}"))).clicked() {
|
||||
pick = Some(i);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.add_space(16.0);
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(190.0);
|
||||
if let Some(i) = current {
|
||||
widgets::dim_label(ui, tl!("Name:"));
|
||||
form::text(ui, d, &format!("name{i}"), 190.0);
|
||||
ui.add_space(10.0);
|
||||
delete = widgets::flat_button(ui, tl!("Delete"), 70.0).clicked();
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(i) = pick {
|
||||
d.fields.insert("selected".into(), json!(i));
|
||||
}
|
||||
if let (true, Some(i)) = (delete, current) {
|
||||
d.fields.insert(format!("deleted{i}"), json!(true));
|
||||
// The row below takes its place (the one above, for the last).
|
||||
let next = rows.iter().copied().find(|r| *r > i).or_else(|| rows.iter().copied().rfind(|r| *r < i));
|
||||
d.fields.insert("selected".into(), json!(next.unwrap_or(0)));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The edits OK applies: each deleted view, and each one whose name was changed.
|
||||
fn edits(d: &Dialog) -> Vec<Value> {
|
||||
(0..count(d))
|
||||
.filter_map(|i| {
|
||||
let (orig, name) = (d.str(&format!("orig{i}")), d.str(&format!("name{i}")));
|
||||
if d.bool(&format!("deleted{i}")) {
|
||||
Some(json!({ "name": orig, "delete": true }))
|
||||
} else if !name.trim().is_empty() && name.trim() != orig {
|
||||
Some(json!({ "name": orig, "newName": name.trim() }))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let edits = edits(d);
|
||||
// A name two views would share keeps the dialog open, to be changed.
|
||||
let r = if edits.is_empty() { Ok(Value::Null) } else { app.run("view.saved.edit", json!({ "edits": edits })) };
|
||||
if r.is_ok() {
|
||||
app.ui.dialog = None;
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
use crate::VectorcraftApp;
|
||||
|
||||
fn app() -> VectorcraftApp {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
for n in ["Overview", "Logo", "Text"] {
|
||||
app.run("view.saved.new", json!({ "name": n })).unwrap();
|
||||
}
|
||||
app
|
||||
}
|
||||
|
||||
fn set(app: &mut VectorcraftApp, k: &str, v: serde_json::Value) {
|
||||
app.ui.dialog.as_mut().unwrap().fields.insert(k.into(), v);
|
||||
}
|
||||
|
||||
fn names(app: &VectorcraftApp) -> Vec<String> {
|
||||
app.session.active().unwrap().doc.views.iter().map(|v| v.name.clone()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_changes_until_ok_and_all_edits_are_one_undo_step() {
|
||||
let mut app = app();
|
||||
super::open(&mut app).unwrap();
|
||||
// Rename the first and delete the last.
|
||||
set(&mut app, "name0", json!(" Whole page "));
|
||||
set(&mut app, "deleted2", json!(true));
|
||||
assert_eq!(names(&app), ["Overview", "Logo", "Text"]);
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(names(&app), ["Whole page", "Logo"]);
|
||||
app.run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(names(&app), ["Overview", "Logo", "Text"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_leaves_them_and_a_shared_name_keeps_the_dialog_open() {
|
||||
let mut app = app();
|
||||
super::open(&mut app).unwrap();
|
||||
set(&mut app, "name0", json!("Gone"));
|
||||
super::super::cancel(&mut app);
|
||||
assert_eq!(names(&app), ["Overview", "Logo", "Text"]);
|
||||
super::open(&mut app).unwrap();
|
||||
set(&mut app, "name0", json!("Text"));
|
||||
assert!(super::super::confirm(&mut app).is_err());
|
||||
assert!(app.ui.dialog.is_some());
|
||||
assert_eq!(names(&app), ["Overview", "Logo", "Text"]);
|
||||
// Deleting the other one frees the name.
|
||||
set(&mut app, "deleted2", json!(true));
|
||||
super::super::confirm(&mut app).unwrap();
|
||||
assert_eq!(names(&app), ["Text", "Logo"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn it_needs_a_saved_view() {
|
||||
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({})).unwrap();
|
||||
assert!(super::open(&mut app).is_err());
|
||||
assert!(app.ui.dialog.is_none());
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,9 @@
|
||||
//! Fields: `tool`; `fidelity` (points; Pencil, Paintbrush and Smooth), `fill` (Pencil and
|
||||
//! Paintbrush), `keepSelected` (Pencil, Paintbrush and Blob Brush), `mergeOnlySelection` (Blob
|
||||
//! Brush), `closeWithin` and `editWithin` (screen pixels, 0 turns it off; Pencil and Paintbrush),
|
||||
//! `angle` (degrees) and `roundness` (percent; Eraser) and `size` (points; Blob Brush and Eraser).
|
||||
//! `angle` (degrees) and `roundness` (percent; Eraser), `livePreview` (Pencil: the stroke shows
|
||||
//! with its fill and stroke while it is drawn, or as a thin line until the release) and `size`
|
||||
//! (points; Blob Brush and Eraser).
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
@@ -25,8 +27,20 @@ pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_wid
|
||||
pub const TOOLS: [&str; 5] = ["pencil", "paintbrush", "smooth", "blobBrush", "eraser"];
|
||||
|
||||
/// The options the dialog edits, in the order it shows them (a tool has those it reports).
|
||||
const KEYS: [&str; 11] =
|
||||
["fidelity", "angle", "roundness", "size", "fill", "altSmooth", "keepSelected", "mergeOnlySelection", "closeWithin", "editWithin", "liveFit"];
|
||||
const KEYS: [&str; 12] = [
|
||||
"fidelity",
|
||||
"angle",
|
||||
"roundness",
|
||||
"size",
|
||||
"fill",
|
||||
"altSmooth",
|
||||
"keepSelected",
|
||||
"mergeOnlySelection",
|
||||
"closeWithin",
|
||||
"editWithin",
|
||||
"livePreview",
|
||||
"liveFit",
|
||||
];
|
||||
|
||||
/// Width of the dialog's rows: every number field ends at its right edge.
|
||||
const CONTENT_W: f32 = 330.0;
|
||||
@@ -190,8 +204,14 @@ fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
if d.fields.contains_key("editWithin") {
|
||||
number(ui, d, ("editWithin", tl!("Edit selected paths within:")), "px", 0, (0.0, 100.0));
|
||||
}
|
||||
if d.fields.contains_key("liveFit") {
|
||||
if d.fields.contains_key("livePreview") {
|
||||
ui.add_space(6.0);
|
||||
check(ui, d, "livePreview", tl!("Live preview"));
|
||||
}
|
||||
if d.fields.contains_key("liveFit") {
|
||||
if !d.fields.contains_key("livePreview") {
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
check(ui, d, "liveFit", tl!("Live curve fitting"));
|
||||
}
|
||||
false
|
||||
@@ -283,6 +303,7 @@ mod tests {
|
||||
"Alt key toggles to Smooth Tool",
|
||||
"Close paths when ends are within:",
|
||||
"Edit selected paths within:",
|
||||
"Live preview",
|
||||
] {
|
||||
assert!(text.contains(label), "{label} in {text}");
|
||||
}
|
||||
@@ -310,7 +331,7 @@ mod tests {
|
||||
assert_eq!((d.f64("fidelity", 0.0), d.bool("fill")), (1.5, false));
|
||||
let pb_text = painted(&mut app);
|
||||
assert!(pb_text.contains("Paintbrush Tool Options"));
|
||||
assert!(!pb_text.contains("Alt key toggles to Smooth Tool"));
|
||||
assert!(!pb_text.contains("Alt key toggles to Smooth Tool") && !pb_text.contains("Live preview"), "{pb_text}");
|
||||
// Smooth has Fidelity only, the Eraser Size only, and the Blob Brush Size, Keep selected and Merge only with selection.
|
||||
app.run("tool.options", json!({"tool": "smooth"})).unwrap();
|
||||
let text = painted(&mut app);
|
||||
|
||||
@@ -24,6 +24,7 @@ mod document_setup;
|
||||
pub mod dxf_import;
|
||||
pub mod dxf_options;
|
||||
pub mod edit_selection;
|
||||
pub mod edit_views;
|
||||
mod effect;
|
||||
pub mod effect_gallery;
|
||||
pub mod envelope;
|
||||
@@ -64,6 +65,7 @@ pub mod new_swatch;
|
||||
pub mod office_export;
|
||||
pub mod package;
|
||||
pub(crate) mod path_ops;
|
||||
pub mod pathfinder_options;
|
||||
pub mod pdf_presets;
|
||||
pub mod perspective_grid;
|
||||
pub mod perspective_options;
|
||||
@@ -83,6 +85,7 @@ mod recovery;
|
||||
mod revolve;
|
||||
pub(crate) mod revolve_gizmo;
|
||||
pub mod saturate;
|
||||
pub mod save_brush_library;
|
||||
mod save_changes;
|
||||
pub mod save_for_web;
|
||||
pub(crate) mod save_options;
|
||||
@@ -299,6 +302,7 @@ registry! {
|
||||
FlattenerPresets: [flattener_presets::KIND] => flattener_presets::SPEC,
|
||||
SaveStyleLibrary: [save_style_library::KIND] => save_style_library::SPEC,
|
||||
SaveSymbolLibrary: [save_symbol_library::KIND] => save_symbol_library::SPEC,
|
||||
SaveBrushLibrary: [save_brush_library::KIND] => save_brush_library::SPEC,
|
||||
Expand: [expand::KIND] => expand::SPEC,
|
||||
SpotColors: [spot_colors::KIND] => spot_colors::SPEC,
|
||||
TransformEach: [transform_each::KIND] => transform_each::SPEC,
|
||||
@@ -364,9 +368,11 @@ registry! {
|
||||
BrushOptions: [brush_options::KIND] => brush_options::SPEC,
|
||||
NewBrush: [new_brush::KIND] => new_brush::SPEC,
|
||||
EditSelection: [edit_selection::KIND] => edit_selection::SPEC,
|
||||
EditViews: [edit_views::KIND] => edit_views::SPEC,
|
||||
PerspectivePlane: [perspective_plane::KIND] => perspective_plane::SPEC,
|
||||
LayerOptions: [layer_options::KIND] => layer_options::SPEC,
|
||||
LayersPanelOptions: [layers_panel_options::KIND] => layers_panel_options::SPEC,
|
||||
PathfinderOptions: [pathfinder_options::KIND] => pathfinder_options::SPEC,
|
||||
RearrangeArtboards: [rearrange_artboards::KIND] => rearrange_artboards::SPEC,
|
||||
ShortcutImport: [shortcut_import::KIND] => DialogSpec::window(shortcut_import::show, shortcut_import::confirm),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
//! Pathfinder panel › Pathfinder Options…: Precision, Remove Redundant Points and Divide and Outline
|
||||
//! Will Remove Unpainted Artwork. OK runs `object.pathfinder.options` (the options live in the
|
||||
//! preferences).
|
||||
//!
|
||||
//! Fields: `precision` (pt, 0.001–10), `removeRedundantPoints` and `removeUnpainted`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::DialogSpec;
|
||||
use super::swatch_options::{grid, label};
|
||||
use crate::state::Dialog;
|
||||
use crate::{VectorcraftApp, widgets};
|
||||
|
||||
/// The dialog kind of Pathfinder Options.
|
||||
pub const KIND: &str = "pathfinderOptions";
|
||||
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Pathfinder Options").into(), body, confirm, min_width: 360.0, ..DialogSpec::FORM };
|
||||
|
||||
/// Open the dialog with the current options.
|
||||
pub fn open(app: &mut VectorcraftApp) {
|
||||
app.ui.dialog = Some(Dialog::new(KIND, json!(app.session.prefs.pathfinder)));
|
||||
}
|
||||
|
||||
fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, text: &str) {
|
||||
let v = d.bool(key);
|
||||
if widgets::check(ui, text, v, true) {
|
||||
d.fields.insert(key.into(), json!(!v));
|
||||
}
|
||||
}
|
||||
|
||||
fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let range = vectorcraft_engine::cmd::PATHFINDER_PRECISION_RANGE;
|
||||
grid(ui, |ui| {
|
||||
label(ui, tl!("Precision:"));
|
||||
let v = d.f64("precision", vectorcraft_engine::PathfinderOptions::default().precision);
|
||||
if let Some(v) = widgets::range_field(ui, "pathfinder-precision", v, range, " pt", 3, 80.0) {
|
||||
d.fields.insert("precision".into(), json!(v));
|
||||
}
|
||||
ui.end_row();
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
check(ui, d, "removeRedundantPoints", tl!("Remove Redundant Points"));
|
||||
check(ui, d, "removeUnpainted", tl!("Divide and Outline Will Remove Unpainted Artwork"));
|
||||
false
|
||||
}
|
||||
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
super::run_and_close(app, "object.pathfinder.options", Value::Object(d.fields.clone()))
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//! Save Brush Library: a name and where it goes: the user library folder (listed under Window →
|
||||
//! Brush Libraries → User Defined) or a `.vectorcraft` file picked in a save dialog (a download on
|
||||
//! the web). OK runs `brush.saveLibrary`.
|
||||
//!
|
||||
//! Fields: `name`, `user` (save to the user library folder), `selectedOnly` and `names` (the
|
||||
//! brushes selected in the Brushes panel), `__user` (there is a user library folder).
|
||||
|
||||
use serde_json::Value;
|
||||
use vectorcraft_engine::cmd::brushlib::BRUSHES_EXT;
|
||||
|
||||
use super::DialogSpec;
|
||||
use super::save_swatch_library::{destination, fields, name_row, params, save};
|
||||
use super::swatch_options::grid;
|
||||
use crate::VectorcraftApp;
|
||||
use crate::state::Dialog;
|
||||
|
||||
/// The dialog kind of Save Brush Library.
|
||||
pub const KIND: &str = "saveBrushLibrary";
|
||||
|
||||
pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Save Brush Library").into(), body, confirm, min_width: 360.0, ..DialogSpec::FORM };
|
||||
|
||||
/// Open Save Brush Library for the document's brushes (`names`: those selected in the panel).
|
||||
pub fn open(app: &mut VectorcraftApp, names: Vec<String>) -> Result<Value, String> {
|
||||
let fields = fields(app, app.session.brush_libraries.user_dir().is_some(), names)?;
|
||||
app.ui.dialog = Some(Dialog::new(KIND, fields));
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
grid(ui, |ui| {
|
||||
name_row(ui, d);
|
||||
destination(ui, d, tl!("Selected Brushes Only"));
|
||||
});
|
||||
false
|
||||
}
|
||||
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
save(app, d, "brush.saveLibrary", BRUSHES_EXT, params(d))
|
||||
}
|
||||
@@ -7,7 +7,8 @@
|
||||
//! (there is a user library folder).
|
||||
//!
|
||||
//! The name and Save To rows and the saving are shared with Save Graphic Style Library
|
||||
//! ([`super::save_style_library`]) and Save Symbol Library ([`super::save_symbol_library`]).
|
||||
//! ([`super::save_style_library`]), Save Symbol Library ([`super::save_symbol_library`]) and Save
|
||||
//! Brush Library ([`super::save_brush_library`]).
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_color::palette_io::PaletteFormat;
|
||||
|
||||
@@ -703,3 +703,26 @@ fn printer_mark_labels_are_distinct_from_language_names() {
|
||||
assert_eq!(save_pdf::choice_label(cs, "language", "Japanese"), crate::i18n::tr(cs, "Japanese"));
|
||||
assert_eq!(save_pdf::choice_label(crate::i18n::Lang::EN, "marks.kind", "Japanese"), "Japanese");
|
||||
}
|
||||
|
||||
/// In a document in millimeters, an offset typed with a decimal comma (`0,1`) is taken as 0.1 mm
|
||||
/// instead of going back to the value the field had, and Offset Path opens on it again (#3837).
|
||||
#[test]
|
||||
fn offset_path_takes_a_decimal_comma() {
|
||||
let (ctx, mut app) = (ctx(), app_with_selection());
|
||||
app.run("document.setUnits", json!({"units": "Millimeters"})).unwrap();
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
crate::menus::invoke(&mut app, "object.path.offsetPath", json!({}));
|
||||
settle(&ctx, &mut app);
|
||||
// The dialog focuses its first field, the offset: type as a user does, then Tab commits it.
|
||||
frame(&ctx, &mut app, vec![Event::Text("0,1".into())]);
|
||||
frame(&ctx, &mut app, vec![Event::Key { key: egui::Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }]);
|
||||
let texts = frame(&ctx, &mut app, vec![]);
|
||||
let mm = vectorcraft_doc::Unit::Millimeters.to_pt(0.1);
|
||||
let offset = app.ui.dialog.as_ref().unwrap().f64("offset", 0.0);
|
||||
assert!((offset - mm).abs() < 1e-9, "0.1 mm: {offset} pt");
|
||||
assert!(texts.iter().any(|(t, _)| t == "0.1 mm"), "the field shows 0.1 mm: {texts:?}");
|
||||
confirm(&mut app).unwrap();
|
||||
crate::menus::invoke(&mut app, "object.path.offsetPath", json!({}));
|
||||
let offset = app.ui.dialog.as_ref().unwrap().f64("offset", 0.0);
|
||||
assert!((offset - mm).abs() < 1e-9, "reopened on 0.1 mm: {offset} pt");
|
||||
}
|
||||
@@ -329,7 +329,6 @@ font-technology Variable Променливи
|
||||
Brush Affects: Четката влияе върху:
|
||||
Brush Definition Дефиниция на четка
|
||||
Brush Libraries Библиотеки с четки
|
||||
Brush Libraries (on the roadmap) Библиотеки с четки (планирани)
|
||||
Brush Options… Опции за четката…
|
||||
Brush Strokes Щрихи с четка
|
||||
Brushes Четки
|
||||
@@ -344,6 +343,7 @@ font-technology Variable Променливи
|
||||
Apply Bullets Прилагане на булети
|
||||
Numbered List Номериран списък
|
||||
Apply Numbers Прилагане на номериране
|
||||
Convert to Text Конвертиране в текст
|
||||
Filled Dot Плътна точка
|
||||
Dash Тире
|
||||
Hollow Circle Празен кръг
|
||||
@@ -2546,6 +2546,7 @@ font-technology Variable Променливи
|
||||
Remove Plug-in Премахване на добавка
|
||||
Remove Selected Assets Премахване на избраните активи
|
||||
Remove Threading Премахване на свързването
|
||||
Break Thread Прекъсване на свързването
|
||||
Remove “{keyword}” Премахване на „{keyword}“
|
||||
Rename Преименуване
|
||||
Rename Asset Преименуване на актива
|
||||
@@ -2744,7 +2745,22 @@ font-technology Variable Променливи
|
||||
Saved to User Defined: {} Запазено в потребителски: {}
|
||||
Saved View 1 Запазен изглед 1
|
||||
Saved View 10 Запазен изглед 10
|
||||
Saved View 11 Запазен изглед 11
|
||||
Saved View 12 Запазен изглед 12
|
||||
Saved View 13 Запазен изглед 13
|
||||
Saved View 14 Запазен изглед 14
|
||||
Saved View 15 Запазен изглед 15
|
||||
Saved View 16 Запазен изглед 16
|
||||
Saved View 17 Запазен изглед 17
|
||||
Saved View 18 Запазен изглед 18
|
||||
Saved View 19 Запазен изглед 19
|
||||
Saved View 2 Запазен изглед 2
|
||||
Saved View 20 Запазен изглед 20
|
||||
Saved View 21 Запазен изглед 21
|
||||
Saved View 22 Запазен изглед 22
|
||||
Saved View 23 Запазен изглед 23
|
||||
Saved View 24 Запазен изглед 24
|
||||
Saved View 25 Запазен изглед 25
|
||||
Saved View 3 Запазен изглед 3
|
||||
Saved View 4 Запазен изглед 4
|
||||
Saved View 5 Запазен изглед 5
|
||||
@@ -4259,6 +4275,7 @@ axis Both И двете
|
||||
@msg {_1} is already used by {_2} {_1} вече се използва от {_2}
|
||||
@msg {_1} is reserved by the system {_1} е запазено от системата
|
||||
@msg {_1} linked file(s) can't be read here: their previews show свързаните файлове {_1} не могат да бъдат прочетени тук: показват се техните прегледи
|
||||
@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes изображенията ({undecoded}) не могат да бъдат декодирани: показват се като зачеркнати рамки
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions свързаните изображения {_1} са променени на диска: „Обновяване на връзките“ показва новите версии
|
||||
@msg Updated {_1} linked file(s) changed on disk Обновени са свързани файлове {_1}, променени на диска
|
||||
@msg {_1}: not saved, so not closed {_1}: не е запазен, затова не е затворен
|
||||
@@ -5110,6 +5127,7 @@ mark-style Japanese Японски
|
||||
theme Appearance Външен вид
|
||||
Load EPS into Clipboard Зареждане на EPS в клипборда
|
||||
@msg an image of {w} × {h} pixels is too large to draw изображение с размери {w} × {h} пиксела е твърде голямо за рисуване
|
||||
@msg an image of {w} × {h} pixels is shown at reduced size изображение с размери {w} × {h} пиксела се показва в намален размер
|
||||
@msg the image can't be read as a texture изображението не може да бъде прочетено като текстура
|
||||
Fill and Stroke Controls Управление на запълването и щриха
|
||||
Coloring Controls Управление на оцветяването
|
||||
@@ -5482,4 +5500,32 @@ axis Y Axis Y ос
|
||||
Rectangular Grid Tool Options Опции на инструмента „Правоъгълна мрежа“
|
||||
Polar Grid Tool Options Опции на инструмента „Полярна мрежа“
|
||||
Fill Line Запълване на линия
|
||||
Pathfinder Options Опции за търсач на пътища
|
||||
Divide and Outline Will Remove Unpainted Artwork „Разделяне“ и „Контур“ премахват небоядисаната графика
|
||||
@msg precision must be from 0.001 to 10 pt precision трябва да е от 0,001 до 10 pt
|
||||
@msg `pathfinder` must be an object `pathfinder` трябва да бъде обект
|
||||
Add to Brushes Добавяне към четки
|
||||
Brush Library Библиотека с четки
|
||||
Save Brush Library Запази библиотека с четки
|
||||
Save Brushes… Запази четки…
|
||||
Open Brush Library Отваряне на библиотека с четки
|
||||
Selected Brushes Only Само избрани четки
|
||||
Brush Libraries Menu Меню с библиотеки с четки
|
||||
User Brush Library 1 Потребителска библиотека с четки 1
|
||||
User Brush Library 2 Потребителска библиотека с четки 2
|
||||
User Brush Library 3 Потребителска библиотека с четки 3
|
||||
User Brush Library 4 Потребителска библиотека с четки 4
|
||||
User Brush Library 5 Потребителска библиотека с четки 5
|
||||
User Brush Library 6 Потребителска библиотека с четки 6
|
||||
User Brush Library 7 Потребителска библиотека с четки 7
|
||||
User Brush Library 8 Потребителска библиотека с четки 8
|
||||
User Brush Library 9 Потребителска библиотека с четки 9
|
||||
User Brush Library 10 Потребителска библиотека с четки 10
|
||||
Art Ribbons Арт ленти
|
||||
Calligraphic Nibs Калиграфски писци
|
||||
Pattern Borders Бордюри с мостри
|
||||
Scatter Shapes Разсеяни фигури
|
||||
Save Brush Library… Запази библиотека с четки…
|
||||
@msg no empty artboards to delete няма празни работни области за изтриване
|
||||
Scale Presets Пресети за мащаб
|
||||
Live preview Преглед на живо
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -327,6 +327,7 @@
|
||||
Apply Bullets Použít odrážky
|
||||
Numbered List Číslovaný seznam
|
||||
Apply Numbers Použít číslování
|
||||
Convert to Text Převést na text
|
||||
Filled Dot Plná tečka
|
||||
Dash Pomlčka
|
||||
Hollow Circle Prázdný kruh
|
||||
@@ -374,6 +375,7 @@
|
||||
Create Vytvořit
|
||||
Release Selection Uvolnit výběr
|
||||
Remove Threading Odstranit zřetězení
|
||||
Break Thread Přerušit zřetězení
|
||||
Fit Headline Přizpůsobit titulek
|
||||
Find Font… Najít písmo…
|
||||
Change Case Změnit velikost písmen
|
||||
@@ -598,6 +600,21 @@
|
||||
Saved View 8 Uložené zobrazení 8
|
||||
Saved View 9 Uložené zobrazení 9
|
||||
Saved View 10 Uložené zobrazení 10
|
||||
Saved View 11 Uložené zobrazení 11
|
||||
Saved View 12 Uložené zobrazení 12
|
||||
Saved View 13 Uložené zobrazení 13
|
||||
Saved View 14 Uložené zobrazení 14
|
||||
Saved View 15 Uložené zobrazení 15
|
||||
Saved View 16 Uložené zobrazení 16
|
||||
Saved View 17 Uložené zobrazení 17
|
||||
Saved View 18 Uložené zobrazení 18
|
||||
Saved View 19 Uložené zobrazení 19
|
||||
Saved View 20 Uložené zobrazení 20
|
||||
Saved View 21 Uložené zobrazení 21
|
||||
Saved View 22 Uložené zobrazení 22
|
||||
Saved View 23 Uložené zobrazení 23
|
||||
Saved View 24 Uložené zobrazení 24
|
||||
Saved View 25 Uložené zobrazení 25
|
||||
Window Okno
|
||||
New Window Nové okno
|
||||
Cascade Do kaskády
|
||||
@@ -1384,7 +1401,6 @@ lighting Light Světlo
|
||||
URL: URL:
|
||||
Use Even-Odd Fill Rule Použít pravidlo výplně sudá-lichá
|
||||
Use Non-Zero Winding Fill Rule Použít pravidlo výplně nenulového vinutí
|
||||
Brush Libraries (on the roadmap) Knihovny štětců (v plánu)
|
||||
List View Zobrazení seznamu
|
||||
New Art Brush from Selection Nový obrazový štětec z výběru
|
||||
New Bristle Brush Nový štětinový štětec
|
||||
@@ -4667,6 +4683,7 @@ imageTrace Outline Obrys
|
||||
@msg {_1} is already used by {_2} {_1} už používá {_2}
|
||||
@msg {_1} is reserved by the system Zkratku {_1} si vyhrazuje systém
|
||||
@msg {_1} linked file(s) can't be read here: their previews show propojené soubory ({_1}) zde nelze přečíst: zobrazují se jejich náhledy
|
||||
@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes obrázky ({undecoded}) nelze dekódovat: zobrazují se jako přeškrtnuté rámečky
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions propojené obrázky ({_1}) se na disku změnily: nové verze zobrazí Aktualizovat propojení
|
||||
@msg {_1}: not saved, so not closed {_1}: neuloženo, proto nezavřeno
|
||||
@msg {bpp}-bit bitmaps can't be read {bpp}bitové bitmapy nelze přečíst
|
||||
@@ -5222,6 +5239,7 @@ mark-style Japanese Japonské
|
||||
@msg unknown parameter `{key}`; the command takes: {keys} neznámý parametr `{key}`; příkaz přijímá: {keys}
|
||||
Load EPS into Clipboard Načíst EPS do schránky
|
||||
@msg an image of {w} × {h} pixels is too large to draw obraz o velikosti {w} × {h} obrazových bodů je příliš velký na vykreslení
|
||||
@msg an image of {w} × {h} pixels is shown at reduced size obraz o velikosti {w} × {h} obrazových bodů se zobrazuje ve zmenšené velikosti
|
||||
@msg the image can't be read as a texture obraz nelze načíst jako texturu
|
||||
Fill and Stroke Controls Ovládací prvky výplně a tahu
|
||||
Coloring Controls Ovládací prvky barev
|
||||
@@ -5558,6 +5576,40 @@ axis Y Axis osa Y
|
||||
Rectangular Grid Tool Options Možnosti nástroje Obdélníková mřížka
|
||||
Polar Grid Tool Options Možnosti nástroje Polární mřížka
|
||||
Fill Line Výplň úsečky
|
||||
Pathfinder Options Možnosti operací s cestami
|
||||
Divide and Outline Will Remove Unpainted Artwork Rozdělit a Obrys odstraní nenatřenou kresbu
|
||||
@msg precision must be from 0.001 to 10 pt precision musí být od 0,001 do 10 pt
|
||||
@msg `pathfinder` must be an object `pathfinder` musí být objekt
|
||||
Add to Brushes Přidat do štětců
|
||||
Brush Library Knihovna štětců
|
||||
Save Brush Library Uložit knihovnu štětců
|
||||
Save Brushes… Uložit štětce…
|
||||
Open Brush Library Otevřít knihovnu štětců
|
||||
Selected Brushes Only Pouze vybrané štětce
|
||||
Brush Libraries Menu Nabídka knihoven štětců
|
||||
User Brush Library 1 Uživatelská knihovna štětců 1
|
||||
User Brush Library 2 Uživatelská knihovna štětců 2
|
||||
User Brush Library 3 Uživatelská knihovna štětců 3
|
||||
User Brush Library 4 Uživatelská knihovna štětců 4
|
||||
User Brush Library 5 Uživatelská knihovna štětců 5
|
||||
User Brush Library 6 Uživatelská knihovna štětců 6
|
||||
User Brush Library 7 Uživatelská knihovna štětců 7
|
||||
User Brush Library 8 Uživatelská knihovna štětců 8
|
||||
User Brush Library 9 Uživatelská knihovna štětců 9
|
||||
User Brush Library 10 Uživatelská knihovna štětců 10
|
||||
Art Ribbons Obrazové stuhy
|
||||
Calligraphic Nibs Kaligrafická pera
|
||||
Pattern Borders Vzorkové okraje
|
||||
Scatter Shapes Rozptýlené tvary
|
||||
Save Brush Library… Uložit knihovnu štětců…
|
||||
@msg `{_1}` has no brushes to apply `{_1}` nemá žádné štětce k použití
|
||||
@msg missing `library` (see brush.libraries) chybí `library` (viz brush.libraries)
|
||||
@msg no brush `{n}` žádný štětec `{n}`
|
||||
@msg no brush `{n}` in `{_1}` žádný štětec `{n}` v `{_1}`
|
||||
@msg no brush library `{key}` (see brush.libraries) žádná knihovna štětců `{key}` (viz brush.libraries)
|
||||
@msg the document has no brushes to save dokument nemá žádné štětce k uložení
|
||||
@msg no empty artboards to delete žádné prázdné pracovní plochy k odstranění
|
||||
Scale Presets Přednastavení měřítka
|
||||
@msg a {width}×{height} screenshot's byte count overflows počet bajtů snímku {width}×{height} přeteče
|
||||
@msg the window's {what} ({points} points × {scale} DPI) cannot size a screenshot okno {what} ({points} bodů × {scale} DPI) nemůže určit velikost snímku
|
||||
Live preview Živý náhled
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -289,6 +289,7 @@
|
||||
Apply Bullets Anvend kugletegn
|
||||
Numbered List Nummereret liste
|
||||
Apply Numbers Anvend nummerering
|
||||
Convert to Text Konvertér til tekst
|
||||
Filled Dot Udfyldt prik
|
||||
Dash Tankestreg
|
||||
Hollow Circle Tom cirkel
|
||||
@@ -336,6 +337,7 @@
|
||||
Create Opret
|
||||
Release Selection Frigør markering
|
||||
Remove Threading Fjern sammenkædning
|
||||
Break Thread Bryd sammenkædning
|
||||
Fit Headline Tilpas overskrift
|
||||
Find Font… Find skrifttype…
|
||||
Change Case Ændr store/små bogstaver
|
||||
@@ -551,6 +553,21 @@
|
||||
Saved View 8 Gemt visning 8
|
||||
Saved View 9 Gemt visning 9
|
||||
Saved View 10 Gemt visning 10
|
||||
Saved View 11 Gemt visning 11
|
||||
Saved View 12 Gemt visning 12
|
||||
Saved View 13 Gemt visning 13
|
||||
Saved View 14 Gemt visning 14
|
||||
Saved View 15 Gemt visning 15
|
||||
Saved View 16 Gemt visning 16
|
||||
Saved View 17 Gemt visning 17
|
||||
Saved View 18 Gemt visning 18
|
||||
Saved View 19 Gemt visning 19
|
||||
Saved View 20 Gemt visning 20
|
||||
Saved View 21 Gemt visning 21
|
||||
Saved View 22 Gemt visning 22
|
||||
Saved View 23 Gemt visning 23
|
||||
Saved View 24 Gemt visning 24
|
||||
Saved View 25 Gemt visning 25
|
||||
Window Vindue
|
||||
New Window Nyt vindue
|
||||
Cascade Kaskade
|
||||
@@ -1302,7 +1319,6 @@ lighting Light Lys
|
||||
URL: URL:
|
||||
Use Even-Odd Fill Rule Brug fyldreglen lige-ulige
|
||||
Use Non-Zero Winding Fill Rule Brug fyldreglen ikke-nul-vikling
|
||||
Brush Libraries (on the roadmap) Penselbiblioteker (på vejkortet)
|
||||
List View Listevisning
|
||||
New Art Brush from Selection Ny kunstpensel fra markering
|
||||
New Bristle Brush Ny bustpensel
|
||||
@@ -4863,6 +4879,7 @@ mark-style Japanese Japansk
|
||||
@msg unknown parameter `{key}`; the command takes: {keys} ukendt parameter `{key}`; kommandoen tager: {keys}
|
||||
Load EPS into Clipboard Indlæs EPS i udklipsholderen
|
||||
@msg an image of {w} × {h} pixels is too large to draw et billede på {w} × {h} pixels er for stort til at tegne
|
||||
@msg an image of {w} × {h} pixels is shown at reduced size et billede på {w} × {h} pixels vises i reduceret størrelse
|
||||
Fill and Stroke Controls Styring af fyld og streg
|
||||
Coloring Controls Styring af farvelægning
|
||||
Draw Mode Controls Styring af tegnetilstand
|
||||
@@ -5498,4 +5515,32 @@ axis Y Axis Y-akse
|
||||
Rectangular Grid Tool Options Indstillinger for rektangulært gitterværktøj
|
||||
Polar Grid Tool Options Indstillinger for polært gitterværktøj
|
||||
Fill Line Udfyld linje
|
||||
Pathfinder Options Pathfinder-indstillinger
|
||||
Divide and Outline Will Remove Unpainted Artwork Opdel og Kontur fjerner grafik uden maling
|
||||
@msg precision must be from 0.001 to 10 pt precision skal være fra 0,001 til 10 pt
|
||||
@msg `pathfinder` must be an object `pathfinder` skal være et objekt
|
||||
Add to Brushes Føj til pensler
|
||||
Brush Library Penselbibliotek
|
||||
Save Brush Library Gem penselbibliotek
|
||||
Save Brushes… Gem pensler…
|
||||
Open Brush Library Åbn penselbibliotek
|
||||
Selected Brushes Only Kun valgte pensler
|
||||
Brush Libraries Menu Menu med penselbiblioteker
|
||||
User Brush Library 1 Brugerpenselbibliotek 1
|
||||
User Brush Library 2 Brugerpenselbibliotek 2
|
||||
User Brush Library 3 Brugerpenselbibliotek 3
|
||||
User Brush Library 4 Brugerpenselbibliotek 4
|
||||
User Brush Library 5 Brugerpenselbibliotek 5
|
||||
User Brush Library 6 Brugerpenselbibliotek 6
|
||||
User Brush Library 7 Brugerpenselbibliotek 7
|
||||
User Brush Library 8 Brugerpenselbibliotek 8
|
||||
User Brush Library 9 Brugerpenselbibliotek 9
|
||||
User Brush Library 10 Brugerpenselbibliotek 10
|
||||
Art Ribbons Kunstbånd
|
||||
Calligraphic Nibs Kalligrafiske penne
|
||||
Pattern Borders Mønsterborter
|
||||
Scatter Shapes Spredte former
|
||||
Save Brush Library… Gem penselbibliotek…
|
||||
@msg no empty artboards to delete ingen tomme tegneflader at slette
|
||||
Scale Presets Skaleringsforudindstillinger
|
||||
Live preview Direkte forhåndsvisning
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -317,7 +317,6 @@ font-technology Variable Variabel
|
||||
Brush Affects: Pinsel wirkt auf:
|
||||
Brush Definition Pinseldefinition
|
||||
Brush Libraries Pinsel-Bibliotheken
|
||||
Brush Libraries (on the roadmap) Pinsel-Bibliotheken (geplant)
|
||||
Brush Options… Pinseloptionen…
|
||||
Brush Strokes Pinselstriche
|
||||
Brushes Pinsel
|
||||
@@ -332,6 +331,7 @@ font-technology Variable Variabel
|
||||
Apply Bullets Aufzählungszeichen anwenden
|
||||
Numbered List Nummerierte Liste
|
||||
Apply Numbers Nummerierung anwenden
|
||||
Convert to Text In Text umwandeln
|
||||
Filled Dot Gefüllter Punkt
|
||||
Dash Strich
|
||||
Hollow Circle Leerer Kreis
|
||||
@@ -2567,6 +2567,7 @@ mark-style Japanese Japanisch
|
||||
Remove Plug-in Plug-in entfernen
|
||||
Remove Selected Assets Ausgewählte Assets entfernen
|
||||
Remove Threading Verkettung entfernen
|
||||
Break Thread Verkettung trennen
|
||||
Remove “{keyword}” „{keyword}“ entfernen
|
||||
Rename Umbenennen
|
||||
Rename Asset Asset umbenennen
|
||||
@@ -2768,7 +2769,22 @@ mark-style Japanese Japanisch
|
||||
Saved to User Defined: {} In „Benutzerdefiniert“ gespeichert: {}
|
||||
Saved View 1 Gespeicherte Ansicht 1
|
||||
Saved View 10 Gespeicherte Ansicht 10
|
||||
Saved View 11 Gespeicherte Ansicht 11
|
||||
Saved View 12 Gespeicherte Ansicht 12
|
||||
Saved View 13 Gespeicherte Ansicht 13
|
||||
Saved View 14 Gespeicherte Ansicht 14
|
||||
Saved View 15 Gespeicherte Ansicht 15
|
||||
Saved View 16 Gespeicherte Ansicht 16
|
||||
Saved View 17 Gespeicherte Ansicht 17
|
||||
Saved View 18 Gespeicherte Ansicht 18
|
||||
Saved View 19 Gespeicherte Ansicht 19
|
||||
Saved View 2 Gespeicherte Ansicht 2
|
||||
Saved View 20 Gespeicherte Ansicht 20
|
||||
Saved View 21 Gespeicherte Ansicht 21
|
||||
Saved View 22 Gespeicherte Ansicht 22
|
||||
Saved View 23 Gespeicherte Ansicht 23
|
||||
Saved View 24 Gespeicherte Ansicht 24
|
||||
Saved View 25 Gespeicherte Ansicht 25
|
||||
Saved View 3 Gespeicherte Ansicht 3
|
||||
Saved View 4 Gespeicherte Ansicht 4
|
||||
Saved View 5 Gespeicherte Ansicht 5
|
||||
@@ -4290,6 +4306,7 @@ theme Appearance Erscheinungsbild
|
||||
@msg {_1} is already used by {_2} {_1} wird bereits von {_2} verwendet
|
||||
@msg {_1} is reserved by the system {_1} ist vom System reserviert
|
||||
@msg {_1} linked file(s) can't be read here: their previews show {_1} verknüpfte Datei(en) können hier nicht gelesen werden: Ihre Vorschauen werden angezeigt
|
||||
@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes {undecoded} Bild(er) konnten nicht dekodiert werden und werden als durchgekreuzte Rahmen angezeigt
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} verknüpfte(s) Bild(er) wurde(n) auf dem Datenträger geändert: „Verknüpfungen aktualisieren“ zeigt die neuen Versionen
|
||||
@msg {_1}: not saved, so not closed {_1}: nicht gespeichert, daher nicht geschlossen
|
||||
@msg {bpp}-bit bitmaps can't be read {bpp}-Bit-Bitmaps können nicht gelesen werden
|
||||
@@ -4788,6 +4805,7 @@ lighting Light Licht
|
||||
@msg unknown parameter `{key}`; the command takes: {keys} unbekannter Parameter `{key}`; der Befehl akzeptiert: {keys}
|
||||
Load EPS into Clipboard EPS in die Zwischenablage laden
|
||||
@msg an image of {w} × {h} pixels is too large to draw ein Bild mit {w} × {h} Pixeln ist zu groß, um gezeichnet zu werden
|
||||
@msg an image of {w} × {h} pixels is shown at reduced size ein Bild mit {w} × {h} Pixeln wird verkleinert angezeigt
|
||||
@msg the image can't be read as a texture das Bild kann nicht als Struktur gelesen werden
|
||||
Basic Basis
|
||||
Fill and Stroke Controls Steuerelemente für Fläche und Kontur
|
||||
@@ -5140,6 +5158,40 @@ axis Y Axis Y-Achse
|
||||
Rectangular Grid Tool Options Optionen für das Rechteckiges-Raster-Werkzeug
|
||||
Polar Grid Tool Options Optionen für das Radiales-Raster-Werkzeug
|
||||
Fill Line Linie füllen
|
||||
Pathfinder Options Pathfinder-Optionen
|
||||
Divide and Outline Will Remove Unpainted Artwork „Fläche aufteilen“ und „Pfadansicht“ entfernen ungefärbtes Bildmaterial
|
||||
@msg precision must be from 0.001 to 10 pt precision muss zwischen 0,001 und 10 pt liegen
|
||||
@msg `pathfinder` must be an object `pathfinder` muss ein Objekt sein
|
||||
Add to Brushes Zu Pinseln hinzufügen
|
||||
Brush Library Pinsel-Bibliothek
|
||||
Save Brush Library Pinsel-Bibliothek speichern
|
||||
Save Brushes… Pinsel speichern…
|
||||
Open Brush Library Pinsel-Bibliothek öffnen
|
||||
Selected Brushes Only Nur ausgewählte Pinsel
|
||||
Brush Libraries Menu Menü „Pinsel-Bibliotheken“
|
||||
User Brush Library 1 Benutzer-Pinsel-Bibliothek 1
|
||||
User Brush Library 2 Benutzer-Pinsel-Bibliothek 2
|
||||
User Brush Library 3 Benutzer-Pinsel-Bibliothek 3
|
||||
User Brush Library 4 Benutzer-Pinsel-Bibliothek 4
|
||||
User Brush Library 5 Benutzer-Pinsel-Bibliothek 5
|
||||
User Brush Library 6 Benutzer-Pinsel-Bibliothek 6
|
||||
User Brush Library 7 Benutzer-Pinsel-Bibliothek 7
|
||||
User Brush Library 8 Benutzer-Pinsel-Bibliothek 8
|
||||
User Brush Library 9 Benutzer-Pinsel-Bibliothek 9
|
||||
User Brush Library 10 Benutzer-Pinsel-Bibliothek 10
|
||||
Art Ribbons Bildbänder
|
||||
Calligraphic Nibs Kalligrafie-Federn
|
||||
Pattern Borders Musterbordüren
|
||||
Scatter Shapes Streuformen
|
||||
Save Brush Library… Pinsel-Bibliothek speichern…
|
||||
@msg `{_1}` has no brushes to apply `{_1}` hat keine Pinsel zum Anwenden
|
||||
@msg missing `library` (see brush.libraries) `library` fehlt (siehe brush.libraries)
|
||||
@msg no brush `{n}` kein Pinsel `{n}`
|
||||
@msg no brush `{n}` in `{_1}` kein Pinsel `{n}` in `{_1}`
|
||||
@msg no brush library `{key}` (see brush.libraries) keine Pinsel-Bibliothek `{key}` (siehe brush.libraries)
|
||||
@msg the document has no brushes to save das Dokument hat keine Pinsel zum Speichern
|
||||
@msg no empty artboards to delete keine leeren Zeichenflächen zum Löschen
|
||||
Scale Presets Skalierungsvorgaben
|
||||
@msg a {width}×{height} screenshot's byte count overflows die Byteanzahl eines {width}×{height}-Screenshots läuft über
|
||||
@msg the window's {what} ({points} points × {scale} DPI) cannot size a screenshot die {what} des Fensters ({points} Punkte × {scale} DPI) kann keinen Screenshot bemessen
|
||||
Live preview Live-Vorschau
|
||||
|
Can't render this file because it contains an unexpected character in line 2 and column 73.
|
@@ -320,7 +320,6 @@ font-technology Variable Μεταβλητές
|
||||
Brush Affects: Το πινέλο επηρεάζει:
|
||||
Brush Definition Ορισμός πινέλου
|
||||
Brush Libraries Βιβλιοθήκες πινέλων
|
||||
Brush Libraries (on the roadmap) Βιβλιοθήκες πινέλων (στον σχεδιασμό)
|
||||
Brush Options… Επιλογές πινέλου…
|
||||
Brush Strokes Πινελιές
|
||||
Brushes Πινέλα
|
||||
@@ -332,6 +331,7 @@ font-technology Variable Μεταβλητές
|
||||
Apply Bullets Εφαρμογή κουκκίδων
|
||||
Numbered List Αριθμημένη λίστα
|
||||
Apply Numbers Εφαρμογή αρίθμησης
|
||||
Convert to Text Μετατροπή σε κείμενο
|
||||
Filled Dot Γεμάτη κουκκίδα
|
||||
Dash Παύλα
|
||||
Hollow Circle Κενός κύκλος
|
||||
@@ -3145,6 +3145,7 @@ theme Appearance Εμφάνιση
|
||||
Remove Plug-in Αφαίρεση προσθέτου
|
||||
Remove Selected Assets Αφαίρεση επιλεγμένων στοιχείων
|
||||
Remove Threading Αφαίρεση σύνδεσης κειμένου
|
||||
Break Thread Διακοπή σύνδεσης κειμένου
|
||||
Remove “{keyword}” Αφαίρεση «{keyword}»
|
||||
Rename Asset Μετονομασία στοιχείου
|
||||
Rename Character Style Μετονομασία στυλ χαρακτήρων
|
||||
@@ -4338,6 +4339,7 @@ theme Appearance Εμφάνιση
|
||||
@msg {_1} is already used by {_2} το {_1} χρησιμοποιείται ήδη από το {_2}
|
||||
@msg {_1} is reserved by the system Το {_1} είναι δεσμευμένο από το σύστημα
|
||||
@msg {_1} linked file(s) can't be read here: their previews show {_1} συνδεδεμένα αρχεία δεν μπορούν να διαβαστούν εδώ: εμφανίζονται οι προεπισκοπήσεις τους
|
||||
@msg {undecoded} image(s) couldn't be decoded and show as crossed boxes {undecoded} εικόνες δεν ήταν δυνατό να αποκωδικοποιηθούν: εμφανίζονται ως πλαίσια με σταυρό
|
||||
@msg {_1} linked image(s) changed on disk: Update Links shows the new versions {_1} συνδεδεμένες εικόνες άλλαξαν στον δίσκο: η Ενημέρωση συνδέσμων εμφανίζει τις νέες εκδόσεις
|
||||
@msg Updated {_1} linked file(s) changed on disk Ενημερώθηκαν {_1} συνδεδεμένα αρχεία που άλλαξαν στον δίσκο
|
||||
@msg {_1}: not saved, so not closed {_1}: δεν αποθηκεύτηκε και επομένως δεν έκλεισε
|
||||
@@ -4986,6 +4988,7 @@ effect Points Σημεία
|
||||
Load EPS into Clipboard Φόρτωση EPS στο πρόχειρο
|
||||
@msg unknown control `{name}`: fillStroke, coloring, drawMode or screenMode Άγνωστο στοιχείο ελέγχου `{name}`: fillStroke, coloring, drawMode ή screenMode
|
||||
@msg an image of {w} × {h} pixels is too large to draw Η εικόνα {w} × {h} εικονοστοιχείων είναι υπερβολικά μεγάλη για σχεδίαση
|
||||
@msg an image of {w} × {h} pixels is shown at reduced size Η εικόνα {w} × {h} εικονοστοιχείων εμφανίζεται σε μειωμένο μέγεθος
|
||||
Open Recent File 1 Άνοιγμα πρόσφατου αρχείου 1
|
||||
Open Recent File 2 Άνοιγμα πρόσφατου αρχείου 2
|
||||
Open Recent File 3 Άνοιγμα πρόσφατου αρχείου 3
|
||||
@@ -5066,6 +5069,21 @@ effect Points Σημεία
|
||||
Saved View 8 Αποθηκευμένη προβολή 8
|
||||
Saved View 9 Αποθηκευμένη προβολή 9
|
||||
Saved View 10 Αποθηκευμένη προβολή 10
|
||||
Saved View 11 Αποθηκευμένη προβολή 11
|
||||
Saved View 12 Αποθηκευμένη προβολή 12
|
||||
Saved View 13 Αποθηκευμένη προβολή 13
|
||||
Saved View 14 Αποθηκευμένη προβολή 14
|
||||
Saved View 15 Αποθηκευμένη προβολή 15
|
||||
Saved View 16 Αποθηκευμένη προβολή 16
|
||||
Saved View 17 Αποθηκευμένη προβολή 17
|
||||
Saved View 18 Αποθηκευμένη προβολή 18
|
||||
Saved View 19 Αποθηκευμένη προβολή 19
|
||||
Saved View 20 Αποθηκευμένη προβολή 20
|
||||
Saved View 21 Αποθηκευμένη προβολή 21
|
||||
Saved View 22 Αποθηκευμένη προβολή 22
|
||||
Saved View 23 Αποθηκευμένη προβολή 23
|
||||
Saved View 24 Αποθηκευμένη προβολή 24
|
||||
Saved View 25 Αποθηκευμένη προβολή 25
|
||||
Three Point Perspective Preset 1 Προεπιλογή προοπτικής τριών σημείων 1
|
||||
Three Point Perspective Preset 2 Προεπιλογή προοπτικής τριών σημείων 2
|
||||
Three Point Perspective Preset 3 Προεπιλογή προοπτικής τριών σημείων 3
|
||||
@@ -5510,6 +5528,40 @@ axis Y Axis Άξονας Y
|
||||
Rectangular Grid Tool Options Επιλογές εργαλείου ορθογώνιου πλέγματος
|
||||
Polar Grid Tool Options Επιλογές εργαλείου πολικού πλέγματος
|
||||
Fill Line Γέμισμα γραμμής
|
||||
Pathfinder Options Επιλογές Pathfinder
|
||||
Divide and Outline Will Remove Unpainted Artwork Η Διαίρεση και το Περίγραμμα αφαιρούν τα γραφικά χωρίς χρώμα
|
||||
@msg precision must be from 0.001 to 10 pt το precision πρέπει να είναι από 0,001 έως 10 pt
|
||||
@msg `pathfinder` must be an object Το `pathfinder` πρέπει να είναι αντικείμενο
|
||||
Add to Brushes Προσθήκη στα πινέλα
|
||||
Brush Library Βιβλιοθήκη πινέλων
|
||||
Save Brush Library Αποθήκευση βιβλιοθήκης πινέλων
|
||||
Save Brushes… Αποθήκευση πινέλων…
|
||||
Open Brush Library Άνοιγμα βιβλιοθήκης πινέλων
|
||||
Selected Brushes Only Μόνο επιλεγμένα πινέλα
|
||||
Brush Libraries Menu Μενού βιβλιοθηκών πινέλων
|
||||
User Brush Library 1 Βιβλιοθήκη πινέλων χρήστη 1
|
||||
User Brush Library 2 Βιβλιοθήκη πινέλων χρήστη 2
|
||||
User Brush Library 3 Βιβλιοθήκη πινέλων χρήστη 3
|
||||
User Brush Library 4 Βιβλιοθήκη πινέλων χρήστη 4
|
||||
User Brush Library 5 Βιβλιοθήκη πινέλων χρήστη 5
|
||||
User Brush Library 6 Βιβλιοθήκη πινέλων χρήστη 6
|
||||
User Brush Library 7 Βιβλιοθήκη πινέλων χρήστη 7
|
||||
User Brush Library 8 Βιβλιοθήκη πινέλων χρήστη 8
|
||||
User Brush Library 9 Βιβλιοθήκη πινέλων χρήστη 9
|
||||
User Brush Library 10 Βιβλιοθήκη πινέλων χρήστη 10
|
||||
Art Ribbons Γραφικές κορδέλες
|
||||
Calligraphic Nibs Καλλιγραφικές πένες
|
||||
Pattern Borders Περιθώρια μοτίβου
|
||||
Scatter Shapes Σχήματα διασποράς
|
||||
Save Brush Library… Αποθήκευση βιβλιοθήκης πινέλων…
|
||||
@msg `{_1}` has no brushes to apply Η `{_1}` δεν έχει πινέλα για εφαρμογή
|
||||
@msg missing `library` (see brush.libraries) λείπει το `library` (δείτε brush.libraries)
|
||||
@msg no brush `{n}` δεν υπάρχει πινέλο `{n}`
|
||||
@msg no brush `{n}` in `{_1}` δεν υπάρχει πινέλο `{n}` στη `{_1}`
|
||||
@msg no brush library `{key}` (see brush.libraries) δεν υπάρχει βιβλιοθήκη πινέλων `{key}` (δείτε brush.libraries)
|
||||
@msg the document has no brushes to save το έγγραφο δεν έχει πινέλα για αποθήκευση
|
||||
@msg no empty artboards to delete δεν υπάρχουν κενοί πίνακες σχεδίασης για διαγραφή
|
||||
Scale Presets Προεπιλογές κλίμακας
|
||||
@msg a {width}×{height} screenshot's byte count overflows το πλήθος byte ενός στιγμιότυπου {width}×{height} υπερχειλίζει
|
||||
@msg the window's {what} ({points} points × {scale} DPI) cannot size a screenshot το {what} του παραθύρου ({points} σημεία × {scale} DPI) δεν μπορεί να καθορίσει μέγεθος στιγμιότυπου
|
||||
Live preview Ζωντανή προεπισκόπηση
|
||||
|
Can't render this file because it contains an unexpected character in line 2070 and column 19.
|
Loaded 100 of 153 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user