Debian Codegraph @

src/utils.rs

raw symbols SCIP
1 /*
2 * Copyright 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 gtk::{gio, glib, prelude::*};
21 use std::cell::RefCell;
22 use std::fs;
23 use std::io;
24 use std::path::{Path, PathBuf};
25 use std::time::{SystemTime, UNIX_EPOCH};
26
27 pub fn list_directory(directory: &Path) -> io::Result<Vec<PathBuf>> {
28 let mut files = Vec::new();
29 for entry in fs::read_dir(directory)? {
30 files.push(entry?.path());
31 }
32 Ok(files)
33 }
34
35 pub fn now() -> u64 {
36 SystemTime::now()
37 .duration_since(UNIX_EPOCH)
38 .map_or(0, |t| t.as_secs())
39 }
40
41 pub trait SettingsWarnExt {
42 fn set_string_or_warn(&self, key: &str, value: &str);
43 fn set_int_or_warn(&self, key: &str, value: i32);
44 fn set_boolean_or_warn(&self, key: &str, value: bool);
45 }
46
47 fn warn_failed_set(key: &str, error: &dyn std::error::Error) {
48 glib::g_warning!(None, "Failed to save setting key {}: {}", key, error);
49 }
50
51 impl SettingsWarnExt for gio::Settings {
52 fn set_string_or_warn(&self, key: &str, value: &str) {
53 if let Err(ref error) = self.set_string(key, value) {
54 warn_failed_set(key, error);
55 }
56 }
57
58 fn set_int_or_warn(&self, key: &str, value: i32) {
59 if let Err(ref error) = self.set_int(key, value) {
60 warn_failed_set(key, error);
61 }
62 }
63
64 fn set_boolean_or_warn(&self, key: &str, value: bool) {
65 if let Err(ref error) = self.set_boolean(key, value) {
66 warn_failed_set(key, error);
67 }
68 }
69 }
70
71 pub fn settings_aware_widget<W, F>(
72 widget: &W,
73 settings: &gio::Settings,
74 settings_key: Option<&str>,
75 f: F,
76 ) where
77 W: IsA<gtk::Widget>,
78 W: glib::clone::Downgrade,
79 <W as glib::clone::Downgrade>::Weak: glib::clone::Upgrade<Strong = W>,
80 F: Fn(&W, &gio::Settings) + 'static,
81 {
82 let signal_handler_id = settings.connect_changed(
83 settings_key,
84 glib::clone!(
85 #[weak]
86 widget,
87 move |s, _| (f)(&widget, s)
88 ),
89 );
90 widget.connect_destroy({
91 let signal_handler_id = RefCell::new(Some(signal_handler_id));
92 let settings = settings.clone();
93 move |_| {
94 if let Some(signal_handler_id) = signal_handler_id.take() {
95 settings.disconnect(signal_handler_id);
96 }
97 }
98 });
99 }