use std::cell::RefCell;
use ratatui::layout::{Alignment, Rect};
use ratatui::style::Style;
use ratatui::text::Line;
use ratatui::widgets::{Block, BorderType, Borders, Paragraph};
use ratatui::Frame;
use ratatui_image::picker::Picker;
use ratatui_image::protocol::StatefulProtocol;
use ratatui_image::StatefulImage;
use crate::tui::image_loader::ImageLoader;
#[derive(Default)]
pub struct ArtProtocolState {
uri: Option<String>,
pub protocol: Option<StatefulProtocol>,
}
impl ArtProtocolState {
pub fn ensure_protocol(
&mut self,
art_uri: &Option<String>,
image_loader: &ImageLoader,
picker: &RefCell<Option<Picker>>,
) {
let uri_changed = self.uri.as_deref() != art_uri.as_deref();
if uri_changed {
self.uri = art_uri.clone();
self.protocol = None;
}
if self.protocol.is_none() {
if let Some(ref uri) = art_uri {
if let Some(img) = image_loader.get(uri) {
if let Some(ref mut p) = *picker.borrow_mut() {
self.protocol = Some(p.new_resize_protocol(img.clone()));
}
}
}
}
}
}
pub fn render_album_art(
frame: &mut Frame,
area: Rect,
protocol: Option<&mut StatefulProtocol>,
border_style: Style,
placeholder_style: Style,
music_note: &str,
) {
if area.width < 3 || area.height < 3 {
return;
}
match protocol {
Some(proto) => {
let block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(border_style);
let inner = block.inner(area);
frame.render_widget(block, area);
if inner.width > 0 && inner.height > 0 {
let image_widget = StatefulImage::new(None);
frame.render_stateful_widget(image_widget, inner, proto);
}
}
None => {
render_placeholder(frame, area, border_style, placeholder_style, music_note);
}
}
}
fn render_placeholder(
frame: &mut Frame,
area: Rect,
border_style: Style,
text_style: Style,
note: &str,
) {
let block = Block::default()
.borders(Borders::ALL)
.border_type(BorderType::Rounded)
.border_style(border_style);
let inner = block.inner(area);
frame.render_widget(block, area);
if inner.height == 0 || inner.width == 0 {
return;
}
let center_y = inner.height / 2;
let note_area = Rect::new(inner.x, inner.y + center_y, inner.width, 1);
let paragraph = Paragraph::new(Line::from(note.to_string()))
.alignment(Alignment::Center)
.style(text_style);
frame.render_widget(paragraph, note_area);
}