Add inline box raise and makebox alignment

This commit is contained in:
gloamxun committed 2026-10-19 12:58:21 +08:00
1 parent 337eaa1778
commit 32b0064e5f
11 files changed
+425 -73

No files matched your search

+143 -27
View File
@@ -1002,6 +1002,65 @@ fn box_font_id_variant(
}
}
fn flat_runs_width(
runs: &[Run],
font_repo: &box_font::Repo<BoxFont>,
latin_font_ids: &FontFamily<box_font::Id>,
monospace_font_ids: Option<&FontFamily<box_font::Id>>,
sans_font_ids: Option<&FontFamily<box_font::Id>>,
small_latin_font_ids: &FontFamily<box_font::Id>,
small_monospace_font_ids: Option<&FontFamily<box_font::Id>>,
small_sans_font_ids: Option<&FontFamily<box_font::Id>>,
cjk_font_id: Option<box_font::Id>,
) -> common::Scaled {
let mut width = common::Scaled::ZERO;
for run in runs {
if let Some(rule) = &run.rule {
width = common::Scaled(width.0.saturating_add(rule.width.0));
continue;
}
if let Some(kern) = run.kern {
width = common::Scaled(width.0.saturating_add(kern.0));
continue;
}
if let Some(glue) = &run.glue {
width = common::Scaled(width.0.saturating_add(glue.width.0));
continue;
}
for character in run.text.chars() {
let mut glyph_character = character;
let mut font_id = paragraph_font_id(
latin_font_ids,
cjk_font_id,
monospace_font_ids,
sans_font_ids,
run,
character,
);
if run.small_caps && character.is_lowercase() {
let mut upper = character.to_uppercase();
if let Some(upper_character) = upper.next()
&& upper.next().is_none()
{
glyph_character = upper_character;
let small_family = if run.monospace {
small_monospace_font_ids.unwrap_or(small_latin_font_ids)
} else if run.sans {
small_sans_font_ids.unwrap_or(small_latin_font_ids)
} else {
small_latin_font_ids
};
font_id = box_font_id_variant(small_family, run.bold, run.italic);
}
}
if let Some(glyph_width) = font_repo.get(font_id).width(glyph_character) {
width = common::Scaled(width.0.saturating_add(glyph_width.0));
}
}
}
width
}
fn paragraph_font_id(
latin: &FontFamily<box_font::Id>,
cjk: Option<box_font::Id>,
@@ -1025,48 +1084,84 @@ fn paragraph_font_id(
}
#[allow(clippy::too_many_arguments)]
const INLINE_BOX_START: char = '\u{F1000}';
const INLINE_BOX_END: char = '\u{F1001}';
#[allow(clippy::too_many_arguments)]
fn flatten_inline_boxes(
runs: &[Run],
font_repo: &mut box_font::Repo<BoxFont>,
latin_font_ids: &FontFamily<box_font::Id>,
monospace_font_ids: Option<&FontFamily<box_font::Id>>,
sans_font_ids: Option<&FontFamily<box_font::Id>>,
small_latin_font_ids: &FontFamily<box_font::Id>,
small_monospace_font_ids: Option<&FontFamily<box_font::Id>>,
small_sans_font_ids: Option<&FontFamily<box_font::Id>>,
cjk_font_id: Option<box_font::Id>,
size: u8,
markers: &mut HashMap<char, Option<common::Scaled>>,
next_marker: &mut u32,
inside: bool,
) -> Vec<Run> {
let mut flattened = Vec::new();
for run in runs {
if let Some(inline) = &run.box_run {
let mut start = run.clone();
start.box_run = None;
start.text = INLINE_BOX_START.to_string();
start.math = None;
start.kern = None;
start.glue = None;
start.penalty = None;
start.rule = None;
flattened.push(start);
flattened.extend(flatten_inline_boxes(
let mut content = flatten_inline_boxes(
&inline.runs,
font_repo,
latin_font_ids,
monospace_font_ids,
sans_font_ids,
small_latin_font_ids,
small_monospace_font_ids,
small_sans_font_ids,
cjk_font_id,
size,
markers,
next_marker,
true,
));
let mut end = run.clone();
end.box_run = None;
end.text = INLINE_BOX_END.to_string();
end.math = None;
end.kern = None;
end.glue = None;
end.penalty = None;
end.rule = None;
flattened.push(end);
);
let content_width = flat_runs_width(
&content,
font_repo,
latin_font_ids,
monospace_font_ids,
sans_font_ids,
small_latin_font_ids,
small_monospace_font_ids,
small_sans_font_ids,
cjk_font_id,
);
let (left_pad, right_pad) = match inline.width {
Some(width) if width > content_width => {
let extra = width.0 - content_width.0;
let left = match inline.align {
texrra_core::document::InlineBoxAlign::Left => 0,
texrra_core::document::InlineBoxAlign::Center => extra / 2,
texrra_core::document::InlineBoxAlign::Right => extra,
};
(common::Scaled(left), common::Scaled(extra - left))
}
_ => (common::Scaled::ZERO, common::Scaled::ZERO),
};
let start_char = char::from_u32(*next_marker)
.expect("inline box markers stay inside a Unicode private use plane");
*next_marker += 1;
let end_char = char::from_u32(*next_marker)
.expect("inline box markers stay inside a Unicode private use plane");
*next_marker += 1;
markers.insert(start_char, Some(inline.raise));
markers.insert(end_char, None);
flattened.push(Run::plain(start_char.to_string()));
if left_pad.0 > 0 {
let mut pad = Run::plain(String::new());
pad.kern = Some(left_pad);
flattened.push(pad);
}
flattened.extend(content.drain(..));
if right_pad.0 > 0 {
let mut pad = Run::plain(String::new());
pad.kern = Some(right_pad);
flattened.push(pad);
}
flattened.push(Run::plain(end_char.to_string()));
continue;
}
if !inside {
@@ -1194,13 +1289,21 @@ fn boxworks_line_break(
if let Some(sans) = &small_sans_font_ids {
register_style_ids(&mut style_by_font, sans, true, false, small_size);
}
let mut inline_markers: HashMap<char, Option<common::Scaled>> = HashMap::new();
let mut next_inline_marker = 0xF2000_u32;
let flattened = flatten_inline_boxes(
runs,
&mut font_repo,
&latin_font_ids,
monospace_font_ids.as_ref(),
sans_font_ids.as_ref(),
&small_latin_font_ids,
small_monospace_font_ids.as_ref(),
small_sans_font_ids.as_ref(),
cjk_font_id,
size,
&mut inline_markers,
&mut next_inline_marker,
false,
);
let mut horizontal = Vec::new();
@@ -1259,7 +1362,7 @@ fn boxworks_line_break(
previous_font_id = None;
}
for character in run.text.chars() {
if character == INLINE_BOX_START || character == INLINE_BOX_END {
if inline_markers.contains_key(&character) {
horizontal.push(
ds::Char {
char: character,
@@ -1401,6 +1504,7 @@ fn boxworks_line_break(
.break_line(&mut vertical, &mut horizontal);
let mut lines = Vec::new();
let mut raise_stack: Vec<common::Scaled> = Vec::new();
for item in vertical {
let ds::Vertical::HBox(line_box) = item else {
continue;
@@ -1456,16 +1560,25 @@ fn boxworks_line_break(
for item in &line_box.list {
match item {
ds::Horizontal::Char(character) => {
if character.font == null_font_id
&& (character.char == INLINE_BOX_START || character.char == INLINE_BOX_END)
{
if let Some(marker) = inline_markers.get(&character.char) {
match marker {
Some(raise) => {
let current = raise_stack.last().copied().unwrap_or_default();
raise_stack.push(common::Scaled(current.0.saturating_add(raise.0)));
}
None => {
raise_stack.pop();
}
}
continue;
}
let y_offset = raise_stack.last().copied().unwrap_or_default();
if let Some(rule) = rules.get(&character.char) {
line_items.push(text_layout::LineItem::Rule {
width: rule.width,
raise: rule.raise,
height: rule.height,
y_offset,
});
} else {
let (bold, italic, monospace, sans, glyph_size) = style_by_font
@@ -1479,6 +1592,7 @@ fn boxworks_line_break(
monospace,
sans,
font_size: glyph_size,
y_offset,
});
}
}
@@ -2364,6 +2478,8 @@ pub(super) fn render_pdf(
sans: false,
small_caps: false,
y_offset: None,
}];
document.push(paragraph(
&heading,
+22 -9
View File
@@ -871,6 +871,7 @@ fn layout_framed_runs(
width: rule.width,
raise: rule.raise,
height: rule.height,
y_offset: run.y_offset.unwrap_or_default(),
});
width += Mm::from(scaled_units_to_mm(i64::from(rule.width.0)));
let above = i64::from(rule.raise.0) + i64::from(rule.height.0);
@@ -945,6 +946,7 @@ fn layout_framed_runs(
monospace: run.monospace,
sans: run.sans,
font_size: glyph_size,
y_offset: run.y_offset.unwrap_or_default(),
});
}
}
@@ -1960,6 +1962,7 @@ pub(super) fn build_positioned_pages(
width: rule_width,
raise: common::Scaled::ZERO,
height: *height,
y_offset: common::Scaled::ZERO,
}],
pre_display_size: None,
};
@@ -2690,18 +2693,26 @@ pub(super) fn text_line_metrics_scaled(
cjk_family: Option<FontFamily<fonts::Font>>,
mono_family: Option<FontFamily<fonts::Font>>,
sans_family: Option<FontFamily<fonts::Font>>,
font_size: u8,
_font_size: u8,
) -> (i64, i64) {
let mut ascent_mm = Mm::from(0.0);
let mut descent_mm = Mm::from(0.0);
for item in &line.items {
if let text_layout::LineItem::Rule { raise, height, .. } = item {
let above = i64::from(raise.0) + i64::from(height.0);
if let text_layout::LineItem::Rule {
raise,
height,
y_offset,
..
} = item
{
let above = i64::from(raise.0) + i64::from(height.0) + i64::from(y_offset.0);
if above > 0 {
ascent_mm = ascent_mm.max(Mm::from(scaled_units_to_mm(above)));
}
if raise.0 < 0 {
descent_mm = descent_mm.max(Mm::from(scaled_units_to_mm(i64::from(-raise.0))));
if raise.0 + y_offset.0 < 0 {
descent_mm = descent_mm.max(Mm::from(scaled_units_to_mm(i64::from(
-raise.0 - y_offset.0,
))));
}
continue;
}
@@ -2712,6 +2723,7 @@ pub(super) fn text_line_metrics_scaled(
monospace,
sans,
font_size: glyph_size,
y_offset,
} = item
else {
continue;
@@ -2738,10 +2750,11 @@ pub(super) fn text_line_metrics_scaled(
}
}
let font = style.font(font_cache);
let glyph_height = font.glyph_height(font_size);
ascent_mm = ascent_mm.max(glyph_height);
descent_mm =
descent_mm.max((style.line_height(font_cache) - glyph_height).max(Mm::from(0.0)));
let glyph_height = font.glyph_height(*glyph_size);
let y_offset = Mm::from(scaled_units_to_mm(i64::from(y_offset.0)));
ascent_mm = ascent_mm.max(glyph_height + y_offset);
descent_mm = descent_mm
.max((style.line_height(font_cache) - glyph_height - y_offset).max(Mm::from(0.0)));
}
let ascent = i64::from(scaled_points(f64::from(ascent_mm) * PDF_POINTS_PER_INCH / 25.4).0);
let height =
+68 -1
View File
@@ -2940,9 +2940,72 @@ fn makebox_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<()> {
let width = match read_optional_bracketed_argument(input, token, "makebox width")? {
Some(tokens) => Some(dimension_from_argument(input, token, &tokens)?),
None => None,
};
let align = match read_optional_bracketed_argument(input, token, "makebox alignment")? {
Some(tokens) => {
let value = tokens
.iter()
.filter_map(|token| token.char())
.collect::<String>();
match value.trim() {
"l" | "" => texrra_core::document::InlineBoxAlign::Left,
"c" => texrra_core::document::InlineBoxAlign::Center,
"r" => texrra_core::document::InlineBoxAlign::Right,
other => {
return Err(input.fatal_error(error::SimpleTokenError::new(
token,
format!("makebox alignment must be l, c, or r, found `{other}`"),
)));
}
}
}
None => texrra_core::document::InlineBoxAlign::Left,
};
let content = read_unexpanded_argument(input, token, "expects box content")?;
let inner = strip_braced_tokens(&content).to_vec();
write_event(input, token, FrontendEventKind::InlineBoxStart);
write_event(
input,
token,
FrontendEventKind::InlineBoxStart {
width,
align,
raise: common::Scaled::ZERO,
},
);
let trace_key = token.trace_key();
let mut expansion = inner;
expansion.push(control_sequence_token(
input,
"texrrainlineboxend",
trace_key,
));
input
.as_mut()
.expansions_mut()
.extend(expansion.into_iter().rev());
Ok(())
}
fn raisebox_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<()> {
let lift_tokens = read_unexpanded_argument(input, token, "expects a raise amount")?;
let lift = dimension_from_argument(input, token, &lift_tokens)?;
let content = read_unexpanded_argument(input, token, "expects box content")?;
let inner = strip_braced_tokens(&content).to_vec();
write_event(
input,
token,
FrontendEventKind::InlineBoxStart {
width: None,
align: texrra_core::document::InlineBoxAlign::Left,
raise: lift,
},
);
let trace_key = token.trace_key();
let mut expansion = inner;
expansion.push(control_sequence_token(
@@ -6284,6 +6347,10 @@ fn built_in_commands() -> HashMap<&'static str, texlang::command::BuiltIn<Compil
"makebox",
texlang::command::BuiltIn::new_execution(makebox_primitive),
);
built_ins.insert(
"raisebox",
texlang::command::BuiltIn::new_execution(raisebox_primitive),
);
built_ins.insert(
"mbox",
texlang::command::BuiltIn::new_execution(makebox_primitive),
+41 -14
View File
@@ -25,11 +25,13 @@ pub(super) enum LineItem {
monospace: bool,
sans: bool,
font_size: u8,
y_offset: Scaled,
},
Rule {
width: Scaled,
raise: Scaled,
height: Scaled,
y_offset: Scaled,
},
Kern(Scaled),
Glue(Scaled),
@@ -38,12 +40,14 @@ pub(super) enum LineItem {
struct TextSpan {
text: String,
style: Style,
y_offset: Mm,
}
pub(super) struct PositionedSpan {
pub(super) text: String,
pub(super) style: Style,
pub(super) x: Mm,
pub(super) y_offset: Mm,
}
pub(super) struct TextLineLayout {
@@ -67,7 +71,12 @@ pub(super) struct TextLine {
enum TextLineItem {
Text(TextSpan),
Rule { width: Mm, raise: Mm, height: Mm },
Rule {
width: Mm,
raise: Mm,
height: Mm,
y_offset: Mm,
},
Kern(Mm),
Glue(Mm),
}
@@ -77,6 +86,7 @@ pub(super) struct PositionedRule {
pub(super) width: Mm,
pub(super) raise: Mm,
pub(super) height: Mm,
pub(super) y_offset: Mm,
}
impl TextLine {
@@ -100,6 +110,7 @@ impl TextLine {
monospace,
sans,
font_size: glyph_size,
y_offset,
} if is_cjk(*character) => {
flush_text(
&mut items,
@@ -123,6 +134,7 @@ impl TextLine {
sans_family,
*glyph_size,
),
y_offset: scaled_to_mm(*y_offset),
}));
}
LineItem::Glyph {
@@ -132,8 +144,9 @@ impl TextLine {
monospace,
sans,
font_size: glyph_size,
y_offset,
} => {
let style_key = (*bold, *italic, *monospace, *sans, *glyph_size);
let style_key = (*bold, *italic, *monospace, *sans, *glyph_size, *y_offset);
if text_style != Some(style_key) {
flush_text(
&mut items,
@@ -152,6 +165,7 @@ impl TextLine {
width,
raise,
height,
y_offset,
} => {
flush_text(
&mut items,
@@ -166,6 +180,7 @@ impl TextLine {
width: scaled_to_mm(*width),
raise: scaled_to_mm(*raise),
height: scaled_to_mm(*height),
y_offset: scaled_to_mm(*y_offset),
});
}
LineItem::Glue(width) => {
@@ -239,15 +254,17 @@ impl TextLine {
width,
raise,
height,
y_offset,
} => {
if *height > Mm::from(0.0) {
ascent = ascent.max(*raise + *height);
descent = descent.max(Mm::from(0.0) - *raise);
ascent = ascent.max(*raise + *height + *y_offset);
descent = descent.max(Mm::from(0.0) - *raise - *y_offset);
rules.push(PositionedRule {
x,
width: *width,
raise: *raise,
height: *height,
y_offset: *y_offset,
});
}
}
@@ -255,12 +272,14 @@ impl TextLine {
let font = span.style.font(fonts);
let glyph_height = font.glyph_height(span.style.font_size());
let line_height = span.style.line_height(fonts);
ascent = ascent.max(glyph_height);
descent = descent.max((line_height - glyph_height).max(Mm::from(0.0)));
ascent = ascent.max(glyph_height + span.y_offset);
descent = descent
.max((line_height - glyph_height - span.y_offset).max(Mm::from(0.0)));
spans.push(PositionedSpan {
text: span.text.clone(),
style: span.style,
x,
y_offset: span.y_offset,
});
x += span.style.str_width(fonts, &span.text);
}
@@ -306,7 +325,7 @@ impl TextLine {
output,
"<rect x=\"{:.4}\" y=\"{:.4}\" width=\"{:.4}\" height=\"{:.4}\" fill=\"#000000\"/>",
f64::from(x + horizontal_offset + rule.x),
f64::from(baseline - rule.raise - rule.height),
f64::from(baseline - rule.y_offset - rule.raise - rule.height),
f64::from(rule.width),
f64::from(rule.height),
);
@@ -332,7 +351,7 @@ impl TextLine {
output,
"<text x=\"{:.4}\" y=\"{:.4}\" xml:space=\"preserve\" font-family=\"{family}\" font-size=\"{:.4}\" font-weight=\"{weight}\" font-style=\"{slant}\">{}</text>",
f64::from(x + horizontal_offset + span.x),
f64::from(baseline),
f64::from(baseline - span.y_offset),
svg_font_size(span.style.font_size()),
escape_html(&span.text),
);
@@ -343,7 +362,7 @@ impl TextLine {
fn flush_text(
items: &mut Vec<TextLineItem>,
text: &mut String,
style_key: &mut Option<(bool, bool, bool, bool, u8)>,
style_key: &mut Option<(bool, bool, bool, bool, u8, Scaled)>,
cjk_family: Option<FontFamily<fonts::Font>>,
monospace_family: Option<FontFamily<fonts::Font>>,
sans_family: Option<FontFamily<fonts::Font>>,
@@ -353,9 +372,10 @@ fn flush_text(
*style_key = None;
return;
}
let (bold, italic, monospace, sans, glyph_size) = style_key
.take()
.unwrap_or((false, false, false, false, font_size));
let (bold, italic, monospace, sans, glyph_size, y_offset) =
style_key
.take()
.unwrap_or((false, false, false, false, font_size, Scaled::ZERO));
items.push(TextLineItem::Text(TextSpan {
text: std::mem::take(text),
style: text_style_for(
@@ -369,6 +389,7 @@ fn flush_text(
sans_family,
glyph_size,
),
y_offset: scaled_to_mm(y_offset),
}));
}
@@ -436,7 +457,10 @@ impl Element for TextLine {
let scale_y = f64::from(rule.height) * 300.0 / 25.4;
area.add_image(
&black,
Position::new(rule.x + horizontal_offset, layout.ascent - rule.raise),
Position::new(
rule.x + horizontal_offset,
layout.ascent - rule.y_offset - rule.raise,
),
Scale::new(scale_x, scale_y),
Rotation::default(),
Some(300.0),
@@ -450,7 +474,10 @@ impl Element for TextLine {
let glyph_height = style
.font(&context.font_cache)
.glyph_height(style.font_size());
let position = Position::new(span.x + horizontal_offset, layout.ascent - glyph_height);
let position = Position::new(
span.x + horizontal_offset,
layout.ascent - glyph_height - span.y_offset,
);
if area
.text_section(&context.font_cache, position, style)
.is_none()