Support scoped XeTeX OpenType colors in PDF and SVG
This commit is contained in:
1 parent
5a4271364a
commit
a0922d0105
10 files changed
+183
-16
No files matched your search
@@ -174,7 +174,7 @@ impl NativeShipout {
|
||||
let y = self.device.vertical_origin + self.box_node.height + p.y;
|
||||
if let MathItem::OpenType(run) = p.item {
|
||||
run.paint(x, y, |value| value, |item, source| {
|
||||
if !matches!(item, DisplayItem::OpenTypeActualText(_)) {
|
||||
if !matches!(item, DisplayItem::OpenTypeActualText(_) | DisplayItem::OpenTypeColor(_)) {
|
||||
page.sources.insert(page.items.len(), source);
|
||||
}
|
||||
page.items.push(item);
|
||||
|
||||
@@ -42,6 +42,8 @@ pub(crate) struct Request {
|
||||
slant: Option<u32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
embolden: Option<u32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
color: Option<[u8; 4]>,
|
||||
}
|
||||
|
||||
fn read_decimal_prefix(value: &str) -> f64 {
|
||||
@@ -62,6 +64,21 @@ fn read_device_factor(value: &str, option: &str, identity: f32) -> Result<Option
|
||||
Ok((value != identity).then(|| value.to_bits()))
|
||||
}
|
||||
|
||||
fn read_color(value: &str) -> Result<[u8; 4], String> {
|
||||
let digits = value.bytes().take(8).take_while(u8::is_ascii_hexdigit).count();
|
||||
if !matches!(digits, 6 | 8) {
|
||||
return Err("OpenType color requires RGB or RGBA hexadecimal digits".into());
|
||||
}
|
||||
let rgb = u32::from_str_radix(&value[..digits], 16)
|
||||
.map_err(|_| "invalid OpenType color")?;
|
||||
Ok(if digits == 6 { (rgb << 8 | 255).to_be_bytes() } else { rgb.to_be_bytes() })
|
||||
}
|
||||
|
||||
pub(crate) fn color_alpha(value: u8) -> f64 {
|
||||
// Match the PDF device's numeric precision for the graphics state.
|
||||
(f64::from(value) * (100_000_000. / 255.)).round() / 100_000_000.
|
||||
}
|
||||
|
||||
impl Request {
|
||||
pub(crate) fn parse(spec: &str) -> Result<Option<Self>, String> {
|
||||
let Some(bracketed) = spec.strip_prefix('[') else {
|
||||
@@ -109,6 +126,7 @@ impl Request {
|
||||
extend: None,
|
||||
slant: None,
|
||||
embolden: None,
|
||||
color: None,
|
||||
};
|
||||
for feature in features
|
||||
.split([';', ','])
|
||||
@@ -144,6 +162,8 @@ impl Request {
|
||||
return Err("invalid OpenType embolden percentage".into());
|
||||
}
|
||||
request.embolden = (value != 0.).then(|| value.to_bits());
|
||||
} else if let Some(value) = feature.strip_prefix("color=") {
|
||||
request.color = Some(read_color(value)?);
|
||||
} else {
|
||||
feature
|
||||
.parse::<Feature>()
|
||||
@@ -757,6 +777,10 @@ impl OpenTypeRun {
|
||||
PaintSource::default(),
|
||||
);
|
||||
}
|
||||
let color = self.font.request.color.filter(|_| !self.glyphs.is_empty());
|
||||
if let Some(color) = color {
|
||||
emit(crate::render::DisplayItem::OpenTypeColor(Some(color)), PaintSource::default());
|
||||
}
|
||||
for glyph in &self.glyphs {
|
||||
let first = self
|
||||
.sources
|
||||
@@ -785,6 +809,9 @@ impl OpenTypeRun {
|
||||
source.derived(crate::provenance::Derivation::FontProgram),
|
||||
);
|
||||
}
|
||||
if color.is_some() {
|
||||
emit(crate::render::DisplayItem::OpenTypeColor(None), PaintSource::default());
|
||||
}
|
||||
if marked {
|
||||
emit(
|
||||
crate::render::DisplayItem::OpenTypeActualText(None),
|
||||
|
||||
@@ -697,6 +697,7 @@ fn page_content(
|
||||
fallback_ids: &[usize; FACE_COUNT],
|
||||
origin: PageOrigin,
|
||||
opentype: &BTreeMap<crate::execution::FontId, opentype_fonts::EmbeddedFont>,
|
||||
font_opacities: &BTreeMap<u8, String>,
|
||||
) -> Vec<u8> {
|
||||
let digits = list.pdf.as_ref().map_or(3, |p| p.file.decimal_digits);
|
||||
let pt = |n: i64| {
|
||||
@@ -863,11 +864,22 @@ fn page_content(
|
||||
Some(text) => opentype_fonts::begin_actual_text(&mut content, text, true),
|
||||
None => content.push_str("EMC\n"),
|
||||
},
|
||||
DisplayItem::OpenTypeColor(color) => {
|
||||
if let Some([r, g, b, alpha]) = color {
|
||||
let [r, g, b] = [*r, *g, *b].map(|channel| f64::from(channel) / 255.);
|
||||
let opacity = &font_opacities[alpha];
|
||||
content.push_str(&format!(
|
||||
"q {r:.3} {g:.3} {b:.3} RG {r:.3} {g:.3} {b:.3} rg /{opacity} gs\n",
|
||||
));
|
||||
} else {
|
||||
content.push_str("Q\n");
|
||||
}
|
||||
}
|
||||
DisplayItem::OpenTypeGlyph { x, y, size, font, glyph, text, .. } => {
|
||||
opentype[&font.id].paint(
|
||||
&mut opentype_text, &mut content, font, *glyph, text,
|
||||
*size, *x - h, height - *y - v, bp_per_unit,
|
||||
[one_inch - h, height - one_inch - v],
|
||||
[one_inch - h, height - one_inch - v], !font_opacities.is_empty(),
|
||||
);
|
||||
}
|
||||
DisplayItem::NativeGlyph {
|
||||
@@ -2299,6 +2311,15 @@ fn write_pdf(
|
||||
font_ids[slot] = write_type0_font(&mut objects, face, slot, &used_chars[slot]);
|
||||
}
|
||||
|
||||
let resources = if resources.is_none() && pages.iter().any(|page| {
|
||||
page.items.iter().any(|item| matches!(item, DisplayItem::OpenTypeColor(Some(_))))
|
||||
}) {
|
||||
Some(crate::pdf_device::page_resources::ResourceOutput::prepare(
|
||||
pages, None, BTreeMap::new(), &[], None, None,
|
||||
)?)
|
||||
} else {
|
||||
resources
|
||||
};
|
||||
let remapped = resources.map(|resources| resources.append(&mut objects, diagnostics));
|
||||
if let Some(resources) = &remapped {
|
||||
for (font, entries) in &resources.fonts {
|
||||
@@ -2522,6 +2543,10 @@ fn write_pdf(
|
||||
for (index, slot) in &used {
|
||||
names.insert(*index, format!("Im{slot}"));
|
||||
}
|
||||
let no_font_opacity = BTreeMap::new();
|
||||
let font_opacities = remapped.as_ref().map_or(
|
||||
&no_font_opacity, |resources| &resources.font_opacities[page_index],
|
||||
);
|
||||
let content = page_content(
|
||||
list,
|
||||
height,
|
||||
@@ -2531,6 +2556,7 @@ fn write_pdf(
|
||||
&fallback_font_ids,
|
||||
origin,
|
||||
&opentype,
|
||||
font_opacities,
|
||||
);
|
||||
objects.push(objects::stream(
|
||||
"",
|
||||
|
||||
@@ -429,6 +429,7 @@ pub(crate) struct ResourceOutput {
|
||||
link_references: BTreeMap<u32, Option<(usize, usize)>>,
|
||||
structure_references: BTreeSet<u32>,
|
||||
page_entries: Vec<Dictionary>,
|
||||
font_opacities: Vec<BTreeMap<u8, String>>,
|
||||
page_attributes: Vec<Dictionary>,
|
||||
page_tree_attributes: Dictionary,
|
||||
font_entries: BTreeMap<FontId, Dictionary>,
|
||||
@@ -439,6 +440,7 @@ pub(crate) struct ResourceOutput {
|
||||
|
||||
pub(crate) struct RemappedResources {
|
||||
pub pages: Vec<Vec<u8>>,
|
||||
pub font_opacities: Vec<BTreeMap<u8, String>>,
|
||||
pub page_attributes: Vec<Vec<u8>>,
|
||||
pub page_tree_attributes: Vec<u8>,
|
||||
pub fonts: BTreeMap<FontId, Vec<u8>>,
|
||||
@@ -461,18 +463,31 @@ impl ResourceOutput {
|
||||
) -> Result<Self, String> {
|
||||
let empty = PdfObjects::default();
|
||||
let objects = objects.unwrap_or(&empty);
|
||||
let page_entries = pages
|
||||
let (page_entries, font_opacities): (Vec<_>, Vec<_>) = pages
|
||||
.iter()
|
||||
.map(|page| {
|
||||
let entries = parse_entries(&page.pdf_resources.entries)?;
|
||||
let mut entries = parse_entries(&page.pdf_resources.entries)?;
|
||||
if entries.has(b"Font") || entries.has(b"XObject") {
|
||||
return Err(
|
||||
"additional PDF resources overlap generated Font or XObject entries".into(),
|
||||
);
|
||||
}
|
||||
Ok(entries)
|
||||
let alphas = page
|
||||
.items
|
||||
.iter()
|
||||
.filter_map(|item| match item {
|
||||
crate::render::DisplayItem::OpenTypeColor(Some([_, _, _, alpha])) => {
|
||||
Some(*alpha)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let names = add_font_opacities(&mut entries, alphas, objects)?;
|
||||
Ok((entries, names))
|
||||
})
|
||||
.collect::<Result<Vec<_>, String>>()?;
|
||||
.collect::<Result<Vec<_>, String>>()?
|
||||
.into_iter()
|
||||
.unzip();
|
||||
let font_entries = fonts
|
||||
.into_iter()
|
||||
.map(|(font, entries)| Ok((font, parse_entries(entries)?)))
|
||||
@@ -563,6 +578,7 @@ impl ResourceOutput {
|
||||
link_references,
|
||||
structure_references,
|
||||
page_entries,
|
||||
font_opacities,
|
||||
page_attributes,
|
||||
page_tree_attributes,
|
||||
font_entries,
|
||||
@@ -628,17 +644,29 @@ impl ResourceOutput {
|
||||
(number, id)
|
||||
})
|
||||
.collect();
|
||||
let encode = |dictionary: Dictionary| {
|
||||
let encode_dictionary = |dictionary: Dictionary, precise: bool| {
|
||||
if dictionary.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut object = Object::Dictionary(dictionary);
|
||||
remap(&mut object, &ids);
|
||||
let bytes = encode_value(object).expect("valid PDF resource dictionary in memory");
|
||||
let bytes = if precise {
|
||||
super::xdv_object::encode_device_value(object)
|
||||
} else {
|
||||
encode_value(object)
|
||||
}
|
||||
.expect("valid PDF resource dictionary in memory");
|
||||
bytes[2..bytes.len() - 2].to_vec()
|
||||
};
|
||||
let encode = |dictionary| encode_dictionary(dictionary, false);
|
||||
RemappedResources {
|
||||
pages: self.page_entries.into_iter().map(&encode).collect(),
|
||||
pages: self
|
||||
.page_entries
|
||||
.into_iter()
|
||||
.zip(&self.font_opacities)
|
||||
.map(|(dictionary, opacities)| encode_dictionary(dictionary, !opacities.is_empty()))
|
||||
.collect(),
|
||||
font_opacities: self.font_opacities,
|
||||
page_attributes: self.page_attributes.into_iter().map(&encode).collect(),
|
||||
page_tree_attributes: encode(self.page_tree_attributes),
|
||||
fonts: self.font_entries.into_iter()
|
||||
@@ -656,6 +684,36 @@ impl ResourceOutput {
|
||||
}
|
||||
}
|
||||
|
||||
fn add_font_opacities(
|
||||
entries: &mut Dictionary,
|
||||
alphas: BTreeSet<u8>,
|
||||
objects: &PdfObjects,
|
||||
) -> Result<BTreeMap<u8, String>, String> {
|
||||
let mut names = BTreeMap::new();
|
||||
if alphas.is_empty() {
|
||||
return Ok(names);
|
||||
}
|
||||
let mut states = match entries.get(b"ExtGState") {
|
||||
Ok(value) => resolve_dictionary(value.clone(), objects)?,
|
||||
Err(_) => Dictionary::new(),
|
||||
};
|
||||
for alpha in alphas {
|
||||
let mut name = format!("TFontAlpha{alpha}");
|
||||
while states.has(name.as_bytes()) {
|
||||
name.push('_');
|
||||
}
|
||||
let opacity = crate::opentype::color_alpha(alpha);
|
||||
let mut definition = Dictionary::new();
|
||||
definition.set("Type", Object::Name(b"ExtGState".to_vec()));
|
||||
definition.set("ca", Object::Real(opacity));
|
||||
definition.set("CA", Object::Real(opacity));
|
||||
states.set(name.as_bytes().to_vec(), Object::Dictionary(definition));
|
||||
names.insert(alpha, name);
|
||||
}
|
||||
entries.set("ExtGState", Object::Dictionary(states));
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
fn references(object: &Object, pending: &mut BTreeSet<u32>) -> Result<(), String> {
|
||||
match object {
|
||||
Object::Reference((number, 0)) if *number > 0 => {
|
||||
|
||||
@@ -327,13 +327,14 @@ impl EmbeddedFont {
|
||||
y: i64,
|
||||
bp_per_unit: f64,
|
||||
page_origin: [i64; 2],
|
||||
font_colors: bool,
|
||||
) {
|
||||
let glyph = &self.glyphs[&glyph];
|
||||
let [horizontal_scale, slant] = font.paint_transform();
|
||||
let device = font.device_transform();
|
||||
let embolden = font.paint_embolden();
|
||||
let emboldened = embolden > 0.;
|
||||
let relative = (device[1] != 0. || emboldened) && device[0] != 0.;
|
||||
let relative = (device[1] != 0. || emboldened || font_colors) && device[0] != 0.;
|
||||
let horizontal_em = size as f64 * if relative { device[0] } else { horizontal_scale };
|
||||
let override_text = glyph
|
||||
.cluster_text
|
||||
@@ -364,7 +365,7 @@ impl EmbeddedFont {
|
||||
begin_actual_text(output, text, false);
|
||||
}
|
||||
let first = state.run.is_none();
|
||||
let start_relative = first && emboldened && relative && state.matrix == device;
|
||||
let start_relative = first && (emboldened || font_colors) && relative && state.matrix == device;
|
||||
state.matrix = device;
|
||||
let run = state.run.get_or_insert_with(|| {
|
||||
let size_bp = size as f64 * bp_per_unit;
|
||||
|
||||
@@ -62,6 +62,8 @@ pub enum DisplayItem {
|
||||
},
|
||||
/// Word-level PDF replacement text. None closes the current word.
|
||||
OpenTypeActualText(Option<String>),
|
||||
/// Word-local font color and alpha. None restores the surrounding paint.
|
||||
OpenTypeColor(Option<[u8; 4]>),
|
||||
/// A native math glyph. `face` preserves the optical master independently
|
||||
/// of the painted size; `slot` preserves CMEX next-larger selection.
|
||||
MathGlyph {
|
||||
@@ -435,7 +437,7 @@ impl DisplayList {
|
||||
}
|
||||
DisplayItem::Fill(_) | DisplayItem::Background(_) | DisplayItem::PdfColor(_) => {}
|
||||
DisplayItem::Special(_) | DisplayItem::PdfImageObject(_)
|
||||
| DisplayItem::OpenTypeActualText(_) => {}
|
||||
| DisplayItem::OpenTypeActualText(_) | DisplayItem::OpenTypeColor(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -518,6 +520,7 @@ impl DisplayList {
|
||||
let mut opentype_faces = std::collections::BTreeMap::new();
|
||||
let mut fill = [0u8, 0, 0];
|
||||
let mut rule_fill = [0u8; 3];
|
||||
let mut opentype_color: Option<[u8; 4]> = None;
|
||||
let mut stroke = [0u8; 3];
|
||||
let mut transparency = SvgTransparency::default();
|
||||
let mut graphics = Vec::new();
|
||||
@@ -587,17 +590,30 @@ impl DisplayList {
|
||||
write!(out, " matrix({horizontal:.9} 0 {shear:.9} -{scale:.9} 0 0)").unwrap();
|
||||
}
|
||||
}
|
||||
let (fill, stroke, alpha) = match opentype_color {
|
||||
Some([r, g, b, a]) => ([r, g, b], [r, g, b], Some(crate::opentype::color_alpha(a))),
|
||||
None => (fill, stroke, None),
|
||||
};
|
||||
write!(
|
||||
out, "\" fill=\"#{:02x}{:02x}{:02x}\"{fill_opacity}",
|
||||
fill[0], fill[1], fill[2],
|
||||
out, "\" fill=\"#{:02x}{:02x}{:02x}\"", fill[0], fill[1], fill[2],
|
||||
).unwrap();
|
||||
match alpha {
|
||||
Some(alpha) if alpha < 1. => write!(out, " fill-opacity=\"{alpha}\"").unwrap(),
|
||||
None => out.push_str(fill_opacity),
|
||||
_ => {}
|
||||
}
|
||||
if embolden > 0. {
|
||||
let stroke_width = embolden / self.units.bp(65536);
|
||||
write!(
|
||||
out,
|
||||
" stroke=\"#{:02x}{:02x}{:02x}\" stroke-width=\"{stroke_width:.9}\" stroke-miterlimit=\"10\"{stroke_opacity}",
|
||||
" stroke=\"#{:02x}{:02x}{:02x}\" stroke-width=\"{stroke_width:.9}\" stroke-miterlimit=\"10\"",
|
||||
stroke[0], stroke[1], stroke[2],
|
||||
).unwrap();
|
||||
match alpha {
|
||||
Some(alpha) if alpha < 1. => write!(out, " stroke-opacity=\"{alpha}\"").unwrap(),
|
||||
None => out.push_str(stroke_opacity),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out.push_str("/></g>\n");
|
||||
}
|
||||
@@ -751,6 +767,7 @@ impl DisplayList {
|
||||
}
|
||||
DisplayItem::Link { .. } | DisplayItem::PdfTextSpace { .. }
|
||||
| DisplayItem::OpenTypeActualText(_) => {}
|
||||
DisplayItem::OpenTypeColor(color) => opentype_color = *color,
|
||||
DisplayItem::Special(content) => {
|
||||
out.push_str(&format!(
|
||||
"<!-- special: {} -->
|
||||
|
||||
@@ -363,6 +363,7 @@ impl SourceMap {
|
||||
if matches!(
|
||||
item,
|
||||
DisplayItem::PdfColor(_) | DisplayItem::PdfImageObject(_) | DisplayItem::PdfTextSpace { .. }
|
||||
| DisplayItem::OpenTypeColor(_)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user