Merge remote-tracking branch 'origin/main' into HEAD

This commit is contained in:
David Mann committed 2026-10-27 01:22:22 +01:00
commit 999e98e8b1
31 files changed
+2820 -310

No files matched your search

+7 -3
View File
@@ -156,9 +156,13 @@ jobs:
# A panic still names its file and line; only backtrace frames lose theirs (Linux keeps
# line-tables-only, so a backtrace with lines is one OS away).
CARGO_PROFILE_DEV_DEBUG: "0"
# The runner has no Japanese or Simplified Chinese system font, and egui 0.37 panics on a
# missing glyph: the localized UI tests need the same craft-fonts input the gate and FreeBSD
# build with (crates/text/build.rs). Same commit as the gate above and release.yml.
# The all-language UI tests shape real Japanese, Chinese, Korean and Devanagari labels
# with kittest's strict `MissingGlyphPolicy::Panic`. A hosted Windows image has no
# guaranteed Japanese or Simplified Chinese system font, and egui 0.37 panics on a
# missing glyph; the app's lazy system fallback runs after layout, too late for the
# first headless frame. Use the same pinned central fonts as Linux and release, so every
# language is drawn by a real embedded face rather than skipping. Same commit as the gate
# above and release.yml.
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
CRAFT_FONTS_REQUIRED: "1"
steps:
+4 -1
View File
@@ -16,6 +16,9 @@ concurrency:
jobs:
sonarcloud:
# Tracked at @main so org-wide CI improvements propagate without PR churn.
# Track shared CI improvements on main.
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
with:
timeout-minutes: 120
fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
secrets: inherit
+1 -1
View File
@@ -8,7 +8,7 @@ use serde_json::{Value, json};
/// The binary, without the variables `mcp` and `serve` fall back to: a test that wants one sets it.
fn bin() -> Command {
let mut cmd = Command::new(env!("CARGO_BIN_EXE_photocraft-cli"));
let mut cmd = Command::new(crate::binary());
for var in ENV_VARS {
cmd.env_remove(var);
}
+5
View File
@@ -3,3 +3,8 @@
mod cli;
mod man_and_completions;
mod orientation;
/// Nextest archives relocate binaries; plain Cargo keeps the compile-time path valid.
fn binary() -> std::ffi::OsString {
std::env::var_os("NEXTEST_BIN_EXE_photocraft_cli").unwrap_or_else(|| env!("CARGO_BIN_EXE_photocraft-cli").into())
}
+1 -1
View File
@@ -10,7 +10,7 @@ use photocraft_codecs::{ChannelLayout, DecodeOptions, EncodeOptions, Format, Ima
use serde_json::Value;
fn bin() -> Command {
Command::new(env!("CARGO_BIN_EXE_photocraft-cli"))
Command::new(crate::binary())
}
fn tmp(name: &str) -> PathBuf {
@@ -34,7 +34,7 @@ fn run_with(args: &[&str], vars: &[(&str, &str)]) -> Run {
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("photocraft-usage-{}-{n}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_photocraft"));
let mut cmd = std::process::Command::new(crate::binary());
for var in VARS {
cmd.env_remove(var);
}
@@ -28,7 +28,7 @@ fn run_with(args: &[&str], vars: &[(&str, &str)]) -> Run {
let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("photocraft-control-exit-{}-{n}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let output = std::process::Command::new(env!("CARGO_BIN_EXE_photocraft"))
let output = std::process::Command::new(crate::binary())
.args(args)
.env("PHOTOCRAFT_CONFIG_DIR", &dir)
// Isolate from the host environment so the test is reproducible.
+5
View File
@@ -3,3 +3,8 @@
mod command_line_usage;
mod control_exit_code;
mod startup_without_display;
/// Nextest archives relocate binaries; plain Cargo keeps the compile-time path valid.
fn binary() -> std::ffi::OsString {
std::env::var_os("NEXTEST_BIN_EXE_photocraft").unwrap_or_else(|| env!("CARGO_BIN_EXE_photocraft").into())
}
@@ -30,7 +30,7 @@ fn missing_display_preserves_existing_gpu_crash_evidence() {
}
fn launch_without_display(dir: &std::path::Path) -> String {
let output = std::process::Command::new(env!("CARGO_BIN_EXE_photocraft"))
let output = std::process::Command::new(crate::binary())
.env("PHOTOCRAFT_CONFIG_DIR", dir)
.env_remove("DISPLAY")
.env_remove("WAYLAND_DISPLAY")
+23
View File
@@ -423,6 +423,29 @@ mod shapes {
}
}
#[test]
fn artistic_text_reads_its_characters_runs_and_anchor() {
let glyphs = F::Obj(tag(b"Glyp"), vec![(tag(b"Utf8"), F::Str("Hi".into()))]);
let run = F::Obj(tag(b"Item"), vec![]);
let attributes = F::Obj(tag(b"GAtt"), vec![(tag(b"Runs"), F::Objs(tag(b"Runs"), vec![vec![(tag(b"Indx"), F::I32(2)), (tag(b"Item"), run)]]))]);
let block = vec![(tag(b"Glyp"), glyphs), (tag(b"GAtt"), attributes)];
let text = F::Def(
100,
vec![tag(b"TxtA")],
vec![
(tag(b"TxtH"), F::Obj(tag(b"ArFr"), vec![(tag(b"FrmB"), F::F64s(vec![0.0, 0.0, 100.0, 50.0]))])),
(tag(b"StSt"), F::Obj(tag(b"StSt"), vec![(tag(b"Blok"), F::Objs(tag(b"Blok"), vec![block]))])),
],
);
let document = read(vec![text], 100);
let Kind::Text(t) = &document.spreads[0].nodes[0].kind else { panic!("expected text") };
assert_eq!(t.runs.len(), 1);
assert_eq!(t.runs[0].text, "Hi");
assert_eq!(t.align, crate::model::Align::Left);
assert_eq!(t.anchor, Point { x: 0.0, y: 0.0 });
assert!(t.frame.is_none());
}
#[test]
fn pie_angles_with_huge_finite_values_do_not_loop_or_emit_nonfinite_points() {
let document = read(vec![shape(100, b"ShPi", vec![(tag(b"AngS"), F::F64(1.0e308)), (tag(b"AngE"), F::F64(-1.0e308))])], 100);
+28 -21
View File
@@ -4,7 +4,7 @@
use crate::model::{Affine, Align, Point, Reader, Text, TextRun, rect};
use crate::paint::{self, Paint};
use crate::stream::{ObjId, Value};
use crate::stream::{ObjId, Stream, Value};
/// Characters read per text node (stories are split into blocks; this caps hostile ones).
const MAX_CHARS: usize = 1 << 20;
@@ -21,26 +21,7 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option<Text> {
let mut placeholders = false;
for block in s.objs(story, b"Blok") {
let glyphs = s.obj(block, b"Glyp")?;
let chars: Vec<char> = match s.str(glyphs, b"Utf8") {
Some(t) => t.chars().collect(),
None => {
// Inline objects (page numbers, anchors) each take one index before the segment text.
let mut v = Vec::new();
// One past the allowance is enough to trip the check below; shared segments
// repeated by reference must not expand beyond it first.
let room = MAX_CHARS.saturating_sub(total).saturating_add(1);
for seg in s.objs(glyphs, b"Mixd") {
if v.len() >= room {
break;
}
let inline = s.objs(seg, b"Glys").len();
v.extend(std::iter::repeat_n('\u{FFFC}', inline.min(room - v.len())));
placeholders |= inline > 0;
v.extend(s.str(seg, b"Utf8").unwrap_or_default().chars().take(room.saturating_sub(v.len())));
}
v
}
};
let chars = block_chars(s, glyphs, total, &mut placeholders);
total = total.checked_add(chars.len())?;
if total > MAX_CHARS {
r.warn("text longer than a million characters (truncated)");
@@ -84,6 +65,32 @@ pub(crate) fn read(r: &mut Reader, id: ObjId, world: Affine) -> Option<Text> {
Some(Text { runs, align, anchor: Point { x: anchor_x, y: first_baseline }, frame: if artistic { None } else { Some(bounds) }, transform: world })
}
/// The characters of one text block. A block without a UTF-8 string is a list of segments: each
/// inline object (page number, anchor) takes one `U+FFFC` before its segment's text. Stops once
/// `total` plus these characters would pass the cap.
fn block_chars(s: &Stream, glyphs: ObjId, total: usize, placeholders: &mut bool) -> Vec<char> {
// One past the allowance is enough to trip the check in `read`; both arms stop there.
let room = MAX_CHARS.saturating_sub(total).saturating_add(1);
match s.str(glyphs, b"Utf8") {
Some(t) => t.chars().take(room).collect(),
None => {
// Inline objects (page numbers, anchors) each take one index before the segment text.
let mut v = Vec::new();
// Shared segments repeated by reference must not expand beyond the allowance first.
for seg in s.objs(glyphs, b"Mixd") {
if v.len() >= room {
break;
}
let inline = s.objs(seg, b"Glys").len();
v.extend(std::iter::repeat_n('\u{FFFC}', inline.min(room - v.len())));
*placeholders |= inline > 0;
v.extend(s.str(seg, b"Utf8").unwrap_or_default().chars().take(room.saturating_sub(v.len())));
}
v
}
}
}
fn slot<T: Copy>(v: Option<&Value>, i: usize, f: impl Fn(&Value) -> Option<T>) -> Option<T> {
match v? {
Value::Array(a) => a.get(i).and_then(f),
+46 -35
View File
@@ -6,7 +6,7 @@
//! `layer.layerStyle.*`.
use photocraft_color::{BlendMode, ColorMode, SampleType};
use photocraft_doc::{Document, Effect, Layer, Size};
use photocraft_doc::{Document, Effect, Layer, Pattern, Size};
use photocraft_geom::Rect;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
@@ -170,19 +170,12 @@ fn targets(s: &Session, p: &Value) -> Vec<photocraft_doc::LayerId> {
crate::layer_multi_cmds::selected(s)
}
fn apply(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "style.presets.apply";
let style = find_style(s, p, CMD)?.clone();
let add = p.get("add").and_then(Value::as_bool).unwrap_or(false);
let ids = targets(s, p);
if ids.is_empty() {
return Err(bad(CMD, "no target layers"));
}
// Pattern overlays name their pattern; resolve to library patterns copied into the document.
/// Resolves each effect's pattern, plus the patterns that strokes and bevels name, copied from the library.
fn resolve_style_effects(s: &Session, fx_list: &[Effect]) -> Result<(Vec<Effect>, Vec<Pattern>)> {
let mut effects = Vec::new();
let mut pats = Vec::new();
for fx in style.effects {
let (fx, pat) = crate::pattern_cmds::resolve_effect(s, fx)?;
for fx in fx_list {
let (fx, pat) = crate::pattern_cmds::resolve_effect(s, fx.clone())?;
effects.push(fx);
pats.extend(pat);
}
@@ -192,6 +185,46 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
pats.push(pat);
}
}
Ok((effects, pats))
}
/// Writes a preset onto one layer: replaces its effects, or appends to them when `add`.
fn apply_to_layer(l: &mut Layer, style: &StylePreset, effects: &[Effect], add: bool) {
if add {
l.effects.items.extend(effects.iter().cloned());
} else {
l.effects.items = effects.to_vec();
l.effects.psd_raw = None;
}
l.effects.psd_raw = None;
l.effects.enabled = true;
// Adding keeps the layer's blending unless the preset carries some: a blend mode, or
// an Opacity saved on its own (`style.presets.new` with `includeBlending: false`).
if !add || style.blend.is_some() || style.opacity.is_some() {
if let Some(b) = style.blend {
l.blend = b;
}
if let Some(f) = style.fill_opacity {
l.fill_opacity = f;
} else if !add {
l.fill_opacity = 1.0;
}
if let Some(o) = style.opacity {
l.opacity = o;
}
}
}
fn apply(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "style.presets.apply";
let style = find_style(s, p, CMD)?.clone();
let add = p.get("add").and_then(Value::as_bool).unwrap_or(false);
let ids = targets(s, p);
if ids.is_empty() {
return Err(bad(CMD, "no target layers"));
}
// Pattern overlays name their pattern; resolve to library patterns copied into the document.
let (effects, pats) = resolve_style_effects(s, &style.effects)?;
let label = format!("Apply Style: {}", style.name);
s.edit(&label, |doc, _| {
for pat in &pats {
@@ -204,29 +237,7 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
// Styles can't sit on the Background: Photoshop turns it into a normal layer first.
crate::extra_cmds::background_to_layer(doc, *id);
let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?;
if add {
l.effects.items.extend(effects.iter().cloned());
} else {
l.effects.items = effects.clone();
l.effects.psd_raw = None;
}
l.effects.psd_raw = None;
l.effects.enabled = true;
// Adding keeps the layer's blending unless the preset carries some: a blend mode, or
// an Opacity saved on its own (`style.presets.new` with `includeBlending: false`).
if !add || style.blend.is_some() || style.opacity.is_some() {
if let Some(b) = style.blend {
l.blend = b;
}
if let Some(f) = style.fill_opacity {
l.fill_opacity = f;
} else if !add {
l.fill_opacity = 1.0;
}
if let Some(o) = style.opacity {
l.opacity = o;
}
}
apply_to_layer(l, &style, &effects, add);
}
Ok(())
})?;
+48 -25
View File
@@ -1047,6 +1047,12 @@ pub struct Warp {
pub values: Vec<f64>,
}
/// Relative to the magnitude so the fit's rounding at large origins isn't rejected.
fn point_fits(expected: [f64; 2], actual: [f64; 2]) -> bool {
let tol = |e: f64| (1e-9 * e.abs().max(1.0)).min(1e-6);
!((actual[0] - expected[0]).abs() >= tol(expected[0]) || (actual[1] - expected[1]).abs() >= tol(expected[1]))
}
impl Warp {
/// No warp over `bounds`.
pub fn none(bounds: [f64; 4]) -> Warp {
@@ -1080,36 +1086,53 @@ impl Warp {
WarpStyle::None => true,
WarpStyle::Custom | WarpStyle::Cylinder => match &self.mesh {
None => true,
Some(m) => {
if !m.is_valid() {
return false;
}
let nx = m.nx();
let (pc, pr) = (m.us.len() - 1, m.vs.len() - 1);
for pj in 0..pr {
for j in 0..4 {
let v = m.vs[pj] + (m.vs[pj + 1] - m.vs[pj]) * j as f64 / 3.0;
for pi in 0..pc {
for i in 0..4 {
let u = m.us[pi] + (m.us[pi + 1] - m.us[pi]) * i as f64 / 3.0;
let expected = self.box_point(u, v);
let actual = m.points[(3 * pj + j) * nx + 3 * pi + i];
// Relative to the magnitude so the fit's rounding at large origins isn't rejected.
let tol = |e: f64| (1e-9 * e.abs().max(1.0)).min(1e-6);
if (actual[0] - expected[0]).abs() >= tol(expected[0]) || (actual[1] - expected[1]).abs() >= tol(expected[1]) {
return false;
}
}
}
}
}
true
}
Some(m) => self.mesh_is_box_fit(m),
},
_ => self.style_warp().is_none(),
}
}
/// True when every control point of `m` sits where the box's own grid puts it.
fn mesh_is_box_fit(&self, m: &BezierMesh) -> bool {
if !m.is_valid() {
return false;
}
let (pc, pr) = (m.us.len() - 1, m.vs.len() - 1);
for pj in 0..pr {
for j in 0..4 {
if !self.mesh_row_is_box_fit(m, pj, j, pc) {
return false;
}
}
}
true
}
/// One sample row (`j` within patch row `pj`) of [`Self::mesh_is_box_fit`].
fn mesh_row_is_box_fit(&self, m: &BezierMesh, pj: usize, j: usize, pc: usize) -> bool {
let nx = m.nx();
let (Some(&v0), Some(&v1)) = (m.vs.get(pj), m.vs.get(pj + 1)) else {
return false;
};
let v = v0 + (v1 - v0) * j as f64 / 3.0;
for pi in 0..pc {
let (Some(&u0), Some(&u1)) = (m.us.get(pi), m.us.get(pi + 1)) else {
return false;
};
for i in 0..4 {
let u = u0 + (u1 - u0) * i as f64 / 3.0;
let expected = self.box_point(u, v);
let Some(&actual) = m.points.get((3 * pj + j) * nx + 3 * pi + i) else {
return false;
};
if !point_fits(expected, actual) {
return false;
}
}
}
true
}
fn box_point(&self, s: f64, t: f64) -> [f64; 2] {
let b = self.bounds;
[b[0] + s * (b[2] - b[0]), b[1] + t * (b[3] - b[1])]
+271 -53
View File
@@ -53,28 +53,48 @@ pub fn classify(c: char) -> Option<CjkChar> {
})
}
/// Script order for a locale tag such as `ja_JP.UTF-8`, `zh-Hant-TW`, `zh_CN` or `ko-KR`.
/// Non-CJK (or unknown) locales get Simplified Chinese first, so Japanese forms only win
/// for shared Han when the locale is Japanese.
pub fn script_order(locale: Option<&str>) -> [CjkScript; 4] {
/// A locale tag reduced to what [`script_order`] and [`locale_script`] compare:
/// lowercase, `_` as `-`, without an encoding or modifier suffix.
fn normalized_locale(locale: Option<&str>) -> String {
locale.unwrap_or("").split(['.', '@']).next().unwrap_or("").to_ascii_lowercase().replace('_', "-")
}
/// The CJK script a locale explicitly asks for, or `None` for a non-CJK (or unknown) locale.
///
/// [`script_order`] also gives non-CJK locales a default order (Simplified Chinese first). The
/// craft-font manifest, however, lists its Japanese faces before Noto Sans CJK SC, so the eager
/// provider keeps that Japanese-first baseline for Han unless the user's locale names another
/// script. This helper distinguishes a non-CJK/unknown effective locale (use the baseline
/// manifest order) from "zh-Hans/zh-Hant/ja/ko, use this script".
pub fn locale_script(locale: Option<&str>) -> Option<CjkScript> {
use CjkScript::*;
let tag = locale.unwrap_or("").split(['.', '@']).next().unwrap_or("").to_ascii_lowercase().replace('_', "-");
let tag = normalized_locale(locale);
let mut parts = tag.split('-');
let lang = parts.next().unwrap_or("");
let rest: Vec<&str> = parts.collect();
match lang {
"ja" => [Japanese, SimplifiedChinese, TraditionalChinese, Korean],
"ko" => [Korean, TraditionalChinese, SimplifiedChinese, Japanese],
"ja" => Some(Japanese),
"ko" => Some(Korean),
"zh" | "yue" => {
let hant = rest.iter().any(|p| matches!(*p, "hant" | "tw" | "hk" | "mo"));
let hans = rest.iter().any(|p| matches!(*p, "hans" | "cn" | "sg"));
if (hant || lang == "yue") && !hans {
[TraditionalChinese, SimplifiedChinese, Japanese, Korean]
} else {
[SimplifiedChinese, TraditionalChinese, Japanese, Korean]
}
if (hant || lang == "yue") && !hans { Some(TraditionalChinese) } else { Some(SimplifiedChinese) }
}
_ => [SimplifiedChinese, TraditionalChinese, Japanese, Korean],
_ => None,
}
}
/// Script order for a locale tag such as `ja_JP.UTF-8`, `zh-Hant-TW`, `zh_CN` or `ko-KR`.
/// Non-CJK (or unknown) locales get Simplified Chinese first for system fonts, so Japanese
/// forms only win for shared Han when the locale is Japanese (craft faces keep the manifest's
/// Japanese-first order through [`locale_script`]).
pub fn script_order(locale: Option<&str>) -> [CjkScript; 4] {
use CjkScript::*;
match locale_script(locale) {
Some(Japanese) => [Japanese, SimplifiedChinese, TraditionalChinese, Korean],
Some(Korean) => [Korean, TraditionalChinese, SimplifiedChinese, Japanese],
Some(TraditionalChinese) => [TraditionalChinese, SimplifiedChinese, Japanese, Korean],
Some(SimplifiedChinese) | None => [SimplifiedChinese, TraditionalChinese, Japanese, Korean],
}
}
@@ -330,7 +350,10 @@ fn fontconfig_match(script: CjkScript) -> Option<FontFile> {
fn fontconfig_font_covers_sample(bytes: &[u8], family: &str, script: CjkScript) -> bool {
use skrifa::MetadataProvider;
let index = face_index_for_family(bytes, family);
let Some(index) = face_index_for_family_checked(bytes, family) else { return false };
if !font_face_is_readable(bytes, index) {
return false;
}
let Ok(font) = skrifa::FontRef::from_index(bytes, index) else { return false };
let sample = match script {
CjkScript::Japanese => "レイヤー図",
@@ -509,51 +532,121 @@ pub fn mac_pingfang() -> Option<std::path::PathBuf> {
None
}
/// Maximum collection faces and cumulative `name` records inspected by [`face_index_for_family`].
/// Maximum collection faces and cumulative `name` records inspected by
/// [`face_index_for_family_checked`].
const MAX_COLLECTION_FACES: usize = 256;
const MAX_NAME_RECORDS: usize = 8192;
/// Face index in a font file (or collection) whose family name is `family`; 0 when `family` is
/// empty or no face matches. Never panics on malformed data.
pub fn face_index_for_family(bytes: &[u8], family: &str) -> u32 {
use skrifa::{
MetadataProvider,
raw::{FileRef, types::Tag},
string::StringId,
};
if family.is_empty() {
return 0;
}
let Ok(FileRef::Collection(c)) = FileRef::new(bytes) else { return 0 };
let mut seen_faces = std::collections::HashSet::new();
let mut seen_names = std::collections::HashSet::new();
let mut budget = MAX_NAME_RECORDS;
for (i, f) in c.iter().take(MAX_COLLECTION_FACES).enumerate() {
if let Some(off_bytes) = bytes.get(12 + i * 4..12 + (i + 1) * 4)
&& let Ok(arr) = <[u8; 4]>::try_from(off_bytes)
&& !seen_faces.insert(u32::from_be_bytes(arr))
{
continue;
}
let Ok(f) = f else { continue };
if let Some(rec) = f.table_directory.table_records().iter().find(|r| r.tag() == Tag::new(b"name"))
&& !seen_names.insert((rec.offset(), rec.length()))
{
continue;
}
for id in [StringId::TYPOGRAPHIC_FAMILY_NAME, StringId::FAMILY_NAME] {
for s in f.localized_strings(id) {
let Some(rem) = budget.checked_sub(1) else {
return 0;
};
budget = rem;
if s.chars().eq(family.chars()) {
return i as u32;
}
/// Whether `font` has a family record exactly equal to `family`, charging each inspected record
/// to `budget` so malformed fonts cannot make this scan unbounded.
fn family_name_matches(font: &skrifa::FontRef<'_>, family: &str, budget: &mut usize) -> bool {
use skrifa::{MetadataProvider, string::StringId};
for id in [StringId::TYPOGRAPHIC_FAMILY_NAME, StringId::FAMILY_NAME] {
for s in font.localized_strings(id) {
let Some(rem) = budget.checked_sub(1) else {
return false;
};
*budget = rem;
if s.chars().eq(family.chars()) {
return true;
}
}
}
0
false
}
/// Whether every table in the selected face of `bytes` really is present in the file.
///
/// `FontRef` reads tables lazily: a face whose `cmap` and `name` are valid can still point another
/// table outside the file. Coverage checks only read `cmap`, so callers that register a selected
/// collection face (by family index, coverage result or face 0) must check this first; epaint
/// panics when it installs a configured face the parser cannot read.
fn face_tables_are_readable(font: &skrifa::raw::FontRef<'_>) -> bool {
let directory = font.table_directory();
let records = directory.table_records();
!records.is_empty() && records.len() == usize::from(directory.num_tables()) && records.iter().all(|record| font.table_data(record.tag()).is_some())
}
/// Whether face `index` of a font file or collection has a complete, in-bounds table directory.
///
/// This is the selected-index counterpart of [`font_file_is_readable`]. A readable collection may
/// still contain a malformed face at `index`; the face's `cmap` and `name` can work while another
/// table points outside the file. Returns `false` for an out-of-range index or malformed data.
/// Never panics.
pub fn font_face_is_readable(bytes: &[u8], index: u32) -> bool {
skrifa::raw::FontRef::from_index(bytes, index).is_ok_and(|font| face_tables_are_readable(&font))
}
/// Whether `bytes` is a font file or font collection that the text engine's parser can read.
///
/// This uses the same `skrifa` parser the text engine lays out and rasterizes with, instead of a
/// hand-written table-directory check with invented face/table caps. A readable non-font or
/// truncated file returns `false`; valid SFNT, OTF and TTC data returns `true`. For a collection,
/// at least one face must have a complete table directory. That does **not** make every face
/// readable: a face selected by family name, coverage or the empty-family face-0 contract must be
/// checked with [`font_face_is_readable`], because its `cmap` and `name` can work while another
/// table points out of bounds.
pub fn font_file_is_readable(bytes: &[u8]) -> bool {
use skrifa::raw::FileRef;
match FileRef::new(bytes) {
Ok(FileRef::Font(font)) => face_tables_are_readable(&font),
Ok(FileRef::Collection(faces)) => faces.iter().any(|face| face.is_ok_and(|font| face_tables_are_readable(&font))),
Err(_) => false,
}
}
/// Face index in a font file (or collection) whose family name is `family`.
///
/// An empty `family` is the explicit "face 0" contract. A single-face file must actually carry
/// the requested family name; a collection must contain a face with it. `None` when the family is
/// missing, the data is malformed or the name budget is exhausted. The returned index has a
/// matching `name`, but its other tables are not validated: use [`font_face_is_readable`] before
/// registering it. Never panics.
pub fn face_index_for_family_checked(bytes: &[u8], family: &str) -> Option<u32> {
use skrifa::raw::{FileRef, types::Tag};
if family.is_empty() {
return Some(0);
}
let mut budget = MAX_NAME_RECORDS;
match FileRef::new(bytes).ok()? {
FileRef::Font(font) => family_name_matches(&font, family, &mut budget).then_some(0),
FileRef::Collection(c) => {
let mut seen_faces = std::collections::HashSet::new();
let mut seen_names = std::collections::HashSet::new();
for (i, f) in c.iter().take(MAX_COLLECTION_FACES).enumerate() {
if let Some(off_bytes) = bytes.get(12 + i * 4..12 + (i + 1) * 4)
&& let Ok(arr) = <[u8; 4]>::try_from(off_bytes)
&& !seen_faces.insert(u32::from_be_bytes(arr))
{
continue;
}
let Ok(f) = f else { continue };
if let Some(rec) = f.table_directory.table_records().iter().find(|r| r.tag() == Tag::new(b"name"))
&& !seen_names.insert((rec.offset(), rec.length()))
{
continue;
}
if family_name_matches(&f, family, &mut budget) {
return u32::try_from(i).ok();
}
if budget == 0 {
return None;
}
}
None
}
}
}
/// Face index in a font file (or collection) whose family name is `family`; 0 when `family` is
/// empty or no face matches. Kept for callers that prefer the historical face-0 fallback; new
/// system-font selection should use [`face_index_for_family_checked`], verify the selected face
/// with [`font_face_is_readable`], and then verify coverage. Never panics on malformed data.
pub fn face_index_for_family(bytes: &[u8], family: &str) -> u32 {
face_index_for_family_checked(bytes, family).unwrap_or(0)
}
#[cfg(test)]
@@ -561,6 +654,19 @@ mod tests {
use super::*;
use CjkScript::*;
#[test]
fn explicit_locale_scripts_are_distinct_from_the_non_cjk_default() {
assert_eq!(locale_script(Some("ja_JP.UTF-8")), Some(Japanese));
assert_eq!(locale_script(Some("ko-KR")), Some(Korean));
assert_eq!(locale_script(Some("zh-Hans-CN")), Some(SimplifiedChinese));
assert_eq!(locale_script(Some("zh_CN")), Some(SimplifiedChinese));
assert_eq!(locale_script(Some("zh-Hant-TW")), Some(TraditionalChinese));
assert_eq!(locale_script(Some("yue-HK")), Some(TraditionalChinese));
for unknown in [None, Some(""), Some("en_US.UTF-8"), Some("C"), Some("de"), Some("!!@@")] {
assert_eq!(locale_script(unknown), None, "{unknown:?}");
}
}
#[test]
fn locale_orders() {
assert_eq!(script_order(Some("ja_JP.UTF-8"))[0], Japanese);
@@ -656,6 +762,118 @@ mod tests {
}
}
/// A two-face TrueType collection built at runtime from the repository's OFL-licensed
/// Inter and JetBrains Mono files. Each face directory is rewritten with offsets relative to
/// the collection, so no font fixture is committed.
fn two_face_ttc(first: &[u8], second: &[u8]) -> Vec<u8> {
let font_count = 2usize;
let tables = |font: &[u8]| u16::from_be_bytes([font[4], font[5]]) as usize;
let dir_lengths = [12 + 16 * tables(first), 12 + 16 * tables(second)];
let mut dir_offsets = Vec::with_capacity(font_count);
let mut cursor = 12 + 4 * font_count;
for length in dir_lengths {
dir_offsets.push(cursor);
cursor += length;
}
let data_start = cursor.next_multiple_of(4);
let mut bases = Vec::with_capacity(font_count);
let mut total = data_start;
for font in [first, second] {
bases.push(total);
total += font.len().next_multiple_of(4);
}
let mut out = vec![0u8; total];
out[..4].copy_from_slice(b"ttcf");
out[4..8].copy_from_slice(&0x0001_0000u32.to_be_bytes());
out[8..12].copy_from_slice(&u32::try_from(font_count).expect("two faces").to_be_bytes());
for (i, offset) in dir_offsets.iter().enumerate() {
let at = 12 + i * 4;
out[at..at + 4].copy_from_slice(&u32::try_from(*offset).expect("collection fits").to_be_bytes());
}
for (i, font) in [first, second].into_iter().enumerate() {
let dir = dir_offsets[i];
let base = bases[i];
out[dir..dir + font.len().min(12)].copy_from_slice(&font[..font.len().min(12)]);
for record in 0..tables(font) {
let src = 12 + 16 * record;
let dst = dir + 12 + 16 * record;
out[dst..dst + 8].copy_from_slice(&font[src..src + 8]);
let table_offset = u32::from_be_bytes(font[src + 8..src + 12].try_into().expect("four bytes"));
let collection_offset = u32::try_from(base).expect("collection fits") + table_offset;
out[dst + 8..dst + 12].copy_from_slice(&collection_offset.to_be_bytes());
out[dst + 12..dst + 16].copy_from_slice(&font[src + 12..src + 16]);
}
out[base..base + font.len()].copy_from_slice(font);
}
out
}
#[test]
fn checked_face_lookup_uses_the_requested_collection_family_and_exact_coverage() {
use crate::scripts::face_covers;
let inter = include_bytes!("../../../assets/fonts/Inter-Regular.ttf");
let jetbrains = include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf");
let ttc = two_face_ttc(inter, jetbrains);
assert_eq!(face_index_for_family_checked(&ttc, "Inter"), Some(0));
assert_eq!(face_index_for_family_checked(&ttc, "JetBrains Mono"), Some(1));
assert_eq!(face_index_for_family_checked(&ttc, "Noto Sans CJK TC"), None);
assert_eq!(face_index_for_family(&ttc, "JetBrains Mono"), 1, "the old wrapper keeps its face-0 fallback only on a miss");
assert_eq!(face_index_for_family_checked(inter, "Inter"), Some(0));
assert_eq!(face_index_for_family_checked(inter, "JetBrains Mono"), None, "a single-face file must carry the requested family");
assert_eq!(face_index_for_family_checked(inter, ""), Some(0), "empty family is the explicit face-0 contract");
assert_eq!(face_index_for_family_checked(b"", "Inter"), None);
// Both faces cover A. JetBrains Mono does not cover Latin Small Letter B with Stroke,
// while Inter does, so a first-covering-face lookup cannot satisfy this pair.
assert!(face_covers(&ttc, 0, 'A'));
assert!(face_covers(&ttc, 1, 'A'));
assert!(face_covers(&ttc, 0, 'ƀ'));
assert!(!face_covers(&ttc, 1, 'ƀ'));
assert!(!face_covers(&ttc, 1, '日'));
assert!(!face_covers(&ttc, 2, 'A'), "out-of-range face index");
}
#[test]
fn font_file_validation_uses_the_layout_parser() {
let inter = include_bytes!("../../../assets/fonts/Inter-Regular.ttf");
let jetbrains = include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf");
assert!(font_file_is_readable(inter));
assert!(font_file_is_readable(&two_face_ttc(inter, jetbrains)));
assert!(!font_file_is_readable(b"this is not a font"));
assert!(!font_file_is_readable(&inter[..20]));
let mut missing_table = inter.to_vec();
// The first directory record begins at 12; its offset occupies bytes 20..24.
missing_table[20..24].copy_from_slice(&u32::MAX.to_be_bytes());
assert!(!font_file_is_readable(&missing_table), "a complete directory cannot point outside the file");
}
/// A readable collection can contain a malformed non-selected face, so the file-level check
/// must not stand in for validating the face a caller selects. The selected face keeps a valid
/// `cmap` (coverage succeeds) and `name` (family lookup succeeds) while another table points
/// past the end of the file.
#[test]
fn selected_face_validation_rejects_a_malformed_face_in_a_readable_collection() {
use crate::scripts::face_covers;
let inter = include_bytes!("../../../assets/fonts/Inter-Regular.ttf");
let jetbrains = include_bytes!("../../../assets/fonts/JetBrainsMono-Regular.ttf");
let mut malformed = jetbrains.to_vec();
let tables = u16::from_be_bytes([malformed[4], malformed[5]]) as usize;
let glyf = (0..tables).map(|i| 12 + 16 * i).find(|&rec| malformed.get(rec..rec + 4) == Some(&b"glyf"[..])).expect("JetBrains Mono has a glyf table");
malformed[glyf + 12..glyf + 16].copy_from_slice(&u32::MAX.to_be_bytes());
let ttc = two_face_ttc(inter, &malformed);
assert!(font_file_is_readable(&ttc), "face 0 remains a readable face");
assert_eq!(face_index_for_family_checked(&ttc, "JetBrains Mono"), Some(1), "the malformed face's name still resolves");
assert!(face_covers(&ttc, 1, 'A'), "the malformed face's cmap still covers A");
assert!(!font_face_is_readable(&ttc, 1), "its glyf table lies outside the collection");
assert!(font_face_is_readable(&ttc, 0), "positive control: the good face stays readable");
assert!(!font_face_is_readable(&ttc, 2), "out-of-range face");
assert!(font_face_is_readable(&two_face_ttc(inter, jetbrains), 1), "positive control: a valid selected face passes");
}
#[test]
fn face_index_handles_bad_data() {
assert_eq!(face_index_for_family(b"", "PingFang SC"), 0);
+13
View File
@@ -280,6 +280,15 @@ pub fn covering_face(bytes: &[u8], c: char) -> Option<u32> {
}
}
/// Whether face `index` of `bytes` (a font or collection) maps `c` in its character map.
/// `false` for an out-of-range face or data that doesn't parse. Never panics.
pub fn face_covers(bytes: &[u8], index: u32, c: char) -> bool {
use skrifa::MetadataProvider;
let Ok(font) = skrifa::FontRef::from_index(bytes, index) else { return false };
font.charmap().map(c).is_some()
}
#[cfg(test)]
mod tests {
use super::*;
@@ -351,6 +360,10 @@ mod tests {
for bad in [&b""[..], b"ttcf", b"ttcf\0\x01\0\0\0\0\0\x02\xff\xff\xff\xff\0\0\0\x10", b"\0\x01\0\0\0\xff"] {
assert_eq!(covering_face(bad, 'A'), None);
}
assert!(face_covers(inter, 0, 'A'));
assert!(!face_covers(inter, 0, 'ส'));
assert!(!face_covers(inter, 1, 'A'), "a single-face file has no face 1");
assert!(!face_covers(b"", 0, 'A'));
}
/// With the real system fonts, each script that has a candidate installed has one that
+27 -7
View File
@@ -145,25 +145,26 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {
edit = Some(json!({"layer": layer.id.0, "preset": preset}));
}
});
// The visible label and the accessible name differ for X and Y ("X" alone does not say
// position), so the name comes from the call site.
// W/H use a short visible label but the full word as the accessible name (a screen reader
// says "Width", not "W"); X/Y already name their axis, so their name comes from the call site
// too.
let num = |ui: &mut egui::Ui, label: &str, name: &str, v: &mut f32, range: std::ops::RangeInclusive<f32>| -> bool {
ui.label(egui::RichText::new(tl!(&label)).color(t.text_dim).size(12.0));
crate::widgets::value_field(ui, v, range, "px", 64.0).accessible_name(tl!(name)).changed()
crate::widgets::value_field(ui, v, range, "px", 64.0).accessible_name(name).changed()
};
let r = a.rect;
ui.horizontal(|ui| {
let (mut w, mut h) = (r.width() as f32, r.height() as f32);
let cw = num(ui, "W", "Width", &mut w, 1.0..=300_000.0);
let ch = num(ui, "H", "Height", &mut h, 1.0..=300_000.0);
let cw = num(ui, "W", tl!("Width"), &mut w, 1.0..=300_000.0);
let ch = num(ui, "H", tl!("Height"), &mut h, 1.0..=300_000.0);
if cw || ch {
edit = Some(json!({"layer": layer.id.0, "width": w.round(), "height": h.round(), "coalesce": key("wh")}));
}
});
ui.horizontal(|ui| {
let (mut x, mut y) = (r.x0 as f32, r.y0 as f32);
let cx = num(ui, "X", "X", &mut x, -300_000.0..=300_000.0);
let cy = num(ui, "Y", "Y", &mut y, -300_000.0..=300_000.0);
let cx = num(ui, "X", tl!("X"), &mut x, -300_000.0..=300_000.0);
let cy = num(ui, "Y", tl!("Y"), &mut y, -300_000.0..=300_000.0);
if cx || cy {
edit = Some(json!({"layer": layer.id.0, "x": x.round(), "y": y.round(), "coalesce": key("xy")}));
}
@@ -446,4 +447,23 @@ mod tests {
app.ui.layer_comp_selected = Some(999);
assert_eq!(crate::comps_ui::target(&app), Some(b));
}
#[test]
fn property_fields_are_named_for_their_axis() {
use egui::accesskit::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
let (mut app, _) = app();
app.run("layer.new.artboard", json!({"rect": [0, 0, 40, 50]})).unwrap();
let id = app.session.active().unwrap().doc.artboards()[0].0;
let layer = app.session.active().unwrap().doc.layer(id).unwrap().clone();
let mut h = Harness::builder()
.with_size(egui::vec2(520.0, 420.0))
.with_context_setup(|ctx| PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ALL[0]))
.build_ui_state(move |ui, app: &mut PhotocraftApp| properties(app, ui, &layer), app);
h.run_steps(2);
let labels: Vec<String> = h.query_all_by_role(Role::SpinButton).filter_map(|n| n.accesskit_node().label()).collect();
assert_eq!(labels, ["Width", "Height", "X", "Y"].map(String::from).to_vec(), "the fields announce their own axis in layout order");
}
}
+81 -33
View File
@@ -16,6 +16,8 @@
//! uploads those blocks instead of compositing every layer again.
use std::collections::VecDeque;
#[cfg(test)]
use std::sync::atomic::AtomicU64;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, SyncSender, TryRecvError};
use std::sync::{Arc, Weak};
@@ -43,6 +45,55 @@ const KEEP: usize = 2;
/// [`GpuCanvas::refresh`] kind of a redraw served from a [`Kept`] composite.
pub(crate) const KEPT: &str = "kept";
/// Tests hold the redraw worker before it draws a batch, so an edit lands while blocks are still
/// to come. A real run never waits: a fast machine draws a test document before its next frame,
/// leaving nothing drawn "before" the edit.
#[cfg(test)]
static HOLD: AtomicBool = AtomicBool::new(false);
/// Identity of the next spawned redraw worker: lets a test tell the worker it watched from a
/// replacement that [`restart`] spawns after an edit.
#[cfg(test)]
static NEXT_WORKER_GENERATION: AtomicU64 = AtomicU64::new(1);
/// Hold the redraw worker until the guard drops.
#[cfg(test)]
pub(crate) fn hold_redraws() -> HoldRedraws {
HOLD.store(true, Ordering::SeqCst);
HoldRedraws
}
/// Wait until worker `generation` of document `doc`'s [`Redraw`] has reached its pre-batch
/// [`HOLD`]. A replacement worker has another generation, so an edit only lands while the worker
/// the test watched still has its blocks to draw. Returns `false` after `timeout`.
#[cfg(test)]
pub(crate) fn wait_for_held_redraw(app: &PhotocraftApp, doc: DocId, generation: u64, timeout: std::time::Duration) -> bool {
let deadline = std::time::Instant::now() + timeout;
loop {
if let Some(r) = app.redraws.get(&doc)
&& r.worker_generation == generation
&& r.reached_hold.load(Ordering::SeqCst)
{
return true;
}
if std::time::Instant::now() >= deadline {
return false;
}
std::thread::sleep(std::time::Duration::from_millis(1));
}
}
/// Releases [`hold_redraws`], including while a test unwinds.
#[cfg(test)]
pub(crate) struct HoldRedraws;
#[cfg(test)]
impl Drop for HoldRedraws {
fn drop(&mut self) {
HOLD.store(false, Ordering::SeqCst);
}
}
/// One finished block, as texels of the canvas texture.
struct Piece {
block: usize,
@@ -70,6 +121,11 @@ pub(crate) struct Redraw {
collected_bytes: u64,
/// Bytes the kept composites may hold: what Memory Usage leaves beside the document.
cap: u64,
/// Set when this worker first reaches the test [`HOLD`], and this worker's generation.
#[cfg(test)]
reached_hold: Arc<AtomicBool>,
#[cfg(test)]
worker_generation: u64,
}
impl Redraw {
@@ -423,11 +479,22 @@ fn spawn(app: &mut PhotocraftApp, ctx: &egui::Context, s: Spawn) {
let left = todo.len();
let (tx, rx) = std::sync::mpsc::sync_channel(BATCH);
let stop = Arc::new(AtomicBool::new(false));
#[cfg(test)]
let reached_hold = Arc::new(AtomicBool::new(false));
#[cfg(test)]
let worker_generation = NEXT_WORKER_GENERATION.fetch_add(1, Ordering::SeqCst);
#[cfg(test)]
let worker_hold = reached_hold.clone();
let work = (blocks.clone(), stop.clone(), ctx.clone());
let spawned = std::thread::Builder::new().name("canvas-redraw".into()).spawn(move || {
let (blocks, stop, ctx) = work;
// A panic stops the redraw: the receiver sees the worker gone and drops it.
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| draw(&doc, display.as_deref(), format, &blocks, &todo, &stop, &tx, &ctx)));
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
#[cfg(test)]
draw(&doc, display.as_deref(), format, &blocks, &todo, &stop, &tx, &ctx, &worker_hold);
#[cfg(not(test))]
draw(&doc, display.as_deref(), format, &blocks, &todo, &stop, &tx, &ctx);
}));
ctx.request_repaint();
});
if let Err(e) = spawned {
@@ -452,40 +519,14 @@ fn spawn(app: &mut PhotocraftApp, ctx: &egui::Context, s: Spawn) {
collected,
collected_bytes,
cap,
#[cfg(test)]
reached_hold,
#[cfg(test)]
worker_generation,
},
);
}
/// A test can hold the worker after a batch: a real worker's speed is not reproducible, and the
/// edit-during-a-redraw test needs the redraw to be certainly still running.
#[cfg(test)]
pub(crate) mod test_hold {
use std::sync::atomic::{AtomicBool, Ordering};
static HELD: AtomicBool = AtomicBool::new(false);
/// Holds every redraw worker after its next batch until this guard drops.
pub(crate) struct Hold;
pub(crate) fn hold() -> Hold {
HELD.store(true, Ordering::SeqCst);
Hold
}
impl Drop for Hold {
fn drop(&mut self) {
HELD.store(false, Ordering::SeqCst);
}
}
/// Called by the worker between batches while a test holds it.
pub(crate) fn wait() {
while HELD.load(Ordering::SeqCst) {
std::thread::sleep(std::time::Duration::from_millis(2));
}
}
}
/// The worker: composite `todo`'s blocks of `doc` in batches and hand each over, until done or
/// stopped.
#[allow(clippy::too_many_arguments)]
@@ -498,8 +539,17 @@ fn draw(
stop: &AtomicBool,
tx: &SyncSender<Piece>,
ctx: &egui::Context,
#[cfg(test)] reached_hold: &AtomicBool,
) {
for batch in todo.chunks(BATCH) {
// A test may hold the worker here; a cancelled redraw must still exit, not wait for release.
#[cfg(test)]
while HOLD.load(Ordering::SeqCst) && !stop.load(Ordering::Relaxed) {
// This worker, identified by its own acknowledgement, reached the hold: a replacement
// spawned after the edit starts with another one and can't satisfy the test's wait.
reached_hold.store(true, Ordering::SeqCst);
std::thread::sleep(std::time::Duration::from_millis(1));
}
if stop.load(Ordering::Relaxed) {
return;
}
@@ -517,8 +567,6 @@ fn draw(
}
ctx.request_repaint();
}
#[cfg(test)]
test_hold::wait();
}
}
+18 -7
View File
@@ -210,13 +210,20 @@ fn a_full_cpu_refresh_draws_in_the_background_with_the_synchronous_pixels() {
fn an_edit_during_a_redraw_is_not_overwritten_by_blocks_drawn_before_it() {
let _gpu = photocraft_testkit::gpu_lock();
let Some(mut g) = gpu_app() else { return };
// Hold the worker after its first batch: how fast it composites is not reproducible (a fast
// machine finished all 4×3 blocks before the edit's frame on FreeBSD), and the test needs the
// redraw to still be running when the edit lands. The hold is released before `settle`.
let hold = test_hold::hold();
// Hold the worker before its first batch and wait until this very worker acknowledges that
// hold: when the fill lands, all 12 blocks of this 4×3 document are still to draw by it.
// Without the hold a fast machine finishes them before the next frame, so the edit never
// races the worker and this test only checked a completed redraw; without the per-worker
// acknowledgement an edit could beat the worker to the hold, and its restarted replacement
// would satisfy the checks.
let held = hold_redraws();
let doc = cpu_only_document(g.harness.state_mut(), 4096, 3072);
g.harness.step();
assert!(g.harness.state().redraws.contains_key(&doc));
let generation = g.harness.state().redraws.get(&doc).expect("the frame started a redraw").worker_generation;
assert!(
wait_for_held_redraw(g.harness.state(), doc, generation, std::time::Duration::from_secs(10)),
"the redraw worker never reached the pre-batch hold; an edit would race an unstarted redraw"
);
// A corner, drawn last (farthest from the view's centre), changes on a layer of its own while
// the redraw runs: a small edit, drawn at once.
g.harness.state_mut().run("layer.new.layer", json!({})).expect("layer");
@@ -226,8 +233,12 @@ fn an_edit_during_a_redraw_is_not_overwritten_by_blocks_drawn_before_it() {
g.harness.state_mut().run("edit.fill", json!({"color": "#22ee22"})).expect("fill");
g.harness.step();
assert_eq!(g.harness.state().perf.last_refresh, "rect", "the fill's damage was drawn synchronously");
assert!(g.harness.state().redraws.contains_key(&doc), "the redraw goes on");
drop(hold);
// Still running with blocks to draw, and drawing the edited document, not the state before it.
let current = g.harness.state().session.active().expect("document").doc.clone();
let r = g.harness.state().redraws.get(&doc).expect("the redraw goes on");
assert!(r.pending.iter().any(|p| *p), "blocks are still to draw");
assert!(Arc::ptr_eq(&r.doc, &current) || *r.doc == *current, "the blocks left draw the edit");
drop(held);
settle(&mut g);
assert_matches_synchronous(&mut g, doc);
}
+25
View File
@@ -1647,6 +1647,31 @@ mod tests {
app.distort.caf.as_ref().unwrap()
}
#[test]
fn settings_dropdowns_are_named_for_their_visible_labels() {
use egui::accesskit::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
let mut app = app_with_selection();
open(&mut app).unwrap();
let mut h = Harness::builder()
.with_size(egui::vec2(1000.0, 900.0))
.with_context_setup(|ctx| PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ALL[0]))
.build_ui_state(|ui, app: &mut PhotocraftApp| show(app, ui.ctx()), app);
h.run_steps(2);
// The Indicates dropdown lives inside a collapsed "Sampling Area Overlay" header.
h.get_by_role_and_label(Role::DisclosureTriangle, "Sampling Area Overlay").click();
h.run_steps(3);
let labels: Vec<String> = h.query_all_by_role(Role::ComboBox).filter_map(|n| n.accesskit_node().label()).collect();
for label in ["Indicates", "Color Adaptation", "Rotation Adaptation", "Output To"] {
assert!(labels.iter().any(|have| have == label), "{label} names its dropdown: {labels:?}");
}
for wrong in ["Contents:", "Color", "Rotation", "Source"] {
assert!(!labels.iter().any(|have| have == wrong), "{wrong} names no control here: {labels:?}");
}
}
/// Photoshop opens the workspace with the Sampling Brush subtracting at a tenth of the
/// window's side, Auto sampling, output to a new layer.
#[test]
+40 -28
View File
@@ -29,6 +29,9 @@ struct Running {
key: String,
ctx: JobCtx,
rx: Receiver<photocraft_engine::Result<Document>>,
/// Test-only notification sent after this worker publishes its real result.
#[cfg(test)]
finished: Receiver<()>,
/// The full-resolution job that follows a coarse one.
refine: Option<ContentAwarePreview>,
/// This job refines a coarse preview already shown: its failure leaves that one shown.
@@ -179,13 +182,25 @@ fn spawn(job: ContentAwarePreview, key: String, refining: bool) -> Option<Runnin
let ctx = JobCtx::new();
let (tx, rx) = std::sync::mpsc::channel();
let worker = ctx.clone();
#[cfg(test)]
let (finished_tx, finished) = std::sync::mpsc::channel();
std::thread::Builder::new()
.name("cam-preview".into())
.spawn(move || {
let _ = tx.send(job.run(&worker).map(|(d, _)| d));
#[cfg(test)]
let _ = finished_tx.send(());
})
.ok()?;
Some(Running { key, ctx, rx, refine, refining })
Some(Running {
key,
ctx,
rx,
#[cfg(test)]
finished,
refine,
refining,
})
}
/// Keep frames coming while a preview waits out its debounce or computes.
@@ -233,16 +248,8 @@ mod tests {
assert!(step(&mut app, 1000.0 + DEBOUNCE_MS / 2.0).is_none() && app.cam_preview.as_ref().unwrap().running.is_none());
// At rest: the job runs, off this thread, and its result shows once it arrives.
let mut now = 1000.0 + DEBOUNCE_MS;
let mut shown = step(&mut app, now);
for _ in 0..600 {
if shown.is_some() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
now += 10.0;
shown = step(&mut app, now);
}
let (preview, key) = shown.expect("a preview once the pointer rested");
assert!(step(&mut app, now).is_none() && app.cam_preview.as_ref().is_some_and(|p| p.running.is_some()), "the preview job starts off this thread");
let (preview, key) = wait_for(&mut app, &mut now, 0).expect("a preview once the pointer rested");
assert!(key > BASE && showing(&app));
assert!(blue(&preview, 72, 30) && !blue(&preview, 22, 30), "the preview shows the move");
let doc = app.session.active().unwrap().doc.clone();
@@ -270,32 +277,37 @@ mod tests {
tool_event(&mut app, ToolEvent::Move { x: 72.0, y: 30.0, pressure: 1.0 }, m);
tool_event(&mut app, ToolEvent::Up { x: 72.0, y: 30.0 }, m);
assert!(crate::cam_transform::active(&app));
let (mut now, mut shown) = (0.0, step(&mut app, 0.0));
for _ in 0..800 {
if shown.is_some() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
now += 10.0;
shown = step(&mut app, now);
}
let (preview, _) = shown.expect("the box shows the result");
let mut now = 0.0;
let (preview, _) = wait_for(&mut app, &mut now, 0).expect("the box shows the result");
assert!(blue(&preview, 72, 30) && !blue(&preview, 22, 30));
// Cancelling the box drops the preview.
crate::cam_transform::cancel(&mut app);
assert!(step(&mut app, now + 1.0).is_none() && app.cam_preview.is_none());
}
/// Step until the canvas shows a preview with a key past `after`, or give up after a while.
/// Wait for the specific worker to publish its result, then let the normal non-blocking
/// `step` path consume it. Coverage instrumentation can make a solve much slower than a
/// fixed polling loop; the watchdog bounds a stuck worker without setting its expected speed.
fn wait_for(app: &mut PhotocraftApp, now: &mut f64, after: u64) -> Option<(Arc<Document>, u64)> {
for _ in 0..6000 {
if let Some(shown) = step(app, *now).filter(|s| s.1 > after) {
return Some(shown);
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(300);
loop {
let shown = step(app, *now);
if shown.as_ref().is_some_and(|s| s.1 > after) {
return shown;
}
let p = app.cam_preview.as_ref()?;
if let Some(running) = &p.running {
let remaining = deadline.checked_duration_since(std::time::Instant::now())?;
running.finished.recv_timeout(remaining).ok()?;
} else if shown.is_some() || p.failed.as_deref() == Some(p.key.as_str()) {
return None;
} else if *now < p.since + DEBOUNCE_MS {
// Advance the simulated debounce clock without sleeping in real time.
*now = p.since + DEBOUNCE_MS;
} else {
return None;
}
std::thread::sleep(std::time::Duration::from_millis(10));
*now += 10.0;
}
None
}
#[test]
@@ -145,6 +145,30 @@ fn dialog_body_renders_for_alpha_spot_and_quick_mask() {
}
}
#[test]
fn value_fields_are_named_for_the_visible_solidity_or_opacity_caption() {
use egui::accesskit::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
let labels = |f: Map<String, Value>, body: fn(&mut egui::Ui, &mut Map<String, Value>)| -> Vec<String> {
let mut h = Harness::builder()
.with_size(egui::vec2(520.0, 300.0))
.with_context_setup(|ctx| crate::PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ALL[0]))
.build_ui_state(&body, f);
h.run_steps(2);
h.query_all_by_role(Role::SpinButton).filter_map(|n| n.accesskit_node().label()).collect()
};
let app = app();
let mut f = fields(&app, &json!(0)).unwrap();
f.insert("indicates".into(), json!("spot"));
assert_eq!(labels(f.clone(), body), ["Solidity:"]);
f.insert("indicates".into(), json!("masked"));
assert_eq!(labels(f, body), ["Opacity:"]);
assert_eq!(labels(new_spot_fields(&app).unwrap(), new_spot_body), ["Solidity:"]);
}
#[test]
fn new_spot_channel_dialog_creates_the_ink_from_the_selection_and_remembers_it() {
let mut app = app();
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -188,7 +188,7 @@ fn cjk_font_order_follows_the_selected_language() {
fn korean_glyphs_remain_available_after_repeated_language_switches() {
use photocraft_text::cjk::{self, CjkChar, CjkScript};
#[cfg(target_os = "linux")]
crate::cjk_fonts::wait_for_fontconfig_cjk_scan();
assert!(crate::cjk_fonts::wait_for_fontconfig_cjk_scan(), "Fontconfig CJK lookup did not finish within 10 seconds");
if !cjk::font_files(CjkScript::Korean).iter().any(|font| font.path.is_file()) {
eprintln!("skipping: no installed Korean font");
return;
+2 -2
View File
@@ -34,8 +34,6 @@ pub fn transform_params(layer: u64, b: [f64; 4], w: Option<f32>, h: Option<f32>,
Some(json!({"layer": layer, "rect": b, "quad": quad}))
}
/// A number field that reports a value once committed (drag released, Enter, focus lost). `label` is its own
/// label and the one stacked with it in the same column ("W" over "X"), which share a centre.
/// The smallest W/H change, in px, that counts as an edit. A pixel frame is whole pixels: under
/// half a pixel is noise. A shape's path is fractional and is scaled to exactly the typed size,
/// so anything past the field's own rounding (half its last shown decimal) is an edit: 400.25 px
@@ -48,6 +46,8 @@ fn edit_tolerance(layer: &Layer, u: LenUnit, extent: f64) -> f32 {
}
}
/// A number field that reports a value once committed (drag released, Enter, focus lost). `label` is its own
/// label and the one stacked with it in the same column ("W" over "X"), which share a centre.
/// `len` is the unit shown and its 100% extent (for percent); `name` is the field's accessible name.
// The explicit accessible name accompanies the existing numeric-field parameters.
#[expect(clippy::too_many_arguments)]
+22
View File
@@ -2763,6 +2763,28 @@ mod tests {
assert_eq!(h.state()["memoryUsageMb"], 50000);
}
#[test]
fn graphics_dropdowns_are_named_for_their_settings() {
use egui::accesskit::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
let obj = json!({"gpuBackend": "auto", "gpuAdapter": ""}).as_object().unwrap().clone();
let mut h = Harness::builder()
.with_size(vec2(700.0, 500.0))
.with_context_setup(|ctx| PhotocraftApp::setup_context(ctx, crate::theme::ThemeKind::ALL[0]))
.build_ui_state(|ui, obj| gpu_status_rows(ui, None, None, obj), obj);
h.run_steps(2);
h.get_by_label("Advanced").click();
h.run_steps(2);
let labels: Vec<String> = h.query_all_by_role(Role::ComboBox).filter_map(|n| n.accesskit_node().label()).collect();
assert!(labels.iter().any(|label| label == "GPU Backend"), "{labels:?}");
if cfg!(target_os = "linux") {
assert!(labels.iter().any(|label| label == "GPU adapter"), "{labels:?}");
}
assert!(!labels.iter().any(|label| label == "Graphics"), "the section title names neither control: {labels:?}");
}
#[test]
fn colour_preferences_take_a_typed_hex_value() {
// #668: the canvas colour (and every colour preference) showed its hex but couldn't take one.
+1
View File
@@ -202,6 +202,7 @@ pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>)
}
let mut linked = f.get("linkRadii").and_then(Value::as_bool).unwrap_or(true);
let mut changed = None;
// `radii` is [top-left, top-right, bottom-right, bottom-left].
ui.horizontal(|ui| {
label(ui, tl!("Radius:"));
ui.vertical(|ui| {
+24
View File
@@ -141,6 +141,30 @@ fn click_slop_scales_with_zoom() {
assert!(is_click([10.0, 10.0], &[], 0.0));
}
#[test]
fn radius_fields_are_named_for_their_corners() {
use egui::accesskit::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
let mut app = app();
let id = open(&mut app, Tool::Rectangle, [10.0, 20.0]).unwrap();
let fields = app.ui.dialog_mut(id).unwrap().fields.clone();
let mut h = Harness::builder().with_size(egui::vec2(520.0, 520.0)).build_ui_state(move |ui, fields| body(&app, ui, fields), fields);
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
h.run_steps(2);
let labels: Vec<String> = h.query_all_by_role(Role::SpinButton).filter_map(|n| n.accesskit_node().label()).collect();
// The visible rows are [top-left, top-right], [bottom-left, bottom-right]; the field for each
// radius index must carry its own corner name (a permutation would still pass a set check).
let corners: Vec<&str> = labels.iter().map(String::as_str).filter(|label| !matches!(*label, "Width:" | "Height:")).collect();
assert_eq!(
corners,
vec!["Top Left Radius:", "Top Right Radius:", "Bottom Left Radius:", "Bottom Right Radius:"],
"radius fields name their corner in layout order: {labels:?}"
);
assert!(!labels.iter().any(|label| label == "Radius:"), "the generic name would leave the corners indistinguishable");
}
/// #4205: the click slop is in screen points, so on a 2x (HiDPI) display at 100 % a 2 pt jitter
/// (4 device px = 4 document px) is still a click that opens Create Rectangle, not a tiny shape.
#[test]
+18
View File
@@ -536,6 +536,24 @@ mod tests {
assert!(app.ui.dialogs.iter().any(|x| x.id == id), "reset leaves the dialog open");
}
#[test]
fn canvas_extension_dropdown_is_named_for_its_setting() {
use egui::accesskit::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.session.execute("file.new", json!({"width": 100, "height": 50})).unwrap();
let mut h =
Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(|ui, app: &mut PhotocraftApp| crate::dialogs::show(app, ui.ctx()), app);
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
open(h.state_mut(), "image.canvasSize").unwrap();
h.run_steps(3);
let labels: Vec<String> = h.query_all_by_role(Role::ComboBox).filter_map(|n| n.accesskit_node().label()).collect();
assert!(labels.iter().any(|label| label == "Canvas extension color:"), "{labels:?}");
assert!(!labels.iter().any(|label| label == "Size"), "the dialog's Size label names a different field: {labels:?}");
}
/// #6019: on an Indexed Color document the dialog opens on, and offers only, Automatic and Nearest Neighbor.
#[test]
fn indexed_color_resamples_with_nearest_neighbor_only() {
+14 -22
View File
@@ -873,28 +873,11 @@ pub fn install_fonts_with(ctx: &egui::Context, cjk: crate::cjk_fonts::Sources) {
fonts.families.entry(FontFamily::Monospace).or_default().insert(0, mono);
}
// The optional craft-fonts input carries Japanese, Simplified Chinese, Korean, Arabic, Thai and
// other faces. Register them up front: the lazy loader cannot react before the first frame
// shapes (and a headless frame panics on a missing glyph rather than drawing tofu).
if cjk.eager_craft_fonts {
// The UI Japanese face comes first, as in the lazy loader (`japanese_for_ui`): egui uses
// the first family member that covers a glyph, and the manifest lists Shippori Mincho
// before BIZ UDPGothic, so manifest order alone would draw Japanese UI in serif glyphs
// and shared Han characters in Japanese forms.
let craft = photocraft_text::craft_fonts::CRAFT_FONTS;
let ui_first: Vec<usize> =
photocraft_text::craft_fonts::japanese_for_ui().iter().filter_map(|f| craft.iter().position(|c| std::ptr::eq(c, *f))).collect();
let order = ui_first.iter().copied().chain((0..craft.len()).filter(|i| !ui_first.contains(i)));
for i in order {
let f = &craft[i];
if f.bytes.is_empty() {
continue;
}
let name = format!("craft-font-{i}");
fonts.font_data.insert(name.clone(), Arc::new(FontData::from_static(f.bytes)));
fonts.families.entry(FontFamily::Proportional).or_default().push(name.clone());
fonts.families.entry(FontFamily::Monospace).or_default().push(name);
}
}
// other faces. They are not registered into this static stack: `cjk_fonts` installs a
// per-character font provider for them, so a broad Simplified Chinese face is not put in the
// family stack ahead of the Japanese or Korean face, and a locale without a Traditional Chinese
// craft face leaves Han to the system font. (A single linear per-family chain still decides a
// glyph once a broad face is discovered; see `cjk_fonts`.)
// Named weights fall back to the default stack for missing glyphs.
let fallback: Vec<String> = fonts.families.get(&FontFamily::Proportional).cloned().unwrap_or_default();
for (fam, primary) in [("medium", medium), ("semibold", semibold)] {
@@ -938,6 +921,11 @@ fn ui_font_size(ctx: &egui::Context) -> UiFontSize {
ctx.data(|d| d.get_temp::<UiFontSize>(ui_fonts_id())).unwrap_or_default()
}
/// The Interface > UI Font Size multiplier for the current context (including the default Small).
pub(crate) fn ui_font_scale(ctx: &egui::Context) -> f32 {
font_scale(ui_font_size(ctx))
}
fn font_scale(size: UiFontSize) -> f32 {
match size {
UiFontSize::Tiny => 10.0 / 12.0,
@@ -999,6 +987,10 @@ impl egui::Plugin for UiFontSizePlugin {
Arc::make_mut(data).tweak.scale = original * font_scale(size);
}
ctx.set_fonts(fonts);
// The provider must use the scale of the definitions that were active while this pass
// laid out text. A face it discovers during the pass is inserted at that old scale; after
// `set_fonts` the rescaled definitions take effect and the provider follows them.
crate::cjk_fonts::set_craft_font_scale(ctx, font_scale(size));
self.applied = size;
ctx.request_repaint();
}
@@ -6,14 +6,11 @@ use serde_json::json;
#[test]
fn all_registered_languages_render_camera_raw_and_switch_without_resetting_view_or_filter() {
// Required central-font acceptance must not pass only because the host supplies Hindi.
if std::env::var_os("CRAFT_FONTS_REQUIRED").is_some() {
let faces: Vec<_> = photocraft_text::craft_fonts::CRAFT_FONTS.iter().filter(|f| f.family == "Noto Sans Devanagari").collect();
assert_eq!(faces.len(), 1, "the central default manifest supplies one Devanagari face");
assert_eq!(faces[0].style, "Regular");
assert_eq!(faces[0].scripts, ["Deva"]);
assert!(!faces[0].bytes.is_empty());
}
// On Linux some scripts arrive through the background Fontconfig lookup. Kittest's strict
// missing-glyph policy must not race that scan: wait for it exactly as the i18n live tests do.
#[cfg(target_os = "linux")]
assert!(photocraft_ui_egui::cjk_fonts::wait_for_fontconfig_cjk_scan(), "Fontconfig CJK lookup did not finish within 10 seconds");
assert_required_camera_raw_fonts();
let _gpu = photocraft_testkit::gpu_lock();
for lang in i18n::Lang::all() {
let gpu = std::env::var_os("PHOTOCRAFT_LOCALE_SNAPSHOTS").is_some();
@@ -116,3 +113,21 @@ fn all_registered_languages_render_camera_raw_and_switch_without_resetting_view_
assert_eq!(after["histogram"], before["histogram"]);
}
}
/// Check central font fixtures independently of the language-switching UI assertions.
fn assert_required_camera_raw_fonts() {
// Required central-font acceptance must not pass only because the host supplies Hindi,
// or because a Windows runner happens to have Japanese fonts: every non-Latin script this
// test renders comes from a real face in the central manifest. The all-language loop then
// checks the actual translated labels under egui_kittest's strict missing-glyph policy.
if std::env::var_os("CRAFT_FONTS_REQUIRED").is_some() {
for (family, script) in [("BIZ UDPGothic", "Jpan"), ("Noto Sans CJK SC", "Hans"), ("NanumGothic", "Kore"), ("Noto Sans Devanagari", "Deva")] {
let faces: Vec<_> = photocraft_text::craft_fonts::CRAFT_FONTS
.iter()
.filter(|f| f.family == family && f.style == "Regular" && f.scripts.contains(&script))
.collect();
assert_eq!(faces.len(), 1, "the central default manifest supplies one {family} {script} Regular face");
assert!(!faces[0].bytes.is_empty(), "{family} {script} has an empty face");
}
}
}
+1 -1
View File
@@ -112,7 +112,7 @@ CRAFT_FONTS_DIR="$PWD/../craft-fonts" cargo test --workspace # runs the Japa
- **UI:** the Japanese fonts (BIZ UDPGothic Regular first) are the first Japanese fallback in the lazy CJK loader (`crates/ui-egui/src/cjk_fonts.rs`), ahead of the system Japanese fonts and in the same locale script order, appended last to every egui family with the usual baseline alignment.
- **Type tool:** the text engine registers them in `FontDb::new` (so also with no system fonts) and puts them first in the Japanese slot of the locale-ordered fallback list: BIZ UDPGothic for sans runs, Shippori Mincho / BIZ UDMincho for serif runs.
- **Web:** the wasm32 build never embeds craft-fonts, even with `CRAFT_FONTS_DIR` set: measured on 2026-10-06, the UI face alone took the release wasm from 24.19 MB to 28.87 MB, over the 24 MiB gate in `packaging/web/package.sh`. Instead it loads fonts served next to it, on demand: `fonts/manifest.txt` beside `index.html`, in craft-fonts' manifest format (`crates/text/src/served.rs`; hosting: `packaging/web/README.md` › Fonts). `PHOTOCRAFT_WEB_FONTS_DIR="$PWD/../craft-fonts" packaging/web/package.sh` puts craft-fonts there. Served families are in the font menus and are fetched when picked or when a document's text needs them; they aren't in the script fallback list yet, so Japanese text set in a Latin font still needs a Japanese font picked (#1615).
- Tests that need the fonts skip with a message when `CRAFT_FONTS` is empty; CI's Linux gate builds with `CRAFT_FONTS_DIR` set and `CRAFT_FONTS_REQUIRED=1`, so they run there. Desktop releases check out craft-fonts at the commit pinned in `.github/workflows/release.yml` (`CRAFT_FONTS_REF`; ci.yml pins the same commit) and ship each font's `OFL.txt` as `OFL-<family>.txt`.
- Tests that need the fonts skip with a message when `CRAFT_FONTS` is empty; CI's Linux gate and Windows test legs build with `CRAFT_FONTS_DIR` set and `CRAFT_FONTS_REQUIRED=1`, so they run there. Desktop releases check out craft-fonts at the commit pinned in `.github/workflows/release.yml` (`CRAFT_FONTS_REF`; ci.yml pins the same commit) and ship each font's `OFL.txt` as `OFL-<family>.txt`.
## One instance per user