src/items/messagebar.rs

246 lines · 9252 bytes

  1#[cfg(feature = "mpv")]
  2use crate::global::functions::secs_display_string;
  3use crate::{config::*, global::structs::*};
  4use ratatui::{
  5    layout::Rect,
  6    style::Style,
  7    widgets::{Block, Borders, Paragraph},
  8};
  9use tui_additions::framework::*;
 10
 11/// a message bar item, contains no fields because the message is taken from `data.global.Message`
 12#[derive(Clone, Copy)]
 13pub enum MessageBar {
 14    Stateless,
 15    /// start and end position of the seeker for mouse scrubbing
 16    Music {
 17        seeker_front: u16,
 18        seeker_rear: u16,
 19    },
 20    /// bar too short for seeker to display
 21    MusicSeekerLess,
 22}
 23
 24impl Default for MessageBar {
 25    fn default() -> Self {
 26        Self::Stateless
 27    }
 28}
 29
 30impl FrameworkItem for MessageBar {
 31    fn render(
 32        &mut self,
 33        frame: &mut ratatui::Frame,
 34        framework: &mut tui_additions::framework::FrameworkClean,
 35        area: ratatui::layout::Rect,
 36        popup_render: bool,
 37        _info: tui_additions::framework::ItemInfo,
 38    ) {
 39        if popup_render {
 40            return;
 41        }
 42
 43        #[cfg(feature = "mpv")]
 44        {
 45            let mpv = framework.data.global.get::<MpvWrapper>().unwrap();
 46            if Self::is_mpv_render(framework) {
 47                let mut label = mpv.property("media-title".to_string()).unwrap();
 48
 49                if let Some((name, ext)) = label.rsplit_once('.') {
 50                    if ext.len() < 5
 51                        && !name.len() > 13
 52                        && &name[name.len() - 1..name.len()] == "]"
 53                        && name[name.len() - 12..name.len() - 1]
 54                            .chars()
 55                            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
 56                        && &name[name.len() - 13..name.len() - 12] == "["
 57                    {
 58                        label = name[0..name.len() - 13].to_string();
 59                    }
 60                }
 61
 62                let duration = mpv
 63                    .property("duration".to_string())
 64                    .unwrap_or_default()
 65                    .parse::<f64>()
 66                    .unwrap() as u64;
 67                let duration_s = secs_display_string(duration as u32);
 68                let playerhead = mpv
 69                    .property("time-pos".to_string())
 70                    .unwrap_or_default()
 71                    .parse::<f64>()
 72                    .unwrap() as u64;
 73                let mut playerhead_s = secs_display_string(playerhead as u32);
 74                if playerhead_s.len() != duration_s.len() {
 75                    playerhead_s = format!(
 76                        "{}{playerhead_s}",
 77                        " ".repeat(duration_s.len() - playerhead_s.len())
 78                    );
 79                }
 80                let percentage = (playerhead * 100 / duration).to_string();
 81
 82                let right_chunk = format!(
 83                    "{playerhead_s}/{duration_s} {}[{percentage}%]",
 84                    " ".repeat(3 - percentage.len())
 85                );
 86                let left_chunk = format!("[Now Playing]: {label}");
 87                let length = area.width as usize - 2;
 88                let total_len = right_chunk.len() + left_chunk.len();
 89
 90                *framework.data.global.get_mut::<Message>().unwrap() =
 91                    Message::Mpv(if length > total_len + 6 {
 92                        let mut seeker_len = length - total_len - 4;
 93                        let seeker_pad = if seeker_len > 10 { seeker_len / 10 } else { 0 };
 94                        seeker_len -= seeker_pad * 2;
 95                        let seeker_pos = (seeker_len - 1) * playerhead as usize / duration as usize;
 96
 97                        let seeker_front = left_chunk.len() + 1 + seeker_pad; // index of first
 98                                                                              // character in seeker
 99                        let seeker_rear = seeker_front + seeker_len - 1; // index of last character
100                                                                         // in seeker
101                        *self = MessageBar::Music {
102                            seeker_front: seeker_front as u16,
103                            seeker_rear: seeker_rear as u16,
104                        };
105                        format!(
106                            "{left_chunk} {}├{}-{}┤{} {right_chunk}",
107                            " ".repeat(seeker_pad),
108                            "─".repeat(seeker_pos),
109                            "─".repeat(seeker_len - seeker_pos - 1),
110                            " ".repeat(seeker_pad)
111                        )
112                    } else if length > total_len + 3 {
113                        *self = MessageBar::MusicSeekerLess;
114                        format!(
115                            "{left_chunk}{}{right_chunk}",
116                            " ".repeat(length - total_len)
117                        )
118                    } else if length > 19 {
119                        *self = MessageBar::MusicSeekerLess;
120                        left_chunk
121                    } else {
122                        *self = MessageBar::MusicSeekerLess;
123                        String::from("Not enough width")
124                    });
125            }
126        }
127
128        let message = framework.data.global.get::<Message>().unwrap();
129        let appearance = framework.data.global.get::<AppearanceConfig>().unwrap();
130
131        // the Option<TextList> that is Some if keys were captured for entering command
132        let command_capture = &framework
133            .data
134            .global
135            .get::<Status>()
136            .unwrap()
137            .command_capture;
138
139        // display with different border style according to type of message and config
140        let block = Block::default()
141            .borders(Borders::ALL)
142            .border_type(appearance.borders)
143            .border_style(Style::default().fg(if command_capture.is_some() {
144                appearance.colors.command_capture
145            } else {
146                match message {
147                    Message::None => appearance.colors.outline,
148                    Message::Success(_) => appearance.colors.message_success_outline,
149                    Message::Error(_) => appearance.colors.message_error_outline,
150                    Message::Message(_) | Message::Mpv(_) => appearance.colors.message_outline,
151                }
152            }));
153
154        // if keys are captured, render the textlist instead of the message text, and exits the
155        // function
156        if let Some(textfield) = command_capture {
157            let paragraph = Paragraph::new(":").block(block);
158            frame.render_widget(paragraph, area);
159            let mut textfield = textfield.clone();
160            textfield.set_width(area.width - 3);
161            let _ = textfield.update();
162            frame.render_widget(
163                textfield,
164                Rect::new(area.x + 2, area.y + 1, area.width - 3, 1),
165            );
166
167            return;
168        }
169
170        let paragraph = Paragraph::new(
171            message.to_string(
172                &framework
173                    .data
174                    .global
175                    .get::<MainConfig>()
176                    .unwrap()
177                    .message_bar_default,
178            ),
179        )
180        .block(block);
181
182        frame.render_widget(paragraph, area);
183    }
184
185    fn selectable(&self) -> bool {
186        false
187    }
188
189    #[cfg(feature = "mpv")]
190    fn mouse_passthrough(
191        &mut self,
192        framework: &mut FrameworkClean,
193        _selected: bool,
194        x: u16,
195        _y: u16,
196        _absolute_x: u16,
197        _absolute_y: u16,
198    ) -> bool {
199        match self {
200            Self::Music {
201                seeker_front,
202                seeker_rear,
203            } => {
204                use std::sync::mpsc;
205
206                let seek_percentage =
207                    (x as i32 - *seeker_front as i32) * 100 / (*seeker_rear - *seeker_front) as i32;
208                let mpv = framework.data.global.get::<MpvWrapper>().unwrap();
209                let (tx, rx) = mpsc::channel();
210                mpv.sender
211                    .send(MpvAction::Command {
212                        name: "seek".to_string(),
213                        args: vec![
214                            seek_percentage.clamp(0, 100).to_string(),
215                            "absolute-percent".to_string(),
216                        ],
217                        responder: tx,
218                    })
219                    .unwrap();
220                if let MpvResponse::Error(e) = rx.recv().unwrap() {
221                    *framework.data.global.get_mut::<Message>().unwrap() = Message::Error(e);
222                }
223                true
224            }
225            _ => false,
226        }
227    }
228}
229
230#[cfg(feature = "mpv")]
231impl MessageBar {
232    pub fn is_mpv_render(framework: &FrameworkClean) -> bool {
233        framework.data.global.get::<MpvWrapper>().unwrap().playing()
234            && matches!(
235                framework.data.global.get::<Message>().unwrap(),
236                Message::Mpv(_) | Message::None
237            )
238            && framework
239                .data
240                .global
241                .get::<Status>()
242                .unwrap()
243                .command_capture
244                .is_none()
245    }
246}