src/items/iteminfo.rs

355 lines · 13531 bytes

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