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]
394 #[allow(unused_variables)]
395 pub fn load_indicator(theme: Option<&str>) -> Option<AnimatedIcon> {
396 #[cfg(all(target_os = "linux", feature = "system-icons"))]
397 {
398 crate::freedesktop::load_freedesktop_spinner(theme)
399 }
400 #[cfg(not(all(target_os = "linux", feature = "system-icons")))]
401 {
402 None
403 }
404 }
405}
406
407#[derive(Debug)]
412#[must_use]
413pub struct SfSymbolsLoader<'a> {
414 #[allow(dead_code)] id: IconId<'a>,
416 #[allow(dead_code)] size: Option<u32>,
418 #[allow(dead_code)] fg_color: Option<[u8; 3]>,
420}
421
422impl<'a> SfSymbolsLoader<'a> {
423 pub fn new(id: impl Into<IconId<'a>>) -> Self {
426 Self {
427 id: id.into(),
428 size: None,
429 fg_color: None,
430 }
431 }
432
433 pub fn size(mut self, size: u32) -> Self {
438 self.size = Some(size.clamp(1, MAX_ICON_SIZE));
439 self
440 }
441
442 pub fn color(mut self, color: Rgba) -> Self {
445 self.fg_color = Some(rgb(color));
446 self
447 }
448
449 pub fn color_opt(mut self, color: Option<Rgba>) -> Self {
452 self.fg_color = color.map(rgb);
453 self
454 }
455
456 #[must_use]
460 #[allow(unused_variables)]
461 pub fn load(self) -> Option<IconData> {
462 #[cfg(all(target_os = "macos", feature = "system-icons"))]
463 {
464 match self.id {
465 IconId::Role(role) => {
466 let name = icon_name(role, IconSet::SfSymbols)?;
467 crate::sficons::load_sf_icon_by_name(name, self.size, self.fg_color)
468 }
469 IconId::Name(n) => {
470 crate::sficons::load_sf_icon_by_name(n, self.size, self.fg_color)
471 }
472 IconId::Custom(p) => {
473 if let Some(n) = p.icon_name(IconSet::SfSymbols)
474 && let Some(data) =
475 crate::sficons::load_sf_icon_by_name(n, self.size, self.fg_color)
476 {
477 return Some(data);
478 }
479 p.icon_svg(IconSet::SfSymbols).map(IconData::Svg)
480 }
481 }
482 }
483 #[cfg(not(all(target_os = "macos", feature = "system-icons")))]
484 {
485 None
486 }
487 }
488 }
490
491#[derive(Debug)]
498#[must_use]
499pub struct SegoeFluentLoader<'a> {
500 #[allow(dead_code)] id: IconId<'a>,
502 #[allow(dead_code)] size: Option<u32>,
504 #[allow(dead_code)] fg_color: Option<[u8; 3]>,
506}
507
508impl<'a> SegoeFluentLoader<'a> {
509 pub fn new(id: impl Into<IconId<'a>>) -> Self {
512 Self {
513 id: id.into(),
514 size: None,
515 fg_color: None,
516 }
517 }
518
519 pub fn size(mut self, size: u32) -> Self {
523 self.size = Some(size.clamp(1, MAX_ICON_SIZE));
524 self
525 }
526
527 pub fn color(mut self, color: Rgba) -> Self {
531 self.fg_color = Some(rgb(color));
532 self
533 }
534
535 pub fn color_opt(mut self, color: Option<Rgba>) -> Self {
538 self.fg_color = color.map(rgb);
539 self
540 }
541
542 #[must_use]
546 #[allow(unused_variables)]
547 pub fn load(self) -> Option<IconData> {
548 #[cfg(all(target_os = "windows", feature = "system-icons"))]
549 {
550 match self.id {
551 IconId::Role(role) => {
552 let name = icon_name(role, IconSet::SegoeFluent)?;
553 crate::winicons::load_windows_icon_by_name(name, self.size, self.fg_color)
554 }
555 IconId::Name(n) => {
556 crate::winicons::load_windows_icon_by_name(n, self.size, self.fg_color)
557 }
558 IconId::Custom(p) => {
559 if let Some(n) = p.icon_name(IconSet::SegoeFluent)
560 && let Some(data) =
561 crate::winicons::load_windows_icon_by_name(n, self.size, self.fg_color)
562 {
563 return Some(data);
564 }
565 p.icon_svg(IconSet::SegoeFluent).map(IconData::Svg)
566 }
567 }
568 }
569 #[cfg(not(all(target_os = "windows", feature = "system-icons")))]
570 {
571 None
572 }
573 }
574 }
576
577#[derive(Debug)]
581#[must_use]
582pub struct MaterialLoader<'a> {
583 #[allow(dead_code)] id: IconId<'a>,
585}
586
587impl<'a> MaterialLoader<'a> {
588 pub fn new(id: impl Into<IconId<'a>>) -> Self {
590 Self { id: id.into() }
591 }
592
593 #[must_use]
597 #[allow(unused_variables)]
598 pub fn load(self) -> Option<IconData> {
599 #[cfg(feature = "material-icons")]
600 {
601 match self.id {
602 IconId::Role(role) => bundled_icon_svg(role, IconSet::Material)
603 .map(|b| IconData::Svg(Cow::Borrowed(b))),
604 IconId::Name(n) => bundled_icon_by_name(n, IconSet::Material)
605 .map(|b| IconData::Svg(Cow::Borrowed(b))),
606 IconId::Custom(p) => {
607 if let Some(n) = p.icon_name(IconSet::Material)
608 && let Some(b) = bundled_icon_by_name(n, IconSet::Material)
609 {
610 return Some(IconData::Svg(Cow::Borrowed(b)));
611 }
612 p.icon_svg(IconSet::Material).map(IconData::Svg)
613 }
614 }
615 }
616 #[cfg(not(feature = "material-icons"))]
617 {
618 None
619 }
620 }
621
622 #[must_use]
626 pub fn load_indicator() -> Option<AnimatedIcon> {
627 #[cfg(feature = "material-icons")]
628 {
629 Some(crate::spinners::material_spinner())
630 }
631 #[cfg(not(feature = "material-icons"))]
632 {
633 None
634 }
635 }
636}
637
638#[derive(Debug)]
640#[must_use]
641pub struct LucideLoader<'a> {
642 #[allow(dead_code)] id: IconId<'a>,
644}
645
646impl<'a> LucideLoader<'a> {
647 pub fn new(id: impl Into<IconId<'a>>) -> Self {
649 Self { id: id.into() }
650 }
651
652 #[must_use]
656 #[allow(unused_variables)]
657 pub fn load(self) -> Option<IconData> {
658 #[cfg(feature = "lucide-icons")]
659 {
660 match self.id {
661 IconId::Role(role) => {
662 bundled_icon_svg(role, IconSet::Lucide).map(|b| IconData::Svg(Cow::Borrowed(b)))
663 }
664 IconId::Name(n) => bundled_icon_by_name(n, IconSet::Lucide)
665 .map(|b| IconData::Svg(Cow::Borrowed(b))),
666 IconId::Custom(p) => {
667 if let Some(n) = p.icon_name(IconSet::Lucide)
668 && let Some(b) = bundled_icon_by_name(n, IconSet::Lucide)
669 {
670 return Some(IconData::Svg(Cow::Borrowed(b)));
671 }
672 p.icon_svg(IconSet::Lucide).map(IconData::Svg)
673 }
674 }
675 }
676 #[cfg(not(feature = "lucide-icons"))]
677 {
678 None
679 }
680 }
681
682 #[must_use]
686 pub fn load_indicator() -> Option<AnimatedIcon> {
687 #[cfg(feature = "lucide-icons")]
688 {
689 Some(crate::spinners::lucide_spinner())
690 }
691 #[cfg(not(feature = "lucide-icons"))]
692 {
693 None
694 }
695 }
696}
697
698#[must_use]
709pub fn load_icon<'a>(id: impl Into<IconId<'a>>, set: IconSet) -> Option<IconData> {
710 let id = id.into();
711 match set {
712 IconSet::Freedesktop => FreedesktopLoader::new(id).load(),
713 IconSet::SfSymbols => SfSymbolsLoader::new(id).load(),
714 IconSet::SegoeFluent => SegoeFluentLoader::new(id).load(),
715 IconSet::Material => MaterialLoader::new(id).load(),
716 IconSet::Lucide => LucideLoader::new(id).load(),
717 }
718}
719
720#[must_use]
732pub fn load_icon_indicator(set: IconSet, theme: Option<&str>) -> Option<AnimatedIcon> {
733 match set {
734 IconSet::Freedesktop => FreedesktopLoader::load_indicator(theme),
735 IconSet::Material => MaterialLoader::load_indicator(),
736 IconSet::Lucide => LucideLoader::load_indicator(),
737 IconSet::SfSymbols | IconSet::SegoeFluent => None,
738 }
739}
740
741#[must_use]
779pub fn load_custom_icon(
780 provider: &(impl IconProvider + ?Sized),
781 set: IconSet,
782 color: Option<Rgba>,
783 size: Option<u32>,
784) -> Option<IconData> {
785 load_custom_icon_in(provider, set, None, color, size)
786}
787
788#[must_use]
801pub fn load_custom_icon_in(
802 provider: &(impl IconProvider + ?Sized),
803 set: IconSet,
804 icon_theme: Option<&str>,
805 color: Option<Rgba>,
806 size: Option<u32>,
807) -> Option<IconData> {
808 load_provider_icon(provider, set, icon_theme, color, size)
809}
810
811pub(crate) fn load_icon_in<'a>(
816 id: IconId<'a>,
817 set: IconSet,
818 theme: Option<&'a str>,
819 color: Option<Rgba>,
820 size: Option<u32>,
821) -> Option<IconData> {
822 match id {
823 IconId::Custom(provider) => load_provider_icon(provider, set, theme, color, size),
824 id => load_set_icon(id, set, theme, color, size),
825 }
826}
827
828fn load_provider_icon(
831 provider: &(impl IconProvider + ?Sized),
832 set: IconSet,
833 theme: Option<&str>,
834 color: Option<Rgba>,
835 size: Option<u32>,
836) -> Option<IconData> {
837 if let Some(name) = provider.icon_name(set)
838 && let Some(data) = load_set_icon(IconId::Name(name), set, theme, color, size)
839 {
840 return Some(data);
841 }
842 provider
843 .icon_svg(set)
844 .map(|svg| colorize_svg_data(IconData::Svg(svg), color))
845}
846
847fn load_set_icon<'a>(
851 id: IconId<'a>,
852 set: IconSet,
853 theme: Option<&'a str>,
854 color: Option<Rgba>,
855 size: Option<u32>,
856) -> Option<IconData> {
857 match set {
858 IconSet::Freedesktop => {
859 let loader = FreedesktopLoader::new(id).color_opt(color);
860 let loader = match size {
861 Some(size) => loader.size(size),
862 None => loader,
863 };
864 match theme {
865 Some(theme) => loader.theme(theme),
866 None => loader,
867 }
868 .load()
869 .map(|data| fill_freedesktop_svg_data(data, color))
870 }
871 IconSet::SfSymbols => {
872 let loader = SfSymbolsLoader::new(id).color_opt(color);
873 match size {
874 Some(size) => loader.size(size),
875 None => loader,
876 }
877 .load()
878 }
879 IconSet::SegoeFluent => {
880 let loader = SegoeFluentLoader::new(id).color_opt(color);
881 match size {
882 Some(size) => loader.size(size),
883 None => loader,
884 }
885 .load()
886 }
887 IconSet::Material => MaterialLoader::new(id)
888 .load()
889 .map(|data| colorize_svg_data(data, color)),
890 IconSet::Lucide => LucideLoader::new(id)
891 .load()
892 .map(|data| colorize_svg_data(data, color)),
893 }
894}
895
896fn colorize_svg_data(data: IconData, color: Option<Rgba>) -> IconData {
899 match (data, color) {
900 (IconData::Svg(svg), Some(color)) => {
901 IconData::Svg(Cow::Owned(colorize_monochrome_svg(&svg, color)))
902 }
903 (data, _) => data,
904 }
905}
906
907fn fill_freedesktop_svg_data(data: IconData, color: Option<Rgba>) -> IconData {
913 match (data, color) {
914 (IconData::Svg(svg), Some(color)) => {
915 let filled = match fill_current_color(&svg, color) {
916 Cow::Owned(filled) => Some(filled),
917 Cow::Borrowed(_) => None,
918 };
919 IconData::Svg(filled.map_or(svg, Cow::Owned))
920 }
921 (data, _) => data,
922 }
923}
924
925#[must_use]
947pub fn colorize_monochrome_svg(svg: &[u8], color: Rgba) -> Vec<u8> {
948 let hex = format!("#{:02x}{:02x}{:02x}", color.r, color.g, color.b);
949
950 let Ok(svg_str) = std::str::from_utf8(svg) else {
951 return svg.to_vec();
952 };
953
954 let replaced = if svg_str.contains("currentColor") {
956 svg_str.replace("currentColor", &hex)
957 } else {
958 svg_str.to_owned()
959 };
960
961 let fill_hex = format!("fill=\"{hex}\"");
963 let replaced = replaced
964 .replace("fill=\"black\"", &fill_hex)
965 .replace("fill=\"#000000\"", &fill_hex)
966 .replace("fill=\"#000\"", &fill_hex);
967 let stroke_hex = format!("stroke=\"{hex}\"");
968 let replaced = replaced
969 .replace("stroke=\"black\"", &stroke_hex)
970 .replace("stroke=\"#000000\"", &stroke_hex)
971 .replace("stroke=\"#000\"", &stroke_hex);
972
973 if replaced != svg_str {
974 return replaced.into_bytes();
975 }
976
977 if let Some(pos) = svg_str.find("<svg")
980 && let Some(tail) = svg_str.get(pos..)
981 && let Some(close) = tail.find('>')
982 {
983 let tag_end = pos.saturating_add(close);
984 if let Some(tag) = svg_str.get(pos..tag_end)
985 && !tag.contains("fill=")
986 {
987 let is_self_closing = tag_end > 0
989 && svg_str
990 .as_bytes()
991 .get(tag_end.saturating_sub(1))
992 .is_some_and(|&b| b == b'/');
993 let inject_pos = if is_self_closing {
994 tag_end.saturating_sub(1)
995 } else {
996 tag_end
997 };
998 if let Some(before) = svg_str.get(..inject_pos)
999 && let Some(after) = svg_str.get(inject_pos..)
1000 {
1001 let mut result = String::with_capacity(svg_str.len().saturating_add(20));
1002 result.push_str(before);
1003 result.push_str(&format!(" fill=\"{hex}\""));
1004 result.push_str(after);
1005 return result.into_bytes();
1006 }
1007 }
1008 }
1009
1010 svg.to_vec()
1012}
1013
1014#[must_use]
1050pub fn fill_current_color(svg: &[u8], color: Rgba) -> Cow<'_, [u8]> {
1051 match std::str::from_utf8(svg) {
1052 Ok(text) if text.contains("currentColor") && !sets_color(text) => Cow::Owned(
1053 text.replace(
1054 "currentColor",
1055 &format!("#{:02x}{:02x}{:02x}", color.r, color.g, color.b),
1056 )
1057 .into_bytes(),
1058 ),
1059 _ => Cow::Borrowed(svg),
1060 }
1061}
1062
1063fn sets_color(svg: &str) -> bool {
1071 let bytes = svg.as_bytes();
1072 svg.match_indices("color").any(|(at, _)| {
1073 let preceded = at
1074 .checked_sub(1)
1075 .and_then(|i| bytes.get(i))
1076 .is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_');
1077 if preceded {
1078 return false;
1079 }
1080 at.checked_add("color".len())
1081 .and_then(|i| bytes.get(i..))
1082 .and_then(|rest| rest.iter().find(|b| !b.is_ascii_whitespace()))
1083 .is_some_and(|b| *b == b':' || *b == b'=')
1084 })
1085}
1086
1087#[cfg(target_os = "linux")]
1111pub(crate) fn icon_base_dirs() -> &'static [std::path::PathBuf] {
1112 static DIRS: std::sync::OnceLock<Vec<std::path::PathBuf>> = std::sync::OnceLock::new();
1113 DIRS.get_or_init(|| {
1114 icon_base_dirs_in(
1115 std::env::home_dir().as_deref(),
1116 std::env::var_os("XDG_DATA_HOME").as_deref(),
1117 std::env::var_os("XDG_DATA_DIRS").as_deref(),
1118 )
1119 })
1120}
1121
1122#[cfg(target_os = "linux")]
1131pub(crate) fn icon_base_dirs_in(
1132 home: Option<&std::path::Path>,
1133 data_home: Option<&std::ffi::OsStr>,
1134 data_dirs: Option<&std::ffi::OsStr>,
1135) -> Vec<std::path::PathBuf> {
1136 use std::path::PathBuf;
1137
1138 let Some(home) = home else {
1139 return Vec::new();
1140 };
1141 let mut dirs: Vec<PathBuf> = std::iter::once(home.join(".icons"))
1142 .chain(
1143 xdg_data_home(data_home, Some(home))
1144 .into_iter()
1145 .chain(xdg_data_dirs(data_dirs))
1146 .map(|dir| dir.join("icons")),
1147 )
1148 .collect();
1149 dirs.retain(|dir| dir.exists());
1150 dirs
1151}
1152
1153#[cfg(target_os = "linux")]
1157pub(crate) fn xdg_data_dirs(var: Option<&std::ffi::OsStr>) -> Vec<std::path::PathBuf> {
1158 use std::path::PathBuf;
1159
1160 var.map(|dirs| {
1161 std::env::split_paths(dirs)
1162 .filter(|dir| dir.is_absolute())
1163 .collect::<Vec<_>>()
1164 })
1165 .filter(|dirs| !dirs.is_empty())
1166 .unwrap_or_else(|| {
1167 vec![
1168 PathBuf::from("/usr/local/share"),
1169 PathBuf::from("/usr/share"),
1170 ]
1171 })
1172}
1173
1174#[cfg(target_os = "linux")]
1179pub(crate) fn xdg_data_home(
1180 var: Option<&std::ffi::OsStr>,
1181 home: Option<&std::path::Path>,
1182) -> Option<std::path::PathBuf> {
1183 var.map(std::path::PathBuf::from)
1184 .filter(|dir| dir.is_absolute())
1185 .or_else(|| home.map(|home| home.join(".local/share")))
1186}
1187
1188#[cfg(target_os = "linux")]
1191pub(crate) fn is_theme_name(name: &str) -> bool {
1192 use std::path::{Component, Path};
1193
1194 let mut components = Path::new(name).components();
1195 matches!(
1196 (components.next(), components.next()),
1197 (Some(Component::Normal(_)), None)
1198 )
1199}
1200
1201#[cfg(target_os = "linux")]
1206pub(crate) fn theme_index(theme: &str, bases: &[std::path::PathBuf]) -> Option<String> {
1207 if !is_theme_name(theme) {
1208 return None;
1209 }
1210 bases
1211 .iter()
1212 .find_map(|base| std::fs::read_to_string(base.join(theme).join("index.theme")).ok())
1213}
1214
1215#[cfg(target_os = "linux")]
1220pub(crate) fn has_theme_index(theme: &str, bases: &[std::path::PathBuf]) -> bool {
1221 theme_index(theme, bases)
1222 .is_some_and(|index| ini_value(&index, "Icon Theme", "Directories").is_some())
1223}
1224
1225#[cfg(target_os = "linux")]
1228fn installed_themes_in(bases: &[std::path::PathBuf]) -> std::collections::BTreeSet<String> {
1229 bases
1230 .iter()
1231 .filter_map(|base| std::fs::read_dir(base).ok())
1232 .flatten()
1233 .filter_map(Result::ok)
1234 .filter_map(|entry| entry.file_name().into_string().ok())
1235 .filter(|name| has_theme_index(name, bases))
1236 .collect()
1237}
1238
1239#[cfg(target_os = "linux")]
1250pub(crate) fn installed_themes() -> &'static std::collections::BTreeSet<String> {
1251 static THEMES: std::sync::OnceLock<std::collections::BTreeSet<String>> =
1252 std::sync::OnceLock::new();
1253 THEMES.get_or_init(|| installed_themes_in(icon_base_dirs()))
1254}
1255
1256#[cfg(target_os = "linux")]
1259pub(crate) fn ini_value<'a>(content: &'a str, section: &str, key: &str) -> Option<&'a str> {
1260 let mut in_section = false;
1261 for line in content.lines().map(str::trim) {
1262 if let Some(group) = line.strip_prefix('[') {
1263 in_section = group.strip_suffix(']') == Some(section);
1264 continue;
1265 }
1266 if in_section
1267 && let Some((name, value)) = line.split_once('=')
1268 && name.trim() == key
1269 && !value.trim().is_empty()
1270 {
1271 return Some(value.trim());
1272 }
1273 }
1274 None
1275}
1276
1277#[must_use]
1290pub fn is_freedesktop_theme_available(theme: &str) -> bool {
1291 #[cfg(target_os = "linux")]
1292 {
1293 installed_themes().contains(theme)
1294 }
1295 #[cfg(not(target_os = "linux"))]
1296 {
1297 let _ = theme;
1298 false
1299 }
1300}
1301
1302#[derive(Debug, Clone, PartialEq, Eq)]
1313#[non_exhaustive]
1314pub enum IconSetChoice {
1315 Default(String),
1328
1329 System,
1340
1341 Freedesktop(String),
1347
1348 Material,
1350
1351 Lucide,
1353}
1354
1355impl fmt::Display for IconSetChoice {
1356 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1357 match self {
1358 Self::Default(name) => write!(f, "default ({name})"),
1359 Self::System => f.write_str(&system_choice_label(&system_icon_theme())),
1360 Self::Freedesktop(name) => write!(f, "{name}"),
1361 Self::Material => write!(f, "Material (bundled)"),
1362 Self::Lucide => write!(f, "Lucide (bundled)"),
1363 }
1364 }
1365}
1366
1367fn system_choice_label(detected: &crate::Result<String>) -> String {
1371 match detected {
1372 Ok(name) => format!("system ({name})"),
1373 Err(_) => "system (unavailable)".to_string(),
1374 }
1375}
1376
1377impl IconSetChoice {
1378 #[must_use]
1386 pub fn effective_icon_set(&self, theme_icon_set: IconSet) -> IconSet {
1387 match self {
1388 Self::Default(_) => theme_icon_set,
1389 Self::System => system_icon_set(),
1390 Self::Freedesktop(_) => IconSet::Freedesktop,
1391 Self::Material => IconSet::Material,
1392 Self::Lucide => IconSet::Lucide,
1393 }
1394 }
1395
1396 #[must_use]
1408 pub fn freedesktop_theme(&self) -> Option<&str> {
1409 match self {
1410 Self::Default(name) | Self::Freedesktop(name) => Some(name),
1411 Self::System | Self::Material | Self::Lucide => None,
1412 }
1413 }
1414
1415 #[must_use]
1420 pub fn follows_preset(&self) -> bool {
1421 matches!(self, Self::Default(_))
1422 }
1423}
1424
1425#[must_use]
1439pub fn default_icon_choice(icon_set: IconSet, icon_theme: Option<&str>) -> IconSetChoice {
1440 let Some(theme) = icon_theme else {
1441 return IconSetChoice::System;
1442 };
1443 let available = match icon_set {
1448 IconSet::Material | IconSet::Lucide => true,
1449 IconSet::Freedesktop => is_freedesktop_theme_available(theme),
1450 IconSet::SfSymbols => cfg!(all(target_os = "macos", feature = "system-icons")),
1451 IconSet::SegoeFluent => cfg!(all(target_os = "windows", feature = "system-icons")),
1452 };
1453 if available {
1454 IconSetChoice::Default(theme.to_string())
1455 } else {
1456 IconSetChoice::System
1457 }
1458}
1459
1460#[must_use]
1480pub fn list_freedesktop_themes() -> Vec<String> {
1481 #[cfg(target_os = "linux")]
1482 {
1483 installed_themes()
1484 .iter()
1485 .filter(|theme| *theme != "hicolor")
1486 .cloned()
1487 .collect()
1488 }
1489 #[cfg(not(target_os = "linux"))]
1490 {
1491 Vec::new()
1492 }
1493}
1494
1495#[cfg(test)]
1500#[allow(clippy::unwrap_used, clippy::expect_used)]
1501mod load_icon_tests {
1502 use super::*;
1503
1504 #[cfg(all(target_os = "linux", feature = "system-icons"))]
1505 fn undetected() -> crate::Result<String> {
1506 Err(crate::Error::PlatformUnsupported {
1507 platform: "the test's failing detection",
1508 })
1509 }
1510
1511 #[test]
1514 #[cfg(all(target_os = "linux", feature = "system-icons"))]
1515 fn freedesktop_loader_without_a_detected_theme_loads_nothing() {
1516 let custom: &dyn IconProvider = &IconRole::ActionCopy;
1517 for id in [
1518 IconId::Role(IconRole::ActionCopy),
1519 IconId::Name("edit-copy"),
1520 IconId::Custom(custom),
1521 ] {
1522 assert!(
1523 FreedesktopLoader::new(id).load_with(undetected).is_none(),
1524 "an icon loaded though no icon theme was detected"
1525 );
1526 }
1527 }
1528
1529 #[test]
1533 #[cfg(all(target_os = "linux", feature = "system-icons"))]
1534 fn freedesktop_loader_without_a_detected_theme_gives_a_providers_own_svg() {
1535 #[derive(Debug)]
1536 struct AppIcon;
1537 impl IconProvider for AppIcon {
1538 fn icon_name(&self, _set: IconSet) -> Option<&str> {
1539 Some("edit-copy")
1540 }
1541 fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>> {
1542 (set == IconSet::Freedesktop).then_some(Cow::Borrowed(b"<svg>app</svg>"))
1543 }
1544 }
1545
1546 let provider: &dyn IconProvider = &AppIcon;
1547 assert_eq!(
1548 FreedesktopLoader::new(provider).load_with(undetected),
1549 Some(IconData::Svg(Cow::Borrowed(b"<svg>app</svg>"))),
1550 "the provider's own SVG did not load without a detected icon theme"
1551 );
1552 }
1553
1554 #[test]
1557 #[cfg(feature = "material-icons")]
1558 fn a_provider_is_passed_to_a_loader_by_reference() {
1559 #[derive(Debug)]
1560 struct AppIcon;
1561 impl IconProvider for AppIcon {
1562 fn icon_name(&self, _set: IconSet) -> Option<&str> {
1563 None
1564 }
1565 fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>> {
1566 (set == IconSet::Material).then_some(Cow::Borrowed(b"<svg>app</svg>"))
1567 }
1568 }
1569
1570 assert_eq!(
1571 MaterialLoader::new(&AppIcon).load(),
1572 Some(IconData::Svg(Cow::Borrowed(b"<svg>app</svg>"))),
1573 "a provider passed by reference did not load its own SVG"
1574 );
1575 }
1576
1577 #[test]
1579 #[cfg(all(target_os = "linux", feature = "system-icons"))]
1580 fn freedesktop_loader_with_a_theme_does_not_detect() {
1581 let runs = std::cell::Cell::new(0);
1582 let _ = FreedesktopLoader::new("edit-copy")
1583 .theme("Adwaita")
1584 .load_with(|| {
1585 runs.set(runs.get() + 1);
1586 undetected()
1587 });
1588 assert_eq!(runs.get(), 0, "an explicit theme ran the detection");
1589 }
1590
1591 #[test]
1592 #[cfg(all(target_os = "linux", feature = "system-icons"))]
1593 fn freedesktop_loader_theme_override_honored_for_name_lookup() {
1594 let result = FreedesktopLoader::new("format-text-rich")
1601 .theme("Adwaita")
1602 .size(24)
1603 .load();
1604 assert!(
1605 result.is_some(),
1606 "theme('Adwaita') must resolve 'format-text-rich' in Adwaita, regardless of system theme"
1607 );
1608 }
1609
1610 #[test]
1611 #[cfg(feature = "material-icons")]
1612 fn load_icon_material_returns_svg() {
1613 let result = MaterialLoader::new(IconRole::ActionCopy).load();
1614 assert!(result.is_some(), "material ActionCopy should return Some");
1615 match result.unwrap() {
1616 IconData::Svg(ref cow) => {
1617 let s = String::from_utf8_lossy(cow);
1618 assert!(s.contains("<svg"), "should contain SVG data");
1619 }
1620 _ => panic!("expected IconData::Svg for bundled material icon"),
1621 }
1622 }
1623
1624 #[test]
1625 #[cfg(feature = "lucide-icons")]
1626 fn load_icon_lucide_returns_svg() {
1627 let result = LucideLoader::new(IconRole::ActionCopy).load();
1628 assert!(result.is_some(), "lucide ActionCopy should return Some");
1629 match result.unwrap() {
1630 IconData::Svg(ref cow) => {
1631 let s = String::from_utf8_lossy(cow);
1632 assert!(s.contains("<svg"), "should contain SVG data");
1633 }
1634 _ => panic!("expected IconData::Svg for bundled lucide icon"),
1635 }
1636 }
1637
1638 #[test]
1644 #[cfg(all(
1645 target_os = "linux",
1646 feature = "system-icons",
1647 feature = "material-icons"
1648 ))]
1649 fn load_icon_unknown_theme_no_cross_set_fallback() -> std::io::Result<()> {
1650 const NAME: &str = "icons::load_icon_tests::load_icon_unknown_theme_no_cross_set_fallback";
1651 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>"##;
1652 if native_theme_test_fixtures::in_child() {
1653 assert_eq!(
1654 FreedesktopLoader::new(IconRole::DialogError).load(),
1655 Some(IconData::Svg(Cow::Borrowed(DIALOG_ERROR.as_bytes()))),
1656 "the system's theme is looked up"
1657 );
1658 assert!(MaterialLoader::new(IconRole::ActionCopy).load().is_some());
1659 assert_eq!(
1660 FreedesktopLoader::new(IconRole::ActionCopy).load(),
1661 None,
1662 "the system's theme lacks edit-copy"
1663 );
1664 assert_eq!(
1665 FreedesktopLoader::new(IconRole::ActionCopy)
1666 .theme("native-theme-no-such-theme")
1667 .load(),
1668 None,
1669 "the theme given is not installed"
1670 );
1671 return Ok(());
1672 }
1673 let child = native_theme_test_fixtures::Child::kde("lacking");
1674 native_theme_test_fixtures::run(NAME, child, |icons| {
1675 native_theme_test_fixtures::write_scalable_theme(
1676 icons,
1677 "lacking",
1678 &[("dialog-error", DIALOG_ERROR)],
1679 )
1680 })
1681 }
1682
1683 #[test]
1684 #[cfg(feature = "material-icons")]
1685 fn load_icon_all_roles_material() {
1686 let mut some_count = 0;
1688 for role in IconRole::ALL.iter().copied() {
1689 if MaterialLoader::new(role).load().is_some() {
1690 some_count += 1;
1691 }
1692 }
1693 assert_eq!(
1695 some_count, 42,
1696 "Material should cover all 42 roles via bundled SVGs"
1697 );
1698 }
1699
1700 #[test]
1701 #[cfg(feature = "lucide-icons")]
1702 fn load_icon_all_roles_lucide() {
1703 let mut some_count = 0;
1704 for role in IconRole::ALL.iter().copied() {
1705 if LucideLoader::new(role).load().is_some() {
1706 some_count += 1;
1707 }
1708 }
1709 assert_eq!(
1711 some_count, 42,
1712 "Lucide should cover all 42 roles via bundled SVGs"
1713 );
1714 }
1715
1716 #[test]
1717 fn freedesktop_loader_stores_the_size_and_colour() {
1718 let loader = FreedesktopLoader::new("edit-copy");
1719 assert_eq!((loader.size, loader.fg_color), (24, None));
1720 let loader = loader.size(48).color(Rgba::new(10, 20, 30, 40));
1721 assert_eq!(loader.size, 48);
1722 assert_eq!(loader.fg_color, Some([10, 20, 30]), "the alpha is ignored");
1723 assert_eq!(loader.color_opt(None).fg_color, None);
1724 }
1725
1726 #[test]
1728 fn the_system_loaders_clamp_the_size() {
1729 for (size, clamped) in [
1730 (0, 1),
1731 (48, 48),
1732 (MAX_ICON_SIZE, MAX_ICON_SIZE),
1733 (MAX_ICON_SIZE + 1, MAX_ICON_SIZE),
1734 (70_000, MAX_ICON_SIZE),
1735 (u32::MAX, MAX_ICON_SIZE),
1736 ] {
1737 assert_eq!(
1738 FreedesktopLoader::new("edit-copy").size(size).size,
1739 clamped,
1740 "freedesktop {size}"
1741 );
1742 assert_eq!(
1743 SfSymbolsLoader::new(IconRole::ActionCopy).size(size).size,
1744 Some(clamped),
1745 "SF Symbols {size}"
1746 );
1747 assert_eq!(
1748 SegoeFluentLoader::new(IconRole::ActionCopy).size(size).size,
1749 Some(clamped),
1750 "Segoe {size}"
1751 );
1752 }
1753 }
1754
1755 #[test]
1756 fn raster_size_in_bound_is_the_decode_bound() {
1757 assert!(!raster_size_in_bound(0));
1758 assert!(raster_size_in_bound(1));
1759 assert!(raster_size_in_bound(4096));
1760 assert!(!raster_size_in_bound(4097));
1761 assert!(!raster_size_in_bound(u32::MAX));
1762 }
1763
1764 #[test]
1765 fn raster_bytes_in_bound_is_the_decode_bound() {
1766 assert_eq!(raster_bytes_in_bound(0, 16), None);
1767 assert_eq!(raster_bytes_in_bound(16, 0), None);
1768 assert_eq!(raster_bytes_in_bound(3, 2), Some(24));
1769 assert_eq!(
1770 raster_bytes_in_bound(8192, 2048),
1771 Some(MAX_ICON_DECODE_BYTES)
1772 );
1773 assert_eq!(raster_bytes_in_bound(8192, 2049), None);
1774 assert_eq!(raster_bytes_in_bound(u32::MAX, u32::MAX), None);
1775 }
1776
1777 #[test]
1778 fn sf_symbols_loader_stores_the_colour() {
1779 let loader = SfSymbolsLoader::new(IconRole::ActionCopy).color(Rgba::new(10, 20, 30, 40));
1780 assert_eq!(loader.fg_color, Some([10, 20, 30]), "the alpha is ignored");
1781 let loader = loader.color_opt(None);
1782 assert_eq!(loader.fg_color, None);
1783 let loader = loader.color_opt(Some(Rgba::rgb(40, 50, 60)));
1784 assert_eq!(loader.fg_color, Some([40, 50, 60]));
1785 assert_eq!(SfSymbolsLoader::new(IconRole::ActionCopy).fg_color, None);
1786 }
1787
1788 #[test]
1789 fn sf_symbols_loader_stores_the_size() {
1790 assert_eq!(SfSymbolsLoader::new(IconRole::ActionCopy).size, None);
1791 assert_eq!(
1792 SfSymbolsLoader::new(IconRole::ActionCopy).size(48).size,
1793 Some(48)
1794 );
1795 }
1796
1797 #[test]
1798 fn segoe_fluent_loader_stores_the_colour() {
1799 let loader = SegoeFluentLoader::new(IconRole::ActionCopy).color(Rgba::new(10, 20, 30, 40));
1800 assert_eq!(loader.fg_color, Some([10, 20, 30]), "the alpha is ignored");
1801 let loader = loader.color_opt(None);
1802 assert_eq!(loader.fg_color, None);
1803 let loader = loader.color_opt(Some(Rgba::rgb(40, 50, 60)));
1804 assert_eq!(loader.fg_color, Some([40, 50, 60]));
1805 assert_eq!(SegoeFluentLoader::new(IconRole::ActionCopy).fg_color, None);
1806 }
1807
1808 #[test]
1809 fn segoe_fluent_loader_stores_the_size() {
1810 assert_eq!(SegoeFluentLoader::new(IconRole::ActionCopy).size, None);
1811 assert_eq!(
1812 SegoeFluentLoader::new(IconRole::ActionCopy).size(48).size,
1813 Some(48)
1814 );
1815 }
1816
1817 #[test]
1820 fn an_sf_symbol_loads_only_on_macos_with_system_icons() {
1821 let result = SfSymbolsLoader::new(IconRole::ActionCopy).load();
1822 assert_eq!(
1823 result.is_some(),
1824 cfg!(all(target_os = "macos", feature = "system-icons"))
1825 );
1826 }
1827
1828 #[test]
1829 #[cfg(feature = "material-icons")]
1830 fn bundled_icon_load_produces_cow_borrowed() {
1831 let result = MaterialLoader::new(IconRole::ActionCopy).load();
1832 assert!(
1833 matches!(result, Some(IconData::Svg(Cow::Borrowed(_)))),
1834 "bundled icon should produce Some(IconData::Svg(Cow::Borrowed(_)))"
1835 );
1836 }
1837}
1838
1839#[cfg(test)]
1840#[allow(clippy::unwrap_used, clippy::expect_used)]
1841mod load_system_icon_by_name_tests {
1842 #[test]
1843 #[cfg(feature = "material-icons")]
1844 fn system_icon_by_name_material() {
1845 let result = super::MaterialLoader::new("content_copy").load();
1846 assert!(
1847 result.is_some(),
1848 "content_copy should be found in Material set"
1849 );
1850 assert!(matches!(result.unwrap(), super::IconData::Svg(_)));
1851 }
1852
1853 #[test]
1854 #[cfg(feature = "lucide-icons")]
1855 fn system_icon_by_name_lucide() {
1856 let result = super::LucideLoader::new("copy").load();
1857 assert!(result.is_some(), "copy should be found in Lucide set");
1858 assert!(matches!(result.unwrap(), super::IconData::Svg(_)));
1859 }
1860
1861 #[test]
1862 #[cfg(feature = "material-icons")]
1863 fn system_icon_by_name_unknown_returns_none() {
1864 let result = super::MaterialLoader::new("nonexistent_xyz").load();
1865 assert!(result.is_none(), "nonexistent name should return None");
1866 }
1867
1868 #[test]
1869 fn system_icon_by_name_sf_on_linux_returns_none() {
1870 #[cfg(not(target_os = "macos"))]
1872 {
1873 let result = super::SfSymbolsLoader::new("doc.on.doc").load();
1874 assert!(
1875 result.is_none(),
1876 "SF Symbols should return None on non-macOS"
1877 );
1878 }
1879 }
1880}
1881
1882#[cfg(test)]
1883#[allow(clippy::unwrap_used, clippy::expect_used)]
1884mod load_custom_icon_tests {
1885 use super::*;
1886
1887 #[test]
1888 #[cfg(feature = "material-icons")]
1889 fn custom_icon_with_icon_role_material() {
1890 let provider: &dyn IconProvider = &IconRole::ActionCopy;
1891 let result = MaterialLoader::new(provider).load();
1892 assert!(
1893 result.is_some(),
1894 "IconRole::ActionCopy should load via material"
1895 );
1896 }
1897
1898 #[test]
1899 #[cfg(feature = "lucide-icons")]
1900 fn custom_icon_with_icon_role_lucide() {
1901 let provider: &dyn IconProvider = &IconRole::ActionCopy;
1902 let result = LucideLoader::new(provider).load();
1903 assert!(
1904 result.is_some(),
1905 "IconRole::ActionCopy should load via lucide"
1906 );
1907 }
1908
1909 #[test]
1910 fn custom_icon_no_cross_set_fallback() {
1911 #[derive(Debug)]
1913 struct NullProvider;
1914 impl IconProvider for NullProvider {
1915 fn icon_name(&self, _set: IconSet) -> Option<&str> {
1916 None
1917 }
1918 fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
1919 None
1920 }
1921 }
1922
1923 let provider: &dyn IconProvider = &NullProvider;
1924 let result = MaterialLoader::new(provider).load();
1925 assert!(
1926 result.is_none(),
1927 "NullProvider should return None (no cross-set fallback)"
1928 );
1929 }
1930
1931 #[test]
1934 fn a_custom_freedesktop_icon_does_not_take_the_providers_material_icon() {
1935 #[derive(Debug)]
1936 struct MaterialOnly;
1937 impl IconProvider for MaterialOnly {
1938 fn icon_name(&self, set: IconSet) -> Option<&str> {
1939 (set == IconSet::Material).then_some("content_copy")
1940 }
1941 fn icon_svg(&self, set: IconSet) -> Option<Cow<'static, [u8]>> {
1942 (set == IconSet::Material).then_some(Cow::Borrowed(
1943 br#"<svg xmlns="http://www.w3.org/2000/svg"/>"#,
1944 ))
1945 }
1946 }
1947
1948 let provider: &dyn IconProvider = &MaterialOnly;
1949 #[cfg(feature = "material-icons")]
1950 assert!(MaterialLoader::new(provider).load().is_some());
1951 assert_eq!(FreedesktopLoader::new(provider).load(), None);
1952 }
1953
1954 #[test]
1955 #[cfg(feature = "material-icons")]
1956 fn custom_icon_via_dyn_dispatch() {
1957 let boxed: Box<dyn IconProvider> = Box::new(IconRole::ActionCopy);
1958 let provider: &dyn IconProvider = &*boxed;
1959 let result = MaterialLoader::new(provider).load();
1960 assert!(
1961 result.is_some(),
1962 "dyn dispatch through Box<dyn IconProvider> should work"
1963 );
1964 }
1965
1966 #[test]
1967 #[cfg(feature = "material-icons")]
1968 fn custom_icon_bundled_svg_fallback() {
1969 #[derive(Debug)]
1971 struct SvgOnlyProvider;
1972 impl IconProvider for SvgOnlyProvider {
1973 fn icon_name(&self, _set: IconSet) -> Option<&str> {
1974 None
1975 }
1976 fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
1977 Some(Cow::Borrowed(b"<svg>test</svg>"))
1978 }
1979 }
1980
1981 let provider: &dyn IconProvider = &SvgOnlyProvider;
1982 let result = MaterialLoader::new(provider).load();
1983 assert!(
1984 result.is_some(),
1985 "provider with icon_svg should return Some"
1986 );
1987 match result.unwrap() {
1988 IconData::Svg(ref cow) => {
1989 assert_eq!(cow.as_ref(), b"<svg>test</svg>");
1990 }
1991 _ => panic!("expected IconData::Svg"),
1992 }
1993 }
1994}
1995
1996#[cfg(test)]
1997#[allow(clippy::unwrap_used, clippy::expect_used)]
1998mod runtime_set_icon_tests {
1999 use super::*;
2000
2001 const COLOR: Rgba = Rgba::rgb(0x12, 0x34, 0x56);
2003
2004 fn svg_text(data: IconData) -> String {
2005 match data {
2006 IconData::Svg(svg) => String::from_utf8(svg.into_owned()).unwrap(),
2007 other => panic!("expected IconData::Svg, got {other:?}"),
2008 }
2009 }
2010
2011 #[derive(Debug)]
2012 struct SvgOnlyProvider;
2013 impl IconProvider for SvgOnlyProvider {
2014 fn icon_name(&self, _set: IconSet) -> Option<&str> {
2015 None
2016 }
2017 fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
2018 Some(Cow::Borrowed(
2019 b"<svg viewBox=\"0 0 24 24\"><path d=\"M0 0\"/></svg>",
2020 ))
2021 }
2022 }
2023
2024 #[test]
2025 #[cfg(feature = "material-icons")]
2026 fn material_role_comes_back_in_the_colour() {
2027 let svg = svg_text(
2028 load_custom_icon(&IconRole::ActionCopy, IconSet::Material, Some(COLOR), None).unwrap(),
2029 );
2030 assert!(
2031 svg.contains("#123456"),
2032 "colour written into the bytes: {svg}"
2033 );
2034 }
2035
2036 #[test]
2037 #[cfg(feature = "lucide-icons")]
2038 fn lucide_role_comes_back_in_the_colour() {
2039 let svg = svg_text(
2040 load_custom_icon(&IconRole::ActionCopy, IconSet::Lucide, Some(COLOR), None).unwrap(),
2041 );
2042 assert!(
2043 svg.contains("#123456"),
2044 "colour written into the bytes: {svg}"
2045 );
2046 assert!(!svg.contains("currentColor"), "{svg}");
2047 }
2048
2049 #[test]
2050 #[cfg(feature = "material-icons")]
2051 fn no_colour_leaves_the_bundled_bytes() {
2052 let loaded =
2053 load_custom_icon(&IconRole::ActionCopy, IconSet::Material, None, None).unwrap();
2054 assert_eq!(
2055 loaded,
2056 MaterialLoader::new(IconRole::ActionCopy).load().unwrap()
2057 );
2058 }
2059
2060 #[test]
2061 fn provider_svg_comes_back_in_the_colour() {
2062 for set in [
2063 IconSet::Freedesktop,
2064 IconSet::SfSymbols,
2065 IconSet::SegoeFluent,
2066 IconSet::Material,
2067 IconSet::Lucide,
2068 ] {
2069 let svg = svg_text(load_custom_icon(&SvgOnlyProvider, set, Some(COLOR), None).unwrap());
2070 assert!(svg.contains("fill=\"#123456\""), "{set:?}: {svg}");
2071 }
2072 }
2073
2074 #[derive(Debug)]
2077 struct EditCopy(Option<&'static [u8]>);
2078 impl IconProvider for EditCopy {
2079 fn icon_name(&self, _set: IconSet) -> Option<&str> {
2080 Some("edit-copy")
2081 }
2082 fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
2083 self.0.map(Cow::Borrowed)
2084 }
2085 }
2086
2087 #[test]
2091 fn a_custom_icon_missing_from_the_icon_theme_given_is_the_providers_own() {
2092 let missing = Some("native-theme-no-such-theme");
2093 assert!(
2094 load_custom_icon_in(&EditCopy(None), IconSet::Freedesktop, missing, None, None)
2095 .is_none()
2096 );
2097 let own = b"<svg viewBox=\"0 0 24 24\"><path d=\"M0 0\"/></svg>";
2098 assert_eq!(
2099 load_custom_icon_in(
2100 &EditCopy(Some(own)),
2101 IconSet::Freedesktop,
2102 missing,
2103 None,
2104 None
2105 ),
2106 Some(IconData::Svg(Cow::Borrowed(own)))
2107 );
2108 }
2109
2110 #[cfg(all(target_os = "linux", feature = "system-icons"))]
2116 #[test]
2117 fn a_custom_icon_is_loaded_at_a_clamped_size() -> std::io::Result<()> {
2118 const NAME: &str =
2119 "icons::runtime_set_icon_tests::a_custom_icon_is_loaded_at_a_clamped_size";
2120 const ZERO: &str = r##"<svg xmlns="http://www.w3.org/2000/svg"/>"##;
2121 const SMALL: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"/>"##;
2122 const AT_512: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"/>"##;
2123 const AT_1024: &str =
2124 r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"/>"##;
2125 if native_theme_test_fixtures::in_child() {
2126 let svg = |svg: &'static str| Some(IconData::Svg(Cow::Borrowed(svg.as_bytes())));
2127 let load = |size| {
2128 load_custom_icon_in(
2129 &EditCopy(None),
2130 IconSet::Freedesktop,
2131 None,
2132 None,
2133 Some(size),
2134 )
2135 };
2136 assert_eq!(load(99_999), svg(AT_512), "asked for 99999");
2137 assert_eq!(load(MAX_ICON_SIZE + 1), svg(AT_512), "asked for 513");
2138 assert_eq!(load(1024), svg(AT_512), "asked for 1024");
2139 assert_eq!(load(0), svg(SMALL), "asked for 0");
2140 return Ok(());
2141 }
2142 let child = native_theme_test_fixtures::Child::kde("sized");
2143 native_theme_test_fixtures::run(NAME, child, |icons| {
2144 native_theme_test_fixtures::write_fixed_theme(
2145 icons,
2146 "sized",
2147 &[
2148 (0, "edit-copy.svg", ZERO.as_bytes()),
2149 (1, "edit-copy.svg", SMALL.as_bytes()),
2150 (512, "edit-copy.svg", AT_512.as_bytes()),
2151 (1024, "edit-copy.svg", AT_1024.as_bytes()),
2152 ],
2153 )
2154 })
2155 }
2156
2157 #[cfg(all(target_os = "linux", feature = "system-icons"))]
2163 #[test]
2164 fn a_custom_icon_is_looked_up_in_the_icon_theme_given() -> std::io::Result<()> {
2165 const NAME: &str =
2166 "icons::runtime_set_icon_tests::a_custom_icon_is_looked_up_in_the_icon_theme_given";
2167 const SYSTEM: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="#3daee9" d="M2 2h12v12H2z"/></svg>"##;
2168 const CHOSEN: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="#e01b24" d="M2 2h12v12H2z"/></svg>"##;
2169 if native_theme_test_fixtures::in_child() {
2170 let svg = |svg: &'static str| Some(IconData::Svg(Cow::Borrowed(svg.as_bytes())));
2171 let load = |theme| {
2172 load_custom_icon_in(&EditCopy(None), IconSet::Freedesktop, theme, None, None)
2173 };
2174 assert_eq!(load(None), svg(SYSTEM), "the system's theme");
2175 assert_eq!(load(Some("chosen")), svg(CHOSEN));
2176 assert_eq!(
2177 load(Some("native-theme-no-such-theme")),
2178 None,
2179 "an icon the theme given lacks is not taken from the system's"
2180 );
2181 return Ok(());
2182 }
2183 let child = native_theme_test_fixtures::Child::kde("system");
2184 native_theme_test_fixtures::run(NAME, child, |icons| {
2185 native_theme_test_fixtures::write_scalable_theme(
2186 icons,
2187 "system",
2188 &[("edit-copy", SYSTEM)],
2189 )?;
2190 native_theme_test_fixtures::write_scalable_theme(
2191 icons,
2192 "chosen",
2193 &[("edit-copy", CHOSEN)],
2194 )
2195 })
2196 }
2197
2198 #[test]
2199 #[cfg(feature = "material-icons")]
2200 fn a_themeless_set_ignores_the_icon_theme() {
2201 assert_eq!(
2202 load_custom_icon_in(
2203 &IconRole::ActionCopy,
2204 IconSet::Material,
2205 Some("breeze"),
2206 Some(COLOR),
2207 None
2208 ),
2209 load_custom_icon(&IconRole::ActionCopy, IconSet::Material, Some(COLOR), None)
2210 );
2211 }
2212
2213 #[test]
2214 fn unsized_provider_is_accepted() {
2215 let provider: &dyn IconProvider = &SvgOnlyProvider;
2216 assert!(load_custom_icon(provider, IconSet::Material, None, None).is_some());
2217 }
2218
2219 #[test]
2220 #[cfg(feature = "material-icons")]
2221 fn custom_id_in_the_dispatcher_is_coloured() {
2222 let provider: &dyn IconProvider = &IconRole::ActionCopy;
2223 let svg = svg_text(
2224 load_icon_in(
2225 IconId::Custom(provider),
2226 IconSet::Material,
2227 None,
2228 Some(COLOR),
2229 None,
2230 )
2231 .unwrap(),
2232 );
2233 assert!(svg.contains("#123456"), "{svg}");
2234 }
2235
2236 #[test]
2237 fn provider_with_nothing_is_none() {
2238 #[derive(Debug)]
2239 struct NullProvider;
2240 impl IconProvider for NullProvider {
2241 fn icon_name(&self, _set: IconSet) -> Option<&str> {
2242 None
2243 }
2244 fn icon_svg(&self, _set: IconSet) -> Option<Cow<'static, [u8]>> {
2245 None
2246 }
2247 }
2248 assert!(load_custom_icon(&NullProvider, IconSet::Material, Some(COLOR), None).is_none());
2249 }
2250
2251 fn svg_of(data: IconData) -> String {
2254 match data {
2255 IconData::Svg(svg) => String::from_utf8_lossy(&svg).into_owned(),
2256 _ => String::new(),
2257 }
2258 }
2259
2260 #[test]
2264 fn a_freedesktop_svg_s_bare_current_color_is_filled_in_the_colour() {
2265 let bare = br#"<svg xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M0 0h16v16H0z"/></svg>"#;
2266 let filled = fill_freedesktop_svg_data(IconData::Svg(Cow::Borrowed(bare)), Some(COLOR));
2267 assert_eq!(
2268 svg_of(filled),
2269 r##"<svg xmlns="http://www.w3.org/2000/svg"><path fill="#123456" d="M0 0h16v16H0z"/></svg>"##
2270 );
2271 }
2272
2273 #[test]
2278 fn a_freedesktop_svg_with_its_own_colour_is_left_as_it_is() {
2279 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>"#;
2280 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>"##;
2281 let bare = br#"<svg xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M0 0h16v16H0z"/></svg>"#;
2282 for (svg, color) in [
2283 (&styled[..], Some(COLOR)),
2284 (&full_colour[..], Some(COLOR)),
2285 (&bare[..], None),
2286 ] {
2287 let data = fill_freedesktop_svg_data(IconData::Svg(Cow::Borrowed(svg)), color);
2288 assert_eq!(svg_of(data), String::from_utf8_lossy(svg));
2289 }
2290 }
2291
2292 #[test]
2293 #[cfg(feature = "material-icons")]
2294 fn indicator_of_a_themeless_set_ignores_the_theme() {
2295 assert_eq!(
2296 load_icon_indicator(IconSet::Material, Some("breeze")),
2297 load_icon_indicator(IconSet::Material, None)
2298 );
2299 }
2300}
2301
2302#[cfg(test)]
2303#[allow(clippy::unwrap_used, clippy::expect_used)]
2304mod loading_indicator_tests {
2305 use super::*;
2306
2307 #[test]
2310 #[cfg(feature = "lucide-icons")]
2311 fn loading_indicator_lucide_returns_frames() {
2312 let anim = LucideLoader::load_indicator();
2313 assert!(anim.is_some(), "lucide should return Some");
2314 let anim = anim.unwrap();
2315 assert!(
2316 matches!(anim, AnimatedIcon::Frames(_)),
2317 "lucide should be pre-rotated Frames"
2318 );
2319 if let AnimatedIcon::Frames(data) = &anim {
2320 assert_eq!(data.frames().len(), 24);
2321 assert_eq!(data.frame_duration_ms().get(), 42);
2322 }
2323 }
2324
2325 #[test]
2328 #[cfg(all(target_os = "linux", feature = "system-icons"))]
2329 fn loading_indicator_freedesktop_depends_on_theme() {
2330 let anim = FreedesktopLoader::load_indicator(None);
2331 if let Some(anim) = anim {
2333 match anim {
2334 AnimatedIcon::Frames(data) => {
2335 assert!(
2336 !data.frames().is_empty(),
2337 "Frames variant should have at least one frame"
2338 );
2339 }
2340 AnimatedIcon::Transform(_) => {
2341 }
2343 }
2344 }
2345 }
2346
2347 #[test]
2349 fn loading_indicator_freedesktop_does_not_panic() {
2350 let _result = FreedesktopLoader::load_indicator(None);
2351 }
2352
2353 #[test]
2356 #[cfg(feature = "lucide-icons")]
2357 fn lucide_spinner_is_frames() {
2358 let anim = crate::spinners::lucide_spinner();
2359 assert!(
2360 matches!(anim, AnimatedIcon::Frames(_)),
2361 "lucide should be pre-rotated Frames"
2362 );
2363 }
2364}
2365
2366#[cfg(test)]
2369#[allow(clippy::unwrap_used, clippy::expect_used)]
2370mod icon_loader_tests {
2371 use super::*;
2372
2373 #[test]
2374 #[cfg(feature = "material-icons")]
2375 fn icon_loader_basic_role() {
2376 let icon = MaterialLoader::new(IconRole::ActionCopy).load();
2377 assert!(icon.is_some());
2378 }
2379
2380 #[test]
2381 #[cfg(feature = "material-icons")]
2382 fn icon_loader_by_name() {
2383 let icon = MaterialLoader::new("content_copy").load();
2384 assert!(icon.is_some());
2385 }
2386
2387 #[test]
2388 #[cfg(feature = "material-icons")]
2389 fn icon_loader_custom_provider() {
2390 let provider: &dyn IconProvider = &IconRole::ActionCopy;
2391 let icon = MaterialLoader::new(provider).load();
2392 assert!(icon.is_some());
2393 }
2394
2395 #[test]
2396 #[cfg(all(target_os = "linux", feature = "system-icons"))]
2397 fn freedesktop_loader_builder_chain_compiles() {
2398 let _ = FreedesktopLoader::new(IconRole::ActionSave)
2402 .size(48)
2403 .color(Rgba::rgb(0, 0, 0))
2404 .theme("Adwaita")
2405 .load();
2406 }
2407
2408 #[test]
2409 #[cfg(feature = "material-icons")]
2410 fn icon_loader_load_indicator() {
2411 let anim = MaterialLoader::load_indicator();
2412 assert!(anim.is_some());
2413 }
2414
2415 #[test]
2416 fn load_icon_free_fn_dispatches() {
2417 let role = IconRole::ActionCopy;
2418 for (set, loaded) in [
2419 (IconSet::Freedesktop, FreedesktopLoader::new(role).load()),
2420 (IconSet::SfSymbols, SfSymbolsLoader::new(role).load()),
2421 (IconSet::SegoeFluent, SegoeFluentLoader::new(role).load()),
2422 (IconSet::Material, MaterialLoader::new(role).load()),
2423 (IconSet::Lucide, LucideLoader::new(role).load()),
2424 ] {
2425 assert_eq!(load_icon(role, set), loaded, "{set}");
2426 }
2427 #[cfg(all(feature = "material-icons", feature = "lucide-icons"))]
2428 assert_ne!(
2429 load_icon(role, IconSet::Material),
2430 load_icon(role, IconSet::Lucide)
2431 );
2432 }
2433
2434 #[test]
2435 fn load_icon_indicator_free_fn_dispatches() {
2436 assert!(load_icon_indicator(IconSet::SfSymbols, None).is_none());
2438 assert!(load_icon_indicator(IconSet::SegoeFluent, None).is_none());
2439 }
2440}
2441
2442#[cfg(all(test, feature = "svg-rasterize", feature = "lucide-icons"))]
2443#[allow(clippy::unwrap_used, clippy::expect_used)]
2444mod spinner_rasterize_tests {
2445 use super::*;
2446
2447 #[test]
2448 fn lucide_spinner_icon_rasterizes() {
2449 let anim = crate::spinners::lucide_spinner();
2450 if let AnimatedIcon::Frames(data) = &anim {
2451 let first = data.frames().first();
2452 if let IconData::Svg(cow) = first {
2453 let result = crate::rasterize::rasterize_svg(cow, 24);
2454 assert!(result.is_ok(), "lucide loader should rasterize");
2455 if let Ok(IconData::Rgba(rgba)) = &result {
2456 assert!(
2457 rgba.data().iter().any(|&b| b != 0),
2458 "lucide loader rasterized to empty image"
2459 );
2460 }
2461 } else {
2462 panic!("lucide spinner frame should be Svg");
2463 }
2464 } else {
2465 panic!("lucide spinner should be Frames");
2466 }
2467 }
2468}
2469
2470#[cfg(test)]
2475mod icon_set_choice_tests {
2476 use super::*;
2477
2478 #[test]
2479 fn system_choice_names_the_detected_theme() {
2480 assert_eq!(
2481 system_choice_label(&Ok("breeze-dark".to_string())),
2482 "system (breeze-dark)"
2483 );
2484 }
2485
2486 #[test]
2487 fn system_choice_shows_a_failed_detection_as_unavailable() {
2488 let label = system_choice_label(&Err(crate::Error::PlatformUnsupported {
2489 platform: "the test's failing detection",
2490 }));
2491 assert_eq!(label, "system (unavailable)");
2492 }
2493
2494 #[test]
2498 fn a_failed_detections_label_leaves_the_reason_out() {
2499 let failures = [
2500 crate::Error::PlatformUnsupported {
2501 platform: "the test's failing detection",
2502 },
2503 crate::Error::WatchUnavailable {
2504 reason: "a reason long enough to fill a drop-down twice over",
2505 },
2506 ];
2507 for failure in failures {
2508 let reason = failure.to_string();
2509 let label = system_choice_label(&Err(failure));
2510 assert_eq!(label, "system (unavailable)", "for {reason:?}");
2511 assert!(!label.contains(&reason), "{label:?} quotes {reason:?}");
2512 }
2513 }
2514
2515 #[test]
2516 fn test_icon_set_choice_display_default() {
2517 let choice = IconSetChoice::Default("Adwaita".to_string());
2518 assert_eq!(choice.to_string(), "default (Adwaita)");
2519 }
2520
2521 #[test]
2522 fn test_icon_set_choice_display_material() {
2523 assert_eq!(IconSetChoice::Material.to_string(), "Material (bundled)");
2524 }
2525
2526 #[test]
2527 fn test_icon_set_choice_display_lucide() {
2528 assert_eq!(IconSetChoice::Lucide.to_string(), "Lucide (bundled)");
2529 }
2530
2531 #[test]
2532 fn test_icon_set_choice_display_freedesktop() {
2533 let choice = IconSetChoice::Freedesktop("breeze".to_string());
2534 assert_eq!(choice.to_string(), "breeze");
2535 }
2536
2537 #[test]
2538 fn test_icon_set_choice_follows_preset() {
2539 assert!(IconSetChoice::Default("Adwaita".to_string()).follows_preset());
2540 assert!(!IconSetChoice::System.follows_preset());
2541 assert!(!IconSetChoice::Freedesktop("breeze".to_string()).follows_preset());
2542 assert!(!IconSetChoice::Material.follows_preset());
2543 assert!(!IconSetChoice::Lucide.follows_preset());
2544 }
2545
2546 #[test]
2547 fn test_icon_set_choice_effective_icon_set() {
2548 let choice = IconSetChoice::Default("Adwaita".to_string());
2550 assert_eq!(
2551 choice.effective_icon_set(IconSet::Freedesktop),
2552 IconSet::Freedesktop
2553 );
2554 assert_eq!(
2555 choice.effective_icon_set(IconSet::Material),
2556 IconSet::Material
2557 );
2558
2559 let sys = IconSetChoice::System.effective_icon_set(IconSet::Material);
2561 assert_eq!(sys, system_icon_set());
2562
2563 let choice = IconSetChoice::Freedesktop("breeze".to_string());
2565 assert_eq!(
2566 choice.effective_icon_set(IconSet::Material),
2567 IconSet::Freedesktop
2568 );
2569
2570 assert_eq!(
2572 IconSetChoice::Material.effective_icon_set(IconSet::Freedesktop),
2573 IconSet::Material
2574 );
2575 assert_eq!(
2576 IconSetChoice::Lucide.effective_icon_set(IconSet::Freedesktop),
2577 IconSet::Lucide
2578 );
2579 }
2580
2581 #[test]
2582 fn test_icon_set_choice_freedesktop_theme() {
2583 assert_eq!(
2584 IconSetChoice::Default("Adwaita".to_string()).freedesktop_theme(),
2585 Some("Adwaita")
2586 );
2587 assert_eq!(
2588 IconSetChoice::Freedesktop("breeze".to_string()).freedesktop_theme(),
2589 Some("breeze")
2590 );
2591 assert_eq!(IconSetChoice::System.freedesktop_theme(), None);
2592 assert_eq!(IconSetChoice::Material.freedesktop_theme(), None);
2593 assert_eq!(IconSetChoice::Lucide.freedesktop_theme(), None);
2594 }
2595
2596 #[test]
2597 fn test_default_icon_choice_none() {
2598 assert_eq!(
2600 default_icon_choice(IconSet::Freedesktop, None),
2601 IconSetChoice::System
2602 );
2603 assert_eq!(
2604 default_icon_choice(IconSet::Material, None),
2605 IconSetChoice::System
2606 );
2607 }
2608
2609 #[test]
2610 fn test_default_icon_choice_bundled() {
2611 assert_eq!(
2613 default_icon_choice(IconSet::Material, Some("any-theme")),
2614 IconSetChoice::Default("any-theme".to_string())
2615 );
2616 assert_eq!(
2617 default_icon_choice(IconSet::Lucide, Some("any-theme")),
2618 IconSetChoice::Default("any-theme".to_string())
2619 );
2620 }
2621
2622 #[test]
2625 fn system_sets_are_available_only_where_their_loader_is_compiled() {
2626 let default =
2627 |set| default_icon_choice(set, Some("x")) == IconSetChoice::Default("x".into());
2628 assert_eq!(
2629 default(IconSet::SfSymbols),
2630 cfg!(all(target_os = "macos", feature = "system-icons"))
2631 );
2632 assert_eq!(
2633 default(IconSet::SegoeFluent),
2634 cfg!(all(target_os = "windows", feature = "system-icons"))
2635 );
2636 }
2637
2638 #[test]
2639 fn test_list_freedesktop_themes_no_panic() {
2640 let themes = list_freedesktop_themes();
2642 #[cfg(not(target_os = "linux"))]
2645 assert!(themes.is_empty());
2646 let _ = themes;
2648 }
2649}
2650
2651#[cfg(all(test, target_os = "linux"))]
2652#[allow(clippy::unwrap_used, reason = "a test fails by panicking")]
2653mod installed_theme_tests {
2654 use super::*;
2655 use std::path::{Path, PathBuf};
2656
2657 struct Bases {
2660 root: PathBuf,
2661 }
2662
2663 impl Bases {
2664 fn new(tag: &str) -> Self {
2665 let root = std::env::temp_dir().join(format!(
2666 "native-theme-installed-{}-{tag}",
2667 std::process::id()
2668 ));
2669 let _ = std::fs::remove_dir_all(&root);
2670 std::fs::create_dir_all(root.join("share/icons")).unwrap();
2671 Self { root }
2672 }
2673
2674 fn icons(&self) -> PathBuf {
2675 self.root.join("share/icons")
2676 }
2677
2678 fn add(&self, base: &Path, theme: &str, index: &str) {
2679 std::fs::create_dir_all(base.join(theme)).unwrap();
2680 std::fs::write(base.join(theme).join("index.theme"), index).unwrap();
2681 }
2682 }
2683
2684 impl Drop for Bases {
2685 fn drop(&mut self) {
2686 let _ = std::fs::remove_dir_all(&self.root);
2687 }
2688 }
2689
2690 #[test]
2694 fn an_installed_theme_lists_directories_in_its_icon_theme_group() {
2695 let bases = Bases::new("predicate");
2696 let icons = bases.icons();
2697 bases.add(
2698 &icons,
2699 "icons",
2700 "[Icon Theme]\nName=icons\nDirectories=actions\n",
2701 );
2702 bases.add(
2703 &icons,
2704 "spaced",
2705 "[Icon Theme]\nName=spaced\nDirectories = actions\n",
2706 );
2707 bases.add(
2708 &icons,
2709 "breeze_cursors",
2710 "[Icon Theme]\nName=Breeze Cursors\nInherits=breeze\n",
2711 );
2712 bases.add(&icons, "default", "[Icon Theme]\nInherits=Adwaita\n");
2713 bases.add(
2714 &icons,
2715 "elsewhere",
2716 "[Icon Theme]\nName=elsewhere\n\n[Other]\nDirectories=actions\n",
2717 );
2718 let dirs = [icons];
2719 assert!(has_theme_index("icons", &dirs));
2720 assert!(has_theme_index("spaced", &dirs));
2721 assert!(!has_theme_index("breeze_cursors", &dirs));
2722 assert!(!has_theme_index("default", &dirs));
2723 assert!(!has_theme_index("elsewhere", &dirs));
2724 assert!(!has_theme_index("missing", &dirs));
2725 assert_eq!(
2726 installed_themes_in(&dirs).into_iter().collect::<Vec<_>>(),
2727 ["icons", "spaced"]
2728 );
2729 }
2730
2731 #[test]
2733 fn breeze_cursors_is_not_available() {
2734 if !Path::new("/usr/share/icons/breeze_cursors/index.theme").exists() {
2735 eprintln!("skipped: breeze_cursors is not installed");
2736 return;
2737 }
2738 assert!(!is_freedesktop_theme_available("breeze_cursors"));
2739 assert!(!list_freedesktop_themes().contains(&"breeze_cursors".to_string()));
2740 }
2741
2742 #[test]
2744 fn listed_themes_are_available() {
2745 for theme in list_freedesktop_themes() {
2746 assert!(is_freedesktop_theme_available(&theme), "{theme}");
2747 }
2748 }
2749
2750 #[test]
2753 fn icon_base_dirs_put_the_user_s_first() {
2754 let bases = Bases::new("order");
2755 let home = bases.root.join("home");
2756 for dir in [".icons", ".local/share/icons"] {
2757 std::fs::create_dir_all(home.join(dir)).unwrap();
2758 }
2759 let system = bases.root.join("share");
2760 assert_eq!(
2761 icon_base_dirs_in(Some(&home), None, Some(system.as_os_str())),
2762 [
2763 home.join(".icons"),
2764 home.join(".local/share/icons"),
2765 system.join("icons")
2766 ]
2767 );
2768 }
2769
2770 #[test]
2774 fn the_first_index_theme_decides_whether_a_theme_is_installed() {
2775 let bases = Bases::new("first-index");
2776 let user = bases.root.join("home/.icons");
2777 bases.add(&user, "shadowed", "[Icon Theme]\nName=shadowed\n");
2778 bases.add(
2779 &bases.icons(),
2780 "shadowed",
2781 "[Icon Theme]\nName=shadowed\nDirectories=actions\n",
2782 );
2783 assert!(!has_theme_index("shadowed", &[user.clone(), bases.icons()]));
2784 assert!(has_theme_index("shadowed", &[bases.icons(), user]));
2785 }
2786}
2787
2788#[cfg(test)]
2789#[allow(
2790 clippy::unwrap_used,
2791 clippy::expect_used,
2792 clippy::panic,
2793 clippy::indexing_slicing,
2794 reason = "a test fails by panicking"
2795)]
2796mod colorize_tests {
2797 use super::{colorize_monochrome_svg, fill_current_color, sets_color};
2798 use crate::color::Rgba;
2799 use std::borrow::Cow;
2800
2801 const BLUE: Rgba = Rgba::new(51, 102, 204, 255);
2802 const RED: Rgba = Rgba::new(255, 0, 0, 255);
2803 const GREEN: Rgba = Rgba::new(20, 184, 82, 255);
2804
2805 #[test]
2806 fn colorize_svg_replaces_fill_black() {
2807 let svg = b"<svg><path fill=\"black\" d=\"M0 0h24v24H0z\"/></svg>";
2808 let result_str = String::from_utf8(colorize_monochrome_svg(svg, BLUE)).unwrap();
2809 assert!(
2810 !result_str.contains("fill=\"black\""),
2811 "fill=\"black\" should be replaced, got: {result_str}"
2812 );
2813 assert!(
2814 result_str.contains("fill=\"#3366cc\""),
2815 "should contain the hex fill, got: {result_str}"
2816 );
2817 }
2818
2819 #[test]
2820 fn colorize_svg_replaces_fill_hex_black() {
2821 let svg = b"<svg><rect fill=\"#000000\" width=\"24\" height=\"24\"/></svg>";
2822 let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
2823 assert!(
2824 !result_str.contains("#000000"),
2825 "fill=\"#000000\" should be replaced, got: {result_str}"
2826 );
2827 assert!(
2828 result_str.contains("fill=\"#ff0000\""),
2829 "should contain the hex fill, got: {result_str}"
2830 );
2831 }
2832
2833 #[test]
2834 fn colorize_svg_replaces_fill_short_hex_black() {
2835 let svg = b"<svg><rect fill=\"#000\" width=\"24\" height=\"24\"/></svg>";
2836 let result_str = String::from_utf8(colorize_monochrome_svg(svg, GREEN)).unwrap();
2837 assert!(
2838 !result_str.contains("fill=\"#000\""),
2839 "fill=\"#000\" should be replaced, got: {result_str}"
2840 );
2841 assert!(
2842 result_str.contains("fill=\"#14b852\""),
2843 "should contain the hex fill, got: {result_str}"
2844 );
2845 }
2846
2847 #[test]
2848 fn colorize_svg_current_color_still_works() {
2849 let svg = b"<svg><path stroke=\"currentColor\" d=\"M0 0\"/></svg>";
2850 let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
2851 assert!(
2852 !result_str.contains("currentColor"),
2853 "currentColor should be replaced"
2854 );
2855 assert!(
2856 result_str.contains("#ff0000"),
2857 "should contain the hex colour"
2858 );
2859 }
2860
2861 #[test]
2862 fn colorize_svg_implicit_black_still_works() {
2863 let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M0 0\"/></svg>";
2865 let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
2866 assert!(
2867 result_str.contains("fill=\"#ff0000\""),
2868 "should inject fill into root svg tag, got: {result_str}"
2869 );
2870 }
2871
2872 #[test]
2873 fn colorize_svg_non_utf8_returns_original() {
2874 let mut svg = b"<svg><path fill=\"black\" d=\"M0 0\"/>".to_vec();
2876 svg.push(0xFF); svg.extend_from_slice(b"</svg>");
2878 let result = colorize_monochrome_svg(&svg, RED);
2879 assert_eq!(result, svg, "non-UTF-8 input should be returned unchanged");
2880 }
2881
2882 #[test]
2883 fn colorize_svg_replaces_stroke_black() {
2884 let svg = b"<svg><path stroke=\"black\" d=\"M0 0h24\"/></svg>";
2885 let result_str = String::from_utf8(colorize_monochrome_svg(svg, BLUE)).unwrap();
2886 assert!(
2887 !result_str.contains("stroke=\"black\""),
2888 "stroke=\"black\" should be replaced, got: {result_str}"
2889 );
2890 assert!(
2891 result_str.contains("stroke=\"#3366cc\""),
2892 "should contain the hex stroke, got: {result_str}"
2893 );
2894 }
2895
2896 #[test]
2897 fn colorize_svg_replaces_stroke_hex_black() {
2898 let svg = b"<svg><line stroke=\"#000000\" x1=\"0\" y1=\"0\" x2=\"24\" y2=\"24\"/></svg>";
2899 let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
2900 assert!(
2901 !result_str.contains("#000000"),
2902 "stroke=\"#000000\" should be replaced"
2903 );
2904 assert!(
2905 result_str.contains("stroke=\"#ff0000\""),
2906 "should contain the hex stroke, got: {result_str}"
2907 );
2908 }
2909
2910 #[test]
2911 fn colorize_self_closing_svg_produces_valid_xml() {
2912 let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\" />";
2914 let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
2915 assert!(
2916 result_str.contains("fill=\"#ff0000\""),
2917 "should inject fill, got: {result_str}"
2918 );
2919 assert!(
2920 !result_str.contains("/ fill="),
2921 "fill must be before '/', got: {result_str}"
2922 );
2923 assert!(
2924 result_str.trim().ends_with("/>"),
2925 "should remain self-closing, got: {result_str}"
2926 );
2927 }
2928
2929 #[test]
2930 fn colorize_svg_with_fill_white_root() {
2931 let svg = b"<svg fill=\"white\"><path/></svg>";
2933 let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
2934 assert!(
2935 result_str.contains("fill=\"white\""),
2936 "fill=\"white\" should be preserved, got: {result_str}"
2937 );
2938 }
2939
2940 #[test]
2941 fn colorize_svg_with_fill_none_root() {
2942 let svg = b"<svg fill=\"none\"><path stroke=\"black\"/></svg>";
2944 let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
2945 assert!(
2946 !result_str.contains("stroke=\"black\""),
2947 "stroke=\"black\" should be replaced, got: {result_str}"
2948 );
2949 assert!(
2950 result_str.contains("stroke=\"#ff0000\""),
2951 "should contain the hex stroke, got: {result_str}"
2952 );
2953 }
2954
2955 #[test]
2957 fn colorize_svg_discards_alpha() {
2958 let svg = b"<svg><path fill=\"black\"/></svg>";
2959 let translucent = Rgba::new(255, 0, 0, 40);
2960 assert_eq!(
2961 colorize_monochrome_svg(svg, translucent),
2962 colorize_monochrome_svg(svg, RED)
2963 );
2964 }
2965
2966 #[test]
2967 fn colorize_svg_replaces_stroke_short_hex_black() {
2968 let svg = b"<svg><path stroke=\"#000\" d=\"M0 0\"/></svg>";
2969 let result_str = String::from_utf8(colorize_monochrome_svg(svg, BLUE)).unwrap();
2970 assert!(
2971 result_str.contains("stroke=\"#3366cc\""),
2972 "stroke=\"#000\" should be replaced, got: {result_str}"
2973 );
2974 }
2975
2976 #[test]
2977 fn colorize_svg_keeps_a_root_fill_and_injects_none() {
2978 let svg = b"<svg fill=\"red\"><path d=\"M0 0\"/></svg>";
2979 let result_str = String::from_utf8(colorize_monochrome_svg(svg, GREEN)).unwrap();
2980 assert!(result_str.contains("fill=\"red\""), "got: {result_str}");
2982 assert!(!result_str.contains("#14b852"), "got: {result_str}");
2983 }
2984
2985 #[test]
2986 fn colorize_svg_mixed_fill_attributes() {
2987 let svg = b"<svg><rect fill=\"black\" width=\"10\" height=\"10\"/><rect fill=\"red\" width=\"10\" height=\"10\"/></svg>";
2989 let result_str = String::from_utf8(colorize_monochrome_svg(svg, GREEN)).unwrap();
2990 assert!(
2991 !result_str.contains("fill=\"black\""),
2992 "fill=\"black\" should be replaced, got: {result_str}"
2993 );
2994 assert!(
2995 result_str.contains("fill=\"red\""),
2996 "fill=\"red\" should be preserved, got: {result_str}"
2997 );
2998 }
2999
3000 #[test]
3001 fn colorize_self_closing_svg_without_a_space_produces_valid_xml() {
3002 let svg = b"<svg xmlns='http://www.w3.org/2000/svg'/>";
3004 let result_str = String::from_utf8(colorize_monochrome_svg(svg, RED)).unwrap();
3005 assert!(
3006 result_str.contains("fill=\"#ff0000\"") && result_str.ends_with("/>"),
3007 "self-closing SVG should remain valid XML, got: {result_str}"
3008 );
3009 assert!(
3010 !result_str.contains("/ fill="),
3011 "fill should not be between / and >, got: {result_str}"
3012 );
3013 }
3014
3015 #[test]
3016 fn fill_current_color_fills_an_unset_current_color() {
3017 let svg = br#"<svg><path fill="currentColor" stroke="currentColor"/></svg>"#;
3018 let filled = fill_current_color(svg, Rgba::new(51, 102, 204, 7));
3019 assert_eq!(
3020 &*filled,
3021 br##"<svg><path fill="#3366cc" stroke="#3366cc"/></svg>"##
3022 );
3023 }
3024
3025 #[test]
3026 fn fill_current_color_borrows_what_it_leaves_alone() {
3027 let plain = br##"<svg><path fill="#2e3436"/></svg>"##;
3028 let styled = br#"<svg><style>.ColorScheme-Text { color:#232629; }</style><path class="ColorScheme-Text" fill="currentColor"/></svg>"#;
3029 let attribute = br##"<svg color="#fff"><path fill="currentColor"/></svg>"##;
3030 let not_utf8 = b"<svg>\xff currentColor</svg>";
3031 for svg in [&plain[..], &styled[..], &attribute[..], ¬_utf8[..]] {
3032 assert!(
3033 matches!(fill_current_color(svg, BLUE), Cow::Borrowed(b) if b == svg),
3034 "{}",
3035 String::from_utf8_lossy(svg)
3036 );
3037 }
3038 }
3039
3040 #[test]
3041 fn sets_color_reads_only_the_color_property() {
3042 assert!(!sets_color(r#"<svg><path fill="currentColor"/></svg>"#));
3043 assert!(sets_color(
3044 r##"<svg color="#fff"><path fill="currentColor"/></svg>"##
3045 ));
3046 assert!(sets_color("<svg><style>.a { color : #fff }</style></svg>"));
3047 assert!(sets_color(r#"<svg><path style="color:#fff"/></svg>"#));
3048 assert!(!sets_color(
3049 r##"<svg><stop stop-color="#fff"/><path fill="currentColor"/></svg>"##
3050 ));
3051 assert!(!sets_color(
3052 r##"<svg flood-color="#fff" lighting-color="#fff" solid-color="#fff"/>"##
3053 ));
3054 assert!(!sets_color(
3055 r##"<svg text-decoration-color="#fff" pagecolor="#fff" bordercolor="#fff"/>"##
3056 ));
3057 assert!(!sets_color(
3058 r#"<svg id="color" class="color"><path fill="currentColor"/></svg>"#
3059 ));
3060 assert!(!sets_color(r#"<svg color-interpolation="sRGB"/>"#));
3061 }
3062}