f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
//! The shadow of a run's text (`w14:shadow`): the share of its lengths that it takes at the
//! run's size, the room that it takes in its line, and the shadow that the target draws as the
//! paths of the glyphs.

use f_office_drawingml::effect::ShadowOffset;
use f_office_paint::{Opacity, Outline, Rgb};
use f_office_units::scale::{DRAWING_WHOLE, PERCENT};
use f_office_units::{Length, div_round_i128, saturated};

use super::face::{DrawnGlow, DrawnReflection, DrawnShadow, ShadowForm, ShadowRoom};
use crate::params::{
    LEGACY_TEXT_SHADOW_DIVISOR, LEGACY_TEXT_SHADOW_GRAY, REFLECTION_DIST_SCALE,
    REFLECTION_END_ALPHA_FLOOR, SHADOW_BOX_STEP, TEXT_SHADOW_BASE_OFFSET, TEXT_SHADOW_POWER,
    TEXT_SHADOW_SIZE,
};
use crate::props::{RunProps, TextGlow, TextReflection, TextShadow};

/// The offset `d` of legacy WordprocessingML text shadow, emboss, and imprint effects at font
/// size `size`: `size / 24` rounded to the nearest [`SHADOW_BOX_STEP`] (0.12 pt), at least one
/// step.
pub(crate) fn legacy_offset(size: Length) -> Length {
    let step = SHADOW_BOX_STEP.units();
    let divisor = i128::from(LEGACY_TEXT_SHADOW_DIVISOR) * i128::from(step);
    let steps = div_round_i128(i128::from(size.units()), divisor).max(1);
    Length::from_units(saturated(steps * i128::from(step)))
}

/// The drawn shadow for a legacy WordprocessingML `w:shadow` at font size `size`: `#C0C0C0`
/// filled glyph paths shifted down-right by [`legacy_offset`].
pub(super) fn legacy_shadow(size: Length) -> DrawnShadow {
    let offset = legacy_offset(size);
    let gray = LEGACY_TEXT_SHADOW_GRAY;
    DrawnShadow {
        across: offset,
        down: offset,
        color: Rgb {
            r: gray,
            g: gray,
            b: gray,
        },
        form: ShadowForm::Paths,
    }
}

/// The room in its line of the shadow `shadow` of text of the size `size`: its blur radius and
/// its offset down, each scaled by [`share`] and rounded to the nearest unit, give the room
/// above the ascent as the blur less the offset and the room below the descent as the blur
/// plus the offset, neither below 0. An offset up is an offset down below 0.
pub(super) fn room(shadow: TextShadow, size: Length) -> ShadowRoom {
    let share = share(size);
    let blur = scaled(shadow.blur, share);
    let down = scaled(
        ShadowOffset::of(shadow.distance, shadow.direction).down,
        share,
    );
    ShadowRoom {
        above: (blur - down).max(Length::ZERO),
        below: (blur + down).max(Length::ZERO),
    }
}

/// The color and opacity of the shadow `shadow` when the target draws it, of a run that is not
/// scaled horizontally (`scaled`, [`scaled_run`]): an untransformed shadow with a color that
/// F-Office finds and a positive opacity (`100% - w14:alpha`). `None` for a scaled run, a scaled
/// or skewed shadow, a wholly transparent shadow, or a color that F-Office does not find.
pub(super) fn sharp(shadow: TextShadow, scaled: bool) -> Option<(Rgb, Opacity)> {
    if scaled {
        return None;
    }
    let [r, g, b] = shadow.color?;
    let opacity = Opacity::clamped(DRAWING_WHOLE - shadow.transparency);
    if opacity.share() <= 0 {
        return None;
    }
    Some((Rgb { r, g, b }, opacity))
}

/// The shadow `shadow` of text of the line size `size`, with `outline` along its glyphs, if any,
/// and `scaled` saying whether the run has a horizontal character scale other than 100%
/// ([`sharp`]): it lies the share s ([`share`]) of its distance and (1 − s) of
/// [`TEXT_SHADOW_BASE_OFFSET`] away, in its direction, each part of the offset rounded to the
/// nearest unit, and its blur spans s of `shadow.blur`. A sharp opaque shadow without an outline
/// is drawn as filled glyph paths; any blurred, translucent or outlined shadow is drawn as an
/// effect picture.
pub(super) fn drawn(
    shadow: TextShadow,
    outline: Option<Outline>,
    scaled_text: bool,
    size: Length,
) -> Option<DrawnShadow> {
    let (color, opacity) = sharp(shadow, scaled_text)?;
    let share = share(size);
    let length = div_round_i128(
        i128::from(shadow.distance.units()) * share
            + i128::from(TEXT_SHADOW_BASE_OFFSET.units()) * (ONE - share),
        ONE,
    );
    let offset = ShadowOffset::of(Length::from_units(saturated(length)), shadow.direction);
    let blur = scaled(shadow.blur, share);
    let form = if blur <= Length::ZERO && opacity == Opacity::FULL && outline.is_none() {
        ShadowForm::Paths
    } else {
        ShadowForm::Picture {
            blur: blur.max(Length::ZERO),
            opacity,
            outline_width: outline.map_or(Length::ZERO, |line| line.width),
        }
    };
    Some(DrawnShadow {
        across: offset.across,
        down: offset.down,
        color,
        form,
    })
}

/// The room in its line of the glow `glow` of text of the size `size`: its radius scaled by
/// [`share`], split into its dilation half and half its blur half (`half + half / 2`), added
/// symmetrically above the ascent and below the descent.
pub(super) fn glow_room(glow: TextGlow, size: Length) -> ShadowRoom {
    let radius = scaled(glow.radius, share(size));
    let half = radius.div_round(2);
    let room = (half + half.div_round(2)).max(Length::ZERO);
    ShadowRoom {
        above: room,
        below: room,
    }
}

/// The glow `glow` of text of the line size `size`, with `scaled_text` saying whether the run
/// has a horizontal character scale other than 100%: its radius scaled by [`share`], color, and
/// opacity (`100% - w14:alpha`).
pub(super) fn drawn_glow(glow: TextGlow, scaled_text: bool, size: Length) -> Option<DrawnGlow> {
    if scaled_text || glow.radius <= Length::ZERO {
        return None;
    }
    let [r, g, b] = glow.color?;
    let opacity = Opacity::clamped(DRAWING_WHOLE - glow.transparency);
    if opacity.share() <= 0 {
        return None;
    }
    let radius = scaled(glow.radius, share(size));
    Some(DrawnGlow {
        radius,
        color: Rgb { r, g, b },
        opacity,
    })
}

/// Mirror pivot distance below the baseline for a text reflection: `distance * descent /
/// REFLECTION_DIST_SCALE`.
fn reflection_pivot(distance: Length, descent: Length) -> Length {
    if distance <= Length::ZERO || descent <= Length::ZERO {
        return Length::ZERO;
    }
    let scaled = div_round_i128(
        i128::from(distance.units()) * i128::from(descent.units()),
        i128::from(REFLECTION_DIST_SCALE.units()),
    );
    Length::from_units(saturated(scaled))
}

/// Scaled blur radius for a text reflection: `blur * line_size / TEXT_SHADOW_SIZE`.
fn reflection_blur(blur: Length, size: Length) -> Length {
    if blur <= Length::ZERO || size <= Length::ZERO {
        return Length::ZERO;
    }
    let scaled = div_round_i128(
        i128::from(blur.units()) * i128::from(size.units()),
        i128::from(TEXT_SHADOW_SIZE.units()),
    );
    Length::from_units(saturated(scaled))
}

/// The room in its line of the reflection `reflection` of text with line `ascent`, `descent`, and
/// `size`: adds nothing above the ascent, and expands descent to `eff_end * ascent + 2 * pivot +
/// blur_scaled`.
pub(super) fn reflection_room(
    reflection: TextReflection,
    (ascent, descent, size): (Length, Length, Length),
) -> ShadowRoom {
    if !reflection.downward {
        return ShadowRoom::default();
    }
    let pivot = reflection_pivot(reflection.distance, descent);
    let blur = reflection_blur(reflection.blur, size);
    let eff_end = if reflection.end_alpha >= REFLECTION_END_ALPHA_FLOOR {
        DRAWING_WHOLE
    } else {
        reflection.end_pos
    };
    let ascent_part = Length::from_units(saturated(div_round_i128(
        i128::from(ascent.units()) * i128::from(eff_end),
        i128::from(DRAWING_WHOLE),
    )));
    let total_below = ascent_part + pivot * 2 + blur;
    ShadowRoom {
        above: Length::ZERO,
        below: (total_below - descent).max(Length::ZERO),
    }
}

/// The drawn reflection (`w14:reflection`) for a run with `outline`, horizontal-scale flag
/// `scaled_text`, and line `(ascent, descent, size)`.
pub(super) fn drawn_reflection(
    reflection: TextReflection,
    outline: Option<Outline>,
    scaled_text: bool,
    (ascent, descent, size): (Length, Length, Length),
) -> Option<DrawnReflection> {
    if scaled_text || !reflection.downward {
        return None;
    }
    let start_opacity = Opacity::clamped(reflection.start_alpha);
    let end_raw = if reflection.end_alpha < REFLECTION_END_ALPHA_FLOOR {
        0
    } else {
        reflection.end_alpha
    };
    let end_opacity = Opacity::clamped(end_raw);
    if start_opacity.share() <= 0 && end_opacity.share() <= 0 {
        return None;
    }
    let pivot = reflection_pivot(reflection.distance, descent);
    let blur = reflection_blur(reflection.blur, size);
    let full_span = (ascent + pivot).max(Length::ZERO);
    let at_pos = |pos: i64| {
        pivot
            + Length::from_units(saturated(div_round_i128(
                i128::from(full_span.units()) * i128::from(pos),
                i128::from(DRAWING_WHOLE),
            )))
    };
    let fade_start = at_pos(reflection.start_pos);
    let fade_end = at_pos(reflection.end_pos).max(fade_start);
    Some(DrawnReflection {
        pivot,
        blur,
        fade_start,
        fade_end,
        start_opacity,
        end_opacity,
        outline_width: outline.map_or(Length::ZERO, |line| line.width),
    })
}

/// Whether a run with `props` has a character scale (`w:w`) other than 100%, whose shadowed text
/// the target draws as paths at places of its own, so that F-Office leaves its shadow undrawn.
pub(super) fn scaled_run(props: &RunProps) -> bool {
    props.scale.is_some_and(|scale| scale != PERCENT)
}

/// The fixed point of [`share`], 2^56: the share counts in parts of it. A root below 2 times
/// itself, and a ratio below 2^10 times the fixed point, stay within an `i128`, and a share
/// this fine gives the lengths of a shadow to their nearest unit.
const ONE: i128 = 1 << (u64::BITS - u8::BITS);

/// The share of its lengths that the shadow of text of the size `size` takes, in parts of
/// [`ONE`]: the size over [`TEXT_SHADOW_SIZE`] to the power of [`TEXT_SHADOW_POWER`], a
/// fraction `n / d`, which is the `d`-th root of the ratio to the `n`-th power. The root comes
/// from Newton's steps in integer arithmetic, which every platform computes alike, from above
/// until a step no longer falls. 0 for a size of 0 or less, or of 2^`d` times the reference
/// size or more, whose root would leave the range of the computation.
fn share(size: Length) -> i128 {
    let (power, root) = TEXT_SHADOW_POWER;
    let units = i128::from(size.units());
    let reference = i128::from(TEXT_SHADOW_SIZE.units());
    if units <= 0 || reference <= 0 || units >= reference << root {
        return 0;
    }
    let ratio = div_round_i128(units * ONE, reference);
    // The root lies below 2, and at or below 1 for a ratio of at most 1, so the steps start
    // above it and fall to it.
    let mut base = if ratio > ONE { 2 * ONE } else { ONE };
    loop {
        let below = times_itself(base, root - 1);
        let next = div_round_i128(
            i128::from(root - 1) * base + div_round_i128(ratio * ONE, below),
            i128::from(root),
        );
        if next >= base {
            return times_itself(base, power);
        }
        base = next;
    }
}

/// `value`, in parts of [`ONE`], multiplied by itself to make `count` factors, each product
/// rounded to the nearest part; [`ONE`] for none.
fn times_itself(value: i128, count: u32) -> i128 {
    (0..count).fold(ONE, |product, _| div_round_i128(product * value, ONE))
}

/// `length` times `share`, in parts of [`ONE`], rounded to the nearest unit, a half up.
fn scaled(length: Length, share: i128) -> Length {
    Length::from_units(saturated(div_round_i128(
        i128::from(length.units()) * share,
        ONE,
    )))
}

#[cfg(test)]
mod tests;