-
Notifications
You must be signed in to change notification settings - Fork 348
Expand file tree
/
Copy pathMusicLibraryMenu.cs
More file actions
1285 lines (1090 loc) · 44.6 KB
/
Copy pathMusicLibraryMenu.cs
File metadata and controls
1285 lines (1090 loc) · 44.6 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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using TMPro;
using UnityEngine;
using YARG.Core;
using YARG.Core.Audio;
using YARG.Core.Game;
using YARG.Core.Input;
using YARG.Core.Song;
using YARG.Localization;
using YARG.Menu.Filters;
using YARG.Menu.ListMenu;
using YARG.Menu.Navigation;
using YARG.Menu.Persistent;
using YARG.Player;
using YARG.Playlists;
using YARG.Scores;
using YARG.Settings;
using YARG.Song;
using static YARG.Menu.Navigation.Navigator;
using Random = UnityEngine.Random;
namespace YARG.Menu.MusicLibrary
{
public enum MusicLibraryMode
{
QuickPlay,
Practice
}
public enum MusicLibraryReloadState
{
None,
Partial,
Full
}
public enum MenuState
{
Library,
PlaylistSelect,
Playlist,
Show
}
public partial class MusicLibraryMenu : ListMenu<ViewType, SongView>
{
private const int RANDOM_SONG_ID = 0;
private const int PLAYLIST_ID = 1;
private const int BACK_ID = 2;
private const int RECOMMENDED_SONGS_ID = 3;
private const int CREATE_NEW_PLAYLIST_ID = 4;
public static MusicLibraryMode LibraryMode;
public static SongEntry CurrentlyPlaying;
public MenuState MenuState;
public Playlist SelectedPlaylist;
private static int _savedIndex;
private static SelectionSnapshot _savedSelectionSnapshot;
private static bool _hasSavedSelectionSnapshot;
private static bool _forceGoToCurrentlyPlaying;
private static SongEntry _forceGoToSong;
private static int _mainLibraryIndex = -1;
private static MusicLibraryReloadState _reloadState = MusicLibraryReloadState.Full;
private static Playlist _savedPlaylist;
public bool PlaylistMode => SelectedPlaylist != null;
public static void SetReload(MusicLibraryReloadState state)
{
_reloadState = state;
}
public static void RequestGoToCurrentlyPlaying(SongEntry song)
{
CurrentlyPlaying = song;
_forceGoToCurrentlyPlaying = song != null;
_forceGoToSong = song;
}
[Space]
[SerializeField]
private SongSearchingField _searchField;
[SerializeField]
private TextMeshProUGUI _subHeader;
[SerializeField]
private Sidebar _sidebar;
[SerializeField]
private GameObject _noPlayerWarning;
[SerializeField]
private PopupMenu _popupMenu;
protected override int ExtraListViewPadding => 15;
protected override bool CanScroll => !_popupMenu.gameObject.activeSelf;
public bool ShouldDisplaySoloHighScores { get; private set; }
public IReadOnlyList<SongCategory> SortedSongs => _sortedSongs;
private CancellationTokenSource _previewCanceller;
private PreviewContext _previewContext;
private double _previewDelay;
private SongEntry _currentSong;
public List<(string, int)> Shortcuts { get; private set; } = new();
private List<HoldContext> _heldInputs = new();
// Doesn't go through PlaylistContainer because it is ephemeral
private static Instrument _lastInstrument;
private static Difficulty _lastDifficulty;
private static bool _needsReload = false;
private bool _needsNavigationSchemeRefresh = false;
public static void NeedsReload()
{
_needsReload = true;
}
protected override void Awake()
{
base.Awake();
// Initialize sidebar
_sidebar.Initialize(this, _searchField);
// Fill in sort information
UpdateSortInformationHeader();
// Ensure collapsed-header sets exist for each sort attribute
InitializeCollapsedHeaderSets();
}
protected override void OnEnable()
{
base.OnEnable();
_heldInputs.Clear();
// Hack to ensure that crowd samples are stopped no matter what
GlobalAudioHandler.StopAllSfxChannels();
// Set navigation scheme
SetNavigationScheme();
// Restore search
_searchField.Restore();
_searchField.OnSearchQueryUpdated += UpdateSearch;
if (CurrentlyPlaying != null)
{
_currentSong = CurrentlyPlaying;
}
FiltersMenu.RefreshActiveFilterPredicate();
SetRefreshIfNeeded();
StemSettings.ApplySettings = SettingsManager.Settings.ApplyVolumesInMusicLibrary.Value;
_previewDelay = 0;
if (_reloadState == MusicLibraryReloadState.Full)
{
Refresh();
}
else if (_reloadState == MusicLibraryReloadState.Partial)
{
// Note that the order matters here: SelectedPlaylist must be set before calling UpdateSearch,
// but SelectedIndex must be set _after_ calling UpdateSearch
SelectedPlaylist = _savedPlaylist;
if (SelectedPlaylist != null)
{
// Preserve the playlist select anchor across menu reloads (e.g., after playing a song)
_lastPlaylistSelectPlaylist = SelectedPlaylist;
MenuState = MenuState.Playlist;
}
UpdateSearch(true);
if (MenuState == MenuState.Library && _mainLibraryIndex != -1)
{
SelectedIndex = _mainLibraryIndex;
}
else
{
SelectedIndex = _savedIndex;
}
}
else if (_currentSong != null)
{
UpdateSearch(true);
}
if (MenuState == MenuState.Library && _hasSavedSelectionSnapshot)
{
RestoreSelectionSnapshot(_savedSelectionSnapshot);
_hasSavedSelectionSnapshot = false;
}
if (_forceGoToCurrentlyPlaying && MenuState == MenuState.Library && !PlaylistMode)
{
TrySelectCurrentSongPreferNaturalLocation(_forceGoToSong ?? _currentSong);
_forceGoToCurrentlyPlaying = false;
_forceGoToSong = null;
}
CurrentlyPlaying = null;
_reloadState = MusicLibraryReloadState.None;
// Set proper text
_subHeader.text = LibraryMode switch
{
MusicLibraryMode.QuickPlay => Localize.Key("Menu.Main.Options.Quickplay"),
MusicLibraryMode.Practice => Localize.Key("Menu.Main.Options.Practice"),
_ => throw new Exception("Unreachable.")
};
// Set IsPractice as well
GlobalVariables.State.IsPractice = LibraryMode == MusicLibraryMode.Practice;
GlobalVariables.State.CurrentReplay = null;
GlobalVariables.State.PlayingWithReplay = false;
// Show no player warning
_noPlayerWarning.SetActive(PlayerContainer.Players.Count <= 0);
// Make sure sort is not by play count if there are only bots
if (PlayerContainer.OnlyHasBotsActive() &&
(SettingsManager.Settings.LibrarySort == SortAttribute.Playcount ||
SettingsManager.Settings.LibrarySort == SortAttribute.Stars))
{
// Name makes a good fallback?
ChangeSort(SortAttribute.Name);
}
// Fill in sort information
UpdateSortInformationHeader();
PlayerContainer.PlayerAdded += OnPlayerAdded;
PlayerContainer.PlayerRemoved += OnPlayerRemoved;
// Ensure the sidebar is rendered correctly on first entry
_sidebar.UpdateSidebar(true);
}
private void SetRefreshIfNeeded()
{
YargProfile profile = null;
foreach (YargPlayer p in PlayerContainer.Players)
{
if (!p.Profile.IsBot)
{
profile = p.Profile;
break;
}
}
Instrument currentInstrument = profile?.CurrentInstrument ?? Instrument.FiveFretGuitar;
Difficulty currentDifficulty = profile?.CurrentDifficulty ?? Difficulty.Expert;
if (_needsReload ||
currentInstrument != _lastInstrument ||
currentDifficulty != _lastDifficulty)
{
_lastInstrument = currentInstrument;
_lastDifficulty = currentDifficulty;
_needsReload = false;
if (_reloadState != MusicLibraryReloadState.Full)
{
_reloadState = MusicLibraryReloadState.Partial;
}
}
}
// Public because PopupMenu may need to reset the navigation scheme
public void SetNavigationScheme(bool reset = false)
{
// Show mode sets its own navigation, don't overwrite
if (MenuState == MenuState.Show)
{
return;
}
if (reset)
{
Navigator.Instance.PopScheme();
}
bool isSelectingPlaylist = MenuState == MenuState.PlaylistSelect;
bool setListNotEmpty = ShowPlaylist.Count > 0;
_sidebar.UpdatePlayButtonLabel(setListNotEmpty);
NavigationScheme.Entry leftEntry = MenuState == MenuState.Playlist
? new NavigationScheme.Entry(MenuAction.Left, "Menu.MusicLibrary.MoveInPlaylist", MovePlaylistEntryUp)
: new NavigationScheme.Entry(MenuAction.Left, "Menu.MusicLibrary.SkipSection", GoToPreviousSection);
NavigationScheme.Entry rightEntry = MenuState == MenuState.Playlist
? new NavigationScheme.Entry(MenuAction.Right, "Menu.MusicLibrary.MoveInPlaylist", MovePlaylistEntryDown)
: new NavigationScheme.Entry(MenuAction.Right, "Menu.MusicLibrary.SkipSection", GoToNextSection);
// Give yellow the same behaviour as green: press to add to set, hold to start the set
NavigationScheme.Entry yellowEntry;
if (SettingsManager.Settings.EnablePlayAShow.Value)
{
yellowEntry = new NavigationScheme.Entry(
MenuAction.Yellow,
"Menu.MusicLibrary.HoldPlayShow",
() => { }, // tap does nothing
holdSeconds: GREEN_HOLD_SECONDS,
onHoldHandler: EnterShowMode
);
}
else
{
yellowEntry = new NavigationScheme.Entry(
MenuAction.Yellow,
"Menu.MusicLibrary.AddHoldStartSet",
_ => AddToPlaylist(),
holdSeconds: GREEN_HOLD_SECONDS,
onHoldHandler: OnGreenHold // Use existing function
);
}
var entries = new List<NavigationScheme.Entry>
{
new NavigationScheme.Entry(MenuAction.Up, "Menu.Common.Up",
ctx =>
{
if (IsButtonHeldByPlayer(ctx.Player, MenuAction.Orange))
{
GoToPreviousSection();
}
else
{
SetWrapAroundState(!ctx.IsRepeat);
SelectedIndex--;
}
}),
new NavigationScheme.Entry(MenuAction.Down, "Menu.Common.Down",
ctx =>
{
if (IsButtonHeldByPlayer(ctx.Player, MenuAction.Orange))
{
GoToNextSection();
}
else
{
SetWrapAroundState(!ctx.IsRepeat);
SelectedIndex++;
}
}),
leftEntry,
rightEntry,
isSelectingPlaylist ?
new NavigationScheme.Entry(
MenuAction.Green,
"Menu.Common.Confirm",
() => CurrentSelection?.PrimaryButtonClick(),
hide: true
) :
new NavigationScheme.Entry(
MenuAction.Green,
setListNotEmpty ?
"Menu.MusicLibrary.AddHoldStartSet" :
"Menu.MusicLibrary.PlayHoldAddToSet",
OnGreenTap,
holdSeconds: GREEN_HOLD_SECONDS,
onHoldHandler: OnGreenHold,
hide: true
),
new NavigationScheme.Entry(MenuAction.Red, "Menu.Common.Back", Back, hide: true),
yellowEntry,
new NavigationScheme.Entry(MenuAction.Blue, "Menu.MusicLibrary.Filters", OpenFilters),
new NavigationScheme.Entry(MenuAction.Orange, "Menu.MusicLibrary.MoreOptions",
OnOrangeHit, OnOrangeRelease),
};
Navigator.Instance.PushScheme(new NavigationScheme(entries, false));
}
protected override void OnSelectedIndexChanged()
{
const double PREVIEW_SCROLL_DELAY = .6f;
base.OnSelectedIndexChanged();
if (IsFiltersMenuOpen())
{
return;
}
_sidebar.UpdateSidebar();
if (CurrentSelection is SongViewType song)
{
if (CurrentlyPlaying == null && song.SongEntry == _currentSong &&
_previewCanceller != null && !_previewCanceller.IsCancellationRequested)
{
return;
}
_currentSong = song.SongEntry;
}
else
{
_currentSong = null;
}
StopPreview();
_previewCanceller = new CancellationTokenSource();
StartPreview(_previewDelay, _previewCanceller);
_previewDelay = PREVIEW_SCROLL_DELAY;
}
protected override List<ViewType> CreateViewList()
{
// Shortcuts will be re-queried every time the list is refreshed
_primaryHeaderIndex = 0;
_recommendedHeaderIndex = -1;
var viewList = MenuState switch
{
MenuState.Library => CreateNormalViewList(),
MenuState.PlaylistSelect => CreatePlaylistSelectViewList(),
MenuState.Playlist => CreatePlaylistViewList(),
MenuState.Show => CreateShowViewList(),
_ => throw new Exception("Unreachable.")
};
// Disable shortcuts if there are less than 2 sort headers in the viewlist
HasSortHeaders = _sortedSongs is not null && _sortedSongs.Length > 1;
return viewList;
}
private List<ViewType> CreateNormalViewList()
{
var list = new List<ViewType>();
_totalStarCount = 0;
// If `_sortedSongs` is null, then this function is being called during very first initialization,
// which means the song list hasn't been constructed yet.
if (_sortedSongs is null || SongContainer.Count <= 0)
{
return list;
}
if (!_sortedSongs.Any(section => section.Songs.Length > 0))
{
list.Add(new SortHeaderViewType(Localize.Key("Menu.MusicLibrary.NoSongsMatchCriteria"), 0, null, Array.Empty<SongEntry>()));
return list;
}
bool allowdupes = SettingsManager.Settings.AllowDuplicateSongs.Value;
int songCount = 0;
foreach (var section in _sortedSongs)
{
if (allowdupes)
{
songCount += section.Songs.Length;
continue;
}
foreach (var song in section.Songs)
{
if (!song.IsDuplicate)
{
++songCount;
}
}
}
if (!_searchField.IsSearching)
{
list.Add(new ButtonViewType(
Localize.Key("Menu.MusicLibrary.Playlists"),
"MusicLibraryIcons[Playlists]",
EnterPlaylistSelectFromLibrary,
PLAYLIST_ID,
Localize.Key("Menu.MusicLibrary.PlaylistsHelp")));
_primaryHeaderIndex += 1;
if (SettingsManager.Settings.LibrarySort < SortAttribute.Instrument &&
SettingsManager.Settings.ShowRecommendedSongs.Value)
{
if (_recommendedSongs != null)
{
string key = Localize.Key("Menu.MusicLibrary.RecommendedSongs",
_recommendedSongs.Length == 1 ? "Singular" : "Plural");
list.Add(new ButtonViewType(key, "MusicLibraryIcons[Recommended]",
() =>
{
bool selectTopOfList = CurrentSelection is SongViewType songView &&
_recommendedSongs.Contains(songView.SongEntry);
bool preserveSelectedIndex = SelectedIndex != _recommendedHeaderIndex;
RefreshAndReselect(selectTopOfList, preserveSelectedIndex);
},
RECOMMENDED_SONGS_ID,
Localize.Key("Menu.MusicLibrary.RecommendedSongsHelp")
));
_recommendedHeaderIndex = list.Count - 1;
foreach (var song in _recommendedSongs)
{
list.Add(new SongViewType(this, song, "recommended"));
}
_primaryHeaderIndex += _recommendedSongs.Length + 1;
}
}
}
bool showSortHeaders = _sortedSongs.Length > 1 ||
YARG.Menu.Filters.FiltersMenu.ActiveFilterPredicate != null;
foreach (var (section, index) in _sortedSongs.Select((s, i) => (s, i)))
{
var displayName = section.Category;
if (SettingsManager.Settings.LibrarySort == SortAttribute.Source)
{
if (SongSources.TryGetSource(section.Category, out var parsedSource))
{
displayName = parsedSource.GetDisplayName();
}
else if (section.Category.Length > 0)
{
displayName = section.Category;
}
else
{
displayName = SongSources.Default.GetDisplayName();
}
}
SortHeaderViewType sortHeader = null;
// When searching with the generic Search Bar, results come back under a single
// "Search Results" category sorted by relevance. We're showing that text in the
// banner and hiding the redundant category header.
bool hideSearchResultsHeader = _searchField.IsSearching &&
string.Equals(section.Category, "Search Results", StringComparison.OrdinalIgnoreCase);
if (showSortHeaders && !hideSearchResultsHeader)
{
Action onHeaderClicked = null;
if (_sortedSongs.Length > 1)
{
onHeaderClicked = () =>
{
var category = _sortedSongs[index];
if (_collapsedHeaders[SettingsManager.Settings.LibrarySort].Contains(category))
{
_collapsedHeaders[SettingsManager.Settings.LibrarySort].Remove(category);
}
else
{
_collapsedHeaders[SettingsManager.Settings.LibrarySort].Add(category);
}
var (headerIndex, offset) = GetClosestHeaderIndexAndOffset();
RequestViewListUpdate();
var closestHeader = ViewList[_sectionHeaderIndices[headerIndex]];
if (closestHeader is SortHeaderViewType closestSortHeader && closestSortHeader.Collapsed)
{
// If the current section is collapsed, return to its header.
offset = 0;
}
SelectedIndex = _sectionHeaderIndices[headerIndex] + offset;
};
}
sortHeader = new SortHeaderViewType(
displayName,
section.Songs.Length,
section.CategoryGroup,
section.Songs,
_collapsedHeaders[SettingsManager.Settings.LibrarySort].Contains(section),
onHeaderClicked);
list.Add(sortHeader);
}
int sectionTotalStars = 0;
bool includeSongs = _sortedSongs.Length <= 1 || !_collapsedHeaders[SettingsManager.Settings.LibrarySort].Contains(section);
foreach (var song in section.Songs)
{
if (!allowdupes && song.IsDuplicate) continue;
StarAmount? starAmount;
if (includeSongs)
{
var songView = new SongViewType(this, song);
list.Add(songView);
starAmount = songView.GetStarAmount();
}
else
{
starAmount = SongViewType.GetStarAmountForSong(song);
}
if (starAmount is not null)
{
sectionTotalStars += starAmount.Value.GetStarCount();
}
}
_totalStarCount += sectionTotalStars;
if (sortHeader != null)
{
sortHeader.TotalStarsCount = sectionTotalStars;
}
}
_totalSongCount = songCount;
CalculateCategoryHeaderIndices(list);
return list;
}
private void ExitLibrary()
{
ShowPlaylist.Clear();
_previewCanceller?.Cancel();
_previewContext?.Dispose();
_previewContext = null;
StemSettings.ApplySettings = true;
MenuManager.Instance.PopMenu();
}
private bool TrySelectCurrentSongPreferNaturalLocation(SongEntry targetSong)
{
if (targetSong == null)
return false;
int newPositionStartIndex = _recommendedHeaderIndex != -1 ? _primaryHeaderIndex : 0;
bool selected = SetIndexTo(i => i is SongViewType view &&
view.SongEntry.SortBasedLocation == targetSong.SortBasedLocation,
newPositionStartIndex);
return selected;
}
public void Refresh()
{
SetRecommendedSongs();
_searchField.Reset();
UpdateSearch(true);
if (IsNavigationSchemeBlocked())
{
_needsNavigationSchemeRefresh = true;
return;
}
SetNavigationScheme();
}
private bool IsNavigationSchemeBlocked()
{
if (_popupMenu != null && _popupMenu.gameObject.activeSelf)
return true;
if (DialogManager.Instance != null && DialogManager.Instance.IsDialogShowing)
return true;
return false;
}
public void RefreshNavigationSchemeAfterPopup()
{
if (!_needsNavigationSchemeRefresh) return;
_needsNavigationSchemeRefresh = false;
SetNavigationScheme(true);
}
private void ClearPreview()
{
StopPreview(clearCurrentSong: true);
}
private void StopPreview(bool clearCurrentSong = false)
{
_ = StopPreviewAsync(clearCurrentSong);
}
private async Task StopPreviewAsync(bool clearCurrentSong = false)
{
if (clearCurrentSong)
{
_currentSong = null;
}
// Snapshot the current preview before awaiting so a newer preview started in the meantime
// cannot be canceled, disposed, or cleared by this older shutdown path.
var previewCanceller = _previewCanceller;
var previewContext = _previewContext;
_previewCanceller = null;
_previewContext = null;
previewCanceller?.Cancel();
if (previewContext != null)
{
await previewContext.WaitForCompletionAsync();
}
previewCanceller?.Dispose();
}
private void DisposePreview()
{
var previewCanceller = _previewCanceller;
var previewContext = _previewContext;
_previewCanceller = null;
_previewContext = null;
_currentSong = null;
previewCanceller?.Cancel();
previewContext?.Dispose();
previewCanceller?.Dispose();
}
private void EnterPlaylistSelectFromLibrary()
{
MenuState = MenuState.PlaylistSelect;
ClearPreview();
Refresh();
if (ViewList.Count > 0)
{
SelectedIndex = 0;
}
else
{
_sidebar.UpdateSidebar(true);
}
}
protected void Update()
{
foreach (var heldInput in _heldInputs)
heldInput.Timer -= Time.unscaledDeltaTime;
if (_needsNavigationSchemeRefresh && !IsNavigationSchemeBlocked())
{
_needsNavigationSchemeRefresh = false;
SetNavigationScheme(true);
}
}
private async void StartPreview(double delay, CancellationTokenSource canceller)
{
if (_currentSong == null)
{
return;
}
if (IsFiltersMenuOpen())
{
return;
}
const double FADE_DURATION = 1.25;
float previewVolume = SettingsManager.Settings.PreviewVolume.Value;
if (previewVolume == 0)
{
return;
}
var context = await PreviewContext.Create(
_currentSong,
previewVolume,
GlobalVariables.State.SongSpeed,
delay,
FADE_DURATION,
canceller.Token);
if (context != null)
{
if (_previewCanceller == canceller && !canceller.IsCancellationRequested)
{
_previewContext = context;
}
else
{
context.Dispose();
}
}
}
protected override void OnDisable()
{
base.OnDisable();
SetSidebarDifficultiesVisible(false);
_heldInputs.Clear();
if (Navigator.Instance == null) return;
// Save state
_savedIndex = SelectedIndex;
_savedPlaylist = SelectedPlaylist;
if (MenuState == MenuState.Library && !PlaylistMode)
{
bool preserveIndexOnDynamicSort = SettingsManager.Settings.LibrarySort == SortAttribute.Playcount ||
SettingsManager.Settings.LibrarySort == SortAttribute.Stars;
_savedSelectionSnapshot = CaptureSelectionSnapshot(preserveIndexOnDynamicSort);
_hasSavedSelectionSnapshot = true;
}
else
{
_hasSavedSelectionSnapshot = false;
}
Navigator.Instance.PopScheme();
StopPreview();
_searchField.OnSearchQueryUpdated -= UpdateSearch;
PlayerContainer.PlayerAdded -= OnPlayerAdded;
PlayerContainer.PlayerRemoved -= OnPlayerRemoved;
}
private void OnDestroy()
{
DisposePreview();
_reloadState = MusicLibraryReloadState.Partial;
StemSettings.ApplySettings = true;
}
private void InitializeCollapsedHeaderSets()
{
foreach (SortAttribute attribute in Enum.GetValues(typeof(SortAttribute)))
{
if (!_collapsedHeaders.ContainsKey(attribute))
{
_collapsedHeaders.Add(attribute, new HashSet<SongCategory>(_comparer));
}
}
}
public void Back()
{
if (_searchField.IsSearching)
{
_searchField.ClearFilterQueries();
return;
}
switch(MenuState)
{
case MenuState.Playlist:
ExitPlaylistView();
break;
case MenuState.PlaylistSelect:
ExitPlaylistSelect();
break;
case MenuState.Show:
LeaveShowMode();
break;
case MenuState.Library:
ExitLibrary();
break;
}
}
private bool IsButtonHeldByPlayer(YargPlayer player, MenuAction button)
{
return _heldInputs.Any(i => i.Context.Player == player && i.Context.Action == button);
}
private const float GREEN_HOLD_SECONDS = 1f;
private void OnGreenTap(NavigationContext _)
{
ExecuteGreenTapAction();
}
public void ExecuteGreenTapAction()
{
if (CurrentSelection is not SongViewType)
{
CurrentSelection?.PrimaryButtonClick();
return;
}
bool setListNotEmpty = ShowPlaylist.Count > 0;
if (setListNotEmpty)
{
// same as Yellow: Add to Setlist
AddToPlaylist();
}
else
{
// same as old Green confirm: Play song
CurrentSelection?.PrimaryButtonClick();
}
}
private void OnGreenHold(NavigationContext _)
{
ExecuteGreenHoldAction();
}
public void ExecuteGreenHoldAction()
{
bool setListNotEmpty = ShowPlaylist.Count > 0;
if (setListNotEmpty)
{
// same as Yellow: Start Setlist
// Blue is now used for filters
StartSetlist();
}
else
{
// same as Yellow: Add to Setlist
AddToPlaylist();
}
}
public string GetGreenHoldActionLabel()
{
bool setListNotEmpty = ShowPlaylist.Count > 0;
return Localize.Key(setListNotEmpty ? "Menu.MusicLibrary.StartSet" : "Menu.MusicLibrary.AddToSet");
}
private void OnOrangeHit(NavigationContext ctx)
{
_heldInputs.Add(new HoldContext(ctx));
}
private void OnOrangeRelease(NavigationContext ctx)
{
var holdContext = _heldInputs.FirstOrDefault(i => i.Context.IsSameAs(ctx));
if (ctx.Action == MenuAction.Orange && (holdContext?.Timer > 0 || ctx.Player is null))
_popupMenu.gameObject.SetActive(true);
_heldInputs.RemoveAll(i => i.Context.IsSameAs(ctx));
}
private void GoToNextSection()
{
var i = _sectionHeaderIndices.BinarySearch(SelectedIndex);
i = i < 0 ? ~i : i + 1;
if (i >= _sectionHeaderIndices.Count)
return;
SelectedIndex = _sectionHeaderIndices[i];
}
private void GoToPreviousSection()
{
var i = _sectionHeaderIndices.BinarySearch(SelectedIndex);
i = i < 0 ? ~i - 1 : i - 1;
if (i < 0)
return;
SelectedIndex = _sectionHeaderIndices[i];
}
public void SelectRandomSong()
{
if (!ViewList.Any(i => i is SongViewType)) return;
do
{
SelectedIndex = Random.Range(0, ViewList.Count);
} while (CurrentSelection is not SongViewType);
}
public void ExpandAll()
{
var (headerIndex, offset) = GetClosestHeaderIndexAndOffset();
_collapsedHeaders[SettingsManager.Settings.LibrarySort].Clear();
RequestViewListUpdate();
SelectedIndex = _sectionHeaderIndices[headerIndex] + offset;
}
public void CollapseAll()
{
var (headerIndex, offset) = GetClosestHeaderIndexAndOffset();
foreach (var cat in _sortedSongs)
{
_collapsedHeaders[SettingsManager.Settings.LibrarySort].Add(cat);
}
RequestViewListUpdate();
var closestHeader = ViewList[_sectionHeaderIndices[headerIndex]];
if (closestHeader is SortHeaderViewType sortHeader && sortHeader.Collapsed)
{
offset = 0;
}
SelectedIndex = _sectionHeaderIndices[headerIndex] + offset;
}