-
-
Notifications
You must be signed in to change notification settings - Fork 211
/
cover.rs
290 lines (242 loc) · 9.36 KB
/
cover.rs
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
use std::collections::HashSet;
use std::io::Write;
use std::path::PathBuf;
use std::process::{Child, Stdio};
use std::sync::{Arc, RwLock};
use cursive::theme::{ColorStyle, ColorType, PaletteColor};
use cursive::{Cursive, Printer, Vec2, View};
use ioctl_rs::{ioctl, TIOCGWINSZ};
use log::{debug, error};
use crate::command::{Command, GotoMode};
use crate::commands::CommandResult;
use crate::library::Library;
use crate::queue::Queue;
use crate::traits::{IntoBoxedViewExt, ListItem, ViewExt};
use crate::ui::album::AlbumView;
use crate::ui::artist::ArtistView;
use crate::Config;
pub struct CoverView {
queue: Arc<Queue>,
library: Arc<Library>,
loading: Arc<RwLock<HashSet<String>>>,
last_size: RwLock<Vec2>,
drawn_url: RwLock<Option<String>>,
ueberzug: RwLock<Option<Child>>,
font_size: Vec2,
}
impl CoverView {
pub fn new(queue: Arc<Queue>, library: Arc<Library>, config: &Config) -> Self {
// Determine size of window both in pixels and chars
let (rows, cols, mut xpixels, mut ypixels) = unsafe {
let query: (u16, u16, u16, u16) = (0, 0, 0, 0);
ioctl(1, TIOCGWINSZ, &query);
query
};
debug!(
"Determined window dimensions: {}x{}, {}x{}",
xpixels, ypixels, cols, rows
);
// Determine font size, considering max scale to prevent tiny covers on HiDPI screens
let scale = config.values().cover_max_scale.unwrap_or(1.0);
xpixels = ((xpixels as f32) / scale) as u16;
ypixels = ((ypixels as f32) / scale) as u16;
let font_size = Vec2::new((xpixels / cols) as usize, (ypixels / rows) as usize);
debug!("Determined font size: {}x{}", font_size.x, font_size.y);
Self {
queue,
library,
ueberzug: RwLock::new(None),
loading: Arc::new(RwLock::new(HashSet::new())),
last_size: RwLock::new(Vec2::new(0, 0)),
drawn_url: RwLock::new(None),
font_size,
}
}
fn draw_cover(&self, url: String, mut draw_offset: Vec2, draw_size: Vec2) {
if draw_size.x <= 1 || draw_size.y <= 1 {
return;
}
let needs_redraw = {
let last_size = self.last_size.read().unwrap();
let drawn_url = self.drawn_url.read().unwrap();
*last_size != draw_size || drawn_url.as_ref() != Some(&url)
};
if !needs_redraw {
return;
}
let path = match self.cache_path(url.clone()) {
Some(p) => p,
None => return,
};
let mut img_size = Vec2::new(640, 640);
let draw_size_pxls = draw_size * self.font_size;
let ratio = f32::min(
f32::min(
draw_size_pxls.x as f32 / img_size.x as f32,
draw_size_pxls.y as f32 / img_size.y as f32,
),
1.0,
);
img_size = Vec2::new(
(ratio * img_size.x as f32) as usize,
(ratio * img_size.y as f32) as usize,
);
// Ueberzug takes an area given in chars and fits the image to
// that area (from the top left). Since we want to center the
// image at least horizontally, we need to fiddle around a bit.
let mut size = img_size / self.font_size;
// Make sure there is equal space in chars on either side
if size.x % 2 != draw_size.x % 2 {
size.x -= 1;
}
// Make sure x is the bottleneck so full width is used
size.y = std::cmp::min(draw_size.y, size.y + 1);
// Round up since the bottom might have empty space within
// the designated box
draw_offset.x += (draw_size.x - size.x) / 2;
draw_offset.y += (draw_size.y - size.y) - (draw_size.y - size.y) / 2;
let cmd = format!("{{\"action\":\"add\",\"scaler\":\"fit_contain\",\"identifier\":\"cover\",\"x\":{},\"y\":{},\"width\":{},\"height\":{},\"path\":\"{}\"}}\n",
draw_offset.x, draw_offset.y,
size.x, size.y,
path.to_str().unwrap()
);
if let Err(e) = self.run_ueberzug_cmd(&cmd) {
error!("Failed to run Ueberzug: {}", e);
return;
}
let mut last_size = self.last_size.write().unwrap();
*last_size = draw_size;
let mut drawn_url = self.drawn_url.write().unwrap();
*drawn_url = Some(url);
}
fn clear_cover(&self) {
let mut drawn_url = self.drawn_url.write().unwrap();
*drawn_url = None;
let cmd = "{\"action\": \"remove\", \"identifier\": \"cover\"}\n";
if let Err(e) = self.run_ueberzug_cmd(cmd) {
error!("Failed to run Ueberzug: {}", e);
}
}
fn run_ueberzug_cmd(&self, cmd: &str) -> Result<(), std::io::Error> {
let mut ueberzug = self.ueberzug.write().unwrap();
if ueberzug.is_none() {
*ueberzug = Some(
std::process::Command::new("ueberzug")
.args(&["layer", "--silent"])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?,
);
}
let stdin = (*ueberzug).as_mut().unwrap().stdin.as_mut().unwrap();
stdin.write_all(cmd.as_bytes())?;
Ok(())
}
fn cache_path(&self, url: String) -> Option<PathBuf> {
let path = crate::utils::cache_path_for_url(url.clone());
let mut loading = self.loading.write().unwrap();
if loading.contains(&url) {
return None;
}
if path.exists() {
return Some(path);
}
loading.insert(url.clone());
let loading_thread = self.loading.clone();
std::thread::spawn(move || {
if let Err(e) = crate::utils::download(url.clone(), path.clone()) {
error!("Failed to download cover: {}", e);
}
let mut loading = loading_thread.write().unwrap();
loading.remove(&url.clone());
});
None
}
}
impl View for CoverView {
fn draw(&self, printer: &Printer<'_, '_>) {
// Completely blank out screen
let style = ColorStyle::new(
ColorType::Palette(PaletteColor::Background),
ColorType::Palette(PaletteColor::Background),
);
printer.with_color(style, |printer| {
for i in 0..printer.size.y {
printer.print_hline((0, i), printer.size.x, " ");
}
});
let cover_url = self.queue.get_current().and_then(|t| t.cover_url());
if let Some(url) = cover_url {
self.draw_cover(url, printer.offset, printer.size);
} else {
self.clear_cover();
}
}
fn required_size(&mut self, constraint: Vec2) -> Vec2 {
Vec2::new(constraint.x, 2)
}
}
impl ViewExt for CoverView {
fn title(&self) -> String {
"Cover".to_string()
}
fn on_leave(&self) {
self.clear_cover();
}
fn on_command(&mut self, _s: &mut Cursive, cmd: &Command) -> Result<CommandResult, String> {
match cmd {
Command::Save => {
if let Some(mut track) = self.queue.get_current() {
track.save(self.library.clone());
}
}
Command::Delete => {
if let Some(mut track) = self.queue.get_current() {
track.unsave(self.library.clone());
}
}
#[cfg(feature = "share_clipboard")]
Command::Share(_mode) => {
let url = self
.queue
.get_current()
.and_then(|t| t.as_listitem().share_url());
if let Some(url) = url {
crate::sharing::write_share(url);
}
return Ok(CommandResult::Consumed(None));
}
Command::Goto(mode) => {
if let Some(track) = self.queue.get_current() {
let queue = self.queue.clone();
let library = self.library.clone();
match mode {
GotoMode::Album => {
if let Some(album) = track.album(queue.clone()) {
let view =
AlbumView::new(queue, library, &album).into_boxed_view_ext();
return Ok(CommandResult::View(view));
}
}
GotoMode::Artist => {
if let Some(artists) = track.artists() {
return match artists.len() {
0 => Ok(CommandResult::Consumed(None)),
// Always choose the first artist even with more because
// the cover image really doesn't play nice with the menu
_ => {
let view = ArtistView::new(queue, library, &artists[0])
.into_boxed_view_ext();
Ok(CommandResult::View(view))
}
};
}
}
}
}
}
_ => {}
};
Ok(CommandResult::Ignored)
}
}