Debian Codegraph @

podcasts-gtk/src/app.rs

raw symbols SCIP
1 // app.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::{Receiver, Sender};
23 use gettextrs::{LocaleCategory, bindtextdomain, setlocale, textdomain};
24 use glib::clone;
25 use gtk::prelude::*;
26 use gtk::{gio, glib};
27 use std::cell::RefCell;
28 use std::collections::HashSet;
29 use std::env;
30 use std::sync::Arc;
31
32 use crate::chapter_parser::Chapter;
33 use crate::config::{APP_ID, LOCALEDIR};
34 use crate::download_covers;
35 use crate::feed_manager::FeedManager;
36 use crate::i18n::i18n;
37 use crate::settings;
38 use crate::utils;
39 use crate::widgets::player::StreamMode;
40 use crate::widgets::show_menu::{mark_all_notif, remove_show_notif};
41 use crate::widgets::{Chapters, EpisodeDescription, SearchResults, ShowWidget};
42 use crate::window::MainWindow;
43 use podcasts_data::dbqueries;
44 use podcasts_data::discovery::FoundPodcast;
45 use podcasts_data::{Episode, EpisodeId, EpisodeModel, Show, ShowId};
46
47 // FIXME: port Optionals to OnceCell
48 #[derive(Debug)]
49 pub struct PdApplicationPrivate {
50 sender: Sender<Action>,
51 receiver: RefCell<Option<Receiver<Action>>>,
52 window: RefCell<Option<MainWindow>>,
53 settings: RefCell<Option<gio::Settings>>,
54 inhibit_cookie: RefCell<u32>,
55 todo_unsub_ids: RefCell<HashSet<ShowId>>,
56 undo_marked_ids: RefCell<Vec<ShowId>>,
57 }
58
59 #[glib::object_subclass]
60 impl ObjectSubclass for PdApplicationPrivate {
61 const NAME: &'static str = "PdApplication";
62 type Type = PdApplication;
63 type ParentType = adw::Application;
64
65 fn new() -> Self {
66 let (sender, r) = async_channel::unbounded();
67 let receiver = RefCell::new(Some(r));
68
69 Self {
70 sender: sender.clone(),
71 receiver,
72 window: RefCell::new(None),
73 settings: RefCell::new(None),
74 inhibit_cookie: RefCell::new(0),
75 todo_unsub_ids: RefCell::new(HashSet::default()),
76 undo_marked_ids: RefCell::new(vec![]),
77 }
78 }
79 }
80
81 impl ObjectImpl for PdApplicationPrivate {}
82
83 impl ApplicationImpl for PdApplicationPrivate {
84 fn activate(&self) {
85 debug!("GtkApplication<PdApplication>::activate");
86
87 self.parent_activate();
88
89 if let Some(ref window) = *self.window.borrow() {
90 // Ideally Gtk4/GtkBuilder make this irrelvent
91 window.present();
92 info!("Window presented");
93 return;
94 }
95
96 let app = self.obj();
97 app.setup_gactions();
98
99 let window = MainWindow::new(&app, &self.sender);
100 window.present();
101 self.window.replace(Some(window));
102
103 app.setup_accels();
104
105 // Setup action channel
106 let receiver = self.receiver.take().unwrap();
107 crate::MAINCONTEXT.spawn_local(clone!(
108 #[weak]
109 app,
110 async move {
111 while let Ok(action) = receiver.recv().await {
112 app.do_action(action);
113 }
114 }
115 ));
116 }
117
118 fn startup(&self) {
119 debug!("GtkApplication<PdApplication>::startup");
120
121 self.parent_startup();
122
123 let settings = gio::Settings::new(APP_ID);
124
125 let cleanup_date = settings::get_cleanup_date(&settings);
126 // Garbage collect watched episodes from the disk
127 utils::cleanup(cleanup_date);
128
129 self.settings.replace(Some(settings));
130 }
131
132 fn shutdown(&self) {
133 // complete any pending unsubscribe actions
134 let mut todo_unsub_ids = self.todo_unsub_ids.borrow_mut();
135 for id in todo_unsub_ids.drain() {
136 if let Ok(pd) = dbqueries::get_podcast_from_id(id) {
137 if let Err(err) = podcasts_data::utils::delete_show(&pd) {
138 error!("Error: {}", err);
139 error!("Failed to delete {}", pd.title());
140 }
141 }
142 }
143 if let Err(err) = download_covers::clean_unfinished_downloads() {
144 error!("Failed to cleanup downloads: {err}");
145 }
146
147 self.parent_shutdown();
148 }
149 }
150
151 impl GtkApplicationImpl for PdApplicationPrivate {}
152 impl AdwApplicationImpl for PdApplicationPrivate {}
153
154 glib::wrapper! {
155 pub struct PdApplication(ObjectSubclass<PdApplicationPrivate>)
156 @extends gio::Application, gtk::Application, adw::Application,
157 @implements gio::ActionMap, gio::ActionGroup;
158 }
159
160 #[derive(Debug, Clone)]
161 pub(crate) enum Action {
162 RefreshAllViews,
163 RefreshEpisodesView,
164 RefreshEpisode(EpisodeId),
165 RefreshShowsView,
166 ReplaceWidget(Arc<Show>),
167 RefreshWidgetIfSame(ShowId),
168 GoToEpisodeDescription(Arc<Show>, Arc<Episode>),
169 GoToShow(Arc<Show>),
170 GoToFoundPodcasts(Arc<Vec<FoundPodcast>>),
171 GoToChaptersPage(EpisodeId, Vec<Chapter>),
172 ChaptersAvailable(EpisodeId, Vec<Chapter>),
173 CopiedUrlNotification,
174 CopyUrl(EpisodeId),
175 MarkAllPlayerNotification(Arc<Show>),
176 MarkAsPlayed(bool, EpisodeId),
177 FeedRefreshed(u64),
178 StartUpdating,
179 StopUpdating,
180 RemoveShow(Arc<Show>),
181 ErrorNotification(String),
182 InitEpisode(EpisodeId),
183 InitEpisodeAt(EpisodeId, i32),
184 StreamEpisode(EpisodeId),
185 UpdateMprisCover(ShowId, bool), // bool = download success, use local file
186 EmptyState,
187 PopulatedState,
188 RaiseWindow,
189 InhibitSuspend,
190 UninhibitSuspend,
191 }
192
193 impl PdApplication {
194 pub(crate) fn new() -> Self {
195 glib::Object::builder()
196 .property("application-id", APP_ID)
197 .property("resource-base-path", "/org/gnome/Podcasts")
198 .build()
199 }
200
201 fn setup_gactions(&self) {
202 let i32_variant_type = glib::VariantTy::INT32;
203 let actions = [
204 gio::ActionEntryBuilder::new("quit")
205 .activate(|app: &Self, _, _| {
206 app.quit();
207 })
208 .build(),
209 gio::ActionEntryBuilder::new("go-to-episode")
210 .parameter_type(Some(i32_variant_type))
211 .activate(|app: &Self, _, id_variant_option| {
212 if let Err(e) = app.go_to_episode(id_variant_option) {
213 error!("failed action app.go-to-episode: {e}");
214 }
215 })
216 .build(),
217 gio::ActionEntryBuilder::new("go-to-show")
218 .parameter_type(Some(i32_variant_type))
219 .activate(|app: &Self, _, id_variant_option| {
220 if let Err(e) = app.go_to_show(id_variant_option) {
221 error!("failed action app.go-to-show: {e}");
222 }
223 })
224 .build(),
225 gio::ActionEntryBuilder::new("undo-mark-all")
226 .parameter_type(Some(i32_variant_type))
227 .activate(|app: &Self, _, id_variant_option| {
228 let data = app.imp();
229 let id = ShowId(id_variant_option.unwrap().get::<i32>().unwrap());
230 let mut ids = data.undo_marked_ids.borrow_mut();
231 if !ids.contains(&id) {
232 ids.push(id);
233 }
234
235 send_blocking!(data.sender, Action::RefreshWidgetIfSame(id));
236 })
237 .build(),
238 gio::ActionEntryBuilder::new("undo-remove-show")
239 .parameter_type(Some(i32_variant_type))
240 .activate(|app: &Self, _, id_variant_option| {
241 let data = app.imp();
242 let id = ShowId(id_variant_option.unwrap().get::<i32>().unwrap());
243 let mut ids = data.todo_unsub_ids.borrow_mut();
244 ids.remove(&id);
245
246 let res = utils::unignore_show(id);
247 debug_assert!(res.is_ok());
248 send_blocking!(data.sender, Action::RefreshAllViews);
249 })
250 .build(),
251 ];
252 self.add_action_entries(actions);
253 }
254
255 /// We check if a show is still on the todo_remove list.
256 /// Also removes it from the list,
257 /// as this should only be called before removal.
258 pub fn is_show_marked_delete(&self, pd: &Show) -> bool {
259 let data = self.imp();
260 let id = pd.id();
261 let mut todo_unsub_ids = data.todo_unsub_ids.borrow_mut();
262
263 todo_unsub_ids.remove(&id)
264 }
265
266 pub fn is_show_marked_mark(&self, pd: &Show) -> bool {
267 let data = self.imp();
268 let id = pd.id();
269 let mut undo_marked_ids = data.undo_marked_ids.borrow_mut();
270
271 if let Some(pos) = undo_marked_ids.iter().position(|x| *x == id) {
272 undo_marked_ids.remove(pos);
273
274 return false;
275 }
276
277 true
278 }
279
280 fn go_to_episode(&self, id_variant_option: Option<&glib::Variant>) -> Result<()> {
281 let id_variant = id_variant_option.expect("missing action_target_value");
282 let id = id_variant.get::<i32>().expect("invalid variant type");
283 let ep = dbqueries::get_episode_from_id(EpisodeId(id))?;
284 let show = dbqueries::get_podcast_from_id(ep.show_id())?;
285 let data = self.imp();
286 send_blocking!(
287 data.sender,
288 Action::GoToEpisodeDescription(Arc::new(show), Arc::new(ep))
289 );
290 Ok(())
291 }
292
293 fn go_to_show(&self, id_variant_option: Option<&glib::Variant>) -> Result<()> {
294 let id_variant = id_variant_option.expect("missing action_target_value");
295 let id = id_variant.get::<i32>().expect("invalid variant type");
296 let show = dbqueries::get_podcast_from_id(ShowId(id))?;
297 let data = self.imp();
298 send_blocking!(data.sender, Action::GoToShow(Arc::new(show)));
299 Ok(())
300 }
301
302 fn setup_accels(&self) {
303 self.set_accels_for_action("app.quit", &["<primary>q"]);
304 self.set_accels_for_action("win.refresh", &["<primary>r", "F5"]);
305 self.set_accels_for_action("win.toggle-pause", &["<primary>space"]);
306 self.set_accels_for_action("win.seek-forwards", &["<primary>Right"]);
307 self.set_accels_for_action("win.seek-backwards", &["<primary>Left"]);
308 self.set_accels_for_action("win.raise-playback-rate", &["<primary>greater"]);
309 self.set_accels_for_action("win.lower-playback-rate", &["<primary>less"]);
310 self.set_accels_for_action("win.go-to-home", &["F1", "<alt>1"]);
311 self.set_accels_for_action("win.go-to-shows", &["F2", "<alt>2"]);
312 // plan: use F3 for Queue page
313 self.set_accels_for_action("win.go-to-discovery", &["F4", "<alt>4", "<primary>n"]);
314 self.set_accels_for_action("win.import", &["<primary>o"]);
315 self.set_accels_for_action("win.export", &["<primary>e"]);
316 self.set_accels_for_action("window.close", &["<primary>w"]);
317 // Make sure to add new shortcuts to shortcuts-dialog.ui !!!
318 }
319
320 fn do_action(&self, action: Action) {
321 let data = self.imp();
322 let w = data.window.borrow();
323 let window = w.as_ref().expect("Window is not initialized");
324
325 info!("Incoming channel action: {:?}", action);
326 match action {
327 Action::RefreshAllViews => window.content().update(),
328 Action::RefreshShowsView => window.content().update_shows(),
329 Action::RefreshWidgetIfSame(id) => {
330 if let Err(e) = window.update_show_widget(id) {
331 error!("failed to refresh show {e}");
332 }
333 }
334 Action::RefreshEpisode(id) => {
335 let ep = match dbqueries::get_episode_widget_from_id(id) {
336 Ok(ep) => ep,
337 Err(e) => {
338 error!("failed to fetch episode for description refresh {e}");
339 return;
340 }
341 };
342 window.content().update_home_episode(&ep);
343 window.update_show_widget_episode(&ep);
344 if let Some(description) = window.episode_description() {
345 if description.id() == id {
346 description.update_episode(&ep);
347 }
348 }
349 }
350 Action::RefreshEpisodesView => window.content().update_home(),
351 Action::ReplaceWidget(pd) => {
352 let widget = ShowWidget::new(pd.clone(), &data.sender);
353 window.replace_show_widget(Some(widget), pd.title());
354 }
355 Action::GoToEpisodeDescription(show, ep) => {
356 let description_widget = EpisodeDescription::new(ep, show, window.sender().clone());
357 window.pop_page::<EpisodeDescription>();
358 window.push_page(&description_widget);
359 }
360 Action::GoToShow(pd) => {
361 self.do_action(Action::ReplaceWidget(pd));
362 window.go_to_show_widget();
363 }
364 Action::GoToFoundPodcasts(found) => {
365 let widget = SearchResults::new(&found, window.sender());
366 window.push_page(&widget);
367 }
368 Action::GoToChaptersPage(ep, chapters) => {
369 let page = Chapters::new_page(&data.sender, window.player().slider(), ep, chapters);
370 window.pop_page_by_tag("chapters");
371 window.push_page(&page);
372 }
373 Action::ChaptersAvailable(ep, chapters) => {
374 window.player().chapters_available(ep, chapters);
375 }
376 Action::CopyUrl(id) => {
377 if let Some(uri) = dbqueries::get_episode_from_id(id)
378 .ok()
379 .and_then(|e| e.uri().map(|s| s.to_string()))
380 {
381 copy_text(&uri);
382 self.do_action(Action::CopiedUrlNotification);
383 }
384 }
385 Action::CopiedUrlNotification => {
386 let text = i18n("Copied URL to clipboard!");
387 let toast = adw::Toast::new(&text);
388 self.send_toast(toast);
389 }
390 Action::MarkAllPlayerNotification(pd) => {
391 let toast = mark_all_notif(pd, &data.sender);
392 self.send_toast(toast);
393 }
394 Action::MarkAsPlayed(played, id) => {
395 if let Ok(mut ep) = dbqueries::get_episode_widget_from_id(id) {
396 if played {
397 let _ = ep.set_played_now();
398 } else {
399 let _ = ep.set_unplayed();
400 }
401 if let Some(description) = window.episode_description() {
402 let pid = ep.show_id();
403 if let Ok(show) = dbqueries::get_podcast_from_id(pid) {
404 description.update_episode_menu(&data.sender, &ep, Arc::new(show));
405 }
406 }
407 self.do_action(Action::RefreshEpisode(ep.id()));
408 }
409 }
410 Action::RemoveShow(pd) => {
411 window.pop_show_widget();
412 window.pop_page::<EpisodeDescription>();
413 data.todo_unsub_ids.borrow_mut().insert(pd.id());
414 let toast = remove_show_notif(pd);
415 self.send_toast(toast);
416 if let Err(e) = window.content().check_empty_state() {
417 error!("Failed to check for empty db state {e}");
418 }
419 }
420 Action::ErrorNotification(err) => {
421 error!("An error notification was triggered: {}", err);
422 let toast = adw::Toast::new(&err);
423 window.add_toast(toast);
424 }
425 Action::StartUpdating => {
426 window.set_updating(true);
427 let progress = window.progress_bar();
428 let updating_timeout = glib::timeout_add_local(
429 std::time::Duration::from_millis(100),
430 clone!(
431 #[weak]
432 progress,
433 #[upgrade_or]
434 glib::ControlFlow::Break,
435 move || {
436 progress.set_visible(true);
437 progress.pulse();
438 glib::ControlFlow::Continue
439 }
440 ),
441 );
442 window.set_updating_timeout(Some(updating_timeout));
443 }
444 Action::StopUpdating => {
445 window.set_updating(false);
446 window.set_updating_timeout(None);
447 window.progress_bar().set_visible(false);
448 }
449 Action::FeedRefreshed(id) => {
450 FeedManager::refresh_done(data.sender.clone(), id);
451 }
452 Action::InitEpisode(id) => {
453 let res = window.init_episode(id, None, StreamMode::LocalOnly);
454 debug_assert!(res.is_ok());
455 }
456 Action::InitEpisodeAt(id, second) => {
457 let res = window.init_episode(id, Some(second), StreamMode::StreamFallback);
458 debug_assert!(res.is_ok());
459 }
460 Action::StreamEpisode(id) => {
461 let res = window.init_episode(id, None, StreamMode::StreamOnly);
462 debug_assert!(res.is_ok());
463 }
464 Action::UpdateMprisCover(id, dl_success) => {
465 let res = window.player().update_mpris_cover(id, dl_success);
466 debug_assert!(res.is_ok());
467 }
468 Action::EmptyState => {
469 if let Some(refresh_action) = window
470 .lookup_action("refresh")
471 .and_then(|action| action.downcast::<gio::SimpleAction>().ok())
472 {
473 refresh_action.set_enabled(false)
474 }
475
476 window.top_switcher().set_sensitive(false);
477 window.bottom_switcher_bar().set_sensitive(false);
478 window.content().switch_to_empty_views();
479 }
480 Action::PopulatedState => {
481 if let Some(refresh_action) = window
482 .lookup_action("refresh")
483 .and_then(|action| action.downcast::<gio::SimpleAction>().ok())
484 {
485 refresh_action.set_enabled(true)
486 }
487
488 window.top_switcher().set_sensitive(true);
489 window.bottom_switcher_bar().set_sensitive(true);
490 window.content().switch_to_populated();
491 }
492 Action::RaiseWindow => window.present(),
493 Action::InhibitSuspend => {
494 let window: Option<&gtk::Window> = None;
495 let old_cookie = *data.inhibit_cookie.borrow();
496 let cookie = self.inhibit(
497 window,
498 gtk::ApplicationInhibitFlags::SUSPEND,
499 Some("podcast playing"),
500 );
501 *data.inhibit_cookie.borrow_mut() = cookie;
502 if old_cookie != 0 {
503 self.uninhibit(old_cookie);
504 }
505 }
506 Action::UninhibitSuspend => {
507 let cookie = *data.inhibit_cookie.borrow();
508 if cookie != 0 {
509 self.uninhibit(cookie);
510 *data.inhibit_cookie.borrow_mut() = 0;
511 }
512 }
513 };
514 }
515
516 pub(crate) fn run() -> glib::ExitCode {
517 // Set up the textdomain for gettext
518 setlocale(LocaleCategory::LcAll, "");
519 bindtextdomain("gnome-podcasts", LOCALEDIR).expect("Unable to bind the text domain");
520 textdomain("gnome-podcasts").expect("Unable to switch to the text domain");
521
522 // Make sure the app icon shows up in PulseAudio settings
523 unsafe {
524 env::set_var("PULSE_PROP_application.icon_name", APP_ID);
525 }
526
527 let application = Self::new();
528
529 // Weird magic I copy-pasted that sets the Application Name in the Shell.
530 glib::set_application_name(&i18n("Podcasts"));
531 gtk::Window::set_default_icon_name(APP_ID);
532 let args: Vec<String> = env::args().collect();
533 ApplicationExtManual::run_with_args(&application, &args)
534 }
535
536 pub(crate) fn send_toast(&self, toast: adw::Toast) {
537 self.imp()
538 .window
539 .borrow()
540 .as_ref()
541 .unwrap()
542 .add_toast(toast);
543 }
544
545 /// Is currently playing this episode (and not paused/stopped).
546 pub(crate) fn is_playing(&self, id: EpisodeId) -> bool {
547 let w = self.imp().window.borrow();
548 let window = w.as_ref().expect("Window is not initialized");
549 let playing_id = window.player().id();
550 playing_id == Some(id) && window.player().is_playing()
551 }
552 }
553
554 fn copy_text(text: &str) -> Option<()> {
555 let display = gtk::gdk::Display::default()?;
556 let clipboard = display.clipboard();
557 clipboard.set_text(text);
558 Some(())
559 }