1use std::collections::HashSet;
9
10use sheetkit_xml::styles::{
11 Alignment, Border, BorderSide, Borders, Color, Fill, Fills, Font, Fonts, NumFmt, NumFmts,
12 PatternFill, Protection, StyleSheet, Xf,
13};
14
15use crate::error::{Error, Result};
16
17const MAX_CELL_XFS: usize = 65430;
19
20const CUSTOM_NUM_FMT_BASE: u32 = 164;
22
23pub mod builtin_num_fmts {
25 pub const GENERAL: u32 = 0;
27 pub const INTEGER: u32 = 1;
29 pub const DECIMAL_2: u32 = 2;
31 pub const THOUSANDS: u32 = 3;
33 pub const THOUSANDS_DECIMAL: u32 = 4;
35 pub const PERCENT: u32 = 9;
37 pub const PERCENT_DECIMAL: u32 = 10;
39 pub const SCIENTIFIC: u32 = 11;
41 pub const DATE_MDY: u32 = 14;
43 pub const DATE_DMY: u32 = 15;
45 pub const DATE_DM: u32 = 16;
47 pub const DATE_MY: u32 = 17;
49 pub const TIME_HM_AP: u32 = 18;
51 pub const TIME_HMS_AP: u32 = 19;
53 pub const TIME_HM: u32 = 20;
55 pub const TIME_HMS: u32 = 21;
57 pub const DATETIME: u32 = 22;
59 pub const TEXT: u32 = 49;
61}
62
63#[derive(Debug, Clone, Default)]
65pub struct Style {
66 pub font: Option<FontStyle>,
67 pub fill: Option<FillStyle>,
68 pub border: Option<BorderStyle>,
69 pub alignment: Option<AlignmentStyle>,
70 pub num_fmt: Option<NumFmtStyle>,
71 pub protection: Option<ProtectionStyle>,
72}
73
74#[derive(Debug, Clone, Default)]
76pub struct FontStyle {
77 pub name: Option<String>,
79 pub size: Option<f64>,
81 pub bold: bool,
83 pub italic: bool,
85 pub underline: bool,
87 pub strikethrough: bool,
89 pub color: Option<StyleColor>,
91}
92
93#[derive(Debug, Clone, PartialEq)]
95pub enum StyleColor {
96 Rgb(String),
98 Theme(u32),
100 Indexed(u32),
102}
103
104#[derive(Debug, Clone)]
106pub struct FillStyle {
107 pub pattern: PatternType,
109 pub fg_color: Option<StyleColor>,
111 pub bg_color: Option<StyleColor>,
113 pub gradient: Option<GradientFillStyle>,
115}
116
117#[derive(Debug, Clone)]
119pub struct GradientFillStyle {
120 pub gradient_type: GradientType,
122 pub degree: Option<f64>,
124 pub left: Option<f64>,
126 pub right: Option<f64>,
128 pub top: Option<f64>,
130 pub bottom: Option<f64>,
132 pub stops: Vec<GradientStop>,
134}
135
136#[derive(Debug, Clone, Copy, PartialEq)]
138pub enum GradientType {
139 Linear,
140 Path,
141}
142
143impl GradientType {
144 fn from_str(s: &str) -> Self {
145 match s {
146 "path" => GradientType::Path,
147 _ => GradientType::Linear,
148 }
149 }
150}
151
152#[derive(Debug, Clone)]
154pub struct GradientStop {
155 pub position: f64,
157 pub color: StyleColor,
159}
160
161#[derive(Debug, Clone, Copy, PartialEq)]
163pub enum PatternType {
164 None,
165 Solid,
166 Gray125,
167 DarkGray,
168 MediumGray,
169 LightGray,
170}
171
172impl PatternType {
173 fn as_str(&self) -> &str {
174 match self {
175 PatternType::None => "none",
176 PatternType::Solid => "solid",
177 PatternType::Gray125 => "gray125",
178 PatternType::DarkGray => "darkGray",
179 PatternType::MediumGray => "mediumGray",
180 PatternType::LightGray => "lightGray",
181 }
182 }
183
184 fn from_str(s: &str) -> Self {
185 match s {
186 "none" => PatternType::None,
187 "solid" => PatternType::Solid,
188 "gray125" => PatternType::Gray125,
189 "darkGray" => PatternType::DarkGray,
190 "mediumGray" => PatternType::MediumGray,
191 "lightGray" => PatternType::LightGray,
192 _ => PatternType::None,
193 }
194 }
195}
196
197#[derive(Debug, Clone, Default)]
199pub struct BorderStyle {
200 pub left: Option<BorderSideStyle>,
201 pub right: Option<BorderSideStyle>,
202 pub top: Option<BorderSideStyle>,
203 pub bottom: Option<BorderSideStyle>,
204 pub diagonal: Option<BorderSideStyle>,
205}
206
207#[derive(Debug, Clone)]
209pub struct BorderSideStyle {
210 pub style: BorderLineStyle,
211 pub color: Option<StyleColor>,
212}
213
214#[derive(Debug, Clone, Copy, PartialEq)]
216pub enum BorderLineStyle {
217 Thin,
218 Medium,
219 Thick,
220 Dashed,
221 Dotted,
222 Double,
223 Hair,
224 MediumDashed,
225 DashDot,
226 MediumDashDot,
227 DashDotDot,
228 MediumDashDotDot,
229 SlantDashDot,
230}
231
232impl BorderLineStyle {
233 fn as_str(&self) -> &str {
234 match self {
235 BorderLineStyle::Thin => "thin",
236 BorderLineStyle::Medium => "medium",
237 BorderLineStyle::Thick => "thick",
238 BorderLineStyle::Dashed => "dashed",
239 BorderLineStyle::Dotted => "dotted",
240 BorderLineStyle::Double => "double",
241 BorderLineStyle::Hair => "hair",
242 BorderLineStyle::MediumDashed => "mediumDashed",
243 BorderLineStyle::DashDot => "dashDot",
244 BorderLineStyle::MediumDashDot => "mediumDashDot",
245 BorderLineStyle::DashDotDot => "dashDotDot",
246 BorderLineStyle::MediumDashDotDot => "mediumDashDotDot",
247 BorderLineStyle::SlantDashDot => "slantDashDot",
248 }
249 }
250
251 fn from_str(s: &str) -> Option<Self> {
252 match s {
253 "thin" => Some(BorderLineStyle::Thin),
254 "medium" => Some(BorderLineStyle::Medium),
255 "thick" => Some(BorderLineStyle::Thick),
256 "dashed" => Some(BorderLineStyle::Dashed),
257 "dotted" => Some(BorderLineStyle::Dotted),
258 "double" => Some(BorderLineStyle::Double),
259 "hair" => Some(BorderLineStyle::Hair),
260 "mediumDashed" => Some(BorderLineStyle::MediumDashed),
261 "dashDot" => Some(BorderLineStyle::DashDot),
262 "mediumDashDot" => Some(BorderLineStyle::MediumDashDot),
263 "dashDotDot" => Some(BorderLineStyle::DashDotDot),
264 "mediumDashDotDot" => Some(BorderLineStyle::MediumDashDotDot),
265 "slantDashDot" => Some(BorderLineStyle::SlantDashDot),
266 _ => None,
267 }
268 }
269}
270
271#[derive(Debug, Clone, Default)]
273pub struct AlignmentStyle {
274 pub horizontal: Option<HorizontalAlign>,
275 pub vertical: Option<VerticalAlign>,
276 pub wrap_text: bool,
277 pub text_rotation: Option<u32>,
278 pub indent: Option<u32>,
279 pub shrink_to_fit: bool,
280}
281
282#[derive(Debug, Clone, Copy, PartialEq)]
284pub enum HorizontalAlign {
285 General,
286 Left,
287 Center,
288 Right,
289 Fill,
290 Justify,
291 CenterContinuous,
292 Distributed,
293}
294
295impl HorizontalAlign {
296 fn as_str(&self) -> &str {
297 match self {
298 HorizontalAlign::General => "general",
299 HorizontalAlign::Left => "left",
300 HorizontalAlign::Center => "center",
301 HorizontalAlign::Right => "right",
302 HorizontalAlign::Fill => "fill",
303 HorizontalAlign::Justify => "justify",
304 HorizontalAlign::CenterContinuous => "centerContinuous",
305 HorizontalAlign::Distributed => "distributed",
306 }
307 }
308
309 fn from_str(s: &str) -> Option<Self> {
310 match s {
311 "general" => Some(HorizontalAlign::General),
312 "left" => Some(HorizontalAlign::Left),
313 "center" => Some(HorizontalAlign::Center),
314 "right" => Some(HorizontalAlign::Right),
315 "fill" => Some(HorizontalAlign::Fill),
316 "justify" => Some(HorizontalAlign::Justify),
317 "centerContinuous" => Some(HorizontalAlign::CenterContinuous),
318 "distributed" => Some(HorizontalAlign::Distributed),
319 _ => None,
320 }
321 }
322}
323
324#[derive(Debug, Clone, Copy, PartialEq)]
326pub enum VerticalAlign {
327 Top,
328 Center,
329 Bottom,
330 Justify,
331 Distributed,
332}
333
334impl VerticalAlign {
335 fn as_str(&self) -> &str {
336 match self {
337 VerticalAlign::Top => "top",
338 VerticalAlign::Center => "center",
339 VerticalAlign::Bottom => "bottom",
340 VerticalAlign::Justify => "justify",
341 VerticalAlign::Distributed => "distributed",
342 }
343 }
344
345 fn from_str(s: &str) -> Option<Self> {
346 match s {
347 "top" => Some(VerticalAlign::Top),
348 "center" => Some(VerticalAlign::Center),
349 "bottom" => Some(VerticalAlign::Bottom),
350 "justify" => Some(VerticalAlign::Justify),
351 "distributed" => Some(VerticalAlign::Distributed),
352 _ => None,
353 }
354 }
355}
356
357#[derive(Debug, Clone)]
359pub enum NumFmtStyle {
360 Builtin(u32),
362 Custom(String),
364}
365
366#[derive(Debug, Clone)]
368pub struct ProtectionStyle {
369 pub locked: bool,
370 pub hidden: bool,
371}
372
373pub struct StyleBuilder {
378 style: Style,
379}
380
381impl StyleBuilder {
382 pub fn new() -> Self {
384 Self {
385 style: Style::default(),
386 }
387 }
388
389 pub fn bold(mut self, bold: bool) -> Self {
393 self.style.font.get_or_insert_with(FontStyle::default).bold = bold;
394 self
395 }
396
397 pub fn italic(mut self, italic: bool) -> Self {
399 self.style
400 .font
401 .get_or_insert_with(FontStyle::default)
402 .italic = italic;
403 self
404 }
405
406 pub fn underline(mut self, underline: bool) -> Self {
408 self.style
409 .font
410 .get_or_insert_with(FontStyle::default)
411 .underline = underline;
412 self
413 }
414
415 pub fn strikethrough(mut self, strikethrough: bool) -> Self {
417 self.style
418 .font
419 .get_or_insert_with(FontStyle::default)
420 .strikethrough = strikethrough;
421 self
422 }
423
424 pub fn font_name(mut self, name: &str) -> Self {
426 self.style.font.get_or_insert_with(FontStyle::default).name = Some(name.to_string());
427 self
428 }
429
430 pub fn font_size(mut self, size: f64) -> Self {
432 self.style.font.get_or_insert_with(FontStyle::default).size = Some(size);
433 self
434 }
435
436 pub fn font_color(mut self, color: StyleColor) -> Self {
438 self.style.font.get_or_insert_with(FontStyle::default).color = Some(color);
439 self
440 }
441
442 pub fn font_color_rgb(self, rgb: &str) -> Self {
444 self.font_color(StyleColor::Rgb(rgb.to_string()))
445 }
446
447 pub fn fill_pattern(mut self, pattern: PatternType) -> Self {
451 self.style
452 .fill
453 .get_or_insert(FillStyle {
454 pattern: PatternType::None,
455 fg_color: None,
456 bg_color: None,
457 gradient: None,
458 })
459 .pattern = pattern;
460 self
461 }
462
463 pub fn fill_fg_color(mut self, color: StyleColor) -> Self {
465 self.style
466 .fill
467 .get_or_insert(FillStyle {
468 pattern: PatternType::None,
469 fg_color: None,
470 bg_color: None,
471 gradient: None,
472 })
473 .fg_color = Some(color);
474 self
475 }
476
477 pub fn fill_fg_color_rgb(self, rgb: &str) -> Self {
479 self.fill_fg_color(StyleColor::Rgb(rgb.to_string()))
480 }
481
482 pub fn fill_bg_color(mut self, color: StyleColor) -> Self {
484 self.style
485 .fill
486 .get_or_insert(FillStyle {
487 pattern: PatternType::None,
488 fg_color: None,
489 bg_color: None,
490 gradient: None,
491 })
492 .bg_color = Some(color);
493 self
494 }
495
496 pub fn solid_fill(mut self, rgb: &str) -> Self {
498 self.style.fill = Some(FillStyle {
499 pattern: PatternType::Solid,
500 fg_color: Some(StyleColor::Rgb(rgb.to_string())),
501 bg_color: self.style.fill.and_then(|f| f.bg_color),
502 gradient: None,
503 });
504 self
505 }
506
507 pub fn border_left(mut self, style: BorderLineStyle, color: StyleColor) -> Self {
511 self.style
512 .border
513 .get_or_insert_with(BorderStyle::default)
514 .left = Some(BorderSideStyle {
515 style,
516 color: Some(color),
517 });
518 self
519 }
520
521 pub fn border_right(mut self, style: BorderLineStyle, color: StyleColor) -> Self {
523 self.style
524 .border
525 .get_or_insert_with(BorderStyle::default)
526 .right = Some(BorderSideStyle {
527 style,
528 color: Some(color),
529 });
530 self
531 }
532
533 pub fn border_top(mut self, style: BorderLineStyle, color: StyleColor) -> Self {
535 self.style
536 .border
537 .get_or_insert_with(BorderStyle::default)
538 .top = Some(BorderSideStyle {
539 style,
540 color: Some(color),
541 });
542 self
543 }
544
545 pub fn border_bottom(mut self, style: BorderLineStyle, color: StyleColor) -> Self {
547 self.style
548 .border
549 .get_or_insert_with(BorderStyle::default)
550 .bottom = Some(BorderSideStyle {
551 style,
552 color: Some(color),
553 });
554 self
555 }
556
557 pub fn border_all(mut self, style: BorderLineStyle, color: StyleColor) -> Self {
559 let side = || BorderSideStyle {
560 style,
561 color: Some(color.clone()),
562 };
563 let border = self.style.border.get_or_insert_with(BorderStyle::default);
564 border.left = Some(side());
565 border.right = Some(side());
566 border.top = Some(side());
567 border.bottom = Some(side());
568 self
569 }
570
571 pub fn horizontal_align(mut self, align: HorizontalAlign) -> Self {
575 self.style
576 .alignment
577 .get_or_insert_with(AlignmentStyle::default)
578 .horizontal = Some(align);
579 self
580 }
581
582 pub fn vertical_align(mut self, align: VerticalAlign) -> Self {
584 self.style
585 .alignment
586 .get_or_insert_with(AlignmentStyle::default)
587 .vertical = Some(align);
588 self
589 }
590
591 pub fn wrap_text(mut self, wrap: bool) -> Self {
593 self.style
594 .alignment
595 .get_or_insert_with(AlignmentStyle::default)
596 .wrap_text = wrap;
597 self
598 }
599
600 pub fn text_rotation(mut self, degrees: u32) -> Self {
602 self.style
603 .alignment
604 .get_or_insert_with(AlignmentStyle::default)
605 .text_rotation = Some(degrees);
606 self
607 }
608
609 pub fn indent(mut self, indent: u32) -> Self {
611 self.style
612 .alignment
613 .get_or_insert_with(AlignmentStyle::default)
614 .indent = Some(indent);
615 self
616 }
617
618 pub fn shrink_to_fit(mut self, shrink: bool) -> Self {
620 self.style
621 .alignment
622 .get_or_insert_with(AlignmentStyle::default)
623 .shrink_to_fit = shrink;
624 self
625 }
626
627 pub fn num_format_builtin(mut self, id: u32) -> Self {
631 self.style.num_fmt = Some(NumFmtStyle::Builtin(id));
632 self
633 }
634
635 pub fn num_format_custom(mut self, format: &str) -> Self {
637 self.style.num_fmt = Some(NumFmtStyle::Custom(format.to_string()));
638 self
639 }
640
641 pub fn locked(mut self, locked: bool) -> Self {
645 self.style
646 .protection
647 .get_or_insert(ProtectionStyle {
648 locked: true,
649 hidden: false,
650 })
651 .locked = locked;
652 self
653 }
654
655 pub fn hidden(mut self, hidden: bool) -> Self {
657 self.style
658 .protection
659 .get_or_insert(ProtectionStyle {
660 locked: true,
661 hidden: false,
662 })
663 .hidden = hidden;
664 self
665 }
666
667 pub fn build(self) -> Style {
671 self.style
672 }
673}
674
675impl Default for StyleBuilder {
676 fn default() -> Self {
677 Self::new()
678 }
679}
680
681fn style_color_to_xml(color: &StyleColor) -> Color {
683 match color {
684 StyleColor::Rgb(rgb) => Color {
685 auto: None,
686 indexed: None,
687 rgb: Some(rgb.clone()),
688 theme: None,
689 tint: None,
690 },
691 StyleColor::Theme(t) => Color {
692 auto: None,
693 indexed: None,
694 rgb: None,
695 theme: Some(*t),
696 tint: None,
697 },
698 StyleColor::Indexed(i) => Color {
699 auto: None,
700 indexed: Some(*i),
701 rgb: None,
702 theme: None,
703 tint: None,
704 },
705 }
706}
707
708fn xml_color_to_style(color: &Color) -> Option<StyleColor> {
710 if let Some(ref rgb) = color.rgb {
711 Some(StyleColor::Rgb(rgb.clone()))
712 } else if let Some(theme) = color.theme {
713 Some(StyleColor::Theme(theme))
714 } else {
715 color.indexed.map(StyleColor::Indexed)
716 }
717}
718
719fn font_style_to_xml(font: &FontStyle) -> Font {
721 use sheetkit_xml::styles::{BoolVal, FontName, FontSize, Underline};
722
723 Font {
724 b: if font.bold {
725 Some(BoolVal { val: None })
726 } else {
727 None
728 },
729 i: if font.italic {
730 Some(BoolVal { val: None })
731 } else {
732 None
733 },
734 strike: if font.strikethrough {
735 Some(BoolVal { val: None })
736 } else {
737 None
738 },
739 u: if font.underline {
740 Some(Underline { val: None })
741 } else {
742 None
743 },
744 sz: font.size.map(|val| FontSize { val }),
745 color: font.color.as_ref().map(style_color_to_xml),
746 name: font.name.as_ref().map(|val| FontName { val: val.clone() }),
747 family: None,
748 scheme: None,
749 }
750}
751
752fn xml_font_to_style(font: &Font) -> FontStyle {
754 FontStyle {
755 name: font.name.as_ref().map(|n| n.val.clone()),
756 size: font.sz.as_ref().map(|s| s.val),
757 bold: font.b.as_ref().is_some_and(|b| b.val.unwrap_or(true)),
758 italic: font.i.as_ref().is_some_and(|i| i.val.unwrap_or(true)),
759 underline: font.u.is_some(),
760 strikethrough: font
761 .strike
762 .as_ref()
763 .is_some_and(|strike| strike.val.unwrap_or(true)),
764 color: font.color.as_ref().and_then(xml_color_to_style),
765 }
766}
767
768fn fill_style_to_xml(fill: &FillStyle) -> Fill {
770 if let Some(ref grad) = fill.gradient {
771 return Fill {
772 pattern_fill: None,
773 gradient_fill: Some(gradient_style_to_xml(grad)),
774 };
775 }
776 Fill {
777 pattern_fill: Some(PatternFill {
778 pattern_type: Some(fill.pattern.as_str().to_string()),
779 fg_color: fill.fg_color.as_ref().map(style_color_to_xml),
780 bg_color: fill.bg_color.as_ref().map(style_color_to_xml),
781 }),
782 gradient_fill: None,
783 }
784}
785
786fn gradient_style_to_xml(grad: &GradientFillStyle) -> sheetkit_xml::styles::GradientFill {
788 sheetkit_xml::styles::GradientFill {
789 gradient_type: match grad.gradient_type {
790 GradientType::Linear => None,
791 GradientType::Path => Some("path".to_string()),
792 },
793 degree: grad.degree,
794 left: grad.left,
795 right: grad.right,
796 top: grad.top,
797 bottom: grad.bottom,
798 stops: grad
799 .stops
800 .iter()
801 .map(|s| sheetkit_xml::styles::GradientStop {
802 position: s.position,
803 color: style_color_to_xml(&s.color),
804 })
805 .collect(),
806 }
807}
808
809fn xml_fill_to_style(fill: &Fill) -> Option<FillStyle> {
811 if let Some(ref gf) = fill.gradient_fill {
812 let gradient_type = gf
813 .gradient_type
814 .as_ref()
815 .map(|s| GradientType::from_str(s))
816 .unwrap_or(GradientType::Linear);
817 let stops: Vec<GradientStop> = gf
818 .stops
819 .iter()
820 .filter_map(|s| {
821 xml_color_to_style(&s.color).map(|c| GradientStop {
822 position: s.position,
823 color: c,
824 })
825 })
826 .collect();
827 return Some(FillStyle {
828 pattern: PatternType::None,
829 fg_color: None,
830 bg_color: None,
831 gradient: Some(GradientFillStyle {
832 gradient_type,
833 degree: gf.degree,
834 left: gf.left,
835 right: gf.right,
836 top: gf.top,
837 bottom: gf.bottom,
838 stops,
839 }),
840 });
841 }
842 let pf = fill.pattern_fill.as_ref()?;
843 let pattern = pf
844 .pattern_type
845 .as_ref()
846 .map(|s| PatternType::from_str(s))
847 .unwrap_or(PatternType::None);
848 Some(FillStyle {
849 pattern,
850 fg_color: pf.fg_color.as_ref().and_then(xml_color_to_style),
851 bg_color: pf.bg_color.as_ref().and_then(xml_color_to_style),
852 gradient: None,
853 })
854}
855
856fn border_side_to_xml(side: &BorderSideStyle) -> BorderSide {
858 BorderSide {
859 style: Some(side.style.as_str().to_string()),
860 color: side.color.as_ref().map(style_color_to_xml),
861 }
862}
863
864fn xml_border_side_to_style(side: &BorderSide) -> Option<BorderSideStyle> {
866 let style_str = side.style.as_ref()?;
867 let style = BorderLineStyle::from_str(style_str)?;
868 Some(BorderSideStyle {
869 style,
870 color: side.color.as_ref().and_then(xml_color_to_style),
871 })
872}
873
874fn border_style_to_xml(border: &BorderStyle) -> Border {
876 Border {
877 diagonal_up: None,
878 diagonal_down: None,
879 left: border.left.as_ref().map(border_side_to_xml),
880 right: border.right.as_ref().map(border_side_to_xml),
881 top: border.top.as_ref().map(border_side_to_xml),
882 bottom: border.bottom.as_ref().map(border_side_to_xml),
883 diagonal: border.diagonal.as_ref().map(border_side_to_xml),
884 }
885}
886
887fn xml_border_to_style(border: &Border) -> BorderStyle {
889 BorderStyle {
890 left: border.left.as_ref().and_then(xml_border_side_to_style),
891 right: border.right.as_ref().and_then(xml_border_side_to_style),
892 top: border.top.as_ref().and_then(xml_border_side_to_style),
893 bottom: border.bottom.as_ref().and_then(xml_border_side_to_style),
894 diagonal: border.diagonal.as_ref().and_then(xml_border_side_to_style),
895 }
896}
897
898fn alignment_style_to_xml(align: &AlignmentStyle) -> Alignment {
900 Alignment {
901 horizontal: align.horizontal.map(|h| h.as_str().to_string()),
902 vertical: align.vertical.map(|v| v.as_str().to_string()),
903 wrap_text: if align.wrap_text { Some(true) } else { None },
904 text_rotation: align.text_rotation,
905 indent: align.indent,
906 shrink_to_fit: if align.shrink_to_fit {
907 Some(true)
908 } else {
909 None
910 },
911 }
912}
913
914fn xml_alignment_to_style(align: &Alignment) -> AlignmentStyle {
916 AlignmentStyle {
917 horizontal: align
918 .horizontal
919 .as_ref()
920 .and_then(|s| HorizontalAlign::from_str(s)),
921 vertical: align
922 .vertical
923 .as_ref()
924 .and_then(|s| VerticalAlign::from_str(s)),
925 wrap_text: align.wrap_text.unwrap_or(false),
926 text_rotation: align.text_rotation,
927 indent: align.indent,
928 shrink_to_fit: align.shrink_to_fit.unwrap_or(false),
929 }
930}
931
932fn protection_style_to_xml(prot: &ProtectionStyle) -> Protection {
934 Protection {
935 locked: Some(prot.locked),
936 hidden: Some(prot.hidden),
937 }
938}
939
940fn xml_protection_to_style(prot: &Protection) -> ProtectionStyle {
942 ProtectionStyle {
943 locked: prot.locked.unwrap_or(true), hidden: prot.hidden.unwrap_or(false),
945 }
946}
947
948fn fonts_equal(a: &Font, b: &Font) -> bool {
950 a.b.is_some() == b.b.is_some()
951 && a.i.is_some() == b.i.is_some()
952 && a.strike.is_some() == b.strike.is_some()
953 && a.u.is_some() == b.u.is_some()
954 && a.sz == b.sz
955 && a.color == b.color
956 && a.name == b.name
957}
958
959fn fills_equal(a: &Fill, b: &Fill) -> bool {
961 a.pattern_fill == b.pattern_fill && a.gradient_fill == b.gradient_fill
962}
963
964fn borders_equal(a: &Border, b: &Border) -> bool {
966 a.left == b.left
967 && a.right == b.right
968 && a.top == b.top
969 && a.bottom == b.bottom
970 && a.diagonal == b.diagonal
971}
972
973fn xfs_equal(a: &Xf, b: &Xf) -> bool {
975 a.num_fmt_id == b.num_fmt_id
976 && a.font_id == b.font_id
977 && a.fill_id == b.fill_id
978 && a.border_id == b.border_id
979 && a.apply_protection == b.apply_protection
980 && a.quote_prefix == b.quote_prefix
981 && a.alignment == b.alignment
982 && a.protection == b.protection
983}
984
985fn add_or_find_font(fonts: &mut Fonts, font: &FontStyle) -> u32 {
988 let xml_font = font_style_to_xml(font);
989
990 for (i, existing) in fonts.fonts.iter().enumerate() {
991 if fonts_equal(existing, &xml_font) {
992 return i as u32;
993 }
994 }
995
996 let id = fonts.fonts.len() as u32;
997 fonts.fonts.push(xml_font);
998 fonts.count = Some(fonts.fonts.len() as u32);
999 id
1000}
1001
1002fn add_or_find_fill(fills: &mut Fills, fill: &FillStyle) -> u32 {
1005 let xml_fill = fill_style_to_xml(fill);
1006
1007 for (i, existing) in fills.fills.iter().enumerate() {
1008 if fills_equal(existing, &xml_fill) {
1009 return i as u32;
1010 }
1011 }
1012
1013 let id = fills.fills.len() as u32;
1014 fills.fills.push(xml_fill);
1015 fills.count = Some(fills.fills.len() as u32);
1016 id
1017}
1018
1019fn add_or_find_border(borders: &mut Borders, border: &BorderStyle) -> u32 {
1022 let xml_border = border_style_to_xml(border);
1023
1024 for (i, existing) in borders.borders.iter().enumerate() {
1025 if borders_equal(existing, &xml_border) {
1026 return i as u32;
1027 }
1028 }
1029
1030 let id = borders.borders.len() as u32;
1031 borders.borders.push(xml_border);
1032 borders.count = Some(borders.borders.len() as u32);
1033 id
1034}
1035
1036fn add_or_find_num_fmt(stylesheet: &mut StyleSheet, fmt: &str) -> Result<u32> {
1042 if let Some(existing) = stylesheet
1043 .num_fmts
1044 .iter()
1045 .flat_map(|nfs| nfs.num_fmts.iter())
1046 .find(|nf| nf.format_code == fmt)
1047 {
1048 return Ok(existing.num_fmt_id);
1049 }
1050
1051 let used: HashSet<u32> = stylesheet
1052 .num_fmts
1053 .iter()
1054 .flat_map(|nfs| nfs.num_fmts.iter().map(|nf| nf.num_fmt_id))
1055 .chain(
1056 stylesheet
1057 .cell_xfs
1058 .xfs
1059 .iter()
1060 .chain(stylesheet.cell_style_xfs.iter().flat_map(|c| c.xfs.iter()))
1061 .filter_map(|xf| xf.num_fmt_id),
1062 )
1063 .chain(
1064 stylesheet
1065 .dxfs
1066 .iter()
1067 .flat_map(|d| d.dxfs.iter())
1068 .filter_map(|dxf| dxf.num_fmt.as_ref().map(|nf| nf.num_fmt_id)),
1069 )
1070 .collect();
1071 let next_id = (CUSTOM_NUM_FMT_BASE..=u32::MAX)
1072 .find(|id| !used.contains(id))
1073 .ok_or_else(|| {
1074 Error::InvalidArgument("no unused custom number format ID available".to_string())
1075 })?;
1076
1077 let num_fmts = stylesheet.num_fmts.get_or_insert_with(|| NumFmts {
1078 count: Some(0),
1079 num_fmts: Vec::new(),
1080 });
1081 num_fmts.num_fmts.push(NumFmt {
1082 num_fmt_id: next_id,
1083 format_code: fmt.to_string(),
1084 });
1085 num_fmts.count = Some(num_fmts.num_fmts.len() as u32);
1086
1087 Ok(next_id)
1088}
1089
1090pub fn add_style(stylesheet: &mut StyleSheet, style: &Style) -> Result<u32> {
1093 if stylesheet.cell_xfs.xfs.len() >= MAX_CELL_XFS {
1094 return Err(Error::CellStylesExceeded { max: MAX_CELL_XFS });
1095 }
1096
1097 let num_fmt_id = match &style.num_fmt {
1100 Some(NumFmtStyle::Builtin(id)) => *id,
1101 Some(NumFmtStyle::Custom(code)) => add_or_find_num_fmt(stylesheet, code)?,
1102 None => 0, };
1104
1105 let font_id = match &style.font {
1106 Some(font) => add_or_find_font(&mut stylesheet.fonts, font),
1107 None => 0, };
1109
1110 let fill_id = match &style.fill {
1111 Some(fill) => add_or_find_fill(&mut stylesheet.fills, fill),
1112 None => 0, };
1114
1115 let border_id = match &style.border {
1116 Some(border) => add_or_find_border(&mut stylesheet.borders, border),
1117 None => 0, };
1119
1120 let alignment = style.alignment.as_ref().map(alignment_style_to_xml);
1121 let protection = style.protection.as_ref().map(protection_style_to_xml);
1122
1123 let xf = Xf {
1124 num_fmt_id: Some(num_fmt_id),
1125 font_id: Some(font_id),
1126 fill_id: Some(fill_id),
1127 border_id: Some(border_id),
1128 xf_id: Some(0),
1129 apply_number_format: if num_fmt_id != 0 { Some(true) } else { None },
1130 apply_font: if font_id != 0 { Some(true) } else { None },
1131 apply_fill: if fill_id != 0 { Some(true) } else { None },
1132 apply_border: if border_id != 0 { Some(true) } else { None },
1133 apply_alignment: if alignment.is_some() {
1134 Some(true)
1135 } else {
1136 None
1137 },
1138 apply_protection: if protection.is_some() {
1139 Some(true)
1140 } else {
1141 None
1142 },
1143 quote_prefix: None,
1144 alignment,
1145 protection,
1146 };
1147
1148 for (i, existing) in stylesheet.cell_xfs.xfs.iter().enumerate() {
1149 if xfs_equal(existing, &xf) {
1150 return Ok(i as u32);
1151 }
1152 }
1153
1154 let id = stylesheet.cell_xfs.xfs.len() as u32;
1155 stylesheet.cell_xfs.xfs.push(xf);
1156 stylesheet.cell_xfs.count = Some(stylesheet.cell_xfs.xfs.len() as u32);
1157
1158 Ok(id)
1159}
1160
1161pub fn get_style(stylesheet: &StyleSheet, style_id: u32) -> Option<Style> {
1163 let xf = stylesheet.cell_xfs.xfs.get(style_id as usize)?;
1164
1165 let font = xf
1166 .font_id
1167 .and_then(|id| stylesheet.fonts.fonts.get(id as usize))
1168 .map(xml_font_to_style);
1169
1170 let fill = xf
1171 .fill_id
1172 .and_then(|id| stylesheet.fills.fills.get(id as usize))
1173 .and_then(xml_fill_to_style);
1174
1175 let border = xf
1176 .border_id
1177 .and_then(|id| stylesheet.borders.borders.get(id as usize))
1178 .map(xml_border_to_style);
1179
1180 let alignment = xf.alignment.as_ref().map(xml_alignment_to_style);
1181
1182 let num_fmt = xf.num_fmt_id.and_then(|id| {
1183 if id == 0 {
1184 return None;
1185 }
1186 if id < CUSTOM_NUM_FMT_BASE {
1188 Some(NumFmtStyle::Builtin(id))
1189 } else {
1190 stylesheet
1192 .num_fmts
1193 .as_ref()
1194 .and_then(|nfs| nfs.num_fmts.iter().find(|nf| nf.num_fmt_id == id))
1195 .map(|nf| NumFmtStyle::Custom(nf.format_code.clone()))
1196 }
1197 });
1198
1199 let protection = xf.protection.as_ref().map(xml_protection_to_style);
1200
1201 Some(Style {
1202 font,
1203 fill,
1204 border,
1205 alignment,
1206 num_fmt,
1207 protection,
1208 })
1209}
1210
1211pub fn compute_style_is_date(stylesheet: &StyleSheet) -> Vec<bool> {
1224 stylesheet
1225 .cell_xfs
1226 .xfs
1227 .iter()
1228 .map(|xf| {
1229 let num_fmt_id = xf.num_fmt_id.unwrap_or(0);
1230 if crate::cell::is_date_num_fmt(num_fmt_id) {
1231 return true;
1232 }
1233 if num_fmt_id >= CUSTOM_NUM_FMT_BASE {
1234 if let Some(nfs) = stylesheet.num_fmts.as_ref() {
1235 if let Some(nf) = nfs.num_fmts.iter().find(|nf| nf.num_fmt_id == num_fmt_id) {
1236 return crate::cell::is_date_format_code(&nf.format_code);
1237 }
1238 }
1239 }
1240 false
1241 })
1242 .collect()
1243}
1244
1245#[cfg(test)]
1246mod tests {
1247 use super::*;
1248
1249 fn default_stylesheet() -> StyleSheet {
1251 StyleSheet::default()
1252 }
1253
1254 fn xf_with_num_fmt(id: u32) -> Xf {
1255 Xf {
1256 num_fmt_id: Some(id),
1257 font_id: None,
1258 fill_id: None,
1259 border_id: None,
1260 xf_id: None,
1261 apply_number_format: None,
1262 apply_font: None,
1263 apply_fill: None,
1264 apply_border: None,
1265 apply_alignment: None,
1266 apply_protection: None,
1267 quote_prefix: None,
1268 alignment: None,
1269 protection: None,
1270 }
1271 }
1272
1273 #[test]
1274 fn test_xfs_equal_includes_passthrough_flags() {
1275 let xf = xf_with_num_fmt(0);
1276 let mut with_quote_prefix = xf.clone();
1277 with_quote_prefix.quote_prefix = Some(true);
1278 assert!(!xfs_equal(&xf, &with_quote_prefix));
1279
1280 let mut with_apply_protection = xf.clone();
1281 with_apply_protection.apply_protection = Some(true);
1282 assert!(!xfs_equal(&xf, &with_apply_protection));
1283 }
1284
1285 #[test]
1286 fn test_compute_style_is_date_builtin() {
1287 let mut ss = default_stylesheet();
1288 ss.cell_xfs.xfs = vec![
1290 xf_with_num_fmt(0),
1291 xf_with_num_fmt(14),
1292 xf_with_num_fmt(21),
1293 xf_with_num_fmt(2),
1294 ];
1295 ss.cell_xfs.count = Some(4);
1296 let flags = compute_style_is_date(&ss);
1297 assert_eq!(flags, vec![false, true, true, false]);
1298 }
1299
1300 #[test]
1301 fn test_compute_style_is_date_custom() {
1302 let mut ss = default_stylesheet();
1303 ss.num_fmts = Some(NumFmts {
1304 count: Some(2),
1305 num_fmts: vec![
1306 NumFmt {
1307 num_fmt_id: 164,
1308 format_code: "yyyy-mm-dd hh:mm".to_string(),
1309 },
1310 NumFmt {
1311 num_fmt_id: 165,
1312 format_code: "#,##0.00".to_string(),
1313 },
1314 ],
1315 });
1316 ss.cell_xfs.xfs = vec![xf_with_num_fmt(164), xf_with_num_fmt(165)];
1317 ss.cell_xfs.count = Some(2);
1318 let flags = compute_style_is_date(&ss);
1319 assert_eq!(flags, vec![true, false]);
1320 }
1321
1322 #[test]
1323 fn test_compute_style_is_date_missing_custom_format() {
1324 let mut ss = default_stylesheet();
1325 ss.cell_xfs.xfs = vec![xf_with_num_fmt(200)];
1327 ss.cell_xfs.count = Some(1);
1328 let flags = compute_style_is_date(&ss);
1329 assert_eq!(flags, vec![false]);
1330 }
1331
1332 #[test]
1333 fn test_compute_style_is_date_default_stylesheet() {
1334 let ss = default_stylesheet();
1337 let flags = compute_style_is_date(&ss);
1338 assert!(!flags.is_empty());
1339 assert!(flags.iter().all(|f| !*f));
1340 }
1341
1342 #[test]
1343 fn test_add_bold_font_style() {
1344 let mut ss = default_stylesheet();
1345 let style = Style {
1346 font: Some(FontStyle {
1347 bold: true,
1348 ..FontStyle::default()
1349 }),
1350 ..Style::default()
1351 };
1352
1353 let id = add_style(&mut ss, &style).unwrap();
1354 assert_eq!(id, 1);
1356 assert_eq!(ss.fonts.fonts.len(), 2);
1358 assert!(ss.fonts.fonts[1].b.is_some());
1359 }
1360
1361 #[test]
1362 fn test_xml_font_boolean_values_respect_explicit_false() {
1363 use sheetkit_xml::styles::BoolVal;
1364
1365 let font = Font {
1366 b: Some(BoolVal { val: Some(false) }),
1367 i: Some(BoolVal { val: Some(false) }),
1368 strike: Some(BoolVal { val: Some(false) }),
1369 u: None,
1370 sz: None,
1371 color: None,
1372 name: None,
1373 family: None,
1374 scheme: None,
1375 };
1376
1377 let style = xml_font_to_style(&font);
1378 assert!(!style.bold);
1379 assert!(!style.italic);
1380 assert!(!style.strikethrough);
1381 }
1382
1383 #[test]
1384 fn test_xml_font_boolean_values_default_to_true_when_val_is_absent() {
1385 use sheetkit_xml::styles::BoolVal;
1386
1387 let font = Font {
1388 b: Some(BoolVal { val: None }),
1389 i: Some(BoolVal { val: None }),
1390 strike: Some(BoolVal { val: None }),
1391 u: None,
1392 sz: None,
1393 color: None,
1394 name: None,
1395 family: None,
1396 scheme: None,
1397 };
1398
1399 let style = xml_font_to_style(&font);
1400 assert!(style.bold);
1401 assert!(style.italic);
1402 assert!(style.strikethrough);
1403 }
1404
1405 #[test]
1406 fn test_add_same_style_twice_deduplication() {
1407 let mut ss = default_stylesheet();
1408 let style = Style {
1409 font: Some(FontStyle {
1410 bold: true,
1411 ..FontStyle::default()
1412 }),
1413 ..Style::default()
1414 };
1415
1416 let id1 = add_style(&mut ss, &style).unwrap();
1417 let id2 = add_style(&mut ss, &style).unwrap();
1418 assert_eq!(id1, id2, "same style should return the same ID");
1419 assert_eq!(ss.fonts.fonts.len(), 2);
1421 assert_eq!(ss.cell_xfs.xfs.len(), 2);
1423 }
1424
1425 #[test]
1426 fn test_add_different_styles_different_ids() {
1427 let mut ss = default_stylesheet();
1428
1429 let bold_style = Style {
1430 font: Some(FontStyle {
1431 bold: true,
1432 ..FontStyle::default()
1433 }),
1434 ..Style::default()
1435 };
1436 let italic_style = Style {
1437 font: Some(FontStyle {
1438 italic: true,
1439 ..FontStyle::default()
1440 }),
1441 ..Style::default()
1442 };
1443
1444 let id1 = add_style(&mut ss, &bold_style).unwrap();
1445 let id2 = add_style(&mut ss, &italic_style).unwrap();
1446 assert_ne!(id1, id2);
1447 }
1448
1449 #[test]
1450 fn test_font_italic() {
1451 let mut ss = default_stylesheet();
1452 let style = Style {
1453 font: Some(FontStyle {
1454 italic: true,
1455 ..FontStyle::default()
1456 }),
1457 ..Style::default()
1458 };
1459
1460 let id = add_style(&mut ss, &style).unwrap();
1461 assert!(id > 0);
1462 let font_id = ss.cell_xfs.xfs[id as usize].font_id.unwrap();
1463 assert!(ss.fonts.fonts[font_id as usize].i.is_some());
1464 }
1465
1466 #[test]
1467 fn test_font_underline() {
1468 let mut ss = default_stylesheet();
1469 let style = Style {
1470 font: Some(FontStyle {
1471 underline: true,
1472 ..FontStyle::default()
1473 }),
1474 ..Style::default()
1475 };
1476
1477 let id = add_style(&mut ss, &style).unwrap();
1478 assert!(id > 0);
1479 let font_id = ss.cell_xfs.xfs[id as usize].font_id.unwrap();
1480 assert!(ss.fonts.fonts[font_id as usize].u.is_some());
1481 }
1482
1483 #[test]
1484 fn test_font_strikethrough() {
1485 let mut ss = default_stylesheet();
1486 let style = Style {
1487 font: Some(FontStyle {
1488 strikethrough: true,
1489 ..FontStyle::default()
1490 }),
1491 ..Style::default()
1492 };
1493
1494 let id = add_style(&mut ss, &style).unwrap();
1495 let font_id = ss.cell_xfs.xfs[id as usize].font_id.unwrap();
1496 assert!(ss.fonts.fonts[font_id as usize].strike.is_some());
1497 }
1498
1499 #[test]
1500 fn test_font_custom_name_and_size() {
1501 let mut ss = default_stylesheet();
1502 let style = Style {
1503 font: Some(FontStyle {
1504 name: Some("Arial".to_string()),
1505 size: Some(14.0),
1506 ..FontStyle::default()
1507 }),
1508 ..Style::default()
1509 };
1510
1511 let id = add_style(&mut ss, &style).unwrap();
1512 let font_id = ss.cell_xfs.xfs[id as usize].font_id.unwrap();
1513 let xml_font = &ss.fonts.fonts[font_id as usize];
1514 assert_eq!(xml_font.name.as_ref().unwrap().val, "Arial");
1515 assert_eq!(xml_font.sz.as_ref().unwrap().val, 14.0);
1516 }
1517
1518 #[test]
1519 fn test_font_with_rgb_color() {
1520 let mut ss = default_stylesheet();
1521 let style = Style {
1522 font: Some(FontStyle {
1523 color: Some(StyleColor::Rgb("FFFF0000".to_string())),
1524 ..FontStyle::default()
1525 }),
1526 ..Style::default()
1527 };
1528
1529 let id = add_style(&mut ss, &style).unwrap();
1530 let font_id = ss.cell_xfs.xfs[id as usize].font_id.unwrap();
1531 let xml_font = &ss.fonts.fonts[font_id as usize];
1532 assert_eq!(
1533 xml_font.color.as_ref().unwrap().rgb,
1534 Some("FFFF0000".to_string())
1535 );
1536 }
1537
1538 #[test]
1539 fn test_fill_solid_color() {
1540 let mut ss = default_stylesheet();
1541 let style = Style {
1542 fill: Some(FillStyle {
1543 pattern: PatternType::Solid,
1544 fg_color: Some(StyleColor::Rgb("FFFFFF00".to_string())),
1545 bg_color: None,
1546 gradient: None,
1547 }),
1548 ..Style::default()
1549 };
1550
1551 let id = add_style(&mut ss, &style).unwrap();
1552 let fill_id = ss.cell_xfs.xfs[id as usize].fill_id.unwrap();
1553 let xml_fill = &ss.fills.fills[fill_id as usize];
1554 let pf = xml_fill.pattern_fill.as_ref().unwrap();
1555 assert_eq!(pf.pattern_type, Some("solid".to_string()));
1556 assert_eq!(
1557 pf.fg_color.as_ref().unwrap().rgb,
1558 Some("FFFFFF00".to_string())
1559 );
1560 }
1561
1562 #[test]
1563 fn test_fill_pattern() {
1564 let mut ss = default_stylesheet();
1565 let style = Style {
1566 fill: Some(FillStyle {
1567 pattern: PatternType::LightGray,
1568 fg_color: None,
1569 bg_color: None,
1570 gradient: None,
1571 }),
1572 ..Style::default()
1573 };
1574
1575 let id = add_style(&mut ss, &style).unwrap();
1576 let fill_id = ss.cell_xfs.xfs[id as usize].fill_id.unwrap();
1577 let xml_fill = &ss.fills.fills[fill_id as usize];
1578 let pf = xml_fill.pattern_fill.as_ref().unwrap();
1579 assert_eq!(pf.pattern_type, Some("lightGray".to_string()));
1580 }
1581
1582 #[test]
1583 fn test_fill_deduplication() {
1584 let mut ss = default_stylesheet();
1585 let style = Style {
1586 fill: Some(FillStyle {
1587 pattern: PatternType::Solid,
1588 fg_color: Some(StyleColor::Rgb("FFFF0000".to_string())),
1589 bg_color: None,
1590 gradient: None,
1591 }),
1592 ..Style::default()
1593 };
1594
1595 let id1 = add_style(&mut ss, &style).unwrap();
1596 let id2 = add_style(&mut ss, &style).unwrap();
1597 assert_eq!(id1, id2);
1598 assert_eq!(ss.fills.fills.len(), 3);
1600 }
1601
1602 #[test]
1603 fn test_border_thin_all_sides() {
1604 let mut ss = default_stylesheet();
1605 let style = Style {
1606 border: Some(BorderStyle {
1607 left: Some(BorderSideStyle {
1608 style: BorderLineStyle::Thin,
1609 color: None,
1610 }),
1611 right: Some(BorderSideStyle {
1612 style: BorderLineStyle::Thin,
1613 color: None,
1614 }),
1615 top: Some(BorderSideStyle {
1616 style: BorderLineStyle::Thin,
1617 color: None,
1618 }),
1619 bottom: Some(BorderSideStyle {
1620 style: BorderLineStyle::Thin,
1621 color: None,
1622 }),
1623 diagonal: None,
1624 }),
1625 ..Style::default()
1626 };
1627
1628 let id = add_style(&mut ss, &style).unwrap();
1629 let border_id = ss.cell_xfs.xfs[id as usize].border_id.unwrap();
1630 let xml_border = &ss.borders.borders[border_id as usize];
1631 assert_eq!(
1632 xml_border.left.as_ref().unwrap().style,
1633 Some("thin".to_string())
1634 );
1635 assert_eq!(
1636 xml_border.right.as_ref().unwrap().style,
1637 Some("thin".to_string())
1638 );
1639 assert_eq!(
1640 xml_border.top.as_ref().unwrap().style,
1641 Some("thin".to_string())
1642 );
1643 assert_eq!(
1644 xml_border.bottom.as_ref().unwrap().style,
1645 Some("thin".to_string())
1646 );
1647 }
1648
1649 #[test]
1650 fn test_border_medium() {
1651 let mut ss = default_stylesheet();
1652 let style = Style {
1653 border: Some(BorderStyle {
1654 left: Some(BorderSideStyle {
1655 style: BorderLineStyle::Medium,
1656 color: Some(StyleColor::Rgb("FF000000".to_string())),
1657 }),
1658 right: None,
1659 top: None,
1660 bottom: None,
1661 diagonal: None,
1662 }),
1663 ..Style::default()
1664 };
1665
1666 let id = add_style(&mut ss, &style).unwrap();
1667 let border_id = ss.cell_xfs.xfs[id as usize].border_id.unwrap();
1668 let xml_border = &ss.borders.borders[border_id as usize];
1669 let left = xml_border.left.as_ref().unwrap();
1670 assert_eq!(left.style, Some("medium".to_string()));
1671 assert_eq!(
1672 left.color.as_ref().unwrap().rgb,
1673 Some("FF000000".to_string())
1674 );
1675 }
1676
1677 #[test]
1678 fn test_border_thick() {
1679 let mut ss = default_stylesheet();
1680 let style = Style {
1681 border: Some(BorderStyle {
1682 bottom: Some(BorderSideStyle {
1683 style: BorderLineStyle::Thick,
1684 color: None,
1685 }),
1686 ..BorderStyle::default()
1687 }),
1688 ..Style::default()
1689 };
1690
1691 let id = add_style(&mut ss, &style).unwrap();
1692 let border_id = ss.cell_xfs.xfs[id as usize].border_id.unwrap();
1693 let xml_border = &ss.borders.borders[border_id as usize];
1694 assert_eq!(
1695 xml_border.bottom.as_ref().unwrap().style,
1696 Some("thick".to_string())
1697 );
1698 }
1699
1700 #[test]
1701 fn test_num_fmt_builtin() {
1702 let mut ss = default_stylesheet();
1703 let style = Style {
1704 num_fmt: Some(NumFmtStyle::Builtin(builtin_num_fmts::PERCENT)),
1705 ..Style::default()
1706 };
1707
1708 let id = add_style(&mut ss, &style).unwrap();
1709 let xf = &ss.cell_xfs.xfs[id as usize];
1710 assert_eq!(xf.num_fmt_id, Some(builtin_num_fmts::PERCENT));
1711 assert_eq!(xf.apply_number_format, Some(true));
1712 }
1713
1714 #[test]
1715 fn test_num_fmt_custom() {
1716 let mut ss = default_stylesheet();
1717 let style = Style {
1718 num_fmt: Some(NumFmtStyle::Custom("#,##0.000".to_string())),
1719 ..Style::default()
1720 };
1721
1722 let id = add_style(&mut ss, &style).unwrap();
1723 let xf = &ss.cell_xfs.xfs[id as usize];
1724 let fmt_id = xf.num_fmt_id.unwrap();
1725 assert!(fmt_id >= CUSTOM_NUM_FMT_BASE);
1726
1727 let num_fmts = ss.num_fmts.as_ref().unwrap();
1729 let nf = num_fmts
1730 .num_fmts
1731 .iter()
1732 .find(|nf| nf.num_fmt_id == fmt_id)
1733 .unwrap();
1734 assert_eq!(nf.format_code, "#,##0.000");
1735 }
1736
1737 #[test]
1738 fn test_num_fmt_custom_deduplication() {
1739 let mut ss = default_stylesheet();
1740 let style = Style {
1741 num_fmt: Some(NumFmtStyle::Custom("0.0%".to_string())),
1742 ..Style::default()
1743 };
1744
1745 let id1 = add_style(&mut ss, &style).unwrap();
1746 let id2 = add_style(&mut ss, &style).unwrap();
1747 assert_eq!(id1, id2);
1748
1749 let num_fmts = ss.num_fmts.as_ref().unwrap();
1751 assert_eq!(num_fmts.num_fmts.len(), 1);
1752 }
1753
1754 #[test]
1755 fn test_alignment_horizontal_center() {
1756 let mut ss = default_stylesheet();
1757 let style = Style {
1758 alignment: Some(AlignmentStyle {
1759 horizontal: Some(HorizontalAlign::Center),
1760 ..AlignmentStyle::default()
1761 }),
1762 ..Style::default()
1763 };
1764
1765 let id = add_style(&mut ss, &style).unwrap();
1766 let xf = &ss.cell_xfs.xfs[id as usize];
1767 assert_eq!(xf.apply_alignment, Some(true));
1768 let align = xf.alignment.as_ref().unwrap();
1769 assert_eq!(align.horizontal, Some("center".to_string()));
1770 }
1771
1772 #[test]
1773 fn test_alignment_vertical_top() {
1774 let mut ss = default_stylesheet();
1775 let style = Style {
1776 alignment: Some(AlignmentStyle {
1777 vertical: Some(VerticalAlign::Top),
1778 ..AlignmentStyle::default()
1779 }),
1780 ..Style::default()
1781 };
1782
1783 let id = add_style(&mut ss, &style).unwrap();
1784 let xf = &ss.cell_xfs.xfs[id as usize];
1785 let align = xf.alignment.as_ref().unwrap();
1786 assert_eq!(align.vertical, Some("top".to_string()));
1787 }
1788
1789 #[test]
1790 fn test_alignment_wrap_text() {
1791 let mut ss = default_stylesheet();
1792 let style = Style {
1793 alignment: Some(AlignmentStyle {
1794 wrap_text: true,
1795 ..AlignmentStyle::default()
1796 }),
1797 ..Style::default()
1798 };
1799
1800 let id = add_style(&mut ss, &style).unwrap();
1801 let xf = &ss.cell_xfs.xfs[id as usize];
1802 let align = xf.alignment.as_ref().unwrap();
1803 assert_eq!(align.wrap_text, Some(true));
1804 }
1805
1806 #[test]
1807 fn test_alignment_text_rotation() {
1808 let mut ss = default_stylesheet();
1809 let style = Style {
1810 alignment: Some(AlignmentStyle {
1811 text_rotation: Some(90),
1812 ..AlignmentStyle::default()
1813 }),
1814 ..Style::default()
1815 };
1816
1817 let id = add_style(&mut ss, &style).unwrap();
1818 let xf = &ss.cell_xfs.xfs[id as usize];
1819 let align = xf.alignment.as_ref().unwrap();
1820 assert_eq!(align.text_rotation, Some(90));
1821 }
1822
1823 #[test]
1824 fn test_protection_locked() {
1825 let mut ss = default_stylesheet();
1826 let style = Style {
1827 protection: Some(ProtectionStyle {
1828 locked: true,
1829 hidden: false,
1830 }),
1831 ..Style::default()
1832 };
1833
1834 let id = add_style(&mut ss, &style).unwrap();
1835 let xf = &ss.cell_xfs.xfs[id as usize];
1836 let prot = xf.protection.as_ref().unwrap();
1837 assert_eq!(prot.locked, Some(true));
1838 assert_eq!(prot.hidden, Some(false));
1839 }
1840
1841 #[test]
1842 fn test_protection_hidden() {
1843 let mut ss = default_stylesheet();
1844 let style = Style {
1845 protection: Some(ProtectionStyle {
1846 locked: false,
1847 hidden: true,
1848 }),
1849 ..Style::default()
1850 };
1851
1852 let id = add_style(&mut ss, &style).unwrap();
1853 let xf = &ss.cell_xfs.xfs[id as usize];
1854 let prot = xf.protection.as_ref().unwrap();
1855 assert_eq!(prot.locked, Some(false));
1856 assert_eq!(prot.hidden, Some(true));
1857 }
1858
1859 #[test]
1860 fn test_combined_style_all_components() {
1861 let mut ss = default_stylesheet();
1862 let style = Style {
1863 font: Some(FontStyle {
1864 name: Some("Arial".to_string()),
1865 size: Some(12.0),
1866 bold: true,
1867 italic: false,
1868 underline: false,
1869 strikethrough: false,
1870 color: Some(StyleColor::Rgb("FF0000FF".to_string())),
1871 }),
1872 fill: Some(FillStyle {
1873 pattern: PatternType::Solid,
1874 fg_color: Some(StyleColor::Rgb("FFFFFF00".to_string())),
1875 bg_color: None,
1876 gradient: None,
1877 }),
1878 border: Some(BorderStyle {
1879 left: Some(BorderSideStyle {
1880 style: BorderLineStyle::Thin,
1881 color: Some(StyleColor::Rgb("FF000000".to_string())),
1882 }),
1883 right: Some(BorderSideStyle {
1884 style: BorderLineStyle::Thin,
1885 color: Some(StyleColor::Rgb("FF000000".to_string())),
1886 }),
1887 top: Some(BorderSideStyle {
1888 style: BorderLineStyle::Medium,
1889 color: None,
1890 }),
1891 bottom: Some(BorderSideStyle {
1892 style: BorderLineStyle::Medium,
1893 color: None,
1894 }),
1895 diagonal: None,
1896 }),
1897 alignment: Some(AlignmentStyle {
1898 horizontal: Some(HorizontalAlign::Center),
1899 vertical: Some(VerticalAlign::Center),
1900 wrap_text: true,
1901 text_rotation: None,
1902 indent: None,
1903 shrink_to_fit: false,
1904 }),
1905 num_fmt: Some(NumFmtStyle::Custom("#,##0.00".to_string())),
1906 protection: Some(ProtectionStyle {
1907 locked: true,
1908 hidden: false,
1909 }),
1910 };
1911
1912 let id = add_style(&mut ss, &style).unwrap();
1913 assert!(id > 0);
1914
1915 let xf = &ss.cell_xfs.xfs[id as usize];
1916 assert!(xf.font_id.unwrap() > 0);
1917 assert!(xf.fill_id.unwrap() > 0);
1918 assert!(xf.border_id.unwrap() > 0);
1919 assert!(xf.num_fmt_id.unwrap() >= CUSTOM_NUM_FMT_BASE);
1920 assert!(xf.alignment.is_some());
1921 assert!(xf.protection.is_some());
1922 assert_eq!(xf.apply_font, Some(true));
1923 assert_eq!(xf.apply_fill, Some(true));
1924 assert_eq!(xf.apply_border, Some(true));
1925 assert_eq!(xf.apply_number_format, Some(true));
1926 assert_eq!(xf.apply_alignment, Some(true));
1927 }
1928
1929 #[test]
1930 fn test_get_style_default() {
1931 let ss = default_stylesheet();
1932 let style = get_style(&ss, 0);
1933 assert!(style.is_some());
1934 let style = style.unwrap();
1935 assert!(style.font.is_some());
1937 }
1938
1939 #[test]
1940 fn test_get_style_invalid_id() {
1941 let ss = default_stylesheet();
1942 let style = get_style(&ss, 999);
1943 assert!(style.is_none());
1944 }
1945
1946 #[test]
1947 fn test_get_style_roundtrip_bold() {
1948 let mut ss = default_stylesheet();
1949 let original = Style {
1950 font: Some(FontStyle {
1951 bold: true,
1952 ..FontStyle::default()
1953 }),
1954 ..Style::default()
1955 };
1956
1957 let id = add_style(&mut ss, &original).unwrap();
1958 let retrieved = get_style(&ss, id).unwrap();
1959 assert!(retrieved.font.is_some());
1960 assert!(retrieved.font.as_ref().unwrap().bold);
1961 }
1962
1963 #[test]
1964 fn test_get_style_roundtrip_fill() {
1965 let mut ss = default_stylesheet();
1966 let original = Style {
1967 fill: Some(FillStyle {
1968 pattern: PatternType::Solid,
1969 fg_color: Some(StyleColor::Rgb("FFFF0000".to_string())),
1970 bg_color: None,
1971 gradient: None,
1972 }),
1973 ..Style::default()
1974 };
1975
1976 let id = add_style(&mut ss, &original).unwrap();
1977 let retrieved = get_style(&ss, id).unwrap();
1978 assert!(retrieved.fill.is_some());
1979 let fill = retrieved.fill.unwrap();
1980 assert_eq!(fill.pattern, PatternType::Solid);
1981 assert_eq!(fill.fg_color, Some(StyleColor::Rgb("FFFF0000".to_string())));
1982 }
1983
1984 #[test]
1985 fn test_get_style_roundtrip_alignment() {
1986 let mut ss = default_stylesheet();
1987 let original = Style {
1988 alignment: Some(AlignmentStyle {
1989 horizontal: Some(HorizontalAlign::Right),
1990 vertical: Some(VerticalAlign::Bottom),
1991 wrap_text: true,
1992 text_rotation: Some(45),
1993 indent: Some(2),
1994 shrink_to_fit: false,
1995 }),
1996 ..Style::default()
1997 };
1998
1999 let id = add_style(&mut ss, &original).unwrap();
2000 let retrieved = get_style(&ss, id).unwrap();
2001 assert!(retrieved.alignment.is_some());
2002 let align = retrieved.alignment.unwrap();
2003 assert_eq!(align.horizontal, Some(HorizontalAlign::Right));
2004 assert_eq!(align.vertical, Some(VerticalAlign::Bottom));
2005 assert!(align.wrap_text);
2006 assert_eq!(align.text_rotation, Some(45));
2007 assert_eq!(align.indent, Some(2));
2008 }
2009
2010 #[test]
2011 fn test_get_style_roundtrip_protection() {
2012 let mut ss = default_stylesheet();
2013 let original = Style {
2014 protection: Some(ProtectionStyle {
2015 locked: false,
2016 hidden: true,
2017 }),
2018 ..Style::default()
2019 };
2020
2021 let id = add_style(&mut ss, &original).unwrap();
2022 let retrieved = get_style(&ss, id).unwrap();
2023 assert!(retrieved.protection.is_some());
2024 let prot = retrieved.protection.unwrap();
2025 assert!(!prot.locked);
2026 assert!(prot.hidden);
2027 }
2028
2029 #[test]
2030 fn test_get_style_roundtrip_num_fmt_builtin() {
2031 let mut ss = default_stylesheet();
2032 let original = Style {
2033 num_fmt: Some(NumFmtStyle::Builtin(builtin_num_fmts::DATE_MDY)),
2034 ..Style::default()
2035 };
2036
2037 let id = add_style(&mut ss, &original).unwrap();
2038 let retrieved = get_style(&ss, id).unwrap();
2039 assert!(retrieved.num_fmt.is_some());
2040 match retrieved.num_fmt.unwrap() {
2041 NumFmtStyle::Builtin(fid) => assert_eq!(fid, builtin_num_fmts::DATE_MDY),
2042 _ => panic!("expected Builtin num fmt"),
2043 }
2044 }
2045
2046 #[test]
2047 fn test_get_style_roundtrip_num_fmt_custom() {
2048 let mut ss = default_stylesheet();
2049 let original = Style {
2050 num_fmt: Some(NumFmtStyle::Custom("yyyy-mm-dd".to_string())),
2051 ..Style::default()
2052 };
2053
2054 let id = add_style(&mut ss, &original).unwrap();
2055 let retrieved = get_style(&ss, id).unwrap();
2056 assert!(retrieved.num_fmt.is_some());
2057 match retrieved.num_fmt.unwrap() {
2058 NumFmtStyle::Custom(code) => assert_eq!(code, "yyyy-mm-dd"),
2059 _ => panic!("expected Custom num fmt"),
2060 }
2061 }
2062
2063 #[test]
2064 fn test_builtin_num_fmt_constants() {
2065 assert_eq!(builtin_num_fmts::GENERAL, 0);
2066 assert_eq!(builtin_num_fmts::INTEGER, 1);
2067 assert_eq!(builtin_num_fmts::DECIMAL_2, 2);
2068 assert_eq!(builtin_num_fmts::THOUSANDS, 3);
2069 assert_eq!(builtin_num_fmts::THOUSANDS_DECIMAL, 4);
2070 assert_eq!(builtin_num_fmts::PERCENT, 9);
2071 assert_eq!(builtin_num_fmts::PERCENT_DECIMAL, 10);
2072 assert_eq!(builtin_num_fmts::SCIENTIFIC, 11);
2073 assert_eq!(builtin_num_fmts::DATE_MDY, 14);
2074 assert_eq!(builtin_num_fmts::DATE_DMY, 15);
2075 assert_eq!(builtin_num_fmts::DATE_DM, 16);
2076 assert_eq!(builtin_num_fmts::DATE_MY, 17);
2077 assert_eq!(builtin_num_fmts::TIME_HM_AP, 18);
2078 assert_eq!(builtin_num_fmts::TIME_HMS_AP, 19);
2079 assert_eq!(builtin_num_fmts::TIME_HM, 20);
2080 assert_eq!(builtin_num_fmts::TIME_HMS, 21);
2081 assert_eq!(builtin_num_fmts::DATETIME, 22);
2082 assert_eq!(builtin_num_fmts::TEXT, 49);
2083 }
2084
2085 #[test]
2086 fn test_pattern_type_roundtrip() {
2087 let types = [
2088 PatternType::None,
2089 PatternType::Solid,
2090 PatternType::Gray125,
2091 PatternType::DarkGray,
2092 PatternType::MediumGray,
2093 PatternType::LightGray,
2094 ];
2095 for pt in &types {
2096 let s = pt.as_str();
2097 let back = PatternType::from_str(s);
2098 assert_eq!(*pt, back);
2099 }
2100 }
2101
2102 #[test]
2103 fn test_border_line_style_roundtrip() {
2104 let styles = [
2105 BorderLineStyle::Thin,
2106 BorderLineStyle::Medium,
2107 BorderLineStyle::Thick,
2108 BorderLineStyle::Dashed,
2109 BorderLineStyle::Dotted,
2110 BorderLineStyle::Double,
2111 BorderLineStyle::Hair,
2112 BorderLineStyle::MediumDashed,
2113 BorderLineStyle::DashDot,
2114 BorderLineStyle::MediumDashDot,
2115 BorderLineStyle::DashDotDot,
2116 BorderLineStyle::MediumDashDotDot,
2117 BorderLineStyle::SlantDashDot,
2118 ];
2119 for bls in &styles {
2120 let s = bls.as_str();
2121 let back = BorderLineStyle::from_str(s).unwrap();
2122 assert_eq!(*bls, back);
2123 }
2124 }
2125
2126 #[test]
2127 fn test_horizontal_align_roundtrip() {
2128 let aligns = [
2129 HorizontalAlign::General,
2130 HorizontalAlign::Left,
2131 HorizontalAlign::Center,
2132 HorizontalAlign::Right,
2133 HorizontalAlign::Fill,
2134 HorizontalAlign::Justify,
2135 HorizontalAlign::CenterContinuous,
2136 HorizontalAlign::Distributed,
2137 ];
2138 for ha in &aligns {
2139 let s = ha.as_str();
2140 let back = HorizontalAlign::from_str(s).unwrap();
2141 assert_eq!(*ha, back);
2142 }
2143 }
2144
2145 #[test]
2146 fn test_vertical_align_roundtrip() {
2147 let aligns = [
2148 VerticalAlign::Top,
2149 VerticalAlign::Center,
2150 VerticalAlign::Bottom,
2151 VerticalAlign::Justify,
2152 VerticalAlign::Distributed,
2153 ];
2154 for va in &aligns {
2155 let s = va.as_str();
2156 let back = VerticalAlign::from_str(s).unwrap();
2157 assert_eq!(*va, back);
2158 }
2159 }
2160
2161 #[test]
2162 fn test_style_color_rgb_roundtrip() {
2163 let color = StyleColor::Rgb("FF00FF00".to_string());
2164 let xml = style_color_to_xml(&color);
2165 let back = xml_color_to_style(&xml).unwrap();
2166 assert_eq!(color, back);
2167 }
2168
2169 #[test]
2170 fn test_style_color_theme_roundtrip() {
2171 let color = StyleColor::Theme(4);
2172 let xml = style_color_to_xml(&color);
2173 let back = xml_color_to_style(&xml).unwrap();
2174 assert_eq!(color, back);
2175 }
2176
2177 #[test]
2178 fn test_style_color_indexed_roundtrip() {
2179 let color = StyleColor::Indexed(10);
2180 let xml = style_color_to_xml(&color);
2181 let back = xml_color_to_style(&xml).unwrap();
2182 assert_eq!(color, back);
2183 }
2184
2185 #[test]
2186 fn test_font_deduplication() {
2187 let mut ss = default_stylesheet();
2188 let font = FontStyle {
2189 name: Some("Courier".to_string()),
2190 size: Some(10.0),
2191 bold: true,
2192 ..FontStyle::default()
2193 };
2194
2195 let id1 = add_or_find_font(&mut ss.fonts, &font);
2196 let id2 = add_or_find_font(&mut ss.fonts, &font);
2197 assert_eq!(id1, id2);
2198 assert_eq!(ss.fonts.fonts.len(), 2);
2200 }
2201
2202 #[test]
2203 fn test_multiple_custom_num_fmts() {
2204 let mut ss = default_stylesheet();
2205 let id1 = add_or_find_num_fmt(&mut ss, "0.0%").unwrap();
2206 let id2 = add_or_find_num_fmt(&mut ss, "#,##0").unwrap();
2207 assert_eq!(id1, 164);
2208 assert_eq!(id2, 165);
2209
2210 let id3 = add_or_find_num_fmt(&mut ss, "0.0%").unwrap();
2212 assert_eq!(id3, 164);
2213 }
2214
2215 fn stylesheet_with_num_fmts(ids: &[u32]) -> StyleSheet {
2216 let mut ss = default_stylesheet();
2217 ss.num_fmts = Some(NumFmts {
2218 count: Some(ids.len() as u32),
2219 num_fmts: ids
2220 .iter()
2221 .map(|id| NumFmt {
2222 num_fmt_id: *id,
2223 format_code: format!("\"fmt{id}\" 0"),
2224 })
2225 .collect(),
2226 });
2227 ss
2228 }
2229
2230 #[test]
2231 fn test_custom_num_fmt_with_max_existing_id_does_not_overflow() {
2232 let mut ss = stylesheet_with_num_fmts(&[164, u32::MAX]);
2233 let style = Style {
2234 num_fmt: Some(NumFmtStyle::Custom("0.000".to_string())),
2235 ..Style::default()
2236 };
2237
2238 let style_id = add_style(&mut ss, &style).unwrap();
2239
2240 let nfs = &ss.num_fmts.as_ref().unwrap().num_fmts;
2241 assert_eq!(nfs.len(), 3);
2242 let new_id = ss.cell_xfs.xfs[style_id as usize].num_fmt_id.unwrap();
2243 assert_eq!(new_id, 165);
2244 assert_eq!(nfs.iter().filter(|nf| nf.num_fmt_id == new_id).count(), 1);
2245 let back = get_style(&ss, style_id).unwrap();
2246 assert!(matches!(back.num_fmt, Some(NumFmtStyle::Custom(ref c)) if c == "0.000"));
2247 }
2248
2249 #[test]
2250 fn test_custom_num_fmt_skips_ids_referenced_by_xfs() {
2251 let mut ss = default_stylesheet();
2252 let mut xf = ss.cell_xfs.xfs[0].clone();
2253 xf.num_fmt_id = Some(164);
2254 ss.cell_xfs.xfs.push(xf);
2255 ss.cell_xfs.count = Some(ss.cell_xfs.xfs.len() as u32);
2256
2257 assert_eq!(add_or_find_num_fmt(&mut ss, "0.0000").unwrap(), 165);
2258 }
2259
2260 #[test]
2261 fn test_xf_count_maintained() {
2262 let mut ss = default_stylesheet();
2263 assert_eq!(ss.cell_xfs.count, Some(1));
2264
2265 let style = Style {
2266 font: Some(FontStyle {
2267 bold: true,
2268 ..FontStyle::default()
2269 }),
2270 ..Style::default()
2271 };
2272 add_style(&mut ss, &style).unwrap();
2273 assert_eq!(ss.cell_xfs.count, Some(2));
2274 }
2275
2276 #[test]
2279 fn test_style_builder_empty() {
2280 let style = StyleBuilder::new().build();
2281 assert!(style.font.is_none());
2282 assert!(style.fill.is_none());
2283 assert!(style.border.is_none());
2284 assert!(style.alignment.is_none());
2285 assert!(style.num_fmt.is_none());
2286 assert!(style.protection.is_none());
2287 }
2288
2289 #[test]
2290 fn test_style_builder_default_equivalent() {
2291 let style = StyleBuilder::default().build();
2292 assert!(style.font.is_none());
2293 assert!(style.fill.is_none());
2294 }
2295
2296 #[test]
2297 fn test_style_builder_font() {
2298 let style = StyleBuilder::new()
2299 .bold(true)
2300 .italic(true)
2301 .font_size(14.0)
2302 .font_name("Arial")
2303 .font_color_rgb("FF0000FF")
2304 .build();
2305 let font = style.font.unwrap();
2306 assert!(font.bold);
2307 assert!(font.italic);
2308 assert_eq!(font.size, Some(14.0));
2309 assert_eq!(font.name, Some("Arial".to_string()));
2310 assert_eq!(font.color, Some(StyleColor::Rgb("FF0000FF".to_string())));
2311 }
2312
2313 #[test]
2314 fn test_style_builder_font_underline_strikethrough() {
2315 let style = StyleBuilder::new()
2316 .underline(true)
2317 .strikethrough(true)
2318 .build();
2319 let font = style.font.unwrap();
2320 assert!(font.underline);
2321 assert!(font.strikethrough);
2322 }
2323
2324 #[test]
2325 fn test_style_builder_font_color_typed() {
2326 let style = StyleBuilder::new().font_color(StyleColor::Theme(4)).build();
2327 let font = style.font.unwrap();
2328 assert_eq!(font.color, Some(StyleColor::Theme(4)));
2329 }
2330
2331 #[test]
2332 fn test_style_builder_solid_fill() {
2333 let style = StyleBuilder::new().solid_fill("FFFF0000").build();
2334 let fill = style.fill.unwrap();
2335 assert_eq!(fill.pattern, PatternType::Solid);
2336 assert_eq!(fill.fg_color, Some(StyleColor::Rgb("FFFF0000".to_string())));
2337 }
2338
2339 #[test]
2340 fn test_style_builder_fill_pattern_and_colors() {
2341 let style = StyleBuilder::new()
2342 .fill_pattern(PatternType::Gray125)
2343 .fill_fg_color_rgb("FFAABBCC")
2344 .fill_bg_color(StyleColor::Indexed(64))
2345 .build();
2346 let fill = style.fill.unwrap();
2347 assert_eq!(fill.pattern, PatternType::Gray125);
2348 assert_eq!(fill.fg_color, Some(StyleColor::Rgb("FFAABBCC".to_string())));
2349 assert_eq!(fill.bg_color, Some(StyleColor::Indexed(64)));
2350 }
2351
2352 #[test]
2353 fn test_style_builder_border_individual_sides() {
2354 let style = StyleBuilder::new()
2355 .border_left(
2356 BorderLineStyle::Thin,
2357 StyleColor::Rgb("FF000000".to_string()),
2358 )
2359 .border_right(
2360 BorderLineStyle::Medium,
2361 StyleColor::Rgb("FF111111".to_string()),
2362 )
2363 .border_top(
2364 BorderLineStyle::Thick,
2365 StyleColor::Rgb("FF222222".to_string()),
2366 )
2367 .border_bottom(
2368 BorderLineStyle::Dashed,
2369 StyleColor::Rgb("FF333333".to_string()),
2370 )
2371 .build();
2372 let border = style.border.unwrap();
2373
2374 let left = border.left.unwrap();
2375 assert_eq!(left.style, BorderLineStyle::Thin);
2376 assert_eq!(left.color, Some(StyleColor::Rgb("FF000000".to_string())));
2377
2378 let right = border.right.unwrap();
2379 assert_eq!(right.style, BorderLineStyle::Medium);
2380
2381 let top = border.top.unwrap();
2382 assert_eq!(top.style, BorderLineStyle::Thick);
2383
2384 let bottom = border.bottom.unwrap();
2385 assert_eq!(bottom.style, BorderLineStyle::Dashed);
2386 }
2387
2388 #[test]
2389 fn test_style_builder_border_all() {
2390 let style = StyleBuilder::new()
2391 .border_all(
2392 BorderLineStyle::Thin,
2393 StyleColor::Rgb("FF000000".to_string()),
2394 )
2395 .build();
2396 let border = style.border.unwrap();
2397 assert!(border.left.is_some());
2398 assert!(border.right.is_some());
2399 assert!(border.top.is_some());
2400 assert!(border.bottom.is_some());
2401 assert!(border.diagonal.is_none());
2403
2404 let left = border.left.unwrap();
2405 assert_eq!(left.style, BorderLineStyle::Thin);
2406 assert_eq!(left.color, Some(StyleColor::Rgb("FF000000".to_string())));
2407 }
2408
2409 #[test]
2410 fn test_style_builder_alignment() {
2411 let style = StyleBuilder::new()
2412 .horizontal_align(HorizontalAlign::Center)
2413 .vertical_align(VerticalAlign::Center)
2414 .wrap_text(true)
2415 .text_rotation(45)
2416 .indent(2)
2417 .shrink_to_fit(true)
2418 .build();
2419 let align = style.alignment.unwrap();
2420 assert_eq!(align.horizontal, Some(HorizontalAlign::Center));
2421 assert_eq!(align.vertical, Some(VerticalAlign::Center));
2422 assert!(align.wrap_text);
2423 assert_eq!(align.text_rotation, Some(45));
2424 assert_eq!(align.indent, Some(2));
2425 assert!(align.shrink_to_fit);
2426 }
2427
2428 #[test]
2429 fn test_style_builder_num_format_builtin() {
2430 let style = StyleBuilder::new().num_format_builtin(2).build();
2431 match style.num_fmt.unwrap() {
2432 NumFmtStyle::Builtin(id) => assert_eq!(id, 2),
2433 _ => panic!("expected builtin format"),
2434 }
2435 }
2436
2437 #[test]
2438 fn test_style_builder_num_format_custom() {
2439 let style = StyleBuilder::new().num_format_custom("#,##0.00").build();
2440 match style.num_fmt.unwrap() {
2441 NumFmtStyle::Custom(fmt) => assert_eq!(fmt, "#,##0.00"),
2442 _ => panic!("expected custom format"),
2443 }
2444 }
2445
2446 #[test]
2447 fn test_style_builder_protection() {
2448 let style = StyleBuilder::new().locked(true).hidden(true).build();
2449 let prot = style.protection.unwrap();
2450 assert!(prot.locked);
2451 assert!(prot.hidden);
2452 }
2453
2454 #[test]
2455 fn test_style_builder_protection_unlock() {
2456 let style = StyleBuilder::new().locked(false).hidden(false).build();
2457 let prot = style.protection.unwrap();
2458 assert!(!prot.locked);
2459 assert!(!prot.hidden);
2460 }
2461
2462 #[test]
2463 fn test_style_builder_full_style() {
2464 let style = StyleBuilder::new()
2465 .bold(true)
2466 .font_size(12.0)
2467 .solid_fill("FFFFFF00")
2468 .border_all(
2469 BorderLineStyle::Thin,
2470 StyleColor::Rgb("FF000000".to_string()),
2471 )
2472 .horizontal_align(HorizontalAlign::Center)
2473 .num_format_builtin(2)
2474 .locked(true)
2475 .build();
2476 assert!(style.font.is_some());
2477 assert!(style.fill.is_some());
2478 assert!(style.border.is_some());
2479 assert!(style.alignment.is_some());
2480 assert!(style.num_fmt.is_some());
2481 assert!(style.protection.is_some());
2482
2483 assert!(style.font.as_ref().unwrap().bold);
2485 assert_eq!(style.font.as_ref().unwrap().size, Some(12.0));
2486 assert_eq!(style.fill.as_ref().unwrap().pattern, PatternType::Solid);
2487 }
2488
2489 #[test]
2490 fn test_style_builder_integrates_with_add_style() {
2491 let mut ss = default_stylesheet();
2492 let style = StyleBuilder::new()
2493 .bold(true)
2494 .font_size(11.0)
2495 .solid_fill("FFFF0000")
2496 .horizontal_align(HorizontalAlign::Center)
2497 .build();
2498
2499 let id = add_style(&mut ss, &style).unwrap();
2500 assert!(id > 0);
2501
2502 let retrieved = get_style(&ss, id).unwrap();
2504 assert!(retrieved.font.as_ref().unwrap().bold);
2505 assert_eq!(retrieved.fill.as_ref().unwrap().pattern, PatternType::Solid);
2506 assert_eq!(
2507 retrieved.alignment.as_ref().unwrap().horizontal,
2508 Some(HorizontalAlign::Center)
2509 );
2510 }
2511}