f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
//! Colors as properties write them: text colors, shading and highlights.

use f_office_drawingml::color::{LightnessStep, SchemeSlot};
use f_office_paint::Rgb;
use f_office_units::scale::PERCENT;
use f_office_xml::enumeration::{Drawn, Values, another, own};
use f_office_xml::{Document, NodeId};

use crate::ns::W;
use crate::params::{HIGHLIGHT_COLORS, SHADING_PERCENTS};
use crate::reader::PartReader;

/// A text color.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Color {
    /// Automatic, which is black on a white page.
    Auto,
    /// Red, green and blue.
    Rgb([u8; 3]),
}

impl Color {
    /// The red, green and blue of the color, or `None` for automatic.
    pub(crate) const fn rgb(self) -> Option<Rgb> {
        match self {
            Self::Auto => None,
            Self::Rgb([r, g, b]) => Some(Rgb { r, g, b }),
        }
    }

    /// The color that a line or text of this color draws with on the white page: automatic
    /// is black.
    pub(crate) const fn drawn(self) -> Rgb {
        match self {
            Self::Auto => Rgb::BLACK,
            Self::Rgb([r, g, b]) => Rgb { r, g, b },
        }
    }
}

/// White, as the red, green and blue of a [`Color::Rgb`].
pub const WHITE: [u8; 3] = [u8::MAX; 3];

/// A pattern of shading: none, or the share in percent of the foreground color over the fill.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Pattern {
    /// No shading (`nil`).
    Nil,
    /// The share of the foreground color.
    Share(i64),
}

/// `ST_Shd`: the percent patterns as their share in [`SHADING_PERCENTS`], and the stripes and
/// crosses as the fill alone. A missing pattern is `clear`.
pub(super) const SHADING: &Values<Pattern> = &Values::new(&[
    own("nil", Pattern::Nil),
    own("clear", Pattern::Share(0)),
    own("solid", Pattern::Share(PERCENT)),
    own(SHADING_PERCENTS[0].0, Pattern::Share(SHADING_PERCENTS[0].1)),
    own(SHADING_PERCENTS[1].0, Pattern::Share(SHADING_PERCENTS[1].1)),
    own(SHADING_PERCENTS[2].0, Pattern::Share(SHADING_PERCENTS[2].1)),
    own(SHADING_PERCENTS[3].0, Pattern::Share(SHADING_PERCENTS[3].1)),
    own(SHADING_PERCENTS[4].0, Pattern::Share(SHADING_PERCENTS[4].1)),
    own(SHADING_PERCENTS[5].0, Pattern::Share(SHADING_PERCENTS[5].1)),
    own(SHADING_PERCENTS[6].0, Pattern::Share(SHADING_PERCENTS[6].1)),
    own(SHADING_PERCENTS[7].0, Pattern::Share(SHADING_PERCENTS[7].1)),
    own(SHADING_PERCENTS[8].0, Pattern::Share(SHADING_PERCENTS[8].1)),
    own(SHADING_PERCENTS[9].0, Pattern::Share(SHADING_PERCENTS[9].1)),
    own(
        SHADING_PERCENTS[10].0,
        Pattern::Share(SHADING_PERCENTS[10].1),
    ),
    own(
        SHADING_PERCENTS[11].0,
        Pattern::Share(SHADING_PERCENTS[11].1),
    ),
    own(
        SHADING_PERCENTS[12].0,
        Pattern::Share(SHADING_PERCENTS[12].1),
    ),
    own(
        SHADING_PERCENTS[13].0,
        Pattern::Share(SHADING_PERCENTS[13].1),
    ),
    own(
        SHADING_PERCENTS[14].0,
        Pattern::Share(SHADING_PERCENTS[14].1),
    ),
    own(
        SHADING_PERCENTS[15].0,
        Pattern::Share(SHADING_PERCENTS[15].1),
    ),
    own(
        SHADING_PERCENTS[16].0,
        Pattern::Share(SHADING_PERCENTS[16].1),
    ),
    own(
        SHADING_PERCENTS[17].0,
        Pattern::Share(SHADING_PERCENTS[17].1),
    ),
    own(
        SHADING_PERCENTS[18].0,
        Pattern::Share(SHADING_PERCENTS[18].1),
    ),
    own(
        SHADING_PERCENTS[19].0,
        Pattern::Share(SHADING_PERCENTS[19].1),
    ),
    own(
        SHADING_PERCENTS[20].0,
        Pattern::Share(SHADING_PERCENTS[20].1),
    ),
    own(
        SHADING_PERCENTS[21].0,
        Pattern::Share(SHADING_PERCENTS[21].1),
    ),
    own(
        SHADING_PERCENTS[22].0,
        Pattern::Share(SHADING_PERCENTS[22].1),
    ),
    another("horzStripe", Pattern::Share(0)),
    another("vertStripe", Pattern::Share(0)),
    another("reverseDiagStripe", Pattern::Share(0)),
    another("diagStripe", Pattern::Share(0)),
    another("horzCross", Pattern::Share(0)),
    another("diagCross", Pattern::Share(0)),
    another("thinHorzStripe", Pattern::Share(0)),
    another("thinVertStripe", Pattern::Share(0)),
    another("thinReverseDiagStripe", Pattern::Share(0)),
    another("thinDiagStripe", Pattern::Share(0)),
    another("thinHorzCross", Pattern::Share(0)),
    another("thinDiagCross", Pattern::Share(0)),
]);

/// Reads the fill of a shading element (`w:shd`): its background `w:fill`, with the share of
/// its foreground `w:color` that the pattern `w:val` gives, such as 20% for `pct20` and all of
/// it for `solid`. No fill, or a clear one, gives `None`, and so does `w:val="nil"`.
pub(crate) fn read_shading(reader: &mut PartReader, node: NodeId) -> Option<Color> {
    let pattern = reader.enumeration(node, "val", SHADING);
    shading_fill(reader.doc, node, pattern)
}

/// Whether a shading element (`w:shd`) gives a fill or a pattern: a fill that [`read_shading`]
/// reads, or a pattern of stripes or crosses, which it reads as the fill alone. It reads the
/// element without a warning of its values, for a shading that F-Office does not draw and that
/// warns of itself in their place.
pub(crate) fn shows_shading(doc: &Document, node: NodeId) -> bool {
    let found = doc
        .attribute(node, Some(W), "val")
        .and_then(|name| SHADING.find(name));
    found.is_some_and(|(_, _, drawn)| drawn == Drawn::AsAnother)
        || shading_fill(doc, node, found.map(|(pattern, ..)| *pattern)).is_some()
}

/// The fill of a shading element with the pattern `pattern` (`None` for a missing pattern or a
/// value outside the type, read as `clear`), as [`read_shading`] says.
fn shading_fill(doc: &Document, node: NodeId, pattern: Option<Pattern>) -> Option<Color> {
    let share = match pattern {
        Some(Pattern::Nil) => return None,
        Some(Pattern::Share(share)) => share,
        None => 0,
    };
    let color = |name| match doc.attribute(node, Some(W), name).map(parse_color) {
        Some(Color::Rgb(rgb)) => Some(rgb),
        _ => None,
    };
    let fill = color("fill");
    if share == 0 {
        return fill.map(Color::Rgb);
    }
    // An automatic foreground is black, and an automatic background white.
    let front = color("color").unwrap_or([0; 3]);
    let back = fill.unwrap_or(WHITE);
    let mix = |f: u8, b: u8| {
        let (f, b) = (i64::from(f), i64::from(b));
        let mixed = (f * share + b * (PERCENT - share) + PERCENT / 2) / PERCENT;
        u8::try_from(mixed).unwrap_or(u8::MAX)
    };
    Some(Color::Rgb([
        mix(front[0], back[0]),
        mix(front[1], back[1]),
        mix(front[2], back[2]),
    ]))
}

/// `ST_HighlightColor`: `none`, no highlight, or one of the 16 colors of
/// [`HIGHLIGHT_COLORS`], each with its name there. Text outside the type counts as
/// missing, so the run takes its style's highlight, where F-Office read it as no highlight
/// before.
pub(super) const HIGHLIGHT: &Values<Option<[u8; 3]>> = &Values::new(&[
    own("none", None),
    own(HIGHLIGHT_COLORS[0].0, Some(HIGHLIGHT_COLORS[0].1)),
    own(HIGHLIGHT_COLORS[1].0, Some(HIGHLIGHT_COLORS[1].1)),
    own(HIGHLIGHT_COLORS[2].0, Some(HIGHLIGHT_COLORS[2].1)),
    own(HIGHLIGHT_COLORS[3].0, Some(HIGHLIGHT_COLORS[3].1)),
    own(HIGHLIGHT_COLORS[4].0, Some(HIGHLIGHT_COLORS[4].1)),
    own(HIGHLIGHT_COLORS[5].0, Some(HIGHLIGHT_COLORS[5].1)),
    own(HIGHLIGHT_COLORS[6].0, Some(HIGHLIGHT_COLORS[6].1)),
    own(HIGHLIGHT_COLORS[7].0, Some(HIGHLIGHT_COLORS[7].1)),
    own(HIGHLIGHT_COLORS[8].0, Some(HIGHLIGHT_COLORS[8].1)),
    own(HIGHLIGHT_COLORS[9].0, Some(HIGHLIGHT_COLORS[9].1)),
    own(HIGHLIGHT_COLORS[10].0, Some(HIGHLIGHT_COLORS[10].1)),
    own(HIGHLIGHT_COLORS[11].0, Some(HIGHLIGHT_COLORS[11].1)),
    own(HIGHLIGHT_COLORS[12].0, Some(HIGHLIGHT_COLORS[12].1)),
    own(HIGHLIGHT_COLORS[13].0, Some(HIGHLIGHT_COLORS[13].1)),
    own(HIGHLIGHT_COLORS[14].0, Some(HIGHLIGHT_COLORS[14].1)),
    own(HIGHLIGHT_COLORS[15].0, Some(HIGHLIGHT_COLORS[15].1)),
]);

/// `ST_ThemeColor`: each slot of the theme's color scheme, the text and background names as
/// the dark and light slots that the settings' default scheme mapping gives them (the
/// settings' own mapping is not read), and `none`, no theme color.
pub(super) const THEME_COLOR: &Values<Option<SchemeSlot>> = &Values::new(&[
    own("dark1", Some(SchemeSlot::Dark1)),
    own("light1", Some(SchemeSlot::Light1)),
    own("dark2", Some(SchemeSlot::Dark2)),
    own("light2", Some(SchemeSlot::Light2)),
    own("accent1", Some(SchemeSlot::Accent1)),
    own("accent2", Some(SchemeSlot::Accent2)),
    own("accent3", Some(SchemeSlot::Accent3)),
    own("accent4", Some(SchemeSlot::Accent4)),
    own("accent5", Some(SchemeSlot::Accent5)),
    own("accent6", Some(SchemeSlot::Accent6)),
    own("hyperlink", Some(SchemeSlot::Hyperlink)),
    own("followedHyperlink", Some(SchemeSlot::FollowedHyperlink)),
    own("none", None),
    own("background1", Some(SchemeSlot::Light1)),
    own("text1", Some(SchemeSlot::Dark1)),
    own("background2", Some(SchemeSlot::Light2)),
    own("text2", Some(SchemeSlot::Dark2)),
]);

/// The text color of a `w:color` element: the theme's color that `w:themeColor` names, moved
/// toward white by `w:themeTint` or toward black by `w:themeShade`, in place of the value
/// `w:val`, when the theme has that color; else the value ([`parse_color`]), or `None` when
/// the element gives neither. A tint or shade is a hexadecimal number of any length up to
/// `FF`, such as `0000BF`. A value within one step of each channel of the moved color is the
/// color that Word saved for it, which the lightness form misses by one step on some colors,
/// and it is drawn as it is.
pub(super) fn read_text_color(reader: &mut PartReader, node: NodeId) -> Option<Color> {
    let doc = reader.doc;
    let value = doc.attribute(node, Some(W), "val").map(parse_color);
    let Some(rgb) = reader
        .enumeration(node, "themeColor", THEME_COLOR)
        .flatten()
        .and_then(|slot| reader.scheme().get(slot))
    else {
        return value;
    };
    let steps = crate::numbers::UCHAR_HEX;
    let step = reader
        .hex(node, "themeTint", steps.clone())
        .map(LightnessStep::Tint)
        .or_else(|| {
            reader
                .hex(node, "themeShade", steps)
                .map(LightnessStep::Shade)
        });
    let Rgb { r, g, b } = step.map_or(rgb, |step| step.apply(rgb));
    let moved = [r, g, b];
    match value {
        Some(Color::Rgb(saved)) if saved.iter().zip(moved).all(|(s, m)| s.abs_diff(m) <= 1) => {
            Some(Color::Rgb(saved))
        }
        _ => Some(Color::Rgb(moved)),
    }
}

/// Reads a color such as `FF0080`, six hexadecimal digits ([`Rgb::from_hex`]). Anything else,
/// such as `auto`, is automatic.
pub fn parse_color(value: &str) -> Color {
    Rgb::from_hex(value).map_or(Color::Auto, |Rgb { r, g, b }| Color::Rgb([r, g, b]))
}

/// The page color of the document whose root element is `root`: the color of its
/// `w:background`, or `None` for no page color or an automatic one.
pub(crate) fn read_page_color(doc: &Document, root: NodeId) -> Option<[u8; 3]> {
    let background = doc.child(root, W, "background")?;
    match parse_color(doc.attribute(background, Some(W), "color")?) {
        Color::Rgb(rgb) => Some(rgb),
        Color::Auto => None,
    }
}

#[cfg(test)]
mod tests {
    use f_office_paint::Rgb;

    use super::Color;

    /// Automatic draws black and has no red, green and blue of its own; a color keeps its own.
    #[test]
    fn draws_automatic_black_and_a_color_as_itself() {
        let red = Rgb { r: 255, g: 0, b: 0 };
        assert_eq!(Color::Auto.drawn(), Rgb::BLACK);
        assert_eq!(Color::Auto.rgb(), None);
        assert_eq!(Color::Rgb([255, 0, 0]).drawn(), red);
        assert_eq!(Color::Rgb([255, 0, 0]).rgb(), Some(red));
    }
}