Debian Codegraph @

src/themes.rs

raw symbols SCIP
1 /*
2 * Copyright 2020-2024 Andrey Kutejko <[email protected]>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, see <http://www.gnu.org/licenses/>.
16 *
17 * For more details see the file COPYING.
18 */
19
20 use crate::theme::Theme;
21 use crate::utils::list_directory;
22 use gtk::{gio, gio::prelude::*};
23 use std::path::Path;
24
25 pub fn themes_from_directory(directory: &Path) -> gio::ListStore {
26 let files = list_directory(directory).unwrap_or_else(|err| {
27 eprintln!(
28 "Failed to list theme directory {}: {}",
29 directory.display(),
30 err
31 );
32 Vec::new()
33 });
34
35 let themes = gio::ListStore::new::<Theme>();
36 for path in files {
37 match Theme::from_file(&path) {
38 Ok(theme) => {
39 themes.append(&theme);
40 }
41 Err(error) => {
42 eprintln!("Failed to load theme '{}': {}", path.display(), error)
43 }
44 }
45 }
46 themes
47 }
48
49 pub fn find_by_name(themes: &gio::ListModel, name: &str) -> Option<(u32, Theme)> {
50 let size = themes.n_items();
51 for index in 0..size {
52 let Some(theme) = themes.item(index).and_downcast::<Theme>() else {
53 continue;
54 };
55 if theme.name() == name || theme.path().file_name().is_some_and(|n| n == name) {
56 return Some((index, theme));
57 }
58 }
59 None
60 }
61
62 const DEFAULT_THEME: &str = "robots.svg";
63
64 pub fn find_best_match(themes: &gio::ListModel, name: &str) -> Result<Theme, &'static str> {
65 if let Some((_, theme)) = find_by_name(themes, name) {
66 return Ok(theme);
67 }
68 if let Some((_, theme)) = find_by_name(themes, DEFAULT_THEME) {
69 return Ok(theme);
70 }
71 Err("No theme was found.")
72 }