lyrics-next 0.2.1

在终端下为 mpd/mpris 提供歌词.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use std::borrow::Cow;

use crate::{
    client::get_lyrics_client,
    config::get_config,
    error::LyricsError,
    song::{
        LyricParser, LyricsLine, PlayTime, PlayerAction, SongInfo, get_current_song,
        get_current_time_song, player_action,
    },
};
use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{
    buffer::Buffer,
    layout::{Constraint, Direction, Layout, Rect, Size},
    style::{Color, Modifier, Style, Stylize},
    text::{Line, Span},
    widgets::{Block, Borders, Gauge, Padding, Paragraph, Widget, Wrap},
};
use rust_i18n::t;
use tracing::{info, warn};

use super::{LYRICS_GAUGE_STYLE, LYRICS_HEADER_STYLE, render_error};

#[derive(Clone, Default)]
pub(super) struct LyricsScreen {
    state: LyricState,
}

impl LyricsScreen {
    pub fn render(&mut self, area: Rect, buf: &mut Buffer) {
        let config = &get_config().read().unwrap().ui;

        let header_height = match config.title {
            true => Constraint::Length(4),
            false => Constraint::Length(0),
        };
        let progress_height = match config.progress_bar {
            true => Constraint::Length(1),
            false => Constraint::Length(0),
        };

        let [header_chunk, lyric_chunk, progress_chunk] = Layout::new(
            Direction::Vertical,
            [
                header_height,      // 标题栏目
                Constraint::Min(1), // 歌词区域
                progress_height,    // 进度
            ],
        )
        .areas(area);

        let size = lyric_chunk.as_size();
        self.update_size(size);

        self.render_title(header_chunk, buf);
        self.render_lyric(lyric_chunk, buf);
        self.render_progress(progress_chunk, buf);
    }

    fn get_window_title(&self) -> String {
        match !self.state.song.title.is_empty() {
            true => self.state.song.title.clone(),
            false => " No song playing ".into(),
        }
    }

    pub fn render_title(&self, area: Rect, buf: &mut Buffer) {
        if self.state.song.title.is_empty() {
            return;
        }
        // 渲染标题区块
        let header_block = Block::default()
            .borders(Borders::ALL)
            .style(LYRICS_HEADER_STYLE);

        // 显示歌曲信息
        let song = &self.state.song.clone();

        let line_title = song.title.clone();
        let line_artist = song.artist.clone();

        let lines = vec![Line::raw(line_title), Line::raw(line_artist)];

        Paragraph::new(lines)
            .block(header_block)
            .centered()
            .wrap(Wrap { trim: true })
            .render(area, buf);
    }

    /// 进度
    pub fn render_progress(&self, area: Rect, buf: &mut Buffer) {
        if self.state.song.title.is_empty() {
            return;
        }

        let song = &self.state.song.clone();

        let label = Span::styled(
            format!(
                "{:0>2}:{:0>2} / {:0>2}:{:0>2}",
                (&self.state.play_time.current_time / 60.0).floor() as u64,
                (&self.state.play_time.current_time % 60.0).floor() as u64,
                (song.duration / 60.0).floor() as u64,
                (song.duration % 60.0).floor() as u64,
            ),
            LYRICS_GAUGE_STYLE,
        );

        Gauge::default()
            .gauge_style(Style::new().blue().on_dark_gray())
            .percent((self.state.progress * 100.0) as u16)
            .label(label)
            .render(area, buf);
    }

    /// 渲染歌词
    pub fn render_lyric(&self, area: Rect, buf: &mut Buffer) {
        let state = &self.state;
        let config = &get_config().read().unwrap().ui;

        // 渲染错误信息
        if let Some(err_msg) = &state.error_message {
            render_error(area, buf, err_msg);
            return;
        }

        // 使用预计算的显示参数
        // TODO: 当一行的内容超出宽度换行时候计算偏移高度
        let metrics = &state.view_metrics;
        let start = state.target_scroll.min(metrics.scroll_range);
        let end = (start + metrics.visible_lines).min(metrics.content_height);
        let mut lines = Vec::new();
        for (i, line) in state.lyrics[start..end].iter().enumerate() {
            let is_current = start + i == state.find_current_line().unwrap_or(0);

            let line_text = match config.time {
                true => format!(
                    "[{:0>2}:{:0>2}] {}",
                    (line.timestamp_start / 60.0).floor() as u64,
                    (line.timestamp_start % 60.0).floor() as u64,
                    line.text
                ),
                false => line.text.clone(),
            };

            let style = if is_current {
                Style::new()
                    .fg(Color::Indexed(196))
                    .bg(Color::Reset)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::new()
                    .fg(Color::Indexed(94 + i as u8))
                    .bg(Color::Reset)
            };

            let line = Line::styled(line_text, style);
            match config.text_center {
                true => lines.push(line.centered()),
                false => lines.push(line),
            }
        }

        let block = Block::default()
            .title(self.get_window_title())
            .borders(Borders::ALL)
            .padding(Padding::horizontal(1));

        Paragraph::new(lines)
            .block(block)
            .wrap(Wrap { trim: true })
            .render(area, buf);
    }

    pub async fn handle_key_event(&mut self, key_event: &KeyEvent) {
        match key_event.code {
            KeyCode::Char('d') | KeyCode::Delete => self.delete().await,
            KeyCode::Left => self.state.action(PlayerAction::Left).await,
            KeyCode::Right => self.state.action(PlayerAction::Right).await,
            KeyCode::Char(' ') => self.state.action(PlayerAction::Toggle).await,
            KeyCode::Char('n') | KeyCode::Char('j') => self.state.action(PlayerAction::Next).await,
            KeyCode::Char('p') | KeyCode::Char('k') => {
                self.state.action(PlayerAction::Previous).await
            }
            KeyCode::Char('c') => {
                // center
                let config = &mut get_config().write().unwrap();
                config.ui.text_center = !config.ui.text_center;
            }
            KeyCode::Char('t') => {
                let config = &mut get_config().write().unwrap();
                config.ui.title = !config.ui.title;
            }
            _ => {}
        }
    }

    pub fn help<'a>() -> Vec<(&'a str, Cow<'a, str>)> {
        vec![
            ("h | ? ", t!("help.lyrics.help")),
            ("q | ESC ", t!("help.lyrics.quit")),
            ("d | Delete ", t!("help.lyrics.delete")),
            ("Left ", t!("help.lyrics.back")),
            ("Right ", t!("help.lyrics.next")),
            ("Space", t!("help.lyrics.pause")),
            ("n | j ", t!("help.lyrics.prev_song")),
            ("p | k ", t!("help.lyrics.next_song")),
            ("t", t!("help.lyrics.toggle_title")),
            ("s", t!("help.lyrics.search")),
        ]
    }

    /// 状态刷新
    pub async fn update(&mut self) {
        self.state.update().await;
    }

    /// 尺寸变动
    pub fn update_size(&mut self, size: Size) {
        self.state.calculate_metrics(size);
    }

    /// 删除
    async fn delete(&mut self) {
        self.state.delete().await;
    }

    pub fn reset(&mut self) {
        self.state.reset();
    }
}

// 新增显示参数结构体
#[derive(Debug, Clone, Copy, Default)]
pub struct ViewMetrics {
    /// 可见行数
    pub visible_lines: usize,
    /// 总内容高度
    pub content_height: usize,
    /// 最大可滚动范围
    pub scroll_range: usize,
}

// 界面状态管理
#[derive(Clone, Default)]
pub struct LyricState {
    // 当前歌曲
    pub song: SongInfo,
    /// 播放时间
    pub play_time: PlayTime,
    /// 当前歌词
    pub lyrics: Vec<LyricsLine>,
    /// 目标滚动位置
    pub target_scroll: usize,
    /// 新增显示参数
    pub view_metrics: ViewMetrics,
    /// 新增错误状态
    pub error_message: Option<String>,
    /// 重试计数器
    pub retry_counter: u32,
    /// 进度
    pub progress: f64,
}

impl LyricState {
    // 预计算显示参数
    pub fn calculate_metrics(&mut self, area: Size) {
        let content_height = self.lyrics.len();
        let viewport_height = area.height as usize;
        let visible_lines = viewport_height.saturating_sub(2); // 保留边界空间
        let scroll_range = content_height.saturating_sub(visible_lines);

        self.view_metrics = ViewMetrics {
            visible_lines,
            content_height,
            scroll_range,
        };
    }

    pub fn reset(&mut self) {
        *self = LyricState::default();
    }

    pub async fn update(&mut self) {
        match self.try_update().await {
            Ok(_) => {
                self.error_message = None; // 清除旧错误        
                self.retry_counter = 0;
            }
            Err(e) => {
                if self.retry_counter < 5 {
                    self.handle_error(e).await;
                }
            }
        }
    }

    async fn try_update(&mut self) -> Result<(), LyricsError> {
        // 获取当前播放器和歌曲信息
        let song = match get_current_song().await {
            Ok(s) => s,
            Err(e) => {
                self.reset();
                return Err(e);
            }
        };

        // 歌曲发生变化时重新加载歌词
        if song != self.song {
            // 切歌时清除错误状态和重试计数
            self.error_message = None;
            self.retry_counter = 0;

            self.song = song.clone();

            // 尝试获取歌词
            match get_lyrics_client().get_lyrics(&song).await {
                Ok(doc) => {
                    self.lyrics = LyricParser::parse(doc, song.duration).await?;
                }
                Err(LyricsError::NoLyricsFound) => {
                    // 没有找到歌词,尝试自动搜索并下载
                    info!(
                        "No lyrics found, attempting auto-download for: {} - {}",
                        song.artist, song.title
                    );
                    self.auto_download_lyrics(&song).await?;
                }
                Err(e) => return Err(e),
            }
        }

        // 获取当前播放进度
        self.play_time = get_current_time_song(self.play_time.clone()).await?;
        self.progress = self.play_time.current_time / song.duration;

        // 更新滚动位置
        if let Some(pos) = self.find_current_line() {
            let target_offset = pos.saturating_sub(self.view_metrics.visible_lines / 2);
            self.target_scroll = target_offset.min(self.view_metrics.scroll_range);
        }

        Ok(())
    }

    async fn auto_download_lyrics(&mut self, song: &SongInfo) -> Result<(), LyricsError> {
        // 搜索歌词列表
        let search_results = get_lyrics_client().get_search(song).await?;

        if search_results.is_empty() {
            warn!("Auto-download failed: No search results found");
            return Err(LyricsError::NoLyricsFound);
        }

        // 获取第一个匹配的歌词
        let best_match = super::super::client::get_first(search_results, song)?;

        info!(
            "Auto-downloading lyrics from {}: {} - {}",
            best_match.source, best_match.artist, best_match.title
        );

        // 下载歌词
        get_lyrics_client().download(song, &best_match).await?;

        // 重新加载已下载的歌词
        let doc = get_lyrics_client().get_lyrics(song).await?;
        self.lyrics = LyricParser::parse(doc, song.duration).await?;

        info!("Auto-download successful");
        Ok(())
    }

    /// 当前播放的 line
    pub fn find_current_line(&self) -> Option<usize> {
        self.lyrics
            .iter()
            .enumerate()
            .find(|(_, line)| {
                self.play_time.current_time >= line.timestamp_start
                    && self.play_time.current_time < line.timestamp_end
            })
            .map(|(i, _)| i)
    }

    async fn handle_error(&mut self, error: LyricsError) {
        if self.retry_counter < 5 {
            self.retry_counter += 1;
            let error_msg = format!("Error: {} (Retry {}/5)", error, self.retry_counter);
            info!("{}", error_msg);
            self.error_message = Some(error_msg);
            // 移除等待,让下一次 update 自然重试
        } else {
            info!("Maximum retries reached");
            // self.error_message = Some("Maximum retries reached".into());
        }
    }

    pub async fn delete(&mut self) {
        if !self.song.title.is_empty() {
            get_lyrics_client().cache.delete(&self.song).await;
            self.reset();
        }
    }

    pub async fn action(&self, action: PlayerAction) {
        if let Err(e) = player_action(action, &self.song).await {
            tracing::error!("Action: {e}");
        }
    }
}