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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
use crate::app::{
SongInfo,
song::{Album, Artist, LazyArtist, artist::ArtistData},
};
use mpd_client::{
client::Client,
commands,
filter::{Filter, Operator},
tag::Tag,
};
use std::collections::HashMap;
/// Lazy-loading library that only fetches artist data when needed
#[derive(Debug, Clone)]
pub struct LazyLibrary {
/// List of all artist names (loaded immediately)
pub artists: Vec<LazyArtist>,
/// Flattened list of all albums sorted alphabetically by album name.
/// This is populated incrementally as artists are loaded.
/// Each entry is (artist_name, Album).
pub all_albums: Vec<(String, Album)>,
pub albums_by_year: Vec<(String, Vec<(String, Album)>)>,
pub albums_by_genre: Vec<(String, Vec<(String, Album)>)>,
/// Flag to track if all_albums is complete (all artists loaded)
pub all_albums_complete: bool,
/// Flag to track if all_albums is sorted
pub all_albums_sorted: bool,
}
impl LazyLibrary {
/// Initialize the library by loading just the artist names.
/// This is fast because it only fetches tag values, not full song metadata.
/// MPD command: list AlbumArtist
pub async fn init(client: &Client) -> color_eyre::Result<Self> {
let start_time = std::time::Instant::now();
log::info!("Initializing lazy library (loading artist names only)...");
// Get all unique album artists using the List command
let album_artists_list = match client.command(commands::List::new(Tag::AlbumArtist)).await {
Ok(list) => list,
Err(e) => {
log::error!("MPD List command failed for AlbumArtist tag: {}", e);
log::error!("This usually indicates:");
log::error!(" - MPD database corruption or inconsistency");
log::error!(" - Permission issues with music directory");
log::error!(" - Network/protocol issues with MPD server");
log::error!(" - Missing or invalid AlbumArtist tags in music files");
return Err(color_eyre::eyre::eyre!(
"Failed to list album artists: {}",
e
));
}
};
let mut artist_names: Vec<String> = album_artists_list
.into_iter()
.filter(|name| !name.is_empty())
.collect();
// Sort alphabetically
artist_names.sort_by_key(|a| a.to_lowercase());
// Add Unknown Artist for songs without artist metadata
artist_names.push("Unknown Artist".to_string());
let artists: Vec<LazyArtist> = artist_names.into_iter().map(LazyArtist::new).collect();
let duration = start_time.elapsed();
log::info!(
"Lazy library initialized: {} artists in {:?}",
artists.len(),
duration
);
Ok(Self {
artists,
all_albums: Vec::new(),
all_albums_complete: false,
all_albums_sorted: false,
albums_by_year: Vec::new(),
albums_by_genre: Vec::new(),
})
}
fn sort_albums(albums: &mut [(String, Album)]) {
albums.sort_by(|a, b| {
// Check if either is "Unknown Album"
let a_is_unknown = a.1.name == "Unknown Album";
let b_is_unknown = b.1.name == "Unknown Album";
match (a_is_unknown, b_is_unknown) {
(true, true) => {
// Both unknown - sort by artist name
a.0.to_lowercase().cmp(&b.0.to_lowercase())
}
(true, false) => std::cmp::Ordering::Greater, // a is unknown, put after b
(false, true) => std::cmp::Ordering::Less, // b is unknown, put a before b
(false, false) => {
// Both known - sort by artist then album
a.0.to_lowercase()
.cmp(&b.0.to_lowercase())
.then_with(|| a.1.name.to_lowercase().cmp(&b.1.name.to_lowercase()))
}
}
});
}
/// Build a grouped index of albums by a specified key (e.g., year or genre).
fn build_albums_by<F, S>(
&self,
key_fn: F,
unknown_label: &str,
group_sort_fn: S,
) -> Vec<(String, Vec<(String, Album)>)>
where
F: Fn(&Album) -> Option<String>,
S: Fn(&str, &str) -> std::cmp::Ordering,
{
let mut by_key: HashMap<String, Vec<(String, Album)>> = HashMap::new();
for (artist, album) in &self.all_albums {
let key = key_fn(album).unwrap_or_else(|| unknown_label.to_string());
by_key
.entry(key)
.or_default()
.push((artist.clone(), album.clone()));
}
let unknown = by_key.remove(unknown_label);
let mut known: Vec<_> = by_key.into_iter().collect();
known.sort_by(|a, b| group_sort_fn(&a.0, &b.0)); // Sort years descending
for (_, albums) in &mut known {
Self::sort_albums(albums)
}
if let Some(mut unknown_albums) = unknown {
Self::sort_albums(&mut unknown_albums);
known.push((unknown_label.to_string(), unknown_albums));
}
known
}
pub fn ensure_albums_by_year_built(&mut self) {
if self.albums_by_year.is_empty() {
self.albums_by_year =
self.build_albums_by(|album| album.year.clone(), "Unknown Year", |a, b| b.cmp(a));
}
}
pub fn ensure_albums_by_genre_built(&mut self) {
if self.albums_by_genre.is_empty() {
self.albums_by_genre = self.build_albums_by(
|album| album.genre.clone(),
"Unknown Genre",
|a, b| a.cmp(b),
);
}
}
/// Load albums and songs for a specific artist by index.
/// MPD command: find "(AlbumArtist == 'artist_name')" sort Album
pub async fn load_artist(
&mut self,
client: &Client,
artist_index: usize,
) -> color_eyre::Result<()> {
if artist_index >= self.artists.len() {
return Err(color_eyre::eyre::eyre!("Artist index out of bounds"));
}
// Skip if already loaded
if self.artists[artist_index].is_loaded() {
return Ok(());
}
// Skip if already loading - prevents concurrent loads
if self.artists[artist_index].is_loading() {
log::debug!(
"Artist {} is already loading, skipping duplicate load",
self.artists[artist_index].name
);
return Ok(());
}
// Set state to Loading to prevent concurrent loads
let artist_name = self.artists[artist_index].name.clone();
self.artists[artist_index].albums = ArtistData::Loading;
log::debug!("Loading albums for artist: {}", artist_name);
let start_time = std::time::Instant::now();
// Fetch all songs for this artist
// For "Unknown Artist", query for empty AlbumArtist tags
let filter = if artist_name == "Unknown Artist" {
Filter::new(Tag::AlbumArtist, Operator::Equal, "".to_string())
} else {
Filter::new(Tag::AlbumArtist, Operator::Equal, artist_name.clone())
};
let find_cmd = commands::Find::new(filter).sort(Tag::Album);
let songs = match client.command(find_cmd).await {
Ok(songs) => {
log::debug!("Found {} songs for artist '{}'", songs.len(), artist_name);
songs
}
Err(e) => {
// Revert to NotLoaded on error
self.artists[artist_index].albums = ArtistData::NotLoaded;
log::error!("Failed to load songs for artist '{}': {}", artist_name, e);
log::error!("This may indicate:");
log::error!(" - Corrupted MPD database entries for this artist");
log::error!(" - Missing or inaccessible music files");
log::error!(" - Permission issues with music directory");
log::error!(" - Network/protocol issues with MPD server");
return Err(color_eyre::eyre::eyre!(
"Failed to find songs for artist '{}': {}",
artist_name,
e
));
}
};
// Group songs by album
let mut albums_map: std::collections::HashMap<String, Vec<SongInfo>> =
std::collections::HashMap::new();
for song in songs {
let song_info = SongInfo::from_song(&song);
let album_name = song_info.album.clone();
albums_map.entry(album_name).or_default().push(song_info);
}
// Build album list
let mut albums: Vec<Album> = albums_map
.into_iter()
.map(|(album_name, mut tracks)| {
// Sort tracks by disc and track number
tracks.sort_by(|a, b| {
a.disc_number
.cmp(&b.disc_number)
.then(a.track_number.cmp(&b.track_number))
.then(a.title.cmp(&b.title))
});
Album::new(album_name, tracks)
})
.collect();
// Sort albums alphabetically
albums.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
let duration = start_time.elapsed();
log::debug!(
"Loaded {} albums for '{}' in {:?}",
albums.len(),
artist_name,
duration
);
// NOTE: We do NOT add to all_albums here because preload_all_albums() already did that
// all_albums is for the Albums view and is populated once during preload
// artist.albums is for the Artists view and is populated when the artist is selected
// Mark as needing sort (defer sorting until all artists loaded or accessed)
self.all_albums_sorted = false;
// Store the loaded albums
self.artists[artist_index].albums = ArtistData::Loaded(albums);
// Check if all artists are now loaded
self.all_albums_complete = self.artists.iter().all(|a| a.is_loaded());
Ok(())
}
/// Get an Artist struct for the given index (for rendering).
/// Returns None if index is out of bounds.
/// If the artist's albums haven't been loaded, returns an Artist with empty albums.
pub fn get_artist(&self, artist_index: usize) -> Option<Artist> {
self.artists.get(artist_index).map(|a| a.to_artist())
}
/// Ensure all_albums is sorted before access.
/// This is a lazy sort: only sorts when needed.
pub fn ensure_albums_sorted(&mut self) {
if !self.all_albums_sorted {
self.all_albums.sort_by(|a, b| {
// Check if either is "Unknown Album"
let a_is_unknown = a.1.name == "Unknown Album";
let b_is_unknown = b.1.name == "Unknown Album";
match (a_is_unknown, b_is_unknown) {
(true, true) => {
// Both unknown - sort by artist name
a.0.to_lowercase().cmp(&b.0.to_lowercase())
}
(true, false) => std::cmp::Ordering::Greater, // a is unknown, put it after b
(false, true) => std::cmp::Ordering::Less, // b is unknown, put a before b
(false, false) => {
// Both known - normal sort
a.1.name
.to_lowercase()
.cmp(&b.1.name.to_lowercase())
.then_with(|| a.0.to_lowercase().cmp(&b.0.to_lowercase()))
}
}
});
self.all_albums_sorted = true;
}
}
/// Preload all albums for the Albums view.
/// Uses a fast bulk approach: fetches all songs at once instead of per-artist.
pub async fn preload_all_albums(&mut self, client: &Client) -> color_eyre::Result<()> {
if self.all_albums_complete {
return Ok(());
}
log::info!("Preloading all albums for Albums and Years view (bulk)...");
let start_time = std::time::Instant::now();
// Fetch ALL songs in the library at once using a filter that matches every song
// This is faster than per-artist queries and more reliable than listallinfo.
// We do this by requiring that the "file" tag exists:
// Filter::tag_exists(Tag::Other("file".into()))
// (Conceptually similar to a raw MPD query like: find "(file != '')")
let filter = Filter::tag_exists(Tag::Other("file".into()));
let all_songs = client
.command(commands::Find::new(filter))
.await
.map_err(|e| color_eyre::eyre::eyre!("Failed to find all songs: {}", e))?;
// Group by artist -> album -> songs
let mut artist_albums: std::collections::HashMap<
String,
std::collections::HashMap<String, Vec<SongInfo>>,
> = std::collections::HashMap::new();
for song in all_songs {
let song_info = SongInfo::from_song(&song);
// Use album artist for grouping (fall back to artist if not set)
// Handle empty strings by treating them as unknown
let artist_name = song
.album_artists()
.first()
.map(|s| s.to_string())
.unwrap_or_else(|| song_info.artist.clone());
// If artist name is empty, use "Unknown Artist"
let artist_name = if artist_name.is_empty() {
"Unknown Artist".to_string()
} else {
artist_name
};
let album_name = song_info.album.clone();
artist_albums
.entry(artist_name)
.or_default()
.entry(album_name)
.or_default()
.push(song_info);
}
// Update each artist's albums
for artist in &mut self.artists {
// Skip if already loaded or currently loading to prevent concurrent access
if artist.is_loaded() || artist.is_loading() {
continue;
}
if let Some(albums_map) = artist_albums.remove(&artist.name) {
let mut albums: Vec<Album> = albums_map
.into_iter()
.map(|(album_name, mut tracks)| {
tracks.sort_by(|a, b| {
a.disc_number
.cmp(&b.disc_number)
.then(a.track_number.cmp(&b.track_number))
.then(a.title.cmp(&b.title))
});
Album::new(album_name, tracks)
})
.collect();
albums.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
// Add to all_albums
for album in &albums {
self.all_albums.push((artist.name.clone(), album.clone()));
}
artist.albums = ArtistData::Loaded(albums);
} else {
// Artist has no songs, mark as loaded with empty albums
artist.albums = ArtistData::Loaded(Vec::new());
}
}
// Handle any remaining artists (e.g., "Unknown Artist") not in the initial list
if let Some(albums_map) = artist_albums.remove("Unknown Artist") {
// Find the Unknown Artist entry
if let Some(artist) = self.artists.iter_mut().find(|a| a.name == "Unknown Artist") {
let mut albums: Vec<Album> = albums_map
.into_iter()
.map(|(album_name, mut tracks)| {
tracks.sort_by(|a, b| {
a.disc_number
.cmp(&b.disc_number)
.then(a.track_number.cmp(&b.track_number))
.then(a.title.cmp(&b.title))
});
Album::new(album_name, tracks)
})
.collect();
albums.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
// Add to all_albums
for album in &albums {
self.all_albums.push((artist.name.clone(), album.clone()));
}
artist.albums = ArtistData::Loaded(albums);
}
}
// Sort all_albums once at the end
self.all_albums.sort_by(|a, b| {
a.1.name
.to_lowercase()
.cmp(&b.1.name.to_lowercase())
.then_with(|| a.0.to_lowercase().cmp(&b.0.to_lowercase()))
});
self.all_albums_sorted = true;
self.all_albums_complete = true;
let duration = start_time.elapsed();
log::info!(
"All albums preloaded: {} albums in {:?}",
self.all_albums.len(),
duration
);
// Build the years and genre index after all albums are loaded
self.ensure_albums_by_year_built();
self.ensure_albums_by_genre_built();
Ok(())
}
}