src/items/iteminfo.rs

403 lines · 15194 bytes

  1use tui::{
  2    layout::Rect,
  3    style::Style,
  4    widgets::{Paragraph, Wrap},
  5};
  6use tui_additions::framework::FrameworkItem;
  7#[cfg(any(feature = "sixel", feature = "halfblock"))]
  8use viuer::{print_from_file, Config};
  9
 10use crate::{
 11    config::{AppearanceConfig, MainConfig},
 12    global::structs::{Item, Status, Task, Tasks},
 13};
 14
 15/// an item info displays info of any `Item`s
 16#[derive(Clone)]
 17pub struct ItemInfo {
 18    pub item: Option<Item>,
 19    pub lazy_scroll: u16,
 20}
 21
 22impl FrameworkItem for ItemInfo {
 23    fn render(
 24        &mut self,
 25        frame: &mut tui::Frame<tui::backend::CrosstermBackend<std::io::Stdout>>,
 26        framework: &mut tui_additions::framework::FrameworkClean,
 27        area: tui::layout::Rect,
 28        popup_render: bool,
 29        _info: tui_additions::framework::ItemInfo,
 30    ) {
 31        if popup_render {
 32            return;
 33        }
 34
 35        let item = if let Some(item) = &self.item {
 36            item
 37        } else {
 38            return;
 39        };
 40
 41        let main_config = framework.data.global.get::<MainConfig>().unwrap();
 42        let status = framework.data.global.get::<Status>().unwrap();
 43
 44        // The scroll (space above) text info will be the height of the image, but if the image fail to display, the scroll will be 0
 45        let scroll = if !status.render_image {
 46            self.lazy_scroll
 47        } else if cfg!(any(feature = "halfblock", feature = "sixel"))
 48            && main_config.images.display()
 49            && !status.popup_opened
 50        {
 51            #[cfg(any(feature = "sixel", feature = "halfblock"))]
 52            let scroll;
 53
 54            #[cfg(not(any(feature = "sixel", feature = "halfblock")))]
 55            let scroll = 0;
 56
 57            #[cfg(any(feature = "sixel", feature = "halfblock"))]
 58            {
 59                let thumbnail_path = home::home_dir()
 60                    .unwrap()
 61                    .join(".cache/youtube-tui/thumbnails/")
 62                    .join(item.thumbnail_id());
 63                if thumbnail_path.exists() {
 64                    #[cfg(any(feature = "sixel", feature = "halfblock"))]
 65                    let config = Config {
 66                        // channel thumbnails are squares, limiting their maximum width can prevent the
 67                        // entire page being taken up by the image
 68                        width: Some(if let Item::MiniChannel(_) = item {
 69                            area.width / 2
 70                        } else if let Item::FullChannel(_) = item {
 71                            area.width / 4
 72                        } else {
 73                            area.width
 74                        } as u32),
 75                        x: area.x,
 76                        y: area.y as i16,
 77                        #[cfg(feature = "sixel")]
 78                        use_sixel: main_config.images.use_sixels(),
 79                        ..Default::default()
 80                    };
 81
 82                    if let Ok((_, height)) = print_from_file(thumbnail_path, &config) {
 83                        scroll = height as u16;
 84                        framework
 85                            .data
 86                            .state
 87                            .get_mut::<Tasks>()
 88                            .unwrap()
 89                            .priority
 90                            .push(Task::LazyRendered);
 91                    } else {
 92                        scroll = self.lazy_scroll;
 93                    }
 94                } else {
 95                    scroll = self.lazy_scroll;
 96                }
 97            }
 98            scroll
 99        } else {
100            self.lazy_scroll
101        };
102
103        self.lazy_scroll = scroll;
104
105        let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
106
107        // Each "span" contains a string and a Style, and they are one line max each
108        // A "text" is used for descriptions in video/playlist and channels, and starts a new line if the old one runs out
109        let (spans, text) = match item {
110            Item::MiniVideo(minivideo) => {
111                let mut out = (
112                    vec![
113                        (
114                            String::from("[Video]"),
115                            Style::default().fg(appearance.colors.item_info.tag),
116                        ),
117                        (
118                            minivideo.title.clone(),
119                            Style::default().fg(appearance.colors.item_info.title),
120                        ),
121                    ],
122                    minivideo.description.as_ref().map(|description| {
123                        (
124                            description.clone(),
125                            Style::default().fg(appearance.colors.item_info.description),
126                        )
127                    }),
128                );
129                if let Some(views) = &minivideo.views {
130                    out.0.push((
131                        format!("{} views", views),
132                        Style::default().fg(appearance.colors.item_info.viewcount),
133                    ));
134                }
135                out.0.push((
136                    format!("Length: {}", minivideo.length),
137                    Style::default().fg(appearance.colors.item_info.length),
138                ));
139                out.0.push((
140                    format!("Uploaded by {}", minivideo.channel),
141                    Style::default().fg(appearance.colors.item_info.author),
142                ));
143                if let Some(published) = &minivideo.published {
144                    out.0.push((
145                        format!("Published {}", published),
146                        Style::default().fg(appearance.colors.item_info.published),
147                    ));
148                }
149
150                out
151            }
152            Item::MiniPlaylist(miniplaylist) => (
153                vec![
154                    (
155                        String::from("[Playlist]"),
156                        Style::default().fg(appearance.colors.item_info.tag),
157                    ),
158                    (
159                        miniplaylist.title.clone(),
160                        Style::default().fg(appearance.colors.item_info.title),
161                    ),
162                    (
163                        format!("Created by by {}", miniplaylist.channel),
164                        Style::default().fg(appearance.colors.item_info.author),
165                    ),
166                    (
167                        format!(
168                            "{} video{}",
169                            miniplaylist.video_count,
170                            if miniplaylist.video_count <= 1 {
171                                ""
172                            } else {
173                                "s"
174                            }
175                        ),
176                        Style::default().fg(appearance.colors.item_info.video_count),
177                    ),
178                ],
179                None,
180            ),
181            Item::MiniChannel(minichannel) => (
182                vec![
183                    (
184                        String::from("[Channel]"),
185                        Style::default().fg(appearance.colors.item_info.tag),
186                    ),
187                    (
188                        minichannel.name.clone(),
189                        Style::default().fg(appearance.colors.item_info.title),
190                    ),
191                    (
192                        format!(
193                            "{} subscriber{}",
194                            minichannel.sub_count_text,
195                            if minichannel.sub_count <= 1 { "" } else { "s" }
196                        ),
197                        Style::default().fg(appearance.colors.item_info.sub_count),
198                    ),
199                    (
200                        format!(
201                            "{} video{}",
202                            minichannel.video_count,
203                            if minichannel.video_count <= 1 {
204                                ""
205                            } else {
206                                "s"
207                            }
208                        ),
209                        Style::default().fg(appearance.colors.item_info.video_count),
210                    ),
211                ],
212                Some((
213                    minichannel.description.clone(),
214                    Style::default().fg(appearance.colors.item_info.description),
215                )),
216            ),
217            Item::FullVideo(fullvideo) => (
218                vec![
219                    (
220                        String::from("[Video]"),
221                        Style::default().fg(appearance.colors.item_info.tag),
222                    ),
223                    (
224                        fullvideo.title.clone(),
225                        Style::default().fg(appearance.colors.item_info.title),
226                    ),
227                    (
228                        format!("{} views", fullvideo.views),
229                        Style::default().fg(appearance.colors.item_info.viewcount),
230                    ),
231                    (
232                        format!("{} likes", fullvideo.likes),
233                        Style::default().fg(appearance.colors.item_info.likes),
234                    ),
235                    (
236                        format!("Length: {}", fullvideo.length),
237                        Style::default().fg(appearance.colors.item_info.length),
238                    ),
239                    (
240                        format!(
241                            "Uploaded by {} ({} subscribers)",
242                            fullvideo.channel, fullvideo.sub_count
243                        ),
244                        Style::default().fg(appearance.colors.item_info.author),
245                    ),
246                    (
247                        format!("Published {}", fullvideo.published),
248                        Style::default().fg(appearance.colors.item_info.published),
249                    ),
250                ],
251                Some((
252                    fullvideo.description.clone(),
253                    Style::default().fg(appearance.colors.item_info.description),
254                )),
255            ),
256            Item::FullPlaylist(fullplaylist) => (
257                vec![
258                    (
259                        String::from("[Playlist]"),
260                        Style::default().fg(appearance.colors.item_info.tag),
261                    ),
262                    (
263                        fullplaylist.title.clone(),
264                        Style::default().fg(appearance.colors.item_info.title),
265                    ),
266                    (
267                        format!("Created by by {}", fullplaylist.channel),
268                        Style::default().fg(appearance.colors.item_info.author),
269                    ),
270                    (
271                        format!(
272                            "{} video{}",
273                            fullplaylist.video_count,
274                            if fullplaylist.video_count <= 1 {
275                                ""
276                            } else {
277                                "s"
278                            }
279                        ),
280                        Style::default().fg(appearance.colors.item_info.video_count),
281                    ),
282                ],
283                Some((
284                    fullplaylist.description.clone(),
285                    Style::default().fg(appearance.colors.item_info.description),
286                )),
287            ),
288            Item::FullChannel(fullchannel) => (
289                vec![
290                    (
291                        if fullchannel.autogenerated {
292                            String::from("[Auto generated]")
293                        } else {
294                            String::from("[Channel]")
295                        },
296                        Style::default().fg(appearance.colors.item_info.tag),
297                    ),
298                    (
299                        fullchannel.name.clone(),
300                        Style::default().fg(appearance.colors.item_info.title),
301                    ),
302                    (
303                        format!("{} total views", fullchannel.total_views),
304                        Style::default().fg(appearance.colors.item_info.viewcount),
305                    ),
306                    (
307                        format!(
308                            "{} subscriber{}",
309                            fullchannel.sub_count_text,
310                            if fullchannel.sub_count <= 1 { "" } else { "s" }
311                        ),
312                        Style::default().fg(appearance.colors.item_info.sub_count),
313                    ),
314                    (
315                        format!("Created at {}", fullchannel.created),
316                        Style::default().fg(appearance.colors.item_info.published),
317                    ),
318                ],
319                Some((
320                    fullchannel.description.clone(),
321                    Style::default().fg(appearance.colors.item_info.description),
322                )),
323            ),
324            Item::Unknown(searchitem_transitional) => (
325                vec![(
326                    format!("Unknown type `{}`", searchitem_transitional.r#type),
327                    Style::default().fg(appearance.colors.text_error),
328                )],
329                Some((
330                    serde_json::to_string(&searchitem_transitional).unwrap(),
331                    Style::default().fg(appearance.colors.item_info.description),
332                )),
333            ),
334            Item::Page(b) => (
335                vec![(
336                    if *b { "Next page" } else { "Previous page" }.to_string(),
337                    Style::default().fg(appearance.colors.item_info.page_turner),
338                )],
339                None,
340            ),
341        };
342
343        let mut y = if scroll >= area.height { 0 } else { scroll } + area.y;
344        let bottom = area.bottom();
345
346        // puts each "span" in its own line
347        for (text, style) in spans.into_iter().take((bottom - y) as usize) {
348            let paragraph = Paragraph::new(text).style(style);
349            frame.render_widget(
350                paragraph,
351                Rect {
352                    y,
353                    height: 1,
354                    ..area
355                },
356            );
357            y += 1;
358        }
359
360        if y > bottom || text.is_none() {
361            return;
362        }
363
364        // displays description only if its a non empty string
365        let (text, style) = text.unwrap();
366        if text.is_empty() {
367            return;
368        }
369        let paragraph = Paragraph::new(format!("Description:\n{}", text))
370            .style(style)
371            .wrap(Wrap { trim: true });
372        frame.render_widget(
373            paragraph,
374            Rect {
375                y,
376                height: bottom - y,
377                ..area
378            },
379        );
380    }
381
382    fn selectable(&self) -> bool {
383        true
384    }
385}
386
387impl Default for ItemInfo {
388    fn default() -> Self {
389        Self {
390            item: None,
391            lazy_scroll: 0,
392        }
393    }
394}
395
396impl ItemInfo {
397    pub fn new(item: Option<Item>) -> Self {
398        Self {
399            item,
400            ..Default::default()
401        }
402    }
403}