Debian Codegraph @

podcasts-gtk/src/widgets/home_view.rs

raw symbols SCIP
1 // home_view.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::subclass::InitializingObject;
25 use gtk::gio;
26 use gtk::{CompositeTemplate, glib, prelude::*};
27
28 use crate::app::Action;
29 use crate::utils::{self, lazy_load};
30 use crate::widgets::{BaseView, EpisodeWidget};
31 use podcasts_data::dbqueries;
32 use podcasts_data::{EpisodeId, EpisodeModel, EpisodeWidgetModel, ShowId};
33
34 #[derive(Debug, Clone)]
35 enum ListSplit {
36 Today,
37 Yday,
38 Week,
39 Month,
40 Rest,
41 }
42
43 #[derive(Debug, Clone)]
44 struct DateBox(ListSplit, Vec<EpisodeWidgetModel>);
45
46 #[derive(Debug, CompositeTemplate, Default)]
47 #[template(resource = "/org/gnome/Podcasts/gtk/home_view.ui")]
48 pub struct HomeViewPriv {
49 #[template_child]
50 view: TemplateChild<BaseView>,
51 #[template_child]
52 today_box: TemplateChild<gtk::Box>,
53 #[template_child]
54 yday_box: TemplateChild<gtk::Box>,
55 #[template_child]
56 week_box: TemplateChild<gtk::Box>,
57 #[template_child]
58 month_box: TemplateChild<gtk::Box>,
59 #[template_child]
60 rest_box: TemplateChild<gtk::Box>,
61 #[template_child]
62 today_list: TemplateChild<gtk::ListBox>,
63 #[template_child]
64 yday_list: TemplateChild<gtk::ListBox>,
65 #[template_child]
66 week_list: TemplateChild<gtk::ListBox>,
67 #[template_child]
68 month_list: TemplateChild<gtk::ListBox>,
69 #[template_child]
70 rest_list: TemplateChild<gtk::ListBox>,
71 }
72
73 #[glib::object_subclass]
74 impl ObjectSubclass for HomeViewPriv {
75 const NAME: &'static str = "PdHomeView";
76 type Type = HomeView;
77 type ParentType = adw::Bin;
78
79 fn class_init(klass: &mut Self::Class) {
80 BaseView::ensure_type();
81 klass.bind_template();
82 }
83
84 fn instance_init(obj: &InitializingObject<Self>) {
85 obj.init_template();
86 }
87 }
88
89 impl WidgetImpl for HomeViewPriv {}
90 impl ObjectImpl for HomeViewPriv {}
91 impl BinImpl for HomeViewPriv {}
92
93 glib::wrapper! {
94 pub struct HomeView(ObjectSubclass<HomeViewPriv>)
95 @extends BaseView, gtk::Widget, adw::Bin,
96 @implements gtk::Accessible, gtk::Buildable, gtk::ConstraintTarget;
97 }
98
99 impl HomeView {
100 pub(crate) fn new(sender: Sender<Action>) -> Self {
101 let home: Self = glib::Object::new();
102
103 crate::MAINCONTEXT.spawn_local_with_priority(
104 glib::source::Priority::DEFAULT_IDLE,
105 glib::clone!(
106 #[weak]
107 home,
108 async move {
109 let results = home.add_to_boxes(sender).await;
110 for result in results {
111 if let Err(e) = result {
112 log::error!("Error: {:?}", e);
113 }
114 }
115 }
116 ),
117 );
118
119 home
120 }
121
122 async fn add_to_boxes(&self, sender: Sender<Action>) -> Vec<Result<(), glib::JoinError>> {
123 let data = gio::spawn_blocking(get_episodes).await;
124
125 let mut handles = Vec::with_capacity(5);
126 if let Ok(Ok(data)) = data {
127 for datebox in data {
128 if datebox.1.is_empty() {
129 continue;
130 }
131
132 let handle = self.add_to_box(datebox, &sender);
133 handles.push(handle);
134 }
135 }
136
137 let results = futures_util::future::join_all(handles).await;
138 results.into_iter().flatten().collect()
139 }
140
141 async fn add_to_box(
142 &self,
143 datebox: DateBox,
144 sender: &Sender<Action>,
145 ) -> Vec<Result<(), glib::JoinError>> {
146 use self::ListSplit::*;
147
148 let DateBox(date, model) = datebox;
149
150 let box_ = match &date {
151 Today => &self.imp().today_box,
152 Yday => &self.imp().yday_box,
153 Week => &self.imp().week_box,
154 Month => &self.imp().month_box,
155 Rest => &self.imp().rest_box,
156 };
157
158 let list = match &date {
159 Today => &self.imp().today_list,
160 Yday => &self.imp().yday_list,
161 Week => &self.imp().week_list,
162 Month => &self.imp().month_list,
163 Rest => &self.imp().rest_list,
164 };
165
166 box_.set_visible(true);
167
168 let sender = sender.clone();
169 let constructor = move |ep: EpisodeWidgetModel| HomeEpisode::new(&sender, ep).upcast();
170 let list = list.upcast_ref::<gtk::Widget>().downgrade();
171 lazy_load(model, list, constructor.clone()).await
172 }
173
174 pub(crate) fn update_episode(&self, ep: &EpisodeWidgetModel) {
175 let imp = self.imp();
176 let id = ep.id();
177 let lists = [
178 &imp.today_list,
179 &imp.yday_list,
180 &imp.week_list,
181 &imp.month_list,
182 &imp.rest_list,
183 ];
184 for list in lists {
185 let mut i = 0;
186 while let Some(row) = list.row_at_index(i) {
187 if let Ok(home_episode) = row.downcast::<HomeEpisode>() {
188 if home_episode.id() == id {
189 home_episode.update(ep);
190 return;
191 }
192 }
193 i += 1;
194 }
195 }
196 }
197 }
198
199 fn get_episodes() -> Result<Vec<DateBox>> {
200 let ignore = utils::get_ignored_shows()?;
201 let episodes = dbqueries::get_episodes_widgets_filter_limit(&ignore, 100)?;
202 Ok(split_model(episodes))
203 }
204
205 fn split(now: &DateTime<Local>, ep: &DateTime<Local>) -> ListSplit {
206 let days_now = now.num_days_from_ce();
207 let days_ep = ep.num_days_from_ce();
208 let weekday = now.weekday().num_days_from_monday() as i32;
209
210 if days_ep == days_now {
211 ListSplit::Today
212 } else if days_ep == days_now - 1 {
213 ListSplit::Yday
214 } else if days_ep >= days_now - weekday {
215 ListSplit::Week
216 } else if now.month() == ep.month() && now.year() == ep.year() {
217 ListSplit::Month
218 } else {
219 ListSplit::Rest
220 }
221 }
222
223 fn split_model(model: Vec<EpisodeWidgetModel>) -> Vec<DateBox> {
224 use self::ListSplit::*;
225
226 let now = Local::now();
227
228 let (mut today, mut yday, mut week, mut month, mut rest) =
229 (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new());
230
231 for ep in model {
232 let epoch_local = DateTime::<Local>::from(ep.epoch().and_utc());
233 match split(&now, &epoch_local) {
234 Today => today.push(ep),
235 Yday => yday.push(ep),
236 Week => week.push(ep),
237 Month => month.push(ep),
238 Rest => rest.push(ep),
239 }
240 }
241
242 vec![
243 DateBox(Today, today),
244 DateBox(Yday, yday),
245 DateBox(Week, week),
246 DateBox(Month, month),
247 DateBox(Rest, rest),
248 ]
249 }
250
251 #[derive(Debug, CompositeTemplate, Default)]
252 #[template(resource = "/org/gnome/Podcasts/gtk/home_episode.ui")]
253 pub struct HomeEpisodePriv {
254 #[template_child]
255 cover: TemplateChild<gtk::Image>,
256 #[template_child]
257 episode: TemplateChild<EpisodeWidget>,
258 }
259
260 impl HomeEpisodePriv {
261 fn init(&self, sender: &Sender<Action>, episode: EpisodeWidgetModel) {
262 let pid = episode.show_id();
263 self.set_cover(pid);
264 self.episode.init(sender, episode, true);
265 // Assure the image is read out along with the Episode title
266 self.cover.set_accessible_role(gtk::AccessibleRole::Label);
267 }
268
269 fn set_cover(&self, show_id: ShowId) {
270 crate::download_covers::load_widget_texture(
271 &self.cover.get(),
272 show_id,
273 crate::Thumb64,
274 true,
275 );
276 }
277 }
278
279 #[glib::object_subclass]
280 impl ObjectSubclass for HomeEpisodePriv {
281 const NAME: &'static str = "PdHomeEpisode";
282 type Type = HomeEpisode;
283 type ParentType = gtk::ListBoxRow;
284
285 fn class_init(klass: &mut Self::Class) {
286 klass.bind_template();
287 }
288
289 fn instance_init(obj: &InitializingObject<Self>) {
290 obj.init_template();
291 }
292 }
293
294 impl WidgetImpl for HomeEpisodePriv {}
295 impl ObjectImpl for HomeEpisodePriv {}
296 impl ListBoxRowImpl for HomeEpisodePriv {}
297
298 glib::wrapper! {
299 pub struct HomeEpisode(ObjectSubclass<HomeEpisodePriv>)
300 @extends gtk::ListBoxRow, gtk::Widget,
301 @implements gtk::Accessible, gtk::Actionable, gtk::Buildable, gtk::ConstraintTarget;
302 }
303
304 impl HomeEpisode {
305 pub(crate) fn new(sender: &Sender<Action>, episode: EpisodeWidgetModel) -> Self {
306 let widget = Self::default();
307 widget.set_action_name(Some("app.go-to-episode"));
308 widget.set_action_target_value(Some(&episode.id().0.to_variant()));
309 widget.imp().init(sender, episode);
310 widget
311 }
312
313 pub(crate) fn id(&self) -> EpisodeId {
314 self.imp().episode.id()
315 }
316
317 pub(crate) fn update(&self, ep: &EpisodeWidgetModel) {
318 self.imp().episode.update_episode_state(ep);
319 }
320 }
321
322 impl Default for HomeEpisode {
323 fn default() -> Self {
324 let widget: Self = glib::Object::new();
325 widget
326 }
327 }