Use external expanded font metrics in native paragraph layout
This commit is contained in:
1 parent
4ad66c120d
commit
12d9eb6a54
9 files changed
+326
-116
No files matched your search
@@ -355,7 +355,7 @@ impl Printer<'_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn character(&mut self, font: FontId, slot: u8, expansion: i32) -> Result<(), String> {
|
fn character(&mut self, font: FontId, slot: u8, expansion: i32) -> Result<(), String> {
|
||||||
let name = self.state.fonts.font(font)?.identifier_text();
|
let (name, expansion) = self.state.fonts.diagnostic_font(font, expansion)?;
|
||||||
self.command(&name);
|
self.command(&name);
|
||||||
if expansion != 0 {
|
if expansion != 0 {
|
||||||
self.literal(&format!(" ({expansion:+})"));
|
self.literal(&format!(" ({expansion:+})"));
|
||||||
|
|||||||
@@ -3999,6 +3999,7 @@ impl Executor {
|
|||||||
files,
|
files,
|
||||||
)?,
|
)?,
|
||||||
Some(Pdffontexpand) => {
|
Some(Pdffontexpand) => {
|
||||||
|
let span = self.current;
|
||||||
let font = self.font_identifier(files)?;
|
let font = self.font_identifier(files)?;
|
||||||
self.optional_equals(files)?;
|
self.optional_equals(files)?;
|
||||||
let stretch = self.integer(files)?;
|
let stretch = self.integer(files)?;
|
||||||
@@ -4008,9 +4009,15 @@ impl Executor {
|
|||||||
if automatic {
|
if automatic {
|
||||||
self.optional_space(files)?;
|
self.optional_space(files)?;
|
||||||
}
|
}
|
||||||
|
let from = self.source_name(span);
|
||||||
|
let defaults = if automatic {
|
||||||
|
self.state.font_defaults()
|
||||||
|
} else {
|
||||||
|
self.font_defaults()
|
||||||
|
};
|
||||||
self.state
|
self.state
|
||||||
.fonts
|
.fonts
|
||||||
.configure_expansion(font, stretch, shrink, step, automatic)
|
.configure_expansion(font, &from, (stretch, shrink, step), automatic, defaults, files)
|
||||||
.map_err(|message| self.error(message, self.current))?;
|
.map_err(|message| self.error(message, self.current))?;
|
||||||
}
|
}
|
||||||
Some(Efcode) => {
|
Some(Efcode) => {
|
||||||
|
|||||||
@@ -38,10 +38,9 @@ impl Executor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn font_defaults(&mut self) -> FontIntegers {
|
pub(super) fn font_defaults(&mut self) -> FontIntegers {
|
||||||
FontIntegers {
|
self.reads.insert(Dependency::Parameter(Parameter::Defaulthyphenchar));
|
||||||
hyphen: self.read_parameter(Parameter::Defaulthyphenchar).width(),
|
self.reads.insert(Dependency::Parameter(Parameter::Defaultskewchar));
|
||||||
skew: self.read_parameter(Parameter::Defaultskewchar).width(),
|
self.state.font_defaults()
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn font_dimension_target(
|
pub(super) fn font_dimension_target(
|
||||||
|
|||||||
@@ -437,20 +437,17 @@ impl Executor {
|
|||||||
self.reads.insert(Dependency::TextFont);
|
self.reads.insert(Dependency::TextFont);
|
||||||
let start = b.vertical_start;
|
let start = b.vertical_start;
|
||||||
let span = b.span;
|
let span = b.span;
|
||||||
let mut trace = super::super::paragraph_trace::Tracer::new(
|
let mut records = Vec::new();
|
||||||
&self.state,
|
|
||||||
self.limits.tokens.saturating_sub(self.diagnostic_bytes),
|
|
||||||
);
|
|
||||||
let result = super::super::paragraph::finish(
|
let result = super::super::paragraph::finish(
|
||||||
b,
|
b,
|
||||||
&self.state,
|
&mut self.state,
|
||||||
final_widow,
|
final_widow,
|
||||||
&mut self.steps,
|
&mut self.steps,
|
||||||
self.limits.steps,
|
self.limits.steps,
|
||||||
&mut trace,
|
(self.limits.tokens.saturating_sub(self.diagnostic_bytes), &mut records),
|
||||||
self.line_break_cache.as_deref(),
|
self.line_break_cache.as_deref(),
|
||||||
|
files,
|
||||||
);
|
);
|
||||||
let records = trace.into_records();
|
|
||||||
if !records.is_empty() {
|
if !records.is_empty() {
|
||||||
self.reads.insert(Dependency::EscapeChar);
|
self.reads.insert(Dependency::EscapeChar);
|
||||||
self.reads.insert(Dependency::NewLineChar);
|
self.reads.insert(Dependency::NewLineChar);
|
||||||
|
|||||||
@@ -40,6 +40,8 @@ pub struct FontInstance {
|
|||||||
parameters: Vec<i32>,
|
parameters: Vec<i32>,
|
||||||
integers: FontIntegers,
|
integers: FontIntegers,
|
||||||
selector: CommandName,
|
selector: CommandName,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
expansion_origin: Option<(FontId, i32)>,
|
||||||
}
|
}
|
||||||
impl FontInstance {
|
impl FontInstance {
|
||||||
pub fn name(&self) -> &str {
|
pub fn name(&self) -> &str {
|
||||||
@@ -146,6 +148,12 @@ pub(super) struct FontExpansion {
|
|||||||
pub step: i32,
|
pub step: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||||
|
struct ExternalExpansion {
|
||||||
|
from: String,
|
||||||
|
variants: BTreeMap<i32, FontId>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||||
pub(crate) struct PdfFontSettings {
|
pub(crate) struct PdfFontSettings {
|
||||||
pub(crate) attributes: Vec<u8>,
|
pub(crate) attributes: Vec<u8>,
|
||||||
@@ -188,6 +196,8 @@ pub struct FontCatalog {
|
|||||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
expansion: BTreeMap<FontId, FontExpansion>,
|
expansion: BTreeMap<FontId, FontExpansion>,
|
||||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
|
external_expansion: BTreeMap<FontId, ExternalExpansion>,
|
||||||
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
expansion_codes: BTreeMap<FontId, BTreeMap<u8, u16>>,
|
expansion_codes: BTreeMap<FontId, BTreeMap<u8, u16>>,
|
||||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
pub(super) pdf_settings: BTreeMap<FontId, PdfFontSettings>,
|
pub(super) pdf_settings: BTreeMap<FontId, PdfFontSettings>,
|
||||||
@@ -216,6 +226,7 @@ impl FontCatalog {
|
|||||||
skew: -1,
|
skew: -1,
|
||||||
},
|
},
|
||||||
selector: CommandName::Control("nullfont".into()),
|
selector: CommandName::Control("nullfont".into()),
|
||||||
|
expansion_origin: None,
|
||||||
}],
|
}],
|
||||||
resources: Vec::new(),
|
resources: Vec::new(),
|
||||||
parameter_words: 7,
|
parameter_words: 7,
|
||||||
@@ -223,6 +234,7 @@ impl FontCatalog {
|
|||||||
protrusion: BTreeMap::new(),
|
protrusion: BTreeMap::new(),
|
||||||
auto_kern: BTreeMap::new(),
|
auto_kern: BTreeMap::new(),
|
||||||
expansion: BTreeMap::new(),
|
expansion: BTreeMap::new(),
|
||||||
|
external_expansion: BTreeMap::new(),
|
||||||
expansion_codes: BTreeMap::new(),
|
expansion_codes: BTreeMap::new(),
|
||||||
pdf_settings: BTreeMap::new(),
|
pdf_settings: BTreeMap::new(),
|
||||||
})
|
})
|
||||||
@@ -279,7 +291,9 @@ impl FontCatalog {
|
|||||||
// Canonical resource identity alone must not merge distinct names or
|
// Canonical resource identity alone must not merge distinct names or
|
||||||
// areas. Re-defining an older font does not make it the last loaded one.
|
// areas. Re-defining an older font does not make it the last loaded one.
|
||||||
for (index, f) in self.fonts.iter_mut().enumerate().skip(1) {
|
for (index, f) in self.fonts.iter_mut().enumerate().skip(1) {
|
||||||
if f.name == name && f.area == area {
|
// A font attached to an expansion family has an internal
|
||||||
|
// identity. A later explicit definition loads a separate font.
|
||||||
|
if f.name == name && f.area == area && f.expansion_origin.is_none() {
|
||||||
let m = f.metrics().unwrap();
|
let m = f.metrics().unwrap();
|
||||||
if m.requested_size(size).is_ok_and(|n| n == m.size_sp()) {
|
if m.requested_size(size).is_ok_and(|n| n == m.size_sp()) {
|
||||||
f.selector = selector;
|
f.selector = selector;
|
||||||
@@ -430,6 +444,7 @@ impl FontCatalog {
|
|||||||
parameters,
|
parameters,
|
||||||
integers: defaults,
|
integers: defaults,
|
||||||
selector,
|
selector,
|
||||||
|
expansion_origin: None,
|
||||||
});
|
});
|
||||||
self.parameter_words += count;
|
self.parameter_words += count;
|
||||||
Ok(id)
|
Ok(id)
|
||||||
@@ -523,12 +538,16 @@ impl FontCatalog {
|
|||||||
pub(super) fn configure_expansion(
|
pub(super) fn configure_expansion(
|
||||||
&mut self,
|
&mut self,
|
||||||
font: FontId,
|
font: FontId,
|
||||||
stretch: i32,
|
from: &str,
|
||||||
shrink: i32,
|
(stretch, shrink, step): (i32, i32, i32),
|
||||||
step: i32,
|
|
||||||
automatic: bool,
|
automatic: bool,
|
||||||
|
defaults: FontIntegers,
|
||||||
|
files: &mut impl SourceProvider,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
self.glyph_font(font)?;
|
self.glyph_font(font)?;
|
||||||
|
if self.font(font)?.expansion_origin.is_some() {
|
||||||
|
return Err("cannot configure expansion on an expanded font".into());
|
||||||
|
}
|
||||||
let step = step.clamp(0, 100);
|
let step = step.clamp(0, 100);
|
||||||
if step == 0 {
|
if step == 0 {
|
||||||
return Err("invalid font expansion step".into());
|
return Err("invalid font expansion step".into());
|
||||||
@@ -538,17 +557,110 @@ impl FontCatalog {
|
|||||||
if stretch == 0 && shrink == 0 {
|
if stretch == 0 && shrink == 0 {
|
||||||
return Err("invalid font expansion limits".into());
|
return Err("invalid font expansion limits".into());
|
||||||
}
|
}
|
||||||
if !automatic {
|
|
||||||
return Err("native font expansion requires autoexpand; external expanded metrics are unsupported".into());
|
|
||||||
}
|
|
||||||
let config = FontExpansion { stretch, shrink, step };
|
let config = FontExpansion { stretch, shrink, step };
|
||||||
if self.expansion.get(&font).is_some_and(|old| *old != config) {
|
let external = !automatic;
|
||||||
return Err("font has already been configured with different expansion settings".into());
|
if let Some(old) = self.expansion.get(&font) {
|
||||||
|
if *old != config || self.has_external_expansion(font) != external {
|
||||||
|
return Err("font has already been configured with different expansion settings".into());
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if external {
|
||||||
|
let mut variants = BTreeMap::new();
|
||||||
|
// The extremes are read when declared; intermediate sizes only
|
||||||
|
// when packing selects them for actual text.
|
||||||
|
for amount in [stretch, -shrink].into_iter().filter(|n| *n != 0) {
|
||||||
|
let variant = self.load_external_variant(font, amount, from, defaults, files)?;
|
||||||
|
variants.insert(amount, variant);
|
||||||
|
}
|
||||||
|
self.external_expansion.insert(font, ExternalExpansion { from: from.into(), variants });
|
||||||
}
|
}
|
||||||
self.expansion.insert(font, config);
|
self.expansion.insert(font, config);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn load_external_variant(
|
||||||
|
&mut self,
|
||||||
|
font: FontId,
|
||||||
|
amount: i32,
|
||||||
|
from: &str,
|
||||||
|
defaults: FontIntegers,
|
||||||
|
files: &mut impl SourceProvider,
|
||||||
|
) -> Result<FontId, String> {
|
||||||
|
let base = self.font(font)?;
|
||||||
|
let size = base.size_sp();
|
||||||
|
let name = format!("{}{amount:+}", base.name);
|
||||||
|
let variant = if let Some(index) = self.fonts.iter().position(|f| {
|
||||||
|
f.name == name && f.size_sp() == size && f.expansion_origin.is_none()
|
||||||
|
}) {
|
||||||
|
FontId(index as u32)
|
||||||
|
} else {
|
||||||
|
self.check_font_capacity()?;
|
||||||
|
let filename = format!("{name}.tfm");
|
||||||
|
let (loaded, metrics) = Self::read_tfm(files, &filename, from, FontSize::At(size))
|
||||||
|
.map_err(|error| format!("cannot load expanded font {filename}: {error}"))?;
|
||||||
|
self.insert_font(
|
||||||
|
(&name, ""),
|
||||||
|
loaded,
|
||||||
|
metrics,
|
||||||
|
CommandName::Control(String::new()),
|
||||||
|
defaults,
|
||||||
|
None,
|
||||||
|
)?
|
||||||
|
};
|
||||||
|
self.fonts[variant.index() as usize].expansion_origin = Some((font, amount));
|
||||||
|
Ok(variant)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn external_limit(
|
||||||
|
&self,
|
||||||
|
font: FontId,
|
||||||
|
amount: i32,
|
||||||
|
) -> Result<Option<&TfmMetrics>, String> {
|
||||||
|
let Some(expansion) = self.external_expansion.get(&font) else {
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let variant = expansion.variants.get(&amount).ok_or("missing external expansion limit")?;
|
||||||
|
Ok(Some(self.glyph_font(*variant)?.metrics()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn expansion_face(
|
||||||
|
&mut self,
|
||||||
|
font: &Arc<NativeFont>,
|
||||||
|
amount: i32,
|
||||||
|
defaults: FontIntegers,
|
||||||
|
files: &mut impl SourceProvider,
|
||||||
|
) -> Result<Arc<NativeFont>, String> {
|
||||||
|
let Some(external) = self.external_expansion.get(&font.id) else {
|
||||||
|
return Ok(Arc::new(NativeFont {
|
||||||
|
expansion: amount,
|
||||||
|
..font.as_ref().clone()
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
let variant = if let Some(variant) = external.variants.get(&amount) {
|
||||||
|
*variant
|
||||||
|
} else {
|
||||||
|
let from = external.from.clone();
|
||||||
|
let variant = self.load_external_variant(font.id, amount, &from, defaults, files)?;
|
||||||
|
self.external_expansion.get_mut(&font.id).unwrap().variants.insert(amount, variant);
|
||||||
|
variant
|
||||||
|
};
|
||||||
|
Ok(self.glyph_font(variant)?.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn diagnostic_font(&self, font: FontId, expansion: i32) -> Result<(String, i32), String> {
|
||||||
|
let f = self.font(font)?;
|
||||||
|
if let Some((base, amount)) = f.expansion_origin {
|
||||||
|
Ok((self.font(base)?.identifier_text(), amount))
|
||||||
|
} else {
|
||||||
|
Ok((f.identifier_text(), expansion))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn has_external_expansion(&self, font: FontId) -> bool {
|
||||||
|
self.external_expansion.contains_key(&font)
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) fn has_expansion(&self) -> bool {
|
pub(super) fn has_expansion(&self) -> bool {
|
||||||
!self.expansion.is_empty()
|
!self.expansion.is_empty()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,9 +8,9 @@ use std::{
|
|||||||
sync::{Arc, Mutex, OnceLock, Weak},
|
sync::{Arc, Mutex, OnceLock, Weak},
|
||||||
};
|
};
|
||||||
|
|
||||||
const SCHEMA: u32 = 51;
|
const SCHEMA: u32 = 52;
|
||||||
const COMPATIBLE_SCHEMAS: [u32; 20] = [
|
const COMPATIBLE_SCHEMAS: [u32; 21] = [
|
||||||
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, SCHEMA,
|
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, SCHEMA,
|
||||||
];
|
];
|
||||||
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
|
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
|
||||||
|
|
||||||
|
|||||||
@@ -951,8 +951,9 @@ fn pack(
|
|||||||
last: bool,
|
last: bool,
|
||||||
terminal_marker: bool,
|
terminal_marker: bool,
|
||||||
ends_in_pre_break: bool,
|
ends_in_pre_break: bool,
|
||||||
state: &State,
|
state: &mut State,
|
||||||
span: Span,
|
span: Span,
|
||||||
|
files: &mut impl SourceProvider,
|
||||||
) -> Result<(Paragraph, NativeBox, super::marks::MigratingMaterial, bool), String> {
|
) -> Result<(Paragraph, NativeBox, super::marks::MigratingMaterial, bool), String> {
|
||||||
let left = p[&Parameter::Leftskip].glue();
|
let left = p[&Parameter::Leftskip].glue();
|
||||||
let mut material = Vec::new();
|
let mut material = Vec::new();
|
||||||
@@ -986,7 +987,7 @@ fn pack(
|
|||||||
));
|
));
|
||||||
let (mut material, adjustments) = super::marks::extract(material);
|
let (mut material, adjustments) = super::marks::extract(material);
|
||||||
if p[&Parameter::Pdfadjustspacing].width() > 0 && state.fonts.has_expansion() {
|
if p[&Parameter::Pdfadjustspacing].width() > 0 && state.fonts.has_expansion() {
|
||||||
expansion::pack(state, &mut material, target)?;
|
expansion::pack(state, &mut material, target, files)?;
|
||||||
}
|
}
|
||||||
let shrinking = material.iter().map(width).sum::<i64>() > target;
|
let shrinking = material.iter().map(width).sum::<i64>() > target;
|
||||||
let mut b = super::boxes::hpack(
|
let mut b = super::boxes::hpack(
|
||||||
@@ -1057,12 +1058,13 @@ fn pre_display_line_size(
|
|||||||
}
|
}
|
||||||
pub(super) fn finish(
|
pub(super) fn finish(
|
||||||
mut b: Builder,
|
mut b: Builder,
|
||||||
state: &State,
|
state: &mut State,
|
||||||
final_widow: Parameter,
|
final_widow: Parameter,
|
||||||
steps: &mut usize,
|
steps: &mut usize,
|
||||||
step_limit: usize,
|
step_limit: usize,
|
||||||
trace: &mut super::paragraph_trace::Tracer<'_>,
|
(trace_limit, records): (usize, &mut Vec<super::ParagraphTrace>),
|
||||||
cache: Option<&LineBreakCache>,
|
cache: Option<&LineBreakCache>,
|
||||||
|
files: &mut impl SourceProvider,
|
||||||
) -> Result<NativeParagraph, String> {
|
) -> Result<NativeParagraph, String> {
|
||||||
b.finish_text(true, state)?;
|
b.finish_text(true, state)?;
|
||||||
if b.nodes.last().is_some_and(|n| {
|
if b.nodes.last().is_some_and(|n| {
|
||||||
@@ -1113,42 +1115,43 @@ pub(super) fn finish(
|
|||||||
return Err("unsupported infinite paragraph background glue".into());
|
return Err("unsupported infinite paragraph background glue".into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let mut work = 0;
|
let mut trace = super::paragraph_trace::Tracer::new(state, trace_limit);
|
||||||
let mut missing_glyphs = Vec::new();
|
let mut missing_glyphs = Vec::new();
|
||||||
let mut result = None;
|
let search = (|| {
|
||||||
let mut selected_pass = 0;
|
let mut work = 0;
|
||||||
for pass in 0..3 {
|
for pass in 0..3 {
|
||||||
if pass == 0 && parameters[&Parameter::Pretolerance].width() < 0 {
|
if pass == 0 && parameters[&Parameter::Pretolerance].width() < 0 {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if pass == 1 {
|
if pass == 1 {
|
||||||
add_hyphens(
|
add_hyphens(
|
||||||
&mut b.nodes,
|
&mut b.nodes,
|
||||||
|
state,
|
||||||
|
b.initial_language,
|
||||||
|
&mut missing_glyphs,
|
||||||
|
steps,
|
||||||
|
step_limit,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
trace.pass(pass, parameters[&Parameter::Pretolerance].width() >= 0)?;
|
||||||
|
if let Some(path) = break_cache::solve(
|
||||||
|
&b.nodes,
|
||||||
|
¶meters,
|
||||||
state,
|
state,
|
||||||
b.initial_language,
|
shape,
|
||||||
&mut missing_glyphs,
|
pass,
|
||||||
steps,
|
&mut work,
|
||||||
step_limit,
|
b.previous_lines,
|
||||||
)?;
|
&mut trace,
|
||||||
|
cache,
|
||||||
|
)? {
|
||||||
|
return Ok((path, pass));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
trace.pass(pass, parameters[&Parameter::Pretolerance].width() >= 0)?;
|
Err(String::from("native paragraph has no legal break sequence"))
|
||||||
if let Some(path) = break_cache::solve(
|
})();
|
||||||
&b.nodes,
|
*records = trace.into_records();
|
||||||
¶meters,
|
let (path, selected_pass) = search?;
|
||||||
state,
|
|
||||||
shape,
|
|
||||||
pass,
|
|
||||||
&mut work,
|
|
||||||
b.previous_lines,
|
|
||||||
trace,
|
|
||||||
cache,
|
|
||||||
)? {
|
|
||||||
result = Some(path);
|
|
||||||
selected_pass = pass;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let path = result.ok_or("native paragraph has no legal break sequence")?;
|
|
||||||
let mut start = 0;
|
let mut start = 0;
|
||||||
let mut post = None;
|
let mut post = None;
|
||||||
let mut lines = Vec::new();
|
let mut lines = Vec::new();
|
||||||
@@ -1174,7 +1177,7 @@ pub(super) fn finish(
|
|||||||
true,
|
true,
|
||||||
point.zero_tail,
|
point.zero_tail,
|
||||||
);
|
);
|
||||||
let dimensions = geometry(¶meters, shape, i + b.previous_lines);
|
let dimensions = geometry(¶meters, state.paragraph_shape(), i + b.previous_lines);
|
||||||
let ends_in_pre_break = point.pre_break.is_some_and(|index| {
|
let ends_in_pre_break = point.pre_break.is_some_and(|index| {
|
||||||
matches!(&b.nodes[index], TextNode::Discretionary { pre_break, .. } if !pre_break.is_empty())
|
matches!(&b.nodes[index], TextNode::Discretionary { pre_break, .. } if !pre_break.is_empty())
|
||||||
});
|
});
|
||||||
@@ -1190,6 +1193,7 @@ pub(super) fn finish(
|
|||||||
ends_in_pre_break,
|
ends_in_pre_break,
|
||||||
state,
|
state,
|
||||||
b.span,
|
b.span,
|
||||||
|
files,
|
||||||
)?;
|
)?;
|
||||||
packed_diagnostic.push(line_box.diagnostic_eligible);
|
packed_diagnostic.push(line_box.diagnostic_eligible);
|
||||||
packed_shrinking.push(shrinking);
|
packed_shrinking.push(shrinking);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
//! pdfTeX expansion uses each live font's stretch and shrink limits. Paragraph
|
//! pdfTeX expansion uses each live font's stretch and shrink limits. Paragraph
|
||||||
//! search budgets the quantization error; packing applies a font to each glyph.
|
//! search budgets the quantization error; packing applies a font to each glyph.
|
||||||
use super::{State, TextNode, metrics};
|
use super::{FontId, SourceProvider, State, TextNode, metrics};
|
||||||
use crate::{math_engine_tex::MathItem, native_font::NativeFont, pdf_device};
|
use crate::{math_engine_tex::MathItem, native_font::NativeFont, pdf_device};
|
||||||
use std::{collections::BTreeMap, ops::AddAssign, sync::Arc};
|
use std::{collections::BTreeMap, ops::AddAssign, sync::Arc};
|
||||||
|
|
||||||
@@ -94,21 +94,34 @@ fn capacity(
|
|||||||
at: usize,
|
at: usize,
|
||||||
limits: Option<&mut Limits>,
|
limits: Option<&mut Limits>,
|
||||||
) -> Result<Capacity, String> {
|
) -> Result<Capacity, String> {
|
||||||
let measure = |font: &NativeFont, slot, width, kern| {
|
let measure = |font: &NativeFont, slot: u8, width, right: Option<u8>| {
|
||||||
let Some(config) = state.fonts.expansion(font.id) else {
|
let Some(config) = state.fonts.expansion(font.id) else {
|
||||||
return Capacity::default();
|
return Ok(Capacity::default());
|
||||||
};
|
};
|
||||||
if font.expansion != 0 {
|
if font.expansion != 0 {
|
||||||
return Capacity::default();
|
return Ok(Capacity::default());
|
||||||
}
|
}
|
||||||
|
let limit_width = |amount| -> Result<i64, String> {
|
||||||
|
if amount == 0 {
|
||||||
|
return Ok(width);
|
||||||
|
}
|
||||||
|
let Some(external) = state.fonts.external_limit(font.id, amount)? else {
|
||||||
|
return Ok(pdf_device::magnify(width, 1000 + amount));
|
||||||
|
};
|
||||||
|
let left = char::from(slot);
|
||||||
|
Ok(match right {
|
||||||
|
Some(right) => external.kern(left, char::from(right)),
|
||||||
|
None => external.width(left),
|
||||||
|
})
|
||||||
|
};
|
||||||
let code = state.fonts.expansion_code(font.id, slot);
|
let code = state.fonts.expansion_code(font.id, slot);
|
||||||
let scale = |value| pdf_device::magnify(value, code);
|
let scale = |value: i64| {
|
||||||
let stretch = pdf_device::magnify(width, 1000 + config.stretch) - width;
|
pdf_device::magnify(if right.is_some() { value } else { value.max(0) }, code)
|
||||||
let shrink = width - pdf_device::magnify(width, 1000 - config.shrink);
|
};
|
||||||
Capacity {
|
Ok(Capacity {
|
||||||
stretch: scale(if kern { stretch } else { stretch.max(0) }),
|
stretch: scale(limit_width(config.stretch)? - width),
|
||||||
shrink: scale(if kern { shrink } else { shrink.max(0) }),
|
shrink: scale(width - limit_width(-config.shrink)?),
|
||||||
}
|
})
|
||||||
};
|
};
|
||||||
if let Some(glyph) = character(&nodes[at]) {
|
if let Some(glyph) = character(&nodes[at]) {
|
||||||
if glyph.font.expansion == 0
|
if glyph.font.expansion == 0
|
||||||
@@ -117,7 +130,7 @@ fn capacity(
|
|||||||
{
|
{
|
||||||
limits.include(config)?;
|
limits.include(config)?;
|
||||||
}
|
}
|
||||||
return Ok(measure(glyph.font, glyph.slot, glyph.width, false));
|
return measure(glyph.font, glyph.slot, glyph.width, None);
|
||||||
}
|
}
|
||||||
if let TextNode::Kern {
|
if let TextNode::Kern {
|
||||||
width,
|
width,
|
||||||
@@ -132,7 +145,7 @@ fn capacity(
|
|||||||
// A boundary kern and a TFM kern between two characters have the same
|
// A boundary kern and a TFM kern between two characters have the same
|
||||||
// node type. Only use the font program's actual kerning pair here.
|
// node type. Only use the font program's actual kerning pair here.
|
||||||
if kern == i64::from(width) {
|
if kern == i64::from(width) {
|
||||||
return Ok(measure(left.font, left.slot, kern, true));
|
return measure(left.font, left.slot, kern, Some(right.slot));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(Capacity::default())
|
Ok(Capacity::default())
|
||||||
@@ -213,11 +226,11 @@ impl Search {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn glyph_ratio(state: &State, glyph: &Character<'_>, line_ratio: i32) -> i32 {
|
fn slot_ratio(state: &State, font: &NativeFont, slot: u8, line_ratio: i32) -> i32 {
|
||||||
let Some(config) = state.fonts.expansion(glyph.font.id) else {
|
let Some(config) = state.fonts.expansion(font.id) else {
|
||||||
return 0;
|
return 0;
|
||||||
};
|
};
|
||||||
if glyph.font.expansion != 0 {
|
if font.expansion != 0 {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
let max = if line_ratio < 0 {
|
let max = if line_ratio < 0 {
|
||||||
@@ -225,19 +238,81 @@ fn glyph_ratio(state: &State, glyph: &Character<'_>, line_ratio: i32) -> i32 {
|
|||||||
} else {
|
} else {
|
||||||
config.stretch
|
config.stretch
|
||||||
};
|
};
|
||||||
let code = state.fonts.expansion_code(glyph.font.id, glyph.slot);
|
let code = state.fonts.expansion_code(font.id, slot);
|
||||||
let magnitude = i64::from(line_ratio.abs()) * i64::from(code) * i64::from(max) / 1_000_000;
|
let magnitude = i64::from(line_ratio.abs()) * i64::from(code) * i64::from(max) / 1_000_000;
|
||||||
let step = i64::from(config.step);
|
let step = i64::from(config.step);
|
||||||
(magnitude + step / 2).div_euclid(step) as i32 * config.step * line_ratio.signum()
|
(magnitude + step / 2).div_euclid(step) as i32 * config.step * line_ratio.signum()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn pack(state: &State, material: &mut [TextNode], target: i64) -> Result<(), String> {
|
#[derive(Default)]
|
||||||
|
struct PackingFonts(BTreeMap<(FontId, i32), Arc<NativeFont>>);
|
||||||
|
|
||||||
|
impl PackingFonts {
|
||||||
|
fn select(
|
||||||
|
&mut self,
|
||||||
|
state: &mut State,
|
||||||
|
font: &Arc<NativeFont>,
|
||||||
|
amount: i32,
|
||||||
|
files: &mut impl SourceProvider,
|
||||||
|
) -> Result<Arc<NativeFont>, String> {
|
||||||
|
use std::collections::btree_map::Entry;
|
||||||
|
let selected = match self.0.entry((font.id, amount)) {
|
||||||
|
Entry::Occupied(entry) => entry.into_mut(),
|
||||||
|
Entry::Vacant(entry) => {
|
||||||
|
let defaults = state.font_defaults();
|
||||||
|
entry.insert(state.fonts.expansion_face(font, amount, defaults, files)?)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(selected.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn external_margin(
|
||||||
|
&mut self,
|
||||||
|
state: &mut State,
|
||||||
|
font: FontId,
|
||||||
|
slot: u8,
|
||||||
|
right: bool,
|
||||||
|
ratio: i32,
|
||||||
|
files: &mut impl SourceProvider,
|
||||||
|
) -> Result<Option<(i32, FontId)>, String> {
|
||||||
|
if !state.fonts.has_external_expansion(font) {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let base = state.fonts.glyph_font(font)?.clone();
|
||||||
|
let amount = slot_ratio(state, &base, slot, ratio);
|
||||||
|
if amount == 0 {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let face = self.select(state, &base, amount, files)?;
|
||||||
|
let code = state.fonts.protrusion_code(font, slot, right);
|
||||||
|
let quad = i64::from(state.fonts.font(face.id)?.quad());
|
||||||
|
Ok(Some((-pdf_device::magnify(quad, code) as i32, face.id)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn pack(
|
||||||
|
state: &mut State,
|
||||||
|
material: &mut [TextNode],
|
||||||
|
target: i64,
|
||||||
|
files: &mut impl SourceProvider,
|
||||||
|
) -> Result<(), String> {
|
||||||
let (natural, stretch, _) = metrics(material, Default::default(), Default::default());
|
let (natural, stretch, _) = metrics(material, Default::default(), Default::default());
|
||||||
let shortfall = target - natural;
|
let shortfall = target - natural;
|
||||||
if shortfall == 0 || (shortfall > 0 && stretch[1..].iter().any(|width| *width != 0)) {
|
if shortfall == 0 || (shortfall > 0 && stretch[1..].iter().any(|width| *width != 0)) {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
let capacity = sum(state, material, None)?;
|
let mut fonts = PackingFonts::default();
|
||||||
|
let mut capacity = sum(state, material, None)?;
|
||||||
|
for node in material.iter() {
|
||||||
|
let TextNode::MarginKern { width, right, font, slot } = *node else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for (ratio, limit) in [(1000, &mut capacity.stretch), (-1000, &mut capacity.shrink)] {
|
||||||
|
if let Some((expanded, _)) = fonts.external_margin(state, font, slot, right, ratio, files)? {
|
||||||
|
*limit += i64::from(expanded) - i64::from(width);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
let available = if shortfall < 0 {
|
let available = if shortfall < 0 {
|
||||||
capacity.shrink
|
capacity.shrink
|
||||||
} else {
|
} else {
|
||||||
@@ -248,54 +323,63 @@ pub(super) fn pack(state: &State, material: &mut [TextNode], target: i64) -> Res
|
|||||||
}
|
}
|
||||||
let ratio =
|
let ratio =
|
||||||
pdf_device::divide_scaled(shortfall.clamp(-available, available), available, 3).0 as i32;
|
pdf_device::divide_scaled(shortfall.clamp(-available, available), available, 3).0 as i32;
|
||||||
let mut fonts = BTreeMap::new();
|
|
||||||
for i in 0..material.len() {
|
for i in 0..material.len() {
|
||||||
if let TextNode::Kern {
|
if let TextNode::MarginKern { ref mut width, right, ref mut font, slot } = material[i] {
|
||||||
width,
|
if let Some((expanded, selected)) = fonts.external_margin(state, *font, slot, right, ratio, files)? {
|
||||||
explicit: false,
|
*width = expanded;
|
||||||
} = material[i]
|
*font = selected;
|
||||||
&& let Some((left, right)) = pair(material, i)
|
|
||||||
&& let kern = left
|
|
||||||
.font
|
|
||||||
.metrics()
|
|
||||||
.kern(char::from(left.slot), char::from(right.slot))
|
|
||||||
&& kern == i64::from(width)
|
|
||||||
{
|
|
||||||
let amount = glyph_ratio(state, &left, ratio);
|
|
||||||
if let TextNode::Kern { width, .. } = &mut material[i] {
|
|
||||||
*width = i32::try_from(pdf_device::magnify(kern, 1000 + amount))
|
|
||||||
.map_err(|_| "expanded native font kern exceeds the scaled point range")?;
|
|
||||||
}
|
}
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
}
|
let Some(glyph) = character(&material[i]) else {
|
||||||
for node in material {
|
|
||||||
let Some(glyph) = character(node) else {
|
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
let amount = glyph_ratio(state, &glyph, ratio);
|
let amount = slot_ratio(state, glyph.font, glyph.slot, ratio);
|
||||||
if amount == 0 {
|
if amount == 0 {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let face = fonts.entry((glyph.font.id, amount)).or_insert_with(|| {
|
let face = fonts.select(state, glyph.font, amount, files)?;
|
||||||
Arc::new(NativeFont {
|
let character = char::from(glyph.slot);
|
||||||
expansion: amount,
|
let external = face.expansion == 0;
|
||||||
..glyph.font.as_ref().clone()
|
if external && !face.has_slot(glyph.slot) {
|
||||||
})
|
return Err(format!("expanded font {} has no TFM slot {}", face.name, glyph.slot));
|
||||||
});
|
}
|
||||||
let TextNode::Glyph { glyph, .. } = node else {
|
// The external left font has already changed when pdfTeX checks
|
||||||
|
// the pair for substitution. The two font identities differ, so
|
||||||
|
// the original kern remains even though the limits affect capacity.
|
||||||
|
if !external
|
||||||
|
&& let Some(TextNode::Kern { width, explicit: false }) = material.get(i + 1)
|
||||||
|
&& let Some((left, right)) = pair(material, i + 1)
|
||||||
|
{
|
||||||
|
let original = left.font.metrics().kern(character, char::from(right.slot));
|
||||||
|
if original == i64::from(*width)
|
||||||
|
&& let TextNode::Kern { width, .. } = &mut material[i + 1]
|
||||||
|
{
|
||||||
|
*width = i32::try_from(pdf_device::magnify(original, 1000 + amount))
|
||||||
|
.map_err(|_| "expanded native font kern exceeds the scaled point range")?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let TextNode::Glyph { font, glyph, .. } = &mut material[i] else {
|
||||||
unreachable!()
|
unreachable!()
|
||||||
};
|
};
|
||||||
glyph.width = pdf_device::magnify(glyph.width, 1000 + amount);
|
*font = face.id;
|
||||||
glyph.italic = pdf_device::magnify(glyph.italic, 1000 + amount);
|
if external {
|
||||||
let geometry = glyph
|
glyph.width = face.metrics().width(character);
|
||||||
.math_geometry
|
glyph.height = face.metrics().height(character);
|
||||||
.as_mut()
|
glyph.depth = face.metrics().depth(character);
|
||||||
.expect("native character geometry");
|
glyph.italic = face.metrics().italic(character);
|
||||||
|
} else {
|
||||||
|
glyph.width = pdf_device::magnify(glyph.width, 1000 + amount);
|
||||||
|
glyph.italic = pdf_device::magnify(glyph.italic, 1000 + amount);
|
||||||
|
}
|
||||||
|
let geometry = glyph.math_geometry.as_mut().expect("native character geometry");
|
||||||
geometry.metrics.width = glyph.width;
|
geometry.metrics.width = glyph.width;
|
||||||
|
geometry.metrics.height = glyph.height;
|
||||||
|
geometry.metrics.depth = glyph.depth;
|
||||||
let MathItem::NativeGlyph { font, .. } = &mut geometry.items[0].item else {
|
let MathItem::NativeGlyph { font, .. } = &mut geometry.items[0].item else {
|
||||||
unreachable!()
|
unreachable!()
|
||||||
};
|
};
|
||||||
*font = face.clone();
|
*font = face;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -1685,6 +1685,13 @@ impl State {
|
|||||||
pub fn group_depth(&self) -> usize {
|
pub fn group_depth(&self) -> usize {
|
||||||
self.groups.len()
|
self.groups.len()
|
||||||
}
|
}
|
||||||
|
pub(super) fn font_defaults(&self) -> super::FontIntegers {
|
||||||
|
super::FontIntegers {
|
||||||
|
hyphen: self.parameter(Parameter::Defaulthyphenchar).width(),
|
||||||
|
skew: self.parameter(Parameter::Defaultskewchar).width(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn fingerprint(&self) -> u64 {
|
pub fn fingerprint(&self) -> u64 {
|
||||||
let mut hash = FingerprintHasher::default();
|
let mut hash = FingerprintHasher::default();
|
||||||
self.hash(&mut hash);
|
self.hash(&mut hash);
|
||||||
|
|||||||
Reference in new issue
Block a user