Merge main into fix/tablet-pen-stroke-held

This commit is contained in:
dotCooCoo committed 2026-12-05 12:13:06 -08:00
commit 5debbe99d9
79 files changed
+9110 -281

No files matched your search

+2 -2
View File
@@ -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% |
+117 -9
View File
@@ -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() {
+5 -4
View File
@@ -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};
+1 -1
View File
@@ -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
),
+38 -21
View File
@@ -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
+6 -5
View File
@@ -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(),
}
}
+9 -1
View File
@@ -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 {
+6 -5
View File
@@ -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];
+18 -1
View File
@@ -5,6 +5,9 @@
use serde_json::{Value, json};
use vectorcraft_doc::NodeKind;
use super::typemenu::all_texts;
use super::{CommandSpec, EngineError, Result, Session, always, bad, cmd, text_param};
use crate::packs::{self, Outcome};
@@ -16,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Language Packs",
[],
None,
"{refresh?: bool (fetch the pinned pack index again; needs downloading on; refused under automation roots; in the desktop app it runs in the background: see refreshing)} the Language packs that spell-check and hyphenate languages other than English, shared by the Craft apps → {packs: [{locale, name, size: bytes, licence: SPDX, class, spelling: bool, hyphenation: bool, installed: bool}…] (the index fetched last; empty before the first fetch), installed: [{locale, name, licence}…] (the packs spelling and hyphenation use), installing: [{locale, done, total}…] (bytes), refreshing: bool, errors: {locale: message} (the last failure of each install or removal; \"\": of the index fetch), downloads: bool (the person allowed downloading), indexOverride: string|null (a test index used instead of the pinned one), available: bool (there is a font store folder to install into)}",
"{refresh?: bool (fetch the pinned pack index again; needs downloading on; refused under automation roots; in the desktop app it runs in the background: see refreshing)} the Language packs that spell-check and hyphenate languages other than English, shared by the Craft apps → {packs: [{locale, name, size: bytes, licence: SPDX, class, spelling: bool, hyphenation: bool, installed: bool}…] (the index fetched last; empty before the first fetch), installed: [{locale, name, licence}…] (the packs spelling and hyphenation use), installing: [{locale, done, total}…] (bytes), refreshing: bool, errors: {locale: message} (the last failure of each install or removal; \"\": of the index fetch), downloads: bool (the person allowed downloading), indexOverride: string|null (a test index used instead of the pinned one), available: bool (there is a font store folder to install into), missing: [{lang, locale: string|null}…] (the languages of the front document's visible, unlocked type that have no dictionary: each with its pack's locale, null before the index is first fetched; a language the fetched index has no pack for is left out)}",
always,
list
),
@@ -82,9 +85,23 @@ fn list(s: &mut Session, p: &Value) -> Result<Value> {
"downloads": backend.as_ref().is_some_and(|b| b.downloads_on()),
"indexOverride": backend.as_ref().and_then(|b| b.index_override()),
"available": backend.is_some(),
"missing": missing(s).iter().map(|m| json!({"lang": m.tag, "locale": m.pack.as_ref().map(|p| &p.locale)})).collect::<Vec<_>>(),
}))
}
/// The languages of the front document's type (the type spell check reads: visible, unlocked) that
/// have no dictionary yet, with the pack for each ([`packs::missing_of`]): what the missing-pack
/// bar offers, and `proof.packs`'s `missing`.
pub fn missing(s: &Session) -> Vec<packs::Missing> {
let Ok(st) = s.doc() else { return Vec::new() };
let texts = all_texts(&st.doc);
let runs = texts.iter().filter_map(|id| match st.doc.node(*id).map(|n| &n.kind) {
Some(NodeKind::Text(t)) => Some(t.runs.iter()),
_ => None,
});
packs::missing_of(runs.flatten().filter_map(|r| r.style.language.as_deref()))
}
/// Refuses `command` for a caller confined to automation roots: the packs are written into the font
/// store the Craft apps share, which is outside them.
fn not_confined(command: &str) -> Result<()> {
+72 -30
View File
@@ -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))
+41
View File
@@ -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");
}
+9 -1
View File
@@ -608,13 +608,21 @@ impl Transaction {
for st in &mut s.docs {
// Past the newest revision the document reached, so the restored one redraws. A
// document the transaction left as it was keeps its revision, so a run made
// away from the session on it still applies.
// away from the session on it still applies. Putting back an older snapshot, or
// reopening a document the calls closed, counts as a rollback: an object the calls
// made can lose its node ID to a new one. The count never goes below the highest
// one the document reached.
let reached: Vec<_> = open.iter().filter(|d| d.uid == st.uid).collect();
let unchanged = !reached.is_empty() && reached.iter().all(|d| d.revision == st.revision && d.selection == st.selection);
if !unchanged {
let newest = reached.iter().map(|d| d.revision).max().unwrap_or(st.revision);
st.revision = newest.max(st.revision).saturating_add(1);
}
let rollbacks = reached.iter().map(|d| d.rollbacks).max().unwrap_or(st.rollbacks);
st.rollbacks = rollbacks.max(st.rollbacks);
if reached.is_empty() || reached.iter().any(|d| !Arc::ptr_eq(&d.doc, &st.doc)) {
st.rollbacks = st.rollbacks.saturating_add(1);
}
crate::deselect_hidden(&s.menu, &st.doc, &mut st.selection);
}
s.active = active;
+1
View File
@@ -231,6 +231,7 @@ pub(crate) fn leave(s: &mut Session, _: &Value) -> Result<Value> {
st.selection.prune(&st.doc);
st.history.redo = Arc::unwrap_or_clone(redo);
st.revision += 1;
st.rollbacks += 1;
} else {
s.edit("Exit Symbol Editing Mode", |d, sel| {
finish(d, sel);
+1
View File
@@ -2249,6 +2249,7 @@ fn discard_empty(s: &mut Session, p: &Value) -> Result<Value> {
st.selection.prune(&st.doc);
super::globaledit::follow_history(st);
st.revision += 1;
st.rollbacks += 1;
return Ok(json!({"removed": true}));
}
}
+13
View File
@@ -121,6 +121,15 @@ pub struct DocState {
/// Advances when Undo, Redo or a canceled undo group restores an older document snapshot. The same node ID can name different objects
/// across that boundary.
pub history_restores: u64,
/// Advances when a canceled interaction, Exit Symbol Editing Mode taking
/// back the entering step, Discard Empty Type taking back the step that made the text, or a command
/// that panicked puts back an older document snapshot. A canceled plug-in run advances it
/// when its calls changed the document. A preview advances it when it discards an earlier preview
/// that allocated node IDs, or fails after discarding an earlier preview's document change.
/// A command run during a tool interaction advances it when it sets aside a preview that allocated
/// node IDs.
/// The same node ID can name different objects across that boundary.
pub rollbacks: u64,
/// Preferences › User Interface › Open Documents As Tabs when the document opened: cleared,
/// the UI opens it in a floating window of its own.
pub opened_as_tab: bool,
@@ -556,6 +565,7 @@ impl DocState {
activated: 0,
reverts: 0,
history_restores: 0,
rollbacks: 0,
opened_as_tab: true,
mask_view: None,
spelling_ignored: Default::default(),
@@ -812,6 +822,9 @@ impl DocState {
/// End the interaction in progress, undoing what it changed.
pub(crate) fn undo_interaction(&mut self) {
if let Some(it) = self.interaction.take() {
if !Arc::ptr_eq(&self.doc, &it.doc) {
self.rollbacks += 1;
}
self.doc = it.doc;
self.selection = Arc::unwrap_or_clone(it.selection);
self.sync_new_art();
+141 -1
View File
@@ -59,6 +59,11 @@ pub trait Backend: Send + Sync {
fn index_override(&self) -> Option<String> {
None
}
/// Turns downloading on. Only from the person's own click in the app (an Install or Refresh
/// button, [`enable_downloads`]): no command calls it.
fn enable_downloads(&self) -> Result<(), String> {
Err(not_allowed())
}
}
/// An install running.
@@ -82,6 +87,8 @@ static JOBS: Mutex<Jobs> = Mutex::new(Jobs { installing: BTreeMap::new(), refres
static BACKGROUND: AtomicBool = AtomicBool::new(false);
/// Goes up each time the installed packs change.
static GENERATION: AtomicU64 = AtomicU64::new(0);
/// Goes up each time a fetch of the index ends, done or failed ([`index_generation`]).
static INDEX_GENERATION: AtomicU64 = AtomicU64::new(0);
fn jobs() -> MutexGuard<'static, Jobs> {
JOBS.lock().unwrap_or_else(PoisonError::into_inner)
@@ -119,6 +126,18 @@ pub fn generation() -> u64 {
GENERATION.load(Ordering::Relaxed)
}
/// Goes up each time a fetch of the index ends, done or failed: what [`available`] lists may have changed (a window
/// that keeps the list keys it on this).
pub fn index_generation() -> u64 {
INDEX_GENERATION.load(Ordering::Relaxed)
}
/// `r`, a fetch of the index that ended, counted in [`index_generation`].
fn fetched<T>(r: T) -> T {
INDEX_GENERATION.fetch_add(1, Ordering::Relaxed);
r
}
/// Read the packs folder again: spelling and hyphenation in its languages change.
fn changed() {
craft_proof::packs::reload();
@@ -149,6 +168,33 @@ fn downloads_off() -> String {
"downloading is turned off; only the person using a Craft app can turn it on, by installing a Language pack there".into()
}
fn not_allowed() -> String {
"only the person using the app can turn on downloading, with their own click".into()
}
/// Turns the font store's downloading on, for every Craft app. The app calls it only for the
/// person's own click on Install or Refresh (never for input the control channel injected), and no
/// command calls it (RFC-0011): an agent can install once the person has turned it on.
pub fn enable_downloads() -> Result<(), String> {
backend().ok_or_else(no_backend)?.enable_downloads()
}
/// An installed pack, as spelling and hyphenation read it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Installed {
/// The pack's locale (`nl`).
pub locale: String,
/// The language's own name, from the pack.
pub name: String,
/// SPDX licence expression of the pack's data.
pub licence: String,
}
/// The packs installed in the store (by this app or another), the ones spelling and hyphenation use.
pub fn installed() -> Vec<Installed> {
craft_proof::packs::installed().into_iter().map(|i| Installed { locale: i.locale, name: i.name, licence: i.licence }).collect()
}
/// The packs the index fetched last lists.
pub fn available() -> Vec<Pack> {
backend().map(|b| b.cached_index()).unwrap_or_default()
@@ -221,6 +267,7 @@ pub fn refresh() -> Result<Outcome, String> {
run(
move || {
let r = b.fetch_index(&cancel).map(|_| ());
INDEX_GENERATION.fetch_add(1, Ordering::Relaxed);
let mut j = jobs();
j.refreshing = None;
if let Err(e) = &r {
@@ -274,7 +321,7 @@ pub fn install(locale: &str) -> Result<Outcome, String> {
fn install_now(b: &dyn Backend, locale: &str, cancel: &Cancel) -> Result<(), String> {
let listed = |packs: &[Pack]| packs.iter().any(|p| p.locale == locale);
if !listed(&b.cached_index()) && !listed(&b.fetch_index(cancel)?) {
if !listed(&b.cached_index()) && !listed(&fetched(b.fetch_index(cancel))?) {
return Err(format!("there is no Language pack for {locale}"));
}
b.install(locale, cancel, &mut |done, total| {
@@ -309,6 +356,93 @@ pub fn remove(locale: &str) -> Result<(), String> {
r
}
/// Most languages [`missing`] reports for one document.
const MAX_MISSING: usize = 16;
/// A language the document's type is in that spelling (and hyphenation) can't check yet: what
/// the missing-pack bar offers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Missing {
/// The type's language tag (`hi`, `sr-Latn`).
pub tag: String,
/// The pack the index lists for it; `None` before the index is first fetched, when whether
/// there is one isn't known yet.
pub pack: Option<Pack>,
}
/// Of the language tags `tags` (a document's type's, in order, repeats allowed), those with no
/// dictionary: each with the pack the index lists for it, or, before the index is first fetched,
/// with none. A language the fetched index has no pack for is left out, and so is any language
/// while there is no store to install into ([`crate::cmd::packs::missing`] reads the tags).
pub fn missing_of<'a>(tags: impl IntoIterator<Item = &'a str>) -> Vec<Missing> {
if backend().is_none() {
return Vec::new();
}
let index = available();
let mut out: Vec<Missing> = Vec::new();
let mut seen: Vec<&str> = Vec::new();
for tag in tags {
if seen.contains(&tag) {
continue;
}
seen.push(tag);
// English spells from built-in data; a tag that is no language (`und`, `zxx`) has none.
let lang = craft_proof::ProofLang::from_tag(Some(tag));
if lang == craft_proof::ProofLang::Other || lang.is_english() || craft_proof::missing_dictionary(Some(tag)).is_none() {
continue;
}
let pack = pack_for_tag(tag, &index).cloned();
if pack.is_none() && !index.is_empty() {
continue;
}
// Two tags of one pack (`nl`, `nl-BE`) offer it once.
if pack.is_some() && out.iter().any(|m| m.pack == pack) {
continue;
}
out.push(Missing { tag: tag.to_string(), pack });
if out.len() >= MAX_MISSING {
break;
}
}
out
}
/// The pack for a language tag: the whole tag's (`pt-pt`), else each shorter prefix's
/// (`sr-latn` for `sr-Latn-RS`, `nl` for `nl-NL`), the first `packs` lists. A variant after the
/// region is tried without the region before the region alone (`ca-ES-valencia` is the
/// `ca-valencia` pack's). `None` for English and for a tag no pack is for.
pub fn pack_for_tag<'a>(tag: &str, packs: &'a [Pack]) -> Option<&'a Pack> {
pack_candidates(tag).iter().find_map(|c| packs.iter().find(|p| &p.locale == c))
}
/// Whether `subtag`, after a tag's language (and script), is a region: two letters or three digits.
fn is_region(subtag: &str) -> bool {
(subtag.len() == 2 && subtag.bytes().all(|b| b.is_ascii_alphabetic())) || (subtag.len() == 3 && subtag.bytes().all(|b| b.is_ascii_digit()))
}
/// The pack locales [`pack_for_tag`] tries for `tag`, best first.
fn pack_candidates(tag: &str) -> Vec<String> {
// A tag is a handful of short subtags; anything longer is junk and only its start is read.
let tag: String = tag.trim().chars().take(64).collect::<String>().replace('_', "-").to_ascii_lowercase();
let parts: Vec<&str> = tag.split('-').collect();
let base = parts.first().copied().unwrap_or("");
if base.is_empty() || base == "en" {
return Vec::new();
}
let mut out: Vec<String> = Vec::new();
for n in (1..=parts.len()).rev() {
let prefix = parts.get(..n).unwrap_or_default();
// The prefix, then without its regions: the variant's pack before the region alone.
let stripped: Vec<&str> = prefix.iter().enumerate().filter(|(i, p)| *i == 0 || !is_region(p)).map(|(_, p)| *p).collect();
for c in [prefix.join("-"), stripped.join("-")] {
if !out.contains(&c) {
out.push(c);
}
}
}
out
}
/// The pack index this build trusts: craft-i18n's Language pack release `language-packs-2` (75
/// packs), pinned by the sha256 of its `index.json`. The font store reads
/// `CRAFT_LANGUAGE_PACK_INDEX` itself, to try packs from a test index (testing only).
@@ -380,6 +514,12 @@ impl Backend for FontStoreBackend {
fn index_override(&self) -> Option<String> {
craft_font_store::language_pack_index_overridden()
}
fn enable_downloads(&self) -> Result<(), String> {
// The store is opened as an agent's, which can't turn downloading on: the same folder,
// opened as the person's, does (the setting is a file in it, read on each use).
craft_font_store::FontStore::new(self.store.dir().to_path_buf(), craft_font_store::Caller::User).enable_network().map_err(|e| e.to_string())
}
}
/// The font store backend in `dir`, for tests that need the real store without a request.
+15 -2
View File
@@ -373,6 +373,9 @@ impl Session {
let previewed = !Arc::ptr_eq(&st.doc, &interaction.doc) || st.selection != *interaction.selection;
let shown = previewed.then(|| (st.doc.clone(), st.selection.clone()));
if previewed {
if st.doc.peek_next_id() > interaction.doc.peek_next_id() {
st.rollbacks += 1;
}
st.doc = interaction.doc.clone();
if let Some((shown_doc, _)) = shown.as_ref().filter(|_| interaction.dialog) {
shown_base_selection(&mut st.selection, shown_doc, &st.doc);
@@ -667,7 +670,7 @@ impl Session {
// `defaultsOnly: true`, and one after it.
let tool_paints = self.tool_paints(false) || self.tool_paints(true);
let new_art_basic = self.prefs.new_art_basic;
let (paint, restore_paint, inherited, last_preview_paint) = {
let (paint, restore_paint, inherited, last_preview_paint, discarded_uid, freed_ids, discarded) = {
let menu = self.menu.clone();
let st = self.doc_mut()?;
let Some(it) = &mut st.interaction else { return Err(EngineError::Other("no interaction in progress".into())) };
@@ -678,6 +681,8 @@ impl Session {
st.revision += 1;
}
let undone = std::mem::replace(&mut st.doc, it.doc.clone());
let freed_ids = undone.peek_next_id() > it.doc.peek_next_id();
let discarded = !Arc::ptr_eq(&undone, &it.doc);
let isolation = it.isolation;
// A batch, or a preview that changed the new-art paints (a pattern rename), started from
// the paints the interaction began with.
@@ -711,7 +716,7 @@ impl Session {
// undone with it.
st.restore_isolation(isolation, &undone);
cmd::globaledit::follow_history(st);
(paint, restore_paint, inherited, last_preview_paint)
(paint, restore_paint, inherited, last_preview_paint, st.uid, freed_ids, discarded)
};
// The paints before the previews that build on each other: a preview that starts from the
// interaction's paints (or from the inherited ones) starts a new run of them. A field that
@@ -757,6 +762,14 @@ impl Session {
}
let after_paint = r.is_ok().then(|| (base, self.paint.clone()));
let after_item = self.active_appearance_item.clone();
// A preview advances rollbacks when it discards an earlier preview that allocated node IDs, or
// fails after discarding an earlier preview's document change, even when the command activates
// another document.
if let Some(st) = self.docs.iter_mut().find(|d| d.uid == discarded_uid)
&& (freed_ids || (r.is_err() && discarded))
{
st.rollbacks += 1;
}
let st = self.doc_mut()?;
if let Some(it) = &mut st.interaction {
it.active_appearance_item =
+3
View File
@@ -473,6 +473,9 @@ impl Session {
for (uid, doc, selection, interaction, history) in snapshot {
// A document the command closed stays closed.
let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid) else { continue };
if !std::sync::Arc::ptr_eq(&st.doc, &doc) {
st.rollbacks += 1;
}
st.doc = doc;
st.selection = selection;
st.interaction = interaction;
+184
View File
@@ -829,6 +829,190 @@ fn canceling_undo_groups_in_two_documents_drops_the_edits_of_both_from_the_journ
assert_eq!(ids.last(), Some(&"edit.undoGroup.end"));
}
/// Exit Symbol Editing Mode with nothing changed takes back the entering step, which puts back an older snapshot, so
/// it advances `rollbacks`; leaving after an edit adds a step and leaves it as it is.
#[test]
fn leaving_symbol_editing_advances_rollbacks_only_when_taking_back_the_entering_step() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("shape.rectangle", &rect_step(10)["params"]).unwrap();
s.execute("symbol.new", &json!({"name": "Box"})).unwrap();
for edited in [false, true] {
let rollbacks = s.doc().unwrap().rollbacks;
s.execute("symbol.edit", &json!({})).unwrap();
if edited {
s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap();
}
s.execute("symbol.exitEditing", &json!({})).unwrap();
if edited {
assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "leaving after an edit keeps the rollback count");
} else {
assert!(s.doc().unwrap().rollbacks > rollbacks, "taking back the entering step advances the rollback count");
}
}
}
/// Discard Empty Type advances `rollbacks` when it takes back the step that made the empty text, which frees the
/// text's node ID; when it removes the text as a new step instead, it leaves the count as it is.
#[test]
fn discard_empty_type_advances_rollbacks_only_when_taking_back_the_step_that_made_the_text() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let made = s.execute("text.create", &json!({"x": 10, "y": 40, "text": ""})).unwrap();
let rollbacks = s.doc().unwrap().rollbacks;
s.execute("text.discardEmpty", &json!({"id": made["id"]})).unwrap();
assert!(s.doc().unwrap().rollbacks > rollbacks, "taking back the step that made the text advances the rollback count");
let kept = s.execute("text.create", &json!({"x": 10, "y": 80, "text": ""})).unwrap();
s.execute("shape.rectangle", &rect_step(10)["params"]).unwrap();
let rollbacks = s.doc().unwrap().rollbacks;
s.execute("text.discardEmpty", &json!({"id": kept["id"]})).unwrap();
assert!(s.doc().unwrap().doc.node(NodeId(kept["id"].as_u64().unwrap())).is_none(), "the empty text is removed");
assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "removing the text as a new step keeps the rollback count");
}
/// A command that panics after changing a document advances that document's `rollbacks` when the document is put
/// back; one that panics before changing it leaves the count as it is.
#[test]
fn a_panicking_command_advances_rollbacks_only_when_it_changed_the_document() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let a = NodeId(s.execute("shape.rectangle", &rect_step(10)["params"]).unwrap()["id"].as_u64().unwrap());
for changed in [false, true] {
let rollbacks = s.doc().unwrap().rollbacks;
let r = s.run_guarded("test.panic", |s| {
if changed {
let st = s.doc_mut()?;
std::sync::Arc::make_mut(&mut st.doc).remove(a)?;
}
s.run_nested(|_| panic!("boom"))
});
assert!(matches!(r, Err(EngineError::Internal { .. })), "the panic is returned as an internal error");
if changed {
assert!(s.doc().unwrap().rollbacks > rollbacks, "putting back the changed document advances the rollback count");
} else {
assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "a panic before any change keeps the rollback count");
}
}
}
/// Canceling an interaction whose preview changed the document advances `rollbacks`; canceling one that changed
/// nothing leaves it as it is.
#[test]
fn interaction_cancellation_advances_rollbacks_only_when_restoring() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
for previewed in [true, false] {
let rollbacks = s.doc().unwrap().rollbacks;
s.begin_interaction("Rectangle").unwrap();
if previewed {
s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap();
}
s.cancel_interaction().unwrap();
if previewed {
assert!(s.doc().unwrap().rollbacks > rollbacks, "a canceled preview advances the rollback count");
} else {
assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "a cancel with no preview keeps the rollback count");
}
}
}
/// A preview advances `rollbacks` when it discards earlier art and frees its node IDs, whether it
/// succeeds or fails. A failed preview also advances it when it discards an earlier document change
/// without freeing IDs. A successful preview that draws the earlier art again also advances the count.
#[test]
fn a_preview_that_discards_earlier_art_and_frees_its_ids_advances_rollbacks() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let rollbacks = s.doc().unwrap().rollbacks;
s.begin_interaction("Rectangle").unwrap();
s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap();
assert!(s.preview("unknown.command", &json!({})).is_err(), "an unknown preview command returns an error");
assert!(s.doc().unwrap().rollbacks > rollbacks, "a failed preview after a drawn preview advances the rollback count");
s.cancel_interaction().unwrap();
let rollbacks = s.doc().unwrap().rollbacks;
s.begin_interaction("Rectangle").unwrap();
assert!(s.preview("unknown.command", &json!({})).is_err(), "an unknown preview command returns an error");
assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "a failed preview with nothing previewed keeps the rollback count");
s.cancel_interaction().unwrap();
let rollbacks = s.doc().unwrap().rollbacks;
s.begin_interaction("Rectangle").unwrap();
s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap();
s.preview("shape.rectangle", &rect_step(30)["params"]).unwrap();
assert_eq!(s.doc().unwrap().rollbacks, rollbacks + 1, "a preview that replaces earlier drawn art advances the rollback count");
s.cancel_interaction().unwrap();
let rollbacks = s.doc().unwrap().rollbacks;
let starting_doc = s.doc().unwrap().doc.clone();
s.begin_interaction("Rectangle").unwrap();
s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap();
s.preview("select.set", &json!({"ids": []})).unwrap();
assert!(std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &starting_doc), "a selection-only preview leaves the starting document Arc");
assert_eq!(
s.doc().unwrap().rollbacks,
rollbacks + 1,
"a preview that leaves the starting document after a drawn preview advances the rollback count"
);
s.cancel_interaction().unwrap();
let kept = s.execute("shape.rectangle", &rect_step(5)["params"]).unwrap()["id"].clone();
let rollbacks = s.doc().unwrap().rollbacks;
let starting_doc = s.doc().unwrap().doc.clone();
s.begin_interaction("Rectangle").unwrap();
s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap();
let steps = json!({"commands": [
{"command": "select.set", "params": {"ids": [kept]}},
{"command": "object.move", "params": {"dx": 5, "dy": 0}}
]});
s.preview("command.batch", &steps).unwrap();
assert!(!std::sync::Arc::ptr_eq(&s.doc().unwrap().doc, &starting_doc), "the move changes the document");
assert_eq!(s.doc().unwrap().rollbacks, rollbacks + 1, "a preview that moves art instead of drawing it advances the rollback count");
s.cancel_interaction().unwrap();
}
/// A command run during a tool interaction sets the preview aside and can reuse the node IDs the
/// preview allocated, so it advances `rollbacks`; with no IDs allocated by the preview it does not.
#[test]
fn a_command_outside_a_tool_interaction_advances_rollbacks_only_when_the_preview_allocated_ids() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.begin_interaction("Rectangle").unwrap();
// A tool interaction routes the command through outside_interaction.
s.active_mut().unwrap().interaction.as_mut().unwrap().tool = true;
let preview_id = s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap()["id"].clone();
let rollbacks = s.doc().unwrap().rollbacks;
let command_id = s.execute("shape.rectangle", &rect_step(30)["params"]).unwrap()["id"].clone();
assert_eq!(command_id, preview_id, "a command outside a tool interaction reuses the rectangle preview's node ID");
assert_eq!(s.doc().unwrap().rollbacks, rollbacks + 1, "setting aside a preview that allocated IDs advances the rollback count");
s.cancel_interaction().unwrap();
for previewed in [true, false] {
s.begin_interaction("Rectangle").unwrap();
s.active_mut().unwrap().interaction.as_mut().unwrap().tool = true;
if previewed {
s.preview("select.none", &json!({})).unwrap();
}
let rollbacks = s.doc().unwrap().rollbacks;
s.execute("shape.rectangle", &rect_step(50)["params"]).unwrap();
assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "a command with no preview IDs keeps the rollback count, previewed: {previewed}");
s.cancel_interaction().unwrap();
}
}
/// A preview that activates another document advances rollbacks in the document whose art it discards.
#[test]
fn a_preview_that_activates_another_document_advances_only_the_source_rollbacks() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("document.activate", &json!({"index": 0})).unwrap();
let source_rollbacks = s.documents()[0].rollbacks;
let destination_rollbacks = s.documents()[1].rollbacks;
s.begin_interaction("Rectangle").unwrap();
s.preview("shape.rectangle", &rect_step(10)["params"]).unwrap();
s.preview("document.activate", &json!({"index": 1})).unwrap();
assert_eq!(s.active_index(), Some(1), "the activation preview makes the destination document active");
assert!(s.documents()[0].rollbacks > source_rollbacks, "discarding the rectangle preview advances the source document's rollback count");
assert_eq!(s.documents()[1].rollbacks, destination_rollbacks, "the activation preview keeps the destination document's rollback count unchanged");
}
/// A cancel drops only the canceled groups' own entries from the journal: an edit made in another
/// document while a group was open stays in that document and in the journal.
#[test]
+97
View File
@@ -265,3 +265,100 @@ fn a_script_cannot_install_a_pack() {
assert!(installed_locales(&mut s).is_empty(), "nothing installed");
assert_eq!(s.execute("proof.installPack", &json!({"locale": "nl"})).unwrap()["installed"], true, "outside a script it installs");
}
/// A backend that only lists `packs` (the index fetched last), for what the missing-pack bar offers.
struct Listing {
dir: PathBuf,
packs: Vec<Pack>,
}
impl Backend for Listing {
fn packs_dir(&self) -> PathBuf {
self.dir.clone()
}
fn downloads_on(&self) -> bool {
false
}
fn cached_index(&self) -> Vec<Pack> {
self.packs.clone()
}
fn fetch_index(&self, _: &Cancel) -> std::result::Result<Vec<Pack>, String> {
Err("downloading is off".into())
}
fn install(&self, _: &str, _: &Cancel, _: &mut dyn FnMut(u64, u64)) -> std::result::Result<(), String> {
Err("downloading is off".into())
}
fn remove(&self, _: &str) -> std::result::Result<(), String> {
Ok(())
}
}
fn pack(locale: &str) -> Pack {
Pack { locale: locale.into(), name: locale.into(), size: 1, licence: "MIT".into(), class: "Embeddable".into(), spelling: true, hyphenation: true }
}
/// `proof.packs`'s `missing`, as (lang, locale).
fn missing(s: &mut Session) -> Vec<(String, Value)> {
let r = s.execute("proof.packs", &json!({})).unwrap();
r["missing"].as_array().unwrap().iter().map(|m| (m["lang"].as_str().unwrap().to_string(), m["locale"].clone())).collect()
}
/// The missing-pack bar offers the languages of the document's type that have no dictionary: a
/// pack the index lists, or, before the index was ever fetched, the language alone; never one the
/// fetched index has no pack for, nor English.
#[test]
fn the_languages_with_no_dictionary_are_offered_their_pack() {
let _turn = packs_lock();
let root = folder("missing");
let _reset = Reset(root.clone());
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap();
s.execute("text.create", &json!({"x": 10, "y": 50, "text": "The house"})).unwrap();
// Konkani: no system has a Hunspell dictionary for it, so the check can't depend on the machine.
let id = s.execute("text.create", &json!({"x": 10, "y": 90, "text": "घर"})).unwrap()["id"].clone();
s.execute("text.setFormat", &json!({"ids": [id], "language": "Konkani"})).unwrap();
assert!(missing(&mut s).is_empty(), "no store, nothing to offer");
let listing = |packs: Vec<Pack>| Some(Arc::new(Listing { dir: root.clone(), packs }) as Arc<dyn Backend>);
packs::set_backend(listing(vec![]));
assert_eq!(missing(&mut s), [("kok".to_string(), Value::Null)], "before the first fetch, the language alone");
packs::set_backend(listing(vec![pack("nl"), pack("kok")]));
assert_eq!(missing(&mut s), [("kok".to_string(), json!("kok"))], "the pack the index lists");
packs::set_backend(listing(vec![pack("nl")]));
assert!(missing(&mut s).is_empty(), "the index has no pack for it");
}
/// A pack is found for a tag's region and variant forms (`sr-Latn-RS` is `sr-latn`'s, `nl-BE`
/// is `nl`'s), not for English.
#[test]
fn a_tag_finds_its_pack_without_its_region() {
let index = [pack("nl"), pack("sr-latn"), pack("ca-valencia"), pack("pt-pt")];
let found = |tag: &str| packs::pack_for_tag(tag, &index).map(|p| p.locale.clone());
assert_eq!(found("nl-BE").as_deref(), Some("nl"));
assert_eq!(found("sr-Latn-RS").as_deref(), Some("sr-latn"));
assert_eq!(found("ca-ES-valencia").as_deref(), Some("ca-valencia"));
assert_eq!(found("pt_PT").as_deref(), Some("pt-pt"));
assert_eq!(found("en-NL"), None);
assert_eq!(found("fy"), None);
}
/// Downloading is turned on in the shared store only by the app for the person's click
/// (`packs::enable_downloads`); a backend that can't (a stand-in) refuses.
#[test]
fn the_persons_click_turns_downloading_on_in_the_shared_store() {
let _turn = packs_lock();
let root = folder("consent");
let _reset = Reset(root.clone());
let mut s = dutch_session();
assert!(packs::enable_downloads().is_err(), "no store");
packs::set_backend(Some(Arc::new(Listing { dir: root.clone(), packs: vec![] })));
assert!(packs::enable_downloads().is_err(), "a backend that can't turn it on");
packs::set_backend(Some(packs::font_store_in(root.clone())));
assert_eq!(s.execute("proof.packs", &json!({})).unwrap()["downloads"], false);
packs::enable_downloads().unwrap();
assert_eq!(s.execute("proof.packs", &json!({})).unwrap()["downloads"], true, "the store the agent opened sees it on");
}
+47
View File
@@ -8131,6 +8131,19 @@ fn install_select_all_then_remove(s: &mut Session, id: &str) {
run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true}));
}
/// Installs a filter `id` that calls `shape.rectangle` and then returns no objects.
fn install_draw_rectangle_then_remove(s: &mut Session, id: &str) {
let grant = json!(["doc.read", "doc.write", "commands"]);
let manifest =
format!(r#"{{"id":"{id}","name":"Test {id}","kind":"filter","api":2,"permissions":{grant},"commandAllowlist":["shape.rectangle"]}}"#);
let imports = r#"(import "env" "vc_call" (func $vc_call (param i32 i32 i32 i32) (result i32)))
(data (i32.const 0x2000) "shape.rectangle")
(data (i32.const 0x2100) "{\22x\22:0,\22y\22:0,\22width\22:5,\22height\22:5}")"#;
let first = "(drop (call $vc_call (i32.const 0x2000) (i32.const 15) (i32.const 0x2100) (i32.const 34)))";
let wasm = wat::parse_str(tpl::with_imports(&manifest, imports, first, r#"{"objects":[]}"#)).unwrap();
run(s, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&wasm), "grant": grant, "replace": true}));
}
/// Runs the job of a run that [`FilterRun::begin_calls`] started as the web build's plug-in worker
/// does, making each command call in `s` → its output.
fn run_job_away(s: &mut Session, job: &cmd::plugin::FilterJob) -> Vec<u8> {
@@ -8201,6 +8214,40 @@ fn a_calling_run_made_away_from_the_session_that_ends_changes_nothing() {
run(&mut s, "plugin.remove", json!({"id": id}));
}
/// A run made away from the session that ends after its calls changed the document advances `rollbacks`.
/// A run whose calls only changed the selection or that ends before any call keeps the rollback count.
#[test]
fn an_ended_calling_run_advances_rollbacks_only_when_its_calls_changed_the_document() {
use cmd::plugin::FilterRun;
let id = "test.engine.callsawayrollback";
let draw_id = "test.engine.callsawayrollbackdraw";
let mut s = session();
install_select_all_then_remove(&mut s, id);
install_draw_rectangle_then_remove(&mut s, draw_id);
let (a, _) = (rect(&mut s, 10.0, "#ff0000"), rect(&mut s, 40.0, "#00ff00"));
for (plugin_id, called, changed_document) in [(draw_id, true, true), (id, true, false), (id, false, false)] {
run(&mut s, "select.set", json!({"ids": [a.0]}));
let rollbacks = s.doc().unwrap().rollbacks;
let job = FilterRun::begin_calls(&mut s, "plugin.run", &json!({"id": plugin_id})).unwrap();
let doc = s.doc().unwrap().doc.clone();
if called {
run_job_away(&mut s, &job);
assert_eq!(!std::sync::Arc::ptr_eq(&doc, &s.doc().unwrap().doc), changed_document, "the calls change only the intended state");
assert_ne!(s.doc().unwrap().selection.objects, vec![a], "the calls change the selection");
}
s.end_plugin_calls();
if changed_document {
assert!(s.doc().unwrap().rollbacks > rollbacks, "an ended run whose calls changed the document advances the rollback count");
} else if called {
assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "an ended run whose calls only changed the selection keeps the rollback count");
} else {
assert_eq!(s.doc().unwrap().rollbacks, rollbacks, "an ended run with no calls keeps the rollback count");
}
}
run(&mut s, "plugin.remove", json!({"id": draw_id}));
run(&mut s, "plugin.remove", json!({"id": id}));
}
/// An output handed in for a run that holds the documents is dropped when that run ends: a later
/// run with the same input and params is not given it, and `plugin.run` without its own output is
/// refused.
+110 -3
View File
@@ -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");
}
+15
View File
@@ -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]
+1 -1
View File
@@ -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(
+1 -1
View File
@@ -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;
+4 -5
View File
@@ -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
+24 -7
View File
@@ -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 {
+78 -10
View File
@@ -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)
}
+92 -2
View File
@@ -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");
}
+1 -1
View File
@@ -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).
+5
View File
@@ -181,6 +181,7 @@ impl VectorcraftApp {
multi_color: None,
global_edit_count: None,
shape_angle: None,
shape_edit_target: None,
radius_corners: None,
selected_rectangles: None,
trace_presets: None,
@@ -253,6 +254,8 @@ impl VectorcraftApp {
trace_runs: Default::default(),
concept_runs: Default::default(),
retype_runs: Default::default(),
#[cfg(not(target_arch = "wasm32"))]
language_packs: Default::default(),
recovery: Default::default(),
closing: None,
prefs: None,
@@ -696,6 +699,7 @@ impl VectorcraftApp {
if self.session.poll_language_packs() {
ctx.request_repaint_after(std::time::Duration::from_millis(250));
}
crate::language_packs::tick(self, ctx);
if self.session.plugins_loading() {
if self.session.poll_plugin_loads() {
ctx.request_repaint_after(std::time::Duration::from_millis(50));
@@ -768,6 +772,7 @@ impl VectorcraftApp {
&& let Some(view) = app.canvas_view()
{
chrome::isolation_bar(app, ui, view.rect);
crate::language_packs::bar(app, ui, view.rect);
}
});
}
+2
View File
@@ -160,6 +160,8 @@ pub struct CanvasCache {
pub(crate) global_edit_count: Option<(crate::panels::properties::GlobalEditKey, usize)>,
/// The selected live shape's angle, for (document uid, revision, kind of shape).
pub shape_angle: Option<ShapeAngleCache>,
/// The shape-wide edit target, for (document uid, revision).
pub(crate) shape_edit_target: Option<((u64, u64), egui::IdSalt)>,
/// The corners a live shape's Corner Radius field sets, as one hash, for (document uid,
/// File › Revert count, revision).
pub(crate) radius_corners: Option<((u64, u64, u64), u64)>,
+3 -1
View File
@@ -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};
+20 -14
View File
@@ -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.
+1 -1
View File
@@ -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] };
+43 -12
View File
@@ -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
+14 -2
View File
@@ -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()
+1
View File
@@ -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,
+121 -2
View File
@@ -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
+1 -1
View File
@@ -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
+10 -5
View File
@@ -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);
+57
View File
@@ -0,0 +1,57 @@
//! Language packs in the window (#4936): Preferences › Language Packs lists the packs that spell-check and
//! hyphenate languages other than English, with Install and Remove, and the missing-pack bar over the canvas offers
//! the pack for a language the document's type is in. The engine does the work ([`vectorcraft_engine::packs`]):
//! installs run on its thread, and the buttons go through `proof.installPack`, `proof.removePack` and
//! `proof.packs {refresh}`, as an agent's would.
//!
//! The one step no command takes is turning on the font store's downloading (RFC-0011): the person's own click on
//! Install, Get Language Pack or Refresh List is their consent, and it turns downloading on for every Craft app. A
//! click the control channel injected never does; an agent can install once the person has turned it on.
//!
//! The web build has no font store yet (storytold/craft-libs#745): the page says so and the bar never shows.
#[cfg(target_arch = "wasm32")]
use craft::theme::variant::Tone;
use craft::ui::contract::{Show as _, ShowContainer as _};
use craft::ui::display::Text;
use craft::ui::layout_components::Stack;
#[cfg(target_arch = "wasm32")]
use craft::ui::notices::Notice;
use egui::Ui;
use crate::VectorcraftApp;
#[cfg(not(target_arch = "wasm32"))]
mod desktop;
#[cfg(not(target_arch = "wasm32"))]
pub use desktop::Runtime;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use desktop::{bar, tick};
/// The Preferences page's id (its English title), beside the categories of the engine's preference table.
pub const PAGE: &str = "Language Packs";
/// Once a frame: nothing on the web.
#[cfg(target_arch = "wasm32")]
pub(crate) fn tick(_app: &mut VectorcraftApp, _ctx: &egui::Context) {}
/// The missing-pack bar: never on the web, which can't install packs.
#[cfg(target_arch = "wasm32")]
pub(crate) fn bar(_app: &mut VectorcraftApp, _ui: &mut Ui, _area: egui::Rect) {}
/// Preferences › Language Packs: what packs are, then (on the desktop) whether downloading is on, the installed packs
/// with Remove, and the packs of the list with Install, each with its progress or its last failure.
pub(crate) fn page(app: &mut VectorcraftApp, ui: &mut Ui) {
Stack::new().show(ui, |ui, _| {
Text::new(tl!("Language packs add spelling and hyphenation for languages other than English. They are shared with the other Craft apps."))
.show(ui);
#[cfg(target_arch = "wasm32")]
{
let _ = &app;
Notice::new(Tone::Info, tl!("Language packs can't be installed in the browser yet: only English is spell-checked here.")).show(ui);
}
#[cfg(not(target_arch = "wasm32"))]
desktop::page(app, ui);
});
}
@@ -0,0 +1,425 @@
//! The desktop's Language packs: the Preferences page's list and the missing-pack bar, over the engine's packs
//! ([`vectorcraft_engine::packs`]), which the web build doesn't have.
use std::collections::{BTreeMap, BTreeSet};
use craft::theme::variant::Tone;
use craft::ui::buttons::Button;
use craft::ui::contract::{Politeness, Props as _, Show as _, ShowContainer as _};
use craft::ui::display::{Progress, Text};
use craft::ui::layout_components::Row;
use craft::ui::notices::Notice;
use craft::ui::patterns::language_packs::{
self, BarOffer, BarState, Consent, LanguagePackWords, MissingPackBar, injected, shown, shown_error, size_text,
};
use craft::ui::runtime::env::Env;
use egui::Ui;
use serde_json::json;
use vectorcraft_engine::packs::{self, Missing, Pack};
use crate::VectorcraftApp;
/// Most characters of a language's name shown (an index may name it at any length).
const MAX_NAME: usize = 40;
/// How long the bar keeps what it worked out while the document is being edited.
const MISSING_REFRESH_SECS: f64 = 1.0;
/// The window's pack state.
#[derive(Default)]
pub struct Runtime {
/// Failures of the window's own (turning downloading on, a command it ran), by locale or language tag (`""`:
/// the list), shown until the next try. The engine keeps the installs' own.
errors: BTreeMap<String, String>,
/// The keys of `errors` that say only the person can turn downloading on: dropped once it is on.
refused: BTreeSet<String>,
/// (document, pack locale or language tag) pairs whose bar was closed.
dismissed: BTreeSet<(u64, String)>,
/// The language tag whose bar asked for the list: its pack installs once the list arrives.
wanted: Option<String>,
/// The installs running when last looked at, to announce each one's end.
running: BTreeSet<String>,
/// What the bar offers for the front document, what it was worked out from, and when.
missing: Option<(MissingKey, f64, Vec<Missing>)>,
/// The index fetched last, and what it was read for (the list is read from disk, so not every frame).
index: Option<(IndexKey, Vec<Pack>)>,
}
impl Runtime {
/// Keeps `message` as the failure for `key`, in place of a refusal it had: downloading coming on drops only
/// refusals, so this one stays.
fn fail(&mut self, key: impl Into<String>, message: String) {
let key = key.into();
self.refused.remove(&key);
self.errors.insert(key, message);
}
/// Forgets the failure (or refusal) for `key`: a new try is starting.
fn clear(&mut self, key: &str) {
self.refused.remove(key);
self.errors.remove(key);
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
struct MissingKey {
document: u64,
revision: u64,
/// The installed packs changed.
generation: u64,
/// A fetch of the list started or ended.
refreshing: bool,
/// A fetch of the list ended (one can start and end between two frames).
index: u64,
}
/// Whether a fetch of the list was running, the fetches that ended, and the installed packs' generation.
type IndexKey = (bool, u64, u64);
/// A language as the window names it: the interface's name for a document language (`Hindi`), with the pack's own
/// name after it when that differs (`Hindi (हिन्दी)`); the pack's own name alone for a language the documents'
/// list doesn't have; the tag when there is neither.
pub(crate) fn language_name(tag: &str, own: Option<&str>) -> String {
let own = own.map(|o| shown(o, MAX_NAME)).filter(|o| !o.is_empty());
let primary = |t: &str| t.split(['-', '_']).next().unwrap_or_default().to_ascii_lowercase();
let languages = vectorcraft_doc::setup::LANGUAGES;
let known = languages
.iter()
.find(|(_, t, _)| t.eq_ignore_ascii_case(tag))
.or_else(|| languages.iter().find(|(_, t, _)| primary(t) == primary(tag)))
.map(|(name, _, _)| tl!(name).to_string());
match (known, own) {
(Some(k), Some(o)) if k != o => format!("{k} ({o})"),
(Some(k), _) => k,
(None, Some(o)) => o,
(None, None) => shown(tag, MAX_NAME),
}
}
/// What a pack provides, as the list says it.
fn provides(p: &Pack) -> String {
match (p.spelling, p.hyphenation) {
(true, true) => tl!("Spelling and hyphenation").to_string(),
(true, false) => tl!("Spelling").to_string(),
(false, true) => tl!("Hyphenation").to_string(),
(false, false) => String::new(),
}
}
/// Once a frame: announces the installs that ended, and installs the pack the bar asked the list for once it
/// arrives.
pub(crate) fn tick(app: &mut VectorcraftApp, ctx: &egui::Context) {
if !app.language_packs.refused.is_empty() && packs::backend().is_some_and(|b| b.downloads_on()) {
// Downloading came on (Refresh List, the bar, another Craft app): the refusals no longer hold.
let refused = std::mem::take(&mut app.language_packs.refused);
app.language_packs.errors.retain(|key, _| !refused.contains(key));
}
let status = packs::status();
let now: BTreeSet<String> = status.installing.iter().map(|(l, _, _)| l.clone()).collect();
let ended: Vec<String> = app.language_packs.running.difference(&now).cloned().collect();
// The installs running now, an agent's too, and the ones the window started that haven't ended.
app.language_packs.running = now;
if !ended.is_empty() {
for locale in ended {
// The status bar is a live region: the end is announced wherever focus is.
announce_end(app, &locale, status.errors.get(&locale).map(String::as_str));
}
app.language_packs.missing = None;
}
if status.refreshing {
return;
}
let Some(tag) = app.language_packs.wanted.take() else { return };
app.language_packs.index = None;
app.language_packs.missing = None;
if let Some(e) = status.errors.get("") {
let message = crate::i18n::fmt(tl!("Couldn't get the list of Language packs: {error}"), &[("error", &shown_error(e))]);
app.language_packs.fail(tag, message.clone());
app.status(message);
} else if let Some(pack) = packs::pack_for_tag(&tag, &packs::available()).cloned() {
// The person's click asked for it, and turned downloading on.
install(app, &pack.locale);
// The session already checked for work this frame. Wake it even if the install ends before the next check.
ctx.request_repaint();
} else {
let name = language_name(&tag, None);
app.status(crate::i18n::fmt(tl!("There is no Language pack for {language} yet."), &[("language", &name)]));
}
}
/// Handles the shared consent decision and remembers which messages are only temporary refusals.
fn consent(app: &mut VectorcraftApp, ui: &Ui, injected: bool, key: &str) -> bool {
app.language_packs.clear(key);
let Some(backend) = packs::backend() else { return false };
let decision = language_packs::consent(backend.downloads_on(), injected, packs::enable_downloads);
if let Some(message) = decision.message(&Env::of(ui).words::<LanguagePackWords>()) {
app.language_packs.fail(key, message);
if decision == Consent::Refused {
app.language_packs.refused.insert(key.to_string());
}
}
decision.is_on()
}
/// `proof.installPack` for `locale`; a refusal is kept for its row. An install that started is watched from now on,
/// so its end is announced even when it ends before the next frame looks; one that is done already is announced now.
fn install(app: &mut VectorcraftApp, locale: &str) {
app.language_packs.clear(locale);
match app.run("proof.installPack", json!({ "locale": locale })) {
Ok(r) if r["installed"] == true => announce_end(app, locale, None),
Ok(_) => {
app.language_packs.running.insert(locale.to_string());
}
Err(e) => {
app.language_packs.fail(locale.to_string(), shown_error(&e));
announce_end(app, locale, Some(&e));
}
}
app.language_packs.missing = None;
}
/// Says in the status bar, a live region, that the install of `locale` ended: installed, or its `error`.
fn announce_end(app: &mut VectorcraftApp, locale: &str, error: Option<&str>) {
let own = packs::installed().into_iter().find(|i| i.locale == locale).map(|i| i.name);
let name = language_name(locale, own.as_deref());
let message = match error {
Some(e) => {
crate::i18n::fmt(tl!("Couldn't install the {language} Language pack: {error}"), &[("language", &name), ("error", &shown_error(e))])
}
None => crate::i18n::fmt(tl!("The {language} Language pack is installed."), &[("language", &name)]),
};
app.status(message);
}
/// Removes through `proof.removePack`; a failure is kept for its row and announced.
fn remove(app: &mut VectorcraftApp, locale: &str) {
app.language_packs.clear(locale);
let own = packs::installed().into_iter().find(|p| p.locale == locale).map(|p| p.name);
let name = language_name(locale, own.as_deref());
let message = match app.run("proof.removePack", json!({ "locale": locale })) {
Ok(_) => crate::i18n::fmt(tl!("The {language} Language pack is removed."), &[("language", &name)]),
Err(e) => {
let error = shown_error(&e);
app.language_packs.fail(locale.to_string(), error.clone());
crate::i18n::fmt(tl!("Couldn't remove the {language} Language pack: {error}"), &[("language", &name), ("error", &error)])
}
};
app.status(message);
app.language_packs.missing = None;
}
/// `proof.packs {refresh: true}` (fetching runs on the engine's thread); a refusal is kept under `key` → whether
/// the fetch started.
fn refresh(app: &mut VectorcraftApp, key: &str) -> bool {
app.language_packs.index = None;
match app.run("proof.packs", json!({ "refresh": true })) {
Ok(_) => true,
Err(e) => {
app.language_packs.fail(key.to_string(), shown_error(&e));
false
}
}
}
/// The index fetched last, read again only when a fetch starts or ends or the installed packs change.
fn index(app: &mut VectorcraftApp) -> Vec<Pack> {
let key = (packs::status().refreshing, packs::index_generation(), packs::generation());
if let Some((k, list)) = &app.language_packs.index
&& *k == key
{
return list.clone();
}
let list = packs::available();
app.language_packs.index = Some((key, list.clone()));
list
}
/// The failure to show for `locale` (`""`: the list): the window's own, else the engine's last.
fn error_of(app: &VectorcraftApp, errors: &BTreeMap<String, String>, locale: &str) -> Option<String> {
app.language_packs.errors.get(locale).cloned().or_else(|| errors.get(locale).map(|e| shown_error(e)))
}
/// The share of an install done, from its bytes (`total` 0: not known yet).
fn fraction(done: u64, total: u64) -> f32 {
if total == 0 { 0.0 } else { (done.min(total) as f64 / total as f64) as f32 }
}
/// "Installing… 40%" for an install's bytes.
fn installing_text(done: u64, total: u64) -> String {
let percent = (fraction(done, total) * 100.0).round().to_string();
crate::i18n::fmt(tl!("Installing… {percent}%"), &[("percent", &percent)])
}
/// The desktop part of Preferences › Language Packs ([`super::page`]).
pub(super) fn page(app: &mut VectorcraftApp, ui: &mut Ui) {
let Some(backend) = packs::backend() else {
Notice::new(Tone::Warn, tl!("Language packs aren't available: there is no font store folder for this user.")).show(ui);
return;
};
let injected = injected(ui.ctx());
let status = packs::status();
let list = index(app);
let installed = packs::installed();
if !backend.downloads_on() {
Text::new(tl!("Downloading is off. Install or Refresh List turns it on, for every Craft app.")).show(ui);
}
if let Some(test) = backend.index_override() {
Notice::new(Tone::Warn, crate::i18n::fmt(tl!("Packs come from a test list: {source}"), &[("source", &shown_error(&test))])).show(ui);
}
let mut refresh_clicked = false;
Row::new().wrap(true).show(ui, |ui, _| {
refresh_clicked |= Button::new(tl!("Refresh List")).enabled(!status.refreshing).show(ui).clicked();
if status.refreshing {
Text::new(tl!("Getting the list of languages…")).show(ui);
}
});
if let Some(e) = error_of(app, &status.errors, "") {
let message = crate::i18n::fmt(tl!("Couldn't get the list of Language packs: {error}"), &[("error", &e)]);
Notice::new(Tone::Bad, message).announce(Politeness::Assertive).show(ui);
}
// The installed packs, whether or not the list has them (another app may have installed one from a newer list).
Text::new(tl!("Installed")).show(ui);
if installed.is_empty() {
Text::new(tl!("No Language packs are installed.")).show(ui);
}
let mut remove_clicked: Option<String> = None;
for pack in &installed {
let name = language_name(&pack.locale, Some(&pack.name));
Row::new().wrap(true).show(ui, |ui, _| {
Text::new(name.clone()).show(ui);
Text::new(shown(&pack.licence, MAX_NAME)).show(ui);
if Button::new(tl!("Remove")).show(ui).clicked() {
remove_clicked = Some(pack.locale.clone());
}
});
if let Some(e) = error_of(app, &status.errors, &pack.locale) {
Notice::new(Tone::Bad, e).announce(Politeness::Assertive).show(ui);
}
}
Text::new(tl!("Available")).show(ui);
if list.is_empty() && !status.refreshing {
Text::new(tl!("The list of Language packs hasn't been fetched yet: Refresh List gets it.")).show(ui);
}
let mut install_clicked: Option<String> = None;
for pack in list.iter().filter(|p| !installed.iter().any(|i| i.locale == p.locale)) {
let name = language_name(&pack.locale, Some(&pack.name));
let running = status.installing.iter().find(|(l, _, _)| *l == pack.locale).map(|(_, d, t)| (*d, *t));
let details: Vec<String> =
[size_text(ui, pack.size), provides(pack), shown(&pack.licence, MAX_NAME)].into_iter().filter(|s| !s.is_empty()).collect();
Row::new().wrap(true).show(ui, |ui, _| {
Text::new(name.clone()).show(ui);
Text::new(details.join(" · ")).show(ui);
match running {
Some((done, total)) => {
Progress::new(fraction(done, total)).show(ui);
Text::new(installing_text(done, total)).show(ui);
}
None => {
if Button::new(tl!("Install")).show(ui).clicked() {
install_clicked = Some(pack.locale.clone());
}
}
}
});
if let Some(e) = error_of(app, &status.errors, &pack.locale) {
Notice::new(Tone::Bad, e).announce(Politeness::Assertive).show(ui);
}
}
if refresh_clicked && consent(app, ui, injected, "") {
refresh(app, "");
}
if let Some(locale) = remove_clicked {
remove(app, &locale);
}
if let Some(locale) = install_clicked
&& consent(app, ui, injected, &locale)
{
install(app, &locale);
}
}
/// What the bar offers for the front document, worked out again when the document, the installed packs or the
/// list change (at most once a [`MISSING_REFRESH_SECS`] while the document is being edited).
fn missing(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<Missing> {
let now = ctx.input(|i| i.time);
let Some(st) = app.session.active() else { return Vec::new() };
let key = MissingKey {
document: st.uid,
revision: st.revision,
generation: packs::generation(),
refreshing: packs::status().refreshing,
index: packs::index_generation(),
};
if let Some((k, at, m)) = &app.language_packs.missing {
let only_edited = k.document == key.document && k.generation == key.generation && k.refreshing == key.refreshing && k.index == key.index;
if *k == key {
return m.clone();
}
let age = now - *at;
if only_edited && age < MISSING_REFRESH_SECS {
// Stale for an edit: a frame comes once it may be worked out again, even with no input by then.
ctx.request_repaint_after(std::time::Duration::from_secs_f64((MISSING_REFRESH_SECS - age).max(0.0)));
return m.clone();
}
}
let m = vectorcraft_engine::cmd::packs::missing(&app.session);
app.language_packs.missing = Some((key, now, m.clone()));
m
}
/// The key a bar is closed under: its pack's locale, else (before the list) its language tag.
fn offer_key(m: &Missing) -> String {
m.pack.as_ref().map_or_else(|| m.tag.clone(), |p| p.locale.clone())
}
/// The offer the bar shows for the front document: the first language missing a pack whose bar wasn't closed.
fn shown_offer(app: &mut VectorcraftApp, ctx: &egui::Context) -> Option<Missing> {
packs::backend()?;
let document = app.session.active()?.uid;
missing(app, ctx).into_iter().find(|m| {
let closed = |key: String| app.language_packs.dismissed.contains(&(document, key));
!closed(offer_key(m)) && !closed(m.tag.clone())
})
}
/// The missing-pack bar at the foot of the canvas `area`: "<Language> spelling and hyphenation need a Language
/// pack.", with Install (and the size) when the list has the pack, else Get Language Pack, which fetches the list
/// and then installs it. Closing it hides it for that language in this document.
pub(crate) fn bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) {
let Some(offer) = shown_offer(app, &ui.ctx().clone()) else { return };
let Some(document) = app.session.active().map(|st| st.uid) else { return };
let status = packs::status();
let name = language_name(&offer.tag, offer.pack.as_ref().map(|p| p.name.as_str()));
let message = crate::i18n::fmt(tl!("{language} spelling and hyphenation need a Language pack."), &[("language", &name)]);
let key = offer_key(&offer);
let running = status.installing.iter().find(|(l, _, _)| *l == key).map(|(_, d, t)| (*d, *t));
let fetching = offer.pack.is_none() && (status.refreshing || app.language_packs.wanted.is_some());
let error = error_of(app, &status.errors, &key);
let bar_offer = offer.pack.as_ref().map_or(BarOffer::Get, |pack| BarOffer::install(pack.size));
let state = match running {
Some((done, total)) => BarState::installing(done, total),
None if fetching => BarState::Fetching,
None => BarState::Idle,
};
// A child that allocates nothing in the canvas, at its foot and clear of the isolation bar.
let mut bar_ui = ui.new_child(egui::UiBuilder::new().max_rect(area.shrink(8.0)).layout(egui::Layout::bottom_up(egui::Align::Center)));
let response = MissingPackBar::new(message, bar_offer).state(state).error(error).show(&mut bar_ui);
if response.dismissed {
app.language_packs.dismissed.insert((document, key.clone()));
}
if response.clicked && consent(app, &bar_ui, response.injected, &key) {
match &offer.pack {
Some(p) => install(app, &p.locale),
None => {
if refresh(app, &key) {
app.language_packs.wanted = Some(offer.tag.clone());
}
}
}
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,406 @@
//! Preferences › Language Packs and the missing-pack bar, over a stand-in for the font store. The packs backend is
//! the whole process's, and with one set the bar shows over any document in a language without a dictionary, so
//! each test that sets it runs in a process of its own ([`crate::testing::in_own_process`]).
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant};
use egui::accesskit::TreeUpdate;
use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect};
use serde_json::json;
use vectorcraft_engine::Session;
use vectorcraft_engine::packs::{self, Backend, Cancel, Pack};
use super::*;
use crate::Services;
/// A stand-in for the font store: it lists a Konkani pack once the list was fetched (or from the start), and installs
/// it by writing its files. Konkani: no system has a Hunspell dictionary for it, so what the bar offers doesn't
/// depend on the machine.
struct Fake {
dir: PathBuf,
network: AtomicBool,
fetched: AtomicBool,
install_gate: Mutex<Option<mpsc::Receiver<()>>>,
}
impl Fake {
fn new(name: &str, fetched: bool) -> Arc<Fake> {
let dir = std::env::temp_dir().join(format!("vc-ui-packs-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let fake = Arc::new(Fake { dir, network: AtomicBool::new(false), fetched: AtomicBool::new(fetched), install_gate: Mutex::default() });
packs::set_backend(Some(fake.clone()));
fake
}
fn downloads(&self) -> bool {
self.network.load(Ordering::Relaxed)
}
}
impl Drop for Fake {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
fn konkani() -> Pack {
Pack {
locale: "kok".into(),
name: "कोंकणी".into(),
size: 2_400_000,
licence: "MIT".into(),
class: "Embeddable".into(),
spelling: true,
hyphenation: true,
}
}
/// Writes a small Konkani pack into `packs/kok`, laid out as the font store unpacks one.
fn write_konkani_pack(packs: &Path) {
let dir = packs.join("kok");
std::fs::create_dir_all(dir.join("LICENCES")).unwrap();
std::fs::write(dir.join("pack.toml"), "locale = \"kok\"\nname = \"कोंकणी\"\nlicence = \"MIT\"\n").unwrap();
std::fs::write(dir.join("LICENCES").join("COPYING"), "Test licence text.").unwrap();
std::fs::write(dir.join("spelling.aff"), "SET UTF-8\n").unwrap();
std::fs::write(dir.join("spelling.dic"), "1\nघर\n").unwrap();
}
impl Backend for Fake {
fn packs_dir(&self) -> PathBuf {
self.dir.clone()
}
fn downloads_on(&self) -> bool {
self.downloads()
}
fn cached_index(&self) -> Vec<Pack> {
if self.fetched.load(Ordering::Relaxed) { vec![konkani()] } else { Vec::new() }
}
fn fetch_index(&self, _: &Cancel) -> Result<Vec<Pack>, String> {
assert!(self.downloads(), "a fetch only once downloading is on");
self.fetched.store(true, Ordering::Relaxed);
Ok(self.cached_index())
}
fn install(&self, locale: &str, _: &Cancel, progress: &mut dyn FnMut(u64, u64)) -> Result<(), String> {
assert!(self.downloads(), "an install only once downloading is on");
assert_eq!(locale, "kok");
let gate = self.install_gate.lock().unwrap().take();
if let Some(gate) = gate {
gate.recv_timeout(Duration::from_secs(10)).map_err(|e| e.to_string())?;
}
progress(1, 1);
write_konkani_pack(&self.dir);
Ok(())
}
fn remove(&self, locale: &str) -> Result<(), String> {
std::fs::remove_dir_all(self.dir.join(locale)).map_err(|e| e.to_string())
}
fn enable_downloads(&self) -> Result<(), String> {
self.network.store(true, Ordering::Relaxed);
Ok(())
}
}
/// Takes the backend away when the test ends, also when it failed.
struct NoBackend;
impl Drop for NoBackend {
fn drop(&mut self) {
packs::run_in_background(false);
packs::set_backend(None);
}
}
fn app() -> VectorcraftApp {
crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default()))
}
/// One frame of the whole app, as the hosts run it → its accessibility tree.
fn frame(a: &mut VectorcraftApp, events: Vec<Event>) -> TreeUpdate {
let ctx = a.ui_ctx.clone().expect("a window context");
let time = ctx.input(|i| i.time) + 0.1;
let raw = RawInput {
events,
time: Some(time),
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(1400.0, 900.0))),
focused: true,
..Default::default()
};
crate::testing::app_frame(a, &ctx, raw).platform_output.accesskit_update.expect("an accessibility tree")
}
/// Frames until no install or fetch of the list runs and none waits to start (the bar's wanted pack), then one more,
/// whose tick announces what ended.
fn idle(a: &mut VectorcraftApp) {
let start = std::time::Instant::now();
loop {
frame(a, vec![]);
let status = packs::status();
if status.installing.is_empty() && !status.refreshing && a.language_packs.wanted.is_none() {
break;
}
assert!(start.elapsed() < std::time::Duration::from_secs(10), "the pack work never ended");
std::thread::sleep(std::time::Duration::from_millis(5));
}
frame(a, vec![]);
}
/// [`idle`], then frames until the layout holds still → the last one's tree.
fn settled(a: &mut VectorcraftApp) -> TreeUpdate {
idle(a);
for _ in 0..5 {
frame(a, vec![]);
}
frame(a, vec![])
}
fn labels(tree: &TreeUpdate) -> Vec<String> {
tree.nodes.iter().filter_map(|(_, n)| n.label().map(str::to_string)).collect()
}
fn has(tree: &TreeUpdate, part: &str) -> bool {
labels(tree).iter().any(|l| l.contains(part))
}
/// The centre of the control named `label` exactly (Install, not the Installed heading).
fn spot(tree: &TreeUpdate, label: &str) -> Option<Pos2> {
spot_where(tree, |l| l == label)
}
/// The centre of the control whose name starts with `start` (`Install (` and the size).
fn spot_starting(tree: &TreeUpdate, start: &str) -> Option<Pos2> {
spot_where(tree, |l| l.starts_with(start))
}
fn spot_where(tree: &TreeUpdate, named: impl Fn(&str) -> bool) -> Option<Pos2> {
let (_, node) = tree.nodes.iter().find(|(_, n)| n.label().is_some_and(|l| named(l.trim())) && n.bounds().is_some())?;
let b = node.bounds()?;
Some(Pos2::new((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5))
}
/// The person's own click at `at` (not the control channel's).
fn click(a: &mut VectorcraftApp, at: Pos2) {
frame(a, vec![Event::PointerMoved(at)]);
for pressed in [true, false] {
frame(a, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }]);
}
idle(a);
}
/// An agent's click on the control named `name`, through the control channel.
fn agent_click(a: &mut VectorcraftApp, name: &str) {
let ctx = a.ui_ctx.clone().expect("a window context");
let (request, _reply) = craft::automation::ControlRequest::new("ui.click", json!({"control": {"name": name}}));
let _ = crate::control::handle(a, &ctx, &request);
for _ in 0..3 {
frame(a, vec![]);
}
idle(a);
}
fn installed() -> Vec<String> {
packs::installed().into_iter().map(|p| p.locale).collect()
}
/// A document with type in Konkani.
fn konkani_document(a: &mut VectorcraftApp) {
a.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let id = a.run("text.create", json!({"x": 10, "y": 50, "text": "घर"})).unwrap()["id"].clone();
a.run("text.setFormat", json!({"ids": [id], "language": "Konkani"})).unwrap();
}
#[test]
fn the_page_installs_and_removes_a_pack_on_the_persons_click() {
if !crate::testing::in_own_process("language_packs::desktop::tests::the_page_installs_and_removes_a_pack_on_the_persons_click") {
return;
}
let _none = NoBackend;
let fake = Fake::new("page", true);
let mut a = app();
crate::prefs_dialog::open(&mut a, Some("language packs"));
let tree = settled(&mut a);
assert!(has(&tree, "Konkani (कोंकणी)"), "the pack is listed by name: {:?}", labels(&tree));
assert!(has(&tree, "Spelling and hyphenation"), "with what it provides");
assert!(has(&tree, "Downloading is off"), "and says downloading is off");
let install = spot(&tree, "Install").expect("an Install button");
click(&mut a, install);
assert!(fake.downloads(), "the person's click turned downloading on");
assert_eq!(installed(), ["kok"]);
assert!(a.ui.status.contains("installed"), "the end is announced: {}", a.ui.status);
let tree = settled(&mut a);
assert!(!has(&tree, "Downloading is off"));
let remove = spot(&tree, "Remove").expect("a Remove button for the installed pack");
click(&mut a, remove);
assert!(installed().is_empty(), "removed");
assert!(spot(&settled(&mut a), "Install").is_some(), "the pack can be installed again");
}
#[test]
fn a_faked_click_never_turns_on_downloading() {
if !crate::testing::in_own_process("language_packs::desktop::tests::a_faked_click_never_turns_on_downloading") {
return;
}
let _none = NoBackend;
let fake = Fake::new("agent", true);
let mut a = app();
crate::prefs_dialog::open(&mut a, Some("Language Packs"));
settled(&mut a);
agent_click(&mut a, "Install");
assert!(!fake.downloads(), "an injected click is no consent");
assert!(installed().is_empty(), "nothing installed");
assert!(has(&settled(&mut a), "Only you can turn on downloading"), "the row says why");
// Once the person turned it on, the refusal goes, and an agent installs.
fake.enable_downloads().unwrap();
assert!(!has(&settled(&mut a), "Only you can turn on downloading"), "the refusal no longer holds");
agent_click(&mut a, "Install");
assert_eq!(installed(), ["kok"]);
}
/// A failure that took a refusal's place is a failure: downloading coming on drops refusals only.
#[test]
fn a_failure_after_a_refusal_outlasts_downloading_coming_on() {
if !crate::testing::in_own_process("language_packs::desktop::tests::a_failure_after_a_refusal_outlasts_downloading_coming_on") {
return;
}
let _none = NoBackend;
let fake = Fake::new("refused-then-failed", true);
let mut a = app();
crate::prefs_dialog::open(&mut a, Some("Language Packs"));
settled(&mut a);
agent_click(&mut a, "Install");
assert!(has(&settled(&mut a), "Only you can turn on downloading"), "refused first");
// Removing a pack that isn't installed fails under the same locale.
remove(&mut a, "kok");
let failure = a.language_packs.errors.get("kok").cloned().expect("the removal's failure");
assert!(!failure.contains("Only you can turn on downloading"), "{failure}");
fake.enable_downloads().unwrap();
settled(&mut a);
assert_eq!(a.language_packs.errors.get("kok"), Some(&failure), "the failure stays once downloading is on");
}
#[test]
fn immediate_pack_errors_reach_the_status_bar() {
if !crate::testing::in_own_process("language_packs::desktop::tests::immediate_pack_errors_reach_the_status_bar") {
return;
}
let _none = NoBackend;
let _fake = Fake::new("immediate-errors", true);
let mut a = app();
// The engine rejects the install before starting a worker because downloading is off.
install(&mut a, "kok");
let install_error = &a.language_packs.errors["kok"];
assert!(a.ui.status.contains("Couldn't install") && a.ui.status.contains(install_error), "{}", a.ui.status);
assert!(packs::status().installing.is_empty());
// The backend rejects removal synchronously because the pack does not exist.
remove(&mut a, "kok");
let remove_error = &a.language_packs.errors["kok"];
assert!(a.ui.status.contains("Couldn't remove") && a.ui.status.contains(remove_error), "{}", a.ui.status);
}
#[test]
fn a_deferred_install_schedules_its_completion_frame() {
if !crate::testing::in_own_process("language_packs::desktop::tests::a_deferred_install_schedules_its_completion_frame") {
return;
}
let _none = NoBackend;
let fake = Fake::new("deferred-repaint", false);
fake.enable_downloads().unwrap();
packs::run_in_background(true);
let (finish, gate) = mpsc::channel();
*fake.install_gate.lock().unwrap() = Some(gate);
let mut a = app();
let ctx = a.ui_ctx.clone().expect("a window context");
// Tick the host without drawing widgets, which can independently ask for repaints.
let tick = |app: &mut VectorcraftApp| {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| app.tick(ui.ctx()));
out.textures_delta.clear();
out.viewport_output[&egui::ViewportId::ROOT].repaint_delay
};
for _ in 0..3 {
tick(&mut a);
}
assert_eq!(tick(&mut a), Duration::MAX, "the idle host does not request a frame");
// The bar's request is pending when the fetch finishes and the host next ticks.
assert!(refresh(&mut a, "kok"));
a.language_packs.wanted = Some("kok".into());
wait_for_pack_worker(|| !packs::status().refreshing);
let repaint_delay = tick(&mut a);
assert!(!packs::status().installing.is_empty(), "the deferred install started during the tick");
assert!(repaint_delay < Duration::MAX, "the host must wake with no further input");
finish.send(()).unwrap();
wait_for_pack_worker(|| packs::status().installing.is_empty());
frame(&mut a, vec![]);
assert_eq!(installed(), ["kok"]);
assert!(a.ui.status.contains("is installed"), "the scheduled frame announces completion: {}", a.ui.status);
}
fn wait_for_pack_worker(done: impl Fn() -> bool) {
let start = Instant::now();
while !done() {
assert!(start.elapsed() < Duration::from_secs(10), "the pack worker did not finish");
std::thread::sleep(Duration::from_millis(5));
}
}
#[test]
fn the_bar_gets_the_pack_for_the_documents_language() {
if !crate::testing::in_own_process("language_packs::desktop::tests::the_bar_gets_the_pack_for_the_documents_language") {
return;
}
let _none = NoBackend;
// No list yet: the bar offers the language alone, and its button gets the list, then the pack.
let fake = Fake::new("bar", false);
let mut a = app();
konkani_document(&mut a);
let tree = settled(&mut a);
assert!(has(&tree, "Konkani spelling and hyphenation need a Language pack."), "{:?}", labels(&tree));
let get = spot(&tree, "Get Language Pack").expect("the bar's button");
click(&mut a, get);
let tree = settled(&mut a);
assert!(fake.downloads(), "the person's click turned downloading on");
assert_eq!(installed(), ["kok"], "the list came, then the pack");
assert!(!has(&tree, "need a Language pack"), "the bar is gone once the language spells: {:?}", labels(&tree));
}
#[test]
fn closing_the_bar_hides_it_for_that_document() {
if !crate::testing::in_own_process("language_packs::desktop::tests::closing_the_bar_hides_it_for_that_document") {
return;
}
let _none = NoBackend;
let _fake = Fake::new("close", true);
let mut a = app();
konkani_document(&mut a);
let tree = settled(&mut a);
assert!(spot_starting(&tree, "Install (").is_some(), "the bar offers the pack with its size: {:?}", labels(&tree));
let close = ["Dismiss", "Close"].iter().find_map(|l| spot(&tree, l)).unwrap_or_else(|| panic!("the bar's close button: {:?}", labels(&tree)));
click(&mut a, close);
assert!(!has(&settled(&mut a), "need a Language pack"), "closed for this document");
konkani_document(&mut a);
assert!(has(&settled(&mut a), "need a Language pack"), "another document in the language offers it again");
assert!(installed().is_empty(), "nothing installed without a click");
}
/// Text from the index isn't ours to trust: control, bidi and tag characters are taken out and it is cut short.
#[test]
fn index_text_is_shown_without_hidden_characters() {
let hostile = "Nederlands\u{202E}lmth.exe\u{E0041}\u{200B}\n";
let shown = language_name("zz", Some(hostile));
assert!(!shown.chars().any(|c| c.is_control() || ('\u{202A}'..='\u{202E}').contains(&c) || ('\u{E0000}'..='\u{E007F}').contains(&c)));
assert!(shown.starts_with("Nederlands"));
assert!(language_name("zz", Some(&"x".repeat(100))).chars().count() <= 40, "cut short");
}
+4
View File
@@ -56,6 +56,7 @@ pub mod icon_data;
pub mod icons;
pub mod io;
pub mod keymap;
pub mod language_packs;
pub mod layout_migration;
pub mod menus;
pub mod opening;
@@ -270,6 +271,9 @@ pub struct VectorcraftApp {
pub concept_runs: panels::concept_vector::ConceptRuns,
/// Retype's search of the installed fonts, off the UI thread ([`retype_runs`]).
pub retype_runs: retype_runs::RetypeRuns,
/// Language packs: the Preferences page's and the missing-pack bar's state ([`language_packs`]). The web has none.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) language_packs: language_packs::Runtime,
/// Data Recovery's timer and startup question ([`recovery`]).
pub recovery: recovery::Timer,
/// The Close, Close All or Quit in progress, which asks about each unsaved document in turn.
+10 -9
View File
@@ -128,8 +128,8 @@ pub(crate) fn corner_length(c: &LiveCorners, k: usize) -> f64 {
}
/// What a corner field edits, as its edit target: the active document's uid, how many times
/// File › Revert and Undo or Redo replaced its content (after which a node id can name another
/// object), the selected objects in id order, and `corners`, the corners the field sets (a picked
/// File › Revert, Undo or Redo and other rollbacks (`DocState::rollbacks`) replaced its content
/// (after which a node id can name another object), the selected objects in id order, and `corners`, the corners the field sets (a picked
/// corner as its [`CornerPlace`]). A field drops a value typed and not yet committed when this
/// changes, even where the new corners have the same radius, and keeps it when the same objects
/// are selected in another order. Rounding a corner replaces its anchors without changing the
@@ -142,7 +142,7 @@ pub(crate) fn corner_target(app: &VectorcraftApp, corners: impl Hash) -> u64 {
.map(|st| {
let mut objects = st.selection.objects.to_vec();
objects.sort_unstable();
(st.uid, st.reverts, st.history_restores, objects)
(st.uid, st.reverts, st.history_restores, st.rollbacks, objects)
})
.hash(&mut hasher);
corners.hash(&mut hasher);
@@ -899,11 +899,12 @@ pub(crate) fn current_transparency(app: &VectorcraftApp) -> Option<(f32, BlendMo
Some(picked.unwrap_or((n.opacity, n.blend)))
}
/// The objects a selection field edits, as a field's edit target: the document with how many times File › Revert and
/// Undo or Redo replaced its content (after which a node id can name another object), the selected objects (or the
/// object targeted in the Layers panel) in id order, and the selected symbol part. A field with an unfinished value
/// drops it when these change, and keeps it when the same objects are selected in another order.
pub(crate) type SelectionTarget = (Option<(u64, u64, u64)>, Vec<NodeId>, Option<(NodeId, Vec<u32>)>);
/// The objects a selection field edits, as a field's edit target: the document with how many times File › Revert,
/// Undo or Redo and other rollbacks (`DocState::rollbacks`) replaced its content (after which a node id can name
/// another object), the selected objects (or the object targeted in the Layers panel) in id order, and the selected
/// symbol part. A field with an unfinished value drops it when these change, and keeps it when the same objects are
/// selected in another order.
pub(crate) type SelectionTarget = (Option<(u64, u64, u64, u64)>, Vec<NodeId>, Option<(NodeId, Vec<u32>)>);
/// The [`SelectionTarget`] of the active document.
pub(crate) fn selection_target(app: &VectorcraftApp) -> SelectionTarget {
@@ -911,7 +912,7 @@ pub(crate) fn selection_target(app: &VectorcraftApp) -> SelectionTarget {
let part = st.selection.symbol_part.as_ref().map(|p| (p.instance, p.path.clone()));
let mut subjects = st.selection.subjects().to_vec();
subjects.sort_unstable();
(Some((st.uid, st.reverts, st.history_restores)), subjects, part)
(Some((st.uid, st.reverts, st.history_restores, st.rollbacks)), subjects, part)
}
/// What the Transparency panel's and the Control bar's Opacity fields edit, as their edit target: the
+17 -11
View File
@@ -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>,
+14
View File
@@ -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> {
+6 -2
View File
@@ -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));
}
+19 -5
View File
@@ -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");
}
}
+16 -2
View File
@@ -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);
+50 -22
View File
@@ -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
}
+7 -4
View File
@@ -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");
}
+5 -5
View File
@@ -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
+23 -2
View File
@@ -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");
}
+79 -27
View File
@@ -11,7 +11,7 @@ use craft::ui::layout_components::{Row, Stack};
use craft::ui::pickers::Select;
use craft::ui::text::{NumberField, link_toggle};
use craft::ui::value_drag::Slider;
use egui::Ui;
use egui::{IdSalt, Ui};
use serde_json::{Value, json};
use vectorcraft_doc::{LiveShape, Node, NodeKind};
use vectorcraft_geom::shapes::CornerKind;
@@ -42,14 +42,22 @@ const SIDES_SLIDER: RangeInclusive<f64> = 3.0..=20.0;
pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShape, headed: bool) -> bool {
match live {
LiveShape::Rectangle { .. } => under_heading(ui, headed.then(|| tl!("Rectangle Properties:")), |ui| {
angle_row(app, ui, live, "rectangleAngle");
let target = shape_edit_target(app);
angle_row(app, ui, live, "rectangleAngle", target);
corner_radius_row(app, ui, n);
}),
LiveShape::Polygon { .. } => under_heading(ui, headed.then(|| tl!("Polygon Properties:")), |ui| polygon_rows(app, ui, n, live)),
LiveShape::Star { .. } => under_heading(ui, headed.then(|| tl!("Star Properties:")), |ui| star_rows(app, ui, live)),
LiveShape::Polygon { .. } => under_heading(ui, headed.then(|| tl!("Polygon Properties:")), |ui| {
let target = shape_edit_target(app);
polygon_rows(app, ui, n, live, target);
}),
LiveShape::Star { .. } => under_heading(ui, headed.then(|| tl!("Star Properties:")), |ui| {
let target = shape_edit_target(app);
star_rows(app, ui, live, target);
}),
LiveShape::Ellipse { pie, .. } => under_heading(ui, Some(tl!("Ellipse Properties:")), |ui| {
angle_row(app, ui, live, "ellipseAngle");
pie_rows(app, ui, *pie);
let target = shape_edit_target(app);
angle_row(app, ui, live, "ellipseAngle", target);
pie_rows(app, ui, *pie, target);
}),
LiveShape::Line { .. } => return line_rows(app, ui, live),
_ => return false,
@@ -57,6 +65,27 @@ pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, l
true
}
/// The edit target of the live shape number fields: the active document, how many times File › Revert replaced its
/// content, how many times Undo or Redo restored an older snapshot, how many times another rollback put one back
/// (`DocState::rollbacks`; after either, the same node ID can name another object), and the selected objects in
/// selection order, which `object.setLiveShape` changes. The first selected object picks the rows, so the same objects
/// in another order can put another property's field in the same place. A field drops a value typed and not yet
/// committed when this changes, even where the newly selected shape shows the same value. Hashed once per (document
/// uid, revision): the panels read it every frame, and Select All can select hundreds of thousands of shapes. The
/// revision is not part of the target, so an edit that leaves the selection as it is keeps the value typed so far.
pub(crate) fn shape_edit_target(app: &mut VectorcraftApp) -> IdSalt {
let Some(st) = app.session.active() else { return IdSalt::new(None::<()>) };
let key = (st.uid, st.revision);
if let Some((k, target)) = app.canvas.shape_edit_target
&& k == key
{
return target;
}
let target = IdSalt::new(Some((st.uid, st.reverts, st.history_restores, st.rollbacks, st.selection.objects.as_slice())));
app.canvas.shape_edit_target = Some((key, target));
target
}
/// `rows` under a sub-heading, or bare when there is none.
fn under_heading(ui: &mut Ui, heading: Option<&'static str>, mut rows: impl FnMut(&mut Ui)) {
match heading {
@@ -75,7 +104,16 @@ fn set_live_shape(app: &mut VectorcraftApp, params: Value) {
}
/// One labelled number field whose edits send `params(number)` to `object.setLiveShape`; a scrub is one undo step.
fn number_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, value: Option<f64>, quantity: Quantity, params: impl Fn(f64) -> Value) {
/// `target` is the field's [`shape_edit_target`].
fn number_row(
app: &mut VectorcraftApp,
ui: &mut Ui,
label: &'static str,
value: Option<f64>,
quantity: Quantity,
target: IdSalt,
params: impl Fn(f64) -> Value,
) {
let mut edit = None;
Field::new(label).show(ui, |ui, _| {
let bind = Bind::given(value);
@@ -84,7 +122,7 @@ fn number_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, value:
Quantity::Degrees => NumberField::new(label, bind).unit("°").commit_decimals(1),
Quantity::Ratio => NumberField::new(label, bind).range(0.001..=1.0).step(0.001).commit_decimals(3),
};
edit = Some(field.show(ui).edit);
edit = Some(field.edit_target(target).show(ui).edit);
});
if let Some(edit) = edit {
// `Scope`, not `Preview`: `Preview` names one command, and each field sends its own params.
@@ -99,9 +137,9 @@ fn number_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, value:
/// A live rectangle's, ellipse's or polygon's Angle row (counterclockwise): the angle the selected shapes of its
/// kind share, blank when they differ. `key` is the `object.setLiveShape` param an edit sets, which turns each of
/// them about its own center.
fn angle_row(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape, key: &'static str) {
fn angle_row(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape, key: &'static str, target: IdSalt) {
let angle = shared_shape_angle(app, live);
number_row(app, ui, tl!("Angle"), angle, Quantity::Degrees, |a| json!({ key: a }));
number_row(app, ui, tl!("Angle"), angle, Quantity::Degrees, target, |a| json!({ key: a }));
}
/// The angle ([`LiveShape::shape_angle`]) every selected live shape of `live`'s kind shares, `None` when they
@@ -151,9 +189,11 @@ fn line_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape) -> bool {
if !only_lines_selected(app) {
return false;
}
let target = shape_edit_target(app);
under_heading(ui, Some(tl!("Line Properties:")), |ui| {
number_row(app, ui, tl!("Line Length"), live.line_length(), Quantity::Length, |l| json!({ "lineLength": l }));
number_row(app, ui, tl!("Line Angle"), Some(live.line_angle().unwrap_or(0.0)), Quantity::Degrees, |a| json!({ "lineAngle": a }));
number_row(app, ui, tl!("Line Length"), live.line_length(), Quantity::Length, target, |l| json!({ "lineLength": l }));
let angle = Some(live.line_angle().unwrap_or(0.0));
number_row(app, ui, tl!("Line Angle"), angle, Quantity::Degrees, target, |a| json!({ "lineAngle": a }));
});
true
}
@@ -161,13 +201,13 @@ fn line_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape) -> bool {
/// An ellipse's Pie Start and End Angle (degrees, counterclockwise from 3 o'clock; 0 to 360 is the whole
/// ellipse), the Constrain Pie Angle link beside them, and Invert Pie, which shows the other part of it. With the
/// link on, a typed angle moves the other one by as much, so each selected ellipse keeps its span.
fn pie_rows(app: &mut VectorcraftApp, ui: &mut Ui, pie: (f64, f64)) {
fn pie_rows(app: &mut VectorcraftApp, ui: &mut Ui, pie: (f64, f64), target: IdSalt) {
let constrain = app.ui.constrain_pie_angle;
// The link sits halfway between the two fields, with no bracket drawn to them.
Row::new().bracket(Bracket::Unlinked).show(ui, |ui, _| {
Stack::new().show(ui, |ui, _| {
for (label, key, v) in [(tl!("Pie Start Angle"), "pieStart", pie.0), (tl!("Pie End Angle"), "pieEnd", pie.1)] {
number_row(app, ui, label, Some(v), Quantity::Degrees, |a| {
number_row(app, ui, label, Some(v), Quantity::Degrees, target, |a| {
if constrain { json!({ key: a, "constrainPie": true }) } else { json!({ key: a }) }
});
}
@@ -181,16 +221,16 @@ fn pie_rows(app: &mut VectorcraftApp, ui: &mut Ui, pie: (f64, f64)) {
/// A live polygon's Polygon Properties: its side count (a field and a slider), angle (counterclockwise), corner
/// type and radius, radius (center to vertex) and side length, and Make Sides Equal, which an uneven scale enables.
fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShape) {
fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShape, target: IdSalt) {
let LiveShape::Polygon { sides, .. } = live else { return };
let radius = live.polygon_radius();
let side = radius.map(|r| 2.0 * r * (std::f64::consts::PI / f64::from((*sides).max(3))).sin());
sides_row(app, ui, *sides);
angle_row(app, ui, live, "polygonAngle");
sides_row(app, ui, *sides, target);
angle_row(app, ui, live, "polygonAngle", target);
corner_kind_row(app, ui, corner_style(app, n).1);
Field::new(tl!("Corner Radius")).show(ui, |ui, _| corner_radius_field(app, ui, n));
number_row(app, ui, tl!("Radius"), radius, Quantity::Length, |r| json!({ "polygonRadius": r }));
number_row(app, ui, tl!("Side Length"), side, Quantity::Length, |l| json!({ "sideLength": l }));
number_row(app, ui, tl!("Radius"), radius, Quantity::Length, target, |r| json!({ "polygonRadius": r }));
number_row(app, ui, tl!("Side Length"), side, Quantity::Length, target, |l| json!({ "sideLength": l }));
if Button::new(tl!("Make Sides Equal")).enabled(!live.polygon_sides_equal()).show(ui).clicked() {
set_live_shape(app, json!({"makeSidesEqual": true}));
}
@@ -200,18 +240,27 @@ fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShap
/// over [`SIDES_SLIDER`]. A typed count is one undo step. A slider drag previews the count and its release records
/// one undo step; Escape during the drag puts the count back. A click on the rail or an arrow key sets the count in
/// one undo step. A count above 20 puts the thumb at the rail's right end, and screen readers read the real count.
fn sides_row(app: &mut VectorcraftApp, ui: &mut Ui, sides: u32) {
count_row(app, ui, tl!("Sides"), "sides", sides, 3.0);
fn sides_row(app: &mut VectorcraftApp, ui: &mut Ui, sides: u32, target: IdSalt) {
count_row(app, ui, tl!("Sides"), "sides", sides, 3.0, target);
}
/// A count row (Polygon Properties' Sides, Star Properties' Points) whose edits set `key`: a field that takes `min`
/// to 1000 and a slider over [`SIDES_SLIDER`], as [`sides_row`] describes.
fn count_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, key: &'static str, sides: u32, min: f64) {
/// to 1000 and a slider over [`SIDES_SLIDER`], as [`sides_row`] describes. The field drops an unfinished value when
/// `target` changes.
fn count_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, key: &'static str, sides: u32, min: f64, target: IdSalt) {
let count = f64::from(sides);
let (mut typed, mut slid) = (None, None);
Field::new(label).show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
typed = Some(NumberField::new(label, Bind::given(Some(count))).range(min..=1000.0).fixed_decimals(0).id_salt("field").show(ui).edit);
typed = Some(
NumberField::new(label, Bind::given(Some(count)))
.range(min..=1000.0)
.fixed_decimals(0)
.id_salt("field")
.edit_target(target)
.show(ui)
.edit,
);
let (lo, hi) = (*SIDES_SLIDER.start(), *SIDES_SLIDER.end());
slid = Some(
Slider::new(Bind::given(count.clamp(lo, hi)), SIDES_SLIDER)
@@ -241,10 +290,10 @@ fn count_row(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, key: &'
/// A live star's Star Properties: its point count (a field that takes 2 to 1000 and a slider over 3 to 20) and its
/// ratio (inner radius over outer radius, 0.001 to 1). Its corners stay with Live Corners and Direct Selection, as any
/// path's do.
fn star_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape) {
fn star_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape, target: IdSalt) {
let Some(points) = live.star_points() else { return };
count_row(app, ui, tl!("Points"), "points", points, 2.0);
number_row(app, ui, tl!("Ratio"), live.star_ratio(), Quantity::Ratio, |r| json!({ "ratio": r }));
count_row(app, ui, tl!("Points"), "points", points, 2.0, target);
number_row(app, ui, tl!("Ratio"), live.star_ratio(), Quantity::Ratio, target, |r| json!({ "ratio": r }));
}
/// The polygon's Corner type select, blank while `kind` is `None` (the corners differ), one number cell wide as the
@@ -259,3 +308,6 @@ fn corner_kind_row(app: &mut VectorcraftApp, ui: &mut Ui, kind: Option<CornerKin
apply_edits(app, &edit, EditPath::Scope, |app, k, _| set_live_shape(app, json!({ "kind": k })));
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,421 @@
use craft::ui::contract::Role;
use egui::{Key, Modifiers};
use vectorcraft_doc::Unit;
use super::*;
use crate::tests::panel_harness::Panel;
/// An app with a new document holding two shapes made by `cmd` with `a` and `b`, and their ids.
fn two(cmd: &str, a: Value, b: Value) -> (VectorcraftApp, Value, Value) {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let a = app.run(cmd, a).unwrap()["id"].clone();
let b = app.run(cmd, b).unwrap()["id"].clone();
(app, a, b)
}
/// Selects `a`, types "3+" into field `name` drawn by `draw`, selects `b`, then types "7" and Enter. Returns the
/// field's value just after `b` is selected, after the Enter, and with `a` selected again.
fn type_across_a_selection_change(
app: VectorcraftApp,
draw: fn(&mut VectorcraftApp, &mut Ui),
a: &Value,
b: &Value,
name: &str,
) -> (Option<String>, Option<String>, Option<String>) {
let mut app = app;
app.run("select.set", json!({"ids": [a]})).unwrap();
let mut p = Panel::new(app, draw);
p.click_role(name, Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().run("select.set", json!({"ids": [b]})).unwrap();
p.frame();
let switched = p.value_role(name, Role::SPIN_BUTTON);
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
let after = p.value_role(name, Role::SPIN_BUTTON);
p.app().run("select.set", json!({"ids": [a]})).unwrap();
p.frame();
(switched, after, p.value_role(name, Role::SPIN_BUTTON))
}
/// Checks that a value typed into field `name` for `a` and not finished is dropped when `b`, which shows `shown`
/// there as `a` does, is selected: the field shows `shown`, "7" and Enter then give `b` 7 (`seven`), not 3+7, and
/// `a` keeps `shown`.
fn check_field(app: VectorcraftApp, draw: fn(&mut VectorcraftApp, &mut Ui), a: &Value, b: &Value, name: &str, shown: &str, seven: &str) {
let (switched, after, first) = type_across_a_selection_change(app, draw, a, b, name);
assert_eq!(switched.as_deref(), Some(shown), "{name}: the field shows the newly selected shape's value");
assert_eq!(after.as_deref(), Some(seven), "{name}: the newly selected shape takes 7, not the unfinished 3+ and 7");
assert_eq!(first.as_deref(), Some(shown), "{name}: the shape the value was first typed for keeps its value");
}
fn pt(v: f64) -> String {
Unit::Points.format(v)
}
fn rectangles() -> (VectorcraftApp, Value, Value) {
two("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30}), json!({"x": 100, "y": 0, "width": 30, "height": 30}))
}
fn polygons() -> (VectorcraftApp, Value, Value) {
two("shape.polygon", json!({"cx": 60, "cy": 60, "radius": 40, "sides": 5}), json!({"cx": 200, "cy": 60, "radius": 40, "sides": 5}))
}
fn ellipses() -> (VectorcraftApp, Value, Value) {
two("shape.ellipse", json!({"x": 0, "y": 0, "width": 40, "height": 30}), json!({"x": 100, "y": 0, "width": 40, "height": 30}))
}
fn lines() -> (VectorcraftApp, Value, Value) {
two("shape.line", json!({"x1": 20, "y1": 20, "x2": 120, "y2": 20}), json!({"x1": 20, "y1": 200, "x2": 120, "y2": 200}))
}
#[test]
fn an_unfinished_rectangle_angle_does_not_reach_another_rectangle() {
let (app, a, b) = rectangles();
check_field(app, crate::panels::transform::show, &a, &b, "Angle", "0°", "7°");
let (app, a, b) = rectangles();
check_field(app, crate::panels::properties::show, &a, &b, "Angle", "0°", "7°");
}
#[test]
fn an_unfinished_polygon_sides_count_does_not_reach_another_polygon() {
let (app, a, b) = polygons();
check_field(app, crate::panels::transform::show, &a, &b, "Sides", "5", "7");
}
#[test]
fn an_unfinished_polygon_angle_radius_or_side_length_does_not_reach_another_polygon() {
let (app, a, b) = polygons();
check_field(app, crate::panels::transform::show, &a, &b, "Angle", "0°", "7°");
let (app, a, b) = polygons();
check_field(app, crate::panels::transform::show, &a, &b, "Radius", &pt(40.0), &pt(7.0));
let (app, a, b) = polygons();
let side = pt(2.0 * 40.0 * (std::f64::consts::PI / 5.0).sin());
check_field(app, crate::panels::transform::show, &a, &b, "Side Length", &side, &pt(7.0));
}
/// After Undo removes the shape a value was typed for, a new shape can take its node ID. The value is dropped when
/// that shape is selected, so it does not reach an object it was not typed for.
#[test]
fn an_unfinished_angle_does_not_reach_a_shape_that_takes_an_undone_shapes_id() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let rect = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [rect]})).unwrap();
let mut p = Panel::new(app, crate::panels::transform::show);
p.click_role("Angle", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().run("edit.undo", json!({})).unwrap();
let ellipse = p.app().run("shape.ellipse", json!({"x": 100, "y": 0, "width": 40, "height": 30})).unwrap()["id"].clone();
assert_eq!(ellipse, rect, "the ellipse takes the undone rectangle's node ID");
p.app().run("select.set", json!({"ids": [ellipse]})).unwrap();
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("0°"), "the field shows the ellipse's angle");
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("7°"), "the ellipse takes 7°, not the unfinished 3+ and 7");
}
/// A canceled undo group removes the shape a value was typed for, and a new shape can take its node ID. The value is
/// dropped when that shape is selected.
#[test]
fn an_unfinished_angle_does_not_reach_a_shape_that_takes_a_canceled_groups_shapes_id() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
app.run("edit.undoGroup.begin", json!({})).unwrap();
let rect = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [rect]})).unwrap();
let mut p = Panel::new(app, crate::panels::transform::show);
p.click_role("Angle", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().run("edit.undoGroup.end", json!({"cancel": true})).unwrap();
let ellipse = p.app().run("shape.ellipse", json!({"x": 100, "y": 0, "width": 40, "height": 30})).unwrap()["id"].clone();
assert_eq!(ellipse, rect, "the ellipse takes the canceled group's rectangle's node ID");
p.app().run("select.set", json!({"ids": [ellipse]})).unwrap();
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("0°"), "the field shows the new shape's angle");
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("7°"), "the ellipse takes 7°, not the unfinished 3+ and 7");
}
/// A canceled interaction removes the shape its preview made and a Corner Radius value was typed for, and a new shape
/// made by `cmd` with `args` takes its node ID. The value is dropped when that shape is selected in the panel `draw`
/// draws.
fn check_corner_radius_after_a_canceled_preview(draw: fn(&mut VectorcraftApp, &mut Ui), cmd: &str, args: Value, panel: &str) {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
app.session.begin_interaction("Shape").unwrap();
let first = app.session.preview(cmd, &args).unwrap()["id"].clone();
let selected = app.session.active().map(|st| st.selection.objects.clone()).unwrap_or_default();
assert_eq!(json!(selected.iter().map(|id| id.0).collect::<Vec<_>>()), json!([first]), "{panel} {cmd}: the preview selects its shape");
let mut p = Panel::new(app, draw);
p.click_role("Corner Radius", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().session.cancel_interaction().unwrap();
let second = p.app().run(cmd, args).unwrap()["id"].clone();
assert_eq!(second, first, "{panel} {cmd}: the new shape takes the canceled preview's shape's node ID");
p.app().run("select.set", json!({"ids": [second]})).unwrap();
p.frame();
let shown = p.value_role("Corner Radius", Role::SPIN_BUTTON);
assert_eq!(shown.as_deref(), Some(pt(0.0).as_str()), "{panel} {cmd}: the field shows the new shape's corner radius");
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
let after = p.value_role("Corner Radius", Role::SPIN_BUTTON);
assert_eq!(after.as_deref(), Some(pt(7.0).as_str()), "{panel} {cmd}: the new shape takes 7, not the unfinished 3+ and 7");
}
#[test]
fn an_unfinished_rectangle_corner_radius_does_not_reach_a_shape_that_takes_a_canceled_previews_shapes_id() {
let rect = json!({"x": 0, "y": 0, "width": 30, "height": 30});
check_corner_radius_after_a_canceled_preview(crate::panels::transform::show, "shape.rectangle", rect, "Transform");
}
#[test]
fn an_unfinished_polygon_corner_radius_does_not_reach_a_shape_that_takes_a_canceled_previews_shapes_id() {
let polygon = json!({"cx": 60, "cy": 60, "radius": 40, "sides": 5});
check_corner_radius_after_a_canceled_preview(crate::panels::transform::show, "shape.polygon", polygon, "Transform");
}
#[test]
fn an_unfinished_rectangle_corner_radius_in_the_properties_panel_does_not_reach_a_shape_that_takes_a_canceled_previews_shapes_id() {
let rect = json!({"x": 0, "y": 0, "width": 30, "height": 30});
check_corner_radius_after_a_canceled_preview(crate::panels::properties::show, "shape.rectangle", rect, "Properties");
}
#[test]
fn an_unfinished_polygon_corner_radius_in_the_properties_panel_does_not_reach_a_shape_that_takes_a_canceled_previews_shapes_id() {
let polygon = json!({"cx": 60, "cy": 60, "radius": 40, "sides": 5});
check_corner_radius_after_a_canceled_preview(crate::panels::properties::show, "shape.polygon", polygon, "Properties");
}
/// Exit Symbol Editing Mode with nothing changed takes back the entering step, which removes the editing copy a value
/// was typed for, and a new shape can take the copy's node ID. The value is dropped when that shape is selected.
#[test]
fn an_unfinished_angle_does_not_reach_a_shape_that_takes_an_unchanged_symbol_copys_id() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap();
app.run("symbol.new", json!({"name": "Box"})).unwrap();
app.run("symbol.edit", json!({})).unwrap();
let copy = app.session.active().map(|st| st.selection.objects.clone()).unwrap_or_default();
assert_eq!(copy.len(), 1, "symbol editing selects the editing copy");
let mut p = Panel::new(app, crate::panels::transform::show);
p.click_role("Angle", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().run("symbol.exitEditing", json!({})).unwrap();
p.app().run("shape.rectangle", json!({"x": 100, "y": 0, "width": 40, "height": 30})).unwrap();
let rect = p.app().run("shape.rectangle", json!({"x": 200, "y": 0, "width": 40, "height": 30})).unwrap()["id"].clone();
assert_eq!(rect, json!(copy[0].0), "the second new rectangle takes the editing copy's node ID");
p.app().run("select.set", json!({"ids": [rect]})).unwrap();
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("0°"), "the field shows the new rectangle's angle");
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("7°"), "the rectangle takes 7°, not the unfinished 3+ and 7");
}
/// A canceled interaction removes a shape its preview made and a value was typed for, and a new shape can take that
/// shape's node ID. The value is dropped when that shape is selected.
#[test]
fn an_unfinished_angle_does_not_reach_a_shape_that_takes_a_canceled_previews_shapes_id() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
app.session.begin_interaction("Rectangle").unwrap();
let previewed = app.session.preview("shape.rectangle", &json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].clone();
let selected = app.session.active().map(|st| st.selection.objects.clone()).unwrap_or_default();
assert_eq!(json!(selected.iter().map(|id| id.0).collect::<Vec<_>>()), json!([previewed]), "the preview selects its rectangle");
let mut p = Panel::new(app, crate::panels::transform::show);
p.click_role("Angle", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().session.cancel_interaction().unwrap();
let rect = p.app().run("shape.rectangle", json!({"x": 100, "y": 0, "width": 40, "height": 30})).unwrap()["id"].clone();
assert_eq!(rect, previewed, "the new rectangle takes the canceled preview's rectangle's node ID");
p.app().run("select.set", json!({"ids": [rect]})).unwrap();
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("0°"), "the field shows the new rectangle's angle");
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("7°"), "the rectangle takes 7°, not the unfinished 3+ and 7");
}
/// A replacement preview reuses the discarded rectangle's node ID and drops its unfinished angle.
/// The replacement rectangle takes the next angle typed into the field.
#[test]
fn an_unfinished_angle_does_not_reach_a_replacement_preview_that_reuses_a_discarded_shapes_id() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
app.session.begin_interaction("Rectangle").unwrap();
let previewed = app.session.preview("shape.rectangle", &json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].clone();
let mut p = Panel::new(app, crate::panels::transform::show);
p.click_role("Angle", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
let steps = json!({"commands": [
{"command": "shape.rectangle", "params": {"x": 100, "y": 10, "width": 40, "height": 30}}
]});
let replacement = p.app().session.preview("command.batch", &steps).unwrap();
let rect = replacement["results"][0]["id"].clone();
assert_eq!(rect, previewed, "the replacement rectangle reuses the discarded rectangle's node ID");
let selected = p.app().session.active().map(|st| st.selection.objects.clone()).unwrap_or_default();
assert_eq!(json!(selected.iter().map(|id| id.0).collect::<Vec<_>>()), json!([rect]), "the preview selects the replacement rectangle");
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("0°"), "the field shows the replacement rectangle's angle");
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("7°"), "the replacement rectangle takes 7°, not the unfinished 3+ and 7");
}
#[test]
fn an_unfinished_ellipse_angle_or_pie_angle_does_not_reach_another_ellipse() {
for (name, shown) in [("Angle", "0°"), ("Pie Start Angle", "0°"), ("Pie End Angle", "360°")] {
let (app, a, b) = ellipses();
check_field(app, crate::panels::transform::show, &a, &b, name, shown, "7°");
}
}
#[test]
fn an_unfinished_star_points_or_ratio_does_not_reach_another_star() {
let stars = || {
two(
"shape.star",
json!({"cx": 60, "cy": 60, "radius1": 40, "radius2": 20, "points": 5}),
json!({"cx": 200, "cy": 60, "radius1": 40, "radius2": 20, "points": 5}),
)
};
let (app, a, b) = stars();
check_field(app, crate::panels::transform::show, &a, &b, "Points", "5", "7");
let (app, a, b) = stars();
check_field(app, crate::panels::transform::show, &a, &b, "Ratio", "0.5", "1");
}
#[test]
fn an_unfinished_line_length_or_angle_does_not_reach_another_line() {
let (app, a, b) = lines();
check_field(app, crate::panels::transform::show, &a, &b, "Line Length", &pt(100.0), &pt(7.0));
let (app, a, b) = lines();
check_field(app, crate::panels::transform::show, &a, &b, "Line Angle", "0°", "7°");
}
/// A value typed for a rectangle and not finished is dropped when File Revert replaces the document's content or
/// another document becomes active, even where the selection has the same ids and the same angle.
#[test]
fn an_unfinished_angle_is_dropped_by_file_revert_or_another_document() {
type Change = fn(&mut VectorcraftApp);
let changes: [(&str, Change); 2] = [
("File Revert", |app| {
// The same content again, with the same rectangle selected after it.
let st = app.session.active().unwrap();
let (doc, ids) = ((*st.doc).clone(), st.selection.objects.clone());
assert!(app.session.replace_document(0, doc));
app.run("select.set", json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()})).unwrap();
}),
("another document became active", |app| {
app.run("document.activate", json!({"index": 1})).unwrap();
}),
];
// The angle of the rectangle in each open document, in whole degrees, and the index of the active document.
let angles = |p: &Panel| -> (Vec<Option<i64>>, Option<usize>) {
let app = p.app();
let docs = app.session.documents();
let angles = docs.iter().map(|st| st.doc.node(st.selection.objects[0]).and_then(|n| n.live_shape()?.shape_angle()).map(|a| a.round() as i64));
let active = app.session.active().map(|a| a.uid);
(angles.collect(), docs.iter().position(|st| Some(st.uid) == active))
};
for (change, apply) in changes {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
for _ in 0..2 {
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let id = app.run("shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [id]})).unwrap();
}
app.run("document.activate", json!({"index": 0})).unwrap();
let mut p = Panel::new(app, crate::panels::transform::show);
p.click_role("Angle", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
apply(&mut p.app());
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("0°"), "{change}: the field shows the rectangle's angle");
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
let (got, active) = angles(&p);
let active = active.unwrap();
let mut want = vec![Some(0), Some(0)];
want[active] = Some(7);
assert_eq!(got, want, "{change}: the rectangle takes 7°, not the unfinished 3+ and 7");
}
}
/// While the selection stays the same, a value typed over several frames is kept and committed whole, also when an
/// edit to an unselected object changes the document in between.
#[test]
fn a_value_typed_with_the_same_selection_is_kept_across_frames() {
let (mut app, a, b) = rectangles();
app.run("select.set", json!({"ids": [a]})).unwrap();
let mut p = Panel::new(app, crate::panels::transform::show);
p.click_role("Angle", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.frame();
let revision = p.app().session.active().unwrap().revision;
p.app().run("stroke.set", json!({"ids": [b], "weight": 4})).unwrap();
assert_ne!(p.app().session.active().unwrap().revision, revision, "the document changed");
p.frame();
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("10°"), "3+7 is committed to the same rectangle");
}
/// An unfinished Sides value is dropped when selecting the star first replaces Sides with Points.
#[test]
fn an_unfinished_sides_count_does_not_reach_a_star_selected_first() {
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
let polygon = app.run("shape.polygon", json!({"cx": 60, "cy": 60, "radius": 40, "sides": 5})).unwrap()["id"].clone();
let star = app.run("shape.star", json!({"cx": 200, "cy": 60, "radius1": 40, "radius2": 20, "points": 5})).unwrap()["id"].clone();
app.run("select.set", json!({"ids": [polygon, star]})).unwrap();
let mut p = Panel::new(app, crate::panels::transform::show);
p.click_role("Sides", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().run("select.set", json!({"ids": [star, polygon]})).unwrap();
p.frame();
assert_eq!(p.value_role("Points", Role::SPIN_BUTTON).as_deref(), Some("5"), "the field shows the star's points");
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
assert_eq!(p.value_role("Points", Role::SPIN_BUTTON).as_deref(), Some("7"), "the star takes 7 points, not the unfinished 3+ and 7");
}
/// An Angle value typed across frames is kept when another corner of the same rectangle is Direct-Selected.
#[test]
fn a_value_typed_for_the_same_shape_is_kept_when_direct_selected_anchors_change() {
let (mut app, a, _) = rectangles();
let id = a.as_u64().unwrap();
app.run("select.anchors", json!({"id": id, "anchors": [[0, 0]], "mode": "set"})).unwrap();
let mut p = Panel::new(app, crate::panels::transform::show);
p.click_role("Angle", Role::SPIN_BUTTON);
p.key(Key::A, Modifiers::COMMAND);
p.type_text("3+");
p.app().run("select.anchors", json!({"id": id, "anchors": [[0, 2]], "mode": "set"})).unwrap();
p.frame();
p.type_text("7");
p.key(Key::Enter, Modifiers::NONE);
p.frame();
assert_eq!(p.value_role("Angle", Role::SPIN_BUTTON).as_deref(), Some("10°"), "3+7 is committed to the same rectangle");
}
+56 -2
View File
@@ -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<'_> {
@@ -744,6 +744,41 @@ mod tests {
assert_eq!(opacity_of(&panel, &b), 0.01, "Undo drops the unfinished value: 1%, not 20+1");
}
/// A canceled undo group drops an unfinished Opacity expression, though the object it takes away and the object
/// made and selected after it have the same id and opacity.
#[test]
fn unfinished_opacity_is_dropped_by_a_canceled_undo_group() {
let mut app = new_app();
run_cmd(&mut app, "edit.undoGroup.begin", json!({}));
let a = run_cmd(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 30, "height": 30}))["id"].clone();
run_cmd(&mut app, "select.set", json!({"ids": [a]}));
let mut panel = Panel::new(app, show);
unfinished_opacity(&mut panel);
run_cmd(&mut panel.app(), "edit.undoGroup.end", json!({"cancel": true}));
let b = run_cmd(&mut panel.app(), "shape.rectangle", json!({"x": 50, "y": 0, "width": 30, "height": 30}))["id"].clone();
assert_eq!(b, a, "the new rectangle has the canceled group's rectangle's id");
run_cmd(&mut panel.app(), "select.set", json!({"ids": [b]}));
finish_opacity(&mut panel);
assert_eq!(opacity_of(&panel, &b), 0.01, "the canceled group drops the unfinished value: 1%, not 20+1");
}
/// Discard Empty Type drops an unfinished Opacity expression when it takes back the step that made the empty
/// text, though the object made and selected after it has the same id and opacity.
#[test]
fn unfinished_opacity_is_dropped_by_discard_empty_type() {
let mut app = new_app();
let a = run_cmd(&mut app, "text.create", json!({"x": 10, "y": 40, "text": ""}))["id"].clone();
run_cmd(&mut app, "select.set", json!({"ids": [a]}));
let mut panel = Panel::new(app, show);
unfinished_opacity(&mut panel);
run_cmd(&mut panel.app(), "text.discardEmpty", json!({"id": a}));
let b = run_cmd(&mut panel.app(), "shape.rectangle", json!({"x": 50, "y": 0, "width": 30, "height": 30}))["id"].clone();
assert_eq!(b, a, "the new rectangle has the discarded text's id");
run_cmd(&mut panel.app(), "select.set", json!({"ids": [b]}));
finish_opacity(&mut panel);
assert_eq!(opacity_of(&panel, &b), 0.01, "Discard Empty Type drops the unfinished value: 1%, not 20+1");
}
/// The same objects selected in another order keep an unfinished Opacity expression.
#[test]
fn unfinished_opacity_stays_when_the_same_objects_are_selected_in_another_order() {
@@ -879,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};
+1 -1
View File
@@ -186,7 +186,7 @@ fn categories(app: &VectorcraftApp) -> impl Iterator<Item = &'static str> {
let _ = app;
None
};
PREF_CATEGORIES.iter().copied().chain(agents)
PREF_CATEGORIES.iter().copied().chain([crate::language_packs::PAGE]).chain(agents)
}
/// The agent settings as the AI Integrations page edits them; `None` where the window has no such page.
+16 -6
View File
@@ -380,15 +380,22 @@ impl Live<'_> {
impl PreferencesModel for Live<'_> {
fn pages(&self) -> Vec<PageSpec<'_>> {
let pages = PREF_CATEGORIES.iter().map(|&cat| self.page(cat));
let mut pages: Vec<PageSpec<'_>> = PREF_CATEGORIES.iter().map(|&cat| self.page(cat)).collect();
// Language Packs after Hyphenation: a page of its own, which installs and removes at once (nothing waits for
// OK, and there is nothing to reset).
let packs = PageSpec::custom(crate::language_packs::PAGE, tl!(crate::language_packs::PAGE))
.resettable(false)
.keywords(tl!("spelling dictionary hyphenation language download install remove"));
let at = pages.iter().position(|p| p.id == "Hyphenation").map_or(pages.len(), |i| i + 1);
pages.insert(at, packs);
// The agent settings, drawn whole by the framework's Agents page, on the desktop.
#[cfg(not(target_arch = "wasm32"))]
let pages = pages.chain(self.app.agents.is_some().then(|| {
if self.app.agents.is_some() {
use crate::agents::PAGE_TITLE;
let keywords = "agents AI MCP ArtCraft Launcher control port folders";
PageSpec::custom(PAGE_TITLE, tl!(PAGE_TITLE)).keywords(keywords).resettable(false)
}));
pages.collect()
pages.push(PageSpec::custom(PAGE_TITLE, tl!(PAGE_TITLE)).keywords(keywords).resettable(false));
}
pages
}
fn set(&mut self, key: &str, value: PrefValue) {
@@ -464,7 +471,10 @@ impl PreferencesModel for Live<'_> {
if page == crate::agents::PAGE_TITLE {
return agents_page(self, ui);
}
let _ = (ui, page);
if page == crate::language_packs::PAGE {
crate::language_packs::page(self.app, ui);
}
// Nothing of the draft changes: a pack installs or is removed at once.
false
}
+5
View File
@@ -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,
+14
View File
@@ -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
View File
@@ -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
+4 -4
View File
@@ -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) |
+2 -1
View File
@@ -551,7 +551,7 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
- **Done:** COLR and SVG glyphs go with type that geometry effects reshape, into Expand Appearance and EMF/WMF
export, where the type's outlines used to leave them out; bitmap glyphs (emoji) too, as images that hold their
own pixels until a document takes them in; estimate unchanged.
- **Done:** spell check (#4936): engine (`text.spelling.check` and `text.spelling.suggest` on craft-proof); custom dictionary and Ignore All (`text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary`, `ignoreAll`); Auto Spell Check (`edit.autoSpellCheck`) with red wavy underlines and canvas context menu suggestions, Ignore All and Add to Dictionary; Edit › Edit Custom Dictionary…; and modal Check Spelling dialog (Edit › Spelling › Check Spelling…, and Spelling › Check Spelling… in the canvas context menu of type, `ui.checkSpelling`) with sentence context, suggestions list, "Change to" edit, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done, Cancel, and keyboard navigation; Language packs for languages other than English, read from the Craft apps' shared font store, with `proof.packs`, `proof.installPack` and `proof.removePack` (a Preferences page to install them and the missing-pack bar remain). Estimate unchanged.
- **Done:** spell check (#4936): engine (`text.spelling.check` and `text.spelling.suggest` on craft-proof); custom dictionary and Ignore All (`text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary`, `ignoreAll`); Auto Spell Check (`edit.autoSpellCheck`) with red wavy underlines and canvas context menu suggestions, Ignore All and Add to Dictionary; Edit › Edit Custom Dictionary…; and modal Check Spelling dialog (Edit › Spelling › Check Spelling…, and Spelling › Check Spelling… in the canvas context menu of type, `ui.checkSpelling`) with sentence context, suggestions list, "Change to" edit, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done, Cancel, and keyboard navigation; Language packs for languages other than English, read from the Craft apps' shared font store, with `proof.packs`, `proof.installPack` and `proof.removePack` ; Edit › Preferences › Language Packs lists them (size, what each provides, licence) with Install, Remove, progress and errors, and a dismissible bar over the canvas offers a pack when the downloaded list contains one for a document language without a dictionary (`proof.packs` `missing`); the person's own click turns downloading on, an injected one never does; the web build has no packs yet (craft-libs#745). Estimate unchanged.
- **Missing:** CJK vertical
composition (custom mojikumi sets and the Mojikumi Settings dialog), Middle Eastern
features beyond bidi, digit types, Character Direction and Kashidas (a split caret; the Middle Eastern & South Asian composers are done, #4935),
@@ -1069,6 +1069,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv
| Date | Change | Summary |
|---|---|---|
| 2026-12-02 | minor | G16: 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-12-02 | minor | G4 type: Language packs UI (#4936): Edit › Preferences › Language Packs lists the installed packs and the packs on the downloadable list (size, spelling, hyphenation, licence) with Install, Remove, progress and errors; a dismissible missing-pack bar over the canvas offers Install when the downloaded list has a pack for a document language without a dictionary, or Get Language Pack before the list is fetched; `proof.packs` reports `missing`; only the person's own click turns downloading on; not on the web (craft-libs#745); scores and estimates unchanged. |
| 2026-11-27 | minor | G4 type: Language packs (#4936): spelling and hyphenation read the packs installed in the Craft apps' shared font store, and `proof.packs`, `proof.installPack` and `proof.removePack` list, install and remove them (installs need downloading on, which only the person turns on); a Preferences page to install them and the missing-pack bar remain; 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-23 | minor | Gradient stop editor: a compact Color-tab menu offers Grayscale Slider, RGB Sliders, HSB Sliders, CMYK Sliders and Web Color Sliders, sharing the Color panel mode and conversion behavior (#7918). Choosing a mode keeps the editor open; Escape closes the menu first. Scores and estimates unchanged. |
+3 -2
View File
@@ -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. |
+12 -4
View File
@@ -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"}}}
@@ -15119,14 +15124,17 @@ installed packs; the web app has none, and no `proof.*` commands.
running (`installing`, with bytes `done` of `total`), whether the index is being fetched (`refreshing`), the last
failure of each locale (`errors`; `""` is the index fetch), whether downloading is on (`downloads`), a test index
used instead of the pinned one (`indexOverride`, from `CRAFT_LANGUAGE_PACK_INDEX`) and whether there is a store to
install into (`available`). `refresh: true` fetches the index again.
install into (`available`), and the languages of the front document's visible, unlocked type that have no
dictionary (`missing`: each `lang` with its pack's `locale`, `null` before the index is first fetched; a language the
fetched index has no pack for is left out). `refresh: true` fetches the index again.
- `proof.installPack {locale}` downloads a pack, checks its sha256 and installs it (fetching the index first when it
doesn't list the locale). Every open document is laid out and checked again with it. `locale` is the pack's tag,
like `nl` or `pt-br` (`pt_BR` reads as `pt-br`).
- `proof.removePack {locale}` removes an installed pack, not while it installs.
Installs and index fetches need downloading on. Only the person using a Craft app turns it on, with their own click
(the setting is the font store's, shared by the apps): no command turns it on, and until then an install is an error
(in VectorCraft: Install, Refresh List or Get Language Pack in Edit › Preferences › Language Packs, or in the bar over
the canvas that offers a missing language's pack; the setting is the font store's, shared by the apps): no command, and no click the control channel injects (`ui.click`), turns it on, and until then an install is an error
that says so. A caller with automation roots (`--automation-read-root`, `--automation-write-root`) can list packs
but not fetch, install or remove them, since the store is outside its roots. A script cannot run the `proof.*`
commands at all, since a run's rollback cannot put the store back. In the desktop app installs and fetches
+4 -3
View File
@@ -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
+4 -2
View File
@@ -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.
+3 -2
View File
@@ -1,6 +1,6 @@
# Type parity
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-18 · **Change:** minor (Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: modal Check Spelling dialog: Edit › Spelling › Check Spelling…, `ui.checkSpelling`, #4936; spell check complete; previously minor: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; `.ai` and EPS files do not carry the choice; scores and estimates unchanged; previously minor: kerning at the Type tool's caret at the start of a line sets the space before the character after it, #5111; previously minor: type's strokes in an envelope paint along its bent glyph outlines at their own weight, Distort Appearance on or off, as users' `.ai` files draw them, #6644; previously minor: a centred or right-aligned line of tracked type is aligned without the tracking after its last character, as the page of users' `.ai` files aligns it, #6610; previously minor: tracking and manual kerning in horizontally scaled type are thousandths of the em as the Horizontal Scale draws it, as the page of users' `.ai` files spaces such type; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: Direct Selection shows and drags the direction handles of type on a path's path, #3565; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen) · **Target:** Adobe Illustrator 2026 (30.x)
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-12-02 · **Change:** minor (Language packs (#4936): Edit › Preferences › Language Packs and the missing-pack bar; previously: Retype phase 1 (#4934): Type › Retype (`type.retype`) turns outlined text that exactly matches an available font back into point text; scores and estimates unchanged; previously: modal Check Spelling dialog: Edit › Spelling › Check Spelling…, `ui.checkSpelling`, #4936; spell check complete; previously minor: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; `.ai` and EPS files do not carry the choice; scores and estimates unchanged; previously minor: kerning at the Type tool's caret at the start of a line sets the space before the character after it, #5111; previously minor: type's strokes in an envelope paint along its bent glyph outlines at their own weight, Distort Appearance on or off, as users' `.ai` files draw them, #6644; previously minor: a centred or right-aligned line of tracked type is aligned without the tracking after its last character, as the page of users' `.ai` files aligns it, #6610; previously minor: tracking and manual kerning in horizontally scaled type are thousandths of the em as the Horizontal Scale draws it, as the page of users' `.ai` files spaces such type; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: Direct Selection shows and drags the direction handles of type on a path's path, #3565; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen) · **Target:** Adobe Illustrator 2026 (30.x)
> **File-font hardening status (2026-11-12, #4569):** implementation and synthetic regressions added; compilation and runtime checks pending. Scores and estimates unchanged.
>
@@ -55,7 +55,7 @@ against Illustrator's public documentation; **estimated** unless noted.
| Hyphenation… and Justification… options | done | Eleven Indian languages use attributed patterns and preserve syllables in both composers (#4947). Hyphenation… (`ui.hyphenation`, `text.setFormat`) sets each paragraph's Words Longer Than, After First, Before Last, Hyphen Limit, Hyphenation Zone (Single-line Composer only) and Hyphenate Capitalized Words, and paragraph styles carry them (#2310). Justification… (`ui.justification`, `text.setFormat`, #2755) sets Word Spacing, Letter Spacing and Glyph Scaling (Minimum, Desired, Maximum), Auto Leading and Single Word Justification; Desired applies to every line, justified lines and the Every-line Composer use the ranges. Vertical type isn't glyph scaled. Auto Leading also sets the Leading the Character panel shows for Auto type, the leading Alt+↑/↓ (`type.step`) steps from, per paragraph, and the lines Fill with Placeholder Text counts. Evidence: `crates/text/src/tests/justify.rs`, `dialogs::justification::tests`, `tests_prefs::auto_leading_steps_and_fills_from_the_paragraph_auto_leading`, `panels::character` test `leading_field_shows_the_paragraph_auto_leading` |
| Tab stops and leaders; Tabs panel | partial | Tabs panel and stops with leaders in the model (`text.tabs.set`); a stop drags from where the press landed (#1458); leaders fill the tab's gap, repeated on a grid so they line up from line to line (#1877); Ctrl-dragging a stop (Command on macOS) moves all the stops together; in right-aligned area type the text before a line's last tab sits at its stops, from the left edge, and the text after it against the right edge, as Illustrator's own layout in a user's `.ai` sets a price list (evidence: `tests::right_aligned_area_type_sets_the_text_after_its_last_tab_against_the_edge`; centred lines are still aligned as a whole); in justified area type the text up to a line's last tab keeps its spacing and its tabs their stops, and the text after the last tab takes the line's room to the far edge, VectorCraft's own rule (evidence: `tests::justify::a_justified_line_with_a_tab_spreads_the_text_after_it_to_the_edge` and the other tab tests in `crates/text/src/tests/justify.rs`) |
| Hidden characters (Show Hidden Characters) | done | `type.hiddenCharacters`: marks spaces, tabs, nonbreaking and narrow nonbreaking spaces, the spaces of a set width, discretionary hyphens, forced line breaks, paragraph ends and the story's end, in horizontal, vertical and right-to-left type and on a path, and none on type in a hidden group or layer; the mark shapes are VectorCraft's own. Evidence: `canvas::tests::hidden_characters_*` |
| Spell check (Check Spelling, Auto Spell Check, custom dictionary) | done | the engine (#4936): `text.spelling.check` lists the unknown words of the document's type, each run in its Language, at the bytes `text.editRange` changes, and `text.spelling.suggest` gives suggestions, both from craft-proof, each paragraph on its own (English from the first dictionary it finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into it; other languages from the dictionaries craft-proof finds for them). The custom dictionary commands are done: `text.spelling.addWord`, `removeWord` and `changeWord` (Add, and Edit Custom Dictionary's Add, Delete and Change), and `text.spelling.dictionary` lists the words, saved to `Custom Dictionary.txt` beside the preferences; Ignore All: `text.spelling.ignoreAll` skips a word in the active document while it is open. Auto Spell Check is done: Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`, off at first, saved with the view settings) draws a red wavy line under the unknown words of the visible type, leaves out type with effects, and follows edits, the custom dictionary and Ignore All. A right-click on an underlined word lists the words its dictionary suggests (each replaces it in one undo step, `text.editRange`), or No Suggestions, then Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check, checked while it is on. Edit › Edit Custom Dictionary… lists the custom dictionary's words, with an Entry field and Add, Delete and Change, applied on Done (Cancel leaves the dictionary as it was). The modal Check Spelling dialog is done: Edit › Spelling › Check Spelling… (`Cmd+I`, `ui.checkSpelling`) opens a modal dialog displaying the unrecognized word in sentence context ("Not in Dictionary"), a list of suggestions with double-click or selection to replace ("Change to" field), and action buttons: Ignore, Ignore All, Change (one-step Undo/Redo via `text.editRange`), Change All (batched across occurrences in a single undo step), Add to Dictionary (`text.spelling.addWord`), Done and Cancel, with keyboard navigation (Tab between controls, Enter to Change or Done, Escape to close). Evidence: `crates/engine/src/tests/spelling.rs`, `crates/ui-egui/src/canvas/tests.rs` (`auto_spell_check_*`), `crates/ui-egui/src/tests/contextmenu.rs` (the right-click), `crates/ui-egui/src/dialogs/custom_dictionary.rs` (the dialog), `crates/ui-egui/src/dialogs/check_spelling.rs` (the Check Spelling dialog). |
| Spell check (Check Spelling, Auto Spell Check, custom dictionary) | done | the engine (#4936): `text.spelling.check` lists the unknown words of the document's type, each run in its Language, at the bytes `text.editRange` changes, and `text.spelling.suggest` gives suggestions, both from craft-proof, each paragraph on its own (English from the first dictionary it finds: a Hunspell dictionary in the user's dictionaries folder, the SCOWL dictionary built in from craft-i18n, a system Hunspell dictionary, and last the public-domain Moby word list built into it; other languages from the dictionaries craft-proof finds for them). The custom dictionary commands are done: `text.spelling.addWord`, `removeWord` and `changeWord` (Add, and Edit Custom Dictionary's Add, Delete and Change), and `text.spelling.dictionary` lists the words, saved to `Custom Dictionary.txt` beside the preferences; Ignore All: `text.spelling.ignoreAll` skips a word in the active document while it is open. Auto Spell Check is done: Edit › Spelling › Auto Spell Check (`edit.autoSpellCheck`, off at first, saved with the view settings) draws a red wavy line under the unknown words of the visible type, leaves out type with effects, and follows edits, the custom dictionary and Ignore All. A right-click on an underlined word lists the words its dictionary suggests (each replaces it in one undo step, `text.editRange`), or No Suggestions, then Ignore All and Add to Dictionary, and a right-click on type has Spelling › Auto Spell Check, checked while it is on. Edit › Edit Custom Dictionary… lists the custom dictionary's words, with an Entry field and Add, Delete and Change, applied on Done (Cancel leaves the dictionary as it was). The modal Check Spelling dialog is done: Edit › Spelling › Check Spelling… (`Cmd+I`, `ui.checkSpelling`) opens a modal dialog displaying the unrecognized word in sentence context ("Not in Dictionary"), a list of suggestions with double-click or selection to replace ("Change to" field), and action buttons: Ignore, Ignore All, Change (one-step Undo/Redo via `text.editRange`), Change All (batched across occurrences in a single undo step), Add to Dictionary (`text.spelling.addWord`), Done and Cancel, with keyboard navigation (Tab between controls, Enter to Change or Done, Escape to close). Language packs (#4936) spell-check and hyphenate other languages: Edit › Preferences › Language Packs installs and removes them (`proof.installPack`, `proof.removePack`), and a bar over the canvas offers the pack for a language of the document's type that has no dictionary. Evidence: `crates/engine/src/tests/spelling.rs`, `crates/ui-egui/src/canvas/tests.rs` (`auto_spell_check_*`), `crates/ui-egui/src/tests/contextmenu.rs` (the right-click), `crates/ui-egui/src/dialogs/custom_dictionary.rs` (the dialog), `crates/ui-egui/src/dialogs/check_spelling.rs` (the Check Spelling dialog), `crates/engine/src/tests/packs.rs` and `crates/ui-egui/src/language_packs/desktop/tests.rs` (Language packs). |
| Smart Punctuation, Change Case, Find & Replace | done | Type › Smart Punctuation… opens a dialog with the ff, fi, ffi and ff, fl, ffl ligatures, Smart Quotes, Smart Spaces, En, Em Dashes, Ellipses and Expert Fractions, Replace In and Report Results, which lists the count of each replacement; ligatures and fractions are written only where the font has a glyph for them. Evidence: `tests::menucmds::smart_punctuation_ligatures_spaces_and_fractions_are_counted`, `smart_punctuation_skips_ligatures_and_fractions_the_font_lacks`, `smart_spaces_keeps_one_space_after_a_period`, `dialogs::smart_punctuation::tests::menu_item_opens_the_dialog_and_ok_reports_the_counts` |
| Alt + numeric-keypad codes while typing (Windows: `Alt+0176` → °) | partial | #5108: on Windows the character Windows posts when Alt comes up after keypad digits is typed at the caret like any other, in the typing's undo step (winit reports it as typed text), and the keypad digits typed with Alt run no shortcut. With NumLock off the keypad keys (Insert, End, arrows, Clear, Home, Page Up/Down without the extended-key flag) count as digits too and don't move the caret (`windows_alt_codes` unit tests; neither NumLock on nor off has been tried on a Windows machine yet). `type.insert {code}` (Windows Alt+0 code, Windows-1252 for 128–159) and `{unicode}` (hex code point) insert a character by its code (`menucmds::insert_a_character_by_its_code`). macOS and Linux have no such system convention and egui reports a keypad digit as the top-row digit, so there it does nothing; in a floating panel window the keypad digits typed with Alt are not taken out of the frame |
| Caret: the arrows and Delete step over whole clusters (Thai consonant with its marks, combining accents, emoji); Backspace removes one character | done | in text with right-to-left characters the arrows move in visual order and stop on both sides of a character drawn with no width, such as a zero width non-joiner |
@@ -93,6 +93,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha
| Date | Change | Summary |
|---|---|---|
| 2026-12-02 | minor | Language packs (#4936): Edit › Preferences › Language Packs lists, installs and removes the packs that spell-check and hyphenate languages other than English, and a dismissible bar over the canvas offers the pack for a language of the document's type without a dictionary; not on the web yet. |
| 2026-11-12 | minor | #4569: file-font identity, ownership and live-face allowance hardening; forged internal family names no longer select global file fonts. Preserve owned fallback bindings through installed-font removal, placement, older saves and recovery. Added synthetic regressions; format-only verification, runtime proof pending. Scores and estimates unchanged. |
| 2026-11-18 | minor | Retype phase 1 (#4934): `type.retype` turns outlined glyphs that exactly match an available font back into point text (font, size, baseline, turn, paint), reporting the shapes it cannot match; the Retype row is now partial. Scores and estimates unchanged |
| 2026-11-15 | minor | Check Spelling dialog (#4936): Edit › Spelling › Check Spelling… (`Cmd+I`, `ui.checkSpelling`) modal dialog with sentence context, suggestions, Ignore, Ignore All, Change, Change All, Add to Dictionary, Done/Cancel, keyboard navigation, and one-step Undo/Redo; spell check complete. Scores and estimates unchanged. |
+1
View File
@@ -84,6 +84,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard
| 2026-12-02 | minor | Canvas context menu: rows for edit, group, path, type, view and artboard commands show a leading icon from the app's icon set, so a row can be found by its shape; rows without a fitting glyph stay text only (#4602); scores and estimates unchanged |
| 2026-12-02 | minor | Retype panel (G12): font rows have an item context menu: a secondary click or Shift+F10 selects the row and offers Apply Font (what a click on the row does; off without live text selected), the panel menu's Small, Medium and Large sample sizes and Reset Retype Panel; the menu closes when the list or the document changes. Headless regressions: `panels::retype::tests`. Scores and estimates unchanged. |
| 2026-12-02 | minor | Headless (RFC-0052) column on the Summary table and every behaviour table: 365 unknown, with marking rules |
| 2026-12-02 | minor | G4 (desktop only; the web page says packs can't be installed there yet): Edit › Preferences › Language Packs (after Hyphenation) lists the installed Language packs, with Remove, and the packs on the downloadable list, with Install, each with its progress and errors; a dismissible bar at the foot of the canvas offers the pack for a language of the document's type without a dictionary when the downloadable list has one, or to fetch the list when none was fetched yet; a language with no pack in the list (Gujarati in the pinned list) gets no offer (#4936); 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. |
| 2026-11-20 | minor | G12: Asset Export tiles have item context menus for Export, Remove, Rename, Select Artwork on Canvas and collecting selected artwork; right-click selects an unselected tile and preserves an existing multi-selection. Headless regressions: panels::tests_asset_export. Scores and estimates unchanged. |