Debian Codegraph @

podcasts-gtk/src/widgets/episode.rs

raw symbols SCIP
1 // episode.rs
2 //
3 // Copyright 2017 Jordan Petridis <[email protected]>
4 //
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program. If not, see <http://www.gnu.org/licenses/>.
17 //
18 // SPDX-License-Identifier: GPL-3.0-or-later
19
20 use adw::subclass::prelude::*;
21 use anyhow::Result;
22 use async_channel::Sender;
23 use chrono::prelude::*;
24 use glib::clone;
25 use glib::subclass::InitializingObject;
26 use gtk::CompositeTemplate;
27 use gtk::prelude::*;
28 use gtk::{gio, glib};
29 use std::cell::Cell;
30 use std::sync::LazyLock;
31
32 use crate::app::Action;
33 use crate::i18n::i18n_f;
34 use crate::manager;
35 use crate::widgets::{DownloadProgressBar, EpisodeMenu};
36 use podcasts_data::EpisodeId;
37 use podcasts_data::dbqueries;
38 use podcasts_data::utils::get_download_dir;
39 use podcasts_data::{EpisodeModel, EpisodeWidgetModel};
40
41 static SIZE_OPTS: LazyLock<humansize::FormatSizeOptions> = LazyLock::new(|| {
42 // Declare a custom humansize option struct
43 // See: https://docs.rs/humansize/2.1.3/humansize/struct.FormatSizeOptions.html
44 humansize::FormatSizeOptions::from(humansize::WINDOWS).decimal_places(0)
45 });
46
47 #[derive(Debug, CompositeTemplate, Default)]
48 #[template(resource = "/org/gnome/Podcasts/gtk/episode_widget.ui")]
49 pub struct EpisodeWidgetPriv {
50 #[template_child]
51 progressbar: TemplateChild<DownloadProgressBar>,
52
53 // InfoLabels
54 #[template_child]
55 title: TemplateChild<gtk::Label>,
56 #[template_child]
57 date: TemplateChild<gtk::Label>,
58 #[template_child]
59 separator1: TemplateChild<gtk::Label>,
60 #[template_child]
61 duration: TemplateChild<gtk::Label>,
62 #[template_child]
63 separator2: TemplateChild<gtk::Label>,
64 #[template_child]
65 local_size: TemplateChild<gtk::Label>,
66 #[template_child]
67 size_separator: TemplateChild<gtk::Label>,
68 #[template_child]
69 total_size: TemplateChild<gtk::Label>,
70 #[template_child]
71 played_checkmark: TemplateChild<gtk::Image>,
72
73 // Buttons
74 #[template_child]
75 play: TemplateChild<gtk::Button>,
76 #[template_child]
77 pause: TemplateChild<gtk::Button>,
78 #[template_child]
79 download: TemplateChild<gtk::Button>,
80 #[template_child]
81 cancel: TemplateChild<gtk::Button>,
82 #[template_child]
83 text_only: TemplateChild<gtk::Button>,
84
85 episode_id: Cell<Option<EpisodeId>>,
86 }
87
88 impl EpisodeWidgetPriv {
89 pub(crate) fn init(
90 &self,
91 sender: &Sender<Action>,
92 episode: EpisodeWidgetModel,
93 add_show_link: bool,
94 ) {
95 crate::MAINCONTEXT.spawn_local_with_priority(
96 glib::source::Priority::LOW,
97 clone!(
98 #[weak(rename_to = this)]
99 self,
100 #[strong]
101 sender,
102 async move {
103 let id = episode.id();
104 this.episode_id.set(Some(id));
105 this.init_info(&episode);
106 if episode.uri().is_none() {
107 this.state_no_uri(id);
108 return;
109 }
110
111 this.init_progressbar(id);
112 // long_press needs to be neutralized by play/pause/dl button clicks
113 let long_press = this.init_context_menu(&sender, add_show_link);
114 this.init_buttons(&sender, id, &long_press);
115 if let Err(err) = this.determine_buttons_state(&episode) {
116 error!("Error: {}", err);
117 }
118 }
119 ),
120 );
121 }
122
123 // Rare case when an episode does not have
124 // any audio files attached as enclosure tags.
125 fn state_no_uri(&self, id: EpisodeId) {
126 self.cancel.set_visible(false);
127 self.play.set_visible(false);
128 self.pause.set_visible(false);
129
130 self.local_size.set_visible(false);
131 self.size_separator.set_visible(false);
132 self.download.set_visible(false);
133 self.text_only.set_visible(true);
134 self.text_only.set_action_name(Some("app.go-to-episode"));
135 self.text_only
136 .set_action_target_value(Some(&id.0.to_variant()));
137 }
138
139 // InProgress State:
140 // * Show ProgressBar and Cancel Button.
141 // * Show `total_size`, `local_size` labels and `size_separator`.
142 // * Hide `date`, `duration` labels
143 // * Hide Download and Play Buttons
144 fn state_prog(&self) {
145 self.cancel.set_visible(true);
146
147 self.total_size.set_visible(true);
148 self.local_size.set_visible(true);
149 self.size_separator.set_visible(true);
150
151 self.date.set_visible(false);
152 self.set_duration_visible(false);
153
154 self.play.set_visible(false);
155 self.pause.set_visible(false);
156 self.download.set_visible(false);
157 self.update_separator2_visibility();
158 }
159
160 // Playable State:
161 // * Hide ProgressBar and Cancel, Download Buttons.
162 // * Hide `local_size` labels and `size_separator`.
163 // * Show `date`, `duration` labels
164 // * Show Play Button and `total_size` label
165 fn state_playable(&self) {
166 self.cancel.set_visible(false);
167 self.download.set_visible(false);
168 self.local_size.set_visible(false);
169 self.size_separator.set_visible(false);
170
171 self.date.set_visible(true);
172 self.set_duration_visible(true);
173
174 self.total_size.set_visible(true);
175 self.play.set_visible(true);
176 self.pause.set_visible(false);
177 self.update_separator2_visibility();
178 }
179
180 // Playing State:
181 // * Hide ProgressBar and Cancel, Download Buttons.
182 // * Hide `local_size` labels and `size_separator`.
183 // * Show `date`, `duration` labels
184 // * Show Pause Button and `total_size` label
185 fn state_playing(&self) {
186 self.cancel.set_visible(false);
187 self.download.set_visible(false);
188 self.local_size.set_visible(false);
189 self.size_separator.set_visible(false);
190
191 self.date.set_visible(true);
192 self.set_duration_visible(true);
193
194 self.total_size.set_visible(true);
195 self.play.set_visible(false);
196 self.pause.set_visible(true);
197 self.update_separator2_visibility();
198 }
199
200 // NotDownloaded State:
201 // * Hide ProgressBar and Cancel, Play Buttons.
202 // * Hide `local_size` labels and `size_separator`.
203 // * Show Download Button
204 // * Show `date`, `duration` labels
205 // * Determine `total_size` label state (Comes from `episode.lenght`).
206 fn state_download(&self) {
207 self.cancel.set_visible(false);
208 self.play.set_visible(false);
209 self.pause.set_visible(false);
210
211 self.local_size.set_visible(false);
212 self.size_separator.set_visible(false);
213
214 self.date.set_visible(true);
215 self.set_duration_visible(true);
216
217 self.download.set_visible(true);
218 self.update_separator2_visibility();
219 }
220
221 /// Change the state of the `EpisodeWidget`.
222 ///
223 /// Function Flowchart:
224 ///
225 ///
226 /// ------------------- --------------
227 /// | Is the Episode | YES | State: |
228 /// | being played | ----> | Playing |
229 /// | right now? | | |
230 /// ------------------- --------------
231 /// |
232 /// | NO
233 /// |
234 /// \_/
235 /// ------------------- --------------
236 /// | Does the Episode| YES | State: |
237 /// | not have a | ----> | NoUri |
238 /// | download link? | | |
239 /// ------------------- --------------
240 /// |
241 /// | NO
242 /// |
243 /// \_/
244 /// ------------------- --------------
245 /// | Is the Episode | YES | State: |
246 /// | currently being | ----> | InProgress |
247 /// | downloaded? | | |
248 /// ------------------- --------------
249 /// |
250 /// | NO
251 /// |
252 /// \_/
253 /// ------------------- --------------
254 /// | is the episode | YES | State: |
255 /// | downloaded | ----> | Playable |
256 /// | already? | | |
257 /// ------------------- --------------
258 /// |
259 /// | NO
260 /// |
261 /// \_/
262 /// -------------------
263 /// | State: |
264 /// | NotDownloaded |
265 /// -------------------
266 fn determine_buttons_state(&self, episode: &EpisodeWidgetModel) -> Result<()> {
267 let is_downloading = self.progressbar.check_if_downloading()?;
268 let app = gio::Application::default()
269 .expect("Could not get default application")
270 .downcast::<crate::PdApplication>()
271 .unwrap();
272 let is_playing = app.is_playing(episode.id());
273 if is_playing {
274 // State Playing
275 self.state_playing();
276 } else if is_downloading {
277 // State InProgress
278 self.state_prog();
279 } else if episode.local_uri().is_some() {
280 // State: Playable
281 self.state_playable();
282 } else {
283 // State: NotDownloaded
284 self.state_download();
285 }
286 Ok(())
287 }
288
289 fn init_info(&self, episode: &EpisodeWidgetModel) {
290 self.set_title(episode);
291 self.set_date(episode.epoch());
292 self.set_duration(episode.duration());
293 self.set_size(episode.length());
294 self.set_played(episode.played().is_some());
295 }
296
297 fn set_title(&self, episode: &EpisodeWidgetModel) {
298 self.title.set_text(episode.title());
299 }
300
301 fn set_played(&self, played: bool) {
302 if played {
303 self.title.add_css_class("dim-label");
304 self.played_checkmark.set_visible(true);
305 } else {
306 self.title.remove_css_class("dim-label");
307 self.played_checkmark.set_visible(false);
308 }
309 }
310
311 // Set the date label of the episode widget.
312 fn set_date(&self, epoch: NaiveDateTime) {
313 let now: DateTime<Local> = Local::now();
314 let ts = DateTime::<Local>::from(epoch.and_utc());
315
316 // If the episode is from a different year, print year as well
317 if now.year() != ts.year() {
318 self.date.set_text(
319 ts.format_localized("%e %b %Y", *crate::CHRONO_LOCALE)
320 .to_string()
321 .trim(),
322 );
323 // Else omit the year from the label
324 } else {
325 self.date.set_text(
326 ts.format_localized("%e %b", *crate::CHRONO_LOCALE)
327 .to_string()
328 .trim(),
329 );
330 }
331 }
332
333 // Set the duration label of the episode widget.
334 fn set_duration(&self, seconds: Option<i32>) {
335 // If length is provided
336 if let Some(s) = seconds {
337 // Convert seconds to minutes
338 let minutes = chrono::Duration::seconds(s.into()).num_minutes();
339 // If the length is 1 or more minutes
340 if minutes != 0 {
341 // Set the label and show them.
342 self.duration
343 .set_text(&i18n_f("{} min", &[&minutes.to_string()]));
344 self.set_duration_visible(true);
345 return;
346 }
347 }
348
349 // Else empty and hide the label
350 self.duration.set_text("");
351 self.set_duration_visible(false);
352 }
353
354 fn set_duration_visible(&self, visible: bool) {
355 // check if there is no duration, hide in that case.
356 if visible && self.duration.text().is_empty() {
357 self.separator1.set_visible(false);
358 self.duration.set_visible(false);
359 } else {
360 self.separator1.set_visible(visible);
361 self.duration.set_visible(visible);
362 }
363 }
364
365 // Set the size label of the episode widget.
366 fn set_size(&self, bytes: Option<i32>) {
367 // Convert the bytes to a String label
368 let size = bytes.and_then(|s| {
369 if s <= 0 {
370 None
371 } else {
372 Some(humansize::format_size(s as u32, *SIZE_OPTS))
373 }
374 });
375
376 if let Some(s) = size {
377 self.total_size.set_text(&s);
378 self.total_size.set_visible(true);
379 } else {
380 self.total_size.set_visible(false);
381 }
382 }
383
384 fn init_progressbar(&self, id: EpisodeId) {
385 self.progressbar.init(id);
386
387 self.progressbar.connect_state_change(clone!(
388 #[weak(rename_to = this)]
389 self,
390 move |_| {
391 if let Err(err) = dbqueries::get_episode_widget_from_id(id)
392 .map(|ep| this.determine_buttons_state(&ep))
393 {
394 error!("Could not get episode info: {err}");
395 }
396 }
397 ));
398
399 self.progressbar
400 .bind_property("local_size", &*self.local_size, "label")
401 .transform_to(move |_, downloaded: u64| {
402 Some(humansize::format_size(downloaded, *SIZE_OPTS))
403 })
404 .flags(glib::BindingFlags::SYNC_CREATE)
405 .build();
406
407 self.progressbar.connect_total_size_notify(clone!(
408 #[weak(rename_to = this)]
409 self,
410 move |_| {
411 // try_from should handle NaN case
412 this.set_size(i32::try_from(this.progressbar.total_size()).ok());
413 }
414 ));
415 }
416
417 fn init_buttons(
418 &self,
419 sender: &Sender<Action>,
420 id: EpisodeId,
421 long_press: &gtk::GestureLongPress,
422 ) {
423 self.cancel.connect_clicked(clone!(
424 #[weak]
425 long_press,
426 #[weak(rename_to = this)]
427 self,
428 move |_| {
429 long_press.set_state(gtk::EventSequenceState::Claimed);
430 if let Err(e) = this.progressbar.cancel() {
431 error!("failed to cancel download {e}");
432 }
433 }
434 ));
435
436 self.pause.connect_clicked(clone!(
437 #[weak]
438 long_press,
439 move |_| {
440 long_press.set_state(gtk::EventSequenceState::Claimed);
441 }
442 ));
443
444 self.play.connect_clicked(clone!(
445 #[weak]
446 long_press,
447 #[strong]
448 sender,
449 move |_| {
450 long_press.set_state(gtk::EventSequenceState::Claimed);
451 if let Ok(episode) = dbqueries::get_episode_widget_from_id(id) {
452 // Play the episode
453 send_blocking!(sender, Action::InitEpisode(episode.id()));
454 }
455 }
456 ));
457
458 self.download.connect_clicked(clone!(
459 #[weak]
460 long_press,
461 #[weak(rename_to = this)]
462 self,
463 #[strong]
464 sender,
465 move |dl| {
466 long_press.set_state(gtk::EventSequenceState::Claimed);
467 if let Ok(ep) = dbqueries::get_episode_widget_from_id(id) {
468 let result = on_download_clicked(&ep, &sender).and_then(|_| {
469 info!("Download started successfully.");
470 this.determine_buttons_state(&ep)
471 });
472 if let Err(err) = result {
473 error!("Failed to start download {err}");
474 } else {
475 this.progressbar.grab_focus();
476 }
477 }
478
479 // Restore sensitivity after operations above complete
480 dl.set_sensitive(true);
481 }
482 ));
483 }
484
485 fn init_context_menu(
486 &self,
487 sender: &Sender<Action>,
488 add_show_link: bool,
489 ) -> gtk::GestureLongPress {
490 let on_rightclick = clone!(
491 #[strong]
492 sender,
493 #[weak(rename_to = this)]
494 self,
495 move |(x, y)| {
496 let id = this.episode_id.get().unwrap();
497 let episode = match dbqueries::get_episode_widget_from_id(id) {
498 Ok(ep) => ep,
499 Err(err) => {
500 error!("Could not get episode info: {err}");
501 return;
502 }
503 };
504 let pid = episode.show_id();
505 let show = if add_show_link { Some(pid) } else { None };
506 let menu = EpisodeMenu::new(&sender, &episode, show);
507 let popover = gtk::PopoverMenu::from_model(Some(&menu.menu));
508 popover.set_parent(&*this.obj());
509 popover.insert_action_group("episode", Some(&menu.group));
510 popover.set_pointing_to(Some(&gtk::gdk::Rectangle::new(x as i32, y as i32, 1, 1)));
511 popover.set_halign(gtk::Align::Start);
512 popover.set_has_arrow(false);
513 popover.popup();
514 }
515 );
516 let on_long_press = on_rightclick.clone();
517 let long_press = gtk::GestureLongPress::new();
518 long_press.connect_pressed(move |_, x, y| {
519 on_long_press((x, y));
520 });
521 let right_click = gtk::GestureClick::builder()
522 .button(gtk::gdk::BUTTON_SECONDARY)
523 .build();
524 right_click.connect_pressed(move |_, _, x, y| {
525 on_rightclick((x, y));
526 });
527 self.obj().add_controller(long_press.clone());
528 self.obj().add_controller(right_click);
529 long_press
530 }
531
532 fn update_separator2_visibility(&self) {
533 self.separator2
534 .set_visible(self.date.is_visible() && self.total_size.is_visible());
535 }
536 }
537 fn on_download_clicked(ep: &EpisodeWidgetModel, sender: &Sender<Action>) -> Result<()> {
538 let pd = dbqueries::get_podcast_from_id(ep.show_id())?;
539 let download_dir = get_download_dir(pd.title())?;
540
541 // Start a new download.
542 manager::add(sender.clone(), ep.id(), download_dir)?;
543 // Update Views
544 send_blocking!(sender, Action::RefreshEpisode(ep.id()));
545 Ok(())
546 }
547
548 #[glib::object_subclass]
549 impl ObjectSubclass for EpisodeWidgetPriv {
550 const NAME: &'static str = "PdEpisode";
551 type Type = EpisodeWidget;
552 type ParentType = gtk::Box;
553
554 fn class_init(klass: &mut Self::Class) {
555 klass.bind_template();
556 }
557
558 fn instance_init(obj: &InitializingObject<Self>) {
559 obj.init_template();
560 }
561 }
562
563 impl WidgetImpl for EpisodeWidgetPriv {}
564 impl ObjectImpl for EpisodeWidgetPriv {}
565 impl BoxImpl for EpisodeWidgetPriv {}
566
567 glib::wrapper! {
568 pub struct EpisodeWidget(ObjectSubclass<EpisodeWidgetPriv>)
569 @extends gtk::Box, gtk::Widget,
570 @implements gtk::Accessible, gtk::Buildable, gtk::ConstraintTarget;
571 }
572
573 impl EpisodeWidget {
574 pub(crate) fn new(
575 sender: &Sender<Action>,
576 episode: EpisodeWidgetModel,
577 add_show_link: bool,
578 ) -> Self {
579 let widget = Self::default();
580 widget.init(sender, episode, add_show_link);
581 widget
582 }
583
584 pub(crate) fn init(
585 &self,
586 sender: &Sender<Action>,
587 episode: EpisodeWidgetModel,
588 add_show_link: bool,
589 ) {
590 self.imp().init(sender, episode, add_show_link);
591 }
592
593 pub(crate) fn id(&self) -> EpisodeId {
594 self.imp().episode_id.get().unwrap()
595 }
596
597 pub(crate) fn update_episode_state(&self, ep: &EpisodeWidgetModel) {
598 let imp = self.imp();
599 if let Err(err) = imp.determine_buttons_state(ep) {
600 error!("Failed to update episode widget buttons {err}");
601 }
602 imp.set_played(ep.played().is_some())
603 }
604 }
605
606 impl Default for EpisodeWidget {
607 fn default() -> Self {
608 let widget: Self = glib::Object::new();
609 widget
610 }
611 }