SongBrowserUI.cs 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413
  1. using BeatSaberMarkupLanguage.Components;
  2. using HMUI;
  3. using SongBrowser.DataAccess;
  4. using SongBrowser.Internals;
  5. using SongCore.Utilities;
  6. using SongDataCore.BeatStar;
  7. using System;
  8. using System.Collections;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using UnityEngine;
  12. using UnityEngine.UI;
  13. using Logger = SongBrowser.Logging.Logger;
  14. namespace SongBrowser.UI
  15. {
  16. public enum UIState
  17. {
  18. Disabled,
  19. Main,
  20. SortBy,
  21. FilterBy
  22. }
  23. public class SongBrowserViewController : ViewController
  24. {
  25. // Named instance
  26. }
  27. /// <summary>
  28. /// Hijack the flow coordinator. Have access to all StandardLevel easily.
  29. /// </summary>
  30. public class SongBrowserUI : MonoBehaviour
  31. {
  32. // Logging
  33. public const String Name = "SongBrowserUI";
  34. private const float SEGMENT_PERCENT = 0.1f;
  35. private const int LIST_ITEMS_VISIBLE_AT_ONCE = 6;
  36. private const float CLEAR_BUTTON_Y = -32.5f;
  37. private const float BUTTON_ROW_Y = -32.5f;
  38. // BeatSaber Internal UI structures
  39. DataAccess.BeatSaberUIController _beatUi;
  40. // New UI Elements
  41. private SongBrowserViewController _viewController;
  42. private List<SongSortButton> _sortButtonGroup;
  43. private List<SongFilterButton> _filterButtonGroup;
  44. private Button _sortByButton;
  45. private Button _sortByDisplay;
  46. private Button _filterByButton;
  47. private Button _filterByDisplay;
  48. private Button _randomButton;
  49. private Button _clearSortFilterButton;
  50. private SimpleDialogPromptViewController _deleteDialog;
  51. private Button _deleteButton;
  52. private Button _pageUpFastButton;
  53. private Button _pageDownFastButton;
  54. private RectTransform _ppStatButton;
  55. private RectTransform _starStatButton;
  56. private RectTransform _njsStatButton;
  57. private RectTransform _noteJumpStartBeatOffsetLabel;
  58. private IAnnotatedBeatmapLevelCollection _lastLevelCollection;
  59. bool _selectingCategory = false;
  60. private SongBrowserModel _model;
  61. public SongBrowserModel Model
  62. {
  63. set
  64. {
  65. _model = value;
  66. }
  67. get
  68. {
  69. return _model;
  70. }
  71. }
  72. private bool _uiCreated = false;
  73. private UIState _currentUiState = UIState.Disabled;
  74. private bool _asyncUpdating = false;
  75. /// <summary>
  76. /// Builds the UI for this plugin.
  77. /// </summary>
  78. public void CreateUI(MainMenuViewController.MenuButton mode)
  79. {
  80. Logger.Trace("CreateUI()");
  81. // Determine the flow controller to use
  82. FlowCoordinator flowCoordinator;
  83. if (mode == MainMenuViewController.MenuButton.SoloFreePlay)
  84. {
  85. Logger.Debug("Entering SOLO mode...");
  86. flowCoordinator = Resources.FindObjectsOfTypeAll<SoloFreePlayFlowCoordinator>().Last();
  87. }
  88. else if (mode == MainMenuViewController.MenuButton.Party)
  89. {
  90. Logger.Debug("Entering PARTY mode...");
  91. flowCoordinator = Resources.FindObjectsOfTypeAll<PartyFreePlayFlowCoordinator>().Last();
  92. }
  93. else
  94. {
  95. Logger.Info("Entering Unsupported mode...");
  96. return;
  97. }
  98. Logger.Debug("Done fetching Flow Coordinator for the appropriate mode...");
  99. _beatUi = new DataAccess.BeatSaberUIController(flowCoordinator);
  100. _lastLevelCollection = null;
  101. // returning to the menu and switching modes could trigger this.
  102. if (_uiCreated)
  103. {
  104. return;
  105. }
  106. try
  107. {
  108. // Create a view controller to store all SongBrowser elements
  109. if (_viewController)
  110. {
  111. UnityEngine.GameObject.Destroy(_viewController);
  112. }
  113. _viewController = BeatSaberUI.CreateCurvedViewController<SongBrowserViewController>("SongBrowserViewController", 125.0f);
  114. _viewController.rectTransform.SetParent(_beatUi.LevelCollectionNavigationController.rectTransform, false);
  115. _viewController.rectTransform.anchorMin = new Vector2(0f, 0f);
  116. _viewController.rectTransform.anchorMax = new Vector2(1f, 1f);
  117. _viewController.rectTransform.anchoredPosition = new Vector2(0, 0);
  118. _viewController.rectTransform.sizeDelta = new Vector2(125, 25);
  119. _viewController.gameObject.SetActive(true);
  120. // delete dialog
  121. this._deleteDialog = UnityEngine.Object.Instantiate<SimpleDialogPromptViewController>(_beatUi.SimpleDialogPromptViewControllerPrefab);
  122. this._deleteDialog.name = "DeleteDialogPromptViewController";
  123. this._deleteDialog.gameObject.SetActive(false);
  124. // create song browser main ui
  125. CreateOuterUi();
  126. CreateSortButtons();
  127. CreateFilterButtons();
  128. CreateDeleteButton();
  129. CreateFastPageButtons();
  130. this.InstallHandlers();
  131. this.ModifySongStatsPanel();
  132. this.ResizeSongUI();
  133. _uiCreated = true;
  134. RefreshSortButtonUI();
  135. Logger.Debug("Done Creating UI...");
  136. }
  137. catch (Exception e)
  138. {
  139. Logger.Exception("Exception during CreateUI: ", e);
  140. }
  141. }
  142. /// <summary>
  143. /// Create the outer ui.
  144. /// </summary>
  145. private void CreateOuterUi()
  146. {
  147. Logger.Debug("Creating outer UI...");
  148. float clearButtonX = -72.5f;
  149. float clearButtonY = CLEAR_BUTTON_Y;
  150. float buttonY = BUTTON_ROW_Y;
  151. float buttonHeight = 5.0f;
  152. float sortByButtonX = -62.5f + buttonHeight;
  153. float outerButtonFontSize = 3.0f;
  154. float displayButtonFontSize = 2.5f;
  155. float outerButtonWidth = 24.0f;
  156. float randomButtonWidth = 10.0f;
  157. // clear button
  158. _clearSortFilterButton = _viewController.CreateIconButton(
  159. "ClearSortAndFilterButton",
  160. "PracticeButton",
  161. new Vector2(clearButtonX, clearButtonY),
  162. new Vector2(randomButtonWidth, randomButtonWidth),
  163. () =>
  164. {
  165. if (_currentUiState == UIState.FilterBy || _currentUiState == UIState.SortBy)
  166. {
  167. RefreshOuterUIState(UIState.Main);
  168. }
  169. else
  170. {
  171. OnClearButtonClickEvent();
  172. }
  173. },
  174. Base64Sprites.XIcon);
  175. _clearSortFilterButton.SetButtonBackgroundActive(false);
  176. // create SortBy button and its display
  177. float curX = sortByButtonX;
  178. Logger.Debug("Creating Sort By...");
  179. _sortByButton = _viewController.CreateUIButton("sortBy", "PracticeButton", new Vector2(curX, buttonY), new Vector2(outerButtonWidth, buttonHeight), () =>
  180. {
  181. RefreshOuterUIState(UIState.SortBy);
  182. }, "Sort By");
  183. _sortByButton.SetButtonTextSize(outerButtonFontSize);
  184. _sortByButton.ToggleWordWrapping(false);
  185. curX += outerButtonWidth;
  186. Logger.Debug("Creating Sort By Display...");
  187. _sortByDisplay = _viewController.CreateUIButton("sortByValue", "PracticeButton", new Vector2(curX, buttonY), new Vector2(outerButtonWidth, buttonHeight), () =>
  188. {
  189. OnSortButtonClickEvent(_model.Settings.sortMode);
  190. }, "");
  191. _sortByDisplay.SetButtonTextSize(displayButtonFontSize);
  192. _sortByDisplay.ToggleWordWrapping(false);
  193. curX += outerButtonWidth;
  194. // create FilterBy button and its display
  195. Logger.Debug("Creating Filter By...");
  196. _filterByButton = _viewController.CreateUIButton("filterBy", "PracticeButton", new Vector2(curX, buttonY), new Vector2(outerButtonWidth, buttonHeight), () =>
  197. {
  198. RefreshOuterUIState(UIState.FilterBy);
  199. }, "Filter By");
  200. _filterByButton.SetButtonTextSize(outerButtonFontSize);
  201. _filterByButton.ToggleWordWrapping(false);
  202. curX += outerButtonWidth;
  203. Logger.Debug("Creating Filter By Display...");
  204. _filterByDisplay = _viewController.CreateUIButton("filterValue", "PracticeButton", new Vector2(curX, buttonY), new Vector2(outerButtonWidth, buttonHeight), () =>
  205. {
  206. _model.Settings.filterMode = SongFilterMode.None;
  207. CancelFilter();
  208. ProcessSongList();
  209. RefreshSongUI();
  210. }, "");
  211. _filterByDisplay.SetButtonTextSize(displayButtonFontSize);
  212. _filterByDisplay.ToggleWordWrapping(false);
  213. // random button
  214. Logger.Debug("Creating Random Button...");
  215. _randomButton = _viewController.CreateIconButton("randomButton", "PracticeButton", new Vector2(curX + (outerButtonWidth / 2.0f) + (randomButtonWidth / 4.0f), clearButtonY), new Vector2(randomButtonWidth, randomButtonWidth), () =>
  216. {
  217. OnSortButtonClickEvent(SongSortMode.Random);
  218. }, Base64Sprites.RandomIcon);
  219. _randomButton.SetButtonBackgroundActive(false);
  220. }
  221. /// <summary>
  222. /// Create the sort button ribbon
  223. /// </summary>
  224. private void CreateSortButtons()
  225. {
  226. Logger.Debug("Create sort buttons...");
  227. float sortButtonFontSize = 2.0f;
  228. float sortButtonX = -63.0f;
  229. float sortButtonWidth = 12.0f;
  230. float buttonSpacing = 0.25f;
  231. float buttonY = BUTTON_ROW_Y;
  232. float buttonHeight = 5.0f;
  233. string[] sortButtonNames = new string[]
  234. {
  235. "Title", "Author", "Newest", "#Plays", "PP", "Stars", "UpVotes", "Rating", "Heat"
  236. };
  237. SongSortMode[] sortModes = new SongSortMode[]
  238. {
  239. SongSortMode.Default, SongSortMode.Author, SongSortMode.Newest, SongSortMode.YourPlayCount, SongSortMode.PP, SongSortMode.Stars, SongSortMode.UpVotes, SongSortMode.Rating, SongSortMode.Heat
  240. };
  241. _sortButtonGroup = new List<SongSortButton>();
  242. for (int i = 0; i < sortButtonNames.Length; i++)
  243. {
  244. float curButtonX = sortButtonX + (sortButtonWidth * i) + (buttonSpacing * i);
  245. SongSortButton sortButton = new SongSortButton();
  246. sortButton.SortMode = sortModes[i];
  247. sortButton.Button = _viewController.CreateUIButton(String.Format("Sort{0}Button", sortButton.SortMode), "PracticeButton",
  248. new Vector2(curButtonX, buttonY), new Vector2(sortButtonWidth, buttonHeight),
  249. () =>
  250. {
  251. OnSortButtonClickEvent(sortButton.SortMode);
  252. RefreshOuterUIState(UIState.Main);
  253. },
  254. sortButtonNames[i]);
  255. sortButton.Button.SetButtonTextSize(sortButtonFontSize);
  256. sortButton.Button.ToggleWordWrapping(false);
  257. _sortButtonGroup.Add(sortButton);
  258. }
  259. }
  260. /// <summary>
  261. /// Create the filter by buttons
  262. /// </summary>
  263. private void CreateFilterButtons()
  264. {
  265. Logger.Debug("Creating filter buttons...");
  266. float filterButtonFontSize = 2.25f;
  267. float filterButtonX = -63.0f;
  268. float filterButtonWidth = 14.25f;
  269. float buttonSpacing = 0.5f;
  270. float buttonY = BUTTON_ROW_Y;
  271. float buttonHeight = 5.0f;
  272. string[] filterButtonNames = new string[]
  273. {
  274. "Search", "Ranked", "Unranked"
  275. };
  276. SongFilterMode[] filterModes = new SongFilterMode[]
  277. {
  278. SongFilterMode.Search, SongFilterMode.Ranked, SongFilterMode.Unranked
  279. };
  280. _filterButtonGroup = new List<SongFilterButton>();
  281. for (int i = 0; i < filterButtonNames.Length; i++)
  282. {
  283. float curButtonX = filterButtonX + (filterButtonWidth * i) + (buttonSpacing * i);
  284. SongFilterButton filterButton = new SongFilterButton();
  285. filterButton.FilterMode = filterModes[i];
  286. filterButton.Button = _viewController.CreateUIButton(String.Format("Filter{0}Button", filterButton.FilterMode), "PracticeButton",
  287. new Vector2(curButtonX, buttonY), new Vector2(filterButtonWidth, buttonHeight),
  288. () =>
  289. {
  290. OnFilterButtonClickEvent(filterButton.FilterMode);
  291. RefreshOuterUIState(UIState.Main);
  292. },
  293. filterButtonNames[i]);
  294. filterButton.Button.SetButtonTextSize(filterButtonFontSize);
  295. filterButton.Button.ToggleWordWrapping(false);
  296. _filterButtonGroup.Add(filterButton);
  297. }
  298. }
  299. /// <summary>
  300. /// Create the fast page up and down buttons
  301. /// </summary>
  302. private void CreateFastPageButtons()
  303. {
  304. Logger.Debug("Creating fast scroll button...");
  305. _pageUpFastButton = BeatSaberUI.CreateIconButton("PageUpFast",
  306. _beatUi.LevelCollectionNavigationController.transform as RectTransform, "PracticeButton",
  307. new Vector2(1f, 24f),
  308. new Vector2(10f, 10f),
  309. delegate ()
  310. {
  311. this.JumpSongList(-1, SEGMENT_PERCENT);
  312. }, Base64Sprites.DoubleArrow);
  313. _pageUpFastButton.SetButtonBackgroundActive(false);
  314. (_pageUpFastButton.transform as RectTransform).Rotate(new Vector3(0, 0, 180));
  315. _pageDownFastButton = BeatSaberUI.CreateIconButton("PageDownFast",
  316. _beatUi.LevelCollectionNavigationController.transform as RectTransform, "PracticeButton",
  317. new Vector2(1f, -24f),
  318. new Vector2(10f, 10f),
  319. delegate ()
  320. {
  321. this.JumpSongList(1, SEGMENT_PERCENT);
  322. }, Base64Sprites.DoubleArrow);
  323. _pageDownFastButton.SetButtonBackgroundActive(false);
  324. }
  325. /// <summary>
  326. /// Create the delete button in the play button container
  327. /// </summary>
  328. private void CreateDeleteButton()
  329. {
  330. // Create delete button
  331. /*Logger.Debug("Creating delete button...");
  332. _deleteButton = BeatSaberUI.CreateIconButton(_beatUi.PlayButtons, _beatUi.PracticeButton, Base64Sprites.DeleteIcon);
  333. _deleteButton.onClick.AddListener(delegate () {
  334. HandleDeleteSelectedLevel();
  335. });
  336. BeatSaberUI.DestroyHoverHint(_deleteButton.transform as RectTransform);*/
  337. }
  338. /// <summary>
  339. /// Resize the stats panel to fit more stats.
  340. /// </summary>
  341. private void ModifySongStatsPanel()
  342. {
  343. // modify stat panel, inject extra row of stats
  344. Logger.Debug("Resizing Stats Panel...");
  345. var statsPanel = _beatUi.StandardLevelDetailView.GetPrivateField<LevelParamsPanel>("_levelParamsPanel");
  346. (statsPanel.transform as RectTransform).Translate(0, 0.05f, 0);
  347. _ppStatButton = BeatSaberUI.CreateStatIcon("PPStatLabel",
  348. statsPanel.GetComponentsInChildren<RectTransform>().First(x => x.name == "NPS"),
  349. statsPanel.transform,
  350. Base64Sprites.GraphIcon,
  351. "PP Value");
  352. _starStatButton = BeatSaberUI.CreateStatIcon("StarStatLabel",
  353. statsPanel.GetComponentsInChildren<RectTransform>().First(x => x.name == "NotesCount"),
  354. statsPanel.transform,
  355. Base64Sprites.StarFullIcon,
  356. "Star Difficulty Rating");
  357. _njsStatButton = BeatSaberUI.CreateStatIcon("NoteJumpSpeedLabel",
  358. statsPanel.GetComponentsInChildren<RectTransform>().First(x => x.name == "ObstaclesCount"),
  359. statsPanel.transform,
  360. Base64Sprites.SpeedIcon,
  361. "Note Jump Speed");
  362. _noteJumpStartBeatOffsetLabel = BeatSaberUI.CreateStatIcon("NoteJumpStartBeatOffsetLabel",
  363. statsPanel.GetComponentsInChildren<RectTransform>().First(x => x.name == "BombsCount"),
  364. statsPanel.transform,
  365. Base64Sprites.NoteStartOffsetIcon,
  366. "Note Jump Start Beat Offset");
  367. }
  368. /// <summary>
  369. /// Resize some of the song table elements.
  370. /// </summary>
  371. public void ResizeSongUI()
  372. {
  373. // shrink play button container
  374. //RectTransform playButtonsRect = Resources.FindObjectsOfTypeAll<RectTransform>().First(x => x.name == "ActionButtons");
  375. //playButtonsRect.localScale = new Vector3(0.825f, 0.825f, 0.825f);
  376. }
  377. /// <summary>
  378. /// Add our handlers into BeatSaber.
  379. /// </summary>
  380. private void InstallHandlers()
  381. {
  382. // level collection, level, difficulty handlers, characteristics
  383. TableView tableView = ReflectionUtil.GetPrivateField<TableView>(_beatUi.LevelCollectionTableView, "_tableView");
  384. // update stats
  385. _beatUi.LevelCollectionViewController.didSelectLevelEvent -= OnDidSelectLevelEvent;
  386. _beatUi.LevelCollectionViewController.didSelectLevelEvent += OnDidSelectLevelEvent;
  387. _beatUi.LevelDetailViewController.didChangeContentEvent -= OnDidPresentContentEvent;
  388. _beatUi.LevelDetailViewController.didChangeContentEvent += OnDidPresentContentEvent;
  389. _beatUi.LevelDetailViewController.didChangeDifficultyBeatmapEvent -= OnDidChangeDifficultyEvent;
  390. _beatUi.LevelDetailViewController.didChangeDifficultyBeatmapEvent += OnDidChangeDifficultyEvent;
  391. // update our view of the game state
  392. _beatUi.LevelFilteringNavigationController.didSelectAnnotatedBeatmapLevelCollectionEvent -= _levelFilteringNavController_didSelectAnnotatedBeatmapLevelCollectionEvent;
  393. _beatUi.LevelFilteringNavigationController.didSelectAnnotatedBeatmapLevelCollectionEvent += _levelFilteringNavController_didSelectAnnotatedBeatmapLevelCollectionEvent;
  394. _beatUi.AnnotatedBeatmapLevelCollectionsViewController.didSelectAnnotatedBeatmapLevelCollectionEvent -= handleDidSelectAnnotatedBeatmapLevelCollection;
  395. _beatUi.AnnotatedBeatmapLevelCollectionsViewController.didSelectAnnotatedBeatmapLevelCollectionEvent += handleDidSelectAnnotatedBeatmapLevelCollection;
  396. // Respond to characteristics changes
  397. _beatUi.BeatmapCharacteristicSelectionViewController.didSelectBeatmapCharacteristicEvent -= OnDidSelectBeatmapCharacteristic;
  398. _beatUi.BeatmapCharacteristicSelectionViewController.didSelectBeatmapCharacteristicEvent += OnDidSelectBeatmapCharacteristic;
  399. // make sure the quick scroll buttons don't desync with regular scrolling
  400. _beatUi.TableViewPageDownButton.onClick.AddListener(delegate ()
  401. {
  402. StartCoroutine(RefreshQuickScrollButtonsAsync());
  403. });
  404. _beatUi.TableViewPageUpButton.onClick.AddListener(delegate ()
  405. {
  406. StartCoroutine(RefreshQuickScrollButtonsAsync());
  407. });
  408. }
  409. /// <summary>
  410. /// Waits for the song UI to be available before trying to update.
  411. /// </summary>
  412. /// <returns></returns>
  413. public IEnumerator AsyncWaitForSongUIUpdate()
  414. {
  415. if (_asyncUpdating)
  416. {
  417. yield break;
  418. }
  419. if (!_uiCreated)
  420. {
  421. yield break;
  422. }
  423. if (!_model.SortWasMissingData)
  424. {
  425. yield break;
  426. }
  427. _asyncUpdating = true;
  428. while (_beatUi != null && (_beatUi.LevelSelectionNavigationController.GetPrivateField<bool>("_isInTransition") ||
  429. _beatUi.LevelDetailViewController.GetPrivateField<bool>("_isInTransition") ||
  430. !_beatUi.LevelSelectionNavigationController.isInViewControllerHierarchy ||
  431. !_beatUi.LevelDetailViewController.isInViewControllerHierarchy ||
  432. !_beatUi.LevelSelectionNavigationController.isActiveAndEnabled ||
  433. !_beatUi.LevelDetailViewController.isActiveAndEnabled))
  434. {
  435. yield return null;
  436. }
  437. //yield return new WaitForEndOfFrame();
  438. if (_model.Settings.sortMode.NeedsScoreSaberData() && SongDataCore.Plugin.Songs.IsDataAvailable())
  439. {
  440. ProcessSongList();
  441. RefreshSongUI();
  442. }
  443. _asyncUpdating = false;
  444. }
  445. /// <summary>
  446. /// Helper to reduce code duplication...
  447. /// </summary>
  448. public void RefreshSongUI(bool scrollToLevel = true)
  449. {
  450. if (!_uiCreated)
  451. {
  452. return;
  453. }
  454. RefreshSongList();
  455. RefreshSortButtonUI();
  456. if (!scrollToLevel)
  457. {
  458. _beatUi.ScrollToLevelByRow(0);
  459. }
  460. RefreshQuickScrollButtons();
  461. RefreshCurrentSelectionDisplay();
  462. }
  463. /// <summary>
  464. /// External helper.
  465. /// </summary>
  466. public void ProcessSongList()
  467. {
  468. if (!_uiCreated)
  469. {
  470. return;
  471. }
  472. this._model.ProcessSongList(_lastLevelCollection, _beatUi.LevelSelectionNavigationController);
  473. }
  474. /// <summary>
  475. /// Helper for common filter cancellation logic.
  476. /// </summary>
  477. public void CancelFilter()
  478. {
  479. Logger.Debug($"Cancelling filter, levelCollection {_lastLevelCollection}");
  480. _model.Settings.filterMode = SongFilterMode.None;
  481. GameObject _noDataGO = _beatUi.LevelCollectionViewController.GetPrivateField<GameObject>("_noDataInfoGO");
  482. string _headerText = _beatUi.LevelCollectionTableView.GetPrivateField<string>("_headerText");
  483. Sprite _headerSprite = _beatUi.LevelCollectionTableView.GetPrivateField<Sprite>("_headerSprite");
  484. IBeatmapLevelCollection levelCollection = _beatUi.GetCurrentSelectedAnnotatedBeatmapLevelCollection().beatmapLevelCollection;
  485. _beatUi.LevelCollectionViewController.SetData(levelCollection, _headerText, _headerSprite, false, _noDataGO);
  486. }
  487. /// <summary>
  488. /// Playlists (fancy name for AnnotatedBeatmapLevelCollection)
  489. /// </summary>
  490. /// <param name="annotatedBeatmapLevelCollection"></param>
  491. public virtual void handleDidSelectAnnotatedBeatmapLevelCollection(IAnnotatedBeatmapLevelCollection annotatedBeatmapLevelCollection)
  492. {
  493. Logger.Trace("handleDidSelectAnnotatedBeatmapLevelCollection()");
  494. _lastLevelCollection = annotatedBeatmapLevelCollection;
  495. Model.Settings.currentLevelCategoryName = _beatUi.LevelFilteringNavigationController.selectedLevelCategory.ToString();
  496. Model.Settings.Save();
  497. Logger.Debug("AnnotatedBeatmapLevelCollection, Selected Level Collection={0}", _lastLevelCollection);
  498. }
  499. /// <summary>
  500. /// Handler for level collection selection, controller.
  501. /// Sets the current level collection into the model and updates.
  502. /// </summary>
  503. /// <param name="arg1"></param>
  504. /// <param name="arg2"></param>
  505. /// <param name="arg3"></param>
  506. /// <param name="arg4"></param>
  507. private void _levelFilteringNavController_didSelectAnnotatedBeatmapLevelCollectionEvent(LevelFilteringNavigationController arg1, IAnnotatedBeatmapLevelCollection arg2,
  508. GameObject arg3, BeatmapCharacteristicSO arg4)
  509. {
  510. Logger.Trace("_levelFilteringNavController_didSelectAnnotatedBeatmapLevelCollectionEvent(levelCollection={0})", arg2);
  511. if (arg2 == null)
  512. {
  513. // Probably means we transitioned between Music Packs and Playlists
  514. arg2 = _beatUi.GetCurrentSelectedAnnotatedBeatmapLevelCollection();
  515. if (arg2 == null)
  516. {
  517. Logger.Warning("Nothing selected. This is likely an error.");
  518. return;
  519. }
  520. }
  521. Logger.Debug("Selected Level Collection={0}", arg2);
  522. // Do something about preview level packs, they can't be used past this point
  523. if (arg2 as PreviewBeatmapLevelPackSO)
  524. {
  525. Logger.Info("Hiding SongBrowser, previewing a song pack.");
  526. Hide();
  527. return;
  528. }
  529. Show();
  530. // category transition, just record the new collection
  531. if (_selectingCategory)
  532. {
  533. Logger.Info("Transitioning level category");
  534. _lastLevelCollection = arg2;
  535. StartCoroutine(RefreshSongListEndOfFrame());
  536. return;
  537. }
  538. // Skip the first time - prevents a bunch of reload content spam
  539. if (_lastLevelCollection == null)
  540. {
  541. return;
  542. }
  543. SelectLevelCollection(arg2);
  544. }
  545. /// <summary>
  546. /// Logic for selecting a level collection.
  547. /// </summary>
  548. /// <param name="levelPack"></param>
  549. public void SelectLevelCollection(IAnnotatedBeatmapLevelCollection levelCollection)
  550. {
  551. try
  552. {
  553. if (levelCollection == null)
  554. {
  555. Logger.Debug("No level collection selected...");
  556. return;
  557. }
  558. // store the real level collection
  559. if (levelCollection.collectionName != SongBrowserModel.FilteredSongsCollectionName && _lastLevelCollection != null)
  560. {
  561. Logger.Debug("Recording levelCollection: {0}", levelCollection.collectionName);
  562. _lastLevelCollection = levelCollection;
  563. Model.Settings.currentLevelCategoryName = _beatUi.LevelFilteringNavigationController.selectedLevelCategory.ToString();
  564. }
  565. // reset level selection
  566. _model.LastSelectedLevelId = null;
  567. // save level collection
  568. this._model.Settings.currentLevelCollectionName = levelCollection.collectionName;
  569. this._model.Settings.Save();
  570. StartCoroutine(ProcessSongListEndOfFrame());
  571. }
  572. catch (Exception e)
  573. {
  574. Logger.Exception("Exception handling SelectLevelCollection...", e);
  575. }
  576. }
  577. /// <summary>
  578. /// End of frame update the song list, the game seems to stomp on us sometimes otherwise
  579. /// TODO - Might not be nice to other plugins
  580. /// </summary>
  581. /// <returns></returns>
  582. public IEnumerator ProcessSongListEndOfFrame()
  583. {
  584. yield return new WaitForEndOfFrame();
  585. ProcessSongList();
  586. RefreshSongUI();
  587. }
  588. public IEnumerator RefreshSongListEndOfFrame()
  589. {
  590. yield return new WaitForEndOfFrame();
  591. RefreshSongUI();
  592. }
  593. /// <summary>
  594. /// Remove all filters, update song list, save.
  595. /// </summary>
  596. private void OnClearButtonClickEvent()
  597. {
  598. Logger.Debug("Clearing all sorts and filters.");
  599. _model.Settings.sortMode = SongSortMode.Original;
  600. _model.Settings.invertSortResults = false;
  601. _model.Settings.filterMode = SongFilterMode.None;
  602. _model.Settings.Save();
  603. CancelFilter();
  604. ProcessSongList();
  605. RefreshSongUI();
  606. }
  607. /// <summary>
  608. /// Sort button clicked.
  609. /// </summary>
  610. private void OnSortButtonClickEvent(SongSortMode sortMode)
  611. {
  612. Logger.Debug("Sort button - {0} - pressed.", sortMode.ToString());
  613. if ((sortMode.NeedsScoreSaberData() && !SongDataCore.Plugin.Songs.IsDataAvailable()))
  614. {
  615. Logger.Info("Data for sort type is not available.");
  616. return;
  617. }
  618. // Clear current selected level id so our song list jumps to the start
  619. _model.LastSelectedLevelId = null;
  620. if (_model.Settings.sortMode == sortMode)
  621. {
  622. _model.ToggleInverting();
  623. }
  624. _model.Settings.sortMode = sortMode;
  625. // update the seed
  626. if (_model.Settings.sortMode == SongSortMode.Random)
  627. {
  628. _model.Settings.randomSongSeed = Guid.NewGuid().GetHashCode();
  629. }
  630. _model.Settings.Save();
  631. ProcessSongList();
  632. RefreshSongUI();
  633. }
  634. /// <summary>
  635. /// Handle filter button logic. Some filters have sub menus that need special logic.
  636. /// </summary>
  637. /// <param name="mode"></param>
  638. private void OnFilterButtonClickEvent(SongFilterMode mode)
  639. {
  640. Logger.Debug($"FilterButton {mode} clicked.");
  641. var curCollection = _beatUi.GetCurrentSelectedAnnotatedBeatmapLevelCollection();
  642. if (_lastLevelCollection == null ||
  643. (curCollection != null &&
  644. curCollection.collectionName != SongBrowserModel.FilteredSongsCollectionName &&
  645. curCollection.collectionName != SongBrowserModel.PlaylistSongsCollectionName))
  646. {
  647. _lastLevelCollection = _beatUi.GetCurrentSelectedAnnotatedBeatmapLevelCollection();
  648. }
  649. if (mode == SongFilterMode.Favorites)
  650. {
  651. _beatUi.SelectLevelCategory(SelectLevelCategoryViewController.LevelCategory.Favorites.ToString());
  652. }
  653. else
  654. {
  655. GameObject _noDataGO = _beatUi.LevelCollectionViewController.GetPrivateField<GameObject>("_noDataInfoGO");
  656. string _headerText = _beatUi.LevelCollectionTableView.GetPrivateField<string>("_headerText");
  657. Sprite _headerSprite = _beatUi.LevelCollectionTableView.GetPrivateField<Sprite>("_headerSprite");
  658. IBeatmapLevelCollection levelCollection = _beatUi.GetCurrentSelectedAnnotatedBeatmapLevelCollection().beatmapLevelCollection;
  659. _beatUi.LevelCollectionViewController.SetData(levelCollection, _headerText, _headerSprite, false, _noDataGO);
  660. }
  661. // If selecting the same filter, cancel
  662. if (_model.Settings.filterMode == mode)
  663. {
  664. _model.Settings.filterMode = SongFilterMode.None;
  665. }
  666. else
  667. {
  668. _model.Settings.filterMode = mode;
  669. }
  670. switch (mode)
  671. {
  672. case SongFilterMode.Search:
  673. OnSearchButtonClickEvent();
  674. break;
  675. default:
  676. _model.Settings.Save();
  677. ProcessSongList();
  678. RefreshSongUI();
  679. break;
  680. }
  681. }
  682. /// <summary>
  683. /// Display the keyboard.
  684. /// </summary>
  685. /// <param name="sortMode"></param>
  686. private void OnSearchButtonClickEvent()
  687. {
  688. Logger.Debug("Filter button - {0} - pressed.", SongFilterMode.Search.ToString());
  689. this.ShowSearchKeyboard();
  690. }
  691. /// <summary>
  692. /// Adjust UI based on level selected.
  693. /// Various ways of detecting if a level is not properly selected. Seems most hit the first one.
  694. /// </summary>
  695. private void OnDidSelectLevelEvent(LevelCollectionViewController view, IPreviewBeatmapLevel level)
  696. {
  697. try
  698. {
  699. Logger.Trace("OnDidSelectLevelEvent()");
  700. if (level == null)
  701. {
  702. Logger.Debug("No level selected?");
  703. return;
  704. }
  705. if (_model.Settings == null)
  706. {
  707. Logger.Debug("Settings not instantiated yet?");
  708. return;
  709. }
  710. _model.LastSelectedLevelId = level.levelID;
  711. HandleDidSelectLevelRow(level);
  712. }
  713. catch (Exception e)
  714. {
  715. Logger.Exception("Exception selecting song:", e);
  716. }
  717. }
  718. /// <summary>
  719. /// Switching one-saber modes for example.
  720. /// </summary>
  721. /// <param name="view"></param>
  722. /// <param name="bc"></param>
  723. private void OnDidSelectBeatmapCharacteristic(BeatmapCharacteristicSegmentedControlController view, BeatmapCharacteristicSO bc)
  724. {
  725. try
  726. {
  727. Logger.Trace("OnDidSelectBeatmapCharacteristic({0})", bc.compoundIdPartName);
  728. _model.CurrentBeatmapCharacteristicSO = bc;
  729. if (_beatUi.StandardLevelDetailView != null)
  730. {
  731. RefreshScoreSaberData(_beatUi.StandardLevelDetailView.selectedDifficultyBeatmap.level);
  732. RefreshNoteJumpSpeed(_beatUi.StandardLevelDetailView.selectedDifficultyBeatmap.noteJumpMovementSpeed,
  733. _beatUi.StandardLevelDetailView.selectedDifficultyBeatmap.noteJumpStartBeatOffset);
  734. }
  735. }
  736. catch (Exception e)
  737. {
  738. Logger.Exception(e);
  739. }
  740. }
  741. /// <summary>
  742. /// Handle difficulty level selection.
  743. /// </summary>
  744. private void OnDidChangeDifficultyEvent(StandardLevelDetailViewController view, IDifficultyBeatmap beatmap)
  745. {
  746. Logger.Trace("OnDidChangeDifficultyEvent({0})", beatmap);
  747. if (view.selectedDifficultyBeatmap == null)
  748. {
  749. return;
  750. }
  751. if (_deleteButton != null)
  752. {
  753. _deleteButton.interactable = (view.selectedDifficultyBeatmap.level.levelID.Length >= 32);
  754. }
  755. RefreshScoreSaberData(view.selectedDifficultyBeatmap.level);
  756. RefreshNoteJumpSpeed(beatmap.noteJumpMovementSpeed, beatmap.noteJumpStartBeatOffset);
  757. }
  758. /// <summary>
  759. /// BeatSaber finished loading content. This is when the difficulty is finally updated.
  760. /// </summary>
  761. /// <param name="view"></param>
  762. /// <param name="type"></param>
  763. private void OnDidPresentContentEvent(StandardLevelDetailViewController view, StandardLevelDetailViewController.ContentType type)
  764. {
  765. Logger.Trace("OnDidPresentContentEvent()");
  766. // v1.12.2 - TODO - is this safe to prevent us from trying to lookup empty/dead content?
  767. if (type != StandardLevelDetailViewController.ContentType.OwnedAndReady)
  768. {
  769. return;
  770. }
  771. if (view.selectedDifficultyBeatmap == null)
  772. {
  773. return;
  774. }
  775. if (_deleteButton != null)
  776. {
  777. _deleteButton.interactable = (_beatUi.LevelDetailViewController.selectedDifficultyBeatmap.level.levelID.Length >= 32);
  778. }
  779. RefreshScoreSaberData(view.selectedDifficultyBeatmap.level);
  780. RefreshNoteJumpSpeed(view.selectedDifficultyBeatmap.noteJumpMovementSpeed, view.selectedDifficultyBeatmap.noteJumpStartBeatOffset);
  781. }
  782. /// <summary>
  783. /// Refresh stats panel.
  784. /// </summary>
  785. /// <param name="level"></param>
  786. private void HandleDidSelectLevelRow(IPreviewBeatmapLevel level)
  787. {
  788. Logger.Trace("HandleDidSelectLevelRow({0})", level);
  789. if (_deleteButton != null)
  790. {
  791. _deleteButton.interactable = (level.levelID.Length >= 32);
  792. }
  793. RefreshQuickScrollButtons();
  794. }
  795. /// <summary>
  796. /// Pop up a delete dialog.
  797. /// </summary>
  798. private void HandleDeleteSelectedLevel()
  799. {
  800. IBeatmapLevel level = _beatUi.LevelDetailViewController.selectedDifficultyBeatmap.level;
  801. _deleteDialog.Init("Delete song", $"Do you really want to delete \"{ level.songName} {level.songSubName}\"?", "Delete", "Cancel",
  802. (selectedButton) =>
  803. {
  804. _beatUi.LevelSelectionFlowCoordinator.InvokePrivateMethod("DismissViewController", new object[] { _deleteDialog, null, false });
  805. if (selectedButton == 0)
  806. {
  807. try
  808. {
  809. // determine the index we are deleting so we can keep the cursor near the same spot after
  810. // the header counts as an index, so if the index came from the level array we have to add 1.
  811. var levelsTableView = _beatUi.LevelCollectionTableView;
  812. List<IPreviewBeatmapLevel> levels = _beatUi.GetCurrentLevelCollectionLevels().ToList();
  813. int selectedIndex = levels.FindIndex(x => x.levelID == _beatUi.StandardLevelDetailView.selectedDifficultyBeatmap.level.levelID);
  814. if (selectedIndex > -1)
  815. {
  816. var song = SongCore.Loader.CustomLevels.First(x => x.Value.levelID == _beatUi.LevelDetailViewController.selectedDifficultyBeatmap.level.levelID).Value;
  817. Logger.Info($"Deleting song: {song.customLevelPath}");
  818. SongCore.Loader.Instance.DeleteSong(song.customLevelPath);
  819. this._model.RemoveSongFromLevelCollection(_beatUi.GetCurrentSelectedAnnotatedBeatmapLevelCollection(), _beatUi.LevelDetailViewController.selectedDifficultyBeatmap.level.levelID);
  820. int removedLevels = levels.RemoveAll(x => x.levelID == _beatUi.StandardLevelDetailView.selectedDifficultyBeatmap.level.levelID);
  821. Logger.Info("Removed " + removedLevels + " level(s) from song list!");
  822. this.UpdateLevelDataModel();
  823. // if we have a song to select at the same index, set the last selected level id, UI updates takes care of the rest.
  824. if (selectedIndex < levels.Count)
  825. {
  826. if (levels[selectedIndex].levelID != null)
  827. {
  828. _model.LastSelectedLevelId = levels[selectedIndex].levelID;
  829. }
  830. }
  831. this.RefreshSongList();
  832. }
  833. }
  834. catch (Exception e)
  835. {
  836. Logger.Error("Unable to delete song! Exception: " + e);
  837. }
  838. }
  839. });
  840. _beatUi.LevelSelectionFlowCoordinator.InvokePrivateMethod("PresentViewController", new object[] { _deleteDialog, null, false });
  841. }
  842. /// <summary>
  843. /// Display the search keyboard
  844. /// </summary>
  845. void ShowSearchKeyboard()
  846. {
  847. var modalKbTag = new BeatSaberMarkupLanguage.Tags.ModalKeyboardTag();
  848. var modalKbView = modalKbTag.CreateObject(_beatUi.LevelSelectionNavigationController.rectTransform);
  849. modalKbView.gameObject.SetActive(true);
  850. var modalKb = modalKbView.GetComponent<ModalKeyboard>();
  851. modalKb.gameObject.SetActive(true);
  852. modalKb.keyboard.EnterPressed += SearchViewControllerSearchButtonPressed;
  853. modalKb.modalView.Show(true, true);
  854. }
  855. /// <summary>
  856. /// Handle search.
  857. /// </summary>
  858. /// <param name="searchFor"></param>
  859. private void SearchViewControllerSearchButtonPressed(string searchFor)
  860. {
  861. Logger.Debug("Searching for \"{0}\"...", searchFor);
  862. _model.Settings.filterMode = SongFilterMode.Search;
  863. _model.Settings.searchTerms.Insert(0, searchFor);
  864. _model.Settings.Save();
  865. _model.LastSelectedLevelId = null;
  866. ProcessSongList();
  867. RefreshSongUI();
  868. }
  869. /// <summary>
  870. /// Make big jumps in the song list.
  871. /// </summary>
  872. /// <param name="numJumps"></param>
  873. private void JumpSongList(int numJumps, float segmentPercent)
  874. {
  875. var levels = _beatUi.GetCurrentLevelCollectionLevels();
  876. if (levels == null)
  877. {
  878. return;
  879. }
  880. int totalSize = levels.Count();
  881. int segmentSize = (int)(totalSize * segmentPercent);
  882. // Jump at least one scree size.
  883. if (segmentSize < LIST_ITEMS_VISIBLE_AT_ONCE)
  884. {
  885. segmentSize = LIST_ITEMS_VISIBLE_AT_ONCE;
  886. }
  887. int currentRow = _beatUi.LevelCollectionTableView.GetPrivateField<int>("_selectedRow");
  888. int jumpDirection = Math.Sign(numJumps);
  889. int newRow = currentRow + (jumpDirection * segmentSize);
  890. if (newRow <= 0)
  891. {
  892. newRow = 0;
  893. }
  894. else if (newRow >= totalSize)
  895. {
  896. newRow = totalSize - 1;
  897. }
  898. Logger.Debug("jumpDirection: {0}, newRow: {1}", jumpDirection, newRow);
  899. _beatUi.ScrollToLevelByRow(newRow);
  900. RefreshQuickScrollButtons();
  901. }
  902. /// <summary>
  903. /// Update GUI elements that show score saber data.
  904. /// </summary>
  905. public void RefreshScoreSaberData(IPreviewBeatmapLevel level)
  906. {
  907. Logger.Trace("RefreshScoreSaberData({0})", level.levelID);
  908. if (!SongDataCore.Plugin.Songs.IsDataAvailable())
  909. {
  910. return;
  911. }
  912. BeatmapDifficulty difficulty = _beatUi.LevelDifficultyViewController.selectedDifficulty;
  913. string difficultyString = difficulty.ToString();
  914. if (difficultyString.Equals("ExpertPlus"))
  915. {
  916. difficultyString = "Expert+";
  917. }
  918. Logger.Debug(difficultyString);
  919. // Check if we have data for this song
  920. Logger.Debug("Checking if have info for song {0}", level.songName);
  921. var hash = SongBrowserModel.GetSongHash(level.levelID);
  922. if (SongDataCore.Plugin.Songs.Data.Songs.ContainsKey(hash))
  923. {
  924. Logger.Debug("Checking if have difficulty for song {0} difficulty {1}", level.songName, difficultyString);
  925. BeatStarSong scoreSaberSong = SongDataCore.Plugin.Songs.Data.Songs[hash];
  926. BeatStarSongDifficultyStats scoreSaberSongDifficulty = scoreSaberSong.diffs.FirstOrDefault(x => String.Equals(x.diff, difficultyString));
  927. if (scoreSaberSongDifficulty != null)
  928. {
  929. Logger.Debug("Display pp for song.");
  930. double pp = scoreSaberSongDifficulty.pp;
  931. double star = scoreSaberSongDifficulty.star;
  932. BeatSaberUI.SetStatButtonText(_ppStatButton, String.Format("{0:0.#}", pp));
  933. BeatSaberUI.SetStatButtonText(_starStatButton, String.Format("{0:0.#}", star));
  934. }
  935. else
  936. {
  937. BeatSaberUI.SetStatButtonText(_ppStatButton, "NA");
  938. BeatSaberUI.SetStatButtonText(_starStatButton, "NA");
  939. }
  940. }
  941. else
  942. {
  943. BeatSaberUI.SetStatButtonText(_ppStatButton, "NA");
  944. BeatSaberUI.SetStatButtonText(_starStatButton, "NA");
  945. }
  946. Logger.Debug("Done refreshing score saber stats.");
  947. }
  948. /// <summary>
  949. /// Helper to refresh the NJS widget.
  950. /// </summary>
  951. /// <param name="noteJumpMovementSpeed"></param>
  952. private void RefreshNoteJumpSpeed(float noteJumpMovementSpeed, float noteJumpStartBeatOffset)
  953. {
  954. BeatSaberUI.SetStatButtonText(_njsStatButton, String.Format("{0}", noteJumpMovementSpeed));
  955. BeatSaberUI.SetStatButtonText(_noteJumpStartBeatOffsetLabel, String.Format("{0}", noteJumpStartBeatOffset));
  956. }
  957. /// <summary>
  958. /// Update interactive state of the quick scroll buttons.
  959. /// </summary>
  960. private void RefreshQuickScrollButtons()
  961. {
  962. if (!_uiCreated)
  963. {
  964. return;
  965. }
  966. _pageUpFastButton.interactable = _beatUi.TableViewPageUpButton.interactable;
  967. _pageUpFastButton.gameObject.SetActive(_beatUi.TableViewPageUpButton.IsActive());
  968. _pageDownFastButton.interactable = _beatUi.TableViewPageDownButton.interactable;
  969. _pageDownFastButton.gameObject.SetActive(_beatUi.TableViewPageDownButton.IsActive());
  970. }
  971. /// <summary>
  972. /// TODO - evaluate this sillyness...
  973. /// </summary>
  974. /// <returns></returns>
  975. public IEnumerator RefreshQuickScrollButtonsAsync()
  976. {
  977. yield return new WaitForEndOfFrame();
  978. RefreshQuickScrollButtons();
  979. }
  980. /// <summary>
  981. /// Show the UI.
  982. /// </summary>
  983. public void Show()
  984. {
  985. Logger.Trace("Show SongBrowserUI()");
  986. this.SetVisibility(true);
  987. }
  988. /// <summary>
  989. /// Hide the UI.
  990. /// </summary>
  991. public void Hide()
  992. {
  993. Logger.Trace("Hide SongBrowserUI()");
  994. this.SetVisibility(false);
  995. }
  996. /// <summary>
  997. /// Handle showing or hiding UI logic.
  998. /// </summary>
  999. /// <param name="visible"></param>
  1000. private void SetVisibility(bool visible)
  1001. {
  1002. // UI not created, nothing visible to hide...
  1003. if (!_uiCreated)
  1004. {
  1005. return;
  1006. }
  1007. _ppStatButton?.gameObject.SetActive(visible);
  1008. _starStatButton?.gameObject.SetActive(visible);
  1009. _njsStatButton?.gameObject.SetActive(visible);
  1010. RefreshOuterUIState(visible == true ? UIState.Main : UIState.Disabled);
  1011. _deleteButton?.gameObject.SetActive(visible);
  1012. _pageUpFastButton?.gameObject.SetActive(visible);
  1013. _pageDownFastButton?.gameObject.SetActive(visible);
  1014. }
  1015. /// <summary>
  1016. /// Update the top UI state.
  1017. /// Hides the outer ui, sort, and filter buttons depending on the state.
  1018. /// </summary>
  1019. private void RefreshOuterUIState(UIState state)
  1020. {
  1021. bool sortButtons = false;
  1022. bool filterButtons = false;
  1023. bool outerButtons = false;
  1024. bool clearButton = true;
  1025. if (state == UIState.SortBy)
  1026. {
  1027. sortButtons = true;
  1028. }
  1029. else if (state == UIState.FilterBy)
  1030. {
  1031. filterButtons = true;
  1032. }
  1033. else if (state == UIState.Main)
  1034. {
  1035. outerButtons = true;
  1036. }
  1037. else
  1038. {
  1039. clearButton = false;
  1040. }
  1041. _sortButtonGroup.ForEach(x => x.Button.gameObject.SetActive(sortButtons));
  1042. _filterButtonGroup.ForEach(x => x.Button.gameObject.SetActive(filterButtons));
  1043. _sortByButton?.gameObject.SetActive(outerButtons);
  1044. _sortByDisplay?.gameObject.SetActive(outerButtons);
  1045. _filterByButton?.gameObject.SetActive(outerButtons);
  1046. _filterByDisplay?.gameObject.SetActive(outerButtons);
  1047. _clearSortFilterButton?.gameObject.SetActive(clearButton);
  1048. _randomButton?.gameObject.SetActive(outerButtons);
  1049. RefreshCurrentSelectionDisplay();
  1050. _currentUiState = state;
  1051. }
  1052. /// <summary>
  1053. /// Adjust the text field of the sort by and filter by displays.
  1054. /// </summary>
  1055. private void RefreshCurrentSelectionDisplay()
  1056. {
  1057. string sortByDisplay;
  1058. if (_model.Settings.sortMode == SongSortMode.Default)
  1059. {
  1060. sortByDisplay = "Title";
  1061. }
  1062. else
  1063. {
  1064. sortByDisplay = _model.Settings.sortMode.ToString();
  1065. }
  1066. _sortByDisplay.SetButtonText(sortByDisplay);
  1067. if (_model.Settings.filterMode != SongFilterMode.Custom)
  1068. {
  1069. // Custom SongFilterMod implies that another mod has modified the text of this button (do not overwrite)
  1070. _filterByDisplay.SetButtonText(_model.Settings.filterMode.ToString());
  1071. }
  1072. }
  1073. /// <summary>
  1074. /// Adjust the UI colors.
  1075. /// </summary>
  1076. public void RefreshSortButtonUI()
  1077. {
  1078. if (!_uiCreated)
  1079. {
  1080. return;
  1081. }
  1082. foreach (SongSortButton sortButton in _sortButtonGroup)
  1083. {
  1084. if (sortButton.SortMode.NeedsScoreSaberData() && !SongDataCore.Plugin.Songs.IsDataAvailable())
  1085. {
  1086. sortButton.Button.SetButtonUnderlineColor(Color.gray);
  1087. }
  1088. else
  1089. {
  1090. sortButton.Button.SetButtonUnderlineColor(Color.white);
  1091. }
  1092. if (sortButton.SortMode == _model.Settings.sortMode)
  1093. {
  1094. if (this._model.Settings.invertSortResults)
  1095. {
  1096. sortButton.Button.SetButtonUnderlineColor(Color.red);
  1097. }
  1098. else
  1099. {
  1100. sortButton.Button.SetButtonUnderlineColor(Color.green);
  1101. }
  1102. }
  1103. }
  1104. foreach (SongFilterButton filterButton in _filterButtonGroup)
  1105. {
  1106. filterButton.Button.SetButtonUnderlineColor(Color.white);
  1107. if (filterButton.FilterMode == _model.Settings.filterMode)
  1108. {
  1109. filterButton.Button.SetButtonUnderlineColor(Color.green);
  1110. }
  1111. }
  1112. if (this._model.Settings.invertSortResults)
  1113. {
  1114. _sortByDisplay.SetButtonUnderlineColor(Color.red);
  1115. }
  1116. else
  1117. {
  1118. _sortByDisplay.SetButtonUnderlineColor(Color.green);
  1119. }
  1120. if (this._model.Settings.filterMode != SongFilterMode.None)
  1121. {
  1122. _filterByDisplay.SetButtonUnderlineColor(Color.green);
  1123. }
  1124. else
  1125. {
  1126. _filterByDisplay.SetButtonUnderlineColor(Color.white);
  1127. }
  1128. }
  1129. /// <summary>
  1130. ///
  1131. /// </summary>
  1132. public void RefreshSongList()
  1133. {
  1134. if (!_uiCreated)
  1135. {
  1136. return;
  1137. }
  1138. _beatUi.RefreshSongList(_model.LastSelectedLevelId);
  1139. }
  1140. /// <summary>
  1141. /// Helper for updating the model (which updates the song list)
  1142. /// </summary>
  1143. public void UpdateLevelDataModel()
  1144. {
  1145. try
  1146. {
  1147. Logger.Trace("UpdateLevelDataModel()");
  1148. // get a current beatmap characteristic...
  1149. if (_model.CurrentBeatmapCharacteristicSO == null && _uiCreated)
  1150. {
  1151. _model.CurrentBeatmapCharacteristicSO = _beatUi.BeatmapCharacteristicSelectionViewController.GetPrivateField<BeatmapCharacteristicSO>("_selectedBeatmapCharacteristic");
  1152. }
  1153. _model.UpdateLevelRecords();
  1154. }
  1155. catch (Exception e)
  1156. {
  1157. Logger.Exception("SongBrowser UI crashed trying to update the internal song lists: ", e);
  1158. }
  1159. }
  1160. /// <summary>
  1161. /// Logic for fixing BeatSaber's level pack selection bugs.
  1162. /// </summary>
  1163. public bool UpdateLevelCollectionSelection()
  1164. {
  1165. if (_uiCreated)
  1166. {
  1167. IAnnotatedBeatmapLevelCollection currentSelected = _beatUi.GetCurrentSelectedAnnotatedBeatmapLevelCollection();
  1168. Logger.Debug("Updating level collection, current selected level collection: {0}", currentSelected);
  1169. // select category
  1170. if (!String.IsNullOrEmpty(_model.Settings.currentLevelCategoryName))
  1171. {
  1172. _selectingCategory = true;
  1173. _beatUi.SelectLevelCategory(_model.Settings.currentLevelCategoryName);
  1174. _selectingCategory = false;
  1175. }
  1176. // select collection
  1177. if (String.IsNullOrEmpty(_model.Settings.currentLevelCollectionName))
  1178. {
  1179. if (currentSelected == null && String.IsNullOrEmpty(_model.Settings.currentLevelCategoryName))
  1180. {
  1181. Logger.Debug("No level collection selected, acquiring the first available, likely OST1...");
  1182. currentSelected = _beatUi.BeatmapLevelsModel.allLoadedBeatmapLevelPackCollection.beatmapLevelPacks[0];
  1183. }
  1184. }
  1185. else if (currentSelected == null || (currentSelected.collectionName != _model.Settings.currentLevelCollectionName))
  1186. {
  1187. Logger.Debug("Automatically selecting level collection: {0}", _model.Settings.currentLevelCollectionName);
  1188. _beatUi.LevelFilteringNavigationController.didSelectAnnotatedBeatmapLevelCollectionEvent -= _levelFilteringNavController_didSelectAnnotatedBeatmapLevelCollectionEvent;
  1189. _lastLevelCollection = _beatUi.GetLevelCollectionByName(_model.Settings.currentLevelCollectionName);
  1190. if (_lastLevelCollection as PreviewBeatmapLevelPackSO)
  1191. {
  1192. Hide();
  1193. }
  1194. _beatUi.SelectLevelCollection(_model.Settings.currentLevelCollectionName);
  1195. _beatUi.LevelFilteringNavigationController.didSelectAnnotatedBeatmapLevelCollectionEvent += _levelFilteringNavController_didSelectAnnotatedBeatmapLevelCollectionEvent;
  1196. }
  1197. if (_lastLevelCollection == null)
  1198. {
  1199. if (currentSelected != null && currentSelected.collectionName != SongBrowserModel.FilteredSongsCollectionName && currentSelected.collectionName != SongBrowserModel.PlaylistSongsCollectionName)
  1200. {
  1201. _lastLevelCollection = currentSelected;
  1202. }
  1203. }
  1204. Logger.Debug("Current Level Collection is: {0}", _lastLevelCollection);
  1205. ProcessSongList();
  1206. }
  1207. return false;
  1208. }
  1209. }
  1210. }