mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 21:42:59 -05:00
Merge main into fix/save-metadata-only-change
This commit is contained in:
commit
4e8dfc369d
54 files changed
+7109
-228
No files matched your search
+2
-2
@@ -18,7 +18,7 @@ gate: all six core workflows (path drawing and editing, paint and style, type, l
|
||||
production, file exchange) work end to end on macOS with save and reopen, and only the last is partial, without
|
||||
blocking it ([Alpha gate](docs/roadmap.md#alpha-gate)).
|
||||
|
||||
> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial, and the pinned CI/release fonts and web startup list contain no Gujarati face; web selection stays unavailable until a Gujarati interface face is bundled. Scores and estimates unchanged.
|
||||
> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status and error messages: 4,946 `@msg` and 56 `@msgplural` rows (2026-12-02); with 155 menu, label and undo rows added the same day the catalog has 10,890 rows; all machine-assisted, native review pending; `gu` is in `COMPLETE_MESSAGES`. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, and since 2026-12-02 the web build fetches it when the interface needs it (`crates/text/web-fonts.txt`, `demand`), so a web build made with `CRAFT_FONTS_DIR` pointing at a craft-fonts checkout that has Noto Sans Gujarati offers Gujarati; a web build without it does not. Scores and estimates unchanged.
|
||||
|
||||
## Headline numbers
|
||||
|
||||
@@ -98,7 +98,7 @@ Weights, evidence and the missing items per area: [target-app-parity.md](docs/ta
|
||||
| Simplified Chinese | `zh-hans` | partial (most messages translated, #2578; some remain untranslated) | 85% |
|
||||
| Spanish | `es` | full | 100% |
|
||||
| Hindi | `hi` | catalog complete; machine-assisted draft, native review pending | complete under the scanner |
|
||||
| Gujarati | `gu` | 4,673 contributor-reviewed catalog rows; 11 corrections applied to the 387 additions | menus and dialogs; status/error messages partial |
|
||||
| Gujarati | `gu` | 4,673 contributor-reviewed catalog rows; 11 corrections applied to the 387 additions | menus, dialogs, status and error messages (messages machine-assisted, review pending) |
|
||||
| Arabic | `ar` | none (no right-to-left interface) | 0% |
|
||||
| French | `fr` | full | 100% |
|
||||
| Portuguese (Brazil) | `pt-br` | full | 100% |
|
||||
|
||||
@@ -1019,7 +1019,8 @@ mod portable {
|
||||
|
||||
/// What our last write put on the clipboard, for a read answered late ([`Unanswered::paste`]): a
|
||||
/// paste does not take what this app copied. Whether the clipboard still holds a copy is
|
||||
/// [`Clipboard::owns`](ClipboardBackend::owns).
|
||||
/// [`Clipboard::owns`](ClipboardBackend::owns). A bitmap is known by its size alone, so another
|
||||
/// app's bitmap of the same size counts as the Copy made here.
|
||||
#[derive(Clone)]
|
||||
enum Ours {
|
||||
Text(String),
|
||||
@@ -1204,7 +1205,10 @@ mod portable {
|
||||
/// paste's bitmap read waits. Once it comes,
|
||||
/// the same read is made again, since the clipboard may have changed hands meanwhile.
|
||||
/// `None`, so the paste takes the internal clipboard, when that answer doesn't come or the
|
||||
/// new one is what `ours` put on the clipboard. Otherwise the clipboard is read as
|
||||
/// clipboard, read as `ours` was written (its text or its bitmap), holds what `ours` put
|
||||
/// there; when that takes a read of its own, copied files are read before it, and before a
|
||||
/// bitmap read the text as well. Otherwise
|
||||
/// the clipboard is read as
|
||||
/// [`Clipboard::read_now_or_later`] and the paste read it, the new answer standing in for
|
||||
/// the read it answers: copied files, else
|
||||
/// text, else the bitmap, and the bitmap when it is asked for and the text is blank or only
|
||||
@@ -1220,21 +1224,49 @@ mod portable {
|
||||
.unwrap_or_else(|why| Answer::failed(request, why))
|
||||
};
|
||||
// The late answer may come from an app that lost the clipboard while it was awaited.
|
||||
let answer = fresh(self.request);
|
||||
let held = match (&answer, ours) {
|
||||
(Answer::Text(Ok(now)), Some(Ours::Text(t))) => now == t,
|
||||
(Answer::Image(Ok(now)), Some(Ours::Image(w, h))) => (now.width, now.height) == (*w, *h),
|
||||
let mut answer = Some(fresh(self.request));
|
||||
// The Copy made here is read as it was written, whatever the late read was: a Copy's
|
||||
// text read that answers late leaves a bitmap Copy with no text to compare.
|
||||
let written = match ours {
|
||||
Some(Ours::Text(_)) => Some(Request::Text),
|
||||
Some(Ours::Image(..)) => Some(Request::Image),
|
||||
None => None,
|
||||
};
|
||||
let mut check = None;
|
||||
let mut text_first = None;
|
||||
let mut files_read = false;
|
||||
if let Some(written) = written.filter(|w| answer.as_ref().is_some_and(|a| a.request() != *w)) {
|
||||
// Copied files are read first: a Copy made here writes none, and a read of the
|
||||
// Copy's format that gets no answer leaves the worker busy for the files' read.
|
||||
let files = answer.take_if(|a| a.request() == Request::Files).unwrap_or_else(|| fresh(Request::Files));
|
||||
if let Some(f) = copied_file(files.files(), mimes) {
|
||||
return Some(f);
|
||||
}
|
||||
files_read = true;
|
||||
// The text is read before a bitmap check for the same reason: a bitmap read that
|
||||
// gets no answer leaves the worker busy for the text's read.
|
||||
if written == Request::Image && mimes.contains(&TEXT) && !answer.as_ref().is_some_and(|a| a.request() == Request::Text) {
|
||||
text_first = Some(fresh(Request::Text));
|
||||
}
|
||||
check = Some(fresh(written));
|
||||
}
|
||||
let held = match (check.as_ref().or(answer.as_ref()), ours) {
|
||||
(Some(Answer::Text(Ok(now))), Some(Ours::Text(t))) => now == t,
|
||||
(Some(Answer::Image(Ok(now))), Some(Ours::Image(w, h))) => (now.width, now.height) == (*w, *h),
|
||||
_ => false,
|
||||
};
|
||||
if held {
|
||||
return None;
|
||||
}
|
||||
let mut answer = Some(answer);
|
||||
let mut read = |request: Request| match answer.take_if(|a| a.request() == request) {
|
||||
let mut read = |request: Request| match answer
|
||||
.take_if(|a| a.request() == request)
|
||||
.or_else(|| check.take_if(|a| a.request() == request))
|
||||
.or_else(|| text_first.take_if(|a| a.request() == request))
|
||||
{
|
||||
Some(answer) => answer,
|
||||
None => fresh(request),
|
||||
};
|
||||
if let Some(f) = copied_file(read(Request::Files).files(), mimes) {
|
||||
if !files_read && let Some(f) = copied_file(read(Request::Files).files(), mimes) {
|
||||
return Some(f);
|
||||
}
|
||||
let text = if mimes.contains(&TEXT) { read(Request::Text).text().ok().filter(|t| !t.is_empty()) } else { None };
|
||||
@@ -2080,6 +2112,82 @@ mod portable {
|
||||
assert!(paste_after_check(2).is_none());
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn a_paste_after_an_unanswered_text_read_finds_a_bitmap_copied_here() {
|
||||
// A Copy reads the clipboard's text first; when that read gets no answer in its wait, the
|
||||
// Copy's art goes out as a `width`×1 bitmap with no text (a placed photo too large for
|
||||
// the SVG markup to go out as text). The paste then waits for the text read's answer.
|
||||
let paste_after_copy = |width: usize, fill: u8| {
|
||||
let (mut cb, release) = slow_owner(move |request| match request {
|
||||
Request::Image => Answer::Image(Ok(arboard::ImageData { width, height: 1, bytes: Cow::Owned(vec![fill; width * 4]) })),
|
||||
_ => Answer::failed(request, "none".into()),
|
||||
});
|
||||
assert!(cb.read_waiting(Request::Text, Duration::ZERO).text().is_err());
|
||||
let unanswered = cb.unanswered(&vectorcraft_engine::cmd::clipboard::PASTE_ORDER).expect("the text read is kept for the paste");
|
||||
let paste = std::thread::spawn(move || unanswered.paste(Some(&Ours::Image(2, 1)), &vectorcraft_engine::cmd::clipboard::PASTE_ORDER));
|
||||
drop(release);
|
||||
paste.join().ok().flatten()
|
||||
};
|
||||
// The bitmap copied here: the paste takes the internal clipboard, not a picture of it.
|
||||
assert!(paste_after_copy(2, 0).is_none());
|
||||
// A bitmap is known by its size: another app's bitmap of the same size counts as the Copy.
|
||||
assert!(paste_after_copy(2, 0xff).is_none());
|
||||
// Another app's bitmap of another size is pasted.
|
||||
let pasted = paste_after_copy(3, 0).expect("the other app's bitmap is pasted");
|
||||
assert_eq!((pasted.mime, decode_png(&pasted.data).map(|i| i.dimensions())), (PNG, Some((3, 1))));
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn a_paste_after_an_unanswered_text_read_takes_copied_files_before_reading_the_bitmap() {
|
||||
let d = tempfile::Builder::new().prefix("vectorcraft-late-files-").tempdir().unwrap();
|
||||
let art = d.path().join("art.png");
|
||||
let mut png = vec![];
|
||||
image::RgbaImage::new(2, 2).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
|
||||
std::fs::write(&art, &png).unwrap();
|
||||
let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let seen = asked.clone();
|
||||
// The owner offers files and no text; a bitmap read would get no answer in its wait.
|
||||
let (mut cb, release) = slow_owner(move |request| {
|
||||
seen.lock().unwrap().push(request);
|
||||
match request {
|
||||
Request::Files => Answer::Files(vec![art.clone()]),
|
||||
_ => Answer::failed(request, "none".into()),
|
||||
}
|
||||
});
|
||||
assert!(cb.read_waiting(Request::Text, Duration::ZERO).text().is_err());
|
||||
let unanswered = cb.unanswered(&vectorcraft_engine::cmd::clipboard::PASTE_ORDER).expect("the text read is kept for the paste");
|
||||
let paste = std::thread::spawn(move || unanswered.paste(Some(&Ours::Image(2, 1)), &vectorcraft_engine::cmd::clipboard::PASTE_ORDER));
|
||||
drop(release);
|
||||
assert_eq!(paste.join().ok().flatten().map(|f| (f.mime, f.data)), Some((PNG, png)));
|
||||
// The files were read before any bitmap read that could leave the worker busy.
|
||||
assert_eq!(*asked.lock().unwrap(), [Request::Text, Request::Text, Request::Files]);
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn a_paste_after_an_unanswered_files_read_reads_the_text_before_the_bitmap() {
|
||||
let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let seen = asked.clone();
|
||||
// The owner offers text and no files; a bitmap read would get no answer in its wait.
|
||||
let (mut cb, release) = slow_owner(move |request| {
|
||||
seen.lock().unwrap().push(request);
|
||||
match request {
|
||||
Request::Files => Answer::Files(vec![]),
|
||||
Request::Text => Answer::Text(Ok("copied elsewhere".into())),
|
||||
Request::Image => Answer::failed(request, "none".into()),
|
||||
}
|
||||
});
|
||||
assert!(cb.read_waiting(Request::Files, Duration::ZERO).files().is_empty());
|
||||
let unanswered = cb.unanswered(&vectorcraft_engine::cmd::clipboard::PASTE_ORDER).expect("the files read is kept for the paste");
|
||||
let paste = std::thread::spawn(move || unanswered.paste(Some(&Ours::Image(2, 1)), &vectorcraft_engine::cmd::clipboard::PASTE_ORDER));
|
||||
drop(release);
|
||||
assert_eq!(paste.join().ok().flatten().map(|f| (f.mime, f.data)), Some((TEXT, b"copied elsewhere".to_vec())));
|
||||
// The text was read before the bitmap read that could leave the worker busy.
|
||||
assert_eq!(*asked.lock().unwrap(), [Request::Files, Request::Files, Request::Text, Request::Image]);
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd", target_os = "openbsd"))]
|
||||
#[test]
|
||||
fn a_late_answer_to_an_ownership_check_is_pasted_only_while_it_is_awaited() {
|
||||
|
||||
@@ -180,10 +180,11 @@ pub(crate) use export_names::{
|
||||
use export_names::{distinct_names_by, write_encoded};
|
||||
use formats::{ARTBOARD, ARTBOARDS, RANGE, USE_ARTBOARDS, import_name, writable};
|
||||
pub use formats::{
|
||||
DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS, builtin_open_filters,
|
||||
export_extensions, extension, file_stem, format, format_for_name, has_own_title, importer_formats, library_open_filters, open_extensions,
|
||||
open_exts, open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_exts, place_filters, places_with_importer,
|
||||
plugin_formats, read_extensions, readable_format, readable_format_for_name, reads_as_dwg, titled_for_export, writable_format,
|
||||
DOC_EXTS, DOCX_EXTS, FORMATS, Format, FormatOption, OPEN_EXTS, PLACE_EXTS, RTF_EXTS, TEXT_DOCUMENT_EXTS, TEXT_EXTS, UNASSOCIATED_EXTS,
|
||||
builtin_open_filters, export_extensions, extension, file_stem, format, format_for_name, has_own_title, importer_formats, library_open_filters,
|
||||
open_extensions, open_exts, open_filters, opens_as_other, opens_with_importer, place_dialog_filters, place_exts, place_filters,
|
||||
places_with_importer, plugin_formats, read_extensions, readable_format, readable_format_for_name, reads_as_dwg, titled_for_export,
|
||||
writable_format,
|
||||
};
|
||||
pub(crate) use formats::{is_own_title, reads};
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Open Document",
|
||||
[],
|
||||
None,
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible file whose first PDF page's PieceInfo holds, in itself or nested up to four dictionaries deep counting PieceInfo, a key starting with AIPrivateData or AIPDFPrivateData, when its pages are imported as editable art rather than its editing copy restored, opens on its trim boxes with cropTo and crop omitted and on its crop boxes with cropTo: crop, or crop: crop and no cropTo), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a file with that PieceInfo key: its trim box when no box is named, its crop box with cropTo: crop or crop: crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignPro
Line truncated
|
||||
"{path | name | dataBase64 (a file's path, or its name with its bytes), pages?: \"2-3, 5\" (PDF/.ai: 1-based, default all; one artboard each) | page?: n, cropTo?: bounding|art|crop (default)|trim|bleed|media (the box each artboard gets; bounding: the art's bounds; trim: the bleed box round it becomes the document's bleed, and the artboards are 36 pt apart plus that bleed on both sides; a PDF-compatible file whose first PDF page's PieceInfo holds, in itself or nested up to four dictionaries deep counting PieceInfo, a key starting with AIPrivateData or AIPDFPrivateData, when its pages are imported as editable art rather than its editing copy restored, opens on its trim boxes with cropTo and crop omitted and on its crop boxes with cropTo: crop, or crop: crop and no cropTo), password? (encrypted PDFs; see document.pdfInfo), textAs?: text (default: point type per line, lines wrapped in a frame as area type where they lay out the same, in the file's fonts by name; missing ones are listed in warnings) | outlines (glyph paths), layers?: true (default: optional content groups become layers with their visibility, print state and lock — art that is off comes in as a hidden layer; other art goes to a layer per page; a PSD file's layers become layers holding their pixels, with their names, visibility, opacity and blend modes, groups as layers of sublayers, layer masks as opacity masks, clipped layers and layers in blend modes VectorCraft doesn't have merged with the layers below) | false (one layer per page, without the art that is off; Save then asks for a name; a PSD file opens as its merged image), hiddenLayers?: false (a PSD file's hidden layers come in hidden instead of being left out), importSlices?: true (a PSD file's slices become user slices over its canvas, with its layers or its merged image; slices the file generated automatically are left out, and slices that can't be read are left out with a warning), editingData?: true (default: an EPS, .ai or PDF that carries its editor's own copy of the art opens from it, with its layers, hidden objects, guides, artboards and the art outside them; a .ai or PDF whose type shows opens from its PDF part with textAs: outlines) | \"always\" (as true, and a .ai's editing copy is used even where it draws differently from its PDF part, which can be older; the warnings say so) | false (only what its page or PDF part prints, for print pipelines; a .ai saved without PDF compatibility then can't be opened), legacyNameEncoding?: windows-1252 (default) | macintosh | windows-949 (also euc-kr) | shift_jis | gbk | big5 (the code page names in the editing data of a .ai or an EPS are read in when they aren't UTF-8: layers, objects, artboards, colors, gradients, patterns, graphic styles, swatches, brushes, symbols, variables and data sets, and data sets' text values; warnings list the first three such names as read, and count the rest), colorMode?: rgb|cmyk (the mode the document opens in, its colours converted as file.documentColorMode does, through the profiles the document keeps after the color management policies of edit.colorSettings, grays? as there; default: the file's — a PDF keeps CMYK, Gray and spot inks (spot swatches at a tint) and opens in CMYK when painted mostly in CMYK), grays?: as file.documentColorMode, dxf?: {layout?: \"Model\" (default) | a paper layout's name (document.dxfInfo lists them), unit?, scale? (the ratio: 1 unit of the art = scale drawing units; default: the drawing at 1:1 in its own unit), fit?: false (scale to fit an artboard of fitTo?: [612, 792], turned to the art's orientation), scaleLineweights?: false (lineweights scale with the art), center?: true (false: the drawing's origin on the artboard's bottom-left corner; fitted art's bottom-left corner), mergeLayers?: false (all art on one layer)} (DXF), crop?: as cropTo (its older name), linkPages?: false (true: each page `pages` picks of a PDF or PDF-compatible .ai opens as a placed document linked to that page of the file, as file.place with link places one, on an artboard of its cropTo box (bounding: its art's bounds; a blank page: its crop box; a file with that PieceInfo key: its trim box when no box is named, its crop box with cropTo: crop or crop: crop; on its trim box a page shows its bleed box round the artboard and gives the document its bleed), in a row 36 pt apart (on trim boxes, plus the bleed on both sides), and a layer named after the page; links.embed makes a page editable art; refused for any other file, without a path, with a password or with textAs: outlines; Save then asks for a name), profileChoice?: \"useEmbedded\"|\"convert\"|\"discard\" (the profile of the document's color mode is not the working space: keep it, convert that model's colors into the working space and take it off, or take it off and keep the numbers) | \"leave\"|\"assignWorking\"|\"assign\" (the document has no profile of its color mode: leave it untagged, tag it with the working space, or with assignPro
Line truncated
|
||||
always,
|
||||
load::open
|
||||
),
|
||||
|
||||
@@ -714,9 +714,18 @@ pub const DOCX_EXTS: &[&str] = &["docx"];
|
||||
/// Word 97-2003 documents: File → Place sets them as area type with their formatting.
|
||||
pub const DOC_EXTS: &[&str] = &["doc"];
|
||||
|
||||
/// The Place dialog's Word filter: Word documents and Word 97-2003 documents.
|
||||
/// The Open and Place dialogs' Word filter: Word documents and Word 97-2003 documents.
|
||||
const WORD_EXTS: &[&str] = &["docx", "doc"];
|
||||
|
||||
/// Text, RTF and Word files: File › Open makes a new document of their text, set as File › Place
|
||||
/// sets it ([`TEXT_EXTS`], [`RTF_EXTS`], [`DOCX_EXTS`] and [`DOC_EXTS`]).
|
||||
pub const TEXT_DOCUMENT_EXTS: &[&str] = &["txt", "rtf", "docx", "doc"];
|
||||
|
||||
/// The Open and Place dialogs' filters of text, RTF and Word files, after the document formats.
|
||||
fn text_document_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
[("Text", TEXT_EXTS), ("RTF", RTF_EXTS), ("Word", WORD_EXTS)].into_iter()
|
||||
}
|
||||
|
||||
/// Every extension File → Place reads: [`OPEN_EXTS`], [`TEXT_EXTS`], [`RTF_EXTS`],
|
||||
/// [`DOCX_EXTS`] and [`DOC_EXTS`].
|
||||
pub const PLACE_EXTS: &[&str] = &[
|
||||
@@ -915,15 +924,20 @@ pub fn opens_as_other(ext: &str) -> bool {
|
||||
/// File › Open's extensions and filters for the installed importer plug-ins.
|
||||
type ImporterPart = (&'static [&'static str], Vec<(&'static str, &'static [&'static str])>);
|
||||
|
||||
/// File › Open's part for the installed importer plug-ins: the extensions of "All readable files"
|
||||
/// ([`OPEN_EXTS`], then the importers' extensions in plug-in id order) and one filter per importer
|
||||
/// File › Open's part for the installed importer plug-ins ([`importer_open_part`]): the
|
||||
/// extensions [`open_extensions`] gives, those of "All readable files", and the importers' filters.
|
||||
type ImporterOpenPart = (&'static [&'static str], &'static [&'static str], Vec<(&'static str, &'static [&'static str])>);
|
||||
|
||||
/// File › Open's part for the installed importer plug-ins: the extensions of the documents it reads
|
||||
/// ([`OPEN_EXTS`], then the importers' extensions in plug-in id order), those of "All readable
|
||||
/// files" (the same, with [`TEXT_DOCUMENT_EXTS`] after [`OPEN_EXTS`]), and one filter per importer
|
||||
/// that has extensions left, under its name. An importer's extensions leave out those a built-in
|
||||
/// format reads, which File › Open reads with that format, and those File › Open opens as something
|
||||
/// else ([`opens_as_other`]). Made once for each set of installed plug-ins, so it lives as long as
|
||||
/// the dialogs that hold it.
|
||||
fn importer_open_part() -> ImporterPart {
|
||||
/// format reads, which File › Open reads with that format, those of text, RTF and Word files, which
|
||||
/// File › Open reads as text, and those File › Open opens as something else ([`opens_as_other`]).
|
||||
/// Made once for each set of installed plug-ins, so it lives as long as the dialogs that hold it.
|
||||
fn importer_open_part() -> ImporterOpenPart {
|
||||
use vectorcraft_plugins::registry;
|
||||
static MADE: std::sync::Mutex<Option<(u64, ImporterPart)>> = std::sync::Mutex::new(None);
|
||||
static MADE: std::sync::Mutex<Option<(u64, ImporterOpenPart)>> = std::sync::Mutex::new(None);
|
||||
let mut made = MADE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let revision = registry::revision();
|
||||
if let Some((r, part)) = made.as_ref()
|
||||
@@ -934,7 +948,8 @@ fn importer_open_part() -> ImporterPart {
|
||||
let mut exts: Vec<&'static str> = open_exts().to_vec();
|
||||
let mut filters = Vec::new();
|
||||
for f in importer_formats() {
|
||||
let own: Vec<&'static str> = f.extensions.iter().copied().filter(|e| readable_format(e).is_none() && !opens_as_other(e)).collect();
|
||||
let own: Vec<&'static str> =
|
||||
f.extensions.iter().copied().filter(|e| readable_format(e).is_none() && !TEXT_DOCUMENT_EXTS.contains(e) && !opens_as_other(e)).collect();
|
||||
if own.is_empty() {
|
||||
continue;
|
||||
}
|
||||
@@ -946,27 +961,31 @@ fn importer_open_part() -> ImporterPart {
|
||||
let own: &'static [&'static str] = if own.len() == f.extensions.len() { f.extensions } else { Box::leak(own.into_boxed_slice()) };
|
||||
filters.push((f.label, own));
|
||||
}
|
||||
let all: Vec<&'static str> = open_exts().iter().chain(TEXT_DOCUMENT_EXTS).chain(&exts[open_exts().len()..]).copied().collect();
|
||||
let exts: &'static [&'static str] = if exts.len() == open_exts().len() { open_exts() } else { Box::leak(exts.into_boxed_slice()) };
|
||||
let part = (exts, filters);
|
||||
let part = (exts, &*Box::leak(all.into_boxed_slice()), filters);
|
||||
*made = Some((revision, part.clone()));
|
||||
part
|
||||
}
|
||||
|
||||
/// Every extension File › Open reads as a document: [`OPEN_EXTS`], then the extensions the
|
||||
/// installed importer plug-ins list that no built-in format reads and that File › Open doesn't open
|
||||
/// as something else ([`opens_as_other`]), in plug-in id order.
|
||||
/// as something else ([`opens_as_other`]), in plug-in id order. Text, RTF and Word files
|
||||
/// ([`TEXT_DOCUMENT_EXTS`]), which File › Open makes a document of, are not among them.
|
||||
pub fn open_extensions() -> &'static [&'static str] {
|
||||
importer_open_part().0
|
||||
}
|
||||
|
||||
/// File › Open's filters: "All readable files" first, then one per readable format, then one per
|
||||
/// importer plug-in (under its name, with the extensions [`open_extensions`] takes from it), then
|
||||
/// swatch and graphic style libraries (which open in their library panels), Libraries panel
|
||||
/// libraries, flattener, PDF, print, perspective grid and export presets and composite fonts
|
||||
/// (imported), shortcut sets, scripts (checked without running them) and plug-ins (installed).
|
||||
/// File › Open's filters: "All readable files" first ([`open_extensions`] with
|
||||
/// [`TEXT_DOCUMENT_EXTS`]), then one per readable format, then text, RTF and Word (`.docx` and
|
||||
/// `.doc`), then one per importer plug-in (under its name, with the extensions [`open_extensions`]
|
||||
/// takes from it), then swatch and graphic style libraries (which open in their library panels),
|
||||
/// Libraries panel libraries, flattener, PDF, print, perspective grid and export presets and
|
||||
/// composite fonts (imported), shortcut sets, scripts (checked without running them) and plug-ins
|
||||
/// (installed).
|
||||
pub fn open_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
let (all, importers) = importer_open_part();
|
||||
std::iter::once(("All readable files", all)).chain(format_filters()).chain(importers).chain(other_open_filters())
|
||||
let (_, all, importers) = importer_open_part();
|
||||
std::iter::once(("All readable files", all)).chain(format_filters()).chain(text_document_filters()).chain(importers).chain(other_open_filters())
|
||||
}
|
||||
|
||||
/// [`open_filters`] without the importer plug-ins: "All readable files" lists [`OPEN_EXTS`]. For
|
||||
@@ -1011,9 +1030,7 @@ pub fn library_open_filters(
|
||||
pub fn place_filters() -> impl Iterator<Item = (&'static str, &'static [&'static str])> {
|
||||
std::iter::once(("All placeable files", place_exts()))
|
||||
.chain(format_filters().filter(|(_, exts)| exts.iter().all(|ext| PLACE_EXTS.contains(ext))))
|
||||
.chain(std::iter::once(("Text", TEXT_EXTS)))
|
||||
.chain(std::iter::once(("RTF", RTF_EXTS)))
|
||||
.chain(std::iter::once(("Word", WORD_EXTS)))
|
||||
.chain(text_document_filters())
|
||||
}
|
||||
|
||||
/// File › Place's part for the installed importer plug-ins whose manifests set `place`: the
|
||||
|
||||
@@ -55,14 +55,15 @@ fn check_extension(cmd: &str, m: &Manifest, name: &str) -> Result<()> {
|
||||
|
||||
/// The importer that opens the file `name` holding `bytes` with `document.open`'s params `p`: the
|
||||
/// one `importer` names, which must list the file's extension; else, when no built-in format reads
|
||||
/// the file, the first installed importer that lists its extension; else `None`.
|
||||
/// the file and it is no text, RTF or Word file by its extension, the first installed importer
|
||||
/// that lists its extension; else `None`.
|
||||
pub(super) fn pick(name: &str, bytes: &[u8], p: &Value) -> Result<Option<Arc<Plugin>>> {
|
||||
if let Some(id) = named(p, C)? {
|
||||
let plugin = import::named(id).map_err(|e| bad(C, e.to_string()))?;
|
||||
check_extension(C, plugin.manifest(), name)?;
|
||||
return Ok(Some(plugin));
|
||||
}
|
||||
if detect(name, bytes).is_some_and(super::formats::reads) {
|
||||
if detect(name, bytes).is_some_and(super::formats::reads) || super::TEXT_DOCUMENT_EXTS.contains(&extension(name).as_str()) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(import::for_extension(&extension(name)).into_iter().next())
|
||||
@@ -92,12 +93,12 @@ pub(crate) fn for_place(name: &str) -> Option<Arc<Plugin>> {
|
||||
}
|
||||
|
||||
/// Whether an importer may read a file of extension `ext` for `mode` when none is named: no
|
||||
/// built-in format reads the extension (for Place, as text, RTF or Word either) and an importer
|
||||
/// that reads for `mode` lists it.
|
||||
/// built-in format reads the extension (nor as text, RTF or Word) and an importer that reads for
|
||||
/// `mode` lists it.
|
||||
fn importer_reads(ext: &str, mode: Mode) -> bool {
|
||||
super::readable_format(ext).is_none()
|
||||
&& match mode {
|
||||
Mode::Import => !import::for_extension(ext).is_empty(),
|
||||
Mode::Import => !super::TEXT_DOCUMENT_EXTS.contains(&ext) && !import::for_extension(ext).is_empty(),
|
||||
Mode::Place => !super::place_exts().contains(&ext) && !import::placing(ext).is_empty(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -815,6 +815,14 @@ pub fn read_for_open(name: &str, bytes: &[u8], path: Option<String>, p: &Value,
|
||||
read_for_open_asking(name, bytes, path, p, update_links, low_res_proxy_eps, false)
|
||||
}
|
||||
|
||||
/// A text, RTF or Word file as a new document of its text, decoded with the `text` options of
|
||||
/// `document.open`'s params `p` ([`crate::cmd::place::text_document`]); any other file as
|
||||
/// [`load_with`] reads it with `opts`.
|
||||
fn text_or_load(name: &str, bytes: &[u8], p: &Value, opts: &LoadOptions) -> Result<Loaded> {
|
||||
let Some((doc, format, warnings)) = crate::cmd::place::text_document(name, bytes, p)? else { return load_with(name, bytes, opts) };
|
||||
Ok(Loaded { doc, format, warnings, restored: false, converted: false, preview_only: false, editing_data: false, native_pdf_compatible: None })
|
||||
}
|
||||
|
||||
/// [`read_for_open`]; with `ask` (the desktop app's File › Open), a document whose profile
|
||||
/// question ([`ReadFile::question`]) Edit › Color Settings asks, and that `p` gives no
|
||||
/// `profileChoice` for, stops after it is decoded: the app asks, and [`ReadFile::answer`] (or
|
||||
@@ -837,7 +845,7 @@ pub fn read_for_open_asking(
|
||||
Some(plugin) => (super::importer::load(name, bytes, &plugin, p)?, opts.color_mode),
|
||||
// The color mode `p` asks for converts the colors after the policies did, through the
|
||||
// profiles the document keeps.
|
||||
None => (load_with(name, bytes, &LoadOptions { color_mode: None, ..opts.clone() })?, opts.color_mode),
|
||||
None => (text_or_load(name, bytes, p, &LoadOptions { color_mode: None, ..opts.clone() })?, opts.color_mode),
|
||||
}
|
||||
};
|
||||
let mut file = ReadFile {
|
||||
|
||||
@@ -101,7 +101,7 @@ fn opens_every_readable_format() {
|
||||
let mime = &doc.images[&im.key].mime;
|
||||
assert_eq!(mime, if name.ends_with("tif") || name.ends_with("bmp") { "image/png" } else { format_for_name(name).unwrap().mime });
|
||||
}
|
||||
assert!(s.execute("document.open", &json!({"name": "x.txt", "dataBase64": "aGVsbG8="})).is_err());
|
||||
assert!(s.execute("document.open", &json!({"name": "x.xyz", "dataBase64": "aGVsbG8="})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -456,13 +456,14 @@ fn open_exts_cover_every_readable_format() {
|
||||
for e in open_exts() {
|
||||
assert!(readable_format(e).is_some(), ".{e} in open_exts() is no readable format");
|
||||
}
|
||||
assert!(readable_format("txt").is_none(), "text documents open through their own reader, not a graphic format");
|
||||
let filters: Vec<_> = open_filters().collect();
|
||||
assert_eq!(filters[0], ("All readable files", open_exts()));
|
||||
assert_eq!(filters[0], ("All readable files", &[open_exts(), TEXT_DOCUMENT_EXTS].concat()[..]));
|
||||
assert_eq!(
|
||||
filters.len(),
|
||||
13 + FORMATS.iter().filter(|f| formats::reads(f)).count(),
|
||||
"and swatch and graphic style libraries, libraries, flattener, PDF, print, perspective grid and export presets, composite \
|
||||
fonts, shortcut sets, scripts, plug-ins"
|
||||
16 + FORMATS.iter().filter(|f| formats::reads(f)).count(),
|
||||
"and text, RTF and Word, swatch and graphic style libraries, libraries, flattener, PDF, print, perspective grid and export \
|
||||
presets, composite fonts, shortcut sets, scripts, plug-ins"
|
||||
);
|
||||
let at = |label: &str| filters.iter().position(|f| f.0 == label).unwrap_or_else(|| panic!("File › Open has no {label} filter"));
|
||||
let styles: &[&str] = &[vectorcraft_doc::style_libs::STYLES_EXT];
|
||||
|
||||
@@ -193,6 +193,76 @@ fn load_sliced(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, given:
|
||||
Ok((l, slices))
|
||||
}
|
||||
|
||||
/// The story of the text, RTF or Word file `name` holding `bytes`, with its format and warnings; a
|
||||
/// text file is decoded with the `text` options of `p` (errors of command `cmd`). `None` when the
|
||||
/// file is none of these.
|
||||
fn text_story(name: &str, bytes: &[u8], p: &Value, cmd: &str) -> Result<Option<(text::Story, &'static Format, Vec<String>)>> {
|
||||
// An Affinity file is recognised by its signature, whatever its name says.
|
||||
if fileio::TEXT_EXTS.contains(&fileio::extension(name).as_str()) && !vectorcraft_affinity::is_affinity(bytes) {
|
||||
let text = text::import(bytes, text::TextOptions::parse(p, cmd)?, cmd)?;
|
||||
return Ok(Some((text::Story::plain(text), &text::FORMAT, vec![])));
|
||||
}
|
||||
// An RTF file is recognized by its content, whatever its name says (a .txt file is plain text).
|
||||
if rtf::is_rtf(bytes) {
|
||||
return Ok(Some((rtf::import(bytes, cmd)?, &rtf::FORMAT, vec![])));
|
||||
}
|
||||
// A Word document is recognized by its name or by its package's `word/document.xml`.
|
||||
if docx::is_docx(name, bytes) {
|
||||
return Ok(Some((docx::import(bytes, cmd)?, &docx::FORMAT, vec![])));
|
||||
}
|
||||
// A Word 97-2003 document is recognized by its name or by its compound file's WordDocument
|
||||
// stream.
|
||||
if doc::is_doc(name, bytes) {
|
||||
let (story, warnings) = doc::import(bytes, cmd)?;
|
||||
return Ok(Some((story, &doc::FORMAT, warnings)));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Whether File › Open reads the file `name` holding `bytes` as a text, RTF or Word document: its
|
||||
/// extension is one of [`fileio::TEXT_DOCUMENT_EXTS`], and it does not start with a PDF header
|
||||
/// (`%PDF-`, a digit, `.`, and a digit) or an Affinity signature (such a file opens as that format,
|
||||
/// whatever its name says).
|
||||
pub fn opens_as_text(name: &str, bytes: &[u8]) -> bool {
|
||||
let pdf = bytes.starts_with(b"%PDF-")
|
||||
&& bytes.get(5).is_some_and(u8::is_ascii_digit)
|
||||
&& bytes.get(6) == Some(&b'.')
|
||||
&& bytes.get(7).is_some_and(u8::is_ascii_digit);
|
||||
fileio::TEXT_DOCUMENT_EXTS.contains(&fileio::extension(name).as_str()) && !pdf && !vectorcraft_affinity::is_affinity(bytes)
|
||||
}
|
||||
|
||||
/// The size of the document File › Open makes of a text, RTF or Word file: a letter page.
|
||||
const TEXT_DOCUMENT: (f64, f64) = (612.0, 792.0);
|
||||
|
||||
/// File › Open of the text, RTF or Word file `name` holding `bytes` (`document.open`, whose params
|
||||
/// `p` give a text file's `text` options): a new letter-size document whose first layer holds the
|
||||
/// file's text as area type, in a frame 36 pt inside the artboard, as File › Place sets it, with
|
||||
/// the file's format and warnings. `None` when the file's extension is not one of
|
||||
/// [`fileio::TEXT_DOCUMENT_EXTS`], when it starts with a PDF or Affinity signature
|
||||
/// ([`opens_as_text`]), or when its content is none of these files.
|
||||
pub(crate) fn text_document(name: &str, bytes: &[u8], p: &Value) -> Result<Option<(Document, &'static Format, Vec<String>)>> {
|
||||
const C: &str = "document.open";
|
||||
if !opens_as_text(name, bytes) {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some((story, format, warnings)) = text_story(name, bytes, p, C)? else { return Ok(None) };
|
||||
// The RTF reader places what it reads of a file cut short; File › Open refuses it as damaged.
|
||||
if format.id == rtf::FORMAT.id && !rtf::is_complete(bytes) {
|
||||
return Err(bad(C, format!("`{}` is damaged: it ends inside an RTF group", fileio::file_name(name))));
|
||||
}
|
||||
if story.plain_text().trim().is_empty() {
|
||||
return Err(bad(C, format!("`{}` has no text to open", fileio::file_name(name))));
|
||||
}
|
||||
let mut d = Document::new(TEXT_DOCUMENT.0, TEXT_DOCUMENT.1);
|
||||
let frame = text_frame(d.artboards.first().map(|a| a.rect));
|
||||
let node = Node::new(d.alloc_id(), NodeKind::Text(Box::new(text::area_text(story, frame, &d.setup))));
|
||||
let node = transformed(node, Affine::translate(frame.origin().to_vec2()));
|
||||
let layer = d.layers.first().map(|l| l.id);
|
||||
d.insert(layer, usize::MAX, node)?;
|
||||
d.title = fileio::file_name(name);
|
||||
Ok(Some((d, format, warnings)))
|
||||
}
|
||||
|
||||
/// The file `p` names, read into placeable art; a DXF drawing's Fit to Artboard fills `board`
|
||||
/// (unless the params name their own box). A PDF/.ai page or an EPS file read from a path is placed
|
||||
/// linked with Link when `link_pdf` (false for the queries, which read it embedded). A PSD or PSB
|
||||
@@ -205,39 +275,11 @@ fn load_into(p: &Value, cmd: &str, board: Option<Rect>, link_pdf: bool, given: O
|
||||
if let Some(plugin) = fileio::importer::named_for_place(src.name, p, cmd)? {
|
||||
return plugin_art(name, src.name, &src.bytes, &plugin, p, cmd);
|
||||
}
|
||||
// An Affinity file is recognised by its signature, whatever its name says.
|
||||
if fileio::TEXT_EXTS.contains(&fileio::extension(src.name).as_str()) && !vectorcraft_affinity::is_affinity(&src.bytes) {
|
||||
let text = text::import(&src.bytes, text::TextOptions::parse(p, cmd)?, cmd)?;
|
||||
if text.trim().is_empty() {
|
||||
return Err(bad(cmd, format!("`{name}` has no text to place")));
|
||||
}
|
||||
let art = Art::Text(text::Story::plain(text));
|
||||
return Ok(Loaded { name, format: &text::FORMAT, art, natural: TEXT_FRAME, warnings: vec![], link: None, board: None });
|
||||
}
|
||||
// An RTF file is recognized by its content, whatever its name says (a .txt file is plain text).
|
||||
if rtf::is_rtf(&src.bytes) {
|
||||
let story = rtf::import(&src.bytes, cmd)?;
|
||||
if let Some((story, format, warnings)) = text_story(src.name, &src.bytes, p, cmd)? {
|
||||
if story.plain_text().trim().is_empty() {
|
||||
return Err(bad(cmd, format!("`{name}` has no text to place")));
|
||||
}
|
||||
return Ok(Loaded { name, format: &rtf::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings: vec![], link: None, board: None });
|
||||
}
|
||||
// A Word document is recognized by its name or by its package's `word/document.xml`.
|
||||
if docx::is_docx(src.name, &src.bytes) {
|
||||
let story = docx::import(&src.bytes, cmd)?;
|
||||
if story.plain_text().trim().is_empty() {
|
||||
return Err(bad(cmd, format!("`{name}` has no text to place")));
|
||||
}
|
||||
return Ok(Loaded { name, format: &docx::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings: vec![], link: None, board: None });
|
||||
}
|
||||
// A Word 97-2003 document is recognized by its name or by its compound file's WordDocument
|
||||
// stream.
|
||||
if doc::is_doc(src.name, &src.bytes) {
|
||||
let (story, warnings) = doc::import(&src.bytes, cmd)?;
|
||||
if story.plain_text().trim().is_empty() {
|
||||
return Err(bad(cmd, format!("`{name}` has no text to place")));
|
||||
}
|
||||
return Ok(Loaded { name, format: &doc::FORMAT, art: Art::Text(story), natural: TEXT_FRAME, warnings, link: None, board: None });
|
||||
return Ok(Loaded { name, format, art: Art::Text(story), natural: TEXT_FRAME, warnings, link: None, board: None });
|
||||
}
|
||||
let format = fileio::detect(src.name, &src.bytes);
|
||||
if format.is_none_or(|f| !fileio::reads(f))
|
||||
|
||||
@@ -62,6 +62,41 @@ pub(super) fn is_rtf(bytes: &[u8]) -> bool {
|
||||
bytes.get(start..).is_some_and(|b| b.starts_with(b"{\\rtf"))
|
||||
}
|
||||
|
||||
/// Does the RTF file `bytes` close every group it opens? A control symbol's escaped brace (`\{`,
|
||||
/// `\}`), an escaped backslash (`\\`) and the bytes of `\binN` binary data open and close nothing.
|
||||
/// A file that ends inside a group was cut short; bytes after the outermost group's closing brace
|
||||
/// are not checked.
|
||||
pub(super) fn is_complete(bytes: &[u8]) -> bool {
|
||||
let mut depth = 0usize;
|
||||
let mut i = 0;
|
||||
while let Some(&b) = bytes.get(i) {
|
||||
match b {
|
||||
b'\\' => {
|
||||
let (word, n, end) = control_word(bytes, i + 1);
|
||||
if word != "bin" {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
// The binary data's length as `import` reads it; data that runs past the end of the
|
||||
// file leaves the file incomplete.
|
||||
let len = usize::try_from(n.unwrap_or(0)).unwrap_or(0);
|
||||
match end.checked_add(len) {
|
||||
Some(next) if next <= bytes.len() => i = next,
|
||||
_ => return false,
|
||||
}
|
||||
continue;
|
||||
}
|
||||
b'{' => depth += 1,
|
||||
// The document ends where its outermost group closes; bytes after it are not read.
|
||||
b'}' if depth <= 1 => return true,
|
||||
b'}' => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// The text of an RTF file's `bytes` with its character and paragraph formatting.
|
||||
pub(super) fn import(bytes: &[u8], cmd: &str) -> Result<Story> {
|
||||
if bytes.len() > text::MAX_TEXT {
|
||||
@@ -717,6 +752,12 @@ mod tests {
|
||||
let deep = format!("{{\\rtf1 {}x{}}}", "{".repeat(5000), "}".repeat(5000));
|
||||
assert_eq!(text_of(&read(&deep)), "x");
|
||||
assert_eq!(text_of(&read(r"{\rtf1 unclosed {\b group")), "unclosed group");
|
||||
assert!(!is_complete(br"{\rtf1 unclosed {\b group"), "cut short");
|
||||
assert!(is_complete(br"{\rtf1 a \{ b \} c \\}"), "escaped braces");
|
||||
assert!(is_complete(b"{\\rtf1 done}\r\n{ trailing bytes"), "bytes after the document's group");
|
||||
assert!(is_complete(b"{\\rtf1 {\\*\\blipuid x}{\\pict\\bin3 {{{}}"), "binary data");
|
||||
assert!(!is_complete(b"{\\rtf1 {\\pict\\bin9 }}"), "binary data past the end of the file");
|
||||
assert!(!is_complete(b"{\\rtf1 {\\pict\\bin99999999999 }}"), "an overflowing binary length");
|
||||
assert!(import(b"{\\rt", "file.place").is_err(), "not RTF");
|
||||
assert!(import(b"Plain words", "file.place").is_err(), "not RTF");
|
||||
}
|
||||
|
||||
@@ -1162,8 +1162,115 @@ fn place_reads_what_open_reads_and_text_files() {
|
||||
let word: (&str, &[&str]) = ("Word", &["docx", "doc"]);
|
||||
assert_eq!((filters.first(), filters.last()), (Some(&("All placeable files", cmd::fileio::place_exts())), Some(&word)));
|
||||
assert_eq!(filters.get(filters.len() - 3..), Some(&[("Text", TEXT_EXTS), ("RTF", RTF_EXTS), word][..]));
|
||||
assert!(
|
||||
!cmd::fileio::open_filters().any(|(_, exts)| ["txt", "rtf", "docx", "doc"].iter().any(|e| exts.contains(e))),
|
||||
"Open doesn't read text, RTF or Word files"
|
||||
// File › Open lists them in "All readable files", after the formats it reads, and in filters
|
||||
// of their own after the format filters; the documents File › Open reads (Batch's source files,
|
||||
// `openExtensions`) leave them out.
|
||||
let open: Vec<_> = cmd::fileio::open_filters().collect();
|
||||
assert_eq!(open[0].0, "All readable files");
|
||||
assert!(open[0].1.starts_with(cmd::fileio::place_exts()), "{:?}", open[0].1);
|
||||
let text = open.iter().position(|f| f.0 == "Text").expect("File › Open has a Text filter");
|
||||
assert_eq!(open.get(text..text + 3), Some(&[("Text", TEXT_EXTS), ("RTF", RTF_EXTS), word][..]));
|
||||
assert_eq!(
|
||||
open.get(text - 1).map(|f| f.0),
|
||||
cmd::fileio::FORMATS.iter().rfind(|f| cmd::fileio::reads(f)).map(|f| f.label),
|
||||
"after the format filters"
|
||||
);
|
||||
assert!(!cmd::fileio::open_extensions().iter().any(|e| ["txt", "rtf", "docx", "doc"].contains(e)));
|
||||
}
|
||||
|
||||
fn open_text(s: &mut Session, name: &str, bytes: &[u8], extra: Value) -> crate::Result<Value> {
|
||||
let mut p = json!({"name": name, "dataBase64": vectorcraft_format::base64_encode(bytes)});
|
||||
if let (Some(o), Value::Object(e)) = (p.as_object_mut(), extra) {
|
||||
o.extend(e);
|
||||
}
|
||||
s.execute("document.open", &p)
|
||||
}
|
||||
|
||||
/// The opened document's one object: its text and frame bounds.
|
||||
fn opened_text(s: &Session) -> (String, Rect) {
|
||||
let st = s.doc().unwrap();
|
||||
let layer = &st.doc.layers[0];
|
||||
let [n] = layer.children().map_or(&[][..], Vec::as_slice) else { panic!("one object on the first layer: {:?}", layer.children()) };
|
||||
let NodeKind::Text(t) = &n.kind else { panic!("not type: {:?}", n.kind) };
|
||||
assert!(matches!(t.kind, TextKind::Area { .. }), "area type");
|
||||
(t.plain_text(), n.geometric_bounds().unwrap())
|
||||
}
|
||||
|
||||
/// File › Open of a text file makes a new letter-size document whose text, read with the Text
|
||||
/// Import Options given, is area type 36 pt inside the artboard; it has no path, so Save asks for a
|
||||
/// name, and nothing to undo.
|
||||
#[test]
|
||||
fn open_makes_a_new_document_of_a_text_file_with_its_options() {
|
||||
let mut s = Session::new();
|
||||
let text = b"Caf\xE9 au lait,\r\nplease.\r\n\r\nThanks";
|
||||
let opts = json!({"text": {"characterSet": "cyrillic", "removeLineReturns": true, "removeParagraphReturns": true}});
|
||||
let r = open_text(&mut s, "order.txt", text, opts).unwrap();
|
||||
assert_eq!((r["format"].as_str(), r["title"].as_str()), (Some("txt"), Some("order.txt")));
|
||||
let (body, frame) = opened_text(&s);
|
||||
assert_eq!(body, "Cafй au lait, please.\nThanks", "decoded as Cyrillic, lines joined, blank lines dropped");
|
||||
assert!(close(frame, Rect::new(36.0, 36.0, 576.0, 756.0)), "a letter page less a 36 pt margin: {frame:?}");
|
||||
let st = s.doc().unwrap();
|
||||
assert_eq!(st.doc.artboards.iter().map(|a| a.rect).collect::<Vec<_>>(), [Rect::new(0.0, 0.0, 612.0, 792.0)]);
|
||||
assert_eq!((st.path.as_deref(), st.history.undo.len()), (None, 0));
|
||||
// Without options each line is a paragraph, read as UTF-8.
|
||||
open_text(&mut s, "order.txt", "Café\r\nau lait".as_bytes(), json!({})).unwrap();
|
||||
assert_eq!(opened_text(&s).0, "Café\nau lait");
|
||||
assert_eq!(s.documents().len(), 2, "each open is a document of its own");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_makes_a_new_document_of_an_rtf_or_word_file() {
|
||||
let mut s = Session::new();
|
||||
let r = open_text(&mut s, "letter.rtf", LETTER_RTF.as_bytes(), json!({})).unwrap();
|
||||
assert_eq!(r["format"], "rtf");
|
||||
assert_eq!(opened_text(&s).0, "Plain and bold words2.\nCentered café");
|
||||
let body = r#"<w:p><w:r><w:t>Minutes</w:t></w:r></w:p><w:p><w:r><w:rPr><w:b/></w:rPr><w:t>Agreed</w:t></w:r></w:p>"#;
|
||||
let r = open_text(&mut s, "minutes.docx", &docx(body, STYLES), json!({})).unwrap();
|
||||
assert_eq!(r["format"], "docx");
|
||||
assert_eq!(opened_text(&s).0, "Minutes\nAgreed");
|
||||
let doc = Word97 { pieces: vec![("Old memo\r", true)], ..Word97::default() }.build();
|
||||
let r = open_text(&mut s, "memo.doc", &doc, json!({})).unwrap();
|
||||
assert_eq!(r["format"], "doc");
|
||||
assert_eq!(opened_text(&s).0, "Old memo");
|
||||
}
|
||||
|
||||
/// A file without text, bad Text Import Options and a damaged file open nothing.
|
||||
#[test]
|
||||
fn text_files_that_cant_be_read_open_no_document() {
|
||||
let mut s = Session::new();
|
||||
let e = open_text(&mut s, "blank.txt", b" \r\n\t\r\n", json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("`blank.txt` has no text to open"), "{e}");
|
||||
let e = open_text(&mut s, "notes.txt", b"words", json!({"text": {"characterSet": "klingon"}})).unwrap_err().to_string();
|
||||
assert!(e.contains("text.characterSet `klingon`"), "{e}");
|
||||
assert!(open_text(&mut s, "broken.docx", b"PK\x03\x04 not a package", json!({})).is_err());
|
||||
assert!(open_text(&mut s, "plain.rtf", b"Plain words, not RTF", json!({})).is_err(), "an .rtf file that isn't RTF");
|
||||
let e = open_text(&mut s, "broken.rtf", br"{\rtf1 unclosed {\b group", json!({})).unwrap_err().to_string();
|
||||
assert!(e.contains("`broken.rtf` is damaged"), "a truncated RTF file: {e}");
|
||||
assert_eq!(s.documents().len(), 0);
|
||||
open_text(&mut s, "escaped.rtf", br"{\rtf1 a \{ brace \} and \\ slash}", json!({})).unwrap();
|
||||
assert_eq!(s.documents().len(), 1, "escaped braces don't count as groups");
|
||||
}
|
||||
|
||||
/// A file whose content is a format File › Open reads (a PDF file) opens as that format even when
|
||||
/// it is named `.txt`, as it did before text files opened.
|
||||
#[test]
|
||||
fn a_pdf_named_txt_opens_as_a_pdf() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 100, "height": 80})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 30})).unwrap();
|
||||
let pdf = s.execute("document.exportPdf", &json!({})).unwrap();
|
||||
let pdf = vectorcraft_format::base64_decode(pdf["dataBase64"].as_str().expect("dataBase64")).unwrap();
|
||||
assert!(pdf.starts_with(b"%PDF"));
|
||||
let r = open_text(&mut s, "drawing.txt", &pdf, json!({})).unwrap();
|
||||
assert_eq!(r["format"], "pdf", "{r}");
|
||||
let st = s.doc().unwrap();
|
||||
assert!(!st.doc.layers.iter().flat_map(|l| l.children().into_iter().flatten()).any(|n| matches!(n.kind, NodeKind::Text(_))), "no text");
|
||||
assert!(!cmd::place::opens_as_text("drawing.txt", &pdf), "File › Open asks no Text Import Options for it");
|
||||
// Text that only looks like the start of a drawing is still text.
|
||||
open_text(&mut s, "notes.txt", b"<svg is the opening tag", json!({})).unwrap();
|
||||
assert_eq!(opened_text(&s).0, "<svg is the opening tag");
|
||||
open_text(&mut s, "notes.txt", b"%PDF is the marker to look for", json!({})).unwrap();
|
||||
assert_eq!(opened_text(&s).0, "%PDF is the marker to look for");
|
||||
open_text(&mut s, "notes.txt", b"%PDF-1 is the prefix to look for", json!({})).unwrap();
|
||||
assert_eq!(opened_text(&s).0, "%PDF-1 is the prefix to look for");
|
||||
}
|
||||
@@ -264,6 +264,21 @@ fn file_open_lists_only_the_extensions_it_opens_with_an_importer() {
|
||||
s.execute("plugin.remove", &json!({"id": "test.claimedonly"})).unwrap();
|
||||
}
|
||||
|
||||
/// A text file opens as a document of its text even when an importer lists `.txt`: the importer
|
||||
/// reads it only when `importer` names it, and File › Open's filter for it leaves `.txt` out.
|
||||
#[test]
|
||||
fn text_files_open_as_text_unless_an_importer_is_named() {
|
||||
let mut s = Session::new();
|
||||
install(&mut s, &tpl::returning(&tpl::importer("test.textclaim", r#"["txt","tcx"]"#, "{}"), RECT));
|
||||
assert_eq!(open(&mut s, "notes.txt", b"words", json!({})).unwrap()["format"], "txt");
|
||||
assert_eq!(open(&mut s, "notes.txt", b"words", json!({"importer": "plugin.test.textclaim"})).unwrap()["format"], "plugin.test.textclaim");
|
||||
let filters: Vec<_> = fileio::open_filters().collect();
|
||||
assert!(filters.contains(&("Test test.textclaim", &["tcx"][..])), "{filters:?}");
|
||||
assert_eq!(filters[0].1.iter().filter(|e| **e == "txt").count(), 1, "All readable files lists .txt once");
|
||||
assert!(!fileio::open_extensions().contains(&"txt"));
|
||||
s.execute("plugin.remove", &json!({"id": "test.textclaim"})).unwrap();
|
||||
}
|
||||
|
||||
/// Several importers list one extension: the one whose id sorts first opens the file, and
|
||||
/// `importer` picks another (by its format id or its id).
|
||||
#[test]
|
||||
|
||||
@@ -364,7 +364,7 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
"open_file",
|
||||
"Open file",
|
||||
&format!(
|
||||
"Open a file as a new, active document: .{} (see run_command document.formats). Templates (.ait, native templates) open as a new untitled document. The reply's `warnings` say what didn't come in as it was (an EPS shown as its preview image says why its PostScript couldn't be read). A file of an extension no built-in format reads opens with the installed importer plug-in that lists it; `importer` names the importer to use (File › Open With), also for an extension a built-in format reads, and `params` gives that importer's parameters.",
|
||||
"Open a file as a new, active document: .{} (see run_command document.formats). Templates (.ait, native templates) open as a new untitled document. A text, RTF or Word file (.txt, .rtf, .docx, .doc) opens as a new letter-size document of its text as area type. A file with one of those extensions that starts with a PDF header or an Affinity signature opens as that format instead. The reply's `warnings` say what didn't come in as it was (an EPS shown as its preview image says why its PostScript couldn't be read). A file of an extension no built-in format reads opens with the installed importer plug-in that lists it; `importer` names the importer to use (File › Open With), also for an extension a built-in format reads, and `params` gives that importer's parameters.",
|
||||
open_exts().join(", .")
|
||||
),
|
||||
obj(
|
||||
|
||||
@@ -47,7 +47,7 @@ pub use effects::stroke::width_outline;
|
||||
pub use fx::pinned_appearance_for_geometry_edit;
|
||||
pub use images::{IMAGE_CACHE_MAX, image_cache_bytes, installed_memory, newly_undecodable, set_image_cache_budget};
|
||||
pub use live::expand_live;
|
||||
pub use pattern::render_pattern_swatch;
|
||||
pub use pattern::{render_pattern_swatch, render_pattern_swatch_words};
|
||||
pub use vectorcraft_effects as effects;
|
||||
pub use vello_cpu;
|
||||
|
||||
|
||||
@@ -243,11 +243,11 @@ pub fn supersample_factor(w: u32, h: u32) -> Option<u32> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Average each `k`×`k` block of `src` (`w`×`h` pixels of 4 premultiplied bytes) into one pixel.
|
||||
pub(crate) fn downsample(src: &[u8], w: usize, h: usize, k: usize) -> Vec<u8> {
|
||||
let (ow, oh) = (w / k.max(1), h / k.max(1));
|
||||
/// Average each `k`×`k` block of `src` (pixels of 4 premultiplied bytes in rows `w` wide) into one
|
||||
/// pixel of `out`, whose rows are `w` / `k` pixels wide.
|
||||
pub(crate) fn downsample(src: &[u8], w: usize, k: usize, out: &mut [u8]) {
|
||||
let ow = w / k.max(1);
|
||||
let n = (k * k).max(1) as u32;
|
||||
let mut out = vec![0u8; ow * oh * 4];
|
||||
for (o, px) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() {
|
||||
let (ox, oy) = (o % ow.max(1), o / ow.max(1));
|
||||
let mut acc = [0u32; 4];
|
||||
@@ -263,7 +263,6 @@ pub(crate) fn downsample(src: &[u8], w: usize, h: usize, k: usize) -> Vec<u8> {
|
||||
*d = ((a + n / 2) / n).min(255) as u8;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// For each of `to` pixels spread over `from` (both above 0), the `from` pixels under it and the
|
||||
|
||||
@@ -28,6 +28,7 @@ use vello_cpu::{Pixmap, RenderContext};
|
||||
|
||||
use crate::ink::Ink;
|
||||
use crate::lru::{self, FrameCache};
|
||||
use crate::renderer::FramePixels;
|
||||
use crate::{Frame, RenderOptions, Rendered, Renderer};
|
||||
|
||||
/// Largest super-tile raster side (pixels).
|
||||
@@ -170,15 +171,21 @@ pub(crate) fn raster_scale(s: f64, period: (f64, f64)) -> f64 {
|
||||
|
||||
/// Rasterize `region` (pattern space) of the infinite tiling into a `w`×`h` pixmap, colours as
|
||||
/// `ink` paints them.
|
||||
fn rasterize(
|
||||
fn rasterize(r: &mut Renderer, doc: &Document, def: &PatternDef, region: Rect, size: (u16, u16), ink: Ink, images: (bool, bool)) -> (Pixmap, bool) {
|
||||
rasterize_as(r, doc, def, (region, size), ink, images, |r, ctx| r.finish(ctx, r.raster))
|
||||
}
|
||||
|
||||
/// [`rasterize`] of `region` into `size` pixels, with the pixels taken from the context by
|
||||
/// `finish`.
|
||||
fn rasterize_as<T>(
|
||||
r: &mut Renderer,
|
||||
doc: &Document,
|
||||
def: &PatternDef,
|
||||
region: Rect,
|
||||
size: (u16, u16),
|
||||
(region, size): (Rect, (u16, u16)),
|
||||
ink: Ink,
|
||||
(mark_undecoded_images, smooth_images): (bool, bool),
|
||||
) -> (Pixmap, bool) {
|
||||
finish: impl FnOnce(&mut Renderer, &mut RenderContext) -> T,
|
||||
) -> (T, bool) {
|
||||
let (w, h) = (size.0.max(1), size.1.max(1));
|
||||
let mut ctx = crate::single_threaded_context(w, h);
|
||||
let view = Affine::scale_non_uniform(w as f64 / region.width().max(1e-9), h as f64 / region.height().max(1e-9))
|
||||
@@ -213,7 +220,7 @@ fn rasterize(
|
||||
r.draw_arc(&mut ctx, &frame, a);
|
||||
}
|
||||
}
|
||||
(r.finish(&mut ctx, r.raster), r.image_left_out.take().unwrap_or(false) || images_left_out() > pattern_images_left_out)
|
||||
(finish(r, &mut ctx), r.image_left_out.take().unwrap_or(false) || images_left_out() > pattern_images_left_out)
|
||||
}
|
||||
|
||||
/// Run `f` with the shared off-screen renderer (None when nested too deep: a pattern whose art
|
||||
@@ -334,13 +341,23 @@ pub(crate) fn set_pattern_paint(ctx: &mut RenderContext, name: &str, xf: Affine,
|
||||
|
||||
/// A swatch thumbnail of pattern `name`: the tiling around the tile, fitted into `size`².
|
||||
pub fn render_pattern_swatch(doc: &Document, name: &str, size: u32) -> Option<Rendered> {
|
||||
pattern_swatch(doc, name, size)
|
||||
}
|
||||
|
||||
/// [`render_pattern_swatch`] with the pixels in words of four bytes, as
|
||||
/// [`Renderer::render_words`] returns them.
|
||||
pub fn render_pattern_swatch_words(doc: &Document, name: &str, size: u32) -> Option<Rendered<Vec<u32>>> {
|
||||
pattern_swatch(doc, name, size)
|
||||
}
|
||||
|
||||
fn pattern_swatch<P: FramePixels>(doc: &Document, name: &str, size: u32) -> Option<Rendered<P>> {
|
||||
let def = doc.pattern(name)?;
|
||||
let (w, h) = (def.width(), def.height());
|
||||
let side = w.max(h);
|
||||
let region = Rect::from_center_size((w / 2.0, h / 2.0), (side, side));
|
||||
let px = size.clamp(1, 1024) as u16;
|
||||
let (pm, _) = with_tile_renderer(|r| rasterize(r, doc, def, region, (px, px), Ink::Display, (false, true)))?;
|
||||
Some(Rendered { width: px as u32, height: px as u32, pixels: crate::group::into_bytes(pm) })
|
||||
let (pixels, _) = with_tile_renderer(|r| rasterize_as(r, doc, def, (region, (px, px)), Ink::Display, (false, true), P::finish))?;
|
||||
Some(Rendered { width: px as u32, height: px as u32, pixels })
|
||||
}
|
||||
|
||||
impl Renderer {
|
||||
|
||||
@@ -189,9 +189,11 @@ impl Renderer {
|
||||
let hairline = std::mem::replace(&mut self.hairline, f64::from(k));
|
||||
let big: Rendered = self.render_as(doc, w * k, h * k, Affine::scale(f64::from(k)) * view, &hard, inks, k, patch);
|
||||
self.hairline = hairline;
|
||||
let pixels = downsample(&big.pixels, big.width as usize, big.height as usize, k as usize);
|
||||
let mut pixels = P::blank(w as usize * h as usize);
|
||||
downsample(&big.pixels, big.width as usize, k as usize, pixels.bytes_mut());
|
||||
#[cfg(test)]
|
||||
group::FINISHED.with(|p| p.set(pixels.bytes_mut().as_ptr() as usize));
|
||||
drop(big);
|
||||
let pixels = P::from_bytes(pixels);
|
||||
self.stats.micros = now().saturating_sub(start);
|
||||
return Rendered { width: w, height: h, pixels };
|
||||
}
|
||||
@@ -455,6 +457,12 @@ impl Renderer {
|
||||
self.region(doc, region, scale, opts)
|
||||
}
|
||||
|
||||
/// [`Self::render_region_with`] with the pixels in words of four bytes, as
|
||||
/// [`Self::render_words`] returns them.
|
||||
pub fn render_region_with_words(&mut self, doc: &Document, region: Rect, scale: f64, opts: &RenderOptions) -> Rendered<Vec<u32>> {
|
||||
self.region(doc, region, scale, opts)
|
||||
}
|
||||
|
||||
fn region<P: FramePixels>(&mut self, doc: &Document, region: Rect, scale: f64, opts: &RenderOptions) -> Rendered<P> {
|
||||
let (w, h) = region_pixels(region, scale);
|
||||
let view = Affine::scale(scale) * Affine::translate((-region.x0, -region.y0));
|
||||
@@ -485,6 +493,16 @@ impl Renderer {
|
||||
|
||||
/// [`Self::render_node`] with `opts` (e.g. [`RenderOptions::mark_undecoded_images`]).
|
||||
pub fn render_node_with(&mut self, doc: &Document, n: &Arc<Node>, w: u16, h: u16, view: Affine, opts: &RenderOptions) -> Option<Rendered> {
|
||||
self.node(doc, n, w, h, view, opts)
|
||||
}
|
||||
|
||||
/// [`Self::render_node`] with the pixels in words of four bytes, as [`Self::render_words`]
|
||||
/// returns them.
|
||||
pub fn render_node_words(&mut self, doc: &Document, n: &Arc<Node>, w: u16, h: u16, view: Affine) -> Option<Rendered<Vec<u32>>> {
|
||||
self.node(doc, n, w, h, view, &RenderOptions::default())
|
||||
}
|
||||
|
||||
fn node<P: FramePixels>(&mut self, doc: &Document, n: &Arc<Node>, w: u16, h: u16, view: Affine, opts: &RenderOptions) -> Option<Rendered<P>> {
|
||||
let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts);
|
||||
self.check_plugins(doc);
|
||||
self.check_symbols(doc);
|
||||
@@ -499,7 +517,7 @@ impl Renderer {
|
||||
/// averaged down, and [`RenderOptions::precise`] picks the quality render mode, as in a page
|
||||
/// render ([`Self::render_as`], [`Self::draw_frame`]). `cell` is as in [`Self::render_as`].
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn node_pixels(
|
||||
fn node_pixels<P: FramePixels>(
|
||||
&mut self,
|
||||
doc: &Document,
|
||||
n: &Arc<Node>,
|
||||
@@ -509,7 +527,7 @@ impl Renderer {
|
||||
opts: &RenderOptions,
|
||||
forced: bool,
|
||||
cell: u32,
|
||||
) -> Vec<u8> {
|
||||
) -> P {
|
||||
if opts.supersample
|
||||
&& opts.anti_alias == AntiAlias::Art
|
||||
&& let Some(k) = supersample_factor(u32::from(w), u32::from(h))
|
||||
@@ -518,9 +536,13 @@ impl Renderer {
|
||||
// `supersample_factor` keeps each side within MAX_CONTEXT_SIDE, so it fits in a u16.
|
||||
let (bw, bh) = (u32::from(w) * k, u32::from(h) * k);
|
||||
let hairline = std::mem::replace(&mut self.hairline, f64::from(k));
|
||||
let big = self.node_pixels(doc, n, (bw as u16, bh as u16), Affine::scale(f64::from(k)) * view, visible, &hard, forced, k);
|
||||
let big: Vec<u8> = self.node_pixels(doc, n, (bw as u16, bh as u16), Affine::scale(f64::from(k)) * view, visible, &hard, forced, k);
|
||||
self.hairline = hairline;
|
||||
return downsample(&big, bw as usize, bh as usize, k as usize);
|
||||
let mut pixels = P::blank(usize::from(w) * usize::from(h));
|
||||
downsample(&big, bw as usize, k as usize, pixels.bytes_mut());
|
||||
#[cfg(test)]
|
||||
group::FINISHED.with(|p| p.set(pixels.bytes_mut().as_ptr() as usize));
|
||||
return pixels;
|
||||
}
|
||||
let px = 1.0 / view.determinant().abs().sqrt().max(1e-12);
|
||||
let mut ctx = single_threaded_context(w, h);
|
||||
@@ -538,10 +560,10 @@ impl Renderer {
|
||||
} else {
|
||||
self.draw_arc(&mut ctx, &frame, n);
|
||||
}
|
||||
let pm = self.finish(&mut ctx, self.raster);
|
||||
let pixels = P::finish(self, &mut ctx);
|
||||
self.end_frame();
|
||||
self.raster = raster;
|
||||
group::into_bytes(pm)
|
||||
pixels
|
||||
}
|
||||
|
||||
/// Render any node (also one outside the tree, e.g. opacity-mask art) fitted into
|
||||
@@ -565,6 +587,42 @@ impl Renderer {
|
||||
background: Option<[u8; 4]>,
|
||||
opts: &RenderOptions,
|
||||
) -> Option<Rendered> {
|
||||
self.node_thumbnail(doc, n, size, background, opts)
|
||||
}
|
||||
|
||||
/// [`Self::render_node_thumbnail`] with the pixels in words of four bytes, as
|
||||
/// [`Self::render_words`] returns them.
|
||||
pub fn render_node_thumbnail_words(&mut self, doc: &Document, n: &Node, size: u32, background: Option<[u8; 4]>) -> Option<Rendered<Vec<u32>>> {
|
||||
self.node_thumbnail(doc, n, size, background, &RenderOptions::default())
|
||||
}
|
||||
|
||||
/// [`Self::render_thumbnail`] with the pixels in words of four bytes, as
|
||||
/// [`Self::render_words`] returns them.
|
||||
pub fn render_thumbnail_words(&mut self, doc: &Document, id: NodeId, size: u32) -> Option<Rendered<Vec<u32>>> {
|
||||
self.node_thumbnail(doc, doc.node(id)?, size, None, &RenderOptions::default())
|
||||
}
|
||||
|
||||
/// [`Self::render_node_thumbnail_with`] with the pixels in words of four bytes, as
|
||||
/// [`Self::render_words`] returns them.
|
||||
pub fn render_node_thumbnail_words_with(
|
||||
&mut self,
|
||||
doc: &Document,
|
||||
n: &Node,
|
||||
size: u32,
|
||||
background: Option<[u8; 4]>,
|
||||
opts: &RenderOptions,
|
||||
) -> Option<Rendered<Vec<u32>>> {
|
||||
self.node_thumbnail(doc, n, size, background, opts)
|
||||
}
|
||||
|
||||
fn node_thumbnail<P: FramePixels>(
|
||||
&mut self,
|
||||
doc: &Document,
|
||||
n: &Node,
|
||||
size: u32,
|
||||
background: Option<[u8; 4]>,
|
||||
opts: &RenderOptions,
|
||||
) -> Option<Rendered<P>> {
|
||||
let _lent = vectorcraft_text::FontDb::global().lend_composite_fonts(&doc.composite_fonts);
|
||||
self.check_plugins(doc);
|
||||
self.check_symbols(doc);
|
||||
@@ -573,9 +631,9 @@ impl Renderer {
|
||||
// A 1-pixel margin on each side, unless the thumbnail is too small to keep one.
|
||||
let s = (w as f64 - 2.0).max(1.0) / b.width().max(b.height()).max(1e-6);
|
||||
let view = Affine::translate((w as f64 / 2.0, w as f64 / 2.0)) * Affine::scale(s) * Affine::translate(-b.center().to_vec2());
|
||||
let mut pixels = self.node_pixels(doc, &Arc::new(n.clone()), (w, w), view, b.inflate(1.0, 1.0), opts, true, 1);
|
||||
let mut pixels: P = self.node_pixels(doc, &Arc::new(n.clone()), (w, w), view, b.inflate(1.0, 1.0), opts, true, 1);
|
||||
if let Some(bg) = background {
|
||||
over_background(&mut pixels, bg);
|
||||
over_background(pixels.bytes_mut(), bg);
|
||||
}
|
||||
Some(Rendered { width: w as u32, height: w as u32, pixels })
|
||||
}
|
||||
@@ -605,6 +663,8 @@ pub(crate) trait FramePixels: Sized {
|
||||
fn finish(r: &mut Renderer, ctx: &mut RenderContext) -> Self;
|
||||
/// The pixels in `bytes` (four a pixel).
|
||||
fn from_bytes(bytes: Vec<u8>) -> Self;
|
||||
/// `pixels` transparent pixels, to be written through [`Self::bytes_mut`].
|
||||
fn blank(pixels: usize) -> Self;
|
||||
/// The pixels as bytes, four a pixel.
|
||||
fn bytes_mut(&mut self) -> &mut [u8];
|
||||
}
|
||||
@@ -618,6 +678,10 @@ impl FramePixels for Vec<u8> {
|
||||
bytes
|
||||
}
|
||||
|
||||
fn blank(pixels: usize) -> Self {
|
||||
vec![0; pixels * 4]
|
||||
}
|
||||
|
||||
fn bytes_mut(&mut self) -> &mut [u8] {
|
||||
self
|
||||
}
|
||||
@@ -646,6 +710,10 @@ impl FramePixels for Vec<u32> {
|
||||
bytes.as_chunks::<4>().0.iter().map(|p| u32::from_ne_bytes(*p)).collect()
|
||||
}
|
||||
|
||||
fn blank(pixels: usize) -> Self {
|
||||
vec![0; pixels]
|
||||
}
|
||||
|
||||
fn bytes_mut(&mut self) -> &mut [u8] {
|
||||
bytemuck::cast_slice_mut(self)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
//! A frame rendered in words ([`Renderer::render_words`]): the bytes [`Renderer::render`] returns,
|
||||
//! rendered straight into the words.
|
||||
//! rendered straight into the words. Node renders, thumbnails, regions with options and pattern
|
||||
//! swatches render in words the same way.
|
||||
|
||||
use std::cell::Cell;
|
||||
|
||||
use vectorcraft_color::{BlendMode as Blend, Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, ColorMode, Node};
|
||||
use vectorcraft_doc::pattern::pattern_paint;
|
||||
use vectorcraft_doc::{Appearance, ColorMode, Node, PatternDef};
|
||||
use vectorcraft_geom::shapes;
|
||||
|
||||
use crate::group::FINISHED;
|
||||
@@ -95,3 +97,91 @@ fn a_region_in_words_holds_the_bytes_of_the_region_in_bytes() {
|
||||
let words = Renderer::new().render_region_words(&plain, region, 1.3, false);
|
||||
assert_eq!(words.pixels.as_ptr() as usize, finished(), "a region's words are returned without a copy");
|
||||
}
|
||||
|
||||
/// The page of [`page`] with [`square`], [`blending_group`] and a square filled with the pattern
|
||||
/// "Checks" (a red square in a 20 pt tile) on it.
|
||||
fn patterned() -> Document {
|
||||
page(ColorMode::Rgb, |d| {
|
||||
let red = rect(d, Rect::new(0.0, 0.0, 10.0, 10.0), Color::rgb(1.0, 0.0, 0.0));
|
||||
let mut def = PatternDef::new("Checks", vec![Arc::new(red)]);
|
||||
def.tile = Rect::new(0.0, 0.0, 20.0, 20.0);
|
||||
d.patterns.push(def);
|
||||
let filled = Appearance::basic(pattern_paint("Checks"), Paint::None, 0.0);
|
||||
let filled = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(30.0, 30.0, 90.0, 90.0)), filled);
|
||||
vec![square(d), blending_group(d), filled]
|
||||
})
|
||||
}
|
||||
|
||||
fn same_bytes(words: &Rendered<Vec<u32>>, bytes: &Rendered, what: &str) {
|
||||
assert_eq!((words.width, words.height), (bytes.width, bytes.height), "{what}: the size");
|
||||
assert!(bytemuck::cast_slice::<u32, u8>(&words.pixels) == bytes.pixels.as_slice(), "{what}: the same bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nodes_thumbnails_and_swatches_in_words_hold_the_bytes_of_the_same_renders_in_bytes() {
|
||||
let d = patterned();
|
||||
let nodes = d.layers[0].children().expect("a layer").to_vec();
|
||||
let view = Affine::scale(0.7) * Affine::translate((-4.0, -9.0));
|
||||
let supersampled = RenderOptions { supersample: true, precise: true, image_mips: true, ..Default::default() };
|
||||
for (i, n) in nodes.iter().enumerate() {
|
||||
let bytes = Renderer::new().render_node(&d, n, 53, 41, view).expect("a node render");
|
||||
let words = Renderer::new().render_node_words(&d, n, 53, 41, view).expect("a node render");
|
||||
same_bytes(&words, &bytes, &format!("node {i}"));
|
||||
for (what, background, opts) in [
|
||||
("transparent", None, RenderOptions::default()),
|
||||
("on white", Some([255; 4]), RenderOptions::default()),
|
||||
("on a translucent color", Some([10, 200, 90, 128]), RenderOptions::default()),
|
||||
("supersampled", None, supersampled.clone()),
|
||||
("supersampled on white", Some([255; 4]), supersampled.clone()),
|
||||
] {
|
||||
let bytes = Renderer::new().render_node_thumbnail_with(&d, n, 37, background, &opts).expect("a thumbnail");
|
||||
let words = Renderer::new().render_node_thumbnail_words_with(&d, n, 37, background, &opts).expect("a thumbnail");
|
||||
same_bytes(&words, &bytes, &format!("node {i}'s thumbnail, {what}"));
|
||||
}
|
||||
let bytes = Renderer::new().render_node_thumbnail(&d, n, 31, Some([255; 4])).expect("a thumbnail");
|
||||
let words = Renderer::new().render_node_thumbnail_words(&d, n, 31, Some([255; 4])).expect("a thumbnail");
|
||||
same_bytes(&words, &bytes, &format!("node {i}'s thumbnail on white, default options"));
|
||||
let bytes = Renderer::new().render_thumbnail(&d, n.id, 29).expect("a thumbnail");
|
||||
let words = Renderer::new().render_thumbnail_words(&d, n.id, 29).expect("a thumbnail");
|
||||
same_bytes(&words, &bytes, &format!("node {i}'s thumbnail by id"));
|
||||
}
|
||||
let region = Rect::new(5.0, 15.0, 70.0, 90.0);
|
||||
for (what, opts) in [("outline", RenderOptions { outline: true, ..Default::default() }), ("supersampled", supersampled)] {
|
||||
let bytes = Renderer::new().render_region_with(&d, region, 1.3, &opts);
|
||||
let words = Renderer::new().render_region_with_words(&d, region, 1.3, &opts);
|
||||
same_bytes(&words, &bytes, &format!("the region, {what}"));
|
||||
}
|
||||
let bytes = render_pattern_swatch(&d, "Checks", 23).expect("a swatch");
|
||||
let words = render_pattern_swatch_words(&d, "Checks", 23).expect("a swatch");
|
||||
same_bytes(&words, &bytes, "the pattern swatch");
|
||||
assert!(render_pattern_swatch_words(&d, "Missing", 23).is_none(), "a pattern the document lacks has no swatch");
|
||||
assert!(Renderer::new().render_thumbnail_words(&d, NodeId(u64::MAX), 29).is_none(), "a node the document lacks has no thumbnail");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nodes_thumbnails_and_swatches_in_words_are_returned_in_the_buffer_they_rendered_into() {
|
||||
let d = patterned();
|
||||
let n = d.layers[0].children().expect("a layer")[1].clone();
|
||||
let mut r = Renderer::new();
|
||||
let out = r.render_node_words(&d, &n, 40, 40, Affine::IDENTITY).expect("a node render");
|
||||
assert_eq!(out.pixels.as_ptr() as usize, finished(), "a node's words are returned without a copy");
|
||||
let supersampled = RenderOptions { supersample: true, ..Default::default() };
|
||||
for background in [None, Some([255; 4])] {
|
||||
for (what, opts) in [("", RenderOptions::default()), (" supersampled", supersampled.clone())] {
|
||||
let out = r.render_node_thumbnail_words_with(&d, &n, 48, background, &opts).expect("a thumbnail");
|
||||
let at = out.pixels.as_ptr() as usize;
|
||||
assert_eq!(at, finished(), "background {background:?}{what}: a thumbnail's words are returned without a copy");
|
||||
}
|
||||
}
|
||||
let out = r.render_node_thumbnail_words(&d, &n, 48, Some([255; 4])).expect("a thumbnail");
|
||||
assert_eq!(out.pixels.as_ptr() as usize, finished(), "a thumbnail on a color's words are returned without a copy");
|
||||
let out = r.render_words(&d, 64, 48, Affine::IDENTITY, &supersampled);
|
||||
assert_eq!(out.pixels.as_ptr() as usize, finished(), "a supersampled frame's words are returned without a copy");
|
||||
let out = r.render_thumbnail_words(&d, n.id, 32).expect("a thumbnail");
|
||||
assert_eq!(out.pixels.as_ptr() as usize, finished(), "a thumbnail's words by id are returned without a copy");
|
||||
let plain = page(ColorMode::Rgb, |d| vec![square(d)]);
|
||||
let out = r.render_region_with_words(&plain, Rect::new(5.0, 15.0, 70.0, 90.0), 1.3, &RenderOptions::default());
|
||||
assert_eq!(out.pixels.as_ptr() as usize, finished(), "a region's words with options are returned without a copy");
|
||||
let out = render_pattern_swatch_words(&d, "Checks", 20).expect("a swatch");
|
||||
assert_eq!(out.pixels.as_ptr() as usize, finished(), "a swatch's words are returned without a copy");
|
||||
}
|
||||
@@ -64,7 +64,7 @@ vectorcraft-cad = { workspace = true }
|
||||
vectorcraft-eps = { workspace = true }
|
||||
vectorcraft-format = { workspace = true }
|
||||
egui = { workspace = true, features = ["bytemuck", "default_fonts", "monochrome_emoji_fonts"] }
|
||||
# With egui's `bytemuck`: copies rendered rasters into egui images whole (`canvas::color_image`).
|
||||
# With egui's `bytemuck`: hands rendered rasters to egui images in their own buffers (`canvas::color_image_owned`).
|
||||
# `default_fonts`: egui 0.37 makes its bundled faces opt-in, and a dependency's dev-features do not
|
||||
# reach our tests; `theme::install_fonts` starts from `FontDefinitions::default()`, which is empty
|
||||
# without them (production would lay out tofu, and the no-interface-fonts tests would bind nothing).
|
||||
|
||||
@@ -51,7 +51,9 @@ pub use fill::Fill;
|
||||
use home::home;
|
||||
pub use panes::{Layout as TileLayout, Panes};
|
||||
pub(crate) use panes::{consolidate, pane, tile, tiled_area};
|
||||
pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job};
|
||||
pub(crate) use raster::{KeptFrame, color_image_owned, render_job};
|
||||
#[cfg(test)]
|
||||
pub(crate) use raster::{assert_handed_over, clear_handed_over};
|
||||
pub(crate) use rulers::{general_lengths, stroke_lengths};
|
||||
pub use selection::HoverObjectKey;
|
||||
pub(crate) use task_bar::{TASK_BAR_ACTIONS, TASK_BAR_CHIPS, has_colors, is_task_bar_action, read_hidden_task_bar_actions};
|
||||
|
||||
@@ -18,25 +18,13 @@ use super::{BodyKind, in_gesture};
|
||||
use crate::doc_windows::Win;
|
||||
use crate::{CacheKey, VectorcraftApp};
|
||||
|
||||
/// The rendered raster `img` as an egui image. Both are premultiplied RGBA8, so its bytes are copied
|
||||
/// over whole instead of pixel by pixel, which costs milliseconds for a canvas on a large screen.
|
||||
/// A raster whose bytes don't match its size gives an empty image of that size.
|
||||
pub(crate) fn color_image(img: &vectorcraft_render::Rendered) -> egui::ColorImage {
|
||||
let size = [img.width as usize, img.height as usize];
|
||||
let expected = size[0].saturating_mul(size[1]).saturating_mul(4);
|
||||
if expected == img.pixels.len() {
|
||||
let pixels: Vec<egui::Color32> = bytemuck::cast_slice(&img.pixels).to_vec();
|
||||
egui::ColorImage::new(size, pixels)
|
||||
} else {
|
||||
egui::ColorImage::new(size, vec![egui::Color32::TRANSPARENT; size[0].saturating_mul(size[1])])
|
||||
}
|
||||
}
|
||||
|
||||
/// The raster `img` rendered in words ([`vectorcraft_render::Renderer::render_words`]) as an egui
|
||||
/// image, in the buffer `img` holds: a word and a [`egui::Color32`] are both four bytes aligned to
|
||||
/// four, so the pixels are not copied. A raster whose pixels don't match its size gives an empty
|
||||
/// image of that size.
|
||||
pub(crate) fn color_image_owned(img: vectorcraft_render::Rendered<Vec<u32>>) -> egui::ColorImage {
|
||||
#[cfg(test)]
|
||||
HANDED_OVER.with(|p| p.set(img.pixels.as_ptr() as usize));
|
||||
let size = [img.width as usize, img.height as usize];
|
||||
if size[0].saturating_mul(size[1]) == img.pixels.len() {
|
||||
let pixels: Vec<egui::Color32> = bytemuck::allocation::try_cast_vec(img.pixels).unwrap_or_else(|(_, v)| bytemuck::cast_slice(&v).to_vec());
|
||||
@@ -764,6 +752,24 @@ thread_local! {
|
||||
/// frame the test finished before it lands in the wait. A test that answers the job from
|
||||
/// another thread sets [`std::time::Duration::MAX`] to wait for that answer.
|
||||
pub(crate) static TEST_FIRST_FRAME_GRACE: std::cell::Cell<std::time::Duration> = const { std::cell::Cell::new(std::time::Duration::ZERO) };
|
||||
/// The address of the words the last [`color_image_owned`] on this thread was given.
|
||||
static HANDED_OVER: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Clears what [`assert_handed_over`] checks, before the image it checks is made.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn clear_handed_over() {
|
||||
HANDED_OVER.with(|p| p.set(0));
|
||||
}
|
||||
|
||||
/// Asserts that `image` was made by [`color_image_owned`] on this thread since
|
||||
/// [`clear_handed_over`], in the words it was given: the pixels were handed over, not copied.
|
||||
#[cfg(test)]
|
||||
#[track_caller]
|
||||
pub(crate) fn assert_handed_over(image: &egui::ColorImage, what: &str) {
|
||||
let given = HANDED_OVER.with(std::cell::Cell::get);
|
||||
assert!(given != 0, "{what}: the image is made from words handed over");
|
||||
assert_eq!(image.pixels.as_ptr() as usize, given, "{what}: the image holds the words it was given, not a copy");
|
||||
}
|
||||
|
||||
/// [`render_ms`] in unit tests: the time [`TEST_RENDER_MS`] holds.
|
||||
|
||||
@@ -7400,7 +7400,7 @@ fn the_worker_s_frame_reaches_its_texture_image_in_the_buffer_it_was_rendered_in
|
||||
let color = color_image_owned(frame);
|
||||
assert_eq!(color.pixels.as_ptr() as usize, at, "the frame's pixels are handed to the image, not copied");
|
||||
let bytes = vectorcraft_render::Renderer::new().render(&doc, job.w, job.h, job.view, &job.opts);
|
||||
assert!(color.pixels == color_image(&bytes).pixels, "the image holds the frame's pixels");
|
||||
assert!(bytemuck::cast_slice::<Color32, u8>(&color.pixels) == bytes.pixels.as_slice(), "the image holds the frame's pixels");
|
||||
assert_eq!(color.size, [256, 128]);
|
||||
// A raster whose pixels don't match its size gives an empty image of that size.
|
||||
let short = vectorcraft_render::Rendered { width: 3, height: 2, pixels: vec![u32::MAX; 5] };
|
||||
|
||||
@@ -34,7 +34,7 @@ use vectorcraft_engine::cmd::swatchlib;
|
||||
use vectorcraft_engine::script::DialogAnswer;
|
||||
|
||||
use super::preview::LivePreview;
|
||||
use crate::panels::color::{WorkingRgb, color_of_values, gamut, model_values};
|
||||
use crate::panels::color::{WorkingRgb, color_of_values, gamut, gamut_of, model_values};
|
||||
use crate::panels::swatches::{DOCUMENT_SWATCHES, colour_libraries};
|
||||
use crate::panels::{color_json, srgba};
|
||||
use crate::{VectorcraftApp, screen_color};
|
||||
@@ -236,10 +236,10 @@ fn library_index(app: &VectorcraftApp, limit: &str) -> Option<usize> {
|
||||
colour_libraries(app).iter().position(|lib| lib.id == limit).map(|i| i + 1)
|
||||
}
|
||||
|
||||
/// The working CMYK profile as the picker's CMYK converter, so its CMYK fields follow the document's
|
||||
/// The CMYK profile of `inks` as the picker's CMYK converter, so its CMYK fields follow the document's
|
||||
/// inks; `None` (the picker's built-in coated CMYK) when the profile can't link to sRGB.
|
||||
fn working_cmyk() -> Option<CmykConverter> {
|
||||
let bytes = cms::icc_bytes(&cms::active().settings().cmyk).ok()?;
|
||||
fn working_cmyk(inks: &cms::Cms) -> Option<CmykConverter> {
|
||||
let bytes = cms::icc_bytes(&inks.settings().cmyk).ok()?;
|
||||
CmykConverter::new(Arc::new(Profile::parse(&bytes).ok()?)).ok()
|
||||
}
|
||||
|
||||
@@ -295,7 +295,7 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
(None, false) => "fill",
|
||||
};
|
||||
let cmyk = app.session.active().is_some_and(|s| s.doc.color_mode == ColorMode::Cmyk);
|
||||
let mut dialog = picker(app, key, &color, cmyk);
|
||||
let mut dialog = picker(app, key, &color, cmyk, None);
|
||||
// The host replaces a picker only for the same document and artboard.
|
||||
if let Some((document, _, index, _)) = artboard {
|
||||
dialog = dialog.instance((document, index));
|
||||
@@ -327,15 +327,19 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
}
|
||||
|
||||
/// The Color Picker with `key` on `color`, with the eyedropper, the gamut warning, the document's
|
||||
/// swatches and libraries, and with `cmyk` (a CMYK document) the working CMYK inks.
|
||||
fn picker(app: &VectorcraftApp, key: &str, color: &Color, cmyk: bool) -> ColorPickerDialog {
|
||||
let mut dialog = ColorPickerDialog::new(key, tl!("Color Picker"), srgba(color))
|
||||
/// swatches and libraries, and with `cmyk` (a CMYK document) the CMYK inks. `inks`: the profiles of the
|
||||
/// document the picker edits when that is not the front document; it shows a CMYK color, tests the
|
||||
/// gamut and fills the CMYK fields through them. `None`: the active profiles.
|
||||
fn picker(app: &VectorcraftApp, key: &str, color: &Color, cmyk: bool, inks: Option<&Arc<cms::Cms>>) -> ColorPickerDialog {
|
||||
let mut dialog = ColorPickerDialog::new(key, tl!("Color Picker"), srgba_in(color, inks))
|
||||
.eyedropper(true)
|
||||
.add_to_swatches(false)
|
||||
.gamut(gamut(app))
|
||||
.gamut(inks.map_or_else(|| gamut(app), |i| gamut_of(i.clone())))
|
||||
.working_rgb(WorkingRgb)
|
||||
.swatch_view(swatch_view(app));
|
||||
if cmyk && let Some(converter) = working_cmyk() {
|
||||
if let Some(cms) = picker_cmyk(cmyk, inks)
|
||||
&& let Some(converter) = working_cmyk(&cms)
|
||||
{
|
||||
dialog = dialog.cmyk(&converter);
|
||||
}
|
||||
if matches!(color, Color::Cmyk { .. } | Color::Lab { .. }) {
|
||||
@@ -344,6 +348,13 @@ fn picker(app: &VectorcraftApp, key: &str, color: &Color, cmyk: bool) -> ColorPi
|
||||
dialog
|
||||
}
|
||||
|
||||
/// The color-management context whose CMYK profile the picker's CMYK fields convert through: `inks`
|
||||
/// whenever given, in an RGB document too, else the active profiles in a CMYK document (`cmyk`).
|
||||
/// `None`: the picker's built-in coated CMYK.
|
||||
fn picker_cmyk(cmyk: bool, inks: Option<&Arc<cms::Cms>>) -> Option<Arc<cms::Cms>> {
|
||||
inks.cloned().or_else(|| cmyk.then(cms::active))
|
||||
}
|
||||
|
||||
/// Opens the Color Picker a running script's `app.showColorPicker` waits at, on `color`; `cmyk`:
|
||||
/// the run's own active document is in CMYK, which the session does not show between slices;
|
||||
/// `profiles`: the RGB and CMYK profiles that document is assigned, which OK converts the pick through. It
|
||||
@@ -352,14 +363,15 @@ pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color, cmyk: bool
|
||||
let Some(dialogs) = app.dialogs() else { return };
|
||||
// The given colour's own values, so that OK can tell an untouched pick from another model's.
|
||||
// The Only Web Colors setting of earlier pickers is not recalled, so the colour opens as given.
|
||||
let dialog = picker(app, SCRIPT_KEY, &color, cmyk).kept(model_values(&color)).web_colors_remembered(false);
|
||||
let inks = script_inks(&profiles);
|
||||
let dialog = picker(app, SCRIPT_KEY, &color, cmyk, Some(&inks)).kept(model_values(&color)).web_colors_remembered(false);
|
||||
let id = dialogs.with(|h| h.open(dialog));
|
||||
app.color_dialogs.pickers.retain(|o| o.id != id);
|
||||
let target = Target::Script { color, cmyk, profiles };
|
||||
app.color_dialogs.pickers.push(Open {
|
||||
id,
|
||||
target,
|
||||
start: srgba(&color),
|
||||
start: srgba_in(&color, Some(&inks)),
|
||||
keep: false,
|
||||
preview: LivePreview::default(),
|
||||
view: Vec::new(),
|
||||
@@ -367,6 +379,25 @@ pub(crate) fn open_for_script(app: &mut VectorcraftApp, color: Color, cmyk: bool
|
||||
});
|
||||
}
|
||||
|
||||
/// The color-management context whose CMYK profile a script's picker shows its CMYK fields in: the
|
||||
/// script's document assigned `profiles`, which may not be the window's front document.
|
||||
fn script_inks(profiles: &(Option<String>, Option<String>)) -> Arc<cms::Cms> {
|
||||
cms::for_document(profiles.0.as_deref(), profiles.1.as_deref())
|
||||
}
|
||||
|
||||
/// `color` as display sRGB: a CMYK color through the CMYK profile of `inks`, anything else as
|
||||
/// [`srgba`] shows it. An RGB color keeps the active RGB profile, which the picker's RGB fields
|
||||
/// ([`WorkingRgb`]) read its channel values in.
|
||||
fn srgba_in(color: &Color, inks: Option<&Arc<cms::Cms>>) -> Srgba {
|
||||
match (inks, color) {
|
||||
(Some(inks), Color::Cmyk { .. }) => {
|
||||
let [r, g, b] = inks.display_rgb(color);
|
||||
Srgba::rgb(r, g, b)
|
||||
}
|
||||
_ => srgba(color),
|
||||
}
|
||||
}
|
||||
|
||||
/// The key of the Color Picker a script opens.
|
||||
pub(crate) const SCRIPT_KEY: &str = "script";
|
||||
|
||||
|
||||
@@ -494,3 +494,37 @@ fn the_canvas_stays_open_under_the_picker() {
|
||||
step(&mut app, &ctx, vec![]);
|
||||
assert_eq!(app.session.doc().unwrap().selection, selected, "the click under the picker leaves the selection");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_picker_shows_cmyk_in_the_scripts_document_profile() {
|
||||
// The front document keeps the working CMYK profile; the script's document is assigned another.
|
||||
let (mut app, _ctx) = app();
|
||||
assert_ne!(cms::active().settings().cmyk, cms::FOGRA52_CMYK, "the front document uses another CMYK profile");
|
||||
let color = Color::Cmyk { c: 1.0, m: 0.0, y: 0.0, k: 0.0 };
|
||||
open_for_script(&mut app, color, true, (None, Some(cms::FOGRA52_CMYK.to_string())));
|
||||
let open = app.color_dialogs.pickers.last().unwrap();
|
||||
let [r, g, b] = cms::for_document(None, Some(cms::FOGRA52_CMYK)).display_rgb(&color);
|
||||
assert_eq!(open.start, Srgba::rgb(r, g, b), "the picker shows the color through the script document's profile");
|
||||
assert_ne!(open.start, srgba(&color), "the front document's profile shows the color differently");
|
||||
let inks = script_inks(&(None, Some(cms::FOGRA52_CMYK.to_string())));
|
||||
assert_eq!(inks.settings().cmyk, cms::FOGRA52_CMYK, "the CMYK fields and gamut use the script document's profile");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_picker_in_an_rgb_document_fills_cmyk_fields_in_the_scripts_profile() {
|
||||
// An RGB document can carry its own CMYK profile; the picker's CMYK fields convert through it.
|
||||
let inks = script_inks(&(None, Some(cms::FOGRA52_CMYK.to_string())));
|
||||
let fields = picker_cmyk(false, Some(&inks)).map(|c| c.settings().cmyk.clone());
|
||||
assert_eq!(fields.as_deref(), Some(cms::FOGRA52_CMYK), "the script document's CMYK profile, in an RGB document too");
|
||||
assert!(picker_cmyk(false, None).is_none(), "the front RGB document keeps the built-in CMYK fields");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_picker_opens_an_rgb_color_as_its_rgb_fields_read_it() {
|
||||
// The RGB fields read channel values in the working RGB profile, so the opening swatch matches them.
|
||||
let inks = script_inks(&(Some(cms::WIDE_GAMUT_RGB.to_string()), None));
|
||||
let color = Color::rgb(0.5, 0.3, 0.2);
|
||||
let [r, g, b] = inks.display_rgb(&color);
|
||||
assert_ne!(Srgba::rgb(r, g, b), srgba(&color), "the two RGB profiles show the color differently");
|
||||
assert_eq!(srgba_in(&color, Some(&inks)), srgba(&color), "the opening color and the RGB fields use one profile");
|
||||
}
|
||||
@@ -349,22 +349,21 @@ fn image(f: &CompositeFont, zoom: u64, marks: &[Mark], ppp: f32, ink: Color32) -
|
||||
mark_line(&mut rendered, ((base - y) as f32 * ppp).round(), ppp.ceil().max(1.0) as usize, m.color());
|
||||
}
|
||||
}
|
||||
crate::canvas::color_image(&rendered)
|
||||
crate::canvas::color_image_owned(rendered)
|
||||
}
|
||||
|
||||
/// Draws a horizontal line `thickness` pixels thick from row `y` across `image`; a row outside it draws nothing.
|
||||
fn mark_line(image: &mut vectorcraft_render::Rendered, y: f32, thickness: usize, color: Color32) {
|
||||
fn mark_line(image: &mut vectorcraft_render::Rendered<Vec<u32>>, y: f32, thickness: usize, color: Color32) {
|
||||
if !y.is_finite() || y < 0.0 {
|
||||
return;
|
||||
}
|
||||
let (width, height) = (image.width as usize, image.height as usize);
|
||||
let first = y as usize;
|
||||
let word = u32::from_ne_bytes(color.to_array());
|
||||
for row in first..first.saturating_add(thickness).min(height) {
|
||||
let start = row.saturating_mul(width).saturating_mul(4);
|
||||
if let Some(line) = image.pixels.get_mut(start..start.saturating_add(width.saturating_mul(4))) {
|
||||
for pixel in line.as_chunks_mut::<4>().0 {
|
||||
pixel.copy_from_slice(&color.to_array());
|
||||
}
|
||||
let start = row.saturating_mul(width);
|
||||
if let Some(line) = image.pixels.get_mut(start..start.saturating_add(width)) {
|
||||
line.fill(word);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -372,7 +371,7 @@ fn mark_line(image: &mut vectorcraft_render::Rendered, y: f32, thickness: usize,
|
||||
/// The sample of `f` set at `size` points in `ink`, its baseline `baseline` points down from the
|
||||
/// top, drawn by the renderer as the canvas draws type (color and bitmap glyphs in their own
|
||||
/// colors) into `px` pixels at `ppp` pixels per point.
|
||||
pub(super) fn draw(f: &CompositeFont, size: f64, baseline: f64, px: (u16, u16), ppp: f32, ink: Color32) -> vectorcraft_render::Rendered {
|
||||
pub(super) fn draw(f: &CompositeFont, size: f64, baseline: f64, px: (u16, u16), ppp: f32, ink: Color32) -> vectorcraft_render::Rendered<Vec<u32>> {
|
||||
let (w, h) = px;
|
||||
let mut doc = vectorcraft_doc::Document::new(f64::from(w) / f64::from(ppp), f64::from(h) / f64::from(ppp));
|
||||
let font = sample_font(f);
|
||||
@@ -384,8 +383,8 @@ pub(super) fn draw(f: &CompositeFont, size: f64, baseline: f64, px: (u16, u16),
|
||||
let t = TextObject::point(Point::new(INSET, baseline), &sample, style);
|
||||
let node = std::sync::Arc::new(vectorcraft_doc::Node::new(doc.alloc_id(), vectorcraft_doc::NodeKind::Text(Box::new(t))));
|
||||
let view = Affine::scale(f64::from(ppp));
|
||||
let empty = || vectorcraft_render::Rendered { width: u32::from(w), height: u32::from(h), pixels: vec![0; usize::from(w) * usize::from(h) * 4] };
|
||||
RENDERER.with(|r| r.borrow_mut().render_node(&doc, &node, w, h, view)).unwrap_or_else(empty)
|
||||
let empty = || vectorcraft_render::Rendered { width: u32::from(w), height: u32::from(h), pixels: vec![0; usize::from(w) * usize::from(h)] };
|
||||
RENDERER.with(|r| r.borrow_mut().render_node_words(&doc, &node, w, h, view)).unwrap_or_else(empty)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -477,4 +476,16 @@ mod zoom_tests {
|
||||
assert_eq!(fields(&panel)["zoom"], json!(400), "canceling an older popup must not undo the later automation edit");
|
||||
assert_eq!(panel.value_role("Zoom", Role::COMBO_BOX).as_deref(), Some("400%"));
|
||||
}
|
||||
|
||||
/// The sample's image holds the pixels the sample was rendered into, with its lines drawn in.
|
||||
#[test]
|
||||
fn the_sample_image_is_handed_over_with_its_lines_drawn_in() {
|
||||
let f = CompositeFont::new("Sample draft", "Source Sans 3", "Regular");
|
||||
crate::canvas::clear_handed_over();
|
||||
let image = image(&f, 100, &[Mark::Baseline], 1.0, Color32::BLACK);
|
||||
crate::canvas::assert_handed_over(&image, "the sample");
|
||||
let [w, _] = image.size;
|
||||
let line = image.pixels.chunks(w).any(|row| row.iter().all(|p| *p == Mark::Baseline.color()));
|
||||
assert!(line, "the baseline is drawn across the sample");
|
||||
}
|
||||
}
|
||||
@@ -585,6 +585,7 @@ fn the_sample_draws_color_glyphs_in_their_colors() {
|
||||
colr.size = 300.0;
|
||||
f.custom = vec![CustomCharSet { name: "Color".into(), characters: COLOUR_CHAR.to_string(), part: colr }];
|
||||
let img = sample::draw(&f, 36.0, 120.0, (900, 160), 1.0, egui::Color32::BLACK);
|
||||
let img = vectorcraft_render::Rendered { width: img.width, height: img.height, pixels: bytemuck::cast_slice::<u32, u8>(&img.pixels).to_vec() };
|
||||
let red = (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).any(|(x, y)| {
|
||||
let p = img.pixel(x, y);
|
||||
p[0] > 200 && p[1] < 60 && p[2] < 60 && p[3] > 200
|
||||
|
||||
@@ -672,8 +672,8 @@ fn thumbnail(doc: &Document, art: &Node) -> egui::ColorImage {
|
||||
static RENDERER: RefCell<vectorcraft_render::Renderer> = RefCell::new(vectorcraft_render::Renderer::new());
|
||||
}
|
||||
RENDERER
|
||||
.with(|r| r.borrow_mut().render_node_thumbnail(doc, art, PREVIEW_PX, Some([255, 255, 255, 255])))
|
||||
.map_or_else(blank, |img| crate::canvas::color_image(&img))
|
||||
.with(|r| r.borrow_mut().render_node_thumbnail_words(doc, art, PREVIEW_PX, Some([255, 255, 255, 255])))
|
||||
.map_or_else(blank, crate::canvas::color_image_owned)
|
||||
}
|
||||
|
||||
/// The designs among `selection`'s rows.
|
||||
@@ -909,6 +909,18 @@ mod tests {
|
||||
app.run("select.set", json!({"ids": [g]})).unwrap();
|
||||
}
|
||||
|
||||
/// A design's preview holds the pixels it was rendered into.
|
||||
#[test]
|
||||
fn a_designs_preview_is_handed_to_its_image_without_a_copy() {
|
||||
let (app, _ctx) = app_with_design();
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
let design = doc.graph_designs.first().expect("the new design");
|
||||
crate::canvas::clear_handed_over();
|
||||
let image = super::thumbnail(doc, &design.art);
|
||||
assert_eq!(image.size, [super::PREVIEW_PX as usize; 2], "the preview's size");
|
||||
crate::canvas::assert_handed_over(&image, "the design's preview");
|
||||
}
|
||||
|
||||
/// The open dialog's fields, as automation lists them.
|
||||
fn fields(app: &VectorcraftApp) -> Value {
|
||||
app.dialogs().unwrap().with(|host| host.open_dialogs()).last().unwrap().fields.clone().unwrap()
|
||||
|
||||
@@ -211,6 +211,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) {
|
||||
super::find_links::pump,
|
||||
);
|
||||
super::missing_fonts::open_next(app);
|
||||
super::text_import::open_next(app);
|
||||
pumps!(app, ctx;
|
||||
super::dxf_import::pump,
|
||||
super::import_pdf::pump,
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! Text Import Options: placing a text file asks how to read it (platform and character set) and
|
||||
//! what to clean up (line breaks inside paragraphs, blank lines between them, runs of spaces). OK
|
||||
//! places it as area type (`file.place` with `text`) and remembers the options: the next text file
|
||||
//! starts from them, and is placed with them when Show Import Options is off.
|
||||
//! starts from them, and is placed with them when Show Import Options is off. Opening a text file
|
||||
//! (File › Open, Open Recent, a drop) asks the same: OK opens it as a new document of its text
|
||||
//! (`document.open` with `text`) and remembers the options.
|
||||
//!
|
||||
//! Fields: `platform` (`windows` | `mac`), `characterSet` (one of [`CHARACTER_SETS`]),
|
||||
//! `removeLineReturns`, `removeParagraphReturns`, `replaceSpaces` (on or off) and `spaces` (how
|
||||
@@ -45,7 +47,11 @@ const SPACES: std::ops::RangeInclusive<i64> = 2..=100;
|
||||
|
||||
/// Is the file `p` names (`path` or `name`) a text file?
|
||||
pub fn is_text(p: &Value) -> bool {
|
||||
let name = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).unwrap_or_default();
|
||||
is_text_name(p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).unwrap_or_default())
|
||||
}
|
||||
|
||||
/// Is the file named `name` a text file, by its extension?
|
||||
fn is_text_name(name: &str) -> bool {
|
||||
vectorcraft_engine::cmd::fileio::TEXT_EXTS.contains(&vectorcraft_engine::cmd::fileio::extension(name).as_str())
|
||||
}
|
||||
|
||||
@@ -106,6 +112,60 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) -> Value {
|
||||
json!({ "dialog": KIND })
|
||||
}
|
||||
|
||||
/// A text file File › Open asks about: its name, bytes, path and `document.open` params.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct TextOpen {
|
||||
name: String,
|
||||
bytes: Vec<u8>,
|
||||
path: Option<String>,
|
||||
params: Value,
|
||||
}
|
||||
|
||||
/// File › Open of the file `name` holding `bytes` (read from `path`) with `document.open`'s params
|
||||
/// `p` asks how to read it first (true) when it is a text file that opens as text (not a PDF or
|
||||
/// Affinity file named `.txt`) and `p` gives no `text` options and names no importer: OK opens it as a new document with the options and remembers them for the
|
||||
/// next text file, and an error keeps the dialog open. The dialog starts from the options
|
||||
/// confirmed last. While any dialog is open, the file waits its turn ([`open_next`]).
|
||||
pub fn offer_open(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<String>, p: &Value) -> bool {
|
||||
if !is_text_name(name)
|
||||
|| !vectorcraft_engine::cmd::place::opens_as_text(name, bytes)
|
||||
|| p.get("text").is_some()
|
||||
|| p.get("importer").is_some_and(|v| !v.is_null())
|
||||
|| app.ui_ctx.is_none()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let file = TextOpen { name: name.to_string(), bytes: bytes.to_vec(), path, params: p.clone() };
|
||||
if app.any_dialog_open() || !app.ui.text_opens.is_empty() {
|
||||
app.ui.text_opens.push(file);
|
||||
return true;
|
||||
}
|
||||
ask_open(app, file)
|
||||
}
|
||||
|
||||
/// Asks about the next text file File › Open waits to open, once no dialog is open.
|
||||
pub(crate) fn open_next(app: &mut VectorcraftApp) {
|
||||
if app.ui.text_opens.is_empty() || app.any_dialog_open() {
|
||||
return;
|
||||
}
|
||||
let file = app.ui.text_opens.remove(0);
|
||||
ask_open(app, file);
|
||||
}
|
||||
|
||||
/// Text Import Options for the text file `file` File › Open opens.
|
||||
fn ask_open(app: &mut VectorcraftApp, file: TextOpen) -> bool {
|
||||
let ctx = app.ui_ctx.clone().unwrap_or_default();
|
||||
let dialog = HostedParamDialog::new(&ctx, KIND, starting_fields(app), build).held_ok();
|
||||
open_held(app, dialog, move |app, result| {
|
||||
let mut p = file.params.clone();
|
||||
p["text"] = options(&result.fields);
|
||||
crate::io::open_document(app, &file.name, &file.bytes, file.path.clone(), &p)?;
|
||||
app.ui.text_import = p["text"].clone();
|
||||
Ok(())
|
||||
})
|
||||
.is_some()
|
||||
}
|
||||
|
||||
/// The `text` options a text file is placed with when Show Import Options is off: those confirmed
|
||||
/// last, else `file.place`'s defaults.
|
||||
pub fn last_options(app: &VectorcraftApp) -> Value {
|
||||
@@ -409,4 +469,63 @@ mod tests {
|
||||
assert_eq!((objects(0), objects(1)), (1, 0), "placed in the document it was dropped on");
|
||||
assert_eq!(app.session.active_index(), Some(0));
|
||||
}
|
||||
|
||||
/// File › Open of a text file asks for its import options, starting from the ones confirmed
|
||||
/// last, and opens nothing until OK: OK opens a new document of its text read with them and
|
||||
/// remembers them, and Cancel opens nothing. Text files opened together are asked about one at
|
||||
/// a time. An RTF file opens without asking.
|
||||
#[test]
|
||||
fn opening_a_text_file_asks_for_the_import_options_then_opens_a_document() {
|
||||
let mut app = host::app();
|
||||
app.ui.text_import = json!({"characterSet": "shiftJis", "platform": "windows"});
|
||||
let text = [b"\x93\xFA\x96\x7B\r\n".as_slice(), b"one\r\n\r\ntwo"].concat();
|
||||
assert_eq!(crate::io::open_bytes(&mut app, "notes.txt", &text, None).unwrap(), Value::Null);
|
||||
assert!(app.session.documents().is_empty(), "nothing opens before OK");
|
||||
assert_eq!(host::fields(&app, KIND)["characterSet"], "shiftJis");
|
||||
host::set(&app, KIND, "removeParagraphReturns", json!(true));
|
||||
host::confirm(&mut app, KIND).unwrap();
|
||||
assert!(!host::is_open(&app, KIND));
|
||||
assert_eq!(app.session.documents().len(), 1);
|
||||
assert_eq!(placed_text(&app).as_deref(), Some("日本\none\ntwo"), "decoded as Shift JIS, the blank line dropped");
|
||||
assert_eq!(app.ui.text_import["removeParagraphReturns"], true, "remembered for the next file");
|
||||
assert_eq!(app.session.doc().unwrap().title(), "notes.txt");
|
||||
|
||||
// Two text files opened together are asked about in turn: Cancel on the first opens
|
||||
// nothing, and the second is asked about next.
|
||||
crate::io::open_bytes(&mut app, "other.txt", b"three", None).unwrap();
|
||||
crate::io::open_bytes(&mut app, "last.txt", b"four", None).unwrap();
|
||||
assert!(host::is_open(&app, KIND));
|
||||
host::cancel(&app, KIND);
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
crate::dialogs::host::pump(&mut app, &ctx);
|
||||
assert_eq!(app.session.documents().len(), 1, "Cancel opens nothing");
|
||||
host::confirm(&mut app, KIND).unwrap();
|
||||
assert_eq!((app.session.documents().len(), placed_text(&app).as_deref()), (2, Some("four")));
|
||||
crate::dialogs::host::pump(&mut app, &ctx);
|
||||
assert!(!host::is_open(&app, KIND), "no file is left to ask about");
|
||||
|
||||
let rtf = br"{\rtf1 Rich {\b words}}";
|
||||
crate::io::open_bytes(&mut app, "rich.rtf", rtf, None).unwrap();
|
||||
assert!(!host::is_open(&app, KIND));
|
||||
assert_eq!((app.session.documents().len(), placed_text(&app).as_deref()), (3, Some("Rich words")));
|
||||
}
|
||||
|
||||
/// A text file opened while another dialog is open waits for that dialog to close before
|
||||
/// Text Import Options asks about it.
|
||||
#[test]
|
||||
fn a_text_file_opened_under_another_dialog_waits_for_it_to_close() {
|
||||
let mut app = host::app();
|
||||
let other = crate::dialogs::circle_options::open(&mut app);
|
||||
let other = other["dialog"].as_str().expect("dialog kind").to_string();
|
||||
assert!(host::is_open(&app, &other));
|
||||
crate::io::open_bytes(&mut app, "notes.txt", b"words", None).unwrap();
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
crate::dialogs::host::pump(&mut app, &ctx);
|
||||
assert!(!host::is_open(&app, KIND), "Text Import Options waits while another dialog is open");
|
||||
host::cancel(&app, &other);
|
||||
crate::dialogs::host::pump(&mut app, &ctx);
|
||||
assert!(host::is_open(&app, KIND), "asked once the other dialog closes");
|
||||
host::confirm(&mut app, KIND).unwrap();
|
||||
assert_eq!(placed_text(&app).as_deref(), Some("words"));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2125,7 +2125,7 @@ fn command_ids(s: &str) -> Vec<&str> {
|
||||
/// the messages each one lacks.
|
||||
const COMPLETE_MESSAGES: &[&str] = &[
|
||||
"cs", "de", "el", "es", "fr", "hi", "hu", "it", "ja", "ka", "ko", "pl", "pt-br", "ru", "sv", "uk", "vi", "zh-hans", "zh-hant", "fi", "tr", "ca",
|
||||
"nl", "da", "id", "bg",
|
||||
"nl", "da", "id", "bg", "gu",
|
||||
];
|
||||
|
||||
/// Crates whose error and status messages reach the status bar, the crates whose errors the
|
||||
|
||||
@@ -69,10 +69,12 @@ fn open_bytes_with(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Opt
|
||||
return load(app, p).map(|_| Value::Null);
|
||||
}
|
||||
// A PDF with several pages or a password asks first (the Import PDF dialog), and so do a DXF
|
||||
// drawing (DXF Import Options) and a PSD file with several layers or with slices (PSD Import
|
||||
// Options), unless `p` says how its layers come in.
|
||||
// drawing (DXF Import Options), a text file (Text Import Options, unless `p` gives `text`) and
|
||||
// a PSD file with several layers or with slices (PSD Import Options), unless `p` says how its
|
||||
// layers come in.
|
||||
if crate::dialogs::import_pdf::offer(app, name, bytes, path.clone(), None)
|
||||
|| crate::dialogs::dxf_import::offer(app, name, bytes, path.clone(), None)
|
||||
|| crate::dialogs::text_import::offer_open(app, name, bytes, path.clone(), p)
|
||||
|| (p.get("layers").is_none() && crate::dialogs::psd_import::offer(app, name, bytes, path.clone(), None))
|
||||
{
|
||||
return Ok(Value::Null);
|
||||
@@ -513,7 +515,9 @@ fn check_import_size(path: &str, explicit: bool) -> Result<(), String> {
|
||||
use std::io::Read as _;
|
||||
use vectorcraft_plugins::import;
|
||||
let ext = fileio::extension(path);
|
||||
if !explicit && (fileio::readable_format(&ext).is_some() || import::for_extension(&ext).is_empty()) {
|
||||
if !explicit
|
||||
&& (fileio::readable_format(&ext).is_some() || fileio::TEXT_DOCUMENT_EXTS.contains(&ext.as_str()) || import::for_extension(&ext).is_empty())
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if std::fs::metadata(path).map_or(true, |m| m.len() <= import::MAX_INPUT_BYTES as u64) {
|
||||
@@ -676,10 +680,11 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va
|
||||
if crate::dialogs::dxf_import::convert_in_background(app, path, &bytes, Some(path.to_string()), None) {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
// A PDF with several pages or a password, a DXF drawing, or a PSD file with several layers
|
||||
// or with slices asks first, as at once.
|
||||
// A PDF with several pages or a password, a DXF drawing, a text file, or a PSD file with
|
||||
// several layers or with slices asks first, as at once.
|
||||
if crate::dialogs::import_pdf::offer(app, path, &bytes, Some(path.to_string()), None)
|
||||
|| crate::dialogs::dxf_import::offer(app, path, &bytes, Some(path.to_string()), None)
|
||||
|| crate::dialogs::text_import::offer_open(app, path, &bytes, Some(path.to_string()), p)
|
||||
|| (p.get("layers").is_none() && crate::dialogs::psd_import::offer(app, path, &bytes, Some(path.to_string()), None))
|
||||
{
|
||||
note_recent(app, path);
|
||||
|
||||
@@ -143,17 +143,7 @@ pub(crate) fn paint_thumb(painter: &egui::Painter, revision: Revision, doc: &Doc
|
||||
let key = (nodes, px);
|
||||
let tex = CACHE.with(|c| c.borrow().get(&key).cloned()).or_else(|| {
|
||||
let art: Vec<&Node> = ids().iter().filter_map(|id| doc.node(*id)).collect();
|
||||
// Same Art Optimized supersample as assets.export (#983): abutting fills leave no seam in
|
||||
// the tile (Layers row thumbs stay cheap without it).
|
||||
let opts = vectorcraft_render::RenderOptions { image_mips: true, precise: true, supersample: true, ..Default::default() };
|
||||
let img = RENDERER.with(|rr| match art.as_slice() {
|
||||
[one] => rr.borrow_mut().render_node_thumbnail_with(doc, one, px, None, &opts),
|
||||
many => {
|
||||
let group = Node::group(NodeId(0), many.iter().map(|n| Arc::new((*n).clone())).collect());
|
||||
rr.borrow_mut().render_node_thumbnail_with(doc, &group, px, None, &opts)
|
||||
}
|
||||
})?;
|
||||
let color = crate::canvas::color_image(&img);
|
||||
let color = RENDERER.with(|rr| thumb_image(&mut rr.borrow_mut(), doc, &art, px))?;
|
||||
let tex = painter.ctx().load_texture(format!("asset-thumb-{}", a.id), color, egui::TextureOptions::LINEAR);
|
||||
CACHE.with(|c| {
|
||||
let mut c = c.borrow_mut();
|
||||
@@ -169,6 +159,22 @@ pub(crate) fn paint_thumb(painter: &egui::Painter, revision: Revision, doc: &Doc
|
||||
}
|
||||
}
|
||||
|
||||
/// The objects `art` of `doc` (back to front) fitted into `px` pixels square, transparent: the
|
||||
/// image of an asset's tile. `None` when they have no bounds.
|
||||
pub(super) fn thumb_image(r: &mut vectorcraft_render::Renderer, doc: &Document, art: &[&Node], px: u32) -> Option<egui::ColorImage> {
|
||||
// Same Art Optimized supersample as assets.export (#983): abutting fills leave no seam in
|
||||
// the tile (Layers row thumbs stay cheap without it).
|
||||
let opts = vectorcraft_render::RenderOptions { image_mips: true, precise: true, supersample: true, ..Default::default() };
|
||||
let img = match art {
|
||||
[one] => r.render_node_thumbnail_words_with(doc, one, px, None, &opts),
|
||||
many => {
|
||||
let group = Node::group(NodeId(0), many.iter().map(|n| Arc::new((*n).clone())).collect());
|
||||
r.render_node_thumbnail_words_with(doc, &group, px, None, &opts)
|
||||
}
|
||||
}?;
|
||||
Some(crate::canvas::color_image_owned(img))
|
||||
}
|
||||
|
||||
/// The document's assets as the tile grid's items.
|
||||
struct Assets {
|
||||
ids: Vec<u64>,
|
||||
|
||||
@@ -180,6 +180,20 @@ pub(crate) fn gamut(_app: &VectorcraftApp) -> Gamut<'static> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The printable test of [`gamut`] in the CMYK space of `inks` instead of the active one, for a
|
||||
/// picker that edits a document other than the front one.
|
||||
pub(crate) fn gamut_of(inks: std::sync::Arc<cms::Cms>) -> Gamut<'static> {
|
||||
Gamut::new(move |c: Srgba| {
|
||||
// The picker samples display sRGB: the same color in the document's RGB space.
|
||||
let color = crate::screen_color::sampled(&inks, [c.r, c.g, c.b]);
|
||||
if !inks.out_of_gamut(&color) {
|
||||
return c;
|
||||
}
|
||||
let [r, g, b] = inks.display_rgb(&inks.convert(&color, cms::Model::Cmyk, inks.settings().intent));
|
||||
Srgba::new(r, g, b, c.a)
|
||||
})
|
||||
}
|
||||
|
||||
/// Serde reader for [`crate::UiState::color_panel`]: junk gives the default, so an unknown value
|
||||
/// doesn't lose the rest of the preferences.
|
||||
pub fn deserialize_panel_state<'de, D: serde::Deserializer<'de>>(d: D) -> Result<ColorPanelState, D::Error> {
|
||||
|
||||
@@ -384,8 +384,8 @@ fn render_object(app: &VectorcraftApp, doc: &Document, n: &Node, g: &GraphicStyl
|
||||
} else {
|
||||
styled_node(n, g, app.session.prefs.override_char_color)
|
||||
};
|
||||
let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail(doc, &styled, px, Some([255; 4])))?;
|
||||
let mut img = crate::canvas::color_image(&img);
|
||||
let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail_words(doc, &styled, px, Some([255; 4])))?;
|
||||
let mut img = crate::canvas::color_image_owned(img);
|
||||
if empty {
|
||||
slash(&mut img);
|
||||
}
|
||||
@@ -1321,13 +1321,17 @@ mod tests {
|
||||
// The large preview on the selected rectangle.
|
||||
let st = app.session.active().unwrap();
|
||||
let n = st.doc.node(st.selection.objects[0]).unwrap();
|
||||
crate::canvas::clear_handed_over();
|
||||
let img = render_object(&app, &st.doc, n, &empty, 60).unwrap();
|
||||
crate::canvas::assert_handed_over(&img, "the large preview with the slash");
|
||||
assert!(red(px(&img, 30, 30)));
|
||||
assert!(dark(px(&img, 1, 30)), "{:?}", px(&img, 1, 30));
|
||||
assert_eq!(px(&img, 10, 10), Color32::WHITE);
|
||||
// A style that paints keeps its own look there, without the slash.
|
||||
let blue = GraphicStyle::new("Blue", Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 1.0));
|
||||
crate::canvas::clear_handed_over();
|
||||
let img = render_object(&app, &st.doc, n, &blue, 60).unwrap();
|
||||
crate::canvas::assert_handed_over(&img, "the large preview");
|
||||
assert_eq!(px(&img, 30, 30), Color32::from_rgb(0, 0, 255));
|
||||
}
|
||||
|
||||
|
||||
@@ -128,7 +128,7 @@ pub(crate) fn render(node: Arc<Node>, doc: Arc<Document>, request: &ThumbRequest
|
||||
static RENDERER: std::cell::RefCell<vectorcraft_render::Renderer> = std::cell::RefCell::new(vectorcraft_render::Renderer::new());
|
||||
}
|
||||
return match RENDERER.with(|r| render_thumb(&mut r.borrow_mut(), &doc, &node, side)) {
|
||||
Some(img) => ThumbRender::Ready(crate::canvas::color_image(&img)),
|
||||
Some(img) => ThumbRender::Ready(crate::canvas::color_image_owned(img)),
|
||||
None => ThumbRender::Blank,
|
||||
};
|
||||
}
|
||||
@@ -141,7 +141,7 @@ pub(crate) fn render(node: Arc<Node>, doc: Arc<Document>, request: &ThumbRequest
|
||||
if cancel.is_cancelled() {
|
||||
return Err(cancelled());
|
||||
}
|
||||
Ok(img.map_or(LoadedPicture::Blank, |img| LoadedPicture::Image(crate::canvas::color_image(&img))))
|
||||
Ok(img.map_or(LoadedPicture::Blank, |img| LoadedPicture::Image(crate::canvas::color_image_owned(img))))
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -309,8 +309,8 @@ fn light_row(n: &Node, quick: Option<bool>, doc: &Document) -> bool {
|
||||
}
|
||||
|
||||
/// The thumbnail of `n` (`px` pixels square) as `r` renders it, on the UI thread or a lane.
|
||||
fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, n: &Node, px: u32) -> Option<vectorcraft_render::Rendered> {
|
||||
r.render_node_thumbnail_with(doc, n, px, None, &thumb_options())
|
||||
fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, n: &Node, px: u32) -> Option<vectorcraft_render::Rendered<Vec<u32>>> {
|
||||
r.render_node_thumbnail_words_with(doc, n, px, None, &thumb_options())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -598,7 +598,7 @@ mod tests {
|
||||
let ThumbRender::Later(job) = rendered(doc, n, &request) else { panic!("a heavy node is made on a lane") };
|
||||
let Ok(LoadedPicture::Image(there)) = job(&Cancel::new()) else { panic!("the job draws the node") };
|
||||
let here = render_thumb(&mut vectorcraft_render::Renderer::new(), doc, n, request.side).expect("this thread draws the node");
|
||||
let here = crate::canvas::color_image(&here);
|
||||
let here = crate::canvas::color_image_owned(here);
|
||||
assert!(here.pixels.iter().any(|p| p.a() > 0), "the thumbnail shows the art");
|
||||
assert_eq!((there.size, &there.pixels), (here.size, &here.pixels), "the same pixels");
|
||||
}
|
||||
@@ -642,4 +642,18 @@ mod tests {
|
||||
assert!(matches!(before.render(&key, &request), ThumbRender::Ready(_)));
|
||||
assert!(matches!(after.render(&key, &request), ThumbRender::Later(_)), "and a long path is made on a lane");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rows_thumbnail_is_handed_to_its_image_without_a_copy() {
|
||||
let request = ThumbRequest::for_cell(24.0, 1.0);
|
||||
let (doc, n) = doc_with(|id| rect(id.0));
|
||||
crate::canvas::clear_handed_over();
|
||||
let ThumbRender::Ready(here) = rendered(&doc, &n, &request) else { panic!("a small object's thumbnail is made at once") };
|
||||
crate::canvas::assert_handed_over(&here, "a thumbnail made here");
|
||||
let (doc, n) = doc_with(|id| path(id.0, 50_000));
|
||||
let ThumbRender::Later(job) = rendered(&doc, &n, &request) else { panic!("a long path is made on a lane") };
|
||||
crate::canvas::clear_handed_over();
|
||||
let Ok(LoadedPicture::Image(there)) = job(&Cancel::new()) else { panic!("the job draws the node") };
|
||||
crate::canvas::assert_handed_over(&there, "a thumbnail made on a lane");
|
||||
}
|
||||
}
|
||||
@@ -173,8 +173,8 @@ impl ThumbSource<NavKey> for NavThumbs {
|
||||
ThumbRender::Later(Box::new(move |_cancel| {
|
||||
let options = image_options(key);
|
||||
let renderer = if key.solid_dashes { &SOLID_RENDERER } else { &NAV_RENDERER };
|
||||
let image = renderer.with(|r| r.borrow_mut().render_region_with(&doc, region, scale, &options));
|
||||
Ok(LoadedPicture::Image(crate::canvas::color_image(&image)))
|
||||
let image = renderer.with(|r| r.borrow_mut().render_region_with_words(&doc, region, scale, &options));
|
||||
Ok(LoadedPicture::Image(crate::canvas::color_image_owned(image)))
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -293,6 +293,20 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The navigator's picture, with and without solid dashes, holds the pixels it was rendered into.
|
||||
#[test]
|
||||
fn the_navigator_picture_is_handed_to_its_image_without_a_copy() {
|
||||
let doc = Arc::new(vectorcraft_doc::Document::new(200.0, 100.0));
|
||||
let source = NavThumbs::new(&doc, 1, DRect::new(-10.0, -10.0, 210.0, 110.0));
|
||||
for solid_dashes in [false, true] {
|
||||
let key = NavKey { uid: 1, artboard_only: false, solid_dashes };
|
||||
let ThumbRender::Later(job) = source.render(&key, &ThumbRequest::for_cell(60.0, 1.0)) else { panic!("the picture is made on a lane") };
|
||||
crate::canvas::clear_handed_over();
|
||||
let Ok(LoadedPicture::Image(image)) = job(&craft::host::queue::Cancel::new()) else { panic!("the job draws the document") };
|
||||
crate::canvas::assert_handed_over(&image, if solid_dashes { "with solid dashes" } else { "with dashes" });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn navigator_reports_a_malformed_zoom_entry() {
|
||||
assert_malformed_zoom_entry_reported(show);
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
|
||||
use std::sync::LazyLock;
|
||||
|
||||
mod profile_picker;
|
||||
use profile_picker::{ProfileAction, ProfileActions, ProfileOption, ProfileSample, ProfileSelect};
|
||||
|
||||
use craft::behavior::{ColumnWidth, EditEvent, GestureId, IconId, Mixed};
|
||||
use craft::draw::ui::stroke::{self as draw, StrokeEditor, StrokeField, StrokeSections};
|
||||
use craft::keymap::CommandRef;
|
||||
@@ -887,57 +890,82 @@ pub(crate) fn profile_select(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
brush_keeps_size(app, shown.as_ref())
|
||||
};
|
||||
let mut entries = vec![];
|
||||
// Each entry's id and silhouette, as `WidthProfile::points`.
|
||||
let mut shapes: Vec<(String, Option<Vec<_>>)> = vec![];
|
||||
let mut picked = String::new();
|
||||
let mut divide = true;
|
||||
for e in app.session.profile_entries().filter(|e| brushed != Some(true) || e.matches(None)) {
|
||||
if !e.built_in && std::mem::take(&mut divide) {
|
||||
entries.push(Entry::separator());
|
||||
}
|
||||
if e.matches(cur) {
|
||||
picked = e.id.to_string();
|
||||
}
|
||||
// A saved profile's name is the user's.
|
||||
entries.push(Entry::new(e.id.to_string(), super::label_or_name(e.label, e.built_in).to_string()));
|
||||
shapes.push((e.id.to_string(), silhouette(e.points).map(<[_]>::to_vec)));
|
||||
entries.push(ProfileOption {
|
||||
id: e.id.to_string(),
|
||||
label: super::label_or_name(e.label, e.built_in).to_string(),
|
||||
points: silhouette(e.points).map(<[ProfileSample]>::to_vec),
|
||||
built_in: e.built_in,
|
||||
});
|
||||
}
|
||||
let brush_tip = tl!("The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile.");
|
||||
// While a brush keeps the size of a profiled stroke the select stays on, to its Uniform row, and still says why.
|
||||
let tip = TooltipSpec::new(if brushed == Some(true) { brush_tip } else { tl!("Variable Width Profile") }).disabled_text(brush_tip);
|
||||
// A profile no row shows (an unsaved one, or a listed one the brushed list leaves out) is drawn and named on the
|
||||
// face under the empty id, without a row of its own.
|
||||
// face without a row of its own.
|
||||
let unlisted = match cur {
|
||||
Some(profile) if picked.is_empty() => {
|
||||
shapes.push((String::new(), silhouette(&profile.points).map(<[_]>::to_vec)));
|
||||
Some(app.session.profile_entry(Some(profile)).map_or(tl!("Custom"), |e| super::label_or_name(e.label, e.built_in)).to_owned())
|
||||
let label = app.session.profile_entry(Some(profile)).map_or(tl!("Custom"), |e| super::label_or_name(e.label, e.built_in)).to_owned();
|
||||
Some((label, silhouette(&profile.points).map(<[ProfileSample]>::to_vec)))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let select = Select::new(tl!("Profile"), Bind::given(picked), &entries);
|
||||
let actions = ProfileActions {
|
||||
can_add: cur.is_some() && brushed != Some(true) && crate::menus::enabled(app, "stroke.widthProfile.add"),
|
||||
can_delete: cur.as_ref().and_then(|p| app.session.profile_entry(Some(p))).is_some_and(|e| !e.built_in)
|
||||
&& brushed != Some(true)
|
||||
&& crate::menus::enabled(app, "stroke.widthProfile.delete"),
|
||||
can_reset: crate::menus::enabled(app, "stroke.widthProfile.reset"),
|
||||
};
|
||||
let select = ProfileSelect::new(tl!("Profile"), Bind::given(picked), entries, paint_profile, actions);
|
||||
let select = match unlisted {
|
||||
Some(label) => select.unlisted_label(label),
|
||||
Some((label, points)) => select.unlisted(label, points),
|
||||
None => select,
|
||||
};
|
||||
let out = select
|
||||
.picture(|id: &String, cx, rect| {
|
||||
if let Some((_, points)) = shapes.iter().find(|(i, _)| i == id) {
|
||||
paint_profile(cx, rect, points.as_deref());
|
||||
}
|
||||
})
|
||||
// Brushed strokes with a profile still open the list, to its Uniform row.
|
||||
.enabled(brushed != Some(false))
|
||||
.tooltip(tip)
|
||||
.show(ui);
|
||||
// A cancel puts back what the gesture changed instead of applying the empty id, which names no profile.
|
||||
apply_select(app, "profile", &out, |app, id| set(app, json!({"profile": id})));
|
||||
apply_select(app, "profile", &out.edit, |app, id| set(app, json!({"profile": id})));
|
||||
if let Some(action) = out.action {
|
||||
apply_profile_action(app, action);
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_profile_action(app: &mut VectorcraftApp, action: ProfileAction) {
|
||||
match action {
|
||||
// Asks for the new profile's name, as the ≡ menu's Add to Profiles… does.
|
||||
ProfileAction::Add => {
|
||||
let params = add_profile_params(app);
|
||||
crate::menus::invoke(app, "ui.paramDialog", params);
|
||||
}
|
||||
ProfileAction::Delete(Some(name)) => {
|
||||
crate::menus::invoke(app, "stroke.widthProfile.delete", json!({"name": name}));
|
||||
}
|
||||
ProfileAction::Delete(None) => {
|
||||
crate::menus::invoke(app, "stroke.widthProfile.delete", json!({}));
|
||||
}
|
||||
ProfileAction::Reset => {
|
||||
crate::dialogs::confirm::ask(app, tl!("Do you want to reset profiles?"), "", "stroke.widthProfile.reset", json!({}));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `ui.paramDialog` params that ask for the name of a new saved profile.
|
||||
fn add_profile_params(app: &VectorcraftApp) -> Value {
|
||||
json!({"command": "stroke.widthProfile.add", "label": "Variable Width Profile", "params": {"name": app.session.next_profile_name()}})
|
||||
}
|
||||
|
||||
/// The command a ≡ menu row runs to ask for the name of a new saved profile.
|
||||
fn add_profile(app: &VectorcraftApp) -> CommandRef {
|
||||
let params =
|
||||
json!({"command": "stroke.widthProfile.add", "label": "Variable Width Profile", "params": {"name": app.session.next_profile_name()}});
|
||||
CommandRef::with_params("ui.paramDialog", params)
|
||||
CommandRef::with_params("ui.paramDialog", add_profile_params(app))
|
||||
}
|
||||
|
||||
/// The rows of the Stroke panel's ≡ menu; their titles and enabled flags come from [`menu_states`].
|
||||
|
||||
@@ -0,0 +1,657 @@
|
||||
//! The Variable Width Profile dropdown (`ProfileSelect`): a combo box whose popup shows the width
|
||||
//! profile list with built-in labels and captionless user-added thumbnails, a right-click Delete
|
||||
//! Profile on saved rows, and a footer bar with Add to Profiles…, Delete Profile, and Reset
|
||||
//! Profiles.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashSet;
|
||||
|
||||
use craft::behavior::nav::{StepResult, ValueAxes, ValueSteps};
|
||||
use craft::behavior::overlay::MinWidth;
|
||||
use craft::behavior::{
|
||||
CancelReason, ColumnKey, ColumnWidth, DisplayOrder, GesturePhase, HitLevel, HitPriority, IconId, ItemSource, Metrics, NavMove, PartKey, Proposal,
|
||||
Selection, Sense, TypeAhead, WheelPhase, wheel_step,
|
||||
};
|
||||
use craft::ui::contract::overlay::OverlayFit;
|
||||
use craft::ui::contract::{
|
||||
Access, ActivateOn, Bind, BindMut, CollectionEvent, ColumnSpec, Common, Component, Cx, Edit as _, EditResponse, Focus as _, HoverLead, Input,
|
||||
LeadOnOpen, LeadSource, MeasureCx, Numeric, Outcome, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, Popup, PopupHandle,
|
||||
Props, Role, Show as _, ShowCollection as _, ShowContainer as _, WordSetCx as _,
|
||||
};
|
||||
use craft::ui::layout_components::Stack;
|
||||
use craft::ui::list::{List, ListRow, RowEvent, ThumbAspect, ThumbSize};
|
||||
use craft::ui::menu::{Menu, MenuItem};
|
||||
use craft::ui::pickers::{SelectFace, toggle_on_key};
|
||||
use craft::ui::primitives::ContentPainterCx;
|
||||
use craft::ui::runtime::env::Label;
|
||||
use craft::ui::runtime::focus::{FocusMove, KeyUse};
|
||||
use craft::ui::runtime::memory::Remember as _;
|
||||
use craft::ui::runtime::overlay::CloseReason;
|
||||
use craft::ui::sections::{FooterAction, FooterBar};
|
||||
use craft::ui::style::{ComponentStyle, StyleCx, SurfaceLook};
|
||||
use egui::{Rect, Response, Vec2};
|
||||
|
||||
const PROFILE_COL: ColumnKey = ColumnKey::new("profile");
|
||||
/// The narrowest the closed control and the open list get, in points: room for a built-in's thumbnail and its
|
||||
/// longest label.
|
||||
const DROPDOWN_MIN_WIDTH: f32 = 132.0;
|
||||
/// The widest the closed control gets, in points, however long the picked profile's name.
|
||||
const CLOSED_MAX_WIDTH: f32 = 145.0;
|
||||
/// The rows Page Up and Page Down step the closed control by.
|
||||
const PAGE_ROWS: isize = 12;
|
||||
/// The size of a saved profile's thumbnail in the open list, in points.
|
||||
const SAVED_THUMB: Vec2 = Vec2::new(80.0, 20.0);
|
||||
/// The space left above and below a saved profile's thumbnail inside its row, in points.
|
||||
const SAVED_THUMB_INSET: f32 = 2.0;
|
||||
const FACE: PartKey = PartKey::new("face");
|
||||
const POPUP: &str = "list";
|
||||
const LIST_SALT: &str = "items";
|
||||
|
||||
/// Row identity in the profile list, keeping the non-interactive divider distinct from any
|
||||
/// user-saved profile name (even a literal `"__profile_separator__"`).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
enum ProfileRowKey {
|
||||
Profile(String),
|
||||
Separator,
|
||||
}
|
||||
|
||||
impl ProfileRowKey {
|
||||
fn profile(&self) -> Option<&str> {
|
||||
match self {
|
||||
ProfileRowKey::Profile(id) => Some(id.as_str()),
|
||||
ProfileRowKey::Separator => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One silhouette sample `(t, left_offset, right_offset)` returned by `stroke::silhouette`.
|
||||
pub(super) type ProfileSample = (f64, f64, f64);
|
||||
|
||||
fn profile_thumb_aspect() -> ThumbAspect {
|
||||
ThumbAspect::new(14, 5)
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
struct ProfileGraphicStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
}
|
||||
|
||||
/// Passive width-profile graphic for captionless user-added rows (`Sense::empty()` lets clicks and
|
||||
/// reorder drags go straight through to the list row).
|
||||
#[derive(Component, Props)]
|
||||
#[component(content_painter, sample = ProfileGraphic::sample)]
|
||||
struct ProfileGraphic {
|
||||
#[common]
|
||||
common: Common,
|
||||
points: Option<Vec<ProfileSample>>,
|
||||
paint: ProfilePaint,
|
||||
size: Vec2,
|
||||
}
|
||||
|
||||
impl ProfileGraphic {
|
||||
fn new(paint: ProfilePaint, points: Option<Vec<ProfileSample>>, size: Vec2) -> Self {
|
||||
Self { common: Common::new(), points, paint, size }
|
||||
}
|
||||
|
||||
fn sample() -> Self {
|
||||
Self::new(|_, _, _| {}, None, SAVED_THUMB)
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for ProfileGraphic {
|
||||
const ROLE: Role = Role::None;
|
||||
const PARTS: bool = false;
|
||||
const STOPS: bool = false;
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = ProfileGraphicStyle;
|
||||
type Output = Response;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: ProfileGraphicStyleKey) -> ProfileGraphicStyle {
|
||||
ProfileGraphicStyle { metrics: Metrics::new() }
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
self.size
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let painter = ui.content_painter(cx);
|
||||
(self.paint)(&painter, cx.rect.shrink2(Vec2::new(0.0, SAVED_THUMB_INSET)), self.points.as_deref());
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> Response {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// One entry in the Variable Width Profile dropdown.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(super) struct ProfileOption {
|
||||
/// Engine preset id (`"uniform"`, `"lens"`, …) or saved profile name.
|
||||
pub id: String,
|
||||
/// Display label shown in the closed face, and in the dropdown row for built-in profiles.
|
||||
pub label: String,
|
||||
/// Profile silhouette samples (`None` for Uniform).
|
||||
pub points: Option<Vec<ProfileSample>>,
|
||||
/// Built-in profiles keep their text captions in the dropdown and cannot be deleted.
|
||||
pub built_in: bool,
|
||||
}
|
||||
|
||||
/// Enable state for the management controls inside the dropdown footer.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub(super) struct ProfileActions {
|
||||
pub can_add: bool,
|
||||
pub can_delete: bool,
|
||||
pub can_reset: bool,
|
||||
}
|
||||
|
||||
/// A management action requested by the dropdown footer or a saved row's menu.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(super) enum ProfileAction {
|
||||
Add,
|
||||
Delete(Option<String>),
|
||||
Reset,
|
||||
}
|
||||
|
||||
/// Output of [`ProfileSelect`]: the underlying profile pick/preview edit and any management action.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct ProfileSelectOutput {
|
||||
pub edit: EditResponse<String>,
|
||||
pub action: Option<ProfileAction>,
|
||||
}
|
||||
|
||||
impl Outcome for ProfileSelectOutput {
|
||||
type Value = String;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.edit.response
|
||||
}
|
||||
}
|
||||
|
||||
/// Paint callback shared between the closed face and list rows.
|
||||
pub(super) type ProfilePaint = fn(&ContentPainterCx, Rect, Option<&[ProfileSample]>);
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
pub(super) struct ProfileSelectStyle {
|
||||
#[style(surface)]
|
||||
surface: SurfaceLook,
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
struct PickerMemory {
|
||||
/// Target key of an open per-row context menu.
|
||||
menu: Option<String>,
|
||||
/// Pre-typed query buffered on focus while closed.
|
||||
type_ahead: TypeAhead,
|
||||
/// Pending lead override when opening from closed type-ahead.
|
||||
reveal_on_open: Option<String>,
|
||||
/// Whether a preview proposal was issued during this open popup session.
|
||||
previewed: bool,
|
||||
}
|
||||
|
||||
/// The Profile drop-down: the width profile list, with a footer that adds the stroke's profile, deletes a saved one
|
||||
/// and resets the list.
|
||||
#[derive(Component, Props)]
|
||||
#[component(overlay, sample = ProfileSelect::sample)]
|
||||
pub(super) struct ProfileSelect {
|
||||
#[common]
|
||||
common: Common,
|
||||
value: Bind<'static, String>,
|
||||
entries: Vec<ProfileOption>,
|
||||
unlisted_label: Option<String>,
|
||||
unlisted_points: Option<Vec<ProfileSample>>,
|
||||
paint: ProfilePaint,
|
||||
actions: ProfileActions,
|
||||
action: Option<ProfileAction>,
|
||||
}
|
||||
|
||||
impl ProfileSelect {
|
||||
pub(super) fn new(
|
||||
label: impl Into<craft::ui::runtime::env::Label>,
|
||||
value: Bind<'static, String>,
|
||||
entries: Vec<ProfileOption>,
|
||||
paint: ProfilePaint,
|
||||
actions: ProfileActions,
|
||||
) -> Self {
|
||||
Self { common: Common::new(), value, entries, unlisted_label: None, unlisted_points: None, paint, actions, action: None }.label(label)
|
||||
}
|
||||
|
||||
pub(super) fn unlisted(mut self, label: String, points: Option<Vec<ProfileSample>>) -> Self {
|
||||
self.unlisted_label = Some(label);
|
||||
self.unlisted_points = points;
|
||||
self
|
||||
}
|
||||
|
||||
fn sample() -> Self {
|
||||
Self::new(
|
||||
"Profile",
|
||||
Bind::given("uniform".to_owned()),
|
||||
vec![ProfileOption { id: "uniform".to_owned(), label: "Uniform".to_owned(), points: None, built_in: true }],
|
||||
|_, _, _| {},
|
||||
ProfileActions::default(),
|
||||
)
|
||||
}
|
||||
|
||||
fn option(&self, id: &str) -> Option<&ProfileOption> {
|
||||
self.entries.iter().find(|e| e.id == id)
|
||||
}
|
||||
|
||||
fn display_for(&self, current: Option<&String>) -> (String, Option<Vec<ProfileSample>>, bool) {
|
||||
let Some(id) = current else {
|
||||
return (tl!("Mixed").to_owned(), None, true);
|
||||
};
|
||||
if let Some(opt) = self.option(id) {
|
||||
return (opt.label.clone(), opt.points.clone(), false);
|
||||
}
|
||||
if let Some(label) = &self.unlisted_label {
|
||||
return (label.clone(), self.unlisted_points.clone(), false);
|
||||
}
|
||||
(tl!("Mixed").to_owned(), None, true)
|
||||
}
|
||||
|
||||
fn face(&self, current: Option<&String>) -> SelectFace<'static> {
|
||||
let (text, points, placeholder) = self.display_for(current);
|
||||
let paint = self.paint;
|
||||
let face = SelectFace::new(text).fit(true).thumb(profile_thumb_aspect(), move |cx, rect| paint(cx, rect, points.as_deref()));
|
||||
if placeholder { face.placeholder() } else { face }
|
||||
}
|
||||
|
||||
fn has_separator(&self) -> bool {
|
||||
self.entries.len() > 1
|
||||
}
|
||||
|
||||
fn step_entry(&self, current: Option<&String>, steps: isize) -> Option<String> {
|
||||
if self.entries.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let cur = current.and_then(|id| self.entries.iter().position(|e| &e.id == id));
|
||||
let next = match cur {
|
||||
Some(at) => (at as isize + steps).clamp(0, (self.entries.len() - 1) as isize) as usize,
|
||||
None if steps >= 0 => 0,
|
||||
None => self.entries.len() - 1,
|
||||
};
|
||||
self.entries.get(next).map(|e| e.id.clone())
|
||||
}
|
||||
|
||||
fn nav_target(&self, current: Option<&String>, mv: NavMove) -> Option<String> {
|
||||
match mv {
|
||||
NavMove::Up | NavMove::Back => self.step_entry(current, -1),
|
||||
NavMove::Down | NavMove::Forward => self.step_entry(current, 1),
|
||||
NavMove::Start => self.entries.first().map(|e| e.id.clone()),
|
||||
NavMove::End => self.entries.last().map(|e| e.id.clone()),
|
||||
NavMove::PageUp => self.step_entry(current, -PAGE_ROWS),
|
||||
NavMove::PageDown => self.step_entry(current, PAGE_ROWS),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ProfileRows<'a> {
|
||||
entries: &'a [ProfileOption],
|
||||
separator: bool,
|
||||
}
|
||||
|
||||
impl<'a> ProfileRows<'a> {
|
||||
fn entry_at(&self, at: usize) -> Option<&'a ProfileOption> {
|
||||
if at == 0 {
|
||||
return self.entries.first();
|
||||
}
|
||||
if self.separator { if at == 1 { None } else { self.entries.get(at - 1) } } else { self.entries.get(at) }
|
||||
}
|
||||
}
|
||||
|
||||
impl DisplayOrder<ProfileRowKey> for ProfileRows<'_> {
|
||||
fn len(&self) -> usize {
|
||||
self.entries.len() + usize::from(self.separator)
|
||||
}
|
||||
|
||||
fn key(&self, at: usize) -> ProfileRowKey {
|
||||
self.entry_at(at).map_or(ProfileRowKey::Separator, |e| ProfileRowKey::Profile(e.id.clone()))
|
||||
}
|
||||
|
||||
fn is_section(&self, at: usize) -> bool {
|
||||
self.separator && at == 1
|
||||
}
|
||||
|
||||
fn enabled(&self, at: usize) -> bool {
|
||||
!(self.separator && at == 1)
|
||||
}
|
||||
|
||||
fn text(&self, at: usize) -> Option<Cow<'_, str>> {
|
||||
self.entry_at(at).map(|e| Cow::Borrowed(e.label.as_str()))
|
||||
}
|
||||
}
|
||||
|
||||
impl ItemSource<ProfileRowKey> for ProfileRows<'_> {}
|
||||
|
||||
impl Component for ProfileSelect {
|
||||
const ROLE: Role = Role::COMBO_BOX;
|
||||
const INPUT: Input = Input::Pointer;
|
||||
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_moves().with_type_ahead();
|
||||
type Style = ProfileSelectStyle;
|
||||
type Output = ProfileSelectOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: ProfileSelectStyleKey) -> ProfileSelectStyle {
|
||||
ProfileSelectStyle { surface: cx.dropdown(), metrics: Metrics::new() }
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS | Sense::WHEEL_Y
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
let mut size = cx.face(self.face(cx.value()));
|
||||
let paint = self.paint;
|
||||
let aspect = profile_thumb_aspect();
|
||||
for entry in self.entries.iter().filter(|e| e.built_in) {
|
||||
let points = entry.points.clone();
|
||||
let mut face = SelectFace::new(entry.label.clone()).fit(true).thumb(aspect, move |painter, rect| paint(painter, rect, points.as_deref()));
|
||||
let measured = cx.child("option", &mut face, Proposal::Ideal);
|
||||
size.x = size.x.max(measured.x);
|
||||
size.y = size.y.max(measured.y);
|
||||
}
|
||||
Vec2::new(size.x.clamp(DROPDOWN_MIN_WIDTH, CLOSED_MAX_WIDTH), size.y)
|
||||
}
|
||||
|
||||
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
cx.part(FACE, rect)
|
||||
.sense(Sense::CLICK | Sense::HOVER | Sense::TAKE_FOCUS)
|
||||
.priority(HitPriority::new(HitLevel::Body, 0))
|
||||
.pointer_only("Enter, Space and Alt+Down open the list")
|
||||
.toggles(POPUP);
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, String>> {
|
||||
Some(self.value.reborrow())
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
let popup = cx.popup(POPUP);
|
||||
toggle_on_key(cx, popup);
|
||||
if !popup.is_open(cx) && !cx.in_wheel_run() && matches!(cx.gesture(), Some(GesturePhase::Begin | GesturePhase::Update)) {
|
||||
cx.cancel(CancelReason::Dismissed);
|
||||
}
|
||||
if let Some(wheel) = cx.take_wheel() {
|
||||
if matches!(wheel.phase, WheelPhase::End) {
|
||||
cx.wheel_run(wheel.phase, None);
|
||||
} else if let StepResult::Set(along) =
|
||||
wheel_step(&ValueSteps::new(0.0, -f64::MAX, f64::MAX, 1.0, 1.0).fine(1.0), ValueAxes::Both, &wheel, cx.env.direction().is_rtl())
|
||||
&& along != 0.0
|
||||
{
|
||||
let steps = along.round() as isize;
|
||||
if let Some(target) = self.step_entry(cx.value().cloned().as_ref(), -steps) {
|
||||
cx.wheel_run(wheel.phase, Some(target));
|
||||
}
|
||||
}
|
||||
}
|
||||
if popup.is_open(cx) {
|
||||
return;
|
||||
}
|
||||
// A screen reader sets the pick by its place in the list, and steps it with Increment and Decrement (moves),
|
||||
// without the keyboard focus, as the framework's `Select` takes them.
|
||||
if let Some(at) = cx.intents().take_set_value() {
|
||||
if cx.in_wheel_run() {
|
||||
cx.commit();
|
||||
}
|
||||
let to = (at.round().max(0.0) as usize).min(self.entries.len().saturating_sub(1));
|
||||
if let Some(entry) = self.entries.get(to) {
|
||||
cx.propose(entry.id.clone());
|
||||
cx.commit();
|
||||
}
|
||||
}
|
||||
while let Some((mv, _)) = cx.intents().take_move() {
|
||||
if cx.in_wheel_run() {
|
||||
cx.commit();
|
||||
}
|
||||
if let Some(target) = self.nav_target(cx.value().cloned().as_ref(), mv) {
|
||||
cx.propose(target);
|
||||
cx.commit();
|
||||
}
|
||||
}
|
||||
if !cx.is_focused() {
|
||||
return;
|
||||
}
|
||||
if let Some(typed) = cx.intents().take_text() {
|
||||
let folder = cx.env.folder();
|
||||
let now = cx.ctx.input(|i| i.time);
|
||||
let cur_idx = cx.value().and_then(|id| self.entries.iter().position(|e| &e.id == id));
|
||||
let matched = {
|
||||
let mem = cx.memory::<PickerMemory>();
|
||||
let mut prefix = String::new();
|
||||
for ch in typed.chars() {
|
||||
prefix = mem.type_ahead.push(ch, now).to_owned();
|
||||
}
|
||||
TypeAhead::pick(&prefix, cur_idx, self.entries.len(), |at| Cow::Borrowed(self.entries[at].label.as_str()), |text| folder.key(text))
|
||||
};
|
||||
if let Some(at) = matched {
|
||||
let id = self.entries[at].id.clone();
|
||||
let mem = cx.memory::<PickerMemory>();
|
||||
mem.reveal_on_open = Some(id.clone());
|
||||
mem.previewed = true;
|
||||
cx.propose(id);
|
||||
popup.open(cx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) {
|
||||
let popup = cx.popup(POPUP);
|
||||
let list_id = cx.id.with(LIST_SALT);
|
||||
let mut overlay = Overlay::dropdown()
|
||||
.fit(OverlayFit::Content)
|
||||
.min_width(MinWidth::None)
|
||||
.min_size(Vec2::new(DROPDOWN_MIN_WIDTH, 0.0))
|
||||
.body_scroll(false)
|
||||
.list(list_id);
|
||||
overlay.dismiss.on_activate = false;
|
||||
|
||||
let fresh = Popup::opening(popup, cx);
|
||||
if fresh {
|
||||
let mem = cx.memory::<PickerMemory>();
|
||||
mem.menu = None;
|
||||
if mem.reveal_on_open.is_none() {
|
||||
mem.previewed = false;
|
||||
}
|
||||
}
|
||||
|
||||
let current = cx.value().cloned().filter(|id| !id.is_empty());
|
||||
let reveal =
|
||||
cx.memory::<PickerMemory>().reveal_on_open.take().or_else(|| fresh.then(|| current.clone()).flatten()).map(ProfileRowKey::Profile);
|
||||
let selection = current.as_ref().map_or_else(Selection::default, |id| Selection::single(ProfileRowKey::Profile(id.clone())));
|
||||
let saved: HashSet<String> = self.entries.iter().filter(|e| !e.built_in).map(|e| e.id.clone()).collect();
|
||||
let view = PopupView { list_id, selection: &selection, reveal: reveal.as_ref(), saved: &saved };
|
||||
|
||||
let body_out = ui.show(popup, overlay, |ui, _| show_popup_body(ui, cx, self, view));
|
||||
|
||||
if let Some((events, footer_action, menu_action)) = body_out {
|
||||
self.handle_list_events(cx, popup, &events);
|
||||
if let Some(act) = footer_action.or(menu_action) {
|
||||
if matches!(act, ProfileAction::Reset) {
|
||||
popup.close(cx);
|
||||
}
|
||||
self.action = Some(act);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(reason) = ui.closing(popup) {
|
||||
let mem = cx.memory::<PickerMemory>();
|
||||
mem.menu = None;
|
||||
if std::mem::take(&mut mem.previewed) && matches!(cx.gesture(), Some(GesturePhase::Begin | GesturePhase::Update)) {
|
||||
match reason {
|
||||
CloseReason::FocusLeft(FocusMove::Keys) => cx.commit(),
|
||||
CloseReason::FocusLeft(_) => cx.cancel(CancelReason::Blur),
|
||||
CloseReason::Escape => cx.cancel(CancelReason::Escape),
|
||||
_ => cx.cancel(CancelReason::Dismissed),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The picked entry's place in the list, read as its label, so a screen reader steps and sets it. A value no
|
||||
/// entry holds reads as the label the face shows.
|
||||
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
|
||||
let (text, _, _) = self.display_for(cx.value());
|
||||
let range = 0.0..=self.entries.len().saturating_sub(1) as f64;
|
||||
let numeric = match cx.value().and_then(|id| self.entries.iter().position(|e| &e.id == id)) {
|
||||
Some(at) => Numeric::new(at as f64, range),
|
||||
None => Numeric::empty(range),
|
||||
};
|
||||
access.numeric(numeric.text(text).step(1.0));
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
ui.face(FACE, self.face(cx.value()));
|
||||
}
|
||||
|
||||
fn finish(mut self, cx: Cx<'_, Self>) -> ProfileSelectOutput {
|
||||
ProfileSelectOutput { edit: cx.edit_response(), action: self.action.take() }
|
||||
}
|
||||
}
|
||||
|
||||
impl ProfileSelect {
|
||||
fn handle_list_events(&mut self, cx: &mut Cx<'_, Self>, popup: PopupHandle, events: &[CollectionEvent<ProfileRowKey, RowEvent>]) {
|
||||
for event in events {
|
||||
match event {
|
||||
CollectionEvent::LeadMoved { key: ProfileRowKey::Profile(key), by: LeadSource::Keys } => {
|
||||
cx.memory::<PickerMemory>().previewed = true;
|
||||
cx.propose(key.clone());
|
||||
}
|
||||
CollectionEvent::Activate(ProfileRowKey::Profile(key))
|
||||
| CollectionEvent::Item(ProfileRowKey::Profile(key), RowEvent::ThumbClicked { .. }) => {
|
||||
cx.propose(key.clone());
|
||||
cx.commit();
|
||||
cx.memory::<PickerMemory>().previewed = false;
|
||||
popup.close(cx);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct PopupView<'a> {
|
||||
list_id: egui::Id,
|
||||
selection: &'a Selection<ProfileRowKey>,
|
||||
reveal: Option<&'a ProfileRowKey>,
|
||||
saved: &'a HashSet<String>,
|
||||
}
|
||||
|
||||
fn show_popup_body(
|
||||
ui: &mut egui::Ui,
|
||||
cx: &mut Cx<'_, ProfileSelect>,
|
||||
picker: &ProfileSelect,
|
||||
view: PopupView<'_>,
|
||||
) -> (Vec<CollectionEvent<ProfileRowKey, RowEvent>>, Option<ProfileAction>, Option<ProfileAction>) {
|
||||
let mut footer_action = None;
|
||||
let mut events = Vec::new();
|
||||
let mut list_resp = None;
|
||||
|
||||
let label = cx.label();
|
||||
let rows = ProfileRows { entries: &picker.entries, separator: picker.has_separator() };
|
||||
let paint = picker.paint;
|
||||
let actions = picker.actions;
|
||||
let builtin_aspect = profile_thumb_aspect();
|
||||
|
||||
Stack::new()
|
||||
.fill_width()
|
||||
.footer(|ui, _| {
|
||||
footer_action = show_footer(ui, actions);
|
||||
})
|
||||
.show(ui, |ui, _| {
|
||||
let mut list = List::<ProfileRowKey>::options(label.clone())
|
||||
.id(view.list_id)
|
||||
.header(false)
|
||||
.columns(vec![ColumnSpec::new(PROFILE_COL, Label::Empty, ColumnWidth::fill(1.0))])
|
||||
.hover_lead(HoverLead::Lead)
|
||||
.activate(ActivateOn::Click)
|
||||
.lead_on_open(LeadOnOpen::First)
|
||||
.selection(Bind::given(view.selection.clone()));
|
||||
if let Some(key) = view.reveal {
|
||||
list = list.reveal(key.clone());
|
||||
}
|
||||
|
||||
let out = list.show_items(ui, &rows, &mut |key, icx| {
|
||||
let ProfileRowKey::Profile(id) = key else {
|
||||
return ListRow::separator();
|
||||
};
|
||||
let Some(entry) = picker.option(id) else {
|
||||
return ListRow::spacer();
|
||||
};
|
||||
let points = entry.points.clone();
|
||||
if entry.built_in {
|
||||
ListRow::new(entry.label.clone()).option().cells(icx.cells()).thumb_aspect(
|
||||
ThumbSize::Small,
|
||||
builtin_aspect,
|
||||
move |painter, rect| paint(painter, rect, points.as_deref()),
|
||||
)
|
||||
} else {
|
||||
ListRow::new("").accessible_name(entry.label.clone()).option().cells(icx.cells()).cell_field(
|
||||
PROFILE_COL,
|
||||
ProfileGraphic::new(paint, points, SAVED_THUMB),
|
||||
|_| {},
|
||||
)
|
||||
}
|
||||
});
|
||||
events = out.events;
|
||||
list_resp = Some(out.response);
|
||||
});
|
||||
|
||||
let list_response = list_resp.unwrap_or_else(|| ui.response().clone());
|
||||
for event in &events {
|
||||
// Only a saved row has a menu: its one item deletes it, and a built-in can't be deleted.
|
||||
if let CollectionEvent::ContextMenu(request) = event
|
||||
&& let Some(id) = request.key.profile()
|
||||
&& view.saved.contains(id)
|
||||
{
|
||||
cx.memory::<PickerMemory>().menu = Some(id.to_owned());
|
||||
}
|
||||
}
|
||||
let menu_action = show_row_menu(ui, cx, picker, &list_response);
|
||||
(events, footer_action, menu_action)
|
||||
}
|
||||
|
||||
fn show_footer(ui: &mut egui::Ui, actions: ProfileActions) -> Option<ProfileAction> {
|
||||
// End-edge placement lays out actions from the right edge inward, so index 0 (`Reset Profiles`)
|
||||
// sits rightmost, with `Delete Profile` and `Add to Profiles` to its left.
|
||||
let bar = FooterBar::actions([
|
||||
FooterAction::new(IconId::new("rotate-ccw"), tl!("Reset Profiles")).enabled(actions.can_reset),
|
||||
FooterAction::new(IconId::new("trash-2"), tl!("Delete Profile")).enabled(actions.can_delete),
|
||||
FooterAction::new(IconId::new("dc-new-item"), tl!("Add to Profiles")).enabled(actions.can_add),
|
||||
])
|
||||
.show_footer(ui);
|
||||
|
||||
match bar.picked {
|
||||
Some(0) => Some(ProfileAction::Reset),
|
||||
Some(1) => Some(ProfileAction::Delete(None)),
|
||||
Some(2) => Some(ProfileAction::Add),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn show_row_menu(ui: &mut egui::Ui, cx: &mut Cx<'_, ProfileSelect>, picker: &ProfileSelect, anchor: &Response) -> Option<ProfileAction> {
|
||||
let target = cx.memory::<PickerMemory>().menu.clone()?;
|
||||
let Some(entry) = picker.option(&target).filter(|e| !e.built_in) else {
|
||||
cx.memory::<PickerMemory>().menu = None;
|
||||
return None;
|
||||
};
|
||||
let title = entry.label.clone();
|
||||
|
||||
let mut action = None;
|
||||
let shown = Menu::context(title, anchor).show(ui, |ui, _| {
|
||||
if MenuItem::new(tl!("Delete Profile")).show(ui).ran {
|
||||
action = Some(ProfileAction::Delete(Some(target.clone())));
|
||||
}
|
||||
});
|
||||
if action.is_some() || shown.closed.is_some() {
|
||||
cx.memory::<PickerMemory>().menu = None;
|
||||
}
|
||||
action
|
||||
}
|
||||
@@ -682,10 +682,8 @@ fn pattern_thumb_in(doc: &Document, cx: &ContentPainterCx<'_>, r: Rect, paint: &
|
||||
px,
|
||||
);
|
||||
let tex = CACHE.with(|c| c.borrow().get(&key).cloned()).unwrap_or_else(|| {
|
||||
let tex = vectorcraft_render::render_pattern_swatch(doc, pattern, px).map(|img| {
|
||||
let color = crate::canvas::color_image(&img);
|
||||
ctx.load_texture(format!("pattern-swatch-{pattern}-{px}"), color, egui::TextureOptions::LINEAR)
|
||||
});
|
||||
let tex = pattern_image(doc, pattern, px)
|
||||
.map(|color| ctx.load_texture(format!("pattern-swatch-{pattern}-{px}"), color, egui::TextureOptions::LINEAR));
|
||||
CACHE.with(|c| {
|
||||
let mut c = c.borrow_mut();
|
||||
if c.len() > 256 {
|
||||
@@ -701,6 +699,11 @@ fn pattern_thumb_in(doc: &Document, cx: &ContentPainterCx<'_>, r: Rect, paint: &
|
||||
true
|
||||
}
|
||||
|
||||
/// The swatch image of pattern `name` in `doc`, `px` pixels square; `None` when `doc` has no such pattern.
|
||||
fn pattern_image(doc: &Document, name: &str, px: u32) -> Option<egui::ColorImage> {
|
||||
vectorcraft_render::render_pattern_swatch_words(doc, name, px).map(crate::canvas::color_image_owned)
|
||||
}
|
||||
|
||||
/// The red of None's slash on a swatch tile and of a disabled opacity mask's cross, drawn on the document's white or
|
||||
/// black paper. It is the same in every theme.
|
||||
pub(super) const OFF_MARK: Color32 = Color32::from_rgb(0xe0, 0x20, 0x20);
|
||||
|
||||
@@ -1716,3 +1716,18 @@ fn idle_frames_replay_the_swatch_rows() {
|
||||
assert!(panel.shows(red), "and they show the swatch again");
|
||||
idle(&mut panel, "after an undo");
|
||||
}
|
||||
|
||||
/// A pattern swatch's image holds the pixels the swatch was rendered into; a pattern the document
|
||||
/// lacks has no image.
|
||||
#[test]
|
||||
fn a_pattern_swatch_image_is_handed_over_without_a_copy() {
|
||||
let mut app = app();
|
||||
let square = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap();
|
||||
app.run("object.pattern.make", json!({"ids": [square], "name": "Dots", "edit": false})).unwrap();
|
||||
let doc = doc(&app);
|
||||
crate::canvas::clear_handed_over();
|
||||
let image = pattern_image(&doc, "Dots", 24).expect("the pattern draws");
|
||||
assert_eq!(image.size, [24, 24], "the swatch's size");
|
||||
crate::canvas::assert_handed_over(&image, "the pattern swatch");
|
||||
assert!(pattern_image(&doc, "Missing", 24).is_none(), "no image for a pattern the document lacks");
|
||||
}
|
||||
@@ -100,7 +100,7 @@ impl ThumbSource<SymbolThumb> for SymbolPictures<'_> {
|
||||
render_art(&mut renderer, self.doc, self.name, vectorcraft_geom::Rect::new(x0, y0, x1, y1), (*w, *h))
|
||||
}
|
||||
};
|
||||
img.map_or(ThumbRender::Blank, |img| ThumbRender::Ready(crate::canvas::color_image(&img)))
|
||||
img.map_or(ThumbRender::Blank, |img| ThumbRender::Ready(crate::canvas::color_image_owned(img)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -198,7 +198,7 @@ pub(crate) mod counters {
|
||||
/// Symbol `name` of `doc` rendered `px` pixels wide: an instance at its natural size, alone on a
|
||||
/// copy of `doc` that keeps its resources (the symbols it nests, patterns, images, swatches,
|
||||
/// brushes, graphic styles) but none of its art.
|
||||
fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, name: &str, px: u32) -> Option<vectorcraft_render::Rendered> {
|
||||
fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, name: &str, px: u32) -> Option<vectorcraft_render::Rendered<Vec<u32>>> {
|
||||
let (w, h) = symbol_size(doc, name);
|
||||
let mut d = doc.clone();
|
||||
let layer = d.alloc_id();
|
||||
@@ -206,7 +206,7 @@ fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, name: &str
|
||||
let id = d.alloc_id();
|
||||
let xf = vectorcraft_geom::Affine::scale_non_uniform(w / 20.0, h / 20.0);
|
||||
d.insert(Some(layer), 0, Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf })).ok()?;
|
||||
r.render_thumbnail(&d, id, px)
|
||||
r.render_thumbnail_words(&d, id, px)
|
||||
}
|
||||
|
||||
/// Symbol `name` of `doc` (an instance at its natural size, as [`render_thumb`] places it) drawn
|
||||
@@ -218,7 +218,7 @@ fn render_art(
|
||||
name: &str,
|
||||
art: vectorcraft_geom::Rect,
|
||||
(w, h): (u32, u32),
|
||||
) -> Option<vectorcraft_render::Rendered> {
|
||||
) -> Option<vectorcraft_render::Rendered<Vec<u32>>> {
|
||||
let (aw, ah) = (art.width(), art.height());
|
||||
if !(aw.is_finite() && ah.is_finite() && aw > 0.0 && ah > 0.0) {
|
||||
return None;
|
||||
@@ -232,7 +232,7 @@ fn render_art(
|
||||
let n = Arc::new(Node::new(id, NodeKind::SymbolInstance { symbol: name.into(), xf }));
|
||||
let view =
|
||||
vectorcraft_geom::Affine::scale_non_uniform(f64::from(w) / aw, f64::from(h) / ah) * vectorcraft_geom::Affine::translate((-art.x0, -art.y0));
|
||||
r.render_node(&d, &n, u16::try_from(w).ok()?, u16::try_from(h).ok()?, view)
|
||||
r.render_node_words(&d, &n, u16::try_from(w).ok()?, u16::try_from(h).ok()?, view)
|
||||
}
|
||||
|
||||
/// The active document's current symbol (`symbol.list`'s `current`), read without running a
|
||||
|
||||
@@ -13,8 +13,9 @@ fn symbols(app: &mut VectorcraftApp) -> Vec<String> {
|
||||
}
|
||||
|
||||
/// Pixels of `img` that something paints opaquely, and those of them that are red.
|
||||
fn painted(img: &vectorcraft_render::Rendered) -> (usize, usize) {
|
||||
let painted: Vec<&[u8; 4]> = img.pixels.as_chunks::<4>().0.iter().filter(|p| p[3] > 200).collect();
|
||||
fn painted(img: &vectorcraft_render::Rendered<Vec<u32>>) -> (usize, usize) {
|
||||
let bytes: &[u8] = bytemuck::cast_slice(&img.pixels);
|
||||
let painted: Vec<&[u8; 4]> = bytes.as_chunks::<4>().0.iter().filter(|p| p[3] > 200).collect();
|
||||
let red = painted.iter().filter(|p| p[0] > 150 && p[1] < 80 && p[2] < 80).count();
|
||||
(painted.len(), red)
|
||||
}
|
||||
@@ -1320,6 +1321,26 @@ fn an_imported_symbols_thumbnail_frames_its_whole_art() {
|
||||
assert!(orange(inset_x, inset_y) && orange(w - 1 - inset_x, h - 1 - inset_y), "{w} × {h}");
|
||||
}
|
||||
|
||||
/// Both pictures of a symbol become images in the pixels they were rendered into.
|
||||
#[test]
|
||||
fn a_symbols_pictures_are_handed_to_their_images_without_a_copy() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 200, "height": 200})).unwrap();
|
||||
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap();
|
||||
s.execute("symbol.new", &json!({"name": "Wide"})).unwrap();
|
||||
let doc = &*s.doc().unwrap().doc;
|
||||
let art = vectorcraft_effects::graphic_bounds(doc, "Wide").expect("the art's bounds");
|
||||
let pictures = SymbolPictures { doc, name: "Wide" };
|
||||
for (what, key) in [
|
||||
("the symbol", SymbolThumb::Symbol { key: 1 }),
|
||||
("its art", SymbolThumb::Art { key: 1, w: 40, h: 30, art: [art.x0, art.y0, art.x1, art.y1].map(f64::to_bits) }),
|
||||
] {
|
||||
crate::canvas::clear_handed_over();
|
||||
let ThumbRender::Ready(image) = pictures.render(&key, &ThumbRequest::for_cell(40.0, 1.0)) else { panic!("{what} renders at once") };
|
||||
crate::canvas::assert_handed_over(&image, what);
|
||||
}
|
||||
}
|
||||
|
||||
/// A document with symbol "Leaf", whose instance stands where its rectangle was, and symbol
|
||||
/// "Dot", which no instance uses; "Dot" is current.
|
||||
fn leaf_and_dot() -> VectorcraftApp {
|
||||
|
||||
@@ -11,7 +11,7 @@ use craft::ui::runtime::commands::CommandStates;
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use super::asset_export::{menu_rows, menu_states};
|
||||
use super::asset_export::{menu_rows, menu_states, thumb_image};
|
||||
use crate::dialogs::ExportForScreensDialog;
|
||||
use crate::tests::panel_harness::Panel;
|
||||
use crate::{Services, VectorcraftApp};
|
||||
@@ -1158,3 +1158,19 @@ fn tile_menu_collects_canvas_art_as_one_or_multiple_assets_and_disables_empty_se
|
||||
assert_eq!(picked(&p).len(), if single { 1 } else { 2 });
|
||||
}
|
||||
}
|
||||
|
||||
/// A tile's image is made in the words its objects were rendered into, for one object and for several.
|
||||
#[test]
|
||||
fn an_assets_tile_image_holds_the_rendered_words_without_a_copy() {
|
||||
let (app, _, [a, b]) = app(false);
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
let node = |id: u64| doc.node(vectorcraft_doc::NodeId(id)).expect("the square");
|
||||
let mut r = vectorcraft_render::Renderer::new();
|
||||
for (what, art) in [("one object", vec![node(a)]), ("two objects", vec![node(a), node(b)])] {
|
||||
crate::canvas::clear_handed_over();
|
||||
let image = thumb_image(&mut r, doc, &art, 40).expect("the squares draw");
|
||||
assert_eq!(image.size, [40, 40], "{what}: the tile's size");
|
||||
assert!(image.pixels.iter().any(|p| p.a() > 0), "{what}: the tile shows the art");
|
||||
crate::canvas::assert_handed_over(&image, what);
|
||||
}
|
||||
}
|
||||
@@ -320,3 +320,218 @@ fn arrowhead_select_lists_the_notched_arrow_after_arrow() {
|
||||
panel.click("Notched Arrow");
|
||||
assert_eq!(current_stroke(&panel.app()).and_then(|s| s.end_arrow), Some(vectorcraft_doc::Arrowhead::NotchedArrow));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropdown_footer_manages_profiles_and_confirms_reset() {
|
||||
use craft::ui::contract::Role;
|
||||
use craft::ui::dialog::StackDialog as _;
|
||||
|
||||
let mut session = vectorcraft_engine::Session::new();
|
||||
session.execute("file.new", &serde_json::json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = session.execute("shape.rectangle", &serde_json::json!({"x": 20, "y": 20, "width": 100, "height": 80})).unwrap()["id"].as_u64().unwrap();
|
||||
session.execute("stroke.set", &serde_json::json!({"weight": 6.0, "profile": "taperStart"})).unwrap();
|
||||
|
||||
let app = crate::VectorcraftApp::new(session, Default::default());
|
||||
let mut panel = crate::tests::panel_harness::Panel::new(app, super::stroke::profile_select);
|
||||
|
||||
assert!(panel.rect("Profile").width() <= 165.0, "closed dropdown shrinks to compact width: {:?}", panel.rect("Profile"));
|
||||
panel.click_role("Profile", Role::COMBO_BOX);
|
||||
assert!(!panel.shows("Flip Along"), "Flip Along button is not shown inside the dropdown");
|
||||
assert!(!panel.shows("Flip Across"), "Flip Across button is not shown inside the dropdown");
|
||||
assert!(panel.shows("Add to Profiles"), "dropdown shows Add to Profiles footer button");
|
||||
assert!(panel.shows("Delete Profile"), "dropdown shows Delete Profile footer button");
|
||||
assert!(panel.shows("Reset Profiles"), "dropdown shows Reset Profiles footer button");
|
||||
assert!(!panel.enabled("Delete Profile"), "a built-in profile can't be deleted");
|
||||
assert!(
|
||||
panel.rect("Reset Profiles").left() >= panel.rect("Delete Profile").right() - 0.5
|
||||
&& panel.rect("Delete Profile").left() >= panel.rect("Add to Profiles").right() - 0.5,
|
||||
"Reset Profiles sits rightmost in the footer"
|
||||
);
|
||||
assert!(panel.rect("Wave").width() <= 165.0, "dropdown shrinks to fit its items: {:?}", panel.rect("Wave"));
|
||||
|
||||
// Selecting Uniform disables Delete Profile; Uniform cannot be deleted.
|
||||
panel.click("Uniform");
|
||||
panel.click_role("Profile", Role::COMBO_BOX);
|
||||
assert!(!panel.enabled("Delete Profile"), "Uniform profile cannot be deleted");
|
||||
|
||||
// Custom profile: Add to Profiles asks for a name and saves the profile under it, and user-added rows hide
|
||||
// their text captions in the dropdown.
|
||||
panel.app().session.execute("stroke.widthPoint.set", &serde_json::json!({"id": id, "t": 0.35, "left": 12.0, "right": 3.0})).unwrap();
|
||||
panel.frame();
|
||||
assert_eq!(panel.value_role("Profile", Role::COMBO_BOX).as_deref(), Some("Custom"));
|
||||
panel.click("Add to Profiles");
|
||||
assert!(panel.app().session.prefs.width_profiles.is_empty(), "Add to Profiles saves nothing before the name is given");
|
||||
{
|
||||
let mut app = panel.app();
|
||||
let dialog = crate::tests::picks::open_dialogs(&app).first().map(|d| d.id).expect("Add to Profiles asks for a name");
|
||||
crate::tests::picks::answer_dialog(&mut app, dialog, &[("name", serde_json::json!("Ribbon"))], true);
|
||||
}
|
||||
panel.frame();
|
||||
let saved_label = panel.app().session.profile_entries().find(|e| !e.built_in).map(|e| e.label.to_owned()).unwrap();
|
||||
assert_eq!(saved_label, "Ribbon", "the profile is saved under the name given");
|
||||
// The name dialog may have closed the list on taking focus; the checks below read the open list.
|
||||
if !panel.shows("Reset Profiles") {
|
||||
panel.click_role("Profile", Role::COMBO_BOX);
|
||||
}
|
||||
assert!(panel.enabled("Delete Profile"), "the saved profile the stroke uses can be deleted");
|
||||
let face_rect = panel.rect("Profile");
|
||||
let popup_captions: Vec<_> = panel.painted(&saved_label).into_iter().filter(|r| !face_rect.contains(r.center())).collect();
|
||||
assert!(popup_captions.is_empty(), "user-added profile shows no caption text in the pulldown: {popup_captions:?}");
|
||||
assert!(!panel.painted("Wave").is_empty(), "built-in profile still shows its caption text");
|
||||
|
||||
// No three-dot menu buttons appear next to any profile row.
|
||||
assert!(!panel.shows("More (Uniform)"));
|
||||
assert!(!panel.shows("More (Wave)"));
|
||||
assert!(!panel.shows(&format!("More ({saved_label})")));
|
||||
|
||||
// Clicking Reset Profiles closes the dropdown and opens the confirmation prompt ("Do you want to reset profiles?").
|
||||
panel.click("Reset Profiles");
|
||||
assert!(!panel.shows("Add to Profiles"), "dropdown closes when confirmation prompt opens");
|
||||
let ctx = panel.ctx().clone();
|
||||
{
|
||||
let mut app = panel.app();
|
||||
let (message, _, command) = crate::dialogs::confirm::open_question(&app).expect("reset confirmation is open");
|
||||
assert_eq!(message, "Do you want to reset profiles?");
|
||||
assert_eq!(command, "stroke.widthProfile.reset");
|
||||
app.dialogs().unwrap().with(|host| {
|
||||
let qid = host.get::<crate::dialogs::confirm::Question>().expect("reset confirmation is open").id();
|
||||
assert!(host.cancel_by_id(&ctx, qid));
|
||||
});
|
||||
crate::dialogs::confirm::pump(&mut app, &ctx);
|
||||
assert!(app.session.profile_entries().any(|e| !e.built_in), "cancelling reset preserves profiles");
|
||||
}
|
||||
|
||||
// Confirming OK executes the reset.
|
||||
panel.click_role("Profile", Role::COMBO_BOX);
|
||||
panel.click("Reset Profiles");
|
||||
let mut app = panel.app();
|
||||
app.dialogs().unwrap().with(|host| {
|
||||
let qid = host.get::<crate::dialogs::confirm::Question>().expect("reset confirmation is open").id();
|
||||
host.set_json_field(&ctx, qid, "choice", serde_json::json!("proceed")).unwrap();
|
||||
assert!(host.confirm_by_id(&ctx, qid));
|
||||
});
|
||||
crate::dialogs::confirm::pump(&mut app, &ctx);
|
||||
assert!(app.session.profile_entries().all(|e| e.built_in), "Reset Profiles clears saved presets");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropdown_row_menu_deletes_saved_profiles_only() {
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
let mut session = vectorcraft_engine::Session::new();
|
||||
session.execute("file.new", &serde_json::json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = session.execute("shape.rectangle", &serde_json::json!({"x": 20, "y": 20, "width": 100, "height": 80})).unwrap()["id"].as_u64().unwrap();
|
||||
session.execute("stroke.set", &serde_json::json!({"weight": 6.0})).unwrap();
|
||||
session.execute("stroke.widthPoint.set", &serde_json::json!({"id": id, "t": 0.35, "left": 12.0, "right": 3.0})).unwrap();
|
||||
session.execute("stroke.widthProfile.add", &serde_json::json!({"name": "Mine"})).unwrap();
|
||||
|
||||
let app = crate::VectorcraftApp::new(session, Default::default());
|
||||
let mut panel = crate::tests::panel_harness::Panel::new(app, super::stroke::profile_select);
|
||||
panel.click_role("Profile", Role::COMBO_BOX);
|
||||
|
||||
// A built-in row offers no Delete Profile.
|
||||
for built_in in ["Uniform", "Wave"] {
|
||||
panel.secondary_click(built_in);
|
||||
assert!(!panel.shows_role("Delete Profile", Role::MENU_ITEM), "{built_in} can't be deleted");
|
||||
}
|
||||
|
||||
// A saved row's menu deletes it.
|
||||
panel.secondary_click("Mine");
|
||||
assert!(panel.shows_role("Delete Profile", Role::MENU_ITEM), "a saved profile offers Delete Profile");
|
||||
panel.click_menu_item("Delete Profile");
|
||||
assert!(!panel.app().session.profile_entries().any(|e| e.id == "Mine"), "the saved profile is deleted");
|
||||
assert!(panel.app().session.profile_entries().any(|e| e.id == "wave"), "the built-ins stay");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropdown_expands_into_available_vertical_space() {
|
||||
use craft::ui::contract::Role;
|
||||
|
||||
let mut session = vectorcraft_engine::Session::new();
|
||||
session.execute("file.new", &serde_json::json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = session.execute("shape.rectangle", &serde_json::json!({"x": 20, "y": 20, "width": 100, "height": 80})).unwrap()["id"].as_u64().unwrap();
|
||||
session.execute("stroke.set", &serde_json::json!({"weight": 6.0})).unwrap();
|
||||
for i in 0..10 {
|
||||
session
|
||||
.execute(
|
||||
"stroke.widthPoint.set",
|
||||
&serde_json::json!({"id": id, "t": 0.25 + 0.05 * f64::from(i), "left": 8.0 + f64::from(i), "right": 4.0}),
|
||||
)
|
||||
.unwrap();
|
||||
session.execute("stroke.widthProfile.add", &serde_json::json!({"name": format!("Saved {i}")})).unwrap();
|
||||
}
|
||||
|
||||
let app = crate::VectorcraftApp::new(session, Default::default());
|
||||
let mut panel = crate::tests::panel_harness::Panel::new(app, super::stroke::profile_select);
|
||||
|
||||
assert!(panel.rect("Profile").width() <= 165.0, "closed dropdown stays compact even with custom profiles: {:?}", panel.rect("Profile"));
|
||||
panel.click_role("Profile", Role::COMBO_BOX);
|
||||
assert!(panel.shows("Saved 9"), "dropdown expands past 12 rows when space is available");
|
||||
assert!(
|
||||
panel.rect("Saved 9").bottom() - panel.rect("Uniform").top() > 350.0,
|
||||
"dropdown opens taller when vertical space allows: uniform={:?}, last={:?}",
|
||||
panel.rect("Uniform"),
|
||||
panel.rect("Saved 9")
|
||||
);
|
||||
assert!(panel.shows("Reset Profiles"), "footer remains visible with expanded list");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dropdown_keeps_sentinel_named_profile_interactive_and_commits_tab_preview() {
|
||||
use craft::ui::contract::Role;
|
||||
use egui::{Key, Modifiers};
|
||||
|
||||
let mut session = vectorcraft_engine::Session::new();
|
||||
session.execute("file.new", &serde_json::json!({"width": 400, "height": 400})).unwrap();
|
||||
let id = session.execute("shape.rectangle", &serde_json::json!({"x": 20, "y": 20, "width": 100, "height": 80})).unwrap()["id"].as_u64().unwrap();
|
||||
session.execute("stroke.set", &serde_json::json!({"weight": 6.0})).unwrap();
|
||||
session.execute("stroke.widthPoint.set", &serde_json::json!({"id": id, "t": 0.35, "left": 12.0, "right": 3.0})).unwrap();
|
||||
session.execute("stroke.widthProfile.add", &serde_json::json!({"name": "__profile_separator__"})).unwrap();
|
||||
session.execute("stroke.set", &serde_json::json!({"profile": "uniform"})).unwrap();
|
||||
|
||||
let app = crate::VectorcraftApp::new(session, Default::default());
|
||||
let mut panel = crate::tests::panel_harness::Panel::new(app, super::stroke::profile_select);
|
||||
|
||||
// A saved profile literally named "__profile_separator__" stays selectable and applies.
|
||||
panel.click_role("Profile", Role::COMBO_BOX);
|
||||
assert!(panel.shows("__profile_separator__"));
|
||||
panel.click("__profile_separator__");
|
||||
assert_eq!(panel.value_role("Profile", Role::COMBO_BOX).as_deref(), Some("__profile_separator__"));
|
||||
|
||||
// Keyboard preview followed by Tab commits the previewed profile instead of cancelling it.
|
||||
panel.click_role("Profile", Role::COMBO_BOX);
|
||||
panel.click("Uniform");
|
||||
panel.click_role("Profile", Role::COMBO_BOX);
|
||||
panel.key(Key::ArrowDown, Modifiers::NONE);
|
||||
assert_eq!(panel.value_role("Profile", Role::COMBO_BOX).as_deref(), Some("Lens"));
|
||||
panel.key(Key::Tab, Modifiers::NONE);
|
||||
assert_eq!(panel.value_role("Profile", Role::COMBO_BOX).as_deref(), Some("Lens"));
|
||||
|
||||
// A fractional scroll-wheel delta steps the closed profile control cleanly.
|
||||
let face_center = panel.rect("Profile").center();
|
||||
panel.scroll_at(face_center, -0.5);
|
||||
assert_ne!(panel.value_role("Profile", Role::COMBO_BOX).as_deref(), Some("Lens"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_screen_reader_sets_and_steps_the_profile() {
|
||||
use craft::ui::contract::Role;
|
||||
use craft::ui::testing::focus::AccessActionKind;
|
||||
|
||||
let mut panel = Panel::new(app_with_line(), stroke::profile_select);
|
||||
let picked = |panel: &Panel| current_stroke(&panel.app()).and_then(|s| s.profile);
|
||||
let preset = |id: &str| WidthProfile::PRESETS.iter().find(|p| p.id == id).map(|p| p.points.to_vec());
|
||||
|
||||
// The value is the row's place in the list: Uniform, Lens, Taper Start, ...
|
||||
let numeric = panel.numeric_role("Profile", Role::COMBO_BOX).expect("the drop-down reports a numeric value");
|
||||
assert_eq!(numeric.value, Some(0.0), "Uniform is the first row");
|
||||
assert_eq!(*numeric.range.end(), (WidthProfile::PRESETS.len() - 1) as f64, "the range ends at the last row");
|
||||
assert_eq!(numeric.text.as_deref(), Some("Uniform"), "the value reads as the row's label");
|
||||
panel.access_role("Profile", Role::COMBO_BOX, AccessActionKind::SetValue(2.0));
|
||||
assert_eq!(picked(&panel).map(|p| p.points), preset("taperStart"), "SetValue picks the third row");
|
||||
assert_eq!(panel.numeric_role("Profile", Role::COMBO_BOX).and_then(|n| n.value), Some(2.0), "the value follows the pick");
|
||||
panel.access_role("Profile", Role::COMBO_BOX, AccessActionKind::Decrement);
|
||||
assert_eq!(picked(&panel).map(|p| p.points), preset("lens"), "Decrement picks the row above");
|
||||
panel.access_role("Profile", Role::COMBO_BOX, AccessActionKind::Increment);
|
||||
assert_eq!(picked(&panel).map(|p| p.points), preset("taperStart"), "Increment picks the row below");
|
||||
}
|
||||
@@ -122,8 +122,8 @@ fn thumb_image(doc: &Arc<Document>, obj: &Node, own_mask: bool, px: u32, bg: Opt
|
||||
} else {
|
||||
obj
|
||||
};
|
||||
let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail_with(doc, n, px.max(8), bg, &super::layers::thumb_options()))?;
|
||||
Some(crate::canvas::color_image(&img))
|
||||
let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail_words_with(doc, n, px.max(8), bg, &super::layers::thumb_options()))?;
|
||||
Some(crate::canvas::color_image_owned(img))
|
||||
}
|
||||
|
||||
impl ThumbSource<MaskKey> for MaskThumbs<'_> {
|
||||
@@ -914,6 +914,25 @@ mod tests {
|
||||
assert!(Arc::ptr_eq(&undone, &held(&app, n.id)), "the node Undo put back");
|
||||
}
|
||||
|
||||
/// The object and mask thumbnails, on a background or none, hold the pixels they were rendered into.
|
||||
#[test]
|
||||
fn object_and_mask_thumbnails_are_handed_to_their_images_without_a_copy() {
|
||||
let mut app = new_app();
|
||||
let a = run_cmd(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone();
|
||||
let b = run_cmd(&mut app, "shape.ellipse", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].clone();
|
||||
run_cmd(&mut app, "select.set", json!({"ids": [a, b]}));
|
||||
run_cmd(&mut app, "transparency.makeOpacityMask", json!({}));
|
||||
let n = state(&mut app).1.expect("the masked object");
|
||||
let doc = app.session.active().unwrap().doc.clone();
|
||||
for own_mask in [false, true] {
|
||||
for bg in [None, Some([255; 4])] {
|
||||
crate::canvas::clear_handed_over();
|
||||
let image = thumb_image(&doc, &n, own_mask, 44, bg).expect("the thumbnail draws");
|
||||
crate::canvas::assert_handed_over(&image, &format!("mask {own_mask}, background {bg:?}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_highlighted_blend_mode_applies_only_once_it_is_chosen() {
|
||||
use egui::{Key, Modifiers};
|
||||
|
||||
@@ -997,6 +997,10 @@ pub struct UiState {
|
||||
/// The Text Import Options confirmed last (`file.place`'s `text` options; null: never used).
|
||||
#[serde(default, skip_serializing_if = "Value::is_null")]
|
||||
pub text_import: Value,
|
||||
/// The text files File › Open opened while Text Import Options was already open, each asked
|
||||
/// about once it closes, the next one first.
|
||||
#[serde(skip)]
|
||||
pub(crate) text_opens: Vec<crate::dialogs::text_import::TextOpen>,
|
||||
/// The documents (uids) whose Missing Fonts dialog waits until no dialog is open, the next one to
|
||||
/// show first.
|
||||
#[serde(skip)]
|
||||
@@ -1635,6 +1639,7 @@ impl Default for UiState {
|
||||
place_link: true,
|
||||
place_import_options: true,
|
||||
text_import: Value::Null,
|
||||
text_opens: vec![],
|
||||
pending_fonts: vec![],
|
||||
stopped_plugin: None,
|
||||
proof_setup: None,
|
||||
|
||||
@@ -298,6 +298,15 @@ impl Panel {
|
||||
self.after();
|
||||
}
|
||||
|
||||
/// A screen reader's action `kind` on the control of `role` named `name`.
|
||||
pub(crate) fn access_role(&mut self, name: &str, role: Role, kind: craft::ui::testing::focus::AccessActionKind) {
|
||||
self.frame();
|
||||
let target = self.look_role(name, role);
|
||||
self.take_input();
|
||||
self.fixture.access(kind, &target);
|
||||
self.after();
|
||||
}
|
||||
|
||||
/// Turns the wheel by `dy` points over `at`.
|
||||
pub(crate) fn scroll_at(&mut self, at: Pos2, dy: f32) {
|
||||
self.frame_with(vec![Event::PointerMoved(at)]);
|
||||
@@ -486,6 +495,11 @@ impl Panel {
|
||||
self.fixture.tree().value_of(self.look_role(name, role).node).map(str::to_owned)
|
||||
}
|
||||
|
||||
/// The numeric value, range and step that the control of `role` named `name` reports to screen readers.
|
||||
pub(crate) fn numeric_role(&self, name: &str, role: Role) -> Option<craft::ui::contract::Numeric> {
|
||||
self.fixture.tree().numeric_of(self.look_role(name, role).node)
|
||||
}
|
||||
|
||||
/// Whether a label named `name` has exactly `value`, where a field's static label may share its name and role.
|
||||
pub(crate) fn label_has_value(&self, name: &str, value: &str) -> bool {
|
||||
let tree = self.fixture.tree();
|
||||
|
||||
+7
-3
@@ -296,8 +296,12 @@ other `sv-*` locale resolve to it), Georgian (`ka`, complete; `ka-GE` and `ka_GE
|
||||
once the menus and `tl!` literals are translated; the untranslated report then lists what the catalog lacks
|
||||
(`VECTORCRAFT_I18N_DUMP=strings.txt cargo test -p vectorcraft-ui-egui dump_source_strings -- --ignored` lists every
|
||||
English string).
|
||||
- A missing translation never fails a test or a build: the interface shows the English text until a translator
|
||||
adds the row. `cargo xtask i18n-report` prints, per language, the strings its catalog lacks (menu strings,
|
||||
- A missing translation shows the English text until a translator adds the row, and fails no build. A few tests
|
||||
do fail on a missing row: every catalog with `complete_menus` needs the `UI_STRINGS` rows
|
||||
(`strings_the_ui_shows_are_in_every_complete_catalog`) and the save panel's file types
|
||||
(`save_panel_file_types_are_in_complete_catalogs`), and every language in `COMPLETE_MESSAGES` needs the
|
||||
cutting-banner and recovery messages (`banner_and_recovery_messages_are_translated_in_every_complete_catalog`)
|
||||
and the script warning question (`script_warning_off_question_is_translated`). `cargo xtask i18n-report` prints, per language, the strings its catalog lacks (menu strings,
|
||||
`tl!` literals, undo step names, menu labels, render-site labels, status and error messages, PostScript
|
||||
error meanings, default swatch names), and `cargo xtask ci` prints the same list in its `i18n-report` step.
|
||||
The report is the test `i18n::tests::untranslated_report`, run with `--nocapture`; it fails only when a
|
||||
@@ -319,7 +323,7 @@ other `sv-*` locale resolve to it), Georgian (`ka`, complete; `ka-GE` and `ka_GE
|
||||
``[{j}] `{_1}`: {why}``, so its reason is translated while a JSON array stays as it is. A literal brace in a
|
||||
row is written `{{` or `}}`, in the English and in the translation: a message made with `format!` keeps the
|
||||
doubled braces of its format string, and a plain string literal has each of its braces doubled, so the row for
|
||||
`"expected {\"objects\": [...]}"` is `expected {{"objects": [...]}}`. Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Vietnamese, Finnish, Turkish, Catalan, Dutch, Danish, Indonesian and Bulgarian
|
||||
`"expected {\"objects\": [...]}"` is `expected {{"objects": [...]}}`. Czech, German, Greek, Spanish, French, Georgian, Hindi, Hungarian, Italian, Japanese, Korean, Polish, Brazilian Portuguese, Russian, Simplified Chinese, Traditional Chinese, Swedish, Ukrainian, Vietnamese, Finnish, Turkish, Catalan, Dutch, Danish, Indonesian, Bulgarian and Gujarati
|
||||
translate status and error messages (`COMPLETE_MESSAGES` in `i18n::tests`); the untranslated report lists the
|
||||
message literals the scan finds, and the phrases a parameter schema's error builds at run time
|
||||
(`SCHEMA_PHRASES`), that one of them has no row for. The scan covers the crates in `MESSAGE_CRATES`, the
|
||||
|
||||
@@ -389,10 +389,10 @@ Gradient meshes in the editing data keep each point's own color where a patch's
|
||||
| FreeHand `.fh*` | open (legacy) | no | no | |
|
||||
| `.cdr` drawings | open | yes (versions 1 to 27, the `WL` files of versions 1 and 2 and the ZIP packages of versions 14 on included: pages, layers, guidelines, groups, clipping containers, curves, paths, rectangles, ellipses, arcs, polygons, uniform fills and outlines, from the object's style where it has none of its own; hidden and locked layers, groups and objects; the winding flag as the nonzero fill rule; uniform transparency of version 13 on as opacity and blend mode; text, bitmaps, blends, contours, brush strokes, fountain, pattern, texture and PostScript fills and arrowheads are left out with a warning, and lenses, other transparency and merge modes without a blend mode are not applied, with a warning; versions 1 and 2 open as one page and one layer without groups, arcs or pies; version 3 envelopes are not applied, so the objects and groups under one keep their outlines and matrices, with a warning; encrypted, ZIP64 and split packages are refused) | no | `.cdt` templates open as new untitled documents; File › Place reads both; after an open with a warning, an export or Save As to the drawing's own path needs `acknowledgeLoss: true`; record layouts and their sources in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`); synthetic test files only; tests in `craft-cdr` `crates/cdr/tests/it/read.rs`, `crates/engine/src/cmd/fileio/tests_cdr.rs` and `crates/engine/tests/import_fuzz.rs` |
|
||||
| `.cmx` exchange files | | yes (files with 32-bit coordinates: pages, layers, groups, curves, uniform fills and outlines with their width, color, caps, joins and dashes; text, images, rectangles, ellipses, clipping paths, other fills and arrowheads are left out with a warning, and lenses are not applied, with a warning; big-endian files and files with 16-bit coordinates are refused) | yes (one file with a page for the artboard, or for each chosen artboard with Use Artboards, and a layer for each layer with art on the page: fills and strokes as curves in CMYK, RGB, gray, spot colors at their tints and Registration, with stroke widths, caps, joins and dashes in whole stroke widths; type as outlines, gradients and patterns as one color, nonzero fills as even-odd; images, clipping masks and transparency are left out with a warning) | File › Place reads them too; after an open with a warning, an export or Save As to the file's own path needs `acknowledgeLoss: true`; layouts and their sources in `craft-cdr` (`storytold/craft-libs@9b28b56bc7`, `crates/cdr/PROVENANCE.md`, R53 to R63; the writer's fields under Written fields at `storytold/craft-libs@51fcc3b041`); synthetic test files only; tests in `craft-cdr` `crates/cdr/tests/it/cmx.rs` and `crates/cdr/tests/it/cmx_write.rs`, `crates/engine/src/cmd/fileio/tests_cmx.rs` and `crates/engine/tests/import_fuzz.rs` |
|
||||
| Text `.txt` | place, export | place (Text Import Options) | yes | place reads Unicode and ANSI, and Shift JIS, GB2312, Chinese Big 5, Cyrillic, GB18030, Greek, Turkish, Baltic and Central European through the WHATWG Encoding Standard's decoders (VectorCraft's own mapping); `tests/textimport.rs`, `place/text.rs`; fuzzed (`text_import_fuzz.rs`) |
|
||||
| RTF `.rtf` | place | place (area type with fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/rtf.rs`; fuzzed (`text_import_fuzz.rs`); `\'hh` bytes read as Windows-1252 or Mac Roman only |
|
||||
| Word `.docx` | place | place (area type with the document's styles and its fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/docx.rs`; fuzzed (`text_import_fuzz.rs`); list numbers, pictures and text boxes are left out |
|
||||
| Word `.doc` | place | place (area type with the same formatting as `.docx`, from the style sheet's styles and direct formatting; Word 97 and later) | no | `tests/textimport.rs`, `place/doc.rs`; fuzzed (`text_import_fuzz.rs`); pictures, headers, footers, notes, comments and text boxes are left out with a warning; encrypted and fast-saved documents are refused |
|
||||
| Text `.txt` | place, export | open as a new letter-size document, place (Text Import Options for both) | yes | place reads Unicode and ANSI, and Shift JIS, GB2312, Chinese Big 5, Cyrillic, GB18030, Greek, Turkish, Baltic and Central European through the WHATWG Encoding Standard's decoders (VectorCraft's own mapping); `tests/textimport.rs`, `place/text.rs`; fuzzed (`text_import_fuzz.rs`) |
|
||||
| RTF `.rtf` | place | open as a new letter-size document, place (area type with fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/rtf.rs`; fuzzed (`text_import_fuzz.rs`); `\'hh` bytes read as Windows-1252 or Mac Roman only; open refuses a file that ends inside a group, and place takes the text read before the end |
|
||||
| Word `.docx` | place | open as a new letter-size document, place (area type with the document's styles and its fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/docx.rs`; fuzzed (`text_import_fuzz.rs`); list numbers, pictures and text boxes are left out |
|
||||
| Word `.doc` | place | open as a new letter-size document, place (area type with the same formatting as `.docx`, from the style sheet's styles and direct formatting; Word 97 and later) | no | `tests/textimport.rs`, `place/doc.rs`; fuzzed (`text_import_fuzz.rs`); pictures, headers, footers, notes, comments and text boxes are left out with a warning; encrypted and fast-saved documents are refused |
|
||||
| CSS | export (CSS Properties) | — | yes | |
|
||||
| OBJ / USDA / glTF | 3D export | — | yes, also USDZ (a 3D asset of Asset Export: `assets.add3D`, `assets.export3D`) | each solid of an object with Extrude & Bevel, Revolve, Inflate or Rotate is a triangle mesh of its faces before projection, at the object's 3D rotation, y up, with a two-sided material in its paint's color; glTF 2.0 is one `.gltf` with its buffer embedded, in meters; USDA and OBJ are in points (USDA says its `metersPerUnit`), OBJ with an `.mtl`; USDZ stores the USDA uncompressed on a 64-byte boundary; tests in `crates/three-d/src/mesh/tests.rs`, `crates/engine/src/cmd/fileio/mesh3d/tests.rs` and `crates/engine/src/tests/assets_3d.rs` |
|
||||
| Affinity `.af`, `.afdesign`, `.afpub` | no | yes (beyond Illustrator) | no (#665) | 51 pinned files, [affinity-validation.md](affinity-validation.md) |
|
||||
|
||||
@@ -24,7 +24,7 @@ English) in-app help, and the docs are English.
|
||||
(`bflatastic`), with community contributors adding or correcting (German by `dwetscher`, Japanese and Traditional
|
||||
Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded as reviewed by native speakers; the contributor approved all 387 later Gujarati additions on 2026-11-14.
|
||||
|
||||
> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, and since 2026-12-02 the web build fetches it when the interface needs it (`crates/text/web-fonts.txt`, `demand`), so Gujarati can be selected on the web. Scores and estimates unchanged.
|
||||
> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status and error messages: 4,946 `@msg` and 56 `@msgplural` rows (2026-12-02); with 155 menu, label and undo rows added the same day the catalog has 10,890 rows; all machine-assisted, native review pending; `gu` is in `COMPLETE_MESSAGES`. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, and since 2026-12-02 the web build fetches it when the interface needs it (`crates/text/web-fonts.txt`, `demand`), so a web build made with `CRAFT_FONTS_DIR` pointing at a craft-fonts checkout that has Noto Sans Gujarati offers Gujarati; a web build without it does not. Scores and estimates unchanged.
|
||||
|
||||
## The thirteen key languages
|
||||
|
||||
@@ -34,7 +34,7 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a
|
||||
| Simplified Chinese (Mandarin) | `zh-hans` | 9,625 rows, 3,735 of them `@msg` and 51 `@msgplural` (counted 2026-11-17 on `main` at `ee60c51fd9`) | all (the untranslated report lists 237 messages without a row for it) | CJK UI font from craft-fonts (BIZ UDPGothic) when embedded, else a system font; IME with marked text at the caret; vertical type partial ([type-parity.md](type-parity.md)) | no | full | — (review) |
|
||||
| Spanish | `es` | 4,009 / 4,020 (99.7%) | all (3,770 `@msg` and 55 `@msgplural` rows, counted 2026-11-18: the untranslated report lists 269 messages without a Spanish row, 236 in its own section and 33 that all 24 checked languages lack) | Latin | no | full | — (review) |
|
||||
| Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; the web fetches Noto Sans Devanagari when the interface needs it | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review and layout |
|
||||
| Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback (Noto Sans Gujarati, in the pinned CI/release fonts); the web fetches Noto Sans Gujarati when the interface needs it | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages |
|
||||
| Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus, dialogs, status and error messages (messages machine-assisted, review pending) | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback (Noto Sans Gujarati, in the pinned CI/release fonts); the web fetches Noto Sans Gujarati when the interface needs it | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | original rows and the 387 additions contributor-reviewed; the 2026-12-02 messages and labels machine-assisted, native review pending | native review of the messages |
|
||||
| Arabic | `ar` | preparatory registration (native name العربية) and 6-form CLDR plural probe only; translations maintained upstream in `storytold/craft-i18n` (`locales/ar/vectorcraft.tsv`) and not yet consumed | none (UI not exposed pending shared catalog) | document text: existing bidirectional layout and paragraph direction; interface UI: not exposed pending shared catalog, with full shell mirroring pending STD-I18N-001 | — (preparatory) | preparatory (not exposed) | 15–20 |
|
||||
| French | `fr` | 9,166 rows, 3,436 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 178 missing messages for it | all | Latin | no | full | — (review) |
|
||||
| Portuguese | `pt-br` | 9,378 rows, 3,563 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) |
|
||||
@@ -101,6 +101,7 @@ font for the web build.
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-12-02 | minor | Gujarati: status and error messages translated (4,926 new `@msg`/`@msgplural` rows, machine-assisted draft, native review pending); `gu` joins `COMPLETE_MESSAGES`. Scores and estimates unchanged. |
|
||||
| 2026-12-02 | minor | Gujarati (`gu`): Web: Gujarati can be selected as the interface language; the web fetches Noto Sans Gujarati when the interface needs it (`crates/text/web-fonts.txt`, `demand`), as it does Noto Sans Devanagari for Hindi. Status/error messages remain partial. Scores and estimates unchanged. |
|
||||
| 2026-11-25 | patch | Arabic (`ar`): preparatory registration and 6-form CLDR plural routing; kept unavailable to users pending upstream `storytold/craft-i18n` catalog |
|
||||
| 2026-11-14 | minor | Gujarati (#6613): contributor proofreading completed for all 387 additions, with 11 wording corrections; 4,673 reviewed catalog rows. Status/error messages remain partial; web selection requires a bundled Gujarati face. Scores and estimates unchanged. |
|
||||
|
||||
+7
-2
@@ -880,7 +880,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions
|
||||
| `invoke_menu` | `{command, params?}` | Invokes a menu item by command id. UI commands such as `view.*` and `window.*` are in `command_list` with `ui: true`; running them needs the desktop app (`--connect`). The app refuses `attributes.openUrl`, `file.export.svg.browser`, `file.saveForWeb.browser` and `file.showPackage` for every control and MCP request, since each opens another app, so the headless error for them does not suggest `--connect`. |
|
||||
| `open_panel` | `{panel}` | Remote only. `panel` is a panel id (`layers`, `swatches`, `colorGuide`, …, as `window.panel` takes) or its display label (`"Color Guide"`), in any case. |
|
||||
| `screenshot` | `{path?, scale?, artboard?, window?, max_side?, traceViews?}` | Returns MCP image content (`image/png`, base64) plus a text block. Renders the artboard with the pixels of a PNG `export` with `background: "white"` at the same scale; `traceViews:true` draws Image Trace objects in the view set with `imageTrace.setView`, as in the app's window; `window:true` captures the app window (remote only), as `ui_screenshot` does, and `max_side` (1–4096, window captures only) scales the returned image down as described for `ui_screenshot`. With `path` the backend (the headless session or the app) writes the PNG there too; a window capture written there keeps its full size with `max_side`. An app that does not send the image back writes a window capture without `path` to a file in a new folder inside the system's temporary folder (on Unix only the user can open it); the server reads the file and then removes the folder, also when the capture or the read fails. |
|
||||
| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG (`.jpg`/`.jpeg`/`.jpe`), GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`), layered raster `.pcraft` documents (as one image at the canvas size; a warning says when only the smaller preview could be read), DWG drawings (`.dwg`, `.dws`, `.dwt`). Templates (`.vctemplate`, `.ait`, `.cdt`, `.dwt`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin.<id>"` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. |
|
||||
| `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG (`.jpg`/`.jpeg`/`.jpe`), GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame), CDR drawings of versions 1 to 27 (`.cdr`, `.cdt`), CMX files with 32-bit coordinates (`.cmx`), layered raster `.pcraft` documents (as one image at the canvas size; a warning says when only the smaller preview could be read), DWG drawings (`.dwg`, `.dws`, `.dwt`). Templates (`.vctemplate`, `.ait`, `.cdt`, `.dwt`) open as a new untitled document. A text, RTF or Word file (`.txt`, `.rtf`, `.docx`, `.doc`) opens as a new letter-size document named after the file, its text area type 36 pt inside the artboard as `file.place` sets it; `run_command document.open` with `text` gives a `.txt` file's Text Import Options, and Save asks for a name. A `.txt` file without text, and an RTF file that ends inside a group, are refused and open nothing. A file with one of those extensions that starts with a PDF header or an Affinity signature opens as that format instead. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin.<id>"` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. |
|
||||
| `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `<name>_<artboard>.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error; versions 1 to 3 get each live star as a plain path of its outline, without its point count and ratio), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a PDF-compatible `.ai` file reads `compress` but not `version`, `preview`, `precision`, `outlineText`, `hiddenObjects`, `transparentImages` or `preserveEditing`, and a legacy `.ai` file reads only its own options). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for each key given beside the path or in `options` that the file doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: <reason>` without a fallback panel for automation; see [Save location errors](#save-location-errors). In the desktop app, a save that runs in the background shows in the progress window after 0.4 s with a moving bar. `file.cancelSave` stops every such save before it replaces its file → `{cancelled: n}`: the file stays as it was, and the document keeps its file and format and stays modified. A save whose file was already being replaced finishes and is reported as saved. `file.saveInBackground` closes the window while the saves go on → `{hidden: n}`. |
|
||||
| `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. |
|
||||
| `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` for type on a path (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning). An invalid effect is rejected before editing. `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. |
|
||||
@@ -4705,7 +4705,9 @@ the color's `typename` can differ from the picker's model and from the color giv
|
||||
picker convert from the RGB profile of the document the window shows (the working RGB profile when it shows none) to the RGB profile of the run's active
|
||||
document, and in a CMYK document they then separate through that document's CMYK profile. Hex, screen-sample and HSB
|
||||
picks, and typed values that Only Web Colors snaps, start in display sRGB and convert only through the active
|
||||
document's profiles. An answer taken from `answers`
|
||||
document's profiles. The picker's CMYK fields, its gamut warning and the swatch of a CMYK color it opens on use the
|
||||
CMYK profile of the run's active document, in an RGB document too; an RGB color opens as the document the window
|
||||
shows draws it, the profile its RGB fields read. An answer taken from `answers`
|
||||
keeps the color model it was given. The picker opens on the color as
|
||||
given, whatever Only Web Colors was left at in another picker. OK with both the color and its model unchanged, and Cancel, return a new object of the color the
|
||||
script gave. The picker shows no preview on the selection and has no Stop button: the status bar's Stop and quitting
|
||||
@@ -9158,6 +9160,9 @@ right]`) and `current`, the selected stroke's profile (`"custom"` when it isn't
|
||||
`stroke.widthProfile.add {name?}` saves the selected stroke's variable width (default name "Width Profile N"),
|
||||
`stroke.widthProfile.delete {name?}` removes a saved one (default: the selected stroke's; built-ins can't be deleted)
|
||||
and `stroke.widthProfile.reset` removes every saved one. `stroke.set {profile}` takes a built-in id or a saved name.
|
||||
In the app, the footer of the Profile drop-down (in the Stroke panel, the Control bar and the Properties panel) runs
|
||||
the same three commands: Add to Profiles asks for a name first, Delete Profile removes the selected stroke's saved
|
||||
profile, and Reset Profiles asks for confirmation. Right-clicking a saved profile's row offers Delete Profile for it.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"stroke.widthProfile.add","params":{"name":"Ribbon"}}}
|
||||
|
||||
+4
-3
@@ -28,7 +28,7 @@
|
||||
|
||||
> Blend redraw update (#5179): renderer bounds include spine-placed keys and steps; both focused CPU regressions pass. Scores and estimates unchanged.
|
||||
|
||||
> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, and since 2026-12-02 the web build fetches it when the interface needs it (`crates/text/web-fonts.txt`, `demand`), so Gujarati can be selected on the web. Scores and estimates unchanged.
|
||||
> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status and error messages: 4,946 `@msg` and 56 `@msgplural` rows (2026-12-02); with 155 menu, label and undo rows added the same day the catalog has 10,890 rows; all machine-assisted, native review pending; `gu` is in `COMPLETE_MESSAGES`. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, and since 2026-12-02 the web build fetches it when the interface needs it (`crates/text/web-fonts.txt`, `demand`), so a web build made with `CRAFT_FONTS_DIR` pointing at a craft-fonts checkout that has Noto Sans Gujarati offers Gujarati; a web build without it does not. Scores and estimates unchanged.
|
||||
|
||||
## Feature submission evidence
|
||||
|
||||
@@ -84,6 +84,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-12-02 | minor | Gujarati: status and error messages translated (4,926 new `@msg`/`@msgplural` rows, machine-assisted draft, native review pending); `gu` joins `COMPLETE_MESSAGES`. Scores and estimates unchanged. |
|
||||
| 2026-11-26 | minor | Show Missing Links in View and the Links panel marks missing linked images and placed documents on the canvas; the link watcher scans them in the background, so turning it on never waits on a file; transient overlays stay out of artwork, export and undo history; command API controls and lists markers (#5547). Scores and estimates unchanged. |
|
||||
| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. |
|
||||
| 2026-11-21 | minor | G12/M14: History row context menus retain the chosen snapshot while the menu is open and pending edits settle; jumps settle typing before counting undo/redo, and discarded states report that they are unavailable. Shift+F10 opens the focused row menu, Escape restores row focus, and switching documents dismisses the popup. History checklist, area and milestone evidence updated (#8845); scores and estimates unchanged. |
|
||||
@@ -170,7 +171,7 @@ Checked 2026-10-10 from the code, tests and open issues; no workflow fails, so V
|
||||
Hindi interface follow-up (2026-11-06): the catalog and zero/one plural rule are implemented;
|
||||
native wording review, layout checks and a web Devanagari font remain. [Notes](localization-hi.md).
|
||||
|
||||
Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule are implemented. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. Since 2026-12-02 the web fetches Noto Sans Gujarati when the interface needs it, so Gujarati can be selected on the web.
|
||||
Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule are implemented. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status and error messages are translated (2026-12-02, machine-assisted, native review pending). Since 2026-12-02 the web fetches Noto Sans Gujarati when the interface needs it, so a web build made with `CRAFT_FONTS_DIR` pointing at a craft-fonts checkout that has Noto Sans Gujarati offers Gujarati; a web build without it does not.
|
||||
|
||||
## Current focus
|
||||
|
||||
@@ -215,7 +216,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule
|
||||
| — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 |
|
||||
| — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 |
|
||||
| M14 follow-up | Color Picker layout (#2008) | ✅ Compact controls, centered header, stacked actions, aligned fields and screen sampling; narrow windows scroll vertically | Included above |
|
||||
| M14 follow-up | Gujarati interface (#6613) | 🟡 Zero/one singular plurals and desktop font fallback; 4,673 contributor-reviewed rows, including 387 approved additions with 11 wording corrections; status/error messages remain partial; the web fetches Noto Sans Gujarati on demand | Included above |
|
||||
| M14 follow-up | Gujarati interface (#6613) | 🟡 Zero/one singular plurals and desktop font fallback; 4,673 contributor-reviewed rows, including 387 approved additions with 11 wording corrections; status/error messages translated (machine-assisted, review pending); the web fetches Noto Sans Gujarati on demand | Included above |
|
||||
| | **Total to full parity** (one agent; from [target-app-parity.md](target-app-parity.md)) | | **~360–590** |
|
||||
|
||||
Milestone estimates predate the 2026-10-10 re-measure for M1–M14; the area table in
|
||||
|
||||
@@ -37,7 +37,7 @@ Native saves on Unix flush the destination directory after writing or replacing
|
||||
|
||||
> Blend redraw update (#5179): renderer bounds include spine-placed keys and steps; both focused CPU regressions pass. Scores and estimates unchanged.
|
||||
|
||||
> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, and since 2026-12-02 the web build fetches it when the interface needs it (`crates/text/web-fonts.txt`, `demand`), so Gujarati can be selected on the web. Scores and estimates unchanged.
|
||||
> **Gujarati status (2026-11-14, #6613):** 4,673 catalog rows: the original 4,286 remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status and error messages: 4,946 `@msg` and 56 `@msgplural` rows (2026-12-02); with 155 menu, label and undo rows added the same day the catalog has 10,890 rows; all machine-assisted, native review pending; `gu` is in `COMPLETE_MESSAGES`. The pinned CI/release fonts include Noto Sans Gujarati as an optional `Gujr` fallback, and since 2026-12-02 the web build fetches it when the interface needs it (`crates/text/web-fonts.txt`, `demand`), so a web build made with `CRAFT_FONTS_DIR` pointing at a craft-fonts checkout that has Noto Sans Gujarati offers Gujarati; a web build without it does not. Scores and estimates unchanged.
|
||||
|
||||
## Feature submission evidence
|
||||
|
||||
@@ -133,6 +133,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-12-02 | minor | Gujarati: status and error messages translated (4,926 new `@msg`/`@msgplural` rows, machine-assisted draft, native review pending); `gu` joins `COMPLETE_MESSAGES`. Scores and estimates unchanged. |
|
||||
| 2026-11-26 | minor | Show Missing Links in View and the Links panel marks missing linked images and placed documents on the canvas; the link watcher scans them in the background, so turning it on never waits on a file; transient overlays stay out of artwork, export and undo history; command API controls and lists markers (#5547). Scores and estimates unchanged. |
|
||||
| 2026-11-25 | minor | Document Info › Objects: total enclosed area (`pathArea` in pt²) for closed and compound paths (holes subtracted per fill rule; guides and open paths left out) and formatted Path Area in document units (#6965). Worked out only when the request covers Objects (`pathArea` null otherwise or with `pathArea: false`); the panel asks for it only while Objects or All Categories is shown. Tests: `info_gives_the_paths_total_area`, `info_works_out_the_path_area_only_for_the_objects_category`, `the_path_area_is_worked_out_only_while_objects_is_shown`, `format_area_formats_and_trims_cleanly`. Scores and estimates unchanged. |
|
||||
| 2026-11-24 | minor | G12: History row context menus use shared Craft List and Menu controls after rebasing onto the panel migration. App-specific actions retain the chosen snapshot across pending edits and dismiss on document switches; keyboard context requests and focus restoration use the shared runtime. Regression cases retained (#8845); scores and estimates unchanged. |
|
||||
@@ -946,6 +947,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- **Width-point creation (G1):** double-click a stroked segment with the Width tool to open Width Point Edit using sampled side widths. OK creates the point and optionally adjusts adjoining widths in one undo step. Cancel or Delete discards a prospective point without changing the document or redo history. Command and pointer tests cover profiles, compound paths, adjoining adjustment, existing-point editing and Undo/Redo. Message-catalog checks and full CI passed; the original capture verifies opening and Cancel, and the dialog layout was reviewed (2026-10-13: 28 focused Width tests, all seven cargo xtask ci stages, and a headless opening/Cancel capture with original PNG review). [Variable-width strokes](https://helpx.adobe.com/illustrator/using/stroke-object.html).
|
||||
- **Escape deselects width points:** with the Width tool, Escape deselects the selected width points, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for deselecting a width point. The path, its widths and the undo history do not change. With no width point selected, Escape does what it does with the other tools, such as leaving isolation mode.
|
||||
- **Width profiles on brushed strokes:** brush art does not follow a stroke's width profile, so while every stroke the list edits draws with a brush, the Profile list in the Stroke panel, the Properties panel and the Control bar is dimmed and says why when hovered (VectorCraft's own rule while brushes ignore width profiles; art and pattern brushes that follow one are still missing). It opens no list while every one of those strokes is uniform, and only Uniform, which removes the profiles, while one has a profile. The Flip Along and Flip Across buttons beside it are off. The strokes are the ones `stroke.set` edits: the active Appearance stroke row in each selected object that has an equal row and the top stroke in the others, else a selected group's or compound shape's own stroke, else the objects' strokes. Images and symbol instances, which take no stroke from the list, do not count. A selection where some of them have no brush, or an object has no stroke, keeps the full list. The Width tool adds, edits and deletes no width points on a brushed stroke, and a press or a double-click on one says why in the status bar; without Shift it deselects the width points of other strokes, and the cursor over a brushed stroke offers no edit. A plain stroke under a selected brushed one stays reachable. Width points selected before their stroke took a brush show no handles, and Delete, Backspace and Escape act as if none were selected. Tests: `panels::tests_strokedepth::{dropdown_is_dimmed_while_the_brush_keeps_its_size, the_active_stroke_row_decides_whether_the_dropdown_is_dimmed, a_groups_own_brushed_stroke_dims_the_dropdown, selecting_another_object_without_an_edit_updates_the_dimming, flip_buttons_leave_a_brushed_strokes_profile_alone, mixed_selection_dims_the_dropdown_only_when_every_stroke_has_a_brush, the_hover_text_is_the_width_tools_status_message}`, `panels::properties::tests::the_width_profile_of_a_brushed_stroke_offers_only_uniform`, `tests::appearance::{brushed_strokes_profiled_reads_the_strokes_stroke_set_edits, brushed_strokes_profiled_reads_a_compound_shapes_own_stroke, brushed_strokes_profiled_reads_a_targeted_layers_active_stroke_row, brushed_strokes_profiled_leaves_out_symbol_instances, brushed_strokes_profiled_falls_back_to_the_top_stroke_where_the_active_row_has_no_match}`, `tests::widthtool::the_width_tool_says_why_it_leaves_a_brushed_compound_path_alone`, `distort::width::tests::{brushed_stroke_is_left_alone_with_a_reason, delete_leaves_the_width_points_of_a_brushed_stroke, a_press_on_a_brushed_stroke_deselects_and_its_cursor_offers_no_edit, shift_on_a_brushed_stroke_keeps_the_selected_width_points, a_plain_stroke_under_a_selected_brushed_one_stays_reachable, a_brush_applied_under_a_still_pointer_takes_away_the_hover, a_brush_added_to_the_library_is_seen_at_the_next_revision}`.
|
||||
- **Profile drop-down footer:** the Profile drop-down in the Stroke panel, the Control bar and the Properties panel ends in a footer with Add to Profiles, Delete Profile and Reset Profiles, the controls the [Apply stroke on an object](https://helpx.adobe.com/illustrator/using/stroke-object.html) page places at the bottom of the width profile list under "Save width profiles". Add asks for a name, Delete removes the selected stroke's saved profile (built-in profiles stay), and Reset asks for confirmation before it removes the saved profiles. Right-clicking a saved row also offers Delete Profile. The drop-down reports the picked row's place to screen readers, which can step and set it. Tests: `panels::tests_strokedepth::{dropdown_footer_manages_profiles_and_confirms_reset, dropdown_row_menu_deletes_saved_profiles_only, a_screen_reader_sets_and_steps_the_profile}`.
|
||||
- **Smooth widths between width points (#5714):** a variable-width stroke changes width along a smooth curve from one width point to the next, where it used to run in a straight line and turn a corner at each point. The public description is that the path "gradually gets wider or narrower from one point to the next" in "a flowing, continuous curve", and that stacked points make a sharp break ([Peachpit, Expressive Strokes](https://www.peachpit.com/articles/article.aspx?p=2979069)); the exact curve is not documented, so each side follows a monotone cubic (Fritsch–Carlson): no kink at a point, flat where a point is wider or narrower than both neighbours, never past the points either side, points on one line kept on it. The outline samples straight runs between width points closely enough to follow the curve to the drawing tolerance (at most 64 samples per span and 4,096 per piece). Presets with a middle point (Lens, Pinch, Teardrop, Wave) look softer; two-point tapers are unchanged. Tests: `appearance::profile::tests::{widths_run_smoothly_through_width_points, widths_never_pass_the_points_either_side, a_step_ends_the_curve_on_each_side, widest_covers_every_width_along_the_profile}`, `stroke::width::tests::{a_straight_run_follows_the_curve_between_width_points, samples_between_width_points_are_capped}`.
|
||||
- **Stroke gradients where a variable-width stroke meets itself (#5960):** with a gradient along or across a stroke that has a width profile, where the stroke crosses itself the later part paints over the earlier one only where the two overlap, and a narrow part running close beside a wide one leaves its edge alone. Each slice of the gradient reaches as far as the stroke is wide where it sits (for a dashed stroke, as wide as it gets within the reach of a cap or dot, found in one pass along the path, so a densely flattened path costs no more per point), where it used to reach as far as the stroke is wide anywhere and paint a square of its colour over the wider part. Strokes without a profile are unchanged. Tests: `stroke::tests_gradient::a_narrow_pass_over_a_wide_one_paints_only_where_they_overlap`, `a_narrow_pass_beside_a_wide_one_leaves_its_edge_alone`, `a_densely_flattened_dashed_pass_beside_a_wide_one_leaves_its_edge_alone` and `widest_ahead_is_the_widest_within_the_window`, with the existing coverage tests (joins, caps, arrowheads, profiles, dashes, aligned strokes).
|
||||
- **Width strokes zoomed out (#995):** a stroke with a width profile keeps its shape while the view zooms out. The canvas keeps a hairline visible (at least half a device pixel); for a profiled stroke it is the profile's widest point that gets that minimum, not the weight, so a 1 pt stroke with a 6x width point is no longer drawn twice as thick at 25% zoom than at 100%. Plain strokes are unchanged. Test: `render::tests::widthzoom`.
|
||||
@@ -1289,7 +1291,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Swedish messages (2026-11-13): the Swedish (`sv`) catalog has an `@msg` row for 464 of the 628 status and error messages the untranslated report listed for it; 162 messages that no complete-message catalog translates, 36 composite font errors among them, are not translated yet, and two unknown-parameter errors that start with the `{within}` placeholder stay in English, as does `{name} must be {lo}–{hi}{unit} (got {v})`, whose existing row can't match because two of its placeholders sit side by side; the rows keep their placeholders, backticked names, quoted values and command ids; native review remains; scores and estimates unchanged.
|
||||
- Window › Toolbars › Keep Tools Beside the Canvas, a VectorCraft layout option that is off by default, docks the Tools panel between left-side panels and the canvas instead of at the window's left edge, and workspaces keep the setting. A floating Tools panel dropped on the canvas's left edge, right of panels docked on the left, docks there and turns the setting on, and one dropped on the window's left edge docks there and turns it off; with no panels docked on the left, a drop leaves the setting as it is (#7837). Scores are unchanged (`window.toolsBesideCanvas`; `docked_tools_keep_the_window_edge_unless_kept_beside_the_canvas`, `tools_dropped_on_a_left_edge_dock_there_and_the_setting_follows`, `tools_dropped_where_the_left_edges_overlap_keep_the_setting`, `tools_dropped_beside_a_collapsed_left_dock_follow_the_strip_dropped_on`).
|
||||
- Hindi (2026-11-06): Hindi (`hi`): 7,877-row machine-assisted catalog, zero/one singular plurals, desktop font fallback and optional Devanagari craft-fonts fallback; all 55 translation tests pass; native review and a web font remain; scores and estimates unchanged. [Terminology and limitations](localization-hi.md).
|
||||
- Gujarati (2026-11-14, #6613): `gu` has 4,673 catalog rows, zero/one singular plurals, installed desktop font fallback and support for optional `Gujr` craft-font faces. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status/error messages remain partial. Since 2026-12-02 the web fetches Noto Sans Gujarati when the interface needs it, so Gujarati can be selected on the web. Current-head validation is recorded in the PR; scores and estimates unchanged.
|
||||
- Gujarati (2026-11-14, #6613): `gu` had 4,673 catalog rows on 2026-11-14 (10,890 on 2026-12-02), zero/one singular plurals, installed desktop font fallback and support for optional `Gujr` craft-font faces. The original 4,286 rows remain unchanged; all 387 additions are contributor-reviewed and approved, with 11 wording corrections. Status and error messages: 4,946 `@msg` and 56 `@msgplural` rows (2026-12-02); with 155 menu, label and undo rows added the same day the catalog has 10,890 rows; all machine-assisted, native review pending; `gu` is in `COMPLETE_MESSAGES`. Since 2026-12-02 the web fetches Noto Sans Gujarati when the interface needs it, so a web build made with `CRAFT_FONTS_DIR` pointing at a craft-fonts checkout that has Noto Sans Gujarati offers Gujarati; a web build without it does not. Current-head validation is recorded in the PR; scores and estimates unchanged.
|
||||
- Hindi wording (2026-11-13): rows outside the plug-in messages keep their English's meaning, quantities and clauses, and use the catalog's save, swatch, crop, resolution, path and type terms; a test checks those terms and the point unit in every row; native review remains; scores and estimates unchanged.
|
||||
- Hindi word senses (2026-11-13): 85 labels and messages use the interface sense of their English: Desired is वांछित and the range message keeps both comparisons, rulers are रूलर, text characters कैरेक्टर, vector points पॉइंट, fills फ़िल्स and High Contrast उच्च कंट्रास्ट; the glossary test rejects the unrelated senses in every row; native review remains; scores and estimates unchanged.
|
||||
- Hindi terms (2026-11-13): every row that names a variable (data merge, variable fonts and widths, environment variables) says वेरिएबल, and joining paths, anchor points, point type and lines says जोड़ें instead of शामिल हों, which stays for joining the community; a test checks both terms in every row; scores and estimates unchanged.
|
||||
|
||||
Reference in new issue
Block a user