Debian Codegraph @

src/utils.rs

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Fragments - utils.rs
2 // Copyright (C) 2022-2023 Felix Häcker <[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 <https://www.gnu.org/licenses/>.
16
17 use std::path::PathBuf;
18
19 use adw::prelude::*;
20 use gio::SimpleAction;
21 use glib::{clone, BindingFlags};
22 use gtk::{gio, glib};
23 use transmission_gobject::{TrTorrent, TrTorrentStatus};
24
25 use crate::backend::{FrgConnectionManager, FrgDirectoryType};
26 use crate::i18n::{i18n, ni18n_f};
27 use crate::ui::{FrgApplicationWindow, FrgTorrentDialog};
28
29 pub fn inapp_notification(text: &str, widget: Option<&gtk::Widget>) {
30 let toast = adw::Toast::builder().title(text).timeout(10).build();
31
32 if let Some(widget) = widget {
33 // Is `widget` part of a PreferencesDialog?
34 if let Some(preferences_dialog) = widget.ancestor(adw::PreferencesDialog::static_type()) {
35 let preferences_dialog = preferences_dialog
36 .downcast::<adw::PreferencesDialog>()
37 .unwrap();
38 preferences_dialog.add_toast(toast);
39 return;
40 }
41
42 // Is `widget` a FrgTorrentDialog?
43 if let Some(torrent_dialog) = widget.downcast_ref::<FrgTorrentDialog>() {
44 torrent_dialog.toast_overlay().add_toast(toast);
45 return;
46 }
47 }
48
49 // Fallback to FrgApplicationWindow
50 let window = FrgApplicationWindow::default();
51 window.toast_overlay().add_toast(toast)
52 }
53
54 pub fn system_notification<T: AsRef<str>>(title: T, subtitle: T, icon: Option<&str>) {
55 let notification = gio::Notification::new(title.as_ref());
56 notification.set_body(Some(subtitle.as_ref()));
57
58 if let Some(icon) = icon {
59 match gio::Icon::for_string(icon) {
60 Ok(gicon) => notification.set_icon(&gicon),
61 Err(err) => debug!("Unable to display notification: {:?}", err),
62 }
63 }
64
65 gio::Application::default()
66 .unwrap()
67 .send_notification(None, &notification);
68 debug!("System Notification: {}", title.as_ref());
69 }
70
71 pub fn bind_connected_property(action: &SimpleAction) {
72 let client = FrgConnectionManager::default().client();
73 client
74 .bind_property("is-connected", action, "enabled")
75 .flags(BindingFlags::SYNC_CREATE)
76 .build();
77 }
78
79 pub fn format_size(size: i64) -> String {
80 glib::format_size(size.try_into().unwrap_or(0)).to_string()
81 }
82
83 pub fn format_speed(speed: i32) -> String {
84 format!("{}/s", format_size(speed as i64))
85 }
86
87 pub fn format_time(total_seconds: u32, limit_at_day: bool) -> String {
88 if total_seconds == u32::MAX || total_seconds == 4294967294 {
89 warn!("Invalid seconds: {}", total_seconds);
90 return "?".into();
91 } else if total_seconds == 1 || total_seconds == 0 {
92 return String::new();
93 }
94
95 if limit_at_day && total_seconds > 86400 {
96 return i18n("more than a day");
97 }
98
99 let seconds: u32 = total_seconds % 60;
100 let minutes: u32 = (total_seconds % 3600) / 60;
101 let hours: u32 = (total_seconds % 86400) / 3600;
102 let days: u32 = (total_seconds % (86400 * 60)) / 86400;
103
104 let str_days = ni18n_f("{} day", "{} days", days, &[&days.to_string()]);
105 let str_hours = ni18n_f("{} hour", "{} hours", hours, &[&hours.to_string()]);
106 let str_minutes = ni18n_f("{} minute", "{} minutes", minutes, &[&minutes.to_string()]);
107 let str_seconds = ni18n_f("{} second", "{} seconds", seconds, &[&seconds.to_string()]);
108
109 if days > 0 {
110 format!("{str_days}, {str_hours}")
111 } else if hours > 0 {
112 format!("{str_hours}, {str_minutes}")
113 } else if minutes > 0 {
114 str_minutes
115 } else if seconds > 0 {
116 str_seconds
117 } else {
118 String::new()
119 }
120 }
121
122 pub fn eta_text(torrent: &TrTorrent) -> String {
123 match torrent.status() {
124 TrTorrentStatus::Stopped => i18n("Paused"),
125 TrTorrentStatus::Download => {
126 let total_seconds: u32 = torrent.eta().try_into().unwrap_or(1);
127 format_time(total_seconds, true)
128 }
129 // i18n: "Queued" is the current status of a torrent
130 TrTorrentStatus::DownloadWait => i18n("Queued"),
131 TrTorrentStatus::Check => i18n("Checking…"),
132 // i18n: "Queued" is the current status of a torrent
133 TrTorrentStatus::CheckWait => i18n("Queued"),
134 TrTorrentStatus::Seed => i18n("Seeding…"),
135 // i18n: "Queued" is the current status of a torrent
136 TrTorrentStatus::SeedWait => i18n("Queued"),
137 }
138 }
139
140 pub fn set_mimetype_image(mimetype: &str, image: &gtk::Image) {
141 let mimetype = if mimetype.is_empty()
142 || mimetype == "0"
143 || mimetype == "application/x-zerosize"
144 || mimetype == "application/octet-stream"
145 {
146 // Fallback to avoid ugly generic icon
147 "text-x-generic"
148 } else {
149 mimetype
150 };
151
152 let icon = gio::content_type_get_symbolic_icon(mimetype);
153 image.set_from_gicon(&icon);
154 }
155
156 pub fn session_dir_filechooser(parent: &gtk::Window, directory_type: FrgDirectoryType) {
157 let (property_name, title) = match directory_type {
158 FrgDirectoryType::Download => ("download-dir", i18n("Select Download Directory")),
159 FrgDirectoryType::Incomplete => ("incomplete-dir", i18n("Select Incomplete Directory")),
160 FrgDirectoryType::None => return,
161 };
162
163 let dialog = gtk::FileDialog::new();
164 dialog.set_title(&title);
165 dialog.set_accept_label(Some(&i18n("_Select")));
166 dialog.select_folder(
167 Some(parent),
168 gio::Cancellable::NONE,
169 clone!(@weak dialog, @weak parent => move |result| {
170 match result {
171 Ok(folder) => {
172 debug!("Selected directory: {:?}", folder.path());
173
174 let session = FrgConnectionManager::default().client().session();
175 session.set_property(property_name, folder);
176
177 FrgConnectionManager::default().check_directories();
178 }
179 Err(err) => {
180 warn!("Selected directory could not be accessed {:?}", err);
181 }
182 }
183 }),
184 );
185 }
186
187 /// Checks whether a directory is accessible and writable
188 pub fn check_writable(dir: PathBuf) -> bool {
189 debug!("Check if directory is writable: {:?}", dir);
190
191 let dummy = dir.join("dummy");
192 let res = std::fs::write(&dummy, "0").and_then(|_| std::fs::remove_file(dummy));
193
194 res.is_ok()
195 }