Debian Codegraph @

src/ui/torrent_dialog.rs

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Fragments - torrent_dialog.rs
2 // Copyright (C) 2022-2024 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::cell::OnceCell;
18
19 use adw::prelude::*;
20 use adw::subclass::dialog::*;
21 use adw::subclass::prelude::*;
22 use gio::SimpleAction;
23 use glib::{clone, subclass, Properties, VariantTy};
24 use gtk::{gio, glib, CompositeTemplate};
25 use transmission_gobject::{TrFile, TrTorrent, TrTorrentStatus};
26
27 use super::{FrgFilePage, FrgFileRow, FrgFolderPage, FrgStatusHeader};
28 use crate::backend::FrgConnectionManager;
29 use crate::i18n::ni18n_f;
30 use crate::model::{FrgFileSorter, FrgFileSorting};
31 use crate::{actions, utils};
32
33 mod imp {
34 use super::*;
35
36 #[derive(Debug, Default, CompositeTemplate, Properties)]
37 #[template(resource = "/de/haeckerfelix/Fragments/gtk/torrent_dialog.ui")]
38 #[properties(wrapper_type = super::FrgTorrentDialog)]
39 pub struct FrgTorrentDialog {
40 #[template_child]
41 pub toast_overlay: TemplateChild<adw::ToastOverlay>,
42 #[template_child]
43 navigation_view: TemplateChild<adw::NavigationView>,
44
45 #[template_child]
46 status_header: TemplateChild<FrgStatusHeader>,
47
48 #[template_child]
49 location_box: TemplateChild<gtk::Box>,
50 #[template_child]
51 location_label: TemplateChild<gtk::Label>,
52
53 #[template_child]
54 error_group: TemplateChild<adw::PreferencesGroup>,
55 #[template_child]
56 error_row: TemplateChild<adw::ActionRow>,
57
58 #[template_child]
59 button_stack: TemplateChild<gtk::Stack>,
60 #[template_child]
61 pause_button: TemplateChild<gtk::Button>,
62 #[template_child]
63 continue_button: TemplateChild<gtk::Button>,
64 #[template_child]
65 open_button: TemplateChild<gtk::Button>,
66 #[template_child]
67 more_button: TemplateChild<gtk::MenuButton>,
68
69 #[template_child]
70 download_image: TemplateChild<gtk::Image>,
71 #[template_child]
72 upload_image: TemplateChild<gtk::Image>,
73 #[template_child]
74 download_speed_label: TemplateChild<gtk::Label>,
75 #[template_child]
76 upload_speed_label: TemplateChild<gtk::Label>,
77 #[template_child]
78 seeders_label: TemplateChild<gtk::Label>,
79 #[template_child]
80 leechers_label: TemplateChild<gtk::Label>,
81 #[template_child]
82 downloaded_label: TemplateChild<gtk::Label>,
83 #[template_child]
84 uploaded_label: TemplateChild<gtk::Label>,
85 #[template_child]
86 metadata_loading_group: TemplateChild<adw::PreferencesGroup>,
87 #[template_child]
88 metadata_percentage_label: TemplateChild<gtk::Label>,
89 #[template_child]
90 file_listbox: TemplateChild<gtk::ListBox>,
91 #[template_child]
92 all_files_group: TemplateChild<adw::PreferencesGroup>,
93 #[template_child]
94 all_files_row: TemplateChild<adw::ActionRow>,
95
96 #[property(get, set, construct_only)]
97 torrent: OnceCell<TrTorrent>,
98
99 view_actions: gio::SimpleActionGroup,
100 files_sorter: FrgFileSorter,
101 }
102
103 #[glib::object_subclass]
104 impl ObjectSubclass for FrgTorrentDialog {
105 const NAME: &'static str = "FrgTorrentDialog";
106 type ParentType = adw::Dialog;
107 type Type = super::FrgTorrentDialog;
108
109 fn class_init(klass: &mut Self::Class) {
110 klass.bind_template();
111 }
112
113 fn instance_init(obj: &subclass::InitializingObject<Self>) {
114 obj.init_template();
115 }
116 }
117
118 #[glib::derived_properties]
119 impl ObjectImpl for FrgTorrentDialog {
120 fn constructed(&self) {
121 self.parent_constructed();
122 let obj: &super::FrgTorrentDialog = &self.obj();
123 let torrent = obj.torrent();
124
125 // Pull extra information from transmission daemon so we can display them in the
126 // dialog. Those aren't getting retrieved by default to avoid unnecessary
127 // deserialization.
128 torrent.set_update_extra_info(true);
129
130 // Bind torrent values
131 self.bind_property("name", obj, "title");
132 self.bind_property("primary-mime-type", &self.status_header.get(), "mimetype");
133 self.bind_property("name", &self.status_header.get(), "title");
134 self.bind_property("size", &self.status_header.get(), "total-bytes");
135 self.bind_property("downloaded", &self.status_header.get(), "downloaded-bytes");
136 self.bind_property("download-dir", &self.location_label.get(), "label");
137 self.bind_property("leechers", &self.leechers_label.get(), "label");
138
139 // Setup `torrent` specific actions
140 actions::install_torrent_actions(&torrent, obj.clone().upcast());
141
142 // "More" menu button
143 let builder =
144 gtk::Builder::from_resource("/de/haeckerfelix/Fragments/gtk/torrent_menu.ui");
145 let menu: gio::MenuModel = builder.object("torrent_more_menu").unwrap();
146 self.more_button.set_menu_model(Some(&menu));
147
148 // Files metadata
149 torrent
150 .bind_property(
151 "metadata-percent-complete",
152 &self.metadata_percentage_label.get(),
153 "label",
154 )
155 .transform_to(|_, p: f32| Some(format!("{:.0}%", p * 100.0)))
156 .sync_create()
157 .build();
158
159 torrent
160 .bind_property(
161 "metadata-percent-complete",
162 &self.metadata_loading_group.get(),
163 "visible",
164 )
165 .transform_to(|_, p: f32| Some(p != 1.0))
166 .sync_create()
167 .build();
168
169 // Files listbox
170 if torrent.files().is_ready() {
171 self.show_overview_files();
172 }
173 torrent
174 .files()
175 .connect_is_ready_notify(clone!(@weak self as this => move|_| {
176 this.show_overview_files();
177 }));
178
179 // Files listbox row activation
180 self.file_listbox
181 .connect_row_activated(clone!(@weak self as this => move |_, row|{
182 let row = row.downcast_ref::<adw::PreferencesRow>().unwrap().child().unwrap();
183 let file_row = row.downcast_ref::<FrgFileRow>().unwrap();
184 let file = file_row.file();
185
186 if let Some(file) = file {
187 if file.is_folder() {
188 this.show_folder(&file);
189 } else {
190 this.show_file(&file);
191 }
192 }
193 }));
194
195 // Setup view actions
196 obj.insert_action_group("view", Some(&self.view_actions));
197 let mut action;
198
199 // view.sorting
200 action = SimpleAction::new_stateful(
201 "sorting",
202 VariantTy::STRING.into(),
203 &"name".to_variant(),
204 );
205 action.connect_change_state(
206 clone!(@weak self.files_sorter as files_sorter => move |action, state|{
207 if let Some(state) = state {
208 action.set_state(state);
209
210 let sorter: FrgFileSorting = state.str().unwrap().into();
211 files_sorter.set_sorting(sorter);
212 }
213 }),
214 );
215 self.view_actions.add_action(&action);
216
217 // view.order
218 action = SimpleAction::new_stateful(
219 "order",
220 VariantTy::STRING.into(),
221 &"ascending".to_variant(),
222 );
223 action.connect_change_state(
224 clone!(@weak self.files_sorter as files_sorter => move |action, state|{
225 if let Some(state) = state {
226 action.set_state(state);
227
228 let descending = state.str().unwrap() == "descending";
229 files_sorter.set_descending(descending);
230 }
231 }),
232 );
233 self.view_actions.add_action(&action);
234
235 // view.folder-before-files
236 action = SimpleAction::new_stateful("folder-before-files", None, &true.to_variant());
237 action.connect_change_state(
238 clone!(@weak self.files_sorter as files_sorter => move |action, state|{
239 if let Some(state) = state {
240 action.set_state(state);
241
242 let value = state.get::<bool>().unwrap();
243 files_sorter.set_folders_before_files(value);
244 }
245 }),
246 );
247 self.view_actions.add_action(&action);
248
249 // view.show-all
250 action = SimpleAction::new("show-all", None);
251 action.connect_activate(clone!(@weak self as this => move |_, _|{
252 if let Some(top_level) = this.obj().torrent().files().top_level(){
253 this.show_folder(&top_level);
254 } else {
255 warn!("Unable to show contents, no top level file available");
256 }
257
258 }));
259 self.view_actions.add_action(&action);
260
261 // view.show-folder
262 action = SimpleAction::new("show-folder", VariantTy::STRING.into());
263 action.connect_activate(clone!(@weak self as this => move |_, param|{
264 if let Some(param) = param {
265 let name = param.get::<String>().unwrap();
266 let folder = this.obj().torrent().files().file_by_name(&name).unwrap();
267 this.show_folder(&folder);
268 }
269 }));
270 self.view_actions.add_action(&action);
271
272 // view.show-file
273 action = SimpleAction::new("show-file", VariantTy::STRING.into());
274 action.connect_activate(clone!(@weak self as this => move |_, param|{
275 if let Some(param) = param {
276 let name = param.get::<String>().unwrap();
277 let file = this.obj().torrent().files().file_by_name(&name).unwrap();
278 this.show_file(&file);
279 }
280 }));
281 self.view_actions.add_action(&action);
282
283 // Update dialog on torrent changes
284 torrent.connect_notify_local(
285 None,
286 clone!(@weak self as this => move |_, _| {
287 this.update_labels();
288 this.update_widgets();
289 }),
290 );
291
292 self.update_labels();
293 self.update_widgets();
294 }
295 }
296
297 impl WidgetImpl for FrgTorrentDialog {}
298
299 impl AdwDialogImpl for FrgTorrentDialog {
300 fn closed(&self) {
301 self.obj().torrent().set_update_extra_info(false);
302 self.parent_closed();
303 }
304 }
305
306 impl FrgTorrentDialog {
307 fn show_folder(&self, folder: &TrFile) {
308 let page = FrgFolderPage::new(folder, &self.files_sorter);
309 self.navigation_view.push(&page);
310 }
311
312 fn show_file(&self, file: &TrFile) {
313 let page = FrgFilePage::new(file);
314 self.navigation_view.push(&page);
315 }
316
317 fn show_overview_files(&self) {
318 let torrent = self.obj().torrent();
319
320 let top_level = if let Some(top_level) = torrent.files().top_level() {
321 top_level
322 } else {
323 warn!("Unable display files in overview page, no top level available");
324 return;
325 };
326
327 // When a torrent has multiple files, the top level entry is always a folder
328 if top_level.is_folder() {
329 self.file_listbox.set_visible(true);
330 let files = top_level.related();
331
332 // We has to limit the files which are getting displayed in a
333 // regular listbox since it doesn't scale like a listview
334 let mut max_files = files.n_items();
335 if max_files > 8 {
336 max_files = 8;
337 let total = torrent.files().n_items();
338
339 // Translators: {} is *always* a number greater than 8
340 let text = ni18n_f(
341 "Show All",
342 "Show All {} Items",
343 total,
344 &[&total.to_string()],
345 );
346
347 // Show row which allows to show all files using a listview
348 self.all_files_row.set_title(&text);
349 self.all_files_group.set_visible(true);
350 self.obj().set_content_height(1200);
351 }
352
353 let sorter = FrgFileSorter::new();
354 let files_sorted = gtk::SortListModel::new(Some(files), Some(sorter));
355
356 // Add some files to the simple listbox
357 for i in 0..max_files {
358 let object = files_sorted.item(i).unwrap();
359 let file = object.downcast_ref::<TrFile>().unwrap();
360
361 let file_row = FrgFileRow::new();
362 file_row.set_file(file);
363
364 let row = adw::PreferencesRow::new();
365 row.set_child(Some(&file_row));
366
367 self.file_listbox.append(&row);
368 }
369 }
370 }
371
372 fn update_labels(&self) {
373 let torrent = self.obj().torrent();
374
375 let eta = utils::eta_text(&torrent);
376 self.status_header.set_eta(eta);
377
378 let downloaded = utils::format_size(torrent.downloaded());
379 self.downloaded_label.set_text(&downloaded);
380
381 let uploaded = utils::format_size(torrent.uploaded());
382 self.uploaded_label.set_text(&uploaded);
383
384 let download_speed = utils::format_speed(torrent.download_speed());
385 self.download_speed_label.set_text(&download_speed);
386
387 let upload_speed = utils::format_speed(torrent.upload_speed());
388 self.upload_speed_label.set_text(&upload_speed);
389
390 let seeders = torrent.seeders().to_string();
391 let seeders_active = torrent.seeders_active().to_string();
392 // Translators: First {} corresponds to the number of seeders, second {} to the
393 // number of active seeders
394 let seeders_text = ni18n_f(
395 "{} ({} active)",
396 "{} ({} active)",
397 torrent.seeders_active().try_into().unwrap_or(0),
398 &[&seeders, &seeders_active],
399 );
400 self.seeders_label.set_text(&seeders_text);
401 }
402
403 fn update_widgets(&self) {
404 let session = FrgConnectionManager::default().client().session();
405 let torrent = self.obj().torrent();
406
407 // Location label
408 // Only show the location info when it differs from the standard download
409 let session_download_dir = if let Some(dir) = session.download_dir() {
410 dir.path().unwrap().to_str().unwrap().to_string()
411 } else {
412 String::new()
413 };
414 let show_location = torrent.download_dir() != session_download_dir;
415 self.location_box.set_visible(show_location);
416
417 // Action button row
418 let button_widget = match torrent.status() {
419 TrTorrentStatus::Stopped => self.continue_button.get(),
420 _ => self.pause_button.get(),
421 };
422 self.button_stack.set_visible_child(&button_widget);
423
424 // Error message row
425 if torrent.error() != 0 {
426 self.error_group.set_visible(true);
427 self.error_row.set_subtitle(&torrent.error_string());
428 } else {
429 self.error_group.set_visible(false);
430 }
431
432 // Status boxes
433 let is_downloading = torrent.download_speed() != 0;
434 let is_uploading = torrent.upload_speed() != 0;
435
436 if is_downloading {
437 self.download_image.add_css_class("active");
438 } else {
439 self.download_image.remove_css_class("active");
440 }
441
442 if is_uploading {
443 self.upload_image.add_css_class("active");
444 } else {
445 self.upload_image.remove_css_class("active");
446 }
447 }
448
449 fn bind_property<T: IsA<gtk::Widget>>(
450 &self,
451 prop_name: &str,
452 widget: &T,
453 widget_prop_name: &str,
454 ) {
455 self.obj()
456 .torrent()
457 .bind_property(prop_name, widget, widget_prop_name)
458 .sync_create()
459 .build();
460 }
461 }
462 }
463
464 glib::wrapper! {
465 pub struct FrgTorrentDialog(ObjectSubclass<imp::FrgTorrentDialog>)
466 @extends gtk::Widget, adw::Dialog;
467 }
468
469 impl FrgTorrentDialog {
470 pub fn new(torrent: &TrTorrent) -> Self {
471 glib::Object::builder().property("torrent", torrent).build()
472 }
473
474 pub fn toast_overlay(&self) -> adw::ToastOverlay {
475 self.imp().toast_overlay.get()
476 }
477 }