1use f_office_paint::{FillRule, Rgb};
32use f_office_units::Edges;
33use std::fmt;
34
35use crate::params::ART_STROKE_UNIT;
36use crate::props::ArtStyle;
37
38pub use crate::params::{
39 ART_PICTURES_BYTE_LIMIT, ART_PICTURES_CLIP_DEPTH_LIMIT, ART_PICTURES_COMMAND_LIMIT,
40 ART_PICTURES_REACH_LIMIT, ART_PICTURES_SHAPE_LIMIT, ART_PICTURES_SIZE_LIMIT,
41};
42
43const HEADER: &str = "f-office art pictures 3";
45
46pub(crate) const UNIT: i32 = crate::params::ART_PICTURE_UNIT;
48
49#[derive(Clone, Debug, Default, PartialEq, Eq)]
53pub struct ArtPictures {
54 pictures: Vec<ArtPicture>,
56}
57
58#[derive(Clone, Debug, Default, PartialEq, Eq)]
60pub(crate) struct ArtPicture {
61 style: ArtStyle,
63 size: u32,
65 pub sides: Edges<SidePicture>,
67 pub corners: Corners<Vec<ArtItem>>,
69}
70
71#[derive(Clone, Debug, Default, PartialEq, Eq)]
73pub(crate) struct SidePicture {
74 pub repeat: Vec<ArtItem>,
76 pub span: Vec<ArtItem>,
78}
79
80#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
82pub(crate) struct Corners<T> {
83 pub top_left: T,
85 pub top_right: T,
87 pub bottom_left: T,
89 pub bottom_right: T,
91}
92
93#[derive(Clone, Debug, PartialEq, Eq)]
95pub(crate) enum ArtItem {
96 Shape(ArtShape),
98 Rect(ArtRect),
100 Clip(ArtClip),
102 End,
104}
105
106#[derive(Clone, Debug, PartialEq, Eq)]
108pub(crate) struct ArtClip {
109 pub fill_rule: FillRule,
111 pub commands: Vec<UnitCommand>,
113}
114
115#[derive(Clone, Debug, PartialEq, Eq)]
117pub(crate) struct ArtShape {
118 pub color: Rgb,
120 pub fill_rule: FillRule,
122 pub commands: Vec<UnitCommand>,
124}
125
126#[derive(Clone, Copy, Debug, PartialEq, Eq)]
128pub(crate) struct ArtRect {
129 pub color: Rgb,
131 pub top_left: UnitPoint,
133 pub bottom_right: UnitPoint,
135 pub stroke: u32,
138}
139
140#[derive(Clone, Copy, Debug, PartialEq, Eq)]
142pub(crate) enum UnitCommand {
143 Move(UnitPoint),
145 Line(UnitPoint),
147 Quad(UnitPoint, UnitPoint),
149 Cubic(UnitPoint, UnitPoint, UnitPoint),
151 Close,
153}
154
155#[derive(Clone, Copy, Debug, PartialEq, Eq)]
157pub(crate) struct UnitPoint {
158 pub x: i32,
160 pub y: i32,
162}
163
164#[derive(Clone, Copy, Debug, PartialEq, Eq)]
166#[non_exhaustive]
167pub struct ArtPicturesError {
168 pub line: usize,
170 pub fault: ArtPicturesFault,
172}
173
174#[derive(Clone, Copy, Debug, PartialEq, Eq)]
176#[non_exhaustive]
177pub enum ArtPicturesFault {
178 TooLarge,
180 NotText,
182 Header,
184 Style,
187 Part,
189 Shape,
191 Clip,
193 Rect,
198 End,
201 Ring,
205 Unknown,
207 TooManyShapes,
209 TooManyCommands,
211 TooDeep,
213}
214
215impl fmt::Display for ArtPicturesError {
216 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217 let what = match self.fault {
218 ArtPicturesFault::TooLarge => "the file is too large",
219 ArtPicturesFault::NotText => "the file is not UTF-8 text",
220 ArtPicturesFault::Header => "the file does not start with the form's first line",
221 ArtPicturesFault::Style => "a style line does not read",
222 ArtPicturesFault::Part => "a part line does not read",
223 ArtPicturesFault::Shape => "a shape line does not read",
224 ArtPicturesFault::Clip => "a clip line does not read",
225 ArtPicturesFault::Rect => "a rect line does not read",
226 ArtPicturesFault::End => "a clip does not end where it should",
227 ArtPicturesFault::Ring => "a ring line does not read",
228 ArtPicturesFault::Unknown => "a line is of no kind of the form",
229 ArtPicturesFault::TooManyShapes => "a part holds too many items",
230 ArtPicturesFault::TooManyCommands => "an outline holds too many commands",
231 ArtPicturesFault::TooDeep => "too many clips are open at once",
232 };
233 if self.line == 0 {
234 write!(f, "the art pictures do not read: {what}")
235 } else {
236 write!(
237 f,
238 "the art pictures do not read: {what} (line {})",
239 self.line
240 )
241 }
242 }
243}
244
245impl std::error::Error for ArtPicturesError {}
246
247impl ArtPictures {
248 #[must_use]
250 pub const fn new() -> Self {
251 Self {
252 pictures: Vec::new(),
253 }
254 }
255
256 pub fn add(&mut self, bytes: &[u8]) -> Result<usize, ArtPicturesError> {
264 let read = read(bytes)?;
265 let count = read.len();
266 for picture in read {
267 let key = (picture.style, picture.size);
268 match self
269 .pictures
270 .binary_search_by_key(&key, |held| (held.style, held.size))
271 {
272 Ok(index) => {
273 if let Some(slot) = self.pictures.get_mut(index) {
274 *slot = picture;
275 }
276 }
277 Err(index) => self.pictures.insert(index, picture),
278 }
279 }
280 Ok(count)
281 }
282
283 #[must_use]
285 pub const fn len(&self) -> usize {
286 self.pictures.len()
287 }
288
289 #[must_use]
291 pub const fn is_empty(&self) -> bool {
292 self.pictures.is_empty()
293 }
294
295 pub(crate) fn picture(&self, style: ArtStyle, size: u32) -> Option<&ArtPicture> {
297 let index = self
298 .pictures
299 .binary_search_by_key(&(style, size), |held| (held.style, held.size))
300 .ok()?;
301 self.pictures.get(index)
302 }
303}
304
305#[derive(Clone, Copy)]
307enum Slot {
308 Repeat(Side),
310 Span(Side),
312 Corner(Corner),
314}
315
316#[derive(Clone, Copy)]
318enum Side {
319 Top,
320 Bottom,
321 Left,
322 Right,
323}
324
325#[derive(Clone, Copy)]
327enum Corner {
328 TopLeft,
329 TopRight,
330 BottomLeft,
331 BottomRight,
332}
333
334impl ArtPicture {
335 const fn items_mut(&mut self, slot: Slot) -> &mut Vec<ArtItem> {
337 match slot {
338 Slot::Repeat(Side::Top) => &mut self.sides.top.repeat,
339 Slot::Repeat(Side::Bottom) => &mut self.sides.bottom.repeat,
340 Slot::Repeat(Side::Left) => &mut self.sides.left.repeat,
341 Slot::Repeat(Side::Right) => &mut self.sides.right.repeat,
342 Slot::Span(Side::Top) => &mut self.sides.top.span,
343 Slot::Span(Side::Bottom) => &mut self.sides.bottom.span,
344 Slot::Span(Side::Left) => &mut self.sides.left.span,
345 Slot::Span(Side::Right) => &mut self.sides.right.span,
346 Slot::Corner(Corner::TopLeft) => &mut self.corners.top_left,
347 Slot::Corner(Corner::TopRight) => &mut self.corners.top_right,
348 Slot::Corner(Corner::BottomLeft) => &mut self.corners.bottom_left,
349 Slot::Corner(Corner::BottomRight) => &mut self.corners.bottom_right,
350 }
351 }
352}
353
354fn read(bytes: &[u8]) -> Result<Vec<ArtPicture>, ArtPicturesError> {
356 let whole = |fault| ArtPicturesError { line: 0, fault };
357 if bytes.len() > ART_PICTURES_BYTE_LIMIT {
358 return Err(whole(ArtPicturesFault::TooLarge));
359 }
360 let text = std::str::from_utf8(bytes).map_err(|_| whole(ArtPicturesFault::NotText))?;
361 let mut lines = text
362 .lines()
363 .enumerate()
364 .map(|(index, line)| (index + 1, line));
365 match lines.next() {
366 Some((_, line)) if line.trim_end() == HEADER => {}
367 _ => {
368 return Err(ArtPicturesError {
369 line: 1,
370 fault: ArtPicturesFault::Header,
371 });
372 }
373 }
374 let mut reading = Reading::default();
375 for (number, line) in lines {
376 let mut words = line.split_ascii_whitespace();
377 let Some(kind) = words.next() else {
378 continue;
379 };
380 reading
381 .line(kind, &mut words)
382 .map_err(|fault| ArtPicturesError {
383 line: number,
384 fault,
385 })?;
386 }
387 if reading.open_clips > 0 {
388 return Err(whole(ArtPicturesFault::End));
389 }
390 Ok(reading.pictures)
391}
392
393#[derive(Default)]
395struct Reading {
396 pictures: Vec<ArtPicture>,
398 slot: Option<Slot>,
400 open_clips: usize,
402}
403
404impl Reading {
405 fn line<'a>(
407 &mut self,
408 kind: &str,
409 words: &mut impl Iterator<Item = &'a str>,
410 ) -> Result<(), ArtPicturesFault> {
411 if matches!(kind, "style" | "part") && self.open_clips > 0 {
412 return Err(ArtPicturesFault::End);
413 }
414 match kind {
415 "style" => {
416 self.pictures.push(read_style(words)?);
417 self.slot = None;
418 }
419 "part" => {
420 if self.pictures.is_empty() {
421 return Err(ArtPicturesFault::Part);
422 }
423 let read = match (words.next(), words.next(), words.next()) {
424 (Some(name), Some(kind), None) => part_slot(name, kind),
425 _ => None,
426 };
427 self.slot = Some(read.ok_or(ArtPicturesFault::Part)?);
428 }
429 "shape" => {
430 self.items().ok_or(ArtPicturesFault::Shape)?;
431 let shape = read_shape(words).ok_or(ArtPicturesFault::Shape)?;
432 self.push(ArtItem::Shape(shape))?;
433 }
434 "rect" => {
435 self.items().ok_or(ArtPicturesFault::Rect)?;
436 let rect = read_rect(words).ok_or(ArtPicturesFault::Rect)?;
437 self.push(ArtItem::Rect(rect))?;
438 }
439 "clip" => {
440 self.items().ok_or(ArtPicturesFault::Clip)?;
441 let clip = read_clip(words).ok_or(ArtPicturesFault::Clip)?;
442 if self.open_clips >= ART_PICTURES_CLIP_DEPTH_LIMIT {
443 return Err(ArtPicturesFault::TooDeep);
444 }
445 self.push(ArtItem::Clip(clip))?;
446 self.open_clips += 1;
447 }
448 "end" => {
449 if self.open_clips == 0 || words.next().is_some() {
450 return Err(ArtPicturesFault::End);
451 }
452 self.push(ArtItem::End)?;
453 self.open_clips -= 1;
454 }
455 "ring" => {
456 let commands = match self.items().and_then(|items| items.last_mut()) {
457 Some(ArtItem::Shape(shape)) => &mut shape.commands,
458 Some(ArtItem::Clip(clip)) => &mut clip.commands,
459 _ => return Err(ArtPicturesFault::Ring),
460 };
461 read_ring(words, commands)?;
462 }
463 _ => return Err(ArtPicturesFault::Unknown),
464 }
465 Ok(())
466 }
467
468 fn items(&mut self) -> Option<&mut Vec<ArtItem>> {
470 let slot = self.slot?;
471 Some(self.pictures.last_mut()?.items_mut(slot))
472 }
473
474 fn push(&mut self, item: ArtItem) -> Result<(), ArtPicturesFault> {
476 let items = self.items().ok_or(ArtPicturesFault::Unknown)?;
477 if items.len() >= ART_PICTURES_SHAPE_LIMIT {
478 return Err(ArtPicturesFault::TooManyShapes);
479 }
480 items.push(item);
481 Ok(())
482 }
483}
484
485fn read_style<'a>(
487 words: &mut impl Iterator<Item = &'a str>,
488) -> Result<ArtPicture, ArtPicturesFault> {
489 let style = words
490 .next()
491 .and_then(ArtStyle::of_name)
492 .ok_or(ArtPicturesFault::Style)?;
493 let size = words
494 .next()
495 .and_then(|size| size.parse::<u32>().ok())
496 .filter(|size| (1..=ART_PICTURES_SIZE_LIMIT).contains(size))
497 .ok_or(ArtPicturesFault::Style)?;
498 if words.next().is_some() {
499 return Err(ArtPicturesFault::Style);
500 }
501 Ok(ArtPicture {
502 style,
503 size,
504 ..ArtPicture::default()
505 })
506}
507
508fn part_slot(name: &str, kind: &str) -> Option<Slot> {
510 let side = match name {
511 "top" => Some(Side::Top),
512 "bottom" => Some(Side::Bottom),
513 "left" => Some(Side::Left),
514 "right" => Some(Side::Right),
515 _ => None,
516 };
517 let corner = match name {
518 "top-left" => Some(Corner::TopLeft),
519 "top-right" => Some(Corner::TopRight),
520 "bottom-left" => Some(Corner::BottomLeft),
521 "bottom-right" => Some(Corner::BottomRight),
522 _ => None,
523 };
524 match (side, corner, kind) {
525 (Some(side), None, "repeat") => Some(Slot::Repeat(side)),
526 (Some(side), None, "span") => Some(Slot::Span(side)),
527 (None, Some(corner), "corner") => Some(Slot::Corner(corner)),
528 _ => None,
529 }
530}
531
532fn read_color<'a>(words: &mut impl Iterator<Item = &'a str>) -> Option<Rgb> {
534 let mut channel = || words.next().and_then(|word| word.parse::<u8>().ok());
535 let (r, g, b) = (channel()?, channel()?, channel()?);
536 Some(Rgb { r, g, b })
537}
538
539fn read_shape<'a>(words: &mut impl Iterator<Item = &'a str>) -> Option<ArtShape> {
541 let color = read_color(words)?;
542 let fill_rule = read_fill_rule(words)?;
543 Some(ArtShape {
544 color,
545 fill_rule,
546 commands: Vec::new(),
547 })
548}
549
550fn read_rect<'a>(words: &mut impl Iterator<Item = &'a str>) -> Option<ArtRect> {
554 let color = read_color(words)?;
555 let mut edge = || {
556 words
557 .next()
558 .and_then(|word| word.parse::<i32>().ok())
559 .filter(|value| value.abs() <= ART_PICTURES_REACH_LIMIT)
560 };
561 let top_left = UnitPoint {
562 x: edge()?,
563 y: edge()?,
564 };
565 let bottom_right = UnitPoint {
566 x: edge()?,
567 y: edge()?,
568 };
569 let stroke = words
570 .next()
571 .and_then(|word| word.parse::<u32>().ok())
572 .filter(|stroke| *stroke <= ART_PICTURES_SIZE_LIMIT.saturating_mul(ART_STROKE_UNIT))?;
573 let ordered = top_left.x <= bottom_right.x && top_left.y <= bottom_right.y;
574 (ordered && words.next().is_none()).then_some(ArtRect {
575 color,
576 top_left,
577 bottom_right,
578 stroke,
579 })
580}
581
582fn read_clip<'a>(words: &mut impl Iterator<Item = &'a str>) -> Option<ArtClip> {
584 Some(ArtClip {
585 fill_rule: read_fill_rule(words)?,
586 commands: Vec::new(),
587 })
588}
589
590fn read_fill_rule<'a>(words: &mut impl Iterator<Item = &'a str>) -> Option<FillRule> {
592 let fill_rule = match words.next()? {
593 "nonzero" => FillRule::NonZero,
594 "evenodd" => FillRule::EvenOdd,
595 _ => return None,
596 };
597 words.next().is_none().then_some(fill_rule)
598}
599
600fn read_ring<'a>(
603 words: &mut impl Iterator<Item = &'a str>,
604 commands: &mut Vec<UnitCommand>,
605) -> Result<(), ArtPicturesFault> {
606 let mut next = vec![UnitCommand::Move(read_point(words)?)];
607 loop {
608 let command = match words.next() {
609 None => break,
610 Some("L") => UnitCommand::Line(read_point(words)?),
611 Some("Q") => UnitCommand::Quad(read_point(words)?, read_point(words)?),
612 Some("C") => {
613 UnitCommand::Cubic(read_point(words)?, read_point(words)?, read_point(words)?)
614 }
615 Some(_) => return Err(ArtPicturesFault::Ring),
616 };
617 next.push(command);
618 if commands.len() + next.len() >= ART_PICTURES_COMMAND_LIMIT {
619 return Err(ArtPicturesFault::TooManyCommands);
620 }
621 }
622 next.push(UnitCommand::Close);
623 commands.append(&mut next);
624 Ok(())
625}
626
627fn read_point<'a>(
629 words: &mut impl Iterator<Item = &'a str>,
630) -> Result<UnitPoint, ArtPicturesFault> {
631 let mut number = || {
632 words
633 .next()
634 .and_then(|word| word.parse::<i32>().ok())
635 .filter(|value| value.abs() <= ART_PICTURES_REACH_LIMIT)
636 .ok_or(ArtPicturesFault::Ring)
637 };
638 let x = number()?;
639 Ok(UnitPoint { x, y: number()? })
640}
641
642#[cfg(test)]
643mod tests;