Debian Codegraph @

podcasts-gtk/src/widgets/download_progress_bar.rs

raw symbols SCIP
1 // download_progress.rs
2 //
3 // Copyright 2017 Jordan Petridis <[email protected]>
4 // Copyright 2023-2024 nee <[email protected]>
5 //
6 // This program is free software: you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation, either version 3 of the License, or
9 // (at your option) any later version.
10 //
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License
17 // along with this program. If not, see <http://www.gnu.org/licenses/>.
18 //
19 // SPDX-License-Identifier: GPL-3.0-or-later
20
21 use adw::prelude::BinExt;
22 use adw::subclass::prelude::*;
23 use anyhow::{Result, anyhow, bail};
24 use glib::Properties;
25 use glib::clone;
26 use gtk::glib;
27 use gtk::prelude::*;
28 use std::cell::Cell;
29 use std::sync::{Arc, Mutex, OnceLock, TryLockError};
30 use std::time::Duration;
31
32 use crate::i18n::i18n;
33 use crate::manager;
34 use crate::manager::ActiveProgress;
35 use podcasts_data::EpisodeId;
36 use podcasts_data::dbqueries;
37 use podcasts_data::downloader::DownloadProgress;
38
39 #[derive(Debug, Default, Properties)]
40 #[properties(wrapper_type = DownloadProgressBar)]
41 pub struct DownloadProgressPriv {
42 progressbar: gtk::ProgressBar,
43 id: OnceLock<EpisodeId>,
44 listener: Cell<bool>, // lock for update callback
45 #[property(get, set)]
46 local_size: Cell<u64>,
47 #[property(get, set)]
48 total_size: Cell<u64>,
49 }
50
51 #[glib::object_subclass]
52 impl ObjectSubclass for DownloadProgressPriv {
53 const NAME: &'static str = "PdDownloadProgress";
54 type Type = super::DownloadProgressBar;
55 type ParentType = adw::Bin;
56 }
57
58 #[glib::derived_properties]
59 impl ObjectImpl for DownloadProgressPriv {
60 fn constructed(&self) {
61 self.parent_constructed();
62 self.progressbar.set_visible(false);
63 self.progressbar.set_hexpand(true);
64 self.progressbar.set_pulse_step(0.0);
65 self.progressbar
66 .update_property(&[gtk::accessible::Property::Label(&i18n("Download progress"))]);
67 }
68 }
69 impl WidgetImpl for DownloadProgressPriv {}
70 impl BinImpl for DownloadProgressPriv {}
71
72 impl DownloadProgressPriv {}
73
74 glib::wrapper! {
75 pub struct DownloadProgressBar(ObjectSubclass<DownloadProgressPriv>)
76 @extends adw::Bin, gtk::Widget,
77 @implements gtk::Accessible, gtk::Buildable, gtk::ConstraintTarget;
78 }
79
80 impl DownloadProgressBar {
81 pub fn init(&self, episode_id: EpisodeId) {
82 let _ = self.imp().id.set(episode_id);
83 self.set_child(Some(&self.imp().progressbar));
84 }
85
86 /// Notifies when downloading started/stopped
87 pub fn connect_state_change<F: Fn(&gtk::ProgressBar) + 'static>(&self, f: F) {
88 self.imp().progressbar.connect_visible_notify(f);
89 }
90
91 pub fn id(&self) -> EpisodeId {
92 *self.imp().id.get().unwrap()
93 }
94
95 fn has_listener(&self) -> bool {
96 self.imp().listener.get()
97 }
98
99 pub fn check_if_downloading(&self) -> Result<bool> {
100 let id = self.id();
101 // Check if the episode is being downloaded
102 if let Some(prog) = self.active_dl()? {
103 // avoid putting up multiple callbacks
104 if self.has_listener() {
105 return Ok(true);
106 }
107 debug!("Download is happening, starting download bar.");
108 // set a callback that will update the state when the download finishes
109 let callback = clone!(
110 #[weak(rename_to = this)]
111 self,
112 #[upgrade_or]
113 glib::ControlFlow::Break,
114 move || {
115 if let Ok(guard) = manager::ACTIVE_DOWNLOADS.read() {
116 if !guard.contains_key(&id) {
117 this.imp().progressbar.set_visible(false);
118 this.imp().progressbar.set_fraction(0.0);
119 this.imp().listener.set(false);
120 debug!("Download bar done, hiding it now.");
121 return glib::ControlFlow::Break;
122 }
123 }
124 glib::ControlFlow::Continue
125 }
126 );
127 glib::timeout_add_local(Duration::from_millis(250), callback);
128 self.imp().listener.set(true);
129 self.imp().progressbar.set_visible(true);
130
131 // Setup a callback that will update the total_size label
132 // with the http ContentLength header number rather than
133 // relying to the RSS feed.
134 update_total_size_callback(self, &prog);
135
136 // Setup a callback that will update the progress bar.
137 update_progressbar_callback(self, &prog, id);
138
139 return Ok(true);
140 }
141 Ok(false)
142 }
143
144 fn active_dl(&self) -> Result<Option<ActiveProgress>> {
145 let id = self.id();
146 let m = manager::ACTIVE_DOWNLOADS
147 .read()
148 .map_err(|_| anyhow!("Failed to get a lock on the mutex."))?;
149
150 Ok(m.get(&id).cloned())
151 }
152
153 pub fn cancel(&self) -> Result<()> {
154 let id = self.id();
155 if let Some(prog) = self.active_dl()? {
156 if let Ok(mut m) = prog.lock() {
157 m.cancel();
158 }
159
160 // Cancel is not instant so we have to wait a bit
161 glib::timeout_add_local(
162 Duration::from_millis(50),
163 clone!(
164 #[weak(rename_to = this)]
165 self,
166 #[upgrade_or]
167 glib::ControlFlow::Break,
168 move || {
169 if let Ok(thing) = this.active_dl() {
170 if thing.is_none() {
171 // Recalculate the widget state
172 if let Err(err) = dbqueries::get_episode_widget_from_id(id) {
173 error!("Error: {}", err);
174 }
175 this.imp().progressbar.set_visible(false);
176 this.imp().progressbar.set_fraction(0.0);
177 return glib::ControlFlow::Break;
178 }
179 }
180
181 glib::ControlFlow::Continue
182 }
183 ),
184 );
185 }
186 Ok(())
187 }
188
189 fn update_progress(&self, local_size: u64, fraction: f64) {
190 self.set_local_size(local_size);
191 self.imp().progressbar.set_fraction(fraction);
192 }
193 }
194
195 // Setup a callback that will update the progress bar.
196 #[inline]
197 fn update_progressbar_callback(
198 widget: &DownloadProgressBar,
199 prog: &Arc<Mutex<manager::Progress>>,
200 episode_id: EpisodeId,
201 ) {
202 let callback = clone!(
203 #[weak]
204 widget,
205 #[strong]
206 prog,
207 #[upgrade_or]
208 glib::ControlFlow::Break,
209 move || {
210 progress_bar_helper(&widget, &prog, episode_id).unwrap_or(glib::ControlFlow::Break)
211 }
212 );
213 glib::timeout_add_local(Duration::from_millis(100), callback);
214 }
215
216 fn progress_bar_helper(
217 widget: &DownloadProgressBar,
218 prog: &Arc<Mutex<manager::Progress>>,
219 episode_id: EpisodeId,
220 ) -> Result<glib::ControlFlow> {
221 let (fraction, downloaded, cancel) = match prog.try_lock() {
222 Ok(guard) => (
223 guard.get_fraction(),
224 guard.get_downloaded(),
225 guard.should_cancel(),
226 ),
227 Err(TryLockError::WouldBlock) => return Ok(glib::ControlFlow::Continue),
228 Err(TryLockError::Poisoned(_)) => bail!("Progress Mutex is poisoned"),
229 };
230
231 // Update the progress_bar.
232 if (0.0..=1.0).contains(&fraction) && (!fraction.is_nan()) {
233 widget.update_progress(downloaded, fraction);
234 }
235
236 // Check if the download is still active
237 let active = match manager::ACTIVE_DOWNLOADS.read() {
238 Ok(guard) => guard.contains_key(&episode_id),
239 Err(_) => return Err(anyhow!("Failed to get a lock on the mutex.")),
240 };
241
242 if (fraction >= 1.0 && !fraction.is_nan()) || !active || cancel {
243 Ok(glib::ControlFlow::Break)
244 } else {
245 Ok(glib::ControlFlow::Continue)
246 }
247 }
248
249 // Setup a callback that will update the total_size label
250 // with the http ContentLength header number rather than
251 // relying to the RSS feed.
252 #[inline]
253 fn update_total_size_callback(widget: &DownloadProgressBar, prog: &Arc<Mutex<manager::Progress>>) {
254 let callback = clone!(
255 #[strong]
256 prog,
257 #[weak]
258 widget,
259 #[upgrade_or]
260 glib::ControlFlow::Break,
261 move || total_size_helper(&widget, &prog).unwrap_or(glib::ControlFlow::Continue),
262 );
263 glib::timeout_add_local(Duration::from_millis(100), callback);
264 }
265
266 fn total_size_helper(
267 widget: &DownloadProgressBar,
268 prog: &Arc<Mutex<manager::Progress>>,
269 ) -> Result<glib::ControlFlow> {
270 // Get the total_bytes.
271 let total_bytes = match prog.try_lock() {
272 Ok(guard) => guard.get_size(),
273 Err(TryLockError::WouldBlock) => return Ok(glib::ControlFlow::Continue),
274 Err(TryLockError::Poisoned(_)) => bail!("Progress Mutex is poisoned"),
275 };
276
277 debug!("Total Size: {}", total_bytes);
278 if total_bytes != 0 {
279 // Update the total_size label
280 widget.set_total_size(total_bytes);
281
282 // Do not call again the callback
283 Ok(glib::ControlFlow::Break)
284 } else {
285 Ok(glib::ControlFlow::Continue)
286 }
287 }