use f_office_paint::{FillRule, Rgb};
use f_office_units::Edges;
use std::fmt;
use crate::params::ART_STROKE_UNIT;
use crate::props::ArtStyle;
pub use crate::params::{
ART_PICTURES_BYTE_LIMIT, ART_PICTURES_CLIP_DEPTH_LIMIT, ART_PICTURES_COMMAND_LIMIT,
ART_PICTURES_REACH_LIMIT, ART_PICTURES_SHAPE_LIMIT, ART_PICTURES_SIZE_LIMIT,
};
const HEADER: &str = "f-office art pictures 3";
pub(crate) const UNIT: i32 = crate::params::ART_PICTURE_UNIT;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ArtPictures {
pictures: Vec<ArtPicture>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct ArtPicture {
style: ArtStyle,
size: u32,
pub sides: Edges<SidePicture>,
pub corners: Corners<Vec<ArtItem>>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct SidePicture {
pub repeat: Vec<ArtItem>,
pub span: Vec<ArtItem>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct Corners<T> {
pub top_left: T,
pub top_right: T,
pub bottom_left: T,
pub bottom_right: T,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum ArtItem {
Shape(ArtShape),
Rect(ArtRect),
Clip(ArtClip),
End,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ArtClip {
pub fill_rule: FillRule,
pub commands: Vec<UnitCommand>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ArtShape {
pub color: Rgb,
pub fill_rule: FillRule,
pub commands: Vec<UnitCommand>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct ArtRect {
pub color: Rgb,
pub top_left: UnitPoint,
pub bottom_right: UnitPoint,
pub stroke: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum UnitCommand {
Move(UnitPoint),
Line(UnitPoint),
Quad(UnitPoint, UnitPoint),
Cubic(UnitPoint, UnitPoint, UnitPoint),
Close,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct UnitPoint {
pub x: i32,
pub y: i32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ArtPicturesError {
pub line: usize,
pub fault: ArtPicturesFault,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ArtPicturesFault {
TooLarge,
NotText,
Header,
Style,
Part,
Shape,
Clip,
Rect,
End,
Ring,
Unknown,
TooManyShapes,
TooManyCommands,
TooDeep,
}
impl fmt::Display for ArtPicturesError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let what = match self.fault {
ArtPicturesFault::TooLarge => "the file is too large",
ArtPicturesFault::NotText => "the file is not UTF-8 text",
ArtPicturesFault::Header => "the file does not start with the form's first line",
ArtPicturesFault::Style => "a style line does not read",
ArtPicturesFault::Part => "a part line does not read",
ArtPicturesFault::Shape => "a shape line does not read",
ArtPicturesFault::Clip => "a clip line does not read",
ArtPicturesFault::Rect => "a rect line does not read",
ArtPicturesFault::End => "a clip does not end where it should",
ArtPicturesFault::Ring => "a ring line does not read",
ArtPicturesFault::Unknown => "a line is of no kind of the form",
ArtPicturesFault::TooManyShapes => "a part holds too many items",
ArtPicturesFault::TooManyCommands => "an outline holds too many commands",
ArtPicturesFault::TooDeep => "too many clips are open at once",
};
if self.line == 0 {
write!(f, "the art pictures do not read: {what}")
} else {
write!(
f,
"the art pictures do not read: {what} (line {})",
self.line
)
}
}
}
impl std::error::Error for ArtPicturesError {}
impl ArtPictures {
#[must_use]
pub const fn new() -> Self {
Self {
pictures: Vec::new(),
}
}
pub fn add(&mut self, bytes: &[u8]) -> Result<usize, ArtPicturesError> {
let read = read(bytes)?;
let count = read.len();
for picture in read {
let key = (picture.style, picture.size);
match self
.pictures
.binary_search_by_key(&key, |held| (held.style, held.size))
{
Ok(index) => {
if let Some(slot) = self.pictures.get_mut(index) {
*slot = picture;
}
}
Err(index) => self.pictures.insert(index, picture),
}
}
Ok(count)
}
#[must_use]
pub const fn len(&self) -> usize {
self.pictures.len()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.pictures.is_empty()
}
pub(crate) fn picture(&self, style: ArtStyle, size: u32) -> Option<&ArtPicture> {
let index = self
.pictures
.binary_search_by_key(&(style, size), |held| (held.style, held.size))
.ok()?;
self.pictures.get(index)
}
}
#[derive(Clone, Copy)]
enum Slot {
Repeat(Side),
Span(Side),
Corner(Corner),
}
#[derive(Clone, Copy)]
enum Side {
Top,
Bottom,
Left,
Right,
}
#[derive(Clone, Copy)]
enum Corner {
TopLeft,
TopRight,
BottomLeft,
BottomRight,
}
impl ArtPicture {
const fn items_mut(&mut self, slot: Slot) -> &mut Vec<ArtItem> {
match slot {
Slot::Repeat(Side::Top) => &mut self.sides.top.repeat,
Slot::Repeat(Side::Bottom) => &mut self.sides.bottom.repeat,
Slot::Repeat(Side::Left) => &mut self.sides.left.repeat,
Slot::Repeat(Side::Right) => &mut self.sides.right.repeat,
Slot::Span(Side::Top) => &mut self.sides.top.span,
Slot::Span(Side::Bottom) => &mut self.sides.bottom.span,
Slot::Span(Side::Left) => &mut self.sides.left.span,
Slot::Span(Side::Right) => &mut self.sides.right.span,
Slot::Corner(Corner::TopLeft) => &mut self.corners.top_left,
Slot::Corner(Corner::TopRight) => &mut self.corners.top_right,
Slot::Corner(Corner::BottomLeft) => &mut self.corners.bottom_left,
Slot::Corner(Corner::BottomRight) => &mut self.corners.bottom_right,
}
}
}
fn read(bytes: &[u8]) -> Result<Vec<ArtPicture>, ArtPicturesError> {
let whole = |fault| ArtPicturesError { line: 0, fault };
if bytes.len() > ART_PICTURES_BYTE_LIMIT {
return Err(whole(ArtPicturesFault::TooLarge));
}
let text = std::str::from_utf8(bytes).map_err(|_| whole(ArtPicturesFault::NotText))?;
let mut lines = text
.lines()
.enumerate()
.map(|(index, line)| (index + 1, line));
match lines.next() {
Some((_, line)) if line.trim_end() == HEADER => {}
_ => {
return Err(ArtPicturesError {
line: 1,
fault: ArtPicturesFault::Header,
});
}
}
let mut reading = Reading::default();
for (number, line) in lines {
let mut words = line.split_ascii_whitespace();
let Some(kind) = words.next() else {
continue;
};
reading
.line(kind, &mut words)
.map_err(|fault| ArtPicturesError {
line: number,
fault,
})?;
}
if reading.open_clips > 0 {
return Err(whole(ArtPicturesFault::End));
}
Ok(reading.pictures)
}
#[derive(Default)]
struct Reading {
pictures: Vec<ArtPicture>,
slot: Option<Slot>,
open_clips: usize,
}
impl Reading {
fn line<'a>(
&mut self,
kind: &str,
words: &mut impl Iterator<Item = &'a str>,
) -> Result<(), ArtPicturesFault> {
if matches!(kind, "style" | "part") && self.open_clips > 0 {
return Err(ArtPicturesFault::End);
}
match kind {
"style" => {
self.pictures.push(read_style(words)?);
self.slot = None;
}
"part" => {
if self.pictures.is_empty() {
return Err(ArtPicturesFault::Part);
}
let read = match (words.next(), words.next(), words.next()) {
(Some(name), Some(kind), None) => part_slot(name, kind),
_ => None,
};
self.slot = Some(read.ok_or(ArtPicturesFault::Part)?);
}
"shape" => {
self.items().ok_or(ArtPicturesFault::Shape)?;
let shape = read_shape(words).ok_or(ArtPicturesFault::Shape)?;
self.push(ArtItem::Shape(shape))?;
}
"rect" => {
self.items().ok_or(ArtPicturesFault::Rect)?;
let rect = read_rect(words).ok_or(ArtPicturesFault::Rect)?;
self.push(ArtItem::Rect(rect))?;
}
"clip" => {
self.items().ok_or(ArtPicturesFault::Clip)?;
let clip = read_clip(words).ok_or(ArtPicturesFault::Clip)?;
if self.open_clips >= ART_PICTURES_CLIP_DEPTH_LIMIT {
return Err(ArtPicturesFault::TooDeep);
}
self.push(ArtItem::Clip(clip))?;
self.open_clips += 1;
}
"end" => {
if self.open_clips == 0 || words.next().is_some() {
return Err(ArtPicturesFault::End);
}
self.push(ArtItem::End)?;
self.open_clips -= 1;
}
"ring" => {
let commands = match self.items().and_then(|items| items.last_mut()) {
Some(ArtItem::Shape(shape)) => &mut shape.commands,
Some(ArtItem::Clip(clip)) => &mut clip.commands,
_ => return Err(ArtPicturesFault::Ring),
};
read_ring(words, commands)?;
}
_ => return Err(ArtPicturesFault::Unknown),
}
Ok(())
}
fn items(&mut self) -> Option<&mut Vec<ArtItem>> {
let slot = self.slot?;
Some(self.pictures.last_mut()?.items_mut(slot))
}
fn push(&mut self, item: ArtItem) -> Result<(), ArtPicturesFault> {
let items = self.items().ok_or(ArtPicturesFault::Unknown)?;
if items.len() >= ART_PICTURES_SHAPE_LIMIT {
return Err(ArtPicturesFault::TooManyShapes);
}
items.push(item);
Ok(())
}
}
fn read_style<'a>(
words: &mut impl Iterator<Item = &'a str>,
) -> Result<ArtPicture, ArtPicturesFault> {
let style = words
.next()
.and_then(ArtStyle::of_name)
.ok_or(ArtPicturesFault::Style)?;
let size = words
.next()
.and_then(|size| size.parse::<u32>().ok())
.filter(|size| (1..=ART_PICTURES_SIZE_LIMIT).contains(size))
.ok_or(ArtPicturesFault::Style)?;
if words.next().is_some() {
return Err(ArtPicturesFault::Style);
}
Ok(ArtPicture {
style,
size,
..ArtPicture::default()
})
}
fn part_slot(name: &str, kind: &str) -> Option<Slot> {
let side = match name {
"top" => Some(Side::Top),
"bottom" => Some(Side::Bottom),
"left" => Some(Side::Left),
"right" => Some(Side::Right),
_ => None,
};
let corner = match name {
"top-left" => Some(Corner::TopLeft),
"top-right" => Some(Corner::TopRight),
"bottom-left" => Some(Corner::BottomLeft),
"bottom-right" => Some(Corner::BottomRight),
_ => None,
};
match (side, corner, kind) {
(Some(side), None, "repeat") => Some(Slot::Repeat(side)),
(Some(side), None, "span") => Some(Slot::Span(side)),
(None, Some(corner), "corner") => Some(Slot::Corner(corner)),
_ => None,
}
}
fn read_color<'a>(words: &mut impl Iterator<Item = &'a str>) -> Option<Rgb> {
let mut channel = || words.next().and_then(|word| word.parse::<u8>().ok());
let (r, g, b) = (channel()?, channel()?, channel()?);
Some(Rgb { r, g, b })
}
fn read_shape<'a>(words: &mut impl Iterator<Item = &'a str>) -> Option<ArtShape> {
let color = read_color(words)?;
let fill_rule = read_fill_rule(words)?;
Some(ArtShape {
color,
fill_rule,
commands: Vec::new(),
})
}
fn read_rect<'a>(words: &mut impl Iterator<Item = &'a str>) -> Option<ArtRect> {
let color = read_color(words)?;
let mut edge = || {
words
.next()
.and_then(|word| word.parse::<i32>().ok())
.filter(|value| value.abs() <= ART_PICTURES_REACH_LIMIT)
};
let top_left = UnitPoint {
x: edge()?,
y: edge()?,
};
let bottom_right = UnitPoint {
x: edge()?,
y: edge()?,
};
let stroke = words
.next()
.and_then(|word| word.parse::<u32>().ok())
.filter(|stroke| *stroke <= ART_PICTURES_SIZE_LIMIT.saturating_mul(ART_STROKE_UNIT))?;
let ordered = top_left.x <= bottom_right.x && top_left.y <= bottom_right.y;
(ordered && words.next().is_none()).then_some(ArtRect {
color,
top_left,
bottom_right,
stroke,
})
}
fn read_clip<'a>(words: &mut impl Iterator<Item = &'a str>) -> Option<ArtClip> {
Some(ArtClip {
fill_rule: read_fill_rule(words)?,
commands: Vec::new(),
})
}
fn read_fill_rule<'a>(words: &mut impl Iterator<Item = &'a str>) -> Option<FillRule> {
let fill_rule = match words.next()? {
"nonzero" => FillRule::NonZero,
"evenodd" => FillRule::EvenOdd,
_ => return None,
};
words.next().is_none().then_some(fill_rule)
}
fn read_ring<'a>(
words: &mut impl Iterator<Item = &'a str>,
commands: &mut Vec<UnitCommand>,
) -> Result<(), ArtPicturesFault> {
let mut next = vec![UnitCommand::Move(read_point(words)?)];
loop {
let command = match words.next() {
None => break,
Some("L") => UnitCommand::Line(read_point(words)?),
Some("Q") => UnitCommand::Quad(read_point(words)?, read_point(words)?),
Some("C") => {
UnitCommand::Cubic(read_point(words)?, read_point(words)?, read_point(words)?)
}
Some(_) => return Err(ArtPicturesFault::Ring),
};
next.push(command);
if commands.len() + next.len() >= ART_PICTURES_COMMAND_LIMIT {
return Err(ArtPicturesFault::TooManyCommands);
}
}
next.push(UnitCommand::Close);
commands.append(&mut next);
Ok(())
}
fn read_point<'a>(
words: &mut impl Iterator<Item = &'a str>,
) -> Result<UnitPoint, ArtPicturesFault> {
let mut number = || {
words
.next()
.and_then(|word| word.parse::<i32>().ok())
.filter(|value| value.abs() <= ART_PICTURES_REACH_LIMIT)
.ok_or(ArtPicturesFault::Ring)
};
let x = number()?;
Ok(UnitPoint { x, y: number()? })
}
#[cfg(test)]
mod tests;