use f_office_paint::{FillRule, GradientItem, GradientStop, PathCommand, Point, Rgb};
use f_office_units::fixed::{ONE, rounded, sin_cos};
use f_office_units::scale::{DRAWING_WHOLE, FULL_TURN};
use f_office_units::{Edges, Length, div_round_i128};
use f_office_warnings::Warnings;
use f_office_xml::{Document, NodeId};
use crate::color::{
ColorNames, DrawColor, PlaceholderModifiers, SchemeColors, WORD_2010, percentage,
};
use crate::{A, Warning, attribute_of, integer, integer_of};
mod curve;
#[cfg(test)]
mod tests;
const MOST_STOPS: usize = 256;
const FEWEST_STOPS: usize = 2;
const DIRECTION_BITS: u32 = 31;
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct LinearGradient {
stops: Vec<(i64, DrawColor)>,
angle: i64,
scaled: bool,
rot_with_shape: bool,
}
impl LinearGradient {
#[must_use]
pub fn read(doc: &Document, fill: NodeId, warnings: &mut Warnings<Warning>) -> Option<Self> {
let (angle, scaled, rot_with_shape) = read_linear_head(doc, fill, false, warnings)?;
let stops = read_stops(doc, fill, true, warnings)?;
Some(Self {
stops,
angle,
scaled,
rot_with_shape,
})
}
#[must_use]
pub fn read_word2010(
doc: &Document,
fill: NodeId,
warnings: &mut Warnings<Warning>,
) -> Option<Self> {
let (angle, scaled) = read_word2010_head(doc, fill)?;
let list = doc.child(fill, WORD_2010, "gsLst")?;
let mut stops = Vec::new();
for stop in doc
.child_elements(list)
.filter(|&node| doc.is(node, WORD_2010, "gs"))
{
if stops.len() == MOST_STOPS {
return None;
}
let place = percentage(doc.attribute(stop, Some(WORD_2010), "pos")?)?;
let (color, unread) =
DrawColor::read_marked(doc, stop, ColorNames::Word2010, warnings)?;
if !(0..=DRAWING_WHOLE).contains(&place) || unread || !color.opaque() {
return None;
}
stops.push((place, color));
}
if stops.len() < FEWEST_STOPS {
return None;
}
stops.sort_by_key(|&(place, _)| place);
Some(Self {
stops,
angle,
scaled,
rot_with_shape: true,
})
}
pub(crate) const fn linear_params(&self) -> (i64, bool, bool) {
(self.angle, self.scaled, self.rot_with_shape)
}
pub(crate) fn resolve_stops(&self, scheme: &SchemeColors) -> Option<Vec<GradientStop>> {
let colors = self
.stops
.iter()
.map(|(place, color)| Some((*place, color.resolve(scheme)?.0)))
.collect::<Option<Vec<_>>>()?;
match two_colors(&colors) {
Some(colors) => Some(curve_stops(&colors)),
None => colors
.iter()
.map(|&(place, rgb)| {
Some(GradientStop::new(u32::try_from(place * 10).ok()?, rgb))
})
.collect(),
}
}
#[must_use]
pub fn fill_path(
&self,
commands: Vec<PathCommand>,
fill_rule: FillRule,
corners: (Point, Point),
scheme: &SchemeColors,
) -> Option<GradientItem> {
let stops = self.resolve_stops(scheme)?;
let axis = self.axis(corners)?;
Some(GradientItem::new(commands, fill_rule, axis, stops))
}
#[must_use]
pub fn item(
&self,
(top_left, bottom_right): (Point, Point),
scheme: &SchemeColors,
) -> Option<GradientItem> {
let stops = self.resolve_stops(scheme)?;
let (left, top, right, bottom) = (top_left.x, top_left.y, bottom_right.x, bottom_right.y);
let corner = |x: Length, y: Length| Point { x, y };
let commands = vec![
PathCommand::MoveTo(corner(left, top)),
PathCommand::LineTo(corner(right, top)),
PathCommand::LineTo(corner(right, bottom)),
PathCommand::LineTo(corner(left, bottom)),
PathCommand::Close,
];
let axis = self.axis((top_left, bottom_right))?;
Some(GradientItem::new(commands, FillRule::NonZero, axis, stops))
}
fn axis(&self, corners: (Point, Point)) -> Option<(Point, Point)> {
linear_axis(self.angle, self.scaled, corners)
}
}
pub(crate) fn linear_axis(
angle: i64,
scaled: bool,
(top_left, bottom_right): (Point, Point),
) -> Option<(Point, Point)> {
let width = i128::from((bottom_right.x - top_left.x).units());
let height = i128::from((bottom_right.y - top_left.y).units());
let [sin, cos] = sin_cos(i128::from(angle) * ONE);
let (across, down) = if scaled {
(cos * height, sin * width)
} else {
(cos, sin)
};
let shift = (128
- across
.unsigned_abs()
.max(down.unsigned_abs())
.leading_zeros())
.saturating_sub(DIRECTION_BITS);
let (across, down) = (across >> shift, down >> shift);
let square = across * across + down * down;
if square == 0 {
return None;
}
let reach = across
.abs()
.checked_mul(width.abs())?
.checked_add(down.abs().checked_mul(height.abs())?)?;
let offset = |component: i128| Some(rounded(component.checked_mul(reach)?, square));
let (along, onto) = (offset(across)?, offset(down)?);
let doubled = |low: Length, high: Length| i128::from(low.units()) + i128::from(high.units());
let (x, y) = (
doubled(top_left.x, bottom_right.x),
doubled(top_left.y, bottom_right.y),
);
let point = |x: i128, y: i128| {
Some(Point {
x: Length::from_units(i64::try_from(rounded(x, 2)).ok()?),
y: Length::from_units(i64::try_from(rounded(y, 2)).ok()?),
})
};
Some((point(x - along, y - onto)?, point(x + along, y + onto)?))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PathGradientKind {
Circle,
Rect,
Shape,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum EffectGradientKind {
Linear { angle: i64, scaled: bool },
Path {
kind: PathGradientKind,
focus: (i64, i64),
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct EffectGradient {
stops: Vec<(i64, DrawColor)>,
kind: EffectGradientKind,
rot_with_shape: bool,
}
impl EffectGradient {
pub(crate) const fn kind(&self) -> EffectGradientKind {
self.kind
}
pub(crate) const fn rot_with_shape(&self) -> bool {
self.rot_with_shape
}
pub(crate) fn resolve_stops(&self, scheme: &SchemeColors) -> Option<Vec<(u32, [u8; 4])>> {
let mut resolved = Vec::with_capacity(self.stops.len());
let mut all_opaque = true;
for (place, color) in &self.stops {
let (rgb, opacity) = color.resolve(scheme)?;
let alpha = u8::try_from(div_round_i128(
i128::from(opacity.share()) * 255,
i128::from(DRAWING_WHOLE),
))
.ok()?;
if alpha < u8::MAX {
all_opaque = false;
}
resolved.push((*place, rgb, alpha));
}
if all_opaque && matches!(self.kind, EffectGradientKind::Path { .. }) {
let rgb_stops: Vec<(i64, Rgb)> = resolved
.iter()
.map(|&(place, rgb, _)| (place, rgb))
.collect();
if let Some(colors) = two_colors(&rgb_stops) {
return Some(curve_direct_stops(&colors));
}
}
resolved
.iter()
.map(|&(place, rgb, alpha)| {
let place = u32::try_from(place * 10).ok()?;
Some((place, [rgb.r, rgb.g, rgb.b, alpha]))
})
.collect()
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum ShapeFillGradient {
Linear(LinearGradient),
Effect(EffectGradient),
}
impl ShapeFillGradient {
pub(crate) fn read_shape(
doc: &Document,
fill: NodeId,
warnings: &mut Warnings<Warning>,
) -> Option<Self> {
let (kind, rot_with_shape) = read_shape_head(doc, fill, warnings)?;
let stops = read_stops(doc, fill, false, warnings)?;
match kind {
EffectGradientKind::Linear { angle, scaled }
if stops.iter().all(|(_, color)| color.opaque()) =>
{
Some(Self::Linear(LinearGradient {
stops,
angle,
scaled,
rot_with_shape,
}))
}
kind => Some(Self::Effect(EffectGradient {
stops,
kind,
rot_with_shape,
})),
}
}
pub(crate) fn first_color(&self) -> Option<DrawColor> {
let stops = match self {
Self::Linear(grad) => &grad.stops,
Self::Effect(grad) => &grad.stops,
};
stops.first().map(|(_, color)| color.clone())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResolvedEffectGradientKind {
Linear {
start: Point,
end: Point,
},
Radial {
center: Point,
rx: Length,
ry: Length,
},
Rect {
center: Point,
bounds: Edges<Length>,
},
Shape {
center: Point,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ResolvedEffectGradient {
pub kind: ResolvedEffectGradientKind,
pub stops: Vec<(u32, [u8; 4])>,
}
fn two_colors(stops: &[(i64, Rgb)]) -> Option<Vec<Rgb>> {
match *stops {
[(0, first), (DRAWING_WHOLE, last)] => Some(vec![first, last]),
[(0, first), (place, middle), (DRAWING_WHOLE, last)]
if first == last && 0 < place && place < DRAWING_WHOLE =>
{
Some(vec![first, middle, last])
}
_ => None,
}
}
fn curve_stops(colors: &[Rgb]) -> Vec<GradientStop> {
let count = curve::PIECE_STEPS * colors.len().saturating_sub(1) + 1;
let mut stops = Vec::with_capacity(count);
for (piece, pair) in colors.windows(2).enumerate() {
let [from, to] =
[pair.first(), pair.last()].map(|color| color.copied().unwrap_or(Rgb::BLACK));
let first = usize::from(piece > 0);
for step in first..=curve::PIECE_STEPS {
let rgb = Rgb {
r: curve::channel(from.r, to.r, step),
g: curve::channel(from.g, to.g, step),
b: curve::channel(from.b, to.b, step),
};
let place = sample_place(piece * curve::PIECE_STEPS + step, count);
stops.push(GradientStop::new(place, rgb));
}
}
stops
}
fn curve_direct_stops(colors: &[Rgb]) -> Vec<(u32, [u8; 4])> {
let count = curve::PIECE_STEPS * colors.len().saturating_sub(1) + 1;
let last = u64::try_from(count.saturating_sub(1)).unwrap_or(1).max(1);
let end = u64::from(GradientStop::END);
let mut stops = Vec::with_capacity(count);
for (piece, pair) in colors.windows(2).enumerate() {
let [from, to] =
[pair.first(), pair.last()].map(|color| color.copied().unwrap_or(Rgb::BLACK));
let first = usize::from(piece > 0);
for step in first..=curve::PIECE_STEPS {
let idx = u64::try_from(piece * curve::PIECE_STEPS + step).unwrap_or(last);
let place = u32::try_from((idx * end * 2 + last) / (last * 2))
.map_or(GradientStop::END, |p| p.min(GradientStop::END));
stops.push((
place,
[
curve::channel(from.r, to.r, step),
curve::channel(from.g, to.g, step),
curve::channel(from.b, to.b, step),
u8::MAX,
],
));
}
}
stops
}
fn sample_place(index: usize, count: usize) -> u32 {
let (Ok(index), Ok(count)) = (u64::try_from(index), u64::try_from(count)) else {
return GradientStop::END;
};
let (part, whole) = (2 * index + 1, (2 * count).saturating_sub(1).max(1));
let end = u64::from(GradientStop::END);
u32::try_from((2 * part * end + whole) / (2 * whole))
.map_or(GradientStop::END, |place| place.min(GradientStop::END))
}
fn read_stops(
doc: &Document,
fill: NodeId,
require_opaque: bool,
warnings: &mut Warnings<Warning>,
) -> Option<Vec<(i64, DrawColor)>> {
let list = doc.child(fill, A, "gsLst")?;
let mut stops = Vec::new();
for stop in doc
.child_elements(list)
.filter(|&node| doc.is(node, A, "gs"))
{
if stops.len() == MOST_STOPS {
return None;
}
let place = attribute_of(doc, stop, "pos", percentage, warnings)?;
let (color, unread) = DrawColor::read_marked(doc, stop, ColorNames::DrawingMl, warnings)?;
if !(0..=DRAWING_WHOLE).contains(&place) || unread || (require_opaque && !color.opaque()) {
return None;
}
stops.push((place, color));
}
if stops.len() < FEWEST_STOPS {
return None;
}
stops.sort_by_key(|&(place, _)| place);
Some(stops)
}
fn read_word2010_head(doc: &Document, fill: NodeId) -> Option<(i64, bool)> {
if doc.child(fill, WORD_2010, "path").is_some() {
return None;
}
let Some(shade) = doc.child(fill, WORD_2010, "lin") else {
return Some((0, false));
};
let angle = match doc.attribute(shade, Some(WORD_2010), "ang") {
Some(text) => integer(text)?,
None => 0,
};
if !(0..FULL_TURN).contains(&angle) {
return None;
}
let scaled = doc
.attribute(shade, Some(WORD_2010), "scaled")
.is_some_and(crate::boolean);
Some((angle, scaled))
}
fn read_linear_head(
doc: &Document,
fill: NodeId,
allow_omitted_lin: bool,
warnings: &mut Warnings<Warning>,
) -> Option<(i64, bool, bool)> {
if doc.child(fill, A, "path").is_some() || !whole_tile(doc, fill) {
return None;
}
let (angle, scaled) = match doc.child(fill, A, "lin") {
Some(shade) => {
let angle = integer_of(doc, shade, "ang", warnings).unwrap_or(0);
if !(0..FULL_TURN).contains(&angle) {
return None;
}
let scaled = doc
.attribute(shade, None, "scaled")
.is_some_and(crate::boolean);
(angle, scaled)
}
None if allow_omitted_lin => (0, false),
None => return None,
};
let rot_with_shape = doc
.attribute(fill, None, "rotWithShape")
.is_none_or(crate::boolean);
Some((angle, scaled, rot_with_shape))
}
fn read_shape_head(
doc: &Document,
fill: NodeId,
warnings: &mut Warnings<Warning>,
) -> Option<(EffectGradientKind, bool)> {
if !whole_tile(doc, fill) {
return None;
}
let rot_with_shape = doc
.attribute(fill, None, "rotWithShape")
.is_none_or(crate::boolean);
if let Some(path) = doc.child(fill, A, "path") {
let kind = match doc.attribute(path, None, "path") {
Some("circle") => PathGradientKind::Circle,
Some("rect") => PathGradientKind::Rect,
Some("shape") => PathGradientKind::Shape,
_ => return None,
};
let focus = read_fill_to_rect(doc, path, warnings);
return Some((EffectGradientKind::Path { kind, focus }, rot_with_shape));
}
let (angle, scaled, _) = read_linear_head(doc, fill, true, warnings)?;
Some((EffectGradientKind::Linear { angle, scaled }, rot_with_shape))
}
fn read_fill_to_rect(doc: &Document, path: NodeId, warnings: &mut Warnings<Warning>) -> (i64, i64) {
let half = DRAWING_WHOLE / 2;
let Some(rect) = doc.child(path, A, "fillToRect") else {
return (half, half);
};
let mut side = |name: &str| attribute_of(doc, rect, name, percentage, warnings).unwrap_or(0);
let (l, t, r, b) = (side("l"), side("t"), side("r"), side("b"));
let cx = i64::midpoint(l, DRAWING_WHOLE - r).clamp(0, DRAWING_WHOLE);
let cy = i64::midpoint(t, DRAWING_WHOLE - b).clamp(0, DRAWING_WHOLE);
(cx, cy)
}
#[derive(Clone, Debug, PartialEq, Eq)]
enum ThemeStopColor {
Fixed(DrawColor),
Placeholder(PlaceholderModifiers),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ThemeGradient {
stops: Vec<(i64, ThemeStopColor)>,
kind: EffectGradientKind,
rot_with_shape: bool,
}
impl ThemeGradient {
pub(crate) fn read(doc: &Document, fill: NodeId) -> Option<Self> {
if !doc.is(fill, A, "gradFill") {
return None;
}
let mut warnings = Warnings::new();
let (kind, rot_with_shape) = read_shape_head(doc, fill, &mut warnings)?;
let list = doc.child(fill, A, "gsLst")?;
let mut stops = Vec::new();
for stop in doc
.child_elements(list)
.filter(|&node| doc.is(node, A, "gs"))
{
if stops.len() == MOST_STOPS {
return None;
}
let place = attribute_of(doc, stop, "pos", percentage, &mut warnings)?;
if !(0..=DRAWING_WHOLE).contains(&place) {
return None;
}
let color = if let Some(modifiers) =
PlaceholderModifiers::read_child(doc, stop, &mut warnings)
{
ThemeStopColor::Placeholder(modifiers)
} else {
let (color, unread) =
DrawColor::read_marked(doc, stop, ColorNames::DrawingMl, &mut warnings)?;
if unread {
return None;
}
ThemeStopColor::Fixed(color)
};
stops.push((place, color));
}
if stops.len() < FEWEST_STOPS {
return None;
}
stops.sort_by_key(|&(place, _)| place);
Some(Self {
stops,
kind,
rot_with_shape,
})
}
pub(crate) fn resolve(&self, reference_color: Option<&DrawColor>) -> Option<ShapeFillGradient> {
let mut stops = Vec::with_capacity(self.stops.len());
for (place, stop) in &self.stops {
let color = match stop {
ThemeStopColor::Fixed(color) => color.clone(),
ThemeStopColor::Placeholder(modifiers) => {
reference_color?.clone().in_place_of(*modifiers)
}
};
stops.push((*place, color));
}
match self.kind {
EffectGradientKind::Linear { angle, scaled }
if stops.iter().all(|(_, color)| color.opaque()) =>
{
Some(ShapeFillGradient::Linear(LinearGradient {
stops,
angle,
scaled,
rot_with_shape: self.rot_with_shape,
}))
}
kind => Some(ShapeFillGradient::Effect(EffectGradient {
stops,
kind,
rot_with_shape: self.rot_with_shape,
})),
}
}
}
fn whole_tile(doc: &Document, fill: NodeId) -> bool {
let flips = doc
.attribute(fill, None, "flip")
.is_some_and(|flip| flip != "none");
let tiled = doc.child(fill, A, "tileRect").is_some_and(|tile| {
["l", "t", "r", "b"].iter().any(|side| {
doc.attribute(tile, None, side)
.is_some_and(|inset| percentage(inset) != Some(0))
})
});
!flips && !tiled
}