f-office-docx 0.1.0

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::{DrawnShadow, ShadowForm, ShadowRoom};
use crate::params::{TEXT_SHADOW_BASE_OFFSET, TEXT_SHADOW_POWER, TEXT_SHADOW_SIZE};
use crate::props::{RunProps, TextShadow};

/// 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,
    })
}

/// 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;