f-office-docx 0.2.1

DOCX model and Word's layout rules.
Documentation
//! The sharp opaque shadow of a run's text: either one filled path of its glyphs' outlines, or
//! (for an outlined run) one effect picture of its glyphs' outlines stroked by the run's line
//! width, each glyph at its place on the device, moved by the shadow's offset, under the text.

use f_office_drawingml::effect::{ShadowColor, ShadowOffset};
use f_office_paint::{FillRule, Group, GroupPlaces, Item, PathCommand, PathItem, Point, Turn};
use f_office_units::{Length, div_round_i128, saturated};

use crate::text::{DrawnGlow, DrawnReflection, DrawnShadow, Face, ShadowForm};
use crate::{Fonts, OutlineCommand};

/// One glyph of a run on the device: its ID, and its origin across and down the page.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct DevicePlace {
    /// The glyph's ID in the run's font.
    pub(super) glyph: u32,
    /// Its origin across the page.
    pub(super) x: Length,
    /// Its origin down the page, on the run's baseline.
    pub(super) y: Length,
}

/// Extracts the glyph outlines of `places` in `face` at `size` (with optional `turn`), shifted
/// by `(dx, dy)` into page coordinates.
pub(super) fn glyph_outlines(
    (fonts, face, size, turn): (&dyn Fonts, &Face, Length, Option<Turn>),
    (dx, dy): (Length, Length),
    places: &[DevicePlace],
) -> Vec<PathCommand> {
    let em = i128::from(face.metrics.units_per_em.max(1));
    let size = i128::from(size.units());
    let mut commands = Vec::new();
    for place in places {
        let Ok(outline) = fonts.outline(face.font, place.glyph) else {
            continue;
        };
        let origin = (place.x + dx, place.y + dy);
        let at = |point| at(point, origin, (size, em), turn);
        commands.extend(outline.iter().map(|command| match *command {
            OutlineCommand::MoveTo(p) => PathCommand::MoveTo(at(p)),
            OutlineCommand::LineTo(p) => PathCommand::LineTo(at(p)),
            OutlineCommand::QuadTo(c, p) => PathCommand::QuadTo(at(c), at(p)),
            OutlineCommand::CubicTo(c, d, p) => PathCommand::CubicTo(at(c), at(d), at(p)),
            OutlineCommand::Close => PathCommand::Close,
        }));
    }
    commands
}

/// The shadow `shadow` of the glyphs `places` of a run in `face`, drawn at `size` with the turn
/// of the run's glyphs, if any, from `fonts`: for [`ShadowForm::Paths`], one filled path,
/// nonzero, of the outline of each glyph at its place moved by the shadow's offset, in the
/// shadow's color, which the PDF writer leaves in place ([`GroupPlaces::Own`]); for
/// [`ShadowForm::Picture`], one effect picture of the glyphs' outlines filled and stroked by the
/// outline's width at 200 pixels per inch. A glyph whose outline the font does not give draws
/// nothing; `None` when no glyph draws.
pub(super) fn item(
    glyphs: (&dyn Fonts, &Face, Length, Option<Turn>),
    shadow: DrawnShadow,
    places: &[DevicePlace],
) -> Option<Item> {
    let shift = match shadow.form {
        ShadowForm::Paths => (shadow.across, shadow.down),
        ShadowForm::Picture { .. } => (Length::ZERO, Length::ZERO),
    };
    let commands = glyph_outlines(glyphs, shift, places);
    if commands.is_empty() {
        return None;
    }
    match shadow.form {
        ShadowForm::Paths => Some(Item::Group(Group {
            items: vec![Item::Path(PathItem {
                commands,
                color: shadow.color,
                fill_rule: FillRule::NonZero,
            })],
            clip: None,
            places: GroupPlaces::Own,
        })),
        ShadowForm::Picture {
            blur,
            opacity,
            outline_width,
        } => super::super::shadow::stroked_picture(
            &commands,
            FillRule::NonZero,
            outline_width,
            ShadowOffset {
                across: shadow.across,
                down: shadow.down,
            },
            blur,
            ShadowColor {
                rgb: shadow.color,
                opacity,
            },
        ),
    }
}

/// The effect picture of a text glow (`w14:glow`) around the glyphs `places` of a run.
pub(super) fn glow_item(
    glyphs: (&dyn Fonts, &Face, Length, Option<Turn>),
    glow: DrawnGlow,
    places: &[DevicePlace],
) -> Option<Item> {
    if glow.radius <= Length::ZERO || glow.opacity.share() <= 0 {
        return None;
    }
    let commands = glyph_outlines(glyphs, (Length::ZERO, Length::ZERO), places);
    if commands.is_empty() {
        return None;
    }
    let half = glow.radius.div_round(2);
    let outline_width = glyphs.1.outline.map_or(Length::ZERO, |line| line.width);
    super::super::shadow::stroked_effect_picture(
        &commands,
        FillRule::NonZero,
        outline_width,
        ShadowOffset {
            across: Length::ZERO,
            down: Length::ZERO,
        },
        (half, half, glow.radius),
        ShadowColor {
            rgb: glow.color,
            opacity: glow.opacity,
        },
    )
}

/// The effect picture of a text reflection (`w14:reflection`) under the glyphs `places` of a run
/// on `baseline`: vertically mirrors the glyphs across `baseline + reflection.pivot`, clips above
/// the mirror line, fades linearly from `fade_start` to `fade_end`, and blurs by `blur`.
pub(super) fn reflection_item(
    glyphs: (&dyn Fonts, &Face, Length, Option<Turn>),
    reflection: DrawnReflection,
    baseline: Length,
    places: &[DevicePlace],
) -> Option<Item> {
    let mut commands = glyph_outlines(glyphs, (Length::ZERO, Length::ZERO), places);
    if commands.is_empty() {
        return None;
    }
    let clip_y = baseline + reflection.pivot;
    mirror_commands_y(&mut commands, clip_y);
    super::super::shadow::reflection_picture(
        &commands,
        FillRule::NonZero,
        reflection.outline_width,
        (
            clip_y,
            baseline + reflection.fade_start,
            baseline + reflection.fade_end,
        ),
        (reflection.start_opacity, reflection.end_opacity),
        reflection.blur,
        glyphs.1.color,
    )
}

/// Mirrors every point of `commands` vertically across `y = pivot_y`.
fn mirror_commands_y(commands: &mut [PathCommand], pivot_y: Length) {
    let two_pivot = pivot_y * 2;
    let flip = |p: &mut Point| p.y = two_pivot - p.y;
    for cmd in commands {
        match cmd {
            PathCommand::MoveTo(p) | PathCommand::LineTo(p) => flip(p),
            PathCommand::QuadTo(c, p) => {
                flip(c);
                flip(p);
            }
            PathCommand::CubicTo(c, d, p) => {
                flip(c);
                flip(d);
                flip(p);
            }
            PathCommand::Close => {}
        }
    }
}

/// The effect picture of a text shadow (`w14:shadow`) cast by a run that also carries a glow
/// (`w14:glow`): dilated by half the glow radius and blurred by the quadrature sum of half the
/// glow radius and the shadow's blur radius.
pub(super) fn shadow_with_glow(
    glyphs: (&dyn Fonts, &Face, Length, Option<Turn>),
    shadow: DrawnShadow,
    glow: DrawnGlow,
    places: &[DevicePlace],
) -> Option<Item> {
    if glow.radius <= Length::ZERO {
        return item(glyphs, shadow, places);
    }
    let commands = glyph_outlines(glyphs, (Length::ZERO, Length::ZERO), places);
    if commands.is_empty() {
        return None;
    }
    let outline_fallback = glyphs.1.outline.map_or(Length::ZERO, |line| line.width);
    let (blur, opacity, outline_width) = match shadow.form {
        ShadowForm::Paths => (
            Length::ZERO,
            f_office_paint::Opacity::FULL,
            outline_fallback,
        ),
        ShadowForm::Picture {
            blur,
            opacity,
            outline_width,
        } => (blur, opacity, outline_width),
    };
    let half = glow.radius.div_round(2);
    let total_blur = super::super::shadow::combined_blur(half, blur);
    let margin = glow.radius.checked_add(blur.max(Length::ZERO))?;
    super::super::shadow::stroked_effect_picture(
        &commands,
        FillRule::NonZero,
        outline_width,
        ShadowOffset {
            across: shadow.across,
            down: shadow.down,
        },
        (half, total_blur, margin),
        ShadowColor {
            rgb: shadow.color,
            opacity,
        },
    )
}

/// The point `[u, v]` of a glyph's outline, in font units with y up, on the page: `size` over
/// the em `em` (both counts) of a unit, from the glyph's `origin`, turned by `turn` about it.
fn at(
    [u, v]: [i32; 2],
    (x, y): (Length, Length),
    (size, em): (i128, i128),
    turn: Option<Turn>,
) -> Point {
    let (right, down) = (i128::from(u) * size, -i128::from(v) * size);
    let (right, down, scale) = match turn {
        None => (right, down, em),
        Some(turn) => (
            i128::from(turn.xx) * right + i128::from(turn.xy) * down,
            i128::from(turn.yx) * right + i128::from(turn.yy) * down,
            em * i128::from(Turn::SCALE),
        ),
    };
    let length = |value| Length::from_units(saturated(div_round_i128(value, scale)));
    Point {
        x: x + length(right),
        y: y + length(down),
    }
}

#[cfg(test)]
mod tests;