-
Notifications
You must be signed in to change notification settings - Fork 348
Expand file tree
/
Copy pathSongContainer.cs
More file actions
841 lines (751 loc) · 33.9 KB
/
Copy pathSongContainer.cs
File metadata and controls
841 lines (751 loc) · 33.9 KB
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
using Cysharp.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.Linq;
using UniRx;
using YARG.Core;
using YARG.Core.Game;
using YARG.Core.Logging;
using YARG.Core.Song;
using YARG.Core.Song.Cache;
using YARG.Core.Utility;
using YARG.Helpers;
using YARG.Helpers.Extensions;
using YARG.Localization;
using YARG.Menu.MusicLibrary;
using YARG.Player;
using YARG.Scores;
using YARG.Settings;
namespace YARG.Song
{
public enum SortAttribute
{
Unspecified,
Name,
Artist,
Album,
Artist_Album,
Genre,
Subgenre,
Year,
Charter,
Folder,
Source,
SongLength,
DateAdded,
Playcount,
Stars,
Playable,
Random,
Instrument,
FiveFretGuitar,
FiveFretBass,
FiveFretRhythm,
FiveFretCoop,
Keys,
SixFretGuitar,
SixFretBass,
SixFretRhythm,
SixFretCoop,
FourLaneDrums,
ProDrums,
FiveLaneDrums,
EliteDrums,
ProGuitar_17,
ProGuitar_22,
ProBass_17,
ProBass_22,
ProKeys,
Vocals,
Harmony,
Band
}
public readonly struct SongCategory
{
public string Category { get; }
public string CategoryGroup { get; }
public SongEntry[] Songs { get; }
public bool Collapsed { get; }
public SongCategory(string category, SongEntry[] songs, string categoryGroupName, bool collapsed = false)
{
Category = category;
Songs = songs;
CategoryGroup = categoryGroupName;
Collapsed = collapsed;
}
public void Deconstruct(out string category, out SongEntry[] songs)
{
category = Category;
songs = Songs;
}
}
public static class SongContainer
{
private static SongCache _songCache = new();
private static SortedSongs _sortedSongs = new();
private static SongEntry[] _songs = Array.Empty<SongEntry>();
private static Dictionary<HashWrapper, List<SongEntry>> _songsByHash = new();
private static SongCategory[] _sortTitles = Array.Empty<SongCategory>();
private static SongCategory[] _sortArtists = Array.Empty<SongCategory>();
private static SongCategory[] _sortAlbums = Array.Empty<SongCategory>();
private static SongCategory[] _sortGenres = Array.Empty<SongCategory>();
private static SongCategory[] _sortSubgenres = Array.Empty<SongCategory>();
private static SongCategory[] _sortYears = Array.Empty<SongCategory>();
private static SongCategory[] _sortCharters = Array.Empty<SongCategory>();
private static SongCategory[] _sortPlaylists = Array.Empty<SongCategory>();
private static SongCategory[] _sortSources = Array.Empty<SongCategory>();
private static SongCategory[] _sortArtistAlbums = Array.Empty<SongCategory>();
private static SongCategory[] _sortSongLengths = Array.Empty<SongCategory>();
private static SongCategory[] _sortDatesAdded = Array.Empty<SongCategory>();
private static Dictionary<Instrument, SongCategory[]> _sortInstruments = new();
private static SongCategory[] _playables = null;
private static SongCategory[] _sortStars = Array.Empty<SongCategory>();
private static readonly Dictionary<SongEntry, StarAmount> _runtimeStars = new();
private static Guid _starsCacheProfileId = Guid.Empty;
private static Instrument _starsCacheInstrument = Instrument.Band;
private static Difficulty _starsCacheDifficulty = Difficulty.Easy;
private static bool _starsCacheValid;
public static IReadOnlyDictionary<string, List<SongEntry>> Titles => _sortedSongs.Titles;
public static IReadOnlyDictionary<string, List<SongEntry>> Years => _sortedSongs.Years;
public static IReadOnlyDictionary<string, List<SongEntry>> SongLengths => _sortedSongs.SongLengths;
public static IReadOnlyDictionary<DateTime, List<SongEntry>> AddedDates => _sortedSongs.DatesAdded;
public static IReadOnlyDictionary<SortString, List<SongEntry>> Artists => _sortedSongs.Artists;
public static IReadOnlyDictionary<SortString, List<SongEntry>> Albums => _sortedSongs.Albums;
public static IReadOnlyDictionary<SortString, List<SongEntry>> Genres => _sortedSongs.Genres;
public static IReadOnlyDictionary<SortString, List<SongEntry>> Subgenres => _sortedSongs.Subgenres;
public static IReadOnlyDictionary<SortString, List<SongEntry>> Charters => _sortedSongs.Charters;
public static IReadOnlyDictionary<SortString, List<SongEntry>> Playlists => _sortedSongs.Playlists;
public static IReadOnlyDictionary<SortString, List<SongEntry>> Sources => _sortedSongs.Sources;
public static IReadOnlyDictionary<SortString, SortedDictionary<SortString, List<SongEntry>>> ArtistAlbums => _sortedSongs.ArtistAlbums;
public static IReadOnlyDictionary<Instrument, SortedDictionary<int, List<SongEntry>>> Instruments => _sortedSongs.Instruments;
public static int Count => _songs.Length;
// public static IReadOnlyDictionary<HashWrapper, List<SongEntry>> SongsByHash => _songCache.Entries;
public static IReadOnlyDictionary<HashWrapper, List<SongEntry>> SongsByHash => _songsByHash;
public static SongEntry[] Songs => _songs;
public static SongEntry[] UnfilteredSongs => _songCache.Entries.Values.SelectMany(e => e).ToArray();
private static bool AllowedByRating(SongRating rating) => rating <= SettingsManager.Settings.MaxSongRating.Value;
#nullable enable
public static async UniTask RunRefresh(bool quick, LoadingContext? context = null)
#nullable disable
{
var directories = new List<string>(SettingsManager.Settings.SongFolders);
string setlistPath = PathHelper.SetlistPath;
if (!string.IsNullOrEmpty(setlistPath) && !directories.Contains(setlistPath))
{
directories.Add(setlistPath);
}
var stopwatch = System.Diagnostics.Stopwatch.StartNew();
var task = UniTask.RunOnThreadPool(() =>
{
_songCache = CacheHandler.RunScan(quick,
PathHelper.SongCachePath,
PathHelper.BadSongsPath,
SettingsManager.Settings.UseFullDirectoryForPlaylists.Value,
directories);
});
while (task.Status == UniTaskStatus.Pending)
{
if (context != null)
{
UpdateSongUi(context);
}
await UniTask.NextFrame();
}
if (SettingsManager.Settings.Genrelizer.Value is GenrelizerMode.Genrelize && !GlobalVariables.OfflineMode)
{
Genrelizer.GenrelizeAll(_songCache, false);
}
else if (SettingsManager.Settings.Genrelizer.Value is GenrelizerMode.Overgenrelize && !GlobalVariables.OfflineMode)
{
Genrelizer.GenrelizeAll(_songCache, true);
}
else
{
Genrelizer.DegenrelizeAll(_songCache);
}
SongSorting.SortEntries(_songCache, _sortedSongs);
FillContainers();
stopwatch.Stop();
YargLogger.LogFormatInfo("Scan time: {0}s", stopwatch.Elapsed.TotalSeconds);
MusicLibraryMenu.SetReload(MusicLibraryReloadState.Full);
SongSources.LoadSprites(context);
}
public static SongCategory[] GetSortedCategory(SortAttribute sort)
{
var proposedSort = Array.Empty<SongCategory>();
try
{
proposedSort = sort switch
{
SortAttribute.Name => _sortTitles,
SortAttribute.Artist => _sortArtists,
SortAttribute.Album => _sortAlbums,
SortAttribute.Genre => _sortGenres,
SortAttribute.Subgenre => _sortSubgenres,
SortAttribute.Year => _sortYears,
SortAttribute.Charter => _sortCharters,
SortAttribute.Folder => _sortPlaylists,
SortAttribute.Source => _sortSources,
SortAttribute.Artist_Album => _sortArtistAlbums,
SortAttribute.SongLength => _sortSongLengths,
SortAttribute.DateAdded => _sortDatesAdded,
SortAttribute.Playcount => GetPlaycounts(),
SortAttribute.Playable => GetPlayableSongs(),
SortAttribute.Stars => GetStars(),
SortAttribute.Random => GetRandomSort(),
SortAttribute.FiveFretGuitar => _sortInstruments[Instrument.FiveFretGuitar],
SortAttribute.FiveFretBass => _sortInstruments[Instrument.FiveFretBass],
SortAttribute.FiveFretRhythm => _sortInstruments[Instrument.FiveFretRhythm],
SortAttribute.FiveFretCoop => _sortInstruments[Instrument.FiveFretCoopGuitar],
SortAttribute.Keys => _sortInstruments[Instrument.Keys],
SortAttribute.SixFretGuitar => _sortInstruments[Instrument.SixFretGuitar],
SortAttribute.SixFretBass => _sortInstruments[Instrument.SixFretBass],
SortAttribute.SixFretRhythm => _sortInstruments[Instrument.SixFretRhythm],
SortAttribute.SixFretCoop => _sortInstruments[Instrument.SixFretCoopGuitar],
SortAttribute.FourLaneDrums => _sortInstruments[Instrument.FourLaneDrums],
SortAttribute.ProDrums => _sortInstruments[Instrument.ProDrums],
SortAttribute.FiveLaneDrums => _sortInstruments[Instrument.FiveLaneDrums],
SortAttribute.EliteDrums => _sortInstruments[Instrument.EliteDrums],
SortAttribute.ProGuitar_17 => _sortInstruments[Instrument.ProGuitar_17Fret],
SortAttribute.ProGuitar_22 => _sortInstruments[Instrument.ProGuitar_22Fret],
SortAttribute.ProBass_17 => _sortInstruments[Instrument.ProBass_17Fret],
SortAttribute.ProBass_22 => _sortInstruments[Instrument.ProBass_22Fret],
SortAttribute.ProKeys => _sortInstruments[Instrument.ProKeys],
SortAttribute.Vocals => _sortInstruments[Instrument.Vocals],
SortAttribute.Harmony => _sortInstruments[Instrument.Harmony],
SortAttribute.Band => _sortInstruments[Instrument.Band],
_ => null
};
}
catch (KeyNotFoundException)
{
YargLogger.LogFormatDebug("Invalid Sort Attribute: {0}", sort);
}
// Make life better when people go back a version and we
// encounter sorts we don't understand by providing a
// default rather than a blank song library
if (proposedSort != null)
{
return proposedSort;
}
YargLogger.LogInfo("Invalid Sort Attribute. Defaulting to Name sort.");
return _sortTitles;
}
public static bool HasInstrument(Instrument instrument)
{
return _sortInstruments.ContainsKey(instrument);
}
private static HashSet<Instrument> _instruments = null;
private static SongCategory[] GetPlayableSongs()
{
HashSet<Instrument> instruments = new();
foreach (var player in PlayerContainer.Players)
{
instruments.Add(player.Profile.CurrentInstrument);
}
if (_playables == null || !_instruments.SetEquals(instruments))
{
_instruments = instruments;
if (instruments.Count == 0)
{
_playables = _sortTitles;
}
else
{
var gamemodes = new HashSet<GameMode>();
var queries = default(HashSet<SongEntry>);
foreach (var player in PlayerContainer.Players)
{
if (!gamemodes.Add(player.Profile.GameMode))
{
continue;
}
var set = new HashSet<SongEntry>();
foreach (var ins in player.Profile.GameMode.PossibleInstruments())
{
if (HasInstrument(ins))
{
foreach (var list in _sortedSongs.Instruments[ins].Values)
{
foreach (var entry in list)
{
set.Add(entry);
}
}
}
}
if (queries != null)
{
queries.IntersectWith(set);
}
else
{
queries = set;
}
}
var arr = new SongCategory[_sortTitles.Length];
int categoryCount = 0;
for (int i = 0; i < arr.Length; i++)
{
var node = _sortTitles[i];
var intersect = new SongEntry[node.Songs.Length];
int intersectCount = 0;
for (int songIndex = 0; songIndex < node.Songs.Length; ++songIndex)
{
if (queries.Contains(node.Songs[songIndex]))
{
intersect[intersectCount++] = node.Songs[songIndex];
}
}
if (intersectCount > 0)
{
arr[categoryCount++] = new SongCategory($"Playable [{node.Category}]", intersect[..intersectCount], node.Category);
}
}
_playables = arr[..categoryCount];
}
}
return _playables;
}
public static SongEntry GetRandomSong()
{
return _songs.Pick();
}
public static void InvalidateStarsCache()
{
_starsCacheValid = false;
_sortStars = Array.Empty<SongCategory>();
_runtimeStars.Clear();
}
// Play count sorting is intentionally not cached, as it must be regenerated after
// every play, when profiles change, and probably a bunch of other stuff
private static SongCategory[] GetPlaycounts()
{
int[] countThresholds = { 100, 50, 40, 30, 20, 10, 5, 1 };
// This should never happen since play count shouldn't be selectable without
// a non-bot profile and MusicLibraryMenu already checks for this, but let's double check
if (PlayerContainer.OnlyHasBotsActive())
{
// Titles seems like a reasonable fallback
return _sortTitles;
}
var player = PlayerContainer.Players.FirstOrDefault(e => !e.Profile.IsBot);
if (player == null)
{
// This case should have been caught above, but just in case
return _sortTitles;
}
// Set up an array of lists of songentries, one for each play count threshold (plus one for the unplayed header)
var categorySongs = new List<SongEntry>[countThresholds.Length];
for (int i = 0; i < countThresholds.Length; i++)
{
categorySongs[i] = new List<SongEntry>();
}
var counts = ScoreContainer.GetPlayedSongsForUserByPlaycount(player.Profile, SortOrdering.Descending);
// Counts will be in descending order, so we can iterate through the list until we drop below the threshold
// and then move to the next threshold
int thresholdIndex = 0;
foreach ((SongEntry song, int count) in counts)
{
if (count < countThresholds[thresholdIndex])
{
// Increase thresholdIndex until threshold is less than or equal to count and add the song to that category
while (count < countThresholds[thresholdIndex] && thresholdIndex < countThresholds.Length - 1)
{
thresholdIndex++;
}
}
// Double check that we haven't run out of thresholds
if (thresholdIndex >= countThresholds.Length)
{
break;
}
categorySongs[thresholdIndex].Add(song);
}
// Get all the unplayed songs and stuff them on the end of the list
var zeroPlaySongs = new List<SongEntry>();
var zeroPlayCategories = new List<SongCategory>();
var previousSort = SettingsManager.Settings.PreviousLibrarySort;
if (previousSort == SortAttribute.Unspecified)
{
// I don't think this should ever happen, but I'm not certain,
// so belt and suspenders wins.
previousSort = SortAttribute.Name;
}
foreach (var category in GetSortedCategory(previousSort))
{
foreach (var song in category.Songs)
{
if (!counts.ContainsKey(song))
{
zeroPlaySongs.Add(song);
}
}
zeroPlayCategories.Add(new SongCategory(category.Category, zeroPlaySongs.ToArray(), category.CategoryGroup));
zeroPlaySongs.Clear();
}
int filledCategories = 0;
for (int i = 0; i < countThresholds.Length; i++)
{
if (categorySongs[i].Count > 0)
{
filledCategories++;
}
}
var categories = new SongCategory[filledCategories + zeroPlayCategories.Count];
// Build the played categories, skipping any unfilled categories
int categoryIndex = 0;
for (int i = 0; i < countThresholds.Length; i++)
{
if (categorySongs[i].Count > 0)
{
categories[categoryIndex] = new SongCategory($"Played {countThresholds[i]}+ times", categorySongs[i].ToArray(), $"Played {countThresholds[i]}+ times");
categoryIndex++;
}
}
// Now add the unplayed categories
for (int i = 0; i < zeroPlayCategories.Count; i++)
{
categories[categoryIndex + i] = zeroPlayCategories[i];
}
return categories;
}
private static SongCategory[] GetStars()
{
if (PlayerContainer.OnlyHasBotsActive())
{
// If the previous sort exists and is reasonable, use that, otherwise use titles
var previousSort = SettingsManager.Settings.PreviousLibrarySort;
if (previousSort != SortAttribute.Stars && previousSort != SortAttribute.Playcount &&
previousSort != SortAttribute.Playable)
{
return GetSortedCategory(previousSort);
}
return _sortTitles;
}
YargPlayer player = PlayerContainer.Players.FirstOrDefault(e => !e.Profile.IsBot);
if (player == null)
{
// This case should have been caught above, but just in case
return _sortTitles;
}
var profile = player.Profile;
if (_starsCacheValid &&
_starsCacheProfileId == profile.Id &&
_starsCacheInstrument == profile.CurrentInstrument &&
_starsCacheDifficulty == profile.CurrentDifficulty)
{
return _sortStars;
}
_runtimeStars.Clear();
Dictionary<HashWrapper, StarAmount> bestStars = ScoreContainer.GetBestStarsForSong(profile);
foreach (var song in _songs)
{
if (!bestStars.TryGetValue(song.Hash, out StarAmount stars))
{
stars = StarAmount.None;
}
_runtimeStars[song] = stars;
}
Instrument instrument = player.Profile.CurrentInstrument;
IntensityComparer comparer = new IntensityComparer(instrument);
// Use Dictionary instead of array due to complex enum values
Dictionary<StarAmount, List<SongEntry>> grouped = new Dictionary<StarAmount, List<SongEntry>>();
foreach (var song in _songs)
{
StarAmount key = StarAmount.NoPart;
if (song[instrument].IsActive() && !_runtimeStars.TryGetValue(song, out key))
{
key = StarAmount.None;
}
if (!grouped.TryGetValue(key, out List<SongEntry> list))
{
list = new List<SongEntry>();
grouped[key] = list;
}
int index = list.BinarySearch(song, comparer);
list.Insert(~index, song);
}
List<StarAmount> sortedKeys = grouped.Keys.ToList();
sortedKeys.Sort((a, b) => b.GetSortWeight().CompareTo(a.GetSortWeight()));
SongCategory[] starCategories = new SongCategory[sortedKeys.Count];
int i = 0;
foreach (var key in sortedKeys)
{
List<SongEntry> list = grouped[key];
string label = key.GetDisplayName();
starCategories[i++] = new SongCategory(label, list.ToArray(), label);
}
_sortStars = starCategories;
_starsCacheProfileId = profile.Id;
_starsCacheInstrument = profile.CurrentInstrument;
_starsCacheDifficulty = profile.CurrentDifficulty;
_starsCacheValid = true;
return _sortStars;
}
private static SongCategory[] GetRandomSort()
{
var shuffled = new List<SongEntry>(_songs);
shuffled.Shuffle();
return new[] { new SongCategory(string.Empty, shuffled.ToArray(), null) };
}
private static void UpdateSongUi(LoadingContext context)
{
var tracker = CacheHandler.Progress;
string phrase = string.Empty;
string subText = null;
switch (tracker.Stage)
{
case ScanStage.LoadingCache:
phrase = "Loading song cache...";
break;
case ScanStage.LoadingSongs:
phrase = "Loading songs...";
break;
case ScanStage.Sorting:
phrase = "Sorting songs...";
break;
case ScanStage.WritingCache:
phrase = "Writing song cache...";
break;
case ScanStage.WritingBadSongs:
phrase = "Writing bad songs...";
break;
}
switch (tracker.Stage)
{
case ScanStage.LoadingCache:
case ScanStage.LoadingSongs:
subText = $"Folders Scanned: {tracker.NumScannedDirectories}\n" +
$"Songs Scanned: {tracker.Count}\n" +
$"Errors: {tracker.BadSongCount}"; break;
}
context.SetLoadingText(phrase, subText);
}
private static void FillContainers()
{
InvalidateStarsCache();
_songs = SetAllSongs(_songCache.Entries);
_sortArtists = Convert(_sortedSongs.Artists, SongAttribute.Artist);
_sortAlbums = Convert(_sortedSongs.Albums, SongAttribute.Album);
_sortGenres = Convert(_sortedSongs.Genres, SongAttribute.Genre);
_sortSubgenres = Convert(_sortedSongs.Subgenres, SongAttribute.Subgenre);
_sortCharters = Convert(_sortedSongs.Charters, SongAttribute.Charter);
_sortPlaylists = Convert(_sortedSongs.Playlists, SongAttribute.Playlist);
_sortSources = Convert(_sortedSongs.Sources, SongAttribute.Source);
_sortArtistAlbums = Combine(_sortedSongs.ArtistAlbums);
_sortTitles = Cast(_sortedSongs.Titles);
_sortYears = Cast(_sortedSongs.Years);
_sortSongLengths = Cast(_sortedSongs.SongLengths);
_playables = null;
_sortDatesAdded = new SongCategory[_sortedSongs.DatesAdded.Count];
{
int index = 0;
foreach (var node in _sortedSongs.DatesAdded)
{
_sortDatesAdded[index++] = new(node.Key.ToLongDateString(), node.Value.ToArray(), node.Key.ToString("y"));
}
}
_sortInstruments.Clear();
foreach (var instrument in _sortedSongs.Instruments)
{
try
{
var arr = new SongCategory[instrument.Value.Count];
int index = 0;
foreach (var difficulty in instrument.Value)
{
string categoryName = $"{instrument.Key.ToSortAttribute().ToLocalizedName()} [{difficulty.Key}]";
arr[index++] = new SongCategory(categoryName, difficulty.Value.ToArray(), categoryName);
}
_sortInstruments.Add(instrument.Key, arr);
}
catch (Exception ex)
{
YargLogger.LogException(ex);
}
}
static SongEntry[] SetAllSongs(Dictionary<HashWrapper, List<SongEntry>> entries)
{
_songsByHash.Clear();
int songCount = 0;
foreach (var node in entries)
{
var count = node.Value.Count;
for (int i = 0; i < count; i++)
{
if (AllowedByRating(node.Value[i].GetSongRating(SettingsManager.Settings.CensorMatureContent.Value)))
{
songCount++;
}
}
}
SongEntry[] songs = new SongEntry[songCount];
int index = 0;
foreach (var node in entries)
{
for (int i = 0; i < node.Value.Count; i++)
{
if (AllowedByRating(node.Value[i].GetSongRating(SettingsManager.Settings.CensorMatureContent.Value)))
{
if (_songsByHash.ContainsKey(node.Key))
{
_songsByHash[node.Key].Add(node.Value[i]);
}
else
{
_songsByHash.Add(node.Key, new List<SongEntry> { node.Value[i] });
}
songs[index++] = node.Value[i];
}
}
}
return songs;
}
static SongCategory[] Convert(SortedDictionary<SortString, List<SongEntry>> list, SongAttribute attribute)
{
var sections = new SongCategory[list.Count];
int index = 0;
foreach (var node in list)
{
string key;
switch (attribute)
{
case SongAttribute.Artist:
key = node.Value[0].Artist;
break;
case SongAttribute.Album:
key = node.Value[0].Album;
break;
case SongAttribute.Charter:
key = node.Value[0].Charter;
break;
case SongAttribute.Genre:
{
var genre = node.Value[0].Genre;
if (genre.Length > 0 && char.IsLower(genre[0]))
{
key = genre[0].ToString();
if (genre.Length > 1)
{
key += genre[1..];
}
}
else
{
key = genre;
}
break;
}
case SongAttribute.Subgenre:
{
var subgenre = string.IsNullOrEmpty(node.Value[0].Subgenre) ? node.Value[0].Genre : node.Value[0].Subgenre;
if (subgenre.Length > 0 && char.IsLower(subgenre[0]))
{
key = subgenre[0].ToString();
if (subgenre.Length > 1)
{
key += subgenre[1..];
}
}
else
{
key = subgenre;
}
break;
}
case SongAttribute.Playlist:
key = node.Value[0].Playlist;
break;
case SongAttribute.Source:
key = node.Value[0].Source;
break;
default:
throw new ArgumentException(nameof(attribute));
}
string categoryGroupName = attribute switch
{
SongAttribute.Artist or
SongAttribute.Album or
SongAttribute.Charter => node.Key.Group switch
{
CharacterGroup.Empty or
CharacterGroup.AsciiSymbol => "*",
CharacterGroup.AsciiNumber => "0-9",
_ => char.ToUpperInvariant(node.Key.SortStr[0]).ToString(),
},
_ => key,
};
sections[index++] = new SongCategory(key, node.Value.ToArray(), categoryGroupName);
}
return sections;
}
static SongCategory[] Cast(SortedDictionary<string, List<SongEntry>> list)
{
var sections = new SongCategory[list.Count];
int index = 0;
foreach (var (key, section) in list)
{
sections[index++] = new SongCategory(key, section.ToArray(), key);
}
return sections;
}
static SongCategory[] Combine(SortedDictionary<SortString, SortedDictionary<SortString, List<SongEntry>>> artistAlbums)
{
int count = 0;
foreach (var artist in artistAlbums)
{
count += artist.Value.Count;
}
var sort = new SongCategory[count];
int index = 0;
foreach (var artist in artistAlbums)
{
string categoryGroupName = artist.Key.Group switch
{
CharacterGroup.Empty or
CharacterGroup.AsciiSymbol => "*",
CharacterGroup.AsciiNumber => "0-9",
_ => char.ToUpperInvariant(artist.Key.SortStr[0]).ToString(),
};
foreach (var album in artist.Value)
{
sort[index++] = new SongCategory($"{album.Value[0].Artist} - {album.Value[0].Album}", album.Value.ToArray(), categoryGroupName);
}
}
return sort;
}
}
public static void RequestContainerRefresh()
{
SongSorting.SortEntries(_songCache, _sortedSongs);
FillContainers();
}
readonly struct IntensityComparer : IComparer<SongEntry>
{
private readonly Instrument _instrument;
public IntensityComparer(Instrument instrument)
{
_instrument = instrument;
}
public int Compare(SongEntry x, SongEntry y)
{
int intensityX = x[_instrument].Intensity;
int intensityY = y[_instrument].Intensity;
if (intensityX == intensityY)
{
return SongEntrySorting.MetadataComparer.Instance.Compare(x, y);
}
else if (intensityX == -1)
{
return 1;
}
else if (intensityY == -1)
{
return -1;
}
return intensityX.CompareTo(intensityY);
}
}
}
}