1use std::fmt;
4
5use std::borrow::Cow;
6
7use crate::color::Rgba;
8#[allow(unused_imports)]
9use crate::detect::{system_icon_set, system_icon_theme};
10use crate::model::IconSet;
11pub use crate::model::{
12 AnimatedIcon, EmptyFrameListError, FrameList, FramesData, IconData, IconProvider, IconRole,
13 RgbaData, TransformAnimation, TransformData, icon_name,
14};
15#[allow(unused_imports)]
16use crate::model::{bundled_icon_by_name, bundled_icon_svg};
17
18#[cfg_attr(
30 not(any(
31 all(target_os = "linux", feature = "system-icons"),
32 feature = "svg-rasterize"
33 )),
34 allow(dead_code)
35)]
36pub(crate) const MAX_ICON_DECODE_BYTES: usize = 64 * 1024 * 1024;
37
38pub const MAX_ICON_SIZE: u32 = 512;
49
50#[cfg_attr(
53 not(all(
54 any(target_os = "macos", target_os = "windows"),
55 feature = "system-icons"
56 )),
57 allow(dead_code)
58)]
59pub(crate) fn raster_size_in_bound(size: u32) -> bool {
60 raster_bytes_in_bound(size, size).is_some()
61}
62
63#[cfg_attr(
67 not(any(
68 all(
69 any(target_os = "macos", target_os = "windows"),
70 feature = "system-icons"
71 ),
72 feature = "svg-rasterize"
73 )),
74 allow(dead_code)
75)]
76pub(crate) fn raster_bytes_in_bound(width: u32, height: u32) -> Option<usize> {
77 if width == 0 || height == 0 {
78 return None;
79 }
80 u64::from(width)
81 .checked_mul(u64::from(height))?
82 .checked_mul(4)
83 .filter(|&bytes| bytes <= MAX_ICON_DECODE_BYTES as u64)
84 .and_then(|bytes| usize::try_from(bytes).ok())
85}
86
87fn rgb(color: Rgba) -> [u8; 3] {
90 [color.r, color.g, color.b]
91}
92
93#[derive(Debug)]
111#[non_exhaustive]
112pub enum IconId<'a> {
113 Role(IconRole),
115 Name(&'a str),
117 Custom(&'a dyn IconProvider),
119}
120
121impl From<IconRole> for IconId<'_> {
122 fn from(role: IconRole) -> Self {
123 IconId::Role(role)
124 }
125}
126
127impl<'a> From<&'a str> for IconId<'a> {
128 fn from(name: &'a str) -> Self {
129 IconId::Name(name)
130 }
131}
132
133impl<'a> From<&'a dyn IconProvider> for IconId<'a> {
134 fn from(provider: &'a dyn IconProvider) -> Self {
135 IconId::Custom(provider)
136 }
137}
138
139impl<'a, T: IconProvider> From<&'a T> for IconId<'a> {
142 fn from(provider: &'a T) -> Self {
143 IconId::Custom(provider)
144 }
145}
146
147#[derive(Debug)]
200#[must_use]
201pub struct FreedesktopLoader<'a> {
202 #[allow(dead_code)]
204 wanted: Wanted<'a>,
205 #[allow(dead_code)]
206 size: u32,
207 #[allow(dead_code)]
208 fg_color: Option<[u8; 3]>,
209 #[allow(dead_code)]
210 theme: Option<&'a str>,
211}
212
213#[derive(Debug)]
215enum Wanted<'a> {
216 #[allow(dead_code)]
219 Id(IconId<'a>),
220 #[allow(dead_code)]
222 AnyOf(&'a [&'a str]),
223}
224
225impl<'a> FreedesktopLoader<'a> {
226 pub fn new(id: impl Into<IconId<'a>>) -> Self {
228 Self::wanting(Wanted::Id(id.into()))
229 }
230
231 pub fn any(names: &'a [&'a str]) -> Self {
260 Self::wanting(Wanted::AnyOf(names))
261 }
262
263 fn wanting(wanted: Wanted<'a>) -> Self {
265 Self {
266 wanted,
267 size: 24,
268 fg_color: None,
269 theme: None,
270 }
271 }
272
273 pub fn size(mut self, size: u32) -> Self {
277 self.size = size.clamp(1, MAX_ICON_SIZE);
278 self
279 }
280
281 pub fn color(mut self, color: Rgba) -> Self {
284 self.fg_color = Some(rgb(color));
285 self
286 }
287
288 pub fn color_opt(mut self, color: Option<Rgba>) -> Self {
291 self.fg_color = color.map(rgb);
292 self
293 }
294
295 pub fn theme(mut self, theme: &'a str) -> Self {
299 self.theme = Some(theme);
300 self
301 }
302
303 #[must_use]
318 pub fn load(self) -> Option<IconData> {
319 self.load_with(system_icon_theme)
320 }
321
322 #[allow(unused_variables)]
325 fn load_with(self, detect: impl FnOnce() -> crate::Result<String>) -> Option<IconData> {
326 #[cfg(all(target_os = "linux", feature = "system-icons"))]
327 {
328 let detected;
329 let theme: Option<&str> = match self.theme {
330 Some(t) => Some(t),
331 None => {
332 detected = detect().ok();
333 detected.as_deref()
334 }
335 };
336 match self.wanted {
337 Wanted::AnyOf(names) => crate::freedesktop::load_freedesktop_icon_by_names(
338 names,
339 theme?,
340 self.size,
341 self.fg_color,
342 ),
343 Wanted::Id(IconId::Role(role)) => {
344 let name = icon_name(role, IconSet::Freedesktop)?;
345 crate::freedesktop::load_freedesktop_icon_by_name(
346 name,
347 theme?,
348 self.size,
349 self.fg_color,
350 )
351 }
352 Wanted::Id(IconId::Name(name)) => {
353 crate::freedesktop::load_freedesktop_icon_by_name(
354 name,
355 theme?,
356 self.size,
357 self.fg_color,
358 )
359 }
360 Wanted::Id(IconId::Custom(provider)) => {
361 if let Some(theme) = theme
362 && let Some(name) = provider.icon_name(IconSet::Freedesktop)
363 && let Some(data) = crate::freedesktop::load_freedesktop_icon_by_name(
364 name,
365 theme,
366 self.size,
367 self.fg_color,
368 )
369 {
370 return Some(data);
371 }
372 provider.icon_svg(IconSet::Freedesktop).map(IconData::Svg)
373 }
374 }
375 }
376 #[cfg(not(all(target_os = "linux", feature = "system-icons")))]
377 {
378 None
379 }
380 }
381
382 #[must_use]
400 #[allow(unused_variables)]
401 pub fn load_where(self, accept: impl FnMut(&IconData) -> bool) -> Option<IconData> {
402 #[cfg(all(target_os = "linux", feature = "system-icons"))]
403 {
404 let mut accept = accept;
405 let detected;
406 let theme: Option<&str> = match self.theme {
407 Some(t) => Some(t),
408 None => {
409 detected = system_icon_theme().ok();
410 detected.as_deref()
411 }
412 };
413 match self.wanted {
414 Wanted::AnyOf(names) => crate::freedesktop::load_freedesktop_icon_by_names_where(
415 names,
416 theme?,
417 self.size,
418 self.fg_color,
419 &mut accept,
420 ),
421 Wanted::Id(IconId::Role(role)) => {
422 let name = icon_name(role, IconSet::Freedesktop)?;
423 crate::freedesktop::load_freedesktop_icon_by_name_where(
424 name,
425 theme?,
426 self.size,
427 self.fg_color,
428 &mut accept,
429 )
430 }
431 Wanted::Id(IconId::Name(name)) => {
432 crate::freedesktop::load_freedesktop_icon_by_name_where(
433 name,
434 theme?,
435 self.size,
436 self.fg_color,
437 &mut accept,
438 )
439 }
440 Wanted::Id(IconId::Custom(provider)) => {
441 if let Some(theme) = theme
442 && let Some(name) = provider.icon_name(IconSet::Freedesktop)
443 && let Some(data) = crate::freedesktop::load_freedesktop_icon_by_name_where(
444 name,
445 theme,
446 self.size,
447 self.fg_color,
448 &mut accept,
449 )
450 {
451 return Some(data);
452 }
453 provider
454 .icon_svg(IconSet::Freedesktop)
455 .map(IconData::Svg)
456 .filter(|data| accept(data))
457 }
458 }
459 }
460 #[cfg(not(all(target_os = "linux", feature = "system-icons")))]
461 {
462 None
463 }
464 }
465
466 #[must_use]
478 #[allow(unused_variables)]
479 pub fn load_indicator(theme: Option<&str>) -> Option<AnimatedIcon> {
480 #[cfg(all(target_os = "linux", feature = "system-icons"))]
481 {
482 crate::freedesktop::load_freedesktop_spinner(theme)
483 }
484 #[cfg(not(all(target_os = "linux", feature = "system-icons")))]
485 {
486 None
487 }
488 }
489}
490
491#[derive(Debug)]
496#[must_use]
497pub struct SfSymbolsLoader<'a> {
498 #[allow(dead_code)] id: IconId<'a>,
500 #[allow(dead_code)] size: Option<u32>,
502 #[allow(dead_code)] fg_color: Option<[u8; 3]>,
504}
505
506impl<'a> SfSymbolsLoader<'a> {
507 pub fn new(id: impl Into<IconId<'a>>) -> Self {
510 Self {
511 id: id.into(),
512 size: None,
513 fg_color: None,
514 }
515 }
516
517 pub fn size(mut self, size: u32) -> Self {
522 self.size = Some(size.clamp(1, MAX_ICON_SIZE));
523 self
524 }
525
526 pub fn color(mut self, color: Rgba) -> Self {
529 self.fg_color = Some(rgb(color));
530 self
531 }
532
533 pub fn color_opt(mut self, color: Option<Rgba>) -> Self {
536 self.fg_color = color.map(rgb);
537 self
538 }
539
540 #[must_use]
544 #[allow(unused_variables)]
545 pub fn load(self) -> Option<IconData> {
546 #[cfg(all(target_os = "macos", feature = "system-icons"))]
547 {
548 match self.id {
549 IconId::Role(role) => {
550 let name = icon_name(role, IconSet::SfSymbols)?;
551 crate::sficons::load_sf_icon_by_name(name, self.size, self.fg_color)
552 }
553 IconId::Name(n) => {
554 crate::sficons::load_sf_icon_by_name(n, self.size, self.fg_color)
555 }
556 IconId::Custom(p) => {
557 if let Some(n) = p.icon_name(IconSet::SfSymbols)
558 && let Some(data) =
559 crate::sficons::load_sf_icon_by_name(n, self.size, self.fg_color)
560 {
561 return Some(data);
562 }
563 p.icon_svg(IconSet::SfSymbols).map(IconData::Svg)
564 }
565 }
566 }
567 #[cfg(not(all(target_os = "macos", feature = "system-icons")))]
568 {
569 None
570 }
571 }
572 }
574
575#[derive(Debug)]
582#[must_use]
583pub struct SegoeFluentLoader<'a> {
584 #[allow(dead_code)] id: IconId<'a>,
586 #[allow(dead_code)] size: Option<u32>,
588 #[allow(dead_code)] fg_color: Option<[u8; 3]>,
590}
591
592impl<'a> SegoeFluentLoader<'a> {
593 pub fn new(id: impl Into<IconId<'a>>) -> Self {
596 Self {
597 id: id.into(),
598 size: None,
599 fg_color: None,
600 }
601 }
602
603 pub fn size(mut self, size: u32) -> Self {
607 self.size = Some(size.clamp(1, MAX_ICON_SIZE));
608 self
609 }
610
611 pub fn color(mut self, color: Rgba) -> Self {
615 self.fg_color = Some(rgb(color));
616 self
617 }
618
619 pub fn color_opt(mut self, color: Option<Rgba>) -> Self {
622 self.fg_color = color.map(rgb);
623 self
624 }
625
626 #[must_use]
630 #[allow(unused_variables)]
631 pub fn load(self) -> Option<IconData> {
632 #[cfg(all(target_os = "windows", feature = "system-icons"))]
633 {
634 match self.id {
635 IconId::Role(role) => {
636 let name = icon_name(role, IconSet::SegoeFluent)?;
637 crate::winicons::load_windows_icon_by_name(name, self.size, self.fg_color)
638 }
639 IconId::Name(n) => {
640 crate::winicons::load_windows_icon_by_name(n, self.size, self.fg_color)
641 }
642 IconId::Custom(p) => {
643 if let Some(n) = p.icon_name(IconSet::SegoeFluent)
644 && let Some(data) =
645 crate::winicons::load_windows_icon_by_name(n, self.size, self.fg_color)
646 {
647 return Some(data);
648 }
649 p.icon_svg(IconSet::SegoeFluent).map(IconData::Svg)
650 }
651 }
652 }
653 #[cfg(not(all(target_os = "windows", feature = "system-icons")))]
654 {
655 None
656 }
657 }
658 }
660
661#[derive(Debug)]
665#[must_use]
666pub struct MaterialLoader<'a> {
667 #[allow(dead_code)] id: IconId<'a>,
669}
670
671impl<'a> MaterialLoader<'a> {
672 pub fn new(id: impl Into<IconId<'a>>) -> Self {
674 Self { id: id.into() }
675 }
676
677 #[must_use]
681 #[allow(unused_variables)]
682 pub fn load(self) -> Option<IconData> {
683 #[cfg(feature = "material-icons")]
684 {
685 match self.id {
686 IconId::Role(role) => bundled_icon_svg(role, IconSet::Material)
687 .map(|b| IconData::Svg(Cow::Borrowed(b))),
688 IconId::Name(n) => bundled_icon_by_name(n, IconSet::Material)
689 .map(|b| IconData::Svg(Cow::Borrowed(b))),
690 IconId::Custom(p) => {
691 if let Some(n) = p.icon_name(IconSet::Material)
692 && let Some(b) = bundled_icon_by_name(n, IconSet::Material)
693 {
694 return Some(IconData::Svg(Cow::Borrowed(b)));
695 }
696 p.icon_svg(IconSet::Material).map(IconData::Svg)
697 }
698 }
699 }
700 #[cfg(not(feature = "material-icons"))]
701 {
702 None
703 }
704 }
705
706 #[must_use]
710 pub fn load_indicator() -> Option<AnimatedIcon> {
711 #[cfg(feature = "material-icons")]
712 {
713 Some(crate::spinners::material_spinner())
714 }
715 #[cfg(not(feature = "material-icons"))]
716 {
717 None
718 }
719 }
720}
721
722#[derive(Debug)]
724#[must_use]
725pub struct LucideLoader<'a> {
726 #[allow(dead_code)] id: IconId<'a>,
728}
729
730impl<'a> LucideLoader<'a> {
731 pub fn new(id: impl Into<IconId<'a>>) -> Self {
733 Self { id: id.into() }
734 }
735
736 #[must_use]
740 #[allow(unused_variables)]
741 pub fn load(self) -> Option<IconData> {
742 #[cfg(feature = "lucide-icons")]
743 {
744 match self.id {
745 IconId::Role(role) => {
746 bundled_icon_svg(role, IconSet::Lucide).map(|b| IconData::Svg(Cow::Borrowed(b)))
747 }
748 IconId::Name(n) => bundled_icon_by_name(n, IconSet::Lucide)
749 .map(|b| IconData::Svg(Cow::Borrowed(b))),
750 IconId::Custom(p) => {
751 if let Some(n) = p.icon_name(IconSet::Lucide)
752 && let Some(b) = bundled_icon_by_name(n, IconSet::Lucide)
753 {
754 return Some(IconData::Svg(Cow::Borrowed(b)));
755 }
756 p.icon_svg(IconSet::Lucide).map(IconData::Svg)
757 }
758 }
759 }
760 #[cfg(not(feature = "lucide-icons"))]
761 {
762 None
763 }
764 }
765
766 #[must_use]
770 pub fn load_indicator() -> Option<AnimatedIcon> {
771 #[cfg(feature = "lucide-icons")]
772 {
773 Some(crate::spinners::lucide_spinner())
774 }
775 #[cfg(not(feature = "lucide-icons"))]
776 {
777 None
778 }
779 }
780}
781
782#[must_use]
793pub fn load_icon<'a>(id: impl Into<IconId<'a>>, set: IconSet) -> Option<IconData> {
794 let id = id.into();
795 match set {
796 IconSet::Freedesktop => FreedesktopLoader::new(id).load(),
797 IconSet::SfSymbols => SfSymbolsLoader::new(id).load(),
798 IconSet::SegoeFluent => SegoeFluentLoader::new(id).load(),
799 IconSet::Material => MaterialLoader::new(id).load(),
800 IconSet::Lucide => LucideLoader::new(id).load(),
801 }
802}
803
804#[must_use]
816pub fn load_icon_indicator(set: IconSet, theme: Option<&str>) -> Option<AnimatedIcon> {
817 match set {
818 IconSet::Freedesktop => FreedesktopLoader::load_indicator(theme),
819 IconSet::Material => MaterialLoader::load_indicator(),
820 IconSet::Lucide => LucideLoader::load_indicator(),
821 IconSet::SfSymbols | IconSet::SegoeFluent => None,
822 }
823}
824
825#[must_use]
863pub fn load_custom_icon(
864 provider: &(impl IconProvider + ?Sized),
865 set: IconSet,
866 color: Option<Rgba>,
867 size: Option<u32>,
868) -> Option<IconData> {
869 load_custom_icon_in(provider, set, None, color, size)
870}
871
872#[must_use]
885pub fn load_custom_icon_in(
886 provider: &(impl IconProvider + ?Sized),
887 set: IconSet,
888 icon_theme: Option<&str>,
889 color: Option<Rgba>,
890 size: Option<u32>,
891) -> Option<IconData> {
892 load_provider_icon(provider, set, icon_theme, color, size)
893}
894
895pub(crate) fn load_icon_in<'a>(
900 id: IconId<'a>,
901 set: IconSet,
902 theme: Option<&'a str>,
903 color: Option<Rgba>,
904 size: Option<u32>,
905) -> Option<IconData> {
906 match id {
907 IconId::Custom(provider) => load_provider_icon(provider, set, theme, color, size),
908 id => load_set_icon(id, set, theme, color, size),
909 }
910}
911
912fn load_provider_icon(
915 provider: &(impl IconProvider + ?Sized),
916 set: IconSet,
917 theme: Option<&str>,
918 color: Option<Rgba>,
919 size: Option<u32>,
920) -> Option<IconData> {
921 if let Some(name) = provider.icon_name(set)
922 && let Some(data) = load_set_icon(IconId::Name(name), set, theme, color, size)
923 {
924 return Some(data);
925 }
926 provider
927 .icon_svg(set)
928 .map(|svg| colorize_svg_data(IconData::Svg(svg), color))
929}
930
931fn load_set_icon<'a>(
935 id: IconId<'a>,
936 set: IconSet,
937 theme: Option<&'a str>,
938 color: Option<Rgba>,
939 size: Option<u32>,
940) -> Option<IconData> {
941 match set {
942 IconSet::Freedesktop => {
943 let loader = FreedesktopLoader::new(id).color_opt(color);
944 let loader = match size {
945 Some(size) => loader.size(size),
946 None => loader,
947 };
948 match theme {
949 Some(theme) => loader.theme(theme),
950 None => loader,
951 }
952 .load()
953 .map(|data| fill_freedesktop_svg_data(data, color))
954 }
955 IconSet::SfSymbols => {
956 let loader = SfSymbolsLoader::new(id).color_opt(color);
957 match size {
958 Some(size) => loader.size(size),
959 None => loader,
960 }
961 .load()
962 }
963 IconSet::SegoeFluent => {
964 let loader = SegoeFluentLoader::new(id).color_opt(color);
965 match size {
966 Some(size) => loader.size(size),
967 None => loader,
968 }
969 .load()
970 }
971 IconSet::Material => MaterialLoader::new(id)
972 .load()
973 .map(|data| colorize_svg_data(data, color)),
974 IconSet::Lucide => LucideLoader::new(id)
975 .load()
976 .map(|data| colorize_svg_data(data, color)),
977 }
978}
979
980fn colorize_svg_data(data: IconData, color: Option<Rgba>) -> IconData {
983 match (data, color) {
984 (IconData::Svg(svg), Some(color)) => {
985 IconData::Svg(Cow::Owned(colorize_monochrome_svg(&svg, color)))
986 }
987 (data, _) => data,
988 }
989}
990
991fn fill_freedesktop_svg_data(data: IconData, color: Option<Rgba>) -> IconData {
997 match (data, color) {
998 (IconData::Svg(svg), Some(color)) => {
999 let filled = match fill_current_color(&svg, color) {
1000 Cow::Owned(filled) => Some(filled),
1001 Cow::Borrowed(_) => None,
1002 };
1003 IconData::Svg(filled.map_or(svg, Cow::Owned))
1004 }
1005 (data, _) => data,
1006 }
1007}
1008
1009#[must_use]
1031pub fn colorize_monochrome_svg(svg: &[u8], color: Rgba) -> Vec<u8> {
1032 let hex = format!("#{:02x}{:02x}{:02x}", color.r, color.g, color.b);
1033
1034 let Ok(svg_str) = std::str::from_utf8(svg) else {
1035 return svg.to_vec();
1036 };
1037
1038 let replaced = if svg_str.contains("currentColor") {
1040 svg_str.replace("currentColor", &hex)
1041 } else {
1042 svg_str.to_owned()
1043 };
1044
1045 let fill_hex = format!("fill=\"{hex}\"");
1047 let replaced = replaced
1048 .replace("fill=\"black\"", &fill_hex)
1049 .replace("fill=\"#000000\"", &fill_hex)
1050 .replace("fill=\"#000\"", &fill_hex);
1051 let stroke_hex = format!("stroke=\"{hex}\"");
1052 let replaced = replaced
1053 .replace("stroke=\"black\"", &stroke_hex)
1054 .replace("stroke=\"#000000\"", &stroke_hex)
1055 .replace("stroke=\"#000\"", &stroke_hex);
1056
1057 if replaced != svg_str {
1058 return replaced.into_bytes();
1059 }
1060
1061 if let Some(pos) = svg_str.find("<svg")
1064 && let Some(tail) = svg_str.get(pos..)
1065 && let Some(close) = tail.find('>')
1066 {
1067 let tag_end = pos.saturating_add(close);
1068 if let Some(tag) = svg_str.get(pos..tag_end)
1069 && !tag.contains("fill=")
1070 {
1071 let is_self_closing = tag_end > 0
1073 && svg_str
1074 .as_bytes()
1075 .get(tag_end.saturating_sub(1))
1076 .is_some_and(|&b| b == b'/');
1077 let inject_pos = if is_self_closing {
1078 tag_end.saturating_sub(1)
1079 } else {
1080 tag_end
1081 };
1082 if let Some(before) = svg_str.get(..inject_pos)
1083 && let Some(after) = svg_str.get(inject_pos..)
1084 {
1085 let mut result = String::with_capacity(svg_str.len().saturating_add(20));
1086 result.push_str(before);
1087 result.push_str(&format!(" fill=\"{hex}\""));
1088 result.push_str(after);
1089 return result.into_bytes();
1090 }
1091 }
1092 }
1093
1094 svg.to_vec()
1096}
1097
1098#[must_use]
1134pub fn fill_current_color(svg: &[u8], color: Rgba) -> Cow<'_, [u8]> {
1135 match std::str::from_utf8(svg) {
1136 Ok(text) if text.contains("currentColor") && !sets_color(text) => Cow::Owned(
1137 text.replace(
1138 "currentColor",
1139 &format!("#{:02x}{:02x}{:02x}", color.r, color.g, color.b),
1140 )
1141 .into_bytes(),
1142 ),
1143 _ => Cow::Borrowed(svg),
1144 }
1145}
1146
1147fn sets_color(svg: &str) -> bool {
1155 let bytes = svg.as_bytes();
1156 svg.match_indices("color").any(|(at, _)| {
1157 let preceded = at
1158 .checked_sub(1)
1159 .and_then(|i| bytes.get(i))
1160 .is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_');
1161 if preceded {
1162 return false;
1163 }
1164 at.checked_add("color".len())
1165 .and_then(|i| bytes.get(i..))
1166 .and_then(|rest| rest.iter().find(|b| !b.is_ascii_whitespace()))
1167 .is_some_and(|b| *b == b':' || *b == b'=')
1168 })
1169}
1170
1171#[cfg(target_os = "linux")]
1195pub(crate) fn icon_base_dirs() -> &'static [std::path::PathBuf] {
1196 static DIRS: std::sync::OnceLock<Vec<std::path::PathBuf>> = std::sync::OnceLock::new();
1197 DIRS.get_or_init(|| {
1198 icon_base_dirs_in(
1199 std::env::home_dir().as_deref(),
1200 std::env::var_os("XDG_DATA_HOME").as_deref(),
1201 std::env::var_os("XDG_DATA_DIRS").as_deref(),
1202 )
1203 })
1204}
1205
1206#[cfg(target_os = "linux")]
1215pub(crate) fn icon_base_dirs_in(
1216 home: Option<&std::path::Path>,
1217 data_home: Option<&std::ffi::OsStr>,
1218 data_dirs: Option<&std::ffi::OsStr>,
1219) -> Vec<std::path::PathBuf> {
1220 use std::path::PathBuf;
1221
1222 let Some(home) = home else {
1223 return Vec::new();
1224 };
1225 let mut dirs: Vec<PathBuf> = std::iter::once(home.join(".icons"))
1226 .chain(
1227 xdg_data_home(data_home, Some(home))
1228 .into_iter()
1229 .chain(xdg_data_dirs(data_dirs))
1230 .map(|dir| dir.join("icons")),
1231 )
1232 .collect();
1233 dirs.retain(|dir| dir.exists());
1234 dirs
1235}
1236
1237#[cfg(target_os = "linux")]
1241pub(crate) fn xdg_data_dirs(var: Option<&std::ffi::OsStr>) -> Vec<std::path::PathBuf> {
1242 use std::path::PathBuf;
1243
1244 var.map(|dirs| {
1245 std::env::split_paths(dirs)
1246 .filter(|dir| dir.is_absolute())
1247 .collect::<Vec<_>>()
1248 })
1249 .filter(|dirs| !dirs.is_empty())
1250 .unwrap_or_else(|| {
1251 vec![
1252 PathBuf::from("/usr/local/share"),
1253 PathBuf::from("/usr/share"),
1254 ]
1255 })
1256}
1257
1258#[cfg(target_os = "linux")]
1263pub(crate) fn xdg_data_home(
1264 var: Option<&std::ffi::OsStr>,
1265 home: Option<&std::path::Path>,
1266) -> Option<std::path::PathBuf> {
1267 var.map(std::path::PathBuf::from)
1268 .filter(|dir| dir.is_absolute())
1269 .or_else(|| home.map(|home| home.join(".local/share")))
1270}
1271
1272#[cfg(target_os = "linux")]
1275pub(crate) fn is_theme_name(name: &str) -> bool {
1276 use std::path::{Component, Path};
1277
1278 let mut components = Path::new(name).components();
1279 matches!(
1280 (components.next(), components.next()),
1281 (Some(Component::Normal(_)), None)
1282 )
1283}
1284
1285#[cfg(target_os = "linux")]
1290pub(crate) fn theme_index(theme: &str, bases: &[std::path::PathBuf]) -> Option<String> {
1291 if !is_theme_name(theme) {
1292 return None;
1293 }
1294 bases
1295 .iter()
1296 .find_map(|base| std::fs::read_to_string(base.join(theme).join("index.theme")).ok())
1297}
1298
1299#[cfg(target_os = "linux")]
1304pub(crate) fn has_theme_index(theme: &str, bases: &[std::path::PathBuf]) -> bool {
1305 theme_index(theme, bases)
1306 .is_some_and(|index| ini_value(&index, "Icon Theme", "Directories").is_some())
1307}
1308
1309#[cfg(target_os = "linux")]
1312fn installed_themes_in(bases: &[std::path::PathBuf]) -> std::collections::BTreeSet<String> {
1313 bases
1314 .iter()
1315 .filter_map(|base| std::fs::read_dir(base).ok())
1316 .flatten()
1317 .filter_map(Result::ok)
1318 .filter_map(|entry| entry.file_name().into_string().ok())
1319 .filter(|name| has_theme_index(name, bases))
1320 .collect()
1321}
1322
1323#[cfg(target_os = "linux")]
1334pub(crate) fn installed_themes() -> &'static std::collections::BTreeSet<String> {
1335 static THEMES: std::sync::OnceLock<std::collections::BTreeSet<String>> =
1336 std::sync::OnceLock::new();
1337 THEMES.get_or_init(|| installed_themes_in(icon_base_dirs()))
1338}
1339
1340#[cfg(target_os = "linux")]
1343pub(crate) fn ini_value<'a>(content: &'a str, section: &str, key: &str) -> Option<&'a str> {
1344 let mut in_section = false;
1345 for line in content.lines().map(str::trim) {
1346 if let Some(group) = line.strip_prefix('[') {
1347 in_section = group.strip_suffix(']') == Some(section);
1348 continue;
1349 }
1350 if in_section
1351 && let Some((name, value)) = line.split_once('=')
1352 && name.trim() == key
1353 && !value.trim().is_empty()
1354 {
1355 return Some(value.trim());
1356 }
1357 }
1358 None
1359}
1360
1361#[must_use]
1374pub fn is_freedesktop_theme_available(theme: &str) -> bool {
1375 #[cfg(target_os = "linux")]
1376 {
1377 installed_themes().contains(theme)
1378 }
1379 #[cfg(not(target_os = "linux"))]
1380 {
1381 let _ = theme;
1382 false
1383 }
1384}
1385
1386#[derive(Debug, Clone, PartialEq, Eq)]
1397#[non_exhaustive]
1398pub enum IconSetChoice {
1399 Default(String),
1412
1413 System,
1424
1425 Freedesktop(String),
1431
1432 Material,
1434
1435 Lucide,
1437}
1438
1439impl fmt::Display for IconSetChoice {
1440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1441 match self {
1442 Self::Default(name) => write!(f, "default ({name})"),
1443 Self::System => f.write_str(&system_choice_label(&system_icon_theme())),
1444 Self::Freedesktop(name) => write!(f, "{name}"),
1445 Self::Material => write!(f, "Material (bundled)"),
1446 Self::Lucide => write!(f, "Lucide (bundled)"),
1447 }
1448 }
1449}
1450
1451fn system_choice_label(detected: &crate::Result<String>) -> String {
1455 match detected {
1456 Ok(name) => format!("system ({name})"),
1457 Err(_) => "system (unavailable)".to_string(),
1458 }
1459}
1460
1461impl IconSetChoice {
1462 #[must_use]
1470 pub fn effective_icon_set(&self, theme_icon_set: IconSet) -> IconSet {
1471 match self {
1472 Self::Default(_) => theme_icon_set,
1473 Self::System => system_icon_set(),
1474 Self::Freedesktop(_) => IconSet::Freedesktop,
1475 Self::Material => IconSet::Material,
1476 Self::Lucide => IconSet::Lucide,
1477 }
1478 }
1479
1480 #[must_use]
1492 pub fn freedesktop_theme(&self) -> Option<&str> {
1493 match self {
1494 Self::Default(name) | Self::Freedesktop(name) => Some(name),
1495 Self::System | Self::Material | Self::Lucide => None,
1496 }
1497 }
1498
1499 #[must_use]
1504 pub fn follows_preset(&self) -> bool {
1505 matches!(self, Self::Default(_))
1506 }
1507}
1508
1509#[must_use]
1523pub fn default_icon_choice(icon_set: IconSet, icon_theme: Option<&str>) -> IconSetChoice {
1524 let Some(theme) = icon_theme else {
1525 return IconSetChoice::System;
1526 };
1527 let available = match icon_set {
1532 IconSet::Material | IconSet::Lucide => true,
1533 IconSet::Freedesktop => is_freedesktop_theme_available(theme),
1534 IconSet::SfSymbols => cfg!(all(target_os = "macos", feature = "system-icons")),
1535 IconSet::SegoeFluent => cfg!(all(target_os = "windows", feature = "system-icons")),
1536 };
1537 if available {
1538 IconSetChoice::Default(theme.to_string())
1539 } else {
1540 IconSetChoice::System
1541 }
1542}
1543
1544#[must_use]
1564pub fn list_freedesktop_themes() -> Vec<String> {
1565 #[cfg(target_os = "linux")]
1566 {
1567 installed_themes()
1568 .iter()
1569 .filter(|theme| *theme != "hicolor")
1570 .cloned()
1571 .collect()
1572 }
1573 #[cfg(not(target_os = "linux"))]
1574 {
1575 Vec::new()
1576 }
1577}
1578
1579#[cfg(test)]
1584#[allow(clippy::unwrap_used, clippy::expect_used)]
1585mod load_icon_tests {
1586 use super::*;
1587
1588 #[cfg(all(target_os = "linux", feature = "system-icons"))]
1589 fn undetected() -> crate::Result<String> {
1590 Err(crate::Error::PlatformUnsupported {
1591 platform: "the test's failing detection",
1592 })
1593 }
1594
1595 #[test]
1598 #[cfg(all(target_os = "linux", feature = "system-icons"))]
1599 fn freedesktop_loader_without_a_detected_theme_loads_nothing() {
1600 let custom: &dyn IconProvider = &IconRole::ActionCopy;
1601 for id in [
1602 IconId::Role(IconRole::ActionCopy),
1603 IconId::Name("edit-copy"),
1604 IconId::Custom(custom),
1605 ] {
1606 assert!(
1607 FreedesktopLoader::new(id).load_with(undetected).is_none(),
1608 "an icon loaded though no icon theme was detected"
1609 );
1610 }
1611 }
1612
1613 #[test]
1617 #[cfg(all(target_os = "linux", feature = "system-icons"))]
1618 fn freedesktop_loader_without_a_detected_theme_gives_a_providers_own_svg() {
1619 #[derive(Debug)]
1620 struct AppIcon;
1621 impl IconProvider for AppIcon {
1622 fn icon_name(&self, _set: IconSet) -> Option<&str> {
1623 Some("edit-copy")
1624 }
1625 fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>> {
1626 (set == IconSet::Freedesktop).then_some(Cow::Borrowed(b"<svg>app</svg>"))
1627 }
1628 }
1629
1630 let provider: &dyn IconProvider = &AppIcon;
1631 assert_eq!(
1632 FreedesktopLoader::new(provider).load_with(undetected),
1633 Some(IconData::Svg(Cow::Borrowed(b"<svg>app</svg>"))),
1634 "the provider's own SVG did not load without a detected icon theme"
1635 );
1636 }
1637
1638 #[test]
1641 #[cfg(feature = "material-icons")]
1642 fn a_provider_is_passed_to_a_loader_by_reference() {
1643 #[derive(Debug)]
1644 struct AppIcon;
1645 impl IconProvider for AppIcon {
1646 fn icon_name(&self, _set: IconSet) -> Option<&str> {
1647 None
1648 }
1649 fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>> {
1650 (set == IconSet::Material).then_some(Cow::Borrowed(b"<svg>app</svg>"))
1651 }
1652 }
1653
1654 assert_eq!(
1655 MaterialLoader::new(&AppIcon).load(),
1656 Some(IconData::Svg(Cow::Borrowed(b"<svg>app</svg>"))),
1657 "a provider passed by reference did not load its own SVG"
1658 );
1659 }
1660
1661 #[test]
1663 #[cfg(all(target_os = "linux", feature = "system-icons"))]
1664 fn freedesktop_loader_with_a_theme_does_not_detect() {
1665 let runs = std::cell::Cell::new(0);
1666 let _ = FreedesktopLoader::new("edit-copy")
1667 .theme("Adwaita")
1668 .load_with(|| {
1669 runs.set(runs.get() + 1);
1670 undetected()
1671 });
1672 assert_eq!(runs.get(), 0, "an explicit theme ran the detection");
1673 }
1674
1675 #[test]
1676 #[cfg(all(target_os = "linux", feature = "system-icons"))]
1677 fn freedesktop_loader_theme_override_honored_for_name_lookup() {
1678 let result = FreedesktopLoader::new("format-text-rich")
1684 .theme("Adwaita")
1685 .size(24)
1686 .load();
1687 assert!(
1688 result.is_some(),
1689 "theme('Adwaita') must resolve 'format-text-rich' in Adwaita, regardless of system theme"
1690 );
1691 }
1692
1693 #[test]
1694 #[cfg(feature = "material-icons")]
1695 fn load_icon_material_returns_svg() {
1696 let result = MaterialLoader::new(IconRole::ActionCopy).load();
1697 assert!(result.is_some(), "material ActionCopy should return Some");
1698 match result.unwrap() {
1699 IconData::Svg(ref cow) => {
1700 let s = String::from_utf8_lossy(cow);
1701 assert!(s.contains("<svg"), "should contain SVG data");
1702 }
1703 _ => panic!("expected IconData::Svg for bundled material icon"),
1704 }
1705 }
1706
1707 #[test]
1708 #[cfg(feature = "lucide-icons")]
1709 fn load_icon_lucide_returns_svg() {
1710 let result = LucideLoader::new(IconRole::ActionCopy).load();
1711 assert!(result.is_some(), "lucide ActionCopy should return Some");
1712 match result.unwrap() {
1713 IconData::Svg(ref cow) => {
1714 let s = String::from_utf8_lossy(cow);
1715 assert!(s.contains("<svg"), "should contain SVG data");
1716 }
1717 _ => panic!("expected IconData::Svg for bundled lucide icon"),
1718 }
1719 }
1720
1721 #[test]
1727 #[cfg(all(
1728 target_os = "linux",
1729 feature = "system-icons",
1730 feature = "material-icons"
1731 ))]
1732 fn load_icon_unknown_theme_no_cross_set_fallback() -> std::io::Result<()> {
1733 const NAME: &str = "icons::load_icon_tests::load_icon_unknown_theme_no_cross_set_fallback";
1734 const DIALOG_ERROR: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><circle fill="#da4453" cx="8" cy="8" r="7"/></svg>"##;
1735 if native_theme_test_fixtures::in_child() {
1736 assert_eq!(
1737 FreedesktopLoader::new(IconRole::DialogError).load(),
1738 Some(IconData::Svg(Cow::Borrowed(DIALOG_ERROR.as_bytes()))),
1739 "the system's theme is looked up"
1740 );
1741 assert!(MaterialLoader::new(IconRole::ActionCopy).load().is_some());
1742 assert_eq!(
1743 FreedesktopLoader::new(IconRole::ActionCopy).load(),
1744 None,
1745 "the system's theme lacks edit-copy"
1746 );
1747 assert_eq!(
1748 FreedesktopLoader::new(IconRole::ActionCopy)
1749 .theme("native-theme-no-such-theme")
1750 .load(),
1751 None,
1752 "the theme given is not installed"
1753 );
1754 return Ok(());
1755 }
1756 let child = native_theme_test_fixtures::Child::kde("lacking");
1757 native_theme_test_fixtures::run(NAME, child, |icons| {
1758 native_theme_test_fixtures::write_scalable_theme(
1759 icons,
1760 "lacking",
1761 &[("dialog-error", DIALOG_ERROR)],
1762 )
1763 })
1764 }
1765
1766 #[test]
1767 #[cfg(feature = "material-icons")]
1768 fn load_icon_all_roles_material() {
1769 let mut some_count = 0;
1771 for role in IconRole::ALL.iter().copied() {
1772 if MaterialLoader::new(role).load().is_some() {
1773 some_count += 1;
1774 }
1775 }
1776 assert_eq!(
1778 some_count, 42,
1779 "Material should cover all 42 roles via bundled SVGs"
1780 );
1781 }
1782
1783 #[test]
1784 #[cfg(feature = "lucide-icons")]
1785 fn load_icon_all_roles_lucide() {
1786 let mut some_count = 0;
1787 for role in IconRole::ALL.iter().copied() {
1788 if LucideLoader::new(role).load().is_some() {
1789 some_count += 1;
1790 }
1791 }
1792 assert_eq!(
1794 some_count, 42,
1795 "Lucide should cover all 42 roles via bundled SVGs"
1796 );
1797 }
1798
1799 #[test]
1800 fn freedesktop_loader_stores_the_size_and_colour() {
1801 let loader = FreedesktopLoader::new("edit-copy");
1802 assert_eq!((loader.size, loader.fg_color), (24, None));
1803 let loader = loader.size(48).color(Rgba::new(10, 20, 30, 40));
1804 assert_eq!(loader.size, 48);
1805 assert_eq!(loader.fg_color, Some([10, 20, 30]), "the alpha is ignored");
1806 assert_eq!(loader.color_opt(None).fg_color, None);
1807 }
1808
1809 #[test]
1811 fn the_system_loaders_clamp_the_size() {
1812 for (size, clamped) in [
1813 (0, 1),
1814 (48, 48),
1815 (MAX_ICON_SIZE, MAX_ICON_SIZE),
1816 (MAX_ICON_SIZE + 1, MAX_ICON_SIZE),
1817 (70_000, MAX_ICON_SIZE),
1818 (u32::MAX, MAX_ICON_SIZE),
1819 ] {
1820 assert_eq!(
1821 FreedesktopLoader::new("edit-copy").size(size).size,
1822 clamped,
1823 "freedesktop {size}"
1824 );
1825 assert_eq!(
1826 SfSymbolsLoader::new(IconRole::ActionCopy).size(size).size,
1827 Some(clamped),
1828 "SF Symbols {size}"
1829 );
1830 assert_eq!(
1831 SegoeFluentLoader::new(IconRole::ActionCopy).size(size).size,
1832 Some(clamped),
1833 "Segoe {size}"
1834 );
1835 }
1836 }
1837
1838 #[test]
1839 fn raster_size_in_bound_is_the_decode_bound() {
1840 assert!(!raster_size_in_bound(0));
1841 assert!(raster_size_in_bound(1));
1842 assert!(raster_size_in_bound(4096));
1843 assert!(!raster_size_in_bound(4097));
1844 assert!(!raster_size_in_bound(u32::MAX));
1845 }
1846
1847 #[test]
1848 fn raster_bytes_in_bound_is_the_decode_bound() {
1849 assert_eq!(raster_bytes_in_bound(0, 16), None);
1850 assert_eq!(raster_bytes_in_bound(16, 0), None);
1851 assert_eq!(raster_bytes_in_bound(3, 2), Some(24));
1852 assert_eq!(
1853 raster_bytes_in_bound(8192, 2048),
1854 Some(MAX_ICON_DECODE_BYTES)
1855 );
1856 assert_eq!(raster_bytes_in_bound(8192, 2049), None);
1857 assert_eq!(raster_bytes_in_bound(u32::MAX, u32::MAX), None);
1858 }
1859
1860 #[test]
1861 fn sf_symbols_loader_stores_the_colour() {
1862 let loader = SfSymbolsLoader::new(IconRole::ActionCopy).color(Rgba::new(10, 20, 30, 40));
1863 assert_eq!(loader.fg_color, Some([10, 20, 30]), "the alpha is ignored");
1864 let loader = loader.color_opt(None);
1865 assert_eq!(loader.fg_color, None);
1866 let loader = loader.color_opt(Some(Rgba::rgb(40, 50, 60)));
1867 assert_eq!(loader.fg_color, Some([40, 50, 60]));
1868 assert_eq!(SfSymbolsLoader::new(IconRole::ActionCopy).fg_color, None);
1869 }
1870
1871 #[test]
1872 fn sf_symbols_loader_stores_the_size() {
1873 assert_eq!(SfSymbolsLoader::new(IconRole::ActionCopy).size, None);
1874 assert_eq!(
1875 SfSymbolsLoader::new(IconRole::ActionCopy).size(48).size,
1876 Some(48)
1877 );
1878 }
1879
1880 #[test]
1881 fn segoe_fluent_loader_stores_the_colour() {
1882 let loader = SegoeFluentLoader::new(IconRole::ActionCopy).color(Rgba::new(10, 20, 30, 40));
1883 assert_eq!(loader.fg_color, Some([10, 20, 30]), "the alpha is ignored");
1884 let loader = loader.color_opt(None);
1885 assert_eq!(loader.fg_color, None);
1886 let loader = loader.color_opt(Some(Rgba::rgb(40, 50, 60)));
1887 assert_eq!(loader.fg_color, Some([40, 50, 60]));
1888 assert_eq!(SegoeFluentLoader::new(IconRole::ActionCopy).fg_color, None);
1889 }
1890
1891 #[test]
1892 fn segoe_fluent_loader_stores_the_size() {
1893 assert_eq!(SegoeFluentLoader::new(IconRole::ActionCopy).size, None);
1894 assert_eq!(
1895 SegoeFluentLoader::new(IconRole::ActionCopy).size(48).size,
1896 Some(48)
1897 );
1898 }
1899
1900 #[test]
1903 fn an_sf_symbol_loads_only_on_macos_with_system_icons() {
1904 let result = SfSymbolsLoader::new(IconRole::ActionCopy).load();
1905 assert_eq!(
1906 result.is_some(),
1907 cfg!(all(target_os = "macos", feature = "system-icons"))
1908 );
1909 }
1910
1911 #[test]
1912 #[cfg(feature = "material-icons")]
1913 fn bundled_icon_load_produces_cow_borrowed() {
1914 let result = MaterialLoader::new(IconRole::ActionCopy).load();
1915 assert!(
1916 matches!(result, Some(IconData::Svg(Cow::Borrowed(_)))),
1917 "bundled icon should produce Some(IconData::Svg(Cow::Borrowed(_)))"
1918 );
1919 }
1920}
1921
1922#[cfg(test)]
1923#[allow(clippy::unwrap_used, clippy::expect_used)]
1924mod load_system_icon_by_name_tests {
1925 #[test]
1926 #[cfg(feature = "material-icons")]
1927 fn system_icon_by_name_material() {
1928 let result = super::MaterialLoader::new("content_copy").load();
1929 assert!(
1930 result.is_some(),
1931 "content_copy should be found in Material set"
1932 );
1933 assert!(matches!(result.unwrap(), super::IconData::Svg(_)));
1934 }
1935
1936 #[test]
1937 #[cfg(feature = "lucide-icons")]
1938 fn system_icon_by_name_lucide() {
1939 let result = super::LucideLoader::new("copy").load();
1940 assert!(result.is_some(), "copy should be found in Lucide set");
1941 assert!(matches!(result.unwrap(), super::IconData::Svg(_)));
1942 }
1943
1944 #[test]
1945 #[cfg(feature = "material-icons")]
1946 fn system_icon_by_name_unknown_returns_none() {
1947 let result = super::MaterialLoader::new("nonexistent_xyz").load();
1948 assert!(result.is_none(), "nonexistent name should return None");
1949 }
1950
1951 #[test]
1952 fn system_icon_by_name_sf_on_linux_returns_none() {
1953 #[cfg(not(target_os = "macos"))]
1955 {
1956 let result = super::SfSymbolsLoader::new("doc.on.doc").load();
1957 assert!(
1958 result.is_none(),
1959 "SF Symbols should return None on non-macOS"
1960 );
1961 }
1962 }
1963}
1964
1965#[cfg(test)]
1966#[allow(clippy::unwrap_used, clippy::expect_used)]
1967mod load_custom_icon_tests {
1968 use super::*;
1969
1970 #[test]
1971 #[cfg(feature = "material-icons")]
1972 fn custom_icon_with_icon_role_material() {
1973 let provider: &dyn IconProvider = &IconRole::ActionCopy;
1974 let result = MaterialLoader::new(provider).load();
1975 assert!(
1976 result.is_some(),
1977 "IconRole::ActionCopy should load via material"
1978 );
1979 }
1980
1981 #[test]
1982 #[cfg(feature = "lucide-icons")]
1983 fn custom_icon_with_icon_role_lucide() {
1984 let provider: &dyn IconProvider = &IconRole::ActionCopy;
1985 let result = LucideLoader::new(provider).load();
1986 assert!(
1987 result.is_some(),
1988 "IconRole::ActionCopy should load via lucide"
1989 );
1990 }
1991
1992 #[test]
1993 fn custom_icon_no_cross_set_fallback() {
1994 #[derive(Debug)]
1996 struct NullProvider;
1997 impl IconProvider for NullProvider {
1998 fn icon_name(&self, _set: IconSet) -> Option<&str> {
1999 None
2000 }
2001 fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
2002 None
2003 }
2004 }
2005
2006 let provider: &dyn IconProvider = &NullProvider;
2007 let result = MaterialLoader::new(provider).load();
2008 assert!(
2009 result.is_none(),
2010 "NullProvider should return None (no cross-set fallback)"
2011 );
2012 }
2013
2014 #[test]
2017 fn a_custom_freedesktop_icon_does_not_take_the_providers_material_icon() {
2018 #[derive(Debug)]
2019 struct MaterialOnly;
2020 impl IconProvider for MaterialOnly {
2021 fn icon_name(&self, set: IconSet) -> Option<&str> {
2022 (set == IconSet::Material).then_some("content_copy")
2023 }
2024 fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>> {
2025 (set == IconSet::Material).then_some(Cow::Borrowed(
2026 br#"<svg xmlns="http://www.w3.org/2000/svg"/>"#,
2027 ))
2028 }
2029 }
2030
2031 let provider: &dyn IconProvider = &MaterialOnly;
2032 #[cfg(feature = "material-icons")]
2033 assert!(MaterialLoader::new(provider).load().is_some());
2034 assert_eq!(FreedesktopLoader::new(provider).load(), None);
2035 }
2036
2037 #[test]
2038 #[cfg(feature = "material-icons")]
2039 fn custom_icon_via_dyn_dispatch() {
2040 let boxed: Box<dyn IconProvider> = Box::new(IconRole::ActionCopy);
2041 let provider: &dyn IconProvider = &*boxed;
2042 let result = MaterialLoader::new(provider).load();
2043 assert!(
2044 result.is_some(),
2045 "dyn dispatch through Box<dyn IconProvider> should work"
2046 );
2047 }
2048
2049 #[test]
2050 #[cfg(feature = "material-icons")]
2051 fn custom_icon_bundled_svg_fallback() {
2052 #[derive(Debug)]
2054 struct SvgOnlyProvider;
2055 impl IconProvider for SvgOnlyProvider {
2056 fn icon_name(&self, _set: IconSet) -> Option<&str> {
2057 None
2058 }
2059 fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
2060 Some(Cow::Borrowed(b"<svg>test</svg>"))
2061 }
2062 }
2063
2064 let provider: &dyn IconProvider = &SvgOnlyProvider;
2065 let result = MaterialLoader::new(provider).load();
2066 assert!(
2067 result.is_some(),
2068 "provider with icon_svg should return Some"
2069 );
2070 match result.unwrap() {
2071 IconData::Svg(ref cow) => {
2072 assert_eq!(cow.as_ref(), b"<svg>test</svg>");
2073 }
2074 _ => panic!("expected IconData::Svg"),
2075 }
2076 }
2077}
2078
2079#[cfg(test)]
2080#[allow(clippy::unwrap_used, clippy::expect_used)]
2081mod runtime_set_icon_tests {
2082 use super::*;
2083
2084 const COLOR: Rgba = Rgba::rgb(0x12, 0x34, 0x56);
2086
2087 fn svg_text(data: IconData) -> String {
2088 match data {
2089 IconData::Svg(svg) => String::from_utf8(svg.into_owned()).unwrap(),
2090 other => panic!("expected IconData::Svg, got {other:?}"),
2091 }
2092 }
2093
2094 #[derive(Debug)]
2095 struct SvgOnlyProvider;
2096 impl IconProvider for SvgOnlyProvider {
2097 fn icon_name(&self, _set: IconSet) -> Option<&str> {
2098 None
2099 }
2100 fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
2101 Some(Cow::Borrowed(
2102 b"<svg viewBox=\"0 0 24 24\"><path d=\"M0 0\"/></svg>",
2103 ))
2104 }
2105 }
2106
2107 #[test]
2108 #[cfg(feature = "material-icons")]
2109 fn material_role_comes_back_in_the_colour() {
2110 let svg = svg_text(
2111 load_custom_icon(&IconRole::ActionCopy, IconSet::Material, Some(COLOR), None).unwrap(),
2112 );
2113 assert!(
2114 svg.contains("#123456"),
2115 "colour written into the bytes: {svg}"
2116 );
2117 }
2118
2119 #[test]
2120 #[cfg(feature = "lucide-icons")]
2121 fn lucide_role_comes_back_in_the_colour() {
2122 let svg = svg_text(
2123 load_custom_icon(&IconRole::ActionCopy, IconSet::Lucide, Some(COLOR), None).unwrap(),
2124 );
2125 assert!(
2126 svg.contains("#123456"),
2127 "colour written into the bytes: {svg}"
2128 );
2129 assert!(!svg.contains("currentColor"), "{svg}");
2130 }
2131
2132 #[test]
2133 #[cfg(feature = "material-icons")]
2134 fn no_colour_leaves_the_bundled_bytes() {
2135 let loaded =
2136 load_custom_icon(&IconRole::ActionCopy, IconSet::Material, None, None).unwrap();
2137 assert_eq!(
2138 loaded,
2139 MaterialLoader::new(IconRole::ActionCopy).load().unwrap()
2140 );
2141 }
2142
2143 #[test]
2144 fn provider_svg_comes_back_in_the_colour() {
2145 for set in [
2146 IconSet::Freedesktop,
2147 IconSet::SfSymbols,
2148 IconSet::SegoeFluent,
2149 IconSet::Material,
2150 IconSet::Lucide,
2151 ] {
2152 let svg = svg_text(load_custom_icon(&SvgOnlyProvider, set, Some(COLOR), None).unwrap());
2153 assert!(svg.contains("fill=\"#123456\""), "{set:?}: {svg}");
2154 }
2155 }
2156
2157 #[derive(Debug)]
2160 struct EditCopy(Option<&'static [u8]>);
2161 impl IconProvider for EditCopy {
2162 fn icon_name(&self, _set: IconSet) -> Option<&str> {
2163 Some("edit-copy")
2164 }
2165 fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
2166 self.0.map(Cow::Borrowed)
2167 }
2168 }
2169
2170 #[test]
2174 fn a_custom_icon_missing_from_the_icon_theme_given_is_the_providers_own() {
2175 let missing = Some("native-theme-no-such-theme");
2176 assert!(
2177 load_custom_icon_in(&EditCopy(None), IconSet::Freedesktop, missing, None, None)
2178 .is_none()
2179 );
2180 let own = b"<svg viewBox=\"0 0 24 24\"><path d=\"M0 0\"/></svg>";
2181 assert_eq!(
2182 load_custom_icon_in(
2183 &EditCopy(Some(own)),
2184 IconSet::Freedesktop,
2185 missing,
2186 None,
2187 None
2188 ),
2189 Some(IconData::Svg(Cow::Borrowed(own)))
2190 );
2191 }
2192
2193 #[cfg(all(target_os = "linux", feature = "system-icons"))]
2199 #[test]
2200 fn a_custom_icon_is_loaded_at_a_clamped_size() -> std::io::Result<()> {
2201 const NAME: &str =
2202 "icons::runtime_set_icon_tests::a_custom_icon_is_loaded_at_a_clamped_size";
2203 const ZERO: &str = r##"<svg xmlns="http://www.w3.org/2000/svg"/>"##;
2204 const SMALL: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"/>"##;
2205 const AT_512: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"/>"##;
2206 const AT_1024: &str =
2207 r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"/>"##;
2208 if native_theme_test_fixtures::in_child() {
2209 let svg = |svg: &'static str| Some(IconData::Svg(Cow::Borrowed(svg.as_bytes())));
2210 let load = |size| {
2211 load_custom_icon_in(
2212 &EditCopy(None),
2213 IconSet::Freedesktop,
2214 None,
2215 None,
2216 Some(size),
2217 )
2218 };
2219 assert_eq!(load(99_999), svg(AT_512), "asked for 99999");
2220 assert_eq!(load(MAX_ICON_SIZE + 1), svg(AT_512), "asked for 513");
2221 assert_eq!(load(1024), svg(AT_512), "asked for 1024");
2222 assert_eq!(load(0), svg(SMALL), "asked for 0");
2223 return Ok(());
2224 }
2225 let child = native_theme_test_fixtures::Child::kde("sized");
2226 native_theme_test_fixtures::run(NAME, child, |icons| {
2227 native_theme_test_fixtures::write_fixed_theme(
2228 icons,
2229 "sized",
2230 &[
2231 (0, "edit-copy.svg", ZERO.as_bytes()),
2232 (1, "edit-copy.svg", SMALL.as_bytes()),
2233 (512, "edit-copy.svg", AT_512.as_bytes()),
2234 (1024, "edit-copy.svg", AT_1024.as_bytes()),
2235 ],
2236 )
2237 })
2238 }
2239
2240 #[cfg(all(target_os = "linux", feature = "system-icons"))]
2246 #[test]
2247 fn a_custom_icon_is_looked_up_in_the_icon_theme_given() -> std::io::Result<()> {
2248 const NAME: &str =
2249 "icons::runtime_set_icon_tests::a_custom_icon_is_looked_up_in_the_icon_theme_given";
2250 const SYSTEM: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="#3daee9" d="M2 2h12v12H2z"/></svg>"##;
2251 const CHOSEN: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="#e01b24" d="M2 2h12v12H2z"/></svg>"##;
2252 if native_theme_test_fixtures::in_child() {
2253 let svg = |svg: &'static str| Some(IconData::Svg(Cow::Borrowed(svg.as_bytes())));
2254 let load = |theme| {
2255 load_custom_icon_in(&EditCopy(None), IconSet::Freedesktop, theme, None, None)
2256 };
2257 assert_eq!(load(None), svg(SYSTEM), "the system's theme");
2258 assert_eq!(load(Some("chosen")), svg(CHOSEN));
2259 assert_eq!(
2260 load(Some("native-theme-no-such-theme")),
2261 None,
2262 "an icon the theme given lacks is not taken from the system's"
2263 );
2264 return Ok(());
2265 }
2266 let child = native_theme_test_fixtures::Child::kde("system");
2267 native_theme_test_fixtures::run(NAME, child, |icons| {
2268 native_theme_test_fixtures::write_scalable_theme(
2269 icons,
2270 "system",
2271 &[("edit-copy", SYSTEM)],
2272 )?;
2273 native_theme_test_fixtures::write_scalable_theme(
2274 icons,
2275 "chosen",
2276 &[("edit-copy", CHOSEN)],
2277 )
2278 })
2279 }
2280
2281 #[test]
2282 #[cfg(feature = "material-icons")]
2283 fn a_themeless_set_ignores_the_icon_theme() {
2284 assert_eq!(
2285 load_custom_icon_in(
2286 &IconRole::ActionCopy,
2287 IconSet::Material,
2288 Some("breeze"),
2289 Some(COLOR),
2290 None
2291 ),
2292 load_custom_icon(&IconRole::ActionCopy, IconSet::Material, Some(COLOR), None)
2293 );
2294 }
2295
2296 #[test]
2297 fn unsized_provider_is_accepted() {
2298 let provider: &dyn IconProvider = &SvgOnlyProvider;
2299 assert!(load_custom_icon(provider, IconSet::Material, None, None).is_some());
2300 }
2301
2302 #[test]
2303 #[cfg(feature = "material-icons")]
2304 fn custom_id_in_the_dispatcher_is_coloured() {
2305 let provider: &dyn IconProvider = &IconRole::ActionCopy;
2306 let svg = svg_text(
2307 load_icon_in(
2308 IconId::Custom(provider),
2309 IconSet::Material,
2310 None,
2311 Some(COLOR),
2312 None,
2313 )
2314 .unwrap(),
2315 );
2316 assert!(svg.contains("#123456"), "{svg}");
2317 }
2318
2319 #[test]
2320 fn provider_with_nothing_is_none() {
2321 #[derive(Debug)]
2322 struct NullProvider;
2323 impl IconProvider for NullProvider {
2324 fn icon_name(&self, _set: IconSet) -> Option<&str> {
2325 None
2326 }
2327 fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
2328 None
2329 }
2330 }
2331 assert!(load_custom_icon(&NullProvider, IconSet::Material, Some(COLOR), None).is_none());
2332 }
2333
2334 fn svg_of(data: IconData) -> String {
2337 match data {
2338 IconData::Svg(svg) => String::from_utf8_lossy(&svg).into_owned(),
2339 _ => String::new(),
2340 }
2341 }
2342
2343 #[test]
2347 fn a_freedesktop_svg_s_bare_current_color_is_filled_in_the_colour() {
2348 let bare = br#"<svg xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M0 0h16v16H0z"/></svg>"#;
2349 let filled = fill_freedesktop_svg_data(IconData::Svg(Cow::Borrowed(bare)), Some(COLOR));
2350 assert_eq!(
2351 svg_of(filled),
2352 r##"<svg xmlns="http://www.w3.org/2000/svg"><path fill="#123456" d="M0 0h16v16H0z"/></svg>"##
2353 );
2354 }
2355
2356 #[test]
2361 fn a_freedesktop_svg_with_its_own_colour_is_left_as_it_is() {
2362 let styled = br#"<svg xmlns="http://www.w3.org/2000/svg"><style id="current-color-scheme">.ColorScheme-Text { color:#232629; }</style><path class="ColorScheme-Text" style="fill:currentColor" d="M0 0h16v16H0z"/></svg>"#;
2363 let full_colour = br##"<svg xmlns="http://www.w3.org/2000/svg"><path fill="#3daee9" d="M0 0h16v16H0z"/><path fill="#ffffff" d="M2 2h4v4H2z"/></svg>"##;
2364 let bare = br#"<svg xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M0 0h16v16H0z"/></svg>"#;
2365 for (svg, color) in [
2366 (&styled[..], Some(COLOR)),
2367 (&full_colour[..], Some(COLOR)),
2368 (&bare[..], None),
2369 ] {
2370 let data = fill_freedesktop_svg_data(IconData::Svg(Cow::Borrowed(svg)), color);
2371 assert_eq!(svg_of(data), String::from_utf8_lossy(svg));
2372 }
2373 }
2374
2375 #[test]
2376 #[cfg(feature = "material-icons")]
2377 fn indicator_of_a_themeless_set_ignores_the_theme() {
2378 assert_eq!(
2379 load_icon_indicator(IconSet::Material, Some("breeze")),
2380 load_icon_indicator(IconSet::Material, None)
2381 );
2382 }
2383}
2384
2385#[cfg(test)]
2386#[allow(clippy::unwrap_used, clippy::expect_used)]
2387mod loading_indicator_tests {
2388 use super::*;
2389
2390 #[test]
2393 #[cfg(feature = "lucide-icons")]
2394 fn loading_indicator_lucide_returns_frames() {
2395 let anim = LucideLoader::load_indicator();
2396 assert!(anim.is_some(), "lucide should return Some");
2397 let anim = anim.unwrap();
2398 assert!(
2399 matches!(anim, AnimatedIcon::Frames(_)),
2400 "lucide should be pre-rotated Frames"
2401 );
2402 if let AnimatedIcon::Frames(data) = &anim {
2403 assert_eq!(data.frames().len(), 24);
2404 assert_eq!(data.frame_duration_ms().get(), 42);
2405 }
2406 }
2407
2408 #[test]
2411 #[cfg(all(target_os = "linux", feature = "system-icons"))]
2412 fn loading_indicator_freedesktop_depends_on_theme() {
2413 let anim = FreedesktopLoader::load_indicator(None);
2414 if let Some(anim) = anim {
2416 match anim {
2417 AnimatedIcon::Frames(data) => {
2418 assert!(
2419 !data.frames().is_empty(),
2420 "Frames variant should have at least one frame"
2421 );
2422 }
2423 AnimatedIcon::Transform(_) => {
2424 }
2426 }
2427 }
2428 }
2429
2430 #[test]
2432 fn loading_indicator_freedesktop_does_not_panic() {
2433 let _result = FreedesktopLoader::load_indicator(None);
2434 }
2435
2436 #[test]
2439 #[cfg(feature = "lucide-icons")]
2440 fn lucide_spinner_is_frames() {
2441 let anim = crate::spinners::lucide_spinner();
2442 assert!(
2443 matches!(anim, AnimatedIcon::Frames(_)),
2444 "lucide should be pre-rotated Frames"
2445 );
2446 }
2447}
2448
2449#[cfg(test)]
2452#[allow(clippy::unwrap_used, clippy::expect_used)]
2453mod icon_loader_tests {
2454 use super::*;
2455
2456 #[test]
2457 #[cfg(feature = "material-icons")]
2458 fn icon_loader_basic_role() {
2459 let icon = MaterialLoader::new(IconRole::ActionCopy).load();
2460 assert!(icon.is_some());
2461 }
2462
2463 #[test]
2464 #[cfg(feature = "material-icons")]
2465 fn icon_loader_by_name() {
2466 let icon = MaterialLoader::new("content_copy").load();
2467 assert!(icon.is_some());
2468 }
2469
2470 #[test]
2471 #[cfg(feature = "material-icons")]
2472 fn icon_loader_custom_provider() {
2473 let provider: &dyn IconProvider = &IconRole::ActionCopy;
2474 let icon = MaterialLoader::new(provider).load();
2475 assert!(icon.is_some());
2476 }
2477
2478 #[test]
2479 #[cfg(all(target_os = "linux", feature = "system-icons"))]
2480 fn freedesktop_loader_builder_chain_compiles() {
2481 let _ = FreedesktopLoader::new(IconRole::ActionSave)
2485 .size(48)
2486 .color(Rgba::rgb(0, 0, 0))
2487 .theme("Adwaita")
2488 .load();
2489 }
2490
2491 #[test]
2492 #[cfg(feature = "material-icons")]
2493 fn icon_loader_load_indicator() {
2494 let anim = MaterialLoader::load_indicator();
2495 assert!(anim.is_some());
2496 }
2497
2498 #[test]
2499 fn load_icon_free_fn_dispatches() {
2500 let role = IconRole::ActionCopy;
2501 for (set, loaded) in [
2502 (IconSet::Freedesktop, FreedesktopLoader::new(role).load()),
2503 (IconSet::SfSymbols, SfSymbolsLoader::new(role).load()),
2504 (IconSet::SegoeFluent, SegoeFluentLoader::new(role).load()),
2505 (IconSet::Material, MaterialLoader::new(role).load()),
2506 (IconSet::Lucide, LucideLoader::new(role).load()),
2507 ] {
2508 assert_eq!(load_icon(role, set), loaded, "{set}");
2509 }
2510 #[cfg(all(feature = "material-icons", feature = "lucide-icons"))]
2511 assert_ne!(
2512 load_icon(role, IconSet::Material),
2513 load_icon(role, IconSet::Lucide)
2514 );
2515 }
2516
2517 #[test]
2518 fn load_icon_indicator_free_fn_dispatches() {
2519 assert!(load_icon_indicator(IconSet::SfSymbols, None).is_none());
2521 assert!(load_icon_indicator(IconSet::SegoeFluent, None).is_none());
2522 }
2523
2524 #[test]
2525 #[cfg(not(all(target_os = "linux", feature = "system-icons")))]
2526 fn load_where_is_none_without_the_freedesktop_loader() {
2527 assert!(
2528 FreedesktopLoader::new("edit-copy")
2529 .load_where(|_| true)
2530 .is_none()
2531 );
2532 }
2533}
2534
2535#[cfg(all(test, target_os = "linux", feature = "system-icons"))]
2540#[allow(clippy::unwrap_used, clippy::expect_used)]
2541mod load_where_tests {
2542 use super::*;
2543 use native_theme_test_fixtures::{Child, in_child, run, write_scalable_theme};
2544 use std::path::Path;
2545
2546 fn svg(title: &str) -> String {
2548 format!(
2549 r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><title>{title}</title><rect width="16" height="16"/></svg>"#
2550 )
2551 }
2552
2553 fn title(icon: &IconData) -> Option<String> {
2555 let IconData::Svg(bytes) = icon else {
2556 return None;
2557 };
2558 let text = String::from_utf8_lossy(bytes);
2559 let (_, rest) = text.split_once("<title>")?;
2560 let (title, _) = rest.split_once("</title>")?;
2561 Some(title.to_string())
2562 }
2563
2564 fn write_inheriting_theme(
2567 icons: &Path,
2568 name: &str,
2569 inherits: &str,
2570 files: &[(&str, &str)],
2571 ) -> std::io::Result<()> {
2572 let dir = icons.join(name);
2573 std::fs::create_dir_all(dir.join("scalable"))?;
2574 std::fs::write(
2575 dir.join("index.theme"),
2576 format!(
2577 "[Icon Theme]\nName={name}\nInherits={inherits}\nDirectories=scalable\n\n\
2578 [scalable]\nSize=16\nType=Scalable\nMinSize=8\nMaxSize=512\n"
2579 ),
2580 )?;
2581 for (icon, svg) in files {
2582 std::fs::write(dir.join(format!("scalable/{icon}.svg")), svg)?;
2583 }
2584 Ok(())
2585 }
2586
2587 #[test]
2588 fn load_where_goes_on_by_names() -> std::io::Result<()> {
2589 const NAME: &str = "icons::load_where_tests::load_where_goes_on_by_names";
2590 if in_child() {
2591 let loader = || FreedesktopLoader::any(&["refused", "kept"]).theme("passing");
2592 let kept = loader()
2593 .load_where(|icon| title(icon).as_deref() != Some("passing/refused"))
2594 .expect("passing/kept passes");
2595 assert_eq!(title(&kept).as_deref(), Some("passing/kept"));
2596 let loaded = loader().load().expect("passing/refused is the first name");
2597 assert_eq!(title(&loaded).as_deref(), Some("passing/refused"));
2598 return Ok(());
2599 }
2600 run(NAME, Child::kde("passing"), |icons| {
2601 write_scalable_theme(
2602 icons,
2603 "passing",
2604 &[
2605 ("refused", &svg("passing/refused")),
2606 ("kept", &svg("passing/kept")),
2607 ],
2608 )
2609 })
2610 }
2611
2612 #[test]
2613 fn load_where_goes_on_by_a_name_through_the_chain() -> std::io::Result<()> {
2614 const NAME: &str =
2615 "icons::load_where_tests::load_where_goes_on_by_a_name_through_the_chain";
2616 if in_child() {
2617 let loader = || FreedesktopLoader::new("x").theme("child");
2618 let loaded = loader().load().expect("the parent's symbolic icon");
2619 assert_eq!(title(&loaded).as_deref(), Some("parent/x-symbolic"));
2620 let kept = loader()
2621 .load_where(|icon| title(icon).as_deref() != Some("parent/x-symbolic"))
2622 .expect("the child's plain icon passes");
2623 assert_eq!(title(&kept).as_deref(), Some("child/x"));
2624 return Ok(());
2625 }
2626 run(NAME, Child::kde("child"), |icons| {
2627 write_inheriting_theme(icons, "child", "parent", &[("x", &svg("child/x"))])?;
2628 write_scalable_theme(
2629 icons,
2630 "parent",
2631 &[("x-symbolic", &svg("parent/x-symbolic"))],
2632 )
2633 })
2634 }
2635
2636 #[test]
2637 fn load_where_by_a_role() -> std::io::Result<()> {
2638 const NAME: &str = "icons::load_where_tests::load_where_by_a_role";
2639 if in_child() {
2640 let loader = || FreedesktopLoader::new(IconRole::DialogError).theme("roles");
2641 let loaded = loader().load();
2642 assert_eq!(
2643 title(loaded.as_ref().expect("roles has dialog-error")).as_deref(),
2644 Some("roles/dialog-error")
2645 );
2646 assert_eq!(loader().load_where(|_| true), loaded);
2647 assert_eq!(loader().load_where(|_| false), None);
2648 return Ok(());
2649 }
2650 run(NAME, Child::kde("roles"), |icons| {
2651 write_scalable_theme(
2652 icons,
2653 "roles",
2654 &[("dialog-error", &svg("roles/dialog-error"))],
2655 )
2656 })
2657 }
2658
2659 #[test]
2660 fn load_where_by_a_provider() -> std::io::Result<()> {
2661 const NAME: &str = "icons::load_where_tests::load_where_by_a_provider";
2662 #[derive(Debug)]
2664 struct CopyProvider;
2665 impl IconProvider for CopyProvider {
2666 fn icon_name(&self, set: IconSet) -> Option<&str> {
2667 (set == IconSet::Freedesktop).then_some("edit-copy")
2668 }
2669 fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>> {
2670 (set == IconSet::Freedesktop).then(|| Cow::Owned(svg("provider").into_bytes()))
2671 }
2672 }
2673 if in_child() {
2674 let provider: &dyn IconProvider = &CopyProvider;
2675 let loader = || FreedesktopLoader::new(provider).theme("copying");
2676 let theme_s = loader()
2677 .load_where(|_| true)
2678 .expect("the theme's edit-copy");
2679 assert_eq!(title(&theme_s).as_deref(), Some("copying/edit-copy"));
2680 let own = loader()
2681 .load_where(|icon| title(icon).as_deref() != Some("copying/edit-copy"))
2682 .expect("the provider's own SVG passes");
2683 assert_eq!(title(&own).as_deref(), Some("provider"));
2684 assert_eq!(loader().load_where(|_| false), None);
2685 return Ok(());
2686 }
2687 run(NAME, Child::kde("copying"), |icons| {
2688 write_scalable_theme(
2689 icons,
2690 "copying",
2691 &[("edit-copy", &svg("copying/edit-copy"))],
2692 )
2693 })
2694 }
2695}
2696
2697#[cfg(all(test, feature = "svg-rasterize", feature = "lucide-icons"))]
2698#[allow(clippy::unwrap_used, clippy::expect_used)]
2699mod spinner_rasterize_tests {
2700 use super::*;
2701
2702 #[test]
2703 fn lucide_spinner_icon_rasterizes() {
2704 let anim = crate::spinners::lucide_spinner();
2705 if let AnimatedIcon::Frames(data) = &anim {
2706 let first = data.frames().first();
2707 if let IconData::Svg(cow) = first {
2708 let result = crate::rasterize::rasterize_svg(cow, 24);
2709 assert!(result.is_ok(), "lucide loader should rasterize");
2710 if let Ok(IconData::Rgba(rgba)) = &result {
2711 assert!(
2712 rgba.data().iter().any(|&b| b != 0),
2713 "lucide loader rasterized to empty image"
2714 );
2715 }
2716 } else {
2717 panic!("lucide spinner frame should be Svg");
2718 }
2719 } else {
2720 panic!("lucide spinner should be Frames");
2721 }
2722 }
2723}
2724
2725#[cfg(test)]
2730mod icon_set_choice_tests {
2731 use super::*;
2732
2733 #[test]
2734 fn system_choice_names_the_detected_theme() {
2735 assert_eq!(
2736 system_choice_label(&Ok("breeze-dark".to_string())),
2737 "system (breeze-dark)"
2738 );
2739 }
2740
2741 #[test]
2742 fn system_choice_shows_a_failed_detection_as_unavailable() {
2743 let label = system_choice_label(&Err(crate::Error::PlatformUnsupported {
2744 platform: "the test's failing detection",
2745 }));
2746 assert_eq!(label, "system (unavailable)");
2747 }
2748
2749 #[test]
2753 fn a_failed_detections_label_leaves_the_reason_out() {
2754 let failures = [
2755 crate::Error::PlatformUnsupported {
2756 platform: "the test's failing detection",
2757 },
2758 crate::Error::WatchUnavailable {
2759 reason: "a reason long enough to fill a drop-down twice over",
2760 },
2761 ];
2762 for failure in failures {
2763 let reason = failure.to_string();
2764 let label = system_choice_label(&Err(failure));
2765 assert_eq!(label, "system (unavailable)", "for {reason:?}");
2766 assert!(!label.contains(&reason), "{label:?} quotes {reason:?}");
2767 }
2768 }
2769
2770 #[test]
2771 fn test_icon_set_choice_display_default() {
2772 let choice = IconSetChoice::Default("Adwaita".to_string());
2773 assert_eq!(choice.to_string(), "default (Adwaita)");
2774 }
2775
2776 #[test]
2777 fn test_icon_set_choice_display_material() {
2778 assert_eq!(IconSetChoice::Material.to_string(), "Material (bundled)");
2779 }
2780
2781 #[test]
2782 fn test_icon_set_choice_display_lucide() {
2783 assert_eq!(IconSetChoice::Lucide.to_string(), "Lucide (bundled)");
2784 }
2785
2786 #[test]
2787 fn test_icon_set_choice_display_freedesktop() {
2788 let choice = IconSetChoice::Freedesktop("breeze".to_string());
2789 assert_eq!(choice.to_string(), "breeze");
2790 }
2791
2792 #[test]
2793 fn test_icon_set_choice_follows_preset() {
2794 assert!(IconSetChoice::Default("Adwaita".to_string()).follows_preset());
2795 assert!(!IconSetChoice::System.follows_preset());
2796 assert!(!IconSetChoice::Freedesktop("breeze".to_string()).follows_preset());
2797 assert!(!IconSetChoice::Material.follows_preset());
2798 assert!(!IconSetChoice::Lucide.follows_preset());
2799 }
2800
2801 #[test]
2802 fn test_icon_set_choice_effective_icon_set() {
2803 let choice = IconSetChoice::Default("Adwaita".to_string());
2805 assert_eq!(
2806 choice.effective_icon_set(IconSet::Freedesktop),
2807 IconSet::Freedesktop
2808 );
2809 assert_eq!(
2810 choice.effective_icon_set(IconSet::Material),
2811 IconSet::Material
2812 );
2813
2814 let sys = IconSetChoice::System.effective_icon_set(IconSet::Material);
2816 assert_eq!(sys, system_icon_set());
2817
2818 let choice = IconSetChoice::Freedesktop("breeze".to_string());
2820 assert_eq!(
2821 choice.effective_icon_set(IconSet::Material),
2822 IconSet::Freedesktop
2823 );
2824
2825 assert_eq!(
2827 IconSetChoice::Material.effective_icon_set(IconSet::Freedesktop),
2828 IconSet::Material
2829 );
2830 assert_eq!(
2831 IconSetChoice::Lucide.effective_icon_set(IconSet::Freedesktop),
2832 IconSet::Lucide
2833 );
2834 }
2835
2836 #[test]
2837 fn test_icon_set_choice_freedesktop_theme() {
2838 assert_eq!(
2839 IconSetChoice::Default("Adwaita".to_string()).freedesktop_theme(),
2840 Some("Adwaita")
2841 );
2842 assert_eq!(
2843 IconSetChoice::Freedesktop("breeze".to_string()).freedesktop_theme(),
2844 Some("breeze")
2845 );
2846 assert_eq!(IconSetChoice::System.freedesktop_theme(), None);
2847 assert_eq!(IconSetChoice::Material.freedesktop_theme(), None);
2848 assert_eq!(IconSetChoice::Lucide.freedesktop_theme(), None);
2849 }
2850
2851 #[test]
2852 fn test_default_icon_choice_none() {
2853 assert_eq!(
2855 default_icon_choice(IconSet::Freedesktop, None),
2856 IconSetChoice::System
2857 );
2858 assert_eq!(
2859 default_icon_choice(IconSet::Material, None),
2860 IconSetChoice::System
2861 );
2862 }
2863
2864 #[test]
2865 fn test_default_icon_choice_bundled() {
2866 assert_eq!(
2868 default_icon_choice(IconSet::Material, Some("any-theme")),
2869 IconSetChoice::Default("any-theme".to_string())
2870 );
2871 assert_eq!(
2872 default_icon_choice(IconSet::Lucide, Some("any-theme")),
2873 IconSetChoice::Default("any-theme".to_string())
2874 );
2875 }
2876
2877 #[test]
2880 fn system_sets_are_available_only_where_their_loader_is_compiled() {
2881 let default =
2882 |set| default_icon_choice(set, Some("x")) == IconSetChoice::Default("x".into());
2883 assert_eq!(
2884 default(IconSet::SfSymbols),
2885 cfg!(all(target_os = "macos", feature = "system-icons"))
2886 );
2887 assert_eq!(
2888 default(IconSet::SegoeFluent),
2889 cfg!(all(target_os = "windows", feature = "system-icons"))
2890 );
2891 }
2892
2893 #[test]
2894 fn test_list_freedesktop_themes_no_panic() {
2895 let themes = list_freedesktop_themes();
2897 #[cfg(not(target_os = "linux"))]
2900 assert!(themes.is_empty());
2901 let _ = themes;
2903 }
2904}
2905
2906#[cfg(all(test, target_os = "linux"))]
2907#[allow(clippy::unwrap_used, reason = "a test fails by panicking")]
2908mod installed_theme_tests {
2909 use super::*;
2910 use std::path::{Path, PathBuf};
2911
2912 struct Bases {
2915 root: PathBuf,
2916 }
2917
2918 impl Bases {
2919 fn new(tag: &str) -> Self {
2920 let root = std::env::temp_dir().join(format!(
2921 "native-theme-installed-{}-{tag}",
2922 std::process::id()
2923 ));
2924 let _ = std::fs::remove_dir_all(&root);
2925 std::fs::create_dir_all(root.join("share/icons")).unwrap();
2926 Self { root }
2927 }
2928
2929 fn icons(&self) -> PathBuf {
2930 self.root.join("share/icons")
2931 }
2932
2933 fn add(&self, base: &Path, theme: &str, index: &str) {
2934 std::fs::create_dir_all(base.join(theme)).unwrap();
2935 std::fs::write(base.join(theme).join("index.theme"), index).unwrap();
2936 }
2937 }
2938
2939 impl Drop for Bases {
2940 fn drop(&mut self) {
2941 let _ = std::fs::remove_dir_all(&self.root);
2942 }
2943 }
2944
2945 #[test]
2949 fn an_installed_theme_lists_directories_in_its_icon_theme_group() {
2950 let bases = Bases::new("predicate");
2951 let icons = bases.icons();
2952 bases.add(
2953 &icons,
2954 "icons",
2955 "[Icon Theme]\nName=icons\nDirectories=actions\n",
2956 );
2957 bases.add(
2958 &icons,
2959 "spaced",
2960 "[Icon Theme]\nName=spaced\nDirectories = actions\n",
2961 );
2962 bases.add(
2963 &icons,
2964 "breeze_cursors",
2965 "[Icon Theme]\nName=Breeze Cursors\nInherits=breeze\n",
2966 );
2967 bases.add(&icons, "default", "[Icon Theme]\nInherits=Adwaita\n");
2968 bases.add(
2969 &icons,
2970 "elsewhere",
2971 "[Icon Theme]\nName=elsewhere\n\n[Other]\nDirectories=actions\n",
2972 );
2973 let dirs = [icons];
2974 assert!(has_theme_index("icons", &dirs));
2975 assert!(has_theme_index("spaced", &dirs));
2976 assert!(!has_theme_index("breeze_cursors", &dirs));
2977 assert!(!has_theme_index("default", &dirs));
2978 assert!(!has_theme_index("elsewhere", &dirs));
2979 assert!(!has_theme_index("missing", &dirs));
2980 assert_eq!(
2981 installed_themes_in(&dirs).into_iter().collect::<Vec<_>>(),
2982 ["icons", "spaced"]
2983 );
2984 }
2985
2986 #[test]
2988 fn breeze_cursors_is_not_available() {
2989 if !Path::new("/usr/share/icons/breeze_cursors/index.theme").exists() {
2990 eprintln!("skipped: breeze_cursors is not installed");
2991 return;
2992 }
2993 assert!(!is_freedesktop_theme_available("breeze_cursors"));
2994 assert!(!list_freedesktop_themes().contains(&"breeze_cursors".to_string()));
2995 }
2996
2997 #[test]
2999 fn listed_themes_are_available() {
3000 for theme in list_freedesktop_themes() {
3001 assert!(is_freedesktop_theme_available(&theme), "{theme}");
3002 }
3003 }
3004
3005 #[test]
3008 fn icon_base_dirs_put_the_user_s_first() {
3009 let bases = Bases::new("order");
3010 let home = bases.root.join("home");
3011 for dir in [".icons", ".local/share/icons"] {
3012 std::fs::create_dir_all(home.join(dir)).unwrap();
3013 }
3014 let system = bases.root.join("share");
3015 assert_eq!(
3016 icon_base_dirs_in(Some(&home), None, Some(system.as_os_str())),
3017 [
3018 home.join(".icons"),
3019 home.join(".local/share/icons"),
3020 system.join("icons")
3021 ]
3022 );
3023 }
3024
3025 #[test]
3029 fn the_first_index_theme_decides_whether_a_theme_is_installed() {
3030 let bases = Bases::new("first-index");
3031 let user = bases.root.join("home/.icons");
3032 bases.add(&user, "shadowed", "[Icon Theme]\nName=shadowed\n");
3033 bases.add(
3034 &bases.icons(),
3035 "shadowed",
3036 "[Icon Theme]\nName=shadowed\nDirectories=actions\n",
3037 );
3038 assert!(!has_theme_index("shadowed", &[user.clone(), bases.icons()]));
3039 assert!(has_theme_index("shadowed", &[bases.icons(), user]));
3040 }
3041}
3042
3043#[cfg(test)]
3044#[allow(
3045 clippy::unwrap_used,
3046 clippy::expect_used,
3047 clippy::panic,
3048 clippy::indexing_slicing,
3049 reason = "a test fails by panicking"
3050)]
3051mod colorize_tests {
3052 use super::{colorize_monochrome_svg, fill_current_color, sets_color};
3053 use crate::color::Rgba;
3054 use std::borrow::Cow;
3055
3056 const BLUE: Rgba = Rgba::new(51, 102, 204, 255);
3057 const RED: Rgba = Rgba::new(255, 0, 0, 255);
3058 const GREEN: Rgba = Rgba::new(20, 184, 82, 255);
3059
3060 #[test]
3061 fn colorize_svg_replaces_fill_black() {
3062 let svg = b"<svg><path fill=\"black\" d=\"M0 0h24v24H0z\"/></svg>";
3063 let result_str = String::from_utf8(colorize_monochrome_svg(svg, BLUE)).unwrap();
3064 assert!(
3065 !result_str.contains("fill=\"black\""),
3066 "fill=\"black\" should be replaced, got: {result_str}"
3067 );
3068 assert!(
3069 result_str.contains("fill=\"#3366cc\""),
3070 "should contain the hex fill, got: {result_str}"
3071 );
3072 }
3073
3074 #[test]
3075 fn colorize_svg_replaces_fill_hex_black() {
3076 let svg = b"<svg><rect fill=\"#000000\" width=\"24\" height=\"24\"/></svg>";
3077 let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
3078 assert!(
3079 !result_str.contains("#000000"),
3080 "fill=\"#000000\" should be replaced, got: {result_str}"
3081 );
3082 assert!(
3083 result_str.contains("fill=\"#ff0000\""),
3084 "should contain the hex fill, got: {result_str}"
3085 );
3086 }
3087
3088 #[test]
3089 fn colorize_svg_replaces_fill_short_hex_black() {
3090 let svg = b"<svg><rect fill=\"#000\" width=\"24\" height=\"24\"/></svg>";
3091 let result_str = String::from_utf8(colorize_monochrome_svg(svg, GREEN)).unwrap();
3092 assert!(
3093 !result_str.contains("fill=\"#000\""),
3094 "fill=\"#000\" should be replaced, got: {result_str}"
3095 );
3096 assert!(
3097 result_str.contains("fill=\"#14b852\""),
3098 "should contain the hex fill, got: {result_str}"
3099 );
3100 }
3101
3102 #[test]
3103 fn colorize_svg_current_color_still_works() {
3104 let svg = b"<svg><path stroke=\"currentColor\" d=\"M0 0\"/></svg>";
3105 let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
3106 assert!(
3107 !result_str.contains("currentColor"),
3108 "currentColor should be replaced"
3109 );
3110 assert!(
3111 result_str.contains("#ff0000"),
3112 "should contain the hex colour"
3113 );
3114 }
3115
3116 #[test]
3117 fn colorize_svg_implicit_black_still_works() {
3118 let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M0 0\"/></svg>";
3120 let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
3121 assert!(
3122 result_str.contains("fill=\"#ff0000\""),
3123 "should inject fill into root svg tag, got: {result_str}"
3124 );
3125 }
3126
3127 #[test]
3128 fn colorize_svg_non_utf8_returns_original() {
3129 let mut svg = b"<svg><path fill=\"black\" d=\"M0 0\"/>".to_vec();
3131 svg.push(0xFF); svg.extend_from_slice(b"</svg>");
3133 let result = colorize_monochrome_svg(&svg, RED);
3134 assert_eq!(result, svg, "non-UTF-8 input should be returned unchanged");
3135 }
3136
3137 #[test]
3138 fn colorize_svg_replaces_stroke_black() {
3139 let svg = b"<svg><path stroke=\"black\" d=\"M0 0h24\"/></svg>";
3140 let result_str = String::from_utf8(colorize_monochrome_svg(svg, BLUE)).unwrap();
3141 assert!(
3142 !result_str.contains("stroke=\"black\""),
3143 "stroke=\"black\" should be replaced, got: {result_str}"
3144 );
3145 assert!(
3146 result_str.contains("stroke=\"#3366cc\""),
3147 "should contain the hex stroke, got: {result_str}"
3148 );
3149 }
3150
3151 #[test]
3152 fn colorize_svg_replaces_stroke_hex_black() {
3153 let svg = b"<svg><line stroke=\"#000000\" x1=\"0\" y1=\"0\" x2=\"24\" y2=\"24\"/></svg>";
3154 let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
3155 assert!(
3156 !result_str.contains("#000000"),
3157 "stroke=\"#000000\" should be replaced"
3158 );
3159 assert!(
3160 result_str.contains("stroke=\"#ff0000\""),
3161 "should contain the hex stroke, got: {result_str}"
3162 );
3163 }
3164
3165 #[test]
3166 fn colorize_self_closing_svg_produces_valid_xml() {
3167 let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\" />";
3169 let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
3170 assert!(
3171 result_str.contains("fill=\"#ff0000\""),
3172 "should inject fill, got: {result_str}"
3173 );
3174 assert!(
3175 !result_str.contains("/ fill="),
3176 "fill must be before '/', got: {result_str}"
3177 );
3178 assert!(
3179 result_str.trim().ends_with("/>"),
3180 "should remain self-closing, got: {result_str}"
3181 );
3182 }
3183
3184 #[test]
3185 fn colorize_svg_with_fill_white_root() {
3186 let svg = b"<svg fill=\"white\"><path/></svg>";
3188 let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
3189 assert!(
3190 result_str.contains("fill=\"white\""),
3191 "fill=\"white\" should be preserved, got: {result_str}"
3192 );
3193 }
3194
3195 #[test]
3196 fn colorize_svg_with_fill_none_root() {
3197 let svg = b"<svg fill=\"none\"><path stroke=\"black\"/></svg>";
3199 let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
3200 assert!(
3201 !result_str.contains("stroke=\"black\""),
3202 "stroke=\"black\" should be replaced, got: {result_str}"
3203 );
3204 assert!(
3205 result_str.contains("stroke=\"#ff0000\""),
3206 "should contain the hex stroke, got: {result_str}"
3207 );
3208 }
3209
3210 #[test]
3212 fn colorize_svg_discards_alpha() {
3213 let svg = b"<svg><path fill=\"black\"/></svg>";
3214 let translucent = Rgba::new(255, 0, 0, 40);
3215 assert_eq!(
3216 colorize_monochrome_svg(svg, translucent),
3217 colorize_monochrome_svg(svg, RED)
3218 );
3219 }
3220
3221 #[test]
3222 fn colorize_svg_replaces_stroke_short_hex_black() {
3223 let svg = b"<svg><path stroke=\"#000\" d=\"M0 0\"/></svg>";
3224 let result_str = String::from_utf8(colorize_monochrome_svg(svg, BLUE)).unwrap();
3225 assert!(
3226 result_str.contains("stroke=\"#3366cc\""),
3227 "stroke=\"#000\" should be replaced, got: {result_str}"
3228 );
3229 }
3230
3231 #[test]
3232 fn colorize_svg_keeps_a_root_fill_and_injects_none() {
3233 let svg = b"<svg fill=\"red\"><path d=\"M0 0\"/></svg>";
3234 let result_str = String::from_utf8(colorize_monochrome_svg(svg, GREEN)).unwrap();
3235 assert!(result_str.contains("fill=\"red\""), "got: {result_str}");
3237 assert!(!result_str.contains("#14b852"), "got: {result_str}");
3238 }
3239
3240 #[test]
3241 fn colorize_svg_mixed_fill_attributes() {
3242 let svg = b"<svg><rect fill=\"black\" width=\"10\" height=\"10\"/><rect fill=\"red\" width=\"10\" height=\"10\"/></svg>";
3244 let result_str = String::from_utf8(colorize_monochrome_svg(svg, GREEN)).unwrap();
3245 assert!(
3246 !result_str.contains("fill=\"black\""),
3247 "fill=\"black\" should be replaced, got: {result_str}"
3248 );
3249 assert!(
3250 result_str.contains("fill=\"red\""),
3251 "fill=\"red\" should be preserved, got: {result_str}"
3252 );
3253 }
3254
3255 #[test]
3256 fn colorize_self_closing_svg_without_a_space_produces_valid_xml() {
3257 let svg = b"<svg xmlns='http://www.w3.org/2000/svg'/>";
3259 let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
3260 assert!(
3261 result_str.contains("fill=\"#ff0000\"") && result_str.ends_with("/>"),
3262 "self-closing SVG should remain valid XML, got: {result_str}"
3263 );
3264 assert!(
3265 !result_str.contains("/ fill="),
3266 "fill should not be between / and >, got: {result_str}"
3267 );
3268 }
3269
3270 #[test]
3271 fn fill_current_color_fills_an_unset_current_color() {
3272 let svg = br#"<svg><path fill="currentColor" stroke="currentColor"/></svg>"#;
3273 let filled = fill_current_color(svg, Rgba::new(51, 102, 204, 7));
3274 assert_eq!(
3275 &*filled,
3276 br##"<svg><path fill="#3366cc" stroke="#3366cc"/></svg>"##
3277 );
3278 }
3279
3280 #[test]
3281 fn fill_current_color_borrows_what_it_leaves_alone() {
3282 let plain = br##"<svg><path fill="#2e3436"/></svg>"##;
3283 let styled = br#"<svg><style>.ColorScheme-Text { color:#232629; }</style><path class="ColorScheme-Text" fill="currentColor"/></svg>"#;
3284 let attribute = br##"<svg color="#fff"><path fill="currentColor"/></svg>"##;
3285 let not_utf8 = b"<svg>\xff currentColor</svg>";
3286 for svg in [&plain[..], &styled[..], &attribute[..], ¬_utf8[..]] {
3287 assert!(
3288 matches!(fill_current_color(svg, BLUE), Cow::Borrowed(b) if b == svg),
3289 "{}",
3290 String::from_utf8_lossy(svg)
3291 );
3292 }
3293 }
3294
3295 #[test]
3296 fn sets_color_reads_only_the_color_property() {
3297 assert!(!sets_color(r#"<svg><path fill="currentColor"/></svg>"#));
3298 assert!(sets_color(
3299 r##"<svg color="#fff"><path fill="currentColor"/></svg>"##
3300 ));
3301 assert!(sets_color("<svg><style>.a { color : #fff }</style></svg>"));
3302 assert!(sets_color(r#"<svg><path style="color:#fff"/></svg>"#));
3303 assert!(!sets_color(
3304 r##"<svg><stop stop-color="#fff"/><path fill="currentColor"/></svg>"##
3305 ));
3306 assert!(!sets_color(
3307 r##"<svg flood-color="#fff" lighting-color="#fff" solid-color="#fff"/>"##
3308 ));
3309 assert!(!sets_color(
3310 r##"<svg text-decoration-color="#fff" pagecolor="#fff" bordercolor="#fff"/>"##
3311 ));
3312 assert!(!sets_color(
3313 r#"<svg id="color" class="color"><path fill="currentColor"/></svg>"#
3314 ));
3315 assert!(!sets_color(r#"<svg color-interpolation="sRGB"/>"#));
3316 }
3317}