src/items/iteminfo.rs

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