1use std::cell::{RefCell, RefMut};
18use std::collections::hash_map::DefaultHasher;
19use std::collections::{HashMap, HashSet};
20use std::ffi::OsString;
21use std::hash::{Hash, Hasher};
22use std::path::{Path, PathBuf};
23use std::rc::Rc;
24
25use crate::icons::read_capped;
26
27const EXTENSIONS: [&str; 2] = ["png", "svg"];
29
30const REMEMBERED: usize = 1024;
33
34const MAX_INDEX_BYTES: u64 = 1024 * 1024;
36
37#[derive(Clone)]
41pub struct IconLookup(Rc<RefCell<Lookup>>);
42
43pub(crate) struct Lookup {
44 pub(crate) theme: String,
45 pub(crate) themes: Themes,
46}
47
48impl IconLookup {
49 pub(crate) fn new(themes: Themes) -> IconLookup {
50 IconLookup(Rc::new(RefCell::new(Lookup {
51 theme: crate::icons::DEFAULT_THEME.to_owned(),
52 themes,
53 })))
54 }
55
56 pub fn find(&self, name: &str, size: u32) -> Option<PathBuf> {
60 let mut lookup = self.borrow();
61 let Lookup { theme, themes } = &mut *lookup;
62 themes.find(theme, name, size, 1)
63 }
64
65 pub fn set_theme(&self, theme: String) {
67 self.borrow().theme = theme;
68 }
69
70 pub(crate) fn borrow(&self) -> RefMut<'_, Lookup> {
72 self.0.borrow_mut()
73 }
74}
75
76pub(crate) struct Themes {
78 bases: Vec<PathBuf>,
79 themes: HashMap<String, Option<Rc<Theme>>>,
81 found: HashMap<(String, String, u32, u32), Found>,
83 tick: u64,
85 listings: HashMap<PathBuf, HashSet<u64>>,
87 xpm: HashSet<String>,
89 read: u64,
91 checked: u64,
93}
94
95struct Found {
96 path: Option<PathBuf>,
97 used: u64,
99}
100
101struct Theme {
102 roots: Vec<PathBuf>,
104 inherits: Vec<String>,
105 directories: Vec<Directory>,
106}
107
108struct Directory {
109 path: String,
110 size: u32,
111 scale: u32,
112 kind: Kind,
113 min: u32,
114 max: u32,
115 threshold: u32,
116}
117
118#[derive(Clone, Copy, PartialEq, Eq)]
119enum Kind {
120 Fixed,
121 Scalable,
122 Threshold,
123}
124
125impl Themes {
126 pub(crate) fn new(mut bases: Vec<PathBuf>) -> Themes {
128 let mut seen = HashSet::new();
129 bases.retain(|base| seen.insert(base.clone()));
130 Themes {
131 bases,
132 themes: HashMap::new(),
133 found: HashMap::new(),
134 tick: 0,
135 listings: HashMap::new(),
136 xpm: HashSet::new(),
137 read: 0,
138 checked: 0,
139 }
140 }
141
142 pub(crate) fn from_env() -> Themes {
144 let var = |name| std::env::var_os(name).filter(|value| !value.is_empty());
145 Themes::new(bases(
146 var("HOME").map(PathBuf::from),
147 var("XDG_DATA_HOME"),
148 var("XDG_DATA_DIRS"),
149 ))
150 }
151
152 #[cfg(test)]
155 pub(crate) fn work(&self) -> (u64, u64, usize) {
156 (self.read, self.checked, self.found.len())
157 }
158
159 pub(crate) fn find(&mut self, theme: &str, name: &str, size: u32, scale: u32) -> Option<PathBuf> {
162 self.tick += 1;
163 let key = (theme.to_owned(), name.to_owned(), size, scale);
164 if let Some(found) = self.found.get_mut(&key) {
165 found.used = self.tick;
166 return found.path.clone();
167 }
168 let path = if safe(name) {
169 let mut visited = HashSet::new();
170 self
171 .in_theme(theme, name, size, scale, &mut visited)
172 .or_else(|| self.in_theme("hicolor", name, size, scale, &mut visited))
173 .or_else(|| self.unthemed(name, &EXTENSIONS))
174 } else {
175 None
176 };
177 if path.is_none() && safe(name) && self.only_xpm(name) && self.xpm.insert(name.to_owned()) {
178 tracing::warn!(name, "icon is only available as XPM, which can't be drawn");
179 }
180 if self.found.len() >= REMEMBERED {
181 let oldest = self
182 .found
183 .iter()
184 .min_by_key(|(_, found)| found.used)
185 .map(|(key, _)| key.clone());
186 if let Some(oldest) = oldest {
187 self.found.remove(&oldest);
188 }
189 }
190 let used = self.tick;
191 self.found.insert(
192 key,
193 Found {
194 path: path.clone(),
195 used,
196 },
197 );
198 path
199 }
200
201 fn in_theme(
204 &mut self,
205 theme: &str,
206 name: &str,
207 size: u32,
208 scale: u32,
209 visited: &mut HashSet<String>,
210 ) -> Option<PathBuf> {
211 if !visited.insert(theme.to_owned()) {
212 return None;
213 }
214 let parsed = self.theme(theme)?;
215 self.lookup(&parsed, name, size, scale).or_else(|| {
216 parsed
217 .inherits
218 .iter()
219 .find_map(|parent| self.in_theme(parent, name, size, scale, visited))
220 })
221 }
222
223 fn lookup(&mut self, parsed: &Theme, name: &str, size: u32, scale: u32) -> Option<PathBuf> {
227 let mut ranked: Vec<(u64, &Directory)> = parsed
228 .directories
229 .iter()
230 .map(|directory| {
231 let rank = if directory.matches(size, scale) {
232 0
233 } else {
234 directory.distance(size, scale).saturating_add(1)
235 };
236 (rank, directory)
237 })
238 .collect();
239 ranked.sort_by_key(|(rank, _)| *rank);
240 ranked
241 .iter()
242 .find_map(|(_, directory)| self.file_in(&parsed.roots, &directory.path, name, &EXTENSIONS))
243 }
244
245 fn file_in(
248 &mut self,
249 roots: &[PathBuf],
250 subdirectory: &str,
251 name: &str,
252 extensions: &[&str],
253 ) -> Option<PathBuf> {
254 roots.iter().find_map(|root| {
255 let directory = root.join(subdirectory);
256 extensions
257 .iter()
258 .map(|extension| format!("{name}.{extension}"))
259 .find(|file| self.has(&directory, file))
260 .map(|file| directory.join(file))
261 })
262 }
263
264 fn has(&mut self, directory: &Path, file: &str) -> bool {
268 self.checked += 1;
269 if !self.listings.contains_key(directory) {
270 self.read += 1;
271 let names = std::fs::read_dir(directory)
272 .map(|entries| {
273 entries
274 .filter_map(Result::ok)
275 .filter_map(|entry| entry.file_name().to_str().map(hashed))
276 .collect()
277 })
278 .unwrap_or_default();
279 self.listings.insert(directory.to_owned(), names);
280 }
281 self
282 .listings
283 .get(directory)
284 .is_some_and(|names| names.contains(&hashed(file)))
285 && directory.join(file).is_file()
286 }
287
288 fn unthemed(&mut self, name: &str, extensions: &[&str]) -> Option<PathBuf> {
290 let bases = self.bases.clone();
291 self.file_in(&bases, "", name, extensions)
292 }
293
294 fn only_xpm(&mut self, name: &str) -> bool {
297 let directories: Vec<(Rc<Theme>, usize)> = self
298 .themes
299 .values()
300 .flatten()
301 .flat_map(|theme| (0..theme.directories.len()).map(|index| (Rc::clone(theme), index)))
302 .collect();
303 self.unthemed(name, &["xpm"]).is_some()
304 || directories.into_iter().any(|(theme, index)| {
305 let subdirectory = &theme.directories[index].path;
306 self
307 .file_in(&theme.roots, subdirectory, name, &["xpm"])
308 .is_some()
309 })
310 }
311
312 fn theme(&mut self, theme: &str) -> Option<Rc<Theme>> {
315 if let Some(parsed) = self.themes.get(theme) {
316 return parsed.clone();
317 }
318 let roots: Vec<PathBuf> = if safe(theme) {
319 self
320 .bases
321 .iter()
322 .map(|base| base.join(theme))
323 .filter(|root| root.is_dir())
324 .collect()
325 } else {
326 Vec::new()
327 };
328 let parsed = roots
329 .iter()
330 .find_map(|root| {
331 let path = root.join("index.theme");
332 read_capped(&path, MAX_INDEX_BYTES)
333 .ok()
334 .map(|bytes| parse(&String::from_utf8_lossy(&bytes), &path))
335 })
336 .map(|(inherits, directories)| {
337 Rc::new(Theme {
338 roots: roots.clone(),
339 inherits,
340 directories,
341 })
342 });
343 if parsed.is_none() && theme != "hicolor" {
344 tracing::warn!(theme, "icon theme not found");
345 }
346 self.themes.insert(theme.to_owned(), parsed.clone());
347 parsed
348 }
349}
350
351fn hashed(name: &str) -> u64 {
353 let mut hasher = DefaultHasher::new();
354 name.hash(&mut hasher);
355 hasher.finish()
356}
357
358pub(crate) fn bases(
364 home: Option<PathBuf>,
365 data_home: Option<OsString>,
366 data_dirs: Option<OsString>,
367) -> Vec<PathBuf> {
368 let mut bases = Vec::new();
369 bases.extend(home.as_ref().map(|home| home.join(".icons")));
370 let data_home = data_home
371 .map(PathBuf::from)
372 .filter(|path| path.is_absolute())
373 .or_else(|| home.map(|home| home.join(".local/share")));
374 bases.extend(data_home.map(|path| path.join("icons")));
375 let data_dirs = data_dirs.unwrap_or_else(|| "/usr/local/share:/usr/share".into());
376 bases.extend(
377 std::env::split_paths(&data_dirs)
378 .filter(|path| path.is_absolute())
379 .map(|path| path.join("icons")),
380 );
381 bases.push(PathBuf::from("/usr/share/pixmaps"));
382 bases
383}
384
385fn safe(name: &str) -> bool {
387 !name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\0'])
388}
389
390fn parse(text: &str, path: &Path) -> (Vec<String>, Vec<Directory>) {
393 let mut sections: HashMap<&str, HashMap<&str, &str>> = HashMap::new();
394 let mut section = None;
395 for line in text.lines().map(str::trim) {
396 if line.is_empty() || line.starts_with('#') {
397 continue;
398 }
399 if let Some(name) = line
400 .strip_prefix('[')
401 .and_then(|line| line.strip_suffix(']'))
402 {
403 section = Some(name);
404 } else if let (Some(section), Some((key, value))) = (section, line.split_once('=')) {
405 sections
406 .entry(section)
407 .or_default()
408 .insert(key.trim(), value.trim());
409 } else {
410 tracing::warn!(path = %path.display(), line, "skipping a line in an icon theme");
411 }
412 }
413 let header = sections.get("Icon Theme");
414 let list = |key| {
415 header
416 .and_then(|header| header.get(key))
417 .into_iter()
418 .flat_map(|value| value.split(','))
419 .map(str::trim)
420 .filter(|item| !item.is_empty())
421 };
422 let mut seen = HashSet::new();
423 let directories = list("Directories")
424 .chain(list("ScaledDirectories"))
425 .filter(|name| seen.insert(*name))
426 .filter_map(|name| {
427 let inside = !name.starts_with('/')
429 && !name.contains('\0')
430 && name.split('/').all(|part| part != "..");
431 if !inside {
432 tracing::warn!(path = %path.display(), directory = name, "skipping an icon directory outside the theme");
433 return None;
434 }
435 let directory = sections.get(name).and_then(|keys| Directory::parse(name, keys));
436 if directory.is_none() {
437 tracing::warn!(path = %path.display(), directory = name, "skipping an icon directory with no usable Size");
438 }
439 directory
440 })
441 .collect();
442 (list("Inherits").map(str::to_owned).collect(), directories)
443}
444
445impl Directory {
446 fn parse(path: &str, keys: &HashMap<&str, &str>) -> Option<Directory> {
447 let number = |key| keys.get(key).and_then(|value| value.parse::<u32>().ok());
448 let size = number("Size")?;
449 Some(Directory {
450 path: path.to_owned(),
451 size,
452 scale: number("Scale").unwrap_or(1).max(1),
453 kind: match keys.get("Type").copied() {
454 Some("Fixed") => Kind::Fixed,
455 Some("Scalable") => Kind::Scalable,
456 _ => Kind::Threshold,
457 },
458 min: number("MinSize").unwrap_or(size),
459 max: number("MaxSize").unwrap_or(size),
460 threshold: number("Threshold").unwrap_or(2),
461 })
462 }
463
464 fn matches(&self, size: u32, scale: u32) -> bool {
466 self.scale == scale
467 && match self.kind {
468 Kind::Fixed => self.size == size,
469 Kind::Scalable => (self.min..=self.max).contains(&size),
470 Kind::Threshold => {
471 self.size.saturating_sub(self.threshold) <= size
472 && size <= self.size.saturating_add(self.threshold)
473 }
474 }
475 }
476
477 fn distance(&self, size: u32, scale: u32) -> u64 {
479 let wanted = u64::from(size) * u64::from(scale);
480 let at = |value: u32| u64::from(value) * u64::from(self.scale);
481 let (low, high) = match self.kind {
482 Kind::Fixed => return at(self.size).abs_diff(wanted),
483 Kind::Scalable => (at(self.min), at(self.max)),
484 Kind::Threshold => (
485 at(self.size.saturating_sub(self.threshold)),
486 at(self.size.saturating_add(self.threshold)),
487 ),
488 };
489 if wanted < low {
491 at(self.min).saturating_sub(wanted)
492 } else if wanted > high {
493 wanted.saturating_sub(at(self.max))
494 } else {
495 0
496 }
497 }
498}