Debian Codegraph @

podcasts-gtk/src/window.rs

raw symbols SCIP
1 // window.rs
2 //
3 // Copyright 2019 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::prelude::*;
21 use adw::subclass::prelude::*;
22 use anyhow::Result;
23 use async_channel::Sender;
24 use glib::clone;
25 use gst::ClockTime;
26 use gtk::CompositeTemplate;
27 use gtk::{gio, glib};
28 use std::cell::{Cell, OnceCell, RefCell};
29 use std::cell::{Ref, RefMut};
30 use std::ops::Deref;
31 use std::rc::Rc;
32 use std::sync::Arc;
33
34 use crate::app::{Action, PdApplication};
35 use crate::config::APP_ID;
36 use crate::feed_manager::FEED_MANAGER;
37 use crate::settings::{self, WindowGeometry};
38 use crate::utils;
39 use crate::widgets::about_dialog;
40 use crate::widgets::player;
41 use crate::widgets::player::{PlayerExt, PlayerWidget, SeekDirection, StreamMode};
42 use crate::widgets::{Content, DiscoveryPage, EpisodeDescription, ShowWidget};
43 use podcasts_data::dbqueries;
44 use podcasts_data::{EpisodeId, EpisodeWidgetModel, ShowId};
45
46 #[derive(Debug, CompositeTemplate, glib::Properties)]
47 #[template(resource = "/org/gnome/Podcasts/gtk/window.ui")]
48 #[properties(wrapper_type = MainWindow)]
49 pub struct MainWindowPriv {
50 pub(crate) content: OnceCell<Rc<Content>>,
51 pub(crate) player: OnceCell<player::PlayerWrapper>,
52 pub(crate) updating_timeout: RefCell<Option<glib::source::SourceId>>,
53 pub(crate) settings: gio::Settings,
54 pub(crate) show_widget: RefCell<Option<ShowWidget>>,
55
56 pub(crate) sender: OnceCell<Sender<Action>>,
57
58 #[template_child]
59 pub(crate) top_switcher: TemplateChild<adw::ViewSwitcher>,
60 #[template_child]
61 pub(crate) content_view: TemplateChild<adw::ToolbarView>,
62 #[template_child]
63 pub(crate) player_toolbar_view: TemplateChild<adw::ToolbarView>,
64 #[template_child]
65 pub(crate) bottom_sheet: TemplateChild<adw::BottomSheet>,
66 #[template_child]
67 pub(crate) bottom_switcher: TemplateChild<adw::ViewSwitcher>,
68 #[template_child]
69 pub(crate) bottom_switcher_bar: TemplateChild<gtk::CenterBox>,
70 #[template_child]
71 pub(crate) toolbar_box: TemplateChild<gtk::Box>,
72 #[template_child]
73 pub(crate) toast_overlay: TemplateChild<adw::ToastOverlay>,
74 #[template_child]
75 pub(crate) navigation_view: TemplateChild<adw::NavigationView>,
76 #[template_child]
77 pub(crate) header_breakpoint: TemplateChild<adw::Breakpoint>,
78 #[template_child]
79 pub(crate) player_breakpoint: TemplateChild<adw::Breakpoint>,
80 #[template_child]
81 pub(crate) show_page: TemplateChild<adw::NavigationPage>,
82
83 #[property(set, get)]
84 pub(crate) updating: Cell<bool>,
85 #[property(set, get)]
86 pub(crate) is_root_page: Cell<bool>, // for bottom switcher visibility
87 #[property(set, get)]
88 pub(crate) is_mobile_layout: Cell<bool>, // for bottom switcher visibility
89 }
90
91 #[glib::object_subclass]
92 impl ObjectSubclass for MainWindowPriv {
93 const NAME: &'static str = "PdMainWindow";
94 type Type = MainWindow;
95 type ParentType = adw::ApplicationWindow;
96
97 fn new() -> Self {
98 let settings = gio::Settings::new(APP_ID);
99
100 Self {
101 content: OnceCell::new(),
102 player: OnceCell::new(),
103 navigation_view: TemplateChild::default(),
104 toast_overlay: TemplateChild::default(),
105 top_switcher: TemplateChild::default(),
106 content_view: TemplateChild::default(),
107 player_toolbar_view: TemplateChild::default(),
108 bottom_sheet: TemplateChild::default(),
109 bottom_switcher: TemplateChild::default(),
110 bottom_switcher_bar: TemplateChild::default(),
111 toolbar_box: TemplateChild::default(),
112 header_breakpoint: TemplateChild::default(),
113 player_breakpoint: TemplateChild::default(),
114 show_page: TemplateChild::default(),
115 updating: Cell::new(false),
116 updating_timeout: RefCell::new(None),
117 sender: OnceCell::new(),
118 show_widget: RefCell::new(None),
119 is_root_page: Cell::new(true),
120 is_mobile_layout: Cell::new(false),
121 settings,
122 }
123 }
124
125 fn class_init(klass: &mut Self::Class) {
126 klass.bind_template();
127 klass.install_action("win.refresh", None, move |win, _, _| {
128 let sender = win.sender();
129 FEED_MANAGER.schedule_full_refresh(sender);
130 });
131 klass.install_action_async("win.import", None, |win, _, _| async move {
132 let sender = win.sender();
133 utils::on_import_clicked(win.upcast_ref(), sender).await;
134 });
135 klass.install_action_async("win.export", None, |win, _, _| async move {
136 let sender = win.sender();
137 utils::on_export_clicked(win.upcast_ref(), sender).await;
138 });
139 klass.install_action("win.about", None, move |win, _, _| {
140 about_dialog(win.upcast_ref());
141 });
142 klass.install_action("win.toggle-pause", None, move |win, _, _| {
143 win.player_mut().toggle_pause();
144 });
145 klass.install_action("win.seek-forwards", None, move |win, _, _| {
146 win.player()
147 .seek(ClockTime::from_seconds(10), SeekDirection::Forward);
148 });
149 klass.install_action("win.seek-backwards", None, move |win, _, _| {
150 win.player()
151 .seek(ClockTime::from_seconds(5), SeekDirection::Backwards);
152 });
153 klass.install_action("win.go-to-home", None, move |win, _, _| {
154 win.pop_to_content();
155 win.content().go_to_home();
156 });
157 klass.install_action("win.go-to-shows", None, move |win, _, _| {
158 win.pop_to_content();
159 win.content().go_to_shows();
160 });
161 klass.install_action("win.go-to-discovery", None, move |win, _, _| {
162 win.go_to_discovery();
163 });
164 klass.install_action("win.close-bottom-sheet", None, move |win, _, _| {
165 win.imp().bottom_sheet.set_open(false);
166 });
167 klass.install_action("win.raise-playback-rate", None, move |win, _, _| {
168 win.player().change_playback_rate(0.25);
169 });
170 klass.install_action("win.lower-playback-rate", None, move |win, _, _| {
171 win.player().change_playback_rate(-0.25);
172 });
173 }
174
175 fn instance_init(obj: &glib::subclass::InitializingObject<Self>) {
176 obj.init_template();
177 }
178 }
179
180 #[glib::derived_properties]
181 impl ObjectImpl for MainWindowPriv {
182 fn constructed(&self) {
183 let window = self.obj();
184 self.parent_constructed();
185
186 if APP_ID.ends_with("Devel") {
187 window.add_css_class("devel");
188 }
189
190 // Retrieve the previous window position and size.
191 WindowGeometry::from_settings(&self.settings).apply(window.upcast_ref());
192 }
193 }
194
195 impl WidgetImpl for MainWindowPriv {}
196 impl WindowImpl for MainWindowPriv {
197 // Save window state on delete event
198 fn close_request(&self) -> glib::Propagation {
199 let obj = self.obj();
200 info!("Saving window position");
201
202 WindowGeometry::from_window(obj.upcast_ref()).write(&self.settings);
203
204 self.parent_close_request()
205 }
206 }
207 impl ApplicationWindowImpl for MainWindowPriv {}
208 impl AdwApplicationWindowImpl for MainWindowPriv {}
209
210 glib::wrapper! {
211 pub struct MainWindow(ObjectSubclass<MainWindowPriv>)
212 @extends gtk::Widget, gtk::Window, gtk::ApplicationWindow, adw::ApplicationWindow,
213 @implements gio::ActionMap, gio::ActionGroup, gtk::ConstraintTarget, gtk::Accessible, gtk::Buildable, gtk::ShortcutManager, gtk::Native, gtk::Root;
214 }
215
216 impl MainWindow {
217 pub(crate) fn new(app: &PdApplication, sender: &Sender<Action>) -> Self {
218 let window: Self = glib::Object::builder().property("application", app).build();
219 let imp = window.imp();
220 let content = Content::new(sender.clone());
221
222 imp.sender.set(sender.clone()).unwrap();
223
224 imp.content_view.set_content(Some(content.overlay()));
225
226 let player = player::PlayerWrapper::new(sender);
227 imp.toolbar_box.prepend(&player.borrow().container);
228
229 imp.bottom_sheet
230 .set_property("sheet", &player.borrow().sheet);
231 imp.bottom_sheet.connect_open_notify(clone!(
232 #[weak]
233 window,
234 move |sheet| {
235 window.player().sheet().on_open_changed(sheet.is_open());
236 }
237 ));
238
239 imp.top_switcher.set_stack(Some(content.stack()));
240 imp.bottom_switcher.set_stack(Some(content.stack()));
241
242 imp.navigation_view.connect_popped(clone!(
243 #[weak]
244 imp,
245 #[weak]
246 window,
247 move |_, _| {
248 if imp
249 .navigation_view
250 .visible_page()
251 .map(|p| p.tag().as_ref().map(|s| s.as_str()) == Some("content"))
252 .unwrap_or(false)
253 {
254 window.set_is_root_page(true);
255 }
256 }
257 ));
258
259 // Update Bottom switcher visibility
260 let update_bottom_switcher_visible = move |window: &MainWindow| {
261 window
262 .bottom_switcher_bar()
263 .set_visible(window.is_root_page() && window.is_mobile_layout());
264 };
265 window.connect_is_root_page_notify(update_bottom_switcher_visible);
266 window.connect_is_mobile_layout_notify(update_bottom_switcher_visible);
267
268 // Setup breakpoints
269 imp.header_breakpoint
270 .add_setter(&window, "is_mobile_layout", Some(&true.to_value()));
271 let p = player.deref();
272 imp.player_breakpoint.connect_apply(clone!(
273 #[weak]
274 p,
275 move |_| {
276 p.borrow().set_small(false);
277 }
278 ));
279 imp.player_breakpoint.connect_unapply(clone!(
280 #[weak]
281 p,
282 move |_| {
283 p.borrow().set_small(true);
284 }
285 ));
286 let breakpoint = imp.player_breakpoint.get();
287 let is_small = window.current_breakpoint().is_none_or(|b| b != breakpoint);
288 p.borrow().set_small(is_small);
289
290 // Update the feeds right after the Window is initialized.
291 if imp.settings.boolean("refresh-on-startup") {
292 info!("Refresh on startup.");
293 FEED_MANAGER.schedule_full_refresh(sender);
294 }
295
296 let refresh_interval = settings::get_refresh_interval(&imp.settings).num_seconds() as u32;
297 info!("Auto-refresh every {:?} seconds.", refresh_interval);
298
299 glib::timeout_add_seconds_local(
300 refresh_interval,
301 clone!(
302 #[strong]
303 sender,
304 move || {
305 FEED_MANAGER.schedule_full_refresh(&sender);
306 glib::ControlFlow::Continue
307 }
308 ),
309 );
310
311 imp.content.set(content).unwrap();
312 imp.player.set(player).unwrap();
313
314 window
315 }
316
317 pub fn push_page<P: IsA<adw::NavigationPage>>(&self, page: &P) {
318 self.imp().navigation_view.push(page);
319 self.set_is_root_page(false);
320 }
321
322 fn pop_to_show_widget(&self) {
323 let imp = self.imp();
324 let is_current_page = imp
325 .navigation_view
326 .visible_page()
327 .and_then(|p| p.tag())
328 .is_some_and(|t| t != "show");
329 if !is_current_page {
330 imp.navigation_view.pop_to_tag("show");
331 }
332 }
333
334 fn pop_to_content(&self) {
335 self.imp().navigation_view.pop_to_tag("content");
336 }
337
338 pub(crate) fn init_episode(
339 &self,
340 id: EpisodeId,
341 second: Option<i32>,
342 stream: StreamMode,
343 ) -> Result<()> {
344 self.imp()
345 .bottom_sheet
346 .set_property("can-open", true.to_value());
347 self.imp()
348 .player
349 .get()
350 .unwrap()
351 .borrow_mut()
352 .initialize_episode(self.sender(), id, stream, second)
353 }
354
355 pub(crate) fn add_toast(&self, toast: adw::Toast) {
356 self.imp().toast_overlay.add_toast(toast);
357 }
358
359 pub(crate) fn set_updating_timeout(&self, timeout: Option<glib::source::SourceId>) {
360 if let Some(old_timeout) = self.imp().updating_timeout.replace(timeout) {
361 old_timeout.remove();
362 }
363 }
364
365 pub(crate) fn progress_bar(&self) -> &gtk::ProgressBar {
366 self.content().progress_bar()
367 }
368
369 pub(crate) fn player(&self) -> Ref<'_, PlayerWidget> {
370 self.imp().player.get().unwrap().borrow()
371 }
372
373 pub(crate) fn player_mut(&self) -> RefMut<'_, PlayerWidget> {
374 self.imp().player.get().unwrap().borrow_mut()
375 }
376
377 pub(crate) fn content(&self) -> &Content {
378 self.imp().content.get().unwrap()
379 }
380
381 pub(crate) fn top_switcher(&self) -> &adw::ViewSwitcher {
382 &self.imp().top_switcher
383 }
384
385 pub(crate) fn bottom_switcher_bar(&self) -> &gtk::CenterBox {
386 &self.imp().bottom_switcher_bar
387 }
388
389 pub(crate) fn sender(&self) -> &Sender<Action> {
390 self.imp().sender.get().unwrap()
391 }
392
393 pub(crate) fn go_to_discovery(&self) {
394 let widget = DiscoveryPage::new(self.sender());
395 self.push_page(&widget);
396 }
397
398 pub(crate) fn replace_show_widget(&self, widget: Option<ShowWidget>, title: &str) {
399 let imp = self.imp();
400 let is_current_page = imp
401 .navigation_view
402 .visible_page()
403 .is_some_and(|p| p == *imp.show_page);
404 imp.show_page.set_child(widget.as_ref());
405 if let Some(widget) = widget.as_ref() {
406 imp.show_page.set_title(title);
407 self.bind_property("is_mobile_layout", widget, "is_mobile_layout")
408 .flags(glib::BindingFlags::SYNC_CREATE)
409 .build();
410 } else if is_current_page {
411 imp.navigation_view.pop();
412 }
413 imp.show_widget.replace(widget);
414 }
415
416 pub(crate) fn update_show_widget(&self, show_id: ShowId) -> Result<()> {
417 let imp = self.imp();
418 let same = imp.show_widget.borrow().as_ref().and_then(|s| s.show_id()) == Some(show_id);
419 if same {
420 let pd = dbqueries::get_podcast_from_id(show_id)?;
421 let widget = ShowWidget::new(Arc::new(pd), self.sender());
422 self.replace_show_widget(Some(widget), &imp.show_page.title());
423 }
424 Ok(())
425 }
426
427 pub(crate) fn update_show_widget_episode(&self, ep: &EpisodeWidgetModel) {
428 let imp = self.imp();
429 let show_id = ep.show_id();
430 let same = imp.show_widget.borrow().as_ref().and_then(|s| s.show_id()) == Some(show_id);
431 if same {
432 if let Some(show_widget) = imp.show_widget.borrow().as_ref() {
433 show_widget.update_episode(ep);
434 }
435 }
436 }
437
438 pub(crate) fn go_to_show_widget(&self) {
439 let imp = self.imp();
440 let is_current_page = imp
441 .navigation_view
442 .visible_page()
443 .is_some_and(|p| p == *imp.show_page);
444 if !is_current_page {
445 self.pop_to_show_widget();
446 imp.navigation_view.push(&*imp.show_page);
447 self.set_is_root_page(false);
448 }
449 }
450
451 pub(crate) fn pop_show_widget(&self) {
452 let imp = self.imp();
453 let is_current_page = imp
454 .navigation_view
455 .visible_page()
456 .is_some_and(|p| p == *imp.show_page);
457 if is_current_page {
458 imp.navigation_view.pop();
459 }
460 }
461
462 pub(crate) fn pop_page<T: IsA<adw::NavigationPage>>(&self) {
463 let imp = self.imp();
464 let is_current_page = imp
465 .navigation_view
466 .visible_page()
467 .is_some_and(|p| p.downcast::<T>().is_ok());
468
469 if is_current_page {
470 imp.navigation_view.pop();
471 }
472 }
473
474 pub(crate) fn pop_page_by_tag(&self, tag: &str) {
475 let imp = self.imp();
476 let is_current_page = imp
477 .navigation_view
478 .visible_page()
479 .and_then(|p| p.tag().map(|s| s == tag))
480 .unwrap_or(false);
481
482 if is_current_page {
483 imp.navigation_view.pop();
484 }
485 }
486
487 pub(crate) fn episode_description(&self) -> Option<EpisodeDescription> {
488 let imp = self.imp();
489 imp.navigation_view
490 .visible_page()
491 .and_then(|p| p.downcast::<EpisodeDescription>().ok())
492 }
493 }