umya_spreadsheet/structs/
fonts.rs

1// fronts
2use crate::reader::driver::*;
3use crate::structs::Font;
4use crate::structs::Style;
5use crate::writer::driver::*;
6use quick_xml::events::{BytesStart, Event};
7use quick_xml::Reader;
8use quick_xml::Writer;
9use std::io::Cursor;
10use thin_vec::ThinVec;
11
12#[derive(Clone, Default, Debug)]
13pub(crate) struct Fonts {
14    font: ThinVec<Font>,
15}
16
17impl Fonts {
18    #[inline]
19    pub(crate) fn get_font(&self) -> &[Font] {
20        &self.font
21    }
22
23    #[inline]
24    pub(crate) fn get_font_mut(&mut self) -> &mut ThinVec<Font> {
25        &mut self.font
26    }
27
28    #[inline]
29    pub(crate) fn set_font(&mut self, value: Font) -> &mut Self {
30        self.font.push(value);
31        self
32    }
33
34    pub(crate) fn set_style(&mut self, style: &Style) -> u32 {
35        match style.get_font() {
36            Some(v) => {
37                let hash_code = v.get_hash_code();
38                let mut id = 0;
39                for font in &self.font {
40                    if font.get_hash_code() == hash_code {
41                        return id;
42                    }
43                    id += 1;
44                }
45                self.set_font(v.clone());
46                id
47            }
48            None => 0,
49        }
50    }
51
52    pub(crate) fn set_attributes<R: std::io::BufRead>(
53        &mut self,
54        reader: &mut Reader<R>,
55        _e: &BytesStart,
56    ) {
57        xml_read_loop!(
58            reader,
59            Event::Empty(ref e) => {
60                if e.name().into_inner() == b"font" {
61                    let obj = Font::default();
62                    self.set_font(obj);
63                }
64            },
65            Event::Start(ref e) => {
66                if e.name().into_inner() == b"font" {
67                    let mut obj = Font::default();
68                    obj.set_attributes(reader, e);
69                    self.set_font(obj);
70                }
71            },
72            Event::End(ref e) => {
73                if e.name().into_inner() == b"fonts" {
74                    return
75                }
76            },
77            Event::Eof => panic!("Error: Could not find {} end element", "fonts")
78        );
79    }
80
81    pub(crate) fn write_to(&self, writer: &mut Writer<Cursor<Vec<u8>>>) {
82        if !self.font.is_empty() {
83            // fonts
84            write_start_tag(
85                writer,
86                "fonts",
87                vec![
88                    ("count", &self.font.len().to_string()),
89                    ("x14ac:knownFonts", "1"),
90                ],
91                false,
92            );
93
94            // font
95            for font in &self.font {
96                font.write_to_font(writer);
97            }
98
99            write_end_tag(writer, "fonts");
100        }
101    }
102}