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
|
use clap::Parser;
use crossterm::event::{self, Event, KeyCode};
use crossterm::terminal::{disable_raw_mode, enable_raw_mode};
use gstreamer::ClockTime;
use gstreamer_play::{Play, PlayVideoRenderer};
use std::fs;
use std::io;
use std::path::PathBuf;
use std::time::Duration;
use tui::layout::{Alignment, Constraint, Direction, Layout, Rect};
use tui::style::{Color, Style};
use tui::widgets::{Block, Borders, Gauge, List, ListItem, ListState, Paragraph};
use tui::{backend::CrosstermBackend, Terminal};
#[derive(Debug, Parser)]
#[command(author = "Himbeer", version = "v0.1.0", about = "A custom music player for the command line, written in Rust.", long_about = None)]
struct Args {
/// Playlist directory. Defaults to current directory.
#[arg(short = 'd', long = "dir")]
dir: Option<String>,
}
#[derive(Debug)]
enum CursorState {
MusicList,
Volume,
Control,
}
impl CursorState {
fn overflowing_next(&mut self) {
*self = match self {
Self::MusicList => Self::Volume,
Self::Volume => Self::Control,
Self::Control => Self::MusicList,
};
}
}
impl Default for CursorState {
fn default() -> Self {
Self::MusicList
}
}
fn subsize(area: Rect, i: u16) -> Rect {
let mut new_area = area;
new_area.y += i * area.height;
new_area
}
fn is_paused(play: &Play) -> bool {
match play.position() {
Some(position) => match play.position() {
Some(new_pos) => position.nseconds() == new_pos.nseconds(),
None => true,
},
None => true,
}
}
fn main() -> anyhow::Result<()> {
let args = Args::parse();
let mut cursor_state = CursorState::default();
gstreamer::init()?;
enable_raw_mode()?;
let play = Play::new(PlayVideoRenderer::NONE);
let stdout = io::stdout();
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
let mut files: Vec<PathBuf> = fs::read_dir(args.dir.unwrap_or_else(|| String::from(".")))?
.map(|e| e.unwrap().path())
.collect();
files.sort();
let mut list_state = ListState::default();
list_state.select(Some(0));
loop {
terminal.draw(|f| {
let main_style = Style::default().bg(Color::Reset).fg(Color::Magenta);
let focused_style = main_style.fg(Color::Cyan);
let sizes = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Length(f.size().width / 2), Constraint::Min(0)])
.split(f.size());
let listing_size = sizes[0];
let status_size = sizes[1];
let files: Vec<ListItem> = files
.iter()
.map(|e| ListItem::new(e.file_name().unwrap().to_str().unwrap()))
.collect();
let highlight_base_style = match cursor_state {
CursorState::MusicList => focused_style,
_ => main_style,
};
let block = Block::default().title("Select music").borders(Borders::ALL);
let listing = List::new(files)
.block(block)
.style(match cursor_state {
CursorState::MusicList => focused_style,
_ => main_style,
})
.highlight_style(
highlight_base_style
.bg(highlight_base_style.fg.unwrap())
.fg(Color::Black),
)
.highlight_symbol("> ");
let status_title = match play.uri() {
Some(uri) => {
String::from("Now playing: ") + uri.as_str().split('/').next_back().unwrap()
}
None => String::from("Idle"),
};
let status_block = Block::default()
.title(status_title)
.borders(Borders::ALL)
.style(main_style);
let status_sizes = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(status_size.height / 10),
Constraint::Min(0),
])
.margin(1)
.split(status_size)[0];
let volume_size = subsize(status_sizes, 0);
let progress_size = subsize(status_sizes, 1);
let control_size = subsize(status_sizes, 2);
let block = Block::default().title("Volume").borders(Borders::ALL);
let volume_gauge = Gauge::default()
.block(block)
.style(match cursor_state {
CursorState::Volume => focused_style,
_ => main_style,
})
.gauge_style(main_style.fg(Color::Blue))
.ratio(play.volume());
let block = Block::default().borders(Borders::ALL);
let progress_gauge = Gauge::default()
.block(block)
.style(main_style)
.gauge_style(main_style.fg(Color::Blue))
.ratio(if let Some(position) = play.position() {
if let Some(duration) = play.duration() {
position.seconds() as f64 / duration.seconds() as f64
} else {
0.0
}
} else {
0.0
});
let control_buttons = if is_paused(&play) {
"[ 🔂 ] [ ⏮ ] [ ◀ ] [ ▶ ] [ ▶ ] [ ⏭ ] [ 🔀 ]"
} else {
"[ 🔂 ] [ ⏮ ] [ ◀ ] [ ⏸ ] [ ▶ ] [ ⏭ ] [ 🔀 ]"
};
let block = Block::default().borders(Borders::ALL);
let control_paragraph = Paragraph::new(control_buttons)
.block(block)
.alignment(Alignment::Center)
.style(match cursor_state {
CursorState::Control => focused_style,
_ => main_style,
});
f.render_stateful_widget(listing, listing_size, &mut list_state);
f.render_widget(status_block, status_size);
f.render_widget(volume_gauge, volume_size);
f.render_widget(progress_gauge, progress_size);
f.render_widget(control_paragraph, control_size);
})?;
if !event::poll(Duration::from_secs(1))? {
continue;
}
if let Event::Key(key) = event::read()? {
match key.code {
KeyCode::Esc | KeyCode::Char('q') => {
break;
}
KeyCode::Tab => {
cursor_state.overflowing_next();
}
KeyCode::Char(' ') => {
if is_paused(&play) {
play.play();
} else {
play.pause();
}
}
_ => match cursor_state {
CursorState::MusicList => match key.code {
KeyCode::Down => match list_state.selected() {
Some(i) => list_state.select(Some((i + 1) % files.len())),
None => list_state.select(Some(0)),
},
KeyCode::Up => match list_state.selected() {
Some(i) => list_state.select(Some(if i > 0 {
(i - 1) % files.len()
} else {
files.len() - 1
})),
None => list_state.select(Some(files.len() - 1)),
},
KeyCode::Char('r') => {
let track = rand::random::<usize>() % files.len();
list_state.select(Some(track));
}
KeyCode::Enter => {
let track = match list_state.selected() {
Some(i) => i,
None => {
continue;
}
};
let file_path = &files[track];
let uri = format!("file://{}", file_path.display());
play.set_uri(Some(&uri));
play.play();
}
_ => {}
},
CursorState::Volume => match key.code {
KeyCode::Left => play.set_volume(0.0_f64.max(play.volume() - 0.01)),
KeyCode::Right => play.set_volume(1.0_f64.min(play.volume() + 0.01)),
KeyCode::Home => play.set_volume(0.0),
KeyCode::End => play.set_volume(1.0),
KeyCode::Down => play.set_volume(0.0_f64.max(play.volume() - 0.05)),
KeyCode::Up => play.set_volume(1.0_f64.min(play.volume() + 0.05)),
_ => {}
},
CursorState::Control => match key.code {
KeyCode::Left => {
if let Some(position) = play.position() {
play.seek(ClockTime::from_seconds(
0_u64.max(position.seconds().saturating_sub(1)),
));
}
}
KeyCode::Right => {
if let Some(position) = play.position() {
if let Some(duration) = play.duration() {
play.seek(ClockTime::from_seconds(
duration
.seconds()
.min(position.seconds().saturating_add(1)),
));
}
}
}
KeyCode::Down => {
if let Some(position) = play.position() {
play.seek(ClockTime::from_seconds(
0_u64.max(position.seconds().saturating_sub(15)),
));
}
}
KeyCode::Up => {
if let Some(position) = play.position() {
if let Some(duration) = play.duration() {
play.seek(ClockTime::from_seconds(
duration
.seconds()
.min(position.seconds().saturating_add(15)),
));
}
}
}
_ => {}
},
},
}
}
}
disable_raw_mode()?;
terminal.clear()?;
terminal.set_cursor(0, 0)?;
Ok(())
}
|