use std::collections::HashMap;
use std::io::Write;
use f_office_paint::{
self as paint, GlyphRun, GradientItem, GradientStop, GroupClip, ImageItem, Page, Painted,
PathItem, Rect as PaintRect, Rgb,
};
use f_office_units::Length;
use pdf_writer::types::{ColorSpaceOperand, FunctionShadingType, LineJoinStyle, TextRenderingMode};
use pdf_writer::{Chunk, Content, Filter, Finish, Name, Rect, Ref, Str};
use crate::fonts::UsedFonts;
use crate::images::EmittedImages;
use crate::stream::{StreamPdf, deflate};
use crate::{
Anchor, Error, FillAnchor, SideStart, Warning, Warnings, clip_commands, decimal, points,
printed, side_scale, stop_offset, text, to_f32, turn_entries, upright_run, upright_start,
};
pub(crate) struct DocState<'f, 'w, W: Write> {
pub(crate) pdf: StreamPdf<'w, W>,
pub(crate) fonts: UsedFonts<'f>,
pub(crate) images: EmittedImages,
pub(crate) ext_gstates: HashMap<i64, Ref>,
pub(crate) warnings: Warnings,
}
impl<W: Write> DocState<'_, '_, W> {
fn opacity_gstate(&mut self, share: i64) -> Result<Ref, Error> {
if let Some(&id) = self.ext_gstates.get(&share) {
return Ok(id);
}
#[expect(
clippy::cast_precision_loss,
reason = "opacity share is at most 100,000"
)]
let alpha = share as f32 / f_office_units::scale::DRAWING_WHOLE as f32;
let id = self.pdf.alloc();
let mut chunk = Chunk::new();
chunk
.ext_graphics(id)
.non_stroking_alpha(alpha)
.stroking_alpha(alpha)
.alpha_source(false);
self.pdf.emit(id, &chunk)?;
self.ext_gstates.insert(share, id);
Ok(id)
}
}
#[derive(Default)]
struct PageResources {
fonts: ResourceMap,
xobjects: ResourceMap,
patterns: ResourceMap,
gstates: ResourceMap,
}
#[derive(Default)]
struct ResourceMap {
by_ref: HashMap<Ref, String>,
order: Vec<(String, Ref)>,
}
impl ResourceMap {
fn intern(&mut self, prefix: &str, id: Ref) -> String {
if let Some(name) = self.by_ref.get(&id) {
return name.clone();
}
let name = format!("{prefix}{}", self.order.len());
self.by_ref.insert(id, name.clone());
self.order.push((name.clone(), id));
name
}
}
struct PageBounds {
min_x: f32,
min_y: f32,
max_x: f32,
max_y: f32,
}
impl PageBounds {
fn new(width: f32, height: f32) -> Self {
Self {
min_x: 0.0,
min_y: 0.0,
max_x: width,
max_y: height,
}
}
fn include(&mut self, x: f32, y: f32) {
self.min_x = self.min_x.min(x);
self.min_y = self.min_y.min(y);
self.max_x = self.max_x.max(x);
self.max_y = self.max_y.max(y);
}
fn include_dl_rect(&mut self, page_h: Length, x: Length, y: Length, w: Length, h: Length) {
let x0 = points(x.min(x + w));
let x1 = points(x.max(x + w));
let y_top = points(page_h - y.min(y + h));
let y_bot = points(page_h - y.max(y + h));
self.include(x0, y_bot);
self.include(x1, y_top);
}
fn to_rect(&self) -> Rect {
Rect::new(self.min_x, self.min_y, self.max_x, self.max_y)
}
}
pub(crate) fn write_page<W: Write>(
page: &Page,
pages_ref: Ref,
state: &mut DocState<'_, '_, W>,
) -> Result<Ref, Error> {
let width = points(page.width());
let height = points(page.height());
if !(width > 0.0 && height > 0.0 && width.is_finite() && height.is_finite()) {
return Err(Error::PageSize);
}
let mut ctx = PageCtx {
height: page.height(),
content: Content::new(),
resources: PageResources::default(),
bounds: PageBounds::new(width, height),
};
let mut painted = page.painted().into_iter();
write_items(&mut ctx, &mut painted, state)?;
let form_bytes = deflate(&ctx.content.finish())?;
let form_ref = state.pdf.alloc();
let mut form_chunk = Chunk::new();
let mut form = form_chunk.form_xobject(form_ref, &form_bytes);
form.filter(Filter::FlateDecode);
form.bbox(ctx.bounds.to_rect());
write_resources(form.resources(), &ctx.resources);
form.finish();
state.pdf.emit(form_ref, &form_chunk)?;
drop(form_bytes);
let mut page_content = Content::new();
page_content.x_object(Name(b"Fm0"));
let page_stream_bytes = page_content.finish();
let content_ref = state.pdf.alloc();
let mut stream_chunk = Chunk::new();
stream_chunk.stream(content_ref, &page_stream_bytes);
state.pdf.emit(content_ref, &stream_chunk)?;
let leaf_ref = state.pdf.alloc();
let mut dict_chunk = Chunk::new();
let mut entry = dict_chunk.page(leaf_ref);
entry
.parent(pages_ref)
.media_box(Rect::new(0.0, 0.0, width, height))
.contents(content_ref);
entry.resources().x_objects().pair(Name(b"Fm0"), form_ref);
entry.finish();
state.pdf.emit(leaf_ref, &dict_chunk)?;
Ok(leaf_ref)
}
fn write_resources(mut res: pdf_writer::writers::Resources<'_>, table: &PageResources) {
write_resource_group(&table.fonts, || res.fonts());
write_resource_group(&table.xobjects, || res.x_objects());
write_resource_group(&table.patterns, || res.patterns());
write_resource_group(&table.gstates, || res.ext_g_states());
}
fn write_resource_group<'a>(map: &ResourceMap, open: impl FnOnce() -> pdf_writer::Dict<'a>) {
if map.order.is_empty() {
return;
}
let mut dict = open();
for (name, id) in &map.order {
dict.pair(Name(name.as_bytes()), *id);
}
}
struct PageCtx {
height: Length,
content: Content,
resources: PageResources,
bounds: PageBounds,
}
fn write_items<W: Write>(
ctx: &mut PageCtx,
painted: &mut std::vec::IntoIter<Painted<'_>>,
state: &mut DocState<'_, '_, W>,
) -> Result<(), Error> {
while let Some(item) = painted.next() {
match item {
Painted::Glyphs(run) => draw_run(ctx, run, state)?,
Painted::Rect(rect) => fill_rect(ctx, rect),
Painted::Path(path) => fill_path(ctx, path),
Painted::Gradient(gradient) => fill_gradient(ctx, gradient, state)?,
Painted::Image(image) => draw_image(ctx, image, state)?,
Painted::ClipStart(clip) => draw_clipped(ctx, clip, painted, state)?,
Painted::ClipEnd => return Ok(()),
}
}
Ok(())
}
fn draw_clipped<W: Write>(
ctx: &mut PageCtx,
clip: &GroupClip,
painted: &mut std::vec::IntoIter<Painted<'_>>,
state: &mut DocState<'_, '_, W>,
) -> Result<(), Error> {
let anchor = crate::path_anchor(ctx.height, &clip.commands);
let commands = clip_commands(&clip.commands);
let filled = paint::fill_commands(&commands);
if filled.is_empty() {
return Err(Error::Clip);
}
ctx.content.save_state();
ctx.content.transform(anchor.matrix());
emit_path_commands(&mut ctx.content, &filled, |p| anchor.local(p.x, p.y));
match clip.fill_rule {
paint::FillRule::NonZero => ctx.content.clip_nonzero().end_path(),
paint::FillRule::EvenOdd => ctx.content.clip_even_odd().end_path(),
};
ctx.content.transform(anchor.undone_matrix());
let res = write_items(ctx, painted, state);
ctx.content.restore_state();
res
}
fn fill_rect(ctx: &mut PageCtx, rect: &PaintRect) {
if !paint::fill_shows(rect.width, rect.height) {
return;
}
ctx.bounds
.include_dl_rect(ctx.height, rect.x, rect.y, rect.width, rect.height);
let corner = (rect.x, rect.y);
let far = (rect.x + rect.width, rect.y + rect.height);
let anchor = FillAnchor::middle(ctx.height, corner, far);
let (left, right) = anchor.span(rect.x - anchor.anchor.x, rect.width);
let (top, bottom) = anchor.span(rect.y - anchor.anchor.y, rect.height);
if !(right > left && bottom > top) {
return;
}
let [r, g, b] = rgb_f32(rect.color);
ctx.content.save_state();
ctx.content.transform(anchor.matrix());
ctx.content.set_fill_rgb(r, g, b);
ctx.content
.move_to(left, top)
.line_to(right, top)
.line_to(right, bottom)
.line_to(left, bottom)
.close_path();
ctx.content.fill_nonzero();
ctx.content.restore_state();
}
fn path_fill_anchor(ctx: &mut PageCtx, commands: &[paint::PathCommand]) -> FillAnchor {
let bounds = crate::path_bounds(commands);
if let Some((low, high)) = bounds {
ctx.bounds
.include_dl_rect(ctx.height, low.x, low.y, high.x - low.x, high.y - low.y);
}
bounds.map_or(
FillAnchor::middle(
ctx.height,
(Length::ZERO, Length::ZERO),
(Length::ZERO, Length::ZERO),
),
|(low, high)| FillAnchor::middle(ctx.height, (low.x, low.y), (high.x, high.y)),
)
}
fn fill_path(ctx: &mut PageCtx, item: &PathItem) {
if !paint::path_shows(&item.commands) {
return;
}
let anchor = path_fill_anchor(ctx, &item.commands);
let filled = paint::fill_commands(&item.commands);
if filled.is_empty() {
return;
}
let [r, g, b] = rgb_f32(item.color);
ctx.content.save_state();
ctx.content.transform(anchor.matrix());
ctx.content.set_fill_rgb(r, g, b);
emit_path_commands(&mut ctx.content, &filled, |p| anchor.local(p.x, p.y));
match item.fill_rule {
paint::FillRule::NonZero => ctx.content.fill_nonzero(),
paint::FillRule::EvenOdd => ctx.content.fill_even_odd(),
};
ctx.content.restore_state();
}
fn fill_gradient<W: Write>(
ctx: &mut PageCtx,
item: &GradientItem,
state: &mut DocState<'_, '_, W>,
) -> Result<(), Error> {
if !paint::path_shows(&item.commands) {
return Ok(());
}
if item.stops.len() < 2 || item.start == item.end {
let path = PathItem {
commands: item.commands.clone(),
color: item.color_at(i64::from(GradientStop::START)),
fill_rule: item.fill_rule,
};
fill_path(ctx, &path);
return Ok(());
}
let mut with_axis = item.commands.clone();
with_axis.push(paint::PathCommand::MoveTo(item.start));
with_axis.push(paint::PathCommand::LineTo(item.end));
let anchor = path_fill_anchor(ctx, &with_axis);
let filled = paint::fill_commands(&item.commands);
if filled.is_empty() {
return Ok(());
}
let ((x1, y1), (x2, y2)) = (
anchor.local(item.start.x, item.start.y),
anchor.local(item.end.x, item.end.y),
);
let shading_ref = emit_axial_shading([x1, y1, x2, y2], &item.stops, &mut state.pdf)?;
let pattern_ref = state.pdf.alloc();
let mut pattern_chunk = Chunk::new();
pattern_chunk
.shading_pattern(pattern_ref)
.shading_ref(shading_ref)
.matrix(anchor.matrix());
state.pdf.emit(pattern_ref, &pattern_chunk)?;
let pattern_name = ctx.resources.patterns.intern("P", pattern_ref);
ctx.content.save_state();
ctx.content.transform(anchor.matrix());
ctx.content.set_fill_color_space(ColorSpaceOperand::Pattern);
ctx.content
.set_fill_pattern([], Name(pattern_name.as_bytes()));
emit_path_commands(&mut ctx.content, &filled, |p| anchor.local(p.x, p.y));
match item.fill_rule {
paint::FillRule::NonZero => ctx.content.fill_nonzero(),
paint::FillRule::EvenOdd => ctx.content.fill_even_odd(),
};
ctx.content.restore_state();
Ok(())
}
fn emit_axial_shading<W: Write>(
coords: [f32; 4],
stops: &[GradientStop],
pdf: &mut StreamPdf<'_, W>,
) -> Result<Ref, Error> {
let mut normalized: Vec<(f32, [f32; 3])> = stops
.iter()
.map(|s| (stop_offset(s.place), rgb_f32(s.color)))
.collect();
normalized.sort_by(|a, b| a.0.total_cmp(&b.0));
let mut segments: Vec<(f32, f32, [f32; 3], [f32; 3])> = Vec::new();
if let Some(&(first_t, first_c)) = normalized.first()
&& first_t > 0.0
{
segments.push((0.0, first_t, first_c, first_c));
}
for pair in normalized.windows(2) {
if let [(t0, c0), (t1, c1)] = *pair
&& t1 > t0
{
segments.push((t0, t1, c0, c1));
}
}
if let Some(&(last_t, last_c)) = normalized.last()
&& last_t < 1.0
{
segments.push((last_t, 1.0, last_c, last_c));
}
if segments.is_empty() {
let color = normalized.first().map_or([0.0, 0.0, 0.0], |s| s.1);
segments.push((0.0, 1.0, color, color));
}
let fn_ref = emit_gradient_function(&segments, pdf)?;
let shading_ref = pdf.alloc();
let mut chunk = Chunk::new();
let mut shading = chunk.function_shading(shading_ref);
shading
.shading_type(FunctionShadingType::Axial)
.coords(coords)
.function(fn_ref)
.extend([true, true]);
shading.color_space().device_rgb();
shading.finish();
pdf.emit(shading_ref, &chunk)?;
Ok(shading_ref)
}
fn emit_gradient_function<W: Write>(
segments: &[(f32, f32, [f32; 3], [f32; 3])],
pdf: &mut StreamPdf<'_, W>,
) -> Result<Ref, Error> {
let mut sub_refs = Vec::with_capacity(segments.len());
for &(_, _, c0, c1) in segments {
let id = pdf.alloc();
let mut chunk = Chunk::new();
chunk
.exponential_function(id)
.domain([0.0, 1.0])
.c0(c0)
.c1(c1)
.n(1.0);
pdf.emit(id, &chunk)?;
sub_refs.push(id);
}
if sub_refs.len() == 1
&& let Some(&only) = sub_refs.first()
{
return Ok(only);
}
let bounds: Vec<f32> = segments
.iter()
.take(segments.len().saturating_sub(1))
.map(|s| s.1)
.collect();
let encode: Vec<f32> = segments.iter().flat_map(|_| [0.0_f32, 1.0_f32]).collect();
let stitch_ref = pdf.alloc();
let mut chunk = Chunk::new();
chunk
.stitching_function(stitch_ref)
.domain([0.0, 1.0])
.functions(sub_refs)
.bounds(bounds)
.encode(encode);
pdf.emit(stitch_ref, &chunk)?;
Ok(stitch_ref)
}
fn draw_image<W: Write>(
ctx: &mut PageCtx,
item: &ImageItem,
state: &mut DocState<'_, '_, W>,
) -> Result<(), Error> {
let w = points(item.width);
let h = points(item.height);
if !(w > 0.0 && h > 0.0 && w.is_finite() && h.is_finite()) {
return Ok(());
}
let xobj_ref = match state.images.get_or_emit(&item.image, &mut state.pdf)? {
Ok(id) => id,
Err(fault) => {
state.warnings.push(Warning::ImageSkipped {
format: item.image.format,
fault,
});
return Ok(());
}
};
let name = ctx.resources.xobjects.intern("Im", xobj_ref);
let gstate_name = if item.image.opacity.share() < f_office_units::scale::DRAWING_WHOLE {
let gs_ref = state.opacity_gstate(item.image.opacity.share())?;
Some(ctx.resources.gstates.intern("Gs", gs_ref))
} else {
None
};
ctx.bounds
.include_dl_rect(ctx.height, item.x, item.y, item.width, item.height);
if let Some(clip) = item.clip {
ctx.bounds
.include_dl_rect(ctx.height, clip.x, clip.y, clip.width, clip.height);
draw_image_clipped(ctx, clip, |ctx| {
emit_image_draw(ctx, item, &name, gstate_name.as_deref());
});
} else {
emit_image_draw(ctx, item, &name, gstate_name.as_deref());
}
Ok(())
}
fn draw_image_clipped(ctx: &mut PageCtx, clip: paint::Clip, draw: impl FnOnce(&mut PageCtx)) {
let width_pt = clip.width.points_f64().abs();
let height_pt = clip.height.points_f64().abs();
if width_pt < 127.0 && height_pt < 127.0 {
let anchor = Anchor::at(ctx.height, clip.x, clip.y);
let Some((l, t, r, b)) =
clip_rect_ltrb(anchor, (clip.x, clip.y), (clip.width, clip.height))
else {
return;
};
ctx.content.save_state();
ctx.content.transform(anchor.matrix());
emit_clip_rect_with_return(&mut ctx.content, l, t, r, b);
ctx.content.transform(anchor.undone_matrix());
draw(ctx);
ctx.content.restore_state();
return;
}
let (left, right) = (
clip.x.min(clip.x + clip.width),
clip.x.max(clip.x + clip.width),
);
let (top, bottom) = (
clip.y.min(clip.y + clip.height),
clip.y.max(clip.y + clip.height),
);
let top_left = Anchor::at(ctx.height, left, top);
let bottom_right = Anchor::at(ctx.height, right, bottom);
let pad_x = to_f32(width_pt.ceil() + 16.0);
let pad_y = to_f32(height_pt.ceil() + 16.0);
let (left_x, top_y) = top_left.local(left, top);
let (right_x, bottom_y) = bottom_right.local(right, bottom);
if !(pad_x > left_x && pad_y > top_y && right_x > -pad_x && bottom_y > -pad_y) {
return;
}
ctx.content.save_state();
ctx.content.transform(top_left.matrix());
emit_clip_rect_with_return(&mut ctx.content, left_x, top_y, pad_x, pad_y);
ctx.content.transform(top_left.undone_matrix());
ctx.content.save_state();
ctx.content.transform(bottom_right.matrix());
emit_clip_rect_with_return(&mut ctx.content, -pad_x, -pad_y, right_x, bottom_y);
ctx.content.transform(bottom_right.undone_matrix());
draw(ctx);
ctx.content.restore_state();
ctx.content.restore_state();
}
fn clip_rect_ltrb(
anchor: Anchor,
(x, y): (Length, Length),
(across, down): (Length, Length),
) -> Option<(f32, f32, f32, f32)> {
let span = |start: Length, length: Length| {
let from = start.points_f64();
let to = from + length.points_f64();
(decimal(from.min(to)), decimal(from.max(to)))
};
let (left, right) = span(x - anchor.x, across);
let (top, bottom) = span(y - anchor.y, down);
(right >= left && bottom >= top).then_some((left, top, right, bottom))
}
fn emit_clip_rect_with_return(content: &mut Content, l: f32, t: f32, r: f32, b: f32) {
content
.move_to(l, t)
.line_to(r, t)
.line_to(r, b)
.line_to(l, b)
.line_to(l, t)
.close_path()
.clip_nonzero()
.end_path();
}
fn emit_image_draw(ctx: &mut PageCtx, item: &ImageItem, name: &str, gstate: Option<&str>) {
match item.turn {
Some(turn) => draw_turned_image(ctx, item, name, gstate, turn),
None => draw_upright_image(ctx, item, name, gstate),
}
}
fn emit_image_xobject(
content: &mut Content,
(name, gstate): (&str, Option<&str>),
anchor: Anchor,
placement: [f32; 6],
scale: (f32, f32),
box_matrix: [f32; 6],
) {
content.save_state();
if let Some(gs) = gstate {
content.set_parameters(Name(gs.as_bytes()));
}
content.transform(anchor.matrix());
content.transform(placement);
if scale != (1.0, 1.0) {
content.transform([scale.0, 0.0, 0.0, scale.1, 0.0, 0.0]);
}
content.transform(box_matrix);
content.rect(0.0, 0.0, 1.0, 1.0).clip_nonzero().end_path();
content.x_object(Name(name.as_bytes()));
content.restore_state();
}
fn draw_upright_image(ctx: &mut PageCtx, item: &ImageItem, name: &str, gstate: Option<&str>) {
let bottom = item.y + item.height;
let anchor = Anchor::at(ctx.height, item.x, bottom);
let (scale_across, across) = side_scale(item.width.points_f64(), SideStart::Corner, 1.0);
let (scale_down, down) = side_scale(item.height.points_f64(), SideStart::Corner, 1.0);
if !(across > 0.0 && down > 0.0) {
return;
}
let (x, y) = anchor.local(item.x, bottom);
emit_image_xobject(
&mut ctx.content,
(name, gstate),
anchor,
[1.0, 0.0, 0.0, 1.0, x, y],
(scale_across, scale_down),
[across, 0.0, 0.0, -down, 0.0, 0.0],
);
}
fn draw_turned_image(
ctx: &mut PageCtx,
item: &ImageItem,
name: &str,
gstate: Option<&str>,
turn: paint::Turn,
) {
let [xx, yx, xy, yy] = turn_entries(turn);
let length = |a: f32, b: f32| printed(a).hypot(printed(b));
let (scale_across, across) =
side_scale(item.width.points_f64(), SideStart::Centre, length(xx, yx));
let (scale_down, down) =
side_scale(item.height.points_f64(), SideStart::Centre, length(xy, yy));
if !(across > 0.0 && down > 0.0) {
return;
}
let half = |side: Length| Length::from_units(side.units().div_euclid(2));
let anchor = Anchor::at(
ctx.height,
item.x + half(item.width),
item.y + half(item.height),
);
let centre = |from: Length, side: Length| decimal((from + from + side).points_f64() / 2.0);
let (centre_x, centre_y) = (
centre(item.x - anchor.x, item.width),
centre(item.y - anchor.y, item.height),
);
emit_image_xobject(
&mut ctx.content,
(name, gstate),
anchor,
[xx, yx, xy, yy, centre_x, centre_y],
(scale_across, scale_down),
[across, 0.0, 0.0, -down, -across / 2.0, down / 2.0],
);
}
struct PreparedGlyph {
cid: u16,
width_1000: f32,
x: Length,
y: Length,
}
struct PreparedGroup<'a> {
glyphs: Vec<PreparedGlyph>,
text: &'a str,
use_actual_text: bool,
}
#[derive(Clone, Copy)]
enum TextPaint {
Fill(Rgb),
Invisible,
Stroke(paint::Outline),
}
fn draw_run<W: Write>(
ctx: &mut PageCtx,
run: &GlyphRun,
state: &mut DocState<'_, '_, W>,
) -> Result<(), Error> {
state.fonts.validate(run.font)?;
if run.glyphs.is_empty() || run.size == Length::ZERO {
return Ok(());
}
let used = state.fonts.get_or_register(run.font, &mut state.pdf)?;
let font_ref = used.type0_ref();
let units = used.units_per_em();
let right_edge = used.right_edge();
let font_name = ctx.resources.fonts.intern("F", font_ref);
let size = points(run.size);
let reach = right_edge
.filter(|&e| e > 0)
.map_or(size, |e| f32::from(e) / units * size);
let upright = run.turn.map(|turn| upright_run(run, turn));
let shown = upright.as_ref().unwrap_or(run);
let groups = prepare_groups(run, shown, state)?;
for group in &groups {
for glyph in &group.glyphs {
let x_pt = points(glyph.x);
let y_pt = points(ctx.height - glyph.y);
ctx.bounds.include(x_pt, y_pt - size);
ctx.bounds.include(x_pt + reach, y_pt + size);
}
}
let line = run.outline.filter(|o| o.width > Length::ZERO);
if run.filled {
emit_run_pass(
ctx,
run,
&groups,
(&font_name, size),
TextPaint::Fill(run.color),
state,
)?;
} else if line.is_none() {
emit_run_pass(
ctx,
run,
&groups,
(&font_name, size),
TextPaint::Invisible,
state,
)?;
}
if let Some(outline) = line {
emit_run_pass(
ctx,
run,
&groups,
(&font_name, size),
TextPaint::Stroke(outline),
state,
)?;
}
Ok(())
}
fn prepare_groups<'a, W: Write>(
run: &'a GlyphRun,
shown: &GlyphRun,
state: &mut DocState<'_, '_, W>,
) -> Result<Vec<PreparedGroup<'a>>, Error> {
let raw_groups = text::positioned_groups(run);
let mut out = Vec::with_capacity(raw_groups.len());
for range in raw_groups {
let places = run.glyphs.get(range.clone()).unwrap_or_default();
let shown_slice = shown.glyphs.get(range).unwrap_or_default();
let mut group_start = usize::MAX;
let mut group_end = 0_usize;
for g in places {
let r = run.glyph_range(g).ok_or(Error::TextRange)?;
group_start = group_start.min(r.start);
group_end = group_end.max(r.end);
}
let group_text = if group_start <= group_end {
run.text
.get(group_start..group_end)
.ok_or(Error::TextRange)?
} else {
""
};
let mut glyphs = Vec::with_capacity(places.len());
let mut any_actual = false;
let multi = places.len() > 1;
for (idx, (orig, upright_g)) in places.iter().zip(shown_slice).enumerate() {
let adv = state
.fonts
.db()
.advance(run.font, orig.id)
.ok_or(Error::UnknownGlyph {
font: run.font,
glyph: orig.id,
})?;
let used = state.fonts.get_or_register(run.font, &mut state.pdf)?;
let width_1000 = f32::from(adv) / used.units_per_em() * 1000.0;
let glyph_text = if multi {
if idx == 0 { group_text } else { "" }
} else {
group_text
};
let mapped = used.record_glyph(orig.id, glyph_text)?;
if mapped.needs_actual_text {
any_actual = true;
}
glyphs.push(PreparedGlyph {
cid: mapped.cid,
width_1000,
x: upright_g.x,
y: upright_g.y,
});
}
let use_actual_text = any_actual && !group_text.is_empty();
out.push(PreparedGroup {
glyphs,
text: group_text,
use_actual_text,
});
}
Ok(out)
}
fn emit_run_pass<W: Write>(
ctx: &mut PageCtx,
run: &GlyphRun,
groups: &[PreparedGroup<'_>],
(font_name, size): (&str, f32),
paint_mode: TextPaint,
state: &mut DocState<'_, '_, W>,
) -> Result<(), Error> {
let invisible_gs = if matches!(paint_mode, TextPaint::Invisible) {
let gs = state.opacity_gstate(0)?;
Some(ctx.resources.gstates.intern("Gs", gs))
} else {
None
};
if let Some(turn) = run.turn {
emit_turned_groups(
ctx,
run,
groups,
(font_name, size),
(paint_mode, invisible_gs.as_deref()),
turn,
);
return Ok(());
}
let mut rest = groups;
while let Some(first_group) = rest.first() {
let Some(origin) = first_group.glyphs.first() else {
rest = rest.get(1..).unwrap_or_default();
continue;
};
let anchor = Anchor::of_line(ctx.height, origin.x, origin.y);
let count = rest
.iter()
.take_while(|g| g.glyphs.iter().all(|gl| anchor.reaches(gl.x, gl.y)))
.count()
.max(1);
let slice = rest.get(..count).unwrap_or_default();
emit_anchored_text_object(
&mut ctx.content,
anchor,
slice,
(font_name, size),
(paint_mode, invisible_gs.as_deref()),
);
rest = rest.get(count..).unwrap_or_default();
}
Ok(())
}
fn emit_turned_groups(
ctx: &mut PageCtx,
run: &GlyphRun,
groups: &[PreparedGroup<'_>],
(font_name, size): (&str, f32),
(paint_mode, invisible_gs): (TextPaint, Option<&str>),
turn: paint::Turn,
) {
let mut glyph_idx = 0_usize;
for group in groups {
let Some(orig_place) = run.glyphs.get(glyph_idx) else {
break;
};
glyph_idx += group.glyphs.len();
let Some(first_upright) = group.glyphs.first() else {
continue;
};
let anchor = Anchor::at(ctx.height, orig_place.x, orig_place.y);
let (ux, uy) = upright_start(turn, anchor, orig_place);
ctx.content.save_state();
apply_text_paint(&mut ctx.content, paint_mode, invisible_gs);
ctx.content.transform(anchor.turned_matrix(turn));
ctx.content.begin_text();
ctx.content.set_font(Name(font_name.as_bytes()), size);
if group.use_actual_text {
begin_actual_text(&mut ctx.content, group.text);
}
let mut cursor_x = f64::from(ux);
let mut cursor_y = f64::from(uy);
let mut has_tm = false;
let mut items: Vec<TjItem> = Vec::new();
for gl in &group.glyphs {
let target_x = f64::from(ux) + (gl.x - first_upright.x).points_f64();
let target_y = f64::from(uy) + (gl.y - first_upright.y).points_f64();
push_glyph_tj(
&mut ctx.content,
&mut items,
(&mut has_tm, &mut cursor_x, &mut cursor_y),
(target_x, target_y, size),
gl,
);
}
flush_tj(&mut ctx.content, &mut items);
if group.use_actual_text {
ctx.content.end_marked_content();
}
ctx.content.end_text();
ctx.content.restore_state();
}
}
fn emit_anchored_text_object(
content: &mut Content,
anchor: Anchor,
groups: &[PreparedGroup<'_>],
(font_name, size): (&str, f32),
(paint_mode, invisible_gs): (TextPaint, Option<&str>),
) {
content.save_state();
apply_text_paint(content, paint_mode, invisible_gs);
content.transform(anchor.matrix());
content.begin_text();
content.set_font(Name(font_name.as_bytes()), size);
let mut cursor_x = 0.0_f64;
let mut cursor_y = 0.0_f64;
let mut has_tm = false;
let mut items: Vec<TjItem> = Vec::new();
for group in groups {
if group.use_actual_text {
flush_tj(content, &mut items);
begin_actual_text(content, group.text);
has_tm = false;
}
for gl in &group.glyphs {
let target_x = (gl.x - anchor.x).points_f64();
let target_y = (gl.y - anchor.y).points_f64();
push_glyph_tj(
content,
&mut items,
(&mut has_tm, &mut cursor_x, &mut cursor_y),
(target_x, target_y, size),
gl,
);
}
if group.use_actual_text {
flush_tj(content, &mut items);
content.end_marked_content();
has_tm = false;
}
}
flush_tj(content, &mut items);
content.end_text();
content.restore_state();
}
enum TjItem {
Bytes(Vec<u8>),
Adjust(f32),
}
#[expect(
clippy::cast_precision_loss,
reason = "UNITS_PER_POINT is exact in double precision"
)]
const WIDTH_TOLERANCE_PT: f64 = 0.2 / Length::UNITS_PER_POINT as f64;
fn push_glyph_tj(
content: &mut Content,
items: &mut Vec<TjItem>,
(has_tm, cursor_x, cursor_y): (&mut bool, &mut f64, &mut f64),
(target_x, target_y, size): (f64, f64, f32),
gl: &PreparedGlyph,
) {
let same_line = *has_tm && (target_y - *cursor_y).abs() <= 1e-6;
if same_line {
let delta_pt = target_x - *cursor_x;
if delta_pt.abs() > WIDTH_TOLERANCE_PT {
let adj = to_f32(-delta_pt * 1000.0 / f64::from(size));
if adj != 0.0 {
items.push(TjItem::Adjust(adj));
*cursor_x -= printed(adj) * f64::from(size) / 1000.0;
}
}
} else {
flush_tj(content, items);
let lx = decimal(target_x);
let ly = decimal(target_y);
content.set_text_matrix([1.0, 0.0, 0.0, -1.0, lx, ly]);
*cursor_x = printed(lx);
*cursor_y = target_y;
*has_tm = true;
}
let cid_bytes = gl.cid.to_be_bytes();
if let Some(TjItem::Bytes(buf)) = items.last_mut() {
buf.extend_from_slice(&cid_bytes);
} else {
items.push(TjItem::Bytes(cid_bytes.to_vec()));
}
*cursor_x += f64::from(gl.width_1000) * f64::from(size) / 1000.0;
}
fn flush_tj(content: &mut Content, items: &mut Vec<TjItem>) {
if items.is_empty() {
return;
}
let mut positioned = content.show_positioned();
let mut array = positioned.items();
for item in items.drain(..) {
match item {
TjItem::Bytes(bytes) => {
array.show(Str(&bytes));
}
TjItem::Adjust(adj) => {
array.adjust(adj);
}
}
}
}
fn apply_text_paint(content: &mut Content, mode: TextPaint, invisible_gs: Option<&str>) {
match mode {
TextPaint::Fill(color) => {
let [r, g, b] = rgb_f32(color);
content.set_text_rendering_mode(TextRenderingMode::Fill);
content.set_fill_rgb(r, g, b);
}
TextPaint::Invisible => {
content.set_text_rendering_mode(TextRenderingMode::Fill);
content.set_fill_rgb(0.0, 0.0, 0.0);
if let Some(gs) = invisible_gs {
content.set_parameters(Name(gs.as_bytes()));
}
}
TextPaint::Stroke(outline) => {
let [r, g, b] = rgb_f32(outline.color);
content.set_text_rendering_mode(TextRenderingMode::Stroke);
content.set_stroke_rgb(r, g, b);
content.set_line_width(points(outline.width));
content.set_miter_limit(10.0);
content.set_line_join(match outline.join {
paint::Join::Round => LineJoinStyle::RoundJoin,
paint::Join::Miter => LineJoinStyle::MiterJoin,
});
}
}
}
fn begin_actual_text(content: &mut Content, text: &str) {
let mut encoded = Vec::with_capacity(2 + text.len() * 2);
encoded.extend_from_slice(&[0xFE, 0xFF]);
for unit in text.encode_utf16() {
encoded.extend_from_slice(&unit.to_be_bytes());
}
content
.begin_marked_content_with_properties(Name(b"Span"))
.properties()
.pair(Name(b"ActualText"), Str(&encoded));
}
fn emit_path_commands(
content: &mut Content,
commands: &[paint::PathCommand],
at: impl Fn(paint::Point) -> (f32, f32),
) {
use paint::PathCommand::{Close, CubicTo, LineTo, MoveTo, QuadTo};
let mut current = (0.0_f32, 0.0_f32);
for command in commands {
match *command {
MoveTo(p) => {
let (x, y) = at(p);
content.move_to(x, y);
current = (x, y);
}
LineTo(p) => {
let (x, y) = at(p);
content.line_to(x, y);
current = (x, y);
}
QuadTo(c, p) => {
let (cx, cy) = at(c);
let (x, y) = at(p);
let c1x = current.0 + (2.0 / 3.0) * (cx - current.0);
let c1y = current.1 + (2.0 / 3.0) * (cy - current.1);
let c2x = x + (2.0 / 3.0) * (cx - x);
let c2y = y + (2.0 / 3.0) * (cy - y);
content.cubic_to(c1x, c1y, c2x, c2y, x, y);
current = (x, y);
}
CubicTo(c0, c1, p) => {
let (x0, y0) = at(c0);
let (x1, y1) = at(c1);
let (x, y) = at(p);
content.cubic_to(x0, y0, x1, y1, x, y);
current = (x, y);
}
Close => {
content.close_path();
}
}
}
}
fn rgb_f32(color: Rgb) -> [f32; 3] {
[
f32::from(color.r) / 255.0,
f32::from(color.g) / 255.0,
f32::from(color.b) / 255.0,
]
}