This commit is contained in:
bflatastic committed 2026-11-18 01:56:45 +07:00
commit cda26daf74
7 files changed
+202 -8

No files matched your search

+28 -4
View File
@@ -561,10 +561,7 @@ impl Mapper {
let shape = if k > 1e-12 && k.is_finite() && linear.determinant().abs() > 1e-24 { Affine::scale(1.0 / k) * linear } else { Affine::IDENTITY };
let f = &t.font;
let h = f64::from(f.height);
// A negative height is the em; a positive one the cell (the em and the internal leading).
let em = if h < 0.0 { -h } else { h * 0.85 };
let size = if em > 0.0 && (em * k).is_finite() { (em * k).clamp(0.5, 5000.0) } else { 12.0 };
let mut style = CharStyle { size, fill: color(t.color), stroke: Paint::None, ..CharStyle::default() };
let mut style = CharStyle { fill: color(t.color), stroke: Paint::None, ..CharStyle::default() };
if !f.family.trim().is_empty() {
style.font_family = f.family.trim().to_string();
}
@@ -575,6 +572,33 @@ impl Mapper {
(false, false) => "Regular",
}
.into();
// The face the font maps to (the fallback face for a font that isn't installed). Characters
// it has no glyph for are drawn from other faces at the same size and Horizontal Scale.
let face = vectorcraft_text::FontDb::global().style_face(&style);
// A negative height is the em. A positive height is the character cell, and the em is
// the cell times unitsPerEm divided by the face's OS/2 usWinAscent plus usWinDescent at
// its instance of a variable font (its own ascent plus descent when it has no OS/2 table).
let cell_em = face.as_ref().and_then(|face| {
let (a, d) = face.vertical_metrics();
Some(face.units_per_em() / face.win_cell_height().unwrap_or(a + d)).filter(|r| r.is_finite() && *r > 0.0)
});
let em = if h < 0.0 { -h } else { h * cell_em.unwrap_or(0.85) };
let sized = em > 0.0 && (em * k).is_finite();
let size = if sized { (em * k).clamp(0.5, 5000.0) } else { 12.0 };
style.size = size;
// An average character width, negative or positive, becomes Horizontal Scale: the face's
// own average width (OS/2 xAvgCharWidth) at the type size is stretched or narrowed to it,
// also when the size was held to its range. A width is ignored when the height is 0.
let width = f64::from(f.width).abs();
if width > 0.0
&& sized
&& let Some(avg) = face.as_ref().and_then(|face| Some(face.average_char_width()? / face.units_per_em()))
{
let h_scale = width * k / (avg * size) * 100.0;
if h_scale.is_finite() {
style.h_scale = h_scale.clamp(1.0, 10000.0);
}
}
style.underline = f.underline;
style.strikethrough = f.strike;
let db = vectorcraft_text::FontDb::global();
+118
View File
@@ -677,6 +677,124 @@ fn text_keeps_a_stretch_across() {
assert!((a - 2.0).abs() < 1e-6 && b.abs() < 1e-6 && c.abs() < 1e-6 && (d - 1.0).abs() < 1e-6, "{:?}", t.xf);
}
/// Source Sans 3 Regular's own values, read from its table directory: unitsPerEm (`head`),
/// xAvgCharWidth and usWinAscent + usWinDescent (`OS/2`), in font units.
fn source_sans_metrics() -> (f64, f64, f64) {
let font: &[u8] = include_bytes!("../../../../assets/fonts/SourceSans3-Regular.ttf");
let u16_at = |at: usize| u16::from_be_bytes([font[at], font[at + 1]]);
let table = |tag: &[u8; 4]| {
let at = (0..usize::from(u16_at(4))).map(|i| 12 + 16 * i).find(|at| &font[*at..*at + 4] == tag).unwrap();
u32::from_be_bytes([font[at + 8], font[at + 9], font[at + 10], font[at + 11]]) as usize
};
let (head, os2) = (table(b"head"), table(b"OS/2"));
let avg = f64::from(i16::from_be_bytes([font[os2 + 2], font[os2 + 3]]));
(f64::from(u16_at(head + 18)), avg, f64::from(u16_at(os2 + 74)) + f64::from(u16_at(os2 + 76)))
}
/// The style of "Hi" drawn in an EMF in Source Sans 3 with a LOGFONT of `height` and `width`
/// (hundredths of a millimeter).
fn emf_font_style(height: i32, width: i32) -> vectorcraft_doc::CharStyle {
emf_font_style_in("Source Sans 3", height, width)
}
/// [`emf_font_style`] with the LOGFONT naming `family`.
fn emf_font_style_in(family: &str, height: i32, width: i32) -> vectorcraft_doc::CharStyle {
let mut text = vec![0; 16];
text.extend(le(&[1, 0, 0]));
text.extend(le(&[1000, 1500, 2, 76, 0, 0, 0, 0, 0, 0]));
text.extend("Hi".encode_utf16().flat_map(u16::to_le_bytes));
let mut font = le(&[2, height, width, 0, 0, 400]);
font.extend([0u8; 8]);
font.extend(family.encode_utf16().chain(std::iter::repeat_n(0, 32 - family.encode_utf16().count())).flat_map(u16::to_le_bytes));
let records = vec![(82, font), (37, le(&[2])), (84, text)];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
let t = all(&back.document)
.into_iter()
.find_map(|n| match n.kind {
NodeKind::Text(t) => Some(t),
_ => None,
})
.unwrap();
t.runs[0].style.clone()
}
#[test]
fn a_font_width_becomes_horizontal_scale() {
let (upem, avg, _) = source_sans_metrics();
let mm = 72.0 / 25.4;
// A 10 mm em and an average character width of 6 mm: the face's average width, avg/upem of
// the em, is scaled to 6 mm.
let want = 6.0 / (avg / upem * 10.0) * 100.0;
for width in [600, -600] {
let st = emf_font_style(-1000, width);
assert_eq!(st.font_family, "Source Sans 3");
assert!((st.size - 10.0 * mm).abs() < 1e-9, "{}", st.size);
assert!((st.h_scale - want).abs() < 1e-9, "width {width}: {} for {want}", st.h_scale);
}
assert_eq!(emf_font_style(-1000, 0).h_scale, 100.0);
// A 4 m em is set at the largest type size, 5000 pt, and a 2.4 m average width keeps its
// width at that size.
let st = emf_font_style(-400_000, 240_000);
assert_eq!(st.size, 5000.0);
let want = 2400.0 * mm / (avg / upem * 5000.0) * 100.0;
assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale);
// With a height of 0 the type is set at the default size and the width is ignored.
assert_eq!(emf_font_style(0, 600).h_scale, 100.0);
}
#[test]
fn a_positive_font_height_is_the_character_cell() {
let (upem, avg, cell) = source_sans_metrics();
let mm = 72.0 / 25.4;
// A 10 mm cell: the em is the cell times unitsPerEm divided by the face's usWinAscent plus
// usWinDescent, and a 6 mm average width is measured against that em.
let em = 10.0 * upem / cell;
let st = emf_font_style(1000, 600);
assert!((st.size - em * mm).abs() < 1e-9, "{} for {}", st.size, em * mm);
let want = 6.0 / (avg / upem * em) * 100.0;
assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale);
}
#[test]
fn a_font_the_system_lacks_is_measured_in_the_face_that_draws_it() {
// A family no system has keeps its name, and layout draws it in Source Sans 3: the cell and
// the average width are measured in that face.
let (upem, avg, cell) = source_sans_metrics();
let mm = 72.0 / 25.4;
let st = emf_font_style_in("Missing Family 7183", 1000, 600);
assert_eq!(st.font_family, "Missing Family 7183");
let em = 10.0 * upem / cell;
assert!((st.size - em * mm).abs() < 1e-9, "{} for {}", st.size, em * mm);
let want = 6.0 / (avg / upem * em) * 100.0;
assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale);
}
#[test]
fn wmf_font_width_becomes_horizontal_scale() {
let (upem, avg, _) = source_sans_metrics();
// CREATEFONTINDIRECT: a 0.1 inch em (144 units) with an average width of 72 units, then
// SELECTOBJECT and TEXTOUT "Hi" at (720, 360).
let mut font = le16(&[-144, 72, 0, 0, 400]);
font.extend([0u8; 8]);
font.extend(b"Source Sans 3".iter().copied().chain(std::iter::repeat_n(0, 19)));
let mut text = le16(&[2]);
text.extend(b"Hi");
text.extend(le16(&[360, 720]));
let records = vec![(0x02FB, font), (0x012D, le16(&[0])), (0x0521, text)];
let back = import(&hand_wmf(1440, 1440, &records)).unwrap();
let t = all(&back.document)
.into_iter()
.find_map(|n| match n.kind {
NodeKind::Text(t) => Some(t),
_ => None,
})
.unwrap();
let st = &t.runs[0].style;
assert!((st.size - 7.2).abs() < 1e-9, "{}", st.size);
let want = 72.0 / (avg / upem * 144.0) * 100.0;
assert!((st.h_scale - want).abs() < 1e-9, "{} for {want}", st.h_scale);
}
#[test]
fn a_clip_whose_box_holds_the_picture_still_clips() {
// A diamond around the middle of the picture, whose box holds the whole frame but which cuts
+22
View File
@@ -368,6 +368,28 @@ impl FontFace {
pub fn line_gap(&self) -> f64 {
self.skrifa().map_or(0.0, |f| f64::from(f.metrics(Size::unscaled(), self.location()).leading)).max(0.0)
}
/// The height of the face's character cell on Windows (the OS/2 table's `usWinAscent` plus
/// `usWinDescent`, at the face's location in a variable font), in font units; `None` when the
/// font has no OS/2 table or the sum isn't positive.
pub fn win_cell_height(&self) -> Option<f64> {
use skrifa::raw::TableProvider;
let f = self.skrifa()?;
let o = f.os2().ok()?;
// A variable font's MVAR table moves usWinAscent (`hcla`) and usWinDescent (`hcld`):
// https://learn.microsoft.com/en-us/typography/opentype/spec/mvar
let varied = |tag: &[u8; 4]| {
f.mvar().ok().and_then(|m| m.metric_delta(skrifa::Tag::new(tag), self.location().coords()).ok()).map_or(0.0, |d| d.to_f64())
};
let h = f64::from(o.us_win_ascent()) + varied(b"hcla") + f64::from(o.us_win_descent()) + varied(b"hcld");
(h > 0.0 && h.is_finite()).then_some(h)
}
/// The average width of the face's characters (the OS/2 table's `xAvgCharWidth`), in font
/// units; `None` when the font has no OS/2 table or gives no positive width.
pub fn average_char_width(&self) -> Option<f64> {
use skrifa::raw::TableProvider;
let w = f64::from(self.skrifa()?.os2().ok()?.x_avg_char_width());
(w > 0.0).then_some(w)
}
/// Every mapped character and its glyph id, sorted by code point (the Glyphs panel).
pub fn chars(&self) -> Vec<(char, u32)> {
self.mapped_chars().to_vec()
+11 -4
View File
@@ -1598,7 +1598,8 @@ pub const PATH_ALIGN_TYPO_FAMILY: &str = "Pathalign Typo Sans";
pub const PATH_ALIGN_HHEA_FAMILY: &str = "Pathalign Hhea Sans";
/// A family of [`path_align_font`]: as [`PATH_ALIGN_TYPO_FAMILY`], as a variable font with one
/// weight axis (400–700, named instances Regular and Bold) whose `MVAR` table raises the
/// typographic ascender and descender by 100 at 700: a box from 0 to 1,000 in Bold.
/// typographic ascender and descender by 100 at 700: a box from 0 to 1,000 in Bold. It also raises
/// `usWinAscent` by 120 and `usWinDescent` by 80 at 700.
pub const PATH_ALIGN_VARIABLE_FAMILY: &str = "Pathalign Variable Sans";
/// A family of [`path_align_font`]: Japanese code page, with no reference ideograph and no ┼.
pub const PATH_ALIGN_NONE_FAMILY: &str = "Pathalign None Sans";
@@ -1693,10 +1694,16 @@ pub fn path_align_font(family: &str) -> Option<Vec<u8>> {
}
if family == PATH_ALIGN_VARIABLE_FAMILY {
let region = VariationRegion::new(vec![RegionAxisCoordinates::new(F2Dot14::from_f32(0.0), F2Dot14::from_f32(1.0), F2Dot14::from_f32(1.0))]);
// Two delta sets (hasc, hdsc) of one 16-bit delta each for the one region.
let data = ItemVariationData::new(2, 1, vec![0], [100_i16.to_be_bytes(), 100_i16.to_be_bytes()].concat());
// Four delta sets (hasc, hdsc, hcla, hcld) of one 16-bit delta each for the one region.
let deltas = [100_i16, 100, 120, 80].map(i16::to_be_bytes).concat();
let data = ItemVariationData::new(4, 1, vec![0], deltas);
let store = ItemVariationStore::new(VariationRegionList::new(1, vec![region]), vec![Some(data)]);
let records = vec![ValueRecord::new(Tag::new(b"hasc"), 0, 0), ValueRecord::new(Tag::new(b"hdsc"), 0, 1)];
let records = vec![
ValueRecord::new(Tag::new(b"hasc"), 0, 0),
ValueRecord::new(Tag::new(b"hcla"), 0, 2),
ValueRecord::new(Tag::new(b"hcld"), 0, 3),
ValueRecord::new(Tag::new(b"hdsc"), 0, 1),
];
let axis = VariationAxisRecord {
axis_tag: Tag::new(b"wght"),
min_value: Fixed::from_i32(400),
+13
View File
@@ -874,6 +874,19 @@ fn on_path_align_takes_a_variable_font_instances_em_box() {
assert!(ascender.len() == 2 && (ascender[0] - 9.0).abs() < 1e-6 && (ascender[1] - 10.0).abs() < 1e-6, "{ascender:?}");
}
/// A variable font's instance takes its Windows character cell from the `usWinAscent` and
/// `usWinDescent` its `MVAR` table varies: 200 units taller in Bold.
#[test]
fn win_cell_height_takes_a_variable_font_instances_mvar() {
use crate::test_fonts::{PATH_ALIGN_VARIABLE_FAMILY, path_align_font};
let db = FontDb::with_font_dirs(vec![]);
db.add_font(path_align_font(PATH_ALIGN_VARIABLE_FAMILY).unwrap());
let st = |font_style: &str| CharStyle { font_family: PATH_ALIGN_VARIABLE_FAMILY.into(), font_style: font_style.into(), ..style(10.0) };
let cell = |font_style: &str| db.style_face(&st(font_style)).and_then(|f| f.win_cell_height()).unwrap();
let (regular, bold) = (cell("Regular"), cell("Bold"));
assert!((bold - regular - 200.0).abs() < 1e-6, "Regular {regular}, Bold {bold}");
}
/// In vertical type, Align to Path moves the glyphs half an em, with their horizontal scale and not
/// their vertical scale, for Ascender and Descender, and leaves them on the path for Center: their
/// baselines and their drawn outlines both.
+9
View File
@@ -8852,6 +8852,15 @@ draws with EMF+ records is read from them. Hatched and pattern brushes fill with
pastes `image/emf` from the system clipboard ahead of text and bitmaps when the platform's clipboard service offers it
(the Windows desktop service doesn't read metafiles yet).
The type size comes from the font's height. A negative height is the em. A positive height is the character cell, and
the em is the cell times the face's units per em divided by its OS/2 `usWinAscent` plus `usWinDescent`, with a
variable font's `MVAR` changes at the face's instance (its ascent plus descent when it has no OS/2 table). When the face gives an average width (OS/2 `xAvgCharWidth`), a font's average
character width, negative or positive, becomes Horizontal Scale: the face's average width at the type size is
stretched or narrowed to the font's width. VectorCraft's own rules are that a negative width is read as its absolute
value and that the width is ignored when the height is 0. For a font the system doesn't have, both values are measured
in the face that replaces it. Characters that face has no glyph for are drawn from other faces at the same size and
Horizontal Scale.
```json
{"name":"export","arguments":{"path":"/tmp/logo.emf"}}
{"name":"run_command","arguments":{"command":"document.export","params":{"format":"wmf","useArtboards":true,"path":"/tmp/icons.wmf"}}}
+1
View File
@@ -2046,6 +2046,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- HEIC and HEIF images open and place from `.heic` and `.heif`, as the [supported file formats](https://helpx.adobe.com/illustrator/kb/supported-file-formats-illustrator.html) list High Efficiency Image under both Open and Place (and [Fix HEIF file import errors on Windows](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/fix-heif-file-import-errors-on-windows.html) covers both ways of bringing HEIF files in): HEVC-coded single pictures and grids of tiles, 8 to 10 bits, with an alpha image, decoded by heic-rs in the engine's default `heif` feature. The container's rotation, mirror and crop are applied. Without an `nclx` box, the HEVC stream's video signal type gives the samples' matrix and range. An RGB ICC profile, or Display P3 with the sRGB curve named by an `nclx` box or, without a color box, by the stream, is converted to sRGB; the EXIF resolution tags size the image, or 72 ppi. Image sequences, other codings and grids of cropped tiles are refused with a message, and so is every HEIF file in a build without the feature. The decoder checks image size before allocating (`crates/engine/src/cmd/fileio/tests_heifread.rs`).
- HP-GL/2 plot files (`.plt`, `.hpgl`, `.hgl`, `.hpg`, or a name no other format reads when the file starts with plotter instructions) open and place as paths on one layer, the artboard round the art: each line drawn with the pen down is a stroked path in its pen's color and width, line types become dash patterns, circles, arcs, wedges and Bézier curves are curves, filled and edged rectangles, wedges and polygons (polygon mode) are filled or stroked paths, and encoded polylines, scaling points, user units and rotation are read. Labels, symbol mode's symbols, raster images and hatching aren't drawn and are listed in the warnings (`crates/cad/src/hpgl/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`).
- PICT pictures (`.pct`, `.pic`, and `.pict` as VectorCraft's own name) open and place, as [the help page](https://helpx.adobe.com/archive/illustrator/illustrator-cs5-5-troubleshooting.pdf) lists Macintosh PICT under both opening and placing: versions 1 and 2, with or without the file's 512 bytes of application data, read by the opcodes of Apple's [Opcodes in Pictures](https://dev.os9.ca/techpubs/mac/QuickDraw/QuickDraw-461.html). Lines, rectangles, rounded rectangles, ovals, arcs, polygons and regions become paths in their pen and pattern colors, text becomes point type in the font the picture names, bitmaps, pixel maps and QuickTime JPEG images become images, and the clip region clips what follows it; File › Place places the picture as one group clipped to its frame. Inverted shapes, other transfer modes and other QuickTime formats come back as warnings, and a picture cut short keeps what came before it (`crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs`).
- EMF and WMF type takes its size from the font's height, where a negative height is the em and a positive height is the character cell, and a font's average character width becomes Horizontal Scale against the face's own average width (OS/2 `xAvgCharWidth`) when the face gives one, as [LOGFONT](https://learn.microsoft.com/en-us/windows/win32/api/wingdi/ns-wingdi-logfontw) and [MS-EMF 2.2.13](https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-emf/1cd7cb7a-1a7c-48d2-b4a4-c218f9d12100) describe the two fields. VectorCraft's own rules are that the cell is the face's `usWinAscent` plus `usWinDescent` at a variable font's instance (its ascent plus descent without an OS/2 table), that a negative width is read as its absolute value, and that the width is ignored when the height is 0 (`a_font_width_becomes_horizontal_scale`, `a_positive_font_height_is_the_character_cell`, `a_font_the_system_lacks_is_measured_in_the_face_that_draws_it`, `wmf_font_width_becomes_horizontal_scale`).
- EMF and WMF files are read by the shared `craft-metafile` reader and open, place and paste as editable paths, clipping groups, images and point type: an EMF drawn with EMF+ records (on their own, or beside plain records) is read from them instead of opening empty, and hatched and pattern brushes fill with their average color (`crates/metafile/src/tests/import.rs`).
- EMF, WMF and EMF+ text keeps the character advances the file gives (ExtTextOut's `lpDx`, DrawDriverString positions) as tracking, with pair kerning off; on a single left to right line, an advance that tracking can't give (wider than its range, or a tab) starts a new point type object where the advance puts it, with an underline or strikethrough filled across the space between and on to the end of the last character's advance; type on more than one line is placed a line at a time, each line aligned by its own advances and split as a single line is (`text_is_spaced_by_its_advances`, `multiline_text_with_advances_aligns_each_line`, `wmf_text_is_spaced_by_its_advances`, `emf_plus_driver_strings_keep_their_positions`, `split_type_keeps_its_underline_and_right_to_left_order`).
- Export As › HP-GL (`document.export {format: "hpgl"}`) writes a `.plt` plot of an artboard, each artboard or the art for pen plotters and cutters: each visible path once along its line in plotter units from the artboard's bottom-left corner or center, a pen per color or a pen table, curves flattened to a tolerance, type as outlines, clipping masks and the artboard's edges applied, and HP-GL or HP-GL/2 (pen colors and encoded polylines); plots read back by the HP-GL reader give the same lines (`crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`).