Browse Source

Code cleanup. Fix bad names, weird spaces, simplify init, etc.

Stephen Damm 6 years ago
parent
commit
155d380586

+ 1 - 1
SongBrowserPlugin/DataAccess/Network/CacheableDownloadHandler.cs

@@ -41,7 +41,7 @@ namespace Mobcast.Coffee.AssetSystem
 		/// <summary>
 		/// Returns the downloaded Texture, or null.
 		/// </summary>
-		public Texture2D texture
+		public Texture2D Texture
 		{
 			get
 			{

+ 2 - 2
SongBrowserPlugin/DataAccess/PlaylistReader.cs

@@ -86,8 +86,8 @@ namespace SongBrowserPlugin.DataAccess
                 foreach (JSONNode node in playlistNode["songs"].AsArray)
                 {
                     PlaylistSong song = new PlaylistSong();
-                    song.key = node["key"];
-                    song.songName = node["songName"];
+                    song.Key = node["key"];
+                    song.SongName = node["songName"];
 
                     playlist.songs.Add(song);
                 }

+ 2 - 2
SongBrowserPlugin/DataAccess/PlaylistSong.cs

@@ -8,7 +8,7 @@ namespace SongBrowserPlugin.DataAccess
 {
     public class PlaylistSong
     {
-        public int key { get; set; }
-        public String songName { get; set; }
+        public int Key { get; set; }
+        public String SongName { get; set; }
     }
 }

+ 11 - 7
SongBrowserPlugin/DataAccess/ScoreSaberDatabase.cs

@@ -27,10 +27,12 @@ namespace SongBrowserPlugin.DataAccess
             {
                 return;
             }
-            ScoreSaberDifficulty ppDifficulty = new ScoreSaberDifficulty();
-            ppDifficulty.name = name;
-            ppDifficulty.star = star;
-            ppDifficulty.pp = pp;
+            ScoreSaberDifficulty ppDifficulty = new ScoreSaberDifficulty
+            {
+                name = name,
+                star = star,
+                pp = pp
+            };
             difficultyToSaberDifficulty.Add(ppDifficulty.name, ppDifficulty);
 
             if (pp > maxPp)
@@ -92,9 +94,11 @@ namespace SongBrowserPlugin.DataAccess
                     ScoreSaberData ppData = null;
                     if (!SongVersionToScoreSaberData.ContainsKey(version))
                     {
-                        ppData = new ScoreSaberData();
-                        ppData.version = version;
-                        ppData.name = name;
+                        ppData = new ScoreSaberData
+                        {
+                            version = version,
+                            name = name
+                        };
 
                         SongVersionToScoreSaberData.Add(version, ppData);
                     }

+ 38 - 22
SongBrowserPlugin/DataAccess/SongBrowserModel.cs

@@ -17,7 +17,7 @@ namespace SongBrowserPlugin
     {
         private const String CUSTOM_SONGS_DIR = "CustomSongs";
 
-        private DateTime EPOCH = new DateTime(1970, 1, 1);
+        private readonly DateTime EPOCH = new DateTime(1970, 1, 1);
 
         private readonly Regex SONG_PATH_VERSION_REGEX = new Regex(@".*/(?<version>[0-9]*-[0-9]*)/");
 
@@ -34,8 +34,10 @@ namespace SongBrowserPlugin
         private Dictionary<String, SongLoaderPlugin.OverrideClasses.CustomLevel> _levelIdToCustomLevel;
         private Dictionary<String, double> _cachedLastWriteTimes;
         private Dictionary<string, int> _weights;
+        private Dictionary<LevelDifficulty, int> _difficultyWeights;
         private Dictionary<string, ScoreSaberData> _levelIdToScoreSaberData = null;
         private Dictionary<string, int> _levelIdToPlayCount;
+        private Dictionary<string, string> _levelIdToSongVersion;
         private Dictionary<String, DirectoryNode> _directoryTree;
         private Stack<DirectoryNode> _directoryStack = new Stack<DirectoryNode>();
 
@@ -171,6 +173,7 @@ namespace SongBrowserPlugin
             _cachedLastWriteTimes = new Dictionary<String, double>();
             _levelIdToScoreSaberData = new Dictionary<string, ScoreSaberData>();
             _levelIdToPlayCount = new Dictionary<string, int>();
+            _levelIdToSongVersion = new Dictionary<string, string>();
 
             // Weights used for keeping the original songs in order
             // Invert the weights from the game so we can order by descending and make LINQ work with us...
@@ -195,6 +198,15 @@ namespace SongBrowserPlugin
                 ["Level9OneSaber"] = 9,
                 ["Level7OneSaber"] = 8,
             };
+
+            _difficultyWeights = new Dictionary<LevelDifficulty, int>
+            {
+                [LevelDifficulty.Easy] = int.MaxValue - 4,
+                [LevelDifficulty.Normal] = int.MaxValue - 3,
+                [LevelDifficulty.Hard] = int.MaxValue - 2,
+                [LevelDifficulty.Expert] = int.MaxValue - 1,
+                [LevelDifficulty.ExpertPlus] = int.MaxValue,
+            };
         }
 
         /// <summary>
@@ -259,6 +271,8 @@ namespace SongBrowserPlugin
             foreach (var level in SongLoader.CustomLevels)
             {
                 // If we already know this levelID, don't both updating it.
+                // SongLoader should filter duplicates but in case of failure we don't want to crash
+
                 if (!_cachedLastWriteTimes.ContainsKey(level.levelID) || customSongDirChanged)
                 {
                     _cachedLastWriteTimes[level.levelID] = (File.GetLastWriteTimeUtc(level.customSongInfo.path) - EPOCH).TotalMilliseconds;
@@ -268,9 +282,19 @@ namespace SongBrowserPlugin
                 {
                     _levelIdToCustomLevel.Add(level.levelID, level);
                 }
+
+                if (!_levelIdToSongVersion.ContainsKey(level.levelID))
+                {
+                    Match m = SONG_PATH_VERSION_REGEX.Match(level.customSongInfo.path);
+                    if (m.Success)
+                    {
+                        String version = m.Groups["version"].Value;
+                        _levelIdToSongVersion.Add(level.levelID, version);
+                    }
+                }
             } 
             lastWriteTimer.Stop();
-            _log.Info("Determining song download time took {0}ms", lastWriteTimer.ElapsedMilliseconds);
+            _log.Info("Determining song download time and determining mappings took {0}ms", lastWriteTimer.ElapsedMilliseconds);
 
             // Update song Infos, directory tree, and sort
             this.UpdateScoreSaberDataMapping();
@@ -348,16 +372,17 @@ namespace SongBrowserPlugin
 
                 ScoreSaberData scoreSaberData = null;
                 
-                Match m = SONG_PATH_VERSION_REGEX.Match(level.customSongInfo.path);
-                if (m.Success)
+                // try to version match first
+                if (_levelIdToSongVersion.ContainsKey(level.levelID))
                 {
-                    String version = m.Groups["version"].Value;
+                    String version = _levelIdToSongVersion[level.levelID];
                     if (scoreSaberDataFile.SongVersionToScoreSaberData.ContainsKey(version))
                     {
                         scoreSaberData = scoreSaberDataFile.SongVersionToScoreSaberData[version];
                     }
                 }
 
+                // fallback to name matching 
                 if (scoreSaberData == null)
                 {
                     if (scoreSaberDataFile.SongNameToScoreSaberData.ContainsKey(level.songName))
@@ -383,8 +408,10 @@ namespace SongBrowserPlugin
             // Determine folder mapping
             Uri customSongDirUri = new Uri(customSongsPath);
 
-            _directoryTree = new Dictionary<string, DirectoryNode>();
-            _directoryTree[CUSTOM_SONGS_DIR] = new DirectoryNode(CUSTOM_SONGS_DIR);
+            _directoryTree = new Dictionary<string, DirectoryNode>
+            {
+                [CUSTOM_SONGS_DIR] = new DirectoryNode(CUSTOM_SONGS_DIR)
+            };
 
             if (_settings.folderSupportEnabled)
             {
@@ -690,7 +717,7 @@ namespace SongBrowserPlugin
             }
 
             _log.Debug("Filtering songs for playlist: {0}", this.CurrentPlaylist);
-            List<String> playlistNameListOrdered = this.CurrentPlaylist.songs.Select(x => x.songName).Distinct().ToList();
+            List<String> playlistNameListOrdered = this.CurrentPlaylist.songs.Select(x => x.SongName).Distinct().ToList();
             Dictionary<String, int> songNameToIndex = playlistNameListOrdered.Select((val, index) => new { Index = index, Value = val }).ToDictionary(i => i.Value, i => i.Index);
             HashSet<String> songNames = new HashSet<String>(playlistNameListOrdered);
             LevelCollectionsForGameplayModes levelCollections = Resources.FindObjectsOfTypeAll<LevelCollectionsForGameplayModes>().FirstOrDefault();
@@ -746,18 +773,7 @@ namespace SongBrowserPlugin
 
         private void SortDifficulty(List<StandardLevelSO> levels)
         {
-            _log.Info("Sorting song list by random");
-
-            System.Random rnd = new System.Random(Guid.NewGuid().GetHashCode());
-
-            Dictionary<LevelDifficulty, int> difficultyWeights = new Dictionary<LevelDifficulty, int>
-            {
-                [LevelDifficulty.Easy] = int.MaxValue - 4,
-                [LevelDifficulty.Normal] = int.MaxValue - 3,
-                [LevelDifficulty.Hard] = int.MaxValue - 2,
-                [LevelDifficulty.Expert] = int.MaxValue - 1,
-                [LevelDifficulty.ExpertPlus] = int.MaxValue,
-            };
+            _log.Info("Sorting song list by difficulty...");
 
             IEnumerable<LevelDifficulty> difficultyIterator = Enum.GetValues(typeof(LevelDifficulty)).Cast<LevelDifficulty>();
             Dictionary<string, int>  levelIdToDifficultyValue = new Dictionary<string, int>();
@@ -778,7 +794,7 @@ namespace SongBrowserPlugin
                             IStandardLevelDifficultyBeatmap beatmap = level.GetDifficultyLevel(difficulty);
                             if (beatmap != null)
                             {
-                                difficultyValue += difficultyWeights[difficulty];
+                                difficultyValue += _difficultyWeights[difficulty];
                                 break;
                             }
                         }
@@ -795,7 +811,7 @@ namespace SongBrowserPlugin
 
         private void SortRandom(List<StandardLevelSO> levels)
         {
-            _log.Info("Sorting song list by random");
+            _log.Info("Sorting song list by random...");
 
             System.Random rnd = new System.Random(Guid.NewGuid().GetHashCode());
 

+ 11 - 7
SongBrowserPlugin/DataAccess/SongBrowserSettings.cs

@@ -136,8 +136,10 @@ namespace SongBrowserPlugin.DataAccess
                 catch (Exception e)
                 {
                     Log.Exception("Unable to deserialize song browser settings file, using default settings: ", e);
-                    retVal = new SongBrowserSettings();
-                    retVal.DisableSavingSettings = true;
+                    retVal = new SongBrowserSettings
+                    {
+                        DisableSavingSettings = true
+                    };
                 }
                 finally
                 {
@@ -193,11 +195,13 @@ namespace SongBrowserPlugin.DataAccess
                 searchTerms.RemoveRange(10, searchTerms.Count - 10);
             }
 
-            var settings = new XmlWriterSettings();
-            settings.OmitXmlDeclaration = false;
-            settings.Indent = true;
-            settings.NewLineOnAttributes = true;
-            settings.NewLineHandling = System.Xml.NewLineHandling.Entitize;
+            var settings = new XmlWriterSettings
+            {
+                OmitXmlDeclaration = false,
+                Indent = true,
+                NewLineOnAttributes = true,
+                NewLineHandling = System.Xml.NewLineHandling.Entitize
+            };
 
             using (var stream = new StreamWriter(path, false, Utf8Encoding))
             {

+ 3 - 4
SongBrowserPlugin/Logger.cs

@@ -14,14 +14,13 @@ namespace SongBrowserPlugin
 
     public class Logger
     {
-        private string loggerName;
-        private LogLevel _LogLevel = LogLevel.Info;
-        private ConsoleColor _defaultFgColor;
+        private readonly string loggerName;
+        private readonly LogLevel _LogLevel = LogLevel.Info;
+        private readonly ConsoleColor _defaultFgColor = ConsoleColor.Gray;
 
         public Logger(string _name)
         {
             loggerName = _name;
-            _defaultFgColor = ConsoleColor.Gray;
         }
 
         public void ResetForegroundColor()

+ 16 - 14
SongBrowserPlugin/UI/Browser/SongBrowserUI.cs

@@ -210,7 +210,7 @@ namespace SongBrowserPlugin.UI
                         buttonWidth, 
                         buttonHeight, 
                         sortModes[i],
-                        onSortButtonClickEvent));
+                        OnSortButtonClickEvent));
                 }
 
                 // Create filter buttons
@@ -221,9 +221,9 @@ namespace SongBrowserPlugin.UI
 
                 List<Tuple<SongFilterMode, UnityEngine.Events.UnityAction, Sprite>> filterButtonSetup = new List<Tuple<SongFilterMode, UnityEngine.Events.UnityAction, Sprite>>()
                 {
-                    Tuple.Create<SongFilterMode, UnityEngine.Events.UnityAction, Sprite>(SongFilterMode.Favorites, onFavoriteFilterButtonClickEvent, _addFavoriteSprite),
-                    Tuple.Create<SongFilterMode, UnityEngine.Events.UnityAction, Sprite>(SongFilterMode.Playlist, onPlaylistButtonClickEvent, playlistSprite),
-                    Tuple.Create<SongFilterMode, UnityEngine.Events.UnityAction, Sprite>(SongFilterMode.Search, onSearchButtonClickEvent, searchSprite),
+                    Tuple.Create<SongFilterMode, UnityEngine.Events.UnityAction, Sprite>(SongFilterMode.Favorites, OnFavoriteFilterButtonClickEvent, _addFavoriteSprite),
+                    Tuple.Create<SongFilterMode, UnityEngine.Events.UnityAction, Sprite>(SongFilterMode.Playlist, OnPlaylistButtonClickEvent, playlistSprite),
+                    Tuple.Create<SongFilterMode, UnityEngine.Events.UnityAction, Sprite>(SongFilterMode.Search, OnSearchButtonClickEvent, searchSprite),
                 };
 
                 _filterButtonGroup = new List<SongFilterButton>();
@@ -238,9 +238,11 @@ namespace SongBrowserPlugin.UI
                         new Vector2(3.5f, 3.5f),
                         new Vector2(1.0f, 1.0f),
                         0);
-                    SongFilterButton filterButton = new SongFilterButton();
-                    filterButton.Button = b;
-                    filterButton.FilterMode = t.Item1;
+                    SongFilterButton filterButton = new SongFilterButton
+                    {
+                        Button = b,
+                        FilterMode = t.Item1
+                    };
                     b.onClick.AddListener(t.Item2);
                     _filterButtonGroup.Add(filterButton);
                 }
@@ -337,7 +339,7 @@ namespace SongBrowserPlugin.UI
         /// <summary>
         /// Sort button clicked.
         /// </summary>
-        private void onSortButtonClickEvent(SongSortMode sortMode)
+        private void OnSortButtonClickEvent(SongSortMode sortMode)
         {
             _log.Debug("Sort button - {0} - pressed.", sortMode.ToString());
             _model.LastSelectedLevelId = null;
@@ -373,7 +375,7 @@ namespace SongBrowserPlugin.UI
         /// <summary>
         /// Filter by favorites.
         /// </summary>
-        private void onFavoriteFilterButtonClickEvent()
+        private void OnFavoriteFilterButtonClickEvent()
         {
             _log.Debug("Filter button - {0} - pressed.", SongFilterMode.Favorites.ToString());
 
@@ -395,7 +397,7 @@ namespace SongBrowserPlugin.UI
         /// Filter button clicked.  
         /// </summary>
         /// <param name="sortMode"></param>
-        private void onSearchButtonClickEvent()
+        private void OnSearchButtonClickEvent()
         {
             _log.Debug("Filter button - {0} - pressed.", SongFilterMode.Search.ToString());
             if (_model.Settings.filterMode != SongFilterMode.Search)
@@ -416,7 +418,7 @@ namespace SongBrowserPlugin.UI
         /// Display the playlist selector.
         /// </summary>
         /// <param name="sortMode"></param>
-        private void onPlaylistButtonClickEvent()
+        private void OnPlaylistButtonClickEvent()
         {
             _log.Debug("Filter button - {0} - pressed.", SongFilterMode.Playlist.ToString());
             _model.LastSelectedLevelId = null;
@@ -1137,19 +1139,19 @@ namespace SongBrowserPlugin.UI
                     // filter playlists
                     if (Input.GetKeyDown(KeyCode.P))
                     {
-                        onPlaylistButtonClickEvent();
+                        OnPlaylistButtonClickEvent();
                     }
 
                     // filter search
                     if (Input.GetKeyDown(KeyCode.S))
                     {
-                        onSearchButtonClickEvent();
+                        OnSearchButtonClickEvent();
                     }
 
                     // filter favorites
                     if (Input.GetKeyDown(KeyCode.F))
                     {
-                        onFavoriteFilterButtonClickEvent();
+                        OnFavoriteFilterButtonClickEvent();
                     }
 
                     // delete

+ 1 - 1
SongBrowserPlugin/UI/ScoreSaberDatabaseDownloader.cs

@@ -20,7 +20,7 @@ namespace SongBrowserPlugin.UI
 
         public Action onScoreSaberDataDownloaded;
 
-        private byte[] _buffer = new byte[4 * 1048576];
+        private readonly byte[] _buffer = new byte[4 * 1048576];
 
         /// <summary>
         /// Awake.