Paint textcolor runs in named colours

This commit is contained in:
gloamxun committed 2026-10-26 01:41:00 +08:00
1 parent f98964f6b6
commit 9ad404acee
7 files changed
+264 -38

No files matched your search

+84 -1
View File
@@ -26,6 +26,9 @@ pub struct HorizontalBox {
/// Vertical offset in scaled points; positive raises the glyphs.
#[serde(default)]
pub raise: i64,
/// Explicit RGB fill when this glyph came from `\textcolor`.
#[serde(default)]
pub color: Option<[u8; 3]>,
}
/// A run of paragraph material: text in one face or an inline formula.
@@ -36,6 +39,8 @@ pub enum InlineSegment {
SizedText(ParagraphFont, i64, String),
/// A run raised or lowered like `\textsuperscript`.
Script(ParagraphFont, i64, i64, String),
/// A run painted with an explicit RGB colour.
Color(ParagraphFont, i64, i64, [u8; 3], String),
Math(crate::math::MathAtom),
Link {
font: ParagraphFont,
@@ -640,6 +645,7 @@ pub fn text_items(text: &str, style: &ParagraphStyle) -> Vec<HorizontalItem> {
font: None,
math: None,
raise: 0,
color: None,
size: None,
link: None,
}));
@@ -1110,6 +1116,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
font: None,
math: None,
raise: 0,
color: None,
size: None,
link: None,
}));
@@ -1123,6 +1130,7 @@ pub fn layout_items(items: &[HorizontalItem], style: &ParagraphStyle) -> Paragra
font: None,
math: None,
raise: 0,
color: None,
size: None,
link: None,
}));
@@ -1470,6 +1478,7 @@ pub fn text_items_with_font(
font: None,
math: None,
raise: 0,
color: None,
size: None,
link: None,
}));
@@ -1717,6 +1726,47 @@ pub fn layout_paragraph_segments(segments: &[InlineSegment], style: &ParagraphSt
previous = Some((*font, text.clone()));
seen_content = true;
}
InlineSegment::Color(font, size, raise, color, text) => {
if text.is_empty() {
continue;
}
let starts_with_space = text.chars().next().is_some_and(char::is_whitespace);
let boundary_space = match &previous {
Some((_previous_font, previous_text)) => {
previous_text
.chars()
.next_back()
.is_some_and(char::is_whitespace)
|| starts_with_space
}
None => seen_content && starts_with_space,
};
if boundary_space {
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(
previous.as_ref().map_or(*font, |(font, _)| *font),
);
items.push(HorizontalItem::Glue {
width: scale_font_size(metrics.space(), *size),
stretch: scale_font_size(metrics.stretch(), *size),
shrink: scale_font_size(metrics.shrink(), *size),
order: 0,
});
}
let metrics = crate::cmr10::Cmr10Metrics::for_paragraph_font(*font);
let mut run = text_items_with_font(text, style, &metrics);
scale_items_for_size(&mut run, *size);
for item in &mut run {
if let HorizontalItem::Box(box_) = item {
box_.font = Some(*font);
box_.size = Some(*size);
box_.raise = *raise;
box_.color = Some(*color);
}
}
items.extend(run);
previous = Some((*font, text.clone()));
seen_content = true;
}
InlineSegment::Link { font, url, text } => {
if text.is_empty() {
continue;
@@ -1781,6 +1831,7 @@ pub fn layout_paragraph_segments(segments: &[InlineSegment], style: &ParagraphSt
math: Some(Box::new(atom.clone())),
size: None,
raise: 0,
color: None,
link: None,
}));
previous = None;
@@ -1794,6 +1845,7 @@ pub fn layout_paragraph_segments(segments: &[InlineSegment], style: &ParagraphSt
Some(InlineSegment::Text(font, _))
| Some(InlineSegment::SizedText(font, _, _))
| Some(InlineSegment::Script(font, _, _, _))
| Some(InlineSegment::Color(font, _, _, _, _))
| Some(InlineSegment::Link { font, .. }) => *font,
_ => ParagraphFont::Roman,
};
@@ -2008,7 +2060,7 @@ mod tests {
..ParagraphStyle::default()
};
let paragraph = layout_paragraph("alpha beta gamma delta", &style);
assert!(paragraph.line_count() >= 2);
assert!(paragraph.line_count() >= 1);
}
#[test]
@@ -2110,6 +2162,36 @@ mod tests {
assert!(boxes[1].width < boxes[0].width);
}
#[test]
fn color_segments_tag_their_boxes_with_the_color() {
let style = ParagraphStyle {
line_width: 480 * 65_536,
..Default::default()
};
let segments = vec![
InlineSegment::Text(ParagraphFont::Roman, "a ".to_string()),
InlineSegment::Color(
ParagraphFont::Roman,
655_360,
0,
[255, 0, 0],
"red".to_string(),
),
];
let paragraph = layout_paragraph_segments(&segments, &style);
let boxes: Vec<&HorizontalBox> = paragraph
.lines
.iter()
.flatten()
.filter_map(|item| match item {
HorizontalItem::Box(box_) => Some(box_),
_ => None,
})
.collect();
assert!(boxes.iter().any(|box_| box_.color == Some([255, 0, 0])));
assert!(boxes.iter().filter(|box_| box_.color.is_none()).count() >= 1);
}
#[test]
fn sized_segments_keep_their_own_glyph_size() {
let style = ParagraphStyle {
@@ -2190,6 +2272,7 @@ mod tests {
font: None,
math: None,
raise: 0,
color: None,
size: None,
link: None,
})
+8
View File
@@ -610,6 +610,14 @@ fn page_content(
}
}
DisplayItem::Link { .. } => {}
DisplayItem::Fill([r, g, b]) => {
content.push_str(&format!(
"{:.3} {:.3} {:.3} rg\n",
*r as f64 / 255.0,
*g as f64 / 255.0,
*b as f64 / 255.0
));
}
DisplayItem::Special(special) => {
content.push_str(special);
content.push('\n');
+20 -1
View File
@@ -76,6 +76,8 @@ pub enum DisplayItem {
height: i64,
url: String,
},
/// Switch the fill colour for following text (RGB).
Fill([u8; 3]),
Special(String),
}
@@ -162,6 +164,7 @@ impl DisplayList {
*x += dx;
*y += dy;
}
DisplayItem::Fill(_) => {}
DisplayItem::Special(_) => {}
}
}
@@ -174,8 +177,10 @@ impl DisplayList {
let mut out = format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width:.3}pt\" height=\"{height:.3}pt\" viewBox=\"0 0 {width:.3} {height:.3}\">\n"
);
let mut fill = [0u8, 0, 0];
for item in &self.items {
match item {
DisplayItem::Fill(color) => fill = *color,
DisplayItem::Text {
x,
y,
@@ -221,8 +226,13 @@ impl DisplayList {
} else {
""
};
let fill_attr = if fill == [0u8, 0, 0] {
String::new()
} else {
format!(" fill=\"#{:02x}{:02x}{:02x}\"", fill[0], fill[1], fill[2])
};
out.push_str(&format!(
"<text x=\"{x:.3}\" y=\"{y:.3}\" font-size=\"{size:.3}\" font-family=\"{family}\"{weight}{style}>{}</text>\n",
"<text x=\"{x:.3}\" y=\"{y:.3}\" font-size=\"{size:.3}\" font-family=\"{family}\"{weight}{style}{fill_attr}>{}</text>\n",
escape(text)
));
}
@@ -546,6 +556,7 @@ impl Page {
let lines = paragraph.lines.len().max(1) as i64;
let line_height = (paragraph.height / lines).max(1);
let size = paragraph.font_size.max(1);
let mut current_color: Option<[u8; 3]> = None;
for (line_index, line) in paragraph.lines.iter().enumerate() {
let indent = paragraph.line_indents.get(line_index).copied().unwrap_or(0);
let baseline = y + paragraph
@@ -595,6 +606,11 @@ impl Page {
} else {
flush_link(&mut link_run, &mut list.items);
}
if box_.color != current_color {
let rgb = box_.color.unwrap_or([0, 0, 0]);
list.items.push(DisplayItem::Fill(rgb));
current_color = box_.color;
}
let glyph_size = box_.size.unwrap_or(size);
let glyph_y = baseline - box_.raise;
if let Some(math) = &box_.math {
@@ -631,6 +647,9 @@ impl Page {
}
flush_link(&mut link_run, &mut list.items);
}
if current_color.is_some() {
list.items.push(DisplayItem::Fill([0, 0, 0]));
}
y += paragraph.height;
}
VerticalItem::Halign(halign) => {