diff --git a/.gitignore b/.gitignore index bf83d346..eafec5b0 100644 --- a/.gitignore +++ b/.gitignore @@ -74,4 +74,6 @@ tx.exe /PitchTracker/bin /PitchTracker/obj /Logs -/Tests/bin \ No newline at end of file +/Tests/bin +*.orig +*.DotSettings diff --git a/PartyModes/PartyModeChallenge/CChallengeRounds.cs b/PartyModes/PartyModeChallenge/CChallengeRounds.cs index 37d46362..b99f6ad8 100644 --- a/PartyModes/PartyModeChallenge/CChallengeRounds.cs +++ b/PartyModes/PartyModeChallenge/CChallengeRounds.cs @@ -40,16 +40,20 @@ namespace VocaluxeLib.PartyModes.Challenge public CChallengeRounds(int numRounds, int numPlayer, int playersPerRound) { if (numRounds < 1 || numPlayer < 1 || playersPerRound < 1) + { throw new ArgumentException("Invalid paramters for the rounds"); + } if (playersPerRound > numPlayer) + { playersPerRound = numPlayer; + } _BuildRounds(numRounds, numPlayer, playersPerRound); if (Count > numRounds) { //Try again and take the better one - List old = new List(_Rounds); + var old = new List(_Rounds); _Rounds.Clear(); _BuildRounds(numRounds, numPlayer, playersPerRound); if (Count > old.Count) @@ -66,50 +70,60 @@ namespace VocaluxeLib.PartyModes.Challenge /// List matching the playerIndex to the number of songs sung private static List _GetPlayersForRound(IList numSung) { - List mustSing = new List(); - int max = numSung.Max(); - for (int i = 0; i < numSung.Count; i++) + var mustSing = new List(); + var max = numSung.Max(); + for (var i = 0; i < numSung.Count; i++) { if (numSung[i] < max) + { mustSing.Add(i); + } } + return mustSing; } private static void _AddCombinations(int numPlayer, int playersPerRound, List combinations) { - List input = new List(numPlayer); - for (int i = 0; i < numPlayer; i++) + var input = new List(numPlayer); + for (var i = 0; i < numPlayer; i++) + { input.Add(i); - CCombinations combs = new CCombinations(input, playersPerRound); + } + + var combs = new CCombinations(input, playersPerRound); combinations.AddRange(combs.Select(combination => new CRound(combination))); combinations.Shuffle(); } private static CRound _GetMatchingCombination(List playersInRound, List numSung, List combinations) { - foreach (CRound round in combinations) + foreach (var round in combinations) { - int matching = round.Players.Count(playersInRound.Contains); + var matching = round.Players.Count(playersInRound.Contains); // A valid round contains only players from playersInRound or all players from playersInRound (and some others) if (matching == round.Players.Count || matching == playersInRound.Count) + { return round; + } } + // It may happen, that there are only players that already sung against each other. So create a 2nd best option with the most number of players that should sing in it - int maxMatching = combinations.Max(c => c.Players.Count(playersInRound.Contains)); - List nextOptions = combinations.Where(c => c.Players.Count(playersInRound.Contains) == maxMatching).ToList(); + var maxMatching = combinations.Max(c => c.Players.Count(playersInRound.Contains)); + var nextOptions = combinations.Where(c => c.Players.Count(playersInRound.Contains) == maxMatching).ToList(); // And select the combination that minimizes the sum of the number of songs sung (--> favor rounds with players that sung less than others) CRound result = null; - int minSung = int.MaxValue; - foreach (CRound round in nextOptions) + var minSung = int.MaxValue; + foreach (var round in nextOptions) { - int curNumSung = round.Players.Sum(pl => numSung[pl]); + var curNumSung = round.Players.Sum(pl => numSung[pl]); if (curNumSung < minSung) { minSung = curNumSung; result = round; } } + Debug.Assert(result != null); return result; } @@ -118,24 +132,35 @@ namespace VocaluxeLib.PartyModes.Challenge { // What we want is that every player sung the same amount of songs // So we keep track how many songs each palyer sung - List numSung = new List(numPlayer); - for (int i = 0; i < numPlayer; i++) + var numSung = new List(numPlayer); + for (var i = 0; i < numPlayer; i++) + { numSung.Add(0); - List combinations = new List(); + } + + var combinations = new List(); // Posibly add more rounds than requested if the song count per player is unequal - for (int i = 0; i < numRounds * 10; i++) + for (var i = 0; i < numRounds * 10; i++) { if (combinations.Count == 0) + { _AddCombinations(numPlayer, playersPerRound, combinations); - List playersInRound = _GetPlayersForRound(numSung); - CRound curRound = _GetMatchingCombination(playersInRound, numSung, combinations); - foreach (int player in curRound.Players) + } + + var playersInRound = _GetPlayersForRound(numSung); + var curRound = _GetMatchingCombination(playersInRound, numSung, combinations); + foreach (var player in curRound.Players) + { numSung[player]++; + } + _Rounds.Add(curRound); combinations.Remove(curRound); //Stop if we have enough rounds and all players sung the same amount of songs if (_Rounds.Count >= numRounds && numSung.All(ct => ct == numSung[0])) + { break; + } } } } diff --git a/PartyModes/PartyModeChallenge/CPartyModeChallenge.cs b/PartyModes/PartyModeChallenge/CPartyModeChallenge.cs index da556692..b5a97923 100644 --- a/PartyModes/PartyModeChallenge/CPartyModeChallenge.cs +++ b/PartyModes/PartyModeChallenge/CPartyModeChallenge.cs @@ -17,12 +17,10 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Linq; using System.Runtime.InteropServices; -using VocaluxeLib.Game; using VocaluxeLib.Menu; -using VocaluxeLib.Songs; +using VocaluxeLib.Utils; [assembly: ComVisible(false)] @@ -31,7 +29,7 @@ namespace VocaluxeLib.PartyModes.Challenge public class CResultTableRow : IComparable { public int Position; - public Guid PlayerID; + public Guid PlayerId; public int NumPlayed; public int NumWon; public int NumSingPoints; @@ -42,13 +40,16 @@ namespace VocaluxeLib.PartyModes.Challenge var row = obj as CResultTableRow; if (row != null) { - int res = row.NumGamePoints.CompareTo(NumGamePoints); + var res = row.NumGamePoints.CompareTo(NumGamePoints); if (res == 0) { res = row.NumSingPoints.CompareTo(NumSingPoints); if (res == 0) + { res = row.NumWon.CompareTo(NumWon); + } } + return res; } @@ -69,7 +70,7 @@ namespace VocaluxeLib.PartyModes.Challenge // ReSharper disable ClassNeverInstantiated.Global public sealed class CPartyModeChallenge : CPartyMode - // ReSharper restore ClassNeverInstantiated.Global + // ReSharper restore ClassNeverInstantiated.Global { public override int MinMics { @@ -123,12 +124,12 @@ namespace VocaluxeLib.PartyModes.Challenge public int NumJokers; public bool RefillJokers; public int[] Jokers; - public List ProfileIDs; + public List ProfileIds; public ESongSource SongSource; public ESongSorting Sorting; public int CategoryIndex; - public int PlaylistID; + public int PlaylistId; public EGameMode GameMode; public int NumMedleySongs; @@ -144,7 +145,7 @@ namespace VocaluxeLib.PartyModes.Challenge private struct SStats { - public Guid ProfileID; + public Guid ProfileId; public int SingPoints; public int GamePoints; public int Won; @@ -158,13 +159,13 @@ namespace VocaluxeLib.PartyModes.Challenge _ScreenSongOptions.Selection.RandomOnly = false; _ScreenSongOptions.Selection.PartyMode = true; _ScreenSongOptions.Selection.CategoryChangeAllowed = true; - _ScreenSongOptions.Selection.NumJokers = new int[] {5, 5}; - _ScreenSongOptions.Selection.TeamNames = new string[] {"foo", "bar"}; + _ScreenSongOptions.Selection.NumJokers = new int[] { 5, 5 }; + _ScreenSongOptions.Selection.TeamNames = new string[] { "foo", "bar" }; - _ScreenSongOptions.Sorting.SearchString = String.Empty; + _ScreenSongOptions.Sorting.SearchString = string.Empty; _ScreenSongOptions.Sorting.SearchActive = false; _ScreenSongOptions.Sorting.DuetOptions = EDuetOptions.NoDuets; - _ScreenSongOptions.Sorting.FilterPlaylistID = -1; + _ScreenSongOptions.Sorting.FilterPlaylistId = -1; GameData = new SData { @@ -174,10 +175,10 @@ namespace VocaluxeLib.PartyModes.Challenge NumJokers = 5, RefillJokers = true, CurrentRoundNr = 1, - ProfileIDs = new List(), + ProfileIds = new List(), Sorting = CBase.Config.GetSongSorting(), SongSource = ESongSource.TR_SONGSOURCE_ALLSONGS, - PlaylistID = 0, + PlaylistId = 0, CategoryIndex = 0, GameMode = EGameMode.TR_GAMEMODE_NORMAL, NumMedleySongs = 5, @@ -197,7 +198,9 @@ namespace VocaluxeLib.PartyModes.Challenge _ScreenSongOptions.Selection.CategoryIndex = -1; if (CBase.Config.GetTabs() == EOffOn.TR_CONFIG_ON && _ScreenSongOptions.Sorting.SongSorting != ESongSorting.TR_CONFIG_NONE) + { _ScreenSongOptions.Sorting.Tabs = EOffOn.TR_CONFIG_ON; + } GameData.ResultTable = new List(); } @@ -205,16 +208,15 @@ namespace VocaluxeLib.PartyModes.Challenge public override bool Init() { if (!base.Init()) + { return false; + } SetDefaults(); return true; } - public override void UpdateGame() - { - - } + public override void UpdateGame() { } private IMenu _GetNextScreen() { @@ -272,6 +274,7 @@ namespace VocaluxeLib.PartyModes.Challenge _Stage = EStage.SongSelection; _PrepareSongSelection(); } + break; case EStage.SongSelection: _Stage = EStage.Singing; @@ -284,6 +287,7 @@ namespace VocaluxeLib.PartyModes.Challenge default: throw new ArgumentException("Invalid stage: " + _Stage); } + _FadeToScreen(); } @@ -306,6 +310,7 @@ namespace VocaluxeLib.PartyModes.Challenge default: // Rest is not allowed throw new ArgumentException("Invalid stage: " + _Stage); } + _FadeToScreen(); } @@ -322,7 +327,9 @@ namespace VocaluxeLib.PartyModes.Challenge public override void OnSongChange(int songIndex, ref SScreenSongOptions screenSongOptions) { if (_ScreenSongOptions.Selection.SelectNextRandomSong && songIndex != -1) + { _ScreenSongOptions.Selection.SelectNextRandomSong = false; + } _ScreenSongOptions.Selection.SongIndex = songIndex; @@ -358,24 +365,29 @@ namespace VocaluxeLib.PartyModes.Challenge public override void JokerUsed(int teamNr) { if (_ScreenSongOptions.Selection.NumJokers == null) + { return; + } if (teamNr >= _ScreenSongOptions.Selection.NumJokers.Length) + { return; + } if (!GameData.RefillJokers) { - CRound round = GameData.Rounds[GameData.CurrentRoundNr - 1]; + var round = GameData.Rounds[GameData.CurrentRoundNr - 1]; GameData.Jokers[round.Players[teamNr]]--; } + _ScreenSongOptions.Selection.NumJokers[teamNr]--; _ScreenSongOptions.Selection.RandomOnly = true; _ScreenSongOptions.Selection.CategoryChangeAllowed = false; } - public override void SongSelected(int songID) + public override void SongSelected(int songId) { - _PrepareRound(new int[] { songID }); + _PrepareRound(new int[] { songId }); Next(); } @@ -383,8 +395,10 @@ namespace VocaluxeLib.PartyModes.Challenge public override void LeavingHighscore() { //Remember sung songs, so they don't will be selected a second time - for(int i = 0; i < CBase.Game.GetNumSongs(); i++) - CBase.Songs.AddPartySongSung(CBase.Game.GetSong(i).ID); + for (var i = 0; i < CBase.Game.GetNumSongs(); i++) + { + CBase.Songs.AddPartySongSung(CBase.Game.GetSong(i).Id); + } GameData.CurrentRoundNr++; @@ -397,17 +411,19 @@ namespace VocaluxeLib.PartyModes.Challenge private void _PrepareMedleyRound() { //Select songs for medley - int[] songIDs = new int[GameData.NumMedleySongs]; - for (int i = 0; i < GameData.NumMedleySongs; i++) + var songIds = new int[GameData.NumMedleySongs]; + for (var i = 0; i < GameData.NumMedleySongs; i++) { if (GameData.Songs.Count == 0) + { _UpdateSongList(); + } - songIDs[i] = GameData.Songs[0]; + songIds[i] = GameData.Songs[0]; GameData.Songs.RemoveAt(0); } - _PrepareRound(songIDs); + _PrepareRound(songIds); } /// @@ -425,7 +441,7 @@ namespace VocaluxeLib.PartyModes.Challenge case ESongSource.TR_SONGSOURCE_ALLSONGS: _ScreenSongOptions.Sorting.SongSorting = CBase.Config.GetSongSorting(); _ScreenSongOptions.Sorting.Tabs = CBase.Config.GetTabs(); - _ScreenSongOptions.Sorting.FilterPlaylistID = -1; + _ScreenSongOptions.Sorting.FilterPlaylistId = -1; _ScreenSongOptions.Selection.SongIndex = -1; _ScreenSongOptions.Selection.CategoryIndex = -1; @@ -435,7 +451,7 @@ namespace VocaluxeLib.PartyModes.Challenge case ESongSource.TR_SONGSOURCE_CATEGORY: _ScreenSongOptions.Sorting.SongSorting = GameData.Sorting; _ScreenSongOptions.Sorting.Tabs = EOffOn.TR_CONFIG_ON; - _ScreenSongOptions.Sorting.FilterPlaylistID = -1; + _ScreenSongOptions.Sorting.FilterPlaylistId = -1; _ScreenSongOptions.Selection.CategoryIndex = GameData.CategoryIndex; _ScreenSongOptions.Selection.CategoryChangeAllowed = false; @@ -444,7 +460,7 @@ namespace VocaluxeLib.PartyModes.Challenge case ESongSource.TR_SONGSOURCE_PLAYLIST: _ScreenSongOptions.Sorting.SongSorting = CBase.Config.GetSongSorting(); _ScreenSongOptions.Sorting.Tabs = EOffOn.TR_CONFIG_OFF; - _ScreenSongOptions.Sorting.FilterPlaylistID = GameData.PlaylistID; + _ScreenSongOptions.Sorting.FilterPlaylistId = GameData.PlaylistId; _ScreenSongOptions.Selection.CategoryChangeAllowed = false; break; @@ -457,9 +473,9 @@ namespace VocaluxeLib.PartyModes.Challenge /// /// Prepare next game and fill song queue based on configuration and given songs. /// - /// Array of SongIDs that are selected + /// Array of SongIds that are selected /// false, if something can't setup correctly - private bool _PrepareRound(int[] songIDs) + private bool _PrepareRound(int[] songIds) { //Reset game CBase.Game.Reset(); @@ -467,73 +483,86 @@ namespace VocaluxeLib.PartyModes.Challenge #region PlayerNames CBase.Game.SetNumPlayer(GameData.NumPlayerAtOnce); - SPlayer[] players = CBase.Game.GetPlayers(); + var players = CBase.Game.GetPlayers(); if (players == null || players.Length < GameData.NumPlayerAtOnce) + { return false; + } //Get current round - CRound c = GameData.Rounds[GameData.CurrentRoundNr - 1]; + var c = GameData.Rounds[GameData.CurrentRoundNr - 1]; - for (int i = 0; i < GameData.NumPlayerAtOnce; i++) + for (var i = 0; i < GameData.NumPlayerAtOnce; i++) { //try to fill with correct player data if (c != null) - players[i].ProfileID = GameData.ProfileIDs[c.Players[i]]; + { + players[i].ProfileId = GameData.ProfileIds[c.Players[i]]; + } else - players[i].ProfileID = Guid.Empty; + { + players[i].ProfileId = Guid.Empty; + } } #endregion PlayerNames #region SongQueue //Add all songs with configure game mode to song queue - for (int i = 0; i < songIDs.Length; i++) - CBase.Game.AddSong(songIDs[i], GameData.GameMode); + for (var i = 0; i < songIds.Length; i++) + { + CBase.Game.AddSong(songIds[i], GameData.GameMode); + } #endregion SongQueue return true; - } private void _SetNumJokers() { - int[] jokers = new int[GameData.NumPlayerAtOnce]; + var jokers = new int[GameData.NumPlayerAtOnce]; if (GameData.RefillJokers) - { - for (int i = 0; i < jokers.Length; i++) - jokers[i] = GameData.NumJokers; + { + for (var i = 0; i < jokers.Length; i++) + { + jokers[i] = GameData.NumJokers; + } } else { if (GameData.Jokers == null) { GameData.Jokers = new int[GameData.NumPlayer]; - for (int i = 0; i < GameData.ProfileIDs.Count; i++) + for (var i = 0; i < GameData.ProfileIds.Count; i++) { GameData.Jokers[i] = GameData.NumJokers; } } - CRound round = GameData.Rounds[GameData.CurrentRoundNr - 1]; - for (int i = 0; i < GameData.NumPlayerAtOnce; i++) + + var round = GameData.Rounds[GameData.CurrentRoundNr - 1]; + for (var i = 0; i < GameData.NumPlayerAtOnce; i++) { jokers[i] = GameData.Jokers[round.Players[i]]; } } + _ScreenSongOptions.Selection.NumJokers = jokers; } private void _SetTeamNames() { - if (GameData.NumPlayerAtOnce < 1 || GameData.ProfileIDs.Count < GameData.NumPlayerAtOnce) + if (GameData.NumPlayerAtOnce < 1 || GameData.ProfileIds.Count < GameData.NumPlayerAtOnce) { - _ScreenSongOptions.Selection.TeamNames = new string[] {"foo", "bar"}; + _ScreenSongOptions.Selection.TeamNames = new string[] { "foo", "bar" }; return; } _ScreenSongOptions.Selection.TeamNames = new string[GameData.NumPlayerAtOnce]; - CRound c = GameData.Rounds[GameData.CurrentRoundNr - 1]; + var c = GameData.Rounds[GameData.CurrentRoundNr - 1]; - for (int i = 0; i < GameData.NumPlayerAtOnce; i++) - _ScreenSongOptions.Selection.TeamNames[i] = CBase.Profiles.GetPlayerName(GameData.ProfileIDs[c.Players[i]]); + for (var i = 0; i < GameData.NumPlayerAtOnce; i++) + { + _ScreenSongOptions.Selection.TeamNames[i] = CBase.Profiles.GetPlayerName(GameData.ProfileIds[c.Players[i]]); + } } /// @@ -543,37 +572,43 @@ namespace VocaluxeLib.PartyModes.Challenge private void _UpdateSongList() { if (GameData.Songs.Count > 0) + { return; + } switch (GameData.SongSource) { case ESongSource.TR_SONGSOURCE_PLAYLIST: - for (int i = 0; i < CBase.Playlist.GetSongCount(GameData.PlaylistID); i++) + for (var i = 0; i < CBase.Playlist.GetSongCount(GameData.PlaylistId); i++) { - int id = CBase.Playlist.GetSong(GameData.PlaylistID, i).SongID; - if (CBase.Songs.GetSongByID(id).AvailableGameModes.Contains(EGameMode.TR_GAMEMODE_MEDLEY)) + var id = CBase.Playlist.GetSong(GameData.PlaylistId, i).SongId; + if (CBase.Songs.GetSongById(id).IsGameModeAvailable(EGameMode.TR_GAMEMODE_MEDLEY)) + { GameData.Songs.Add(id); + } } + break; case ESongSource.TR_SONGSOURCE_ALLSONGS: - ReadOnlyCollection avSongs = CBase.Songs.GetSongs(); - GameData.Songs.AddRange(avSongs.Where(song => song.AvailableGameModes.Contains(EGameMode.TR_GAMEMODE_MEDLEY)).Select(song => song.ID)); + var avSongs = CBase.Songs.GetSongs(); + GameData.Songs.AddRange(avSongs.Where(song => song.IsGameModeAvailable(EGameMode.TR_GAMEMODE_MEDLEY)).Select(song => song.Id)); break; case ESongSource.TR_SONGSOURCE_CATEGORY: //Save old sorting to roll it back after getting songs for configured category - ESongSorting oldSorting = CBase.Config.GetSongSorting(); - CBase.Songs.SortSongs(GameData.Sorting, EOffOn.TR_CONFIG_ON, CBase.Config.GetIgnoreArticles() ,String.Empty, EDuetOptions.NoDuets, -1); + var oldSorting = CBase.Config.GetSongSorting(); + CBase.Songs.SortSongs(GameData.Sorting, EOffOn.TR_CONFIG_ON, CBase.Config.GetIgnoreArticles(), string.Empty, EDuetOptions.NoDuets, -1); CBase.Songs.SetCategory(GameData.CategoryIndex); avSongs = CBase.Songs.GetVisibleSongs(); - GameData.Songs.AddRange(avSongs.Where(song => song.AvailableGameModes.Contains(EGameMode.TR_GAMEMODE_MEDLEY)).Select(song => song.ID)); + GameData.Songs.AddRange(avSongs.Where(song => song.IsGameModeAvailable(EGameMode.TR_GAMEMODE_MEDLEY)).Select(song => song.Id)); CBase.Songs.SetCategory(-1); - CBase.Songs.SortSongs(oldSorting, CBase.Config.GetTabs(), CBase.Config.GetIgnoreArticles(), String.Empty, EDuetOptions.NoDuets, -1); + CBase.Songs.SortSongs(oldSorting, CBase.Config.GetTabs(), CBase.Config.GetIgnoreArticles(), string.Empty, EDuetOptions.NoDuets, -1); break; } + GameData.Songs.Shuffle(); } @@ -582,41 +617,46 @@ namespace VocaluxeLib.PartyModes.Challenge //Prepare results table if (GameData.ResultTable.Count == 0) { - for (int i = 0; i < GameData.NumPlayer; i++) + for (var i = 0; i < GameData.NumPlayer; i++) { - var row = new CResultTableRow { PlayerID = GameData.ProfileIDs[i], NumPlayed = 0, NumWon = 0, NumSingPoints = 0, NumGamePoints = 0 }; + var row = new CResultTableRow { PlayerId = GameData.ProfileIds[i], NumPlayed = 0, NumWon = 0, NumSingPoints = 0, NumGamePoints = 0 }; GameData.ResultTable.Add(row); } GameData.Results = new int[GameData.NumRounds, GameData.NumPlayerAtOnce]; - for (int i = 0; i < GameData.NumRounds; i++) + for (var i = 0; i < GameData.NumRounds; i++) { - for (int j = 0; j < GameData.NumPlayerAtOnce; j++) + for (var j = 0; j < GameData.NumPlayerAtOnce; j++) + { GameData.Results[i, j] = 0; + } } } //Get points from game - CPoints points = CBase.Game.GetPoints(); - SPlayer[] players = CBase.Game.GetPlayers(); + var points = CBase.Game.GetPoints(); + var players = CBase.Game.GetPlayers(); //Go over all rounds and sum up points - for (int round = 0; round < points.NumRounds; round++) + for (var round = 0; round < points.NumRounds; round++) { - SPlayer[] res = points.GetPlayer(round, GameData.NumPlayerAtOnce); + var res = points.GetPlayer(round, GameData.NumPlayerAtOnce); if (res == null || res.Length < GameData.NumPlayerAtOnce) + { return; + } - for (int p = 0; p < GameData.NumPlayerAtOnce; p++) + for (var p = 0; p < GameData.NumPlayerAtOnce; p++) { players[p].Points += res[p].Points; players[p].PointsGoldenNotes += res[p].PointsGoldenNotes; players[p].PointsLineBonus += res[p].PointsLineBonus; } } + //Calculate average points - for (int p = 0; p < GameData.NumPlayerAtOnce; p++) + for (var p = 0; p < GameData.NumPlayerAtOnce; p++) { players[p].Points /= points.NumRounds; players[p].PointsGoldenNotes /= points.NumRounds; @@ -626,15 +666,15 @@ namespace VocaluxeLib.PartyModes.Challenge GameData.Results[GameData.CurrentRoundNr - 2, p] = (int)Math.Round(players[p].Points); } - List stats = _GetPointsForPlayer(players); + var stats = _GetPointsForPlayer(players); - for (int i = 0; i < GameData.NumPlayerAtOnce; i++) + for (var i = 0; i < GameData.NumPlayerAtOnce; i++) { //Find matching row in results table - int index = -1; - for (int j = 0; j < GameData.ResultTable.Count; j++) + var index = -1; + for (var j = 0; j < GameData.ResultTable.Count; j++) { - if (stats[i].ProfileID == GameData.ResultTable[j].PlayerID) + if (stats[i].ProfileId == GameData.ResultTable[j].PlayerId) { index = j; break; @@ -642,8 +682,11 @@ namespace VocaluxeLib.PartyModes.Challenge } if (index == -1) + { continue; - CResultTableRow row = GameData.ResultTable[index]; + } + + var row = GameData.ResultTable[index]; //Update results entry row.NumPlayed++; @@ -657,13 +700,16 @@ namespace VocaluxeLib.PartyModes.Challenge GameData.ResultTable.Sort(); //Update position-number - int pos = 1; - int lastPoints = 0; - int lastSingPoints = 0; - foreach (CResultTableRow resultRow in GameData.ResultTable) + var pos = 1; + var lastPoints = 0; + var lastSingPoints = 0; + foreach (var resultRow in GameData.ResultTable) { if (lastPoints > resultRow.NumGamePoints || lastSingPoints > resultRow.NumSingPoints) + { pos++; + } + resultRow.Position = pos; lastPoints = resultRow.NumGamePoints; lastSingPoints = resultRow.NumSingPoints; @@ -673,21 +719,21 @@ namespace VocaluxeLib.PartyModes.Challenge private List _GetPointsForPlayer(SPlayer[] results) { var result = new List(); - for (int i = 0; i < GameData.NumPlayerAtOnce; i++) + for (var i = 0; i < GameData.NumPlayerAtOnce; i++) { - var stat = new SStats {ProfileID = results[i].ProfileID, SingPoints = (int)Math.Round(results[i].Points), Won = 0, GamePoints = 0}; + var stat = new SStats { ProfileId = results[i].ProfileId, SingPoints = (int)Math.Round(results[i].Points), Won = 0, GamePoints = 0 }; result.Add(stat); } result.Sort((s1, s2) => s1.SingPoints.CompareTo(s2.SingPoints)); - int current = result[result.Count - 1].SingPoints; - int points = result.Count; - bool wonset = false; + var current = result[result.Count - 1].SingPoints; + var points = result.Count; + var wonset = false; - for (int i = result.Count - 1; i >= 0; i--) + for (var i = result.Count - 1; i >= 0; i--) { - SStats res = result[i]; + var res = result[i]; if (i < result.Count - 1) { @@ -700,7 +746,10 @@ namespace VocaluxeLib.PartyModes.Challenge else { if (!wonset) + { res.Won = 1; + } + res.GamePoints = points; } } @@ -719,4 +768,4 @@ namespace VocaluxeLib.PartyModes.Challenge return result; } } -} +} \ No newline at end of file diff --git a/PartyModes/PartyModeChallenge/CPartyScreenChallengeConfig.cs b/PartyModes/PartyModeChallenge/CPartyScreenChallengeConfig.cs index 99cfae4d..a16672b1 100644 --- a/PartyModes/PartyModeChallenge/CPartyScreenChallengeConfig.cs +++ b/PartyModes/PartyModeChallenge/CPartyScreenChallengeConfig.cs @@ -22,7 +22,7 @@ namespace VocaluxeLib.PartyModes.Challenge { // ReSharper disable UnusedMember.Global public class CPartyScreenChallengeConfig : CPartyScreenChallenge - // ReSharper restore UnusedMember.Global + // ReSharper restore UnusedMember.Global { // Version number for theme files. Increment it, if you've changed something on the theme files! protected override int _ScreenVersion @@ -46,14 +46,14 @@ namespace VocaluxeLib.PartyModes.Challenge base.Init(); _ThemeSelectSlides = new string[] { _SelectSlideNumPlayers, _SelectSlideNumMics, _SelectSlideNumRounds, _SelectSlideNumJokers, _SelectSlideRefillJokers }; - _ThemeButtons = new string[] {_ButtonNext, _ButtonBack}; + _ThemeButtons = new string[] { _ButtonNext, _ButtonBack }; } public override bool HandleInput(SKeyEvent keyEvent) { base.HandleInput(keyEvent); - if (keyEvent.KeyPressed) {} + if (keyEvent.KeyPressed) { } else { switch (keyEvent.Key) @@ -67,10 +67,15 @@ namespace VocaluxeLib.PartyModes.Challenge _UpdateSlides(); if (_Buttons[_ButtonBack].Selected) + { _PartyMode.Back(); + } if (_Buttons[_ButtonNext].Selected) + { _PartyMode.Next(); + } + break; case Keys.Left: @@ -82,6 +87,7 @@ namespace VocaluxeLib.PartyModes.Challenge break; } } + return true; } @@ -93,14 +99,20 @@ namespace VocaluxeLib.PartyModes.Challenge { _UpdateSlides(); if (_Buttons[_ButtonBack].Selected) + { _PartyMode.Back(); + } if (_Buttons[_ButtonNext].Selected) + { _PartyMode.Next(); + } } if (mouseEvent.RB) + { _PartyMode.Back(); + } return true; } @@ -121,22 +133,26 @@ namespace VocaluxeLib.PartyModes.Challenge { // build num player slide (min player ... max player); _SelectSlides[_SelectSlideNumPlayers].Clear(); - for (int i = _PartyMode.MinPlayers; i <= _PartyMode.MaxPlayers; i++) + for (var i = _PartyMode.MinPlayers; i <= _PartyMode.MaxPlayers; i++) + { _SelectSlides[_SelectSlideNumPlayers].AddValue(i.ToString()); + } + _SelectSlides[_SelectSlideNumPlayers].SelectedValue = _PartyMode.GameData.NumPlayer.ToString(); // build num joker slide 1 to 10 _SelectSlides[_SelectSlideNumJokers].Clear(); - for (int i = 1; i <= 10; i++) + for (var i = 1; i <= 10; i++) { _SelectSlides[_SelectSlideNumJokers].AddValue(i.ToString()); } + _SelectSlides[_SelectSlideNumJokers].SelectedValue = "5"; //build joker config slide _SelectSlides[_SelectSlideRefillJokers].Clear(); - _SelectSlides[_SelectSlideRefillJokers].AddValue(CBase.Language.Translate("TR_BUTTON_NO", PartyModeID)); - _SelectSlides[_SelectSlideRefillJokers].AddValue(CBase.Language.Translate("TR_BUTTON_YES", PartyModeID)); + _SelectSlides[_SelectSlideRefillJokers].AddValue(CBase.Language.Translate("TR_BUTTON_NO", PartyModeId)); + _SelectSlides[_SelectSlideRefillJokers].AddValue(CBase.Language.Translate("TR_BUTTON_YES", PartyModeId)); _SelectSlides[_SelectSlideRefillJokers].SelectLastValue(); _UpdateMicsAtOnce(); @@ -146,22 +162,25 @@ namespace VocaluxeLib.PartyModes.Challenge private void _UpdateSlides() { - int player = _PartyMode.GameData.NumPlayer; - int mics = _PartyMode.GameData.NumPlayerAtOnce; + var player = _PartyMode.GameData.NumPlayer; + var mics = _PartyMode.GameData.NumPlayerAtOnce; _PartyMode.GameData.NumPlayer = _SelectSlides[_SelectSlideNumPlayers].Selection + _PartyMode.MinPlayers; _PartyMode.GameData.NumPlayerAtOnce = _SelectSlides[_SelectSlideNumMics].Selection + _PartyMode.MinPlayers; _PartyMode.GameData.NumRounds = (_SelectSlides[_SelectSlideNumRounds].Selection + 1) * _RoundSteps; _PartyMode.GameData.NumJokers = _SelectSlides[_SelectSlideNumJokers].Selection + 1; - _PartyMode.GameData.RefillJokers = (_SelectSlides[_SelectSlideRefillJokers].Selection == 1) ? true : false; + _PartyMode.GameData.RefillJokers = _SelectSlides[_SelectSlideRefillJokers].Selection == 1 ? true : false; _UpdateMicsAtOnce(); _SetRoundSteps(); if (player != _PartyMode.GameData.NumPlayer || mics != _PartyMode.GameData.NumPlayerAtOnce) { - int num = CHelper.CombinationCount(_PartyMode.GameData.NumPlayer, _PartyMode.GameData.NumPlayerAtOnce); + var num = CHelper.CombinationCount(_PartyMode.GameData.NumPlayer, _PartyMode.GameData.NumPlayerAtOnce); while (num > _MaxNumRounds) + { num -= _RoundSteps; + } + _PartyMode.GameData.NumRounds = num; } @@ -170,15 +189,20 @@ namespace VocaluxeLib.PartyModes.Challenge private void _UpdateMicsAtOnce() { - int maxNum = Math.Min(_PartyMode.MaxMics, _PartyMode.GameData.NumPlayer); + var maxNum = Math.Min(_PartyMode.MaxMics, _PartyMode.GameData.NumPlayer); if (_PartyMode.GameData.NumPlayerAtOnce > maxNum) + { _PartyMode.GameData.NumPlayerAtOnce = maxNum; + } // build mics at once slide _SelectSlides[_SelectSlideNumMics].Clear(); - for (int i = 1; i <= maxNum; i++) + for (var i = 1; i <= maxNum; i++) + { _SelectSlides[_SelectSlideNumMics].AddValue(i.ToString()); + } + _SelectSlides[_SelectSlideNumMics].Selection = _PartyMode.GameData.NumPlayerAtOnce - _PartyMode.MinPlayers; } @@ -186,8 +210,11 @@ namespace VocaluxeLib.PartyModes.Challenge { // build num rounds slide _SelectSlides[_SelectSlideNumRounds].Clear(); - for (int i = _RoundSteps; i <= _MaxNumRounds; i += _RoundSteps) + for (var i = _RoundSteps; i <= _MaxNumRounds; i += _RoundSteps) + { _SelectSlides[_SelectSlideNumRounds].AddValue(i.ToString()); + } + _SelectSlides[_SelectSlideNumRounds].Selection = _PartyMode.GameData.NumRounds / _RoundSteps - 1; } @@ -199,8 +226,8 @@ namespace VocaluxeLib.PartyModes.Challenge return; } - int res = _PartyMode.GameData.NumPlayer / _PartyMode.GameData.NumPlayerAtOnce; - int mod = _PartyMode.GameData.NumPlayer % _PartyMode.GameData.NumPlayerAtOnce; + var res = _PartyMode.GameData.NumPlayer / _PartyMode.GameData.NumPlayerAtOnce; + var mod = _PartyMode.GameData.NumPlayer % _PartyMode.GameData.NumPlayerAtOnce; _RoundSteps = mod == 0 ? res : _PartyMode.GameData.NumPlayer; } diff --git a/PartyModes/PartyModeChallenge/CPartyScreenChallengeMain.cs b/PartyModes/PartyModeChallenge/CPartyScreenChallengeMain.cs index a8765a3d..27a1d0df 100644 --- a/PartyModes/PartyModeChallenge/CPartyScreenChallengeMain.cs +++ b/PartyModes/PartyModeChallenge/CPartyScreenChallengeMain.cs @@ -41,7 +41,7 @@ namespace VocaluxeLib.PartyModes.Challenge // ReSharper disable UnusedMember.Global public class CPartyScreenChallengeMain : CPartyScreenChallenge - // ReSharper restore UnusedMember.Global + // ReSharper restore UnusedMember.Global { // Version number for theme files. Increment it, if you've changed something on the theme files! protected override int _ScreenVersion @@ -97,17 +97,17 @@ namespace VocaluxeLib.PartyModes.Challenge base.Init(); _ThemeTexts = new string[] - { - _TextPosition, _TextPlayerName, _TextNumPlayed, _TextWon, _TextSingPoints, _TextGamePoints, _TextNextPlayer, _TextPopupReallyExit, _TextRoundNumber, - _TextRoundPlayer, - _TextRoundScore, _TextFinishMessage, _TextFinishPlayerWin, _TextNextPlayerMessage - }; + { + _TextPosition, _TextPlayerName, _TextNumPlayed, _TextWon, _TextSingPoints, _TextGamePoints, _TextNextPlayer, _TextPopupReallyExit, _TextRoundNumber, + _TextRoundPlayer, + _TextRoundScore, _TextFinishMessage, _TextFinishPlayerWin, _TextNextPlayerMessage + }; _ThemeButtons = new string[] - { - _ButtonNextRound, _ButtonBack, _ButtonExit, _ButtonPopupYes, _ButtonPopupNo, _ButtonPlayerScrollDown, _ButtonPlayerScrollUp, _ButtonRoundsScrollDown, - _ButtonRoundsScrollUp - }; - _ThemeStatics = new string[] {_StaticPopupBG, _StaticNextPlayer}; + { + _ButtonNextRound, _ButtonBack, _ButtonExit, _ButtonPopupYes, _ButtonPopupNo, _ButtonPlayerScrollDown, _ButtonPlayerScrollUp, _ButtonRoundsScrollDown, + _ButtonRoundsScrollUp + }; + _ThemeStatics = new string[] { _StaticPopupBG, _StaticNextPlayer }; } public override void LoadTheme(string xmlPath) @@ -119,7 +119,7 @@ namespace VocaluxeLib.PartyModes.Challenge _NextPlayerTexts = new List(); _NextPlayerStatics = new List(); - for (int i = 0; i < _PartyMode.MaxPlayers; i++) + for (var i = 0; i < _PartyMode.MaxPlayers; i++) { _NextPlayerTexts.Add(GetNewText(_Texts[_TextNextPlayer])); _AddText(_NextPlayerTexts[_NextPlayerTexts.Count - 1]); @@ -127,6 +127,7 @@ namespace VocaluxeLib.PartyModes.Challenge _AddStatic(_NextPlayerStatics[_NextPlayerStatics.Count - 1]); _NextPlayerStatics[_NextPlayerStatics.Count - 1].Aspect = EAspect.Crop; } + _Statics[_StaticNextPlayer].Visible = false; } @@ -134,7 +135,7 @@ namespace VocaluxeLib.PartyModes.Challenge { base.HandleInput(keyEvent); - if (keyEvent.KeyPressed) {} + if (keyEvent.KeyPressed) { } else { switch (keyEvent.Key) @@ -144,42 +145,76 @@ namespace VocaluxeLib.PartyModes.Challenge if (!_ExitPopupVisible) { if (_PartyMode.GameData.CurrentRoundNr == 1) + { _PartyMode.Back(); + } else + { _ShowPopup(true); + } } else + { _ShowPopup(false); + } + break; case Keys.Enter: if (!_ExitPopupVisible) { if (_Buttons[_ButtonNextRound].Selected) + { _PartyMode.Next(); + } + if (_Buttons[_ButtonBack].Selected && _PartyMode.GameData.CurrentRoundNr == 1) + { _PartyMode.Back(); + } + if (_Buttons[_ButtonExit].Selected && _PartyMode.GameData.CurrentRoundNr > 1) + { _ShowPopup(true); + } + if (_Buttons[_ButtonPlayerScrollUp].Selected) + { _ScrollPlayerTable(-1); + } + if (_Buttons[_ButtonPlayerScrollDown].Selected) + { _ScrollPlayerTable(1); + } + if (_Buttons[_ButtonRoundsScrollUp].Selected) + { _ScrollRoundsTable(-1); + } + if (_Buttons[_ButtonRoundsScrollDown].Selected) + { _ScrollRoundsTable(1); + } } else { if (_Buttons[_ButtonPopupYes].Selected) + { _EndParty(); + } + if (_Buttons[_ButtonPopupNo].Selected) + { _ShowPopup(false); + } } + break; } } + return true; } @@ -192,26 +227,51 @@ namespace VocaluxeLib.PartyModes.Challenge if (!_ExitPopupVisible) { if (_Buttons[_ButtonNextRound].Selected) + { _PartyMode.Next(); + } + if (_Buttons[_ButtonBack].Selected && _PartyMode.GameData.CurrentRoundNr == 1) + { _PartyMode.Back(); + } + if (_Buttons[_ButtonExit].Selected && _PartyMode.GameData.CurrentRoundNr > 1) + { _ShowPopup(true); + } + if (_Buttons[_ButtonPlayerScrollUp].Selected) + { _ScrollPlayerTable(-1); + } + if (_Buttons[_ButtonPlayerScrollDown].Selected) + { _ScrollPlayerTable(1); + } + if (_Buttons[_ButtonRoundsScrollUp].Selected) + { _ScrollRoundsTable(-1); + } + if (_Buttons[_ButtonRoundsScrollDown].Selected) + { _ScrollRoundsTable(1); + } } else { if (_Buttons[_ButtonPopupYes].Selected) + { _EndParty(); + } + if (_Buttons[_ButtonPopupNo].Selected) + { _ShowPopup(false); + } } } @@ -220,20 +280,31 @@ namespace VocaluxeLib.PartyModes.Challenge if (!_ExitPopupVisible) { if (_PartyMode.GameData.CurrentRoundNr == 1) + { _PartyMode.Back(); + } else + { _ShowPopup(true); + } } else + { _ShowPopup(false); + } } if (mouseEvent.Wheel != 0) { if (CHelper.IsInBounds(_RoundsTableScrollArea, mouseEvent)) + { _ScrollRoundsTable(mouseEvent.Wheel); + } + if (CHelper.IsInBounds(_PlayerTableScrollArea, mouseEvent)) + { _ScrollPlayerTable(mouseEvent.Wheel); + } } return true; @@ -250,9 +321,14 @@ namespace VocaluxeLib.PartyModes.Challenge _UpdateNextPlayerPositions(); _UpdateNextPlayerContents(); if (_PartyMode.GameData.CurrentRoundNr == 1) + { _BuildRoundsTable(); + } else + { _ScrollRoundsTable(_PartyMode.GameData.CurrentRoundNr - 2); + } + _UpdateRoundsTable(); if (_PartyMode.GameData.CurrentRoundNr == 1) @@ -305,16 +381,18 @@ namespace VocaluxeLib.PartyModes.Challenge _Buttons[_ButtonPopupNo].Visible = _ExitPopupVisible; if (_ExitPopupVisible) + { _SelectElement(_Buttons[_ButtonPopupNo]); + } } private void _UpdateNextPlayerPositions() { - float x = (float)CBase.Settings.GetRenderW() / 2 - - ((_PartyMode.GameData.NumPlayerAtOnce * _Statics[_StaticNextPlayer].Rect.W) + ((_PartyMode.GameData.NumPlayerAtOnce - 1) * 15)) / 2; + var x = (float)CBase.Settings.GetRenderW() / 2 - + (_PartyMode.GameData.NumPlayerAtOnce * _Statics[_StaticNextPlayer].Rect.W + (_PartyMode.GameData.NumPlayerAtOnce - 1) * 15) / 2; const float staticY = 885; const float textY = 825; - for (int i = 0; i < _PartyMode.GameData.NumPlayerAtOnce; i++) + for (var i = 0; i < _PartyMode.GameData.NumPlayerAtOnce; i++) { //static _NextPlayerStatics[i].X = x; @@ -327,7 +405,8 @@ namespace VocaluxeLib.PartyModes.Challenge x += _Statics[_StaticNextPlayer].Rect.W + 15; } - for (int i = _PartyMode.GameData.NumPlayerAtOnce; i < _PartyMode.MaxPlayers; i++) + + for (var i = _PartyMode.GameData.NumPlayerAtOnce; i < _PartyMode.MaxPlayers; i++) { _NextPlayerStatics[i].Visible = false; _NextPlayerTexts[i].Visible = false; @@ -339,9 +418,9 @@ namespace VocaluxeLib.PartyModes.Challenge if (_PartyMode.GameData.CurrentRoundNr <= _PartyMode.GameData.Rounds.Count) { _Texts[_TextNextPlayerMessage].Visible = true; - for (int i = 0; i < _PartyMode.GameData.NumPlayerAtOnce; i++) + for (var i = 0; i < _PartyMode.GameData.NumPlayerAtOnce; i++) { - Guid id = _PartyMode.GameData.ProfileIDs[_PartyMode.GameData.Rounds[_PartyMode.GameData.CurrentRoundNr - 1].Players[i]]; + var id = _PartyMode.GameData.ProfileIds[_PartyMode.GameData.Rounds[_PartyMode.GameData.CurrentRoundNr - 1].Players[i]]; _NextPlayerStatics[i].Texture = CBase.Profiles.GetAvatar(id); _NextPlayerTexts[i].Text = CBase.Profiles.GetPlayerName(id); _NextPlayerTexts[i].Color = CBase.Themes.GetPlayerColor(i + 1); @@ -350,7 +429,7 @@ namespace VocaluxeLib.PartyModes.Challenge else { _Texts[_TextNextPlayerMessage].Visible = false; - for (int i = 0; i < _PartyMode.GameData.NumPlayerAtOnce; i++) + for (var i = 0; i < _PartyMode.GameData.NumPlayerAtOnce; i++) { _NextPlayerStatics[i].Visible = false; _NextPlayerTexts[i].Visible = false; @@ -362,21 +441,22 @@ namespace VocaluxeLib.PartyModes.Challenge { //Create lists _RoundsTable = new List(); - for (int i = 0; i < 5; i++) + for (var i = 0; i < 5; i++) { - var rtr = new CRoundsTableRow {TextPlayer = new List(), TextScores = new List()}; + var rtr = new CRoundsTableRow { TextPlayer = new List(), TextScores = new List() }; _RoundsTable.Add(rtr); } + //Create statics and texts for rounds - foreach (CRoundsTableRow roundRow in _RoundsTable) + foreach (var roundRow in _RoundsTable) { //Round-number - CText text = GetNewText(_Texts[_TextRoundNumber]); + var text = GetNewText(_Texts[_TextRoundNumber]); _AddText(text); roundRow.Number = text; - for (int row = 0; row < 2; row++) + for (var row = 0; row < 2; row++) { - for (int column = 0; column < 3; column++) + for (var column = 0; column < 3; column++) { //Player text = GetNewText(_Texts[_TextRoundPlayer]); @@ -399,39 +479,42 @@ namespace VocaluxeLib.PartyModes.Challenge _NumRoundsVisible = _PartyMode.GameData.NumPlayerAtOnce <= numPlayerInOneRow ? 5 : 3; if (_NumRoundsVisible > _PartyMode.GameData.Rounds.Count) + { _NumRoundsVisible = _PartyMode.GameData.Rounds.Count; + } - float numberX = _Texts[_TextRoundNumber].X; - float numberY = _Texts[_TextRoundNumber].Y; + var numberX = _Texts[_TextRoundNumber].X; + var numberY = _Texts[_TextRoundNumber].Y; _RoundsTableScrollArea.X = numberX; _RoundsTableScrollArea.Y = numberY; _RoundsTableScrollArea.W = CBase.Settings.GetRenderW() - _Texts[_TextRoundNumber].X - 20; - float delta = _Texts[_TextRoundNumber].Rect.H; + var delta = _Texts[_TextRoundNumber].Rect.H; //Update statics and texts for rounds - foreach (CRoundsTableRow roundRow in _RoundsTable) + foreach (var roundRow in _RoundsTable) { //Round-number roundRow.Number.X = numberX; roundRow.Number.Y = numberY; - var numInnerRows = (int)Math.Ceiling(_PartyMode.GameData.NumPlayerAtOnce / ((double)numPlayerInOneRow)); - for (int row = 0; row < numInnerRows; row++) + var numInnerRows = (int)Math.Ceiling(_PartyMode.GameData.NumPlayerAtOnce / (double)numPlayerInOneRow); + for (var row = 0; row < numInnerRows; row++) { - int num = (row + 1) * numPlayerInOneRow; - int numPlayerInThisRow = numPlayerInOneRow; + var num = (row + 1) * numPlayerInOneRow; + var numPlayerInThisRow = numPlayerInOneRow; if (num > _PartyMode.GameData.NumPlayerAtOnce) { num = _PartyMode.GameData.NumPlayerAtOnce; - numPlayerInThisRow = _PartyMode.GameData.NumPlayerAtOnce - (row * numPlayerInOneRow); + numPlayerInThisRow = _PartyMode.GameData.NumPlayerAtOnce - row * numPlayerInOneRow; } - for (int column = row * numPlayerInOneRow; column < num; column++) + + for (var column = row * numPlayerInOneRow; column < num; column++) { //Player - float x = numberX + 15 + (CBase.Settings.GetRenderW() - _Texts[_TextRoundNumber].X - 20) / numPlayerInThisRow * (column - row * numPlayerInOneRow) + - ((CBase.Settings.GetRenderW() - _Texts[_TextRoundNumber].X - 20) / numPlayerInThisRow) / 2; - float maxw = ((CBase.Settings.GetRenderW() - _Texts[_TextRoundNumber].X - 20) / numPlayerInThisRow) / 2 - 5; + var x = numberX + 15 + (CBase.Settings.GetRenderW() - _Texts[_TextRoundNumber].X - 20) / numPlayerInThisRow * (column - row * numPlayerInOneRow) + + (CBase.Settings.GetRenderW() - _Texts[_TextRoundNumber].X - 20) / numPlayerInThisRow / 2; + var maxw = (CBase.Settings.GetRenderW() - _Texts[_TextRoundNumber].X - 20) / numPlayerInThisRow / 2 - 5; roundRow.TextPlayer[column].X = x; roundRow.TextPlayer[column].Y = numberY; roundRow.TextPlayer[column].W = maxw; @@ -440,33 +523,40 @@ namespace VocaluxeLib.PartyModes.Challenge roundRow.TextScores[column].Y = numberY + delta; roundRow.TextScores[column].W = maxw; } + numberY = numberY + 2 * delta; } + numberY = numberY + delta / 2; } + _RoundsTableScrollArea.H = numberY - _RoundsTableScrollArea.Y; } private void _UpdateRoundsTable() { - for (int i = 0; i < _RoundsTable.Count; i++) + for (var i = 0; i < _RoundsTable.Count; i++) { - for (int p = 0; p < _RoundsTable[i].TextPlayer.Count; p++) + for (var p = 0; p < _RoundsTable[i].TextPlayer.Count; p++) { if (_PartyMode.GameData.Rounds.Count > i + _RoundsTableOffset && _PartyMode.GameData.Rounds[i + _RoundsTableOffset].Players.Count > p) { _RoundsTable[i].Number.Visible = true; _RoundsTable[i].TextPlayer[p].Visible = true; _RoundsTable[i].TextScores[p].Visible = true; - _RoundsTable[i].Number.Text = (i + 1 + _RoundsTableOffset) + ")"; + _RoundsTable[i].Number.Text = i + 1 + _RoundsTableOffset + ")"; _RoundsTable[i].TextPlayer[p].Text = - CBase.Profiles.GetPlayerName(_PartyMode.GameData.ProfileIDs[_PartyMode.GameData.Rounds[i + _RoundsTableOffset].Players[p]]); + CBase.Profiles.GetPlayerName(_PartyMode.GameData.ProfileIds[_PartyMode.GameData.Rounds[i + _RoundsTableOffset].Players[p]]); // ReSharper disable ConvertIfStatementToConditionalTernaryExpression - if ((_PartyMode.GameData.CurrentRoundNr - 1) > i + _RoundsTableOffset) + if (_PartyMode.GameData.CurrentRoundNr - 1 > i + _RoundsTableOffset) // ReSharper restore ConvertIfStatementToConditionalTernaryExpression + { _RoundsTable[i].TextScores[p].Text = _PartyMode.GameData.Results[i + _RoundsTableOffset, p].ToString(); + } else + { _RoundsTable[i].TextScores[p].Text = ""; + } } else { @@ -474,10 +564,11 @@ namespace VocaluxeLib.PartyModes.Challenge _RoundsTable[i].TextScores[p].Visible = false; } } + if (_PartyMode.GameData.Rounds.Count < i + _RoundsTableOffset || i + 1 > _NumRoundsVisible) { _RoundsTable[i].Number.Visible = false; - for (int p = 0; p < _RoundsTable[i].TextPlayer.Count; p++) + for (var p = 0; p < _RoundsTable[i].TextPlayer.Count; p++) { _RoundsTable[i].TextPlayer[p].Visible = false; _RoundsTable[i].TextScores[p].Visible = false; @@ -491,24 +582,24 @@ namespace VocaluxeLib.PartyModes.Challenge private void _BuildPlayerTable() { - _PlayerTableScrollArea = new SRectF {X = _Texts[_TextPosition].X, Y = _Texts[_TextPosition].Y, W = _Texts[_TextGamePoints].X - _Texts[_TextPosition].X}; + _PlayerTableScrollArea = new SRectF { X = _Texts[_TextPosition].X, Y = _Texts[_TextPosition].Y, W = _Texts[_TextGamePoints].X - _Texts[_TextPosition].X }; _PlayerTable = new List(); - float delta = _Texts[_TextPosition].Rect.H * 1.2f; + var delta = _Texts[_TextPosition].Rect.H * 1.2f; float h = 0; - for (int i = 0; i < 10; i++) + for (var i = 0; i < 10; i++) { var row = new STableRow - { - Pos = GetNewText(_Texts[_TextPosition]), - Name = GetNewText(_Texts[_TextPlayerName]), - Rounds = GetNewText(_Texts[_TextNumPlayed]), - Won = GetNewText(_Texts[_TextWon]), - SingPoints = GetNewText(_Texts[_TextSingPoints]), - GamePoints = GetNewText(_Texts[_TextGamePoints]) - }; + { + Pos = GetNewText(_Texts[_TextPosition]), + Name = GetNewText(_Texts[_TextPlayerName]), + Rounds = GetNewText(_Texts[_TextNumPlayed]), + Won = GetNewText(_Texts[_TextWon]), + SingPoints = GetNewText(_Texts[_TextSingPoints]), + GamePoints = GetNewText(_Texts[_TextGamePoints]) + }; row.Pos.Y += delta * (i + 1); row.Name.Y += delta * (i + 1); @@ -517,7 +608,7 @@ namespace VocaluxeLib.PartyModes.Challenge row.SingPoints.Y += delta * (i + 1); row.GamePoints.Y += delta * (i + 1); - row.Pos.Text = (i + 1) + "."; + row.Pos.Text = i + 1 + "."; row.Pos.Visible = false; row.Name.Visible = false; @@ -537,14 +628,15 @@ namespace VocaluxeLib.PartyModes.Challenge h = delta * (i + 1); } + _PlayerTableScrollArea.H = h + delta; } private void _UpdatePlayerTable() { - for (int i = 0; i < _PlayerTable.Count; i++) + for (var i = 0; i < _PlayerTable.Count; i++) { - STableRow row = _PlayerTable[i]; + var row = _PlayerTable[i]; if (i + _PlayerTableOffset < _PartyMode.GameData.ResultTable.Count) { @@ -556,7 +648,7 @@ namespace VocaluxeLib.PartyModes.Challenge row.GamePoints.Visible = true; row.Pos.Text = _PartyMode.GameData.ResultTable[i + _PlayerTableOffset].Position + "."; - row.Name.Text = CBase.Profiles.GetPlayerName(_PartyMode.GameData.ResultTable[i + _PlayerTableOffset].PlayerID); + row.Name.Text = CBase.Profiles.GetPlayerName(_PartyMode.GameData.ResultTable[i + _PlayerTableOffset].PlayerId); row.Rounds.Text = _PartyMode.GameData.ResultTable[i + _PlayerTableOffset].NumPlayed.ToString(); row.Won.Text = _PartyMode.GameData.ResultTable[i + _PlayerTableOffset].NumWon.ToString(); row.SingPoints.Text = _PartyMode.GameData.ResultTable[i + _PlayerTableOffset].NumSingPoints.ToString(); @@ -574,21 +666,31 @@ namespace VocaluxeLib.PartyModes.Challenge } _Buttons[_ButtonPlayerScrollUp].Visible = _PlayerTableOffset > 0; - _Buttons[_ButtonPlayerScrollDown].Visible = _PartyMode.GameData.ProfileIDs.Count - _NumPlayerVisible - _PlayerTableOffset > 0; + _Buttons[_ButtonPlayerScrollDown].Visible = _PartyMode.GameData.ProfileIds.Count - _NumPlayerVisible - _PlayerTableOffset > 0; } private void _ScrollPlayerTable(int offset) { - if (_PartyMode.GameData.ProfileIDs.Count <= _NumPlayerVisible) + if (_PartyMode.GameData.ProfileIds.Count <= _NumPlayerVisible) + { _PlayerTableOffset = 0; + } else if (offset < 0 && _PlayerTableOffset + offset >= 0) + { _PlayerTableOffset += offset; + } else if (offset < 0 && _PlayerTableOffset + offset < 0) + { _PlayerTableOffset = 0; - else if (offset > 0 && _PlayerTableOffset + offset <= _PartyMode.GameData.ProfileIDs.Count - _NumPlayerVisible) + } + else if (offset > 0 && _PlayerTableOffset + offset <= _PartyMode.GameData.ProfileIds.Count - _NumPlayerVisible) + { _PlayerTableOffset += offset; - else if (offset > 0 && _PlayerTableOffset + offset > _PartyMode.GameData.ProfileIDs.Count - _NumPlayerVisible) - _PlayerTableOffset = _PartyMode.GameData.ProfileIDs.Count - _NumPlayerVisible; + } + else if (offset > 0 && _PlayerTableOffset + offset > _PartyMode.GameData.ProfileIds.Count - _NumPlayerVisible) + { + _PlayerTableOffset = _PartyMode.GameData.ProfileIds.Count - _NumPlayerVisible; + } _UpdatePlayerTable(); } @@ -596,36 +698,51 @@ namespace VocaluxeLib.PartyModes.Challenge private void _ScrollRoundsTable(int offset) { if (_PartyMode.GameData.Rounds.Count <= _NumRoundsVisible) + { _RoundsTableOffset = 0; + } else if (offset < 0 && _RoundsTableOffset + offset >= 0) + { _RoundsTableOffset += offset; + } else if (offset < 0 && _RoundsTableOffset + offset < 0) + { _RoundsTableOffset = 0; + } else if (offset > 0 && _RoundsTableOffset + offset <= _PartyMode.GameData.Rounds.Count - _NumRoundsVisible) + { _RoundsTableOffset += offset; + } else if (offset > 0 && _RoundsTableOffset + offset > _PartyMode.GameData.Rounds.Count - _NumRoundsVisible) + { _RoundsTableOffset = _PartyMode.GameData.Rounds.Count - _NumRoundsVisible; + } _UpdateRoundsTable(); } private string _GetPlayerWinString() { - string s = ""; + var s = ""; - for (int i = 0; i < _PartyMode.GameData.ResultTable.Count; i++) + for (var i = 0; i < _PartyMode.GameData.ResultTable.Count; i++) { if (_PartyMode.GameData.ResultTable[i].Position == 1) { if (i > 0) + { s += ", "; - s += CBase.Profiles.GetPlayerName(_PartyMode.GameData.ResultTable[i].PlayerID); + } + + s += CBase.Profiles.GetPlayerName(_PartyMode.GameData.ResultTable[i].PlayerId); } else + { break; + } } return s; } } -} +} \ No newline at end of file diff --git a/PartyModes/PartyModeChallenge/CPartyScreenChallengeNames.cs b/PartyModes/PartyModeChallenge/CPartyScreenChallengeNames.cs index bddb2940..b142341c 100644 --- a/PartyModes/PartyModeChallenge/CPartyScreenChallengeNames.cs +++ b/PartyModes/PartyModeChallenge/CPartyScreenChallengeNames.cs @@ -23,7 +23,7 @@ namespace VocaluxeLib.PartyModes.Challenge { // ReSharper disable UnusedMember.Global public class CPartyScreenChallengeNames : CMenuPartyNameSelection - // ReSharper restore UnusedMember.Global + // ReSharper restore UnusedMember.Global { // Version number for theme files. Increment it, if you've changed something on the theme files! protected override int _ScreenVersion @@ -45,24 +45,32 @@ namespace VocaluxeLib.PartyModes.Challenge { base.OnShow(); SetPartyModeData(_PartyMode.GameData.NumPlayer); - while (_PartyMode.GameData.ProfileIDs.Count > _NumPlayer) - _PartyMode.GameData.ProfileIDs.RemoveAt(_PartyMode.GameData.ProfileIDs.Count - 1); + while (_PartyMode.GameData.ProfileIds.Count > _NumPlayer) + { + _PartyMode.GameData.ProfileIds.RemoveAt(_PartyMode.GameData.ProfileIds.Count - 1); + } - List[] ids = new List[] {_PartyMode.GameData.ProfileIDs}; + var ids = new List[] { _PartyMode.GameData.ProfileIds }; SetPartyModeProfiles(ids); } public override void Back() { if (_TeamList.Length == 1) - _PartyMode.GameData.ProfileIDs = _TeamList[0]; + { + _PartyMode.GameData.ProfileIds = _TeamList[0]; + } + _PartyMode.Back(); } public override void Next() { if (_TeamList.Length == 1) - _PartyMode.GameData.ProfileIDs = _TeamList[0]; + { + _PartyMode.GameData.ProfileIds = _TeamList[0]; + } + _PartyMode.Next(); } } diff --git a/PartyModes/PartyModeChallenge/CPartyScreenChallengeSongs.cs b/PartyModes/PartyModeChallenge/CPartyScreenChallengeSongs.cs index f7261c4e..937589b9 100644 --- a/PartyModes/PartyModeChallenge/CPartyScreenChallengeSongs.cs +++ b/PartyModes/PartyModeChallenge/CPartyScreenChallengeSongs.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using VocaluxeLib.Menu; +using VocaluxeLib.Menu; namespace VocaluxeLib.PartyModes.Challenge { @@ -26,7 +22,7 @@ namespace VocaluxeLib.PartyModes.Challenge Source = _PartyMode.GameData.SongSource; Sorting = _PartyMode.GameData.Sorting; Category = _PartyMode.GameData.CategoryIndex; - Playlist = _PartyMode.GameData.PlaylistID; + Playlist = _PartyMode.GameData.PlaylistId; SongMode = _PartyMode.GameData.GameMode; NumMedleySongs = _PartyMode.GameData.NumMedleySongs; @@ -62,9 +58,9 @@ namespace VocaluxeLib.PartyModes.Challenge _PartyMode.GameData.SongSource = Source; _PartyMode.GameData.Sorting = Sorting; _PartyMode.GameData.CategoryIndex = Category; - _PartyMode.GameData.PlaylistID = Playlist; + _PartyMode.GameData.PlaylistId = Playlist; _PartyMode.GameData.GameMode = SongMode; _PartyMode.GameData.NumMedleySongs = NumMedleySongs; } } -} +} \ No newline at end of file diff --git a/PartyModes/PartyModeChallenge/PartyModeChallenge.csproj b/PartyModes/PartyModeChallenge/PartyModeChallenge.csproj index 45417cfc..a77c5b4b 100644 --- a/PartyModes/PartyModeChallenge/PartyModeChallenge.csproj +++ b/PartyModes/PartyModeChallenge/PartyModeChallenge.csproj @@ -27,6 +27,7 @@ Off ..\..\CheckingRules.ruleset false + 9.0 AnyCPU @@ -40,6 +41,7 @@ Off false true + 9.0 AnyCPU @@ -52,6 +54,7 @@ 4 Off false + 9.0 AnyCPU @@ -65,6 +68,7 @@ Off false true + 9.0 bin @@ -78,6 +82,7 @@ false pdbonly true + 9.0 @@ -119,4 +124,4 @@ rm -f "$(SolutionDir)Output\PartyModes\$(TargetName)\Code\GlobalSuppressions.cs" --> - + \ No newline at end of file diff --git a/PartyModes/PartyModeTicTacToe/CPartyModeTicTacToe.cs b/PartyModes/PartyModeTicTacToe/CPartyModeTicTacToe.cs index 6a911fcd..eb0a7aea 100644 --- a/PartyModes/PartyModeTicTacToe/CPartyModeTicTacToe.cs +++ b/PartyModes/PartyModeTicTacToe/CPartyModeTicTacToe.cs @@ -17,12 +17,10 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Linq; using System.Runtime.InteropServices; -using VocaluxeLib.Game; using VocaluxeLib.Menu; -using VocaluxeLib.Songs; +using VocaluxeLib.Utils; [assembly: ComVisible(false)] @@ -30,7 +28,7 @@ namespace VocaluxeLib.PartyModes.TicTacToe { public class CRound { - public int[] SongIDs; + public int[] SongIds; public int SingerTeam1; public int SingerTeam2; public int PointsTeam1; @@ -90,7 +88,7 @@ namespace VocaluxeLib.PartyModes.TicTacToe public readonly EGameMode[] AvailableGameModes = { EGameMode.TR_GAMEMODE_NORMAL, EGameMode.TR_GAMEMODE_SHORTSONG, EGameMode.TR_GAMEMODE_DUET }; - private enum EStage + private enum EStage { Config, Songs, @@ -106,13 +104,13 @@ namespace VocaluxeLib.PartyModes.TicTacToe public int NumFields; public int NumJockers; public int Team; - public List ProfileIDsTeam1; - public List ProfileIDsTeam2; + public List ProfileIdsTeam1; + public List ProfileIdsTeam2; public ESongSource SongSource; public ESongSorting Sorting; public int CategoryIndex; - public int PlaylistID; + public int PlaylistId; public EGameMode GameMode; public int NumMedleySongs; @@ -137,35 +135,35 @@ namespace VocaluxeLib.PartyModes.TicTacToe _ScreenSongOptions.Selection.RandomOnly = false; _ScreenSongOptions.Selection.PartyMode = true; _ScreenSongOptions.Selection.CategoryChangeAllowed = true; - _ScreenSongOptions.Selection.NumJokers = new int[] {5, 5}; - _ScreenSongOptions.Selection.TeamNames = new string[] {"foo", "bar"}; + _ScreenSongOptions.Selection.NumJokers = new int[] { 5, 5 }; + _ScreenSongOptions.Selection.TeamNames = new string[] { "foo", "bar" }; - _ScreenSongOptions.Sorting.SearchString = String.Empty; + _ScreenSongOptions.Sorting.SearchString = string.Empty; _ScreenSongOptions.Sorting.SearchActive = false; _ScreenSongOptions.Sorting.DuetOptions = EDuetOptions.NoDuets; GameData = new SData - { - NumPlayerTeam1 = 2, - NumPlayerTeam2 = 2, - NumFields = 9, - NumJockers = 1, - ProfileIDsTeam1 = new List(), - ProfileIDsTeam2 = new List(), - CurrentRoundNr = 0, - FieldNr = 0, - Sorting = CBase.Config.GetSongSorting(), - SongSource = ESongSource.TR_SONGSOURCE_ALLSONGS, - PlaylistID = 0, - CategoryIndex = 0, - GameMode = EGameMode.TR_GAMEMODE_NORMAL, - NumMedleySongs = 5, - Rounds = new List(), - Songs = new List(), - NumJokerRandom = new int[2], - NumJokerRetry = new int[2], - RefillJokers = EOffOn.TR_CONFIG_OFF - }; + { + NumPlayerTeam1 = 2, + NumPlayerTeam2 = 2, + NumFields = 9, + NumJockers = 1, + ProfileIdsTeam1 = new List(), + ProfileIdsTeam2 = new List(), + CurrentRoundNr = 0, + FieldNr = 0, + Sorting = CBase.Config.GetSongSorting(), + SongSource = ESongSource.TR_SONGSOURCE_ALLSONGS, + PlaylistId = 0, + CategoryIndex = 0, + GameMode = EGameMode.TR_GAMEMODE_NORMAL, + NumMedleySongs = 5, + Rounds = new List(), + Songs = new List(), + NumJokerRandom = new int[2], + NumJokerRetry = new int[2], + RefillJokers = EOffOn.TR_CONFIG_OFF + }; } public override void SetDefaults() @@ -178,7 +176,9 @@ namespace VocaluxeLib.PartyModes.TicTacToe _ScreenSongOptions.Selection.SongIndex = -1; if (CBase.Config.GetTabs() == EOffOn.TR_CONFIG_ON && _ScreenSongOptions.Sorting.SongSorting != ESongSorting.TR_CONFIG_NONE) + { _ScreenSongOptions.Sorting.Tabs = EOffOn.TR_CONFIG_ON; + } GameData.Songs.Clear(); GameData.Rounds.Clear(); @@ -187,7 +187,9 @@ namespace VocaluxeLib.PartyModes.TicTacToe public override bool Init() { if (!base.Init()) + { return false; + } SetDefaults(); return true; @@ -224,7 +226,9 @@ namespace VocaluxeLib.PartyModes.TicTacToe private void _FadeToScreen() { if (CBase.Graphics.GetNextScreen() != _GetNextScreen()) + { CBase.Graphics.FadeTo(_GetNextScreen()); + } } public void Next() @@ -253,11 +257,15 @@ namespace VocaluxeLib.PartyModes.TicTacToe _Stage = EStage.Main; GameData.Team = GameData.Team == 1 ? 0 : 1; if (GameData.RefillJokers == EOffOn.TR_CONFIG_ON) + { _SetNumJokers(); + } + break; default: throw new ArgumentException("Invalid stage: " + _Stage); } + _FadeToScreen(); } @@ -280,6 +288,7 @@ namespace VocaluxeLib.PartyModes.TicTacToe default: // Rest is not allowed throw new ArgumentException("Invalid stage: " + _Stage); } + _FadeToScreen(); } @@ -308,16 +317,16 @@ namespace VocaluxeLib.PartyModes.TicTacToe throw new ArgumentException("Not required!"); } - public override void JokerUsed(int teamNr) {} + public override void JokerUsed(int teamNr) { } - public override void SongSelected(int songID) + public override void SongSelected(int songId) { throw new ArgumentException("Not required!"); } public override void LeavingHighscore() { - CBase.Songs.AddPartySongSung(CBase.Game.GetSong(0).ID); + CBase.Songs.AddPartySongSung(CBase.Game.GetSong(0).Id); _UpdateScores(); Next(); } @@ -325,7 +334,7 @@ namespace VocaluxeLib.PartyModes.TicTacToe private void _CreateRounds() { GameData.Rounds = new List(); - for (int i = 0; i < GameData.NumFields; i++) + for (var i = 0; i < GameData.NumFields; i++) { var r = new CRound(); GameData.Rounds.Add(r); @@ -335,33 +344,39 @@ namespace VocaluxeLib.PartyModes.TicTacToe public void UpdateSongList() { if (GameData.Songs.Count > 0) + { return; + } switch (GameData.SongSource) { case ESongSource.TR_SONGSOURCE_PLAYLIST: - for (int i = 0; i < CBase.Playlist.GetSongCount(GameData.PlaylistID); i++) + for (var i = 0; i < CBase.Playlist.GetSongCount(GameData.PlaylistId); i++) { - int id = CBase.Playlist.GetSong(GameData.PlaylistID, i).SongID; - if (CBase.Songs.GetSongByID(id).AvailableGameModes.Contains(GameData.GameMode)) + var id = CBase.Playlist.GetSong(GameData.PlaylistId, i).SongId; + if (CBase.Songs.GetSongById(id).IsGameModeAvailable(GameData.GameMode)) + { GameData.Songs.Add(id); + } } + break; case ESongSource.TR_SONGSOURCE_ALLSONGS: - ReadOnlyCollection avSongs = CBase.Songs.GetSongs(); - GameData.Songs.AddRange(avSongs.Where(song => song.AvailableGameModes.Contains(GameData.GameMode)).Select(song => song.ID)); + var avSongs = CBase.Songs.GetSongs(); + GameData.Songs.AddRange(avSongs.Where(song => song.IsGameModeAvailable(GameData.GameMode)).Select(song => song.Id)); break; case ESongSource.TR_SONGSOURCE_CATEGORY: CBase.Songs.SortSongs(GameData.Sorting, EOffOn.TR_CONFIG_ON, CBase.Config.GetIgnoreArticles(), "", EDuetOptions.All, -1); CBase.Songs.SetCategory(GameData.CategoryIndex); avSongs = CBase.Songs.GetVisibleSongs(); - GameData.Songs.AddRange(avSongs.Where(song => song.AvailableGameModes.Contains(GameData.GameMode)).Select(song => song.ID)); + GameData.Songs.AddRange(avSongs.Where(song => song.IsGameModeAvailable(GameData.GameMode)).Select(song => song.Id)); CBase.Songs.SetCategory(-1); break; } + GameData.Songs.Shuffle(); } @@ -372,32 +387,37 @@ namespace VocaluxeLib.PartyModes.TicTacToe CBase.Game.SetNumPlayer(2); - SPlayer[] players = CBase.Game.GetPlayers(); + var players = CBase.Game.GetPlayers(); if (players == null) + { return; + } if (players.Length < 2) + { return; + } - CRound round = GameData.Rounds[roundNr]; + var round = GameData.Rounds[roundNr]; - for (int i = 0; i < 2; i++) + for (var i = 0; i < 2; i++) { //default values - players[i].ProfileID = Guid.Empty; + players[i].ProfileId = Guid.Empty; } //try to fill with the right data - players[0].ProfileID = GameData.ProfileIDsTeam1[round.SingerTeam1]; - players[1].ProfileID = GameData.ProfileIDsTeam2[round.SingerTeam2]; + players[0].ProfileId = GameData.ProfileIdsTeam1[round.SingerTeam1]; + players[1].ProfileId = GameData.ProfileIdsTeam2[round.SingerTeam2]; - foreach(int song in round.SongIDs) + foreach (var song in round.SongIds) + { CBase.Game.AddSong(song, GameData.GameMode); + } } private void _SetNumJokers() { - GameData.NumJokerRandom[0] = GameData.NumJockers; GameData.NumJokerRandom[1] = GameData.NumJockers; @@ -423,19 +443,23 @@ namespace VocaluxeLib.PartyModes.TicTacToe private void _UpdateScores() { if (!GameData.Rounds[GameData.FieldNr].Finished) + { GameData.CurrentRoundNr++; + } - CPoints points = CBase.Game.GetPoints(); - SPlayer[] results = CBase.Game.GetPlayers(); + var points = CBase.Game.GetPoints(); + var results = CBase.Game.GetPlayers(); if (results == null || results.Length < 2) + { return; + } //Sum up all points - for (int r = 0; r < points.NumRounds; r++) + for (var r = 0; r < points.NumRounds; r++) { - SPlayer[] player = points.GetPlayer(r, 2); - for (int i = 0; i < 2; i++) + var player = points.GetPlayer(r, 2); + for (var i = 0; i < 2; i++) { results[i].Points += player[i].Points; results[i].PointsGoldenNotes += player[i].PointsGoldenNotes; @@ -444,7 +468,7 @@ namespace VocaluxeLib.PartyModes.TicTacToe } //Calc average of points - for (int i = 0; i < 2; i++) + for (var i = 0; i < 2; i++) { results[i].Points /= points.NumRounds; results[i].PointsGoldenNotes /= points.NumRounds; @@ -456,9 +480,13 @@ namespace VocaluxeLib.PartyModes.TicTacToe GameData.Rounds[GameData.FieldNr].PointsTeam2 = (int)Math.Round(results[1].Points); GameData.Rounds[GameData.FieldNr].Finished = true; if (GameData.Rounds[GameData.FieldNr].PointsTeam1 < GameData.Rounds[GameData.FieldNr].PointsTeam2) + { GameData.Rounds[GameData.FieldNr].Winner = 2; + } else if (GameData.Rounds[GameData.FieldNr].PointsTeam1 > GameData.Rounds[GameData.FieldNr].PointsTeam2) + { GameData.Rounds[GameData.FieldNr].Winner = 1; + } else { GameData.Rounds[GameData.FieldNr].Finished = false; diff --git a/PartyModes/PartyModeTicTacToe/CPartyScreenTicTacToeConfig.cs b/PartyModes/PartyModeTicTacToe/CPartyScreenTicTacToeConfig.cs index 0d68bb52..ddb702e8 100644 --- a/PartyModes/PartyModeTicTacToe/CPartyScreenTicTacToeConfig.cs +++ b/PartyModes/PartyModeTicTacToe/CPartyScreenTicTacToeConfig.cs @@ -16,11 +16,8 @@ #endregion using System; -using System.Collections.Generic; using System.Diagnostics; -using System.Linq; using System.Windows.Forms; -using VocaluxeLib.Songs; namespace VocaluxeLib.PartyModes.TicTacToe { @@ -71,10 +68,15 @@ namespace VocaluxeLib.PartyModes.TicTacToe _UpdateSlides(); if (_Buttons[_ButtonBack].Selected) + { _PartyMode.Back(); + } if (_Buttons[_ButtonNext].Selected) + { _PartyMode.Next(); + } + break; case Keys.Left: @@ -86,6 +88,7 @@ namespace VocaluxeLib.PartyModes.TicTacToe break; } } + return true; } @@ -97,14 +100,20 @@ namespace VocaluxeLib.PartyModes.TicTacToe { _UpdateSlides(); if (_Buttons[_ButtonBack].Selected) + { _PartyMode.Back(); + } if (_Buttons[_ButtonNext].Selected) + { _PartyMode.Next(); + } } if (mouseEvent.RB) + { _PartyMode.Back(); + } return true; } @@ -135,8 +144,10 @@ namespace VocaluxeLib.PartyModes.TicTacToe _SelectSlides[_SelectSlideNumFields].SelectedTag = _PartyMode.GameData.NumFields; _SelectSlides[_SelectSlideNumJockers].Clear(); - for (int i = 0; i <= 3; i++) + for (var i = 0; i <= 3; i++) + { _SelectSlides[_SelectSlideNumJockers].AddValue(i); + } _SelectSlides[_SelectSlideNumJockers].SelectedTag = _PartyMode.GameData.NumJockers; diff --git a/PartyModes/PartyModeTicTacToe/CPartyScreenTicTacToeMain.cs b/PartyModes/PartyModeTicTacToe/CPartyScreenTicTacToeMain.cs index 9f04452d..daf6d6e2 100644 --- a/PartyModes/PartyModeTicTacToe/CPartyScreenTicTacToeMain.cs +++ b/PartyModes/PartyModeTicTacToe/CPartyScreenTicTacToeMain.cs @@ -17,10 +17,8 @@ using System; using System.Collections.Generic; -using System.Linq; using System.Windows.Forms; using VocaluxeLib.Menu; -using VocaluxeLib.Songs; namespace VocaluxeLib.PartyModes.TicTacToe { @@ -71,7 +69,7 @@ namespace VocaluxeLib.PartyModes.TicTacToe private const string _StaticTeam2 = "StaticTeam2"; private readonly string[] _EqualizerTeam = new string[] - {"EqualizerTeam1", "EqualizerTeam2"}; + { "EqualizerTeam1", "EqualizerTeam2" }; private bool _ExitPopupVisible; @@ -97,12 +95,12 @@ namespace VocaluxeLib.PartyModes.TicTacToe base.Init(); _ThemeTexts = new string[] - {_TextPopupReallyExit, _TextTeamChoosing, _TextFinishMessage, _TextNextPlayerT1, _TextNextPlayerT2, _TextNextPlayerNameT1, _TextNextPlayerNameT2}; + { _TextPopupReallyExit, _TextTeamChoosing, _TextFinishMessage, _TextNextPlayerT1, _TextNextPlayerT2, _TextNextPlayerNameT1, _TextNextPlayerNameT2 }; _ThemeButtons = new string[] - { - _ButtonNextRound, _ButtonBack, _ButtonExit, _ButtonPopupYes, _ButtonPopupNo, _ButtonField, _ButtonJokerRandomT1, _ButtonJokerRandomT2, _ButtonJokerRetryT1, - _ButtonJokerRetryT2, _ButtonSwitchPlayerT1, _ButtonSwitchPlayerT2 - }; + { + _ButtonNextRound, _ButtonBack, _ButtonExit, _ButtonPopupYes, _ButtonPopupNo, _ButtonField, _ButtonJokerRandomT1, _ButtonJokerRandomT2, _ButtonJokerRetryT1, + _ButtonJokerRetryT2, _ButtonSwitchPlayerT1, _ButtonSwitchPlayerT2 + }; _ThemeStatics = new string[] { _StaticPopupBG, _StaticAvatarT1, _StaticAvatarT2, _StaticTeam1, _StaticTeam2 }; var texts = new List(); @@ -135,28 +133,48 @@ namespace VocaluxeLib.PartyModes.TicTacToe if (!_ExitPopupVisible) { if (_PartyMode.GameData.CurrentRoundNr == 1 && _Status != EStatus.FieldSelected) + { _Back(); + } else if (_Status == EStatus.None) + { _EndParty(); + } else + { _ShowPopup(true); + } } else + { _ShowPopup(false); + } + break; case Keys.Enter: if (!_ExitPopupVisible) { if (_Buttons[_ButtonNextRound].Selected) + { _NextRound(); + } + if (_Buttons[_ButtonBack].Selected && _PartyMode.GameData.CurrentRoundNr == 1 && _Status != EStatus.FieldSelected) + { _Back(); + } + if (_Buttons[_ButtonExit].Selected && (_PartyMode.GameData.CurrentRoundNr > 1 || _Status == EStatus.FieldSelected) && _Status != EStatus.None) + { _ShowPopup(true); + } else if (_Status == EStatus.None) + { _EndParty(); - for (int i = 0; i < _PartyMode.GameData.NumFields; i++) + } + + for (var i = 0; i < _PartyMode.GameData.NumFields; i++) { switch (_Status) { @@ -166,6 +184,7 @@ namespace VocaluxeLib.PartyModes.TicTacToe _PartyMode.GameData.FieldNr = i; _FieldSelected(); } + break; case EStatus.JokerRetry: @@ -174,35 +193,61 @@ namespace VocaluxeLib.PartyModes.TicTacToe _PartyMode.GameData.FieldNr = i; _FieldSelectedAgain(); } + break; } } + if (_Status == EStatus.FieldSelected) { if (_Buttons[_ButtonJokerRandomT1].Selected) + { _UseJoker(0, 0); + } + if (_Buttons[_ButtonJokerRandomT2].Selected) + { _UseJoker(1, 0); + } + if (_Buttons[_ButtonJokerRetryT1].Selected) + { _UseJoker(0, 1); + } + if (_Buttons[_ButtonJokerRetryT2].Selected) + { _UseJoker(1, 1); + } + if (_Buttons[_ButtonSwitchPlayerT1].Selected) + { _ChangePlayer(0, true); + } + if (_Buttons[_ButtonSwitchPlayerT2].Selected) + { _ChangePlayer(1, true); + } } } else { if (_Buttons[_ButtonPopupYes].Selected) + { _EndParty(); + } + if (_Buttons[_ButtonPopupNo].Selected) + { _ShowPopup(false); + } } + break; } } + return true; } @@ -215,17 +260,28 @@ namespace VocaluxeLib.PartyModes.TicTacToe if (!_ExitPopupVisible) { if (_Buttons[_ButtonNextRound].Selected) + { _NextRound(); + } + if (_Buttons[_ButtonBack].Selected) + { _Back(); + } + if (_Buttons[_ButtonExit].Selected) { if (_Status == EStatus.None) + { _EndParty(); + } else + { _ShowPopup(true); + } } - for (int i = 0; i < _PartyMode.GameData.NumFields; i++) + + for (var i = 0; i < _PartyMode.GameData.NumFields; i++) { switch (_Status) { @@ -235,6 +291,7 @@ namespace VocaluxeLib.PartyModes.TicTacToe _PartyMode.GameData.FieldNr = i; _FieldSelected(); } + break; case EStatus.JokerRetry: @@ -243,31 +300,55 @@ namespace VocaluxeLib.PartyModes.TicTacToe _PartyMode.GameData.FieldNr = i; _FieldSelectedAgain(); } + break; } } + if (_Status == EStatus.FieldSelected) { if (_Buttons[_ButtonJokerRandomT1].Selected) + { _UseJoker(0, 0); + } + if (_Buttons[_ButtonJokerRandomT2].Selected) + { _UseJoker(1, 0); + } + if (_Buttons[_ButtonJokerRetryT1].Selected) + { _UseJoker(0, 1); + } + if (_Buttons[_ButtonJokerRetryT2].Selected) + { _UseJoker(1, 1); + } + if (_Buttons[_ButtonSwitchPlayerT1].Selected) + { _ChangePlayer(0, true); + } + if (_Buttons[_ButtonSwitchPlayerT2].Selected) + { _ChangePlayer(1, true); + } } } else { if (_Buttons[_ButtonPopupYes].Selected) + { _EndParty(); + } + if (_Buttons[_ButtonPopupNo].Selected) + { _ShowPopup(false); + } } } @@ -276,14 +357,22 @@ namespace VocaluxeLib.PartyModes.TicTacToe if (!_ExitPopupVisible) { if (_PartyMode.GameData.CurrentRoundNr == 1 && _Status != EStatus.FieldSelected) + { _Back(); + } else if (_Status == EStatus.None) + { _EndParty(); + } else + { _ShowPopup(true); + } } else + { _ShowPopup(false); + } } if (mouseEvent.Wheel != 0) { } @@ -322,7 +411,7 @@ namespace VocaluxeLib.PartyModes.TicTacToe _UpdateFields(); _UpdateFieldContents(); - int winner = _GetWinner(); + var winner = _GetWinner(); if (_PartyMode.GameData.CurrentRoundNr <= _PartyMode.GameData.NumFields && winner == 0) { _UpdateTeamChoosingMessage(); @@ -354,14 +443,15 @@ namespace VocaluxeLib.PartyModes.TicTacToe if (winner > 0) { _Texts[_TextFinishMessage].Color = CBase.Themes.GetPlayerColor(winner); - _Texts[_TextFinishMessage].Text = CBase.Language.Translate("TR_SCREENMAIN_WINNER", PartyModeID) + " " + CBase.Language.Translate("TR_TEAM", PartyModeID) + " " + + _Texts[_TextFinishMessage].Text = CBase.Language.Translate("TR_SCREENMAIN_WINNER", PartyModeId) + " " + CBase.Language.Translate("TR_TEAM", PartyModeId) + " " + winner; } else { _Texts[_TextFinishMessage].Color = new SColorF(1, 1, 1, 1); - _Texts[_TextFinishMessage].Text = CBase.Language.Translate("TR_SCREENMAIN_NOWINNER", PartyModeID); + _Texts[_TextFinishMessage].Text = CBase.Language.Translate("TR_SCREENMAIN_NOWINNER", PartyModeId); } + _SelectElement(_Buttons[_ButtonExit]); } @@ -371,9 +461,11 @@ namespace VocaluxeLib.PartyModes.TicTacToe public override bool UpdateGame() { if (!_Equalizers[_EqualizerTeam[0]].Visible) + { return true; + } - for (int i = 0; i < 2; i++) + for (var i = 0; i < 2; i++) { CBase.Record.AnalyzeBuffer(i); _Equalizers["EqualizerTeam" + (i + 1)].Update(CBase.Record.ToneWeigth(i), CBase.Record.GetMaxVolume(i)); @@ -384,9 +476,9 @@ namespace VocaluxeLib.PartyModes.TicTacToe private void _CreateFields() { - for (int i = 0; i < 25; i++) + for (var i = 0; i < 25; i++) { - CButton f = GetNewButton(_Buttons[_ButtonField]); + var f = GetNewButton(_Buttons[_ButtonField]); f.Visible = false; _AddButton(f); _Fields.Add(f); @@ -396,16 +488,16 @@ namespace VocaluxeLib.PartyModes.TicTacToe private void _UpdateFields() { var numOneRow = (int)Math.Sqrt(_PartyMode.GameData.NumFields); - float fieldSizeY = ((float)CBase.Settings.GetRenderH() - 150 - numOneRow * _FieldSpace) / numOneRow; - float fieldSizeX = ((float)CBase.Settings.GetRenderW() - 300 - numOneRow * _FieldSpace) / numOneRow; + var fieldSizeY = ((float)CBase.Settings.GetRenderH() - 150 - numOneRow * _FieldSpace) / numOneRow; + var fieldSizeX = ((float)CBase.Settings.GetRenderW() - 300 - numOneRow * _FieldSpace) / numOneRow; _FieldSize = Math.Min(fieldSizeX, fieldSizeY); _FieldFirstX = (float)CBase.Settings.GetRenderW() / 2 - (numOneRow * _FieldSize + (numOneRow - 1) * _FieldSpace) / 2; _FieldFirstY = 140 + (CBase.Settings.GetRenderH() - 140) / 2 - (numOneRow * _FieldSize + numOneRow * _FieldSpace) / 2; - int row = 0; - int column = 0; - float x = _FieldFirstX; - float y = _FieldFirstY; - for (int i = 0; i < _Fields.Count; i++) + var row = 0; + var column = 0; + var x = _FieldFirstX; + var y = _FieldFirstY; + for (var i = 0; i < _Fields.Count; i++) { if (i < _PartyMode.GameData.NumFields) { @@ -416,7 +508,7 @@ namespace VocaluxeLib.PartyModes.TicTacToe _Fields[i].Visible = true; _Fields[i].Selectable = true; column++; - if ((i + 1) >= numOneRow * (row + 1)) + if (i + 1 >= numOneRow * (row + 1)) { column = 0; row++; @@ -424,7 +516,9 @@ namespace VocaluxeLib.PartyModes.TicTacToe x = _FieldFirstX; } else + { x = _FieldFirstX + _FieldSize * column + _FieldSpace * column; + } } else { @@ -436,7 +530,7 @@ namespace VocaluxeLib.PartyModes.TicTacToe private void _UpdateFieldContents() { - for (int i = 0; i < _PartyMode.GameData.Rounds.Count; i++) + for (var i = 0; i < _PartyMode.GameData.Rounds.Count; i++) { _Fields[i].Selectable = true; _Fields[i].Texture = _Buttons[_ButtonField].Texture; @@ -445,26 +539,34 @@ namespace VocaluxeLib.PartyModes.TicTacToe if (_PartyMode.GameData.Rounds[i].Finished) { _Fields[i].Selectable = false; - _Fields[i].Texture = CBase.Songs.GetSongByID(_PartyMode.GameData.Rounds[i].SongIDs[0]).CoverTextureBig; + _Fields[i].Texture = CBase.Songs.GetSongById(_PartyMode.GameData.Rounds[i].SongIds[0]).CoverTextureBig; _Fields[i].Color = CBase.Themes.GetPlayerColor(_PartyMode.GameData.Rounds[i].Winner); _Fields[i].SelColor = CBase.Themes.GetPlayerColor(_PartyMode.GameData.Rounds[i].Winner); } + if (_Status == EStatus.FieldSelected && _PartyMode.GameData.FieldNr == i) { - _Fields[i].Texture = CBase.Songs.GetSongByID(_PartyMode.GameData.Rounds[i].SongIDs[0]).CoverTextureBig; + _Fields[i].Texture = CBase.Songs.GetSongById(_PartyMode.GameData.Rounds[i].SongIds[0]).CoverTextureBig; _Fields[i].Color = new SColorF(1, 1, 1, 1); _Fields[i].SelColor = new SColorF(1, 1, 1, 1); _Fields[i].Selectable = false; } + if (_Status == EStatus.JokerRetry && _PartyMode.GameData.Rounds[i].Finished) { _Fields[i].SelColor = CBase.Themes.GetPlayerColor(_PartyMode.GameData.Team + 1); _Fields[i].Selectable = true; } + if (_Status == EStatus.JokerRetry && !_PartyMode.GameData.Rounds[i].Finished) + { _Fields[i].Selectable = false; + } + if (_Status == EStatus.FieldSelected) + { _Fields[i].Selectable = false; + } } } @@ -474,17 +576,18 @@ namespace VocaluxeLib.PartyModes.TicTacToe { _ChangePlayer(); } + _PartyMode.UpdateSongList(); - int[] songIDs = new int[_PartyMode.GameData.GameMode == EGameMode.TR_GAMEMODE_MEDLEY ? _PartyMode.GameData.NumMedleySongs : 1]; - for (int i = 0; i < songIDs.Length; i++) + var songIds = new int[_PartyMode.GameData.GameMode == EGameMode.TR_GAMEMODE_MEDLEY ? _PartyMode.GameData.NumMedleySongs : 1]; + for (var i = 0; i < songIds.Length; i++) { - songIDs[i] = _PartyMode.GameData.Songs[0]; + songIds[i] = _PartyMode.GameData.Songs[0]; _PartyMode.GameData.Songs.RemoveAt(0); } - _StartPreview(songIDs[0]); + _StartPreview(songIds[0]); _Status = EStatus.FieldSelected; - _PartyMode.GameData.Rounds[_PartyMode.GameData.FieldNr].SongIDs = songIDs; + _PartyMode.GameData.Rounds[_PartyMode.GameData.FieldNr].SongIds = songIds; _UpdateFieldContents(); _UpdateJokerButtons(); _UpdateSwitchPlayerButtons(); @@ -498,10 +601,10 @@ namespace VocaluxeLib.PartyModes.TicTacToe private void _FieldSelectedAgain() { - int[] songIDs = _PartyMode.GameData.Rounds[_OldSelectedField].SongIDs; - _StartPreview(songIDs[0]); + var songIds = _PartyMode.GameData.Rounds[_OldSelectedField].SongIds; + _StartPreview(songIds[0]); _Status = EStatus.FieldSelected; - _PartyMode.GameData.Rounds[_PartyMode.GameData.FieldNr].SongIDs = songIDs; + _PartyMode.GameData.Rounds[_PartyMode.GameData.FieldNr].SongIds = songIds; _PartyMode.GameData.Rounds[_PartyMode.GameData.FieldNr].SingerTeam1 = _PartyMode.GameData.Rounds[_OldSelectedField].SingerTeam1; _PartyMode.GameData.Rounds[_PartyMode.GameData.FieldNr].SingerTeam2 = _PartyMode.GameData.Rounds[_OldSelectedField].SingerTeam2; _UpdateFieldContents(); @@ -516,32 +619,31 @@ namespace VocaluxeLib.PartyModes.TicTacToe _SelectElement(_Buttons[_ButtonNextRound]); } - private void _StartPreview(int songID) + private void _StartPreview(int songId) { - CSong song = CBase.Songs.GetSongByID(songID); + var song = CBase.Songs.GetSongById(songId); CBase.BackgroundMusic.LoadPreview(song); } private int _GetRamdom(int max) { lock (syncLock) - { - return random.Next(max+1); + { + return random.Next(max + 1); } } private void _ChangePlayer(int teamNr = -1, bool next = false) { - - if (_PartyMode.GameData.ProfileIDsTeam1.Count > 0 && (teamNr == 0 || teamNr == -1)) + if (_PartyMode.GameData.ProfileIdsTeam1.Count > 0 && (teamNr == 0 || teamNr == -1)) { - idPlayer1 = _GetTeamPlayer(idPlayer1, _PartyMode.GameData.ProfileIDsTeam1.Count, next); + idPlayer1 = _GetTeamPlayer(idPlayer1, _PartyMode.GameData.ProfileIdsTeam1.Count, next); _PartyMode.GameData.Rounds[_PartyMode.GameData.FieldNr].SingerTeam1 = idPlayer1; } - if (_PartyMode.GameData.ProfileIDsTeam2.Count > 0 && (teamNr == 1 || teamNr == -1)) + if (_PartyMode.GameData.ProfileIdsTeam2.Count > 0 && (teamNr == 1 || teamNr == -1)) { - idPlayer2 = _GetTeamPlayer(idPlayer2, _PartyMode.GameData.ProfileIDsTeam2.Count, next); + idPlayer2 = _GetTeamPlayer(idPlayer2, _PartyMode.GameData.ProfileIdsTeam2.Count, next); _PartyMode.GameData.Rounds[_PartyMode.GameData.FieldNr].SingerTeam2 = idPlayer2; } @@ -553,15 +655,16 @@ namespace VocaluxeLib.PartyModes.TicTacToe if (next) { idPlayer++; - if (idPlayer >= _PartyMode.GameData.ProfileIDsTeam1.Count) + if (idPlayer >= _PartyMode.GameData.ProfileIdsTeam1.Count) { idPlayer = 0; } } else { - idPlayer = _GetRamdom(_PartyMode.GameData.ProfileIDsTeam1.Count - 1); + idPlayer = _GetRamdom(_PartyMode.GameData.ProfileIdsTeam1.Count - 1); } + return idPlayer; } @@ -572,13 +675,13 @@ namespace VocaluxeLib.PartyModes.TicTacToe _Texts[_TextNextPlayerNameT1].Visible = true; _Texts[_TextNextPlayerNameT2].Visible = true; _Texts[_TextNextPlayerNameT1].Text = - CBase.Profiles.GetPlayerName(_PartyMode.GameData.ProfileIDsTeam1[_PartyMode.GameData.Rounds[_PartyMode.GameData.FieldNr].SingerTeam1]); + CBase.Profiles.GetPlayerName(_PartyMode.GameData.ProfileIdsTeam1[_PartyMode.GameData.Rounds[_PartyMode.GameData.FieldNr].SingerTeam1]); _Texts[_TextNextPlayerNameT2].Text = - CBase.Profiles.GetPlayerName(_PartyMode.GameData.ProfileIDsTeam2[_PartyMode.GameData.Rounds[_PartyMode.GameData.FieldNr].SingerTeam2]); + CBase.Profiles.GetPlayerName(_PartyMode.GameData.ProfileIdsTeam2[_PartyMode.GameData.Rounds[_PartyMode.GameData.FieldNr].SingerTeam2]); _Statics[_StaticAvatarT1].Visible = true; _Statics[_StaticAvatarT2].Visible = true; - _Statics[_StaticAvatarT1].Texture = CBase.Profiles.GetAvatar(_PartyMode.GameData.ProfileIDsTeam1[_PartyMode.GameData.Rounds[_PartyMode.GameData.FieldNr].SingerTeam1]); - _Statics[_StaticAvatarT2].Texture = CBase.Profiles.GetAvatar(_PartyMode.GameData.ProfileIDsTeam2[_PartyMode.GameData.Rounds[_PartyMode.GameData.FieldNr].SingerTeam2]); + _Statics[_StaticAvatarT1].Texture = CBase.Profiles.GetAvatar(_PartyMode.GameData.ProfileIdsTeam1[_PartyMode.GameData.Rounds[_PartyMode.GameData.FieldNr].SingerTeam1]); + _Statics[_StaticAvatarT2].Texture = CBase.Profiles.GetAvatar(_PartyMode.GameData.ProfileIdsTeam2[_PartyMode.GameData.Rounds[_PartyMode.GameData.FieldNr].SingerTeam2]); _Statics[_StaticTeam1].Visible = true; _Statics[_StaticTeam2].Visible = true; _Equalizers[_EqualizerTeam[0]].Visible = true; @@ -596,6 +699,7 @@ namespace VocaluxeLib.PartyModes.TicTacToe _PartyMode.GameData.NumJokerRandom[teamNr]--; _FieldSelected(true); } + break; //Retry-Joker @@ -610,20 +714,26 @@ namespace VocaluxeLib.PartyModes.TicTacToe _UpdateFieldContents(); _Buttons[_ButtonNextRound].Visible = false; } + break; } + _UpdateJokerButtons(); } private void _UpdateTeamChoosingMessage() { _Texts[_TextTeamChoosing].Color = CBase.Themes.GetPlayerColor(_PartyMode.GameData.Team + 1); - _Texts[_TextTeamChoosing].Text = CBase.Language.Translate("TR_TEAM", PartyModeID) + " " + (_PartyMode.GameData.Team + 1) + "! " + - CBase.Language.Translate("TR_SCREENMAIN_TEAM_CHOOSE", PartyModeID); + _Texts[_TextTeamChoosing].Text = CBase.Language.Translate("TR_TEAM", PartyModeId) + " " + (_PartyMode.GameData.Team + 1) + "! " + + CBase.Language.Translate("TR_SCREENMAIN_TEAM_CHOOSE", PartyModeId); if (_Status == EStatus.JokerRetry || _Status == EStatus.FieldChoosing) + { _Texts[_TextTeamChoosing].Visible = true; + } else + { _Texts[_TextTeamChoosing].Visible = false; + } } private void _UpdateJokerButtons() @@ -649,7 +759,6 @@ namespace VocaluxeLib.PartyModes.TicTacToe _Buttons[_ButtonSwitchPlayerT1].Visible = true; _Buttons[_ButtonSwitchPlayerT2].Visible = true; } - } private void _NextRound() @@ -672,7 +781,9 @@ namespace VocaluxeLib.PartyModes.TicTacToe _Buttons[_ButtonPopupNo].Visible = _ExitPopupVisible; if (_ExitPopupVisible) + { _SelectElement(_Buttons[_ButtonPopupNo]); + } } private void _Back() @@ -683,51 +794,71 @@ namespace VocaluxeLib.PartyModes.TicTacToe private void _BuildWinnerPossibilities() { var numOneRow = (int)Math.Sqrt(_PartyMode.GameData.NumFields); - _Possibilities = new int[(numOneRow * 2) + 2, numOneRow]; - for (int i = 0; i < _Possibilities.GetLength(0); i++) + _Possibilities = new int[numOneRow * 2 + 2, numOneRow]; + for (var i = 0; i < _Possibilities.GetLength(0); i++) { if (i < numOneRow) { - for (int c = 0; c < numOneRow; c++) + for (var c = 0; c < numOneRow; c++) + { _Possibilities[i, c] = i * numOneRow + c; + } } else if (i < numOneRow * 2) { - for (int c = 0; c < numOneRow; c++) - _Possibilities[i, c] = (i - numOneRow) + (c * numOneRow); + for (var c = 0; c < numOneRow; c++) + { + _Possibilities[i, c] = i - numOneRow + c * numOneRow; + } } else if (i == _Possibilities.GetLength(0) - 2) { - for (int c = 0; c < numOneRow; c++) + for (var c = 0; c < numOneRow; c++) + { _Possibilities[i, c] = (numOneRow + 1) * c; + } } else if (i == _Possibilities.GetLength(0) - 1) { - for (int c = 0; c < numOneRow; c++) + for (var c = 0; c < numOneRow; c++) + { _Possibilities[i, c] = (numOneRow - 1) * c + (numOneRow - 1); + } } } } private int _GetWinner() { - for (int i = 0; i < _Possibilities.GetLength(0); i++) + for (var i = 0; i < _Possibilities.GetLength(0); i++) { var check = new List(); - for (int j = 0; j < _Possibilities.GetLength(1); j++) + for (var j = 0; j < _Possibilities.GetLength(1); j++) { if (_PartyMode.GameData.Rounds[_Possibilities[i, j]].Winner > 0) + { check.Add(_PartyMode.GameData.Rounds[_Possibilities[i, j]].Winner); + } } + if (check.Count != _Possibilities.GetLength(1)) + { continue; + } + //Check for winner if (check.Contains(1) && !check.Contains(2)) + { return 1; + } + if (check.Contains(2) && !check.Contains(1)) + { return 2; + } } + return 0; } } -} +} \ No newline at end of file diff --git a/PartyModes/PartyModeTicTacToe/CPartyScreenTicTacToeNames.cs b/PartyModes/PartyModeTicTacToe/CPartyScreenTicTacToeNames.cs index 875000e7..c4235b39 100644 --- a/PartyModes/PartyModeTicTacToe/CPartyScreenTicTacToeNames.cs +++ b/PartyModes/PartyModeTicTacToe/CPartyScreenTicTacToeNames.cs @@ -17,14 +17,13 @@ using System; using System.Collections.Generic; -using System.Linq; using VocaluxeLib.Menu; namespace VocaluxeLib.PartyModes.TicTacToe { // ReSharper disable UnusedMember.Global public class CPartyScreenTicTacToeNames : CMenuPartyNameSelection - // ReSharper restore UnusedMember.Global + // ReSharper restore UnusedMember.Global { // Version number for theme files. Increment it, if you've changed something on the theme files! protected override int _ScreenVersion @@ -44,14 +43,19 @@ namespace VocaluxeLib.PartyModes.TicTacToe { base.OnShow(); - while (_PartyMode.GameData.ProfileIDsTeam1.Count > _PartyMode.GameData.NumPlayerTeam1) - _PartyMode.GameData.ProfileIDsTeam1.RemoveAt(_PartyMode.GameData.ProfileIDsTeam1.Count - 1); - while (_PartyMode.GameData.ProfileIDsTeam2.Count > _PartyMode.GameData.NumPlayerTeam2) - _PartyMode.GameData.ProfileIDsTeam2.RemoveAt(_PartyMode.GameData.ProfileIDsTeam2.Count - 1); + while (_PartyMode.GameData.ProfileIdsTeam1.Count > _PartyMode.GameData.NumPlayerTeam1) + { + _PartyMode.GameData.ProfileIdsTeam1.RemoveAt(_PartyMode.GameData.ProfileIdsTeam1.Count - 1); + } + + while (_PartyMode.GameData.ProfileIdsTeam2.Count > _PartyMode.GameData.NumPlayerTeam2) + { + _PartyMode.GameData.ProfileIdsTeam2.RemoveAt(_PartyMode.GameData.ProfileIdsTeam2.Count - 1); + } SetPartyModeData(2, _PartyMode.GameData.NumPlayerTeam1 + _PartyMode.GameData.NumPlayerTeam2, - new int[] {_PartyMode.GameData.NumPlayerTeam1, _PartyMode.GameData.NumPlayerTeam2}); - List[] ids = new List[] {_PartyMode.GameData.ProfileIDsTeam1, _PartyMode.GameData.ProfileIDsTeam2}; + new int[] { _PartyMode.GameData.NumPlayerTeam1, _PartyMode.GameData.NumPlayerTeam2 }); + var ids = new List[] { _PartyMode.GameData.ProfileIdsTeam1, _PartyMode.GameData.ProfileIdsTeam2 }; SetPartyModeProfiles(ids); } @@ -59,14 +63,16 @@ namespace VocaluxeLib.PartyModes.TicTacToe { if (_TeamList.Length == 2) { - _PartyMode.GameData.ProfileIDsTeam1 = _TeamList[0]; - _PartyMode.GameData.ProfileIDsTeam2 = _TeamList[1]; + _PartyMode.GameData.ProfileIdsTeam1 = _TeamList[0]; + _PartyMode.GameData.ProfileIdsTeam2 = _TeamList[1]; } + if (_NumPlayerTeams.Length == 2) { _PartyMode.GameData.NumPlayerTeam1 = _NumPlayerTeams[0]; _PartyMode.GameData.NumPlayerTeam2 = _NumPlayerTeams[1]; } + _PartyMode.Back(); } @@ -74,13 +80,14 @@ namespace VocaluxeLib.PartyModes.TicTacToe { if (_TeamList.Length == 2) { - _PartyMode.GameData.ProfileIDsTeam1 = _TeamList[0]; - _PartyMode.GameData.ProfileIDsTeam2 = _TeamList[1]; + _PartyMode.GameData.ProfileIdsTeam1 = _TeamList[0]; + _PartyMode.GameData.ProfileIdsTeam2 = _TeamList[1]; } - _PartyMode.GameData.NumPlayerTeam1 = _PartyMode.GameData.ProfileIDsTeam1.Count; - _PartyMode.GameData.NumPlayerTeam2 = _PartyMode.GameData.ProfileIDsTeam2.Count; + + _PartyMode.GameData.NumPlayerTeam1 = _PartyMode.GameData.ProfileIdsTeam1.Count; + _PartyMode.GameData.NumPlayerTeam2 = _PartyMode.GameData.ProfileIdsTeam2.Count; _PartyMode.Next(); } } -} +} \ No newline at end of file diff --git a/PartyModes/PartyModeTicTacToe/CPartyScreenTicTacToeSongs.cs b/PartyModes/PartyModeTicTacToe/CPartyScreenTicTacToeSongs.cs index a899cc61..98bdf504 100644 --- a/PartyModes/PartyModeTicTacToe/CPartyScreenTicTacToeSongs.cs +++ b/PartyModes/PartyModeTicTacToe/CPartyScreenTicTacToeSongs.cs @@ -15,7 +15,6 @@ // along with Vocaluxe. If not, see . #endregion -using System.Collections.Generic; using VocaluxeLib.Menu; namespace VocaluxeLib.PartyModes.TicTacToe @@ -40,7 +39,7 @@ namespace VocaluxeLib.PartyModes.TicTacToe Source = _PartyMode.GameData.SongSource; Sorting = _PartyMode.GameData.Sorting; Category = _PartyMode.GameData.CategoryIndex; - Playlist = _PartyMode.GameData.PlaylistID; + Playlist = _PartyMode.GameData.PlaylistId; SongMode = _PartyMode.GameData.GameMode; NumMedleySongs = _PartyMode.GameData.NumMedleySongs; @@ -76,9 +75,9 @@ namespace VocaluxeLib.PartyModes.TicTacToe _PartyMode.GameData.SongSource = Source; _PartyMode.GameData.Sorting = Sorting; _PartyMode.GameData.CategoryIndex = Category; - _PartyMode.GameData.PlaylistID = Playlist; + _PartyMode.GameData.PlaylistId = Playlist; _PartyMode.GameData.GameMode = SongMode; _PartyMode.GameData.NumMedleySongs = NumMedleySongs; } } -} +} \ No newline at end of file diff --git a/PartyModes/PartyModeTicTacToe/PartyModeTicTacToe.csproj b/PartyModes/PartyModeTicTacToe/PartyModeTicTacToe.csproj index 29711ae2..df23bd6d 100644 --- a/PartyModes/PartyModeTicTacToe/PartyModeTicTacToe.csproj +++ b/PartyModes/PartyModeTicTacToe/PartyModeTicTacToe.csproj @@ -27,6 +27,7 @@ Off ..\..\CheckingRules.ruleset false + 9.0 AnyCPU @@ -40,6 +41,7 @@ Off false true + 9.0 AnyCPU @@ -52,6 +54,7 @@ 4 Off false + 9.0 AnyCPU @@ -65,6 +68,7 @@ Off false true + 9.0 bin @@ -78,6 +82,7 @@ false pdbonly true + 9.0 @@ -119,4 +124,4 @@ rm -f "$(SolutionDir)Output\PartyModes\$(TargetName)\Code\GlobalSuppressions.cs" --> - + \ No newline at end of file diff --git a/Tests/PartyModeChallenge/CPartyModeChallangeTest.cs b/Tests/PartyModeChallenge/CPartyModeChallangeTest.cs index 507df1c6..d74c17a1 100644 --- a/Tests/PartyModeChallenge/CPartyModeChallangeTest.cs +++ b/Tests/PartyModeChallenge/CPartyModeChallangeTest.cs @@ -20,9 +20,7 @@ using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Vocaluxe.Base; -using Vocaluxe.Reporting; using VocaluxeLib; -using VocaluxeLib.Log; using VocaluxeLib.PartyModes.Challenge; namespace Tests.PartyModeChallenge @@ -31,20 +29,19 @@ namespace Tests.PartyModeChallenge public class CPartyModeChallangeTest { #region Tests - [Test] public void TestRoundBoundaries() { // ReSharper disable ObjectCreationAsStatement new CChallengeRounds(1, 1, 1); // Should succeed // ReSharper restore ObjectCreationAsStatement - for (int inv = -1; inv <= 0; inv++) + for (var inv = -1; inv <= 0; inv++) { - int invL = inv; + var invL = inv; // ReSharper disable ObjectCreationAsStatement - Assert.Throws(() => new CChallengeRounds(invL, 1, 1)); - Assert.Throws(() => new CChallengeRounds(1, invL, 1)); - Assert.Throws(() => new CChallengeRounds(1, 1, invL)); + Assert.Throws(new Action(() => new CChallengeRounds(invL, 1, 1))); + Assert.Throws(new Action(() => new CChallengeRounds(1, invL, 1))); + Assert.Throws(new Action(() => new CChallengeRounds(1, 1, invL))); // ReSharper restore ObjectCreationAsStatement } } @@ -54,36 +51,38 @@ namespace Tests.PartyModeChallenge { CBase.Game = new CBGame(); - int roundFactor = (numPlayer % numMic == 0) ? numPlayer / numMic : numPlayer; - for (int numRounds = roundFactor; numRounds <= 100 && numRounds <= roundFactor * 5; numRounds += roundFactor) + var roundFactor = numPlayer % numMic == 0 ? numPlayer / numMic : numPlayer; + for (var numRounds = roundFactor; numRounds <= 100 && numRounds <= roundFactor * 5; numRounds += roundFactor) { - CChallengeRounds rounds = new CChallengeRounds(numRounds, numPlayer, numMic); - Assert.IsTrue(rounds.Count >= numRounds); + var rounds = new CChallengeRounds(numRounds, numPlayer, numMic); + Assert.That(rounds.Count >= numRounds, Is.True); _CheckRounds(rounds, numPlayer); - Assert.That(rounds.Count, Is.GreaterThanOrEqualTo(numRounds), + Assert.That(rounds.Count, Is.GreaterThanOrEqualTo(numRounds), $"Number of rounds should be >= {numRounds}, is {rounds.Count} for {numPlayer}/{numMic}"); } } - #endregion #region Helper methods private static void _CheckRounds(CChallengeRounds rounds, int numPlayer) { - List numSongs = new List(numPlayer); - for (int i = 0; i < numPlayer; i++) - numSongs.Add(0); - for (int i = 0; i < rounds.Count; i++) + var numSongs = new List(numPlayer); + for (var i = 0; i < numPlayer; i++) { - foreach (int player in rounds[i].Players) + numSongs.Add(0); + } + + for (var i = 0; i < rounds.Count; i++) + { + foreach (var player in rounds[i].Players) { - Assert.IsTrue(player >= 0 && player < numPlayer); + Assert.That(player >= 0 && player < numPlayer, Is.True); numSongs[player]++; } } - Assert.IsTrue(numSongs.Min() == numSongs.Max(), "Some players have more songs than others"); - } + Assert.That(numSongs.Min() == numSongs.Max(), Is.True, "Some players have more songs than others"); + } #endregion } -} +} \ No newline at end of file diff --git a/Tests/Properties/AssemblyInfo.cs b/Tests/Properties/AssemblyInfo.cs index bb5ab59a..ec32fc9f 100644 --- a/Tests/Properties/AssemblyInfo.cs +++ b/Tests/Properties/AssemblyInfo.cs @@ -1,5 +1,4 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -30,4 +29,4 @@ using System.Runtime.InteropServices; // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/Tests/Tests.csproj b/Tests/Tests.csproj index 2bb83943..45cfb32f 100644 --- a/Tests/Tests.csproj +++ b/Tests/Tests.csproj @@ -28,6 +28,7 @@ prompt 4 x86 + 9.0 pdbonly @@ -37,6 +38,7 @@ prompt 4 x86 + 9.0 true @@ -47,6 +49,7 @@ prompt 4 x64 + 9.0 pdbonly @@ -56,14 +59,15 @@ prompt 4 x64 + 9.0 - - + + @@ -117,4 +121,4 @@ --> - + \ No newline at end of file diff --git a/Tests/VocaluxeLib/Log/CBenchmarkTest.cs b/Tests/VocaluxeLib/Log/CBenchmarkTest.cs index 54d92fa7..90e33838 100644 --- a/Tests/VocaluxeLib/Log/CBenchmarkTest.cs +++ b/Tests/VocaluxeLib/Log/CBenchmarkTest.cs @@ -15,7 +15,6 @@ // along with Vocaluxe. If not, see . #endregion -using System; using System.IO; using NUnit.Framework; using VocaluxeLib.Log; @@ -28,7 +27,6 @@ namespace Tests.VocaluxeLib.Log private string _TestFolder; #region Setup methods - [SetUp] public void SetUp() { @@ -40,18 +38,16 @@ namespace Tests.VocaluxeLib.Log { Directory.Delete(_TestFolder, true); } - #endregion #region Tests - [Test] public void BenchmarkTimeTest() { const string testMessage = "BenchmarkTime Test"; - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); const string versionTag = "Test Version (1.2.4)"; // Init Log @@ -68,59 +64,59 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains($"[Information] Started \"{ testMessage }\"", mainLogContent, "Start entry wrong"); - StringAssert.Contains($"[Information] Finished \"{ testMessage }\" successfully in ", mainLogContent, "Finish entry wrong"); - StringAssert.AreEqualIgnoringCase("", songLogContent, "Benchmark should not create song log entries"); + Assert.That(mainLogContent, Contains.Substring($"[Information] Started \"{testMessage}\""), "Start entry wrong"); + Assert.That(mainLogContent, Contains.Substring($"[Information] Finished \"{testMessage}\" successfully in "), "Finish entry wrong"); + Assert.That(songLogContent, Is.Empty, "Benchmark should not create song log entries"); } [Test] public void BenchmarkBeginTest() { const string testMessage = "BenchmarkBegin Test"; - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); const string versionTag = "Test Version (1.2.4)"; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => { Assert.Fail("Benchmarks should not show the reporter."); }, ELogLevel.Verbose); - + using (var token = CBenchmark.Begin(testMessage)) { System.Threading.Thread.Sleep(1); token.End(); } - + // Close logfile CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains($"[Information] Started \"{ testMessage }\"", mainLogContent, "Start entry wrong"); - StringAssert.Contains($"[Information] Finished \"{ testMessage }\" successfully in ", mainLogContent, "Finish entry wrong"); - StringAssert.AreEqualIgnoringCase("", songLogContent, "Benchmark should not create song log entries"); + Assert.That(mainLogContent, Contains.Substring($"[Information] Started \"{testMessage}\""), "Start entry wrong"); + Assert.That(mainLogContent, Contains.Substring($"[Information] Finished \"{testMessage}\" successfully in "), "Finish entry wrong"); + Assert.That(songLogContent, Is.Empty, "Benchmark should not create song log entries"); } [Test] public void BenchmarkBeginWithoutEndTest() { const string testMessage = "BenchmarkBegin Test"; - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); const string versionTag = "Test Version (1.2.4)"; // Init Log @@ -137,28 +133,25 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains($"[Information] Started \"{ testMessage }\"", mainLogContent, "Start entry wrong"); - StringAssert.Contains($"[Information] Failed \"{ testMessage }\" in ", mainLogContent, "Finish entry wrong"); - StringAssert.AreEqualIgnoringCase("", songLogContent, "Benchmark should not create song log entries"); + Assert.That(mainLogContent, Contains.Substring($"[Information] Started \"{testMessage}\""), "Start entry wrong"); + Assert.That(mainLogContent, Contains.Substring($"[Information] Failed \"{testMessage}\" in "), "Finish entry wrong"); + Assert.That(songLogContent, Is.Empty, "Benchmark should not create song log entries"); } - #endregion #region Helper methods - private string _GetTemporaryDirectory() { - string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(tempDirectory); return tempDirectory; } - #endregion } -} +} \ No newline at end of file diff --git a/Tests/VocaluxeLib/Log/CLogTest.cs b/Tests/VocaluxeLib/Log/CLogTest.cs index 48eb5b84..106d3d7f 100644 --- a/Tests/VocaluxeLib/Log/CLogTest.cs +++ b/Tests/VocaluxeLib/Log/CLogTest.cs @@ -34,7 +34,6 @@ namespace Tests.VocaluxeLib.Log private string _TestFolder; #region Setup methods - [SetUp] public void SetUp() { @@ -46,39 +45,36 @@ namespace Tests.VocaluxeLib.Log { Directory.Delete(_TestFolder, true); } - #endregion #region Tests - #region Verbose tests - [Test] public void VerboseTestWithDataWithException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Verbose] " + _TestMessageWithResolvedData, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Verbose] " + _TestMessageWithResolvedData), "Main log entry wrong"); - StringAssert.Contains(_TestMessageWithResolvedData, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessageWithResolvedData), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Verbose(new Exception(_TestExceptionMessage), _TestMessageWithData, CLog.Params(_FirstParam, _SecondParam), show); @@ -88,50 +84,50 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Verbose] " +_TestMessageWithResolvedData, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_TestExceptionMessage, mainLogContent, "Exception is missing"); - StringAssert.Contains(_SecondParam, mainLogContent, "Second data field is missing"); - StringAssert.Contains(_TestMessageWithResolvedData, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Verbose] " + _TestMessageWithResolvedData), "Main log entry wrong"); + Assert.That(mainLogContent, Contains.Substring(_TestExceptionMessage), "Exception is missing"); + Assert.That(mainLogContent, Contains.Substring(_SecondParam), "Second data field is missing"); + Assert.That(songLogContent, Contains.Substring(_TestMessageWithResolvedData), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } [Test] public void VerboseTestWithDataWithoutException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Verbose] " + _TestMessageWithResolvedData, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Verbose] " + _TestMessageWithResolvedData), "Main log entry wrong"); - StringAssert.Contains(_TestMessageWithResolvedData, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessageWithResolvedData), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Verbose(_TestMessageWithData, CLog.Params(_FirstParam, _SecondParam), show); @@ -141,49 +137,49 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Verbose] " +_TestMessageWithResolvedData, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_SecondParam, mainLogContent, "Second data field is missing"); - StringAssert.Contains(_TestMessageWithResolvedData, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Verbose] " + _TestMessageWithResolvedData), "Main log entry wrong"); + Assert.That(mainLogContent, Contains.Substring(_SecondParam), "Second data field is missing"); + Assert.That(songLogContent, Contains.Substring(_TestMessageWithResolvedData), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } [Test] public void VerboseTestWithoutDataWithException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Verbose] " + _TestMessage, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Verbose] " + _TestMessage), "Main log entry wrong"); - StringAssert.Contains(_TestMessage, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessage), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Verbose(new Exception(_TestExceptionMessage), _TestMessage, show); @@ -193,49 +189,49 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Verbose] " +_TestMessage, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_TestExceptionMessage, mainLogContent, "Exception is missing"); - StringAssert.Contains(_TestMessage, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Verbose] " + _TestMessage), "Main log entry wrong"); + Assert.That(mainLogContent, Contains.Substring(_TestExceptionMessage), "Exception is missing"); + Assert.That(songLogContent, Contains.Substring(_TestMessage), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } [Test] public void VerboseTestWithoutDataWithoutException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Verbose] " + _TestMessage, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Verbose] " + _TestMessage), "Main log entry wrong"); - StringAssert.Contains(_TestMessage, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessage), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Verbose(_TestMessage, show); @@ -245,51 +241,50 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Verbose] " +_TestMessage, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_TestMessage, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Verbose] " + _TestMessage), "Main log entry wrong"); + Assert.That(songLogContent, Contains.Substring(_TestMessage), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } - #endregion - #region Debug tests + #region Debug tests [Test] public void DebugTestWithDataWithException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Debug] " + _TestMessageWithResolvedData, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Debug] " + _TestMessageWithResolvedData), "Main log entry wrong"); - StringAssert.Contains(_TestMessageWithResolvedData, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessageWithResolvedData), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Debug(new Exception(_TestExceptionMessage), _TestMessageWithData, CLog.Params(_FirstParam, _SecondParam), show); @@ -299,50 +294,50 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Debug] " +_TestMessageWithResolvedData, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_TestExceptionMessage, mainLogContent, "Exception is missing"); - StringAssert.Contains(_SecondParam, mainLogContent, "Second data field is missing"); - StringAssert.Contains(_TestMessageWithResolvedData, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Debug] " + _TestMessageWithResolvedData), "Main log entry wrong"); + Assert.That(mainLogContent, Contains.Substring(_TestExceptionMessage), "Exception is missing"); + Assert.That(mainLogContent, Contains.Substring(_SecondParam), "Second data field is missing"); + Assert.That(songLogContent, Contains.Substring(_TestMessageWithResolvedData), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } [Test] public void DebugTestWithDataWithoutException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Debug] " + _TestMessageWithResolvedData, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Debug] " + _TestMessageWithResolvedData), "Main log entry wrong"); - StringAssert.Contains(_TestMessageWithResolvedData, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessageWithResolvedData), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Debug(_TestMessageWithData, CLog.Params(_FirstParam, _SecondParam), show); @@ -352,49 +347,49 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Debug] " +_TestMessageWithResolvedData, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_SecondParam, mainLogContent, "Second data field is missing"); - StringAssert.Contains(_TestMessageWithResolvedData, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Debug] " + _TestMessageWithResolvedData), "Main log entry wrong"); + Assert.That(mainLogContent, Contains.Substring(_SecondParam), "Second data field is missing"); + Assert.That(songLogContent, Contains.Substring(_TestMessageWithResolvedData), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } [Test] public void DebugTestWithoutDataWithException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Debug] " + _TestMessage, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Debug] " + _TestMessage), "Main log entry wrong"); - StringAssert.Contains(_TestMessage, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessage), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Debug(new Exception(_TestExceptionMessage), _TestMessage, show); @@ -404,49 +399,49 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Debug] " +_TestMessage, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_TestExceptionMessage, mainLogContent, "Exception is missing"); - StringAssert.Contains(_TestMessage, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Debug] " + _TestMessage), "Main log entry wrong"); + Assert.That(mainLogContent, Contains.Substring(_TestExceptionMessage), "Exception is missing"); + Assert.That(songLogContent, Contains.Substring(_TestMessage), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } [Test] public void DebugTestWithoutDataWithoutException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Debug] " + _TestMessage, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Debug] " + _TestMessage), "Main log entry wrong"); - StringAssert.Contains(_TestMessage, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessage), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Debug(_TestMessage, show); @@ -456,51 +451,50 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Debug] " +_TestMessage, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_TestMessage, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Debug] " + _TestMessage), "Main log entry wrong"); + Assert.That(songLogContent, Contains.Substring(_TestMessage), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } - #endregion - #region Information tests + #region Information tests [Test] public void InformationTestWithDataWithException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Information] " + _TestMessageWithResolvedData, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Information] " + _TestMessageWithResolvedData), "Main log entry wrong"); - StringAssert.Contains(_TestMessageWithResolvedData, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessageWithResolvedData), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Information(new Exception(_TestExceptionMessage), _TestMessageWithData, CLog.Params(_FirstParam, _SecondParam), show); @@ -510,50 +504,50 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Information] " +_TestMessageWithResolvedData, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_TestExceptionMessage, mainLogContent, "Exception is missing"); - StringAssert.Contains(_SecondParam, mainLogContent, "Second data field is missing"); - StringAssert.Contains(_TestMessageWithResolvedData, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Information] " + _TestMessageWithResolvedData), "Main log entry wrong"); + Assert.That(mainLogContent, Contains.Substring(_TestExceptionMessage), "Exception is missing"); + Assert.That(mainLogContent, Contains.Substring(_SecondParam), "Second data field is missing"); + Assert.That(songLogContent, Contains.Substring(_TestMessageWithResolvedData), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } [Test] public void InformationTestWithDataWithoutException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Information] " + _TestMessageWithResolvedData, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Information] " + _TestMessageWithResolvedData), "Main log entry wrong"); - StringAssert.Contains(_TestMessageWithResolvedData, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessageWithResolvedData), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Information(_TestMessageWithData, CLog.Params(_FirstParam, _SecondParam), show); @@ -563,49 +557,49 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Information] " +_TestMessageWithResolvedData, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_SecondParam, mainLogContent, "Second data field is missing"); - StringAssert.Contains(_TestMessageWithResolvedData, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Information] " + _TestMessageWithResolvedData), "Main log entry wrong"); + Assert.That(mainLogContent, Contains.Substring(_SecondParam), "Second data field is missing"); + Assert.That(songLogContent, Contains.Substring(_TestMessageWithResolvedData), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } [Test] public void InformationTestWithoutDataWithException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Information] " + _TestMessage, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Information] " + _TestMessage), "Main log entry wrong"); - StringAssert.Contains(_TestMessage, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessage), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Information(new Exception(_TestExceptionMessage), _TestMessage, show); @@ -615,49 +609,49 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Information] " +_TestMessage, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_TestExceptionMessage, mainLogContent, "Exception is missing"); - StringAssert.Contains(_TestMessage, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Information] " + _TestMessage), "Main log entry wrong"); + Assert.That(mainLogContent, Contains.Substring(_TestExceptionMessage), "Exception is missing"); + Assert.That(songLogContent, Contains.Substring(_TestMessage), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } [Test] public void InformationTestWithoutDataWithoutException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Information] " + _TestMessage, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Information] " + _TestMessage), "Main log entry wrong"); - StringAssert.Contains(_TestMessage, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessage), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Information(_TestMessage, show); @@ -667,51 +661,50 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Information] " +_TestMessage, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_TestMessage, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Information] " + _TestMessage), "Main log entry wrong"); + Assert.That(songLogContent, Contains.Substring(_TestMessage), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } - #endregion - #region Warning tests + #region Warning tests [Test] public void WarningTestWithDataWithException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Warning] " + _TestMessageWithResolvedData, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Warning] " + _TestMessageWithResolvedData), "Main log entry wrong"); - StringAssert.Contains(_TestMessageWithResolvedData, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessageWithResolvedData), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Warning(new Exception(_TestExceptionMessage), _TestMessageWithData, CLog.Params(_FirstParam, _SecondParam), show); @@ -721,50 +714,50 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Warning] " +_TestMessageWithResolvedData, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_TestExceptionMessage, mainLogContent, "Exception is missing"); - StringAssert.Contains(_SecondParam, mainLogContent, "Second data field is missing"); - StringAssert.Contains(_TestMessageWithResolvedData, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Warning] " + _TestMessageWithResolvedData), "Main log entry wrong"); + Assert.That(mainLogContent, Contains.Substring(_TestExceptionMessage), "Exception is missing"); + Assert.That(mainLogContent, Contains.Substring(_SecondParam), "Second data field is missing"); + Assert.That(songLogContent, Contains.Substring(_TestMessageWithResolvedData), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } [Test] public void WarningTestWithDataWithoutException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Warning] " + _TestMessageWithResolvedData, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Warning] " + _TestMessageWithResolvedData), "Main log entry wrong"); - StringAssert.Contains(_TestMessageWithResolvedData, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessageWithResolvedData), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Warning(_TestMessageWithData, CLog.Params(_FirstParam, _SecondParam), show); @@ -774,49 +767,49 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Warning] " +_TestMessageWithResolvedData, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_SecondParam, mainLogContent, "Second data field is missing"); - StringAssert.Contains(_TestMessageWithResolvedData, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Warning] " + _TestMessageWithResolvedData), "Main log entry wrong"); + Assert.That(mainLogContent, Contains.Substring(_SecondParam), "Second data field is missing"); + Assert.That(songLogContent, Contains.Substring(_TestMessageWithResolvedData), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } [Test] public void WarningTestWithoutDataWithException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Warning] " + _TestMessage, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Warning] " + _TestMessage), "Main log entry wrong"); - StringAssert.Contains(_TestMessage, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessage), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Warning(new Exception(_TestExceptionMessage), _TestMessage, show); @@ -826,49 +819,49 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Warning] " +_TestMessage, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_TestExceptionMessage, mainLogContent, "Exception is missing"); - StringAssert.Contains(_TestMessage, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Warning] " + _TestMessage), "Main log entry wrong"); + Assert.That(mainLogContent, Contains.Substring(_TestExceptionMessage), "Exception is missing"); + Assert.That(songLogContent, Contains.Substring(_TestMessage), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } [Test] public void WarningTestWithoutDataWithoutException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Warning] " + _TestMessage, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Warning] " + _TestMessage), "Main log entry wrong"); - StringAssert.Contains(_TestMessage, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessage), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Warning(_TestMessage, show); @@ -878,51 +871,50 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Warning] " +_TestMessage, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_TestMessage, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Warning] " + _TestMessage), "Main log entry wrong"); + Assert.That(songLogContent, Contains.Substring(_TestMessage), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } - #endregion - #region Error tests + #region Error tests [Test] public void ErrorTestWithDataWithException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Error] " + _TestMessageWithResolvedData, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Error] " + _TestMessageWithResolvedData), "Main log entry wrong"); - StringAssert.Contains(_TestMessageWithResolvedData, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessageWithResolvedData), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Error(new Exception(_TestExceptionMessage), _TestMessageWithData, CLog.Params(_FirstParam, _SecondParam), show); @@ -932,50 +924,50 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Error] " +_TestMessageWithResolvedData, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_TestExceptionMessage, mainLogContent, "Exception is missing"); - StringAssert.Contains(_SecondParam, mainLogContent, "Second data field is missing"); - StringAssert.Contains(_TestMessageWithResolvedData, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Error] " + _TestMessageWithResolvedData), "Main log entry wrong"); + Assert.That(mainLogContent, Contains.Substring(_TestExceptionMessage), "Exception is missing"); + Assert.That(mainLogContent, Contains.Substring(_SecondParam), "Second data field is missing"); + Assert.That(songLogContent, Contains.Substring(_TestMessageWithResolvedData), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } [Test] public void ErrorTestWithDataWithoutException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Error] " + _TestMessageWithResolvedData, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Error] " + _TestMessageWithResolvedData), "Main log entry wrong"); - StringAssert.Contains(_TestMessageWithResolvedData, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessageWithResolvedData), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Error(_TestMessageWithData, CLog.Params(_FirstParam, _SecondParam), show); @@ -985,49 +977,49 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Error] " +_TestMessageWithResolvedData, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_SecondParam, mainLogContent, "Second data field is missing"); - StringAssert.Contains(_TestMessageWithResolvedData, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Error] " + _TestMessageWithResolvedData), "Main log entry wrong"); + Assert.That(mainLogContent, Contains.Substring(_SecondParam), "Second data field is missing"); + Assert.That(songLogContent, Contains.Substring(_TestMessageWithResolvedData), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } [Test] public void ErrorTestWithoutDataWithException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Error] " + _TestMessage, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Error] " + _TestMessage), "Main log entry wrong"); - StringAssert.Contains(_TestMessage, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessage), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Error(new Exception(_TestExceptionMessage), _TestMessage, show); @@ -1037,49 +1029,49 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Error] " +_TestMessage, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_TestExceptionMessage, mainLogContent, "Exception is missing"); - StringAssert.Contains(_TestMessage, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Error] " + _TestMessage), "Main log entry wrong"); + Assert.That(mainLogContent, Contains.Substring(_TestExceptionMessage), "Exception is missing"); + Assert.That(songLogContent, Contains.Substring(_TestMessage), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } [Test] public void ErrorTestWithoutDataWithoutException([Values(true, false)] bool show) { - string testFileName = Path.GetRandomFileName(); - string testFileSongName = Path.GetRandomFileName(); - string testFileMarkerName = Path.GetRandomFileName(); - string versionTag = "Test Version (1.2.4)"; - bool messageShown = false; + var testFileName = Path.GetRandomFileName(); + var testFileSongName = Path.GetRandomFileName(); + var testFileMarkerName = Path.GetRandomFileName(); + var versionTag = "Test Version (1.2.4)"; + var messageShown = false; // Init Log CLog.Init(_TestFolder, testFileName, testFileSongName, testFileMarkerName, versionTag, (crash, cont, tag, log, error) => - { - messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + { + messageShown = true; + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[Error] " + _TestMessage, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[Error] " + _TestMessage), "Main log entry wrong"); - StringAssert.Contains(_TestMessage, error, "Error message wrong"); - }, - ELogLevel.Verbose); + Assert.That(error, Contains.Substring(_TestMessage), "Error message wrong"); + }, + ELogLevel.Verbose); // Add log entry CLog.Error(_TestMessage, show); @@ -1089,36 +1081,31 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); - string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); - string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); + var mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); + var songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[Error] " +_TestMessage, mainLogContent, "Main log entry wrong"); - StringAssert.Contains(_TestMessage, songLogContent, "Song log entry wrong"); - if(!show) + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Error] " + _TestMessage), "Main log entry wrong"); + Assert.That(songLogContent, Contains.Substring(_TestMessage), "Song log entry wrong"); + if (!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } - #endregion - #endregion #region Helper methods - private string _GetTemporaryDirectory() { - string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(tempDirectory); return tempDirectory; } - #endregion - } -} +} \ No newline at end of file diff --git a/Tests/VocaluxeLib/Log/CLogTest.tt b/Tests/VocaluxeLib/Log/CLogTest.tt index 1ca560dd..2236b3e2 100644 --- a/Tests/VocaluxeLib/Log/CLogTest.tt +++ b/Tests/VocaluxeLib/Log/CLogTest.tt @@ -92,16 +92,16 @@ namespace Tests.VocaluxeLib.Log (crash, cont, tag, log, error) => { messageShown = true; - Assert.IsTrue(show); - Assert.IsFalse(crash); - Assert.IsTrue(cont); - Assert.AreEqual(versionTag, tag); + Assert.That(show, Is.True); + Assert.That(crash, Is.False); + Assert.That(cont, Is.True); + Assert.That(tag, Is.EqualTo(versionTag)); - StringAssert.Contains("[Information] Starting to log", log, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, log, "Main log version tag entry wrong"); - StringAssert.Contains("[<#= LogLevel #>] " + <#= WithData?"_TestMessageWithResolvedData":"_TestMessage" #>, log, "Main log entry wrong"); + Assert.That(log, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(log, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(log, Contains.Substring("[<#= LogLevel #>] " + <#= WithData?"_TestMessageWithResolvedData":"_TestMessage" #>), "Main log entry wrong"); - StringAssert.Contains(<#= WithData?"_TestMessageWithResolvedData":"_TestMessage" #>, error, "Error message wrong"); + Assert.That(error, Contains.Substring(<#= WithData?"_TestMessageWithResolvedData":"_TestMessage" #>), "Error message wrong"); }, ELogLevel.Verbose); @@ -115,27 +115,27 @@ namespace Tests.VocaluxeLib.Log CLog.Close(); // Check log - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileName)), "Mainlog file is missing."); - Assert.IsTrue(File.Exists(Path.Combine(_TestFolder, testFileSongName)), "Songlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileName)), Is.True, "Mainlog file is missing."); + Assert.That(File.Exists(Path.Combine(_TestFolder, testFileSongName)), Is.True, "Songlog file is missing."); string mainLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileName)); string songLogContent = File.ReadAllText(Path.Combine(_TestFolder, testFileSongName)); - StringAssert.Contains("[Information] Starting to log", mainLogContent, "Main log start entry wrong"); - StringAssert.Contains("Version = " + versionTag, mainLogContent, "Main log version tag entry wrong"); - StringAssert.Contains("[<#= LogLevel #>] " +<#= WithData?"_TestMessageWithResolvedData":"_TestMessage" #>, mainLogContent, "Main log entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[Information] Starting to log"), "Main log start entry wrong"); + Assert.That(mainLogContent, Contains.Substring("Version = " + versionTag), "Main log version tag entry wrong"); + Assert.That(mainLogContent, Contains.Substring("[<#= LogLevel #>] " +<#= WithData?"_TestMessageWithResolvedData":"_TestMessage" #>), "Main log entry wrong"); <# if(WithException) { #> - StringAssert.Contains(_TestExceptionMessage, mainLogContent, "Exception is missing"); + Assert.That(mainLogContent, Contains.Substring(_TestExceptionMessage), "Exception is missing"); <# } #> <# if(WithData) { #> - StringAssert.Contains(_SecondParam, mainLogContent, "Second data field is missing"); + Assert.That(mainLogContent, Contains.Substring(_SecondParam), "Second data field is missing"); <# } #> <# if(LogLevel!="Fatal") { #> - StringAssert.Contains(<#= WithData?"_TestMessageWithResolvedData":"_TestMessage" #>, songLogContent, "Song log entry wrong"); + Assert.That(songLogContent, Contains.Substring(<#= WithData?"_TestMessageWithResolvedData":"_TestMessage" #>), "Song log entry wrong"); <# } #> if(!show) { - Assert.IsFalse(messageShown); + Assert.That(messageShown, Is.False); } } <# } #> diff --git a/Tests/VocaluxeLib/Log/Rolling/CLogFileRollerTest.cs b/Tests/VocaluxeLib/Log/Rolling/CLogFileRollerTest.cs index b8089613..526c7a71 100644 --- a/Tests/VocaluxeLib/Log/Rolling/CLogFileRollerTest.cs +++ b/Tests/VocaluxeLib/Log/Rolling/CLogFileRollerTest.cs @@ -29,7 +29,6 @@ namespace Tests.VocaluxeLib.Log.Rolling private string _TestFolder; #region Setup methods - [SetUp] public void SetUp() { @@ -41,20 +40,18 @@ namespace Tests.VocaluxeLib.Log.Rolling { Directory.Delete(_TestFolder, true); } - #endregion #region Tests - [Test] - public void RollFilesTest([Range(0,4)] int numFilesExisting, [Range(0, 3)] int numOldFilesToKeep) + public void RollFilesTest([Range(0, 4)] int numFilesExisting, [Range(0, 3)] int numOldFilesToKeep) { // Create existing files if (numFilesExisting > 0) { CreateFile(_TestFolder, _TestFileName, 0); } - + for (var i = 1; i < numFilesExisting; i++) { CreateFile(_TestFolder, GetFileName(i), i); @@ -63,33 +60,31 @@ namespace Tests.VocaluxeLib.Log.Rolling // Roll the files CLogFileRoller.RollLogs(Path.Combine(_TestFolder, _TestFileName), numOldFilesToKeep); - + // Check main file - Assert.IsFalse(File.Exists(Path.Combine(_TestFolder, _TestFileName)), "Main file was not deleted."); + Assert.That(File.Exists(Path.Combine(_TestFolder, _TestFileName)), Is.False, "Main file was not deleted."); //Check other files - for (int i = 1; i <= Math.Max(numOldFilesToKeep, numFilesExisting); i++) + for (var i = 1; i <= Math.Max(numOldFilesToKeep, numFilesExisting); i++) { var fileToCheck = Path.Combine(_TestFolder, GetFileName(i)); - if (i <= Math.Min(numFilesExisting,numOldFilesToKeep)) + if (i <= Math.Min(numFilesExisting, numOldFilesToKeep)) { - Assert.IsTrue(File.Exists(fileToCheck), $"File {GetFileName(i)} is missing."); - Assert.AreEqual((i - 1).ToString(), File.ReadAllText(fileToCheck), "Rotation is wrong"); + Assert.That(File.Exists(fileToCheck), Is.True, $"File {GetFileName(i)} is missing."); + Assert.That(File.ReadAllText(fileToCheck), Is.EqualTo((i - 1).ToString()), "Rotation is wrong"); } else { - Assert.IsFalse(File.Exists(fileToCheck)); + Assert.That(File.Exists(fileToCheck), Is.False); } } } - #endregion #region Helper methods - private string _GetTemporaryDirectory() { - string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); + var tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(tempDirectory); return tempDirectory; } @@ -103,8 +98,6 @@ namespace Tests.VocaluxeLib.Log.Rolling { return _TestFileName.Replace(".", $"_{i}."); } - #endregion - } -} +} \ No newline at end of file diff --git a/Tests/VocaluxeLib/Utils/Combinatorics/CCombinationsTest.cs b/Tests/VocaluxeLib/Utils/Combinatorics/CCombinationsTest.cs index dbdf71c9..ee05bcb7 100644 --- a/Tests/VocaluxeLib/Utils/Combinatorics/CCombinationsTest.cs +++ b/Tests/VocaluxeLib/Utils/Combinatorics/CCombinationsTest.cs @@ -27,72 +27,82 @@ namespace Tests.VocaluxeLib.Utils.Combinatorics public class CCombinationsTest { #region Tests - [Test] public void TestCount() { - Assert.AreEqual(4, CCombinations.Count(4, 3)); - Assert.AreEqual(6, CCombinations.Count(4, 2)); - Assert.AreEqual(66, CCombinations.Count(12, 2)); + Assert.That(CCombinations.Count(4, 3), Is.EqualTo(4)); + Assert.That(CCombinations.Count(4, 2), Is.EqualTo(6)); + Assert.That(CCombinations.Count(12, 2), Is.EqualTo(66)); // Corner cases - for (int i = 1; i < 12; i++) + for (var i = 1; i < 12; i++) { - Assert.AreEqual(1, CCombinations.Count(i, 0)); - Assert.AreEqual(1, CCombinations.Count(i, i)); - Assert.AreEqual(0, CCombinations.Count(i, i + 1)); + Assert.That(CCombinations.Count(i, 0), Is.EqualTo(1)); + Assert.That(CCombinations.Count(i, i), Is.EqualTo(1)); + Assert.That(CCombinations.Count(i, i + 1), Is.EqualTo(0)); } + // Check identity (n k) = (n n-k) - for (int i = 0; i <= 12; i++) - Assert.AreEqual(CCombinations.Count(12, i), CCombinations.Count(12, 12 - i)); - Assert.That(() => CCombinations.Count(-1, -1), Throws.TypeOf()); - Assert.That(() => CCombinations.Count(-1, 1), Throws.TypeOf()); - Assert.That(() => CCombinations.Count(1, -1), Throws.TypeOf()); + for (var i = 0; i <= 12; i++) + { + Assert.That(CCombinations.Count(12, 12 - i), Is.EqualTo(CCombinations.Count(12, i))); + } + + Assert.Throws(new Action(() => CCombinations.Count(-1, -1))); + Assert.Throws(new Action(() => CCombinations.Count(-1, 1))); + Assert.Throws(new Action(() => CCombinations.Count(1, -1))); } [Test] public void TestResults([Range(0, 8, 1)] int n) { - Random rand = new Random(); - - for (int k = 0; k <= n; k++) + var rand = new Random(); + + for (var k = 0; k <= n; k++) { - List collection = new List(n); - int r = rand.Next(1000); - for (int i = 0; i < n; i++) + var collection = new List(n); + var r = rand.Next(1000); + for (var i = 0; i < n; i++) + { collection.Add(i + r); - CCombinations combs = new CCombinations(collection, k); - Assert.AreEqual(CCombinations.Count(n, k), combs.Count()); + } + + var combs = new CCombinations(collection, k); + Assert.That(combs.Count(), Is.EqualTo(CCombinations.Count(n, k))); _CheckResults(combs, collection); } } - #endregion #region Helper methods - // ReSharper disable UnusedParameter.Local private static void _CheckResults(CCombinations combs, List input) - // ReSharper restore UnusedParameter.Local + // ReSharper restore UnusedParameter.Local { - List> results = new List>(); - foreach (List comb in combs) + var results = new List>(); + foreach (var comb in combs) { - foreach (List other in results) - Assert.IsFalse(other.SequenceEqual(comb), "Result must be unique"); - for (int i = 0; i < comb.Count - 1; i++) + foreach (var other in results) { - Assert.IsTrue(comb.IndexOf(comb[i], i + 1) < 0, "Repetition not allowed"); - Assert.IsTrue(input.Contains(comb[i]), "Output must be in input sequence"); + Assert.That(other.SequenceEqual(comb), Is.False, "Result must be unique"); } + + for (var i = 0; i < comb.Count - 1; i++) + { + Assert.That(comb.IndexOf(comb[i], i + 1), Is.LessThan(0),"Repetition not allowed"); + Assert.That(input.Contains(comb[i]), Is.True, "Output must be in input sequence"); + } + results.Add(comb); } - Assert.AreEqual(combs.Count(), results.Count); - List> results2 = combs.GetAll(); - Assert.AreEqual(results.Count, results2.Count); - for (int i = 0; i < results2.Count; i++) - Assert.IsTrue(results[i].SequenceEqual(results2[i])); - } + Assert.That(results, Has.Count.EqualTo(combs.Count())); + var results2 = combs.GetAll(); + Assert.That(results, Has.Count.EqualTo(results2.Count)); + for (var i = 0; i < results2.Count; i++) + { + Assert.That(results[i], Is.EquivalentTo(results2[i])); + } + } #endregion } -} +} \ No newline at end of file diff --git a/Tests/VocaluxeLib/XML/CXmlSerializerTest.cs b/Tests/VocaluxeLib/XML/CXmlSerializerTest.cs index 68c3ecba..06609554 100644 --- a/Tests/VocaluxeLib/XML/CXmlSerializerTest.cs +++ b/Tests/VocaluxeLib/XML/CXmlSerializerTest.cs @@ -21,9 +21,9 @@ using System.ComponentModel; using System.IO; using System.Xml.Serialization; using NUnit.Framework; +using Vocaluxe.Base; using VocaluxeLib; using VocaluxeLib.Xml; -using Vocaluxe.Base; namespace Tests.VocaluxeLib.XML { @@ -34,7 +34,6 @@ namespace Tests.VocaluxeLib.XML private const string _Empty = _Head + @""; #region Tests - [Test] public void TestBasic() { @@ -51,67 +50,76 @@ namespace Tests.VocaluxeLib.XML 2 "; var xml = new CXmlDeserializer(); - SBasic foo = xml.DeserializeString(s); - Assert.AreEqual(1, foo.I); - Assert.AreEqual("2", foo.S); - Assert.AreEqual(3, foo.F, 0.0001); - Assert.AreEqual(4, foo.D, 0.0001); + var foo = xml.DeserializeString(s); + Assert.That(foo.I, Is.EqualTo(1)); + Assert.That(foo.S, Is.EqualTo("2")); + Assert.That(foo.F, Is.EqualTo(3).Within(0.0001)); + Assert.That(foo.D, Is.EqualTo(4).Within(0.0001)); foo = xml.DeserializeString(sUnordered); - Assert.AreEqual(1, foo.I); - Assert.AreEqual("2", foo.S); - Assert.AreEqual(3, foo.F, 0.0001); - Assert.AreEqual(4, foo.D, 0.0001); + Assert.That(foo.I, Is.EqualTo(1)); + Assert.That(foo.S, Is.EqualTo("2")); + Assert.That(foo.F, Is.EqualTo(3).Within(0.0001)); + Assert.That(foo.D, Is.EqualTo(4).Within(0.0001)); } [Test] public void TestMissingXmlElement() { - string[] s = new string[] { @" - 2 - 3 - 4 -", @" - 1 - 3 - 4 -", @" - 1 - 2 - 3 -" }; - foreach (string s1 in s) + var s = new string[] { - string sTmp = s1; - _AssertFail(sTmp); + @" + 2 + 3 + 4 +", + @" + 1 + 3 + 4 +", + @" + 1 + 2 + 3 +" + }; + foreach (var s1 in s) + { + _AssertXmlSerializeFailWithMissingElement(s1); } } [Test] public void TestMissingStructElement() { - string[] s = new string[] { @" - 1 - 1 - 2 - 3 - 4 -", @" - 1 - 1 - 2 - 3 - 4 -", @" - 1 - 2 - 3 - 4 - 1 -" }; - foreach (string s1 in s) + var s = new string[] { - string sTmp = s1; - _AssertFail(sTmp); + @" + 1 + 1 + 2 + 3 + 4 +", + @" + 1 + 1 + 2 + 3 + 4 +", + @" + 1 + 2 + 3 + 4 + 1 +" + }; + foreach (var s1 in s) + { + var sTmp = s1; + _AssertXmlSerializeFailWithMissingElement(sTmp); } } @@ -127,7 +135,7 @@ namespace Tests.VocaluxeLib.XML _AssertSerDeserMatch(s); } - private readonly string[] _XmlList = new string[] + private readonly string[] _XmlList = { _Head + @" @@ -153,22 +161,22 @@ namespace Tests.VocaluxeLib.XML { var xml = new CXmlDeserializer(); var ser = new CXmlSerializer(); - SList foo = xml.DeserializeString(_XmlList[0]); - Assert.AreEqual(foo.Ints.Count, 2, "Deserialization failed"); - Assert.AreEqual(foo.Ints[0].I, 1, "Deserialization failed"); - Assert.AreEqual(foo.Ints[1].I, 1, "Deserialization failed"); - string res = ser.Serialize(foo); - Assert.AreEqual(_XmlList[0], res, "Serialization failed"); + var foo = xml.DeserializeString(_XmlList[0]); + Assert.That(foo.Ints, Has.Count.EqualTo(2), "Deserialization failed"); + Assert.That(foo.Ints[0].I, Is.EqualTo(1), "Deserialization failed"); + Assert.That(foo.Ints[1].I, Is.EqualTo(1), "Deserialization failed"); + var res = ser.Serialize(foo); + Assert.That(res, Is.EqualTo(_XmlList[0]), "Serialization failed"); foo = xml.DeserializeString(_XmlList[1]); - Assert.AreEqual(foo.Ints.Count, 0, "Deserialization2 failed"); + Assert.That(foo.Ints, Is.Empty, "Deserialization2 failed"); res = ser.Serialize(foo); - Assert.AreEqual(_XmlList[2], res, "Serialization2 failed"); + Assert.That(_XmlList[2], Is.EqualTo(res), "Serialization2 failed"); foo = xml.DeserializeString(_XmlList[2]); - Assert.AreEqual(foo.Ints.Count, 0, "Deserialization2 failed"); + Assert.That(foo.Ints, Is.Empty, "Deserialization2 failed"); _AssertSerDeserMatch(_XmlList[2]); res = ser.Serialize(foo); - Assert.AreEqual(_XmlList[2], res, "Serialization2 failed"); - _AssertFail(_Empty); + Assert.That(_XmlList[2], Is.EqualTo(res), "Serialization2 failed"); + _AssertXmlSerializeFailWithMissingElement(_Empty); } [Test] @@ -176,21 +184,21 @@ namespace Tests.VocaluxeLib.XML { var xml = new CXmlDeserializer(); var ser = new CXmlSerializer(); - SArray foo = xml.DeserializeString(_XmlList[0]); - Assert.AreEqual(foo.Ints.Length, 2, "Deserialization failed"); - Assert.AreEqual(foo.Ints[0].I, 1, "Deserialization failed"); - Assert.AreEqual(foo.Ints[1].I, 1, "Deserialization failed"); - string res = ser.Serialize(foo); - Assert.AreEqual(_XmlList[0], res, "Serialization failed"); + var foo = xml.DeserializeString(_XmlList[0]); + Assert.That(foo.Ints, Has.Length.EqualTo(2), "Deserialization failed"); + Assert.That(foo.Ints[0].I, Is.EqualTo(1), "Deserialization failed"); + Assert.That(foo.Ints[1].I, Is.EqualTo(1), "Deserialization failed"); + var res = ser.Serialize(foo); + Assert.That(res, Is.EqualTo(_XmlList[0]), "Serialization failed"); foo = xml.DeserializeString(_XmlList[1]); - Assert.AreEqual(foo.Ints.Length, 0, "Deserialization2 failed"); + Assert.That(foo.Ints, Is.Empty, "Deserialization2 failed"); res = ser.Serialize(foo); - Assert.AreEqual(_XmlList[2], res, "Serialization2 failed"); + Assert.That(_XmlList[2], Is.EqualTo(res), "Serialization2 failed"); foo = xml.DeserializeString(_XmlList[2]); - Assert.AreEqual(foo.Ints.Length, 0, "Deserialization2 failed"); + Assert.That(foo.Ints, Is.Empty, "Deserialization2 failed"); res = ser.Serialize(foo); - Assert.AreEqual(_XmlList[2], res, "Serialization2 failed"); - _AssertFail(_Empty); + Assert.That(_XmlList[2], Is.EqualTo(res), "Serialization2 failed"); + _AssertXmlSerializeFailWithMissingElement(_Empty); } private const string _XmlListEmb = _Head + @" @@ -225,25 +233,25 @@ namespace Tests.VocaluxeLib.XML { var xml = new CXmlDeserializer(); var ser = new CXmlSerializer(); - SListEmb foo = xml.DeserializeString(_XmlListEmb); - Assert.AreEqual(foo.Ints.Count, 1, "Deserialization failed"); - Assert.AreEqual(foo.Ints[0].I, 1, "Deserialization failed"); - string res = ser.Serialize(foo); - Assert.AreEqual(_XmlListEmb, res, "Serialization failed"); + var foo = xml.DeserializeString(_XmlListEmb); + Assert.That(foo.Ints, Has.Count.EqualTo(1), "Deserialization failed"); + Assert.That(foo.Ints[0].I, Is.EqualTo(1), "Deserialization failed"); + var res = ser.Serialize(foo); + Assert.That(res, Is.EqualTo(_XmlListEmb), "Serialization failed"); foo = xml.DeserializeString(_XmlListEmb2); - Assert.AreEqual(foo.Ints.Count, 2, "Deserialization failed"); - Assert.AreEqual(foo.Ints[1].I, 2, "Deserialization failed"); + Assert.That(foo.Ints, Has.Count.EqualTo(2), "Deserialization failed"); + Assert.That(foo.Ints[1].I, Is.EqualTo(2) , "Deserialization failed"); res = ser.Serialize(foo); - Assert.AreEqual(_XmlListEmb2, res, "Serialization failed"); + Assert.That(res, Is.EqualTo(_XmlListEmb2), "Serialization failed"); foo = xml.DeserializeString(_XmlListEmb3); - Assert.AreEqual(foo.Ints.Count, 0, "Deserialization failed"); + Assert.That(foo.Ints, Is.Empty, "Deserialization failed"); res = ser.Serialize(foo); - Assert.AreEqual(_XmlListEmb3, res, "Serialization failed"); + Assert.That(res, Is.EqualTo(_XmlListEmb3), "Serialization failed"); ser = new CXmlSerializer(true); foo.Ints.Clear(); res = ser.Serialize(foo); - Assert.AreEqual(_XmlListEmb4, res, "Serialization failed"); - _AssertFail(_Empty); + Assert.That(res, Is.EqualTo(_XmlListEmb4), "Serialization failed"); + _AssertXmlSerializeFailWithMissingElement(_Empty); } [Test] @@ -251,25 +259,25 @@ namespace Tests.VocaluxeLib.XML { var xml = new CXmlDeserializer(); var ser = new CXmlSerializer(); - SArrayEmb foo = xml.DeserializeString(_XmlListEmb); - Assert.AreEqual(foo.Ints.Length, 1, "Deserialization failed"); - Assert.AreEqual(foo.Ints[0].I, 1, "Deserialization failed"); - string res = ser.Serialize(foo); - Assert.AreEqual(_XmlListEmb, res, "Serialization failed"); + var foo = xml.DeserializeString(_XmlListEmb); + Assert.That(foo.Ints, Has.Length.EqualTo(1), "Deserialization failed"); + Assert.That(foo.Ints[0].I, Is.EqualTo(1), "Deserialization failed"); + var res = ser.Serialize(foo); + Assert.That(res, Is.EqualTo(_XmlListEmb), "Serialization failed"); foo = xml.DeserializeString(_XmlListEmb2); - Assert.AreEqual(foo.Ints.Length, 2, "Deserialization failed"); - Assert.AreEqual(foo.Ints[1].I, 2, "Deserialization failed"); + Assert.That(foo.Ints, Has.Length.EqualTo(2), "Deserialization failed"); + Assert.That(foo.Ints[1].I, Is.EqualTo(2), "Deserialization failed"); res = ser.Serialize(foo); - Assert.AreEqual(_XmlListEmb2, res, "Serialization failed"); + Assert.That(res, Is.EqualTo(_XmlListEmb2), "Serialization failed"); foo = xml.DeserializeString(_XmlListEmb3); - Assert.AreEqual(foo.Ints.Length, 0, "Deserialization failed"); + Assert.That(foo.Ints, Is.Empty, "Deserialization failed"); res = ser.Serialize(foo); - Assert.AreEqual(_XmlListEmb3, res, "Serialization failed"); + Assert.That(res, Is.EqualTo(_XmlListEmb3), "Serialization failed"); ser = new CXmlSerializer(true); - foo.Ints = new SEntry[0]; + foo.Ints = Array.Empty(); res = ser.Serialize(foo); - Assert.AreEqual(_XmlListEmb4, res, "Serialization failed"); - _AssertFail(_Empty); + Assert.That(res, Is.EqualTo(_XmlListEmb4), "Serialization failed"); + _AssertXmlSerializeFailWithMissingElement(_Empty); } [Test] @@ -279,9 +287,9 @@ namespace Tests.VocaluxeLib.XML 2 3 "; - SProperty foo = _AssertSerDeserMatch(xmlString); - Assert.AreEqual(3, foo.Private); - Assert.AreEqual(3, foo.Auto); + var foo = _AssertSerDeserMatch(xmlString); + Assert.That(foo.Private, Is.EqualTo(3)); + Assert.That(foo.Auto, Is.EqualTo(3)); } [Test] @@ -305,7 +313,7 @@ namespace Tests.VocaluxeLib.XML public void TestIgnore() { _AssertSerDeserMatch(_XmlIgnore); - _AssertFail(_XmlIgnore2); + _AssertXmlSerializeFailWithMissingElement(_XmlIgnore2); } [Test] @@ -314,15 +322,15 @@ namespace Tests.VocaluxeLib.XML var foo = new SIgnore { I = 1 }; var xml = new CXmlDeserializer(); var ser = new CXmlSerializer(); - SIgnore bar = xml.DeserializeString(_XmlIgnore, foo); - Assert.AreEqual(1, bar.I); - Assert.AreEqual(_XmlIgnore, ser.Serialize(bar)); + var bar = xml.DeserializeString(_XmlIgnore, foo); + Assert.That(bar.I, Is.EqualTo(1)); + Assert.That(ser.Serialize(bar), Is.EqualTo(_XmlIgnore)); var foo2 = new CIgnore { I = 1 }; - CIgnore bar2 = xml.DeserializeString(_XmlIgnore, foo2); - Assert.AreEqual(1, bar2.I); - Assert.AreEqual(foo2.J, bar2.J, "Original classes should be modified by the deserialization"); - Assert.AreEqual(_XmlIgnore, ser.Serialize(bar2)); + var bar2 = xml.DeserializeString(_XmlIgnore, foo2); + Assert.That(bar2.I, Is.EqualTo(1)); + Assert.That(bar2.J, Is.EqualTo(foo2.J), "Original classes should be modified by the deserialization"); + Assert.That(ser.Serialize(bar2), Is.EqualTo(_XmlIgnore)); } [Test] @@ -359,16 +367,16 @@ namespace Tests.VocaluxeLib.XML "; _AssertSerDeserMatch(s); var xml = new CXmlDeserializer(new CXmlErrorHandler(exception => { })); - SDefault foo = xml.DeserializeString(@""); - Assert.AreEqual(foo.I, 1337); - Assert.AreEqual(foo.F, null); - Assert.AreEqual(foo.S, "Foo"); - Assert.AreEqual(foo.D, 666); - Assert.AreEqual(foo.Sub.I, 111); - string newXml = new CXmlSerializer().Serialize(foo); - Assert.AreEqual(_Head + @" + var foo = xml.DeserializeString(@""); + Assert.That(foo.I, Is.EqualTo(1337)); + Assert.That(foo.F, Is.Null); + Assert.That(foo.S, Is.EqualTo("Foo")); + Assert.That(foo.D, Is.EqualTo(666)); + Assert.That(foo.Sub.I, Is.EqualTo(111)); + var newXml = new CXmlSerializer().Serialize(foo); + Assert.That(newXml, Is.EqualTo(_Head + @" -", newXml); +")); } [Test] @@ -382,9 +390,9 @@ namespace Tests.VocaluxeLib.XML "; _AssertSerDeserMatch(s); var xml = new CXmlDeserializer(new CXmlErrorHandler(exception => { })); - SUnescaping foo = xml.DeserializeString(@""); - Assert.AreEqual(foo.S, "Foo\'Bar"); - Assert.AreEqual(foo.Sub.S, "Foo\'Bar"); + var foo = xml.DeserializeString(@""); + Assert.That(foo.S, Is.EqualTo("Foo\'Bar")); + Assert.That(foo.Sub.S, Is.EqualTo("Foo\'Bar")); } [Test] @@ -398,37 +406,38 @@ namespace Tests.VocaluxeLib.XML "; _AssertSerDeserMatch(s); var xml = new CXmlDeserializer(new CXmlErrorHandler(exception => { }), true); - SUnescaping foo = xml.DeserializeString(@""); - Assert.AreEqual(foo.S, "Foo'Bar"); - Assert.AreEqual(foo.Sub.S, "Foo'Bar"); + var foo = xml.DeserializeString(@""); + Assert.That(foo.S, Is.EqualTo("Foo'Bar")); + Assert.That(foo.Sub.S, Is.EqualTo("Foo'Bar")); } [Test] - public void TestRealFiles([Values(typeof(SThemeCover), typeof(CConfig.SConfig), /*typeof(SThemeScreen),*/ typeof(SDefaultFonts), typeof(SSkin), typeof(STheme), typeof(Dictionary))] Type type) + public void TestRealFiles( + [Values(typeof(SThemeCover), typeof(CConfig.SConfig), /*typeof(SThemeScreen),*/ typeof(SDefaultFonts), typeof(SSkin), typeof(STheme), + typeof(Dictionary))] + Type type) { - string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "VocaluxeLib", "XML", "TestFiles"); + var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "VocaluxeLib", "XML", "TestFiles"); - string xmlPath = Path.Combine(filePath, type.Name + ".xml"); + var xmlPath = Path.Combine(filePath, type.Name + ".xml"); var deser = new CXmlDeserializer(); - object foo = deser.Deserialize(xmlPath, Activator.CreateInstance(type)); + var foo = deser.Deserialize(xmlPath, Activator.CreateInstance(type)); - Assert.IsInstanceOf(type, foo, "Wrong type with " + type.Name); + Assert.That(foo, Is.InstanceOf(type), "Wrong type with " + type.Name); var ser = new CXmlSerializer(type == typeof(CConfig.SConfig)); - string newXml = ser.Serialize(foo, type == typeof(Dictionary) ? "resources" : null); + var newXml = ser.Serialize(foo, type == typeof(Dictionary) ? "resources" : null); // Typename will be uppercase but input is lowercase newXml = newXml.Replace("(String xmlString) where T2 : Exception where T : new() + private static void _AssertXmlSerializeFailWithMissingElement(string xmlString) + where TSerializeType : new() + where TXmlException : CXmlException { var deserializer = new CXmlDeserializer(); - - Exception exception = - Assert.Catch(() => deserializer.DeserializeString(xmlString)); - Assert.IsInstanceOf(typeof(T2), exception); + Assert.Throws(new Action(() => deserializer.DeserializeString(xmlString))); } private static T _AssertSerDeserMatch(string xmlString) where T : new() { var deserializer = new CXmlDeserializer(); var serializer = new CXmlSerializer(); - T foo = deserializer.DeserializeString(xmlString); - string xmlNew = serializer.Serialize(foo); - Assert.AreEqual(xmlString, xmlNew); + var foo = deserializer.DeserializeString(xmlString); + var xmlNew = serializer.Serialize(foo); + Assert.That(xmlString, Is.EqualTo(xmlNew)); return foo; } - #endregion } -} +} \ No newline at end of file diff --git a/Vocaluxe.sln.DotSettings b/Vocaluxe.sln.DotSettings index a7008703..f7329168 100644 --- a/Vocaluxe.sln.DotSettings +++ b/Vocaluxe.sln.DotSettings @@ -10,10 +10,15 @@ DO_NOT_SHOW DO_NOT_SHOW DO_NOT_SHOW - <?xml version="1.0" encoding="utf-16"?><Profile name="Cleanup"><CSArrangeThisQualifier>True</CSArrangeThisQualifier><CSRemoveCodeRedundancies>True</CSRemoveCodeRedundancies><CSUseVar><BehavourStyle>CAN_CHANGE_TO_EXPLICIT</BehavourStyle><LocalVariableStyle>IMPLICIT_WHEN_INITIALIZER_HAS_TYPE</LocalVariableStyle><ForeachVariableStyle>ALWAYS_EXPLICIT</ForeachVariableStyle></CSUseVar><CSOptimizeUsings><OptimizeUsings>False</OptimizeUsings><EmbraceInRegion>False</EmbraceInRegion><RegionName></RegionName></CSOptimizeUsings><CSReformatCode>True</CSReformatCode><CSharpFormatDocComments>True</CSharpFormatDocComments><CSShortenReferences>True</CSShortenReferences><StyleCop.Documentation><SA1600ElementsMustBeDocumented>False</SA1600ElementsMustBeDocumented><SA1604ElementDocumentationMustHaveSummary>False</SA1604ElementDocumentationMustHaveSummary><SA1609PropertyDocumentationMustHaveValueDocumented>False</SA1609PropertyDocumentationMustHaveValueDocumented><SA1611ElementParametersMustBeDocumented>False</SA1611ElementParametersMustBeDocumented><SA1615ElementReturnValueMustBeDocumented>False</SA1615ElementReturnValueMustBeDocumented><SA1617VoidReturnValueMustNotBeDocumented>False</SA1617VoidReturnValueMustNotBeDocumented><SA1618GenericTypeParametersMustBeDocumented>False</SA1618GenericTypeParametersMustBeDocumented><SA1626SingleLineCommentsMustNotUseDocumentationStyleSlashes>False</SA1626SingleLineCommentsMustNotUseDocumentationStyleSlashes><SA1628DocumentationTextMustBeginWithACapitalLetter>False</SA1628DocumentationTextMustBeginWithACapitalLetter><SA1629DocumentationTextMustEndWithAPeriod>False</SA1629DocumentationTextMustEndWithAPeriod><SA1633SA1641UpdateFileHeader>Ignore</SA1633SA1641UpdateFileHeader><SA1639FileHeaderMustHaveSummary>False</SA1639FileHeaderMustHaveSummary><SA1642ConstructorSummaryDocumentationMustBeginWithStandardText>False</SA1642ConstructorSummaryDocumentationMustBeginWithStandardText><SA1643DestructorSummaryDocumentationMustBeginWithStandardText>False</SA1643DestructorSummaryDocumentationMustBeginWithStandardText><SA1644DocumentationHeadersMustNotContainBlankLines>False</SA1644DocumentationHeadersMustNotContainBlankLines></StyleCop.Documentation><StyleCop.Layout><SA1500CurlyBracketsForMultiLineStatementsMustNotShareLine>False</SA1500CurlyBracketsForMultiLineStatementsMustNotShareLine><SA1509OpeningCurlyBracketsMustNotBePrecededByBlankLine>True</SA1509OpeningCurlyBracketsMustNotBePrecededByBlankLine><SA1510ChainedStatementBlocksMustNotBePrecededByBlankLine>True</SA1510ChainedStatementBlocksMustNotBePrecededByBlankLine><SA1511WhileDoFooterMustNotBePrecededByBlankLine>True</SA1511WhileDoFooterMustNotBePrecededByBlankLine><SA1512SingleLineCommentsMustNotBeFollowedByBlankLine>True</SA1512SingleLineCommentsMustNotBeFollowedByBlankLine><SA1513ClosingCurlyBracketMustBeFollowedByBlankLine>False</SA1513ClosingCurlyBracketMustBeFollowedByBlankLine><SA1514ElementDocumentationHeaderMustBePrecededByBlankLine>False</SA1514ElementDocumentationHeaderMustBePrecededByBlankLine><SA1515SingleLineCommentMustBeProceededByBlankLine>False</SA1515SingleLineCommentMustBeProceededByBlankLine></StyleCop.Layout><StyleCop.Readability><SA1100DoNotPrefixCallsWithBaseUnlessLocalImplementationExists>True</SA1100DoNotPrefixCallsWithBaseUnlessLocalImplementationExists><SA1106CodeMustNotContainEmptyStatements>True</SA1106CodeMustNotContainEmptyStatements><SA1108BlockStatementsMustNotContainEmbeddedComments>True</SA1108BlockStatementsMustNotContainEmbeddedComments><SA1109BlockStatementsMustNotContainEmbeddedRegions>True</SA1109BlockStatementsMustNotContainEmbeddedRegions><SA1120CommentsMustContainText>False</SA1120CommentsMustContainText><SA1121UseBuiltInTypeAlias>False</SA1121UseBuiltInTypeAlias><SA1122UseStringEmptyForEmptyStrings>False</SA1122UseStringEmptyForEmptyStrings><SA1123DoNotPlaceRegionsWithinElements>False</SA1123DoNotPlaceRegionsWithinElements><SA1124CodeMustNotContainEmptyRegions>True</SA1124CodeMustNotContainEmptyRegions></StyleCop.Readability><StyleCop.Spacing><SA1001CommasMustBeSpacedCorrectly>False</SA1001CommasMustBeSpacedCorrectly><SA1005SingleLineCommentsMustBeginWithSingleSpace>False</SA1005SingleLineCommentsMustBeginWithSingleSpace><SA1006PreprocessorKeywordsMustNotBePrecededBySpace>True</SA1006PreprocessorKeywordsMustNotBePrecededBySpace><SA1021NegativeSignsMustBeSpacedCorrectly>True</SA1021NegativeSignsMustBeSpacedCorrectly><SA1022PositiveSignsMustBeSpacedCorrectly>True</SA1022PositiveSignsMustBeSpacedCorrectly><SA1025CodeMustNotContainMultipleWhitespaceInARow>True</SA1025CodeMustNotContainMultipleWhitespaceInARow></StyleCop.Spacing><StyleCop.Ordering><AlphabeticalUsingDirectives>Ignore</AlphabeticalUsingDirectives><ExpandUsingDirectives>Ignore</ExpandUsingDirectives><SA1212PropertyAccessorsMustFollowOrder>True</SA1212PropertyAccessorsMustFollowOrder><SA1213EventAccessorsMustFollowOrder>True</SA1213EventAccessorsMustFollowOrder></StyleCop.Ordering><CSUpdateFileHeader>True</CSUpdateFileHeader><CSUseAutoProperty>True</CSUseAutoProperty></Profile> + <?xml version="1.0" encoding="utf-16"?><Profile name="Cleanup"><CSArrangeThisQualifier>True</CSArrangeThisQualifier><CSRemoveCodeRedundancies>True</CSRemoveCodeRedundancies><CSUseVar><BehavourStyle>CAN_CHANGE_TO_EXPLICIT</BehavourStyle><LocalVariableStyle>IMPLICIT_WHEN_INITIALIZER_HAS_TYPE</LocalVariableStyle><ForeachVariableStyle>ALWAYS_EXPLICIT</ForeachVariableStyle></CSUseVar><CSOptimizeUsings><OptimizeUsings>True</OptimizeUsings></CSOptimizeUsings><CSReformatCode>True</CSReformatCode><StyleCop.Documentation><SA1600ElementsMustBeDocumented>False</SA1600ElementsMustBeDocumented><SA1604ElementDocumentationMustHaveSummary>False</SA1604ElementDocumentationMustHaveSummary><SA1609PropertyDocumentationMustHaveValueDocumented>False</SA1609PropertyDocumentationMustHaveValueDocumented><SA1611ElementParametersMustBeDocumented>False</SA1611ElementParametersMustBeDocumented><SA1615ElementReturnValueMustBeDocumented>False</SA1615ElementReturnValueMustBeDocumented><SA1617VoidReturnValueMustNotBeDocumented>False</SA1617VoidReturnValueMustNotBeDocumented><SA1618GenericTypeParametersMustBeDocumented>False</SA1618GenericTypeParametersMustBeDocumented><SA1626SingleLineCommentsMustNotUseDocumentationStyleSlashes>False</SA1626SingleLineCommentsMustNotUseDocumentationStyleSlashes><SA1628DocumentationTextMustBeginWithACapitalLetter>False</SA1628DocumentationTextMustBeginWithACapitalLetter><SA1629DocumentationTextMustEndWithAPeriod>False</SA1629DocumentationTextMustEndWithAPeriod><SA1633SA1641UpdateFileHeader>Ignore</SA1633SA1641UpdateFileHeader><SA1639FileHeaderMustHaveSummary>False</SA1639FileHeaderMustHaveSummary><SA1642ConstructorSummaryDocumentationMustBeginWithStandardText>False</SA1642ConstructorSummaryDocumentationMustBeginWithStandardText><SA1643DestructorSummaryDocumentationMustBeginWithStandardText>False</SA1643DestructorSummaryDocumentationMustBeginWithStandardText><SA1644DocumentationHeadersMustNotContainBlankLines>False</SA1644DocumentationHeadersMustNotContainBlankLines></StyleCop.Documentation><StyleCop.Layout><SA1500CurlyBracketsForMultiLineStatementsMustNotShareLine>False</SA1500CurlyBracketsForMultiLineStatementsMustNotShareLine><SA1509OpeningCurlyBracketsMustNotBePrecededByBlankLine>True</SA1509OpeningCurlyBracketsMustNotBePrecededByBlankLine><SA1510ChainedStatementBlocksMustNotBePrecededByBlankLine>True</SA1510ChainedStatementBlocksMustNotBePrecededByBlankLine><SA1511WhileDoFooterMustNotBePrecededByBlankLine>True</SA1511WhileDoFooterMustNotBePrecededByBlankLine><SA1512SingleLineCommentsMustNotBeFollowedByBlankLine>True</SA1512SingleLineCommentsMustNotBeFollowedByBlankLine><SA1513ClosingCurlyBracketMustBeFollowedByBlankLine>False</SA1513ClosingCurlyBracketMustBeFollowedByBlankLine><SA1514ElementDocumentationHeaderMustBePrecededByBlankLine>False</SA1514ElementDocumentationHeaderMustBePrecededByBlankLine><SA1515SingleLineCommentMustBeProceededByBlankLine>False</SA1515SingleLineCommentMustBeProceededByBlankLine></StyleCop.Layout><StyleCop.Readability><SA1100DoNotPrefixCallsWithBaseUnlessLocalImplementationExists>True</SA1100DoNotPrefixCallsWithBaseUnlessLocalImplementationExists><SA1106CodeMustNotContainEmptyStatements>True</SA1106CodeMustNotContainEmptyStatements><SA1108BlockStatementsMustNotContainEmbeddedComments>True</SA1108BlockStatementsMustNotContainEmbeddedComments><SA1109BlockStatementsMustNotContainEmbeddedRegions>True</SA1109BlockStatementsMustNotContainEmbeddedRegions><SA1120CommentsMustContainText>False</SA1120CommentsMustContainText><SA1121UseBuiltInTypeAlias>False</SA1121UseBuiltInTypeAlias><SA1122UseStringEmptyForEmptyStrings>False</SA1122UseStringEmptyForEmptyStrings><SA1123DoNotPlaceRegionsWithinElements>False</SA1123DoNotPlaceRegionsWithinElements><SA1124CodeMustNotContainEmptyRegions>True</SA1124CodeMustNotContainEmptyRegions></StyleCop.Readability><StyleCop.Spacing><SA1001CommasMustBeSpacedCorrectly>False</SA1001CommasMustBeSpacedCorrectly><SA1005SingleLineCommentsMustBeginWithSingleSpace>False</SA1005SingleLineCommentsMustBeginWithSingleSpace><SA1006PreprocessorKeywordsMustNotBePrecededBySpace>True</SA1006PreprocessorKeywordsMustNotBePrecededBySpace><SA1021NegativeSignsMustBeSpacedCorrectly>True</SA1021NegativeSignsMustBeSpacedCorrectly><SA1022PositiveSignsMustBeSpacedCorrectly>True</SA1022PositiveSignsMustBeSpacedCorrectly><SA1025CodeMustNotContainMultipleWhitespaceInARow>True</SA1025CodeMustNotContainMultipleWhitespaceInARow></StyleCop.Spacing><StyleCop.Ordering><AlphabeticalUsingDirectives>Ignore</AlphabeticalUsingDirectives><ExpandUsingDirectives>Ignore</ExpandUsingDirectives><SA1212PropertyAccessorsMustFollowOrder>True</SA1212PropertyAccessorsMustFollowOrder><SA1213EventAccessorsMustFollowOrder>True</SA1213EventAccessorsMustFollowOrder></StyleCop.Ordering><CSUseAutoProperty>True</CSUseAutoProperty><CSCodeStyleAttributes ArrangeVarStyle="True" RemoveRedundantParentheses="True" ArrangeBraces="True" ArrangeNullCheckingPattern="True" /><XAMLCollapseEmptyTags>False</XAMLCollapseEmptyTags></Profile> <?xml version="1.0" encoding="utf-16"?><Profile name="Simple Reformat"><CSOptimizeUsings><OptimizeUsings>False</OptimizeUsings><EmbraceInRegion>False</EmbraceInRegion><RegionName></RegionName></CSOptimizeUsings><CSReformatCode>True</CSReformatCode><StyleCop.Documentation><SA1600ElementsMustBeDocumented>False</SA1600ElementsMustBeDocumented><SA1604ElementDocumentationMustHaveSummary>False</SA1604ElementDocumentationMustHaveSummary><SA1609PropertyDocumentationMustHaveValueDocumented>False</SA1609PropertyDocumentationMustHaveValueDocumented><SA1611ElementParametersMustBeDocumented>False</SA1611ElementParametersMustBeDocumented><SA1615ElementReturnValueMustBeDocumented>False</SA1615ElementReturnValueMustBeDocumented><SA1617VoidReturnValueMustNotBeDocumented>False</SA1617VoidReturnValueMustNotBeDocumented><SA1618GenericTypeParametersMustBeDocumented>False</SA1618GenericTypeParametersMustBeDocumented><SA1626SingleLineCommentsMustNotUseDocumentationStyleSlashes>False</SA1626SingleLineCommentsMustNotUseDocumentationStyleSlashes><SA1628DocumentationTextMustBeginWithACapitalLetter>False</SA1628DocumentationTextMustBeginWithACapitalLetter><SA1629DocumentationTextMustEndWithAPeriod>False</SA1629DocumentationTextMustEndWithAPeriod><SA1633SA1641UpdateFileHeader>Ignore</SA1633SA1641UpdateFileHeader><SA1639FileHeaderMustHaveSummary>False</SA1639FileHeaderMustHaveSummary><SA1642ConstructorSummaryDocumentationMustBeginWithStandardText>False</SA1642ConstructorSummaryDocumentationMustBeginWithStandardText><SA1643DestructorSummaryDocumentationMustBeginWithStandardText>False</SA1643DestructorSummaryDocumentationMustBeginWithStandardText><SA1644DocumentationHeadersMustNotContainBlankLines>False</SA1644DocumentationHeadersMustNotContainBlankLines></StyleCop.Documentation><StyleCop.Spacing><SA1001CommasMustBeSpacedCorrectly>False</SA1001CommasMustBeSpacedCorrectly><SA1005SingleLineCommentsMustBeginWithSingleSpace>False</SA1005SingleLineCommentsMustBeginWithSingleSpace><SA1006PreprocessorKeywordsMustNotBePrecededBySpace>True</SA1006PreprocessorKeywordsMustNotBePrecededBySpace><SA1021NegativeSignsMustBeSpacedCorrectly>True</SA1021NegativeSignsMustBeSpacedCorrectly><SA1022PositiveSignsMustBeSpacedCorrectly>True</SA1022PositiveSignsMustBeSpacedCorrectly><SA1025CodeMustNotContainMultipleWhitespaceInARow>True</SA1025CodeMustNotContainMultipleWhitespaceInARow></StyleCop.Spacing><StyleCop.Readability><SA1100DoNotPrefixCallsWithBaseUnlessLocalImplementationExists>True</SA1100DoNotPrefixCallsWithBaseUnlessLocalImplementationExists><SA1106CodeMustNotContainEmptyStatements>True</SA1106CodeMustNotContainEmptyStatements><SA1108BlockStatementsMustNotContainEmbeddedComments>True</SA1108BlockStatementsMustNotContainEmbeddedComments><SA1109BlockStatementsMustNotContainEmbeddedRegions>True</SA1109BlockStatementsMustNotContainEmbeddedRegions><SA1120CommentsMustContainText>False</SA1120CommentsMustContainText><SA1121UseBuiltInTypeAlias>False</SA1121UseBuiltInTypeAlias><SA1122UseStringEmptyForEmptyStrings>False</SA1122UseStringEmptyForEmptyStrings><SA1123DoNotPlaceRegionsWithinElements>False</SA1123DoNotPlaceRegionsWithinElements><SA1124CodeMustNotContainEmptyRegions>True</SA1124CodeMustNotContainEmptyRegions></StyleCop.Readability><StyleCop.Layout><SA1500CurlyBracketsForMultiLineStatementsMustNotShareLine>False</SA1500CurlyBracketsForMultiLineStatementsMustNotShareLine><SA1509OpeningCurlyBracketsMustNotBePrecededByBlankLine>True</SA1509OpeningCurlyBracketsMustNotBePrecededByBlankLine><SA1510ChainedStatementBlocksMustNotBePrecededByBlankLine>True</SA1510ChainedStatementBlocksMustNotBePrecededByBlankLine><SA1511WhileDoFooterMustNotBePrecededByBlankLine>True</SA1511WhileDoFooterMustNotBePrecededByBlankLine><SA1512SingleLineCommentsMustNotBeFollowedByBlankLine>True</SA1512SingleLineCommentsMustNotBeFollowedByBlankLine><SA1513ClosingCurlyBracketMustBeFollowedByBlankLine>False</SA1513ClosingCurlyBracketMustBeFollowedByBlankLine><SA1514ElementDocumentationHeaderMustBePrecededByBlankLine>False</SA1514ElementDocumentationHeaderMustBePrecededByBlankLine><SA1515SingleLineCommentMustBeProceededByBlankLine>False</SA1515SingleLineCommentMustBeProceededByBlankLine></StyleCop.Layout><StyleCop.Ordering><AlphabeticalUsingDirectives>Ignore</AlphabeticalUsingDirectives><ExpandUsingDirectives>Ignore</ExpandUsingDirectives><SA1212PropertyAccessorsMustFollowOrder>True</SA1212PropertyAccessorsMustFollowOrder><SA1213EventAccessorsMustFollowOrder>True</SA1213EventAccessorsMustFollowOrder></StyleCop.Ordering><CSShortenReferences>True</CSShortenReferences><CSUseVar><BehavourStyle>CAN_CHANGE_TO_EXPLICIT</BehavourStyle><LocalVariableStyle>IMPLICIT_WHEN_INITIALIZER_HAS_TYPE</LocalVariableStyle><ForeachVariableStyle>ALWAYS_EXPLICIT</ForeachVariableStyle></CSUseVar><CSharpFormatDocComments>True</CSharpFormatDocComments></Profile> Cleanup Simple Reformat + Required + Required + Required + Required + BlockScoped 0 0 0 @@ -29,9 +34,11 @@ ONLY_FOR_MULTILINE 1 True - ALWAYS + NEVER NEVER True + NEVER + NEVER NEVER LINE_BREAK False @@ -43,24 +50,34 @@ 180 WRAP_IF_LONG WRAP_IF_LONG + <Patterns xmlns="urn:schemas-jetbrains-com:member-reordering-patterns" /> False False False license - This file is part of $SOLUTION$. + This file is part of ${File.SolutionName}. -$SOLUTION$ is free software: you can redistribute it and/or modify +${File.SolutionName} is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. -$SOLUTION$ is distributed in the hope that it will be useful, +${File.SolutionName} is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License -along with $SOLUTION$. If not, see <http://www.gnu.org/licenses/>. +along with ${File.SolutionName}. If not, see <http://www.gnu.org/licenses/>. + True + False + False + True + False + False + True + False + True AA AC AL @@ -116,19 +133,34 @@ along with $SOLUTION$. If not, see <http://www.gnu.org/licenses/>.<Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> <Policy Inspect="True" Prefix="T" Suffix="" Style="AaBb" /> <Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /> + <Policy><Descriptor Staticness="Static" AccessRightKinds="Private" Description="Static readonly fields (private)"><ElementKinds><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="_" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Private" Description="Constant fields (private)"><ElementKinds><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="_" Suffix="" Style="AaBb" /></Policy> <Policy><Descriptor Staticness="Static, Instance" AccessRightKinds="Private, Protected, ProtectedInternal, Internal, Public" Description="Enums"><ElementKinds><Kind Name="ENUM" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="E" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Any" Description="Type parameters"><ElementKinds><Kind Name="TYPE_PARAMETER" /></ElementKinds></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="T" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Instance" AccessRightKinds="Private" Description="Instance fields (private)"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="_" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Instance" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Instance fields (not private)"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Constant fields (not private)"><ElementKinds><Kind Name="CONSTANT_FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Static" AccessRightKinds="Protected, ProtectedInternal, Internal, Public, PrivateProtected" Description="Static fields (not private)"><ElementKinds><Kind Name="FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Any" Description="Parameters"><ElementKinds><Kind Name="PARAMETER" /></ElementKinds></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="aaBb" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Any" Description="Enum members"><ElementKinds><Kind Name="ENUM_MEMBER" /></ElementKinds></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AaBb" /></Policy> <Policy><Descriptor Staticness="Static, Instance" AccessRightKinds="Private, Protected, ProtectedInternal, Internal, Public" Description="Classes"><ElementKinds><Kind Name="CLASS" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="C" Suffix="" Style="AaBb" /></Policy> <Policy><Descriptor Staticness="Static, Instance" AccessRightKinds="Private, Protected" Description="Fields (not public)"><ElementKinds><Kind Name="FIELD" /><Kind Name="READONLY_FIELD" /><Kind Name="METHOD" /><Kind Name="PROPERTY" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="_" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Any" AccessRightKinds="Any" Description="Types and namespaces"><ElementKinds><Kind Name="NAMESPACE" /><Kind Name="CLASS" /><Kind Name="STRUCT" /><Kind Name="ENUM" /><Kind Name="DELEGATE" /></ElementKinds></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="" Suffix="" Style="AaBb" /></Policy> <Policy><Descriptor Staticness="Static, Instance" AccessRightKinds="Private, Protected, ProtectedInternal, Internal, Public" Description="Structs"><ElementKinds><Kind Name="STRUCT" /></ElementKinds></Descriptor><Policy Inspect="True" Prefix="S" Suffix="" Style="AaBb" /></Policy> + <Policy><Descriptor Staticness="Static" AccessRightKinds="Private" Description="Static fields (private)"><ElementKinds><Kind Name="FIELD" /></ElementKinds></Descriptor><Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="_" Suffix="" Style="AaBb" /></Policy> + True True True True True + True True True True True - False + True + True + Vocaluxe.testsettings True False diff --git a/Vocaluxe/Base/CBackgroundMusic.cs b/Vocaluxe/Base/CBackgroundMusic.cs index 9493f013..70a57453 100644 --- a/Vocaluxe/Base/CBackgroundMusic.cs +++ b/Vocaluxe/Base/CBackgroundMusic.cs @@ -20,8 +20,8 @@ using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using VocaluxeLib; -using VocaluxeLib.Songs; using VocaluxeLib.Draw; +using VocaluxeLib.Songs; using VocaluxeLib.Utils.Player; namespace Vocaluxe.Base @@ -64,7 +64,10 @@ namespace Vocaluxe.Base get { if (IsPlayingPreview) + { return false; + } + return !_BGMusicFiles.Contains(_CurrentPlaylistElement); } } @@ -75,12 +78,19 @@ namespace Vocaluxe.Base set { if (Disabled == value) + { return; + } + _Disabled = value; if (_Disabled) + { Pause(); + } else + { Play(); + } } } @@ -93,9 +103,9 @@ namespace Vocaluxe.Base set { _BGPlayer.Loop = value; } } - public static int SongID + public static int SongId { - get { return _CurPlayer.SongID; } + get { return _CurPlayer.SongId; } } public static bool SongHasVideo @@ -114,7 +124,10 @@ namespace Vocaluxe.Base set { if (IsPlayingPreview == value) + { return; + } + Pause(); _CurPlayer = value ? _PreviewPlayer : _BGPlayer; Play(); @@ -144,7 +157,9 @@ namespace Vocaluxe.Base { _OwnSongsAvailable = value; if (_OwnSongsAvailable && _MusicSource != EBackgroundMusicSource.TR_CONFIG_NO_OWN_MUSIC) + { _AddOwnMusic(); + } } } @@ -155,12 +170,17 @@ namespace Vocaluxe.Base public static void Init() { if (_Initialized) + { return; + } - IEnumerable soundFiles = CHelper.ListSoundFiles(CSettings.FolderNameBackgroundMusic, true, true); + var soundFiles = CHelper.ListSoundFiles(CSettings.FolderNameBackgroundMusic, true, true); - foreach (string path in soundFiles) + foreach (var path in soundFiles) + { _BGMusicFiles.Add(new CPlaylistElement(path)); + } + _CurPlayer = _BGPlayer; //Set a default to have a consistent starting point, use SetMusicSource afterwards _MusicSource = EBackgroundMusicSource.TR_CONFIG_NO_OWN_MUSIC; @@ -185,19 +205,27 @@ namespace Vocaluxe.Base public static void Play() { if (!IsPlayingPreview && CConfig.Config.Sound.BackgroundMusic != EBackgroundMusicOffOn.TR_CONFIG_ON) + { return; + } if (IsPlayingPreview || _BGPlayer.SoundLoaded) + { _CurPlayer.Play(); + } else + { Next(); + } } public static void Stop() { _CurPlayer.Stop(); if (!IsPlayingPreview) + { _CurrentPlaylistElement = null; + } } public static void Pause() @@ -208,7 +236,9 @@ namespace Vocaluxe.Base public static void Next() { if (IsPlayingPreview) + { return; + } Stop(); //stop last song if any if (_PreviousMusicIndex < _PreviousFiles.Count - 2) @@ -223,7 +253,10 @@ namespace Vocaluxe.Base if (_NotPlayedFiles.Count == 0) { if (_PreviousFiles.Count == 0) + { return; //No songs to play + } + _NotPlayedFiles.AddRange(_PreviousFiles); } @@ -233,15 +266,21 @@ namespace Vocaluxe.Base _PreviousFiles.Add(_CurrentPlaylistElement); _PreviousMusicIndex = _PreviousFiles.Count - 1; } + _StartSong(); } public static void Previous() { if (IsPlayingPreview) + { return; + } + if (_PreviousMusicIndex < 0) + { return; + } if (_CurrentPlaylistElement == null || (_BGPlayer.Position <= 1.5f && _PreviousMusicIndex > 0)) { @@ -250,12 +289,13 @@ namespace Vocaluxe.Base _CurrentPlaylistElement = _PreviousFiles[_PreviousMusicIndex]; } + _StartSong(); } public static void Update() { - if (_PreviewStartHelperTask != null && ( _PreviewPlayer.Length > 0 || _PreviewStartWaitCounter++ >= _PreviewStartWaitMaxTries)) + if (_PreviewStartHelperTask != null && (_PreviewPlayer.Length > 0 || _PreviewStartWaitCounter++ >= _PreviewStartWaitMaxTries)) { lock (_PreviewStartHelperTaskLock) { @@ -270,11 +310,15 @@ namespace Vocaluxe.Base } if (!IsPlaying) + { return; + } _CurPlayer.Update(); if (!IsPlayingPreview && _BGPlayer.IsFinished) + { Next(); + } } public static CTextureRef GetVideoTexture() @@ -285,7 +329,10 @@ namespace Vocaluxe.Base public static void SetMusicSource(EBackgroundMusicSource source) { if (_MusicSource == source) + { return; + } + _MusicSource = source; switch (_MusicSource) { @@ -308,7 +355,9 @@ namespace Vocaluxe.Base public static void LoadPreview(CSong song, float start = -1f) { if (song == null) + { throw new ArgumentNullException("song"); + } if (!IsPlayingPreview) { @@ -317,9 +366,11 @@ namespace Vocaluxe.Base } //Change song position only if song is changed or near to end - bool songChanged = _CurPlayer.SongID != song.ID; + var songChanged = _CurPlayer.SongId != song.Id; if (!songChanged && _CurPlayer.Position + 30 < _CurPlayer.Length) + { return; + } _PreviewPlayer.Load(song); @@ -327,33 +378,47 @@ namespace Vocaluxe.Base { _PreviewStartHelperTask = new Task(() => { - float length = _PreviewPlayer.Length; + var length = _PreviewPlayer.Length; if (length < 1) + { length = 30; // If length is unknow or invalid assume a length of 30s + } if (start < 0) - start = (song.Preview.Source == EDataSource.None) ? length / 4f : song.Preview.StartTime; + { + start = song.Preview.Source == EDataSource.None ? length / 4f : song.Preview.StartTime; + } + if (start > length - 5f) + { start = Math.Max(0f, Math.Min(length / 4f, length - 5f)); + } + if (start >= 0.5f) + { start -= 0.5f; + } _PreviewPlayer.Position = start; Play(); }); } + _CurPlayer = _PreviewPlayer; } public static void StopPreview() { if (!IsPlayingPreview) + { return; + } + Stop(); _CurPlayer = _BGPlayer; if (_MusicSource != EBackgroundMusicSource.TR_CONFIG_NO_OWN_MUSIC) { - var song = CSongs.GetSong(_PreviewPlayer.SongID); + var song = CSongs.GetSong(_PreviewPlayer.SongId); if (song != null) { _CurPlayer.Load(song); @@ -364,6 +429,7 @@ namespace Vocaluxe.Base _CurPlayer.Stop(); } } + CSound.SetGlobalVolume(CConfig.BackgroundMusicVolume); } @@ -384,13 +450,18 @@ namespace Vocaluxe.Base //otherwhise load if (!_CurrentPlaylistElement.HasMetaData) + { _BGPlayer.Load(_CurrentPlaylistElement.MusicFilePath, 0f, true); + } else { //Seek to #Start-Tag, if found - float start = 0f; + var start = 0f; if (_CurrentPlaylistElement.Start > 0.001 && CConfig.Config.Sound.BackgroundMusicUseStart == EOffOn.TR_CONFIG_ON) + { start = _CurrentPlaylistElement.Start; + } + _BGPlayer.Load(_CurrentPlaylistElement.Song, start, true); } } @@ -398,22 +469,33 @@ namespace Vocaluxe.Base private static void _AddOwnMusic() { if (_OwnMusicAdded || !_OwnSongsAvailable) + { return; - foreach (CSong song in CSongs.AllSongs) + } + + foreach (var song in CSongs.AllSongs) + { _NotPlayedFiles.Add(new CPlaylistElement(song)); + } + _OwnMusicAdded = true; } private static void _RemoveOwnMusic() { if (!_OwnMusicAdded) + { return; - _NotPlayedFiles.RemoveAll(el => el.SongID >= 0); - _PreviousFiles.RemoveAll(el => el.SongID >= 0); + } + + _NotPlayedFiles.RemoveAll(el => el.SongId >= 0); + _PreviousFiles.RemoveAll(el => el.SongId >= 0); _PreviousMusicIndex = _PreviousFiles.IndexOf(_CurrentPlaylistElement); if (IsPlaying && !_IsBackgroundFile(_CurrentPlaylistElement)) + { Next(); + } _OwnMusicAdded = false; } @@ -421,7 +503,10 @@ namespace Vocaluxe.Base private static void _AddBackgroundMusic() { if (_BackgroundMusicAdded) + { return; + } + _NotPlayedFiles.AddRange(_BGMusicFiles); _BackgroundMusicAdded = true; } @@ -429,13 +514,18 @@ namespace Vocaluxe.Base private static void _RemoveBackgroundMusic() { if (!_BackgroundMusicAdded) + { return; - _NotPlayedFiles.RemoveAll(el => el.SongID < 0); - _PreviousFiles.RemoveAll(el => el.SongID < 0); + } + + _NotPlayedFiles.RemoveAll(el => el.SongId < 0); + _PreviousFiles.RemoveAll(el => el.SongId < 0); _PreviousMusicIndex = _PreviousFiles.IndexOf(_CurrentPlaylistElement); if (IsPlaying && _IsBackgroundFile(_CurrentPlaylistElement)) + { Next(); + } _BackgroundMusicAdded = false; } @@ -445,4 +535,4 @@ namespace Vocaluxe.Base return _BGMusicFiles.Contains(element); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CConfig.cs b/Vocaluxe/Base/CConfig.cs index 91683de0..dae4516a 100644 --- a/Vocaluxe/Base/CConfig.cs +++ b/Vocaluxe/Base/CConfig.cs @@ -17,7 +17,6 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Linq; @@ -28,7 +27,6 @@ using Vocaluxe.Lib.Sound.Record; using Vocaluxe.Lib.Webcam; using VocaluxeLib; using VocaluxeLib.Log; -using VocaluxeLib.Profile; using VocaluxeLib.Xml; namespace Vocaluxe.Base @@ -46,7 +44,7 @@ namespace Vocaluxe.Base #pragma warning disable 649 // ReSharper disable MemberCanBePrivate.Global public struct SConfigInfo - // ReSharper restore MemberCanBePrivate.Global + // ReSharper restore MemberCanBePrivate.Global { // ReSharper disable NotAccessedField.Global // ReSharper disable NotAccessedField.Local @@ -76,7 +74,8 @@ namespace Vocaluxe.Base [DefaultValue(ERenderer.TR_CONFIG_DIRECT3D)] public ERenderer Renderer; #else - [DefaultValue(ERenderer.TR_CONFIG_OPENGL)] public ERenderer Renderer; + [DefaultValue(ERenderer.TR_CONFIG_OPENGL)] + public ERenderer Renderer; #endif [DefaultValue(ETextureQuality.TR_CONFIG_TEXTURE_HIGH)] @@ -116,16 +115,26 @@ namespace Vocaluxe.Base public struct SConfigTheme { - [XmlElement("Name"), DefaultValue("Vocaluxe 2024")] public string Theme; - [DefaultValue("Standard")] public string Skin; - [XmlElement("Cover"), DefaultValue("Vocaluxe 2024")] public string CoverTheme; - [DefaultValue(EOffOn.TR_CONFIG_ON)] public EOffOn DrawNoteLines; - [DefaultValue(EOffOn.TR_CONFIG_ON)] public EOffOn DrawToneHelper; - [DefaultValue(ETimerLook.TR_CONFIG_TIMERLOOK_EXPANDED)] public ETimerLook TimerLook; - [DefaultValue(EPlayerInfo.TR_CONFIG_PLAYERINFO_BOTH)] public EPlayerInfo PlayerInfo; - [DefaultValue(EFadePlayerInfo.TR_CONFIG_FADEPLAYERINFO_OFF)] public EFadePlayerInfo FadePlayerInfo; - [DefaultValue(ECoverLoading.TR_CONFIG_COVERLOADING_DYNAMIC)] public ECoverLoading CoverLoading; - [DefaultValue(ELyricStyle.TR_CONFIG_LYRICSTYLE_SLIDE)] public ELyricStyle LyricStyle; + [XmlElement("Name"), DefaultValue("Vocaluxe 2024")] + public string Theme; + [DefaultValue("Standard")] + public string Skin; + [XmlElement("Cover"), DefaultValue("Vocaluxe 2024")] + public string CoverTheme; + [DefaultValue(EOffOn.TR_CONFIG_ON)] + public EOffOn DrawNoteLines; + [DefaultValue(EOffOn.TR_CONFIG_ON)] + public EOffOn DrawToneHelper; + [DefaultValue(ETimerLook.TR_CONFIG_TIMERLOOK_EXPANDED)] + public ETimerLook TimerLook; + [DefaultValue(EPlayerInfo.TR_CONFIG_PLAYERINFO_BOTH)] + public EPlayerInfo PlayerInfo; + [DefaultValue(EFadePlayerInfo.TR_CONFIG_FADEPLAYERINFO_OFF)] + public EFadePlayerInfo FadePlayerInfo; + [DefaultValue(ECoverLoading.TR_CONFIG_COVERLOADING_DYNAMIC)] + public ECoverLoading CoverLoading; + [DefaultValue(ELyricStyle.TR_CONFIG_LYRICSTYLE_SLIDE)] + public ELyricStyle LyricStyle; } public struct SConfigSound @@ -171,17 +180,28 @@ namespace Vocaluxe.Base [DefaultValue(ESongMenu.TR_CONFIG_TILE_BOARD)] public ESongMenu SongMenu; // ReSharper restore MemberHidesStaticFromOuterClass - [DefaultValue(ESongSorting.TR_CONFIG_ARTIST)] public ESongSorting SongSorting; - [DefaultValue(EOffOn.TR_CONFIG_ON)] public EOffOn IgnoreArticles; - [DefaultValue(ETimerMode.TR_CONFIG_TIMERMODE_REMAINING)] public ETimerMode TimerMode; - [XmlAltName("NumPlayer"), DefaultValue(2)] public int NumPlayers; - [DefaultValue(EOffOn.TR_CONFIG_OFF)] public EOffOn Tabs; - [DefaultValue(EOffOn.TR_CONFIG_OFF)] public EOffOn AutoplayPreviews; - [XmlAltName("AutoplayPreviewDelay"), DefaultValue(500)] public int AutoplayPreviewDelay; - [DefaultValue(ELyricsPosition.TR_CONFIG_LYRICSPOSITION_BOTTOM)] public ELyricsPosition LyricsPosition; - [DefaultValue(0.1f)] public float MinLineBreakTime; //Minimum time to show the text before it is (to be) sung (if possible) - [XmlArrayItem("Player"), XmlArray] public string[] Players; - [DefaultValue(EHighscoreStyle.TR_CONFIG_HIGHSCORE_LIST_BEST)] public EHighscoreStyle HighscoreStyle; + [DefaultValue(ESongSorting.TR_CONFIG_ARTIST)] + public ESongSorting SongSorting; + [DefaultValue(EOffOn.TR_CONFIG_ON)] + public EOffOn IgnoreArticles; + [DefaultValue(ETimerMode.TR_CONFIG_TIMERMODE_REMAINING)] + public ETimerMode TimerMode; + [XmlAltName("NumPlayer"), DefaultValue(2)] + public int NumPlayers; + [DefaultValue(EOffOn.TR_CONFIG_OFF)] + public EOffOn Tabs; + [DefaultValue(EOffOn.TR_CONFIG_OFF)] + public EOffOn AutoplayPreviews; + [XmlAltName("AutoplayPreviewDelay"), DefaultValue(500)] + public int AutoplayPreviewDelay; + [DefaultValue(ELyricsPosition.TR_CONFIG_LYRICSPOSITION_BOTTOM)] + public ELyricsPosition LyricsPosition; + [DefaultValue(0.1f)] + public float MinLineBreakTime; //Minimum time to show the text before it is (to be) sung (if possible) + [XmlArrayItem("Player"), XmlArray] + public string[] Players; + [DefaultValue(EHighscoreStyle.TR_CONFIG_HIGHSCORE_LIST_BEST)] + public EHighscoreStyle HighscoreStyle; } public struct SConfigVideo @@ -243,7 +263,7 @@ namespace Vocaluxe.Base //Folders //We need full path for folders for matching folder path with textfile path when loading public static readonly List SongFolders = new List - { + { #if INSTALLER Path.Combine(CSettings.DataFolder, CSettings.FolderNameSongs), Path.Combine(CSettings.ProgramFolder, FolderNameSongs) @@ -252,13 +272,13 @@ namespace Vocaluxe.Base #elif LINUX Path.Combine(CSettings.DataFolder, CSettings.FolderNameSongs) #endif - }; + }; /// /// Folders with profiles /// First one is used for new profiles /// public static readonly List ProfileFolders = new List - { + { #if INSTALLER Path.Combine(CSettings.DataFolder, CSettings.FolderNameProfiles), CSettings.FolderNameProfiles @@ -366,22 +386,31 @@ namespace Vocaluxe.Base set { if (Config.Game.SongMenu == value) + { return; + } + Config.Game.SongMenu = value; if (SongMenuChanged != null) + { SongMenuChanged(); + } } } public static void Init() { if (_Initialized) + { return; + } // Init config file _LoadConfig(); if (!File.Exists(_FileConfig)) + { SaveConfig(); + } _Initialized = true; } @@ -401,24 +430,35 @@ namespace Vocaluxe.Base { Config = xml.Deserialize(_FileConfig); if (_XmlErrorsOccured) + { CLog.Error("There were some warnings or errors loading the config file. Some values might have been reset to their defaults."); + } } else + { Config = xml.DeserializeString(""); + } NormalizeSongPaths(); if (Config.Game.MinLineBreakTime < 0) + { Config.Game.MinLineBreakTime = 0.1f; + } if (!Config.Game.NumPlayers.IsInRange(1, CSettings.MaxNumPlayer)) + { Config.Game.NumPlayers = 2; + } + Array.Resize(ref Config.Game.Players, CSettings.MaxNumPlayer); if (!Config.Graphics.NumScreens.IsInRange(1, CSettings.MaxNumScreens)) + { Config.Graphics.NumScreens = 1; + } - bool langExists = CLanguage.SetLanguage(Config.Game.Language); + var langExists = CLanguage.SetLanguage(Config.Game.Language); if (langExists == false) { @@ -430,7 +470,9 @@ namespace Vocaluxe.Base Config.Record.MicDelay = (int)(20 * Math.Round(Config.Record.MicDelay / 20.0)); if (!Config.Server.ServerPort.IsInRange(1, 65535)) + { Config.Server.ServerPort = 3000; + } Config.Info = new SConfigInfo { @@ -451,7 +493,10 @@ namespace Vocaluxe.Base { // Avoid multiple comments (e.g. for array entries) if (_CommentsGot.Contains(elName)) + { return null; + } + _CommentsGot.Add(elName); switch (elName) { @@ -576,7 +621,8 @@ namespace Vocaluxe.Base case "ServerPort": return "Server Port (default: 3000) [1..65535]"; case "SongCountCoverThreshold": - return "Threshold of songs for that covers will not longer be included in get-all-songs-requests (e.g. song list) (default: 70) [-1..65535] -1 => always deliver covers"; + return + "Threshold of songs for that covers will not longer be included in get-all-songs-requests (e.g. song list) (default: 70) [-1..65535] -1 => always deliver covers"; case "Stretch": return "Stretch view to full window size: " + CHelper.ListStrings(Enum.GetNames(typeof(EOffOn))); default: @@ -596,7 +642,7 @@ namespace Vocaluxe.Base /// public static float CalcCycleTime() { - return (1f / Config.Graphics.MaxFPS) * 1000f; + return 1f / Config.Graphics.MaxFPS * 1000f; } /// @@ -606,32 +652,43 @@ namespace Vocaluxe.Base /// public static bool IsMicConfig(int player = 0) { - ReadOnlyCollection devices = CRecord.GetDevices(); + var devices = CRecord.GetDevices(); if (devices == null) + { return false; + } if (player > 0) + { return devices.Any(t => t.PlayerChannel.Contains(player)); + } - for (int p = 0; p < CSettings.MaxNumPlayer; ++p) + for (var p = 0; p < CSettings.MaxNumPlayer; ++p) + { if (devices.Any(t => t.PlayerChannel.Contains(p + 1))) { return true; } + } return false; } public static int GetMaxNumMics() { - int max = 0; - for (int i = 1; i <= CSettings.MaxNumPlayer; i++) + var max = 0; + for (var i = 1; i <= CSettings.MaxNumPlayer; i++) { if (IsMicConfig(i)) + { max = i; + } else + { break; + } } + return max; } @@ -647,11 +704,13 @@ namespace Vocaluxe.Base { //Look for (usb-)mic //SRecordDevice[] Devices = new SRecordDevice[CRecord.RecordGetDevices().Length]; - ReadOnlyCollection devices = CRecord.GetDevices(); + var devices = CRecord.GetDevices(); if (devices == null) + { return false; + } - foreach (CRecordDevice device in devices) + foreach (var device in devices) { //Has Device some signal-names in name -> This could be a (usb-)mic if (Regex.IsMatch(device.Name, "Usb|Wireless", RegexOptions.IgnoreCase)) @@ -672,8 +731,9 @@ namespace Vocaluxe.Base } } } + //If no usb-mics found -> Look for Devices with "mic" or "mik" - foreach (CRecordDevice device in devices) + foreach (var device in devices) { //Has Device some signal-names in name -> This could be a mic if (Regex.IsMatch(device.Name, "Mic|Mik", RegexOptions.IgnoreCase)) @@ -712,17 +772,21 @@ namespace Vocaluxe.Base { SongFolders.Clear(); - foreach (string folder in Config.Game.SongFolder) + foreach (var folder in Config.Game.SongFolder) { //Check if folder exists if (Directory.Exists(folder)) + { SongFolders.Add(Path.GetFullPath(folder)); + } } } - + //Test if songfolders are still empty or now empty - if(Config.Game.SongFolder.Length == 0) + if (Config.Game.SongFolder.Length == 0) + { Config.Game.SongFolder = SongFolders.ToArray(); + } } /// @@ -731,19 +795,19 @@ namespace Vocaluxe.Base /// Parameters public static void LoadCommandLineParams(string[] args) { - Regex spliterParam = new Regex(@"-{1,2}|\/", RegexOptions.IgnoreCase); + var spliterParam = new Regex(@"-{1,2}|\/", RegexOptions.IgnoreCase); //Complete argument string - string arguments = args.Aggregate(String.Empty, (current, arg) => current + arg + " "); + var arguments = args.Aggregate(string.Empty, (current, arg) => current + arg + " "); args = spliterParam.Split(arguments); - foreach (string text in args) + foreach (var text in args) { - Regex spliterVal = new Regex(@"\s", RegexOptions.IgnoreCase); + var spliterVal = new Regex(@"\s", RegexOptions.IgnoreCase); //split arg with Spilter-Regex and save in parts - string[] parts = spliterVal.Split(text.Trim(), 2); + var parts = spliterVal.Split(text.Trim(), 2); switch (parts.Length) { @@ -757,6 +821,7 @@ namespace Vocaluxe.Base //Add value _Values.Add(""); } + break; @@ -770,6 +835,7 @@ namespace Vocaluxe.Base //Add value _Values.Add(parts[1]); } + break; } } @@ -781,25 +847,31 @@ namespace Vocaluxe.Base public static void UseCommandLineParamsBefore() { //Check each parameter - for (int i = 0; i < _Params.Count; i++) + for (var i = 0; i < _Params.Count; i++) { //Switch parameter to lower case - string param = _Params[i].ToLower(); + var param = _Params[i].ToLower(); - string value = _Values[i]; + var value = _Values[i]; switch (param) { case "configfile": //Check if value is valid if (_CheckFile(value)) + { _FileConfig = value; + } + break; case "scorefile": //Check if value is valid if (_CheckFile(value)) + { FileHighscoreDB = value; + } + break; case "playlistfolder": @@ -819,16 +891,16 @@ namespace Vocaluxe.Base /// public static void UseCommandLineParamsAfter() { - bool songFoldersOverwritten = false; + var songFoldersOverwritten = false; //Check each parameter - for (int i = 0; i < _Params.Count; i++) + for (var i = 0; i < _Params.Count; i++) { //Switch parameter as lower case - string param = _Params[i]; + var param = _Params[i]; param = param.ToLower(); - string value = _Values[i]; + var value = _Values[i]; switch (param) { @@ -839,8 +911,12 @@ namespace Vocaluxe.Base SongFolders.Clear(); songFoldersOverwritten = true; } + if (!SongFolders.Contains(value)) + { SongFolders.Add(value); + } + break; } } @@ -848,13 +924,16 @@ namespace Vocaluxe.Base private static bool _CheckFile(string value) { - char[] chars = Path.GetInvalidPathChars(); - for (int i = 0; i < chars.Length; i++) + var chars = Path.GetInvalidPathChars(); + for (var i = 0; i < chars.Length; i++) { if (value.Contains(chars[i].ToString())) + { return false; + } } - return !String.IsNullOrEmpty(Path.GetFileName(value)) && Path.HasExtension(value); + + return !string.IsNullOrEmpty(Path.GetFileName(value)) && Path.HasExtension(value); } /// @@ -862,23 +941,25 @@ namespace Vocaluxe.Base /// public static void UsePlayers() { - CProfile[] profiles = CProfiles.GetProfiles(); + var profiles = CProfiles.GetProfiles(); - for (int j = 0; j < CSettings.MaxNumPlayer; j++) + for (var j = 0; j < CSettings.MaxNumPlayer; j++) { - CGame.Players[j].ProfileID = Guid.Empty; + CGame.Players[j].ProfileId = Guid.Empty; if (string.IsNullOrEmpty(Config.Game.Players[j])) + { continue; + } - foreach (CProfile profile in profiles) + foreach (var profile in profiles) { if (Path.GetFileName(profile.FilePath) == Config.Game.Players[j] && profile.Active == EOffOn.TR_CONFIG_ON) { //Update Game-infos with player - CGame.Players[j].ProfileID = profile.ID; + CGame.Players[j].ProfileId = profile.Id; } } } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CController.cs b/Vocaluxe/Base/CController.cs index 773bac5d..e6447c66 100644 --- a/Vocaluxe/Base/CController.cs +++ b/Vocaluxe/Base/CController.cs @@ -44,15 +44,20 @@ namespace Vocaluxe.Base private static void _AddController(IController controller) { if (controller.Init()) + { _Controller.Add(controller); + } } public static void Close() { if (_Controller != null) { - foreach (IController controller in _Controller) + foreach (var controller in _Controller) + { controller.Close(); + } + _Controller = null; _KeysPool = null; _MousePool = null; @@ -61,14 +66,18 @@ namespace Vocaluxe.Base public static void Connect() { - foreach (IController controller in _Controller) + foreach (var controller in _Controller) + { controller.Connect(); + } } public static void Disconnect() { - foreach (IController controller in _Controller) + foreach (var controller in _Controller) + { controller.Disconnect(); + } } public static bool IsConnected() @@ -79,17 +88,21 @@ namespace Vocaluxe.Base public static void Update() { - foreach (IController controller in _Controller) + foreach (var controller in _Controller) { controller.Update(); var ke = new SKeyEvent(); while (controller.PollKeyEvent(ref ke)) + { _KeysPool.Add(ke); + } var me = new SMouseEvent(); while (controller.PollMouseEvent(ref me)) + { _MousePool.Add(me); + } } } @@ -101,6 +114,7 @@ namespace Vocaluxe.Base _KeysPool.RemoveAt(0); return true; } + return false; } @@ -112,13 +126,16 @@ namespace Vocaluxe.Base _MousePool.RemoveAt(0); return true; } + return false; } public static void SetRumble(float duration) { - foreach (IController controller in _Controller) + foreach (var controller in _Controller) + { controller.SetRumble(duration); + } } } } \ No newline at end of file diff --git a/Vocaluxe/Base/CCover.cs b/Vocaluxe/Base/CCover.cs index 152d378a..8c4a1993 100644 --- a/Vocaluxe/Base/CCover.cs +++ b/Vocaluxe/Base/CCover.cs @@ -18,11 +18,10 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Drawing; using System.IO; +using System.Linq; using System.Threading; using System.Threading.Tasks; -using System.Linq; using VocaluxeLib; using VocaluxeLib.Draw; using VocaluxeLib.Log; @@ -69,11 +68,14 @@ namespace Vocaluxe.Base /// public static int GetCoverThemeIndex() { - for (int i = 0; i < _CoverThemes.Count; i++) + for (var i = 0; i < _CoverThemes.Count; i++) { if (_CoverThemes[i].Info.Name == CConfig.Config.Theme.CoverTheme) + { return i; + } } + return -1; } @@ -85,7 +87,9 @@ namespace Vocaluxe.Base lock (_Covers) { if (!_CoverExists(name)) + { return NoCover; + } return _Covers[name]; } @@ -93,27 +97,37 @@ namespace Vocaluxe.Base public static CTextureRef GenerateCover(string text, ECoverGeneratorType type, CSong firstSong) { - CTextureRef texture = Cover(text); + var texture = Cover(text); if (texture != NoCover) + { return texture; + } + texture = CDraw.CopyTexture(NoCover); Task.Factory.StartNew(() => + { + _CancelToken.Token.ThrowIfCancellationRequested(); + var coverBmp = !_CoverGenerators.ContainsKey(type) + ? null : _CoverGenerators[type].GetCover(text, firstSong != null ? Path.Combine(firstSong.Folder, firstSong.CoverFileName) : null); + _CancelToken.Token.ThrowIfCancellationRequested(); + if (coverBmp == null && _CoverGenerators.ContainsKey(ECoverGeneratorType.Default)) { - _CancelToken.Token.ThrowIfCancellationRequested(); - Bitmap coverBmp = !_CoverGenerators.ContainsKey(type) - ? null : _CoverGenerators[type].GetCover(text, firstSong != null ? Path.Combine(firstSong.Folder, firstSong.CoverFileName) : null); - _CancelToken.Token.ThrowIfCancellationRequested(); - if (coverBmp == null && _CoverGenerators.ContainsKey(ECoverGeneratorType.Default)) - coverBmp = _CoverGenerators[ECoverGeneratorType.Default].GetCover(text, firstSong != null ? Path.Combine(firstSong.Folder, firstSong.CoverFileName) : null); - _CancelToken.Token.ThrowIfCancellationRequested(); - if (coverBmp != null) - CDraw.EnqueueTextureUpdate(texture, coverBmp); - _CancelToken.Token.ThrowIfCancellationRequested(); - }, _CancelToken.Token); + coverBmp = _CoverGenerators[ECoverGeneratorType.Default].GetCover(text, firstSong != null ? Path.Combine(firstSong.Folder, firstSong.CoverFileName) : null); + } + + _CancelToken.Token.ThrowIfCancellationRequested(); + if (coverBmp != null) + { + CDraw.EnqueueTextureUpdate(texture, coverBmp); + } + + _CancelToken.Token.ThrowIfCancellationRequested(); + }, _CancelToken.Token); lock (_Covers) { _Covers.Add(text, texture); } + return texture; } @@ -136,7 +150,7 @@ namespace Vocaluxe.Base // Stefan1200: Added a workaround to fix issue #446, because switching the cover theme gets bugged on the song screen and needed a game restart. // Toggle the tabs view fixes this bug somehow. - CSongs.Categorizer.Tabs = (CConfig.Config.Game.Tabs == EOffOn.TR_CONFIG_ON ? EOffOn.TR_CONFIG_OFF : EOffOn.TR_CONFIG_ON); + CSongs.Categorizer.Tabs = CConfig.Config.Game.Tabs == EOffOn.TR_CONFIG_ON ? EOffOn.TR_CONFIG_OFF : EOffOn.TR_CONFIG_ON; CSongs.Categorizer.Tabs = CConfig.Config.Game.Tabs; } @@ -144,13 +158,15 @@ namespace Vocaluxe.Base { lock (_Covers) { - foreach (string key in _Covers.Keys) + foreach (var key in _Covers.Keys) { - CTextureRef texture = _Covers[key]; + var texture = _Covers[key]; CDraw.RemoveTexture(ref texture); } + _Covers.Clear(); } + lock (_CoverGenerators) { _CoverGenerators.Clear(); @@ -162,13 +178,14 @@ namespace Vocaluxe.Base /// private static SThemeCover _GetCoverTheme() { - int index = GetCoverThemeIndex(); + var index = GetCoverThemeIndex(); if (index < 0) { index = 0; CConfig.Config.Theme.CoverTheme = _CoverThemes[0].Info.Name; } - return _CoverThemes[index]; + + return _CoverThemes[index]; } /// @@ -178,11 +195,11 @@ namespace Vocaluxe.Base { _CoverThemes.Clear(); - string folderPath = Path.Combine(CSettings.ProgramFolder, CSettings.FolderNameCover); - IEnumerable files = CHelper.ListFiles(folderPath, "*.xml"); + var folderPath = Path.Combine(CSettings.ProgramFolder, CSettings.FolderNameCover); + var files = CHelper.ListFiles(folderPath, "*.xml"); var xml = new CXmlDeserializer(); - foreach (string file in files) + foreach (var file in files) { SThemeCover theme; try @@ -195,7 +212,7 @@ namespace Vocaluxe.Base continue; } - if (!String.IsNullOrEmpty(theme.Info.Folder) && !String.IsNullOrEmpty(theme.Info.Name)) + if (!string.IsNullOrEmpty(theme.Info.Folder) && !string.IsNullOrEmpty(theme.Info.Name)) { theme.FolderPath = Path.Combine(folderPath, theme.Info.Folder); _CoverThemes.Add(theme); @@ -208,29 +225,38 @@ namespace Vocaluxe.Base /// private static bool _LoadCovers() { - SThemeCover coverTheme = _GetCoverTheme(); + var coverTheme = _GetCoverTheme(); - Debug.Assert(!String.IsNullOrEmpty(coverTheme.Info.Name)); + Debug.Assert(!string.IsNullOrEmpty(coverTheme.Info.Name)); - IEnumerable files = CHelper.ListImageFiles(coverTheme.FolderPath, true, true); + var files = CHelper.ListImageFiles(coverTheme.FolderPath, true, true); lock (_Covers) { - foreach (string file in files) + foreach (var file in files) + { _AddCover(Path.GetFileNameWithoutExtension(file), file); + } + if (_CoverExists(_NoCoverName)) + { NoCover = _Covers[_NoCoverName]; + } else if (_CoverExists(_NoCoverNameAlt)) + { NoCover = _Covers[_NoCoverNameAlt]; + } else { - CLog.Fatal("Covertheme \"{ThemeName}\" does not include a cover file named \"{MissingFileName}\" and cannot be used!", CLog.Params(coverTheme.Info.Name, _NoCoverName)); + CLog.Fatal("Covertheme \"{ThemeName}\" does not include a cover file named \"{MissingFileName}\" and cannot be used!", + CLog.Params(coverTheme.Info.Name, _NoCoverName)); _UnloadCovers(); // Remove current theme and recursively try the other themes _CoverThemes.Remove(coverTheme); return _CoverThemes.Count > 0 && _LoadCovers(); } } + _LoadCoverGenerators(coverTheme); return true; } @@ -271,11 +297,14 @@ namespace Vocaluxe.Base { lock (_CoverGenerators) { - foreach (SThemeCoverGenerator theme in coverTheme.CoverGenerators) + foreach (var theme in coverTheme.CoverGenerators) { if (_CoverGenerators.ContainsKey(theme.Type)) + { continue; - CCoverGenerator el = new CCoverGenerator(theme, coverTheme.FolderPath); + } + + var el = new CCoverGenerator(theme, coverTheme.FolderPath); _CoverGenerators.Add(theme.Type, el); } } @@ -291,8 +320,10 @@ namespace Vocaluxe.Base lock (_Covers) { if (!_CoverExists(name)) + { _Covers.Add(name, CDraw.AddTexture(file)); + } } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CCoverGenerator.cs b/Vocaluxe/Base/CCoverGenerator.cs index 39034d1b..2a10831e 100644 --- a/Vocaluxe/Base/CCoverGenerator.cs +++ b/Vocaluxe/Base/CCoverGenerator.cs @@ -23,9 +23,9 @@ using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Drawing.Text; using System.IO; +using System.Linq; using Vocaluxe.Base.Fonts; using VocaluxeLib; -using System.Linq; namespace Vocaluxe.Base { @@ -49,9 +49,9 @@ namespace Vocaluxe.Base /// /// Split lines after special chars, descending priority /// - private static readonly char[] _SplitCharPreferences = {':', '/', '-'}; - private static readonly char[] _SplitCharAfter = {':', '/', '-', ' ', ')', '.', '*', ','}; - private static readonly char[] _SplitCharBefore = {'('}; + private static readonly char[] _SplitCharPreferences = { ':', '/', '-' }; + private static readonly char[] _SplitCharAfter = { ':', '/', '-', ' ', ')', '.', '*', ',' }; + private static readonly char[] _SplitCharBefore = { '(' }; public CCoverGenerator(SThemeCoverGenerator theme, string basePath) { @@ -64,6 +64,7 @@ namespace Vocaluxe.Base _Image = Path.Combine(basePath, _Theme.Image); _Valid = File.Exists(_Image); } + _MarginLeft = theme.Text.Margin.Left.HasValue ? theme.Text.Margin.Left.Value : theme.Text.Margin.Default; _MarginRight = theme.Text.Margin.Right.HasValue ? theme.Text.Margin.Right.Value : theme.Text.Margin.Default; _MarginTop = theme.Text.Margin.Top.HasValue ? theme.Text.Margin.Top.Value : theme.Text.Margin.Default; @@ -83,9 +84,10 @@ namespace Vocaluxe.Base { if (_WidthTrimmed < 0f) { - string text = Text.TrimEnd(null); + var text = Text.TrimEnd(null); _WidthTrimmed = text.Length == Text.Length ? Width : _Graphics.MeasureString(text, _Font).Width; } + return _WidthTrimmed; } } @@ -94,7 +96,7 @@ namespace Vocaluxe.Base public CTextElement(string text, Graphics g, Font font) { Text = text; - SizeF dimensions = g.MeasureString(text, font); + var dimensions = g.MeasureString(text, font); Width = dimensions.Width; Height = (dimensions.Height + font.Height) / 2; _Graphics = g; @@ -114,28 +116,32 @@ namespace Vocaluxe.Base g.Clear(_BGColor.AsColor()); ImageAttributes ia = null; - if (_Theme.ShowFirstCover && !String.IsNullOrEmpty(firstCoverPath) && File.Exists(firstCoverPath)) + if (_Theme.ShowFirstCover && !string.IsNullOrEmpty(firstCoverPath) && File.Exists(firstCoverPath)) { - using (Bitmap bmp2 = new Bitmap(firstCoverPath)) + using (var bmp2 = new Bitmap(firstCoverPath)) + { g.DrawImage(bmp2, bmpBackground.GetRect(), 0, 0, bmp2.Width, bmp2.Height, GraphicsUnit.Pixel); - ColorMatrix cm = new ColorMatrix {Matrix33 = _Theme.ImageAlpha}; + } + + var cm = new ColorMatrix { Matrix33 = _Theme.ImageAlpha }; ia = new ImageAttributes(); ia.SetColorMatrix(cm); } + g.DrawImage(bmpBackground, bmpBackground.GetRect(), 0, 0, bmpBackground.Width, bmpBackground.Height, GraphicsUnit.Pixel, ia); } private void _DrawText(Graphics g, Size bmpSize, CFont font, List elements) { - Font fo = CFonts.GetSystemFont(font); + var fo = CFonts.GetSystemFont(font); - float maxHeight = elements.Select(el => el.Height).Max(); - int lineCount = elements.Last().Line + 1; + var maxHeight = elements.Select(el => el.Height).Max(); + var lineCount = elements.Last().Line + 1; //Have to use size in em not pixels! - float emSize = fo.Size * fo.FontFamily.GetCellAscent(fo.Style) / fo.FontFamily.GetEmHeight(fo.Style); - float outlineSize = CFonts.GetOutlineSize(font) * font.Height; - SColorF outlineColorF = CFonts.GetOutlineColor(font); + var emSize = fo.Size * fo.FontFamily.GetCellAscent(fo.Style) / fo.FontFamily.GetEmHeight(fo.Style); + var outlineSize = CFonts.GetOutlineSize(font) * font.Height; + var outlineColorF = CFonts.GetOutlineColor(font); outlineColorF.A = outlineColorF.A * _TextColor.A; using (var path = new GraphicsPath()) @@ -143,37 +149,43 @@ namespace Vocaluxe.Base { pen.LineJoin = LineJoin.Round; pen.Alignment = PenAlignment.Outset; - float top = (bmpSize.Height - _MarginBottom - _MarginTop - maxHeight * lineCount) / 2 + _MarginTop; - int nextLineEl = 0; - for (int i = 0; i < lineCount; i++) + var top = (bmpSize.Height - _MarginBottom - _MarginTop - maxHeight * lineCount) / 2 + _MarginTop; + var nextLineEl = 0; + for (var i = 0; i < lineCount; i++) { - int firstEl = nextLineEl; + var firstEl = nextLineEl; for (; nextLineEl < elements.Count; nextLineEl++) { if (elements[nextLineEl].Line > i) + { break; + } } - string line = elements.GetRange(firstEl, nextLineEl - firstEl).Aggregate("", (current, element) => current + element.Text); + var line = elements.GetRange(firstEl, nextLineEl - firstEl).Aggregate("", (current, element) => current + element.Text); float left; if (lineCount == 1 || (i == 1 && lineCount == 3)) { //Center Text if this is the only line or the middle line - float width = _GetWidth(elements, firstEl, nextLineEl - 1); + var width = _GetWidth(elements, firstEl, nextLineEl - 1); left = (bmpSize.Width - _MarginLeft - _MarginRight - width) / 2 + _MarginLeft; } else if (i == lineCount - 1) { //Place last line at right - float width = _GetWidth(elements, firstEl, nextLineEl - 1); + var width = _GetWidth(elements, firstEl, nextLineEl - 1); left = bmpSize.Width - width - _MarginRight; } else + { left = _MarginLeft; + } + //g.DrawString(line, fo, new SolidBrush(_TextColor.AsColor()), left, top, StringFormat.GenericTypographic); path.AddString(line, fo.FontFamily, (int)fo.Style, emSize, new PointF(left, top), StringFormat.GenericTypographic); top += maxHeight + _LineSpace; } + g.DrawPath(pen, path); g.FillPath(new SolidBrush(_TextColor.AsColor()), path); } @@ -182,14 +194,17 @@ namespace Vocaluxe.Base public Bitmap GetCover(string text, string firstCoverPath) { if (!_Valid) - return null; - text = CLanguage.Translate(_Theme.Text.Text.Replace("%TEXT%", text)); - using (Bitmap bmpImage = new Bitmap(_Image)) { - Bitmap bmp = new Bitmap(bmpImage.Width, bmpImage.Height, PixelFormat.Format32bppArgb); + return null; + } + + text = CLanguage.Translate(_Theme.Text.Text.Replace("%TEXT%", text)); + using (var bmpImage = new Bitmap(_Image)) + { + var bmp = new Bitmap(bmpImage.Width, bmpImage.Height, PixelFormat.Format32bppArgb); try { - using (Graphics g = Graphics.FromImage(bmp)) + using (var g = Graphics.FromImage(bmp)) { g.SmoothingMode = SmoothingMode.AntiAlias; g.InterpolationMode = InterpolationMode.HighQualityBicubic; @@ -199,17 +214,21 @@ namespace Vocaluxe.Base if (text != "") { - CFont font = new CFont(_Theme.Text.Font); - Font fo = CFonts.GetSystemFont(font); - IEnumerable textParts = _SplitText(text); - List elements = textParts.Select(line => new CTextElement(line, g, fo)).ToList(); - float factor = _DistributeText(elements, bmp.Width, bmp.Height); - foreach (CTextElement element in elements) + var font = new CFont(_Theme.Text.Font); + var fo = CFonts.GetSystemFont(font); + var textParts = _SplitText(text); + var elements = textParts.Select(line => new CTextElement(line, g, fo)).ToList(); + var factor = _DistributeText(elements, bmp.Width, bmp.Height); + foreach (var element in elements) + { element.AdjustSize(factor); + } + font.Height *= factor / (1f + CFonts.GetOutlineSize(font)); //Adjust for outline size _DrawText(g, bmp.GetSize(), font, elements); } } + return bmp; } catch (Exception) @@ -217,6 +236,7 @@ namespace Vocaluxe.Base bmp.Dispose(); } } + return null; } @@ -230,19 +250,22 @@ namespace Vocaluxe.Base /// Factor for resizing the text (Maximizing this factor means maximizing the height) private float _DistributeText(List elements, int width, int height) { - int availableWidth = width - _MarginLeft - _MarginRight; - int availableHeight = height - _MarginTop - _MarginBottom; + var availableWidth = width - _MarginLeft - _MarginRight; + var availableHeight = height - _MarginTop - _MarginBottom; - float textHeight = elements.Select(el => el.Height).Max(); + var textHeight = elements.Select(el => el.Height).Max(); //Try 1 line: - float textWidth = _GetWidth(elements, 0); - int maxHeight = Math.Min(availableHeight, (int)_Theme.Text.Font.Size); - float factorH = maxHeight / textHeight; - float factorW = availableWidth / textWidth; + var textWidth = _GetWidth(elements, 0); + var maxHeight = Math.Min(availableHeight, (int)_Theme.Text.Font.Size); + var factorH = maxHeight / textHeight; + var factorW = availableWidth / textWidth; if (factorH <= factorW) + { return factorH; //Limited by Height - float factor1 = factorW; + } + + var factor1 = factorW; //Try 2 lines if (elements.Count == 1) @@ -250,15 +273,19 @@ namespace Vocaluxe.Base //Only 1 element -> 1 line return factor1; } + availableWidth -= _Theme.Text.Indent; maxHeight = Math.Min(availableHeight / 2 - _LineSpace, (int)_Theme.Text.Font.Size); factorH = maxHeight / textHeight; if (factorH <= factor1) + { return factor1; //Cannot get any bigger with more lines - int splitEl = _GetSplitElement(elements, textWidth / 2); + } + + var splitEl = _GetSplitElement(elements, textWidth / 2); Debug.Assert(splitEl >= 0 && splitEl < elements.Count - 1); - float width1 = _GetWidth(elements, 0, splitEl); - float width2 = _GetWidth(elements, splitEl + 1); + var width1 = _GetWidth(elements, 0, splitEl); + var width2 = _GetWidth(elements, splitEl + 1); factorW = availableWidth / Math.Max(width1, width2); if (factorH <= factorW) { @@ -268,8 +295,9 @@ namespace Vocaluxe.Base _SetLine(elements, splitEl + 1, elements.Count - 1, 1); return factorH; } + // factor2 < factorH && factorH>factor1 - float factor2 = factorW; + var factor2 = factorW; //Try 3 lines maxHeight = Math.Min(availableHeight / 3 - 2 * _LineSpace, (int)_Theme.Text.Font.Size); @@ -278,29 +306,35 @@ namespace Vocaluxe.Base { //Only 2 elements or cannot get any bigger if (factor2 <= factor1) + { return factor1; + } + _SetLine(elements, splitEl + 1, elements.Count - 1, 1); return factor2; } - int splitEl21 = _GetSplitElement(elements, textWidth / 3, false); - int splitEl22 = _GetSplitElement(elements, textWidth / 3, true, splitEl21 + 1); + + var splitEl21 = _GetSplitElement(elements, textWidth / 3, false); + var splitEl22 = _GetSplitElement(elements, textWidth / 3, true, splitEl21 + 1); Debug.Assert(splitEl21 >= 0 && splitEl21 < splitEl22 && splitEl22 < elements.Count - 1); - float width21 = _GetWidth(elements, 0, splitEl21); - float width22 = _GetWidth(elements, splitEl21 + 1, splitEl22); - float width23 = _GetWidth(elements, splitEl22 + 1); + var width21 = _GetWidth(elements, 0, splitEl21); + var width22 = _GetWidth(elements, splitEl21 + 1, splitEl22); + var width23 = _GetWidth(elements, splitEl22 + 1); factorW = availableWidth / Math.Max(Math.Max(width21, width22), width23); - float factor3 = Math.Min(factorH, factorW); + var factor3 = Math.Min(factorH, factorW); if (factor3 > Math.Max(factor1, factor2)) { _SetLine(elements, splitEl21 + 1, splitEl22, 1); _SetLine(elements, splitEl22 + 1, elements.Count - 1, 2); return factor3; } + if (factor2 > factor1) { _SetLine(elements, splitEl + 1, elements.Count - 1, 1); return factor2; } + return factor1; } @@ -325,19 +359,30 @@ namespace Vocaluxe.Base private static float _GetWidth(List list, int start, int end) { if (start < 0) + { start = 0; + } + if (end >= list.Count) + { end = list.Count - 1; + } + if (start > end) + { return 0f; - float width = list.GetRange(start, end - start).Select(el => el.Width).Sum(); + } + + var width = list.GetRange(start, end - start).Select(el => el.Width).Sum(); return width + list[end].WidthTrimmed; } private static void _SetLine(List list, int start, int end, int line) { - for (int i = start; i <= end; i++) + for (var i = start; i <= end; i++) + { list[i].Line = line; + } } /// @@ -352,63 +397,88 @@ namespace Vocaluxe.Base { //Assert we have enough elements Debug.Assert(singleSplit && elements.Count - startElement >= 2 || !singleSplit && elements.Count - startElement >= 3); - float curWidth = 0f; + var curWidth = 0f; int splitEl; for (splitEl = startElement; splitEl < elements.Count; splitEl++) { curWidth += elements[splitEl].Width; if (curWidth >= requestedWidth) + { break; + } } // At this point we can either keep splitEl on this line for move it to the next line // ==> line with splitEl is to long, without it is to short. so find the best option // Check if line starts or ends with a long word, than put that on a single line if (splitEl == startElement) + { return splitEl; + } + // These 2 conditions also cover if the text fits on 1 line if (!singleSplit && splitEl >= elements.Count - 2) + { return elements.Count - 3; // Make sure we have 2 elements left if in multi split mode! - if (splitEl >= elements.Count - 1) - return elements.Count - 2; // Make sure we have 1 element left! + } - float diffWith = curWidth - requestedWidth; - float diffWithout = requestedWidth - (curWidth - elements[splitEl].Width); + if (splitEl >= elements.Count - 1) + { + return elements.Count - 2; // Make sure we have 1 element left! + } + + var diffWith = curWidth - requestedWidth; + var diffWithout = requestedWidth - (curWidth - elements[splitEl].Width); if (!singleSplit) { // If we split in 3 lines, add the error of the next 2 lines to the current error for both cases - int splitEl2 = _GetSplitElement(elements, requestedWidth, true, splitEl + 1); - int splitEl3 = _GetSplitElement(elements, requestedWidth, true, splitEl); + var splitEl2 = _GetSplitElement(elements, requestedWidth, true, splitEl + 1); + var splitEl3 = _GetSplitElement(elements, requestedWidth, true, splitEl); diffWith += Math.Abs(requestedWidth - _GetWidth(elements, splitEl + 1, splitEl2)) + Math.Abs(requestedWidth - _GetWidth(elements, splitEl2 + 1)); diffWithout += Math.Abs(requestedWidth - _GetWidth(elements, splitEl, splitEl3)) + Math.Abs(requestedWidth - _GetWidth(elements, splitEl3 + 1)); } - float diff = diffWith - diffWithout; + + var diff = diffWith - diffWithout; //Differences below this value are considered acceptable - float equalDist = requestedWidth * 0.025f; + var equalDist = requestedWidth * 0.025f; if (diff > equalDist) + { return splitEl - 1; // width error with element is much higher than without -> put element on next line + } + if (diff < -equalDist) + { return splitEl; // width error with element is much less than without -> keep element on line + } //The real split would be somewhere in the middle of the element so we can move it to either line - string tmp = elements[splitEl].Text.TrimEnd(null); - char lastCharWith = tmp[tmp.Length - 1]; + var tmp = elements[splitEl].Text.TrimEnd(null); + var lastCharWith = tmp[tmp.Length - 1]; tmp = elements[splitEl - 1].Text.TrimEnd(null); - char lastCharWithout = tmp[tmp.Length - 1]; + var lastCharWithout = tmp[tmp.Length - 1]; //Check if last chars are special chars if (Char.IsLetterOrDigit(lastCharWith)) { if (Char.IsLetterOrDigit(lastCharWithout)) + { return startElement == 0 ? splitEl : splitEl - 1; //Both are alphanumeric, favor longer first lines but shorter middle lines + } + return splitEl - 1; //Split after non-alphanumeric char } - if (Char.IsLetterOrDigit(lastCharWithout)) - return splitEl; //Split after non-alphanumeric char - int indexWith = Array.IndexOf(_SplitCharPreferences, lastCharWith); - int indexWithout = Array.IndexOf(_SplitCharPreferences, lastCharWithout); + if (Char.IsLetterOrDigit(lastCharWithout)) + { + return splitEl; //Split after non-alphanumeric char + } + + var indexWith = Array.IndexOf(_SplitCharPreferences, lastCharWith); + var indexWithout = Array.IndexOf(_SplitCharPreferences, lastCharWithout); if (indexWith <= indexWithout) + { return startElement == 0 ? splitEl : splitEl - 1; //favor longer first lines but shorter middle lines + } + return splitEl - 1; } @@ -422,15 +492,16 @@ namespace Vocaluxe.Base Debug.Assert(!String.IsNullOrWhiteSpace(text)); text = text.Trim().TrimMultipleWs(); - List lines = new List(); + var lines = new List(); if (text.Length == 1) { lines.Add(text); return lines; } + //Split the text on non-letter chars - int curStart = 0; - for (int i = 1; i < text.Length - 1; i++) + var curStart = 0; + for (var i = 1; i < text.Length - 1; i++) { if ((Array.IndexOf(_SplitCharAfter, text[i]) >= 0 && (Char.IsLetterOrDigit(text, i + 1) || Array.IndexOf(_SplitCharBefore, text[i + 1]) >= 0)) || (Char.IsLetterOrDigit(text, i) && Array.IndexOf(_SplitCharBefore, text[i + 1]) >= 0)) @@ -439,20 +510,24 @@ namespace Vocaluxe.Base curStart = ++i; } } + //Add the rest lines.Add(text.Substring(curStart)); //Check for initials (like J. R.R. Tolkien) and join them curStart = -1; - string curText = ""; - for (int i = 0; i < lines.Count; i++) + var curText = ""; + for (var i = 0; i < lines.Count; i++) { - string part = lines[i].Trim(); + var part = lines[i].Trim(); if (part.Length == 2 && part[1] == '.') { //Initials found, continue or start new if (curStart < 0) + { curStart = i; + } + curText += lines[i]; } else if (curStart >= 0) @@ -465,10 +540,12 @@ namespace Vocaluxe.Base lines.RemoveRange(curStart + 1, i - curStart - 1); i = curStart; } + curText = ""; curStart = -1; } } + //Handle last part if (curStart >= 0) { @@ -482,14 +559,16 @@ namespace Vocaluxe.Base } // Remove single char lines - for (int i = 0; i < lines.Count; i++) + for (var i = 0; i < lines.Count; i++) { - string part = lines[i]; + var part = lines[i]; if (part.Trim().Length == 1) { lines.RemoveAt(i); if (i == 0) + { lines[0] = part + lines[0]; + } else { lines[i - 1] += part; @@ -497,6 +576,7 @@ namespace Vocaluxe.Base } } } + return lines; } } diff --git a/Vocaluxe/Base/CCursor.cs b/Vocaluxe/Base/CCursor.cs index fe8629d8..60bdbcf7 100644 --- a/Vocaluxe/Base/CCursor.cs +++ b/Vocaluxe/Base/CCursor.cs @@ -54,18 +54,24 @@ namespace Vocaluxe.Base public void Draw() { if (_Movetimer.ElapsedMilliseconds > CSettings.MouseMoveOffTime) + { Deactivate(); + } if (_Fading != null) { bool finished; _Cursor.Color.A = _Fading.GetValue(out finished); if (finished) + { _Fading = null; + } } if (Visible && (CSettings.ProgramState == EProgramState.EditTheme || ShowCursor)) + { CDraw.DrawTexture(_Cursor); + } } public void UpdatePosition(int x, int y) @@ -87,7 +93,7 @@ namespace Vocaluxe.Base public void LoadSkin() { - SThemeCursor theme = CThemes.GetCursorTheme(); + var theme = CThemes.GetCursorTheme(); _Cursor = CDraw.CopyTexture(CThemes.GetSkinTexture(theme.SkinName, -1)); theme.Color.Get(-1, out _Cursor.Color); @@ -103,8 +109,8 @@ namespace Vocaluxe.Base public void ReloadSkin() { - int x = X; - int y = Y; + var x = X; + var y = Y; UnloadSkin(); LoadSkin(); UpdatePosition(x, y); @@ -113,7 +119,10 @@ namespace Vocaluxe.Base public void Deactivate() { if (!IsActive) + { return; + } + _MouseMoveDiffMin = CSettings.MouseMoveDiffMinInactive; _Movetimer.Reset(); _Fade(0f, 0.5f); @@ -122,10 +131,13 @@ namespace Vocaluxe.Base public void Activate() { // Here we need to restart the timer in all cases but only set fading and diff if we are not yet active - bool active = IsActive; + var active = IsActive; _Movetimer.Restart(); if (active) + { return; + } + _MouseMoveDiffMin = CSettings.MouseMoveDiffMinActive; _Fade(1f, 0.2f); } diff --git a/Vocaluxe/Base/CDataBase.cs b/Vocaluxe/Base/CDataBase.cs index 1cf8c52c..47e9f310 100644 --- a/Vocaluxe/Base/CDataBase.cs +++ b/Vocaluxe/Base/CDataBase.cs @@ -40,11 +40,13 @@ namespace Vocaluxe.Base CLog.Fatal("Error initializing Highscore-DB"); return false; } + if (!_CoverDB.Init()) { CLog.Fatal("Error initializing Cover-DB"); return false; - } + } + return true; } @@ -55,6 +57,7 @@ namespace Vocaluxe.Base _HighscoreDB.Close(); _HighscoreDB = null; } + if (_CoverDB != null) { _CoverDB.Close(); @@ -62,21 +65,22 @@ namespace Vocaluxe.Base } } - public static bool GetDataBaseSongInfos(string artist, string title, out int numPlayed, out DateTime dateAdded, out int highscoreID) + public static bool GetDataBaseSongInfos(string artist, string title, out int numPlayed, out DateTime dateAdded, out int highscoreId) { if (_HighscoreDB == null) { numPlayed = 0; dateAdded = new DateTime(); - highscoreID = 0; + highscoreId = 0; return false; } - return _HighscoreDB.GetDataBaseSongInfos(artist, title, out numPlayed, out dateAdded, out highscoreID); + + return _HighscoreDB.GetDataBaseSongInfos(artist, title, out numPlayed, out dateAdded, out highscoreId); } - public static List LoadScore(int songID, EGameMode gameMode, EHighscoreStyle style) + public static List LoadScore(int songId, EGameMode gameMode, EHighscoreStyle style) { - return _HighscoreDB == null ? null : _HighscoreDB.LoadScore(songID, gameMode, style); + return _HighscoreDB == null ? null : _HighscoreDB.LoadScore(songId, gameMode, style); } public static int AddScore(SPlayer player) @@ -84,10 +88,12 @@ namespace Vocaluxe.Base return _HighscoreDB == null ? -1 : _HighscoreDB.AddScore(player); } - public static void IncreaseSongCounter(int dataBaseSongID) + public static void IncreaseSongCounter(int dataBaseSongId) { if (_HighscoreDB != null) - _HighscoreDB.IncreaseSongCounter(dataBaseSongID); + { + _HighscoreDB.IncreaseSongCounter(dataBaseSongId); + } } public static bool GetCover(string fileName, ref CTextureRef tex, int maxSize) @@ -98,7 +104,9 @@ namespace Vocaluxe.Base public static void CommitCovers() { if (_CoverDB != null) + { _CoverDB.CommitCovers(); + } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CDraw.cs b/Vocaluxe/Base/CDraw.cs index 65dbe81b..1f831277 100644 --- a/Vocaluxe/Base/CDraw.cs +++ b/Vocaluxe/Base/CDraw.cs @@ -35,7 +35,10 @@ namespace Vocaluxe.Base public static bool Init() { if (_Draw != null) + { return false; + } + switch (CConfig.Config.Graphics.Renderer) { case ERenderer.TR_CONFIG_SOFTWARE: @@ -52,6 +55,7 @@ namespace Vocaluxe.Base CLog.Fatal(e, "Error in initializing of OpenGL. Please check whether your graphic card drivers are up to date."); return false; } + break; #if WIN @@ -66,6 +70,7 @@ namespace Vocaluxe.Base "download the DirectX runtimes at https://www.microsoft.com/en-us/download/details.aspx?id=8109"); return false; } + break; #endif @@ -73,6 +78,7 @@ namespace Vocaluxe.Base _Draw = new CDrawWinForm(); break; } + return _Draw.Init(); } @@ -267,7 +273,9 @@ namespace Vocaluxe.Base { // Disposed textures call this, possibly at program end! if (_Draw != null) + { _Draw.RemoveTexture(ref texture); + } } /// @@ -383,9 +391,11 @@ namespace Vocaluxe.Base public static void DrawTexture(CTextureRef textureRef, SRectF bounds, EAspect aspect, SColorF color) { if (textureRef == null) + { return; + } - SRectF rect = CHelper.FitInBounds(bounds, textureRef.OrigAspect, aspect); + var rect = CHelper.FitInBounds(bounds, textureRef.OrigAspect, aspect); DrawTexture(textureRef, rect, color, bounds); } @@ -403,4 +413,4 @@ namespace Vocaluxe.Base _Draw.DrawTextureReflection(textureRef, rect, color, bounds, space, height, allMonitors); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CGame.cs b/Vocaluxe/Base/CGame.cs index 9b101a00..f4f4c2b2 100644 --- a/Vocaluxe/Base/CGame.cs +++ b/Vocaluxe/Base/CGame.cs @@ -38,12 +38,8 @@ namespace Vocaluxe.Base /// Last beat that has been evaluated /// private static int _LastEvalBeat; - private static readonly Random _Rand = new Random(); - public static Random Rand - { - get { return _Rand; } - } + public static Random Rand { get; } = new Random(); public static float GetBeatFromTime(float time, float bpm, float gap) { @@ -53,7 +49,9 @@ namespace Vocaluxe.Base public static float GetTimeFromBeats(float beats, float bpm) { if (bpm > 0f) + { return beats / bpm * 60f; + } return 0f; } @@ -185,7 +183,9 @@ namespace Vocaluxe.Base set { if (value > 0 && value <= CSettings.MaxNumPlayer) + { _NumPlayers = value; + } } } @@ -196,7 +196,7 @@ namespace Vocaluxe.Base public static void ResetPlayer() { - for (int i = 0; i < Players.Length; i++) + for (var i = 0; i < Players.Length; i++) { Players[i].Points = 0f; Players[i].PointsLineBonus = 0f; @@ -207,13 +207,14 @@ namespace Vocaluxe.Base Players[i].SungLines = new List(); Players[i].CurrentLine = -1; Players[i].CurrentNote = -1; - Players[i].SongID = -1; + Players[i].SongId = -1; Players[i].GameMode = EGameMode.TR_GAMEMODE_NORMAL; Players[i].DateTicks = DateTime.Now.Ticks; Players[i].SongFinished = false; Players[i].RatingLastLine = 0f; Players[i].TimeLastLineChange = float.MaxValue; } + _LastEvalBeat = -100; CurrentBeatF = -100; MidRecordedBeat = -100; @@ -221,37 +222,49 @@ namespace Vocaluxe.Base public static void UpdatePoints(float time) { - CSong song = _SongQueue.GetSong(); + var song = _SongQueue.GetSong(); if (song == null) + { return; + } - float b = GetBeatFromTime(time, song.BPM, song.Gap); + var b = GetBeatFromTime(time, song.Bpm, song.Gap); if (b <= CurrentBeatF) + { return; + } CurrentBeatF = b; - MidRecordedBeat = -0.5f + GetBeatFromTime(time, song.BPM, song.Gap + CConfig.Config.Record.MicDelay / 1000f); + MidRecordedBeat = -0.5f + GetBeatFromTime(time, song.Bpm, song.Gap + CConfig.Config.Record.MicDelay / 1000f); - for (int p = 0; p < _NumPlayers; p++) + for (var p = 0; p < _NumPlayers; p++) + { CRecord.AnalyzeBuffer(p); + } if (_LastEvalBeat >= RecordedBeat) - return; - - for (int p = 0; p < _NumPlayers; p++) { - for (int beat = _LastEvalBeat + 1; beat <= RecordedBeat; beat++) + return; + } + + for (var p = 0; p < _NumPlayers; p++) + { + for (var beat = _LastEvalBeat + 1; beat <= RecordedBeat; beat++) { if ((_SongQueue.GetCurrentGameMode() == EGameMode.TR_GAMEMODE_MEDLEY && song.Medley.EndBeat == beat) || (_SongQueue.GetCurrentGameMode() == EGameMode.TR_GAMEMODE_SHORTSONG && song.ShortEnd.EndBeat == beat)) + { Players[p].SongFinished = true; + } - CSongLine[] lines = song.Notes.GetVoice(Players[p].VoiceNr).Lines; - int line = song.Notes.GetVoice(Players[p].VoiceNr).FindPreviousLine(beat); + var lines = song.Notes.GetVoice(Players[p].VoiceNr).Lines; + var line = song.Notes.GetVoice(Players[p].VoiceNr).FindPreviousLine(beat); if (line < 0 || lines[line].EndBeat < beat) + { continue; + } if (Players[p].CurrentLine != line && line > 0) { @@ -260,48 +273,59 @@ namespace Vocaluxe.Base //Check for already sung if (line < Players[p].SungLines.Count - 1) + { continue; // Already sung whole line + } + if (line == Players[p].SungLines.Count - 1) { //We are in the last line if (beat <= Players[p].SungLines[line].LastNoteBeat) + { continue; //We already have something that ends with/after that beat + } } if (line != Players[p].CurrentLine) + { Players[p].CurrentNote = -1; + } Players[p].CurrentLine = line; while (Players[p].SungLines.Count <= line) + { Players[p].SungLines.Add(new CSungLine()); + } - CSongNote[] notes = lines[line].Notes; - int note = lines[line].FindPreviousNote(beat); + var notes = lines[line].Notes; + var note = lines[line].FindPreviousNote(beat); if (note < 0 || notes[note].EndBeat < beat) + { continue; + } Players[p].CurrentNote = note; if (line == lines.Length - 1 && beat == lines[line].LastNoteBeat) - Players[p].SongFinished = true; - - if (notes[note].PointsForBeat > 0 && (CRecord.ToneValid(p) -#if DEBUG_HIT - || true -#elif DEBUG_HIT_1 - || (true && p == 0) -#endif - )) { - int tone = notes[note].Tone; - int tonePlayer = CRecord.GetTone(p); + Players[p].SongFinished = true; + } + + if (notes[note].PointsForBeat > 0 && CRecord.ToneValid(p)) + { + var tone = notes[note].Tone; + var tonePlayer = CRecord.GetTone(p); while (tonePlayer - tone > 6) + { tonePlayer -= 12; + } while (tonePlayer - tone < -6) + { tonePlayer += 12; + } #if DEBUG_HIT tonePlayer = tone; @@ -310,29 +334,35 @@ namespace Vocaluxe.Base #endif if (notes[note].Type == ENoteType.Rap || notes[note].Type == ENoteType.RapGolden) + { tonePlayer = tone; + } Players[p].NoteDiff = Math.Abs(tone - tonePlayer); - bool hit = Players[p].NoteDiff <= (2 - (int)CProfiles.GetDifficulty(Players[p].ProfileID)); + var hit = Players[p].NoteDiff <= 2 - (int)CProfiles.GetDifficulty(Players[p].ProfileId); if (hit) { // valid //CRecord.RecordSetTone(p, Tone); - double points = (CSettings.MaxScore - CSettings.LinebonusScore) * (double)notes[note].PointsForBeat / - song.Notes.GetVoice(Players[p].VoiceNr).Points; + var points = (CSettings.MaxScore - CSettings.LinebonusScore) * (double)notes[note].PointsForBeat / + song.Notes.GetVoice(Players[p].VoiceNr).Points; if (notes[note].Type == ENoteType.Golden || notes[note].Type == ENoteType.RapGolden) + { Players[p].PointsGoldenNotes += points; + } Players[p].Points += points; // update player notes (sung notes) if (Players[p].SungLines[line].NoteCount > 0) { - CSungNote lastNote = Players[p].SungLines[line].LastNote; + var lastNote = Players[p].SungLines[line].LastNote; if (notes[note].StartBeat == beat || lastNote.EndBeat + 1 != beat || lastNote.Tone != tone || !lastNote.Hit) + { Players[p].SungLines[line].AddNote(new CSungNote(beat, 1, tone, notes[note], points)); + } else { Players[p].SungLines[line].IncLastNoteLength(); @@ -340,7 +370,9 @@ namespace Vocaluxe.Base } } else + { Players[p].SungLines[line].AddNote(new CSungNote(beat, 1, tone, notes[note], points)); + } Players[p].SungLines[line].LastNote.CheckPerfect(); Players[p].SungLines[line].IsPerfect(lines[line]); @@ -349,27 +381,37 @@ namespace Vocaluxe.Base { if (Players[p].SungLines[line].NoteCount > 0) { - CSungNote lastNote = Players[p].SungLines[line].LastNote; + var lastNote = Players[p].SungLines[line].LastNote; if (lastNote.Tone != tonePlayer || lastNote.EndBeat + 1 != beat || lastNote.Hit) + { Players[p].SungLines[line].AddNote(new CSungNote(beat, 1, tonePlayer)); + } else + { Players[p].SungLines[line].IncLastNoteLength(); + } } else + { Players[p].SungLines[line].AddNote(new CSungNote(beat, 1, tonePlayer)); + } } } // Check if line ended - int numLinesWithPoints = song.Notes.GetNumLinesWithPoints(Players[p].VoiceNr); + var numLinesWithPoints = song.Notes.GetNumLinesWithPoints(Players[p].VoiceNr); if (beat == lines[line].LastNoteBeat && lines[line].Points > 0 && numLinesWithPoints > 0) { // Line Bonus - double factor = Players[p].SungLines[line].Points / (double)lines[line].Points; + var factor = Players[p].SungLines[line].Points / (double)lines[line].Points; if (factor <= 0.4) + { factor = 0.0; + } else if (factor >= 0.9) + { factor = 1.0; + } else { factor -= 0.4; @@ -377,71 +419,88 @@ namespace Vocaluxe.Base factor *= factor; } - double points = CSettings.LinebonusScore * factor / numLinesWithPoints; + var points = CSettings.LinebonusScore * factor / numLinesWithPoints; Players[p].Points += points; Players[p].PointsLineBonus += points; Players[p].SungLines[line].BonusPoints += points; //Calculate rating //Shift fraction of correct sung notes to [-0.1, 0.1], player needs to sing five lines fully correctly to get highest ranking - double current = Players[p].SungLines[line].Points / (double)lines[line].Points; + var current = Players[p].SungLines[line].Points / (double)lines[line].Points; Players[p].Rating = (Players[p].Rating + (current * 0.2 - 0.1)).Clamp(0, 1); Players[p].RatingLastLine = current; } } } + _LastEvalBeat = RecordedBeat; } public static void ResetToLastLine(int soundStream, CVideoStream vidStream) { - float[] time = _GetLastSungLineStart(); + var time = _GetLastSungLineStart(); ResetToTime(time[0], time[1], soundStream, vidStream); } public static void ResetToTime(float time, float nextStart, int soundStream, CVideoStream vidStream) { if (time < 0) + { time = 0; + } - CurrentBeatF = GetBeatFromTime(time, GetSong().BPM, GetSong().Gap); + CurrentBeatF = GetBeatFromTime(time, GetSong().Bpm, GetSong().Gap); - for (int p = 0; p < _NumPlayers; p++) + for (var p = 0; p < _NumPlayers; p++) { Players[p].Points = 0; Players[p].PointsGoldenNotes = 0; Players[p].PointsLineBonus = 0; - int l = 0; - int deleteLine = 0; - foreach (CSungLine line in Players[p].SungLines) + var l = 0; + var deleteLine = 0; + foreach (var line in Players[p].SungLines) { - int n = -1; - int deleteNote = 0; + var n = -1; + var deleteNote = 0; Players[p].PointsLineBonus += line.BonusPoints; - foreach (CSungNote note in line.Notes) + foreach (var note in line.Notes) { if (note.StartBeat < nextStart) { if (note.Hit && (note.HitNote.Type == ENoteType.Golden || note.HitNote.Type == ENoteType.RapGolden)) + { Players[p].PointsGoldenNotes += note.Points; + } + Players[p].Points += note.Points; } else if (deleteNote != -1) + { deleteNote = n; + } + n++; } + while (line.NoteCount > n && n >= 0) { if (line.Notes[n].Hit && (line.Notes[n].HitNote.Type == ENoteType.Golden || line.Notes[n].HitNote.Type == ENoteType.RapGolden)) + { Players[p].PointsGoldenNotes -= line.Notes[n].Points; + } + Players[p].Points -= line.Notes[n].Points; line.DeleteNote(n); } if (line.LastNoteBeat > CurrentBeat && deleteLine == 0) + { deleteLine = l; + } + l++; } + Players[p].SungLines.RemoveRange(deleteLine, Players[p].SungLines.Count - deleteLine); } @@ -456,34 +515,44 @@ namespace Vocaluxe.Base private static float[] _GetNoteTimeBeforeBeat(int beat) { - CSong song = GetSong(); - int startBeat = (int)Math.Floor(beat - GetBeatFromTime(CSettings.PauseResetTime, song.BPM, 0f)); - int lastStart = 0; - int nextStart = 0; - foreach (CVoice voice in song.Notes.Voices) + var song = GetSong(); + var startBeat = (int)Math.Floor(beat - GetBeatFromTime(CSettings.PauseResetTime, song.Bpm, 0f)); + var lastStart = 0; + var nextStart = 0; + foreach (var voice in song.Notes.Voices) { - int lastEnd = 0; - int voiceStart = 0; - int nextStartNote = 0; - foreach (CSongLine line in voice.Lines) + var lastEnd = 0; + var voiceStart = 0; + var nextStartNote = 0; + foreach (var line in voice.Lines) { - foreach (CSongNote note in line.Notes) + foreach (var note in line.Notes) { if (note.StartBeat > startBeat) { nextStartNote = note.StartBeat; break; } + voiceStart = note.StartBeat; lastEnd = note.EndBeat; } + if (nextStartNote > 0) + { break; + } } + if (nextStartNote - beat > CSettings.PauseResetTime) + { lastStart = beat; + } else if (nextStartNote - lastEnd > CSettings.PauseResetTime) - lastStart = nextStartNote - (int)Math.Floor(GetBeatFromTime(CSettings.PauseResetTime, song.BPM, 0f)); + { + lastStart = nextStartNote - (int)Math.Floor(GetBeatFromTime(CSettings.PauseResetTime, song.Bpm, 0f)); + } + if (voiceStart > lastStart) { lastStart = voiceStart; @@ -491,7 +560,7 @@ namespace Vocaluxe.Base } } - return new float[] {GetTimeFromBeats(lastStart, GetSong().BPM), nextStart}; + return new float[] { GetTimeFromBeats(lastStart, GetSong().Bpm), nextStart }; } } } \ No newline at end of file diff --git a/Vocaluxe/Base/CGraphics.cs b/Vocaluxe/Base/CGraphics.cs index eb0edf59..b1931981 100644 --- a/Vocaluxe/Base/CGraphics.cs +++ b/Vocaluxe/Base/CGraphics.cs @@ -53,7 +53,7 @@ namespace Vocaluxe.Base { get { - int id = _Screens.IndexOf(NextScreen); + var id = _Screens.IndexOf(NextScreen); return (EScreen)id; } } @@ -92,6 +92,7 @@ namespace Vocaluxe.Base _PopupScreens.Add(new CPopupScreenVolumeControl()); _PopupScreens.Add(new CPopupScreenServerQR()); } + CurrentScreen = _Screens[(int)EScreen.Load]; NextScreen = null; _CurrentPopupScreen = EPopupScreens.NoPopup; @@ -109,39 +110,48 @@ namespace Vocaluxe.Base public static void Close() { if (_CurrentPopupScreen != EPopupScreens.NoPopup && _PopupScreens.Count > 0) + { _PopupScreens[(int)_CurrentPopupScreen].OnClose(); + } + if (CurrentScreen != null) + { CurrentScreen.OnClose(); + } } public static void LoadTheme() { _Cursor.LoadSkin(); - for (int i = 0; i < _Screens.Count; i++) + for (var i = 0; i < _Screens.Count; i++) { using (CBenchmark.Time("Load Theme " + Enum.GetNames(typeof(EScreen))[i])) { _Screens[i].Init(); - _Screens[i].LoadTheme(CThemes.GetThemeScreensPath(_Screens[i].PartyModeID)); + _Screens[i].LoadTheme(CThemes.GetThemeScreensPath(_Screens[i].PartyModeId)); } } - foreach (IMenu popup in _PopupScreens) + foreach (var popup in _PopupScreens) { popup.Init(); - popup.LoadTheme(CThemes.GetThemeScreensPath(popup.PartyModeID)); + popup.LoadTheme(CThemes.GetThemeScreensPath(popup.PartyModeId)); } } public static void ReloadTheme() { _Cursor.ReloadSkin(); - foreach (IMenu screen in _Screens) - screen.ReloadTheme(CThemes.GetThemeScreensPath(screen.PartyModeID)); + foreach (var screen in _Screens) + { + screen.ReloadTheme(CThemes.GetThemeScreensPath(screen.PartyModeId)); + } - foreach (IMenu popup in _PopupScreens) - popup.ReloadTheme(CThemes.GetThemeScreensPath(popup.PartyModeID)); + foreach (var popup in _PopupScreens) + { + popup.ReloadTheme(CThemes.GetThemeScreensPath(popup.PartyModeId)); + } CParty.ReloadTheme(); } @@ -149,11 +159,15 @@ namespace Vocaluxe.Base public static void ReloadSkin() { _Cursor.ReloadSkin(); - foreach (IMenu menu in _Screens) + foreach (var menu in _Screens) + { menu.ReloadSkin(); + } - foreach (IMenu menu in _PopupScreens) + foreach (var menu in _PopupScreens) + { menu.ReloadSkin(); + } CParty.ReloadSkin(); } @@ -163,13 +177,17 @@ namespace Vocaluxe.Base foreach (CMenu screen in _Screens) { if (screen.ThemePath == null || screen.ThemeName == "ScreenTest") + { continue; + } screen.SaveTheme(); } - foreach (IMenu popup in _PopupScreens) + foreach (var popup in _PopupScreens) + { popup.SaveTheme(); + } CParty.SaveThemes(); } @@ -182,7 +200,7 @@ namespace Vocaluxe.Base public static bool UpdateGameLogic(CKeys keys, CMouse mouse) { - bool run = true; + var run = true; _Cursor.Visible = mouse.Visible; mouse.CopyEvents(); @@ -215,27 +233,35 @@ namespace Vocaluxe.Base { _Fading = new CFading(0f, 1f, CConfig.Config.Graphics.FadeTime); - if (NextScreen.PartyModeID != -1) + if (NextScreen.PartyModeId != -1) { - CFonts.PartyModeID = NextScreen.PartyModeID; + CFonts.PartyModeId = NextScreen.PartyModeId; NextScreen.OnShow(); - CFonts.PartyModeID = -1; + CFonts.PartyModeId = -1; } else + { NextScreen.OnShow(); + } + if (_Cursor.IsActive) + { NextScreen.ProcessMouseMove(_Cursor.X, _Cursor.Y); + } HidePopup(EPopupScreens.PopupPlayerControl); - if (NextScreen.CurrentMusicType != EMusicType.Background && NextScreen.CurrentMusicType != EMusicType.Preview && NextScreen.CurrentMusicType != EMusicType.BackgroundPreview) + if (NextScreen.CurrentMusicType != EMusicType.Background && NextScreen.CurrentMusicType != EMusicType.Preview && + NextScreen.CurrentMusicType != EMusicType.BackgroundPreview) + { CBackgroundMusic.Disabled = true; + } } if (_Fading != null) { Debug.Assert(NextScreen != null); bool finished; - float newAlpha = _Fading.GetValue(out finished); + var newAlpha = _Fading.GetValue(out finished); if (!finished) { @@ -247,24 +273,30 @@ namespace Vocaluxe.Base _DrawScreen(NextScreen); GlobalAlpha = 1f; - int oldVol = CConfig.GetVolumeByType(CurrentScreen.CurrentMusicType); - int newVol = CConfig.GetVolumeByType(NextScreen.CurrentMusicType); + var oldVol = CConfig.GetVolumeByType(CurrentScreen.CurrentMusicType); + var newVol = CConfig.GetVolumeByType(NextScreen.CurrentMusicType); CSound.SetGlobalVolume((int)((newVol - oldVol) * newAlpha + oldVol)); } else { _FinishScreenFading(); if (_Cursor.IsActive) + { CurrentScreen.ProcessMouseMove(_Cursor.X, _Cursor.Y); + } _DrawScreen(CurrentScreen); } } else + { _DrawScreen(CurrentScreen); + } - foreach (IMenu popup in _PopupScreens) + foreach (var popup in _PopupScreens) + { popup.Draw(); + } _Cursor.Draw(); _DrawDebugInfos(); @@ -275,37 +307,47 @@ namespace Vocaluxe.Base private static void _FinishScreenFading() { if (_Fading == null) + { return; + } + Debug.Assert(NextScreen != null); CurrentScreen.OnClose(); CurrentScreen = NextScreen; NextScreen = null; CurrentScreen.OnShowFinish(); CSound.SetGlobalVolume(CConfig.GetVolumeByType(CurrentScreen.CurrentMusicType)); - if (CurrentScreen.CurrentMusicType == EMusicType.Background || CurrentScreen.CurrentMusicType == EMusicType.Preview || CurrentScreen.CurrentMusicType == EMusicType.BackgroundPreview) + if (CurrentScreen.CurrentMusicType == EMusicType.Background || CurrentScreen.CurrentMusicType == EMusicType.Preview || + CurrentScreen.CurrentMusicType == EMusicType.BackgroundPreview) { CBackgroundMusic.Disabled = false; CBackgroundMusic.IsPlayingPreview = CurrentScreen.CurrentMusicType == EMusicType.Preview || CurrentScreen.CurrentMusicType == EMusicType.BackgroundPreview; } + _Fading = null; } private static void _DrawScreen(IMenu screen) { - if (screen.PartyModeID != -1) + if (screen.PartyModeId != -1) { - CFonts.PartyModeID = screen.PartyModeID; + CFonts.PartyModeId = screen.PartyModeId; screen.Draw(); - CFonts.PartyModeID = -1; + CFonts.PartyModeId = -1; } else + { screen.Draw(); + } } public static IMenu GetScreen(EScreen screen) { if (screen == EScreen.Unknown || screen == EScreen.CountEntry) + { throw new ArgumentException("Invalid screen: " + screen); + } + return _Screens[(int)screen]; } @@ -317,10 +359,16 @@ namespace Vocaluxe.Base public static void FadeTo(IMenu screen) { if (screen == null) + { throw new ArgumentNullException("screen"); + } + Debug.Assert(NextScreen == null || NextScreen != screen, "Don't fade to currently fading screen!"); if (screen == NextScreen) + { return; + } + // Make sure the last screen change is done _FinishScreenFading(); NextScreen = screen; @@ -336,7 +384,9 @@ namespace Vocaluxe.Base public static void HidePopup(EPopupScreens popupScreen) { if (_CurrentPopupScreen != popupScreen) + { return; + } _PopupScreens[(int)popupScreen].OnClose(); _CurrentPopupScreen = EPopupScreens.NoPopup; @@ -356,25 +406,30 @@ namespace Vocaluxe.Base #region private stuff private static bool _HandleInputs(CKeys keys, CMouse mouse) { - SKeyEvent keyEvent = new SKeyEvent(); - SMouseEvent mouseEvent = new SMouseEvent(); - SKeyEvent inputKeyEvent = new SKeyEvent(); - SMouseEvent inputMouseEvent = new SMouseEvent(); + var keyEvent = new SKeyEvent(); + var mouseEvent = new SMouseEvent(); + var inputKeyEvent = new SKeyEvent(); + var inputMouseEvent = new SMouseEvent(); - bool popupPlayerControlAllowed = CurrentScreen.CurrentMusicType == EMusicType.Background; - bool popupVolumeControlAllowed = CurrentScreen.CurrentMusicType != EMusicType.None; + var popupPlayerControlAllowed = CurrentScreen.CurrentMusicType == EMusicType.Background; + var popupVolumeControlAllowed = CurrentScreen.CurrentMusicType != EMusicType.None; //Hide volume control for bg-music if bg-music is disabled - if (popupVolumeControlAllowed && (CurrentScreen.CurrentMusicType == EMusicType.Background || CurrentScreen.CurrentMusicType == EMusicType.BackgroundPreview) && CConfig.Config.Sound.BackgroundMusic == EBackgroundMusicOffOn.TR_CONFIG_OFF) + if (popupVolumeControlAllowed && (CurrentScreen.CurrentMusicType == EMusicType.Background || CurrentScreen.CurrentMusicType == EMusicType.BackgroundPreview) && + CConfig.Config.Sound.BackgroundMusic == EBackgroundMusicOffOn.TR_CONFIG_OFF) + { popupVolumeControlAllowed = false; + } - bool resume = true; + var resume = true; bool eventsAvailable; - bool inputEventsAvailable = CController.PollKeyEvent(ref inputKeyEvent); + var inputEventsAvailable = CController.PollKeyEvent(ref inputKeyEvent); while ((eventsAvailable = keys.PollEvent(ref keyEvent)) || inputEventsAvailable) { if (!eventsAvailable) + { keyEvent = inputKeyEvent; + } if (keyEvent.IsArrowKey() || keyEvent.Key == Keys.NumPad0 || keyEvent.Key == Keys.D0 || keyEvent.Key == Keys.Add) { @@ -386,27 +441,47 @@ namespace Vocaluxe.Base { case Keys.Right: if (keyEvent.ModShift) + { CConfig.Config.Graphics.BorderLeft++; + } else + { CConfig.Config.Graphics.BorderRight--; + } + break; case Keys.Left: if (keyEvent.ModShift) + { CConfig.Config.Graphics.BorderLeft--; + } else + { CConfig.Config.Graphics.BorderRight++; + } + break; case Keys.Down: if (keyEvent.ModShift) + { CConfig.Config.Graphics.BorderTop++; + } else + { CConfig.Config.Graphics.BorderBottom--; + } + break; case Keys.Up: if (keyEvent.ModShift) + { CConfig.Config.Graphics.BorderTop--; + } else + { CConfig.Config.Graphics.BorderBottom++; + } + break; case Keys.D0: case Keys.NumPad0: @@ -426,8 +501,10 @@ namespace Vocaluxe.Base CConfig.Config.Graphics.ScreenAlignment = EGeneralAlignment.Middle; break; } + break; } + CConfig.SaveConfig(); break; } @@ -436,9 +513,13 @@ namespace Vocaluxe.Base if (keyEvent.Key == Keys.F11) { if (_CurrentPopupScreen == EPopupScreens.NoPopup) + { ShowPopup(EPopupScreens.PopupServerQR); + } else + { HidePopup(EPopupScreens.PopupServerQR); + } } if (keyEvent.Key == Keys.F8) @@ -449,42 +530,62 @@ namespace Vocaluxe.Base if (popupPlayerControlAllowed && keyEvent.Key == Keys.Tab) { if (_CurrentPopupScreen == EPopupScreens.NoPopup && CConfig.Config.Sound.BackgroundMusic == EBackgroundMusicOffOn.TR_CONFIG_ON) + { ShowPopup(EPopupScreens.PopupPlayerControl); + } else + { HidePopup(EPopupScreens.PopupPlayerControl); + } } if (popupPlayerControlAllowed && CConfig.Config.Sound.BackgroundMusic != EBackgroundMusicOffOn.TR_CONFIG_OFF) { if (keyEvent.Key == Keys.MediaNextTrack) + { CBackgroundMusic.Next(); + } else if (keyEvent.Key == Keys.MediaPreviousTrack) + { CBackgroundMusic.Previous(); + } else if (keyEvent.Key == Keys.MediaPlayPause) { if (CBackgroundMusic.IsPlaying) + { CBackgroundMusic.Pause(); + } else + { CBackgroundMusic.Play(); + } } } - if (keyEvent.ModShift && (keyEvent.Key == Keys.F1)) + if (keyEvent.ModShift && keyEvent.Key == Keys.F1) + { CSettings.ProgramState = EProgramState.EditTheme; - else if (keyEvent.ModAlt && (keyEvent.Key == Keys.Enter)) - CConfig.Config.Graphics.FullScreen = (CConfig.Config.Graphics.FullScreen == EOffOn.TR_CONFIG_ON) ? EOffOn.TR_CONFIG_OFF : EOffOn.TR_CONFIG_ON; - else if (keyEvent.ModAlt && (keyEvent.Key == Keys.P)) + } + else if (keyEvent.ModAlt && keyEvent.Key == Keys.Enter) + { + CConfig.Config.Graphics.FullScreen = CConfig.Config.Graphics.FullScreen == EOffOn.TR_CONFIG_ON ? EOffOn.TR_CONFIG_OFF : EOffOn.TR_CONFIG_ON; + } + else if (keyEvent.ModAlt && keyEvent.Key == Keys.P) + { CDraw.MakeScreenShot(); + } else { if (_Fading == null) { - bool handled = false; + var handled = false; if (_CurrentPopupScreen != EPopupScreens.NoPopup) { handled = _PopupScreens[(int)_CurrentPopupScreen].HandleInput(keyEvent); if (popupVolumeControlAllowed && _CurrentPopupScreen == EPopupScreens.PopupVolumeControl && handled) + { _VolumePopupTimer.Restart(); + } } else if (popupVolumeControlAllowed && _PopupScreens[(int)EPopupScreens.PopupVolumeControl].HandleInput(keyEvent)) { @@ -493,12 +594,16 @@ namespace Vocaluxe.Base } if (!handled) + { resume &= CurrentScreen.HandleInput(keyEvent); + } } } if (!eventsAvailable) + { inputEventsAvailable = CController.PollKeyEvent(ref inputKeyEvent); + } } inputEventsAvailable = CController.PollMouseEvent(ref inputMouseEvent); @@ -506,24 +611,32 @@ namespace Vocaluxe.Base while ((eventsAvailable = mouse.PollEvent(ref mouseEvent)) || inputEventsAvailable) { if (!eventsAvailable) + { mouseEvent = inputMouseEvent; + } if (mouseEvent.Wheel != 0) + { _Cursor.Activate(); + } _UpdateMousePosition(mouseEvent.X, mouseEvent.Y); - bool isOverPopupPlayerControl = CHelper.IsInBounds(_PopupScreens[(int)EPopupScreens.PopupPlayerControl].ScreenArea, mouseEvent); + var isOverPopupPlayerControl = CHelper.IsInBounds(_PopupScreens[(int)EPopupScreens.PopupPlayerControl].ScreenArea, mouseEvent); if (popupPlayerControlAllowed && isOverPopupPlayerControl) { if (_CurrentPopupScreen == EPopupScreens.NoPopup && CConfig.Config.Sound.BackgroundMusic == EBackgroundMusicOffOn.TR_CONFIG_ON) + { ShowPopup(EPopupScreens.PopupPlayerControl); + } } if (!isOverPopupPlayerControl && _CurrentPopupScreen == EPopupScreens.PopupPlayerControl) + { HidePopup(EPopupScreens.PopupPlayerControl); + } - bool isOverPopupVolumeControl = CHelper.IsInBounds(_PopupScreens[(int)EPopupScreens.PopupVolumeControl].ScreenArea, mouseEvent); + var isOverPopupVolumeControl = CHelper.IsInBounds(_PopupScreens[(int)EPopupScreens.PopupVolumeControl].ScreenArea, mouseEvent); if (popupVolumeControlAllowed && isOverPopupVolumeControl) { if (_CurrentPopupScreen == EPopupScreens.NoPopup) @@ -542,52 +655,69 @@ namespace Vocaluxe.Base _VolumePopupTimer.Reset(); } } + _CursorOverVolumeControl = isOverPopupVolumeControl; - bool handled = false; + var handled = false; if (_CurrentPopupScreen != EPopupScreens.NoPopup) + { handled = _PopupScreens[(int)_CurrentPopupScreen].HandleMouse(mouseEvent); + } if (!handled && _Fading == null && (_Cursor.IsActive || mouseEvent.LB || mouseEvent.RB || mouseEvent.MB)) + { resume &= CurrentScreen.HandleMouse(mouseEvent); + } if (!eventsAvailable) + { inputEventsAvailable = CController.PollMouseEvent(ref inputMouseEvent); + } } + return resume; } private static bool _HandleInputThemeEditor(CKeys keys, CMouse mouse) { - SKeyEvent keyEvent = new SKeyEvent(); - SMouseEvent mouseEvent = new SMouseEvent(); + var keyEvent = new SKeyEvent(); + var mouseEvent = new SMouseEvent(); while (keys.PollEvent(ref keyEvent)) { - if (keyEvent.ModShift && (keyEvent.Key == Keys.F1)) + if (keyEvent.ModShift && keyEvent.Key == Keys.F1) { CSettings.ProgramState = EProgramState.Normal; CurrentScreen.NextElement(); } - else if (keyEvent.ModAlt && (keyEvent.Key == Keys.Enter)) - CConfig.Config.Graphics.FullScreen = (CConfig.Config.Graphics.FullScreen == EOffOn.TR_CONFIG_ON) ? EOffOn.TR_CONFIG_OFF : EOffOn.TR_CONFIG_ON; - else if (keyEvent.ModAlt && (keyEvent.Key == Keys.P)) + else if (keyEvent.ModAlt && keyEvent.Key == Keys.Enter) + { + CConfig.Config.Graphics.FullScreen = CConfig.Config.Graphics.FullScreen == EOffOn.TR_CONFIG_ON ? EOffOn.TR_CONFIG_OFF : EOffOn.TR_CONFIG_ON; + } + else if (keyEvent.ModAlt && keyEvent.Key == Keys.P) + { CDraw.MakeScreenShot(); + } else { if (_Fading == null) + { CurrentScreen.HandleInputThemeEditor(keyEvent); + } } } while (mouse.PollEvent(ref mouseEvent)) { if (_Fading == null) + { CurrentScreen.HandleMouseThemeEditor(mouseEvent); + } _UpdateMousePosition(mouseEvent.X, mouseEvent.Y); } + return true; } @@ -605,26 +735,33 @@ namespace Vocaluxe.Base } if (_VolumePopupTimer.IsRunning) + { _Cursor.Activate(); + } if (_CurrentPopupScreen != EPopupScreens.NoPopup) + { _PopupScreens[(int)_CurrentPopupScreen].UpdateGame(); + } + return CurrentScreen.UpdateGame(); } private static void _DrawDebugInfos() { if (CConfig.Config.Debug.DebugLevel == EDebugLevel.TR_CONFIG_OFF) + { return; + } - List debugOutput = new List {CTime.GetFPS().ToString("FPS: 000")}; + var debugOutput = new List { CTime.GetFPS().ToString("FPS: 000") }; if (CConfig.Config.Debug.DebugLevel >= EDebugLevel.TR_CONFIG_LEVEL1) { debugOutput.Add(CSound.GetStreamCount().ToString(CLanguage.Translate("TR_DEBUG_AUDIO_STREAMS") + ": 00")); debugOutput.Add(CVideo.GetNumStreams().ToString(CLanguage.Translate("TR_DEBUG_VIDEO_STREAMS") + ": 00")); debugOutput.Add(CDraw.TextureCount().ToString(CLanguage.Translate("TR_DEBUG_TEXTURES") + ": 00000")); - long memory = GC.GetTotalMemory(false); + var memory = GC.GetTotalMemory(false); debugOutput.Add((memory / 1000000L).ToString(CLanguage.Translate("TR_DEBUG_MEMORY") + ": 00000 MB")); if (CConfig.Config.Debug.DebugLevel >= EDebugLevel.TR_CONFIG_LEVEL2) @@ -639,17 +776,20 @@ namespace Vocaluxe.Base debugOutput.Add(CSongs.NumSongsWithCoverLoaded.ToString(CLanguage.Translate("TR_DEBUG_SONGS") + ": 00000")); if (CConfig.Config.Debug.DebugLevel >= EDebugLevel.TR_CONFIG_LEVEL_MAX) + { debugOutput.Add(_Cursor.X.ToString(CLanguage.Translate("TR_DEBUG_MOUSE") + " : (0000/") + _Cursor.Y.ToString("0000)")); + } } } } - CFont font = new CFont("Normal", EStyle.Normal, 25); - SColorF gray = new SColorF(1f, 1f, 1f, 0.5f); + + var font = new CFont("Normal", EStyle.Normal, 25); + var gray = new SColorF(1f, 1f, 1f, 0.5f); float y = 0; - foreach (string txt in debugOutput) + foreach (var txt in debugOutput) { - float textWidth = CFonts.GetTextWidth(txt, font); - RectangleF rect = new RectangleF(CSettings.RenderW - textWidth, y, textWidth, CFonts.GetTextHeight(txt, font)); + var textWidth = CFonts.GetTextWidth(txt, font); + var rect = new RectangleF(CSettings.RenderW - textWidth, y, textWidth, CFonts.GetTextHeight(txt, font)); CDraw.DrawRect(gray, new SRectF(rect.X, rect.Top, rect.Width, rect.Height, CSettings.ZNear)); CFonts.DrawText(txt, font, rect.X, rect.Y, CSettings.ZNear); y += rect.Height; @@ -657,4 +797,4 @@ namespace Vocaluxe.Base } #endregion private stuff } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CLanguage.cs b/Vocaluxe/Base/CLanguage.cs index e1a30c41..8432e741 100644 --- a/Vocaluxe/Base/CLanguage.cs +++ b/Vocaluxe/Base/CLanguage.cs @@ -36,7 +36,7 @@ namespace Vocaluxe.Base struct SPartyLanguage { - public int PartyModeID; + public int PartyModeId; public Dictionary Texts; } @@ -52,7 +52,9 @@ namespace Vocaluxe.Base set { if (value >= 0 && value < _Languages.Count) + { _CurrentLanguage = value; + } } } @@ -60,8 +62,10 @@ namespace Vocaluxe.Base { var languages = new string[_Languages.Count]; - for (int i = 0; i < _Languages.Count; i++) + for (var i = 0; i < _Languages.Count; i++) + { languages[i] = _Languages[i].Name; + } return languages; } @@ -71,29 +75,36 @@ namespace Vocaluxe.Base var files = new List(); files.AddRange(CHelper.ListFiles(CSettings.FolderNameLanguages, "*.xml", true, true)); - foreach (string file in files) + foreach (var file in files) + { _LoadLanguageFile(file); + } + return _CurrentLanguage >= 0 && _FallbackLanguage >= 0; } public static bool SetLanguage(string language) { - int nr = _GetLanguageNr(language); + var nr = _GetLanguageNr(language); if (nr != -1) { _CurrentLanguage = nr; return true; } + return false; } private static int _GetLanguageNr(string language) { - for (int i = 0; i < _Languages.Count; i++) + for (var i = 0; i < _Languages.Count; i++) { if (_Languages[i].Name == language) + { return i; + } } + return -1; } @@ -101,10 +112,10 @@ namespace Vocaluxe.Base /// Checks if a translation exists and returns it /// /// Word to translate - /// + /// /// Translated word or keyWord if translation does not exist /// True if word was translated - private static bool _GetTranslation(string keyWord, int partyModeID, out string translation) + private static bool _GetTranslation(string keyWord, int partyModeId, out string translation) { if (keyWord == null) { @@ -118,45 +129,54 @@ namespace Vocaluxe.Base return false; } - if (partyModeID != -1) + if (partyModeId != -1) { - Dictionary partyModeTexts = _GetPartyModeTexts(_CurrentLanguage, partyModeID); + var partyModeTexts = _GetPartyModeTexts(_CurrentLanguage, partyModeId); if (partyModeTexts != null && partyModeTexts.TryGetValue(keyWord, out translation)) + { return true; + } - partyModeTexts = _GetPartyModeTexts(_FallbackLanguage, partyModeID); + partyModeTexts = _GetPartyModeTexts(_FallbackLanguage, partyModeId); if (partyModeTexts != null && partyModeTexts.TryGetValue(keyWord, out translation)) + { return true; + } } if (_Languages[_CurrentLanguage].Texts.TryGetValue(keyWord, out translation)) + { return true; + } + if (_Languages[_FallbackLanguage].Texts.TryGetValue(keyWord, out translation)) + { return true; + } translation = keyWord; return false; } - public static string Translate(string keyWord, int partyModeID = -1) + public static string Translate(string keyWord, int partyModeId = -1) { string translation; - _GetTranslation(keyWord, partyModeID, out translation); + _GetTranslation(keyWord, partyModeId, out translation); return translation; } - public static bool TranslationExists(string keyWord, int partyModeID = -1) + public static bool TranslationExists(string keyWord, int partyModeId = -1) { string translation; - return _GetTranslation(keyWord, partyModeID, out translation); + return _GetTranslation(keyWord, partyModeId, out translation); } - public static bool LoadPartyLanguageFiles(int partyModeID, string path) + public static bool LoadPartyLanguageFiles(int partyModeId, string path) { var files = new List(); files.AddRange(CHelper.ListFiles(path, "*.xml", true, true)); - return files.All(file => _LoadPartyLanguageFile(partyModeID, file)); + return files.All(file => _LoadPartyLanguageFile(partyModeId, file)); } private static bool _LoadLanguageEntries(string filePath, out Dictionary texts) @@ -167,7 +187,9 @@ namespace Vocaluxe.Base texts = deser.Deserialize>(filePath); string language; if (!texts.TryGetValue("language", out language)) + { throw new Exception("'language' entry is missing"); + } } catch (Exception e) { @@ -175,44 +197,54 @@ namespace Vocaluxe.Base texts = null; return false; } + return true; } - private static bool _LoadPartyLanguageFile(int partyModeID, string filePath) + private static bool _LoadPartyLanguageFile(int partyModeId, string filePath) { - var lang = new SPartyLanguage {PartyModeID = partyModeID}; + var lang = new SPartyLanguage { PartyModeId = partyModeId }; if (!_LoadLanguageEntries(filePath, out lang.Texts)) + { return false; + } - int nr = _GetLanguageNr(lang.Texts["language"]); + var nr = _GetLanguageNr(lang.Texts["language"]); if (nr >= 0) + { _Languages[nr].PartyModeTexts.Add(lang); + } + return true; } private static void _LoadLanguageFile(string fileName) { - var lang = new SLanguage {FilePath = Path.Combine(CSettings.ProgramFolder, CSettings.FolderNameLanguages, fileName), PartyModeTexts = new List()}; + var lang = new SLanguage { FilePath = Path.Combine(CSettings.ProgramFolder, CSettings.FolderNameLanguages, fileName), PartyModeTexts = new List() }; if (!_LoadLanguageEntries(lang.FilePath, out lang.Texts)) + { return; + } lang.Name = lang.Texts["language"]; if (lang.Name == CSettings.FallbackLanguage) { _FallbackLanguage = _Languages.Count; if (_CurrentLanguage < 0) + { _CurrentLanguage = _FallbackLanguage; + } } _Languages.Add(lang); } - private static Dictionary _GetPartyModeTexts(int language, int partyModeID) + private static Dictionary _GetPartyModeTexts(int language, int partyModeId) { return - _Languages[language].PartyModeTexts.Where(partyLanguage => partyLanguage.PartyModeID == partyModeID).Select(partyLanguage => partyLanguage.Texts).FirstOrDefault(); + _Languages[language].PartyModeTexts.Where(partyLanguage => partyLanguage.PartyModeId == partyModeId).Select(partyLanguage => partyLanguage.Texts).FirstOrDefault(); } } } \ No newline at end of file diff --git a/Vocaluxe/Base/CMain.cs b/Vocaluxe/Base/CMain.cs index f9eac29f..fa502d95 100644 --- a/Vocaluxe/Base/CMain.cs +++ b/Vocaluxe/Base/CMain.cs @@ -19,16 +19,15 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Drawing; -using System.Runtime.CompilerServices; using Vocaluxe.Base.Fonts; using Vocaluxe.Base.ThemeSystem; using VocaluxeLib; -using VocaluxeLib.Game; using VocaluxeLib.Draw; +using VocaluxeLib.Game; using VocaluxeLib.Log; using VocaluxeLib.Menu; -using VocaluxeLib.Songs; using VocaluxeLib.Profile; +using VocaluxeLib.Songs; namespace Vocaluxe.Base { @@ -56,7 +55,7 @@ namespace Vocaluxe.Base public static void Init() { CBase.Assign(_Config, _Settings, _Themes, _BackgroundMusic, _Draw, _Graphics, _Fonts, _Language, - _Game, _Profiles, _Record, _Songs, _Video, _Sound, _Cover, _DataBase, _Controller, _Playlist); + _Game, _Profiles, _Record, _Songs, _Video, _Sound, _Cover, _DataBase, _Controller, _Playlist); } } @@ -293,24 +292,24 @@ namespace Vocaluxe.Base class CBtheme : IThemes { - public string GetThemeScreensPath(int partyModeID) + public string GetThemeScreensPath(int partyModeId) { - return CThemes.GetThemeScreensPath(partyModeID); + return CThemes.GetThemeScreensPath(partyModeId); } - public CTextureRef GetSkinTexture(string textureName, int partyModeID) + public CTextureRef GetSkinTexture(string textureName, int partyModeId) { - return CThemes.GetSkinTexture(textureName, partyModeID); + return CThemes.GetSkinTexture(textureName, partyModeId); } - public CVideoStream GetSkinVideo(string videoName, int partyModeID, bool loop) + public CVideoStream GetSkinVideo(string videoName, int partyModeId, bool loop) { - return CThemes.GetSkinVideo(videoName, partyModeID, loop); + return CThemes.GetSkinVideo(videoName, partyModeId, loop); } - public bool GetColor(string colorName, int partyModeID, out SColorF color) + public bool GetColor(string colorName, int partyModeId, out SColorF color) { - return CThemes.GetColor(colorName, partyModeID, out color); + return CThemes.GetColor(colorName, partyModeId, out color); } public SColorF GetPlayerColor(int playerNr) @@ -538,9 +537,9 @@ namespace Vocaluxe.Base return CLanguage.Translate(keyWord); } - public string Translate(string keyWord, int partyModeID) + public string Translate(string keyWord, int partyModeId) { - return CLanguage.Translate(keyWord, partyModeID); + return CLanguage.Translate(keyWord, partyModeId); } public bool TranslationExists(string keyWord) @@ -606,9 +605,9 @@ namespace Vocaluxe.Base return CGame.GetBeatFromTime(time, bpm, gap); } - public void AddSong(int songID, EGameMode gameMode) + public void AddSong(int songId, EGameMode gameMode) { - CGame.AddSong(songID, gameMode); + CGame.AddSong(songId, gameMode); } public void Reset() @@ -649,19 +648,19 @@ namespace Vocaluxe.Base return CProfiles.NumProfiles; } - public EGameDifficulty GetDifficulty(Guid profileID) + public EGameDifficulty GetDifficulty(Guid profileId) { - return CProfiles.GetDifficulty(profileID); + return CProfiles.GetDifficulty(profileId); } - public string GetPlayerName(Guid profileID, int playerNum = 0) + public string GetPlayerName(Guid profileId, int playerNum = 0) { - return CProfiles.GetPlayerName(profileID, playerNum); + return CProfiles.GetPlayerName(profileId, playerNum); } - public CTextureRef GetAvatar(Guid profileID) + public CTextureRef GetAvatar(Guid profileId) { - return CProfiles.GetAvatarTextureFromProfile(profileID); + return CProfiles.GetAvatarTextureFromProfile(profileId); } public CAvatar GetAvatarByFilename(string fileName) @@ -669,14 +668,14 @@ namespace Vocaluxe.Base return CProfiles.GetAvatarByFilename(fileName); } - public bool IsProfileIDValid(Guid profileID) + public bool IsProfileIdValid(Guid profileId) { - return CProfiles.IsProfileIDValid(profileID); + return CProfiles.IsProfileIdValid(profileId); } - public bool IsGuest(Guid profileID) + public bool IsGuest(Guid profileId) { - return CProfiles.IsGuestProfile(profileID); + return CProfiles.IsGuestProfile(profileId); } public void AddProfileChangedCallback(ProfileChangedCallback notification) @@ -780,9 +779,9 @@ namespace Vocaluxe.Base return CSongs.GetVisibleSongByIndex(visibleIndex); } - public CSong GetSongByID(int songID) + public CSong GetSongById(int songId) { - return CSongs.GetSong(songID); + return CSongs.GetSong(songId); } public ReadOnlyCollection GetSongs() @@ -800,9 +799,9 @@ namespace Vocaluxe.Base return CSongs.GetCategoryByIndex(index); } - public void AddPartySongSung(int songID) + public void AddPartySongSung(int songId) { - CSongs.AddPartySongSung(songID); + CSongs.AddPartySongSung(songId); } public void ResetSongSung() @@ -815,9 +814,9 @@ namespace Vocaluxe.Base CSongs.ResetPartySongSung(catIndex); } - public void SortSongs(ESongSorting sorting, EOffOn tabs, EOffOn ignoreArticles, String searchString, EDuetOptions duetOptions, int playlistID) + public void SortSongs(ESongSorting sorting, EOffOn tabs, EOffOn ignoreArticles, String searchString, EDuetOptions duetOptions, int playlistId) { - CSongs.Sort(sorting, tabs, ignoreArticles, searchString, duetOptions, playlistID); + CSongs.Sort(sorting, tabs, ignoreArticles, searchString, duetOptions, playlistId); } public void NextCategory() @@ -833,9 +832,9 @@ namespace Vocaluxe.Base class CBvideo : IVideo { - public CVideoStream Load(string videoFileName) + public CVideoStream Load(string videoUri) { - return CVideo.Load(videoFileName); + return CVideo.Load(videoUri); } public bool Skip(CVideoStream stream, float startPosition, float videoGap) @@ -897,9 +896,9 @@ namespace Vocaluxe.Base class CBsound : ISound { - public int Load(string soundFile, bool loop = false, bool prescan = false) + public int Load(string uri, bool loop = false, bool prescan = false) { - return CSound.Load(soundFile, loop, prescan); + return CSound.Load(uri, loop, prescan); } public void SetPosition(int soundStream, float newPosition) @@ -947,9 +946,9 @@ namespace Vocaluxe.Base CSound.SetGlobalVolume(volume); } - public bool IsPaused(int streamID) + public bool IsPaused(int streamId) { - return CSound.IsPaused(streamID); + return CSound.IsPaused(streamId); } } @@ -973,9 +972,9 @@ namespace Vocaluxe.Base return CDataBase.GetCover(fileName, ref texture, coverSize); } - public bool GetDataBaseSongInfos(string artist, string title, out int numPlayed, out DateTime dateAdded, out int highscoreID) + public bool GetDataBaseSongInfos(string artist, string title, out int numPlayed, out DateTime dateAdded, out int highscoreId) { - return CDataBase.GetDataBaseSongInfos(artist, title, out numPlayed, out dateAdded, out highscoreID); + return CDataBase.GetDataBaseSongInfos(artist, title, out numPlayed, out dateAdded, out highscoreId); } } @@ -989,9 +988,9 @@ namespace Vocaluxe.Base class CBplaylist : IPlaylist { - public void SetName(int playlistID, string name) + public void SetName(int playlistId, string name) { - CPlaylists.SetName(playlistID, name); + CPlaylists.SetName(playlistId, name); } public List GetIds() @@ -1004,24 +1003,24 @@ namespace Vocaluxe.Base return CPlaylists.Names; } - public bool Exists(int playlistID) + public bool Exists(int playlistId) { - return CPlaylists.Get(playlistID) != null; + return CPlaylists.Get(playlistId) != null; } - public string GetName(int playlistID) + public string GetName(int playlistId) { - return CPlaylists.GetName(playlistID); + return CPlaylists.GetName(playlistId); } - public void Delete(int playlistID) + public void Delete(int playlistId) { - CPlaylists.Delete(playlistID); + CPlaylists.Delete(playlistId); } - public void Save(int playlistID) + public void Save(int playlistId) { - CPlaylists.Save(playlistID); + CPlaylists.Save(playlistId); } public int GetNumPlaylists() @@ -1029,54 +1028,54 @@ namespace Vocaluxe.Base return CPlaylists.NumPlaylists; } - public void AddSong(int playlistID, int songID) + public void AddSong(int playlistId, int songId) { - CPlaylists.AddSong(playlistID, songID); + CPlaylists.AddSong(playlistId, songId); } - public void AddSong(int playlistID, int songID, EGameMode gameMode) + public void AddSong(int playlistId, int songId, EGameMode gameMode) { - CPlaylists.AddSong(playlistID, songID, gameMode); + CPlaylists.AddSong(playlistId, songId, gameMode); } - public void InsertSong(int playlistID, int positionIndex, int songID, EGameMode gameMode) + public void InsertSong(int playlistId, int positionIndex, int songId, EGameMode gameMode) { - CPlaylists.InsertSong(playlistID, positionIndex, songID, gameMode); + CPlaylists.InsertSong(playlistId, positionIndex, songId, gameMode); } - public void MoveSong(int playlistID, int sourceIndex, int destIndex) + public void MoveSong(int playlistId, int sourceIndex, int destIndex) { - CPlaylists.MoveSong(playlistID, sourceIndex, destIndex); + CPlaylists.MoveSong(playlistId, sourceIndex, destIndex); } - public void MoveSongDown(int playlistID, int songIndex) + public void MoveSongDown(int playlistId, int songIndex) { - CPlaylists.MovePSongDown(playlistID, songIndex); + CPlaylists.MovePSongDown(playlistId, songIndex); } - public void MoveSongUp(int playlistID, int songIndex) + public void MoveSongUp(int playlistId, int songIndex) { - CPlaylists.MoveSongUp(playlistID, songIndex); + CPlaylists.MoveSongUp(playlistId, songIndex); } - public void DeleteSong(int playlistID, int songIndex) + public void DeleteSong(int playlistId, int songIndex) { - CPlaylists.DeleteSong(playlistID, songIndex); + CPlaylists.DeleteSong(playlistId, songIndex); } - public int GetSongCount(int playlistID) + public int GetSongCount(int playlistId) { - return CPlaylists.GetSongCount(playlistID); + return CPlaylists.GetSongCount(playlistId); } - public CPlaylistSong GetSong(int playlistID, int songIndex) + public CPlaylistSong GetSong(int playlistId, int songIndex) { - return CPlaylists.GetSong(playlistID, songIndex); + return CPlaylists.GetSong(playlistId, songIndex); } - public bool ContainsSong(int playlistID, int songID) + public bool ContainsSong(int playlistId, int songId) { - return CPlaylists.ContainsSong(playlistID, songID); + return CPlaylists.ContainsSong(playlistId, songId); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CParty.cs b/Vocaluxe/Base/CParty.cs index 6687bffa..e5942a08 100644 --- a/Vocaluxe/Base/CParty.cs +++ b/Vocaluxe/Base/CParty.cs @@ -35,44 +35,54 @@ namespace Vocaluxe.Base private const int _PartyModeSystemVersion = 2; private static readonly Dictionary _PartyModes = new Dictionary(); - private static int _NextID; + private static int _NextId; private static IPartyMode _CurrentPartyMode; #region public stuff public static bool Init() { if (_PartyModes.Count > 0) + { return false; //Already initialized - SPartyMode pm = new SPartyMode - { - Info = new SPartyModeInfos {Author = "Vocaluxe Team", Description = "Normal game", Name = "Normal", TargetAudience = "Just a normal game for everyone"}, - PartyMode = new CPartyModeNormal(-1), - PartyModeSystemVersion = _PartyModeSystemVersion, - ScreenFiles = new List() - }; + } + + var pm = new SPartyMode + { + Info = new SPartyModeInfos { Author = "Vocaluxe Team", Description = "Normal game", Name = "Normal", TargetAudience = "Just a normal game for everyone" }, + PartyMode = new CPartyModeNormal(-1), + PartyModeSystemVersion = _PartyModeSystemVersion, + ScreenFiles = new List() + }; _PartyModes.Add(-1, pm); _CurrentPartyMode = pm.PartyMode; - Debug.Assert(_CurrentPartyMode != null && _CurrentPartyMode.ID == -1); + Debug.Assert(_CurrentPartyMode != null && _CurrentPartyMode.Id == -1); //load other party modes _LoadPartyModes(); return _CurrentPartyMode.Init(); } - public static int CurrentPartyModeID + public static int CurrentPartyModeId { - get { return _CurrentPartyMode.ID; } + get { return _CurrentPartyMode.Id; } set { - if (_CurrentPartyMode.ID == value) { + if (_CurrentPartyMode.Id == value) + { _CurrentPartyMode.SetDefaults(); return; } + if (value != -1 && !_PartyModes.ContainsKey(value)) - throw new ArgumentException("Partymode with ID=" + value + " does not exist!"); - IPartyMode pm = _PartyModes[value].PartyMode; + { + throw new ArgumentException("Partymode with Id=" + value + " does not exist!"); + } + + var pm = _PartyModes[value].PartyMode; if (pm.Init()) + { _CurrentPartyMode = pm; + } else { CLog.Error("Could not init PartyMode \"" + _PartyModes[value].Info.Name + "\"! Removing...", true); @@ -88,42 +98,51 @@ namespace Vocaluxe.Base public static void ReloadTheme() { - foreach (SPartyMode pm in _PartyModes.Values) + foreach (var pm in _PartyModes.Values) + { pm.PartyMode.ReloadTheme(); + } } public static void ReloadSkin() { - foreach (SPartyMode pm in _PartyModes.Values) + foreach (var pm in _PartyModes.Values) + { pm.PartyMode.ReloadSkin(); + } } public static void SaveThemes() { - foreach (SPartyMode pm in _PartyModes.Values) + foreach (var pm in _PartyModes.Values) + { pm.PartyMode.SaveScreens(); + } } public static List GetPartyModeInfos() { - List list = new List(); - foreach (SPartyMode pm in _PartyModes.Values) + var list = new List(); + foreach (var pm in _PartyModes.Values) { - if (pm.PartyMode.ID >= 0) + if (pm.PartyMode.Id >= 0) + { list.Add(pm.Info); + } } + return list; } public static void SetNormalGameMode() { CSongs.ResetPartySongSung(); - CurrentPartyModeID = -1; + CurrentPartyModeId = -1; } - public static void SetPartyMode(int partyModeID) + public static void SetPartyMode(int partyModeId) { - CurrentPartyModeID = partyModeID; + CurrentPartyModeId = partyModeId; } #endregion public stuff @@ -163,9 +182,9 @@ namespace Vocaluxe.Base _CurrentPartyMode.JokerUsed(teamNr); } - public static void SongSelected(int songID) + public static void SongSelected(int songId) { - _CurrentPartyMode.SongSelected(songID); + _CurrentPartyMode.SongSelected(songId); } public static void FinishedSinging() @@ -190,25 +209,31 @@ namespace Vocaluxe.Base var files = new List(); files.AddRange(CHelper.ListFiles(CSettings.FolderNamePartyModes, "*.xml", false, true)); - foreach (string file in files) + foreach (var file in files) { SPartyMode pm; if (_LoadPartyMode(file, out pm)) - _PartyModes.Add(pm.PartyMode.ID, pm); + { + _PartyModes.Add(pm.PartyMode.Id, pm); + } } } private static bool _LoadPartyMode(string filePath, out SPartyMode pm) { - CXmlDeserializer deser = new CXmlDeserializer(); + var deser = new CXmlDeserializer(); try { pm = deser.Deserialize(filePath); if (pm.PartyModeSystemVersion != _PartyModeSystemVersion) + { throw new Exception("Wrong PartyModeSystemVersion " + pm.PartyModeSystemVersion + " expected: " + _PartyModeSystemVersion); + } if (pm.ScreenFiles.Count == 0) + { throw new Exception("No ScreenFiles found"); + } } catch (Exception e) { @@ -217,18 +242,20 @@ namespace Vocaluxe.Base return false; } - string pathToPm = Path.Combine(CSettings.ProgramFolder, CSettings.FolderNamePartyModes, pm.Info.Folder); - string pathToCode = Path.Combine(pathToPm, CSettings.FolderNamePartyModeCode); + var pathToPm = Path.Combine(CSettings.ProgramFolder, CSettings.FolderNamePartyModes, pm.Info.Folder); + var pathToCode = Path.Combine(pathToPm, CSettings.FolderNamePartyModeCode); var filesToCompile = new List(); filesToCompile.AddRange(CHelper.ListFiles(pathToCode, "*.cs", false, true)); - Assembly output = _CompileFiles(filesToCompile.ToArray()); + var output = _CompileFiles(filesToCompile.ToArray()); if (output == null) + { return false; + } - object instance = output.CreateInstance(typeof(IPartyMode).Namespace + "." + pm.Info.Folder + "." + pm.Info.PartyModeFile, false, - BindingFlags.Public | BindingFlags.Instance, null, new object[] {_NextID++}, null, null); + var instance = output.CreateInstance(typeof(IPartyMode).Namespace + "." + pm.Info.Folder + "." + pm.Info.PartyModeFile, false, + BindingFlags.Public | BindingFlags.Instance, null, new object[] { _NextId++ }, null, null); if (instance == null) { CLog.Error("Error creating Instance of PartyMode file: " + filePath); @@ -245,21 +272,25 @@ namespace Vocaluxe.Base return false; } - if (!CLanguage.LoadPartyLanguageFiles(pm.PartyMode.ID, Path.Combine(pathToPm, CSettings.FolderNamePartyModeLanguages))) + if (!CLanguage.LoadPartyLanguageFiles(pm.PartyMode.Id, Path.Combine(pathToPm, CSettings.FolderNamePartyModeLanguages))) { CLog.Error("Error loading language files for PartyMode: " + filePath); return false; } - if (!CThemes.ReadThemesFromFolder(Path.Combine(pathToPm, CSettings.FolderNameThemes), pm.PartyMode.ID)) - return false; - - if (!CThemes.LoadPartymodeTheme(pm.PartyMode.ID)) - return false; - - foreach (string screenfile in pm.ScreenFiles) + if (!CThemes.ReadThemesFromFolder(Path.Combine(pathToPm, CSettings.FolderNameThemes), pm.PartyMode.Id)) { - CMenuParty screen = _GetPartyScreenInstance(output, screenfile, pm.Info.Folder); + return false; + } + + if (!CThemes.LoadPartymodeTheme(pm.PartyMode.Id)) + { + return false; + } + + foreach (var screenfile in pm.ScreenFiles) + { + var screen = _GetPartyScreenInstance(output, screenfile, pm.Info.Folder); if (screen != null) { @@ -267,8 +298,11 @@ namespace Vocaluxe.Base pm.PartyMode.AddScreen(screen, screenfile); } else + { return false; + } } + pm.PartyMode.LoadTheme(); pm.Info.ExtInfo = pm.PartyMode; return true; @@ -277,20 +311,22 @@ namespace Vocaluxe.Base private static Assembly _CompileFiles(string[] files) { if (files == null || files.Length == 0) + { return null; + } var compilerParams = new CompilerParameters(); compilerParams.ReferencedAssemblies.Add("System.Windows.Forms.dll"); compilerParams.ReferencedAssemblies.Add("System.dll"); compilerParams.ReferencedAssemblies.Add("System.Core.dll"); - compilerParams.ReferencedAssemblies.Add(Path.Combine("libs","managed","VocaluxeLib.dll")); + compilerParams.ReferencedAssemblies.Add(Path.Combine("libs", "managed", "VocaluxeLib.dll")); compilerParams.GenerateInMemory = true; #if DEBUG compilerParams.IncludeDebugInformation = true; #endif - using (CodeDomProvider cdp = CodeDomProvider.CreateProvider("CSharp")) + using (var cdp = CodeDomProvider.CreateProvider("CSharp")) { CompilerResults compileResult; @@ -307,9 +343,13 @@ namespace Vocaluxe.Base if (compileResult.Errors.Count > 0) { foreach (CompilerError e in compileResult.Errors) + { CLog.Error("Error Compiling Source (" + CHelper.ListStrings(files) + "): " + e.ErrorText + " in '" + e.FileName + "' (" + e.Line + ")"); + } + return null; } + return compileResult.CompiledAssembly; } } @@ -317,9 +357,11 @@ namespace Vocaluxe.Base private static CMenuParty _GetPartyScreenInstance(Assembly assembly, string screenName, string partyModeName) { if (assembly == null) + { return null; + } - object instance = assembly.CreateInstance(typeof(IPartyMode).Namespace + "." + partyModeName + "." + screenName); + var instance = assembly.CreateInstance(typeof(IPartyMode).Namespace + "." + partyModeName + "." + screenName); if (instance == null) { CLog.Error("Error creating Instance of PartyScreen: " + screenName); @@ -336,6 +378,7 @@ namespace Vocaluxe.Base CLog.Error("Error casting PartyScreen: " + screenName + "; " + e.Message); return null; } + return screen; } #endregion private stuff diff --git a/Vocaluxe/Base/CPlaylistElement.cs b/Vocaluxe/Base/CPlaylistElement.cs index 4e82592a..2ee49fa2 100644 --- a/Vocaluxe/Base/CPlaylistElement.cs +++ b/Vocaluxe/Base/CPlaylistElement.cs @@ -24,16 +24,16 @@ namespace Vocaluxe.Base class CPlaylistElement { public readonly CSong Song; - private readonly string _MusicFilePath = String.Empty; + private readonly string _MusicFilePath = string.Empty; public bool HasMetaData { get { return Song != null; } } - public int SongID + public int SongId { - get { return HasMetaData ? Song.ID : -1; } + get { return HasMetaData ? Song.Id : -1; } } public string MusicFilePath @@ -63,7 +63,7 @@ namespace Vocaluxe.Base public float Finish { - get { return HasMetaData ? Song.Finish : 0f; } + get { return HasMetaData ? Song.End : 0f; } } public CTextureRef Cover @@ -79,14 +79,20 @@ namespace Vocaluxe.Base public CPlaylistElement(CSong song) { if (song == null) + { throw new ArgumentNullException("song"); + } + Song = song; } public CPlaylistElement(string filePath) { - if (String.IsNullOrEmpty(filePath)) + if (string.IsNullOrEmpty(filePath)) + { throw new ArgumentNullException("filePath"); + } + _MusicFilePath = filePath; } } diff --git a/Vocaluxe/Base/CPlaylists.cs b/Vocaluxe/Base/CPlaylists.cs index 8c47b962..96b68427 100644 --- a/Vocaluxe/Base/CPlaylists.cs +++ b/Vocaluxe/Base/CPlaylists.cs @@ -17,7 +17,6 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; @@ -25,7 +24,6 @@ using Vocaluxe.Lib.Playlist; using VocaluxeLib; using VocaluxeLib.Log; using VocaluxeLib.Menu; -using VocaluxeLib.Songs; namespace Vocaluxe.Base { @@ -66,9 +64,9 @@ namespace Vocaluxe.Base var files = new List(); files.AddRange(CHelper.ListFiles(Path.Combine(CSettings.DataFolder, CConfig.FolderPlaylists), "*.upl", true, true)); - foreach (string file in files) + foreach (var file in files) { - CPlaylistFile playlist = _ConvertUSDXPlaylist(file); + var playlist = _ConvertUSDXPlaylist(file); playlist.Save(); _Playlists.Add(playlist); } @@ -81,38 +79,45 @@ namespace Vocaluxe.Base var files = new List(); files.AddRange(CHelper.ListFiles(Path.Combine(CSettings.DataFolder, CConfig.FolderPlaylists), "*.xml", true, true)); - foreach (string file in files) + foreach (var file in files) { - CPlaylistFile playlist = new CPlaylistFile(); + var playlist = new CPlaylistFile(); if (playlist._Load(file)) + { _Playlists.Add(playlist); + } } } - public static CPlaylistFile Get(int playlistID) + public static CPlaylistFile Get(int playlistId) { - return _Playlists.FirstOrDefault(pl => pl.Id == playlistID); + return _Playlists.FirstOrDefault(pl => pl.Id == playlistId); } - public static string GetName(int playlistID) + public static string GetName(int playlistId) { - CPlaylistFile pl = Get(playlistID); + var pl = Get(playlistId); return pl == null ? "Error: Can't find Playlist" : pl.Name; } - public static void SetName(int playlistID, string name) + public static void SetName(int playlistId, string name) { - CPlaylistFile pl = Get(playlistID); + var pl = Get(playlistId); if (pl != null) + { pl.Name = name; + } } - public static void Delete(int playlistID) + public static void Delete(int playlistId) { - CPlaylistFile pl = Get(playlistID); + var pl = Get(playlistId); if (pl == null) + { return; + } + if (pl.File != "" && File.Exists(pl.File)) { try @@ -121,94 +126,113 @@ namespace Vocaluxe.Base } catch (Exception) { - CLog.Error("Can't delete Playlist File " + _Playlists[playlistID].File + ".xml"); + CLog.Error("Can't delete Playlist File " + _Playlists[playlistId].File + ".xml"); } } + _Playlists.Remove(pl); } - public static void Save(int playlistID) + public static void Save(int playlistId) { - CPlaylistFile pl = Get(playlistID); + var pl = Get(playlistId); if (pl != null) + { pl.Save(); + } } public static int NewPlaylist(string name = "New Playlist") { - CPlaylistFile pl = new CPlaylistFile {Name = name}; + var pl = new CPlaylistFile { Name = name }; _Playlists.Add(pl); return pl.Id; } - public static void AddSong(int playlistID, int songID) + public static void AddSong(int playlistId, int songId) { - CPlaylistFile pl = Get(playlistID); + var pl = Get(playlistId); if (pl != null) - pl.AddSong(songID); + { + pl.AddSong(songId); + } } - public static void AddSong(int playlistID, int songID, EGameMode gameMode) + public static void AddSong(int playlistId, int songId, EGameMode gameMode) { - CPlaylistFile pl = Get(playlistID); + var pl = Get(playlistId); if (pl != null) - pl.AddSong(songID, gameMode); + { + pl.AddSong(songId, gameMode); + } } - public static void InsertSong(int playlistID, int positionIndex, int songID, EGameMode gameMode) + public static void InsertSong(int playlistId, int positionIndex, int songId, EGameMode gameMode) { - CPlaylistFile pl = Get(playlistID); + var pl = Get(playlistId); if (pl != null) - pl.InsertSong(positionIndex, songID, gameMode); + { + pl.InsertSong(positionIndex, songId, gameMode); + } } - public static void MoveSong(int playlistID, int sourceIndex, int destIndex) + public static void MoveSong(int playlistId, int sourceIndex, int destIndex) { - CPlaylistFile pl = Get(playlistID); + var pl = Get(playlistId); if (pl != null) + { pl.MoveSong(sourceIndex, destIndex); + } } - public static void MovePSongDown(int playlistID, int songIndex) + public static void MovePSongDown(int playlistId, int songIndex) { - CPlaylistFile pl = Get(playlistID); + var pl = Get(playlistId); if (pl != null) + { pl.MoveSongDown(songIndex); + } } - public static void MoveSongUp(int playlistID, int songIndex) + public static void MoveSongUp(int playlistId, int songIndex) { - CPlaylistFile pl = Get(playlistID); + var pl = Get(playlistId); if (pl != null) + { pl.MoveSongUp(songIndex); + } } - public static void DeleteSong(int playlistID, int songIndex) + public static void DeleteSong(int playlistId, int songIndex) { - CPlaylistFile pl = Get(playlistID); + var pl = Get(playlistId); if (pl != null) + { pl.DeleteSong(songIndex); + } } - public static int GetSongCount(int playlistID) + public static int GetSongCount(int playlistId) { - CPlaylistFile pl = Get(playlistID); + var pl = Get(playlistId); return pl != null ? pl.Songs.Count : -1; } - public static CPlaylistSong GetSong(int playlistID, int songIndex) + public static CPlaylistSong GetSong(int playlistId, int songIndex) { - CPlaylistFile pl = Get(playlistID); + var pl = Get(playlistId); if (pl == null || songIndex >= pl.Songs.Count) + { return null; + } return pl.Songs[songIndex]; } - public static bool ContainsSong(int playlistID, int songID) + public static bool ContainsSong(int playlistId, int songId) { - CPlaylistFile pl = Get(playlistID); - return pl != null && pl.Songs.Find((x) => x.SongID == songID) != null; + var pl = Get(playlistId); + return pl != null && pl.Songs.Find((x) => x.SongId == songId) != null; } #region private methods @@ -225,10 +249,13 @@ namespace Vocaluxe.Base private static CPlaylistFile _ConvertUSDXPlaylist(string file) { var pl = new CPlaylistFile(); - ReadOnlyCollection allSongs = CSongs.AllSongs; + var allSongs = CSongs.AllSongs; if (!File.Exists(file)) + { return null; + } + try { StreamReader sr; @@ -237,30 +264,40 @@ namespace Vocaluxe.Base string line; while ((line = sr.ReadLine()) != null) { - int pos = line.IndexOf(":", StringComparison.Ordinal); + var pos = line.IndexOf(":", StringComparison.Ordinal); if (pos <= 0) + { continue; + } + if (line[0] == '#') { //Name or comment - string identifier = line.Substring(1, pos - 1).Trim(); - string value = line.Substring(pos + 1, line.Length - pos - 1).Trim(); + var identifier = line.Substring(1, pos - 1).Trim(); + var value = line.Substring(pos + 1, line.Length - pos - 1).Trim(); if (identifier.ToUpper() == "NAME") + { pl.Name = value; + } } else { //Song - string artist = line.Substring(0, pos - 1).Trim(); - string title = line.Substring(pos + 1, line.Length - pos - 1).Trim(); - CSong plSong = allSongs.FirstOrDefault(song => song.Artist == artist && song.Title == title); + var artist = line.Substring(0, pos - 1).Trim(); + var title = line.Substring(pos + 1, line.Length - pos - 1).Trim(); + var plSong = allSongs.FirstOrDefault(song => song.Artist == artist && song.Title == title); if (plSong != null) - pl.AddSong(plSong.ID); + { + pl.AddSong(plSong.Id); + } else + { CLog.Error("Can't find song '" + title + "' from '" + artist + "' in playlist file: " + file); + } } } } + File.Delete(file); } catch diff --git a/Vocaluxe/Base/CProfiles.cs b/Vocaluxe/Base/CProfiles.cs index 04354a5f..97cb5631 100644 --- a/Vocaluxe/Base/CProfiles.cs +++ b/Vocaluxe/Base/CProfiles.cs @@ -17,8 +17,8 @@ using System; using System.Collections.Generic; -using System.Linq; using System.IO; +using System.Linq; using System.Text.RegularExpressions; using VocaluxeLib; using VocaluxeLib.Draw; @@ -46,7 +46,7 @@ namespace Vocaluxe.Base public CProfile Profile; public CAvatar Avatar; public EAction Action; - public Guid ProfileID; + public Guid ProfileId; } #endregion enums and structs @@ -54,7 +54,7 @@ namespace Vocaluxe.Base private static Dictionary _Profiles; private static Dictionary _Avatars; - private static Queue _AvatarIDs; + private static Queue _AvatarIds; private static readonly Queue _Queue = new Queue(); private static readonly Object _QueueMutex = new Object(); @@ -80,9 +80,11 @@ namespace Vocaluxe.Base public static void Init() { _Avatars = new Dictionary(); - _AvatarIDs = new Queue(1000); - for (int i = 0; i < 1000; i++) - _AvatarIDs.Enqueue(i); + _AvatarIds = new Queue(1000); + for (var i = 0; i < 1000; i++) + { + _AvatarIds.Enqueue(i); + } _Profiles = new Dictionary(); @@ -95,7 +97,7 @@ namespace Vocaluxe.Base { while (_Queue.Count > 0) { - SChange change = _Queue.Dequeue(); + var change = _Queue.Dequeue(); switch (change.Action) { case EAction.LoadProfiles: @@ -110,61 +112,78 @@ namespace Vocaluxe.Base break; case EAction.AddProfile: - CProfile newProf = change.Profile; + var newProf = change.Profile; if (newProf == null) - break; - - newProf.ID = Guid.NewGuid(); - if (newProf.Avatar == null) - newProf.Avatar = _Avatars.Values.First(); - else if (newProf.Avatar.ID < 0) { - newProf.Avatar.ID = _AvatarIDs.Dequeue(); - _Avatars.Add(newProf.Avatar.ID, newProf.Avatar); + break; + } + + newProf.Id = Guid.NewGuid(); + if (newProf.Avatar == null) + { + newProf.Avatar = _Avatars.Values.First(); + } + else if (newProf.Avatar.Id < 0) + { + newProf.Avatar.Id = _AvatarIds.Dequeue(); + _Avatars.Add(newProf.Avatar.Id, newProf.Avatar); _AvatarsChanged = true; } + newProf.SaveProfile(); - _Profiles.Add(newProf.ID, newProf); + _Profiles.Add(newProf.Id, newProf); _ProfilesChanged = true; break; case EAction.EditProfile: if (change.Profile == null) + { break; + } - if (!IsProfileIDValid(change.Profile.ID)) + if (!IsProfileIdValid(change.Profile.Id)) + { return; + } - _Profiles[change.Profile.ID] = change.Profile; + _Profiles[change.Profile.Id] = change.Profile; _ProfilesChanged = true; break; case EAction.DeleteProfile: - if (!IsProfileIDValid(change.ProfileID)) + if (!IsProfileIdValid(change.ProfileId)) + { break; + } - _DeleteProfile(change.ProfileID); + _DeleteProfile(change.ProfileId); _ProfilesChanged = true; break; case EAction.AddAvatar: if (change.Avatar == null) + { break; + } - change.Avatar.ID = _AvatarIDs.Dequeue(); - _Avatars.Add(change.Avatar.ID, change.Avatar); + change.Avatar.Id = _AvatarIds.Dequeue(); + _Avatars.Add(change.Avatar.Id, change.Avatar); _AvatarsChanged = true; break; case EAction.EditAvatar: if (change.Avatar == null) + { break; + } - if (!IsAvatarIDValid(change.Avatar.ID)) + if (!IsAvatarIdValid(change.Avatar.Id)) + { return; + } - _Avatars[change.Avatar.ID] = change.Avatar; + _Avatars[change.Avatar.Id] = change.Avatar; _AvatarsChanged = true; break; } @@ -172,19 +191,25 @@ namespace Vocaluxe.Base } if (_ProfileChangedCallbacks.Count == 0) + { return; + } var flags = EProfileChangedFlags.None; if (_AvatarsChanged) + { flags = EProfileChangedFlags.Avatar; + } if (_ProfilesChanged) + { flags |= EProfileChangedFlags.Profile; + } if (flags != EProfileChangedFlags.None) { - int index = 0; + var index = 0; while (index < _ProfileChangedCallbacks.Count) { try @@ -195,9 +220,11 @@ namespace Vocaluxe.Base { _ProfileChangedCallbacks.RemoveAt(index); } + index++; } } + _AvatarsChanged = false; _ProfilesChanged = false; } @@ -209,7 +236,7 @@ namespace Vocaluxe.Base public static void LoadProfiles() { - var change = new SChange {Action = EAction.LoadProfiles}; + var change = new SChange { Action = EAction.LoadProfiles }; lock (_QueueMutex) { @@ -219,7 +246,7 @@ namespace Vocaluxe.Base public static void LoadAvatars() { - var change = new SChange {Action = EAction.LoadAvatars}; + var change = new SChange { Action = EAction.LoadAvatars }; lock (_QueueMutex) { @@ -230,9 +257,11 @@ namespace Vocaluxe.Base public static void AddProfile(CProfile newProfile) { if (newProfile == null) + { return; + } - var change = new SChange {Action = EAction.AddProfile, Profile = newProfile}; + var change = new SChange { Action = EAction.AddProfile, Profile = newProfile }; lock (_QueueMutex) { @@ -243,9 +272,11 @@ namespace Vocaluxe.Base public static void EditProfile(CProfile editProfile) { if (editProfile == null) + { return; + } - var change = new SChange {Action = EAction.EditProfile, Profile = editProfile}; + var change = new SChange { Action = EAction.EditProfile, Profile = editProfile }; lock (_QueueMutex) { @@ -253,12 +284,14 @@ namespace Vocaluxe.Base } } - public static void DeleteProfile(Guid profileID) + public static void DeleteProfile(Guid profileId) { - if (!IsProfileIDValid(profileID)) + if (!IsProfileIdValid(profileId)) + { return; + } - var change = new SChange {Action = EAction.DeleteProfile, ProfileID = profileID}; + var change = new SChange { Action = EAction.DeleteProfile, ProfileId = profileId }; lock (_QueueMutex) { @@ -269,9 +302,11 @@ namespace Vocaluxe.Base public static void AddAvatar(CAvatar newAvatar) { if (newAvatar == null) + { return; + } - var change = new SChange {Action = EAction.AddAvatar, Avatar = newAvatar}; + var change = new SChange { Action = EAction.AddAvatar, Avatar = newAvatar }; lock (_QueueMutex) { @@ -282,9 +317,11 @@ namespace Vocaluxe.Base public static void EditAvatar(CAvatar editAvatar) { if (editAvatar == null) + { return; + } - var change = new SChange {Action = EAction.EditAvatar, Avatar = editAvatar}; + var change = new SChange { Action = EAction.EditAvatar, Avatar = editAvatar }; lock (_QueueMutex) { @@ -295,25 +332,31 @@ namespace Vocaluxe.Base public static CProfile[] GetProfiles() { if (_Profiles.Count == 0) + { return new CProfile[0]; + } var list = new List(_Profiles.Values); list.Sort(_AlphaNumericCompareByPlayerName); return list.ToArray(); } - public static CProfile GetProfile(Guid profileID) + public static CProfile GetProfile(Guid profileId) { - if (!IsProfileIDValid(profileID)) + if (!IsProfileIdValid(profileId)) + { return null; + } - return _Profiles[profileID]; + return _Profiles[profileId]; } public static IEnumerable GetAvatars() { if (_Avatars.Count == 0) + { return null; + } var result = new CAvatar[_Avatars.Count]; _Avatars.Values.CopyTo(result, 0); @@ -324,199 +367,242 @@ namespace Vocaluxe.Base public static Guid NewProfile(string fileName = "") { var profile = new CProfile - { - FilePath = fileName != "" ? Path.Combine(CConfig.ProfileFolders[0], fileName) : String.Empty - }; + { + FilePath = fileName != "" ? Path.Combine(CConfig.ProfileFolders[0], fileName) : string.Empty + }; if (File.Exists(profile.FilePath)) + { return Guid.Empty; + } - profile.ID = Guid.NewGuid(); - _Profiles.Add(profile.ID, profile); + profile.Id = Guid.NewGuid(); + _Profiles.Add(profile.Id, profile); _ProfilesChanged = true; - return profile.ID; + return profile.Id; } public static int NewAvatar(string fileName) { - CAvatar avatar = CAvatar.GetAvatar(fileName); + var avatar = CAvatar.GetAvatar(fileName); if (avatar == null) + { return -1; + } - avatar.ID = _AvatarIDs.Dequeue(); - _Avatars.Add(avatar.ID, avatar); + avatar.Id = _AvatarIds.Dequeue(); + _Avatars.Add(avatar.Id, avatar); _AvatarsChanged = true; - return avatar.ID; + return avatar.Id; } public static void SaveProfiles() { - foreach (Guid id in _Profiles.Keys) + foreach (var id in _Profiles.Keys) + { _Profiles[id].SaveProfile(); + } } - public static bool IsProfileIDValid(Guid profileID) + public static bool IsProfileIdValid(Guid profileId) { - return profileID != Guid.Empty && _Profiles.ContainsKey(profileID); + return profileId != Guid.Empty && _Profiles.ContainsKey(profileId); } - public static bool IsAvatarIDValid(int avatarID) + public static bool IsAvatarIdValid(int avatarId) { - return _Avatars.ContainsKey(avatarID); + return _Avatars.ContainsKey(avatarId); } #endregion public methods #region profile properties - public static string GetPlayerName(Guid profileID, int playerNum = 0) + public static string GetPlayerName(Guid profileId, int playerNum = 0) { - if (IsProfileIDValid(profileID)) - return _Profiles[profileID].PlayerName; + if (IsProfileIdValid(profileId)) + { + return _Profiles[profileId].PlayerName; + } - string playerName = CLanguage.Translate("TR_SCREENNAMES_PLAYER"); + var playerName = CLanguage.Translate("TR_SCREENNAMES_PLAYER"); if (playerNum > 0) + { playerName += " " + playerNum; + } + return playerName; } - public static void SetPlayerName(Guid profileID, string playerName) + public static void SetPlayerName(Guid profileId, string playerName) { - if (!IsProfileIDValid(profileID)) + if (!IsProfileIdValid(profileId)) + { return; + } - _Profiles[profileID].PlayerName = playerName; + _Profiles[profileId].PlayerName = playerName; } - public static string GetProfileFileName(Guid profileID) + public static string GetProfileFileName(Guid profileId) { - if (!IsProfileIDValid(profileID)) - return String.Empty; + if (!IsProfileIdValid(profileId)) + { + return string.Empty; + } - return Path.GetFileName(_Profiles[profileID].FilePath); + return Path.GetFileName(_Profiles[profileId].FilePath); } - public static string AddGetPlayerName(Guid profileID, char chr) + public static string AddGetPlayerName(Guid profileId, char chr) { - if (!IsProfileIDValid(profileID)) - return String.Empty; + if (!IsProfileIdValid(profileId)) + { + return string.Empty; + } - _Profiles[profileID].PlayerName += chr; - return _Profiles[profileID].PlayerName; + _Profiles[profileId].PlayerName += chr; + return _Profiles[profileId].PlayerName; } - public static string GetDeleteCharInPlayerName(Guid profileID) + public static string GetDeleteCharInPlayerName(Guid profileId) { - if (!IsProfileIDValid(profileID)) - return String.Empty; + if (!IsProfileIdValid(profileId)) + { + return string.Empty; + } - CProfile profile = _Profiles[profileID]; - if (!String.IsNullOrEmpty(profile.PlayerName)) + var profile = _Profiles[profileId]; + if (!string.IsNullOrEmpty(profile.PlayerName)) + { profile.PlayerName = profile.PlayerName.Remove(profile.PlayerName.Length - 1); + } return profile.PlayerName; } - public static EGameDifficulty GetDifficulty(Guid profileID) + public static EGameDifficulty GetDifficulty(Guid profileId) { - return IsProfileIDValid(profileID) ? _Profiles[profileID].Difficulty : EGameDifficulty.TR_CONFIG_NORMAL; + return IsProfileIdValid(profileId) ? _Profiles[profileId].Difficulty : EGameDifficulty.TR_CONFIG_NORMAL; } - public static void SetDifficulty(Guid profileID, EGameDifficulty difficulty) + public static void SetDifficulty(Guid profileId, EGameDifficulty difficulty) { - if (!IsProfileIDValid(profileID)) + if (!IsProfileIdValid(profileId)) + { return; + } - _Profiles[profileID].Difficulty = difficulty; + _Profiles[profileId].Difficulty = difficulty; } - public static EUserRole GetUserRoleProfile(Guid profileID) + public static EUserRole GetUserRoleProfile(Guid profileId) { - return IsProfileIDValid(profileID) ? _Profiles[profileID].UserRole : EUserRole.TR_USERROLE_GUEST; + return IsProfileIdValid(profileId) ? _Profiles[profileId].UserRole : EUserRole.TR_USERROLE_GUEST; } - public static void SetUserRoleProfile(Guid profileID, EUserRole option) + public static void SetUserRoleProfile(Guid profileId, EUserRole option) { - if (!IsProfileIDValid(profileID)) + if (!IsProfileIdValid(profileId)) + { return; + } + //Only allow the change of TR_USERROLE_GUEST, TR_USERROLE_NORMAL and TR_USERROLE_ADMIN - const EUserRole mask = (EUserRole.TR_USERROLE_GUEST | EUserRole.TR_USERROLE_NORMAL | EUserRole.TR_USERROLE_ADMIN); + const EUserRole mask = EUserRole.TR_USERROLE_GUEST | EUserRole.TR_USERROLE_NORMAL | EUserRole.TR_USERROLE_ADMIN; option &= mask; - _Profiles[profileID].UserRole = (_Profiles[profileID].UserRole & ~mask) | option; + _Profiles[profileId].UserRole = (_Profiles[profileId].UserRole & ~mask) | option; } - public static EOffOn GetActive(Guid profileID) + public static EOffOn GetActive(Guid profileId) { - return IsProfileIDValid(profileID) ? _Profiles[profileID].Active : EOffOn.TR_CONFIG_OFF; + return IsProfileIdValid(profileId) ? _Profiles[profileId].Active : EOffOn.TR_CONFIG_OFF; } - public static void SetActive(Guid profileID, EOffOn option) + public static void SetActive(Guid profileId, EOffOn option) { - if (!IsProfileIDValid(profileID)) + if (!IsProfileIdValid(profileId)) + { return; + } - _Profiles[profileID].Active = option; + _Profiles[profileId].Active = option; } - public static bool IsGuestProfile(Guid profileID) + public static bool IsGuestProfile(Guid profileId) { - if (!IsProfileIDValid(profileID)) + if (!IsProfileIdValid(profileId)) + { return true; // this will prevent from saving dummy profiles to highscore db + } - return _Profiles[profileID].UserRole <= EUserRole.TR_USERROLE_GUEST; + return _Profiles[profileId].UserRole <= EUserRole.TR_USERROLE_GUEST; } - public static bool IsActive(Guid profileID) + public static bool IsActive(Guid profileId) { - if (!IsProfileIDValid(profileID)) + if (!IsProfileIdValid(profileId)) + { return false; - return _Profiles[profileID].Active == EOffOn.TR_CONFIG_ON; + } + + return _Profiles[profileId].Active == EOffOn.TR_CONFIG_ON; } - public static void SetAvatar(Guid profileID, int avatarID) + public static void SetAvatar(Guid profileId, int avatarId) { - if (!IsProfileIDValid(profileID) || !IsAvatarIDValid(avatarID)) + if (!IsProfileIdValid(profileId) || !IsAvatarIdValid(avatarId)) + { return; + } - _Profiles[profileID].Avatar = _Avatars[avatarID]; + _Profiles[profileId].Avatar = _Avatars[avatarId]; } - public static int GetAvatarID(Guid profileID) + public static int GetAvatarId(Guid profileId) { - if (!IsProfileIDValid(profileID) || _Profiles[profileID].Avatar == null) + if (!IsProfileIdValid(profileId) || _Profiles[profileId].Avatar == null) + { return -1; + } - return _Profiles[profileID].Avatar.ID; + return _Profiles[profileId].Avatar.Id; } - public static CAvatar GetAvatar(Guid profileID) + public static CAvatar GetAvatar(Guid profileId) { - if (!IsProfileIDValid(profileID)) + if (!IsProfileIdValid(profileId)) + { return null; + } - return _Profiles[profileID].Avatar; + return _Profiles[profileId].Avatar; } //TODO: Remove this? - public static Guid GetProfileID(Guid num) + public static Guid GetProfileId(Guid num) { - return _Profiles[num].ID; + return _Profiles[num].Id; } #endregion profile properties #region avatar texture - public static CTextureRef GetAvatarTexture(int avatarID) + public static CTextureRef GetAvatarTexture(int avatarId) { - if (!IsAvatarIDValid(avatarID)) + if (!IsAvatarIdValid(avatarId)) + { return null; + } - return _Avatars[avatarID].Texture; + return _Avatars[avatarId].Texture; } - public static CTextureRef GetAvatarTextureFromProfile(Guid profileID) + public static CTextureRef GetAvatarTextureFromProfile(Guid profileId) { - if (!IsProfileIDValid(profileID) || _Profiles[profileID].Avatar == null) + if (!IsProfileIdValid(profileId) || _Profiles[profileId].Avatar == null) + { return null; + } - return _Profiles[profileID].Avatar.Texture; + return _Profiles[profileId].Avatar.Texture; } #endregion avatar texture @@ -530,30 +616,41 @@ namespace Vocaluxe.Base { var ids = new Guid[_Profiles.Keys.Count]; _Profiles.Keys.CopyTo(ids, 0); - foreach (Guid id in ids) + foreach (var id in ids) { if (_Profiles[id].LoadProfile()) + { knownFiles.Add(Path.GetFileName(_Profiles[id].FilePath)); + } else + { _Profiles.Remove(id); + } } } var files = new List(); - foreach (string path in CConfig.ProfileFolders) + foreach (var path in CConfig.ProfileFolders) + { files.AddRange(CHelper.ListFiles(path, "*.xml", true, true)); + } - foreach (string file in files) + foreach (var file in files) { if (knownFiles.Contains(Path.GetFileName(file))) + { continue; + } var profile = new CProfile(); if (profile.LoadProfile(file)) - _Profiles.Add(profile.ID, profile); + { + _Profiles.Add(profile.Id, profile); + } } + _ProfilesChanged = true; } @@ -564,79 +661,96 @@ namespace Vocaluxe.Base { var ids = new int[_Avatars.Keys.Count]; _Avatars.Keys.CopyTo(ids, 0); - foreach (int id in ids) + foreach (var id in ids) { if (_Avatars[id].Reload()) + { knownFiles.Add(Path.GetFileName(_Avatars[id].FileName)); + } else + { _Avatars.Remove(id); + } } } var files = new List(); - foreach (string path in CConfig.ProfileFolders) + foreach (var path in CConfig.ProfileFolders) + { files.AddRange(CHelper.ListImageFiles(path, true, true)); + } - foreach (string file in files) + foreach (var file in files) { if (knownFiles.Contains(Path.GetFileName(file))) + { continue; + } - CAvatar avatar = CAvatar.GetAvatar(file); + var avatar = CAvatar.GetAvatar(file); if (avatar != null) { - avatar.ID = _AvatarIDs.Dequeue(); - _Avatars.Add(avatar.ID, avatar); + avatar.Id = _AvatarIds.Dequeue(); + _Avatars.Add(avatar.Id, avatar); } } + _ProfilesChanged = true; } - private static void _DeleteProfile(Guid profileID) + private static void _DeleteProfile(Guid profileId) { - if (!IsProfileIDValid(profileID)) - return; - - if (string.IsNullOrEmpty(_Profiles[profileID].FilePath)) + if (!IsProfileIdValid(profileId)) { - _RemoveProfile(profileID); + return; + } + + if (string.IsNullOrEmpty(_Profiles[profileId].FilePath)) + { + _RemoveProfile(profileId); return; } try { //Check if profile saved in config - for (int i = 0; i < CSettings.MaxNumPlayer; i++) + for (var i = 0; i < CSettings.MaxNumPlayer; i++) { - if (CConfig.Config.Game.Players[i] == GetProfileFileName(profileID)) + if (CConfig.Config.Game.Players[i] == GetProfileFileName(profileId)) { CConfig.Config.Game.Players[i] = string.Empty; CConfig.SaveConfig(); } } - File.Delete(_Profiles[profileID].FilePath); - _RemoveProfile(profileID); + + File.Delete(_Profiles[profileId].FilePath); + _RemoveProfile(profileId); //Check if profile is selected in game - for (int i = 0; i < CGame.Players.Length; i++) + for (var i = 0; i < CGame.Players.Length; i++) { - if (CGame.Players[i].ProfileID == profileID) - CGame.Players[i].ProfileID = Guid.Empty; + if (CGame.Players[i].ProfileId == profileId) + { + CGame.Players[i].ProfileId = Guid.Empty; + } } } catch (Exception) { - CLog.Error("Can't delete Profile File " + _Profiles[profileID].FilePath); + CLog.Error("Can't delete Profile File " + _Profiles[profileId].FilePath); } + _ProfilesChanged = true; } - private static void _RemoveProfile(Guid profileID) + private static void _RemoveProfile(Guid profileId) { - if (!IsProfileIDValid(profileID)) + if (!IsProfileIdValid(profileId)) + { return; + } - _Profiles.Remove(profileID); + _Profiles.Remove(profileId); _ProfilesChanged = true; } @@ -652,13 +766,16 @@ namespace Vocaluxe.Base public static CAvatar GetAvatarByFilename(string fileName) { - string name = Path.GetFileName(fileName); + var name = Path.GetFileName(fileName); - foreach (int id in _Avatars.Keys) + foreach (var id in _Avatars.Keys) { if (Path.GetFileName(_Avatars[id].FileName) == name) + { return _Avatars[id]; + } } + return null; } #endregion private methods diff --git a/Vocaluxe/Base/CRecord.cs b/Vocaluxe/Base/CRecord.cs index cd82e459..00f065d1 100644 --- a/Vocaluxe/Base/CRecord.cs +++ b/Vocaluxe/Base/CRecord.cs @@ -17,11 +17,11 @@ using System.Collections.ObjectModel; using Vocaluxe.Lib.Sound.Record; +using Vocaluxe.Lib.Sound.Record.PortAudio; +using VocaluxeLib; #if WIN using Vocaluxe.Lib.Sound.Record.DirectSound; #endif -using Vocaluxe.Lib.Sound.Record.PortAudio; -using VocaluxeLib; namespace Vocaluxe.Base { @@ -32,7 +32,10 @@ namespace Vocaluxe.Base public static bool Init() { if (_Record != null) + { return false; + } + switch (CConfig.Config.Sound.RecordLib) { #if WIN @@ -41,11 +44,12 @@ namespace Vocaluxe.Base break; #endif - // case ERecordLib.PortAudio: + // case ERecordLib.PortAudio: default: _Record = new CPortAudioRecord(); break; } + return _Record.Init(); } @@ -120,15 +124,18 @@ namespace Vocaluxe.Base public static ReadOnlyCollection GetDevices() { - ReadOnlyCollection devices = _Record.RecordDevices(); + var devices = _Record.RecordDevices(); if (devices != null) { - foreach (CRecordDevice device in devices) + foreach (var device in devices) { - for(int ch = 0; ch < device.Channels; ++ch) - device.PlayerChannel[ch] = _GetPlayerFromMicConfig(device.Name, device.Driver, ch+1); + for (var ch = 0; ch < device.Channels; ++ch) + { + device.PlayerChannel[ch] = _GetPlayerFromMicConfig(device.Name, device.Driver, ch + 1); + } } + return devices; } @@ -137,13 +144,16 @@ namespace Vocaluxe.Base private static int _GetPlayerFromMicConfig(string device, string devicedriver, int channel) { - for (int p = 0; p < CSettings.MaxNumPlayer; p++) + for (var p = 0; p < CSettings.MaxNumPlayer; p++) { if (CConfig.Config.Record.MicConfig[p].DeviceName == device && CConfig.Config.Record.MicConfig[p].DeviceDriver == devicedriver && CConfig.Config.Record.MicConfig[p].Channel == channel) + { return p + 1; + } } + return 0; } } diff --git a/Vocaluxe/Base/CSettings.cs b/Vocaluxe/Base/CSettings.cs index d1bbd5fa..8fae9294 100644 --- a/Vocaluxe/Base/CSettings.cs +++ b/Vocaluxe/Base/CSettings.cs @@ -20,11 +20,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; -using System.Text; using System.Windows.Forms; using VocaluxeLib; using VocaluxeLib.Log; -using VocaluxeLib.Xml; namespace Vocaluxe.Base { @@ -38,8 +36,6 @@ namespace Vocaluxe.Base // ReSharper restore UnusedMember.Global } - - /// /// This class contains settings for the program /// These are not editable, everything that can be changed by the user is in CConfig @@ -57,7 +53,6 @@ namespace Vocaluxe.Base //TODO: This should not be here as it can change //State of the program public static EProgramState ProgramState = EProgramState.Start; - public static ERevision VersionRevision { @@ -67,14 +62,17 @@ namespace Vocaluxe.Base { return ERevision.Alpha; } + if (Version.ToLower().Contains("beta")) { return ERevision.Beta; } + if (Version.ToLower().Contains("rc")) { return ERevision.RC; } + return ERevision.Release; } } @@ -113,7 +111,7 @@ namespace Vocaluxe.Base public const string FileNameOldHighscoreDB = "Ultrastar.db"; public const string FileNameCoverDB = "CoverDB.sqlite"; - + public const string FileNameMainLog = "Vocaluxe.log"; public const string FileNameSongLog = "Song.log"; public const string FileNameCrashMarker = "Marker"; @@ -204,20 +202,14 @@ namespace Vocaluxe.Base public static string Version { - get - { - return Application.ProductVersion.Split('-').First(); - } + get { return Application.ProductVersion.Split('-').First(); } } public static string FullVersion { - get - { - return Application.ProductVersion; - } + get { return Application.ProductVersion; } } - + public static string GetFullVersionText() { return ((AssemblyTitleAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute), false).First()).Title; @@ -231,19 +223,21 @@ namespace Vocaluxe.Base public static void CreateFolders() { var folders = new List - { - Path.Combine(ProgramFolder, FolderNameCover), - Path.Combine(ProgramFolder, FolderNameFonts), - Path.Combine(DataFolder, FolderNameScreenshots), - Path.Combine(ProgramFolder, FolderNameBackgroundMusic), - Path.Combine(ProgramFolder, FolderNameSounds), - Path.Combine(DataFolder, CConfig.FolderPlaylists) - }; + { + Path.Combine(ProgramFolder, FolderNameCover), + Path.Combine(ProgramFolder, FolderNameFonts), + Path.Combine(DataFolder, FolderNameScreenshots), + Path.Combine(ProgramFolder, FolderNameBackgroundMusic), + Path.Combine(ProgramFolder, FolderNameSounds), + Path.Combine(DataFolder, CConfig.FolderPlaylists) + }; folders.AddRange(CConfig.ProfileFolders); folders.AddRange(CConfig.SongFolders); - foreach (string folder in folders) + foreach (var folder in folders) + { _CreateFolder(folder); + } } private static void _CreateFolder(string path) @@ -261,4 +255,4 @@ namespace Vocaluxe.Base } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CSongCategorizer.cs b/Vocaluxe/Base/CSongCategorizer.cs index 8354cd3f..039ebf1e 100644 --- a/Vocaluxe/Base/CSongCategorizer.cs +++ b/Vocaluxe/Base/CSongCategorizer.cs @@ -48,10 +48,16 @@ namespace Vocaluxe.Base set { if (value == _Tabs) + { return; + } + _Tabs = value; if (_Tabs == EOffOn.TR_CONFIG_ON) + { CSongs.Category = -1; + } + _SetChanged(); } } @@ -67,7 +73,7 @@ namespace Vocaluxe.Base CCategory lastCategory = null; CCategory noCategory = null; - foreach (CSongPointer songPointer in CSongs.Sorter.SortedSongs) + foreach (var songPointer in CSongs.Sorter.SortedSongs) { if (songPointer.SortString != "") { @@ -76,6 +82,7 @@ namespace Vocaluxe.Base lastCategory = new CCategory(songPointer.SortString); _Categories.Add(lastCategory); } + lastCategory.Songs.Add(songPointer); } else @@ -85,6 +92,7 @@ namespace Vocaluxe.Base noCategory = new CCategory(_GetNoCategoryName()); _Categories.Add(noCategory); } + noCategory.Songs.Add(songPointer); } } @@ -95,28 +103,35 @@ namespace Vocaluxe.Base /// private static void _AdjustCategoryNames() { - ESongSorting sorting = CSongs.Sorter.SongSorting; + var sorting = CSongs.Sorter.SongSorting; switch (sorting) { case ESongSorting.TR_CONFIG_DECADE: - foreach (CSongPointer songPointer in CSongs.Sorter.SortedSongs) + foreach (var songPointer in CSongs.Sorter.SortedSongs) { - string year = songPointer.SortString; + var year = songPointer.SortString; if (year != "") { year = year.Substring(0, 3); songPointer.SortString = year + "0 - " + year + "9"; } } + break; case ESongSorting.TR_CONFIG_TITLE_LETTER: case ESongSorting.TR_CONFIG_ARTIST_LETTER: - foreach (CSongPointer songPointer in CSongs.Sorter.SortedSongs) - songPointer.SortString = (songPointer.SortString.Length == 0 || !Char.IsLetter(songPointer.SortString, 0)) ? "#" : songPointer.SortString[0].ToString(); + foreach (var songPointer in CSongs.Sorter.SortedSongs) + { + songPointer.SortString = songPointer.SortString.Length == 0 || !Char.IsLetter(songPointer.SortString, 0) ? "#" : songPointer.SortString[0].ToString(); + } + break; case ESongSorting.TR_CONFIG_DATEADDED: - foreach (CSongPointer songPointer in CSongs.Sorter.SortedSongs) - songPointer.SortString = CSongs.GetSong(songPointer.SongID).DateAdded.ToString("dd/MM/yyyy"); + foreach (var songPointer in CSongs.Sorter.SortedSongs) + { + songPointer.SortString = CSongs.GetSong(songPointer.SongId).DateAdded.ToString("dd/MM/yyyy"); + } + break; } } @@ -161,18 +176,23 @@ namespace Vocaluxe.Base Debug.Assert(false, "Forgot category option"); break; } + return noCategoryName; } private void _FillCategories() { if (!_Changed) + { return; + } _Categories.Clear(); if (_Tabs != EOffOn.TR_CONFIG_OFF) + { _CreateCategories(); + } else { //No categories. So don't create them! @@ -180,13 +200,16 @@ namespace Vocaluxe.Base _Categories[0].Songs.AddRange(CSongs.Sorter.SortedSongs); } - foreach (CCategory cat in _Categories) + foreach (var cat in _Categories) { cat.CoverTextureSmall = CCover.Cover(cat.Name); if (cat.CoverTextureSmall == CCover.NoCover) + { cat.CoverTextureSmall = CCover.GenerateCover(cat.Name, CCover._SongSortingToType(CSongs.Sorter.SongSorting), cat.GetSong(0)); + } } + _Changed = false; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CSongFilter.cs b/Vocaluxe/Base/CSongFilter.cs index 107ede92..033a5389 100644 --- a/Vocaluxe/Base/CSongFilter.cs +++ b/Vocaluxe/Base/CSongFilter.cs @@ -27,9 +27,9 @@ namespace Vocaluxe.Base { private readonly List _FilteredSongs = new List(); - private String _SearchString = String.Empty; + private String _SearchString = string.Empty; private EDuetOptions _DuetOptions = EDuetOptions.All; - private int _PlaylistID = -1; + private int _PlaylistId = -1; public List FilteredSongs { @@ -71,13 +71,13 @@ namespace Vocaluxe.Base SetOptions(searchString, duetOptions, -1); } - public void SetOptions(String searchString, EDuetOptions duetOptions, int playlistID) + public void SetOptions(String searchString, EDuetOptions duetOptions, int playlistId) { - if (searchString != _SearchString || duetOptions != _DuetOptions || playlistID != _PlaylistID) + if (searchString != _SearchString || duetOptions != _DuetOptions || playlistId != _PlaylistId) { _SearchString = searchString; _DuetOptions = duetOptions; - _PlaylistID = playlistID; + _PlaylistId = playlistId; _SetChanged(); } } @@ -85,36 +85,42 @@ namespace Vocaluxe.Base private void _FilterSongs() { if (!_Changed) + { return; + } _FilteredSongs.Clear(); string[] searchStrings = null; if (_SearchString != "") - searchStrings = _SearchString.ToUpper().Split(new char[] {' '}); + { + searchStrings = _SearchString.ToUpper().Split(new char[] { ' ' }); + } - String searchForArtist = null; // a: - String searchForTitle = null; // t: - String searchForGenre = null; // g: - String searchForYear = null; // y: - String searchForLanguage = null; // l: - String searchForCreator = null; // c: - String searchForEdition = null; // e: - String searchForTags = null; // #: - String searchForAlbum = null; // al: - String searchForFileName = null; // fi: - String searchForFolderName = null; // fo: - bool expertSearch = false; + String searchForArtist = null; // a: + String searchForTitle = null; // t: + String searchForGenre = null; // g: + String searchForYear = null; // y: + String searchForLanguage = null; // l: + String searchForCreator = null; // c: + String searchForEdition = null; // e: + String searchForTags = null; // #: + String searchForAlbum = null; // al: + String searchForFileName = null; // fi: + String searchForFolderName = null; // fo: + var expertSearch = false; if (searchStrings != null) { - foreach (String searchToken in searchStrings) + foreach (var searchToken in searchStrings) { if (searchToken.Length < 3) + { continue; + } - String temp = searchToken.Substring(0, 2); - bool foundIt = true; + var temp = searchToken.Substring(0, 2); + var foundIt = true; switch (temp) { @@ -149,12 +155,18 @@ namespace Vocaluxe.Base if (foundIt) { - if (!expertSearch) expertSearch = true; + if (!expertSearch) + { + expertSearch = true; + } + continue; } if (searchToken.Length < 4) + { continue; + } foundIt = true; temp = searchToken.Substring(0, 3); @@ -176,114 +188,163 @@ namespace Vocaluxe.Base } if (foundIt && !expertSearch) + { expertSearch = true; + } } } - foreach (CSong song in CSongs.Songs) + foreach (var song in CSongs.Songs) { - if (_PlaylistID != -1 && !CBase.Playlist.ContainsSong(_PlaylistID, song.ID)) + if (_PlaylistId != -1 && !CBase.Playlist.ContainsSong(_PlaylistId, song.Id)) + { continue; - + } + if ((song.IsDuet && _DuetOptions != EDuetOptions.NoDuets) || (!song.IsDuet && _DuetOptions != EDuetOptions.Duets)) { if (searchStrings == null) + { _FilteredSongs.Add(song); + } else if (expertSearch) { // Stefan1200: Stop at a maximum of 800 search result to prevent performance issues if (_FilteredSongs.Count >= 800) + { break; + } if (searchForAlbum != null && song.Album.ToUpper().Contains(searchForAlbum)) + { _FilteredSongs.Add(song); + } + if (searchForArtist != null && song.Artist.ToUpper().Contains(searchForArtist)) + { _FilteredSongs.Add(song); + } + if (searchForTitle != null && song.Title.ToUpper().Contains(searchForTitle)) + { _FilteredSongs.Add(song); + } + if (searchForCreator != null && song.Creator.ToUpper().Contains(searchForCreator)) + { _FilteredSongs.Add(song); + } + if (searchForFileName != null && song.FileName.ToUpper().Contains(searchForFileName)) + { _FilteredSongs.Add(song); + } + if (searchForFolderName != null && song.FolderName.ToUpper().Contains(searchForFolderName)) + { _FilteredSongs.Add(song); + } if (searchForGenre != null) { - foreach (String genre in song.Genres) + foreach (var genre in song.Genres) { if (genre.ToUpper().Contains(searchForGenre)) + { _FilteredSongs.Add(song); + } } } if (searchForLanguage != null) { - foreach (String language in song.Languages) + foreach (var language in song.Languages) { if (language.ToUpper().Contains(searchForLanguage)) + { _FilteredSongs.Add(song); + } } } if (searchForEdition != null) { - foreach (String edition in song.Editions) + foreach (var edition in song.Editions) { if (edition.ToUpper().Contains(searchForEdition)) + { _FilteredSongs.Add(song); + } } } if (searchForTags != null) { - foreach (String tag in song.Tags) + foreach (var tag in song.Tags) { if (tag.ToUpper().Contains(searchForTags)) + { _FilteredSongs.Add(song); + } } } if (searchForYear != null) { - int pos = searchForYear.IndexOf("-"); + var pos = searchForYear.IndexOf("-"); if (pos == -1) { if (song.Year.Contains(searchForYear)) + { _FilteredSongs.Add(song); + } } else if (searchForYear.Length == 9) { - int yearStart = -1; - int yearEnd = -1; + var yearStart = -1; + var yearEnd = -1; if (!Int32.TryParse(searchForYear.Substring(0, pos), out yearStart)) + { continue; + } + if (!Int32.TryParse(searchForYear.Substring(pos + 1), out yearEnd)) + { continue; + } // Stefan1200: Prevent searches like 0000-9999, limit for a max distance of 100 years if (yearEnd - yearStart > 100) + { continue; + } - int yearSearch = -1; + var yearSearch = -1; if (!Int32.TryParse(song.Year, out yearSearch)) + { continue; + } if (yearSearch >= yearStart && yearSearch <= yearEnd) + { _FilteredSongs.Add(song); + } } } } else { - string search = song.Title.ToUpper() + " " + song.Artist.ToUpper(); + var search = song.Title.ToUpper() + " " + song.Artist.ToUpper(); if (searchStrings.All(search.Contains)) + { _FilteredSongs.Add(song); + } } } } + _Changed = false; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CSongSorter.cs b/Vocaluxe/Base/CSongSorter.cs index cc253c0b..c4a140ae 100644 --- a/Vocaluxe/Base/CSongSorter.cs +++ b/Vocaluxe/Base/CSongSorter.cs @@ -50,7 +50,10 @@ namespace Vocaluxe.Base set { if (value == _IgnoreArticles) + { return; + } + _IgnoreArticles = value; _SetChanged(); } @@ -62,7 +65,10 @@ namespace Vocaluxe.Base set { if (value == _SongSorting) + { return; + } + _SongSorting = value; _SetChanged(); } @@ -85,29 +91,32 @@ namespace Vocaluxe.Base private int _SortByFieldArtistTitle(CSongPointer s1, CSongPointer s2) { - int res = String.Compare(s1.SortString, s2.SortString, StringComparison.CurrentCultureIgnoreCase); + var res = String.Compare(s1.SortString, s2.SortString, StringComparison.CurrentCultureIgnoreCase); if (res == 0) { if (_IgnoreArticles == EOffOn.TR_CONFIG_ON) { - res = String.Compare(CSongs.Songs[s1.SongID].ArtistSorting, CSongs.Songs[s2.SongID].ArtistSorting, StringComparison.CurrentCultureIgnoreCase); - return res != 0 ? res : String.Compare(CSongs.Songs[s1.SongID].TitleSorting, CSongs.Songs[s2.SongID].TitleSorting, StringComparison.CurrentCultureIgnoreCase); + res = String.Compare(CSongs.Songs[s1.SongId].ArtistSorting, CSongs.Songs[s2.SongId].ArtistSorting, StringComparison.CurrentCultureIgnoreCase); + return res != 0 ? res : String.Compare(CSongs.Songs[s1.SongId].TitleSorting, CSongs.Songs[s2.SongId].TitleSorting, StringComparison.CurrentCultureIgnoreCase); } - res = String.Compare(CSongs.Songs[s1.SongID].Artist, CSongs.Songs[s2.SongID].Artist, StringComparison.CurrentCultureIgnoreCase); - return res != 0 ? res : String.Compare(CSongs.Songs[s1.SongID].Title, CSongs.Songs[s2.SongID].Title, StringComparison.CurrentCultureIgnoreCase); + + res = String.Compare(CSongs.Songs[s1.SongId].Artist, CSongs.Songs[s2.SongId].Artist, StringComparison.CurrentCultureIgnoreCase); + return res != 0 ? res : String.Compare(CSongs.Songs[s1.SongId].Title, CSongs.Songs[s2.SongId].Title, StringComparison.CurrentCultureIgnoreCase); } + return res; } private int _SortByFieldTitle(CSongPointer s1, CSongPointer s2) { - int res = String.Compare(s1.SortString, s2.SortString, StringComparison.CurrentCultureIgnoreCase); + var res = String.Compare(s1.SortString, s2.SortString, StringComparison.CurrentCultureIgnoreCase); if (res == 0) { return _IgnoreArticles == EOffOn.TR_CONFIG_ON - ? String.Compare(CSongs.Songs[s1.SongID].TitleSorting, CSongs.Songs[s2.SongID].TitleSorting, StringComparison.CurrentCultureIgnoreCase) : - String.Compare(CSongs.Songs[s1.SongID].Title, CSongs.Songs[s2.SongID].Title, StringComparison.CurrentCultureIgnoreCase); + ? String.Compare(CSongs.Songs[s1.SongId].TitleSorting, CSongs.Songs[s2.SongId].TitleSorting, StringComparison.CurrentCultureIgnoreCase) : + String.Compare(CSongs.Songs[s1.SongId].Title, CSongs.Songs[s2.SongId].Title, StringComparison.CurrentCultureIgnoreCase); } + return res; } @@ -116,7 +125,7 @@ namespace Vocaluxe.Base /// private int _SortByLetterFieldTitle(CSongPointer s1, CSongPointer s2) { - int res = String.Compare(s1.SortString[0].ToString(), s2.SortString[0].ToString(), StringComparison.CurrentCultureIgnoreCase); + var res = String.Compare(s1.SortString[0].ToString(), s2.SortString[0].ToString(), StringComparison.CurrentCultureIgnoreCase); return res != 0 ? res : _SortByFieldTitle(s1, s2); } @@ -125,7 +134,7 @@ namespace Vocaluxe.Base /// private int _SortByLetterFieldArtistTitle(CSongPointer s1, CSongPointer s2) { - int res = String.Compare(s1.SortString[0].ToString(), s2.SortString[0].ToString(), StringComparison.CurrentCultureIgnoreCase); + var res = String.Compare(s1.SortString[0].ToString(), s2.SortString[0].ToString(), StringComparison.CurrentCultureIgnoreCase); return res != 0 ? res : _SortByFieldArtistTitle(s1, s2); } @@ -171,26 +180,38 @@ namespace Vocaluxe.Base Debug.Assert(false, "Forgot sorting option"); break; } + Debug.Assert(value != null || values != null, "Sorting implementation faulty"); if (value != null) - list.Add(new CSongPointer(song.ID, value)); + { + list.Add(new CSongPointer(song.Id, value)); + } else { if (values.Count == 0) - list.Add(new CSongPointer(song.ID, "")); + { + list.Add(new CSongPointer(song.Id, "")); + } else - list.AddRange(values.Select(val => new CSongPointer(song.ID, val))); + { + list.AddRange(values.Select(val => new CSongPointer(song.Id, val))); + } } } private void _SortSongs() { if (!_Changed) + { return; + } - List sortList = new List(); - foreach (CSong song in CSongs.Filter.FilteredSongs) + var sortList = new List(); + foreach (var song in CSongs.Filter.FilteredSongs) + { _AddSongToList(song, sortList); + } + switch (_SongSorting) { case ESongSorting.TR_CONFIG_ARTIST: @@ -209,10 +230,12 @@ namespace Vocaluxe.Base } if (_SongSorting == ESongSorting.TR_CONFIG_DATEADDED) + { sortList.Reverse(); + } _SortedSongs = sortList.ToArray(); _Changed = false; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CSongs.cs b/Vocaluxe/Base/CSongs.cs index b8ff71ba..42f0b4c0 100644 --- a/Vocaluxe/Base/CSongs.cs +++ b/Vocaluxe/Base/CSongs.cs @@ -19,9 +19,9 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.IO; using System.Linq; using System.Threading; -using System.IO; using System.Threading.Tasks; using VocaluxeLib; using VocaluxeLib.Log; @@ -33,7 +33,6 @@ namespace Vocaluxe.Base { public delegate void CategoryChangedHandler(); - private static readonly List _Songs = new List(); private static readonly List _SongsForRandom = new List(); private static bool _CoverLoaded; @@ -47,10 +46,7 @@ namespace Vocaluxe.Base private static Thread _CoverLoaderThread; public static event CategoryChangedHandler OnCategoryChanged; - public static List Songs - { - get { return _Songs; } - } + public static List Songs { get; } = new List(); public static bool SongsLoaded { get; private set; } @@ -59,14 +55,17 @@ namespace Vocaluxe.Base get { if (SongsLoaded && NumAllSongs == 0) + { _CoverLoaded = true; + } + return _CoverLoaded; } } public static int NumAllSongs { - get { return _Songs.Count; } + get { return Songs.Count; } } public static int NumSongsVisible @@ -84,18 +83,26 @@ namespace Vocaluxe.Base get { if (_CatIndex >= Categories.Count) + { _CatIndex = -1; + } + return _CatIndex; } set { if (value == _CatIndex) + { return; + } + if (value == -1 || _IsCatIndexValid(value)) { _CatIndex = value; if (OnCategoryChanged != null) + { OnCategoryChanged(); + } } } } @@ -133,17 +140,25 @@ namespace Vocaluxe.Base public static void NextCategory() { if (Category == Categories.Count - 1) + { Category = 0; + } else + { Category++; + } } public static void PrevCategory() { if (Category == 0) + { Category = Categories.Count - 1; + } else + { Category--; + } } private static int _NumSongsWithCoverLoaded; @@ -164,20 +179,23 @@ namespace Vocaluxe.Base return _IsCatIndexValid(_CatIndex) ? Categories[_CatIndex].Name : ""; } - public static CSong GetSong(int songID) + public static CSong GetSong(int songId) { - return songID >= 0 && songID < _Songs.Count ? _Songs[songID] : null; + return songId >= 0 && songId < Songs.Count ? Songs[songId] : null; } - public static void AddPartySongSung(int songID) + public static void AddPartySongSung(int songId) { - foreach (CCategory category in Categories) + foreach (var category in Categories) { - foreach (CSongPointer song in category.Songs.Where(song => song.SongID == songID)) + foreach (var song in category.Songs.Where(song => song.SongId == songId)) { song.IsSung = true; if (category.GetNumSongsNotSung() == 0) + { ResetPartySongSung(_GetCategoryNumber(category)); + } + return; } } @@ -185,74 +203,95 @@ namespace Vocaluxe.Base public static void ResetPartySongSung() { - foreach (CSongPointer song in Sorter.SortedSongs) + foreach (var song in Sorter.SortedSongs) + { song.IsSung = false; + } } public static void ResetPartySongSung(int catIndex) { if (_IsCatIndexValid(catIndex)) { - foreach (CSongPointer song in Categories[catIndex].Songs) + foreach (var song in Categories[catIndex].Songs) + { song.IsSung = false; + } } } - public static int GetVisibleSongNumber(int songID) + public static int GetVisibleSongNumber(int songId) { - int i = -1; - foreach (CSong song in VisibleSongs) + var i = -1; + foreach (var song in VisibleSongs) { i++; - if (song.ID == songID) + if (song.Id == songId) + { return i; + } } + return i; } public static int GetRandomSong() { if (_SongsForRandom.Count == 0) + { UpdateRandomSongList(); + } if (_SongsForRandom.Count == 0) + { return -1; + } - CSong song = _SongsForRandom[CGame.Rand.Next(0, _SongsForRandom.Count - 1)]; + var song = _SongsForRandom[CGame.Rand.Next(0, _SongsForRandom.Count - 1)]; _SongsForRandom.Remove(song); - return GetVisibleSongNumber(song.ID); + return GetVisibleSongNumber(song.Id); } public static void UpdateRandomSongList() { _SongsForRandom.Clear(); - List visibleSongs = VisibleSongs.ToList(); + var visibleSongs = VisibleSongs.ToList(); if (visibleSongs.Count == 0) + { return; + } // Calc average sing-count - int totalCounts = visibleSongs.Sum(song => song.NumPlayedSession); - int averageCount = totalCounts / visibleSongs.Count; + var totalCounts = visibleSongs.Sum(song => song.NumPlayedSession); + var averageCount = totalCounts / visibleSongs.Count; - foreach (CSong song in visibleSongs) + foreach (var song in visibleSongs) { if (song.NumPlayedSession <= averageCount) + { _SongsForRandom.Add(song); + } } if (_SongsForRandom.Count == 0) + { _SongsForRandom.AddRange(visibleSongs); + } } public static int GetRandomCategory() { if (_CategoriesForRandom.Count == 0) + { UpdateRandomCategoryList(); + } if (_CategoriesForRandom.Count == 0) + { return -1; + } - CCategory category = _CategoriesForRandom[CGame.Rand.Next(0, _CategoriesForRandom.Count - 1)]; + var category = _CategoriesForRandom[CGame.Rand.Next(0, _CategoriesForRandom.Count - 1)]; _CategoriesForRandom.Remove(category); return _GetCategoryNumber(category); } @@ -265,17 +304,20 @@ namespace Vocaluxe.Base private static int _GetCategoryNumber(CCategory category) { - for (int i = 0; i < Categories.Count; i++) + for (var i = 0; i < Categories.Count; i++) { if (Categories[i] == category) + { return i; + } } + return -1; } public static ReadOnlyCollection AllSongs { - get { return _Songs.AsReadOnly(); } + get { return Songs.AsReadOnly(); } } public static ReadOnlyCollection VisibleSongs @@ -286,13 +328,16 @@ namespace Vocaluxe.Base if (_IsCatIndexValid(_CatIndex)) { // ReSharper disable LoopCanBeConvertedToQuery - foreach (CSongPointer sp in Categories[_CatIndex].Songs) + foreach (var sp in Categories[_CatIndex].Songs) // ReSharper restore LoopCanBeConvertedToQuery { if (!sp.IsSung) - songs.Add(_Songs[sp.SongID]); + { + songs.Add(Songs[sp.SongId]); + } } } + return songs.AsReadOnly(); } } @@ -310,7 +355,9 @@ namespace Vocaluxe.Base public static CCategory GetCategoryByIndex(int index) { if (!_IsCatIndexValid(index)) + { return null; + } return Categorizer.Categories[index]; } @@ -323,9 +370,12 @@ namespace Vocaluxe.Base public static CSong GetVisibleSongByIndex(int index) { if (index < 0) + { return null; - ReadOnlyCollection visSongs = VisibleSongs; - return (index < visSongs.Count) ? visSongs[index] : null; + } + + var visSongs = VisibleSongs; + return index < visSongs.Count ? visSongs[index] : null; } private static void _HandleCategoriesChanged(object sender, EventArgs args) @@ -333,9 +383,9 @@ namespace Vocaluxe.Base _CategoriesForRandom.Clear(); } - public static void Sort(ESongSorting sorting, EOffOn tabs, EOffOn ignoreArticles, String searchString, EDuetOptions duetOptions, int playlistID) + public static void Sort(ESongSorting sorting, EOffOn tabs, EOffOn ignoreArticles, String searchString, EDuetOptions duetOptions, int playlistId) { - Filter.SetOptions(searchString, duetOptions, playlistID); + Filter.SetOptions(searchString, duetOptions, playlistId); Sorter.SetOptions(sorting, ignoreArticles); Categorizer.Tabs = tabs; } @@ -345,22 +395,26 @@ namespace Vocaluxe.Base using (CBenchmark.Time("Load Songs")) { SongsLoaded = false; - _Songs.Clear(); + Songs.Clear(); _NumSongsLoaded = 0; IEnumerable files; - + using (CBenchmark.Time("List Songs")) { var fileSet = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (string path in CConfig.SongFolders) + foreach (var path in CConfig.SongFolders) { if (!Directory.Exists(path)) + { continue; + } - foreach (string file in CHelper.ListTextFiles(path, true, true)) + foreach (var file in CHelper.ListTextFiles(path, true, true)) + { fileSet.Add(file); + } } files = fileSet; @@ -377,9 +431,11 @@ namespace Vocaluxe.Base Parallel.ForEach(fileList, options, file => { - CSong song = CSong.LoadSong(file); + var song = CSong.LoadSong(file); if (song == null) + { return; + } if (song.LoadNotes()) { @@ -388,45 +444,50 @@ namespace Vocaluxe.Base } }); - int id = 0; - foreach (CSong song in bag.OrderBy(s => s.Folder).ThenBy(s => s.FileName)) + var id = 0; + foreach (var song in bag.OrderBy(s => s.Folder).ThenBy(s => s.FileName)) { - song.ID = id++; - _Songs.Add(song); + song.Id = id++; + Songs.Add(song); } } } - - using (CBenchmark.Time("Sorted Songs")) - { - Sorter.SongSorting = CConfig.Config.Game.SongSorting; - Sorter.IgnoreArticles = CConfig.Config.Game.IgnoreArticles; - Categorizer.Tabs = CConfig.Config.Game.Tabs; - Categorizer.ObjectChanged += _HandleCategoriesChanged; - } - Category = -1; - SongsLoaded = true; + using (CBenchmark.Time("Sorted Songs")) + { + Sorter.SongSorting = CConfig.Config.Game.SongSorting; + Sorter.IgnoreArticles = CConfig.Config.Game.IgnoreArticles; + Categorizer.Tabs = CConfig.Config.Game.Tabs; + Categorizer.ObjectChanged += _HandleCategoriesChanged; + } - switch (CConfig.Config.Theme.CoverLoading) - { - case ECoverLoading.TR_CONFIG_COVERLOADING_ATSTART: - _LoadCovers(); - break; - case ECoverLoading.TR_CONFIG_COVERLOADING_DYNAMIC: - _LoadCoversAsync(); - break; - } + Category = -1; + SongsLoaded = true; + + switch (CConfig.Config.Theme.CoverLoading) + { + case ECoverLoading.TR_CONFIG_COVERLOADING_ATSTART: + _LoadCovers(); + break; + case ECoverLoading.TR_CONFIG_COVERLOADING_DYNAMIC: + _LoadCoversAsync(); + break; + } } private static void _LoadCoversAsync() { if (!SongsLoaded || CoverLoaded) + { return; + } if (_CoverLoaderThread != null) + { return; - _CoverLoaderThread = new Thread(_LoadCovers) {Name = "CoverLoader", Priority = ThreadPriority.BelowNormal, IsBackground = true}; + } + + _CoverLoaderThread = new Thread(_LoadCovers) { Name = "CoverLoader", Priority = ThreadPriority.BelowNormal, IsBackground = true }; _CoverLoaderThread.Start(); } @@ -434,18 +495,20 @@ namespace Vocaluxe.Base { using (CBenchmark.Time("Loaded Covers")) { - int songCount = _Songs.Count; - AutoResetEvent ev = new AutoResetEvent(songCount == 0); + var songCount = Songs.Count; + var ev = new AutoResetEvent(songCount == 0); NumSongsWithCoverLoaded = 0; - foreach (CSong song in _Songs) + foreach (var song in Songs) { - CSong tmp = song; + var tmp = song; Task.Factory.StartNew(() => { tmp.LoadSmallCover(); if (Interlocked.Increment(ref _NumSongsWithCoverLoaded) >= songCount) + { ev.Set(); + } }); } @@ -455,4 +518,4 @@ namespace Vocaluxe.Base } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CSound.cs b/Vocaluxe/Base/CSound.cs index 391f6292..b23aded8 100644 --- a/Vocaluxe/Base/CSound.cs +++ b/Vocaluxe/Base/CSound.cs @@ -16,13 +16,13 @@ #endregion using System.IO; +using System.Threading; +using Vocaluxe.Lib.Sound; using Vocaluxe.Lib.Sound.Playback; using Vocaluxe.Lib.Sound.Playback.GstreamerSharp; using Vocaluxe.Lib.Sound.Playback.OpenAL; using Vocaluxe.Lib.Sound.Playback.PortAudio; using VocaluxeLib; -using System.Threading; -using Vocaluxe.Lib.Sound; namespace Vocaluxe.Base { @@ -45,7 +45,10 @@ namespace Vocaluxe.Base public static bool Init() { if (_Playback != null) + { return false; + } + switch (CConfig.Config.Sound.PlayBackLib) { case EPlaybackLib.PortAudio: @@ -64,6 +67,7 @@ namespace Vocaluxe.Base _Playback = new CPortAudioPlay(); break; } + return _Playback.Init(); } @@ -84,13 +88,18 @@ namespace Vocaluxe.Base public static void CloseAllStreams() { if (_Playback != null) + { _Playback.CloseAll(); + } } public static void Close() { if (_Playback != null) + { _Playback.Close(); + } + _Playback = null; } @@ -180,13 +189,12 @@ namespace Vocaluxe.Base _Playback.SetPosition(stream, position); } #endregion Stream Handling - #endregion Playback #region Sounds public static int PlaySound(ESounds sound, bool fade = true) { - string file = Path.Combine(CSettings.ProgramFolder, CSettings.FolderNameSounds); + var file = Path.Combine(CSettings.ProgramFolder, CSettings.FolderNameSounds); switch (sound) { case ESounds.T440: @@ -215,30 +223,40 @@ namespace Vocaluxe.Base } if (!File.Exists(file)) + { return -1; + } - int stream = Load(file, false, fade); + var stream = Load(file, false, fade); if (stream < 0) + { return -1; + } + Play(stream); if (fade) { - float length = -1f; - for (int i = 0; i < 5; i++) + var length = -1f; + for (var i = 0; i < 5; i++) { length = GetLength(stream); if (length >= 0f) + { break; + } + Thread.Sleep(1); } + if (length > 0f) { SetStreamVolume(stream, 0); Fade(stream, 100, length); } } + return stream; } #endregion Sounds } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/CUtility.cs b/Vocaluxe/Base/CUtility.cs index 8402169c..ff8825c8 100644 --- a/Vocaluxe/Base/CUtility.cs +++ b/Vocaluxe/Base/CUtility.cs @@ -27,18 +27,18 @@ namespace Vocaluxe.Base { private static readonly Stopwatch _Stopwatch = new Stopwatch(); private static float _Fps; - private static readonly double _NanosecPerTick = (1000.0 * 1000.0 * 1000.0) / Stopwatch.Frequency; + private static readonly double _NanosecPerTick = 1000.0 * 1000.0 * 1000.0 / Stopwatch.Frequency; // ReSharper disable MemberCanBePrivate.Global public static void Reset() - // ReSharper restore MemberCanBePrivate.Global + // ReSharper restore MemberCanBePrivate.Global { _Stopwatch.Reset(); } // ReSharper disable MemberCanBePrivate.Global public static void Start() - // ReSharper restore MemberCanBePrivate.Global + // ReSharper restore MemberCanBePrivate.Global { _Stopwatch.Start(); } @@ -58,20 +58,26 @@ namespace Vocaluxe.Base { if (_Stopwatch.IsRunning) { - long ticks = _Stopwatch.ElapsedTicks; + var ticks = _Stopwatch.ElapsedTicks; if (Stopwatch.IsHighResolution && ticks != 0) - return (float)((_NanosecPerTick * ticks) / (1000.0 * 1000.0)); + { + return (float)(_NanosecPerTick * ticks / (1000.0 * 1000.0)); + } + return _Stopwatch.ElapsedMilliseconds; } + return 0f; } public static void CalculateFPS() { - float ms = GetMilliseconds(); + var ms = GetMilliseconds(); if (ms > 0) + { _Fps = 1 / ms; + } } public static double GetFPS() @@ -111,15 +117,19 @@ namespace Vocaluxe.Base private void _Add(bool alt, bool shift, bool ctrl, bool pressed, char unicode, Keys key) { - bool keyRepeat = false; - if ((_Char == unicode) && _KeyPressed) - keyRepeat = true; - else if (_Keys == key) - keyRepeat = true; - - if (!_Timer.IsRunning || (_Timer.ElapsedMilliseconds > 75) || !keyRepeat) + var keyRepeat = false; + if (_Char == unicode && _KeyPressed) { - var pool = new SKeyEvent(ESender.Keyboard, alt, shift, ctrl, pressed && (unicode != Char.MinValue), unicode, key); + keyRepeat = true; + } + else if (_Keys == key) + { + keyRepeat = true; + } + + if (!_Timer.IsRunning || _Timer.ElapsedMilliseconds > 75 || !keyRepeat) + { + var pool = new SKeyEvent(ESender.Keyboard, alt, shift, ctrl, pressed && unicode != Char.MinValue, unicode, key); lock (_CopyLock) { @@ -142,7 +152,7 @@ namespace Vocaluxe.Base private void _CheckModifiers() { - Keys keys = Control.ModifierKeys; + var keys = Control.ModifierKeys; _ModShift = (keys & Keys.Shift) == Keys.Shift; _ModAlt = (keys & Keys.Alt) == Keys.Alt; @@ -153,9 +163,9 @@ namespace Vocaluxe.Base { _CheckModifiers(); - bool repeat = _Keys == e.KeyCode; + var repeat = _Keys == e.KeyCode; - if (!_Timer.IsRunning || (_Timer.ElapsedMilliseconds > 75) || !repeat) + if (!_Timer.IsRunning || _Timer.ElapsedMilliseconds > 75 || !repeat) { _Keys = e.KeyCode; _Add(_ModAlt, _ModShift, _ModCtrl, _KeyPressed, repeat ? _Char : Char.MinValue, _Keys); @@ -173,7 +183,7 @@ namespace Vocaluxe.Base // ReSharper disable UnusedParameter.Global public void KeyUp(KeyEventArgs e) - // ReSharper restore UnusedParameter.Global + // ReSharper restore UnusedParameter.Global { _CheckModifiers(); _KeyPressed = false; @@ -187,6 +197,7 @@ namespace Vocaluxe.Base _Del(0); return true; } + return false; } @@ -194,8 +205,11 @@ namespace Vocaluxe.Base { lock (_CopyLock) { - foreach (SKeyEvent e in _KeysPool) + foreach (var e in _KeysPool) + { _ActualPool.Add(e); + } + _KeysPool.Clear(); } } @@ -227,7 +241,10 @@ namespace Vocaluxe.Base _CheckModifiers(); x = (int)(x * (float)CSettings.RenderW * CConfig.Config.Graphics.NumScreens / CDraw.GetScreenWidth()); while (x > CSettings.RenderW) + { x -= CSettings.RenderW; + } + y = (int)(y * (float)CSettings.RenderH / CDraw.GetScreenHeight()); var pool = new SMouseEvent(ESender.Mouse, _Mod, x, y, lb, ld, rb, -wheel / 120, lbh, rbh, mb, mbh); @@ -245,15 +262,23 @@ namespace Vocaluxe.Base private void _CheckModifiers() { - Keys keys = Control.ModifierKeys; + var keys = Control.ModifierKeys; _Mod = EModifier.None; if ((keys & Keys.Shift) != 0) + { _Mod |= EModifier.Shift; + } + if ((keys & Keys.Alt) != 0) + { _Mod |= EModifier.Alt; + } + if ((keys & Keys.Control) != 0) + { _Mod |= EModifier.Ctrl; + } } public void MouseMove(MouseEventArgs e) @@ -268,8 +293,8 @@ namespace Vocaluxe.Base public void MouseDown(MouseEventArgs e) { - bool lb = e.Button == MouseButtons.Left; - bool ld = false; + var lb = e.Button == MouseButtons.Left; + var ld = false; if (lb) { if (_Timer.IsRunning && _Timer.ElapsedMilliseconds < 450) @@ -284,15 +309,17 @@ namespace Vocaluxe.Base } } else + { _Timer.Reset(); + } _Add(e.X, e.Y, lb, ld, e.Button == MouseButtons.Right, e.Delta, false, false, - e.Button == MouseButtons.Middle, false); + e.Button == MouseButtons.Middle, false); } // ReSharper disable UnusedParameter.Global public void MouseUp(MouseEventArgs e) - // ReSharper restore UnusedParameter.Global + // ReSharper restore UnusedParameter.Global { //CheckModifiers(); //Add(_ModALT, _ModSHIFT, _ModCTRL, e.X, e.Y, e.Button == MouseButtons.Left, e.Button == MouseButtons.Right, e.Delta); @@ -301,7 +328,10 @@ namespace Vocaluxe.Base public bool PollEvent(ref SMouseEvent mouseEvent) { if (_CurrentPool.Count <= 0) + { return false; + } + mouseEvent = _CurrentPool[0]; _Del(0); return true; @@ -311,8 +341,11 @@ namespace Vocaluxe.Base { lock (_CopyLock) { - foreach (SMouseEvent e in _EventsPool) + foreach (var e in _EventsPool) + { _CurrentPool.Add(e); + } + _EventsPool.Clear(); } } diff --git a/Vocaluxe/Base/CVideo.cs b/Vocaluxe/Base/CVideo.cs index d9af124b..527e653f 100644 --- a/Vocaluxe/Base/CVideo.cs +++ b/Vocaluxe/Base/CVideo.cs @@ -30,7 +30,10 @@ namespace Vocaluxe.Base public static bool Init() { if (_VideoDecoder != null) + { return false; + } + switch (CConfig.Config.Video.VideoDecoder) { case EVideoDecoder.FFmpeg: @@ -66,6 +69,7 @@ namespace Vocaluxe.Base { throw new NotSupportedException("_VideoDecoder is null (already closed?)"); } + return _VideoDecoder.Load(videoFileName); } @@ -73,7 +77,9 @@ namespace Vocaluxe.Base { //Check for null because the videostreams may close themselves on destroy (GC) if (_VideoDecoder != null) + { _VideoDecoder.Close(ref stream); + } } public static float GetLength(CVideoStream stream) @@ -82,6 +88,7 @@ namespace Vocaluxe.Base { throw new ArgumentException("stream is null"); } + if (_VideoDecoder == null) { throw new NotSupportedException("_VideoDecoder is null (already closed?)"); @@ -96,6 +103,7 @@ namespace Vocaluxe.Base { throw new ArgumentException("stream is null"); } + if (_VideoDecoder == null) { throw new NotSupportedException("_VideoDecoder is null (already closed?)"); @@ -110,6 +118,7 @@ namespace Vocaluxe.Base { throw new ArgumentException("stream is null"); } + if (_VideoDecoder == null) { throw new NotSupportedException("_VideoDecoder is null (already closed?)"); @@ -124,6 +133,7 @@ namespace Vocaluxe.Base { throw new ArgumentException("stream is null"); } + if (_VideoDecoder == null) { throw new NotSupportedException("_VideoDecoder is null (already closed?)"); @@ -138,6 +148,7 @@ namespace Vocaluxe.Base { throw new ArgumentException("stream is null"); } + if (_VideoDecoder == null) { throw new NotSupportedException("_VideoDecoder is null (already closed?)"); @@ -152,6 +163,7 @@ namespace Vocaluxe.Base { throw new ArgumentException("stream is null"); } + if (_VideoDecoder == null) { throw new NotSupportedException("_VideoDecoder is null (already closed?)"); @@ -166,6 +178,7 @@ namespace Vocaluxe.Base { throw new ArgumentException("stream is null"); } + if (_VideoDecoder == null) { throw new NotSupportedException("_VideoDecoder is null (already closed?)"); @@ -184,7 +197,6 @@ namespace Vocaluxe.Base _VideoDecoder.Update(); } #endregion Interface - #endregion VideoDecoder } } \ No newline at end of file diff --git a/Vocaluxe/Base/CVideoPlayer.cs b/Vocaluxe/Base/CVideoPlayer.cs index 1f451396..b721843c 100644 --- a/Vocaluxe/Base/CVideoPlayer.cs +++ b/Vocaluxe/Base/CVideoPlayer.cs @@ -45,6 +45,7 @@ namespace Vocaluxe.Base { return; } + _Loaded = true; CVideo.Pause(_VideoStream); } @@ -57,6 +58,7 @@ namespace Vocaluxe.Base { return; } + //CVideo.VdSkip(_VideoStream, 0f, 0f); _VideoTimer.Start(); CVideo.Resume(_VideoStream); @@ -68,6 +70,7 @@ namespace Vocaluxe.Base { CVideo.Pause(_VideoStream); } + _VideoTimer.Stop(); } @@ -77,6 +80,7 @@ namespace Vocaluxe.Base { return; } + CVideo.Resume(_VideoStream); _VideoTimer.Start(); } @@ -90,13 +94,16 @@ namespace Vocaluxe.Base if (!_Finished) { - float videoTime = _VideoTimer.ElapsedMilliseconds / 1000f; + var videoTime = _VideoTimer.ElapsedMilliseconds / 1000f; _Finished = CVideo.Finished(_VideoStream); CVideo.GetFrame(_VideoStream, videoTime); } + if (_VideoStream.Texture == null) + { return; + } CDraw.DrawTexture(_VideoStream.Texture, CSettings.RenderRect, EAspect.Crop); } @@ -107,17 +114,24 @@ namespace Vocaluxe.Base { return; } - bool paused = _VideoTimer.IsRunning; + + var paused = _VideoTimer.IsRunning; if (paused) + { CVideo.Resume(_VideoStream); - float videoTime = 0f; + } + + var videoTime = 0f; while (_VideoStream.Texture == null && videoTime < 1f) { CVideo.GetFrame(_VideoStream, 0); videoTime += 0.05f; } + if (paused) + { CVideo.Pause(_VideoStream); + } } public void Close() @@ -126,6 +140,7 @@ namespace Vocaluxe.Base { CVideo.Close(ref _VideoStream); } + _Loaded = false; _Finished = false; _VideoTimer.Reset(); diff --git a/Vocaluxe/Base/CWebcam.cs b/Vocaluxe/Base/CWebcam.cs index a73e1fd0..04fd4706 100644 --- a/Vocaluxe/Base/CWebcam.cs +++ b/Vocaluxe/Base/CWebcam.cs @@ -29,7 +29,10 @@ namespace Vocaluxe.Base public static bool Init() { if (_Webcam != null) + { return false; + } + switch (CConfig.Config.Video.WebcamLib) { case EWebcamLib.AForgeNet: @@ -40,8 +43,12 @@ namespace Vocaluxe.Base _Webcam = new CAForgeNet(); break; } + if (!_Webcam.Init()) + { return false; + } + _Webcam.Select(CConfig.Config.Video.WebcamConfig.HasValue ? CConfig.Config.Video.WebcamConfig.Value : new SWebcamConfig()); CConfig.Config.Video.WebcamConfig = _Webcam.GetConfig(); @@ -52,7 +59,10 @@ namespace Vocaluxe.Base public static void Close() { if (_Webcam == null) + { return; + } + _Webcam.Close(); _Webcam = null; } @@ -70,19 +80,25 @@ namespace Vocaluxe.Base public static void Pause() { if (_Webcam != null) + { _Webcam.Pause(); + } } public static void Start() { if (_Webcam != null) + { _Webcam.Start(); + } } public static void Stop() { if (_Webcam != null) + { _Webcam.Stop(); + } } public static bool Select(SWebcamConfig c) @@ -93,7 +109,9 @@ namespace Vocaluxe.Base public static void DeSelect() { if (_Webcam != null) + { _Webcam.DeSelect(); + } } public static SWebcamDevice[] GetDevices() @@ -103,12 +121,12 @@ namespace Vocaluxe.Base public static bool IsDeviceAvailable() { - return (_Webcam != null) && _Webcam.IsDeviceAvailable(); + return _Webcam != null && _Webcam.IsDeviceAvailable(); } public static bool IsCapturing() { - return (_Webcam != null) && _Webcam.IsCapturing(); + return _Webcam != null && _Webcam.IsCapturing(); } } } \ No newline at end of file diff --git a/Vocaluxe/Base/Fonts/CFontStyle.cs b/Vocaluxe/Base/Fonts/CFontStyle.cs index 448f4b13..d8631d83 100644 --- a/Vocaluxe/Base/Fonts/CFontStyle.cs +++ b/Vocaluxe/Base/Fonts/CFontStyle.cs @@ -79,6 +79,7 @@ namespace Vocaluxe.Base.Fonts case EStyle.BoldItalic: return FontStyle.Bold | FontStyle.Italic; } + throw new ArgumentException("Invalid style: " + _Style); } @@ -97,6 +98,7 @@ namespace Vocaluxe.Base.Fonts CLog.Error("Error opening font file " + _FilePath + ": " + e.Message); } } + return new Font(_Family, height, _GetSystemFontStyle(), GraphicsUnit.Pixel); } @@ -139,23 +141,28 @@ namespace Vocaluxe.Base.Fonts CGlyph glyph; if (!_Glyphs.TryGetValue(chr, out glyph)) { - float maxHeight = (height < 0 || _MaxGlyphHeight + 50 >= height) ? _MaxGlyphHeight : (float)Math.Round(height / 50) * 50; + var maxHeight = height < 0 || _MaxGlyphHeight + 50 >= height ? _MaxGlyphHeight : (float)Math.Round(height / 50) * 50; glyph = new CGlyph(chr, this, maxHeight); _Glyphs.Add(chr, glyph); } + if (glyph.MaxHeight + 50 < height) { glyph.UnloadTexture(); glyph = new CGlyph(chr, this, (float)Math.Round(height / 50) * 50); _Glyphs[chr] = glyph; } + return glyph; } private void _UnloadGlyphs() { - foreach (CGlyph glyph in _Glyphs.Values) + foreach (var glyph in _Glyphs.Values) + { glyph.UnloadTexture(); + } + _Glyphs.Clear(); } @@ -170,9 +177,11 @@ namespace Vocaluxe.Base.Fonts _Fonts.Dispose(); _Fonts = null; } + _UnloadGlyphs(); _Disposed = true; } + GC.SuppressFinalize(this); } } diff --git a/Vocaluxe/Base/Fonts/CFonts.cs b/Vocaluxe/Base/Fonts/CFonts.cs index 545b6c7f..1702c363 100644 --- a/Vocaluxe/Base/Fonts/CFonts.cs +++ b/Vocaluxe/Base/Fonts/CFonts.cs @@ -34,20 +34,26 @@ namespace Vocaluxe.Base.Fonts private static readonly List _FontFamilies = new List(); private static readonly List _LoggedMissingFonts = new List(); - public static int PartyModeID { get; set; } + public static int PartyModeId { get; set; } public static bool Init() { if (_IsInitialized) + { return false; - PartyModeID = -1; + } + + PartyModeId = -1; return _LoadDefaultFonts(); } public static void Close() { - foreach (SFontFamily font in _FontFamilies) + foreach (var font in _FontFamilies) + { font.Dispose(); + } + _FontFamilies.Clear(); _IsInitialized = false; } @@ -78,12 +84,14 @@ namespace Vocaluxe.Base.Fonts public static void DrawText(string text, CFont font, float x, float y, float z, SColorF color, bool allMonitors = true) { if (font.Height <= 0f || text == "") + { return; + } - CFontStyle fontStyle = _GetFontStyle(font); + var fontStyle = _GetFontStyle(font); - float dx = x; - foreach (char chr in text) + var dx = x; + foreach (var chr in text) { fontStyle.DrawGlyph(chr, font.Height, dx, y, z, color, allMonitors); dx += fontStyle.GetWidth(chr, font.Height); @@ -93,12 +101,14 @@ namespace Vocaluxe.Base.Fonts public static void DrawTextReflection(string text, CFont font, float x, float y, float z, SColorF color, float rspace, float rheight) { if (font.Height <= 0f || text == "") + { return; + } - CFontStyle fontStyle = _GetFontStyle(font); + var fontStyle = _GetFontStyle(font); - float dx = x; - foreach (char chr in text) + var dx = x; + foreach (var chr in text) { fontStyle.DrawGlyphReflection(chr, font.Height, dx, y, z, color, rspace, rheight); dx += fontStyle.GetWidth(chr, font.Height); @@ -108,35 +118,46 @@ namespace Vocaluxe.Base.Fonts public static void DrawText(string text, CFont font, float x, float y, float z, SColorF color, float begin, float end) { if (font.Height <= 0f || text == "") - return; - - float w = GetTextWidth(text, font); - if (w <= 0f) - return; - - float xStart = x + w * begin; - float xEnd = x + w * end; - float xCur = x; - - CFontStyle fontStyle = _GetFontStyle(font); - - foreach (char chr in text) { - float w2 = fontStyle.GetWidth(chr, font.Height); - float b = (xStart - xCur) / w2; + return; + } + + var w = GetTextWidth(text, font); + if (w <= 0f) + { + return; + } + + var xStart = x + w * begin; + var xEnd = x + w * end; + var xCur = x; + + var fontStyle = _GetFontStyle(font); + + foreach (var chr in text) + { + var w2 = fontStyle.GetWidth(chr, font.Height); + var b = (xStart - xCur) / w2; if (b < 1f) { if (b < 0f) + { b = 0f; - float e = (xEnd - xCur) / w2; + } + + var e = (xEnd - xCur) / w2; if (e > 0f) { if (e > 1f) + { e = 1f; + } + fontStyle.DrawGlyph(chr, font.Height, xCur, y, z, color, b, e); } } + xCur += w2; } } @@ -169,7 +190,7 @@ namespace Vocaluxe.Base.Fonts private static CFontStyle _GetFontStyle(CFont font) { - int index = _GetFontIndex(font.Name); + var index = _GetFontIndex(font.Name); switch (font.Style) { @@ -182,18 +203,19 @@ namespace Vocaluxe.Base.Fonts case EStyle.BoldItalic: return _FontFamilies[index].BoldItalic; } + throw new ArgumentException("Invalid Style: " + font.Style); } public static float GetTextWidth(string text, CFont font) { - CFontStyle fontStyle = _GetFontStyle(font); + var fontStyle = _GetFontStyle(font); return text.Sum(chr => fontStyle.GetWidth(chr, font.Height)); } public static float GetTextHeight(string text, CFont font) { - CFontStyle fontStyle = _GetFontStyle(font); + var fontStyle = _GetFontStyle(font); return text == "" ? 0 : text.Select(chr => fontStyle.GetHeight(chr, font.Height)).Max(); } @@ -201,16 +223,25 @@ namespace Vocaluxe.Base.Fonts { if (fontName != "") { - int index = _GetPartyFontIndex(fontName, PartyModeID); + var index = _GetPartyFontIndex(fontName, PartyModeId); if (index < 0) + { index = _GetThemeFontIndex(fontName, CConfig.Config.Theme.Theme); + } + if (index >= 0) + { return index; - for (int i = 0; i < _FontFamilies.Count; i++) + } + + for (var i = 0; i < _FontFamilies.Count; i++) { if (_FontFamilies[i].Name == fontName) + { return i; + } } + if (!_LoggedMissingFonts.Contains(fontName)) { _LoggedMissingFonts.Add(fontName); @@ -218,10 +249,14 @@ namespace Vocaluxe.Base.Fonts } } else + { CLog.Error("Empty fontName requested"); + } if (_FontFamilies.Count == 0) + { CLog.Fatal("No fonts found!"); + } return 0; } @@ -230,23 +265,27 @@ namespace Vocaluxe.Base.Fonts { Debug.Assert(fontName != "" && themeName != ""); - for (int i = 0; i < _FontFamilies.Count; i++) + for (var i = 0; i < _FontFamilies.Count; i++) { if (_FontFamilies[i].Name == fontName && _FontFamilies[i].ThemeName == themeName) + { return i; + } } return -1; } - private static int _GetPartyFontIndex(string fontName, int partyModeID) + private static int _GetPartyFontIndex(string fontName, int partyModeId) { Debug.Assert(fontName != ""); - for (int i = 0; i < _FontFamilies.Count; i++) + for (var i = 0; i < _FontFamilies.Count; i++) { - if (_FontFamilies[i].PartyModeID == partyModeID && _FontFamilies[i].Name == fontName) + if (_FontFamilies[i].PartyModeId == partyModeId && _FontFamilies[i].Name == fontName) + { return i; + } } return -1; @@ -279,8 +318,11 @@ namespace Vocaluxe.Base.Fonts public static bool LoadThemeFonts(IEnumerable fontFamilies, string fontFolder, string themeName, int partyModeId) { if (fontFamilies == null) + { return true; - foreach (SFontFamily fontFamily in fontFamilies) + } + + foreach (var fontFamily in fontFamilies) { if (!_LoadFont(fontFamily, fontFolder, themeName, partyModeId)) { @@ -288,7 +330,7 @@ namespace Vocaluxe.Base.Fonts return false; } } - + using (CBenchmark.Time("Build Glyphs")) { _BuildGlyphs(); @@ -300,19 +342,19 @@ namespace Vocaluxe.Base.Fonts private static bool _LoadFont(SFontFamily fontFamily, string fontFolder, string themeName, int partyModeId) { fontFamily.ThemeName = themeName; - fontFamily.PartyModeID = partyModeId; + fontFamily.PartyModeId = partyModeId; fontFamily.Normal = new CFontStyle(Path.Combine(fontFolder, fontFamily.Folder, fontFamily.FileNormal), EStyle.Normal, fontFamily.Outline, fontFamily.OutlineColor); fontFamily.Italic = new CFontStyle(Path.Combine(fontFolder, fontFamily.Folder, fontFamily.FileItalic), EStyle.Italic, fontFamily.Outline, fontFamily.OutlineColor); fontFamily.Bold = new CFontStyle(Path.Combine(fontFolder, fontFamily.Folder, fontFamily.FileBold), EStyle.Bold, fontFamily.Outline, fontFamily.OutlineColor); fontFamily.BoldItalic = new CFontStyle(Path.Combine(fontFolder, fontFamily.Folder, fontFamily.FileBoldItalic), EStyle.BoldItalic, fontFamily.Outline, - fontFamily.OutlineColor); + fontFamily.OutlineColor); _FontFamilies.Add(fontFamily); return true; } public static void UnloadThemeFonts(string themeName) { - int index = 0; + var index = 0; while (index < _FontFamilies.Count) { if (_FontFamilies[index].ThemeName == themeName) @@ -321,23 +363,27 @@ namespace Vocaluxe.Base.Fonts _FontFamilies.RemoveAt(index); } else + { index++; + } } } - public static void UnloadPartyModeFonts(int partyModeID) + public static void UnloadPartyModeFonts(int partyModeId) { - Debug.Assert(partyModeID >= 0); - int index = 0; + Debug.Assert(partyModeId >= 0); + var index = 0; while (index < _FontFamilies.Count) { - if (_FontFamilies[index].PartyModeID == partyModeID) + if (_FontFamilies[index].PartyModeId == partyModeId) { _FontFamilies[index].Dispose(); _FontFamilies.RemoveAt(index); } else + { index++; + } } } @@ -345,9 +391,9 @@ namespace Vocaluxe.Base.Fonts { const string text = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; - foreach (SFontFamily fontFamily in _FontFamilies) + foreach (var fontFamily in _FontFamilies) { - foreach (char chr in text) + foreach (var chr in text) { fontFamily.Normal.GetOrAddGlyph(chr, -1); fontFamily.Bold.GetOrAddGlyph(chr, -1); diff --git a/Vocaluxe/Base/Fonts/CGlyph.cs b/Vocaluxe/Base/Fonts/CGlyph.cs index acfa367e..e3a54da2 100644 --- a/Vocaluxe/Base/Fonts/CGlyph.cs +++ b/Vocaluxe/Base/Fonts/CGlyph.cs @@ -39,21 +39,21 @@ namespace Vocaluxe.Base.Fonts public CGlyph(char chr, CFontStyle fontStyle, float maxHeight) { MaxHeight = maxHeight; - float outlineSize = fontStyle.Outline * maxHeight; - string chrString = chr.ToString(); + var outlineSize = fontStyle.Outline * maxHeight; + var chrString = chr.ToString(); - Font fo = fontStyle.GetSystemFont(maxHeight); + var fo = fontStyle.GetSystemFont(maxHeight); SizeF fullSize; Size bmpSize; - using (Graphics g = Graphics.FromHwnd(IntPtr.Zero)) + using (var g = Graphics.FromHwnd(IntPtr.Zero)) { fullSize = g.MeasureString(chrString, fo); if (chr != ' ') { //Gets exact height and width for drawing more than 1 char. But width is to small to draw char on bitmap as e.g. italic chars will get cropped //See https://stackoverflow.com/questions/11708621/how-to-measure-width-of-a-string-precisely - StringFormat format = StringFormat.GenericTypographic; - RectangleF rect = new RectangleF(0, 0, 2000, 2000); + var format = StringFormat.GenericTypographic; + var rect = new RectangleF(0, 0, 2000, 2000); CharacterRange[] ranges = { new CharacterRange(0, chrString.Length) }; format.SetMeasurableCharacterRanges(ranges); _BoundingBox = g.MeasureCharacterRanges(chrString, fo, rect, format)[0].GetBounds(g).Size; @@ -61,7 +61,10 @@ namespace Vocaluxe.Base.Fonts // ReSharper disable CompareOfFloatsByEqualityOperator if (_BoundingBox.Height == 0) // ReSharper restore CompareOfFloatsByEqualityOperator + { _BoundingBox.Height = fullSize.Height; + } + _BoundingBox.Width += outlineSize / 2; _BoundingBox.Height += outlineSize; fullSize.Width += outlineSize; @@ -74,8 +77,9 @@ namespace Vocaluxe.Base.Fonts bmpSize = new Size(1, 1); } } + using (var bmp = new Bitmap(bmpSize.Width, bmpSize.Height, PixelFormat.Format32bppArgb)) - using (Graphics g = Graphics.FromImage(bmp)) + using (var g = Graphics.FromImage(bmp)) { g.Clear(Color.Transparent); @@ -95,7 +99,7 @@ namespace Vocaluxe.Base.Fonts using (var path = new GraphicsPath()) { //Have to use size in em not pixels! - float emSize = fo.Size * fo.FontFamily.GetCellAscent(fo.Style) / fo.FontFamily.GetEmHeight(fo.Style); + var emSize = fo.Size * fo.FontFamily.GetCellAscent(fo.Style) / fo.FontFamily.GetEmHeight(fo.Style); path.AddString(chrString, fo.FontFamily, (int)fo.Style, emSize, point, new StringFormat()); using (var pen = new Pen(fontStyle.OutlineColor.AsColor(), outlineSize)) @@ -105,10 +109,11 @@ namespace Vocaluxe.Base.Fonts g.FillPath(Brushes.White, path); } } + _DrawBounding = _GetRealBounds(bmp); - using (Bitmap bmpCropped = bmp.Clone(_DrawBounding, PixelFormat.Format32bppArgb)) + using (var bmpCropped = bmp.Clone(_DrawBounding, PixelFormat.Format32bppArgb)) { - float dx = (fullSize.Width - _BoundingBox.Width - 1) / 2; + var dx = (fullSize.Width - _BoundingBox.Width - 1) / 2; _DrawBounding.X -= dx; _Texture = CDraw.AddTexture(bmpCropped); /*_DrawBounding.X *= _Texture.Width / _DrawBounding.Width; @@ -152,27 +157,27 @@ namespace Vocaluxe.Base.Fonts public void GetTextureAndRect(float fontHeight, float x, float y, float z, out CTextureRef texture, out SRectF rect) { texture = _Texture; - float factor = _GetFactor(fontHeight); + var factor = _GetFactor(fontHeight); x += _DrawBounding.X * factor; y += _DrawBounding.Y * factor; - float h = _DrawBounding.Height * factor; - float w = _DrawBounding.Width * factor; + var h = _DrawBounding.Height * factor; + var w = _DrawBounding.Width * factor; rect = new SRectF(x, y, w, h, z); } private static Rectangle _GetRealBounds(Bitmap bmp) { int minX = 0, maxX = bmp.Width - 1, minY = 0; - BitmapData bmpData = bmp.LockBits(bmp.GetRect(), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); - int values = bmpData.Width * bmp.Height; + var bmpData = bmp.LockBits(bmp.GetRect(), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); + var values = bmpData.Width * bmp.Height; var rgbValues = new Int32[values]; Marshal.Copy(bmpData.Scan0, rgbValues, 0, values); - int index = 0; - bool found = false; + var index = 0; + var found = false; //find from top - for (int y = 0; y < bmp.Height && !found; y++) + for (var y = 0; y < bmp.Height && !found; y++) { - for (int x = 0; x < bmp.Width; x++) + for (var x = 0; x < bmp.Width; x++) { if (rgbValues[index] != 0) { @@ -182,15 +187,17 @@ namespace Vocaluxe.Base.Fonts found = true; break; } + index++; } } + found = false; //find left - for (int x = 0; x < minX && !found; x++) + for (var x = 0; x < minX && !found; x++) { index = x + minY * bmp.Width; - for (int y = minY; y < bmp.Height; y++) + for (var y = minY; y < bmp.Height; y++) { if (rgbValues[index] != 0) { @@ -198,15 +205,17 @@ namespace Vocaluxe.Base.Fonts minX = x; break; } + index += bmp.Width; } } + found = false; //find right - for (int x = bmp.Width - 1; x > maxX && !found; x--) + for (var x = bmp.Width - 1; x > maxX && !found; x--) { index = x + minY * bmp.Width; - for (int y = minY; y < bmp.Height; y++) + for (var y = minY; y < bmp.Height; y++) { if (rgbValues[index] != 0) { @@ -214,6 +223,7 @@ namespace Vocaluxe.Base.Fonts maxX = x; break; } + index += bmp.Width; } } @@ -222,15 +232,23 @@ namespace Vocaluxe.Base.Fonts const int d = 4; minX = minX - d; if (minX < 0) + { minX = 0; + } + minY = minY - d; if (minY < 0) + { minY = 0; + } + maxX = maxX + d; if (maxX > bmp.Width) + { maxX = bmp.Width; + } return new Rectangle(minX, minY, maxX - minX, bmp.Height - minY); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/Server/CVocaluxeServer.cs b/Vocaluxe/Base/Server/CVocaluxeServer.cs index 3ab9727b..fa304cc7 100644 --- a/Vocaluxe/Base/Server/CVocaluxeServer.cs +++ b/Vocaluxe/Base/Server/CVocaluxeServer.cs @@ -22,7 +22,6 @@ using System.Drawing; using System.IO; using System.Linq; using System.Net; -using System.Reflection; using System.Security.Cryptography; using System.ServiceModel; using System.ServiceModel.Web; @@ -52,34 +51,32 @@ namespace Vocaluxe.Base.Server return "App controller"; } - public override void Connect() {} + public override void Connect() { } - public override void Disconnect() {} + public override void Disconnect() { } public override bool IsConnected() { return true; } - public override void SetRumble(float duration) {} + public override void SetRumble(float duration) { } } public static readonly CControllerFramework Controller = new CServerController(); - #region server control - public static void Init() { - int port = CConfig.Config.Server.ServerPort; - bool encrypted = CConfig.Config.Server.ServerEncryption == EOffOn.TR_CONFIG_ON; - string hostname = Dns.GetHostName(); - string protocol = (encrypted) ? "https" : "http"; + var port = CConfig.Config.Server.ServerPort; + var encrypted = CConfig.Config.Server.ServerEncryption == EOffOn.TR_CONFIG_ON; + var hostname = Dns.GetHostName(); + var protocol = encrypted ? "https" : "http"; _BaseAddress = new Uri(protocol + "://" + hostname + ":" + port + "/"); _Encrypted = encrypted; _Host = new WebServiceHost(typeof(CWebservice), _BaseAddress); - WebHttpBinding wb = new WebHttpBinding + var wb = new WebHttpBinding { MaxReceivedMessageSize = 10485760, MaxBufferSize = 10485760, @@ -91,6 +88,7 @@ namespace Vocaluxe.Base.Server wb.Security.Mode = WebHttpSecurityMode.Transport; wb.Security.Transport = new HttpTransportSecurity { ClientCredentialType = HttpClientCredentialType.None }; } + _Host.AddServiceEndpoint(typeof(ICWebservice), wb, ""); Start(); @@ -125,7 +123,9 @@ namespace Vocaluxe.Base.Server } } else + { _Host.Abort(); + } } } } @@ -148,8 +148,7 @@ namespace Vocaluxe.Base.Server private static void _RegisterUrlAndCert(int port, bool reserve) { #if WIN - - ProcessStartInfo info = new ProcessStartInfo + var info = new ProcessStartInfo { FileName = "VocaluxeServerConfig.exe", WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory, @@ -160,11 +159,14 @@ namespace Vocaluxe.Base.Server }; try { - using (Process p = Process.Start(info)) + using (var p = Process.Start(info)) { p.WaitForExit(); if (p.ExitCode != 0) + { MessageBox.Show("Registering the Server failed (Code " + p.ExitCode + ")!\r\nThe Server might not work correctly."); + } + p.Close(); } } @@ -173,8 +175,7 @@ namespace Vocaluxe.Base.Server MessageBox.Show("Registering the Server failed (" + e + ")!\r\nThe Server might not work correctly."); } #else - - //Required? + //Required? #endif } @@ -187,28 +188,27 @@ namespace Vocaluxe.Base.Server public static bool IsServerRunning() { if (_Host == null) + { return false; + } return _Host.State == CommunicationState.Opened; } - #endregion #region task control - public static void ProcessServerTasks() { //Serial processing - one by one while (_ServerTaskQueue.Count > 0) { //Get a task from the queue - Task task = _ServerTaskQueue.Dequeue(); + var task = _ServerTaskQueue.Dequeue(); //Start the task task.RunSynchronously(TaskScheduler.FromCurrentSynchronizationContext()); } } - public static TReturnType DoTask(Func action) { var task = new Task(action); @@ -225,7 +225,8 @@ namespace Vocaluxe.Base.Server return task.Result; } - public static TReturnType DoTask(Func action, TParameterType1 parameter1, TParameterType2 parameter2) + public static TReturnType DoTask(Func action, TParameterType1 parameter1, + TParameterType2 parameter2) { var task = new Task(() => action(parameter1, parameter2)); _ServerTaskQueue.Enqueue(task); @@ -233,7 +234,8 @@ namespace Vocaluxe.Base.Server return task.Result; } - public static TReturnType DoTask(Func action, TParameterType1 parameter1, TParameterType2 parameter2, TParameterType3 parameter3) + public static TReturnType DoTask( + Func action, TParameterType1 parameter1, TParameterType2 parameter2, TParameterType3 parameter3) { var task = new Task(() => action(parameter1, parameter2, parameter3)); _ServerTaskQueue.Enqueue(task); @@ -241,7 +243,9 @@ namespace Vocaluxe.Base.Server return task.Result; } - public static TReturnType DoTask(Func action, TParameterType1 parameter1, TParameterType2 parameter2, TParameterType3 parameter3, TParameterType4 parameter4) + public static TReturnType DoTask( + Func action, TParameterType1 parameter1, TParameterType2 parameter2, + TParameterType3 parameter3, TParameterType4 parameter4) { var task = new Task(() => action(parameter1, parameter2, parameter3, parameter4)); _ServerTaskQueue.Enqueue(task); @@ -249,7 +253,6 @@ namespace Vocaluxe.Base.Server return task.Result; } - public static void DoTaskWithoutReturn(Action action) { var task = new Task(action); @@ -264,33 +267,36 @@ namespace Vocaluxe.Base.Server task.Wait(); //wait until the task is completed } - public static void DoTaskWithoutReturn(Action action, TParameterType1 parameter1, TParameterType2 parameter2) + public static void DoTaskWithoutReturn(Action action, TParameterType1 parameter1, + TParameterType2 parameter2) { var task = new Task(() => action(parameter1, parameter2)); _ServerTaskQueue.Enqueue(task); task.Wait(); //wait until the task is completed } - public static void DoTaskWithoutReturn(Action action, TParameterType1 parameter1, TParameterType2 parameter2, TParameterType3 parameter3) + public static void DoTaskWithoutReturn(Action action, + TParameterType1 parameter1, TParameterType2 parameter2, TParameterType3 parameter3) { var task = new Task(() => action(parameter1, parameter2, parameter3)); _ServerTaskQueue.Enqueue(task); task.Wait(); //wait until the task is completed } - public static void DoTaskWithoutReturn(Action action, TParameterType1 parameter1, TParameterType2 parameter2, TParameterType3 parameter3, TParameterType4 parameter4) + public static void DoTaskWithoutReturn( + Action action, TParameterType1 parameter1, TParameterType2 parameter2, TParameterType3 parameter3, + TParameterType4 parameter4) { var task = new Task(() => action(parameter1, parameter2, parameter3, parameter4)); _ServerTaskQueue.Enqueue(task); task.Wait(); //wait until the task is completed } - #endregion public static bool SendKeyEvent(string key) { - bool result = false; - string lowerKey = key.ToLower(); + var result = false; + var lowerKey = key.ToLower(); if (!string.IsNullOrEmpty(lowerKey)) { @@ -331,18 +337,19 @@ namespace Vocaluxe.Base.Server default: if (lowerKey.StartsWith("f")) { - string numberString = lowerKey.Substring(1); + var numberString = lowerKey.Substring(1); int number; Keys fKey; if (Int32.TryParse(numberString, out number) && number >= 1 - && number <= 12 - && Enum.TryParse("F" + number, true, out fKey)) + && number <= 12 + && Enum.TryParse("F" + number, true, out fKey)) { Controller.AddKeyEvent(new SKeyEvent(ESender.Keyboard, false, false, false, false, Char.MinValue, fKey)); result = true; } } + break; } } @@ -352,15 +359,15 @@ namespace Vocaluxe.Base.Server public static bool SendKeyStringEvent(string keyString, bool isShiftPressed, bool isAltPressed, bool isCtrlPressed) { - bool result = false; + var result = false; - foreach (char key in keyString) + foreach (var key in keyString) { Controller.AddKeyEvent(new SKeyEvent(ESender.Keyboard, isAltPressed, - Char.IsUpper(key) || isShiftPressed, - isCtrlPressed, true, - isShiftPressed ? Char.ToUpper(key) : key, - _ParseKeys(key))); + Char.IsUpper(key) || isShiftPressed, + isCtrlPressed, true, + isShiftPressed ? Char.ToUpper(key) : key, + _ParseKeys(key))); result = true; } @@ -390,42 +397,47 @@ namespace Vocaluxe.Base.Server #region profile public static SProfileData GetProfileData(Guid profileId, bool isReadonly) { - CProfile profile = CProfiles.GetProfile(profileId); + var profile = CProfiles.GetProfile(profileId); if (profile == null) + { return new SProfileData(); + } + return _CreateProfileData(profile, isReadonly); } public static bool SendProfileData(SProfileData profile) { CProfile newProfile; - CProfile existingProfile = CProfiles.GetProfile(profile.ProfileId); + var existingProfile = CProfiles.GetProfile(profile.ProfileId); if (existingProfile != null) { newProfile = new CProfile - { - ID = existingProfile.ID, - FilePath = existingProfile.FilePath, - Active = existingProfile.Active, - Avatar = existingProfile.Avatar, - Difficulty = existingProfile.Difficulty, - UserRole = existingProfile.UserRole, - PlayerName = existingProfile.PlayerName - }; + { + Id = existingProfile.Id, + FilePath = existingProfile.FilePath, + Active = existingProfile.Active, + Avatar = existingProfile.Avatar, + Difficulty = existingProfile.Difficulty, + UserRole = existingProfile.UserRole, + PlayerName = existingProfile.PlayerName + }; } else { newProfile = new CProfile - { - Active = EOffOn.TR_CONFIG_ON, - UserRole = EUserRole.TR_USERROLE_NORMAL - }; + { + Active = EOffOn.TR_CONFIG_ON, + UserRole = EUserRole.TR_USERROLE_NORMAL + }; } if (profile.Avatar != null) + { newProfile.Avatar = _AddAvatar(profile.Avatar); - else if (newProfile.Avatar == null || newProfile.Avatar.ID == -1) + } + else if (newProfile.Avatar == null || newProfile.Avatar.Id == -1) { newProfile.Avatar = CProfiles.GetAvatars().First(); @@ -436,16 +448,22 @@ namespace Vocaluxe.Base.Server } if (!string.IsNullOrEmpty(profile.PlayerName)) + { newProfile.PlayerName = profile.PlayerName; + } else if (!string.IsNullOrEmpty(newProfile.PlayerName)) + { newProfile.PlayerName = "DummyName"; + } if (profile.Difficulty >= 0 && profile.Difficulty <= 2) + { newProfile.Difficulty = (EGameDifficulty)profile.Difficulty; + } if (profile.Type >= 0 && profile.Type <= 1) { - EUserRole option = profile.Type == 0 ? EUserRole.TR_USERROLE_GUEST : EUserRole.TR_USERROLE_NORMAL; + var option = profile.Type == 0 ? EUserRole.TR_USERROLE_GUEST : EUserRole.TR_USERROLE_NORMAL; //Only allow the change of TR_USERROLE_GUEST and TR_USERROLE_NORMAL const EUserRole mask = EUserRole.TR_USERROLE_NORMAL; newProfile.UserRole = (newProfile.UserRole & mask) | option; @@ -460,11 +478,11 @@ namespace Vocaluxe.Base.Server } else { - RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); - byte[] buffer = new byte[32]; + var rng = new RNGCryptoServiceProvider(); + var buffer = new byte[32]; rng.GetNonZeroBytes(buffer); - byte[] salt = buffer; - byte[] hashedPassword = _Hash((new UTF8Encoding()).GetBytes(profile.Password), salt); + var salt = buffer; + var hashedPassword = _Hash(new UTF8Encoding().GetBytes(profile.Password), salt); newProfile.PasswordSalt = salt; newProfile.PasswordHash = hashedPassword; @@ -478,14 +496,16 @@ namespace Vocaluxe.Base.Server CProfiles.SaveProfiles(); } else + { CProfiles.AddProfile(newProfile); + } return true; } public static SProfileData[] GetProfileList() { - List result = new List(CProfiles.NumProfiles); + var result = new List(CProfiles.NumProfiles); result.AddRange(CProfiles.GetProfiles().Select(profile => _CreateProfileData(profile, true))); @@ -494,22 +514,25 @@ namespace Vocaluxe.Base.Server private static SProfileData _CreateProfileData(CProfile profile, bool isReadonly) { - SProfileData profileData = new SProfileData - { - IsEditable = !isReadonly, - ProfileId = profile.ID, - PlayerName = profile.PlayerName, - //Is TR_USERROLE_GUEST or TR_USERROLE_NORMAL? - Type = (profile.UserRole.HasFlag(EUserRole.TR_USERROLE_NORMAL) ? 1 : 0), - Difficulty = (int)profile.Difficulty - }; + var profileData = new SProfileData + { + IsEditable = !isReadonly, + ProfileId = profile.Id, + PlayerName = profile.PlayerName, + //Is TR_USERROLE_GUEST or TR_USERROLE_NORMAL? + Type = profile.UserRole.HasFlag(EUserRole.TR_USERROLE_NORMAL) ? 1 : 0, + Difficulty = (int)profile.Difficulty + }; - CAvatar avatar = profile.Avatar; + var avatar = profile.Avatar; if (avatar != null) { if (File.Exists(avatar.FileName)) + { profileData.Avatar = new CBase64Image(_CreateDelayedImage(avatar.FileName)); + } } + return profileData; } @@ -517,14 +540,15 @@ namespace Vocaluxe.Base.Server { try { - string filename = _SaveImage(avatarData, "snapshot", CConfig.ProfileFolders[0]); + var filename = _SaveImage(avatarData, "snapshot", CConfig.ProfileFolders[0]); - CAvatar avatar = CAvatar.GetAvatar(filename); + var avatar = CAvatar.GetAvatar(filename); if (avatar != null) { CProfiles.AddAvatar(avatar); return avatar; } + return null; } catch @@ -540,10 +564,12 @@ namespace Vocaluxe.Base.Server public static bool SendPhoto(SPhotoData photoData) { if (photoData.Photo == null) + { return false; + } - string name = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"); - string filePath = _SaveImage(photoData.Photo, name, CSettings.FolderNamePhotos); + var name = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"); + var filePath = _SaveImage(photoData.Photo, name, CSettings.FolderNamePhotos); if (!string.IsNullOrEmpty(filePath)) { _PhotosOfThisRound.Add(filePath); @@ -555,7 +581,7 @@ namespace Vocaluxe.Base.Server internal static string[] GetPhotosOfThisRound() { - string[] result = _PhotosOfThisRound.ToArray(); + var result = _PhotosOfThisRound.ToArray(); _PhotosOfThisRound.Clear(); return result; } @@ -566,11 +592,13 @@ namespace Vocaluxe.Base.Server public static byte[] GetSiteFile(string filename) { - string path = "Website/" + filename; + var path = "Website/" + filename; path = path.Replace("..", ""); if (!File.Exists(path)) + { return null; + } /*string content = File.ReadAllText(path); @@ -584,15 +612,20 @@ namespace Vocaluxe.Base.Server private static string _CreateDelayedImage(string filename) { - byte[] by = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(filename)); + var by = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(filename)); var sb = new StringBuilder(); - foreach (byte b in by) + foreach (var b in by) + { sb.Append(b.ToString("x2")); + } - string hashedFilename = sb.ToString(); + var hashedFilename = sb.ToString(); if (!_DelayedImagePath.ContainsKey(hashedFilename)) + { _DelayedImagePath.Add(hashedFilename, filename); + } + return hashedFilename; } @@ -604,15 +637,18 @@ namespace Vocaluxe.Base.Server public static CBase64Image GetDelayedImage(string hashedFilename) { if (!_DelayedImagePath.ContainsKey(hashedFilename)) + { throw new FileNotFoundException("Image not found"); + } - string fileName = _DelayedImagePath[hashedFilename]; + var fileName = _DelayedImagePath[hashedFilename]; if (File.Exists(fileName)) { - Image image = Image.FromFile(fileName); + var image = Image.FromFile(fileName); return new CBase64Image(image, image.RawFormat); } + throw new FileNotFoundException("Image not found"); } #endregion @@ -620,43 +656,46 @@ namespace Vocaluxe.Base.Server #region songs public static SSongInfo GetSong(int songId) { - CSong song = CSongs.GetSong(songId); + var song = CSongs.GetSong(songId); return _GetSongInfo(song, true); } - private static SSongInfo[] _SongInfoCache = null; + public static SSongInfo[] GetAllSongs() { - bool sendCovers = CConfig.Config.Server.SongCountCoverThreshold == -1 || CConfig.Config.Server.SongCountCoverThreshold > CSongs.Songs.Count; + var sendCovers = CConfig.Config.Server.SongCountCoverThreshold == -1 || CConfig.Config.Server.SongCountCoverThreshold > CSongs.Songs.Count; if (_SongInfoCache == null) { - List songs = CSongs.Songs; + var songs = CSongs.Songs; _SongInfoCache = (from s in songs select _GetSongInfo(s, sendCovers)).AsParallel().ToArray(); } - + return _SongInfoCache; } public static string GetMp3Path(int songId) { - CSong song = CSongs.GetSong(songId); + var song = CSongs.GetSong(songId); return song.GetMP3(); } public static int GetCurrentSongId() { - CSong song = CGame.GetSong(); + var song = CGame.GetSong(); if (song == null) + { return -1; - return song.ID; + } + + return song.Id; } private static SSongInfo _GetSongInfo(CSong song, bool includeCover) { - SSongInfo result = new SSongInfo(); + var result = new SSongInfo(); if (song != null) { result.Title = song.Title; @@ -665,7 +704,7 @@ namespace Vocaluxe.Base.Server result.Language = song.Languages.FirstOrDefault(); result.Year = song.Year; result.IsDuet = song.IsDuet; - result.SongId = song.ID; + result.SongId = song.Id; if (includeCover) { if (song.CoverFileName == "") @@ -677,8 +716,8 @@ namespace Vocaluxe.Base.Server result.Cover = new CBase64Image(_CreateDelayedImage(song.Folder + "\\" + song.CoverFileName)); } } - } + return result; } #endregion @@ -687,20 +726,25 @@ namespace Vocaluxe.Base.Server public static SPlaylistData[] GetPlaylists() { return (from p in CPlaylists.Playlists - select _GetPlaylistInfo(p)).ToArray(); + select _GetPlaylistInfo(p)).ToArray(); } public static SPlaylistData GetPlaylist(int playlistId) { if (CPlaylists.Get(playlistId) == null) + { throw new ArgumentException("invalid playlistId"); + } + return _GetPlaylistInfo(CPlaylists.Get(playlistId)); } public static void AddSongToPlaylist(int songId, int playlistId, bool allowDuplicates) { if (CPlaylists.Get(playlistId) == null) + { throw new ArgumentException("invalid playlistId"); + } if (allowDuplicates || !PlaylistContainsSong(songId, playlistId)) { @@ -708,98 +752,128 @@ namespace Vocaluxe.Base.Server CPlaylists.Save(playlistId); } else + { throw new ArgumentException("song exists in this playlist"); + } } public static void RemoveSongFromPlaylist(int position, int playlistId, int songId) { - CPlaylistFile pl = CPlaylists.Get(playlistId); + var pl = CPlaylists.Get(playlistId); if (pl == null) + { throw new ArgumentException("invalid playlistId"); + } + if (!PlaylistContainsSong(songId, playlistId)) + { throw new ArgumentException("invalid songId"); + } + if (position < 0 || pl.Songs.Count <= position - || pl.Songs[position].SongID != songId) + || pl.Songs[position].SongId != songId) + { throw new ArgumentException("invalid position"); + } + pl.DeleteSong(position); pl.Save(); } public static void MoveSongInPlaylist(int newPosition, int playlistId, int songId) { - CPlaylistFile pl = CPlaylists.Get(playlistId); + var pl = CPlaylists.Get(playlistId); if (pl == null) + { throw new ArgumentException("invalid playlistId"); + } + if (!PlaylistContainsSong(songId, playlistId)) + { throw new ArgumentException("invalid songId"); + } if (pl.Songs.Count < newPosition) + { throw new ArgumentException("invalid newPosition"); + } - int oldPosition = pl.Songs.FindIndex(s => s.SongID == songId); + var oldPosition = pl.Songs.FindIndex(s => s.SongId == songId); pl.MoveSong(oldPosition, newPosition); pl.Save(); } public static bool PlaylistContainsSong(int songId, int playlistId) { - CPlaylistFile pl = CPlaylists.Get(playlistId); + var pl = CPlaylists.Get(playlistId); if (pl == null) + { throw new ArgumentException("invalid playlistId"); - return pl.Songs.Any(s => s.SongID == songId); + } + + return pl.Songs.Any(s => s.SongId == songId); } public static SPlaylistSongInfo[] GetPlaylistSongs(int playlistId) { - CPlaylistFile pl = CPlaylists.Get(playlistId); + var pl = CPlaylists.Get(playlistId); if (pl == null) + { throw new ArgumentException("invalid playlistId"); + } return _GetPlaylistSongInfos(pl); } private static SPlaylistSongInfo _GetPlaylistSongInfo(CPlaylistSong playlistSong, int playlistId, int playlistPos) { - SPlaylistSongInfo result = new SPlaylistSongInfo(); + var result = new SPlaylistSongInfo(); if (playlistSong != null) { result.PlaylistId = playlistId; result.GameMode = (int)playlistSong.GameMode; result.PlaylistPosition = playlistPos; - result.Song = _GetSongInfo(CSongs.GetSong(playlistSong.SongID), true); + result.Song = _GetSongInfo(CSongs.GetSong(playlistSong.SongId), true); } + return result; } private static SPlaylistSongInfo[] _GetPlaylistSongInfos(CPlaylistFile playlist) { - SPlaylistSongInfo[] result = new SPlaylistSongInfo[playlist.Songs.Count]; - for (int i = 0; i < playlist.Songs.Count; i++) + var result = new SPlaylistSongInfo[playlist.Songs.Count]; + for (var i = 0; i < playlist.Songs.Count; i++) + { result[i] = _GetPlaylistSongInfo(playlist.Songs[i], playlist.Id, i); + } + return result; } private static SPlaylistData _GetPlaylistInfo(CPlaylistFile playlist) { return new SPlaylistData - { - PlaylistId = playlist.Id, - PlaylistName = playlist.Name, - SongCount = playlist.Songs.Count, - LastChanged = DateTime.Now.ToLongDateString() - }; + { + PlaylistId = playlist.Id, + PlaylistName = playlist.Name, + SongCount = playlist.Songs.Count, + LastChanged = DateTime.Now.ToLongDateString() + }; } public static void RemovePlaylist(int playlistId) { if (CPlaylists.Get(playlistId) == null) + { throw new ArgumentException("invalid playlistId"); + } + CPlaylists.Delete(playlistId); } public static int AddPlaylist(string playlistName) { - int newPlaylistId = CPlaylists.NewPlaylist(playlistName); + var newPlaylistId = CPlaylists.NewPlaylist(playlistName); CPlaylists.Save(newPlaylistId); return newPlaylistId; @@ -809,31 +883,41 @@ namespace Vocaluxe.Base.Server #region user management public static bool ValidatePassword(Guid profileId, string password) { - CProfile profile = CProfiles.GetProfile(profileId); + var profile = CProfiles.GetProfile(profileId); if (profile == null) + { return false; + } if (profile.PasswordHash == null) { if (string.IsNullOrEmpty(password)) + { return true; //Allow empty passwords + } + return false; } - byte[] salt = profile.PasswordSalt; - return _Hash((new UTF8Encoding()).GetBytes(password), salt).SequenceEqual(profile.PasswordHash); + var salt = profile.PasswordSalt; + return _Hash(new UTF8Encoding().GetBytes(password), salt).SequenceEqual(profile.PasswordHash); } public static bool ValidatePassword(Guid profileId, byte[] hashedPassword) { - CProfile profile = CProfiles.GetProfile(profileId); + var profile = CProfiles.GetProfile(profileId); if (profile == null) + { return false; + } if (profile.PasswordHash == null) { if (hashedPassword == null) + { return true; //Allow empty passwords + } + return false; } @@ -843,38 +927,46 @@ namespace Vocaluxe.Base.Server private static byte[] _GetPasswordSalt(Guid profileId) { - CProfile profile = CProfiles.GetProfile(profileId); + var profile = CProfiles.GetProfile(profileId); if (profile == null) + { throw new ArgumentException("Invalid profileId"); + } if (profile.PasswordHash == null) + { throw new ArgumentException("Empty password"); + } return profile.PasswordSalt; } public static int GetUserRole(Guid profileId) { - CProfile profile = CProfiles.GetProfile(profileId); + var profile = CProfiles.GetProfile(profileId); if (profile == null) + { throw new ArgumentException("Invalid profileId"); + } //Hide TR_USERROLE_GUEST and TR_USERROLE_NORMAL //const EUserRole mask = (EUserRole.TR_USERROLE_GUEST | EUserRole.TR_USERROLE_NORMAL); - return (int)(profile.UserRole); + return (int)profile.UserRole; } public static void SetUserRole(Guid profileId, int userRole) { - CProfile profile = CProfiles.GetProfile(profileId); + var profile = CProfiles.GetProfile(profileId); if (profile == null) + { throw new ArgumentException("Invalid profileId"); + } var option = (EUserRole)userRole; //Only allow the change of all options exept TR_USERROLE_GUEST and TR_USERROLE_NORMAL - const EUserRole mask = (EUserRole.TR_USERROLE_GUEST | EUserRole.TR_USERROLE_NORMAL); + const EUserRole mask = EUserRole.TR_USERROLE_GUEST | EUserRole.TR_USERROLE_NORMAL; option &= ~mask; profile.UserRole = (profile.UserRole & mask) | option; @@ -886,9 +978,9 @@ namespace Vocaluxe.Base.Server public static Guid GetUserIdFromUsername(string username) { - IEnumerable playerIds = (from p in CProfiles.GetProfiles() - where String.Equals(p.PlayerName, username, StringComparison.OrdinalIgnoreCase) - select p.ID); + var playerIds = from p in CProfiles.GetProfiles() + where String.Equals(p.PlayerName, username, StringComparison.OrdinalIgnoreCase) + select p.Id; return playerIds.FirstOrDefault(); } @@ -896,7 +988,7 @@ namespace Vocaluxe.Base.Server { HashAlgorithm hashAlgo = new SHA256Managed(); - byte[] data = new byte[password.Length + salt.Length]; + var data = new byte[password.Length + salt.Length]; password.CopyTo(data, 0); salt.CopyTo(data, password.Length); @@ -907,13 +999,15 @@ namespace Vocaluxe.Base.Server private static string _SaveImage(CBase64Image imageDate, string name, string folder) { - Image avatarImage = imageDate.GetImage(); - string extension = imageDate.GetImageType(); + var avatarImage = imageDate.GetImage(); + var extension = imageDate.GetImageType(); if (!Directory.Exists(folder)) + { Directory.CreateDirectory(folder); + } - string file = CHelper.GetUniqueFileName(folder, name + "." + extension); + var file = CHelper.GetUniqueFileName(folder, name + "." + extension); avatarImage.Save(file); return file; diff --git a/Vocaluxe/Base/Server/CWebservice.cs b/Vocaluxe/Base/Server/CWebservice.cs index e2315c80..b6a6473c 100644 --- a/Vocaluxe/Base/Server/CWebservice.cs +++ b/Vocaluxe/Base/Server/CWebservice.cs @@ -28,17 +28,20 @@ namespace Vocaluxe.Base.Server { private static Guid _GetSession() { - Guid sessionKey = Guid.Empty; - string sessionHeader = + var sessionKey = Guid.Empty; + var sessionHeader = ((HttpRequestMessageProperty)OperationContext.Current.IncomingMessageProperties["httpRequest"]).Headers["session"]; if (string.IsNullOrEmpty(sessionHeader)) + { return sessionKey; + } + try { sessionKey = Guid.Parse(sessionHeader); } - catch (Exception) - { } + catch (Exception) { } + CSessionControl.ResetSessionTimeout(sessionKey); return sessionKey; } @@ -46,24 +49,28 @@ namespace Vocaluxe.Base.Server public void SendKeyEvent(string key) { if (!_CheckRight(EUserRights.UseKeyboard)) + { return; + } - CVocaluxeServer.DoTask(CVocaluxeServer.SendKeyEvent,key); + CVocaluxeServer.DoTask(CVocaluxeServer.SendKeyEvent, key); } public void SendKeyStringEvent(string keyString, bool isShiftPressed = false, bool isAltPressed = false, bool isCtrlPressed = false) { if (!_CheckRight(EUserRights.UseKeyboard)) + { return; - + } + CVocaluxeServer.DoTask(CVocaluxeServer.SendKeyStringEvent, keyString, isShiftPressed, isAltPressed, isCtrlPressed); } #region profile public Guid GetOwnProfileId() { - Guid sessionKey = _GetSession(); + var sessionKey = _GetSession(); if (sessionKey == Guid.Empty) { if (WebOperationContext.Current != null) @@ -71,9 +78,11 @@ namespace Vocaluxe.Base.Server WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Forbidden; WebOperationContext.Current.OutgoingResponse.StatusDescription = "No session"; } + return Guid.Empty; } - Guid profileId = CSessionControl.GetUserIdFromSession(sessionKey); + + var profileId = CSessionControl.GetUserIdFromSession(sessionKey); if (profileId == Guid.Empty) { if (WebOperationContext.Current != null) @@ -81,20 +90,24 @@ namespace Vocaluxe.Base.Server WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Forbidden; WebOperationContext.Current.OutgoingResponse.StatusDescription = "No session"; } + return Guid.Empty; } + return profileId; } public void SendProfile(SProfileData profile) { - Guid sessionKey = _GetSession(); + var sessionKey = _GetSession(); if (profile.ProfileId != Guid.Empty) //Guid.Empty is the id for a new profile { if (CSessionControl.GetUserIdFromSession(sessionKey) != profile.ProfileId - && !(_CheckRight(EUserRights.EditAllProfiles))) + && !_CheckRight(EUserRights.EditAllProfiles)) + { return; + } } CVocaluxeServer.DoTask(CVocaluxeServer.SendProfileData, profile); @@ -102,15 +115,16 @@ namespace Vocaluxe.Base.Server public SProfileData GetProfile(Guid profileId) { - Guid sessionKey = _GetSession(); + var sessionKey = _GetSession(); if (CSessionControl.GetUserIdFromSession(sessionKey) == profileId || _CheckRight(EUserRights.ViewOtherProfiles)) { - bool isReadonly = (!CSessionControl.RequestRight(sessionKey, EUserRights.EditAllProfiles) && - CSessionControl.GetUserIdFromSession(sessionKey) != profileId); + var isReadonly = !CSessionControl.RequestRight(sessionKey, EUserRights.EditAllProfiles) && + CSessionControl.GetUserIdFromSession(sessionKey) != profileId; - return CVocaluxeServer.DoTask(CVocaluxeServer.GetProfileData,profileId, isReadonly); + return CVocaluxeServer.DoTask(CVocaluxeServer.GetProfileData, profileId, isReadonly); } + return new SProfileData(); } @@ -124,14 +138,16 @@ namespace Vocaluxe.Base.Server public void SendPhoto(SPhotoData photo) { if (_CheckRight(EUserRights.UploadPhotos)) + { CVocaluxeServer.DoTask(CVocaluxeServer.SendPhoto, photo); + } } #endregion #region website public Guid Login(string username, string password) { - Guid sessionId = CSessionControl.OpenSession(username, password); + var sessionId = CSessionControl.OpenSession(username, password); if (sessionId == Guid.Empty) { if (WebOperationContext.Current != null) @@ -140,21 +156,24 @@ namespace Vocaluxe.Base.Server WebOperationContext.Current.OutgoingResponse.StatusDescription = "Wrong username or password"; } } + return sessionId; } public void Logout() { - Guid sessionKey = _GetSession(); - CSessionControl.InvalidateSessionByID(sessionKey); + var sessionKey = _GetSession(); + CSessionControl.InvalidateSessionById(sessionKey); } public Stream Index() { if (WebOperationContext.Current != null) + { WebOperationContext.Current.OutgoingResponse.ContentType = "text/html"; + } - return new MemoryStream(CVocaluxeServer.DoTask(CVocaluxeServer.GetSiteFile,"index.html")); + return new MemoryStream(CVocaluxeServer.DoTask(CVocaluxeServer.GetSiteFile, "index.html")); } public Stream GetJsFile(string filename) @@ -168,13 +187,18 @@ namespace Vocaluxe.Base.Server DateTime.UtcNow.AddHours(4).ToString("r")); } - byte[] data = CVocaluxeServer.DoTask(CVocaluxeServer.GetSiteFile, "js/" + filename); + var data = CVocaluxeServer.DoTask(CVocaluxeServer.GetSiteFile, "js/" + filename); if (data != null) + { return new MemoryStream(data); + } if (WebOperationContext.Current != null) + { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; + } + return null; } @@ -189,12 +213,18 @@ namespace Vocaluxe.Base.Server DateTime.UtcNow.AddHours(4).ToString("r")); } - byte[] data = CVocaluxeServer.DoTask(CVocaluxeServer.GetSiteFile, "css/" + filename); + var data = CVocaluxeServer.DoTask(CVocaluxeServer.GetSiteFile, "css/" + filename); if (data != null) + { return new MemoryStream(data); + } + if (WebOperationContext.Current != null) + { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; + } + return null; } @@ -209,12 +239,18 @@ namespace Vocaluxe.Base.Server DateTime.UtcNow.AddYears(1).ToString("r")); } - byte[] data = CVocaluxeServer.DoTask(CVocaluxeServer.GetSiteFile, "css\\images\\" + filename); + var data = CVocaluxeServer.DoTask(CVocaluxeServer.GetSiteFile, "css\\images\\" + filename); if (data != null) + { return new MemoryStream(data); + } + if (WebOperationContext.Current != null) + { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; + } + return null; } @@ -229,12 +265,18 @@ namespace Vocaluxe.Base.Server DateTime.UtcNow.AddYears(1).ToString("r")); } - byte[] data = CVocaluxeServer.DoTask(CVocaluxeServer.GetSiteFile, "img/" + filename); + var data = CVocaluxeServer.DoTask(CVocaluxeServer.GetSiteFile, "img/" + filename); if (data != null) + { return new MemoryStream(data); + } + if (WebOperationContext.Current != null) + { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; + } + return null; } @@ -249,13 +291,18 @@ namespace Vocaluxe.Base.Server DateTime.UtcNow.AddHours(4).ToString("r")); } - byte[] data = CVocaluxeServer.DoTask(CVocaluxeServer.GetSiteFile, "locales/" + filename); + var data = CVocaluxeServer.DoTask(CVocaluxeServer.GetSiteFile, "locales/" + filename); if (data != null) + { return new MemoryStream(data); + } if (WebOperationContext.Current != null) + { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; + } + return null; } @@ -303,18 +350,21 @@ namespace Vocaluxe.Base.Server } - String path = CVocaluxeServer.DoTask(CVocaluxeServer.GetMp3Path,songId); + var path = CVocaluxeServer.DoTask(CVocaluxeServer.GetMp3Path, songId); path = path.Replace("..", ""); - if (!File.Exists(path) - || !(path.EndsWith(".mp3", StringComparison.InvariantCulture) - || path.EndsWith(".ogg", StringComparison.InvariantCulture) - || path.EndsWith(".wav", StringComparison.InvariantCulture) - || path.EndsWith(".webm", StringComparison.InvariantCulture))) + if (!File.Exists(path) + || !(path.EndsWith(".mp3", StringComparison.InvariantCulture) + || path.EndsWith(".ogg", StringComparison.InvariantCulture) + || path.EndsWith(".wav", StringComparison.InvariantCulture) + || path.EndsWith(".webm", StringComparison.InvariantCulture))) { if (WebOperationContext.Current != null) + { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.NotFound; + } + return null; } @@ -364,13 +414,14 @@ namespace Vocaluxe.Base.Server return new SPlaylistData(); } - } public void AddSongToPlaylist(int songId, int playlistId, bool allowDuplicates) { if (!_CheckRight(EUserRights.AddSongToPlaylist)) + { return; + } try { @@ -389,7 +440,9 @@ namespace Vocaluxe.Base.Server public void RemoveSongFromPlaylist(int position, int playlistId, int songId) { if (!_CheckRight(EUserRights.RemoveSongsFromPlaylists)) + { return; + } try { @@ -408,7 +461,9 @@ namespace Vocaluxe.Base.Server public void MoveSongInPlaylist(int newPosition, int playlistId, int songId) { if (!_CheckRight(EUserRights.ReorderPlaylists)) + { return; + } try { @@ -455,6 +510,7 @@ namespace Vocaluxe.Base.Server WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Forbidden; WebOperationContext.Current.OutgoingResponse.StatusDescription = e.Message; } + return new SPlaylistSongInfo[0]; } } @@ -462,7 +518,9 @@ namespace Vocaluxe.Base.Server public void RemovePlaylist(int playlistId) { if (!_CheckRight(EUserRights.DeletePlaylists)) + { return; + } try { @@ -481,7 +539,9 @@ namespace Vocaluxe.Base.Server public int AddPlaylist(string playlistName) { if (!_CheckRight(EUserRights.CreatePlaylists)) - return -1; + { + return -1; + } try { @@ -509,7 +569,9 @@ namespace Vocaluxe.Base.Server public void SetUserRole(Guid profileId, int userRole) { if (_CheckRight(EUserRights.EditAllProfiles)) + { CVocaluxeServer.DoTaskWithoutReturn(CVocaluxeServer.SetUserRole, profileId, userRole); + } } public bool HasUserRight(int right) @@ -519,7 +581,7 @@ namespace Vocaluxe.Base.Server private static bool _CheckRight(EUserRights requestedRight) { - Guid sessionKey = _GetSession(); + var sessionKey = _GetSession(); if (sessionKey == Guid.Empty) { @@ -528,6 +590,7 @@ namespace Vocaluxe.Base.Server WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Forbidden; WebOperationContext.Current.OutgoingResponse.StatusDescription = "No session"; } + return false; } @@ -538,20 +601,26 @@ namespace Vocaluxe.Base.Server WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Forbidden; WebOperationContext.Current.OutgoingResponse.StatusDescription = "Not allowed"; } + return false; } + return true; } private static bool _CheckRightWithNoErrorMessage(EUserRights requestedRight) { - Guid sessionKey = _GetSession(); + var sessionKey = _GetSession(); if (sessionKey == Guid.Empty) + { return false; + } if (!CSessionControl.RequestRight(sessionKey, requestedRight)) + { return false; + } return true; } diff --git a/Vocaluxe/Base/Server/ICWebservice.cs b/Vocaluxe/Base/Server/ICWebservice.cs index 62fdb3d5..26f13a9d 100644 --- a/Vocaluxe/Base/Server/ICWebservice.cs +++ b/Vocaluxe/Base/Server/ICWebservice.cs @@ -26,185 +26,185 @@ namespace Vocaluxe.Base.Server public interface ICWebservice { [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/sendKeyEvent?key={key}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/sendKeyEvent?key={key}")] void SendKeyEvent(string key); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/sendKeyStringEvent?keyString={keyString}&shift={isShiftPressed}&alt={isAltPressed}&ctrl={isCtrlPressed}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/sendKeyStringEvent?keyString={keyString}&shift={isShiftPressed}&alt={isAltPressed}&ctrl={isCtrlPressed}")] void SendKeyStringEvent(string keyString, bool isShiftPressed = false, bool isAltPressed = false, bool isCtrlPressed = false); #region profile [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/getOwnProfileId")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/getOwnProfileId")] Guid GetOwnProfileId(); [OperationContract, WebInvoke(Method = "POST", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/sendProfile")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/sendProfile")] void SendProfile(SProfileData profile); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/getProfile?profileId={profileId}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/getProfile?profileId={profileId}")] SProfileData GetProfile(Guid profileId); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/getProfileList")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/getProfileList")] SProfileData[] GetProfileList(); #endregion #region photo [OperationContract, WebInvoke(Method = "POST", - RequestFormat = WebMessageFormat.Json, - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/sendPhoto")] + RequestFormat = WebMessageFormat.Json, + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/sendPhoto")] void SendPhoto(SPhotoData photo); #endregion #region website [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/login?username={username}&password={password}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/login?username={username}&password={password}")] Guid Login(string username, string password); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/logout")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/logout")] void Logout(); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "")] Stream Index(); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/js/{filename}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/js/{filename}")] Stream GetJsFile(String filename); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/css/{filename}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/css/{filename}")] Stream GetCssFile(String filename); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/css/images/{filename}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/css/images/{filename}")] Stream GetCssImageFile(String filename); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/img/{filename}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/img/{filename}")] Stream GetImgFile(String filename); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/locales/{filename}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/locales/{filename}")] Stream GetLocaleFile(String filename); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/delayedImage?id={id}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/delayedImage?id={id}")] CBase64Image GetDelayedImage(String id); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/isServerOnline")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/isServerOnline")] bool IsServerOnline(); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/getServerVersion")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/getServerVersion")] String GetServerVersion(); #endregion #region songs [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/getSong?songId={songId}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/getSong?songId={songId}")] SSongInfo GetSong(int songId); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/getCurrentSongId")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/getCurrentSongId")] int GetCurrentSongId(); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/getAllSongs")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/getAllSongs")] SSongInfo[] GetAllSongs(); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/getMp3?songId={songId}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/getMp3?songId={songId}")] Stream GetMp3File(int songId); #endregion #region playlist [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/getPlaylists")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/getPlaylists")] SPlaylistData[] GetPlaylists(); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/getPlaylist?id={playlistId}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/getPlaylist?id={playlistId}")] SPlaylistData GetPlaylist(int playlistId); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/addSongToPlaylist?songId={songId}&playlistId={playlistId}&duplicates={allowDuplicates}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/addSongToPlaylist?songId={songId}&playlistId={playlistId}&duplicates={allowDuplicates}")] void AddSongToPlaylist(int songId, int playlistId, bool allowDuplicates); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/removeSongFromPlaylist?position={position}&playlistId={playlistId}&songId={songId}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/removeSongFromPlaylist?position={position}&playlistId={playlistId}&songId={songId}")] void RemoveSongFromPlaylist(int position, int playlistId, int songId); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/moveSongInPlaylist?newPosition={newPosition}&playlistId={playlistId}&songId={songId}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/moveSongInPlaylist?newPosition={newPosition}&playlistId={playlistId}&songId={songId}")] void MoveSongInPlaylist(int newPosition, int playlistId, int songId); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/playlistContainsSong?songId={songId}&playlistId={playlistId}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/playlistContainsSong?songId={songId}&playlistId={playlistId}")] bool PlaylistContainsSong(int songId, int playlistId); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/getPlaylistSongs?playlistId={playlistId}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/getPlaylistSongs?playlistId={playlistId}")] SPlaylistSongInfo[] GetPlaylistSongs(int playlistId); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/removePlaylist?playlistId={playlistId}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/removePlaylist?playlistId={playlistId}")] void RemovePlaylist(int playlistId); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/addPlaylist?playlistName={playlistName}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/addPlaylist?playlistName={playlistName}")] int AddPlaylist(string playlistName); #endregion #region user management [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/getUserRole?profileId={profileId}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/getUserRole?profileId={profileId}")] int GetUserRole(Guid profileId); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/setUserRole?profileId={profileId}&userRole={userRole}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/setUserRole?profileId={profileId}&userRole={userRole}")] void SetUserRole(Guid profileId, int userRole); [OperationContract, WebInvoke(Method = "GET", - ResponseFormat = WebMessageFormat.Json, - UriTemplate = "/hasUserRight?right={right}")] + ResponseFormat = WebMessageFormat.Json, + UriTemplate = "/hasUserRight?right={right}")] bool HasUserRight(int right); #endregion } diff --git a/Vocaluxe/Base/Server/Session.cs b/Vocaluxe/Base/Server/Session.cs index 43ff2ae8..7928caf6 100644 --- a/Vocaluxe/Base/Server/Session.cs +++ b/Vocaluxe/Base/Server/Session.cs @@ -21,37 +21,20 @@ namespace Vocaluxe.Base.Server { class CSession { - private readonly Guid _ID; - public Guid Id - { - get { return _ID; } - } + public Guid Id { get; } - private readonly Guid _ProfileId; - public Guid ProfileId - { - get { return _ProfileId; } - } + public Guid ProfileId { get; } - private readonly EUserRoles _Roles; - internal EUserRoles Roles - { - get { return _Roles; } - } - - private DateTime _LastSeen; - public DateTime LastSeen - { - get { return _LastSeen; } - internal set { _LastSeen = value; } - } + internal EUserRoles Roles { get; } + + public DateTime LastSeen { get; internal set; } public CSession(Guid id, Guid profileId, EUserRoles roles) { - _ID = id; - _ProfileId = profileId; - _Roles = roles; - _LastSeen = DateTime.Now; + Id = id; + ProfileId = profileId; + Roles = roles; + LastSeen = DateTime.Now; } } } \ No newline at end of file diff --git a/Vocaluxe/Base/Server/SessionControl.cs b/Vocaluxe/Base/Server/SessionControl.cs index e0ee47db..8f95b1bd 100644 --- a/Vocaluxe/Base/Server/SessionControl.cs +++ b/Vocaluxe/Base/Server/SessionControl.cs @@ -31,32 +31,34 @@ namespace Vocaluxe.Base.Server static CSessionControl() { _ActiveSessions = new Dictionary(); - Timer timer = new Timer(_UserTimeoutCheckIntervall) {AutoReset = true, Enabled = true}; + var timer = new Timer(_UserTimeoutCheckIntervall) { AutoReset = true, Enabled = true }; timer.Elapsed += _CheckForUserTimeouts; timer.Start(); } private static void _CheckForUserTimeouts(object sender, ElapsedEventArgs e) { - var sessionIdsToRemove = _ActiveSessions.Where(pair => (DateTime.Now-pair.Value.LastSeen).TotalMilliseconds > _UserTimeout) - .Select(pair => pair.Key) - .ToList(); + var sessionIdsToRemove = _ActiveSessions.Where(pair => (DateTime.Now - pair.Value.LastSeen).TotalMilliseconds > _UserTimeout) + .Select(pair => pair.Key) + .ToList(); foreach (var sessionToRemove in sessionIdsToRemove) { - InvalidateSessionByID(sessionToRemove); + InvalidateSessionById(sessionToRemove); } } public static Guid OpenSession(string userName, string password) { if (!_ValidateUserAndPassword(userName, password)) + { return Guid.Empty; + } - Guid newId = Guid.NewGuid(); - Guid id = _GetProfileIdFormUsername(userName); - EUserRoles roles = _GetUserRoles(id); - CSession session = new CSession(newId, id, roles); + var newId = Guid.NewGuid(); + var id = _GetProfileIdFormUsername(userName); + var roles = _GetUserRoles(id); + var session = new CSession(newId, id, roles); //InvalidateSessions(id); _ActiveSessions.Add(newId, session); @@ -80,13 +82,15 @@ namespace Vocaluxe.Base.Server internal static void InvalidateSessionByProfile(Guid profileId) { - foreach (KeyValuePair s in (from kv in _ActiveSessions - where kv.Value.ProfileId == profileId - select kv).ToList()) + foreach (var s in (from kv in _ActiveSessions + where kv.Value.ProfileId == profileId + select kv).ToList()) + { _ActiveSessions.Remove(s.Key); + } } - internal static void InvalidateSessionByID(Guid sessionId) + internal static void InvalidateSessionById(Guid sessionId) { if (_ActiveSessions.ContainsKey(sessionId)) { @@ -96,14 +100,17 @@ namespace Vocaluxe.Base.Server internal static bool RequestRight(Guid sessionId, EUserRights requestedRight) { - return ((CUserRoleControl.GetUserRightsFromUserRole(_ActiveSessions[sessionId].Roles) - .HasFlag(requestedRight))); + return CUserRoleControl.GetUserRightsFromUserRole(_ActiveSessions[sessionId].Roles) + .HasFlag(requestedRight); } internal static Guid GetUserIdFromSession(Guid sessionId) { if (!_ActiveSessions.ContainsKey(sessionId)) + { return Guid.Empty; + } + return _ActiveSessions[sessionId].ProfileId; } diff --git a/Vocaluxe/Base/Server/UserRoleControl.cs b/Vocaluxe/Base/Server/UserRoleControl.cs index febad3bd..5bbe842f 100644 --- a/Vocaluxe/Base/Server/UserRoleControl.cs +++ b/Vocaluxe/Base/Server/UserRoleControl.cs @@ -23,55 +23,55 @@ namespace Vocaluxe.Base.Server static class CUserRoleControl { private static readonly Dictionary _RoleRightsMapping = new Dictionary + { { - { - EUserRoles.TR_USERROLE_ADMIN, - (EUserRights.EditAllProfiles | - EUserRights.UploadPhotos | - EUserRights.ViewOtherProfiles | - EUserRights.UseKeyboard | - EUserRights.AddSongToPlaylist | - EUserRights.ReorderPlaylists | - EUserRights.CreatePlaylists | - EUserRights.DeletePlaylists | - EUserRights.RemoveSongsFromPlaylists) - }, - { - EUserRoles.TR_USERROLE_GUEST, - EUserRights.None - }, - { - EUserRoles.TR_USERROLE_NORMAL, - (EUserRights.UploadPhotos | - EUserRights.ViewOtherProfiles) - }, - { - EUserRoles.TR_USERROLE_KEYBOARDUSER, - EUserRights.UseKeyboard - }, - { - EUserRoles.TR_USERROLE_ADDSONGSUSER, - EUserRights.AddSongToPlaylist - }, - { - EUserRoles.TR_USERROLE_PLAYLISTEDITOR, - (EUserRights.AddSongToPlaylist | - EUserRights.ReorderPlaylists | - EUserRights.CreatePlaylists | - EUserRights.DeletePlaylists | - EUserRights.RemoveSongsFromPlaylists) - }, - { - EUserRoles.TR_USERROLE_PROFILEEDITOR, - EUserRights.EditAllProfiles - } - }; + EUserRoles.TR_USERROLE_ADMIN, + EUserRights.EditAllProfiles | + EUserRights.UploadPhotos | + EUserRights.ViewOtherProfiles | + EUserRights.UseKeyboard | + EUserRights.AddSongToPlaylist | + EUserRights.ReorderPlaylists | + EUserRights.CreatePlaylists | + EUserRights.DeletePlaylists | + EUserRights.RemoveSongsFromPlaylists + }, + { + EUserRoles.TR_USERROLE_GUEST, + EUserRights.None + }, + { + EUserRoles.TR_USERROLE_NORMAL, + EUserRights.UploadPhotos | + EUserRights.ViewOtherProfiles + }, + { + EUserRoles.TR_USERROLE_KEYBOARDUSER, + EUserRights.UseKeyboard + }, + { + EUserRoles.TR_USERROLE_ADDSONGSUSER, + EUserRights.AddSongToPlaylist + }, + { + EUserRoles.TR_USERROLE_PLAYLISTEDITOR, + EUserRights.AddSongToPlaylist | + EUserRights.ReorderPlaylists | + EUserRights.CreatePlaylists | + EUserRights.DeletePlaylists | + EUserRights.RemoveSongsFromPlaylists + }, + { + EUserRoles.TR_USERROLE_PROFILEEDITOR, + EUserRights.EditAllProfiles + } + }; internal static EUserRights GetUserRightsFromUserRole(EUserRoles userRole) { return _RoleRightsMapping.Where(role => userRole.HasFlag(role.Key)) - .Select(role => role.Value) - .Aggregate(EUserRights.None, (current, r) => current | r); + .Select(role => role.Value) + .Aggregate(EUserRights.None, (current, r) => current | r); } } } \ No newline at end of file diff --git a/Vocaluxe/Base/Server/VocaluxeStructs.cs b/Vocaluxe/Base/Server/VocaluxeStructs.cs index 3467f81d..efe46e46 100644 --- a/Vocaluxe/Base/Server/VocaluxeStructs.cs +++ b/Vocaluxe/Base/Server/VocaluxeStructs.cs @@ -83,9 +83,9 @@ namespace Vocaluxe.Base.Server public CBase64Image(Image img, ImageFormat format) { - MemoryStream ms = new MemoryStream(); + var ms = new MemoryStream(); img.Save(ms, format); - string formatString = ImageCodecInfo.GetImageEncoders().FirstOrDefault(x => x.FormatID == format.Guid).FilenameExtension.Replace("*.", "").ToLower(); + var formatString = ImageCodecInfo.GetImageEncoders().FirstOrDefault(x => x.FormatID == format.Guid).FilenameExtension.Replace("*.", "").ToLower(); base64Data = "data:image/" + formatString + ";base64," + Convert.ToBase64String(ms.ToArray()); } @@ -96,17 +96,17 @@ namespace Vocaluxe.Base.Server public Image GetImage() { - string onlyBase64Data = base64Data.Substring(base64Data.IndexOf(";base64,") + (";base64,").Length); - byte[] imageData = Convert.FromBase64String(onlyBase64Data); - MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length); + var onlyBase64Data = base64Data.Substring(base64Data.IndexOf(";base64,") + ";base64,".Length); + var imageData = Convert.FromBase64String(onlyBase64Data); + var ms = new MemoryStream(imageData, 0, imageData.Length); ms.Write(imageData, 0, imageData.Length); - Image image = Image.FromStream(ms, true); + var image = Image.FromStream(ms, true); return image; } public string GetImageType() { - Match match = Regex.Match(base64Data, "(?<=data:image/)[a-zA-Z]+(?=;base64)"); + var match = Regex.Match(base64Data, "(?<=data:image/)[a-zA-Z]+(?=;base64)"); return match.Success ? match.Groups[0].Value : ""; } } diff --git a/Vocaluxe/Base/ThemeSystem/CBaseSkin.cs b/Vocaluxe/Base/ThemeSystem/CBaseSkin.cs index 273a7aa2..6447a7cc 100644 --- a/Vocaluxe/Base/ThemeSystem/CBaseSkin.cs +++ b/Vocaluxe/Base/ThemeSystem/CBaseSkin.cs @@ -16,19 +16,20 @@ #endregion using System; -using System.Collections.Generic; using VocaluxeLib.Log; namespace Vocaluxe.Base.ThemeSystem { class CBaseSkin : CSkin { - public CBaseSkin(string folder, string file, CTheme parent) : base(folder, file, parent) {} + public CBaseSkin(string folder, string file, CTheme parent) : base(folder, file, parent) { } public override bool Load() { if (!base.Load()) + { return false; + } if (!_CheckRequiredElements()) { @@ -41,18 +42,30 @@ namespace Vocaluxe.Base.ThemeSystem private bool _CheckRequiredElements() { - List missingTextures = _Required.Textures.FindAll(name => !_Textures.ContainsKey(name)); - List missingVideos = _Required.Videos.FindAll(name => !_Videos.ContainsKey(name)); - List missingColors = _Required.Colors.FindAll(name => !_Data.Colors.ContainsKey(name)); + var missingTextures = _Required.Textures.FindAll(name => !_Textures.ContainsKey(name)); + var missingVideos = _Required.Videos.FindAll(name => !_Videos.ContainsKey(name)); + var missingColors = _Required.Colors.FindAll(name => !_Data.Colors.ContainsKey(name)); if (missingTextures.Count + missingVideos.Count + missingColors.Count == 0) + { return true; - string msg = "The skin \"" + this + "\" is missing the following elements: "; + } + + var msg = "The skin \"" + this + "\" is missing the following elements: "; if (missingTextures.Count > 0) + { msg += Environment.NewLine + "Textures: " + String.Join(", ", missingTextures); + } + if (missingVideos.Count > 0) + { msg += Environment.NewLine + "Videos: " + String.Join(", ", missingVideos); + } + if (missingColors.Count > 0) + { msg += Environment.NewLine + "Colors: " + String.Join(", ", missingColors); + } + CLog.Error(msg); return false; } diff --git a/Vocaluxe/Base/ThemeSystem/CBaseTheme.cs b/Vocaluxe/Base/ThemeSystem/CBaseTheme.cs index f0cd3950..8bf3e1b1 100644 --- a/Vocaluxe/Base/ThemeSystem/CBaseTheme.cs +++ b/Vocaluxe/Base/ThemeSystem/CBaseTheme.cs @@ -34,7 +34,7 @@ namespace Vocaluxe.Base.ThemeSystem } } - public CBaseTheme(string filePath) : base(filePath, -1) {} + public CBaseTheme(string filePath) : base(filePath, -1) { } protected override CSkin _GetNewSkin(string path, string file) { @@ -50,7 +50,9 @@ namespace Vocaluxe.Base.ThemeSystem protected override bool _Load() { if (!_Data.Cursor.HasValue) + { return false; + } return CFonts.LoadThemeFonts(_Data.Fonts, Path.Combine(_Folder, Name, CSettings.FolderNameThemeFonts), Name, -1); } @@ -59,18 +61,28 @@ namespace Vocaluxe.Base.ThemeSystem { CSkin skin; if (!_Skins.TryGetValue(CConfig.Config.Theme.Skin, out skin)) + { skin = _Skins.Values.FirstOrDefault(); + } + while (skin != null) { if (skin.Load()) + { break; + } + skin.Unload(); CLog.Error("Failed to load skin " + skin + "! Removing...", true); _Skins.Remove(skin.Name); skin = _Skins.Values.FirstOrDefault(); } + if (skin == null) + { return false; + } + CurrentSkin = skin; return true; } diff --git a/Vocaluxe/Base/ThemeSystem/CPartySkin.cs b/Vocaluxe/Base/ThemeSystem/CPartySkin.cs index b09c93bb..ca6405b7 100644 --- a/Vocaluxe/Base/ThemeSystem/CPartySkin.cs +++ b/Vocaluxe/Base/ThemeSystem/CPartySkin.cs @@ -25,41 +25,57 @@ namespace Vocaluxe.Base.ThemeSystem { private CSkin _BaseSkin; - public CPartySkin(string folder, string file, CTheme parent) : base(folder, file, parent) {} + public CPartySkin(string folder, string file, CTheme parent) : base(folder, file, parent) { } public override bool Load() { _BaseSkin = CThemes.CurrentThemes[-1].CurrentSkin; if (!base.Load()) + { return false; - for (int i = 1; i <= CSettings.MaxNumPlayer; i++) + } + + for (var i = 1; i <= CSettings.MaxNumPlayer; i++) { if (!_Data.Colors.ContainsKey("Player" + i)) + { continue; + } + CLog.Debug("Party themes cannot contain player colors. They will be ignored!"); break; } + return true; } public override bool GetColor(string name, out SColorF color) { if (_Parent.Name == "Default" && !_Required.Colors.Contains(name)) + { CLog.Debug("Non-Default color: " + name); + } + return base.GetColor(name, out color) || _BaseSkin.GetColor(name, out color); } public override CVideoStream GetVideo(string name, bool loop) { if (_Parent.Name == "Default" && !_Required.Videos.Contains(name)) + { CLog.Debug("Non-Default color: " + name); + } + return base.GetVideo(name, loop) ?? _BaseSkin.GetVideo(name, loop); } public override CTextureRef GetTexture(string name) { if (_Parent.Name == "Default" && !_Required.Textures.Contains(name)) + { CLog.Debug("Non-Default color: " + name); + } + return base.GetTexture(name) ?? _BaseSkin.GetTexture(name); } } diff --git a/Vocaluxe/Base/ThemeSystem/CPartyTheme.cs b/Vocaluxe/Base/ThemeSystem/CPartyTheme.cs index b6167fb6..732dc5f8 100644 --- a/Vocaluxe/Base/ThemeSystem/CPartyTheme.cs +++ b/Vocaluxe/Base/ThemeSystem/CPartyTheme.cs @@ -25,12 +25,12 @@ namespace Vocaluxe.Base.ThemeSystem { class CPartyTheme : CTheme { - public CPartyTheme(string filePath, int partyModeID) : base(filePath, partyModeID) {} + public CPartyTheme(string filePath, int partyModeId) : base(filePath, partyModeId) { } public override void Unload() { base.Unload(); - CFonts.UnloadPartyModeFonts(PartyModeID); + CFonts.UnloadPartyModeFonts(PartyModeId); } protected override CSkin _GetNewSkin(string path, string file) @@ -40,7 +40,7 @@ namespace Vocaluxe.Base.ThemeSystem protected override bool _Load() { - return CFonts.LoadThemeFonts(_Data.Fonts, Path.Combine(_Folder, "..", CSettings.FolderNamePartyModeFonts), Name, PartyModeID); + return CFonts.LoadThemeFonts(_Data.Fonts, Path.Combine(_Folder, "..", CSettings.FolderNamePartyModeFonts), Name, PartyModeId); } private CSkin _GetSkinToLoad(int fallbackNum) @@ -60,25 +60,36 @@ namespace Vocaluxe.Base.ThemeSystem default: throw new ArgumentException(); } + return skin; } protected override bool _LoadSkin() { CSkin skin = null; - for (int i = 0; i < 3; i++) + for (var i = 0; i < 3; i++) { skin = _GetSkinToLoad(i); if (skin == null) + { continue; + } + if (skin.Load()) + { break; + } + skin.Unload(); CLog.Error("Failed to load skin " + skin + "! Removing...", true); _Skins.Remove(skin.Name); } + if (skin == null) + { return false; + } + CurrentSkin = skin; return true; } diff --git a/Vocaluxe/Base/ThemeSystem/CSkin.cs b/Vocaluxe/Base/ThemeSystem/CSkin.cs index 398d1d35..dd87bbb2 100644 --- a/Vocaluxe/Base/ThemeSystem/CSkin.cs +++ b/Vocaluxe/Base/ThemeSystem/CSkin.cs @@ -19,12 +19,12 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; +using System.Linq; using System.Xml.Serialization; using VocaluxeLib; using VocaluxeLib.Draw; -using VocaluxeLib.Xml; -using System.Linq; using VocaluxeLib.Log; +using VocaluxeLib.Xml; namespace Vocaluxe.Base.ThemeSystem { @@ -40,14 +40,15 @@ namespace Vocaluxe.Base.ThemeSystem protected struct SRequiredElements { - [XmlIgnore] public List Textures, Videos, Colors; + [XmlIgnore] + public List Textures, Videos, Colors; [XmlElement("Textures")] public string TexturesStr { get { return string.Join("\r\n", Textures); } set { - string[] entries = value.Split(new string[] {"\r\n", "\n"}, StringSplitOptions.RemoveEmptyEntries); + var entries = value.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries); Textures = entries.Select(s => s.Trim()).Where(s => !string.IsNullOrEmpty(s)).ToList(); } } @@ -57,7 +58,7 @@ namespace Vocaluxe.Base.ThemeSystem get { return string.Join("\r\n", Videos); } set { - string[] entries = value.Split(new string[] {"\r\n", "\n"}, StringSplitOptions.RemoveEmptyEntries); + var entries = value.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries); Videos = entries.Select(s => s.Trim()).Where(s => !string.IsNullOrEmpty(s)).ToList(); } } @@ -67,7 +68,7 @@ namespace Vocaluxe.Base.ThemeSystem get { return string.Join("\r\n", Colors); } set { - string[] entries = value.Split(new string[] {"\r\n", "\n"}, StringSplitOptions.RemoveEmptyEntries); + var entries = value.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries); Colors = entries.Select(s => s.Trim()).Where(s => !string.IsNullOrEmpty(s)).ToList(); } } @@ -92,7 +93,7 @@ namespace Vocaluxe.Base.ThemeSystem public static bool InitRequiredElements() { - string path = Path.Combine(CSettings.ProgramFolder, CSettings.FileNameRequiredSkinElements); + var path = Path.Combine(CSettings.ProgramFolder, CSettings.FileNameRequiredSkinElements); var xml = new CXmlDeserializer(); try { @@ -103,19 +104,26 @@ namespace Vocaluxe.Base.ThemeSystem CLog.Error("Error reading required elements: " + e); return false; } - for (int i = 1; i <= CSettings.MaxNumPlayer; i++) + + for (var i = 1; i <= CSettings.MaxNumPlayer; i++) { - string name = "Player" + i; + var name = "Player" + i; if (!_Required.Colors.Contains(name)) + { _Required.Colors.Add(name); + } } + return true; } public static void Close() { if (_Required.Textures == null) + { return; + } + _Required.Textures.Clear(); _Required.Videos.Clear(); _Required.Colors.Clear(); @@ -141,7 +149,7 @@ namespace Vocaluxe.Base.ThemeSystem _Data = xml.Deserialize(Path.Combine(_Folder, _FileName)); if (_Data.SkinSystemVersion != _SkinSystemVersion) { - string errorMsg = _Data.SkinSystemVersion < _SkinSystemVersion ? "the file ist outdated!" : "the file is for newer program versions!"; + var errorMsg = _Data.SkinSystemVersion < _SkinSystemVersion ? "the file ist outdated!" : "the file is for newer program versions!"; errorMsg += " Current Version is " + _SkinSystemVersion; throw new Exception(errorMsg); } @@ -158,30 +166,35 @@ namespace Vocaluxe.Base.ThemeSystem public virtual bool Load() { if (_IsLoaded) + { return true; + } + Debug.Assert(_Textures.Count == 0 && _Videos.Count == 0); // load skins/textures - foreach (KeyValuePair kvp in _Data.Skins) + foreach (var kvp in _Data.Skins) { - CTextureRef texture = CDraw.AddTexture(Path.Combine(_Folder, kvp.Value)); + var texture = CDraw.AddTexture(Path.Combine(_Folder, kvp.Value)); if (texture == null) { CLog.Error("Error on loading texture \"" + kvp.Key + "\": " + kvp.Value, true); return false; } + _Textures.Add(kvp.Key, texture); } // load videos - foreach (KeyValuePair kvp in _Data.Videos) + foreach (var kvp in _Data.Videos) { - CVideoSkinElement sk = new CVideoSkinElement {FileName = kvp.Value}; + var sk = new CVideoSkinElement { FileName = kvp.Value }; if (!File.Exists(Path.Combine(_Folder, sk.FileName))) { CLog.Error("Video \"" + kvp.Key + "\": (" + sk.FileName + ") not found!"); continue; } + _Videos.Add(kvp.Key, sk); } @@ -191,11 +204,15 @@ namespace Vocaluxe.Base.ThemeSystem public void Unload() { - foreach (CTextureRef tex in _Textures.Values) + foreach (var tex in _Textures.Values) + { tex.Dispose(); + } - foreach (CVideoSkinElement vsk in _Videos.Values) + foreach (var vsk in _Videos.Values) + { CVideo.Close(ref vsk.VideoStream); + } _Textures.Clear(); _Videos.Clear(); @@ -218,8 +235,10 @@ namespace Vocaluxe.Base.ThemeSystem sk.VideoStream = CVideo.Load(Path.Combine(_Folder, sk.FileName)); CVideo.SetLoop(sk.VideoStream, loop); } + return sk.VideoStream; } + return null; } diff --git a/Vocaluxe/Base/ThemeSystem/CTheme.cs b/Vocaluxe/Base/ThemeSystem/CTheme.cs index b31a2f78..5b97e280 100644 --- a/Vocaluxe/Base/ThemeSystem/CTheme.cs +++ b/Vocaluxe/Base/ThemeSystem/CTheme.cs @@ -42,7 +42,7 @@ namespace Vocaluxe.Base.ThemeSystem get { return _Skins.Keys.ToArray(); } } - public readonly int PartyModeID; + public readonly int PartyModeId; protected readonly string _Folder; private readonly string _FileName; @@ -53,11 +53,11 @@ namespace Vocaluxe.Base.ThemeSystem private bool _IsLoaded; - protected CTheme(string filePath, int partyModeID) + protected CTheme(string filePath, int partyModeId) { _Folder = Path.GetDirectoryName(filePath); _FileName = Path.GetFileName(filePath); - PartyModeID = partyModeID; + PartyModeId = partyModeId; CurrentSkin = null; } @@ -74,7 +74,7 @@ namespace Vocaluxe.Base.ThemeSystem _Data = xml.Deserialize(Path.Combine(_Folder, _FileName)); if (_Data.ThemeSystemVersion != _ThemeSystemVersion) { - string errorMsg = _Data.ThemeSystemVersion < _ThemeSystemVersion ? "the file ist outdated!" : "the file is for newer program versions!"; + var errorMsg = _Data.ThemeSystemVersion < _ThemeSystemVersion ? "the file ist outdated!" : "the file is for newer program versions!"; errorMsg += " Current Version is " + _ThemeSystemVersion; throw new Exception(errorMsg); } @@ -85,20 +85,21 @@ namespace Vocaluxe.Base.ThemeSystem return false; } - string path = Path.Combine(_Folder, Name); - IEnumerable files = CHelper.ListFiles(path, "*.xml"); + var path = Path.Combine(_Folder, Name); + var files = CHelper.ListFiles(path, "*.xml"); // Load skins, succeed if at least 1 skin was loaded - bool ok = false; - foreach (string file in files) + var ok = false; + foreach (var file in files) { - CSkin skin = _GetNewSkin(path, file); + var skin = _GetNewSkin(path, file); if (skin.Init()) { _Skins.Add(skin.Name, skin); ok = true; } } + return ok; } @@ -109,11 +110,16 @@ namespace Vocaluxe.Base.ThemeSystem public bool Load() { if (_IsLoaded) + { return true; + } if (!_LoadSkin()) + { return false; - bool ok = _Load(); + } + + var ok = _Load(); _IsLoaded = ok; return ok; @@ -126,6 +132,7 @@ namespace Vocaluxe.Base.ThemeSystem CurrentSkin.Unload(); CurrentSkin = null; } + _IsLoaded = false; } @@ -141,8 +148,9 @@ namespace Vocaluxe.Base.ThemeSystem CurrentSkin.Unload(); CurrentSkin = null; } - bool ok = _LoadSkin(); + + var ok = _LoadSkin(); Debug.Assert(ok); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Base/ThemeSystem/CThemes.cs b/Vocaluxe/Base/ThemeSystem/CThemes.cs index 1262c473..bf55a746 100644 --- a/Vocaluxe/Base/ThemeSystem/CThemes.cs +++ b/Vocaluxe/Base/ThemeSystem/CThemes.cs @@ -15,13 +15,12 @@ // along with Vocaluxe. If not, see . #endregion -using System; using System.Collections.Generic; +using System.Diagnostics; using System.IO; using System.Linq; using VocaluxeLib; using VocaluxeLib.Draw; -using System.Diagnostics; using VocaluxeLib.Log; namespace Vocaluxe.Base.ThemeSystem @@ -31,7 +30,7 @@ namespace Vocaluxe.Base.ThemeSystem private static readonly List _Themes = new List(); public static string[] ThemeNames { - get { return _Themes.Where(th=>th is CBaseTheme).Select(th => th.Name).Distinct().ToArray(); } + get { return _Themes.Where(th => th is CBaseTheme).Select(th => th.Name).Distinct().ToArray(); } } public static string[] SkinNames @@ -58,8 +57,11 @@ namespace Vocaluxe.Base.ThemeSystem public static void Unload() { - foreach (CTheme theme in _Themes) + foreach (var theme in _Themes) + { theme.Unload(); + } + CurrentThemes.Clear(); } @@ -70,54 +72,68 @@ namespace Vocaluxe.Base.ThemeSystem /// public static void Load() { - CTheme theme = _Themes.FirstOrDefault(th => th is CBaseTheme && th.Name == CConfig.Config.Theme.Theme) ?? _Themes.FirstOrDefault(th => th is CBaseTheme); + var theme = _Themes.FirstOrDefault(th => th is CBaseTheme && th.Name == CConfig.Config.Theme.Theme) ?? _Themes.FirstOrDefault(th => th is CBaseTheme); while (theme != null) { if (theme.Load()) + { break; + } + theme.Unload(); CLog.Error("Failed to load theme {ThemeName}! Removing...", CLog.Params(theme.Name, theme), true); _Themes.Remove(theme); theme = _Themes.FirstOrDefault(th => th is CBaseTheme); } + CurrentThemes.Add(-1, theme); if (theme == null) + { CLog.Fatal("No themes found! Cannot continue!"); + } else { CConfig.Config.Theme.Theme = theme.Name; CConfig.Config.Theme.Skin = theme.CurrentSkin.Name; - int[] ids = _Themes.Select(th => th.PartyModeID).Distinct().ToArray(); - foreach (int id in ids.Where(id => id >= 0)) + var ids = _Themes.Select(th => th.PartyModeId).Distinct().ToArray(); + foreach (var id in ids.Where(id => id >= 0)) + { LoadPartymodeTheme(id); + } } } - public static bool LoadPartymodeTheme(int partyModeID) + public static bool LoadPartymodeTheme(int partyModeId) { - Debug.Assert(partyModeID >= 0); - CTheme theme = _Themes.FirstOrDefault(th => th.PartyModeID == partyModeID && th.Name == CConfig.Config.Theme.Theme); + Debug.Assert(partyModeId >= 0); + var theme = _Themes.FirstOrDefault(th => th.PartyModeId == partyModeId && th.Name == CConfig.Config.Theme.Theme); if (theme != null) { if (theme.Load()) { - CurrentThemes.Add(partyModeID, theme); + CurrentThemes.Add(partyModeId, theme); return true; } + theme.Unload(); CLog.Error("Failed to load theme " + theme + " for partymode! Removing...", true); _Themes.Remove(theme); } - theme = _Themes.First(th => th.PartyModeID == partyModeID && th.Name == CSettings.DefaultName); + + theme = _Themes.First(th => th.PartyModeId == partyModeId && th.Name == CSettings.DefaultName); if (theme.Load()) { - CurrentThemes.Add(partyModeID, theme); + CurrentThemes.Add(partyModeId, theme); return true; } + CLog.Error("Failed to load default theme for partymode! Unloading partymode!", true); - foreach (CPartyTheme th in _Themes.Where(th => th.PartyModeID == partyModeID)) + foreach (CPartyTheme th in _Themes.Where(th => th.PartyModeId == partyModeId)) + { th.Unload(); - _Themes.RemoveAll(th => th.PartyModeID == partyModeID); + } + + _Themes.RemoveAll(th => th.PartyModeId == partyModeId); return false; } @@ -129,31 +145,42 @@ namespace Vocaluxe.Base.ThemeSystem public static void ReloadSkin() { - foreach (CTheme theme in CurrentThemes.Values) + foreach (var theme in CurrentThemes.Values) + { theme.ReloadSkin(); + } } - public static bool ReadThemesFromFolder(string path, int partyModeID) + public static bool ReadThemesFromFolder(string path, int partyModeId) { - IEnumerable files = CHelper.ListFiles(path, "*.xml", false, true); + var files = CHelper.ListFiles(path, "*.xml", false, true); - List newThemes = new List(); - foreach (string file in files) + var newThemes = new List(); + foreach (var file in files) { CTheme theme; - if (partyModeID < 0) + if (partyModeId < 0) + { theme = new CBaseTheme(file); + } else - theme = new CPartyTheme(file, partyModeID); + { + theme = new CPartyTheme(file, partyModeId); + } + if (theme.Init()) + { newThemes.Add(theme); + } } + if (newThemes.Count == 0) { CLog.Error("No valid themes found in " + path); return false; } - if (partyModeID >= 0 && newThemes.Count(th => th.Name == CSettings.DefaultName) == 0) + + if (partyModeId >= 0 && newThemes.Count(th => th.Name == CSettings.DefaultName) == 0) { CLog.Error("Partymode misses default theme in " + path); return false; @@ -163,33 +190,42 @@ namespace Vocaluxe.Base.ThemeSystem return true; } - public static string GetThemeScreensPath(int partyModeID) + public static string GetThemeScreensPath(int partyModeId) { CTheme theme; - return CurrentThemes.TryGetValue(partyModeID, out theme) ? theme.GetScreenPath() : null; + return CurrentThemes.TryGetValue(partyModeId, out theme) ? theme.GetScreenPath() : null; } - private static void _LogMissingElement(int partyModeID, string elType, string elName) + private static void _LogMissingElement(int partyModeId, string elType, string elName) { - CLog.Error("Skin " + CurrentThemes[partyModeID].CurrentSkin + " is missing the " + elType + " \"" + elName + "\"! Expect visual problems!"); + CLog.Error("Skin " + CurrentThemes[partyModeId].CurrentSkin + " is missing the " + elType + " \"" + elName + "\"! Expect visual problems!"); } - public static CTextureRef GetSkinTexture(string textureName, int partyModeID) + public static CTextureRef GetSkinTexture(string textureName, int partyModeId) { - if (String.IsNullOrEmpty(textureName)) + if (string.IsNullOrEmpty(textureName)) + { return null; - CTextureRef texture = CurrentThemes[partyModeID].CurrentSkin.GetTexture(textureName); + } + + var texture = CurrentThemes[partyModeId].CurrentSkin.GetTexture(textureName); if (texture == null) - _LogMissingElement(partyModeID, "texture", textureName); + { + _LogMissingElement(partyModeId, "texture", textureName); + } + return texture; } - public static CVideoStream GetSkinVideo(string videoName, int partyModeID, bool loop = true) + public static CVideoStream GetSkinVideo(string videoName, int partyModeId, bool loop = true) { - Debug.Assert(!String.IsNullOrEmpty(videoName)); - CVideoStream video = CurrentThemes[partyModeID].CurrentSkin.GetVideo(videoName, loop); + Debug.Assert(!string.IsNullOrEmpty(videoName)); + var video = CurrentThemes[partyModeId].CurrentSkin.GetVideo(videoName, loop); if (video == null) - _LogMissingElement(partyModeID, "video", videoName); + { + _LogMissingElement(partyModeId, "video", videoName); + } + return video; } @@ -198,14 +234,15 @@ namespace Vocaluxe.Base.ThemeSystem return ((CBaseTheme)CurrentThemes[-1]).CursorTheme; } - public static bool GetColor(string colorName, int partyModeID, out SColorF color) + public static bool GetColor(string colorName, int partyModeId, out SColorF color) { - Debug.Assert(!String.IsNullOrEmpty(colorName)); - if (!CurrentThemes[partyModeID].CurrentSkin.GetColor(colorName, out color)) + Debug.Assert(!string.IsNullOrEmpty(colorName)); + if (!CurrentThemes[partyModeId].CurrentSkin.GetColor(colorName, out color)) { - _LogMissingElement(partyModeID, "color", colorName); + _LogMissingElement(partyModeId, "color", colorName); return false; } + return true; } @@ -213,7 +250,10 @@ namespace Vocaluxe.Base.ThemeSystem { SColorF color; if (!GetColor("Player" + playerNr, -1, out color)) + { CLog.Error("Invalid color requested: Color for player " + playerNr + ". Expect visual problems!", true); + } + return color; } } diff --git a/Vocaluxe/Base/XmlStructs.cs b/Vocaluxe/Base/XmlStructs.cs index 12046975..8a06d5ed 100644 --- a/Vocaluxe/Base/XmlStructs.cs +++ b/Vocaluxe/Base/XmlStructs.cs @@ -17,7 +17,6 @@ using System.Collections.Generic; using System.ComponentModel; -using System.Diagnostics; using System.Xml.Serialization; using Vocaluxe.Base.Fonts; using VocaluxeLib; @@ -36,7 +35,8 @@ namespace Vocaluxe.Base struct SThemeCursor { - [XmlElement("Skin")] public string SkinName; + [XmlElement("Skin")] + public string SkinName; public float W; public float H; @@ -48,13 +48,15 @@ namespace Vocaluxe.Base { public int ThemeSystemVersion; public SInfo Info; - [XmlArray, DefaultValue(null)] public SFontFamily[] Fonts; + [XmlArray, DefaultValue(null)] + public SFontFamily[] Fonts; public SThemeCursor? Cursor; } struct SDefaultFonts { - [XmlArray] public SFontFamily[] Fonts; + [XmlArray] + public SFontFamily[] Fonts; } /// @@ -64,10 +66,13 @@ namespace Vocaluxe.Base struct SFontFamily { public string Name; - [XmlIgnore] public int PartyModeID; - [XmlIgnore] public string ThemeName; + [XmlIgnore] + public int PartyModeId; + [XmlIgnore] + public string ThemeName; - [XmlNormalized] public float Outline; //0..1, 0=not outline 1=100% outline + [XmlNormalized] + public float Outline; //0..1, 0=not outline 1=100% outline public SColorF OutlineColor; public string Folder; @@ -77,10 +82,14 @@ namespace Vocaluxe.Base public string FileItalic; public string FileBoldItalic; - [XmlIgnore] public CFontStyle Normal; - [XmlIgnore] public CFontStyle Italic; - [XmlIgnore] public CFontStyle Bold; - [XmlIgnore] public CFontStyle BoldItalic; + [XmlIgnore] + public CFontStyle Normal; + [XmlIgnore] + public CFontStyle Italic; + [XmlIgnore] + public CFontStyle Bold; + [XmlIgnore] + public CFontStyle BoldItalic; public void Dispose() { @@ -102,13 +111,15 @@ namespace Vocaluxe.Base struct SPlaylistInfo { - [XmlElement("PlaylistName")] public string Name; + [XmlElement("PlaylistName")] + public string Name; } struct SPlaylist { public SPlaylistInfo Info; - [XmlArray] public SPlaylistSong[] Songs; + [XmlArray] + public SPlaylistSong[] Songs; } #region Partymode @@ -119,17 +130,22 @@ namespace Vocaluxe.Base public string Author; public string Folder; public string PartyModeFile; - [XmlAltName("PartyModeVersionMajor")] public int VersionMajor; - [XmlAltName("PartyModeVersionMinor")] public int VersionMinor; + [XmlAltName("PartyModeVersionMajor")] + public int VersionMajor; + [XmlAltName("PartyModeVersionMinor")] + public int VersionMinor; public string TargetAudience; - [XmlIgnore] public IPartyModeInfo ExtInfo; + [XmlIgnore] + public IPartyModeInfo ExtInfo; } struct SPartyMode { public int PartyModeSystemVersion; - [XmlArray("PartyScreens"), XmlArrayItem("ScreenFile")] public List ScreenFiles; - [XmlIgnore] public IPartyMode PartyMode; + [XmlArray("PartyScreens"), XmlArrayItem("ScreenFile")] + public List ScreenFiles; + [XmlIgnore] + public IPartyMode PartyMode; public SPartyModeInfos Info; } #endregion Partymode diff --git a/Vocaluxe/COSFunctions.cs b/Vocaluxe/COSFunctions.cs index 91f451a9..063c21cb 100644 --- a/Vocaluxe/COSFunctions.cs +++ b/Vocaluxe/COSFunctions.cs @@ -36,9 +36,12 @@ namespace Vocaluxe public static void AddEnvironmentPath(string path) { - string newPath = Environment.GetEnvironmentVariable("PATH") ?? string.Empty; + var newPath = Environment.GetEnvironmentVariable("PATH") ?? string.Empty; if (newPath.Length > 0) + { newPath += ";"; + } + newPath += path; Environment.SetEnvironmentVariable("PATH", newPath); diff --git a/Vocaluxe/CProgrammHelper.cs b/Vocaluxe/CProgrammHelper.cs index f7d865c7..1413da92 100644 --- a/Vocaluxe/CProgrammHelper.cs +++ b/Vocaluxe/CProgrammHelper.cs @@ -15,7 +15,6 @@ // along with Vocaluxe. If not, see . #endregion -using System; using System.IO; using System.Reflection; using System.Security; @@ -32,32 +31,44 @@ namespace Vocaluxe { private static bool _CheckUninstallKey(string name, string key) { - using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(key)) + using (var rk = Registry.LocalMachine.OpenSubKey(key)) { if (rk == null) - throw new SecurityException(); - foreach (string skName in rk.GetSubKeyNames()) { - using (RegistryKey sk = rk.OpenSubKey(skName)) + throw new SecurityException(); + } + + foreach (var skName in rk.GetSubKeyNames()) + { + using (var sk = rk.OpenSubKey(skName)) { if (sk == null || sk.GetValue("DisplayName") == null) + { continue; - string displayName = sk.GetValue("DisplayName").ToString().ToLower(); + } + + var displayName = sk.GetValue("DisplayName").ToString().ToLower(); if (displayName.Equals(name) || displayName.StartsWith(name) || name.StartsWith(displayName)) + { return true; + } } } } + return false; } private static bool _KeyExists(string key) { - using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(key)) + using (var rk = Registry.LocalMachine.OpenSubKey(key)) { if (rk != null) + { return true; + } } + return false; } @@ -86,47 +97,55 @@ namespace Vocaluxe const string baseKey = @"SOFTWARE\Microsoft\VisualStudio\14.0\VC\Runtimes\"; const string wow6432BaseKey = @"SOFTWARE\Wow6432Node\Microsoft\VisualStudio\14.0\VC\Runtimes\"; - #if ARCH_X64 +#if ARCH_X64 string[] arches = { "x64" }; - #elif ARCH_X86 +#elif ARCH_X86 string[] arches = { "x86" }; - #else +#else string[] arches = { "x86", "x64" }; - #endif +#endif - foreach (string arch in arches) - { - using (RegistryKey rk = Registry.LocalMachine.OpenSubKey(baseKey + arch) ?? - Registry.LocalMachine.OpenSubKey(wow6432BaseKey + arch)) + foreach (var arch in arches) { - if (rk == null) - continue; + using (var rk = Registry.LocalMachine.OpenSubKey(baseKey + arch) ?? + Registry.LocalMachine.OpenSubKey(wow6432BaseKey + arch)) + { + if (rk == null) + { + continue; + } - object installed = rk.GetValue("Installed"); - if (installed == null) - continue; + var installed = rk.GetValue("Installed"); + if (installed == null) + { + continue; + } - int installedValue; - if (int.TryParse(installed.ToString(), out installedValue) && installedValue == 1) - return true; + int installedValue; + if (int.TryParse(installed.ToString(), out installedValue) && installedValue == 1) + { + return true; + } + } } - } - return false; + return false; } private static void _EnsureDataFolderExists() { - if (!Directory.Exists(CSettings.DataFolder)) { + if (!Directory.Exists(CSettings.DataFolder)) + { Directory.CreateDirectory(CSettings.DataFolder); // copy default profiles to DataFolder instead of adding ProgramFolder to CConfig.ProfileFolders // because we want to be able to edit them, but might not have permission to write to ProgramFolder - string profilePath = Path.Combine(CSettings.DataFolder, CSettings.FolderNameProfiles); + var profilePath = Path.Combine(CSettings.DataFolder, CSettings.FolderNameProfiles); Directory.CreateDirectory(profilePath); - DirectoryInfo defaultProfileDir = new DirectoryInfo(Path.Combine(CSettings.ProgramFolder, CSettings.FolderNameProfiles)); - FileInfo[] files = defaultProfileDir.GetFiles(); - foreach (FileInfo file in files) { - string newPath = Path.Combine(profilePath, file.Name); + var defaultProfileDir = new DirectoryInfo(Path.Combine(CSettings.ProgramFolder, CSettings.FolderNameProfiles)); + var files = defaultProfileDir.GetFiles(); + foreach (var file in files) + { + var newPath = Path.Combine(profilePath, file.Name); file.CopyTo(newPath, false); } } @@ -143,13 +162,13 @@ namespace Vocaluxe } if (!_IsVC2015To2022Installed()) - { - CLog.Fatal( - "VC++ 2015-2022 Redistributables are missing. Please install them first.\r\n" + - "Download x64: https://aka.ms/vc14/vc_redist.x64.exe\r\n" + - "Download x86: https://aka.ms/vc14/vc_redist.x86.exe"); - return false; - } + { + CLog.Fatal( + "VC++ 2015-2022 Redistributables are missing. Please install them first.\r\n" + + "Download x64: https://aka.ms/vc14/vc_redist.x64.exe\r\n" + + "Download x86: https://aka.ms/vc14/vc_redist.x86.exe"); + return false; + } #endif //TODO: check for dependencies on linux? return true; @@ -161,7 +180,7 @@ namespace Vocaluxe string path = "x86"; #endif #if ARCH_X64 - string path = "x64"; + var path = "x64"; #endif path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + Path.DirectorySeparatorChar + path; COSFunctions.AddEnvironmentPath(path); @@ -170,4 +189,4 @@ namespace Vocaluxe #endif } } -} +} \ No newline at end of file diff --git a/Vocaluxe/CSplashScreen.cs b/Vocaluxe/CSplashScreen.cs index 30f1f9b2..3360fdf9 100644 --- a/Vocaluxe/CSplashScreen.cs +++ b/Vocaluxe/CSplashScreen.cs @@ -30,7 +30,7 @@ namespace Vocaluxe public CSplashScreen() { - string path = Path.Combine(CSettings.ProgramFolder, CSettings.FolderNameGraphics, CSettings.FileNameLogo); + var path = Path.Combine(CSettings.ProgramFolder, CSettings.FolderNameGraphics, CSettings.FileNameLogo); if (File.Exists(path)) { try @@ -44,7 +44,9 @@ namespace Vocaluxe } } else + { CLog.Error("Can't find " + path); + } path = Path.Combine(CSettings.ProgramFolder, CSettings.FileNameIcon); if (File.Exists(path)) @@ -59,7 +61,9 @@ namespace Vocaluxe } } else + { CLog.Error("Can't find " + path); + } SetStyle(ControlStyles.SupportsTransparentBackColor, true); BackColor = Color.Transparent; @@ -82,14 +86,16 @@ namespace Vocaluxe set { base.BackColor = value; } } - protected override void OnPaint(PaintEventArgs e) {} + protected override void OnPaint(PaintEventArgs e) { } protected override void OnPaintBackground(PaintEventArgs e) { if (_Logo == null) + { return; + } - Graphics g = e.Graphics; + var g = e.Graphics; g.DrawImage(_Logo, new Rectangle(0, 0, Width, Height)); } } diff --git a/Vocaluxe/GameModes/CGameMode.cs b/Vocaluxe/GameModes/CGameMode.cs index 73f61fdf..66bea98f 100644 --- a/Vocaluxe/GameModes/CGameMode.cs +++ b/Vocaluxe/GameModes/CGameMode.cs @@ -23,16 +23,17 @@ namespace Vocaluxe.GameModes abstract class CGameMode : IGameMode { private CSong _LastSong; - private int _LastSongID = -1; + private int _LastSongId = -1; - public CSong GetSong(int songID) + public CSong GetSong(int songId) { - if (songID != _LastSongID) + if (songId != _LastSongId) { - CSong song = CSongs.GetSong(songID); + var song = CSongs.GetSong(songId); _LastSong = _PrepareSong(song); - _LastSongID = songID; + _LastSongId = songId; } + return _LastSong; } diff --git a/Vocaluxe/GameModes/CGameModes.cs b/Vocaluxe/GameModes/CGameModes.cs index a7e7d4b2..1c164e33 100644 --- a/Vocaluxe/GameModes/CGameModes.cs +++ b/Vocaluxe/GameModes/CGameModes.cs @@ -29,21 +29,27 @@ namespace Vocaluxe.GameModes public static void Init() { _GameModes = new Dictionary - { - {EGameMode.TR_GAMEMODE_NORMAL, new CGameModeNormal()}, - {EGameMode.TR_GAMEMODE_DUET, new CGameModeDuet()}, - {EGameMode.TR_GAMEMODE_SHORTSONG, new CGameModeShort()}, - {EGameMode.TR_GAMEMODE_MEDLEY, new CGameModeMedley()} - }; + { + { EGameMode.TR_GAMEMODE_NORMAL, new CGameModeNormal() }, + { EGameMode.TR_GAMEMODE_DUET, new CGameModeDuet() }, + { EGameMode.TR_GAMEMODE_SHORTSONG, new CGameModeShort() }, + { EGameMode.TR_GAMEMODE_MEDLEY, new CGameModeMedley() } + }; } public static IGameMode Get(EGameMode gameMode) { if (_GameModes == null) + { return null; + } + IGameMode result; if (!_GameModes.TryGetValue(gameMode, out result)) + { result = _GameModes[EGameMode.TR_GAMEMODE_NORMAL]; + } + return result; } } @@ -52,7 +58,7 @@ namespace Vocaluxe.GameModes { protected override CSong _PrepareSong(CSong song) { - return (song.IsGameModeAvailable(EGameMode.TR_GAMEMODE_NORMAL)) ? song : null; + return song.IsGameModeAvailable(EGameMode.TR_GAMEMODE_NORMAL) ? song : null; } } @@ -60,7 +66,7 @@ namespace Vocaluxe.GameModes { protected override CSong _PrepareSong(CSong song) { - return (song.IsGameModeAvailable(EGameMode.TR_GAMEMODE_DUET)) ? song : null; + return song.IsGameModeAvailable(EGameMode.TR_GAMEMODE_DUET) ? song : null; } } @@ -69,8 +75,11 @@ namespace Vocaluxe.GameModes protected override CSong _PrepareSong(CSong song) { if (!song.IsGameModeAvailable(EGameMode.TR_GAMEMODE_SHORTSONG)) + { return null; - var newSong = new CSong(song) {Finish = CGame.GetTimeFromBeats(song.ShortEnd.EndBeat, song.BPM) + CSettings.DefaultMedleyFadeOutTime + song.Gap}; + } + + var newSong = new CSong(song) { End = CGame.GetTimeFromBeats(song.ShortEnd.EndBeat, song.Bpm) + CSettings.DefaultMedleyFadeOutTime + song.Gap }; // set lines to short mode newSong.Notes.SetMedley(0, song.ShortEnd.EndBeat); @@ -83,12 +92,17 @@ namespace Vocaluxe.GameModes protected override CSong _PrepareSong(CSong song) { if (!song.IsGameModeAvailable(EGameMode.TR_GAMEMODE_MEDLEY)) + { return null; - var newSong = new CSong(song) {Start = CGame.GetTimeFromBeats(song.Medley.StartBeat, song.BPM) - song.Medley.FadeInTime + song.Gap}; - if (newSong.Start < 0f) - newSong.Start = 0f; + } - newSong.Finish = CGame.GetTimeFromBeats(song.Medley.EndBeat, song.BPM) + song.Medley.FadeOutTime + song.Gap; + var newSong = new CSong(song) { Start = CGame.GetTimeFromBeats(song.Medley.StartBeat, song.Bpm) - song.Medley.FadeInTime + song.Gap }; + if (newSong.Start < 0f) + { + newSong.Start = 0f; + } + + newSong.End = CGame.GetTimeFromBeats(song.Medley.EndBeat, song.Bpm) + song.Medley.FadeOutTime + song.Gap; // set lines to medley mode newSong.Notes.SetMedley(song.Medley.StartBeat, song.Medley.EndBeat); diff --git a/Vocaluxe/GameModes/IGameMode.cs b/Vocaluxe/GameModes/IGameMode.cs index a6ed88f6..87c560e4 100644 --- a/Vocaluxe/GameModes/IGameMode.cs +++ b/Vocaluxe/GameModes/IGameMode.cs @@ -21,6 +21,6 @@ namespace Vocaluxe.GameModes { interface IGameMode { - CSong GetSong(int songID); + CSong GetSong(int songId); } } \ No newline at end of file diff --git a/Vocaluxe/Lib/Database/CCoverDB.cs b/Vocaluxe/Lib/Database/CCoverDB.cs index 11c0cbf8..a00e5d36 100644 --- a/Vocaluxe/Lib/Database/CCoverDB.cs +++ b/Vocaluxe/Lib/Database/CCoverDB.cs @@ -16,15 +16,14 @@ #endregion using System; -using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; +using Microsoft.Data.Sqlite; using Vocaluxe.Base; using VocaluxeLib; using VocaluxeLib.Draw; using VocaluxeLib.Log; -using Microsoft.Data.Sqlite; namespace Vocaluxe.Lib.Database { @@ -32,20 +31,28 @@ namespace Vocaluxe.Lib.Database { private SqliteTransaction _TransactionCover; - public CCoverDB(string filePath) : base(filePath) {} + public CCoverDB(string filePath) : base(filePath) { } public override bool Init() { lock (_Mutex) { if (!base.Init()) + { return false; + } if (_Version < 0) + { return _CreateCoverDB(); + } + if (_Version < CSettings.DatabaseCoverVersion) + { throw new NotImplementedException("Upgrading of cover DB not implemented"); + } } + return true; } @@ -63,7 +70,10 @@ namespace Vocaluxe.Lib.Database public bool GetCover(string coverPath, ref CTextureRef tex, int maxSize) { if (_Connection == null) + { return false; + } + if (!File.Exists(coverPath)) { CLog.Error("Can't find File: " + coverPath); @@ -74,28 +84,34 @@ namespace Vocaluxe.Lib.Database { //Double check here because we may have just closed our connection if (_Connection == null) + { return false; + } + using (var command = new SqliteCommand()) { command.Connection = _Connection; // If we have an open transaction on this connection, all commands must use it. if (_TransactionCover != null) + { command.Transaction = _TransactionCover; + } + command.CommandText = "SELECT id, width, height FROM Cover WHERE [Path] = @path"; command.Parameters.Clear(); command.Parameters.AddWithValue("@path", coverPath); - SqliteDataReader reader = command.ExecuteReader(); + var reader = command.ExecuteReader(); if (reader != null && reader.HasRows) { reader.Read(); - int id = reader.GetInt32(0); - int w = reader.GetInt32(1); - int h = reader.GetInt32(2); + var id = reader.GetInt32(0); + var w = reader.GetInt32(1); + var h = reader.GetInt32(2); reader.Close(); - command.CommandText = "SELECT Data FROM CoverData WHERE CoverID = @id"; + command.CommandText = "SELECT Data FROM CoverData WHERE CoverId = @id"; command.Parameters.Clear(); command.Parameters.AddWithValue("@id", id); reader = command.ExecuteReader(); @@ -103,33 +119,39 @@ namespace Vocaluxe.Lib.Database if (reader.HasRows) { reader.Read(); - byte[] data2 = _GetBytes(reader); + var data2 = _GetBytes(reader); reader.Dispose(); tex = CDraw.EnqueueTexture(w, h, data2); return true; } + command.CommandText = "DELETE FROM Cover WHERE id = @id"; command.Parameters.Clear(); command.Parameters.AddWithValue("@id", id); command.ExecuteNonQuery(); } + if (reader != null) + { reader.Close(); + } } } // At this point we do not have a mathing entry in the CoverDB (either no Data found and deleted or nothing at all) // We break out of the lock to do the bitmap loading and resizing here to allow multithreaded loading - Bitmap origin = CHelper.LoadBitmap(coverPath); + var origin = CHelper.LoadBitmap(coverPath); if (origin == null) + { return false; + } - Size size = origin.GetSize(); + var size = origin.GetSize(); if (size.Width > maxSize || size.Height > maxSize) { size = CHelper.FitInBounds(new SRectF(0, 0, maxSize, maxSize, 0), (float)size.Width / size.Height, EAspect.LetterBox).SizeI; - Bitmap tmp = origin.Resize(size); + var tmp = origin.Resize(size); origin.Dispose(); origin = tmp; } @@ -139,7 +161,7 @@ namespace Vocaluxe.Lib.Database try { data = new byte[size.Width * size.Height * 4]; - BitmapData bmpData = origin.LockBits(origin.GetRect(), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); + var bmpData = origin.LockBits(origin.GetRect(), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); Marshal.Copy(bmpData.Scan0, data, 0, data.Length); origin.UnlockBits(bmpData); } @@ -154,9 +176,15 @@ namespace Vocaluxe.Lib.Database { //Double check here because we may have just closed our connection if (_Connection == null) + { return false; + } + if (_TransactionCover == null) + { _TransactionCover = _Connection.BeginTransaction(); + } + using (var command = new SqliteCommand()) { command.Connection = _Connection; @@ -171,14 +199,14 @@ namespace Vocaluxe.Lib.Database command.CommandText = "SELECT id FROM Cover WHERE [Path] = @path"; command.Parameters.Clear(); command.Parameters.AddWithValue("@path", coverPath); - SqliteDataReader reader = command.ExecuteReader(); + var reader = command.ExecuteReader(); if (reader != null) { reader.Read(); - int id = reader.GetInt32(0); + var id = reader.GetInt32(0); reader.Dispose(); - command.CommandText = "INSERT INTO CoverData (CoverID, Data) VALUES (@id, @data)"; + command.CommandText = "INSERT INTO CoverData (CoverId, Data) VALUES (@id, @data)"; command.Parameters.Clear(); command.Parameters.AddWithValue("@id", id); command.Parameters.AddWithValue("@data", data); @@ -187,6 +215,7 @@ namespace Vocaluxe.Lib.Database } } } + return false; } @@ -204,7 +233,10 @@ namespace Vocaluxe.Lib.Database private void _CommitCovers() { if (_TransactionCover == null) + { return; + } + _TransactionCover.Commit(); _TransactionCover.Dispose(); _TransactionCover = null; @@ -230,7 +262,7 @@ namespace Vocaluxe.Lib.Database command.ExecuteNonQuery(); command.CommandText = "CREATE TABLE IF NOT EXISTS CoverData ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " + - "CoverID INTEGER NOT NULL, Data BLOB NOT NULL);"; + "CoverId INTEGER NOT NULL, Data BLOB NOT NULL);"; command.ExecuteNonQuery(); } } @@ -239,6 +271,7 @@ namespace Vocaluxe.Lib.Database CLog.Error("Error creating Cover DB " + e); return false; } + return true; } } diff --git a/Vocaluxe/Lib/Database/CDatabaseBase.cs b/Vocaluxe/Lib/Database/CDatabaseBase.cs index 0c8a57a1..0d5bd9a0 100644 --- a/Vocaluxe/Lib/Database/CDatabaseBase.cs +++ b/Vocaluxe/Lib/Database/CDatabaseBase.cs @@ -41,7 +41,10 @@ namespace Vocaluxe.Lib.Database lock (_Mutex) { if (_Connection != null) + { return false; + } + _Connection = new SqliteConnection("Data Source=" + _FilePath); try { @@ -62,17 +65,24 @@ namespace Vocaluxe.Lib.Database { reader = command.ExecuteReader(); } - catch (Exception) {} + catch (Exception) { } if (reader == null || !reader.Read() || reader.FieldCount == 0) + { _Version = -1; + } else + { _Version = reader.GetInt32(0); + } if (reader != null) + { reader.Dispose(); + } } } + return true; } @@ -115,6 +125,7 @@ namespace Vocaluxe.Lib.Database stream.Write(buffer, 0, bytesRead); fieldOffset += bytesRead; } + return stream.ToArray(); } } diff --git a/Vocaluxe/Lib/Database/CHighscoreDB.cs b/Vocaluxe/Lib/Database/CHighscoreDB.cs index 2809902b..c284eb61 100644 --- a/Vocaluxe/Lib/Database/CHighscoreDB.cs +++ b/Vocaluxe/Lib/Database/CHighscoreDB.cs @@ -20,11 +20,10 @@ using System.Collections.Generic; using System.IO; using System.Text; using Community.CsharpSqlite; +using Microsoft.Data.Sqlite; using Vocaluxe.Base; using VocaluxeLib; using VocaluxeLib.Log; -using VocaluxeLib.Songs; -using Microsoft.Data.Sqlite; namespace Vocaluxe.Lib.Database { @@ -38,11 +37,11 @@ namespace Vocaluxe.Lib.Database public string Str2; } - public CHighscoreDB(string filePath) : base(filePath) {} + public CHighscoreDB(string filePath) : base(filePath) { } public override bool Init() { - string oldDBFilePath = Path.Combine(CSettings.DataFolder, CSettings.FileNameOldHighscoreDB); + var oldDBFilePath = Path.Combine(CSettings.DataFolder, CSettings.FileNameOldHighscoreDB); if (File.Exists(oldDBFilePath)) { if (File.Exists(_FilePath)) @@ -52,11 +51,13 @@ namespace Vocaluxe.Lib.Database CLog.Fatal("Cannot init Highscore DB: Error opening old database: {DBFile}" + CLog.Params(oldDBFilePath)); return false; } + if (!_CreateOrConvert(_FilePath)) { CLog.Fatal("Cannot init Highscore DB: Error opening database: {DBFile}", CLog.Params(_FilePath)); return false; } + if (!_ImportData(oldDBFilePath)) { CLog.Fatal("Cannot init Highscore DB: Error importing data"); @@ -72,6 +73,7 @@ namespace Vocaluxe.Lib.Database return false; } } + File.Delete(oldDBFilePath); } else if (!_CreateOrConvert(_FilePath)) @@ -79,6 +81,7 @@ namespace Vocaluxe.Lib.Database CLog.Fatal("Cannot init Highscore DB: Error opening database: {DBFile}", CLog.Params(_FilePath)); return false; } + return true; } @@ -87,11 +90,11 @@ namespace Vocaluxe.Lib.Database //Do nothing } - public bool GetDataBaseSongInfos(string artist, string title, out int numPlayed, out DateTime dateAdded, out int highscoreID) + public bool GetDataBaseSongInfos(string artist, string title, out int numPlayed, out DateTime dateAdded, out int highscoreId) { string sArtist; string sTitle; - int songID; + int songId; using (var connection = new SqliteConnection()) { connection.ConnectionString = "Data Source=" + _FilePath; @@ -100,19 +103,20 @@ namespace Vocaluxe.Lib.Database { connection.Open(); } - catch (Exception) {} + catch (Exception) { } using (var command = new SqliteCommand()) { command.Connection = connection; - songID = _GetDataBaseSongID(artist, title, 0, command); - highscoreID = songID; + songId = _GetDataBaseSongId(artist, title, 0, command); + highscoreId = songId; } } - return _GetDataBaseSongInfos(songID, out sArtist, out sTitle, out numPlayed, out dateAdded, _FilePath); + + return _GetDataBaseSongInfos(songId, out sArtist, out sTitle, out numPlayed, out dateAdded, _FilePath); } - public void IncreaseSongCounter(int dataBaseSongID) + public void IncreaseSongCounter(int dataBaseSongId) { using (var connection = new SqliteConnection()) { @@ -122,18 +126,18 @@ namespace Vocaluxe.Lib.Database { connection.Open(); } - catch (Exception) {} + catch (Exception) { } using (var command = new SqliteCommand()) { command.Connection = connection; - _IncreaseSongCounter(dataBaseSongID, command); + _IncreaseSongCounter(dataBaseSongId, command); } } } public int AddScore(string playerName, int score, int lineNr, long date, int medley, int duet, int shortSong, int difficulty, - string artist, string title, int numPlayed, string filePath) + string artist, string title, int numPlayed, string filePath) { using (var connection = new SqliteConnection()) { @@ -151,8 +155,8 @@ namespace Vocaluxe.Lib.Database using (var command = new SqliteCommand()) { command.Connection = connection; - int dataBaseSongID = _GetDataBaseSongID(artist, title, numPlayed, command); - int result = _AddScore(playerName, score, lineNr, date, medley, duet, shortSong, difficulty, dataBaseSongID, command); + var dataBaseSongId = _GetDataBaseSongId(artist, title, numPlayed, command); + var result = _AddScore(playerName, score, lineNr, date, medley, duet, shortSong, difficulty, dataBaseSongId, command); return result; } } @@ -173,9 +177,9 @@ namespace Vocaluxe.Lib.Database return -1; } - int medley = 0; - int duet = 0; - int shortSong = 0; + var medley = 0; + var duet = 0; + var shortSong = 0; switch (player.GameMode) { case EGameMode.TR_GAMEMODE_MEDLEY: @@ -192,25 +196,25 @@ namespace Vocaluxe.Lib.Database using (var command = new SqliteCommand()) { command.Connection = connection; - int dataBaseSongID = CSongs.GetSong(player.SongID).DataBaseSongID; - return _AddScore(CProfiles.GetPlayerName(player.ProfileID), (int)Math.Round(player.Points), player.VoiceNr, player.DateTicks, medley, - duet, shortSong, (int)CProfiles.GetDifficulty(player.ProfileID), dataBaseSongID, command); + var dataBaseSongId = CSongs.GetSong(player.SongId).DataBaseSongId; + return _AddScore(CProfiles.GetPlayerName(player.ProfileId), (int)Math.Round(player.Points), player.VoiceNr, player.DateTicks, medley, + duet, shortSong, (int)CProfiles.GetDifficulty(player.ProfileId), dataBaseSongId, command); } } } private int _AddScore(string playerName, int score, int lineNr, long date, int medley, int duet, int shortSong, int difficulty, - int dataBaseSongID, SqliteCommand command) + int dataBaseSongId, SqliteCommand command) { - int lastInsertID = -1; + var lastInsertId = -1; - if (dataBaseSongID >= 0) + if (dataBaseSongId >= 0) { - command.CommandText = "SELECT id FROM Scores WHERE SongID = @SongID AND PlayerName = @PlayerName AND Score = @Score AND " + + command.CommandText = "SELECT id FROM Scores WHERE SongId = @SongId AND PlayerName = @PlayerName AND Score = @Score AND " + "LineNr = @LineNr AND Date = @Date AND Medley = @Medley AND Duet = @Duet AND ShortSong = @ShortSong AND Difficulty = @Difficulty"; command.Parameters.Clear(); - command.Parameters.AddWithValue("@SongID", dataBaseSongID); - command.Parameters.AddWithValue("@PlayerName", playerName ?? String.Empty); + command.Parameters.AddWithValue("@SongId", dataBaseSongId); + command.Parameters.AddWithValue("@PlayerName", playerName ?? string.Empty); command.Parameters.AddWithValue("@Score", score); command.Parameters.AddWithValue("@LineNr", lineNr); command.Parameters.AddWithValue("@Date", date); @@ -224,22 +228,26 @@ namespace Vocaluxe.Lib.Database { reader = command.ExecuteReader(); } - catch (Exception) {} + catch (Exception) { } if (reader != null && reader.HasRows) { if (reader.Read()) + { return reader.GetInt32(0); + } } if (reader != null) + { reader.Dispose(); + } - command.CommandText = "INSERT INTO Scores (SongID, PlayerName, Score, LineNr, Date, Medley, Duet, ShortSong, Difficulty) " + - "VALUES (@SongID, @PlayerName, @Score, @LineNr, @Date, @Medley, @Duet, @ShortSong, @Difficulty)"; + command.CommandText = "INSERT INTO Scores (SongId, PlayerName, Score, LineNr, Date, Medley, Duet, ShortSong, Difficulty) " + + "VALUES (@SongId, @PlayerName, @Score, @LineNr, @Date, @Medley, @Duet, @ShortSong, @Difficulty)"; command.Parameters.Clear(); - command.Parameters.AddWithValue("@SongID", dataBaseSongID); - command.Parameters.AddWithValue("@PlayerName", playerName ?? String.Empty); + command.Parameters.AddWithValue("@SongId", dataBaseSongId); + command.Parameters.AddWithValue("@PlayerName", playerName ?? string.Empty); command.Parameters.AddWithValue("@Score", score); command.Parameters.AddWithValue("@LineNr", lineNr); command.Parameters.AddWithValue("@Date", date); @@ -257,15 +265,18 @@ namespace Vocaluxe.Lib.Database if (reader != null && reader.HasRows) { while (reader.Read()) - lastInsertID = reader.GetInt32(0); + { + lastInsertId = reader.GetInt32(0); + } + reader.Dispose(); } } - return lastInsertID; + return lastInsertId; } - public List LoadScore(int songID, EGameMode gameMode, EHighscoreStyle style) + public List LoadScore(int songId, EGameMode gameMode, EHighscoreStyle style) { var scores = new List(); using (var connection = new SqliteConnection()) @@ -284,9 +295,9 @@ namespace Vocaluxe.Lib.Database using (var command = new SqliteCommand()) { command.Connection = connection; - int medley = 0; - int duet = 0; - int shortSong = 0; + var medley = 0; + var duet = 0; + var shortSong = 0; switch (gameMode) { case EGameMode.TR_GAMEMODE_MEDLEY: @@ -300,129 +311,137 @@ namespace Vocaluxe.Lib.Database break; } - int dataBaseSongID = _GetDataBaseSongID(songID, command); - if (dataBaseSongID < 0) + var dataBaseSongId = _GetDataBaseSongId(songId, command); + if (dataBaseSongId < 0) + { return scores; + } switch (style) { case EHighscoreStyle.TR_CONFIG_HIGHSCORE_LIST_BEST: command.CommandText = "SELECT os.PlayerName, os.Score, os.Date, os.Difficulty, os.LineNr, os.id " + - "FROM Scores os " + - "INNER JOIN ( " + - "SELECT sc.PlayerName, sc.Score, sc.Difficulty, sc.LineNr, MIN(sc.Date) AS Date " + - "FROM Scores sc " + - "INNER JOIN ( " + - "SELECT Playername, MAX(Score) AS Score, Difficulty, LineNr " + - "FROM Scores " + - "WHERE [SongID] = @SongID AND [Medley] = @Medley AND [Duet] = @Duet AND [ShortSong] = @ShortSong " + - "GROUP BY PlayerName, Difficulty, LineNr " + - ") AS mc " + - "ON sc.PlayerName = mc.PlayerName AND sc.Difficulty = mc.Difficulty AND sc.LineNr = mc.LineNr AND sc.Score = mc.Score " + - "WHERE [SongID] = @SongID AND [Medley] = @Medley AND [Duet] = @Duet AND [ShortSong] = @ShortSong " + - "GROUP BY sc.PlayerName, sc.Difficulty, sc.LineNr, sc.Score " + - ") AS iq " + - "ON os.PlayerName = iq.PlayerName AND os.Difficulty = iq.Difficulty AND os.LineNr = iq.LineNr AND os.Score = iq.Score AND os.Date = iq.Date " + - "WHERE [SongID] = @SongID AND [Medley] = @Medley AND [Duet] = @Duet AND [ShortSong] = @ShortSong " + - "GROUP BY os.PlayerName, os.Difficulty, os.LineNr, os.Score " + - "ORDER BY os.Score DESC, os.Date ASC"; + "FROM Scores os " + + "INNER JOIN ( " + + "SELECT sc.PlayerName, sc.Score, sc.Difficulty, sc.LineNr, MIN(sc.Date) AS Date " + + "FROM Scores sc " + + "INNER JOIN ( " + + "SELECT Playername, MAX(Score) AS Score, Difficulty, LineNr " + + "FROM Scores " + + "WHERE [SongId] = @SongId AND [Medley] = @Medley AND [Duet] = @Duet AND [ShortSong] = @ShortSong " + + "GROUP BY PlayerName, Difficulty, LineNr " + + ") AS mc " + + "ON sc.PlayerName = mc.PlayerName AND sc.Difficulty = mc.Difficulty AND sc.LineNr = mc.LineNr AND sc.Score = mc.Score " + + "WHERE [SongId] = @SongId AND [Medley] = @Medley AND [Duet] = @Duet AND [ShortSong] = @ShortSong " + + "GROUP BY sc.PlayerName, sc.Difficulty, sc.LineNr, sc.Score " + + ") AS iq " + + "ON os.PlayerName = iq.PlayerName AND os.Difficulty = iq.Difficulty AND os.LineNr = iq.LineNr AND os.Score = iq.Score AND os.Date = iq.Date " + + "WHERE [SongId] = @SongId AND [Medley] = @Medley AND [Duet] = @Duet AND [ShortSong] = @ShortSong " + + "GROUP BY os.PlayerName, os.Difficulty, os.LineNr, os.Score " + + "ORDER BY os.Score DESC, os.Date ASC"; break; case EHighscoreStyle.TR_CONFIG_HIGHSCORE_LIST_ALL: command.CommandText = "SELECT PlayerName, Score, Date, Difficulty, LineNr, id " + - "FROM Scores " + - "WHERE [SongID] = @SongID AND [Medley] = @Medley AND [Duet] = @Duet AND [ShortSong] = @ShortSong " + - "ORDER BY [Score] DESC, [Date] ASC"; + "FROM Scores " + + "WHERE [SongId] = @SongId AND [Medley] = @Medley AND [Duet] = @Duet AND [ShortSong] = @ShortSong " + + "ORDER BY [Score] DESC, [Date] ASC"; break; } command.Parameters.Clear(); - command.Parameters.AddWithValue("@SongID", dataBaseSongID); + command.Parameters.AddWithValue("@SongId", dataBaseSongId); command.Parameters.AddWithValue("@Medley", medley); command.Parameters.AddWithValue("@Duet", duet); command.Parameters.AddWithValue("@ShortSong", shortSong); - SqliteDataReader reader = command.ExecuteReader(); + var reader = command.ExecuteReader(); if (reader != null && reader.HasRows) { while (reader.Read()) { var score = new SDBScoreEntry - { - Name = reader.GetString(0), - Score = reader.GetInt32(1), - Date = new DateTime(reader.GetInt64(2)).ToString("dd/MM/yyyy"), - Difficulty = (EGameDifficulty)reader.GetInt32(3), - VoiceNr = reader.GetInt32(4), - ID = reader.GetInt32(5) - }; + { + Name = reader.GetString(0), + Score = reader.GetInt32(1), + Date = new DateTime(reader.GetInt64(2)).ToString("dd/MM/yyyy"), + Difficulty = (EGameDifficulty)reader.GetInt32(3), + VoiceNr = reader.GetInt32(4), + Id = reader.GetInt32(5) + }; scores.Add(score); } + reader.Dispose(); } } } + return scores; } - private void _IncreaseSongCounter(int dataBaseSongID, SqliteCommand command) + private void _IncreaseSongCounter(int dataBaseSongId, SqliteCommand command) { command.CommandText = "UPDATE Songs SET NumPlayed = NumPlayed + 1 WHERE [id] = @id"; command.Parameters.Clear(); - command.Parameters.AddWithValue("@id", dataBaseSongID); + command.Parameters.AddWithValue("@id", dataBaseSongId); command.ExecuteNonQuery(); } - private int _GetDataBaseSongID(int songID, SqliteCommand command) + private int _GetDataBaseSongId(int songId, SqliteCommand command) { - CSong song = CSongs.GetSong(songID); + var song = CSongs.GetSong(songId); if (song == null) + { return -1; + } - return _GetDataBaseSongID(song.Artist, song.Title, 0, command); + return _GetDataBaseSongId(song.Artist, song.Title, 0, command); } - private int _GetDataBaseSongID(string artist, string title, int defNumPlayed, SqliteCommand command) + private int _GetDataBaseSongId(string artist, string title, int defNumPlayed, SqliteCommand command) { command.CommandText = "SELECT id FROM Songs WHERE [Title] = @title AND [Artist] = @artist"; command.Parameters.Clear(); - command.Parameters.AddWithValue("@title", title ?? String.Empty); - command.Parameters.AddWithValue("@artist", artist ?? String.Empty); + command.Parameters.AddWithValue("@title", title ?? string.Empty); + command.Parameters.AddWithValue("@artist", artist ?? string.Empty); - SqliteDataReader reader = command.ExecuteReader(); + var reader = command.ExecuteReader(); if (reader != null && reader.HasRows) { reader.Read(); - int id = reader.GetInt32(0); + var id = reader.GetInt32(0); reader.Dispose(); return id; } if (reader != null) + { reader.Close(); + } command.CommandText = "INSERT INTO Songs (Title, Artist, NumPlayed, DateAdded) " + "VALUES (@title, @artist, @numplayed, @dateadded)"; command.Parameters.Clear(); - command.Parameters.AddWithValue("@title", title ?? String.Empty); - command.Parameters.AddWithValue("@artist", artist ?? String.Empty); + command.Parameters.AddWithValue("@title", title ?? string.Empty); + command.Parameters.AddWithValue("@artist", artist ?? string.Empty); command.Parameters.AddWithValue("@numplayed", defNumPlayed); command.Parameters.AddWithValue("@dateadded", DateTime.Now.Ticks); command.ExecuteNonQuery(); command.CommandText = "SELECT id FROM Songs WHERE [Title] = @title AND [Artist] = @artist"; command.Parameters.Clear(); - command.Parameters.AddWithValue("@title", title ?? String.Empty); - command.Parameters.AddWithValue("@artist", artist ?? String.Empty); + command.Parameters.AddWithValue("@title", title ?? string.Empty); + command.Parameters.AddWithValue("@artist", artist ?? string.Empty); reader = command.ExecuteReader(); if (reader != null) { reader.Read(); - int id = reader.GetInt32(0); + var id = reader.GetInt32(0); reader.Dispose(); return id; } @@ -430,10 +449,10 @@ namespace Vocaluxe.Lib.Database return -1; } - private bool _GetDataBaseSongInfos(int songID, out string artist, out string title, out int numPlayed, out DateTime dateAdded, string filePath) + private bool _GetDataBaseSongInfos(int songId, out string artist, out string title, out int numPlayed, out DateTime dateAdded, string filePath) { - artist = String.Empty; - title = String.Empty; + artist = string.Empty; + title = string.Empty; numPlayed = 0; dateAdded = DateTime.Today; @@ -455,7 +474,7 @@ namespace Vocaluxe.Lib.Database command.Connection = connection; command.CommandText = "SELECT Artist, Title, NumPlayed, DateAdded FROM Songs WHERE [id] = @id"; command.Parameters.Clear(); - command.Parameters.AddWithValue("@id", songID); + command.Parameters.AddWithValue("@id", songId); SqliteDataReader reader; try @@ -472,22 +491,33 @@ namespace Vocaluxe.Lib.Database reader.Read(); if (!reader.IsDBNull(0)) + { artist = reader.GetString(0); + } if (!reader.IsDBNull(1)) - title = reader.GetString(1); + { + title = reader.GetString(1); + } if (!reader.IsDBNull(2)) + { numPlayed = reader.GetInt32(2); + } if (!reader.IsDBNull(3)) + { dateAdded = new DateTime(reader.GetInt64(3)); + } reader.Dispose(); return true; } + if (reader != null) + { reader.Dispose(); + } } } @@ -525,7 +555,7 @@ namespace Vocaluxe.Lib.Database command.ExecuteNonQuery(); command.CommandText = "CREATE TABLE IF NOT EXISTS Scores ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " + - "SongID INTEGER NOT NULL, PlayerName TEXT NOT NULL, Score INTEGER NOT NULL, LineNr INTEGER NOT NULL, Date BIGINT NOT NULL, " + + "SongId INTEGER NOT NULL, PlayerName TEXT NOT NULL, Score INTEGER NOT NULL, LineNr INTEGER NOT NULL, Date BIGINT NOT NULL, " + "Medley INTEGER NOT NULL, Duet INTEGER NOT NULL, ShortSong INTEGER NOT NULL, Difficulty INTEGER NOT NULL);"; command.ExecuteNonQuery(); } @@ -561,7 +591,7 @@ namespace Vocaluxe.Lib.Database command.ExecuteNonQuery(); command.CommandText = "CREATE TABLE IF NOT EXISTS Scores ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " + - "SongID INTEGER NOT NULL, PlayerName TEXT NOT NULL, Score INTEGER NOT NULL, LineNr INTEGER NOT NULL, Date BIGINT NOT NULL, " + + "SongId INTEGER NOT NULL, PlayerName TEXT NOT NULL, Score INTEGER NOT NULL, LineNr INTEGER NOT NULL, Date BIGINT NOT NULL, " + "Medley INTEGER NOT NULL, Duet INTEGER NOT NULL, Difficulty INTEGER NOT NULL);"; command.ExecuteNonQuery(); } @@ -575,7 +605,7 @@ namespace Vocaluxe.Lib.Database /// private bool _CreateOrConvert(string filePath) { - bool result = true; + var result = true; using (var connection = new SqliteConnection()) { connection.ConnectionString = "Data Source=" + filePath; @@ -593,10 +623,10 @@ namespace Vocaluxe.Lib.Database { command.Connection = connection; command.CommandText = "PRAGMA user_version"; - SqliteDataReader reader = command.ExecuteReader(); + var reader = command.ExecuteReader(); reader.Read(); - int version = reader.GetInt32(0); + var version = reader.GetInt32(0); reader.Dispose(); @@ -604,7 +634,7 @@ namespace Vocaluxe.Lib.Database command.CommandText = "SELECT name FROM sqlite_master WHERE type='table' AND name='US_Scores';"; reader = command.ExecuteReader(); reader.Read(); - bool scoresTableExists = reader.HasRows; + var scoresTableExists = reader.HasRows; reader.Dispose(); @@ -615,7 +645,7 @@ namespace Vocaluxe.Lib.Database { reader = command.ExecuteReader(); } - catch (Exception) {} + catch (Exception) { } if (reader == null || reader.FieldCount == 0) { @@ -637,12 +667,14 @@ namespace Vocaluxe.Lib.Database result &= _UpdateDatabase(2, connection); } else + { _CreateHighscoreDB(filePath); + } } else { reader.Read(); - int currentVersion = reader.GetInt32(0); + var currentVersion = reader.GetInt32(0); if (currentVersion < CSettings.DatabaseHighscoreVersion) { // update database @@ -651,7 +683,9 @@ namespace Vocaluxe.Lib.Database } if (reader != null) + { reader.Dispose(); + } } } @@ -683,35 +717,36 @@ namespace Vocaluxe.Lib.Database command.Connection = connection; //The USDX database has no column for LineNr, Medley and Duet so just fill 0 in there command.CommandText = - "INSERT INTO Scores (SongID, PlayerName, Score, LineNr, Date, Medley, Duet, Difficulty) SELECT SongID, Player, Score, '0', Date, '0', '0', Difficulty from US_Scores"; + "INSERT INTO Scores (SongId, PlayerName, Score, LineNr, Date, Medley, Duet, Difficulty) SELECT SongId, Player, Score, '0', Date, '0', '0', Difficulty from US_Scores"; command.ExecuteNonQuery(); - command.CommandText = "INSERT INTO Songs SELECT ID, Artist, Title, TimesPlayed from US_Songs"; + command.CommandText = "INSERT INTO Songs SELECT Id, Artist, Title, TimesPlayed from US_Songs"; command.ExecuteNonQuery(); var scores = new List(); var songs = new List(); command.CommandText = "SELECT id, PlayerName, Date FROM Scores"; - SqliteDataReader reader = command.ExecuteReader(); + var reader = command.ExecuteReader(); if (reader != null && reader.HasRows) { while (reader.Read()) { - var data = new SData {Id = reader.GetInt32(0), Str1 = reader.GetString(1)}; + var data = new SData { Id = reader.GetInt32(0), Str1 = reader.GetString(1) }; Int64 ticks = 0; try { ticks = reader.GetInt64(2); } - catch {} + catch { } data.Ticks = _UnixTimeToTicks((int)ticks); scores.Add(data); } + reader.Close(); } @@ -723,37 +758,40 @@ namespace Vocaluxe.Lib.Database { while (reader.Read()) { - var data = new SData {Id = reader.GetInt32(0), Str1 = reader.GetString(1), Str2 = reader.GetString(2)}; + var data = new SData { Id = reader.GetInt32(0), Str1 = reader.GetString(1), Str2 = reader.GetString(2) }; songs.Add(data); } } if (reader != null) + { reader.Dispose(); + } - SqliteTransaction transaction = connection.BeginTransaction(); + var transaction = connection.BeginTransaction(); command.Transaction = transaction; // update Title and Artist strings - foreach (SData data in songs) + foreach (var data in songs) { - command.CommandText = "UPDATE Songs SET [Artist] = @artist, [Title] = @title WHERE [ID] = @id"; + command.CommandText = "UPDATE Songs SET [Artist] = @artist, [Title] = @title WHERE [Id] = @id"; command.Parameters.Clear(); - command.Parameters.AddWithValue("@title", data.Str2 ?? String.Empty); - command.Parameters.AddWithValue("@artist", data.Str1 ?? String.Empty); + command.Parameters.AddWithValue("@title", data.Str2 ?? string.Empty); + command.Parameters.AddWithValue("@artist", data.Str1 ?? string.Empty); command.Parameters.AddWithValue("@id", data.Id); command.ExecuteNonQuery(); } // update player names - foreach (SData data in scores) + foreach (var data in scores) { command.CommandText = "UPDATE Scores SET [PlayerName] = @player, [Date] = @date WHERE [id] = @id"; command.Parameters.Clear(); - command.Parameters.AddWithValue("@player", data.Str1 ?? String.Empty); + command.Parameters.AddWithValue("@player", data.Str1 ?? string.Empty); command.Parameters.AddWithValue("@date", data.Ticks); command.Parameters.AddWithValue("@id", data.Id); command.ExecuteNonQuery(); } + transaction.Commit(); //Delete old tables after conversion @@ -808,18 +846,21 @@ namespace Vocaluxe.Lib.Database { command.Connection = connection; command.CommandText = "PRAGMA table_info(US_Scores);"; - bool dateExists = false; - using (SqliteDataReader reader = command.ExecuteReader()) + var dateExists = false; + using (var reader = command.ExecuteReader()) { //Check for column Date while (reader.Read()) { - for (int i = 0; i < reader.FieldCount; i++) + for (var i = 0; i < reader.FieldCount; i++) { if (reader.GetName(i) == "name") { if (reader.GetString(i) == "Date") + { dateExists = true; + } + break; } } @@ -828,11 +869,11 @@ namespace Vocaluxe.Lib.Database //This is a USDX 1.01 DB command.CommandText = !dateExists - ? "INSERT INTO Scores (SongID, PlayerName, Score, LineNr, Date, Medley, Duet, Difficulty) SELECT SongID, Player, Score, '0', '0', '0', '0', Difficulty from US_Scores" - : "INSERT INTO Scores (SongID, PlayerName, Score, LineNr, Date, Medley, Duet, Difficulty) SELECT SongID, Player, Score, '0', Date, '0', '0', Difficulty from US_Scores"; + ? "INSERT INTO Scores (SongId, PlayerName, Score, LineNr, Date, Medley, Duet, Difficulty) SELECT SongId, Player, Score, '0', '0', '0', '0', Difficulty from US_Scores" + : "INSERT INTO Scores (SongId, PlayerName, Score, LineNr, Date, Medley, Duet, Difficulty) SELECT SongId, Player, Score, '0', Date, '0', '0', Difficulty from US_Scores"; command.ExecuteNonQuery(); - command.CommandText = "INSERT INTO Songs SELECT ID, Artist, Title, TimesPlayed from US_Songs"; + command.CommandText = "INSERT INTO Songs SELECT Id, Artist, Title, TimesPlayed from US_Songs"; command.ExecuteNonQuery(); // convert from CP1252 to UTF8 @@ -840,28 +881,32 @@ namespace Vocaluxe.Lib.Database var songs = new List(); Sqlite3.sqlite3 oldDB; - int res = Sqlite3.sqlite3_open(filePath, out oldDB); + var res = Sqlite3.sqlite3_open(filePath, out oldDB); if (res != Sqlite3.SQLITE_OK) + { CLog.Error("Error opening Database: " + filePath + " (" + Sqlite3.sqlite3_errmsg(oldDB) + ")"); + } else { var stmt = new Sqlite3.Vdbe(); res = Sqlite3.sqlite3_prepare_v2(oldDB, "SELECT id, Artist, Title FROM Songs", -1, ref stmt, 0); if (res != Sqlite3.SQLITE_OK) + { CLog.Error("Error query Database: " + filePath + " (" + Sqlite3.sqlite3_errmsg(oldDB) + ")"); + } else { //Sqlite3.sqlite3_step(Stmt); - Encoding utf8 = Encoding.UTF8; - Encoding cp1252 = Encoding.GetEncoding(1252); + var utf8 = Encoding.UTF8; + var cp1252 = Encoding.GetEncoding(1252); while (Sqlite3.sqlite3_step(stmt) == Sqlite3.SQLITE_ROW) { - var data = new SData {Id = Sqlite3.sqlite3_column_int(stmt, 0)}; + var data = new SData { Id = Sqlite3.sqlite3_column_int(stmt, 0) }; - byte[] bytes = Sqlite3.sqlite3_column_rawbytes(stmt, 1); + var bytes = Sqlite3.sqlite3_column_rawbytes(stmt, 1); data.Str1 = bytes != null ? utf8.GetString(Encoding.Convert(cp1252, utf8, bytes)) : "Someone"; bytes = Sqlite3.sqlite3_column_rawbytes(stmt, 2); @@ -869,6 +914,7 @@ namespace Vocaluxe.Lib.Database songs.Add(data); } + Sqlite3.sqlite3_finalize(stmt); } @@ -877,54 +923,66 @@ namespace Vocaluxe.Lib.Database // ReSharper disable ConvertIfStatementToConditionalTernaryExpression if (!dateExists) // ReSharper restore ConvertIfStatementToConditionalTernaryExpression + { res = Sqlite3.sqlite3_prepare_v2(oldDB, "SELECT id, PlayerName FROM Scores", -1, ref stmt, 0); + } else + { res = Sqlite3.sqlite3_prepare_v2(oldDB, "SELECT id, PlayerName, Date FROM Scores", -1, ref stmt, 0); + } if (res != Sqlite3.SQLITE_OK) + { CLog.Error("Error query Database: " + filePath + " (" + Sqlite3.sqlite3_errmsg(oldDB) + ")"); + } else { //Sqlite3.sqlite3_step(Stmt); - Encoding utf8 = Encoding.UTF8; - Encoding cp1252 = Encoding.GetEncoding(1252); + var utf8 = Encoding.UTF8; + var cp1252 = Encoding.GetEncoding(1252); while (Sqlite3.sqlite3_step(stmt) == Sqlite3.SQLITE_ROW) { - var data = new SData {Id = Sqlite3.sqlite3_column_int(stmt, 0)}; + var data = new SData { Id = Sqlite3.sqlite3_column_int(stmt, 0) }; - byte[] bytes = Sqlite3.sqlite3_column_rawbytes(stmt, 1); + var bytes = Sqlite3.sqlite3_column_rawbytes(stmt, 1); data.Str1 = bytes != null ? utf8.GetString(Encoding.Convert(cp1252, utf8, bytes)) : "Someone"; if (dateExists) + { data.Ticks = _UnixTimeToTicks(Sqlite3.sqlite3_column_int(stmt, 2)); + } scores.Add(data); } + Sqlite3.sqlite3_finalize(stmt); } } + Sqlite3.sqlite3_close(oldDB); - SqliteTransaction transaction = connection.BeginTransaction(); + var transaction = connection.BeginTransaction(); command.Transaction = transaction; // update Title and Artist strings - foreach (SData data in songs) + foreach (var data in songs) { - command.CommandText = "UPDATE Songs SET [Artist] = @artist, [Title] = @title WHERE [ID] = @id"; + command.CommandText = "UPDATE Songs SET [Artist] = @artist, [Title] = @title WHERE [Id] = @id"; command.Parameters.Clear(); - command.Parameters.AddWithValue("@title", data.Str2 ?? String.Empty); - command.Parameters.AddWithValue("@artist", data.Str1 ?? String.Empty); + command.Parameters.AddWithValue("@title", data.Str2 ?? string.Empty); + command.Parameters.AddWithValue("@artist", data.Str1 ?? string.Empty); command.Parameters.AddWithValue("@id", data.Id); command.ExecuteNonQuery(); } // update player names - foreach (SData data in scores) + foreach (var data in scores) { if (!dateExists) + { command.CommandText = "UPDATE Scores SET [PlayerName] = @player WHERE [id] = @id"; + } else { command.CommandText = "UPDATE Scores SET [PlayerName] = @player, [Date] = @date WHERE [id] = @id"; @@ -932,11 +990,15 @@ namespace Vocaluxe.Lib.Database command.Parameters.Clear(); if (dateExists) + { command.Parameters.AddWithValue("@date", data.Ticks); - command.Parameters.AddWithValue("@player", data.Str1 ?? String.Empty); + } + + command.Parameters.AddWithValue("@player", data.Str1 ?? string.Empty); command.Parameters.AddWithValue("@id", data.Id); command.ExecuteNonQuery(); } + transaction.Commit(); //Delete old tables after conversion @@ -953,12 +1015,16 @@ namespace Vocaluxe.Lib.Database private bool _UpdateDatabase(int currentVersion, SqliteConnection connection) { - bool updated = true; + var updated = true; if (currentVersion < 2) + { updated &= _ConvertV1toV2(connection); + } else if (currentVersion < 3) + { updated &= _ConvertV2toV3(connection); + } return updated; } @@ -998,7 +1064,7 @@ namespace Vocaluxe.Lib.Database command.ExecuteNonQuery(); //Read NumPlayed from Scores and save to Songs - command.CommandText = "SELECT SongID, Date FROM Scores ORDER BY Date ASC"; + command.CommandText = "SELECT SongId, Date FROM Scores ORDER BY Date ASC"; SqliteDataReader reader; try @@ -1011,25 +1077,29 @@ namespace Vocaluxe.Lib.Database } long lastDateAdded = -1; - int lastID = -1; - DateTime dt = new DateTime(1, 1, 1, 0, 0, 5); - long sec = dt.Ticks; - List ids = new List(); + var lastId = -1; + var dt = new DateTime(1, 1, 1, 0, 0, 5); + var sec = dt.Ticks; + var ids = new List(); while (reader.Read()) { - int id = reader.GetInt32(0); - long dateAdded = reader.GetInt64(1); - if (id != lastID || dateAdded > lastDateAdded + sec) + var id = reader.GetInt32(0); + var dateAdded = reader.GetInt64(1); + if (id != lastId || dateAdded > lastDateAdded + sec) { ids.Add(id); - lastID = id; + lastId = id; lastDateAdded = dateAdded; } } + reader.Dispose(); - foreach (int id in ids) + foreach (var id in ids) + { _IncreaseSongCounter(id, command); + } + command.Dispose(); return true; @@ -1056,11 +1126,14 @@ namespace Vocaluxe.Lib.Database using (var cmdSource = new SqliteCommand()) { cmdSource.Connection = connSource; + #region import table scores - cmdSource.CommandText = "SELECT SongID, PlayerName, Score, LineNr, Date, Medley, Duet, ShortSong, Difficulty FROM Scores"; - SqliteDataReader source = cmdSource.ExecuteReader(); + cmdSource.CommandText = "SELECT SongId, PlayerName, Score, LineNr, Date, Medley, Duet, ShortSong, Difficulty FROM Scores"; + var source = cmdSource.ExecuteReader(); if (source == null) + { return false; + } if (source.FieldCount == 0) { @@ -1070,21 +1143,23 @@ namespace Vocaluxe.Lib.Database while (source.Read()) { - int songid = source.GetInt32(0); - string player = source.GetString(1); - int score = source.GetInt32(2); - int linenr = source.GetInt32(3); - long date = source.GetInt64(4); - int medley = source.GetInt32(5); - int duet = source.GetInt32(6); - int shortsong = source.GetInt32(7); - int diff = source.GetInt32(8); + var songid = source.GetInt32(0); + var player = source.GetString(1); + var score = source.GetInt32(2); + var linenr = source.GetInt32(3); + var date = source.GetInt64(4); + var medley = source.GetInt32(5); + var duet = source.GetInt32(6); + var shortsong = source.GetInt32(7); + var diff = source.GetInt32(8); string artist, title; DateTime dateadded; int numplayed; if (_GetDataBaseSongInfos(songid, out artist, out title, out numplayed, out dateadded, sourceDBPath)) + { AddScore(player, score, linenr, date, medley, duet, shortsong, diff, artist, title, numplayed, _FilePath); + } } #endregion import table scores diff --git a/Vocaluxe/Lib/Draw/CDirect3D.cs b/Vocaluxe/Lib/Draw/CDirect3D.cs index 728e1217..b38dfb1e 100644 --- a/Vocaluxe/Lib/Draw/CDirect3D.cs +++ b/Vocaluxe/Lib/Draw/CDirect3D.cs @@ -15,8 +15,6 @@ // along with Vocaluxe. If not, see . #endregion -using SlimDX; -using SlimDX.Direct3D9; using System; using System.Collections.Generic; using System.Drawing; @@ -24,6 +22,8 @@ using System.Drawing.Imaging; using System.IO; using System.Runtime.InteropServices; using System.Windows.Forms; +using SlimDX; +using SlimDX.Direct3D9; using SlimDX.Windows; using Vocaluxe.Base; using VocaluxeLib; @@ -39,7 +39,9 @@ namespace Vocaluxe.Lib.Draw protected override void WndProc(ref Message m) { if (OnMessage == null || OnMessage(ref m)) + { base.WndProc(ref m); + } } } @@ -63,7 +65,9 @@ namespace Vocaluxe.Lib.Draw { base.Dispose(); if (D3DTexture != null) + { D3DTexture.Dispose(); + } } } @@ -148,7 +152,7 @@ namespace Vocaluxe.Lib.Draw if ( !_D3D.CheckDeviceMultisampleType(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware, _D3D.Adapters.DefaultAdapter.CurrentDisplayMode.Format, false, msType, - out quality)) + out quality)) { CLog.Error("[Direct3D] This AAMode is not supported by this device or driver, fallback to no AA"); msType = MultisampleType.None; @@ -163,8 +167,8 @@ namespace Vocaluxe.Lib.Draw _PresentParameters.PresentationInterval = CConfig.Config.Graphics.VSync == EOffOn.TR_CONFIG_ON ? PresentInterval.Default : PresentInterval.Immediate; //GMA 950 graphics devices can only process vertices in software mode - Capabilities caps = _D3D.GetDeviceCaps(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware); - CreateFlags flags = (caps.DeviceCaps & DeviceCaps.HWTransformAndLight) != 0 ? CreateFlags.HardwareVertexProcessing : CreateFlags.SoftwareVertexProcessing; + var caps = _D3D.GetDeviceCaps(_D3D.Adapters.DefaultAdapter.Adapter, DeviceType.Hardware); + var flags = (caps.DeviceCaps & DeviceCaps.HWTransformAndLight) != 0 ? CreateFlags.HardwareVertexProcessing : CreateFlags.SoftwareVertexProcessing; //Check if Pow2 textures are needed _NonPowerOf2TextureSupported = true; @@ -198,10 +202,14 @@ namespace Vocaluxe.Lib.Draw { // The window was minimized, so restore it to the last known size if (_Form.ClientSize.Width == 0 || _Form.ClientSize.Height == 0) + { _Form.ClientSize = _SizeBeforeMinimize; + } if (_H == _Form.ClientSize.Height && _W == _Form.ClientSize.Width && CConfig.Config.Graphics.ScreenAlignment == _CurrentAlignment) + { return; + } _CurrentAlignment = CConfig.Config.Graphics.ScreenAlignment; _H = _Form.ClientSize.Height; @@ -252,21 +260,26 @@ namespace Vocaluxe.Lib.Draw public override bool Init() { if (!base.Init()) + { return false; + } if (_Device.Disposed) + { return false; + } _InitDevice(); //This creates a new white texture and adds it to the texture pool //This texture is used for the DrawRect method using (var blankMap = new Bitmap(1, 1)) - using (Graphics g = Graphics.FromImage(blankMap)) + using (var g = Graphics.FromImage(blankMap)) { g.Clear(Color.White); _BlankTexture = AddTexture(blankMap); } + return true; } @@ -274,44 +287,88 @@ namespace Vocaluxe.Lib.Draw { _AdjustNewBorders(); - _VertexBuffer = new VertexBuffer(_Device, CSettings.VertexBufferElements * (4 * Marshal.SizeOf(typeof(STexturedColoredVertex))), Usage.WriteOnly | Usage.Dynamic, - VertexFormat.Position | VertexFormat.Texture1 | VertexFormat.Diffuse, Pool.Default); + _VertexBuffer = new VertexBuffer(_Device, CSettings.VertexBufferElements * 4 * Marshal.SizeOf(typeof(STexturedColoredVertex)), Usage.WriteOnly | Usage.Dynamic, + VertexFormat.Position | VertexFormat.Texture1 | VertexFormat.Diffuse, Pool.Default); if (_Device.SetStreamSource(0, _VertexBuffer, 0, Marshal.SizeOf(typeof(STexturedColoredVertex))).IsFailure) + { CLog.Error("Failed to set stream source"); + } + _Device.VertexDeclaration = STexturedColoredVertex.GetDeclaration(_Device); if (_Device.SetRenderState(RenderState.CullMode, Cull.None).IsFailure) + { CLog.Error("Failed to set cull mode"); + } + if (_Device.SetRenderState(RenderState.AlphaBlendEnable, true).IsFailure) + { CLog.Error("Failed to enable alpha blending"); + } + if (_Device.SetRenderState(RenderState.Lighting, false).IsFailure) + { CLog.Error("Failed to disable lighting"); + } + if (_Device.SetRenderState(RenderState.DestinationBlend, Blend.InverseSourceAlpha).IsFailure) + { CLog.Error("Failed to set destination blend"); + } + if (_Device.SetRenderState(RenderState.SourceBlend, Blend.SourceAlpha).IsFailure) + { CLog.Error("Failed to set source blend"); + } + if (_PresentParameters.Multisample != MultisampleType.None) { if (_Device.SetRenderState(RenderState.MultisampleAntialias, true).IsFailure) + { CLog.Error("Failed to set antialiasing"); + } } + if (_Device.SetSamplerState(0, SamplerState.MinFilter, TextureFilter.Linear).IsFailure) + { CLog.Error("Failed to set min filter"); + } + if (_Device.SetSamplerState(0, SamplerState.MagFilter, TextureFilter.Linear).IsFailure) + { CLog.Error("Failed to set mag filter"); + } + if (_Device.SetSamplerState(0, SamplerState.MipFilter, TextureFilter.Linear).IsFailure) + { CLog.Error("Failed to set mip filter"); + } + if (_Device.SetSamplerState(0, SamplerState.AddressU, TextureAddress.Clamp).IsFailure) + { CLog.Error("Failed to set clamping on u"); + } + if (_Device.SetSamplerState(0, SamplerState.AddressV, TextureAddress.Clamp).IsFailure) + { CLog.Error("Failed to set claming on v"); + } + if (_Device.SetTextureStageState(0, TextureStage.AlphaArg1, TextureArgument.Texture).IsFailure) + { CLog.Error("Failed to set alpha argument 1"); + } + if (_Device.SetTextureStageState(0, TextureStage.AlphaArg2, TextureArgument.Diffuse).IsFailure) + { CLog.Error("Failed to set alpha argument 2"); + } + if (_Device.SetTextureStageState(0, TextureStage.AlphaOperation, TextureOperation.Modulate).IsFailure) + { CLog.Error("Failed to set alpha operation"); + } var indices = new Int16[6]; indices[0] = 0; @@ -323,7 +380,7 @@ namespace Vocaluxe.Lib.Draw _IndexBuffer = new IndexBuffer(_Device, 6 * sizeof(Int16), Usage.WriteOnly, Pool.Managed, true); - DataStream stream = _IndexBuffer.Lock(0, 0, LockFlags.Discard); + var stream = _IndexBuffer.Lock(0, 0, LockFlags.Discard); stream.WriteRange(indices); _IndexBuffer.Unlock(); _Device.Indices = _IndexBuffer; @@ -332,14 +389,19 @@ namespace Vocaluxe.Lib.Draw protected override void _OnBeforeDraw() { if (_Device.BeginScene().IsFailure) + { CLog.Error("Failed to begin scene"); + } } protected override void _OnAfterDraw() { _RenderVertexBuffer(); if (_Device.EndScene().IsFailure) + { CLog.Error("Failed to end scene"); + } + try { //Now push the frame to the Viewport @@ -357,6 +419,7 @@ namespace Vocaluxe.Lib.Draw _InitDevice(); } } + Application.DoEvents(); } @@ -370,23 +433,30 @@ namespace Vocaluxe.Lib.Draw _VertexBuffer.Dispose(); _IndexBuffer.Dispose(); if (_Device.Reset(_PresentParameters).IsFailure) + { CLog.Error("Failed to reset the device"); + } } protected override void _AdjustNewBorders() { const float dx = (float)CSettings.RenderW / 2; const float dy = (float)CSettings.RenderH / 2; - Matrix translate = Matrix.Translation(new Vector3(-dx, dy, 0)); - Matrix projection = Matrix.OrthoOffCenterLH( - -dx - _BorderLeft, (CSettings.RenderW * CConfig.Config.Graphics.NumScreens) - dx + _BorderRight, + var translate = Matrix.Translation(new Vector3(-dx, dy, 0)); + var projection = Matrix.OrthoOffCenterLH( + -dx - _BorderLeft, CSettings.RenderW * CConfig.Config.Graphics.NumScreens - dx + _BorderRight, -dy - _BorderBottom, dy + _BorderTop, CSettings.ZNear, CSettings.ZFar); if (_Device.SetTransform(TransformState.Projection, projection).IsFailure) + { CLog.Error("Failed to set orthogonal matrix"); + } + if (_Device.SetTransform(TransformState.World, translate).IsFailure) + { CLog.Error("Failed to set translation matrix"); + } } /// @@ -437,7 +507,7 @@ namespace Vocaluxe.Lib.Draw dc.Wy2 -= 0.5f; color.A *= CGraphics.GlobalAlpha; - int c = color.AsColor().ToArgb(); + var c = color.AsColor().ToArgb(); int c2; if (isReflection) { @@ -445,7 +515,9 @@ namespace Vocaluxe.Lib.Draw c2 = color.AsColor().ToArgb(); } else + { c2 = c; + } var vert = new STexturedColoredVertex[4]; vert[0] = new STexturedColoredVertex(new Vector3(dc.Wx1, -dc.Wy1, dc.Wz), new Vector2(dc.Tx1, dc.Ty1), c); @@ -465,7 +537,10 @@ namespace Vocaluxe.Lib.Draw { //The vertexbuffer is full, so we need to flush it before we can continue if (_Vertices.Count >= CSettings.VertexBufferElements) + { _RenderVertexBuffer(); + } + _Vertices.Enqueue(vertices[0]); _Vertices.Enqueue(vertices[1]); _Vertices.Enqueue(vertices[2]); @@ -480,25 +555,37 @@ namespace Vocaluxe.Lib.Draw private void _RenderVertexBuffer() { if (_Vertices.Count <= 0) + { return; + } + //The vertex buffer locks are slow actions, its better to lock once per frame and write all vertices to the buffer at once - DataStream stream = _VertexBuffer.Lock(0, _Vertices.Count * Marshal.SizeOf(typeof(STexturedColoredVertex)), LockFlags.Discard); + var stream = _VertexBuffer.Lock(0, _Vertices.Count * Marshal.SizeOf(typeof(STexturedColoredVertex)), LockFlags.Discard); stream.WriteRange(_Vertices.ToArray()); _VertexBuffer.Unlock(); stream.Dispose(); - for (int i = 0; i < _Vertices.Count; i += 4) + for (var i = 0; i < _Vertices.Count; i += 4) { //Apply rotation if (_Device.SetTransform(TransformState.World, _VerticesRotationMatrices.Dequeue()).IsFailure) + { CLog.Error("Failed to set world transformation"); + } + //Apply texture if (_Device.SetTexture(0, _VerticesTextures.Dequeue()).IsFailure) + { CLog.Error("Failed to set texture"); + } + //Draw 2 triangles from vertexbuffer if (_Device.DrawIndexedPrimitives(PrimitiveType.TriangleList, i, 0, 4, 0, 2).IsFailure) + { CLog.Error("Failed to draw quad"); + } } + //Clear the queues for the next frame _Vertices.Clear(); _VerticesTextures.Clear(); @@ -512,7 +599,9 @@ namespace Vocaluxe.Lib.Draw protected override void _ClearScreen() { if (_Device.Clear(ClearFlags.Target | ClearFlags.ZBuffer, Color.Black, 1.0f, 0).IsFailure) + { CLog.Error("Failed to clear the backbuffer"); + } } /// @@ -521,9 +610,9 @@ namespace Vocaluxe.Lib.Draw /// public CTextureRef CopyScreen() { - CD3DTexture tex = _CreateTexture(new Size(_W, _H)); - Surface backbufferSurface = _Device.GetBackBuffer(0, 0); - Surface textureSurface = tex.D3DTexture.GetSurfaceLevel(0); + var tex = _CreateTexture(new Size(_W, _H)); + var backbufferSurface = _Device.GetBackBuffer(0, 0); + var textureSurface = tex.D3DTexture.GetSurfaceLevel(0); Surface.FromSurface(textureSurface, backbufferSurface, Filter.Default, 0, new Rectangle(0, 0, _W, _H), new Rectangle(0, 0, _W, _H)); backbufferSurface.Dispose(); @@ -544,8 +633,8 @@ namespace Vocaluxe.Lib.Draw } else { - Surface backbufferSurface = _Device.GetBackBuffer(0, 0); - Surface textureSurface = texture.D3DTexture.GetSurfaceLevel(0); + var backbufferSurface = _Device.GetBackBuffer(0, 0); + var textureSurface = texture.D3DTexture.GetSurfaceLevel(0); Surface.FromSurface(textureSurface, backbufferSurface, Filter.Default, 0); backbufferSurface.Dispose(); } @@ -556,10 +645,10 @@ namespace Vocaluxe.Lib.Draw /// public void MakeScreenShot() { - string file = CHelper.GetUniqueFileName(Path.Combine(CSettings.DataFolder, CSettings.FolderNameScreenshots), "Screenshot.png"); + var file = CHelper.GetUniqueFileName(Path.Combine(CSettings.DataFolder, CSettings.FolderNameScreenshots), "Screenshot.png"); //create a surface of the frame - using (Surface surface = _Device.GetBackBuffer(0, 0)) + using (var surface = _Device.GetBackBuffer(0, 0)) { var screen = new Bitmap(Surface.ToStream(surface, ImageFileFormat.Png)); screen.Save(file, ImageFormat.Png); @@ -592,49 +681,56 @@ namespace Vocaluxe.Lib.Draw protected override CD3DTexture _CreateTexture(Size dataSize) { if (dataSize.Width < 0) + { return new CD3DTexture(null, dataSize); + } + return new CD3DTexture(_Device, dataSize, _CheckForNextPowerOf2(dataSize.Width), _CheckForNextPowerOf2(dataSize.Height)); } protected override void _WriteDataToTexture(CD3DTexture texture, byte[] data) { //Lock the texture and fill it with the data - DataRectangle rect = texture.D3DTexture.LockRectangle(0, LockFlags.Discard); - int rowWidth = 4 * texture.DataSize.Width; + var rect = texture.D3DTexture.LockRectangle(0, LockFlags.Discard); + var rowWidth = 4 * texture.DataSize.Width; if (rowWidth == rect.Pitch) + { rect.Data.Write(data, 0, data.Length); + } else { - for (int i = 0; i + rowWidth <= data.Length; i += rowWidth) + for (var i = 0; i + rowWidth <= data.Length; i += rowWidth) { rect.Data.Write(data, i, rowWidth); //Go to next row rect.Data.Position = rect.Data.Position - rowWidth + rect.Pitch; } } + texture.D3DTexture.UnlockRectangle(0); } private static Matrix _CalculateRotationMatrix(float rot, float rx1, float rx2, float ry1, float ry2) { - Matrix originTranslation = Matrix.Translation(new Vector3(-(float)CSettings.RenderW / 2, (float)CSettings.RenderH / 2, 0)); + var originTranslation = Matrix.Translation(new Vector3(-(float)CSettings.RenderW / 2, (float)CSettings.RenderH / 2, 0)); if (Math.Abs(rot) > float.Epsilon) { - float rotation = rot * (float)Math.PI / 180; - float centerX = (rx1 + rx2) / 2f; - float centerY = -(ry1 + ry2) / 2f; + var rotation = rot * (float)Math.PI / 180; + var centerX = (rx1 + rx2) / 2f; + var centerY = -(ry1 + ry2) / 2f; - Matrix translationA = Matrix.Translation(-centerX, -centerY, 0); - Matrix rotationMat = Matrix.RotationZ(-rotation); - Matrix translationB = Matrix.Translation(centerX, centerY, 0); + var translationA = Matrix.Translation(-centerX, -centerY, 0); + var rotationMat = Matrix.RotationZ(-rotation); + var translationB = Matrix.Translation(centerX, centerY, 0); //Multiplicate the matrices to get the real world matrix, //First shift the texture into the center //Rotate it and shift it back to the origin position //Apply the originTranslation after - Matrix result = translationA * rotationMat * translationB * originTranslation; + var result = translationA * rotationMat * translationB * originTranslation; return result; } + return originTranslation; } @@ -642,12 +738,12 @@ namespace Vocaluxe.Lib.Draw { private static VertexDeclaration _Declaration; private static readonly VertexElement[] _Elements = - { - new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), - new VertexElement(0, sizeof(float) * 3, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), - new VertexElement(0, sizeof(float) * 3 + sizeof(float) * 2, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), - VertexElement.VertexDeclarationEnd - }; + { + new VertexElement(0, 0, DeclarationType.Float3, DeclarationMethod.Default, DeclarationUsage.Position, 0), + new VertexElement(0, sizeof(float) * 3, DeclarationType.Float2, DeclarationMethod.Default, DeclarationUsage.TextureCoordinate, 0), + new VertexElement(0, sizeof(float) * 3 + sizeof(float) * 2, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0), + VertexElement.VertexDeclarationEnd + }; // ReSharper disable NotAccessedField.Local private Vector3 _Position; @@ -665,7 +761,9 @@ namespace Vocaluxe.Lib.Draw public static VertexDeclaration GetDeclaration(Device device) { if (_Declaration == null || _Declaration.Disposed) + { _Declaration = new VertexDeclaration(device, _Elements); + } return _Declaration; } diff --git a/Vocaluxe/Lib/Draw/CDrawBase.cs b/Vocaluxe/Lib/Draw/CDrawBase.cs index 846c03f6..6b7fe26f 100644 --- a/Vocaluxe/Lib/Draw/CDrawBase.cs +++ b/Vocaluxe/Lib/Draw/CDrawBase.cs @@ -16,12 +16,12 @@ #endregion using System; +using System.Diagnostics; using System.Threading; using Vocaluxe.Base; +using Vocaluxe.Base.Server; using VocaluxeLib; using VocaluxeLib.Draw; -using System.Diagnostics; -using Vocaluxe.Base.Server; namespace Vocaluxe.Lib.Draw { @@ -70,9 +70,9 @@ namespace Vocaluxe.Lib.Draw { _Y = 0; //The windows width is too big - int old = _W; + var old = _W; _W = (int)Math.Round(_H * CSettings.GetRenderAspect()); - int diff = old - _W; + var diff = old - _W; switch (_CurrentAlignment) { case EGeneralAlignment.Start: @@ -90,9 +90,9 @@ namespace Vocaluxe.Lib.Draw { _X = 0; //The windows height is too big - int old = _H; + var old = _H; _H = (int)Math.Round(_W / CSettings.GetRenderAspect()); - int diff = old - _H; + var diff = old - _H; switch (_CurrentAlignment) { case EGeneralAlignment.Start: @@ -146,13 +146,19 @@ namespace Vocaluxe.Lib.Draw { drawCoords = new SDrawCoords(); if (Math.Abs(rect.W) < 1 || Math.Abs(rect.H) < 1 || Math.Abs(bounds.H) < 1 || Math.Abs(bounds.W) < 1) + { return false; + } if (bounds.X >= rect.Right || bounds.Right <= rect.X) + { return false; + } if (bounds.Y >= rect.Bottom || bounds.Bottom <= rect.Y) + { return false; + } drawCoords.Tx1 = Math.Max(0, (bounds.X - rect.X) / rect.W * texture.WidthRatio); drawCoords.Wx1 = Math.Max(rect.X, bounds.X); @@ -166,7 +172,7 @@ namespace Vocaluxe.Lib.Draw if (mirrored) { - float tmp = drawCoords.Ty1; + var tmp = drawCoords.Ty1; drawCoords.Ty1 = drawCoords.Ty2; drawCoords.Ty2 = tmp; } @@ -191,9 +197,14 @@ namespace Vocaluxe.Lib.Draw { drawCoords = new SDrawCoords(); if (Math.Abs(rect.W) < 1 || Math.Abs(rect.H) < 1) + { return false; + } + if (begin >= 1 || begin >= end) + { return false; + } Debug.Assert(begin.IsInRange(0, 1) && end.IsInRange(0, 1)); @@ -209,7 +220,7 @@ namespace Vocaluxe.Lib.Draw if (mirrored) { - float tmp = drawCoords.Ty1; + var tmp = drawCoords.Ty1; drawCoords.Ty1 = drawCoords.Ty2; drawCoords.Ty2 = tmp; } @@ -223,26 +234,38 @@ namespace Vocaluxe.Lib.Draw public void DrawTexture(CTextureRef textureRef, SRectF rect, SColorF color, bool mirrored = false, bool allMonitors = true) { if (Math.Abs(color.A) < 0.01) + { return; + } + SDrawCoords dc; TTextureType texture; if (!_GetTexture(textureRef, out texture)) + { return; + } + if (allMonitors) { - for (int i = 0; i < CConfig.Config.Graphics.NumScreens; i++) + for (var i = 0; i < CConfig.Config.Graphics.NumScreens; i++) { - SRectF newrect = rect; + var newrect = rect; newrect.X += CSettings.RenderW * i; if (!_CalcDrawCoords(texture, newrect, out dc, mirrored)) + { return; + } + _DrawTexture(texture, dc, color); } } else { if (!_CalcDrawCoords(texture, rect, out dc, mirrored)) + { return; + } + _DrawTexture(texture, dc, color); } } @@ -258,29 +281,40 @@ namespace Vocaluxe.Lib.Draw public void DrawTexture(CTextureRef textureRef, SRectF rect, SColorF color, SRectF bounds, bool mirrored = false, bool allMonitors = true) { if (Math.Abs(color.A) < 0.01) + { return; + } + SDrawCoords dc; TTextureType texture; if (!_GetTexture(textureRef, out texture)) + { return; + } if (allMonitors) { - for (int i = 0; i < CConfig.Config.Graphics.NumScreens; i++) + for (var i = 0; i < CConfig.Config.Graphics.NumScreens; i++) { - SRectF newrect = rect; - SRectF newbounds = bounds; + var newrect = rect; + var newbounds = bounds; newrect.X += CSettings.RenderW * i; newbounds.X += CSettings.RenderW * i; if (!_CalcDrawCoords(texture, newrect, newbounds, out dc, mirrored)) + { return; + } + _DrawTexture(texture, dc, color); } } else { if (!_CalcDrawCoords(texture, rect, bounds, out dc, mirrored)) + { return; + } + _DrawTexture(texture, dc, color); } } @@ -296,27 +330,38 @@ namespace Vocaluxe.Lib.Draw public void DrawTexture(CTextureRef textureRef, SRectF rect, SColorF color, float begin, float end, bool allMonitors = true) { if (Math.Abs(color.A) < 0.01) + { return; + } + SDrawCoords dc; TTextureType texture; if (!_GetTexture(textureRef, out texture)) + { return; + } if (allMonitors) { - for (int i = 0; i < CConfig.Config.Graphics.NumScreens; i++) + for (var i = 0; i < CConfig.Config.Graphics.NumScreens; i++) { - SRectF newrect = rect; + var newrect = rect; newrect.X += CSettings.RenderW * i; if (!_CalcDrawCoords(texture, newrect, out dc, false, begin, end)) + { return; + } + _DrawTexture(texture, dc, color); } } else { if (!_CalcDrawCoords(texture, rect, out dc, false, begin, end)) + { return; + } + _DrawTexture(texture, dc, color); } } @@ -335,11 +380,16 @@ namespace Vocaluxe.Lib.Draw Debug.Assert(height >= 0); if (Math.Abs(color.A) < 0.01 || height < 1) + { return; + } + SDrawCoords dc; TTextureType texture; if (!_GetTexture(textureRef, out texture)) + { return; + } int loops; if (allMonitors) @@ -351,23 +401,29 @@ namespace Vocaluxe.Lib.Draw loops = 1; } - for (int i = 0; i < loops; i++) + for (var i = 0; i < loops; i++) { - SRectF newrect = rect; - SRectF newbounds = bounds; + var newrect = rect; + var newbounds = bounds; newrect.X += CSettings.RenderW * i; newbounds.X += CSettings.RenderW * i; if (!_CalcDrawCoords(texture, newrect, newbounds, out dc, true)) + { return; + } if (height > newrect.H) + { height = newrect.H; + } dc.Wy1 += newrect.H + space; // Move from start of rect to end of rect with spacing dc.Wy2 += space + height; // Move from end of rect dc.Ty2 += (newrect.H - height) / newrect.H; // Adjust so not all of the start of the texture is drawn (mirrored--> Ty1>Ty2) if (dc.Ty2 < dc.Ty1) // Make sure we actually draw something + { _DrawTexture(texture, dc, color, true); + } } } @@ -384,9 +440,13 @@ namespace Vocaluxe.Lib.Draw _Fullscreen = false; if (CConfig.Config.Graphics.FullScreen == EOffOn.TR_CONFIG_ON) + { _EnterFullScreen(); + } else + { _DoResize(); //Resize window if aspect ratio is incorrect + } while (_Run) { @@ -399,15 +459,22 @@ namespace Vocaluxe.Lib.Draw //Clear the previous Frame _ClearScreen(); if (!CGraphics.Draw()) + { _Run = false; + } + _OnAfterDraw(); if (!CGraphics.UpdateGameLogic(_Keys, _Mouse)) + { _Run = false; + } //Apply fullscreen mode - if ((CConfig.Config.Graphics.FullScreen == EOffOn.TR_CONFIG_ON) != _Fullscreen) + if (CConfig.Config.Graphics.FullScreen == EOffOn.TR_CONFIG_ON != _Fullscreen) + { _ToggleFullScreen(); + } //Apply border changes if (_BorderLeft != CConfig.Config.Graphics.BorderLeft || _BorderRight != CConfig.Config.Graphics.BorderRight || _BorderTop != CConfig.Config.Graphics.BorderTop || @@ -422,18 +489,23 @@ namespace Vocaluxe.Lib.Draw } if (_CurrentAlignment != CConfig.Config.Graphics.ScreenAlignment) + { _DoResize(); + } if (CConfig.Config.Graphics.VSync == EOffOn.TR_CONFIG_OFF) { if (CTime.IsRunning()) { - int delay = (int)Math.Floor(CConfig.CalcCycleTime() - CTime.GetMilliseconds()); + var delay = (int)Math.Floor(CConfig.CalcCycleTime() - CTime.GetMilliseconds()); if (delay >= 1 && delay < 500) + { Thread.Sleep(delay); + } } } + //Calculate the FPS Rate and restart the timer after a frame CTime.CalculateFPS(); CTime.Restart(); @@ -443,9 +515,13 @@ namespace Vocaluxe.Lib.Draw private void _ToggleFullScreen() { if (!_Fullscreen) + { _EnterFullScreen(); + } else + { _LeaveFullScreen(); + } } } } \ No newline at end of file diff --git a/Vocaluxe/Lib/Draw/CDrawBaseWindows.cs b/Vocaluxe/Lib/Draw/CDrawBaseWindows.cs index 6915cd8c..eee882e6 100644 --- a/Vocaluxe/Lib/Draw/CDrawBaseWindows.cs +++ b/Vocaluxe/Lib/Draw/CDrawBaseWindows.cs @@ -52,14 +52,14 @@ namespace Vocaluxe.Lib.Draw { _Form.Close(); } - catch {} + catch { } } protected void _CenterToScreen() { - Screen screen = Screen.FromControl(_Form); + var screen = Screen.FromControl(_Form); _Form.Location = new Point((screen.WorkingArea.Width - _Form.Width) / 2, - (screen.WorkingArea.Height - _Form.Height) / 2); + (screen.WorkingArea.Height - _Form.Height) / 2); } private static bool _OnMessageAvoidScreenOff(ref Message m) @@ -76,8 +76,10 @@ namespace Vocaluxe.Lib.Draw case 0xF170: // SC_MONITORPOWER return false; } + break; } + return true; } @@ -92,7 +94,7 @@ namespace Vocaluxe.Lib.Draw _Form.FormBorderStyle = FormBorderStyle.None; - Screen screen = Screen.FromControl(_Form); + var screen = Screen.FromControl(_Form); _Form.DesktopBounds = new Rectangle(screen.Bounds.Location, new Size(screen.Bounds.Width, screen.Bounds.Height)); if (_Form.WindowState == FormWindowState.Maximized) @@ -102,7 +104,9 @@ namespace Vocaluxe.Lib.Draw _Form.WindowState = FormWindowState.Maximized; } else + { _DoResize(); + } } protected override void _LeaveFullScreen() @@ -154,9 +158,9 @@ namespace Vocaluxe.Lib.Draw protected void _OnMouseLeave(object sender, EventArgs e) { _Mouse.Visible = false; - #if !WIN && !DEBUG +#if !WIN && !DEBUG _Form.Cursor = Cursors.Default; - #endif +#endif Cursor.Show(); } @@ -164,9 +168,9 @@ namespace Vocaluxe.Lib.Draw { Cursor.Hide(); _Mouse.Visible = true; - #if !WIN && !DEBUG //don't want to be stuck without a cursor when debugging +#if !WIN && !DEBUG //don't want to be stuck without a cursor when debugging _Form.Cursor = new Cursor("Linux/blank.cur"); //Cursor.Hide() doesn't work in Mono - #endif +#endif } #endregion @@ -191,13 +195,15 @@ namespace Vocaluxe.Lib.Draw _Keys.KeyUp(e); } #endregion keyboard event handlers - #endregion public override bool Init() { if (!base.Init()) + { return false; + } + _Form.Icon = new Icon(Path.Combine(CSettings.ProgramFolder, CSettings.FileNameIcon)); _Form.Text = CSettings.GetFullVersionText(); ((IFormHook)_Form).OnMessage = _OnMessageAvoidScreenOff; diff --git a/Vocaluxe/Lib/Draw/CDrawWinForm.cs b/Vocaluxe/Lib/Draw/CDrawWinForm.cs index f4de18e3..f8066774 100644 --- a/Vocaluxe/Lib/Draw/CDrawWinForm.cs +++ b/Vocaluxe/Lib/Draw/CDrawWinForm.cs @@ -87,11 +87,11 @@ namespace Vocaluxe.Lib.Draw private void _DrawBuffer() { - Graphics frontBuffer = Graphics.FromHwnd(Handle); - int h = ClientSize.Height; - int w = ClientSize.Width; - int y = 0; - int x = 0; + var frontBuffer = Graphics.FromHwnd(Handle); + var h = ClientSize.Height; + var w = ClientSize.Width; + var y = 0; + var x = 0; if (ClientSize.Width / (float)ClientSize.Height > CSettings.GetRenderAspect()) { @@ -111,9 +111,13 @@ namespace Vocaluxe.Lib.Draw private void _ToggleFullScreen() { if (!_Fullscreen) + { _Maximize(this); + } else + { _Restore(this); + } } private void _Maximize(Form targetForm) @@ -146,7 +150,7 @@ namespace Vocaluxe.Lib.Draw private void _OnResizeEvent(object sender, EventArgs e) { - Graphics frontBuffer = Graphics.FromHwnd(Handle); + var frontBuffer = Graphics.FromHwnd(Handle); frontBuffer.Clear(Color.Black); } @@ -172,6 +176,7 @@ namespace Vocaluxe.Lib.Draw base.WndProc(ref m); break; } + break; default: base.WndProc(ref m); @@ -220,11 +225,13 @@ namespace Vocaluxe.Lib.Draw public void MainLoop() { _Run = true; - int delay = 0; + var delay = 0; Show(); if (CConfig.Config.Graphics.FullScreen == EOffOn.TR_CONFIG_ON) + { _Maximize(this); + } while (_Run) { @@ -237,19 +244,26 @@ namespace Vocaluxe.Lib.Draw _Run = CGraphics.UpdateGameLogic(_Keys, _Mouse); _FlipBuffer(); - if ((CConfig.Config.Graphics.FullScreen == EOffOn.TR_CONFIG_ON) != _Fullscreen) + if (CConfig.Config.Graphics.FullScreen == EOffOn.TR_CONFIG_ON != _Fullscreen) + { _ToggleFullScreen(); + } if (CTime.IsRunning()) + { delay = (int)Math.Floor(CConfig.CalcCycleTime() - CTime.GetMilliseconds()); + } if (delay >= 1) + { Thread.Sleep(delay); + } CTime.CalculateFPS(); CTime.Restart(); } } + Close(); } @@ -260,6 +274,7 @@ namespace Vocaluxe.Lib.Draw base.Close(); } catch { } + Dispose(); } @@ -282,10 +297,10 @@ namespace Vocaluxe.Lib.Draw { var bmp = new Bitmap(_Backbuffer); _Bitmaps.Add(bmp); - CTextureRef texture = _GetNewTexture(bmp.GetSize()); + var texture = _GetNewTexture(bmp.GetSize()); // Add to Texture List - _Textures[texture.ID] = texture; + _Textures[texture.Id] = texture; return texture; } @@ -298,12 +313,14 @@ namespace Vocaluxe.Lib.Draw texture = CopyScreen(); } else - _Bitmaps[texture.ID] = new Bitmap(_Backbuffer); + { + _Bitmaps[texture.Id] = new Bitmap(_Backbuffer); + } } public void MakeScreenShot() { - string file = CHelper.GetUniqueFileName(Path.Combine(CSettings.DataFolder, CSettings.FolderNameScreenshots), "Screenshot.png"); + var file = CHelper.GetUniqueFileName(Path.Combine(CSettings.DataFolder, CSettings.FolderNameScreenshots), "Screenshot.png"); _Backbuffer.Save(file, ImageFormat.Png); } @@ -316,10 +333,10 @@ namespace Vocaluxe.Lib.Draw { var bmp2 = new Bitmap(bmp); _Bitmaps.Add(bmp2); - CTextureRef texture = _GetNewTexture(bmp.GetSize()); + var texture = _GetNewTexture(bmp.GetSize()); // Add to Texture List - _Textures[texture.ID] = texture; + _Textures[texture.Id] = texture; return texture; } @@ -335,12 +352,16 @@ namespace Vocaluxe.Lib.Draw { CTextureRef texture; if (_TextureCache.TryGetValue(texturePath, out texture)) + { return texture; + } + using (var bmp = new Bitmap(texturePath)) { texture = AddTexture(bmp); _TextureCache.Add(texturePath, texture); } + return texture; } @@ -349,13 +370,16 @@ namespace Vocaluxe.Lib.Draw private bool _TextureExists(CTextureRef texture) { - return texture != null && _Textures.ContainsKey(texture.ID); + return texture != null && _Textures.ContainsKey(texture.Id); } public CTextureRef CopyTexture(CTextureRef textureRef) { if (_TextureExists(textureRef)) - return AddTexture(_Bitmaps[textureRef.ID]); + { + return AddTexture(_Bitmaps[textureRef.Id]); + } + return null; } @@ -363,10 +387,11 @@ namespace Vocaluxe.Lib.Draw { if (_TextureExists(texture)) { - _Bitmaps[texture.ID].Dispose(); - _Textures.Remove(texture.ID); + _Bitmaps[texture.Id].Dispose(); + _Textures.Remove(texture.Id); texture.SetRemoved(); } + texture = null; } @@ -394,7 +419,7 @@ namespace Vocaluxe.Lib.Draw { using (var bmp = new Bitmap(w, h)) { - BitmapData bmpData = bmp.LockBits(bmp.GetRect(), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); + var bmpData = bmp.LockBits(bmp.GetRect(), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); Marshal.Copy(data, 0, bmpData.Scan0, data.Length); bmp.UnlockBits(bmpData); return AddTexture(bmp); @@ -405,30 +430,37 @@ namespace Vocaluxe.Lib.Draw { if (_TextureExists(texture)) { - BitmapData bmpData = _Bitmaps[texture.ID].LockBits(new Rectangle(0, 0, _Bitmaps[texture.ID].Width, _Bitmaps[texture.ID].Height), - ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); + var bmpData = _Bitmaps[texture.Id].LockBits(new Rectangle(0, 0, _Bitmaps[texture.Id].Width, _Bitmaps[texture.Id].Height), + ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); Marshal.Copy(data, 0, bmpData.Scan0, data.Length); - _Bitmaps[texture.ID].UnlockBits(bmpData); + _Bitmaps[texture.Id].UnlockBits(bmpData); } } public void UpdateTexture(CTextureRef textureRef, Bitmap bmp) { if (_TextureExists(textureRef)) - _Bitmaps[textureRef.ID] = bmp; + { + _Bitmaps[textureRef.Id] = bmp; + } } public void DrawTexture(CTextureRef texture, SRectF rect, SColorF color, bool mirrored = false, bool allMonitors = true) { if (texture != null) + { DrawTexture(texture, rect, color, rect, mirrored); + } } public void DrawTexture(CTextureRef texture, SRectF rect, SColorF color, SRectF bounds, bool mirrored = false, bool allMonitors = true) { if (!_TextureExists(texture)) + { return; - Bitmap coloredBitmap = _ColorizeBitmap(_Bitmaps[texture.ID], color); + } + + var coloredBitmap = _ColorizeBitmap(_Bitmaps[texture.Id], color); _G.DrawImage(coloredBitmap, new RectangleF(rect.X, rect.Y, rect.W, rect.H)); coloredBitmap.Dispose(); } @@ -446,7 +478,7 @@ namespace Vocaluxe.Lib.Draw { var newBitmap = new Bitmap(original.Width, original.Height); - using (Graphics g = Graphics.FromImage(newBitmap)) + using (var g = Graphics.FromImage(newBitmap)) { var cm = new ColorMatrix { Matrix33 = color.A, Matrix00 = color.R, Matrix11 = color.G, Matrix22 = color.B, Matrix44 = 1 }; @@ -455,7 +487,7 @@ namespace Vocaluxe.Lib.Draw ia.SetColorMatrix(cm); g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), - 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, ia); + 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, ia); } } diff --git a/Vocaluxe/Lib/Draw/COpenGL.cs b/Vocaluxe/Lib/Draw/COpenGL.cs index cdb702ab..f396d3b7 100644 --- a/Vocaluxe/Lib/Draw/COpenGL.cs +++ b/Vocaluxe/Lib/Draw/COpenGL.cs @@ -15,19 +15,18 @@ // along with Vocaluxe. If not, see . #endregion -using System.Diagnostics; -using System.Drawing.Imaging; -using OpenTK; -using OpenTK.Graphics; using System; +using System.Diagnostics; using System.Drawing; +using System.Drawing.Imaging; using System.IO; using System.Windows.Forms; +using OpenTK; +using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using Vocaluxe.Base; using VocaluxeLib; using VocaluxeLib.Draw; -using BeginMode = OpenTK.Graphics.OpenGL.BeginMode; using BlendingFactorDest = OpenTK.Graphics.OpenGL.BlendingFactorDest; using BlendingFactorSrc = OpenTK.Graphics.OpenGL.BlendingFactorSrc; using ClearBufferMask = OpenTK.Graphics.OpenGL.ClearBufferMask; @@ -54,7 +53,9 @@ namespace Vocaluxe.Lib.Draw protected override void WndProc(ref Message m) { if (OnMessage == null || OnMessage(ref m)) + { base.WndProc(ref m); + } } } @@ -67,7 +68,10 @@ namespace Vocaluxe.Lib.Draw { Name = name; if (name == 0) + { return; + } + GL.BindTexture(TextureTarget.Texture2D, Name); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, texWidth, texHeight, 0, PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero); @@ -89,7 +93,9 @@ namespace Vocaluxe.Lib.Draw { base.Dispose(); if (Name != 0) + { GL.DeleteTexture(Name); + } } } @@ -106,7 +112,7 @@ namespace Vocaluxe.Lib.Draw //Check AA Mode CConfig.Config.Graphics.AAMode = (EAntiAliasingModes)_CheckAntiAliasingMode((int)CConfig.Config.Graphics.AAMode); - bool ok = false; + var ok = false; try { #if WIN @@ -116,7 +122,9 @@ namespace Vocaluxe.Lib.Draw #endif _Control = new GLControl(gm, 2, 1, GraphicsContextFlags.Default); if (_Control.GraphicsMode != null) + { ok = true; + } } catch (Exception) { @@ -124,7 +132,9 @@ namespace Vocaluxe.Lib.Draw } if (!ok) + { _Control = new GLControl(); + } _Control.MakeCurrent(); _Control.VSync = CConfig.Config.Graphics.VSync == EOffOn.TR_CONFIG_ON; @@ -149,10 +159,12 @@ namespace Vocaluxe.Lib.Draw private static int _CheckAntiAliasingMode(int setValue) { - int samples = 0; + var samples = 0; if (setValue > 32) + { setValue = 32; + } while (samples <= setValue) { @@ -167,15 +179,25 @@ namespace Vocaluxe.Lib.Draw } if (mode.Samples != samples) + { break; + } + if (samples == 0) + { samples = 2; + } else + { samples *= 2; + } } if (samples == 2) + { return 0; + } + return samples / 2; } @@ -231,7 +253,9 @@ namespace Vocaluxe.Lib.Draw public override bool Init() { if (!base.Init()) + { return false; + } // Init Texturing GL.Enable(EnableCap.Texture2D); @@ -285,20 +309,21 @@ namespace Vocaluxe.Lib.Draw { GL.MatrixMode(MatrixMode.Projection); GL.LoadIdentity(); - GL.Ortho(-CConfig.Config.Graphics.BorderLeft, CConfig.Config.Graphics.BorderRight + CSettings.RenderW * CConfig.Config.Graphics.NumScreens, CConfig.Config.Graphics.BorderBottom + CSettings.RenderH, - -CConfig.Config.Graphics.BorderTop, CSettings.ZNear, CSettings.ZFar); + GL.Ortho(-CConfig.Config.Graphics.BorderLeft, CConfig.Config.Graphics.BorderRight + CSettings.RenderW * CConfig.Config.Graphics.NumScreens, + CConfig.Config.Graphics.BorderBottom + CSettings.RenderH, + -CConfig.Config.Graphics.BorderTop, CSettings.ZNear, CSettings.ZFar); } public void MakeScreenShot() { - string file = CHelper.GetUniqueFileName(Path.Combine(CSettings.DataFolder, CSettings.FolderNameScreenshots), "Screenshot.png"); + var file = CHelper.GetUniqueFileName(Path.Combine(CSettings.DataFolder, CSettings.FolderNameScreenshots), "Screenshot.png"); - int width = GetScreenWidth(); - int height = GetScreenHeight(); + var width = GetScreenWidth(); + var height = GetScreenHeight(); using (var screen = new Bitmap(width, height)) { - BitmapData bmpData = screen.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); + var bmpData = screen.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.ReadPixels(0, 0, width, height, PixelFormat.Bgra, PixelType.UnsignedByte, bmpData.Scan0); screen.UnlockBits(bmpData); @@ -311,8 +336,8 @@ namespace Vocaluxe.Lib.Draw public CTextureRef CopyScreen() { //TODO: Check if _W,_H needs to be used or not - Size size = new Size(GetScreenWidth(), GetScreenHeight()); - COGLTexture texture = _CreateTexture(size); + var size = new Size(GetScreenWidth(), GetScreenHeight()); + var texture = _CreateTexture(size); GL.BindTexture(TextureTarget.Texture2D, texture.Name); GL.CopyTexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, 0, 0, size.Width, size.Height); //TODO: Use _X,_Y and _W,_H? @@ -340,12 +365,15 @@ namespace Vocaluxe.Lib.Draw public void DrawRect(SColorF color, SRectF rect, bool allMonitors = true) { - int loops = 1; + var loops = 1; if (allMonitors) - loops = CConfig.Config.Graphics.NumScreens; - for (int i = 0; i < loops; i++) { - SRectF newrect = rect; + loops = CConfig.Config.Graphics.NumScreens; + } + + for (var i = 0; i < loops; i++) + { + var newrect = rect; newrect.X += CSettings.RenderW * i; GL.Enable(EnableCap.Blend); @@ -360,6 +388,7 @@ namespace Vocaluxe.Lib.Draw GL.Rotate(-newrect.Rotation, 0f, 0f, 1f); GL.Translate(-0.5f, -0.5f, 0); } + GL.Vertex3(newrect.X, newrect.Y, newrect.Z + CGraphics.ZOffset); GL.Vertex3(newrect.X, newrect.Y + newrect.H, newrect.Z + CGraphics.ZOffset); GL.Vertex3(newrect.X + newrect.W, newrect.Y + newrect.H, newrect.Z + CGraphics.ZOffset); @@ -373,24 +402,34 @@ namespace Vocaluxe.Lib.Draw public void DrawRectReflection(SColorF color, SRectF rect, float space, float height) { if (rect.H < height) + { height = rect.H; + } - float rx1 = rect.X; - float rx2 = rect.X + rect.W; - float ry1 = rect.Y + rect.H + space; - float ry2 = rect.Y + rect.H + space + height; + var rx1 = rect.X; + var rx2 = rect.X + rect.W; + var ry1 = rect.Y + rect.H + space; + var ry2 = rect.Y + rect.H + space + height; if (rx1 < rect.X) + { rx1 = rect.X; + } if (rx2 > rect.X + rect.W) + { rx2 = rect.X + rect.W; + } if (ry1 < rect.Y + space) + { ry1 = rect.Y + space; + } if (ry2 > rect.Y + rect.H + space + height) + { ry2 = rect.Y + rect.H + space + height; + } GL.Enable(EnableCap.Blend); @@ -423,8 +462,11 @@ namespace Vocaluxe.Lib.Draw protected override COGLTexture _CreateTexture(Size dataSize) { if (dataSize.Width < 0) + { return new COGLTexture(0, dataSize); - COGLTexture texture = new COGLTexture(GL.GenTexture(), dataSize, _CheckForNextPowerOf2(dataSize.Width), _CheckForNextPowerOf2(dataSize.Height)); + } + + var texture = new COGLTexture(GL.GenTexture(), dataSize, _CheckForNextPowerOf2(dataSize.Width), _CheckForNextPowerOf2(dataSize.Height)); return texture; } @@ -432,10 +474,13 @@ namespace Vocaluxe.Lib.Draw private void _ClearTexture(COGLTexture texture) { if (texture.DataSize.Equals(texture.Size)) + { return; + } + GL.BindFramebuffer(OpenTK.Graphics.OpenGL.FramebufferTarget.Framebuffer, _FBO); GL.FramebufferTexture2D(OpenTK.Graphics.OpenGL.FramebufferTarget.Framebuffer, OpenTK.Graphics.OpenGL.FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, - texture.Name, 0); + texture.Name, 0); GL.ClearColor(Color.FromArgb(0)); GL.Clear(ClearBufferMask.ColorBufferBit); GL.ClearColor(Color.Black); @@ -495,7 +540,10 @@ namespace Vocaluxe.Lib.Draw GL.Vertex3(dc.Wx1, dc.Wy1, dc.Wz); if (isReflection) + { GL.Color4(color.R, color.G, color.B, 0); + } + GL.TexCoord2(dc.Tx1, dc.Ty2); GL.Vertex3(dc.Wx1, dc.Wy2, dc.Wz); @@ -503,7 +551,10 @@ namespace Vocaluxe.Lib.Draw GL.Vertex3(dc.Wx2, dc.Wy2, dc.Wz); if (isReflection) + { GL.Color4(color.R, color.G, color.B, color.A * CGraphics.GlobalAlpha); + } + GL.TexCoord2(dc.Tx2, dc.Ty1); GL.Vertex3(dc.Wx2, dc.Wy1, dc.Wz); diff --git a/Vocaluxe/Lib/Draw/CTextureBase.cs b/Vocaluxe/Lib/Draw/CTextureBase.cs index 01c0dc86..938b8544 100644 --- a/Vocaluxe/Lib/Draw/CTextureBase.cs +++ b/Vocaluxe/Lib/Draw/CTextureBase.cs @@ -74,13 +74,22 @@ namespace Vocaluxe.Lib.Draw private void _CalcRatios() { if (_DataSize.Width == Size.Width) + { WidthRatio = 1f; + } else + { WidthRatio = (float)_DataSize.Width / Size.Width; + } + if (_DataSize.Height == Size.Height) + { HeightRatio = 1f; + } else + { HeightRatio = (float)_DataSize.Height / Size.Height; + } } private bool _IsDisposed; @@ -88,7 +97,10 @@ namespace Vocaluxe.Lib.Draw public virtual void Dispose() { if (_IsDisposed) + { throw new ObjectDisposedException(GetType().Name); + } + RefCount = 0; _IsDisposed = true; } diff --git a/Vocaluxe/Lib/Draw/CTextureProvider.cs b/Vocaluxe/Lib/Draw/CTextureProvider.cs index 52fb5226..8791ff5e 100644 --- a/Vocaluxe/Lib/Draw/CTextureProvider.cs +++ b/Vocaluxe/Lib/Draw/CTextureProvider.cs @@ -98,10 +98,10 @@ namespace Vocaluxe.Lib.Draw protected bool _NonPowerOf2TextureSupported; - private int _NextID; - private readonly Object _MutexID = new object(); + private int _NextId; + private readonly Object _MutexId = new object(); - // Maps texture IDs to textures. Multiple IDs can be mapped to one texture (-->texture.RefCount>1) + // Maps texture Ids to textures. Multiple Ids can be mapped to one texture (-->texture.RefCount>1) private readonly Dictionary _Textures = new Dictionary(); // Maps texturePaths to textures. Texture may have already been disposed (RefCount<=0) private readonly Dictionary _TextureCache = new Dictionary(); @@ -109,11 +109,11 @@ namespace Vocaluxe.Lib.Draw private readonly Dictionary> _BitmapsLoading = new Dictionary>(); private int _TextureCount; - private int _MainThreadID; + private int _MainThreadId; public virtual bool Init() { - _MainThreadID = Thread.CurrentThread.ManagedThreadId; + _MainThreadId = Thread.CurrentThread.ManagedThreadId; return true; } @@ -123,11 +123,14 @@ namespace Vocaluxe.Lib.Draw lock (_Textures) { //Dispose all textures - foreach (TTextureType texture in _Textures.Values) + foreach (var texture in _Textures.Values) { if (texture != null && --texture.RefCount <= 0) + { texture.Dispose(); + } } + _Textures.Clear(); _TextureCache.Clear(); } @@ -138,7 +141,7 @@ namespace Vocaluxe.Lib.Draw /// protected void _EnsureMainThread() { - Debug.Assert(_MainThreadID == Thread.CurrentThread.ManagedThreadId); + Debug.Assert(_MainThreadId == Thread.CurrentThread.ManagedThreadId); } /// @@ -149,9 +152,15 @@ namespace Vocaluxe.Lib.Draw protected int _CheckForNextPowerOf2(int n) { if (_NonPowerOf2TextureSupported) + { return n; + } + if (n < 0) + { throw new ArgumentOutOfRangeException("n", "Must be positive."); + } + return (int)Math.Pow(2, Math.Ceiling(Math.Log(n, 2))); } @@ -185,8 +194,8 @@ namespace Vocaluxe.Lib.Draw /// private static bool _RequiresResize(Size size) { - int maxArea = _GetMaxTextureArea(); - int curArea = size.Width * size.Height; + var maxArea = _GetMaxTextureArea(); + var curArea = size.Width * size.Height; return curArea > maxArea; } @@ -197,13 +206,16 @@ namespace Vocaluxe.Lib.Draw private Size _GetNewTextureSize(Size size) { Debug.Assert(size.Width > 0 && size.Height > 0); - int maxArea = _GetMaxTextureArea(); - int curArea = size.Width * size.Height; + var maxArea = _GetMaxTextureArea(); + var curArea = size.Width * size.Height; if (curArea <= maxArea) + { return size; + } + Debug.Assert(_RequiresResize(size)); - double factor = Math.Sqrt((double)maxArea / curArea); - Size newSize = new Size((int)(size.Width * factor), (int)(size.Height * factor)); + var factor = Math.Sqrt((double)maxArea / curArea); + var newSize = new Size((int)(size.Width * factor), (int)(size.Height * factor)); if (!_NonPowerOf2TextureSupported) { if (size.Width < size.Height) @@ -211,16 +223,21 @@ namespace Vocaluxe.Lib.Draw newSize.Width = _CheckForNextPowerOf2(newSize.Width); newSize.Height = _CheckForNextPowerOf2(maxArea / newSize.Width); if (newSize.Width * newSize.Height > maxArea) + { newSize.Height /= 2; + } } else { newSize.Height = _CheckForNextPowerOf2(newSize.Height); newSize.Width = _CheckForNextPowerOf2(maxArea / newSize.Height); if (newSize.Width * newSize.Height > maxArea) + { newSize.Width /= 2; + } } } + Debug.Assert(newSize.Width * newSize.Height <= maxArea); return newSize; } @@ -229,7 +246,7 @@ namespace Vocaluxe.Lib.Draw protected virtual void _WriteDataToTexture(TTextureType texture, IntPtr data) { - byte[] dataArray = new byte[4 * texture.DataSize.Width * texture.DataSize.Height]; + var dataArray = new byte[4 * texture.DataSize.Width * texture.DataSize.Height]; Marshal.Copy(data, dataArray, 0, dataArray.Length); _WriteDataToTexture(texture, dataArray); } @@ -250,7 +267,7 @@ namespace Vocaluxe.Lib.Draw /// private TTextureType _CreateAndFillTexture(Size dataSize, byte[] data) { - TTextureType texture = _CreateTexture(dataSize); + var texture = _CreateTexture(dataSize); _WriteDataToTexture(texture, data); return texture; } @@ -266,7 +283,7 @@ namespace Vocaluxe.Lib.Draw Bitmap bmp2 = null; try { - Size size = _GetNewTextureSize(bmp.GetSize()); + var size = _GetNewTextureSize(bmp.GetSize()); if (!size.Equals(bmp.GetSize())) { bmp2 = bmp.Resize(size); @@ -274,18 +291,25 @@ namespace Vocaluxe.Lib.Draw } //Fill the new Bitmap with the texture data - BitmapData bmpData = bmp.LockBits(bmp.GetRect(), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); + var bmpData = bmp.LockBits(bmp.GetRect(), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); if (texture == null) + { texture = _CreateTexture(size); + } else + { texture.DataSize = size; + } + _WriteDataToTexture(texture, bmpData.Scan0); bmp.UnlockBits(bmpData); } finally { if (bmp2 != null) + { bmp2.Dispose(); + } } } @@ -299,14 +323,17 @@ namespace Vocaluxe.Lib.Draw /// private void _AddToCache(TTextureType texture, Size origSize, string texturePath) { - if (String.IsNullOrEmpty(texturePath)) + if (string.IsNullOrEmpty(texturePath)) + { return; + } + Debug.Assert(texture != null); lock (_Textures) { Debug.Assert(!_TextureCache.ContainsKey(texturePath)); texture.TexturePath = texturePath; - STextureCacheEntry cacheEntry = new STextureCacheEntry {OrigSize = origSize, Texture = texture}; + var cacheEntry = new STextureCacheEntry { OrigSize = origSize, Texture = texture }; _TextureCache.Add(texturePath, cacheEntry); } } @@ -321,29 +348,36 @@ namespace Vocaluxe.Lib.Draw private CTextureRef _GetFromCache(string texturePath, out Task loader) { loader = null; - if (String.IsNullOrEmpty(texturePath)) + if (string.IsNullOrEmpty(texturePath)) + { return null; + } + lock (_TextureCache) - lock (_Textures) + lock (_Textures) + { + STextureCacheEntry cacheEntry; + if (_TextureCache.TryGetValue(texturePath, out cacheEntry)) { - STextureCacheEntry cacheEntry; - if (_TextureCache.TryGetValue(texturePath, out cacheEntry)) + if (cacheEntry.Texture.RefCount <= 0) { - if (cacheEntry.Texture.RefCount <= 0) - _TextureCache.Remove(texturePath); - else + _TextureCache.Remove(texturePath); + } + else + { + if (cacheEntry.OrigSize.Width < 0) { - if (cacheEntry.OrigSize.Width < 0) + lock (_BitmapsLoading) { - lock (_BitmapsLoading) - { - loader = _BitmapsLoading[texturePath]; - } + loader = _BitmapsLoading[texturePath]; } - return _GetTextureReference(cacheEntry.OrigSize, cacheEntry.Texture); } + + return _GetTextureReference(cacheEntry.OrigSize, cacheEntry.Texture); } } + } + return null; } @@ -360,18 +394,23 @@ namespace Vocaluxe.Lib.Draw Debug.Assert(origSize.Width > 0 && origSize.Height > 0 || origSize.Width == -1 && origSize.Height == -1); Debug.Assert(texture != null); int id; - lock (_MutexID) + lock (_MutexId) { - id = _NextID++; + id = _NextId++; } - CTextureRef textureRef = new CTextureRef(id, origSize); + + var textureRef = new CTextureRef(id, origSize); lock (_Textures) { if (texture.RefCount == 0) + { _TextureCount++; + } + texture.RefCount++; _Textures.Add(id, texture); } + return textureRef; } @@ -392,14 +431,23 @@ namespace Vocaluxe.Lib.Draw private static bool _IsTextureUsable(TTextureType texture, Size dataSize) { if (texture == null) + { return false; + } + if (!texture.DataSize.Equals(dataSize)) { if (texture.Size.Width < dataSize.Width || texture.Size.Height < dataSize.Height) + { return false; // Texture memory to small + } + if (texture.Size.Width * 0.9 > dataSize.Width || texture.Size.Height * 0.9 > dataSize.Height) + { return false; // Texture memory to big + } } + return true; } @@ -410,9 +458,10 @@ namespace Vocaluxe.Lib.Draw texture = null; return false; } + lock (_Textures) { - return _Textures.TryGetValue(textureRef.ID, out texture) && (!checkDrawable || texture.IsLoaded); + return _Textures.TryGetValue(textureRef.Id, out texture) && (!checkDrawable || texture.IsLoaded); } } @@ -428,7 +477,10 @@ namespace Vocaluxe.Lib.Draw if (texture != null && --texture.RefCount <= 0) { if (texture.TexturePath != null) + { _TextureCache.Remove(texture.TexturePath); + } + texture.Dispose(); _TextureCount--; } @@ -442,63 +494,82 @@ namespace Vocaluxe.Lib.Draw { while (_TextureQueue.Count > 0) { - STextureQueue q = _TextureQueue.Dequeue(); + var q = _TextureQueue.Dequeue(); if (q.Action == EQueueAction.Add) { - TTextureType oldTexture = q.TextureOrRef as TTextureType; + var oldTexture = q.TextureOrRef as TTextureType; Debug.Assert(oldTexture != null, "Queued type is wrong"); Debug.Assert(!oldTexture.IsLoaded); if (oldTexture.RefCount <= 0) { - Bitmap bmp = q.Data as Bitmap; + var bmp = q.Data as Bitmap; if (bmp != null) + { bmp.Dispose(); + } + continue; } + TTextureType texture = null; // ReSharper disable CanBeReplacedWithTryCastAndCheckForNull if (q.Data is Bitmap) { - Bitmap bmp = (Bitmap)q.Data; + var bmp = (Bitmap)q.Data; _WriteBitmapToTexture(ref texture, bmp); bmp.Dispose(); } else if (q.Data is byte[]) + { texture = _CreateAndFillTexture(q.DataSize, (byte[])q.Data); + } else + { throw new ArgumentException("q.Data is of invalid type"); + } // ReSharper restore CanBeReplacedWithTryCastAndCheckForNull + _MergeTextures(oldTexture, texture); } else { - CTextureRef textureRef = q.TextureOrRef as CTextureRef; + var textureRef = q.TextureOrRef as CTextureRef; Debug.Assert(textureRef != null, "Queued type is wrong"); - if (!_Textures.ContainsKey(textureRef.ID)) + if (!_Textures.ContainsKey(textureRef.Id)) { - Bitmap bmp = q.Data as Bitmap; + var bmp = q.Data as Bitmap; if (bmp != null) + { bmp.Dispose(); + } + continue; } + if (q.Action == EQueueAction.Update) { // ReSharper disable CanBeReplacedWithTryCastAndCheckForNull if (q.Data is Bitmap) { - Bitmap bmp = (Bitmap)q.Data; + var bmp = (Bitmap)q.Data; UpdateTexture(textureRef, bmp); bmp.Dispose(); } else if (q.Data is byte[]) + { UpdateTexture(textureRef, q.DataSize, (byte[])q.Data); + } else + { throw new ArgumentException("q.Data is of invalid type"); + } // ReSharper restore CanBeReplacedWithTryCastAndCheckForNull } else if (q.Action == EQueueAction.Delete) + { RemoveTexture(ref textureRef); + } } } } @@ -517,9 +588,12 @@ namespace Vocaluxe.Lib.Draw { newTexture.RefCount += oldTexture.RefCount; IEnumerable oldKeys = _Textures.Where(pair => pair.Value == oldTexture).Select(pair => pair.Key).ToArray(); - foreach (int key in oldKeys) + foreach (var key in oldKeys) + { _Textures[key] = newTexture; - if (!String.IsNullOrEmpty(oldTexture.TexturePath)) + } + + if (!string.IsNullOrEmpty(oldTexture.TexturePath)) { newTexture.TexturePath = oldTexture.TexturePath; STextureCacheEntry cacheEntry; @@ -529,6 +603,7 @@ namespace Vocaluxe.Lib.Draw _TextureCache[newTexture.TexturePath] = cacheEntry; } } + oldTexture.Dispose(); } } @@ -548,9 +623,13 @@ namespace Vocaluxe.Lib.Draw if (_RequiresResize(bmp.GetSize())) { if (asyncResize) + { Task.Factory.StartNew(() => _ResizeTextureAndEnqueue(texture, bmp, action)); + } else + { _ResizeTextureAndEnqueue(texture, bmp, action); + } } else { @@ -569,7 +648,7 @@ namespace Vocaluxe.Lib.Draw /// private void _ResizeTextureAndEnqueue(object texture, Bitmap bmp, EQueueAction action) { - Bitmap bmp2 = bmp.Resize(_GetNewTextureSize(bmp.Size)); + var bmp2 = bmp.Resize(_GetNewTextureSize(bmp.Size)); bmp.Dispose(); lock (_TextureQueue) { @@ -586,7 +665,7 @@ namespace Vocaluxe.Lib.Draw /// private Size _LoadAndEnqueueBitmap(string filePath, CTextureRef textureRef, TTextureType texture) { - Bitmap bmp = CHelper.LoadBitmap(filePath); + var bmp = CHelper.LoadBitmap(filePath); if (bmp == null) { RemoveTexture(ref textureRef); // Done asynchonously in the function @@ -598,9 +677,11 @@ namespace Vocaluxe.Lib.Draw _BitmapsLoading.Remove(filePath); } } + return new Size(-1, -1); } - Size origSize = bmp.GetSize(); + + var origSize = bmp.GetSize(); textureRef.OrigSize = origSize; // Update cache, use the same lock as in add/get cache methods lock (_Textures) @@ -611,11 +692,13 @@ namespace Vocaluxe.Lib.Draw cacheEntry.OrigSize = origSize; _TextureCache[filePath] = cacheEntry; } + lock (_BitmapsLoading) { _BitmapsLoading.Remove(filePath); } } + _EnqueueTextureAddOrUpdate(texture, bmp, EQueueAction.Add, false); return origSize; } @@ -634,17 +717,24 @@ namespace Vocaluxe.Lib.Draw { textureRef = _GetFromCache(texturePath, out loader); } + if (textureRef != null) { if (loader != null) + { textureRef.OrigSize = loader.Result; + } + Debug.Assert(textureRef.OrigSize.Width > 0); return textureRef; } - Bitmap bmp = CHelper.LoadBitmap(texturePath); + var bmp = CHelper.LoadBitmap(texturePath); if (bmp == null) + { return null; + } + try { textureRef = AddTexture(bmp, texturePath); @@ -653,6 +743,7 @@ namespace Vocaluxe.Lib.Draw { bmp.Dispose(); } + return textureRef; } @@ -672,10 +763,12 @@ namespace Vocaluxe.Lib.Draw { _EnsureMainThread(); if (bmp.Height == 0 || bmp.Width == 0) + { return null; + } CTextureRef textureRef; - Size origSize = bmp.GetSize(); + var origSize = bmp.GetSize(); TTextureType texture = null; Task loader; // Make the Get/Add Cache methods atomic @@ -689,10 +782,16 @@ namespace Vocaluxe.Lib.Draw _AddToCache(texture, origSize, texturePath); } } + if (textureRef == null) + { textureRef = _GetTextureReference(origSize, texture); + } else if (loader != null) + { textureRef.OrigSize = loader.Result; + } + Debug.Assert(textureRef.OrigSize.Width > 0); return textureRef; } @@ -700,7 +799,7 @@ namespace Vocaluxe.Lib.Draw public CTextureRef AddTexture(int w, int h, byte[] data) { _EnsureMainThread(); - TTextureType texture = _CreateAndFillTexture(new Size(w, h), data); + var texture = _CreateAndFillTexture(new Size(w, h), data); return _GetTextureReference(w, h, texture); } @@ -708,8 +807,8 @@ namespace Vocaluxe.Lib.Draw { lock (_TextureQueue) { - TTextureType texture = _CreateTexture(new Size(-1, -1)); - CTextureRef textureRef = _GetTextureReference(w, h, texture); + var texture = _CreateTexture(new Size(-1, -1)); + var textureRef = _GetTextureReference(w, h, texture); _TextureQueue.Enqueue(new STextureQueue(texture, EQueueAction.Add, new Size(w, h), data)); return textureRef; } @@ -717,8 +816,8 @@ namespace Vocaluxe.Lib.Draw public CTextureRef EnqueueTexture(Bitmap bmp) { - TTextureType texture = _CreateTexture(new Size(-1, -1)); - CTextureRef textureRef = _GetTextureReference(bmp.GetSize(), texture); + var texture = _CreateTexture(new Size(-1, -1)); + var textureRef = _GetTextureReference(bmp.GetSize(), texture); _EnqueueTextureAddOrUpdate(texture, bmp, EQueueAction.Add, true); return textureRef; @@ -733,7 +832,10 @@ namespace Vocaluxe.Lib.Draw // All solved with atomic get/add cache and _WaitForTextureLoaded if (!File.Exists(filePath)) + { return null; + } + CTextureRef textureRef; TTextureType texture = null; Task loader; @@ -744,7 +846,7 @@ namespace Vocaluxe.Lib.Draw if (textureRef == null) { Debug.Assert(loader == null); - Size invalidSize = new Size(-1, -1); + var invalidSize = new Size(-1, -1); texture = _CreateTexture(invalidSize); // This cache entry has to be updated once the real origSize is available _AddToCache(texture, invalidSize, filePath); @@ -762,9 +864,12 @@ namespace Vocaluxe.Lib.Draw if (texture == null) { // Found in cache - CTextureRef tmp = textureRef; // Workaround for implicitly captured closure warning (false positive) + var tmp = textureRef; // Workaround for implicitly captured closure warning (false positive) if (loader != null) + { Task.Factory.StartNew(() => tmp.OrigSize = loader.Result); + } + return textureRef; } @@ -796,8 +901,11 @@ namespace Vocaluxe.Lib.Draw _EnsureMainThread(); TTextureType texture; if (!_GetTexture(textureRef, out texture, false)) + { return; - bool reuseTexture = _IsTextureUsable(texture, dataSize); + } + + var reuseTexture = _IsTextureUsable(texture, dataSize); if (reuseTexture && texture.RefCount == 1) { texture.DataSize = dataSize; @@ -808,7 +916,7 @@ namespace Vocaluxe.Lib.Draw _DisposeTexture(texture); texture = _CreateAndFillTexture(dataSize, data); texture.RefCount = 1; - _Textures[textureRef.ID] = texture; + _Textures[textureRef.Id] = texture; } } @@ -817,17 +925,22 @@ namespace Vocaluxe.Lib.Draw _EnsureMainThread(); TTextureType texture; if (!_GetTexture(textureRef, out texture, false)) + { return; - bool reuseTexture = _IsTextureUsable(texture, bmp.Size); + } + + var reuseTexture = _IsTextureUsable(texture, bmp.Size); if (reuseTexture && texture.RefCount == 1) + { _WriteBitmapToTexture(ref texture, bmp); + } else { _DisposeTexture(texture); texture = null; _WriteBitmapToTexture(ref texture, bmp); texture.RefCount = 1; - _Textures[textureRef.ID] = texture; + _Textures[textureRef.Id] = texture; } } @@ -838,18 +951,25 @@ namespace Vocaluxe.Lib.Draw { TTextureType texture; if (!_GetTexture(textureRef, out texture, false)) + { return null; + } + // If bitmap is not yet loaded, wait for it - if (!String.IsNullOrEmpty(texture.TexturePath)) + if (!string.IsNullOrEmpty(texture.TexturePath)) { Task loader; lock (_BitmapsLoading) { _BitmapsLoading.TryGetValue(texture.TexturePath, out loader); } + if (loader != null) + { textureRef.OrigSize = loader.Result; + } } + Debug.Assert(textureRef.OrigSize.Width > 0); return _GetTextureReference(textureRef.OrigSize, texture); } @@ -862,29 +982,36 @@ namespace Vocaluxe.Lib.Draw public void RemoveTexture(ref CTextureRef textureRef) { if (textureRef == null) - return; - if (textureRef.ID > 0) { - if (_MainThreadID != Thread.CurrentThread.ManagedThreadId) + return; + } + + if (textureRef.Id > 0) + { + if (_MainThreadId != Thread.CurrentThread.ManagedThreadId) { lock (_TextureQueue) { _TextureQueue.Enqueue(new STextureQueue(textureRef, EQueueAction.Delete, null)); } + textureRef = null; return; } + lock (_Textures) { TTextureType t; - if (_Textures.TryGetValue(textureRef.ID, out t)) + if (_Textures.TryGetValue(textureRef.Id, out t)) { _DisposeTexture(t); - _Textures.Remove(textureRef.ID); + _Textures.Remove(textureRef.Id); } + textureRef.SetRemoved(); } } + textureRef = null; } diff --git a/Vocaluxe/Lib/Input/CControllerFramework.cs b/Vocaluxe/Lib/Input/CControllerFramework.cs index 2ac282d1..b9519062 100644 --- a/Vocaluxe/Lib/Input/CControllerFramework.cs +++ b/Vocaluxe/Lib/Input/CControllerFramework.cs @@ -34,7 +34,10 @@ namespace Vocaluxe.Lib.Input public virtual bool Init() { if (_Initialized) + { return false; + } + _CurrentKeysPool = new List(); _CurrentMousePool = new List(); _Initialized = true; @@ -44,13 +47,22 @@ namespace Vocaluxe.Lib.Input public virtual void Close() { if (!_Initialized) + { return; + } + _CurrentKeysPool = null; _CurrentMousePool = null; lock (_KeysPool) + { _KeysPool.Clear(); + } + lock (_MousePool) + { _MousePool.Clear(); + } + _Initialized = false; } @@ -63,18 +75,27 @@ namespace Vocaluxe.Lib.Input public virtual void Update() { if (!_Initialized) + { return; + } + lock (_KeysPool) { - foreach (SKeyEvent e in _KeysPool) + foreach (var e in _KeysPool) + { _CurrentKeysPool.Add(e); + } + _KeysPool.Clear(); } lock (_MousePool) { - foreach (SMouseEvent e in _MousePool) + foreach (var e in _MousePool) + { _CurrentMousePool.Add(e); + } + _MousePool.Clear(); } } @@ -82,26 +103,34 @@ namespace Vocaluxe.Lib.Input public virtual bool PollKeyEvent(ref SKeyEvent keyEvent) { if (!_Initialized) + { return false; + } + if (_CurrentKeysPool.Count > 0) { keyEvent = _CurrentKeysPool[0]; _CurrentKeysPool.RemoveAt(0); return true; } + return false; } public virtual bool PollMouseEvent(ref SMouseEvent mouseEvent) { if (!_Initialized) + { return false; + } + if (_CurrentMousePool.Count > 0) { mouseEvent = _CurrentMousePool[0]; _CurrentMousePool.RemoveAt(0); return true; } + return false; } @@ -110,7 +139,10 @@ namespace Vocaluxe.Lib.Input public void AddKeyEvent(SKeyEvent keyEvent) { if (!_Initialized) + { return; + } + lock (_KeysPool) { _KeysPool.Add(keyEvent); @@ -120,7 +152,10 @@ namespace Vocaluxe.Lib.Input public void AddMouseEvent(SMouseEvent mouseEvent) { if (!_Initialized) + { return; + } + lock (_MousePool) { _MousePool.Add(mouseEvent); diff --git a/Vocaluxe/Lib/Input/CGamePad.cs b/Vocaluxe/Lib/Input/CGamePad.cs index d9fb8d72..57d1a47c 100644 --- a/Vocaluxe/Lib/Input/CGamePad.cs +++ b/Vocaluxe/Lib/Input/CGamePad.cs @@ -16,9 +16,9 @@ #endregion using System; -using System.Threading; -using System.Diagnostics; using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; using System.Windows.Forms; using OpenTK.Input; using Vocaluxe.Base; @@ -79,7 +79,9 @@ namespace Vocaluxe.Lib.Input public override bool Init() { if (!base.Init()) + { return false; + } _rumbleTimer = new CRumbleTimer(); _evTerminate = new AutoResetEvent(false); @@ -97,10 +99,14 @@ namespace Vocaluxe.Lib.Input public override void Connect() { if (_active) + { return; + } if (_evTerminate == null) + { _evTerminate = new AutoResetEvent(false); + } if (_handlerThread == null) { @@ -126,12 +132,16 @@ namespace Vocaluxe.Lib.Input _active = false; if (_evTerminate != null) + { _evTerminate.Set(); + } if (_handlerThread != null) { if (!_handlerThread.Join(ThreadJoinTimeoutMs)) + { Debug.WriteLine("CGamePad: Handler thread did not terminate within timeout."); + } _handlerThread = null; } @@ -139,7 +149,9 @@ namespace Vocaluxe.Lib.Input try { if (_GamePadIndex != -1) + { GamePad.SetVibration(_GamePadIndex, 0.0f, 0.0f); + } } catch (Exception ex) { @@ -167,7 +179,9 @@ namespace Vocaluxe.Lib.Input lock (_Sync) { if (_rumbleTimer != null) + { _rumbleTimer.Set(duration); + } } } @@ -180,7 +194,9 @@ namespace Vocaluxe.Lib.Input Thread.Sleep(PollSleepMs); if (!_EnsureConnected()) + { continue; + } try { @@ -202,13 +218,19 @@ namespace Vocaluxe.Lib.Input private bool _EnsureConnected() { if (Connected) + { return true; + } if (_DoConnect()) + { return true; + } if (_evTerminate != null) + { _evTerminate.WaitOne(ReconnectWaitMs); + } return false; } @@ -224,16 +246,22 @@ namespace Vocaluxe.Lib.Input stopRumble = _rumbleTimer != null && _rumbleTimer.ShouldStop; } - int currentIndex = _GamePadIndex; + var currentIndex = _GamePadIndex; if (currentIndex == -1) + { return; + } if (startRumble) + { GamePad.SetVibration(currentIndex, 1.0f, 1.0f); + } else if (stopRumble) + { GamePad.SetVibration(currentIndex, 0.0f, 0.0f); + } - GamePadState state = GamePad.GetState(currentIndex); + var state = GamePad.GetState(currentIndex); if (!GamePad.GetCapabilities(currentIndex).IsConnected) { @@ -261,7 +289,9 @@ namespace Vocaluxe.Lib.Input private static void _StopVibrationBestEffort(int gamePadIndex) { if (gamePadIndex == -1) + { return; + } try { @@ -275,17 +305,17 @@ namespace Vocaluxe.Lib.Input private void _HandleButtons(GamePadState buttonStates) { - bool leftClickTriggered = - (buttonStates.Buttons.LeftShoulder == OpenTK.Input.ButtonState.Pressed && - _oldButtonStates.Buttons.LeftShoulder == OpenTK.Input.ButtonState.Released); + var leftClickTriggered = + buttonStates.Buttons.LeftShoulder == OpenTK.Input.ButtonState.Pressed && + _oldButtonStates.Buttons.LeftShoulder == OpenTK.Input.ButtonState.Released; - bool rightClickTriggered = - (buttonStates.Buttons.RightShoulder == OpenTK.Input.ButtonState.Pressed && - _oldButtonStates.Buttons.RightShoulder == OpenTK.Input.ButtonState.Released); + var rightClickTriggered = + buttonStates.Buttons.RightShoulder == OpenTK.Input.ButtonState.Pressed && + _oldButtonStates.Buttons.RightShoulder == OpenTK.Input.ButtonState.Released; leftClickTriggered |= - (buttonStates.Buttons.RightStick == OpenTK.Input.ButtonState.Pressed && - _oldButtonStates.Buttons.RightStick == OpenTK.Input.ButtonState.Released); + buttonStates.Buttons.RightStick == OpenTK.Input.ButtonState.Pressed && + _oldButtonStates.Buttons.RightStick == OpenTK.Input.ButtonState.Released; var keys = new List(); @@ -380,7 +410,7 @@ namespace Vocaluxe.Lib.Input keys.Add(Keys.Back); } - foreach (Keys key in keys) + foreach (var key in keys) { AddKeyEvent(new SKeyEvent( ESender.Gamepad, @@ -392,16 +422,20 @@ namespace Vocaluxe.Lib.Input key)); } - float rightX = buttonStates.ThumbSticks.Right.X; - float rightY = buttonStates.ThumbSticks.Right.Y; + var rightX = buttonStates.ThumbSticks.Right.X; + var rightY = buttonStates.ThumbSticks.Right.Y; if (Math.Abs(rightX) < RightStickMouseDeadZone) + { rightX = 0.0f; + } if (Math.Abs(rightY) < RightStickMouseDeadZone) + { rightY = 0.0f; + } - bool hasMouseDelta = + var hasMouseDelta = Math.Abs(rightX) > MouseAxisEpsilon || Math.Abs(rightY) > MouseAxisEpsilon; @@ -414,7 +448,7 @@ namespace Vocaluxe.Lib.Input _mouseX = Math.Min(CSettings.RenderW, Math.Max(0.0f, _mouseX)); _mouseY = Math.Min(CSettings.RenderH, Math.Max(0.0f, _mouseY)); - bool mouseMoved = + var mouseMoved = hasMouseDelta || leftClickTriggered || rightClickTriggered; @@ -478,7 +512,7 @@ namespace Vocaluxe.Lib.Input { _GamePadIndex = -1; - for (int i = 0; i < MaxGamePads; i++) + for (var i = 0; i < MaxGamePads; i++) { try { @@ -495,7 +529,9 @@ namespace Vocaluxe.Lib.Input } if (_GamePadIndex == -1) + { return false; + } _oldButtonStates = new GamePadState(); _ResetAllRepeatTimers(); @@ -525,4 +561,4 @@ namespace Vocaluxe.Lib.Input return true; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Input/CHIDAPI.cs b/Vocaluxe/Lib/Input/CHIDAPI.cs index 86fa686e..4136f1a1 100644 --- a/Vocaluxe/Lib/Input/CHIDAPI.cs +++ b/Vocaluxe/Lib/Input/CHIDAPI.cs @@ -17,7 +17,6 @@ using System; using System.Runtime.InteropServices; -using Vocaluxe.Base; using VocaluxeLib.Log; namespace Vocaluxe.Lib.Input @@ -26,16 +25,21 @@ namespace Vocaluxe.Lib.Input public struct SHIDDeviceInfo { // ReSharper disable MemberCanBePrivate.Global - [MarshalAs(UnmanagedType.LPTStr)] public readonly String Path; + [MarshalAs(UnmanagedType.LPTStr)] + public readonly String Path; public readonly ushort VendorString; - public readonly ushort ProductID; - [MarshalAs(UnmanagedType.LPWStr)] public readonly String SerialNumber; + public readonly ushort ProductId; + [MarshalAs(UnmanagedType.LPWStr)] + public readonly String SerialNumber; public readonly ushort ReleaseNumber; - [MarshalAs(UnmanagedType.LPWStr)] public readonly String ManufacturerString; - [MarshalAs(UnmanagedType.LPWStr)] public readonly String ProductString; + [MarshalAs(UnmanagedType.LPWStr)] + public readonly String ManufacturerString; + [MarshalAs(UnmanagedType.LPWStr)] + public readonly String ProductString; public readonly ushort UsagePage; public readonly ushort Usage; - [MarshalAs(UnmanagedType.LPWStr)] public readonly int InterfaceNumber; + [MarshalAs(UnmanagedType.LPWStr)] + public readonly int InterfaceNumber; internal IntPtr Next; // ReSharper restore MemberCanBePrivate.Global } @@ -101,13 +105,13 @@ namespace Vocaluxe.Lib.Input } [DllImport(_HIDApiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_enumerate", CharSet = CharSet.Ansi)] - private static extern IntPtr hid_enumerate(ushort vendorID, ushort productID); + private static extern IntPtr hid_enumerate(ushort vendorId, ushort productId); //HIDDeviceInfo - public static IntPtr Enumerate(ushort vendorID, ushort productID) + public static IntPtr Enumerate(ushort vendorId, ushort productId) { //HIDDeviceInfo - return hid_enumerate(vendorID, productID); + return hid_enumerate(vendorId, productId); } [DllImport(_HIDApiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_free_enumeration", CharSet = CharSet.Unicode)] @@ -119,14 +123,14 @@ namespace Vocaluxe.Lib.Input } [DllImport(_HIDApiDll, ExactSpelling = false, CallingConvention = CallingConvention.Cdecl, EntryPoint = "hid_open", CharSet = CharSet.Unicode)] - private static extern IntPtr hid_open(ushort vendorID, ushort productID, IntPtr serialNumber); + private static extern IntPtr hid_open(ushort vendorId, ushort productId, IntPtr serialNumber); - public static bool Open(ushort vendorID, ushort productID, out IntPtr handle) + public static bool Open(ushort vendorId, ushort productId, out IntPtr handle) { handle = IntPtr.Zero; try { - handle = hid_open(vendorID, productID, IntPtr.Zero); + handle = hid_open(vendorId, productId, IntPtr.Zero); } catch (Exception e) { @@ -135,7 +139,9 @@ namespace Vocaluxe.Lib.Input } if (handle != IntPtr.Zero) + { return true; + } return false; } @@ -161,7 +167,7 @@ namespace Vocaluxe.Lib.Input public static int ReadTimeout(IntPtr device, ref byte[] data, int length, int milliseconds) { - IntPtr dataPtr = Marshal.AllocHGlobal(length); + var dataPtr = Marshal.AllocHGlobal(length); int bytesRead; try { @@ -174,9 +180,13 @@ namespace Vocaluxe.Lib.Input } if (bytesRead != -1) + { Marshal.Copy(dataPtr, data, 0, bytesRead); + } else + { data = null; + } Marshal.FreeHGlobal(dataPtr); @@ -189,7 +199,7 @@ namespace Vocaluxe.Lib.Input public static int Read(IntPtr device, out byte[] data, int length) { data = new byte[length]; - IntPtr dataPtr = Marshal.AllocHGlobal(length); + var dataPtr = Marshal.AllocHGlobal(length); int result; try @@ -203,9 +213,13 @@ namespace Vocaluxe.Lib.Input } if (result != -1) + { Marshal.Copy(dataPtr, data, 0, result); + } else + { data = null; + } Marshal.FreeHGlobal(dataPtr); return result; @@ -249,6 +263,7 @@ namespace Vocaluxe.Lib.Input CLog.Error("Error CHIDAPI.Close(): " + e); return false; } + return true; } diff --git a/Vocaluxe/Lib/Input/IController.cs b/Vocaluxe/Lib/Input/IController.cs index cd6bec01..97af97fd 100644 --- a/Vocaluxe/Lib/Input/IController.cs +++ b/Vocaluxe/Lib/Input/IController.cs @@ -126,10 +126,12 @@ namespace Vocaluxe.Lib.Input public EGesture GetGesture(Point newPosition) { if (!_Locked) + { return EGesture.None; + } - int dx = newPosition.X - _Begin.X; - int dy = newPosition.Y - _Begin.Y; + var dx = newPosition.X - _Begin.X; + var dy = newPosition.Y - _Begin.Y; //Back/Escape if (dx < -150 && Math.Abs(dy) < 150) diff --git a/Vocaluxe/Lib/Input/WiiMote/CWiiMote.cs b/Vocaluxe/Lib/Input/WiiMote/CWiiMote.cs index c2919c1b..a30b79d9 100644 --- a/Vocaluxe/Lib/Input/WiiMote/CWiiMote.cs +++ b/Vocaluxe/Lib/Input/WiiMote/CWiiMote.cs @@ -31,7 +31,7 @@ namespace Vocaluxe.Lib.Input.WiiMote private bool[] _ButtonStates; private Point _OldPosition; private bool _Connected; - + private Object _Sync; private bool _Active; private CRumbleTimer _RumbleTimer; @@ -46,7 +46,10 @@ namespace Vocaluxe.Lib.Input.WiiMote public override bool Init() { if (!base.Init()) + { return false; + } + _Sync = new Object(); _RumbleTimer = new CRumbleTimer(); _Gesture = new CGesture(); @@ -74,9 +77,12 @@ namespace Vocaluxe.Lib.Input.WiiMote public override void Connect() { if (_Active) + { return; + } + _Active = true; - + _WiiMote.Connect(); } @@ -118,7 +124,7 @@ namespace Vocaluxe.Lib.Input.WiiMote _WiiMote.SetRumble(true); Thread.Sleep(250); _WiiMote.SetRumble(false); - + bool startRumble; bool stopRumble; @@ -129,9 +135,13 @@ namespace Vocaluxe.Lib.Input.WiiMote } if (startRumble) + { _WiiMote.SetRumble(true); + } else if (stopRumble) + { _WiiMote.SetRumble(false); + } _Connected = true; } @@ -140,43 +150,69 @@ namespace Vocaluxe.Lib.Input.WiiMote private void _WmWiiMoteChanged(object sender, CWiiMoteChangedEventArgs args) { if (!_Active) + { return; + } - CWiiMoteStatus ws = args.WiiMoteState; + var ws = args.WiiMoteState; - Point p = ws.IRState.Position; + var p = ws.IRState.Position; p.X = 1023 - p.X; - EGesture gesture = _Gesture.GetGesture(p); - bool lb = false; - bool rb = gesture == EGesture.Back; + var gesture = _Gesture.GetGesture(p); + var lb = false; + var rb = gesture == EGesture.Back; var key = Keys.None; if (ws.ButtonState.A && !_ButtonStates[0]) + { lb = true; + } else if (ws.ButtonState.B && !_ButtonStates[1]) + { _Gesture.SetLockPosition(p); + } else if (!ws.ButtonState.B && _ButtonStates[1]) + { _Gesture.Reset(); + } else if (ws.ButtonState.Down && !_ButtonStates[2]) + { key = Keys.Right; + } else if (ws.ButtonState.Up && !_ButtonStates[3]) + { key = Keys.Left; + } else if (ws.ButtonState.Left && !_ButtonStates[4]) + { key = Keys.Down; + } else if (ws.ButtonState.Right && !_ButtonStates[5]) + { key = Keys.Up; + } else if (ws.ButtonState.Home && !_ButtonStates[6]) + { key = Keys.Space; + } else if (ws.ButtonState.Minus && !_ButtonStates[7]) + { key = Keys.Subtract; + } else if (ws.ButtonState.Plus && !_ButtonStates[8]) + { key = Keys.Add; + } else if (ws.ButtonState.One && !_ButtonStates[9]) + { key = Keys.Enter; + } else if (ws.ButtonState.Two && !_ButtonStates[10]) + { key = Keys.Escape; + } _ButtonStates[0] = ws.ButtonState.A; _ButtonStates[1] = ws.ButtonState.B; @@ -192,30 +228,41 @@ namespace Vocaluxe.Lib.Input.WiiMote if (key != Keys.None) + { AddKeyEvent(new SKeyEvent(ESender.WiiMote, false, false, false, false, char.MinValue, key)); + } //mouse events const float reducing = 0.15f; const float factor = 1f / (1f - reducing * 2f); - float rx = ((p.X / 1024f) - reducing) * factor; - float ry = ((p.Y / 768f) - reducing) * factor; + var rx = (p.X / 1024f - reducing) * factor; + var ry = (p.Y / 768f - reducing) * factor; var x = (int)(rx * CSettings.RenderW); var y = (int)(ry * CSettings.RenderH); - bool lbh = !lb && ws.ButtonState.A; + var lbh = !lb && ws.ButtonState.A; - int wheel = 0; + var wheel = 0; if (gesture == EGesture.ScrollUp) + { wheel = -1; + } + if (gesture == EGesture.ScrollDown) + { wheel = 1; + } if (!lb && !rb && (p.X != _OldPosition.X || p.Y != _OldPosition.Y)) + { AddMouseEvent(new SMouseEvent(ESender.WiiMote, EModifier.None, x, y, false, false, false, wheel, lbh, false, false, false)); + } else if (lb || rb) + { AddMouseEvent(new SMouseEvent(ESender.WiiMote, EModifier.None, x, y, lb, false, rb, wheel, false, false, false, false)); + } _OldPosition.X = p.X; _OldPosition.Y = p.Y; diff --git a/Vocaluxe/Lib/Input/WiiMote/WiiMoteLib.cs b/Vocaluxe/Lib/Input/WiiMote/WiiMoteLib.cs index e6642331..f29eabe0 100644 --- a/Vocaluxe/Lib/Input/WiiMote/WiiMoteLib.cs +++ b/Vocaluxe/Lib/Input/WiiMote/WiiMoteLib.cs @@ -18,13 +18,11 @@ using System; using System.Drawing; using System.Threading; -using Vocaluxe.Base; using VocaluxeLib; using VocaluxeLib.Log; namespace Vocaluxe.Lib.Input.WiiMote { - #region DataTypes public class CWiiMoteStatus { @@ -136,6 +134,7 @@ namespace Vocaluxe.Lib.Input.WiiMote WiiMoteState = ws; } } + public class CWiiMoteConnectionChangedEventArgs : EventArgs { public readonly bool Connected; @@ -150,10 +149,10 @@ namespace Vocaluxe.Lib.Input.WiiMote public sealed class CWiiMoteLib { // ReSharper disable InconsistentNaming - private const ushort _VID = 0x057e; + private const ushort _VId = 0x057e; // ReSharper restore InconsistentNaming - private const ushort _PID = 0x0306; //Wiimotion - private const ushort _PIDPlus = 0x0330; //Wiimotion Plus + private const ushort _PId = 0x0306; //Wiimotion + private const ushort _PIdPlus = 0x0330; //Wiimotion Plus // registers private const int _RegisterIR = 0x04b00030; @@ -200,7 +199,9 @@ namespace Vocaluxe.Lib.Input.WiiMote _Connected = value; if (WiiMoteConnectionChanged != null) + { WiiMoteConnectionChanged.Invoke(this, new CWiiMoteConnectionChangedEventArgs(value)); + } } } @@ -232,14 +233,17 @@ namespace Vocaluxe.Lib.Input.WiiMote private void _StartReader() { - _Reader = new Thread(_ReaderLoop) {Name = "WiiMoteLib"}; + _Reader = new Thread(_ReaderLoop) { Name = "WiiMoteLib" }; _Reader.Start(); } private void _WaitForReader() { if (_Reader == null) + { return; + } + _Reader.Join(); _Reader = null; } @@ -248,27 +252,35 @@ namespace Vocaluxe.Lib.Input.WiiMote { //We might have had a reader thread, that is not finished yet, so let it finish and close it's handle first or it will close the new one _WaitForReader(); - Connected = CHIDApi.Open(_VID, pid, out _Handle); + Connected = CHIDApi.Open(_VId, pid, out _Handle); if (Connected) { _StartReader(); if (!_ReadCalibration()) + { Connected = false; + } } } public bool Connect() { if (Connected) + { return true; + } if (_Error) + { return false; + } - _TryConnect(_PID); //Try WiiMotion + _TryConnect(_PId); //Try WiiMotion if (!Connected) - _TryConnect(_PIDPlus); //Try WiiMotion Plus + { + _TryConnect(_PIdPlus); //Try WiiMotion Plus + } return Connected; } @@ -281,7 +293,9 @@ namespace Vocaluxe.Lib.Input.WiiMote public void SetReportType(EInputReport type, EIRSensitivity irSensitivity, bool continuous) { if (!Connected) + { return; + } switch (type) { @@ -309,7 +323,9 @@ namespace Vocaluxe.Lib.Input.WiiMote _WiiMoteState.LEDState.LED4 = led4; if (!Connected) + { return; + } _ClearReport(); @@ -329,9 +345,9 @@ namespace Vocaluxe.Lib.Input.WiiMote // the LED report also handles rumble SetLEDs(_WiiMoteState.LEDState.LED1, - _WiiMoteState.LEDState.LED2, - _WiiMoteState.LEDState.LED3, - _WiiMoteState.LEDState.LED4); + _WiiMoteState.LEDState.LED2, + _WiiMoteState.LEDState.LED3, + _WiiMoteState.LEDState.LED4); } #endregion Interface @@ -362,10 +378,14 @@ namespace Vocaluxe.Lib.Input.WiiMote if (bytesRead > 0 && _ParseInputReport(buff)) { if (WiiMoteChanged != null) + { WiiMoteChanged.Invoke(this, new CWiiMoteChangedEventArgs(_WiiMoteState)); + } } + Thread.Sleep(5); } + CHIDApi.Close(_Handle); } @@ -473,6 +493,7 @@ namespace Vocaluxe.Lib.Input.WiiMote _WiiMoteState.IRState.Sensors[0].Position.Y = buff[7] | ((buff[8] >> 6) & 0x03) << 8; _WiiMoteState.IRState.Sensors[0].Width = 0; } + _WiiMoteState.IRState.Sensors[1].Active = !(buff[9] == 0xff && buff[10] == 0xff); if (_WiiMoteState.IRState.Sensors[1].Active) { @@ -480,17 +501,22 @@ namespace Vocaluxe.Lib.Input.WiiMote _WiiMoteState.IRState.Sensors[1].Position.Y = buff[10] | ((buff[8] >> 2) & 0x03) << 8; _WiiMoteState.IRState.Sensors[1].Width = 0; } + break; case EIRMode.Extended: - for (int i = 0; i < 4; i++) + for (var i = 0; i < 4; i++) { _WiiMoteState.IRState.Sensors[i].Active = !(buff[6 + i * 3] == 0xff && buff[7 + i * 3] == 0xff && buff[8 + i * 3] == 0xff); if (!_WiiMoteState.IRState.Sensors[i].Active) + { continue; + } + _WiiMoteState.IRState.Sensors[i].Position.X = buff[6 + i * 3] | ((buff[8 + i * 3] >> 4) & 0x03) << 8; _WiiMoteState.IRState.Sensors[i].Position.Y = buff[7 + i * 3] | ((buff[8 + i * 3] >> 6) & 0x03) << 8; _WiiMoteState.IRState.Sensors[i].Width = buff[8 + i * 3] & 0x0f; } + break; } @@ -505,14 +531,22 @@ namespace Vocaluxe.Lib.Input.WiiMote else if (_WiiMoteState.IRState.Sensors[0].Active) { if (_WiiMoteState.IRState.Sensors[0].Position.X > 512) + { _WiiMoteState.IRState.Position.X = _WiiMoteState.IRState.Sensors[0].Position.X - _WiiMoteState.IRState.Distance.X / 2; + } else + { _WiiMoteState.IRState.Position.X = _WiiMoteState.IRState.Sensors[0].Position.X + _WiiMoteState.IRState.Distance.X / 2; + } if (_WiiMoteState.IRState.Sensors[0].Position.X < 384) + { _WiiMoteState.IRState.Position.Y = _WiiMoteState.IRState.Sensors[0].Position.Y - _WiiMoteState.IRState.Distance.Y / 2; + } else + { _WiiMoteState.IRState.Position.Y = _WiiMoteState.IRState.Sensors[0].Position.Y + _WiiMoteState.IRState.Distance.Y / 2; + } } } @@ -530,13 +564,15 @@ namespace Vocaluxe.Lib.Input.WiiMote Connected = false; } - int size = (buff[3] >> 4) + 1; - int offset = buff[4] << 8 | buff[5]; + var size = (buff[3] >> 4) + 1; + var offset = buff[4] << 8 | buff[5]; Array.Copy(buff, 6, _ReadBuff, offset - _Address, size); if (_Address + _Size == offset + size) + { _ReadDone.Set(); + } } private byte _RumbleBit @@ -547,9 +583,11 @@ namespace Vocaluxe.Lib.Input.WiiMote private bool _ReadCalibration() { // this appears to change the report type to 0x31 - byte[] buff = _ReadData(0x0016, 7); + var buff = _ReadData(0x0016, 7); if (buff == null) + { return false; + } _WiiMoteState.AccelCalibrationInfo.X0 = buff[0]; _WiiMoteState.AccelCalibrationInfo.Y0 = buff[1]; @@ -583,36 +621,37 @@ namespace Vocaluxe.Lib.Input.WiiMote switch (sensitivity) { case EIRSensitivity.Level1: - _WriteData(_RegisterIRSensitivity1, 9, new byte[] {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0x64, 0x00, 0xfe}); + _WriteData(_RegisterIRSensitivity1, 9, new byte[] { 0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0x64, 0x00, 0xfe }); Thread.Sleep(50); - _WriteData(_RegisterIRSensitivity2, 2, new byte[] {0xfd, 0x05}); + _WriteData(_RegisterIRSensitivity2, 2, new byte[] { 0xfd, 0x05 }); break; case EIRSensitivity.Level2: - _WriteData(_RegisterIRSensitivity1, 9, new byte[] {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0x96, 0x00, 0xb4}); + _WriteData(_RegisterIRSensitivity1, 9, new byte[] { 0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0x96, 0x00, 0xb4 }); Thread.Sleep(50); - _WriteData(_RegisterIRSensitivity2, 2, new byte[] {0xb3, 0x04}); + _WriteData(_RegisterIRSensitivity2, 2, new byte[] { 0xb3, 0x04 }); break; case EIRSensitivity.Level3: - _WriteData(_RegisterIRSensitivity1, 9, new byte[] {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0xaa, 0x00, 0x64}); + _WriteData(_RegisterIRSensitivity1, 9, new byte[] { 0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0xaa, 0x00, 0x64 }); Thread.Sleep(50); - _WriteData(_RegisterIRSensitivity2, 2, new byte[] {0x63, 0x03}); + _WriteData(_RegisterIRSensitivity2, 2, new byte[] { 0x63, 0x03 }); break; case EIRSensitivity.Level4: - _WriteData(_RegisterIRSensitivity1, 9, new byte[] {0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0xc8, 0x00, 0x36}); + _WriteData(_RegisterIRSensitivity1, 9, new byte[] { 0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0xc8, 0x00, 0x36 }); Thread.Sleep(50); - _WriteData(_RegisterIRSensitivity2, 2, new byte[] {0x35, 0x03}); + _WriteData(_RegisterIRSensitivity2, 2, new byte[] { 0x35, 0x03 }); break; case EIRSensitivity.Level5: - _WriteData(_RegisterIRSensitivity1, 9, new byte[] {0x07, 0x00, 0x00, 0x71, 0x01, 0x00, 0x72, 0x00, 0x20}); + _WriteData(_RegisterIRSensitivity1, 9, new byte[] { 0x07, 0x00, 0x00, 0x71, 0x01, 0x00, 0x72, 0x00, 0x20 }); Thread.Sleep(50); - _WriteData(_RegisterIRSensitivity2, 2, new byte[] {0x1, 0x03}); + _WriteData(_RegisterIRSensitivity2, 2, new byte[] { 0x1, 0x03 }); break; case EIRSensitivity.Max: - _WriteData(_RegisterIRSensitivity1, 9, new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x00, 0x41}); + _WriteData(_RegisterIRSensitivity1, 9, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x90, 0x00, 0x41 }); Thread.Sleep(50); - _WriteData(_RegisterIRSensitivity2, 2, new byte[] {0x40, 0x00}); + _WriteData(_RegisterIRSensitivity2, 2, new byte[] { 0x40, 0x00 }); break; } + Thread.Sleep(50); _WriteData(_RegisterIRMode, (byte)mode); Thread.Sleep(50); @@ -670,7 +709,7 @@ namespace Vocaluxe.Lib.Input.WiiMote private void _WriteData(int address, byte data) { - _WriteData(address, 1, new byte[] {data}); + _WriteData(address, 1, new byte[] { data }); } private void _WriteData(int address, byte size, byte[] buff) diff --git a/Vocaluxe/Lib/Playlist/CPlaylistFile.cs b/Vocaluxe/Lib/Playlist/CPlaylistFile.cs index 9c9c9ac4..8a9cfd15 100644 --- a/Vocaluxe/Lib/Playlist/CPlaylistFile.cs +++ b/Vocaluxe/Lib/Playlist/CPlaylistFile.cs @@ -23,7 +23,6 @@ using Vocaluxe.Base; using VocaluxeLib; using VocaluxeLib.Log; using VocaluxeLib.Menu; -using VocaluxeLib.Songs; using VocaluxeLib.Xml; namespace Vocaluxe.Lib.Playlist @@ -35,33 +34,37 @@ namespace Vocaluxe.Lib.Playlist public readonly int Id; public List Songs = new List(); - private static int _NextID; + private static int _NextId; public CPlaylistFile() { - Id = _NextID++; + Id = _NextId++; } public void Save() { if (string.IsNullOrEmpty(File)) { - string filename = string.Empty; + var filename = string.Empty; // ReSharper disable LoopCanBeConvertedToQuery - foreach (char chr in Name) + foreach (var chr in Name) // ReSharper restore LoopCanBeConvertedToQuery { if (char.IsLetter(chr)) + { filename += chr.ToString(); + } } if (filename == "") + { filename = "1"; + } File = CHelper.GetUniqueFileName(Path.Combine(CSettings.DataFolder, CConfig.FolderPlaylists), filename + ".xml"); } - SPlaylist data = new SPlaylist {Info = {Name = Name}, Songs = Songs.Select(plSong => plSong.ToStruct()).ToArray()}; + var data = new SPlaylist { Info = { Name = Name }, Songs = Songs.Select(plSong => plSong.ToStruct()).ToArray() }; var xml = new CXmlSerializer(); xml.Serialize(File, data); @@ -81,36 +84,40 @@ namespace Vocaluxe.Lib.Playlist CLog.Error("Cannot load playlist from " + file + ": " + e.Message); return false; } + Name = data.Info.Name; Songs = new List(); - foreach (SPlaylistSong songEntry in data.Songs) + foreach (var songEntry in data.Songs) { - CSong plSong = CSongs.AllSongs.FirstOrDefault(song => song.Artist == songEntry.Artist && song.Title == songEntry.Title); + var plSong = CSongs.AllSongs.FirstOrDefault(song => song.Artist == songEntry.Artist && song.Title == songEntry.Title); if (plSong == null) + { CLog.Error("Can't find song '" + songEntry.Title + "' from '" + songEntry.Artist + "' in playlist file: " + File); + } else { - var playlistSong = new CPlaylistSong(plSong.ID, songEntry.GameMode); + var playlistSong = new CPlaylistSong(plSong.Id, songEntry.GameMode); Songs.Add(playlistSong); } } + return true; } - public void AddSong(int songID) + public void AddSong(int songId) { var song = new CPlaylistSong - { - SongID = songID, - GameMode = CSongs.GetSong(songID).IsGameModeAvailable(EGameMode.TR_GAMEMODE_DUET) ? EGameMode.TR_GAMEMODE_DUET : EGameMode.TR_GAMEMODE_NORMAL - }; + { + SongId = songId, + GameMode = CSongs.GetSong(songId).IsGameModeAvailable(EGameMode.TR_GAMEMODE_DUET) ? EGameMode.TR_GAMEMODE_DUET : EGameMode.TR_GAMEMODE_NORMAL + }; Songs.Add(song); } - public void AddSong(int songID, EGameMode gm) + public void AddSong(int songId, EGameMode gm) { - var song = new CPlaylistSong(songID, gm); + var song = new CPlaylistSong(songId, gm); Songs.Add(song); } @@ -123,31 +130,39 @@ namespace Vocaluxe.Lib.Playlist public void MoveSongUp(int songNr) { if (songNr < Songs.Count && songNr > 0) + { Songs.Reverse(songNr - 1, 2); + } } public void MoveSongDown(int songNr) { if (songNr < Songs.Count - 1 && songNr >= 0) + { Songs.Reverse(songNr, 2); + } } public void MoveSong(int sourceNr, int destNr) { if (sourceNr < 0 || destNr < 0 || sourceNr == destNr || sourceNr >= Songs.Count || destNr >= Songs.Count) + { return; + } - CPlaylistSong song = Songs[sourceNr]; + var song = Songs[sourceNr]; Songs.RemoveAt(sourceNr); Songs.Insert(destNr, song); } - public void InsertSong(int destNr, int songID, EGameMode gm) + public void InsertSong(int destNr, int songId, EGameMode gm) { if (destNr < 0 || destNr >= Songs.Count) + { return; + } - CPlaylistSong ps = new CPlaylistSong(songID, gm); + var ps = new CPlaylistSong(songId, gm); Songs.Insert(destNr, ps); } } diff --git a/Vocaluxe/Lib/Sound/CPortAudioHandle.cs b/Vocaluxe/Lib/Sound/CPortAudioHandle.cs index 49244cde..52295767 100644 --- a/Vocaluxe/Lib/Sound/CPortAudioHandle.cs +++ b/Vocaluxe/Lib/Sound/CPortAudioHandle.cs @@ -19,7 +19,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; using PortAudioSharp; -using Vocaluxe.Base; using VocaluxeLib.Log; namespace Vocaluxe.Lib.Sound @@ -49,8 +48,11 @@ namespace Vocaluxe.Lib.Sound if (_RefCount == 0) { if (CheckError("Initialize", PortAudio.Pa_Initialize())) + { throw new Exception(); + } } + _RefCount++; } } @@ -63,10 +65,14 @@ namespace Vocaluxe.Lib.Sound private void _Dispose(bool disposing) { if (_Disposed) + { return; + } if (!disposing) + { CLog.Debug("Did not close CPortAudioHandle"); + } IntPtr[] streamsToClose; lock (_Mutex) @@ -75,15 +81,21 @@ namespace Vocaluxe.Lib.Sound } if (streamsToClose.Length > 0) + { CLog.Debug("Did not close " + streamsToClose.Length + " PortAudio-Stream(s)"); + } - foreach (IntPtr stream in streamsToClose) + foreach (var stream in streamsToClose) + { CloseStream(stream); + } lock (_Mutex) { if (_Disposed) + { return; + } Debug.Assert(_RefCount > 0); _RefCount--; @@ -119,18 +131,23 @@ namespace Vocaluxe.Lib.Sound } public PortAudio.PaError OpenStream(out IntPtr stream, ref PortAudio.PaStreamParameters? inputParameters, ref PortAudio.PaStreamParameters? outputParameters, - double sampleRate, uint framesPerBuffer, PortAudio.PaStreamFlags streamFlags, - PortAudio.PaStreamCallbackDelegate streamCallback, IntPtr userData) + double sampleRate, uint framesPerBuffer, PortAudio.PaStreamFlags streamFlags, + PortAudio.PaStreamCallbackDelegate streamCallback, IntPtr userData) { lock (_Mutex) { if (_Disposed) + { throw new ObjectDisposedException("PortAudioHandle already disposed"); + } - PortAudio.PaError res = PortAudio.Pa_OpenStream(out stream, ref inputParameters, ref outputParameters, sampleRate, framesPerBuffer, streamFlags, streamCallback, - userData); + var res = PortAudio.Pa_OpenStream(out stream, ref inputParameters, ref outputParameters, sampleRate, framesPerBuffer, streamFlags, streamCallback, + userData); if (res == PortAudio.PaError.paNoError) + { _Streams.Add(stream); + } + return res; } } @@ -147,13 +164,13 @@ namespace Vocaluxe.Lib.Sound /// /// True on success public bool OpenInputStream(out IntPtr stream, ref PortAudio.PaStreamParameters? inputParameters, - double sampleRate, uint framesPerBuffer, PortAudio.PaStreamFlags streamFlags, - PortAudio.PaStreamCallbackDelegate streamCallback, IntPtr userData) + double sampleRate, uint framesPerBuffer, PortAudio.PaStreamFlags streamFlags, + PortAudio.PaStreamCallbackDelegate streamCallback, IntPtr userData) { PortAudio.PaStreamParameters? outputParameters = null; return !CheckError("OpenInputStream", - OpenStream(out stream, ref inputParameters, ref outputParameters, sampleRate, framesPerBuffer, streamFlags, streamCallback, userData)); + OpenStream(out stream, ref inputParameters, ref outputParameters, sampleRate, framesPerBuffer, streamFlags, streamCallback, userData)); } /// @@ -168,13 +185,13 @@ namespace Vocaluxe.Lib.Sound /// /// True on success public bool OpenOutputStream(out IntPtr stream, ref PortAudio.PaStreamParameters? outputParameters, - double sampleRate, uint framesPerBuffer, PortAudio.PaStreamFlags streamFlags, - PortAudio.PaStreamCallbackDelegate streamCallback, IntPtr userData) + double sampleRate, uint framesPerBuffer, PortAudio.PaStreamFlags streamFlags, + PortAudio.PaStreamCallbackDelegate streamCallback, IntPtr userData) { PortAudio.PaStreamParameters? inputParameters = null; return !CheckError("OpenOutputStream", - OpenStream(out stream, ref inputParameters, ref outputParameters, sampleRate, framesPerBuffer, streamFlags, streamCallback, userData)); + OpenStream(out stream, ref inputParameters, ref outputParameters, sampleRate, framesPerBuffer, streamFlags, streamCallback, userData)); } public void CloseStream(IntPtr stream) @@ -182,7 +199,9 @@ namespace Vocaluxe.Lib.Sound lock (_Mutex) { if (_Disposed) + { return; + } if (stream == IntPtr.Zero) { @@ -190,7 +209,7 @@ namespace Vocaluxe.Lib.Sound return; } - bool wasTracked = _Streams.Remove(stream); + var wasTracked = _Streams.Remove(stream); if (!wasTracked) { CLog.Debug("Stream was already removed or never tracked, skipping duplicate close."); @@ -201,10 +220,10 @@ namespace Vocaluxe.Lib.Sound { try { - PortAudio.PaError isStoppedResult = PortAudio.Pa_IsStreamStopped(stream); + var isStoppedResult = PortAudio.Pa_IsStreamStopped(stream); if (isStoppedResult == PortAudio.PaError.paStreamIsNotStopped) { - PortAudio.PaError stopResult = PortAudio.Pa_StopStream(stream); + var stopResult = PortAudio.Pa_StopStream(stream); if (stopResult != PortAudio.PaError.paNoError && stopResult != PortAudio.PaError.paStreamIsStopped) { @@ -217,9 +236,11 @@ namespace Vocaluxe.Lib.Sound CLog.Error(ex, "Error stopping stream before close:"); } - PortAudio.PaError closeResult = PortAudio.Pa_CloseStream(stream); + var closeResult = PortAudio.Pa_CloseStream(stream); if (closeResult != PortAudio.PaError.paNoError) + { CLog.Error("CloseStream error: " + PortAudio.Pa_GetErrorText(closeResult)); + } } catch (AccessViolationException ex) { @@ -242,18 +263,21 @@ namespace Vocaluxe.Lib.Sound public bool CheckError(String action, PortAudio.PaError errorCode) { if (_Disposed) + { throw new ObjectDisposedException("PortAudioHandle already disposed"); + } if (errorCode != PortAudio.PaError.paNoError) { CLog.Error(action + " error: " + PortAudio.Pa_GetErrorText(errorCode)); if (errorCode == PortAudio.PaError.paUnanticipatedHostError) { - PortAudio.PaHostErrorInfo errorInfo = PortAudio.Pa_GetLastHostErrorInfo(); + var errorInfo = PortAudio.Pa_GetLastHostErrorInfo(); CLog.Error("- Host error API type: " + errorInfo.hostApiType); CLog.Error("- Host error code: " + errorInfo.errorCode); CLog.Error("- Host error text: " + errorInfo.errorText); } + return true; } @@ -267,18 +291,23 @@ namespace Vocaluxe.Lib.Sound public int GetHostApi() { if (_Disposed) - throw new ObjectDisposedException("PortAudioHandle already disposed"); - - int selectedHostApi = PortAudio.Pa_GetDefaultHostApi(); - int apiCount = PortAudio.Pa_GetHostApiCount(); - for (int i = 0; i < apiCount; i++) { - PortAudio.PaHostApiInfo apiInfo = PortAudio.Pa_GetHostApiInfo(i); - if ((apiInfo.type == PortAudio.PaHostApiTypeId.paDirectSound) - || (apiInfo.type == PortAudio.PaHostApiTypeId.paALSA)) - selectedHostApi = i; + throw new ObjectDisposedException("PortAudioHandle already disposed"); } + + var selectedHostApi = PortAudio.Pa_GetDefaultHostApi(); + var apiCount = PortAudio.Pa_GetHostApiCount(); + for (var i = 0; i < apiCount; i++) + { + var apiInfo = PortAudio.Pa_GetHostApiInfo(i); + if (apiInfo.type == PortAudio.PaHostApiTypeId.paDirectSound + || apiInfo.type == PortAudio.PaHostApiTypeId.paALSA) + { + selectedHostApi = i; + } + } + return selectedHostApi; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/EAudioEffect.cs b/Vocaluxe/Lib/Sound/EAudioEffect.cs index cc85a9cf..50d26e9e 100644 --- a/Vocaluxe/Lib/Sound/EAudioEffect.cs +++ b/Vocaluxe/Lib/Sound/EAudioEffect.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; namespace Vocaluxe.Lib.Sound { @@ -11,4 +8,4 @@ namespace Vocaluxe.Lib.Sound None = 0, Karaoke = 1 } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/Playback/CAudioStreamBase.cs b/Vocaluxe/Lib/Sound/Playback/CAudioStreamBase.cs index bad098cf..d53011b3 100644 --- a/Vocaluxe/Lib/Sound/Playback/CAudioStreamBase.cs +++ b/Vocaluxe/Lib/Sound/Playback/CAudioStreamBase.cs @@ -23,7 +23,6 @@ namespace Vocaluxe.Lib.Sound.Playback { abstract class CAudioStreamBase : IAudioStream { - private readonly int _ID; protected readonly string _Medium; protected readonly bool _Loop; protected readonly EAudioEffect _Effect; @@ -33,10 +32,7 @@ namespace Vocaluxe.Lib.Sound.Playback protected EStreamAction _AfterFadeAction = EStreamAction.Nothing; protected CFading _Fading; - public int ID - { - get { return _ID; } - } + public int Id { get; } public bool IsFading { @@ -52,7 +48,7 @@ namespace Vocaluxe.Lib.Sound.Playback protected CAudioStreamBase(int id, string medium, bool loop, EAudioEffect effect = EAudioEffect.None) { - _ID = id; + Id = id; _Medium = medium; _Loop = loop; _Effect = effect; @@ -72,7 +68,9 @@ namespace Vocaluxe.Lib.Sound.Playback protected virtual void _Dispose(bool disposing) { if (!disposing) + { CLog.Debug("Audio stream " + _Medium + " was not closed."); + } } public void Close() @@ -116,6 +114,7 @@ namespace Vocaluxe.Lib.Sound.Playback IsPaused = true; break; } + _Fading = null; } } diff --git a/Vocaluxe/Lib/Sound/Playback/CPlaybackBase.cs b/Vocaluxe/Lib/Sound/Playback/CPlaybackBase.cs index d8f08ffe..ef807d3b 100644 --- a/Vocaluxe/Lib/Sound/Playback/CPlaybackBase.cs +++ b/Vocaluxe/Lib/Sound/Playback/CPlaybackBase.cs @@ -28,7 +28,7 @@ namespace Vocaluxe.Lib.Sound.Playback protected readonly List _Streams = new List(); private readonly List _StreamsToDelete = new List(); private bool _InUpdate; - private int _NextID; + private int _NextId; protected float _GlobalVolume = 1f; public abstract bool Init(); @@ -36,56 +36,82 @@ namespace Vocaluxe.Lib.Sound.Playback public virtual void Close() { if (!_Initialized) + { return; - List streams = new List(); + } + + var streams = new List(); //Get all streams but do not modify list without holding the lock //Calling dispose from within the lock may deadlock in closeproc (if a thread is already there) lock (_Streams) { streams.AddRange(_Streams); } - foreach (IAudioStream stream in streams) + + foreach (var stream in streams) + { stream.Dispose(); + } + while (_Streams.Count > 0) + { Thread.Sleep(5); + } + _Initialized = false; } public void CloseAll() { if (!_Initialized) + { return; + } + lock (_Streams) { - foreach (IAudioStream stream in _Streams) + foreach (var stream in _Streams) + { stream.Close(); + } + _Streams.Clear(); } } public int GetGlobalVolume() { - return (_Initialized) ? (int) Math.Round(_GlobalVolume * 100) : 100; + return _Initialized ? (int)Math.Round(_GlobalVolume * 100) : 100; } public void SetGlobalVolume(int volume) { if (!_Initialized) + { return; - float volumeF = volume.Clamp(0, 100) / 100f; + } + + var volumeF = volume.Clamp(0, 100) / 100f; lock (_Streams) { - foreach (IAudioStream stream in _Streams) + foreach (var stream in _Streams) + { if (!stream.IsFading) + { stream.VolumeMax = volumeF; + } + } } + _GlobalVolume = volumeF; } public int GetStreamCount() { if (!_Initialized) + { return 0; + } lock (_Streams) { @@ -96,19 +122,28 @@ namespace Vocaluxe.Lib.Sound.Playback public void Update() { if (!_Initialized) + { return; + } + lock (_Streams) { _InUpdate = true; - foreach (IAudioStream stream in _Streams) + foreach (var stream in _Streams) + { stream.Update(); + } + //This is required because a stream may call the close listener from inside the update method //lock() only protects from different threads not from the same, so we use StreamsToDelete to not modify _Streams while iterating it _InUpdate = false; if (_StreamsToDelete.Count > 0) { - foreach (IAudioStream stream in _StreamsToDelete) + foreach (var stream in _StreamsToDelete) + { _Streams.Remove(stream); + } + _StreamsToDelete.Clear(); } } @@ -121,8 +156,11 @@ namespace Vocaluxe.Lib.Sound.Playback public int Load(string medium, bool loop = false, bool prescan = false, EAudioEffect effect = EAudioEffect.None) { if (!_Initialized) + { return -1; - IAudioStream stream = _CreateStream(_NextID++, medium, loop, effect); + } + + var stream = _CreateStream(_NextId++, medium, loop, effect); if (stream.Open(prescan)) { @@ -132,153 +170,216 @@ namespace Vocaluxe.Lib.Sound.Playback stream.VolumeMax = _GlobalVolume; stream.SetOnCloseListener(this); _Streams.Add(stream); - return stream.ID; + return stream.Id; } } + return -1; } - public void Close(int streamID) + public void Close(int streamId) { if (!_Initialized) + { return; + } + lock (_Streams) { - int index = _GetStreamIndex(streamID); + var index = _GetStreamIndex(streamId); if (index >= 0) - _Streams[index].Close(); - } - } - - public void Play(int streamID) - { - if (!_Initialized) - return; - lock (_Streams) - { - if (_StreamExists(streamID)) - _Streams[_GetStreamIndex(streamID)].Play(); - } - } - - public void Pause(int streamID) - { - if (!_Initialized) - return; - lock (_Streams) - { - if (_StreamExists(streamID)) - _Streams[_GetStreamIndex(streamID)].IsPaused = true; - } - } - - public void Stop(int streamID) - { - if (!_Initialized) - return; - lock (_Streams) - { - if (_StreamExists(streamID)) - _Streams[_GetStreamIndex(streamID)].Stop(); - } - } - - public void Fade(int streamID, int targetVolume, float seconds, EStreamAction afterFadeAction = EStreamAction.Nothing) - { - if (!_Initialized) - return; - float targetVolumeF = targetVolume.Clamp(0, 100) / 100f; - lock (_Streams) - { - if (_StreamExists(streamID)) - _Streams[_GetStreamIndex(streamID)].Fade(targetVolumeF, seconds, afterFadeAction); - } - } - - public void SetStreamVolume(int streamID, int volume) - { - if (!_Initialized) - return; - float volumeF = volume.Clamp(0, 100) / 100f; - lock (_Streams) - { - if (_StreamExists(streamID)) { - _Streams[_GetStreamIndex(streamID)].Volume = volumeF; - _Streams[_GetStreamIndex(streamID)].CancelFading(); + _Streams[index].Close(); } } } - public float GetLength(int streamID) + public void Play(int streamId) { if (!_Initialized) - return -1f; - lock (_Streams) { - if (_StreamExists(streamID)) - return _Streams[_GetStreamIndex(streamID)].Length; - } - return -1f; - } - - public float GetPosition(int streamID) - { - if (!_Initialized) - return -1f; - lock (_Streams) - { - if (_StreamExists(streamID)) - return _Streams[_GetStreamIndex(streamID)].Position; - } - - return -1f; - } - - public void SetPosition(int streamID, float position) - { - if (!_Initialized) return; + } + lock (_Streams) { - if (_StreamExists(streamID)) - _Streams[_GetStreamIndex(streamID)].Position = position; + if (_StreamExists(streamId)) + { + _Streams[_GetStreamIndex(streamId)].Play(); + } } } - public bool IsPlaying(int streamID) + public void Pause(int streamId) { if (!_Initialized) - return false; + { + return; + } + lock (_Streams) { - if (_StreamExists(streamID)) - return !_Streams[_GetStreamIndex(streamID)].IsPaused && !_Streams[_GetStreamIndex(streamID)].IsFinished; + if (_StreamExists(streamId)) + { + _Streams[_GetStreamIndex(streamId)].IsPaused = true; + } } + } + + public void Stop(int streamId) + { + if (!_Initialized) + { + return; + } + + lock (_Streams) + { + if (_StreamExists(streamId)) + { + _Streams[_GetStreamIndex(streamId)].Stop(); + } + } + } + + public void Fade(int streamId, int targetVolume, float seconds, EStreamAction afterFadeAction = EStreamAction.Nothing) + { + if (!_Initialized) + { + return; + } + + var targetVolumeF = targetVolume.Clamp(0, 100) / 100f; + lock (_Streams) + { + if (_StreamExists(streamId)) + { + _Streams[_GetStreamIndex(streamId)].Fade(targetVolumeF, seconds, afterFadeAction); + } + } + } + + public void SetStreamVolume(int streamId, int volume) + { + if (!_Initialized) + { + return; + } + + var volumeF = volume.Clamp(0, 100) / 100f; + lock (_Streams) + { + if (_StreamExists(streamId)) + { + _Streams[_GetStreamIndex(streamId)].Volume = volumeF; + _Streams[_GetStreamIndex(streamId)].CancelFading(); + } + } + } + + public float GetLength(int streamId) + { + if (!_Initialized) + { + return -1f; + } + + lock (_Streams) + { + if (_StreamExists(streamId)) + { + return _Streams[_GetStreamIndex(streamId)].Length; + } + } + + return -1f; + } + + public float GetPosition(int streamId) + { + if (!_Initialized) + { + return -1f; + } + + lock (_Streams) + { + if (_StreamExists(streamId)) + { + return _Streams[_GetStreamIndex(streamId)].Position; + } + } + + return -1f; + } + + public void SetPosition(int streamId, float position) + { + if (!_Initialized) + { + return; + } + + lock (_Streams) + { + if (_StreamExists(streamId)) + { + _Streams[_GetStreamIndex(streamId)].Position = position; + } + } + } + + public bool IsPlaying(int streamId) + { + if (!_Initialized) + { + return false; + } + + lock (_Streams) + { + if (_StreamExists(streamId)) + { + return !_Streams[_GetStreamIndex(streamId)].IsPaused && !_Streams[_GetStreamIndex(streamId)].IsFinished; + } + } + return false; } - public bool IsPaused(int streamID) + public bool IsPaused(int streamId) { if (!_Initialized) + { return false; + } + lock (_Streams) { - if (_StreamExists(streamID)) - return _Streams[_GetStreamIndex(streamID)].IsPaused; + if (_StreamExists(streamId)) + { + return _Streams[_GetStreamIndex(streamId)].IsPaused; + } } + return false; } - public bool IsFinished(int streamID) + public bool IsFinished(int streamId) { if (!_Initialized) + { return true; + } + lock (_Streams) { - if (_StreamExists(streamID)) - return _Streams[_GetStreamIndex(streamID)].IsFinished; + if (_StreamExists(streamId)) + { + return _Streams[_GetStreamIndex(streamId)].IsFinished; + } } + return true; } @@ -286,26 +387,29 @@ namespace Vocaluxe.Lib.Sound.Playback /// Returns true if stream with given id is found /// MUST hold _Stream-lock /// - /// Stream id + /// Stream id /// - protected bool _StreamExists(int streamID) + protected bool _StreamExists(int streamId) { - return _GetStreamIndex(streamID) != -1; + return _GetStreamIndex(streamId) != -1; } /// /// Returns the index of the stream with the given id /// MUST hold _Stream-lock /// - /// Stream id + /// Stream id /// - protected int _GetStreamIndex(int streamID) + protected int _GetStreamIndex(int streamId) { - for (int i = 0; i < _Streams.Count; i++) + for (var i = 0; i < _Streams.Count; i++) { - if (_Streams[i].ID == streamID) + if (_Streams[i].Id == streamId) + { return i; + } } + return -1; } #endregion Stream Handling @@ -315,10 +419,14 @@ namespace Vocaluxe.Lib.Sound.Playback lock (_Streams) { if (_InUpdate) //This is only possible if this is called from inside the update method + { _StreamsToDelete.Add(stream); + } else + { _Streams.Remove(stream); + } } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/Playback/CRingBuffer.cs b/Vocaluxe/Lib/Sound/Playback/CRingBuffer.cs index 2d1c4dc7..ad14dd59 100644 --- a/Vocaluxe/Lib/Sound/Playback/CRingBuffer.cs +++ b/Vocaluxe/Lib/Sound/Playback/CRingBuffer.cs @@ -25,12 +25,8 @@ namespace Vocaluxe.Lib.Sound.Playback private readonly int _Size; private int _ReadPos; private int _WritePos; - private int _BytesNotRead; - public int BytesNotRead - { - get { return _BytesNotRead; } - } + public int BytesNotRead { get; private set; } public CRingBuffer(int size) { @@ -43,17 +39,20 @@ namespace Vocaluxe.Lib.Sound.Playback { _ReadPos = 0; _WritePos = 0; - _BytesNotRead = 0; + BytesNotRead = 0; } public void Write(byte[] data) { - int start = 0; - int end = data.Length; + var start = 0; + var end = data.Length; if (end - start > _Size) + { start = end - _Size; - int lenTotal = end - start; - int len = Math.Min(lenTotal, _Size - _WritePos); + } + + var lenTotal = end - start; + var len = Math.Min(lenTotal, _Size - _WritePos); Buffer.BlockCopy(data, start, _Data, _WritePos, len); _WritePos += len; if (_WritePos >= _Size) @@ -67,22 +66,25 @@ namespace Vocaluxe.Lib.Sound.Playback _WritePos += len; } } - _BytesNotRead += lenTotal; + + BytesNotRead += lenTotal; } public void Read(byte[] data) { - int lenTotal = Math.Min(data.Length, _BytesNotRead); + var lenTotal = Math.Min(data.Length, BytesNotRead); if (lenTotal == 0) + { return; + } - int len = Math.Min(lenTotal, _Size - _ReadPos); + var len = Math.Min(lenTotal, _Size - _ReadPos); Buffer.BlockCopy(_Data, _ReadPos, data, 0, len); _ReadPos += len; if (_ReadPos >= _Size) { _ReadPos = 0; - int start = len; + var start = len; len = lenTotal - len; if (len > 0) { @@ -90,7 +92,8 @@ namespace Vocaluxe.Lib.Sound.Playback _ReadPos += len; } } - _BytesNotRead -= lenTotal; + + BytesNotRead -= lenTotal; } } } \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/Playback/Decoder/CAudioDecoderFFmpeg.cs b/Vocaluxe/Lib/Sound/Playback/Decoder/CAudioDecoderFFmpeg.cs index 7abe611b..bfbda592 100644 --- a/Vocaluxe/Lib/Sound/Playback/Decoder/CAudioDecoderFFmpeg.cs +++ b/Vocaluxe/Lib/Sound/Playback/Decoder/CAudioDecoderFFmpeg.cs @@ -17,7 +17,6 @@ using System; using System.Runtime.InteropServices; -using Vocaluxe.Base; using Vocaluxe.Lib.Video.Acinerella; using VocaluxeLib.Log; @@ -81,11 +80,11 @@ namespace Vocaluxe.Lib.Sound.Playback.Decoder } _FormatInfo = new SFormatInfo - { - SamplesPerSecond = audiodecoder.StreamInfo.AudioInfo.SamplesPerSecond, - BitDepth = audiodecoder.StreamInfo.AudioInfo.BitDepth, - ChannelCount = audiodecoder.StreamInfo.AudioInfo.ChannelCount - }; + { + SamplesPerSecond = audiodecoder.StreamInfo.AudioInfo.SamplesPerSecond, + BitDepth = audiodecoder.StreamInfo.AudioInfo.BitDepth, + ChannelCount = audiodecoder.StreamInfo.AudioInfo.ChannelCount + }; _CurrentTime = 0f; @@ -95,6 +94,7 @@ namespace Vocaluxe.Lib.Sound.Playback.Decoder Close(); return false; } + _FileOpened = true; return true; } @@ -106,6 +106,7 @@ namespace Vocaluxe.Lib.Sound.Playback.Decoder CAcinerella.AcFreeDecoder(_Audiodecoder); _Audiodecoder = IntPtr.Zero; } + if (_InstancePtr != IntPtr.Zero) { CAcinerella.AcClose(_InstancePtr); @@ -129,11 +130,13 @@ namespace Vocaluxe.Lib.Sound.Playback.Decoder public void SetPosition(float time) { if (!_FileOpened) + { return; + } try { - CAcinerella.AcSeek(_Audiodecoder, (time > _CurrentTime) ? 0 : -1, (Int64)(time * 1000f)); + CAcinerella.AcSeek(_Audiodecoder, time > _CurrentTime ? 0 : -1, (Int64)(time * 1000f)); } catch (Exception) { @@ -156,7 +159,7 @@ namespace Vocaluxe.Lib.Sound.Playback.Decoder return; } - bool frameFinished = CAcinerella.AcGetAudioFrame(_InstancePtr, _Audiodecoder); + var frameFinished = CAcinerella.AcGetAudioFrame(_InstancePtr, _Audiodecoder); if (frameFinished) { @@ -168,7 +171,9 @@ namespace Vocaluxe.Lib.Sound.Playback.Decoder buffer = new byte[decoder.BufferSize]; if (decoder.BufferSize > 0) + { Marshal.Copy(decoder.Buffer, buffer, 0, buffer.Length); + } return; } @@ -177,6 +182,6 @@ namespace Vocaluxe.Lib.Sound.Playback.Decoder timeStamp = 0f; } - public void Dispose() {} + public void Dispose() { } } } \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/Playback/GstreamerSharp/CGstreamerSharpAudio.cs b/Vocaluxe/Lib/Sound/Playback/GstreamerSharp/CGstreamerSharpAudio.cs index bd903d2d..a6e5543d 100644 --- a/Vocaluxe/Lib/Sound/Playback/GstreamerSharp/CGstreamerSharpAudio.cs +++ b/Vocaluxe/Lib/Sound/Playback/GstreamerSharp/CGstreamerSharpAudio.cs @@ -15,10 +15,9 @@ // along with Vocaluxe. If not, see . #endregion -using Gst; using System; -using Vocaluxe.Base; using System.IO; +using Gst; using VocaluxeLib.Log; namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp @@ -28,8 +27,10 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp public override bool Init() { if (_Initialized) + { return false; - #if WIN + } +#if WIN #if ARCH_X86 const string varName = "GSTREAMER_1_0_ROOT_X86"; #endif @@ -46,7 +47,7 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp #endif if (!Directory.Exists(dllDirectory)) { - string gstreamerEnvVar = Environment.GetEnvironmentVariable(varName, EnvironmentVariableTarget.User); + var gstreamerEnvVar = Environment.GetEnvironmentVariable(varName, EnvironmentVariableTarget.User); if (gstreamerEnvVar == null || !Directory.Exists(gstreamerEnvVar)) { @@ -58,10 +59,10 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp dllDirectory = gstreamerEnvVar + "bin\\"; } } - - + + COSFunctions.AddEnvironmentPath(dllDirectory); - #endif +#endif Application.Init(); _Initialized = Application.IsInitialized; @@ -71,7 +72,10 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp public override void Close() { if (!_Initialized) + { return; + } + base.Close(); Application.Deinit(); } diff --git a/Vocaluxe/Lib/Sound/Playback/GstreamerSharp/CGstreamerSharpAudioStream.cs b/Vocaluxe/Lib/Sound/Playback/GstreamerSharp/CGstreamerSharpAudioStream.cs index f433c8c5..f94cc1b4 100644 --- a/Vocaluxe/Lib/Sound/Playback/GstreamerSharp/CGstreamerSharpAudioStream.cs +++ b/Vocaluxe/Lib/Sound/Playback/GstreamerSharp/CGstreamerSharpAudioStream.cs @@ -19,7 +19,6 @@ using System; using GLib; using Gst; using Vocaluxe.Base; -using VocaluxeLib; using VocaluxeLib.Log; namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp @@ -62,7 +61,10 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp //TODO: Is it ok, to remove this? Gst should post a message if duration was changed so this should not be required // Removing would not work in some cases where length is not know at startup if (base.Length < 0 && _Element != null) + { _UpdateDuration(); + } + return base.Length >= 0f ? base.Length : 0f; } } @@ -71,26 +73,31 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp { get { - if (_Element == null || (_Element.CurrentState == State.Paused && _Element.PendingState != State.VoidPending)) { return _Position; } - - + + long position; if (!_Element.QueryPosition(Format.Time, out position)) + { CLog.Error("Could not query position"); + } else - _Position = ((float)position / Constants.SECOND); - - + { + _Position = (float)position / Constants.SECOND; + } + + return _Position; } set { if (_Element != null) + { _Element.SeekSimple(Format.Time, SeekFlags.Accurate | SeekFlags.Flush, (long)(value * Constants.SECOND)); + } } } @@ -105,28 +112,39 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp set { if (_Element != null) + { _Element.SetState(value ? State.Paused : State.Playing); + } } } - public CGstreamerSharpAudioStream(int id, string medium, bool loop, EAudioEffect effect = EAudioEffect.None) : base(id, medium, loop, effect) {} + public CGstreamerSharpAudioStream(int id, string medium, bool loop, EAudioEffect effect = EAudioEffect.None) : base(id, medium, loop, effect) { } public override bool Open(bool prescan) { System.Diagnostics.Debug.Assert(!_FileOpened); if (_FileOpened) + { return false; + } + Length = -1; - Element convert = ElementFactory.Make("audioconvert", "convert"); - Element audiosink = ElementFactory.Make("autoaudiosink", "audiosink"); + var convert = ElementFactory.Make("audioconvert", "convert"); + var audiosink = ElementFactory.Make("autoaudiosink", "audiosink"); if (convert == null || audiosink == null) { CLog.Error("Could not create pipeline"); if (convert != null) + { convert.Dispose(); + } + if (audiosink != null) + { audiosink.Dispose(); + } + return false; } @@ -136,13 +154,13 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp { audiokaraoke = ElementFactory.Make("audiokaraoke", "karaoke"); audioSinkBin.Add(audiokaraoke); - audioSinkBin.Add(convert); - audioSinkBin.Add(audiosink); - + audioSinkBin.Add(convert); + audioSinkBin.Add(audiosink); + audiokaraoke.Link(audiosink); audiokaraoke["level"] = CConfig.Config.Sound.KaraokeEffectLevel; audiokaraoke["mono-level"] = CConfig.Config.Sound.KaraokeEffectLevel; - + convert.Link(audiokaraoke); } else @@ -152,10 +170,9 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp convert.Link(audiosink); } - - - Pad pad = convert.GetStaticPad("sink"); - GhostPad ghostpad = new GhostPad("sink", pad); + + var pad = convert.GetStaticPad("sink"); + var ghostpad = new GhostPad("sink", pad); if (pad == null) { @@ -167,6 +184,7 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp { audiokaraoke.Dispose(); } + return false; } @@ -181,8 +199,10 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp { audiokaraoke.Dispose(); } + return false; } + if (!audioSinkBin.AddPad(ghostpad)) { CLog.Error("Could not add pad"); @@ -194,6 +214,7 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp { audiokaraoke.Dispose(); } + return false; } @@ -209,8 +230,10 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp { audiokaraoke.Dispose(); } + return false; } + _Element["audio-sink"] = audioSinkBin; _Element["flags"] = 1 << 1; _Element["uri"] = new Uri(_Medium).AbsoluteUri; @@ -219,12 +242,13 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp // Passing CLOCK_TIME_NONE here causes the pipeline to block for a long time so with // prescan enabled the pipeline will wait 500ms for stream to initialize and then continue // if it takes more than 500ms, duration queries will be performed asynchronously - Message msg = _Element.Bus.TimedPopFiltered(prescan ? ulong.MaxValue : 0L, MessageType.AsyncDone | MessageType.Error); + var msg = _Element.Bus.TimedPopFiltered(prescan ? ulong.MaxValue : 0L, MessageType.AsyncDone | MessageType.Error); if (!_OnMessage(msg)) { _Dispose(true); return false; } + _FileOpened = true; return true; } @@ -232,34 +256,51 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp protected override void _Dispose(bool disposing) { if (_Element == null) + { return; + } + Element element; lock (_ElementLock) { //Atomic get and set if (_Element == null) + { return; + } + element = _Element; _Element = null; //Now everything "seems" closed } // Should not be needed but we had an error report (#226) - so we double check here to prevent a crash if (element == null) + { return; - + } + if (element.TargetState == State.Playing) + { element.SetState(State.Paused); //Stop output + } + if (_CloseStreamListener != null) + { _CloseStreamListener.OnCloseStream(this); + } + //Now really close it in the background - var t = new System.Threading.Thread(() => _TerminateStream(element)) {Name = "GSt Terminate"}; + var t = new System.Threading.Thread(() => _TerminateStream(element)) { Name = "GSt Terminate" }; t.Start(); } private static void _TerminateStream(Element element) { if (element == null) + { return; + } + //One of these might take a bit, so better do this in the background to avoid lags element.SetState(State.Null); element.Dispose(); @@ -268,33 +309,48 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp public override void Play() { if (_Element != null) + { _Element.SetState(State.Playing); + } } public override void Stop() { if (_Element != null) + { _Element.SetState(State.Ready); + } + Position = 0; } private void _SetElementVolume() { if (_Element != null) + { _Element["volume"] = Volume * VolumeMax; + } } private bool _OnMessage(Message msg) { if (msg == null || msg.Handle == IntPtr.Zero) + { return true; + } + switch (msg.Type) { case MessageType.Eos: if (_Loop) + { Position = 0; + } else + { _IsFinished = true; + } + break; case MessageType.Error: GException error; @@ -306,6 +362,7 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp _UpdateDuration(); break; } + msg.Dispose(); return true; } @@ -314,7 +371,9 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp { base.Update(); while (_Element != null && _Element.Bus != null && _Element.Bus.HavePending()) + { _OnMessage(_Element.Bus.Pop()); + } } private void _UpdateDuration() @@ -322,10 +381,15 @@ namespace Vocaluxe.Lib.Sound.Playback.GstreamerSharp lock (_ElementLock) { if (_Element == null) + { return; + } + long duration; if (_Element.QueryDuration(Format.Time, out duration)) + { Length = duration / (float)Constants.SECOND; + } } } } diff --git a/Vocaluxe/Lib/Sound/Playback/IAudioStream.cs b/Vocaluxe/Lib/Sound/Playback/IAudioStream.cs index 45d99556..c4302c98 100644 --- a/Vocaluxe/Lib/Sound/Playback/IAudioStream.cs +++ b/Vocaluxe/Lib/Sound/Playback/IAudioStream.cs @@ -27,7 +27,7 @@ namespace Vocaluxe.Lib.Sound.Playback public interface IAudioStream : IDisposable { - int ID { get; } + int Id { get; } bool IsFading { get; } float Volume { get; set; } float VolumeMax { get; set; } diff --git a/Vocaluxe/Lib/Sound/Playback/IPlayback.cs b/Vocaluxe/Lib/Sound/Playback/IPlayback.cs index 20792586..6543bbf6 100644 --- a/Vocaluxe/Lib/Sound/Playback/IPlayback.cs +++ b/Vocaluxe/Lib/Sound/Playback/IPlayback.cs @@ -36,30 +36,30 @@ namespace Vocaluxe.Lib.Sound.Playback void CloseAll(); #region stream Handling - int Load(string medium, bool loop = false, bool prescan = false, EAudioEffect effekt= EAudioEffect.None); - void Close(int streamID); + int Load(string medium, bool loop = false, bool prescan = false, EAudioEffect effekt = EAudioEffect.None); + void Close(int streamId); - void Play(int streamID); - void Pause(int streamID); - void Stop(int streamID); - void Fade(int streamID, int targetVolume, float seconds, EStreamAction afterFadeAction = EStreamAction.Nothing); + void Play(int streamId); + void Pause(int streamId); + void Stop(int streamId); + void Fade(int streamId, int targetVolume, float seconds, EStreamAction afterFadeAction = EStreamAction.Nothing); /// /// Set the stream's current volume. Cancels fading /// - /// Id of the stream (obtained by Load) + /// Id of the stream (obtained by Load) /// Volume in percent - void SetStreamVolume(int streamID, int volume); + void SetStreamVolume(int streamId, int volume); - float GetLength(int streamID); - float GetPosition(int streamID); - void SetPosition(int streamID, float position); + float GetLength(int streamId); + float GetPosition(int streamId); + void SetPosition(int streamId, float position); - bool IsPlaying(int streamID); - bool IsPaused(int streamID); - bool IsFinished(int streamID); + bool IsPlaying(int streamId); + bool IsPaused(int streamId); + bool IsFinished(int streamId); void Update(); #endregion stream Handling } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/Playback/OpenAL/COpenALPlay.cs b/Vocaluxe/Lib/Sound/Playback/OpenAL/COpenALPlay.cs index 13ee98ad..79685469 100644 --- a/Vocaluxe/Lib/Sound/Playback/OpenAL/COpenALPlay.cs +++ b/Vocaluxe/Lib/Sound/Playback/OpenAL/COpenALPlay.cs @@ -26,7 +26,9 @@ namespace Vocaluxe.Lib.Sound.Playback.OpenAL public override bool Init() { if (_Initialized) + { return false; + } _Context = new AudioContext(); _Context.MakeCurrent(); @@ -38,7 +40,10 @@ namespace Vocaluxe.Lib.Sound.Playback.OpenAL public override void Close() { if (!_Initialized) + { return; + } + base.Close(); _Context.Dispose(); _Context = null; diff --git a/Vocaluxe/Lib/Sound/Playback/OpenAL/COpenAlStream.cs b/Vocaluxe/Lib/Sound/Playback/OpenAL/COpenAlStream.cs index 38a0cb77..ef71ca51 100644 --- a/Vocaluxe/Lib/Sound/Playback/OpenAL/COpenAlStream.cs +++ b/Vocaluxe/Lib/Sound/Playback/OpenAL/COpenAlStream.cs @@ -81,12 +81,13 @@ namespace Vocaluxe.Lib.Sound.Playback.OpenAL { get { - float time = _CurrentTime + _Timer.ElapsedMilliseconds / 1000f; + var time = _CurrentTime + _Timer.ElapsedMilliseconds / 1000f; if (time > Length) { _Timer.Stop(); time = Length; } + return time; } set @@ -96,6 +97,7 @@ namespace Vocaluxe.Lib.Sound.Playback.OpenAL _SetStart = value; _SetSkip = true; } + //Set position here in case we immediately request it, it will be reset in Update method _CurrentTime = value; _Timer.Restart(); @@ -123,7 +125,7 @@ namespace Vocaluxe.Lib.Sound.Playback.OpenAL } } - public COpenAlStream(int id, string medium, bool loop, EAudioEffect effect = EAudioEffect.None) : base(id, medium, loop, effect) {} + public COpenAlStream(int id, string medium, bool loop, EAudioEffect effect = EAudioEffect.None) : base(id, medium, loop, effect) { } protected override void _Dispose(bool disposing) { @@ -132,9 +134,13 @@ namespace Vocaluxe.Lib.Sound.Playback.OpenAL { _Terminated = true; if (_DecoderThread != null) + { _EventDecode.Set(); + } else + { _DoFree(); + } } } @@ -153,7 +159,9 @@ namespace Vocaluxe.Lib.Sound.Playback.OpenAL { Debug.Assert(!_FileOpened); if (_FileOpened) + { return false; + } if (!File.Exists(_Medium)) { @@ -161,12 +169,12 @@ namespace Vocaluxe.Lib.Sound.Playback.OpenAL return false; } - bool ok = true; + var ok = true; try { _Source = AL.GenSource(); _Buffers = new int[_BufferCount]; - for (int i = 0; i < _BufferCount; i++) + for (var i = 0; i < _BufferCount; i++) { _Buffers[i] = AL.GenBuffer(); ok = ok && _Buffers[i] != 0; @@ -176,6 +184,7 @@ namespace Vocaluxe.Lib.Sound.Playback.OpenAL { ok = false; } + if (!ok) { Dispose(); @@ -191,6 +200,7 @@ namespace Vocaluxe.Lib.Sound.Playback.OpenAL CLog.Error("Error opening audio file: " + _Medium); return false; } + _Format = _Decoder.GetFormatInfo(); if (_Format.SamplesPerSecond == 0) { @@ -212,7 +222,7 @@ namespace Vocaluxe.Lib.Sound.Playback.OpenAL _SampleBuf = new byte[(int)CConfig.Config.Sound.AudioBufferSize]; //From now on closing the driver and the decoder is handled by the thread ONLY! - _DecoderThread = new Thread(_Execute) {Priority = ThreadPriority.Normal, Name = Path.GetFileName(_Medium)}; + _DecoderThread = new Thread(_Execute) { Priority = ThreadPriority.Normal, Name = Path.GetFileName(_Medium) }; _DecoderThread.Start(); _FileOpened = true; @@ -263,7 +273,9 @@ namespace Vocaluxe.Lib.Sound.Playback.OpenAL private void _DoDecode() { if (_Paused || _Terminated || _NoMoreData) + { return; + } float timecode; byte[] buffer; @@ -271,7 +283,9 @@ namespace Vocaluxe.Lib.Sound.Playback.OpenAL lock (_MutexData) { if (_Data.BytesNotRead > _BeginRefill) + { return; + } } _Decoder.Decode(out buffer, out timecode); @@ -284,7 +298,10 @@ namespace Vocaluxe.Lib.Sound.Playback.OpenAL _DoSkip(); } else + { _NoMoreData = true; + } + return; } @@ -293,7 +310,9 @@ namespace Vocaluxe.Lib.Sound.Playback.OpenAL _Data.Write(buffer); _TimeCode = timecode; if (_Data.BytesNotRead < _BeginRefill) + { _EventDecode.Set(); + } } } @@ -307,28 +326,38 @@ namespace Vocaluxe.Lib.Sound.Playback.OpenAL AL.DeleteBuffers(_Buffers); _Buffers = null; } + AL.DeleteSource(_Source); _Source = 0; } + if (_DecoderThread != null) { if (Thread.CurrentThread.ManagedThreadId != _DecoderThread.ManagedThreadId) + { throw new Exception("Another thread should never free the decoder thread!"); + } + _DecoderThread = null; } + if (_Decoder != null) { _Decoder.Close(); _Decoder = null; } + _SampleBuf = null; if (_EventDecode != null) { _EventDecode.Close(); _EventDecode = null; } + if (_CloseStreamListener != null) + { _CloseStreamListener.OnCloseStream(this); + } } #endregion Threading @@ -337,55 +366,63 @@ namespace Vocaluxe.Lib.Sound.Playback.OpenAL base.Update(); if (_Paused || _Terminated || IsFinished) + { return; + } int queuedCount; - bool useQueuedBuffer = false; + var useQueuedBuffer = false; AL.GetSource(_Source, ALGetSourcei.BuffersQueued, out queuedCount); - int freeBufferCt = _BufferCount; + var freeBufferCt = _BufferCount; if (queuedCount > 0) { AL.GetSource(_Source, ALGetSourcei.BuffersProcessed, out freeBufferCt); useQueuedBuffer = true; //Console.WriteLine("Buffers Processed on Stream " + _Source + " = " + processedCount); if (freeBufferCt < 1) + { return; + } } lock (_MutexData) { queuedCount = 0; - for (int j = 0; j < freeBufferCt; j++) + for (var j = 0; j < freeBufferCt; j++) { if (_Data.BytesNotRead < _SampleBuf.Length && !(_NoMoreData && _Data.BytesNotRead > 0)) + { break; + } + _Data.Read(_SampleBuf); - float volume = Volume * VolumeMax; + var volume = Volume * VolumeMax; //We want to scale all values. No matter how many channels we have (_ByteCount=2 or 4) we have short values //So just process 2 bytes a time - for (int i = 0; i < _SampleBuf.Length; i += 2) + for (var i = 0; i < _SampleBuf.Length; i += 2) { - byte[] b = BitConverter.GetBytes((Int16)(BitConverter.ToInt16(_SampleBuf, i) * volume)); + var b = BitConverter.GetBytes((Int16)(BitConverter.ToInt16(_SampleBuf, i) * volume)); _SampleBuf[i] = b[0]; _SampleBuf[i + 1] = b[1]; } - int buffer = useQueuedBuffer ? AL.SourceUnqueueBuffer(_Source) : _Buffers[queuedCount]; + var buffer = useQueuedBuffer ? AL.SourceUnqueueBuffer(_Source) : _Buffers[queuedCount]; if (buffer != 0) { - ALFormat alFormat = (_Format.ChannelCount == 2) ? ALFormat.Stereo16 : ALFormat.Mono16; + var alFormat = _Format.ChannelCount == 2 ? ALFormat.Stereo16 : ALFormat.Mono16; AL.BufferData(buffer, alFormat, _SampleBuf, _SampleBuf.Length, _Format.SamplesPerSecond); AL.SourceQueueBuffer(_Source, buffer); } + queuedCount++; } } - float latency = CConfig.Config.Sound.AudioLatency / 1000f + queuedCount * _SampleBuf.Length / _BytesPerSecond + 0.1f; + var latency = CConfig.Config.Sound.AudioLatency / 1000f + queuedCount * _SampleBuf.Length / _BytesPerSecond + 0.1f; _CurrentTime = _TimeCode - _Data.BytesNotRead / _BytesPerSecond - latency; _Timer.Restart(); } diff --git a/Vocaluxe/Lib/Sound/Playback/PortAudio/CPortAudioPlay.cs b/Vocaluxe/Lib/Sound/Playback/PortAudio/CPortAudioPlay.cs index f5110988..f3b2fb4b 100644 --- a/Vocaluxe/Lib/Sound/Playback/PortAudio/CPortAudioPlay.cs +++ b/Vocaluxe/Lib/Sound/Playback/PortAudio/CPortAudioPlay.cs @@ -22,7 +22,9 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio public override bool Init() { if (_Initialized) + { return false; + } _Initialized = true; diff --git a/Vocaluxe/Lib/Sound/Playback/PortAudio/CPortAudioStream.cs b/Vocaluxe/Lib/Sound/Playback/PortAudio/CPortAudioStream.cs index d8040976..8980d9dd 100644 --- a/Vocaluxe/Lib/Sound/Playback/PortAudio/CPortAudioStream.cs +++ b/Vocaluxe/Lib/Sound/Playback/PortAudio/CPortAudioStream.cs @@ -74,12 +74,13 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio { // Decoder may return wrong timestamps. This is why we use the synctimer // If you change this do exessive testing for monoton timestamps espacially for ogg files - float time = Math.Max(0f, _SyncTimer.Time); + var time = Math.Max(0f, _SyncTimer.Time); if (time > Length) { _SyncTimer.Pause(); time = Length; } + return time; } } @@ -100,9 +101,15 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio set { if (_Paused == value) + { return; + } + if (!_FileOpened || _Terminated) + { return; + } + _Paused = value; lock (_LockData) { @@ -132,13 +139,15 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio } } - public CPortAudioStream(int id, string medium, bool loop, EAudioEffect effect = EAudioEffect.None) : base(id, medium, loop, effect) {} + public CPortAudioStream(int id, string medium, bool loop, EAudioEffect effect = EAudioEffect.None) : base(id, medium, loop, effect) { } public override bool Open(bool prescan) { Debug.Assert(!_FileOpened); if (_FileOpened) + { return false; + } if (!File.Exists(_Medium)) { @@ -150,11 +159,13 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio { _PaHandle = new CPortAudioHandle(); - int hostApi = _PaHandle.GetHostApi(); + var hostApi = _PaHandle.GetHostApi(); _ApiInfo = PortAudioSharp.PortAudio.Pa_GetHostApiInfo(hostApi); _OutputDeviceInfo = PortAudioSharp.PortAudio.Pa_GetDeviceInfo(_ApiInfo.defaultOutputDevice); if (_OutputDeviceInfo.defaultLowOutputLatency < 0.1) + { _OutputDeviceInfo.defaultLowOutputLatency = 0.1; + } _PaStreamCallback = _ProcessNewData; } @@ -173,7 +184,7 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio return false; } - SFormatInfo format = _Decoder.GetFormatInfo(); + var format = _Decoder.GetFormatInfo(); if (format.SamplesPerSecond == 0) { Dispose(); @@ -188,22 +199,22 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio _SyncTimer.Time = 0f; PortAudioSharp.PortAudio.PaStreamParameters? outputParams = new PortAudioSharp.PortAudio.PaStreamParameters - { - channelCount = format.ChannelCount, - device = _ApiInfo.defaultOutputDevice, - sampleFormat = PortAudioSharp.PortAudio.PaSampleFormat.paInt16, - suggestedLatency = _OutputDeviceInfo.defaultLowOutputLatency, - hostApiSpecificStreamInfo = IntPtr.Zero - }; + { + channelCount = format.ChannelCount, + device = _ApiInfo.defaultOutputDevice, + sampleFormat = PortAudioSharp.PortAudio.PaSampleFormat.paInt16, + suggestedLatency = _OutputDeviceInfo.defaultLowOutputLatency, + hostApiSpecificStreamInfo = IntPtr.Zero + }; if (!_PaHandle.OpenOutputStream( - out _Stream, - ref outputParams, - format.SamplesPerSecond, - (uint)CConfig.Config.Sound.AudioBufferSize / 2, - PortAudioSharp.PortAudio.PaStreamFlags.paNoFlag, - _PaStreamCallback, - IntPtr.Zero) || _Stream == IntPtr.Zero) + out _Stream, + ref outputParams, + format.SamplesPerSecond, + (uint)CConfig.Config.Sound.AudioBufferSize / 2, + PortAudioSharp.PortAudio.PaStreamFlags.paNoFlag, + _PaStreamCallback, + IntPtr.Zero) || _Stream == IntPtr.Zero) { Dispose(); return false; @@ -217,7 +228,7 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio _FileOpened = true; _Data = new CRingBuffer(_Bufsize); _NoMoreData = false; - _DecoderThread = new Thread(_Execute) {Priority = ThreadPriority.Normal, Name = Path.GetFileName(_Medium)}; + _DecoderThread = new Thread(_Execute) { Priority = ThreadPriority.Normal, Name = Path.GetFileName(_Medium) }; _DecoderThread.Start(); return true; @@ -230,23 +241,33 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio { _Terminated = true; if (_DecoderThread != null) + { _EventDecode.Set(); + } else + { _DoFree(); + } } } public override void Play() { if (!_FileOpened || _Terminated || !IsPaused) + { return; + } + IsPaused = false; } public override void Stop() { if (!_FileOpened || _Terminated) + { return; + } + IsPaused = true; Position = 0f; } @@ -295,7 +316,9 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio private void _DoDecode() { if (_Paused || _Terminated || _NoMoreData) + { return; + } float timecode; byte[] buffer; @@ -303,7 +326,9 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio lock (_LockData) { if (_Data.BytesNotRead > _BeginRefill) + { return; + } } _Decoder.Decode(out buffer, out timecode); @@ -316,7 +341,10 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio _DoSkip(); } else + { _NoMoreData = true; + } + return; } @@ -325,7 +353,9 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio _Data.Write(buffer); _TimeCode = timecode; if (_Data.BytesNotRead < _BeginRefill) + { _EventDecode.Set(); + } } } @@ -334,28 +364,40 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio if (_PaHandle != null) { if (_Stream != IntPtr.Zero) + { _PaHandle.CloseStream(_Stream); + } + _PaHandle.Close(); _PaHandle = null; } + if (_DecoderThread != null) { if (Thread.CurrentThread.ManagedThreadId != _DecoderThread.ManagedThreadId) + { throw new Exception("Another thread should never free the decoder thread!"); + } + _DecoderThread = null; } + if (_Decoder != null) { _Decoder.Close(); _Decoder = null; } + if (_EventDecode != null) { _EventDecode.Close(); _EventDecode = null; } + if (_CloseStreamListener != null) + { _CloseStreamListener.OnCloseStream(this); + } } #endregion Threading @@ -380,32 +422,36 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio { Console.WriteLine(e.ToString()); } + return PortAudioSharp.PortAudio.PaStreamCallbackResult.paContinue; } lock (_LockData) { - int dataLen = _Data.BytesNotRead; + var dataLen = _Data.BytesNotRead; if ((_NoMoreData && dataLen > 0) || dataLen >= buf.Length) { dataLen = Math.Min(dataLen, buf.Length); _Data.Read(buf); //We want to scale all values. No matter how many channels we have (_ByteCount=2 or 4) we have short values //So just process 2 bytes a time - float volume = Volume * VolumeMax; - for (int i = 0; i < dataLen; i += 2) + var volume = Volume * VolumeMax; + for (var i = 0; i < dataLen; i += 2) { - byte[] b = BitConverter.GetBytes((Int16)(BitConverter.ToInt16(buf, i) * volume)); + var b = BitConverter.GetBytes((Int16)(BitConverter.ToInt16(buf, i) * volume)); buf[i] = b[0]; buf[i + 1] = b[1]; } - float latency = buf.Length / _BytesPerSecond + _Latency; - float time = _TimeCode - _Data.BytesNotRead / _BytesPerSecond - latency; + + var latency = buf.Length / _BytesPerSecond + _Latency; + var time = _TimeCode - _Data.BytesNotRead / _BytesPerSecond - latency; _SyncTimer.Update(time); } if (_Data.BytesNotRead < _BeginRefill && !_NoMoreData) + { _EventDecode.Set(); + } } try diff --git a/Vocaluxe/Lib/Sound/Playback/PortAudio/CPt1.cs b/Vocaluxe/Lib/Sound/Playback/PortAudio/CPt1.cs index a4a7d561..9940f106 100644 --- a/Vocaluxe/Lib/Sound/Playback/PortAudio/CPt1.cs +++ b/Vocaluxe/Lib/Sound/Playback/PortAudio/CPt1.cs @@ -32,12 +32,14 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio { get { - double nanosecPerTick = (1000.0 * 1000.0 * 1000.0) / Stopwatch.Frequency; - long ticks = _Timer.ElapsedTicks; - float dt = _Timer.ElapsedMilliseconds / 1000f; + var nanosecPerTick = 1000.0 * 1000.0 * 1000.0 / Stopwatch.Frequency; + var ticks = _Timer.ElapsedTicks; + var dt = _Timer.ElapsedMilliseconds / 1000f; if (Stopwatch.IsHighResolution && ticks != 0) + { dt = (float)(ticks * nanosecPerTick / 1000000000.0); + } return _CurrentTime + dt; } @@ -45,7 +47,9 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio set { if (value < 0f) + { return; + } _CurrentTime = value; _OldTime = value; @@ -67,16 +71,20 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio { _Timer.Stop(); - double nanosecPerTick = (1000.0 * 1000.0 * 1000.0) / Stopwatch.Frequency; - long ticks = _Timer.ElapsedTicks; - float dt = _Timer.ElapsedMilliseconds / 1000f; + var nanosecPerTick = 1000.0 * 1000.0 * 1000.0 / Stopwatch.Frequency; + var ticks = _Timer.ElapsedTicks; + var dt = _Timer.ElapsedMilliseconds / 1000f; if (Stopwatch.IsHighResolution && ticks != 0) + { dt = (float)(ticks * nanosecPerTick / 1000000000.0); + } - float ts = 0f; + var ts = 0f; if (dt > 0) + { ts = 1 / (_T / dt + 1); + } _CurrentTime = ts * (_K * newTime - _OldTime) + _OldTime; _OldTime = _CurrentTime; diff --git a/Vocaluxe/Lib/Sound/Playback/PortAudio/CSyncTimer.cs b/Vocaluxe/Lib/Sound/Playback/PortAudio/CSyncTimer.cs index 7a924663..00e3d7a1 100644 --- a/Vocaluxe/Lib/Sound/Playback/PortAudio/CSyncTimer.cs +++ b/Vocaluxe/Lib/Sound/Playback/PortAudio/CSyncTimer.cs @@ -30,12 +30,14 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio { get { - double nanosecPerTick = (1000.0 * 1000.0 * 1000.0) / Stopwatch.Frequency; - long ticks = _Timer.ElapsedTicks; - float dt = _Timer.ElapsedMilliseconds / 1000f; + var nanosecPerTick = 1000.0 * 1000.0 * 1000.0 / Stopwatch.Frequency; + var ticks = _Timer.ElapsedTicks; + var dt = _Timer.ElapsedMilliseconds / 1000f; if (Stopwatch.IsHighResolution && ticks != 0) + { dt = (float)(ticks * nanosecPerTick / 1000000000.0); + } return _SetValue + dt; } @@ -57,11 +59,11 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio public float Update(float newTime) { - float et = _ExternTime.Update(newTime); + var et = _ExternTime.Update(newTime); - float dt = Time; + var dt = Time; - float diff = et - dt; + var diff = et - dt; if (Math.Abs(diff) > 0.05f) { _Timer.Restart(); @@ -72,11 +74,16 @@ namespace Vocaluxe.Lib.Sound.Playback.PortAudio else { if (diff > 0.01f) + { _SetValue += 0.000025f; + } if (diff < -0.01f) + { _SetValue -= 0.000025f; + } } + //Console.WriteLine(diff.ToString()); return dt; } diff --git a/Vocaluxe/Lib/Sound/Record/CBuffer.cs b/Vocaluxe/Lib/Sound/Record/CBuffer.cs index c55e572f..c38009f8 100644 --- a/Vocaluxe/Lib/Sound/Record/CBuffer.cs +++ b/Vocaluxe/Lib/Sound/Record/CBuffer.cs @@ -80,8 +80,10 @@ namespace Vocaluxe.Lib.Sound.Record ToneValid = false; ToneAbs = 0; Tone = 0; - for (int i = 0; i < ToneWeigths.Length; i++) + for (var i = 0; i < ToneWeigths.Length; i++) + { ToneWeigths[i] = 0f; + } } public void ProcessNewBuffer(byte[] buffer) @@ -97,7 +99,7 @@ namespace Vocaluxe.Lib.Sound.Record public void AnalyzeBuffer() { - int tone = _PitchTracker.GetNote(out _MaxVolume, ToneWeigths); + var tone = _PitchTracker.GetNote(out _MaxVolume, ToneWeigths); if (tone >= 0) { ToneAbs = tone; @@ -105,7 +107,9 @@ namespace Vocaluxe.Lib.Sound.Record ToneValid = true; } else + { ToneValid = false; + } } public void Dispose() diff --git a/Vocaluxe/Lib/Sound/Record/CDelayTest.cs b/Vocaluxe/Lib/Sound/Record/CDelayTest.cs index 456885d9..cd7657ee 100644 --- a/Vocaluxe/Lib/Sound/Record/CDelayTest.cs +++ b/Vocaluxe/Lib/Sound/Record/CDelayTest.cs @@ -46,9 +46,12 @@ namespace Vocaluxe.Lib.Sound.Record public void Start(int[] channels) { if (Running) + { return; + } + Reset(); - for (int i = 0; i < _DelaysChannel.Length; i++) + for (var i = 0; i < _DelaysChannel.Length; i++) { if (i < channels.Length && channels[i] >= 0) { @@ -58,8 +61,11 @@ namespace Vocaluxe.Lib.Sound.Record CRecord.SetVolumeThreshold(channels[i], _DelaysChannel[i].OrigThreshold / 3); } else + { _DelaysChannel[i].Channel = -1; + } } + _Stream = CSound.PlaySound(ESounds.T440, false); Running = true; } @@ -67,21 +73,28 @@ namespace Vocaluxe.Lib.Sound.Record private void _Stop() { if (!Running) + { return; + } + Running = false; _CloseStream(); - foreach (SDelayChannel delay in _DelaysChannel) + foreach (var delay in _DelaysChannel) { if (delay.Channel >= 0) + { CRecord.SetVolumeThreshold(delay.Channel, delay.OrigThreshold); + } } } public void Reset() { _Stop(); - for (int i = 0; i < _DelaysChannel.Length; i++) + for (var i = 0; i < _DelaysChannel.Length; i++) + { Delays[i] = 0; + } } private void _CloseStream() @@ -96,30 +109,42 @@ namespace Vocaluxe.Lib.Sound.Record public void Update() { if (!Running) + { return; + } - float time = CSound.GetPosition(_Stream) * 1000f; + var time = CSound.GetPosition(_Stream) * 1000f; if (time <= 0f) + { return; + } - bool isActive = false; + var isActive = false; if (time <= _MaxDelayTime) { - for (int i = 0; i < _DelaysChannel.Length; i++) + for (var i = 0; i < _DelaysChannel.Length; i++) { if (_DelaysChannel[i].Channel < 0 || _DelaysChannel[i].Finished) + { continue; + } + if (CRecord.GetTone(_DelaysChannel[i].Channel) == 9) { Delays[i] = (int)time; _DelaysChannel[i].Finished = true; } else + { isActive = true; + } } } + if (!isActive) + { _Stop(); + } } } } \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/Record/CRecordBase.cs b/Vocaluxe/Lib/Sound/Record/CRecordBase.cs index eb8b2391..22ad03ee 100644 --- a/Vocaluxe/Lib/Sound/Record/CRecordBase.cs +++ b/Vocaluxe/Lib/Sound/Record/CRecordBase.cs @@ -15,10 +15,10 @@ // along with Vocaluxe. If not, see . #endregion +using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Vocaluxe.Base; -using System; namespace Vocaluxe.Lib.Sound.Record { @@ -39,12 +39,16 @@ namespace Vocaluxe.Lib.Sound.Record public virtual bool Init() { if (_Initialized) + { return false; + } _Devices = new List(); _Buffer = new CBuffer[CSettings.MaxNumPlayer]; - for (int i = 0; i < _Buffer.Length; i++) + for (var i = 0; i < _Buffer.Length; i++) + { _Buffer[i] = new CBuffer(); + } _Initialized = true; @@ -57,13 +61,18 @@ namespace Vocaluxe.Lib.Sound.Record public virtual void Close() { if (!_Initialized) + { return; + } _Devices = null; if (_Buffer != null) { - foreach (CBuffer buffer in _Buffer) + foreach (var buffer in _Buffer) + { buffer.Dispose(); + } + _Buffer = null; } @@ -77,24 +86,29 @@ namespace Vocaluxe.Lib.Sound.Record /// Recorded samples, assume Int16 and interleaved for multi-channels protected void _HandleData(CRecordDevice device, byte[] data) { + var totalChannels = device.Channels; + var doubleChannels = totalChannels * 2; + var allBuffers = new byte[totalChannels][]; - int totalChannels = device.Channels; - int doubleChannels = totalChannels * 2; - byte[][] allBuffers = new byte[totalChannels][]; - - for (int currChannel = 0; currChannel < totalChannels; ++currChannel) - allBuffers[currChannel] = new byte[data.Length / totalChannels]; - - for (int i = 0; i < data.Length / doubleChannels; ++i) + for (var currChannel = 0; currChannel < totalChannels; ++currChannel) { - for (int j = 0; j < doubleChannels; ++j) - allBuffers[(int)Math.Floor(j / (double)2)][i * 2 + (j % 2)] = data[i * doubleChannels + j]; + allBuffers[currChannel] = new byte[data.Length / totalChannels]; } - for (int ch = 0; ch < totalChannels; ++ch) + for (var i = 0; i < data.Length / doubleChannels; ++i) + { + for (var j = 0; j < doubleChannels; ++j) + { + allBuffers[(int)Math.Floor(j / (double)2)][i * 2 + j % 2] = data[i * doubleChannels + j]; + } + } + + for (var ch = 0; ch < totalChannels; ++ch) { if (device.PlayerChannel[ch] > 0) + { _Buffer[device.PlayerChannel[ch] - 1].ProcessNewBuffer(allBuffers[ch]); + } } } @@ -105,7 +119,9 @@ namespace Vocaluxe.Lib.Sound.Record public void AnalyzeBuffer(int player) { if (!_Initialized) + { return; + } _Buffer[player].AnalyzeBuffer(); } @@ -113,7 +129,9 @@ namespace Vocaluxe.Lib.Sound.Record public int GetToneAbs(int player) { if (!_Initialized) + { return 0; + } return _Buffer[player].ToneAbs; } @@ -126,7 +144,9 @@ namespace Vocaluxe.Lib.Sound.Record public void SetTone(int player, int tone) { if (!_Initialized) + { return; + } _Buffer[player].Tone = tone; } @@ -144,7 +164,9 @@ namespace Vocaluxe.Lib.Sound.Record public void SetVolumeThreshold(int player, float threshold) { if (!_Initialized) + { return; + } _Buffer[player].VolTreshold = threshold; } @@ -166,7 +188,7 @@ namespace Vocaluxe.Lib.Sound.Record public ReadOnlyCollection RecordDevices() { - return (_Initialized && _Devices.Count > 0) ? _Devices.AsReadOnly() : null; + return _Initialized && _Devices.Count > 0 ? _Devices.AsReadOnly() : null; } } } \ No newline at end of file diff --git a/Vocaluxe/Lib/Sound/Record/DirectSound/CDirectSoundRecord.cs b/Vocaluxe/Lib/Sound/Record/DirectSound/CDirectSoundRecord.cs index 1c8def06..917f63bc 100644 --- a/Vocaluxe/Lib/Sound/Record/DirectSound/CDirectSoundRecord.cs +++ b/Vocaluxe/Lib/Sound/Record/DirectSound/CDirectSoundRecord.cs @@ -30,13 +30,15 @@ namespace Vocaluxe.Lib.Sound.Record.DirectSound public override bool Init() { if (!base.Init()) + { return false; + } _Sources = new List(); - DeviceCollection devices = DirectSoundCapture.GetDevices(); + var devices = DirectSoundCapture.GetDevices(); - foreach (DeviceInformation dev in devices) + foreach (var dev in devices) { using (var ds = new DirectSoundCapture(dev.DriverGuid)) { @@ -61,19 +63,26 @@ namespace Vocaluxe.Lib.Sound.Record.DirectSound public bool Start() { if (!_Initialized) - return false; - - foreach (CBuffer buffer in _Buffer) - buffer.Reset(); - - foreach (CRecordDevice device in _Devices) { - bool usingDevice = false; - for (int ch = 0; ch < device.Channels; ++ch) + return false; + } + + foreach (var buffer in _Buffer) + { + buffer.Reset(); + } + + foreach (var device in _Devices) + { + var usingDevice = false; + for (var ch = 0; ch < device.Channels; ++ch) { if (device.PlayerChannel[ch] > 0) + { usingDevice = true; + } } + if (usingDevice) { var source = new CSoundCardSource(device.Driver, (short)device.Channels) { SampleRateKhz = 44.1 }; @@ -90,13 +99,16 @@ namespace Vocaluxe.Lib.Sound.Record.DirectSound public bool Stop() { if (!_Initialized) + { return false; + } - foreach (CSoundCardSource source in _Sources) + foreach (var source in _Sources) { source.Stop(); source.Dispose(); } + _Sources.Clear(); return true; @@ -105,10 +117,16 @@ namespace Vocaluxe.Lib.Sound.Record.DirectSound private void _OnDataReady(object sender, CSampleDataEventArgs e) { if (!_Initialized) + { return; - CRecordDevice dev = _Devices.FirstOrDefault(device => device.Driver == e.Guid); + } + + var dev = _Devices.FirstOrDefault(device => device.Driver == e.Guid); if (dev == null) + { return; + } + _HandleData(dev, e.Data); } } diff --git a/Vocaluxe/Lib/Sound/Record/DirectSound/CSoundCardSource.cs b/Vocaluxe/Lib/Sound/Record/DirectSound/CSoundCardSource.cs index 50858b15..988a98db 100644 --- a/Vocaluxe/Lib/Sound/Record/DirectSound/CSoundCardSource.cs +++ b/Vocaluxe/Lib/Sound/Record/DirectSound/CSoundCardSource.cs @@ -60,17 +60,23 @@ namespace Vocaluxe.Lib.Sound.Record.DirectSound _SampleRate = value; if (_Running) + { Restart(); + } } } public void Start() { if (_Running) + { throw new InvalidOperationException(); + } if (_CaptureDevice == null) + { _CaptureDevice = new DirectSoundCapture(new Guid(_Guid)); + } _WaveFormat.FormatTag = WaveFormatTag.Pcm; // Change to WaveFormatTag.IeeeFloat for float _WaveFormat.BitsPerSample = 16; // Set this to 32 for float @@ -92,19 +98,21 @@ namespace Vocaluxe.Lib.Sound.Record.DirectSound _BufferPortionSize = _CaptureBuffer.SizeInBytes / _BufferPortionCount; _Notifications = new List(); - for (int i = 0; i < _BufferPortionCount; i++) + for (var i = 0; i < _BufferPortionCount; i++) { - var notification = new NotificationPosition {Offset = _BufferPortionCount - 1 + (_BufferPortionSize * i), Event = new AutoResetEvent(false)}; + var notification = new NotificationPosition { Offset = _BufferPortionCount - 1 + _BufferPortionSize * i, Event = new AutoResetEvent(false) }; _Notifications.Add(notification); } _CaptureBuffer.SetNotificationPositions(_Notifications.ToArray()); _WaitHandles = new WaitHandle[_Notifications.Count]; - for (int i = 0; i < _Notifications.Count; i++) + for (var i = 0; i < _Notifications.Count; i++) + { _WaitHandles[i] = _Notifications[i].Event; + } - _CaptureThread = new Thread(_DoCapture) {Name = "DirectSoundCapture", IsBackground = true}; + _CaptureThread = new Thread(_DoCapture) { Name = "DirectSoundCapture", IsBackground = true }; _Running = true; _CaptureThread.Start(); @@ -128,8 +136,10 @@ namespace Vocaluxe.Lib.Sound.Record.DirectSound if (_Notifications != null) { - foreach (NotificationPosition notification in _Notifications) + foreach (var notification in _Notifications) + { notification.Event.Close(); + } _Notifications.Clear(); _Notifications = null; @@ -144,7 +154,7 @@ namespace Vocaluxe.Lib.Sound.Record.DirectSound private void _DoCapture() { - int bufferPortionSamples = _BufferPortionSize / sizeof(byte); + var bufferPortionSamples = _BufferPortionSize / sizeof(byte); // Buffer type must match this.waveFormat.FormatTag and this.waveFormat.BitsPerSample var bufferPortion = new byte[bufferPortionSamples]; @@ -153,7 +163,7 @@ namespace Vocaluxe.Lib.Sound.Record.DirectSound while (_Running) { - int bufferPortionIndex = WaitHandle.WaitAny(_WaitHandles); + var bufferPortionIndex = WaitHandle.WaitAny(_WaitHandles); _CaptureBuffer.Read( bufferPortion, diff --git a/Vocaluxe/Lib/Sound/Record/IRecord.cs b/Vocaluxe/Lib/Sound/Record/IRecord.cs index e8166dae..77ede5e7 100644 --- a/Vocaluxe/Lib/Sound/Record/IRecord.cs +++ b/Vocaluxe/Lib/Sound/Record/IRecord.cs @@ -15,14 +15,13 @@ // along with Vocaluxe. If not, see . #endregion -using System; using System.Collections.ObjectModel; namespace Vocaluxe.Lib.Sound.Record { class CRecordDevice { - public readonly int ID; + public readonly int Id; public readonly string Name; public readonly string Driver; @@ -31,7 +30,7 @@ namespace Vocaluxe.Lib.Sound.Record public CRecordDevice(int id, string name, string driver, int channels) { - ID = id; + Id = id; Name = name; Driver = driver; Channels = channels; @@ -49,8 +48,8 @@ namespace Vocaluxe.Lib.Sound.Record public SMicConfig(int dummy) // ReSharper restore UnusedParameter.Local { - DeviceName = String.Empty; - DeviceDriver = String.Empty; + DeviceName = string.Empty; + DeviceDriver = string.Empty; Channel = 0; } } diff --git a/Vocaluxe/Lib/Sound/Record/PitchTracker/CAnalyzer.cs b/Vocaluxe/Lib/Sound/Record/PitchTracker/CAnalyzer.cs index 546bdf95..7780f6a7 100644 --- a/Vocaluxe/Lib/Sound/Record/PitchTracker/CAnalyzer.cs +++ b/Vocaluxe/Lib/Sound/Record/PitchTracker/CAnalyzer.cs @@ -74,8 +74,11 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker Analyzer_Process(_Instance); maxVolume = Analyzer_GetPeak(_Instance); if (maxVolume < _VolumeTreshold) + { return -1; - int note = (int)Math.Round(Analyzer_FindNote(_Instance, 60, 1800)); + } + + var note = (int)Math.Round(Analyzer_FindNote(_Instance, 60, 1800)); _SetWeights(note, weights); return note; } @@ -88,7 +91,10 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker protected override void _Dispose(bool disposing) { if (_Instance == IntPtr.Zero) + { throw new ObjectDisposedException(GetType().Name); + } + Analyzer_Free(_Instance); _Instance = IntPtr.Zero; } diff --git a/Vocaluxe/Lib/Sound/Record/PitchTracker/CPitchTrackerTest.cs b/Vocaluxe/Lib/Sound/Record/PitchTracker/CPitchTrackerTest.cs index 81b934c1..dbe27995 100644 --- a/Vocaluxe/Lib/Sound/Record/PitchTracker/CPitchTrackerTest.cs +++ b/Vocaluxe/Lib/Sound/Record/PitchTracker/CPitchTrackerTest.cs @@ -19,7 +19,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; -using VocaluxeLib; using VocaluxeLib.Log; using VocaluxeLib.Utils; @@ -57,26 +56,30 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker _CurTestCount = 0; _CurPassedCount = new int[_Analyzers.Count]; _Weights = new float[_Analyzers.Count][]; - for (int i = 0; i < _Analyzers.Count; i++) + for (var i = 0; i < _Analyzers.Count; i++) + { _Weights[i] = new float[_Analyzers[i].GetNumHalfTones()]; + } + _SamplesPerSec = new int[_Analyzers.Count]; } private void _InitNext(string lastTest) { - string msg = "Errors " + lastTest + ": "; - for (int i = 0; i < _CurPassedCount.Length; i++) + var msg = "Errors " + lastTest + ": "; + for (var i = 0; i < _CurPassedCount.Length; i++) { msg += _CurTestCount - _CurPassedCount[i] + " "; _PassedCount[i] += _CurPassedCount[i]; _CurPassedCount[i] = 0; } + msg += "of " + _CurTestCount; CLog.Debug(msg); _TestCount += _CurTestCount; _CurTestCount = 0; //Do a reset first as we actually have an impossible situation (drop by multiple octaves) - byte[] data = new byte[4096 * 2]; + var data = new byte[4096 * 2]; _Process(data); } #endregion @@ -84,7 +87,10 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker public void RunTest(bool reRun = false) { if (_IsRun && !reRun) + { return; + } + _IsRun = true; _InitTests(); @@ -109,13 +115,13 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker _TestSpeed(); CLog.Debug("Finished: "); - for (int i = 0; i < _Analyzers.Count; i++) + for (var i = 0; i < _Analyzers.Count; i++) { - string msg = _Analyzers[i].GetType().Name + ":"; + var msg = _Analyzers[i].GetType().Name + ":"; msg += " Errors=" + (_TestCount - _PassedCount[i]); msg += " Passed=" + _PassedCount[i]; msg += " Total=" + _TestCount; - msg += " Speed=" + _SamplesPerSec[i] / 1000 + "kSamples/s (=" + (_SamplesPerSec[i] / 44100) + "rec.s/s)"; + msg += " Speed=" + _SamplesPerSec[i] / 1000 + "kSamples/s (=" + _SamplesPerSec[i] / 44100 + "rec.s/s)"; CLog.Debug(msg); } } @@ -124,21 +130,22 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker { const int samplesPerBuffer = 512; byte[] data; - byte[] data2 = new byte[samplesPerBuffer * 2]; + var data2 = new byte[samplesPerBuffer * 2]; double angle = 0; const int repeats = 100; _GetSineWave(_BaseToneFreq * Math.Pow(_HalftoneBase, 5), 44100, samplesPerBuffer * repeats, ref angle, out data); - for (int i = 0; i < _Analyzers.Count; i++) + for (var i = 0; i < _Analyzers.Count; i++) { - CPitchTracker analyzer = _Analyzers[i]; - Stopwatch sw = new Stopwatch(); + var analyzer = _Analyzers[i]; + var sw = new Stopwatch(); sw.Start(); - for (int j = 0; j < repeats; j++) + for (var j = 0; j < repeats; j++) { Buffer.BlockCopy(data, 0, data2, 0, samplesPerBuffer * 2); analyzer.Input(data2); analyzer.GetNote(out _MaxVolume, _Weights[i]); } + sw.Stop(); _SamplesPerSec[i] = (int)Math.Round(samplesPerBuffer * repeats / (sw.ElapsedMilliseconds / 1000.0)); } @@ -146,7 +153,7 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker private void _Process(byte[] data) { - for (int j = 0; j < _Analyzers.Count; j++) + for (var j = 0; j < _Analyzers.Count; j++) { _Analyzers[j].Input(data); _Tones[j] = _Analyzers[j].GetNote(out _MaxVolume, _Weights[j]); @@ -156,12 +163,18 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker private static string _ToneToNote(int tone, bool withOctave = true) { if (tone < 0) + { return "inv."; + } + tone += 24; - string[] notes = {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"}; - string result = notes[tone % 12]; + string[] notes = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" }; + var result = notes[tone % 12]; if (withOctave) - result += (tone / 12); + { + result += tone / 12; + } + return result; } @@ -172,43 +185,60 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker const int toneTo = 47; //B5 const int sampleCt = 4096; const int batchCt = 512; - byte[] data2 = new byte[batchCt * 2]; + var data2 = new byte[batchCt * 2]; Console.WriteLine("Testing notes " + _ToneToNote(toneFrom) + " - " + _ToneToNote(toneTo)); double angle = 0; - bool[] valids = new bool[_Analyzers.Count]; - for (int distort = 0; distort < 10; distort++) + var valids = new bool[_Analyzers.Count]; + for (var distort = 0; distort < 10; distort++) { //Do a reset first as we actually have an impossible situation (drop by multiple octaves) - byte[] data = new byte[sampleCt * 2]; + var data = new byte[sampleCt * 2]; _Process(data); - for (int tone = toneFrom; tone <= toneTo; tone++) + for (var tone = toneFrom; tone <= toneTo; tone++) { _GetSineWave(_BaseToneFreq * Math.Pow(_HalftoneBase, tone), 44100, sampleCt, ref angle, out data); if (tone == 46 && distort == 4) + { data = new byte[data.Length]; + } + _Distort(data, tone, distort); - for (int i = 0; i < sampleCt / batchCt; i++) + for (var i = 0; i < sampleCt / batchCt; i++) { Buffer.BlockCopy(data, i * batchCt * 2, data2, 0, batchCt * 2); _Process(data2); if (i * batchCt < 2048) + { continue; + } + _CurTestCount++; - bool ok = true; - for (int j = 0; j < valids.Length; j++) + var ok = true; + for (var j = 0; j < valids.Length; j++) { valids[j] = _Tones[j] == tone; if (!valids[j]) + { ok = false; + } else + { _CurPassedCount[j]++; + } } + if (ok) + { continue; - string msg = "Note " + _ToneToNote(tone) + "(" + distort + ") at buffer " + (i + 1) + "/" + (sampleCt / batchCt) + " detected as "; - for (int j = 0; j < valids.Length; j++) + } + + var msg = "Note " + _ToneToNote(tone) + "(" + distort + ") at buffer " + (i + 1) + "/" + sampleCt / batchCt + " detected as "; + for (var j = 0; j < valids.Length; j++) + { msg += _ToneToNote(_Tones[j]) + (valids[j] ? "" : "(!)") + "; "; + } + CLog.Debug(msg); /*CWavFile w = new CWavFile(); w.Create(tone + "-" + distort + ".wav", 1, 44100, 16); @@ -221,10 +251,10 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker private static short[] _GetDistort(int sampleCt, int tone, int type) { - short[] sdata = new short[sampleCt]; + var sdata = new short[sampleCt]; if (type < 9) { - int newTone = 1; + var newTone = 1; switch (type) { case 0: @@ -255,6 +285,7 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker newTone = 29; break; } + byte[] data2; double angle = 0; _GetSineWave(_BaseToneFreq * Math.Pow(_HalftoneBase, tone + newTone), 44100, sampleCt, ref angle, out data2); @@ -262,41 +293,56 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker } else { - Random r = new Random(0xBEEF); - for (int i = 0; i < sdata.Length; i++) + var r = new Random(0xBEEF); + for (var i = 0; i < sdata.Length; i++) + { sdata[i] = (short)(r.Next() - Int16.MinValue); + } } + return sdata; } private static void _Distort(byte[] data, int tone, int distortCt) { if (distortCt < 1) + { return; - short[] sdata = new short[data.Length / 2]; + } + + var sdata = new short[data.Length / 2]; Buffer.BlockCopy(data, 0, sdata, 0, data.Length); - short[][] distortions = new short[distortCt][]; - for (int i = 0; i < distortCt; i++) + var distortions = new short[distortCt][]; + for (var i = 0; i < distortCt; i++) + { distortions[i] = _GetDistort(data.Length / 2, tone, i); + } - for (int i = 0; i < sdata.Length; i++) + for (var i = 0; i < sdata.Length; i++) { double distortion = 0; - for (int j = 0; j < distortCt; j++) + for (var j = 0; j < distortCt; j++) + { distortion += distortions[j][i]; + } + distortion /= distortCt; sdata[i] = (short)(sdata[i] * 4.0 / 5.0 + distortion / 5.0); } + Buffer.BlockCopy(sdata, 0, data, 0, data.Length); } private static void _GetSineWave(double freq, int sampleRate, int sampleCt, ref double angle, out byte[] data) { const short max = short.MaxValue; - short[] data16Bit = new short[sampleCt]; - for (int i = 0; i < sampleCt; i++) + var data16Bit = new short[sampleCt]; + for (var i = 0; i < sampleCt; i++) + { data16Bit[i] = (short)(Math.Sin(2 * Math.PI * i / sampleRate * freq + angle) * max); + } + angle = 2 * Math.PI * sampleCt / sampleRate * freq + angle; angle = angle % (2 * Math.PI); data = new byte[data16Bit.Length * 2]; @@ -313,22 +359,29 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker private void _TestFile(string fileName, string testFileName) { if (!File.Exists(testFileName)) + { return; - List tones = new List(); - using (StreamReader reader = new StreamReader(testFileName)) + } + + var tones = new List(); + using (var reader = new StreamReader(testFileName)) { String line; while ((line = reader.ReadLine()) != null) { - int p = line.IndexOf(' '); + var p = line.IndexOf(' '); if (p < 0) + { continue; + } + STimedNote note; note.Time = int.Parse(line.Substring(0, p)); note.Note = int.Parse(line.Substring(p + 1)); tones.Add(note); } } + _TestFile(fileName, tones); } @@ -337,71 +390,93 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker STimedNote note; note.Note = tone; note.Time = 46; - List tones = new List {note}; + var tones = new List { note }; _TestFile(fileName, tones); } private static bool _IsNoteValid(int note, int time, IList tones) { const int lastNoteMaxTimeDiff = 1536 * 1000 / 44100; // old note is valid for 1536 more samples - for (int i = 0; i < tones.Count; i++) + for (var i = 0; i < tones.Count; i++) { if (tones[i].Time > time) + { break; + } + if (i + 1 == tones.Count || time <= tones[i + 1].Time + lastNoteMaxTimeDiff) { if (tones[i].Note == note || tones[i].Note < 0) + { return true; + } } } + return false; } private void _TestFile(string fileName, IList tones) { - CWavFile wavFile = new CWavFile(); + var wavFile = new CWavFile(); try { if (!wavFile.Open(fileName)) + { return; + } + if (wavFile.BitsPerSample != 16) { wavFile.Close(); return; } - int samplesRead = 0; - int curTimeIndex = -1; - int curNote = -1; + + var samplesRead = 0; + var curTimeIndex = -1; + var curNote = -1; const int maxSamplesPerBatch = 512; - bool[] valids = new bool[_Tones.Length]; + var valids = new bool[_Tones.Length]; while (wavFile.NumSamplesLeft > maxSamplesPerBatch) { - byte[] samples = wavFile.GetNextSamples16BitAsBytes(maxSamplesPerBatch, 1); + var samples = wavFile.GetNextSamples16BitAsBytes(maxSamplesPerBatch, 1); samplesRead += samples.Length / 2; - int time = samplesRead * 1000 / wavFile.SampleRate; + var time = samplesRead * 1000 / wavFile.SampleRate; _Process(samples); while (curTimeIndex + 1 < tones.Count && time >= tones[curTimeIndex + 1].Time) { curTimeIndex++; curNote = tones[curTimeIndex].Note; } + if (curNote < 0) + { continue; + } + _CurTestCount++; - bool error = false; - for (int i = 0; i < _Tones.Length; i++) + var error = false; + for (var i = 0; i < _Tones.Length; i++) { valids[i] = _IsNoteValid(_Tones[i], time, tones); if (valids[i]) + { _CurPassedCount[i]++; + } else + { error = true; + } } + if (error) { - string msg = "Note " + _ToneToNote(curNote) + " at " + time + "ms detected as "; - for (int i = 0; i < _Tones.Length; i++) + var msg = "Note " + _ToneToNote(curNote) + " at " + time + "ms detected as "; + for (var i = 0; i < _Tones.Length; i++) + { msg += _ToneToNote(_Tones[i]) + (valids[i] ? "" : "(!)") + "; "; + } + CLog.Debug(msg); } } @@ -410,6 +485,7 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker { Console.WriteLine("Error on file " + fileName + ": " + e); } + wavFile.Close(); } #endregion diff --git a/Vocaluxe/Lib/Sound/Record/PitchTracker/CPtAKF.cs b/Vocaluxe/Lib/Sound/Record/PitchTracker/CPtAKF.cs index 351dac22..40ff3c88 100644 --- a/Vocaluxe/Lib/Sound/Record/PitchTracker/CPtAKF.cs +++ b/Vocaluxe/Lib/Sound/Record/PitchTracker/CPtAKF.cs @@ -80,7 +80,10 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker protected override void _Dispose(bool disposing) { if (_Instance == IntPtr.Zero) + { throw new ObjectDisposedException(GetType().Name); + } + PtAKF_Free(_Instance); _Instance = IntPtr.Zero; } diff --git a/Vocaluxe/Lib/Sound/Record/PitchTracker/CPtDyWa.cs b/Vocaluxe/Lib/Sound/Record/PitchTracker/CPtDyWa.cs index 2f21ea0b..d3b02c6e 100644 --- a/Vocaluxe/Lib/Sound/Record/PitchTracker/CPtDyWa.cs +++ b/Vocaluxe/Lib/Sound/Record/PitchTracker/CPtDyWa.cs @@ -59,7 +59,7 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker public override int GetNote(out float maxVolume, float[] weights) { - int note = (int)Math.Round(PtDyWa_FindNote(_Instance, out maxVolume)); + var note = (int)Math.Round(PtDyWa_FindNote(_Instance, out maxVolume)); _SetWeights(note, weights); return note; } @@ -78,7 +78,10 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker protected override void _Dispose(bool disposing) { if (_Instance == IntPtr.Zero) + { throw new ObjectDisposedException(GetType().Name); + } + PtDyWa_Free(_Instance); _Instance = IntPtr.Zero; } diff --git a/Vocaluxe/Lib/Sound/Record/PitchTracker/IPitchTracker.cs b/Vocaluxe/Lib/Sound/Record/PitchTracker/IPitchTracker.cs index 15f95bea..cc4f2a92 100644 --- a/Vocaluxe/Lib/Sound/Record/PitchTracker/IPitchTracker.cs +++ b/Vocaluxe/Lib/Sound/Record/PitchTracker/IPitchTracker.cs @@ -51,11 +51,17 @@ namespace Vocaluxe.Lib.Sound.Record.PitchTracker protected static void _SetWeights(int note, float[] weights) { Debug.Assert(weights.Length == NumHalfTonesDef); - for (int i = 0; i < NumHalfTonesDef; i++) + for (var i = 0; i < NumHalfTonesDef; i++) + { weights[i] *= 0.9f; + } + if (note < 0) + { return; - int w = note % NumHalfTonesDef; + } + + var w = note % NumHalfTonesDef; weights[w] = Math.Min(1f, weights[w] + 0.15f); } diff --git a/Vocaluxe/Lib/Sound/Record/PortAudio/CPortAudioRecord.cs b/Vocaluxe/Lib/Sound/Record/PortAudio/CPortAudioRecord.cs index 11030ab0..11419e89 100644 --- a/Vocaluxe/Lib/Sound/Record/PortAudio/CPortAudioRecord.cs +++ b/Vocaluxe/Lib/Sound/Record/PortAudio/CPortAudioRecord.cs @@ -16,11 +16,8 @@ #endregion using System; -using System.Collections.Generic; -using System.Linq; using System.Runtime.InteropServices; using System.Threading; -using Vocaluxe.Base; using VocaluxeLib.Log; namespace Vocaluxe.Lib.Sound.Record.PortAudio @@ -39,17 +36,19 @@ namespace Vocaluxe.Lib.Sound.Record.PortAudio public override bool Init() { if (!base.Init()) + { return false; + } try { _PaHandle = new CPortAudioHandle(); - int hostAPI = _PaHandle.GetHostApi(); - int numDevices = PortAudioSharp.PortAudio.Pa_GetDeviceCount(); - for (int i = 0; i < numDevices; i++) + var hostAPI = _PaHandle.GetHostApi(); + var numDevices = PortAudioSharp.PortAudio.Pa_GetDeviceCount(); + for (var i = 0; i < numDevices; i++) { - PortAudioSharp.PortAudio.PaDeviceInfo info = PortAudioSharp.PortAudio.Pa_GetDeviceInfo(i); + var info = PortAudioSharp.PortAudio.Pa_GetDeviceInfo(i); if (info.hostApi == hostAPI && info.maxInputChannels > 0) { var dev = new CRecordDevice(i, info.name, info.name + i, info.maxInputChannels); @@ -80,26 +79,32 @@ namespace Vocaluxe.Lib.Sound.Record.PortAudio public bool Start() { if (!_Initialized) + { return false; + } Stop(); if (_RecHandle != null && _PaHandle != null) { - for (int i = 0; i < _RecHandle.Length; i++) + for (var i = 0; i < _RecHandle.Length; i++) { - IntPtr handle = _RecHandle[i]; + var handle = _RecHandle[i]; if (handle == IntPtr.Zero) + { continue; + } - int waitcount = 0; + var waitcount = 0; while (waitcount < 5) { try { if (PortAudioSharp.PortAudio.Pa_IsStreamStopped(handle) != PortAudioSharp.PortAudio.PaError.paStreamIsNotStopped) + { break; + } } catch (Exception ex) { @@ -126,28 +131,34 @@ namespace Vocaluxe.Lib.Sound.Record.PortAudio } } - foreach (CBuffer buffer in _Buffer) - buffer.Reset(); - - for (int dev = 0; dev < _Devices.Count; dev++) + foreach (var buffer in _Buffer) { - bool usingDevice = false; - for (int ch = 0; ch < _Devices[dev].Channels; ++ch) + buffer.Reset(); + } + + for (var dev = 0; dev < _Devices.Count; dev++) + { + var usingDevice = false; + for (var ch = 0; ch < _Devices[dev].Channels; ++ch) { if (_Devices[dev].PlayerChannel[ch] > 0) + { usingDevice = true; + } } if (!usingDevice) + { continue; + } PortAudioSharp.PortAudio.PaStreamParameters? inputParams = new PortAudioSharp.PortAudio.PaStreamParameters { channelCount = _Devices[dev].Channels, - device = _Devices[dev].ID, + device = _Devices[dev].Id, sampleFormat = PortAudioSharp.PortAudio.PaSampleFormat.paInt16, - suggestedLatency = PortAudioSharp.PortAudio.Pa_GetDeviceInfo(_Devices[dev].ID).defaultLowInputLatency, + suggestedLatency = PortAudioSharp.PortAudio.Pa_GetDeviceInfo(_Devices[dev].Id).defaultLowInputLatency, hostApiSpecificStreamInfo = IntPtr.Zero }; @@ -160,10 +171,12 @@ namespace Vocaluxe.Lib.Sound.Record.PortAudio _MyRecProc, new IntPtr(dev))) { - for (int j = 0; j < _RecHandle.Length; j++) + for (var j = 0; j < _RecHandle.Length; j++) { if (_RecHandle[j] == IntPtr.Zero) + { continue; + } try { @@ -178,15 +191,18 @@ namespace Vocaluxe.Lib.Sound.Record.PortAudio _RecHandle[j] = IntPtr.Zero; } } + return false; } if (_PaHandle.CheckError("Start Stream (rec)", PortAudioSharp.PortAudio.Pa_StartStream(_RecHandle[dev]))) { - for (int j = 0; j < _RecHandle.Length; j++) + for (var j = 0; j < _RecHandle.Length; j++) { if (_RecHandle[j] == IntPtr.Zero) + { continue; + } try { @@ -201,6 +217,7 @@ namespace Vocaluxe.Lib.Sound.Record.PortAudio _RecHandle[j] = IntPtr.Zero; } } + return false; } } @@ -215,22 +232,28 @@ namespace Vocaluxe.Lib.Sound.Record.PortAudio public bool Stop() { if (!_Initialized) + { return false; - - if (_RecHandle == null) - return true; + } - foreach (IntPtr handle in _RecHandle) + if (_RecHandle == null) + { + return true; + } + + foreach (var handle in _RecHandle) { if (handle == IntPtr.Zero) + { continue; + } try { - PortAudioSharp.PortAudio.PaError isStoppedResult = PortAudioSharp.PortAudio.Pa_IsStreamStopped(handle); + var isStoppedResult = PortAudioSharp.PortAudio.Pa_IsStreamStopped(handle); if (isStoppedResult == PortAudioSharp.PortAudio.PaError.paStreamIsNotStopped) { - PortAudioSharp.PortAudio.PaError stopResult = PortAudioSharp.PortAudio.Pa_StopStream(handle); + var stopResult = PortAudioSharp.PortAudio.Pa_StopStream(handle); if (stopResult != PortAudioSharp.PortAudio.PaError.paNoError && stopResult != PortAudioSharp.PortAudio.PaError.paStreamIsStopped) { @@ -258,11 +281,13 @@ namespace Vocaluxe.Lib.Sound.Record.PortAudio if (_PaHandle != null) { - for (int i = 0; i < _RecHandle.Length; i++) + for (var i = 0; i < _RecHandle.Length; i++) { - IntPtr handle = _RecHandle[i]; + var handle = _RecHandle[i]; if (handle == IntPtr.Zero) + { continue; + } try { @@ -305,11 +330,11 @@ namespace Vocaluxe.Lib.Sound.Record.PortAudio { if (frameCount > 0 && input != IntPtr.Zero) { - CRecordDevice dev = _Devices[userData.ToInt32()]; + var dev = _Devices[userData.ToInt32()]; uint numBytes; numBytes = frameCount * (uint)dev.Channels * 2; - byte[] recbuffer = new byte[numBytes]; + var recbuffer = new byte[numBytes]; // copy from managed to unmanaged memory Marshal.Copy(input, recbuffer, 0, (int)numBytes); @@ -324,4 +349,4 @@ namespace Vocaluxe.Lib.Sound.Record.PortAudio return PortAudioSharp.PortAudio.PaStreamCallbackResult.paContinue; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Lib/Video/Acinerella/CAcinerella.cs b/Vocaluxe/Lib/Video/Acinerella/CAcinerella.cs index 51031b77..e460b96a 100644 --- a/Vocaluxe/Lib/Video/Acinerella/CAcinerella.cs +++ b/Vocaluxe/Lib/Video/Acinerella/CAcinerella.cs @@ -226,11 +226,10 @@ namespace Vocaluxe.Lib.Video.Acinerella _AcInstanceLocks.Add(pAcDecoder.ToInt64(), l); } } - + return l; } - // Defines the type of an Acinerella media stream. Currently only video and // audio streams are supported, subtitle and data streams will be marked as // "unknown". @@ -327,7 +326,7 @@ namespace Vocaluxe.Lib.Video.Acinerella return _ac_create_decoder(pAcInstance, firstVideoStreamId); } } - + public static IntPtr AcCreateAudioDecoder(IntPtr pAcInstance) { lock (_GetLockToken(pAcInstance)) @@ -338,6 +337,7 @@ namespace Vocaluxe.Lib.Video.Acinerella { throw new ArgumentException("The instace does not contain a audio stream."); } + return _ac_create_decoder(pAcInstance, firstAudioStreamId); } } @@ -346,16 +346,20 @@ namespace Vocaluxe.Lib.Video.Acinerella { var instance = (SACInstance)Marshal.PtrToStructure(pAcInstance, typeof(SACInstance)); - int currentStream = 0; + var currentStream = 0; SACStreamInfo currentStreamInfo; while (currentStream < instance.StreamCount) { AcGetStreamInfo(pAcInstance, currentStream, out currentStreamInfo); if (currentStreamInfo.StreamType == type) + { return currentStream; + } + currentStream++; } + return -1; } @@ -373,7 +377,6 @@ namespace Vocaluxe.Lib.Video.Acinerella _ac_free_decoder(pAcDecoder); } } - } // Decodes a package using the specified decoder. The decodec data is stored in the @@ -408,7 +411,7 @@ namespace Vocaluxe.Lib.Video.Acinerella { lock (_GetLockToken(pAcDecoder)) { - int asd = _ac_get_frame(pAcInstance, pAcDecoder); + var asd = _ac_get_frame(pAcInstance, pAcDecoder); return asd == 0; } } diff --git a/Vocaluxe/Lib/Video/Acinerella/CDecoder.cs b/Vocaluxe/Lib/Video/Acinerella/CDecoder.cs index 823c5290..19003688 100644 --- a/Vocaluxe/Lib/Video/Acinerella/CDecoder.cs +++ b/Vocaluxe/Lib/Video/Acinerella/CDecoder.cs @@ -60,7 +60,10 @@ namespace Vocaluxe.Lib.Video.Acinerella set { if (_Paused == value) + { return; + } + _Paused = value; if (_Paused) { @@ -78,10 +81,14 @@ namespace Vocaluxe.Lib.Video.Acinerella public bool Open(string fileName) { if (_Thread != null) + { return false; + } if (!File.Exists(fileName)) + { return false; + } _Thread = new CDecoderThread(); if (_Thread.LoadFile(fileName)) @@ -90,6 +97,7 @@ namespace Vocaluxe.Lib.Video.Acinerella Finished = false; return _Thread.Start(); } + _Thread = null; return false; } @@ -97,7 +105,10 @@ namespace Vocaluxe.Lib.Video.Acinerella public void Close() { if (_Thread != null) + { _Thread.Stop(); + } + Length = 0; Finished = true; } @@ -109,6 +120,7 @@ namespace Vocaluxe.Lib.Video.Acinerella videoTime = Length - _Gap; return false; } + if (Loop) { time = _LoopTime + _LoopTimer.ElapsedMilliseconds / 1000f; @@ -118,12 +130,16 @@ namespace Vocaluxe.Lib.Video.Acinerella { time -= Length; } while (time >= Length); + _LoopTime = time; _LoopTimer.Restart(); } } else + { time += _Gap; + } + _Thread.SyncTime(time); bool finished; @@ -131,7 +147,10 @@ namespace Vocaluxe.Lib.Video.Acinerella videoTime = time - _Gap; if (finished) //Only set, not reset + { Finished = true; + } + return frame != null; } @@ -141,7 +160,10 @@ namespace Vocaluxe.Lib.Video.Acinerella _Gap = gap; _Thread.Skip(start + gap); if (Loop) + { Loop = true; //Reset loop (timer) + } + return true; } } diff --git a/Vocaluxe/Lib/Video/Acinerella/CDecoderThread.cs b/Vocaluxe/Lib/Video/Acinerella/CDecoderThread.cs index 2e845f4d..0b5e4213 100644 --- a/Vocaluxe/Lib/Video/Acinerella/CDecoderThread.cs +++ b/Vocaluxe/Lib/Video/Acinerella/CDecoderThread.cs @@ -81,13 +81,17 @@ namespace Vocaluxe.Lib.Video.Acinerella var instance = (SACInstance)Marshal.PtrToStructure(_Instance, typeof(SACInstance)); Length = instance.Info.Duration / 1000f; - bool ok = instance.Opened && Length > 0.001f; + var ok = instance.Opened && Length > 0.001f; _DropSeekEnabled = true; if (ok) + { return true; + } + _Free(); } - catch (Exception) {} + catch (Exception) { } + CLog.Error("Error opening video file: " + _FileName); _Instance = IntPtr.Zero; return false; @@ -100,13 +104,15 @@ namespace Vocaluxe.Lib.Video.Acinerella CLog.Error("Tried to start a video file that is not open: " + _FileName); return false; } + if (_Thread != null) { CLog.Error("Tried to start a video file that is already started: " + _FileName); return false; } + RequestTime = 0f; - _Thread = new Thread(_Execute) {Priority = ThreadPriority.Normal, Name = Path.GetFileName(_FileName)}; + _Thread = new Thread(_Execute) { Priority = ThreadPriority.Normal, Name = Path.GetFileName(_FileName) }; _Thread.Start(); return true; } @@ -121,14 +127,20 @@ namespace Vocaluxe.Lib.Video.Acinerella public void Pause() { if (_Paused) + { return; + } + _Paused = true; } public void Resume() { if (!_Paused) + { return; + } + _Paused = false; } @@ -148,6 +160,7 @@ namespace Vocaluxe.Lib.Video.Acinerella _LastShownTime = time - _FrameDuration; //Set this to time to detect overflow of time in FindFrame but subtract FrameDuration so GetFrame will get the first frame _RequestSkip = true; } + _EvNoMoreFrames.Set(); } @@ -159,33 +172,42 @@ namespace Vocaluxe.Lib.Video.Acinerella while ((frame = _Framebuffer.Pop()) != null) { //float frameEnd = frame.Time + _FrameDuration; - float frameTime = frame.Time; + var frameTime = frame.Time; if (frameTime > now) { //2 Cases: all following frames are after this one, or we have a loop and 'now' wrapped over //First case is if we have no loop or we did not wrap or frame is before last one (last is the case if frame is already one of the new iterations, e.g. Last=19 now=1 frame=2) if (!Loop || _LastShownTime <= now || frameTime < _LastShownTime) + { break; //Following frames (incl this one) are after now, so do not consider any of them + } } - // ReSharper disable CompareOfFloatsByEqualityOperator + // ReSharper disable CompareOfFloatsByEqualityOperator else if (Loop && RequestTime == _LoopedRequestTime) // ReSharper restore CompareOfFloatsByEqualityOperator { //Frame time might have wrapped but now did not if (frameTime < _LastShownTime && _LastShownTime <= now) + { break; //Following frames (incl this one) are after now, so do not consider any of them + } } + //Get the last(newest) possible frame and skip the rest if (result != null) { //Frame is to old -> Discard result.SetRead(); } + result = frame; if (_Paused) + { break; //Just get 1 frame if paused otherwise a paused movie could move a bit + } } + return result; } @@ -206,21 +228,31 @@ namespace Vocaluxe.Lib.Video.Acinerella } else { - CFramebuffer.CFrame curFrame = _FindFrame(time); + var curFrame = _FindFrame(time); if (curFrame != null) { if (frame == null) + { frame = CDraw.AddTexture(_Width, _Height, curFrame.Data); + } else + { CDraw.UpdateTexture(frame, _Width, _Height, curFrame.Data); + } + if (!_Paused) + { curFrame.SetRead(); + } + time = curFrame.Time; _LastShownTime = time; result = frame != null; } else + { result = false; + } if (_IsSleeping) { @@ -228,6 +260,7 @@ namespace Vocaluxe.Lib.Video.Acinerella _EvWakeUp.Set(); } } + finished = _NoMoreFrames && _Framebuffer.IsEmpty(); return result; @@ -237,7 +270,9 @@ namespace Vocaluxe.Lib.Video.Acinerella public void SyncTime(float time) { if (_Thread == null) + { return; //Not initialized + } if (RequestTime - time >= _FrameDuration) { @@ -259,11 +294,16 @@ namespace Vocaluxe.Lib.Video.Acinerella while ((frame = _Framebuffer.Pop()) != null) { if (frame.Time + _FrameDuration >= time) + { return; + } } + //If we don't the Length might be inaccurate (e.g. last frame ends at 19.98 but Length=20) if (time >= Length - 2 * _FrameDuration) + { return; + } } RequestTime = time; @@ -287,13 +327,17 @@ namespace Vocaluxe.Lib.Video.Acinerella } if (videoStreamIndex < 0) + { return false; + } _Width = decoder.StreamInfo.VideoInfo.FrameWidth; _Height = decoder.StreamInfo.VideoInfo.FrameHeight; if (decoder.StreamInfo.VideoInfo.FramesPerSecond > 0) + { _FrameDuration = 1f / (float)decoder.StreamInfo.VideoInfo.FramesPerSecond; + } _Framebuffer.Init(_Width * _Height * 4); _FrameAvailable = false; @@ -304,7 +348,9 @@ namespace Vocaluxe.Lib.Video.Acinerella private void _Free() { if (_Videodecoder != IntPtr.Zero) + { CAcinerella.AcFreeDecoder(_Videodecoder); + } if (_Instance != IntPtr.Zero) { @@ -316,9 +362,11 @@ namespace Vocaluxe.Lib.Video.Acinerella // Skip to a given time (in s) private void _Skip() { - float skipTime = RequestTime; //Copy to variable to have consistent checks + var skipTime = RequestTime; //Copy to variable to have consistent checks if (skipTime < 0 || skipTime >= Length) + { skipTime = 0; + } try { @@ -328,6 +376,7 @@ namespace Vocaluxe.Lib.Video.Acinerella { CLog.Error("Error seeking video file \"" + _FileName + "\": " + e.Message); } + _LastDecodedTime = skipTime; _FrameAvailable = false; @@ -340,26 +389,27 @@ namespace Vocaluxe.Lib.Video.Acinerella const int seekThreshold = 25; // 25 frames = 0.5 second with _FrameDuration = 0.02f if (_NoMoreFrames) + { return; + } - float videoTime = RequestTime; - float timeDifference = videoTime - _LastDecodedTime; + var videoTime = RequestTime; + var timeDifference = videoTime - _LastDecodedTime; - bool dropFrame = timeDifference >= (minFrameDropCount - 1) * _FrameDuration; + var dropFrame = timeDifference >= (minFrameDropCount - 1) * _FrameDuration; - bool hasFrameDecoded = false; + var hasFrameDecoded = false; if (dropFrame) { - - var frameDropCount = (int)Math.Ceiling(timeDifference / _FrameDuration); - if (!_DropSeekEnabled || frameDropCount < seekThreshold) - { - hasFrameDecoded = _DropWithSkip(frameDropCount); - } - else - { - hasFrameDecoded = _DropWithSeek(videoTime, frameDropCount); - } + var frameDropCount = (int)Math.Ceiling(timeDifference / _FrameDuration); + if (!_DropSeekEnabled || frameDropCount < seekThreshold) + { + hasFrameDecoded = _DropWithSkip(frameDropCount); + } + else + { + hasFrameDecoded = _DropWithSeek(videoTime, frameDropCount); + } } if (!hasFrameDecoded) @@ -373,8 +423,11 @@ namespace Vocaluxe.Lib.Video.Acinerella CLog.Error("Error AcGetFrame " + _FileName); } } + if (hasFrameDecoded) + { _FrameAvailable = true; + } else { if (Loop) @@ -383,13 +436,15 @@ namespace Vocaluxe.Lib.Video.Acinerella _Skip(); } else + { _NoMoreFrames = true; + } } } private bool _DropWithSeek(float videoTime, int frameDropCount) { - bool hasFrameDecoded = false; + var hasFrameDecoded = false; try { hasFrameDecoded = CAcinerella.AcSeek(_Videodecoder, 0, (long)videoTime * 1000L); @@ -411,7 +466,7 @@ namespace Vocaluxe.Lib.Video.Acinerella private bool _DropWithSkip(int frameDropCount) { - bool hasFrameDecoded = false; + var hasFrameDecoded = false; // Add 1 dropped frame per 16 frames (Power of 2 -> Div is fast) as skipping takes time too and we don't want to skip again frameDropCount += frameDropCount / 16; try @@ -422,6 +477,7 @@ namespace Vocaluxe.Lib.Video.Acinerella { CLog.Error("Error AcSkipFrame " + _FileName); } + return hasFrameDecoded; } @@ -441,14 +497,17 @@ namespace Vocaluxe.Lib.Video.Acinerella CLog.Error(e, "Couldn't copy the frame to the managed environment."); return false; } - + if (decoder.Buffer != IntPtr.Zero) { _LastDecodedTime = (float)decoder.Timecode; result = _Framebuffer.Put(decoder.Buffer, _LastDecodedTime); } else + { result = false; + } + _FrameAvailable = false; return result; } @@ -465,7 +524,10 @@ namespace Vocaluxe.Lib.Video.Acinerella while (!_Terminated) { if (_NoMoreFrames) + { _EvNoMoreFrames.WaitOne(); + } + if (_RequestSkip) { _RequestSkip = false; @@ -474,7 +536,9 @@ namespace Vocaluxe.Lib.Video.Acinerella } if (!_FrameAvailable) + { _Decode(); + } //Bail out if we want to skip if (!_RequestSkip && _FrameAvailable) @@ -487,10 +551,14 @@ namespace Vocaluxe.Lib.Video.Acinerella lock (_BufferMutex) { if (_RequestSkip) + { continue; //Frame is invalid if we want to skip + } + _Framebuffer.SetWritten(); } } + _WaitCount = 0; Thread.Sleep(5); //Sleep for a bit to give other threads an opportunity to run } diff --git a/Vocaluxe/Lib/Video/Acinerella/CFramebuffer.cs b/Vocaluxe/Lib/Video/Acinerella/CFramebuffer.cs index 4ea6c543..44b6e1ae 100644 --- a/Vocaluxe/Lib/Video/Acinerella/CFramebuffer.cs +++ b/Vocaluxe/Lib/Video/Acinerella/CFramebuffer.cs @@ -44,22 +44,18 @@ namespace Vocaluxe.Lib.Video.Acinerella } private readonly CFrame[] _Frames; - private readonly int _Size; private int _DataSize; private int _Last; private int _First; private int _Next; private bool _Initialized; - public int Size - { - get { return _Size; } - } + public int Size { get; } // Constructs a framebuffer with max. size frames public CFramebuffer(int size) { - _Size = size; + Size = size; _Frames = new CFrame[size]; } @@ -68,15 +64,18 @@ namespace Vocaluxe.Lib.Video.Acinerella public void Init(int dataSize) { _DataSize = dataSize; - for (int i = 0; i < _Size; i++) + for (var i = 0; i < Size; i++) + { _Frames[i] = new CFrame(this, i, dataSize); + } + _Initialized = true; } private int _GetNextIndex(int current) { current++; - return (current < _Size) ? current : 0; + return current < Size ? current : 0; } public bool IsFull() @@ -93,8 +92,11 @@ namespace Vocaluxe.Lib.Video.Acinerella public bool Put(IntPtr data, float time) { if (!_Initialized || IsFull()) + { return false; - CFrame frame = _Frames[_Last]; + } + + var frame = _Frames[_Last]; Marshal.Copy(data, frame.Data, 0, _DataSize); frame.Time = time; return true; @@ -118,8 +120,11 @@ namespace Vocaluxe.Lib.Video.Acinerella public CFrame Pop() { if (_Next == _Last) + { return null; - CFrame res = _Frames[_Next]; + } + + var res = _Frames[_Next]; _Next = _GetNextIndex(_Next); return res; } @@ -127,7 +132,9 @@ namespace Vocaluxe.Lib.Video.Acinerella private void _SetRead(int index) { if ((_First <= index && (index < _Next || _Next < _First)) || (_Next < _First && index < _Next)) + { _First = _GetNextIndex(index); + } } //Only call from reader thread diff --git a/Vocaluxe/Lib/Video/CVideoDecoderFFmpeg.cs b/Vocaluxe/Lib/Video/CVideoDecoderFFmpeg.cs index 48e6954e..dc1e367d 100644 --- a/Vocaluxe/Lib/Video/CVideoDecoderFFmpeg.cs +++ b/Vocaluxe/Lib/Video/CVideoDecoderFFmpeg.cs @@ -24,7 +24,7 @@ namespace Vocaluxe.Lib.Video class CVideoDecoderFFmpeg : IVideoDecoder { private readonly Dictionary _Decoder = new Dictionary(); - private int _LastID; + private int _LastId; public bool Init() { @@ -34,8 +34,11 @@ namespace Vocaluxe.Lib.Video public void CloseAll() { - foreach (CDecoder decoder in _Decoder.Values) + foreach (var decoder in _Decoder.Values) + { decoder.Close(); + } + _Decoder.Clear(); } @@ -45,23 +48,28 @@ namespace Vocaluxe.Lib.Video if (decoder.Open(videoFileName)) { - int id = _LastID++; + var id = _LastId++; _Decoder.Add(id, decoder); return new CVideoStream(id); } + return null; } public void Close(ref CVideoStream stream) { if (stream == null) + { return; + } + CDecoder decoder; if (_TryGetDecoder(stream, out decoder)) { decoder.Close(); - _Decoder.Remove(stream.ID); + _Decoder.Remove(stream.Id); } + stream.SetClosed(); stream = null; } @@ -75,7 +83,10 @@ namespace Vocaluxe.Lib.Video { CDecoder decoder; if (_TryGetDecoder(stream, out decoder)) + { return decoder.GetFrame(ref stream.Texture, time, out stream.VideoTime); + } + stream.VideoTime = 0; return false; } @@ -84,7 +95,10 @@ namespace Vocaluxe.Lib.Video { CDecoder decoder; if (_TryGetDecoder(stream, out decoder)) + { return decoder.Length; + } + return 0f; } @@ -92,7 +106,10 @@ namespace Vocaluxe.Lib.Video { CDecoder decoder; if (_TryGetDecoder(stream, out decoder)) + { return decoder.Skip(start, gap); + } + return false; } @@ -100,32 +117,41 @@ namespace Vocaluxe.Lib.Video { CDecoder decoder; if (_TryGetDecoder(stream, out decoder)) + { decoder.Loop = loop; + } } public void Pause(CVideoStream stream) { CDecoder decoder; if (_TryGetDecoder(stream, out decoder)) + { decoder.Paused = true; + } } public void Resume(CVideoStream stream) { CDecoder decoder; if (_TryGetDecoder(stream, out decoder)) + { decoder.Paused = false; + } } public bool Finished(CVideoStream stream) { CDecoder decoder; if (_TryGetDecoder(stream, out decoder)) + { return decoder.Finished; + } + return true; } - public void Update() {} + public void Update() { } private bool _TryGetDecoder(CVideoStream stream, out CDecoder decoder) { @@ -134,7 +160,8 @@ namespace Vocaluxe.Lib.Video decoder = null; return false; } - return _Decoder.TryGetValue(stream.ID, out decoder); + + return _Decoder.TryGetValue(stream.Id, out decoder); } } } \ No newline at end of file diff --git a/Vocaluxe/Lib/Video/IVideoDecoder.cs b/Vocaluxe/Lib/Video/IVideoDecoder.cs index c4484f9e..223b2560 100644 --- a/Vocaluxe/Lib/Video/IVideoDecoder.cs +++ b/Vocaluxe/Lib/Video/IVideoDecoder.cs @@ -40,9 +40,9 @@ namespace Vocaluxe.Lib.Video CVideoStream Load(string videoFileName); /// - /// Closes the stream with the given ID + /// Closes the stream with the given Id /// - /// ID of the stream + /// Id of the stream void Close(ref CVideoStream stream); /// diff --git a/Vocaluxe/Lib/Webcam/CAForgeNet.cs b/Vocaluxe/Lib/Webcam/CAForgeNet.cs index 0d6e9918..dfcb3cec 100644 --- a/Vocaluxe/Lib/Webcam/CAForgeNet.cs +++ b/Vocaluxe/Lib/Webcam/CAForgeNet.cs @@ -16,12 +16,12 @@ #endregion using System; -using AForge.Video; -using AForge.Video.DirectShow; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; +using AForge.Video; +using AForge.Video.DirectShow; using Vocaluxe.Base; using VocaluxeLib.Draw; @@ -41,31 +41,36 @@ namespace Vocaluxe.Lib.Webcam public bool Init() { - FilterInfoCollection webcams = new FilterInfoCollection(FilterCategory.VideoInputDevice); + var webcams = new FilterInfoCollection(FilterCategory.VideoInputDevice); foreach (FilterInfo info in webcams) { var tmpdev = new VideoCaptureDevice(info.MonikerString); if (tmpdev.VideoCapabilities.Length == 0) + { continue; - var device = new SWebcamDevice - { - Name = info.Name, - MonikerString = info.MonikerString, - Capabilities = new List(tmpdev.VideoCapabilities.Length) - }; + } - foreach (VideoCapabilities capabilities in tmpdev.VideoCapabilities) + var device = new SWebcamDevice + { + Name = info.Name, + MonikerString = info.MonikerString, + Capabilities = new List(tmpdev.VideoCapabilities.Length) + }; + + foreach (var capabilities in tmpdev.VideoCapabilities) { var item = new SCapabilities - { - Framerate = capabilities.AverageFrameRate, - Height = capabilities.FrameSize.Height, - Width = capabilities.FrameSize.Width - }; + { + Framerate = capabilities.AverageFrameRate, + Height = capabilities.FrameSize.Height, + Width = capabilities.FrameSize.Width + }; device.Capabilities.Add(item); } + _Devices.Add(device); } + return true; } @@ -78,7 +83,10 @@ namespace Vocaluxe.Lib.Webcam public void DeSelect() { if (_Webcam == null) + { return; + } + _Webcam.Stop(); _Webcam.NewFrame -= _OnFrame; _IsCapturing = false; @@ -93,19 +101,22 @@ namespace Vocaluxe.Lib.Webcam private static float _GetScore(int value, int valueRequested) { if (valueRequested <= 0) + { return 1; + } + return 1.0f - (float)Math.Abs(value - valueRequested) / Math.Max(value, valueRequested); } private static VideoCapabilities _SelectWebcamConfig(VideoCapabilities[] capabilities, SWebcamConfig config) { - int configTaken = 0; + var configTaken = 0; if (config.Framerate != 0 && config.Height != 0 && config.Width != 0) { float bestMatchScore = 0; - for (int i = 0; i < capabilities.Length; i++) + for (var i = 0; i < capabilities.Length; i++) { - float score = _GetScore(capabilities[i].AverageFrameRate, config.Framerate); + var score = _GetScore(capabilities[i].AverageFrameRate, config.Framerate); score += _GetScore(capabilities[i].FrameSize.Height, config.Height); score += _GetScore(capabilities[i].FrameSize.Width, config.Width); if (score >= bestMatchScore) @@ -128,12 +139,14 @@ namespace Vocaluxe.Lib.Webcam DeSelect(); if (_Devices.Count < 1) + { return false; + } - string moniker = _Devices[0].MonikerString; + var moniker = _Devices[0].MonikerString; if (config.MonikerString != "") { - foreach (SWebcamDevice device in _Devices) + foreach (var device in _Devices) { if (device.MonikerString == config.MonikerString) { @@ -142,6 +155,7 @@ namespace Vocaluxe.Lib.Webcam } } } + _Webcam = new VideoCaptureDevice(moniker); _Webcam.VideoResolution = _SelectWebcamConfig(_Webcam.VideoCapabilities, config); @@ -157,7 +171,10 @@ namespace Vocaluxe.Lib.Webcam public void Start() { if (_Webcam == null) + { return; + } + if (_IsCapturing) { if (_Paused) @@ -208,12 +225,18 @@ namespace Vocaluxe.Lib.Webcam if (_Data != null && _Data.Length == _Width * _Height * 4 && _NewFrameAvailable) { if (frame == null) + { frame = CDraw.AddTexture(_Width, _Height, _Data); + } else + { CDraw.UpdateTexture(frame, _Width, _Height, _Data); + } + _NewFrameAvailable = false; return true; } + return false; } } @@ -225,11 +248,12 @@ namespace Vocaluxe.Lib.Webcam if (_Data != null && _Data.Length == _Width * _Height * 4) { var bmp = new Bitmap(_Width, _Height); - BitmapData bitmapdata = bmp.LockBits(new Rectangle(0, 0, _Width, _Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); + var bitmapdata = bmp.LockBits(new Rectangle(0, 0, _Width, _Height), ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); Marshal.Copy(_Data, 0, bitmapdata.Scan0, _Data.Length); bmp.UnlockBits(bitmapdata); return bmp; } + return null; } } @@ -237,19 +261,30 @@ namespace Vocaluxe.Lib.Webcam private void _OnFrame(object sender, NewFrameEventArgs e) { if (_Paused) + { return; + } + if (e.Frame.Width == 0 || e.Frame.Height == 0) + { return; + } + lock (_MutexData) { if (!IsCapturing()) + { return; + } + if (_Data == null || _Data.Length != e.Frame.Width * e.Frame.Height * 4) + { _Data = new byte[e.Frame.Width * e.Frame.Height * 4]; + } _Width = e.Frame.Width; _Height = e.Frame.Height; - BitmapData bitmapdata = e.Frame.LockBits(new Rectangle(0, 0, _Width, _Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); + var bitmapdata = e.Frame.LockBits(new Rectangle(0, 0, _Width, _Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); Marshal.Copy(bitmapdata.Scan0, _Data, 0, _Data.Length); e.Frame.UnlockBits(bitmapdata); _NewFrameAvailable = true; diff --git a/Vocaluxe/Program.cs b/Vocaluxe/Program.cs index ffbf9eb6..cfa387cb 100644 --- a/Vocaluxe/Program.cs +++ b/Vocaluxe/Program.cs @@ -39,7 +39,7 @@ namespace Vocaluxe class CLoadingException : Exception { public CLoadingException(string component) - : base("Failed to load " + component) {} + : base("Failed to load " + component) { } } static class CMainProgram @@ -77,8 +77,10 @@ namespace Vocaluxe // Close program if there is another instance running if (!_EnsureSingleInstance()) + { return; -#if !DEBUG + } +#if !DEBUG try { _Run(args); @@ -103,30 +105,35 @@ namespace Vocaluxe Directory.CreateDirectory(CSettings.DataFolder); // Delete CoverDB.sqlite if marker exists (cover size changed) - string flagPath = Path.Combine(CSettings.DataFolder, "DeleteCoverDB.flag"); - string coverDbPath = Path.Combine(CSettings.DataFolder, CSettings.FileNameCoverDB); + var flagPath = Path.Combine(CSettings.DataFolder, "DeleteCoverDB.flag"); + var coverDbPath = Path.Combine(CSettings.DataFolder, CSettings.FileNameCoverDB); if (File.Exists(flagPath)) { if (File.Exists(coverDbPath)) + { File.Delete(coverDbPath); // Delete the database + } File.Delete(flagPath); // Remove the marker so it doesn't repeat } // Init Log CLog.Init(CSettings.FolderNameLogs, - CSettings.FileNameMainLog, - CSettings.FileNameSongLog, - CSettings.FileNameCrashMarker, - CSettings.GetFullVersionText(), - CReporter.ShowReporterFunc, + CSettings.FileNameMainLog, + CSettings.FileNameSongLog, + CSettings.FileNameCrashMarker, + CSettings.GetFullVersionText(), + CReporter.ShowReporterFunc, ELogLevel.Information); if (!CProgrammHelper.CheckRequirements()) + { return; + } + CProgrammHelper.Init(); - + using (CBenchmark.Time("Init Program")) { CMain.Init(); @@ -136,7 +143,9 @@ namespace Vocaluxe using (CBenchmark.Time("Init Language")) { if (!CLanguage.Init()) + { throw new CLoadingException("Language"); + } } Application.DoEvents(); @@ -160,7 +169,9 @@ namespace Vocaluxe using (CBenchmark.Time("Init Draw")) { if (!CDraw.Init()) + { throw new CLoadingException("drawing"); + } } Application.DoEvents(); @@ -169,7 +180,9 @@ namespace Vocaluxe using (CBenchmark.Time("Init Playback")) { if (!CSound.Init()) + { throw new CLoadingException("playback"); + } } Application.DoEvents(); @@ -178,7 +191,9 @@ namespace Vocaluxe using (CBenchmark.Time("Init Record")) { if (!CRecord.Init()) + { throw new CLoadingException("record"); + } } Application.DoEvents(); @@ -187,7 +202,9 @@ namespace Vocaluxe using (CBenchmark.Time("Init Videodecoder")) { if (!CVideo.Init()) + { throw new CLoadingException("video"); + } } Application.DoEvents(); @@ -196,7 +213,9 @@ namespace Vocaluxe using (CBenchmark.Time("Init Database")) { if (!CDataBase.Init()) + { throw new CLoadingException("database"); + } } Application.DoEvents(); @@ -205,7 +224,9 @@ namespace Vocaluxe using (CBenchmark.Time("Init Webcam")) { if (!CWebcam.Init()) + { throw new CLoadingException("webcam"); + } } Application.DoEvents(); @@ -230,7 +251,9 @@ namespace Vocaluxe using (CBenchmark.Time("Init Fonts")) { if (!CFonts.Init()) + { throw new CLoadingException("fonts"); + } } Application.DoEvents(); @@ -239,9 +262,11 @@ namespace Vocaluxe using (CBenchmark.Time("Init Theme")) { if (!CThemes.Init()) + { throw new CLoadingException("theme"); + } } - + using (CBenchmark.Time("Load Theme")) { CThemes.Load(); @@ -253,7 +278,9 @@ namespace Vocaluxe using (CBenchmark.Time("Init Cover")) { if (!CCover.Init()) + { throw new CLoadingException("covertheme"); + } } Application.DoEvents(); @@ -297,7 +324,9 @@ namespace Vocaluxe using (CBenchmark.Time("Init Party Modes")) { if (!CParty.Init()) + { throw new CLoadingException("Party Modes"); + } } Application.DoEvents(); @@ -308,17 +337,23 @@ namespace Vocaluxe } catch (Exception e) { - CLog.Error(e, "Error on start up: {ExceptionMessage}", CLog.Params(e.Message), show:true); + CLog.Error(e, "Error on start up: {ExceptionMessage}", CLog.Params(e.Message), show: true); if (_SplashScreen != null) + { _SplashScreen.Close(); + } + _CloseProgram(); return; } + Application.DoEvents(); // Start Main Loop if (_SplashScreen != null) + { _SplashScreen.Close(); + } CDraw.MainLoop(); } @@ -448,7 +483,8 @@ namespace Vocaluxe { CLog.Close(); // Do this last, so we get all log entries! } - catch (Exception) {} + catch (Exception) { } + Environment.Exit(Environment.ExitCode); } @@ -465,19 +501,21 @@ namespace Vocaluxe { // a fix to handle mscorlib.resources if (args.Name.IndexOf(".resources", StringComparison.Ordinal) >= 0) + { return null; + } Assembly assembly = null; - string[] arr = args.Name.Split(new char[] {','}); + var arr = args.Name.Split(new char[] { ',' }); if (arr.Length > 0) { - string fileName = arr[0] + ".dll"; + var fileName = arr[0] + ".dll"; #if ARCH_X86 string arch = "x86"; #endif #if ARCH_X64 - string arch = "x64"; + var arch = "x64"; #endif string[] probePaths = @@ -489,9 +527,12 @@ namespace Vocaluxe Path.Combine(CSettings.ProgramFolder, fileName) }; - string path = probePaths.FirstOrDefault(File.Exists); + var path = probePaths.FirstOrDefault(File.Exists); if (string.IsNullOrEmpty(path)) + { return null; + } + try { assembly = Assembly.LoadFrom(path); @@ -508,10 +549,11 @@ namespace Vocaluxe CLog.Error("Cannot load assembly " + args.Name + " from " + path + ": " + e + "\r\nOuter Error: " + e1); } } - #if LINUX - catch(FileNotFoundException){} - #endif +#if LINUX + catch (FileNotFoundException) { } +#endif } + return assembly; } @@ -525,19 +567,22 @@ namespace Vocaluxe //TODO: put it into language file MessageBox.Show("Another Instance of Vocaluxe is already runnning!"); #if WIN - Process currentProcess = Process.GetCurrentProcess(); - Process[] processes = Process.GetProcessesByName(currentProcess.ProcessName); + var currentProcess = Process.GetCurrentProcess(); + var processes = Process.GetProcessesByName(currentProcess.ProcessName); - foreach (Process process in processes.Where(t => t.Id != currentProcess.Id)) + foreach (var process in processes.Where(t => t.Id != currentProcess.Id)) { - IntPtr wnd = process.MainWindowHandle; + var wnd = process.MainWindowHandle; if (wnd != IntPtr.Zero) + { COSFunctions.SetForegroundWindow(wnd); + } } #endif return false; } + return true; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Properties/AssemblyInfo.cs b/Vocaluxe/Properties/AssemblyInfo.cs index 186a5161..8720370a 100644 --- a/Vocaluxe/Properties/AssemblyInfo.cs +++ b/Vocaluxe/Properties/AssemblyInfo.cs @@ -42,9 +42,9 @@ using System.Runtime.InteropServices; [assembly: ComVisible(false)] -// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird +// Die folgende GUId bestimmt die Id der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("da631594-f891-4994-9869-c37e626e44f9")] // Allow internal access from the Tests project -[assembly:InternalsVisibleTo("Tests")] +[assembly: InternalsVisibleTo("Tests")] diff --git a/Vocaluxe/Reporting/Reporter.cs b/Vocaluxe/Reporting/Reporter.cs index e713df7f..917c5c29 100644 --- a/Vocaluxe/Reporting/Reporter.cs +++ b/Vocaluxe/Reporting/Reporter.cs @@ -32,8 +32,10 @@ namespace Vocaluxe.Reporting { // Init string with defaults for the case that loading localizations caused the problem private string _TitleText = "We are sorry"; - private string _MessageCrashText = "that Vocaluxe run into an error and crashed.\r\nTo help us fix the problem please send us a report.\r\nEdit the following log before submitting to remove possibly sensitive information."; - private string _MessageNoCrashText = "that you experienced an error.\r\nTo help us fix the problem please send us a report.\r\nEdit the following log before submitting to remove possibly sensitive information."; + private string _MessageCrashText = + "that Vocaluxe run into an error and crashed.\r\nTo help us fix the problem please send us a report.\r\nEdit the following log before submitting to remove possibly sensitive information."; + private string _MessageNoCrashText = + "that you experienced an error.\r\nTo help us fix the problem please send us a report.\r\nEdit the following log before submitting to remove possibly sensitive information."; private string _NoUploadText = "Don\'t upload anything (you can still copy the error message above)"; private string _GistAndIssueText = "Upload and open an issue (publicly visible + requires a github account)"; private string _GistOnlyText = "Upload and get a link to your report (publicly visible)"; @@ -47,8 +49,6 @@ namespace Vocaluxe.Reporting private string _LastErrorNa = "Not available"; private string _IssueTemplate = "Describe your issue here.\n\n### Steps to reproduce\nTell us how to reproduce this issue.\n\n### Vocaluxe version and logfile\n{0}\n{1}"; - - private int _Step = 0; private readonly bool _Crash; private readonly string _VocaluxeVersionTag; @@ -57,7 +57,6 @@ namespace Vocaluxe.Reporting private static readonly HttpClient _Client = new HttpClient(); private static readonly Regex _GetGistUrlRegex = new Regex("\"html_url\": *\"([^\"]+)\""); - public static ShowReporterDelegate ShowReporterFunc { get { return _ShowReporter; } @@ -141,7 +140,7 @@ namespace Vocaluxe.Reporting this.SubmitedTitleLabel.Text = _SubmitedMessageText; this.LastErrorTitleLabel.Text = _LastErrorTitleText; this.LastErrorBox.Text = string.IsNullOrWhiteSpace(lastError) ? _LastErrorNa : lastError; - this.LogBox.Text = log.Replace("\n","\r\n"); + this.LogBox.Text = log.Replace("\n", "\r\n"); this.LogBox.SelectionStart = 0; } @@ -184,7 +183,6 @@ namespace Vocaluxe.Reporting this.LogBox.Enabled = true; this.LastErrorBox.Enabled = false; } - } break; @@ -196,7 +194,7 @@ namespace Vocaluxe.Reporting private void NoUpload_CheckedChanged(object sender, EventArgs e) { - this.SubmitButton.Text = this.NoUploadSelect.Checked ? (_ShowContinue ? _SubmitStep2ContinueText : _SubmitStep2ExitText) : _SubmitStep0Text; + this.SubmitButton.Text = this.NoUploadSelect.Checked ? _ShowContinue ? _SubmitStep2ContinueText : _SubmitStep2ExitText : _SubmitStep0Text; } /// @@ -215,7 +213,7 @@ namespace Vocaluxe.Reporting this.SubmitButton.Text = _ShowContinue ? _SubmitStep2ContinueText : _SubmitStep2ExitText; this.SubmitButton.Enabled = true; this.SubmitedTitleLabel.Visible = true; - this.Url.Text = string.IsNullOrWhiteSpace(url)?_LogUploadErrorText:url; + this.Url.Text = string.IsNullOrWhiteSpace(url) ? _LogUploadErrorText : url; this.Url.Visible = true; this.Url.SelectAll(); this.Url.Focus(); @@ -227,7 +225,7 @@ namespace Vocaluxe.Reporting /// /// The log to upload. /// The error message displayed to the user (if available). - private async void _StartGistUpload(string log, string lastError= "not available") + private async void _StartGistUpload(string log, string lastError = "not available") { // Upload log to github gist and show the link _UploadFinished(await _UploadLogToGist(log, lastError)); @@ -241,13 +239,13 @@ namespace Vocaluxe.Reporting private async void _StartIssueUpload(string log, string lastError = "not available") { // Upload log to github gist - string gistUrl = await _UploadLogToGist(log, lastError); + var gistUrl = await _UploadLogToGist(log, lastError); // Build issue body - string template = string.Format(_IssueTemplate, _VocaluxeVersionTag, gistUrl); + var template = string.Format(_IssueTemplate, _VocaluxeVersionTag, gistUrl); // Build url for github issue template - string issueUrl = $"https://github.com/Vocaluxe/Vocaluxe/issues/new?title=Give%20me%20a%20meaningful%20title&body={ Uri.EscapeDataString(template) }"; + var issueUrl = $"https://github.com/Vocaluxe/Vocaluxe/issues/new?title=Give%20me%20a%20meaningful%20title&body={Uri.EscapeDataString(template)}"; // Show the link _UploadFinished(issueUrl); @@ -262,24 +260,24 @@ namespace Vocaluxe.Reporting /// The log that should be uploaded. /// The error message displayed to the user (if available). /// The link to the uploaded file. - private async Task _UploadLogToGist(string log, string lastError= "not available") + private async Task _UploadLogToGist(string log, string lastError = "not available") { - string json = JsonConvert.SerializeObject(new CGistCreateData() + var json = JsonConvert.SerializeObject(new CGistCreateData { - Description = $"An { (_Crash ? "crash" : "error") } log submission for { _VocaluxeVersionTag }", + Description = $"An {(_Crash ? "crash" : "error")} log submission for {_VocaluxeVersionTag}", Public = false, - Files = new Dictionary() + Files = new Dictionary { { "Vocaluxe.log", - new CGistFileData() + new CGistFileData { Content = log } }, { "LastError.txt", - new CGistFileData() + new CGistFileData { Content = lastError } @@ -288,7 +286,7 @@ namespace Vocaluxe.Reporting }); var content = new StringContent(json, Encoding.UTF8, "application/json"); - string responseString = ""; + var responseString = ""; try { var response = await _Client.PostAsync("https://api.github.com/gists", content); @@ -297,12 +295,12 @@ namespace Vocaluxe.Reporting } catch (HttpRequestException e) { - CLog.Error(e, "Couldn't upload log", show:true, propertyValues:CLog.Params(json)); + CLog.Error(e, "Couldn't upload log", show: true, propertyValues: CLog.Params(json)); } - return _GetGistUrlRegex.Match(responseString)?.Groups[1]?.Value??""; + return _GetGistUrlRegex.Match(responseString)?.Groups[1]?.Value ?? ""; } - + /// /// Helper class for gist creation. /// @@ -314,7 +312,6 @@ namespace Vocaluxe.Reporting public bool Public { get; set; } [JsonProperty("files")] public Dictionary Files { get; set; } - } /// @@ -326,4 +323,4 @@ namespace Vocaluxe.Reporting public string Content { get; set; } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CPopupScreenPlayerControl.cs b/Vocaluxe/Screens/CPopupScreenPlayerControl.cs index 0ce70b67..c99213d1 100644 --- a/Vocaluxe/Screens/CPopupScreenPlayerControl.cs +++ b/Vocaluxe/Screens/CPopupScreenPlayerControl.cs @@ -67,7 +67,9 @@ namespace Vocaluxe.Screens { CConfig.Config.Video.VideosToBackground = EOffOn.TR_CONFIG_OFF; if (!_VideoPreviewInt) + { CBackgroundMusic.VideoEnabled = false; + } } } else @@ -75,6 +77,7 @@ namespace Vocaluxe.Screens CConfig.Config.Video.VideosToBackground = EOffOn.TR_CONFIG_ON; CBackgroundMusic.VideoEnabled = true; } + CConfig.SaveConfig(); } } @@ -88,15 +91,15 @@ namespace Vocaluxe.Screens { base.Init(); - _ThemeStatics = new string[] {_StaticBG, _StaticCover}; - _ThemeTexts = new string[] {_TextCurrentSong}; - _ThemeButtons = new string[] {_ButtonPlay, _ButtonPause, _ButtonPrevious, _ButtonNext, _ButtonRepeat, _ButtonShowVideo, _ButtonSing, _ButtonToBackgroundVideo}; + _ThemeStatics = new string[] { _StaticBG, _StaticCover }; + _ThemeTexts = new string[] { _TextCurrentSong }; + _ThemeButtons = new string[] { _ButtonPlay, _ButtonPause, _ButtonPrevious, _ButtonNext, _ButtonRepeat, _ButtonShowVideo, _ButtonSing, _ButtonToBackgroundVideo }; } public override bool HandleInput(SKeyEvent keyEvent) { base.HandleInput(keyEvent); - if (keyEvent.KeyPressed && !Char.IsControl(keyEvent.Unicode)) {} + if (keyEvent.KeyPressed && !Char.IsControl(keyEvent.Unicode)) { } else { switch (keyEvent.Key) @@ -108,21 +111,45 @@ namespace Vocaluxe.Screens case Keys.Enter: if (_Buttons[_ButtonNext].Selected) + { CBackgroundMusic.Next(); + } + if (_Buttons[_ButtonPrevious].Selected) + { CBackgroundMusic.Previous(); + } + if (_Buttons[_ButtonPlay].Selected) + { CBackgroundMusic.Play(); + } + if (_Buttons[_ButtonPause].Selected) + { CBackgroundMusic.Pause(); + } + if (_Buttons[_ButtonRepeat].Selected) + { CBackgroundMusic.RepeatSong = !CBackgroundMusic.RepeatSong; + } + if (_Buttons[_ButtonShowVideo].Selected) + { _VideoPreview = !_VideoPreview; + } + if (_Buttons[_ButtonSing].Selected) - _StartSong(CBackgroundMusic.SongID); + { + _StartSong(CBackgroundMusic.SongId); + } + if (_Buttons[_ButtonToBackgroundVideo].Selected) + { _VideoBackground = !_VideoBackground; + } + break; } } @@ -136,21 +163,44 @@ namespace Vocaluxe.Screens if (mouseEvent.LB && _IsMouseOverCurSelection(mouseEvent)) { if (_Buttons[_ButtonNext].Selected) + { CBackgroundMusic.Next(); + } + if (_Buttons[_ButtonPrevious].Selected) + { CBackgroundMusic.Previous(); + } + if (_Buttons[_ButtonPlay].Selected) + { CBackgroundMusic.Play(); + } + if (_Buttons[_ButtonPause].Selected) + { CBackgroundMusic.Pause(); + } + if (_Buttons[_ButtonRepeat].Selected) + { CBackgroundMusic.RepeatSong = !CBackgroundMusic.RepeatSong; + } + if (_Buttons[_ButtonShowVideo].Selected) + { _VideoPreview = !_VideoPreview; + } + if (_Buttons[_ButtonSing].Selected) - _StartSong(CBackgroundMusic.SongID); + { + _StartSong(CBackgroundMusic.SongId); + } + if (_Buttons[_ButtonToBackgroundVideo].Selected) + { _VideoBackground = !_VideoBackground; + } } else if (mouseEvent.LB) { @@ -162,6 +212,7 @@ namespace Vocaluxe.Screens //CGraphics.HidePopup(EPopupScreens.PopupPlayerControl); return false; } + return true; } @@ -179,14 +230,19 @@ namespace Vocaluxe.Screens public override bool UpdateGame() { if (CBackgroundMusic.VideoEnabled && _VideoPreview && CBackgroundMusic.SongHasVideo) + { _Statics[_StaticCover].Texture = CBackgroundMusic.GetVideoTexture(); + } else + { _Statics[_StaticCover].Texture = CBackgroundMusic.Cover; + } + _Statics[_StaticCover].Visible = !_VideoPreviewInt || !CBackgroundMusic.SongHasVideo; _Buttons[_ButtonToBackgroundVideo].Pressed = _VideoBackground; _Buttons[_ButtonShowVideo].Pressed = _VideoPreviewInt; _Buttons[_ButtonRepeat].Pressed = CBackgroundMusic.RepeatSong; - _Buttons[_ButtonSing].Visible = CBackgroundMusic.CanSing && CParty.CurrentPartyModeID == -1; + _Buttons[_ButtonSing].Visible = CBackgroundMusic.CanSing && CParty.CurrentPartyModeId == -1; _Buttons[_ButtonPause].Visible = CBackgroundMusic.IsPlaying; _Buttons[_ButtonPlay].Visible = !CBackgroundMusic.IsPlaying; _Texts[_TextCurrentSong].Text = CBackgroundMusic.ArtistAndTitle; @@ -196,13 +252,18 @@ namespace Vocaluxe.Screens private void _StartSong(int songNr) { if (songNr < 0 || !CSongs.SongsLoaded) + { return; + } + CGame.Reset(); CGame.ClearSongs(); var gm = EGameMode.TR_GAMEMODE_NORMAL; if (CSongs.AllSongs[songNr].IsGameModeAvailable(EGameMode.TR_GAMEMODE_DUET)) + { gm = EGameMode.TR_GAMEMODE_DUET; + } CGame.AddSong(songNr, gm); diff --git a/Vocaluxe/Screens/CPopupScreenServerQR.cs b/Vocaluxe/Screens/CPopupScreenServerQR.cs index 6c198aaa..9b6aff30 100644 --- a/Vocaluxe/Screens/CPopupScreenServerQR.cs +++ b/Vocaluxe/Screens/CPopupScreenServerQR.cs @@ -16,12 +16,12 @@ #endregion using System.Windows.Forms; +using QRCoder; using Vocaluxe.Base; using Vocaluxe.Base.Server; using VocaluxeLib; -using VocaluxeLib.Menu; using VocaluxeLib.Draw; -using QRCoder; +using VocaluxeLib.Menu; namespace Vocaluxe.Screens { @@ -43,8 +43,8 @@ namespace Vocaluxe.Screens { base.Init(); - _ThemeStatics = new string[] {_StaticQRServer}; - _ThemeTexts = new string[] {_TextServerAddress, _TextServerNotRunning}; + _ThemeStatics = new string[] { _StaticQRServer }; + _ThemeTexts = new string[] { _TextServerAddress, _TextServerNotRunning }; } public override void OnShow() @@ -56,6 +56,7 @@ namespace Vocaluxe.Screens _Statics[_StaticQRServer].Texture = _QRServerAddress; _Texts[_TextServerAddress].Text = CVocaluxeServer.GetServerAddress(); } + _Texts[_TextServerAddress].Visible = CVocaluxeServer.IsServerRunning(); _Statics[_StaticQRServer].Visible = CVocaluxeServer.IsServerRunning(); _Texts[_TextServerNotRunning].Visible = !CVocaluxeServer.IsServerRunning(); @@ -68,6 +69,7 @@ namespace Vocaluxe.Screens CGraphics.HidePopup(EPopupScreens.PopupServerQR); return true; } + return false; } @@ -80,6 +82,7 @@ namespace Vocaluxe.Screens CGraphics.HidePopup(EPopupScreens.PopupServerQR); return true; } + return base.HandleInput(keyEvent); } @@ -90,10 +93,10 @@ namespace Vocaluxe.Screens private void _GenerateQRs() { - QRCodeGenerator qr = new QRCodeGenerator(); + var qr = new QRCodeGenerator(); //ServerAddress - QRCodeGenerator.QRCode qrcode = qr.CreateQrCode(CVocaluxeServer.GetServerAddress(), QRCodeGenerator.ECCLevel.H); + var qrcode = qr.CreateQrCode(CVocaluxeServer.GetServerAddress(), QRCodeGenerator.ECCLevel.H); _QRServerAddress = CDraw.AddTexture(qrcode.GetGraphic(20)); } } diff --git a/Vocaluxe/Screens/CPopupScreenVolumeControl.cs b/Vocaluxe/Screens/CPopupScreenVolumeControl.cs index 4bb77849..c2751361 100644 --- a/Vocaluxe/Screens/CPopupScreenVolumeControl.cs +++ b/Vocaluxe/Screens/CPopupScreenVolumeControl.cs @@ -42,8 +42,8 @@ namespace Vocaluxe.Screens { base.Init(); - _ThemeStatics = new string[] {_StaticBG}; - _ThemeSelectSlides = new string[] {_SelectSlideVolume}; + _ThemeStatics = new string[] { _StaticBG }; + _ThemeSelectSlides = new string[] { _SelectSlideVolume }; } public override void LoadTheme(string xmlPath) @@ -51,7 +51,7 @@ namespace Vocaluxe.Screens base.LoadTheme(xmlPath); _SelectSlides[_SelectSlideVolume].AddValues(new string[] - {"0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"}); + { "0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100" }); } public override bool HandleInput(SKeyEvent keyEvent) @@ -60,14 +60,22 @@ namespace Vocaluxe.Screens if (keyEvent.ModShift || keyEvent.Sender == ESender.WiiMote) { if (keyEvent.Key == Keys.Add || keyEvent.Key == Keys.PageUp) + { _SelectSlides[_SelectSlideVolume].Selection++; + } else if (keyEvent.Key == Keys.Subtract || keyEvent.Key == Keys.PageDown) + { _SelectSlides[_SelectSlideVolume].Selection--; + } else + { return false; + } } else + { return false; + } _SaveConfig(); return true; @@ -81,18 +89,21 @@ namespace Vocaluxe.Screens _SaveConfig(); return true; } + if (mouseEvent.Wheel > 0 && CHelper.IsInBounds(ScreenArea, mouseEvent)) { _SelectSlides[_SelectSlideVolume].Selection = _SelectSlides[_SelectSlideVolume].Selection - mouseEvent.Wheel; _SaveConfig(); return true; } + if (mouseEvent.Wheel < 0 && CHelper.IsInBounds(ScreenArea, mouseEvent)) { _SelectSlides[_SelectSlideVolume].Selection = _SelectSlides[_SelectSlideVolume].Selection - mouseEvent.Wheel; _SaveConfig(); return true; } + return !mouseEvent.RB; } @@ -110,7 +121,7 @@ namespace Vocaluxe.Screens private void _SaveConfig() { - int volume = _SelectSlides[_SelectSlideVolume].Selection * 5; + var volume = _SelectSlides[_SelectSlideVolume].Selection * 5; CConfig.SetVolumeByType(CGraphics.CurrentScreen.CurrentMusicType, volume); CConfig.SaveConfig(); CSound.SetGlobalVolume(volume); @@ -118,7 +129,7 @@ namespace Vocaluxe.Screens private void _UpdateSlides() { - int volume = CConfig.GetVolumeByType(CGraphics.CurrentScreen.CurrentMusicType); + var volume = CConfig.GetVolumeByType(CGraphics.CurrentScreen.CurrentMusicType); _SelectSlides[_SelectSlideVolume].Selection = volume / 5; } } diff --git a/Vocaluxe/Screens/CScreenCredits.cs b/Vocaluxe/Screens/CScreenCredits.cs index 7e3601a0..ec6e7c15 100644 --- a/Vocaluxe/Screens/CScreenCredits.cs +++ b/Vocaluxe/Screens/CScreenCredits.cs @@ -18,11 +18,9 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Windows.Forms; -using System.Drawing; using System.IO; +using System.Windows.Forms; using Vocaluxe.Base; -using Vocaluxe.Base.Fonts; using VocaluxeLib; using VocaluxeLib.Draw; using VocaluxeLib.Log; @@ -69,8 +67,8 @@ namespace Vocaluxe.Screens public override void LoadTheme(string xmlPath) { // Vocaluxe-Logo - bool ressourceOK = true; - string path = Path.Combine(CSettings.ProgramFolder, CSettings.FolderNameGraphics, CSettings.FileNameCreditsLogo); + var ressourceOK = true; + var path = Path.Combine(CSettings.ProgramFolder, CSettings.FolderNameGraphics, CSettings.FileNameCreditsLogo); if (File.Exists(path)) { @@ -81,6 +79,7 @@ namespace Vocaluxe.Screens { ressourceOK = false; } + if (!ressourceOK) { CLog.Fatal("Could not load all resources!"); @@ -89,7 +88,7 @@ namespace Vocaluxe.Screens } // Position Y for the first scrolling element - float scrollY = CSettings.RenderH - 1f; + var scrollY = CSettings.RenderH - 1f; // Create logo if (_TexLogo != null) @@ -105,16 +104,16 @@ namespace Vocaluxe.Screens } // Helper variables for font sizes - int bigHeadlineSize = 45; - int headlineSize = 40; - int boldSize = 35; - int textSize = 30; - float paragraphSpacing = 30f; // Space between paragraphs + var bigHeadlineSize = 45; + var headlineSize = 40; + var boldSize = 35; + var textSize = 30; + var paragraphSpacing = 30f; // Space between paragraphs // Helper method to add text with formatting void AddText(string content, int size, EStyle style, float yOffset, EAlignment alignment = EAlignment.Center) { - CText text = GetNewText(new CText(CSettings.RenderW / 2, scrollY + yOffset, -2f, size, -1, alignment, style, "Outline", new SColorF(1, 1, 1, 1), content)); + var text = GetNewText(new CText(CSettings.RenderW / 2, scrollY + yOffset, -2f, size, -1, alignment, style, "Outline", new SColorF(1, 1, 1, 1), content)); text.Visible = false; _ScrollingElements.Add(text); _AddText(text); @@ -239,35 +238,39 @@ namespace Vocaluxe.Screens public override bool HandleMouse(SMouseEvent mouseEvent) { if (mouseEvent.LB || mouseEvent.RB) + { _LeaveScreen(); + } + return true; } public override bool UpdateGame() { if (_BackgroundVideo != null) - { - float deltaTime = (_ScrollTimer.ElapsedMilliseconds - _previousVideoElapsedMilliseconds) / 1000f; - _previousVideoElapsedMilliseconds = _ScrollTimer.ElapsedMilliseconds; + { + var deltaTime = (_ScrollTimer.ElapsedMilliseconds - _previousVideoElapsedMilliseconds) / 1000f; + _previousVideoElapsedMilliseconds = _ScrollTimer.ElapsedMilliseconds; - _BackgroundVideoTime += deltaTime; + _BackgroundVideoTime += deltaTime; - float videoLength = CVideo.GetLength(_BackgroundVideo); + var videoLength = CVideo.GetLength(_BackgroundVideo); - // Keep time within video length to avoid seeking backward - if (_BackgroundVideoTime >= videoLength) - { - _BackgroundVideoTime -= videoLength; - } + // Keep time within video length to avoid seeking backward + if (_BackgroundVideoTime >= videoLength) + { + _BackgroundVideoTime -= videoLength; + } - CVideo.GetFrame(_BackgroundVideo, _BackgroundVideoTime); - } + CVideo.GetFrame(_BackgroundVideo, _BackgroundVideoTime); + } - if (!_Animation() && CGraphics.NextScreen != CGraphics.GetScreen(EScreen.Main)) - _LeaveScreen(); - - return true; + if (!_Animation() && CGraphics.NextScreen != CGraphics.GetScreen(EScreen.Main)) + { + _LeaveScreen(); + } + return true; } public override void OnShow() @@ -275,7 +278,7 @@ namespace Vocaluxe.Screens base.OnShow(); // Reset positions - foreach (dynamic element in _ScrollingElements) + foreach (var element in _ScrollingElements) { if (_ElementStartYPositions.TryGetValue(element, out float startY)) { @@ -292,7 +295,7 @@ namespace Vocaluxe.Screens _previousVideoElapsedMilliseconds = 0f; - string path = Path.Combine(CSettings.ProgramFolder, CSettings.FolderNameGraphics, CSettings.FileNameCreditsVideo); + var path = Path.Combine(CSettings.ProgramFolder, CSettings.FolderNameGraphics, CSettings.FileNameCreditsVideo); if (File.Exists(path)) { // Load the video if not already loaded @@ -301,14 +304,13 @@ namespace Vocaluxe.Screens _BackgroundVideo = CVideo.Load(path); CVideo.SetLoop(_BackgroundVideo, true); // Set the video to loop } - } else { CLog.Error("Background video not found: " + path); } - foreach (dynamic element in _ScrollingElements) + foreach (var element in _ScrollingElements) { element.Visible = true; } @@ -319,7 +321,7 @@ namespace Vocaluxe.Screens _previousAnimationElapsedMilliseconds = 0; _BackgroundVideoTime = 0f; - foreach (dynamic element in _ScrollingElements) + foreach (var element in _ScrollingElements) { element.Visible = true; } @@ -329,9 +331,9 @@ namespace Vocaluxe.Screens { if (_Active && _BackgroundVideo != null && _BackgroundVideo.Texture != null) { - CTextureRef background = _BackgroundVideo.Texture; - SRectF bounds = CSettings.RenderRect; - SRectF rect = CHelper.FitInBounds(bounds, background.OrigAspect, EAspect.Crop); + var background = _BackgroundVideo.Texture; + var bounds = CSettings.RenderRect; + var rect = CHelper.FitInBounds(bounds, background.OrigAspect, EAspect.Crop); CDraw.DrawTexture(background, rect, background.Color, bounds); } @@ -352,14 +354,16 @@ namespace Vocaluxe.Screens private bool _Animation() { if (!_ScrollTimer.IsRunning) + { return false; + } - float deltaTime = (_ScrollTimer.ElapsedMilliseconds - _previousAnimationElapsedMilliseconds) / 1000f; // Convert milliseconds to seconds + var deltaTime = (_ScrollTimer.ElapsedMilliseconds - _previousAnimationElapsedMilliseconds) / 1000f; // Convert milliseconds to seconds _previousAnimationElapsedMilliseconds = _ScrollTimer.ElapsedMilliseconds; - float scrollSpeed = 60f; + var scrollSpeed = 60f; - foreach (dynamic element in _ScrollingElements) + foreach (var element in _ScrollingElements) { if (element is CText text) { @@ -372,7 +376,7 @@ namespace Vocaluxe.Screens } // Check if the last element has scrolled off the top - dynamic lastElement = _ScrollingElements[_ScrollingElements.Count - 1]; + var lastElement = _ScrollingElements[_ScrollingElements.Count - 1]; float elementBottomY = 0; if (lastElement is CText lastText) { @@ -392,4 +396,4 @@ namespace Vocaluxe.Screens return true; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenHighscore.cs b/Vocaluxe/Screens/CScreenHighscore.cs index fcff3acc..4c274303 100644 --- a/Vocaluxe/Screens/CScreenHighscore.cs +++ b/Vocaluxe/Screens/CScreenHighscore.cs @@ -21,10 +21,8 @@ using System.Linq; using System.Windows.Forms; using Vocaluxe.Base; using VocaluxeLib; -using VocaluxeLib.Game; using VocaluxeLib.Menu; using VocaluxeLib.Songs; -using Vocaluxe.Lib.Sound; namespace Vocaluxe.Screens { @@ -46,7 +44,7 @@ namespace Vocaluxe.Screens private string[] _ParticleEffectNew; private List[] _Scores; - private List _NewEntryIDs; + private List _NewEntryIds; private int _Round; private int _Pos; private bool _IsDuet; @@ -59,10 +57,10 @@ namespace Vocaluxe.Screens private int _HighscoreStream = -1; private bool _HasPlayedHighscoreSound = false; - + private static int PlaySound(ESounds sound, int volume) { - int streamId = CSound.PlaySound(sound, false); + var streamId = CSound.PlaySound(sound, false); CSound.SetStreamVolume(streamId, volume); return streamId; @@ -72,50 +70,52 @@ namespace Vocaluxe.Screens { base.Init(); - var texts = new List {_TextSongName, _TextSongMode}; + var texts = new List { _TextSongName, _TextSongMode }; _TextNumber = new string[_NumEntrys]; - for (int i = 0; i < _NumEntrys; i++) + for (var i = 0; i < _NumEntrys; i++) { _TextNumber[i] = "TextNumber" + (i + 1); texts.Add(_TextNumber[i]); } _TextName = new string[_NumEntrys]; - for (int i = 0; i < _NumEntrys; i++) + for (var i = 0; i < _NumEntrys; i++) { _TextName[i] = "TextName" + (i + 1); texts.Add(_TextName[i]); } _TextScore = new string[_NumEntrys]; - for (int i = 0; i < _NumEntrys; i++) + for (var i = 0; i < _NumEntrys; i++) { _TextScore[i] = "TextScore" + (i + 1); texts.Add(_TextScore[i]); } _TextDate = new string[_NumEntrys]; - for (int i = 0; i < _NumEntrys; i++) + for (var i = 0; i < _NumEntrys; i++) { _TextDate[i] = "TextDate" + (i + 1); texts.Add(_TextDate[i]); } _ParticleEffectNew = new string[_NumEntrys]; - for (int i = 0; i < _NumEntrys; i++) + for (var i = 0; i < _NumEntrys; i++) + { _ParticleEffectNew[i] = "ParticleEffectNew" + (i + 1); + } _ThemeStatics = new string[] { "StaticTop1Bar", "StaticTop2Bar", "StaticTop3Bar" }; _ThemeTexts = texts.ToArray(); _ThemeParticleEffects = _ParticleEffectNew; - _NewEntryIDs = new List(); + _NewEntryIds = new List(); } public override bool HandleInput(SKeyEvent keyEvent) { - if (keyEvent.KeyPressed && !Char.IsControl(keyEvent.Unicode)) {} + if (keyEvent.KeyPressed && !Char.IsControl(keyEvent.Unicode)) { } else { switch (keyEvent.Key) @@ -128,12 +128,18 @@ namespace Vocaluxe.Screens case Keys.Down: if (!_FromScreenSong) + { _ChangePos(1); + } + break; case Keys.Up: if (!_FromScreenSong) + { _ChangePos(-1); + } + break; case Keys.Left: @@ -151,17 +157,21 @@ namespace Vocaluxe.Screens public override bool HandleMouse(SMouseEvent mouseEvent) { - if (mouseEvent.LB && _IsMouseOverCurSelection(mouseEvent)) {} + if (mouseEvent.LB && _IsMouseOverCurSelection(mouseEvent)) { } if (mouseEvent.LB) + { _LeaveScreen(); + } if (mouseEvent.RB) + { _LeaveScreen(); + } if (mouseEvent.MB) { - int lastRound = _Round; + var lastRound = _Round; _ChangeRound(1); if (lastRound == _Round) { @@ -176,12 +186,12 @@ namespace Vocaluxe.Screens public override bool UpdateGame() { - int numScores = _Scores[_Round].Count; - _Statics["StaticTop1Bar"].Visible = (numScores >= 1); - _Statics["StaticTop2Bar"].Visible = (numScores >= 2); - _Statics["StaticTop3Bar"].Visible = (numScores >= 3); - - for (int p = 0; p < _NumEntrys; p++) + var numScores = _Scores[_Round].Count; + _Statics["StaticTop1Bar"].Visible = numScores >= 1; + _Statics["StaticTop2Bar"].Visible = numScores >= 2; + _Statics["StaticTop3Bar"].Visible = numScores >= 3; + + for (var p = 0; p < _NumEntrys; p++) { if (_Pos + p < _Scores[_Round].Count) { @@ -192,18 +202,22 @@ namespace Vocaluxe.Screens _Texts[_TextNumber[p]].Text = (_Pos + p + 1).ToString(); - string name = _Scores[_Round][_Pos + p].Name; + var name = _Scores[_Round][_Pos + p].Name; name += " [" + CLanguage.Translate(Enum.GetName(typeof(EGameDifficulty), _Scores[_Round][_Pos + p].Difficulty)) + "]"; if (_IsDuet) { - int voiceNr = _Scores[_Round][_Pos + p].VoiceNr; + var voiceNr = _Scores[_Round][_Pos + p].VoiceNr; string voiceName = null; CSong song; if (_FromScreenSong) - song = CSongs.GetSong(CScreenSong.getSelectedSongID()); + { + song = CSongs.GetSong(CScreenSong.getSelectedSongId()); + } else + { song = CGame.GetSong(_Round); + } if (song != null && song.Notes != null && song.Notes.VoiceNames != null) { @@ -213,28 +227,33 @@ namespace Vocaluxe.Screens } catch { - voiceName = null; // Ungültiger Index + voiceName = null; // Ungültiger Index } } if (!string.IsNullOrWhiteSpace(voiceName)) + { name += " (" + voiceName + ")"; + } else + { name += " (P" + (voiceNr + 1) + ")"; - } + } + } + _Texts[_TextName[p]].Text = name; _Texts[_TextScore[p]].Text = _Scores[_Round][_Pos + p].Score.ToString("D"); _Texts[_TextDate[p]].Text = _Scores[_Round][_Pos + p].Date; - _ParticleEffects[_ParticleEffectNew[p]].Visible = _IsNewEntry(_Scores[_Round][_Pos + p].ID); + _ParticleEffects[_ParticleEffectNew[p]].Visible = _IsNewEntry(_Scores[_Round][_Pos + p].Id); if (_ParticleEffects[_ParticleEffectNew[p]].Visible && !_HasPlayedHighscoreSound) { - _HighscoreStream = CScreenHighscore.PlaySound(ESounds.Highscore, CConfig.SoundEffectVolume); - _HasPlayedHighscoreSound = true; + _HighscoreStream = CScreenHighscore.PlaySound(ESounds.Highscore, CConfig.SoundEffectVolume); + _HasPlayedHighscoreSound = true; } - } + } else { _Texts[_TextNumber[p]].Visible = false; @@ -244,6 +263,7 @@ namespace Vocaluxe.Screens _ParticleEffects[_ParticleEffectNew[p]].Visible = false; } } + return true; } @@ -253,7 +273,7 @@ namespace Vocaluxe.Screens _HasPlayedHighscoreSound = false; _Round = 0; _Pos = 0; - _NewEntryIDs.Clear(); + _NewEntryIds.Clear(); _AddScoresToDB(); _LoadScores(); _UpdateRound(); @@ -263,27 +283,33 @@ namespace Vocaluxe.Screens private bool _IsNewEntry(int id) { - return _NewEntryIDs.Any(t => t == id); + return _NewEntryIds.Any(t => t == id); } private void _AddScoresToDB() { - CPoints points = CGame.GetPoints(); + var points = CGame.GetPoints(); if (points == null) + { return; + } // No points in Karaoke Mode if (CScreenSong.GetAudioMode() == EAudioMode.TR_AUDIOMODE_KARAOKE) - return; - - for (int round = 0; round < points.NumRounds; round++) { - SPlayer[] players = points.GetPlayer(round, CGame.NumPlayers); + return; + } - for (int p = 0; p < players.Length; p++) + for (var round = 0; round < points.NumRounds; round++) + { + var players = points.GetPlayer(round, CGame.NumPlayers); + + for (var p = 0; p < players.Length; p++) { - if (players[p].Points > CSettings.MinScoreForDB && players[p].SongFinished && !CProfiles.IsGuestProfile(players[p].ProfileID)) - _NewEntryIDs.Add(CDataBase.AddScore(players[p])); + if (players[p].Points > CSettings.MinScoreForDB && players[p].SongFinished && !CProfiles.IsGuestProfile(players[p].ProfileId)) + { + _NewEntryIds.Add(CDataBase.AddScore(players[p])); + } } } } @@ -291,20 +317,20 @@ namespace Vocaluxe.Screens private void _LoadScores() { _Pos = 0; - int rounds = CGame.NumRounds; + var rounds = CGame.NumRounds; if (rounds == 0) { _FromScreenSong = true; _Round = (int)EGameMode.TR_GAMEMODE_NORMAL; _Scores = new List[4]; - int songID = CScreenSong.getSelectedSongID(); - EHighscoreStyle style = CBase.Config.GetHighscoreStyle(); - bool foundHighscoreEntries = false; + var songId = CScreenSong.getSelectedSongId(); + var style = CBase.Config.GetHighscoreStyle(); + var foundHighscoreEntries = false; - for (int gameModeNum = 0; gameModeNum < 4; gameModeNum++) + for (var gameModeNum = 0; gameModeNum < 4; gameModeNum++) { - _Scores[gameModeNum] = CDataBase.LoadScore(songID, (EGameMode)gameModeNum, style); + _Scores[gameModeNum] = CDataBase.LoadScore(songId, (EGameMode)gameModeNum, style); if (!foundHighscoreEntries && _Scores[gameModeNum].Count > 0) { _Round = gameModeNum; @@ -316,12 +342,12 @@ namespace Vocaluxe.Screens { _FromScreenSong = false; _Scores = new List[rounds]; - for (int round = 0; round < rounds; round++) + for (var round = 0; round < rounds; round++) { - int songID = CGame.GetSong(round).ID; - EGameMode gameMode = CGame.GetGameMode(round); - EHighscoreStyle style = CBase.Config.GetHighscoreStyle(); - _Scores[round] = CDataBase.LoadScore(songID, gameMode, style); + var songId = CGame.GetSong(round).Id; + var gameMode = CGame.GetGameMode(round); + var style = CBase.Config.GetHighscoreStyle(); + _Scores[round] = CDataBase.LoadScore(songId, gameMode, style); } } } @@ -329,22 +355,30 @@ namespace Vocaluxe.Screens private void _UpdateRound() { _IsDuet = false; - CPoints points = CGame.GetPoints(); - + var points = CGame.GetPoints(); + CSong song; if (_FromScreenSong) - song = CSongs.GetSong(CScreenSong.getSelectedSongID()); + { + song = CSongs.GetSong(CScreenSong.getSelectedSongId()); + } else + { song = CGame.GetSong(_Round); + } if (song == null) + { return; + } _Texts[_TextSongName].Text = song.Artist + " - " + song.Title; if (points != null && !_FromScreenSong && points.NumRounds > 1) + { _Texts[_TextSongName].Text += " (" + (_Round + 1) + "/" + points.NumRounds + ")"; + } - switch ((_FromScreenSong ? (EGameMode)_Round : CGame.GetGameMode(_Round))) + switch (_FromScreenSong ? (EGameMode)_Round : CGame.GetGameMode(_Round)) { case EGameMode.TR_GAMEMODE_NORMAL: _Texts[_TextSongMode].Text = "TR_GAMEMODE_NORMAL"; @@ -374,7 +408,9 @@ namespace Vocaluxe.Screens private void _ChangePos(int num) { if (_Scores[_Round].Count == 0 || _Scores[_Round].Count <= _NumEntrys) + { _Pos = 0; + } else { _Pos += num; @@ -387,13 +423,17 @@ namespace Vocaluxe.Screens if (_FromScreenSong) { if (_Round == (int)EGameMode.TR_GAMEMODE_SHORTSONG) + { _Round = (int)EGameMode.TR_GAMEMODE_NORMAL; + } else + { ++_Round; + } } else { - CPoints points = CGame.GetPoints(); + var points = CGame.GetPoints(); _Round += num; _Round = _Round.Clamp(0, points.NumRounds - 1); } @@ -402,14 +442,14 @@ namespace Vocaluxe.Screens } private void _LeaveScreen() - { + { if (_HighscoreStream != -1) { - CSound.Close(_HighscoreStream); + CSound.Close(_HighscoreStream); _HighscoreStream = -1; } - + CParty.LeavingHighscore(); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenLoad.cs b/Vocaluxe/Screens/CScreenLoad.cs index e2670bd2..9380b197 100644 --- a/Vocaluxe/Screens/CScreenLoad.cs +++ b/Vocaluxe/Screens/CScreenLoad.cs @@ -36,7 +36,7 @@ namespace Vocaluxe.Screens private const string _TextStatus = "TextStatus"; private const string _TextProgramName = "TextProgramName"; - private readonly string[] _IntroVideo = new string[] {"IntroIn", "IntroMid", "IntroOut"}; + private readonly string[] _IntroVideo = new string[] { "IntroIn", "IntroMid", "IntroOut" }; private Thread _SongLoaderThread; private bool _SkipIntro; @@ -50,17 +50,19 @@ namespace Vocaluxe.Screens { base.Init(); - _ThemeTexts = new string[] {_TextStatus, _TextProgramName}; + _ThemeTexts = new string[] { _TextStatus, _TextProgramName }; _Intros = new CVideoPlayer[_IntroVideo.Length]; - for (int i = 0; i < _Intros.Length; i++) + for (var i = 0; i < _Intros.Length; i++) + { _Intros[i] = new CVideoPlayer(); + } } public override bool HandleInput(SKeyEvent keyEvent) { base.HandleInput(keyEvent); - if (keyEvent.KeyPressed) {} + if (keyEvent.KeyPressed) { } else { switch (keyEvent.Key) @@ -73,6 +75,7 @@ namespace Vocaluxe.Screens break; } } + return true; } @@ -81,7 +84,9 @@ namespace Vocaluxe.Screens base.HandleMouse(mouseEvent); if (mouseEvent.LB || mouseEvent.RB) + { _SkipIntro = true; + } return true; } @@ -111,8 +116,11 @@ namespace Vocaluxe.Screens if (CConfig.Config.Video.VideoBackgrounds == EOffOn.TR_CONFIG_ON) { - for (int i = 0; i < _Intros.Length; i++) + for (var i = 0; i < _Intros.Length; i++) + { _Intros[i].Load(_IntroVideo[i]); + } + _Texts[_TextProgramName].Visible = false; } } @@ -123,13 +131,15 @@ namespace Vocaluxe.Screens if (CConfig.Config.Video.VideoBackgrounds == EOffOn.TR_CONFIG_ON) { - foreach (CVideoPlayer videoPlayer in _Intros) + foreach (var videoPlayer in _Intros) + { videoPlayer.PreLoad(); + } } - + _TimerLoadSongsFull = CBenchmark.Time("Loaded Songs Full"); - - _SongLoaderThread = new Thread(CSongs.LoadSongs) {Name = "SongLoader", IsBackground = true}; + + _SongLoaderThread = new Thread(CSongs.LoadSongs) { Name = "SongLoader", IsBackground = true }; _SongLoaderThread.Start(); CBackgroundMusic.OwnSongsAvailable = false; @@ -140,7 +150,7 @@ namespace Vocaluxe.Screens { _CheckStartIntroVideos(); - bool next = CConfig.Config.Theme.CoverLoading != ECoverLoading.TR_CONFIG_COVERLOADING_ATSTART || CSongs.CoverLoaded; + var next = CConfig.Config.Theme.CoverLoading != ECoverLoading.TR_CONFIG_COVERLOADING_ATSTART || CSongs.CoverLoaded; if ((_IntroOutPlayed || _SkipIntro) && next && CSettings.ProgramState == EProgramState.Start && CSongs.SongsLoaded) { @@ -158,7 +168,9 @@ namespace Vocaluxe.Screens CBackgroundMusic.OwnSongsAvailable = true; if (CConfig.Config.Video.VideoBackgrounds == EOffOn.TR_CONFIG_ON || CConfig.Config.Video.VideosToBackground == EOffOn.TR_CONFIG_ON) + { CBackgroundMusic.VideoEnabled = true; + } CBackgroundMusic.Play(); } @@ -169,7 +181,9 @@ namespace Vocaluxe.Screens public override void Draw() { if (_CurrentIntroVideo >= 0 && _CurrentIntroVideo < _Intros.Length) + { _Intros[_CurrentIntroVideo].Draw(); + } base.Draw(); } @@ -178,8 +192,10 @@ namespace Vocaluxe.Screens { base.OnClose(); - foreach (CVideoPlayer videoPlayer in _Intros) + foreach (var videoPlayer in _Intros) + { videoPlayer.Close(); + } // Stop the song full load timer _TimerLoadSongsFull.Dispose(); @@ -194,7 +210,9 @@ namespace Vocaluxe.Screens private void _CheckStartIntroVideos() { if (_IntroOutPlayed) + { return; + } if (CConfig.Config.Video.VideoBackgrounds == EOffOn.TR_CONFIG_OFF) { @@ -222,7 +240,9 @@ namespace Vocaluxe.Screens _Intros[2].Start(); } else if (_CurrentIntroVideo == 2 && _Intros[2].IsFinished) + { _IntroOutPlayed = true; + } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenMain.cs b/Vocaluxe/Screens/CScreenMain.cs index 1461eabd..9a16e92d 100644 --- a/Vocaluxe/Screens/CScreenMain.cs +++ b/Vocaluxe/Screens/CScreenMain.cs @@ -19,7 +19,6 @@ using System.Windows.Forms; using Vocaluxe.Base; using VocaluxeLib; using VocaluxeLib.Menu; -using Vocaluxe.Lib.Sound; namespace Vocaluxe.Screens { @@ -42,10 +41,10 @@ namespace Vocaluxe.Screens private int _WarningStream = -1; private bool _HasPlayedWarningSound = false; - + private static int PlaySound(ESounds sound, int volume) { - int streamId = CSound.PlaySound(sound, false); + var streamId = CSound.PlaySound(sound, false); CSound.SetStreamVolume(streamId, volume); return streamId; @@ -56,9 +55,9 @@ namespace Vocaluxe.Screens { base.Init(); - _ThemeStatics = new string[] {"StaticMenuBar", _StaticWarningProfiles}; - _ThemeButtons = new string[] {_ButtonSing, _ButtonParty, _ButtonOptions, _ButtonProfiles, _ButtonExit}; - _ThemeTexts = new string[] {_TextRelease, _TextWarningProfiles}; + _ThemeStatics = new string[] { "StaticMenuBar", _StaticWarningProfiles }; + _ThemeButtons = new string[] { _ButtonSing, _ButtonParty, _ButtonOptions, _ButtonProfiles, _ButtonExit }; + _ThemeTexts = new string[] { _TextRelease, _TextWarningProfiles }; } public override void LoadTheme(string xmlPath) @@ -76,7 +75,7 @@ namespace Vocaluxe.Screens { base.HandleInput(keyEvent); - if (keyEvent.KeyPressed) {} + if (keyEvent.KeyPressed) { } else { switch (keyEvent.Key) @@ -88,7 +87,10 @@ namespace Vocaluxe.Screens case Keys.S: if (CProfiles.NumProfiles > 0) + { CGraphics.FadeTo(EScreen.Song); + } + _LeaveScreen(); break; @@ -129,7 +131,9 @@ namespace Vocaluxe.Screens } if (_Buttons[_ButtonExit].Selected) + { return false; + } break; @@ -138,6 +142,7 @@ namespace Vocaluxe.Screens break; } } + return true; } @@ -173,7 +178,9 @@ namespace Vocaluxe.Screens } if (_Buttons[_ButtonExit].Selected) + { return false; + } } return true; @@ -181,7 +188,7 @@ namespace Vocaluxe.Screens public override bool UpdateGame() { - bool profileOK = CProfiles.NumProfiles > 0; + var profileOK = CProfiles.NumProfiles > 0; _Statics[_StaticWarningProfiles].Visible = !profileOK; _Texts[_TextWarningProfiles].Visible = !profileOK; _Buttons[_ButtonSing].Selectable = profileOK; @@ -189,19 +196,20 @@ namespace Vocaluxe.Screens if (_Texts[_TextWarningProfiles].Visible && !_HasPlayedWarningSound) { - _WarningStream = CScreenMain.PlaySound(ESounds.Warning, CConfig.SoundEffectVolume); - _HasPlayedWarningSound = true; + _WarningStream = CScreenMain.PlaySound(ESounds.Warning, CConfig.SoundEffectVolume); + _HasPlayedWarningSound = true; } + return true; } - + private void _LeaveScreen() - { + { if (_WarningStream != -1) { - CSound.Close(_WarningStream); + CSound.Close(_WarningStream); _WarningStream = -1; } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenNames.cs b/Vocaluxe/Screens/CScreenNames.cs index 34746d04..b98db299 100644 --- a/Vocaluxe/Screens/CScreenNames.cs +++ b/Vocaluxe/Screens/CScreenNames.cs @@ -22,9 +22,7 @@ using Vocaluxe.Base; using VocaluxeLib; using VocaluxeLib.Draw; using VocaluxeLib.Menu; -using VocaluxeLib.Songs; using VocaluxeLib.Profile; -using Vocaluxe.Lib.Sound; namespace Vocaluxe.Screens { @@ -48,21 +46,21 @@ namespace Vocaluxe.Screens private const string _StaticWarningMics = "StaticWarningMics"; private const string _TextWarningProfiles = "TextWarningProfiles"; private const string _StaticWarningProfiles = "StaticWarningProfiles"; - private readonly string[] _StaticPlayer = new string[] {"StaticPlayer1", "StaticPlayer2", "StaticPlayer3", "StaticPlayer4", "StaticPlayer5", "StaticPlayer6"}; + private readonly string[] _StaticPlayer = new string[] { "StaticPlayer1", "StaticPlayer2", "StaticPlayer3", "StaticPlayer4", "StaticPlayer5", "StaticPlayer6" }; private readonly string[] _StaticPlayerAvatar = new string[] - {"StaticPlayerAvatar1", "StaticPlayerAvatar2", "StaticPlayerAvatar3", "StaticPlayerAvatar4", "StaticPlayerAvatar5", "StaticPlayerAvatar6"}; - private readonly string[] _TextPlayer = new string[] {"TextPlayer1", "TextPlayer2", "TextPlayer3", "TextPlayer4", "TextPlayer5", "TextPlayer6"}; + { "StaticPlayerAvatar1", "StaticPlayerAvatar2", "StaticPlayerAvatar3", "StaticPlayerAvatar4", "StaticPlayerAvatar5", "StaticPlayerAvatar6" }; + private readonly string[] _TextPlayer = new string[] { "TextPlayer1", "TextPlayer2", "TextPlayer3", "TextPlayer4", "TextPlayer5", "TextPlayer6" }; private readonly string[] _EqualizerPlayer = new string[] - {"EqualizerPlayer1", "EqualizerPlayer2", "EqualizerPlayer3", "EqualizerPlayer4", "EqualizerPlayer5", "EqualizerPlayer6"}; + { "EqualizerPlayer1", "EqualizerPlayer2", "EqualizerPlayer3", "EqualizerPlayer4", "EqualizerPlayer5", "EqualizerPlayer6" }; private readonly string[] _SelectSlideDuetPlayer = new string[] - {"SelectSlideDuetPlayer1", "SelectSlideDuetPlayer2", "SelectSlideDuetPlayer3", "SelectSlideDuetPlayer4", "SelectSlideDuetPlayer5", "SelectSlideDuetPlayer6"}; + { "SelectSlideDuetPlayer1", "SelectSlideDuetPlayer2", "SelectSlideDuetPlayer3", "SelectSlideDuetPlayer4", "SelectSlideDuetPlayer5", "SelectSlideDuetPlayer6" }; private readonly CTextureRef[] _OriginalPlayerAvatarTextures = new CTextureRef[CSettings.MaxNumPlayer]; private bool _SelectingKeyboardActive; private bool _SelectingFast; private int _SelectingSwitchNr = -1; private int _SelectingFastPlayerNr; - private Guid _SelectedProfileID = Guid.Empty; + private Guid _SelectedProfileId = Guid.Empty; private bool _AvatarsChanged; private bool _ProfilesChanged; @@ -73,10 +71,10 @@ namespace Vocaluxe.Screens private int _WarningStream = -1; private bool _HasPlayedWarningSound = false; - + private static int PlaySound(ESounds sound, int volume) { - int streamId = CSound.PlaySound(sound, false); + var streamId = CSound.PlaySound(sound, false); CSound.SetStreamVolume(streamId, volume); return streamId; @@ -94,7 +92,7 @@ namespace Vocaluxe.Screens statics.Add(_StaticWarningProfiles); _ThemeStatics = statics.ToArray(); - var texts = new List {_SelectSlidePlayerNumber}; + var texts = new List { _SelectSlidePlayerNumber }; texts.AddRange(_SelectSlideDuetPlayer); _ThemeSelectSlides = texts.ToArray(); @@ -129,11 +127,12 @@ namespace Vocaluxe.Screens { base.LoadTheme(xmlPath); - for (int i = 0; i < CSettings.MaxNumPlayer; i++) + for (var i = 0; i < CSettings.MaxNumPlayer; i++) { _OriginalPlayerAvatarTextures[i] = _Statics[_StaticPlayerAvatar[i]].Texture; _Statics[_StaticPlayerAvatar[i]].Aspect = EAspect.Crop; } + _AddStatic(_ChooseAvatarStatic); } @@ -149,6 +148,7 @@ namespace Vocaluxe.Screens //Update Tiles-List _NameSelections[_NameSelection].UpdateList(); } + break; case Keys.Subtract: @@ -159,6 +159,7 @@ namespace Vocaluxe.Screens //Update Tiles-List _NameSelections[_NameSelection].UpdateList(); } + break; case Keys.P: @@ -171,33 +172,43 @@ namespace Vocaluxe.Screens else { if (_SelectingFastPlayerNr + 1 <= CGame.NumPlayers) + { _SelectingFastPlayerNr++; + } else + { _SelectingFastPlayerNr = 1; + } + _NameSelections[_NameSelection].FastSelection(true, _SelectingFastPlayerNr); } + break; } + //Check if selecting with keyboard is active if (_SelectingKeyboardActive) { //Handle left/right/up/down _NameSelections[_NameSelection].HandleInput(keyEvent); - int numberPressed = -1; - bool resetSelection = false; + var numberPressed = -1; + var resetSelection = false; switch (keyEvent.Key) { case Keys.Enter: //Check, if a player is selected - if (_NameSelections[_NameSelection].SelectedID != Guid.Empty) + if (_NameSelections[_NameSelection].SelectedId != Guid.Empty) { - _SelectedProfileID = _NameSelections[_NameSelection].SelectedID; + _SelectedProfileId = _NameSelections[_NameSelection].SelectedId; - if (!CProfiles.IsProfileIDValid(_SelectedProfileID)) + if (!CProfiles.IsProfileIdValid(_SelectedProfileId)) + { return true; + } - _UpdateSelectedProfile(_SelectingFastPlayerNr - 1, _SelectedProfileID); + _UpdateSelectedProfile(_SelectingFastPlayerNr - 1, _SelectedProfileId); } + //Started selecting with 'P' if (_SelectingFast) { @@ -213,7 +224,10 @@ namespace Vocaluxe.Screens } } else + { resetSelection = true; + } + break; case Keys.D1: @@ -260,7 +274,7 @@ namespace Vocaluxe.Screens case Keys.F10: if (CGame.GetNumSongs() == 1 && CGame.GetSong(0).IsDuet) { - CSelectSlide selectSlideDuetPart = _SelectSlides[_SelectSlideDuetPlayer[_SelectingFastPlayerNr - 1]]; + var selectSlideDuetPart = _SelectSlides[_SelectSlideDuetPlayer[_SelectingFastPlayerNr - 1]]; selectSlideDuetPart.Selection = (selectSlideDuetPart.Selection + 1) % 2; //Reset all values _SelectingFastPlayerNr = 0; @@ -269,8 +283,10 @@ namespace Vocaluxe.Screens _NameSelections[_NameSelection].FastSelection(false, -1); _SelectElement(_Buttons[_ButtonStart]); } + break; } + if (numberPressed > 0 || resetSelection) { if (numberPressed == _SelectingFastPlayerNr || resetSelection) @@ -286,10 +302,11 @@ namespace Vocaluxe.Screens _SelectingFastPlayerNr = numberPressed; _NameSelections[_NameSelection].FastSelection(true, numberPressed); } + _SelectingFast = false; } } - //Normal Keyboard handling + //Normal Keyboard handling else { base.HandleInput(keyEvent); @@ -313,6 +330,7 @@ namespace Vocaluxe.Screens _StartSong(); _LeaveScreen(); } + break; case Keys.D1: @@ -354,6 +372,7 @@ namespace Vocaluxe.Screens _SelectingKeyboardActive = true; _NameSelections[_NameSelection].FastSelection(true, _SelectingFastPlayerNr); } + if (_NameSelections[_NameSelection].Selected && !_SelectingKeyboardActive) { _SelectingKeyboardActive = true; @@ -369,15 +388,19 @@ namespace Vocaluxe.Screens public override bool HandleMouse(SMouseEvent mouseEvent) { - bool stopSelectingFast = false; + var stopSelectingFast = false; if (_SelectingFast) + { _NameSelections[_NameSelection].HandleMouse(mouseEvent); + } else + { base.HandleMouse(mouseEvent); + } //Check if LeftButton is hold and Select-Mode inactive - if (mouseEvent.LBH && _SelectedProfileID == Guid.Empty && !_SelectingFast) + if (mouseEvent.LBH && _SelectedProfileId == Guid.Empty && !_SelectingFast) { //Save mouse-coords _OldMouseX = mouseEvent.X; @@ -386,11 +409,11 @@ namespace Vocaluxe.Screens if (_NameSelections[_NameSelection].IsOverTile(mouseEvent)) { //Get player-number of tile - _SelectedProfileID = _NameSelections[_NameSelection].TilePlayerID(mouseEvent); - if (_SelectedProfileID != Guid.Empty) + _SelectedProfileId = _NameSelections[_NameSelection].TilePlayerId(mouseEvent); + if (_SelectedProfileId != Guid.Empty) { //Update of Drag/Drop-Texture - CStatic selectedPlayer = _NameSelections[_NameSelection].TilePlayerAvatar(mouseEvent); + var selectedPlayer = _NameSelections[_NameSelection].TilePlayerAvatar(mouseEvent); _ChooseAvatarStatic.Visible = true; _ChooseAvatarStatic.MaxRect = selectedPlayer.Rect; _ChooseAvatarStatic.Z = CSettings.ZNear; @@ -400,14 +423,14 @@ namespace Vocaluxe.Screens } else { - for (int i = 0; i < CGame.NumPlayers; i++) + for (var i = 0; i < CGame.NumPlayers; i++) { if (CHelper.IsInBounds(_Statics[_StaticPlayer[i]].Rect, mouseEvent)) { _SelectingSwitchNr = i; - _SelectedProfileID = CGame.Players[i].ProfileID; + _SelectedProfileId = CGame.Players[i].ProfileId; //Update of Drag/Drop-Texture - CStatic selectedPlayer = _Statics[_StaticPlayerAvatar[i]]; + var selectedPlayer = _Statics[_StaticPlayerAvatar[i]]; _ChooseAvatarStatic.Visible = true; _ChooseAvatarStatic.MaxRect = selectedPlayer.Rect; _ChooseAvatarStatic.Z = CSettings.ZNear; @@ -420,7 +443,7 @@ namespace Vocaluxe.Screens } //Check if LeftButton is hold and Select-Mode active - if (mouseEvent.LBH && _SelectedProfileID != Guid.Empty && !_SelectingFast) + if (mouseEvent.LBH && _SelectedProfileId != Guid.Empty && !_SelectingFast) { //Update coords for Drag/Drop-Texture _ChooseAvatarStatic.X += mouseEvent.X - _OldMouseX; @@ -428,35 +451,48 @@ namespace Vocaluxe.Screens _OldMouseX = mouseEvent.X; _OldMouseY = mouseEvent.Y; } - // LeftButton isn't hold anymore, but Select-Mode is still active -> "Drop" of Avatar - else if (_SelectedProfileID != Guid.Empty && !_SelectingFast) + // LeftButton isn't hold anymore, but Select-Mode is still active -> "Drop" of Avatar + else if (_SelectedProfileId != Guid.Empty && !_SelectingFast) { //Foreach Drop-Area - for (int i = 0; i < _StaticPlayer.Length; i++) + for (var i = 0; i < _StaticPlayer.Length; i++) { //Check first, if area is "Active" if (!_Statics[_StaticPlayer[i]].Visible) + { continue; + } + //Check if Mouse is in area if (CHelper.IsInBounds(_Statics[_StaticPlayer[i]].Rect, mouseEvent)) { - if (_SelectingSwitchNr > -1 && CGame.Players[i].ProfileID != Guid.Empty) - _UpdateSelectedProfile(_SelectingSwitchNr, CGame.Players[i].ProfileID); + if (_SelectingSwitchNr > -1 && CGame.Players[i].ProfileId != Guid.Empty) + { + _UpdateSelectedProfile(_SelectingSwitchNr, CGame.Players[i].ProfileId); + } else if (_SelectingSwitchNr > -1) + { _ResetPlayerSelection(_SelectingSwitchNr); + } - if (!CProfiles.IsProfileIDValid(_SelectedProfileID)) + if (!CProfiles.IsProfileIdValid(_SelectedProfileId)) + { return true; + } - _UpdateSelectedProfile(i, _SelectedProfileID); + _UpdateSelectedProfile(i, _SelectedProfileId); break; } + //Selected player is dropped out of area if (_SelectingSwitchNr > -1) + { _ResetPlayerSelection(_SelectingSwitchNr); + } } + _SelectingSwitchNr = -1; - _SelectedProfileID = Guid.Empty; + _SelectedProfileId = Guid.Empty; //Reset variables _ChooseAvatarStatic.Visible = false; } @@ -466,22 +502,30 @@ namespace Vocaluxe.Screens if (_NameSelections[_NameSelection].IsOverTile(mouseEvent)) { //Get player-number of tile - _SelectedProfileID = _NameSelections[_NameSelection].TilePlayerID(mouseEvent); - if (_SelectedProfileID != Guid.Empty) + _SelectedProfileId = _NameSelections[_NameSelection].TilePlayerId(mouseEvent); + if (_SelectedProfileId != Guid.Empty) { - if (!CProfiles.IsProfileIDValid(_SelectedProfileID)) + if (!CProfiles.IsProfileIdValid(_SelectedProfileId)) + { return true; + } - _UpdateSelectedProfile(_SelectingFastPlayerNr - 1, _SelectedProfileID); + _UpdateSelectedProfile(_SelectingFastPlayerNr - 1, _SelectedProfileId); _SelectingFastPlayerNr++; if (_SelectingFastPlayerNr <= CGame.NumPlayers) + { _NameSelections[_NameSelection].FastSelection(true, _SelectingFastPlayerNr); + } else + { stopSelectingFast = true; + } } else + { stopSelectingFast = true; + } } } else if (mouseEvent.LB && _IsMouseOverCurSelection(mouseEvent)) @@ -497,24 +541,29 @@ namespace Vocaluxe.Screens _LeaveScreen(); } else + { _UpdatePlayerNumber(); + } + //Update Tiles-List _NameSelections[_NameSelection].UpdateList(); } if (mouseEvent.LD && _NameSelections[_NameSelection].IsOverTile(mouseEvent) && !_SelectingFast) { - _SelectedProfileID = _NameSelections[_NameSelection].TilePlayerID(mouseEvent); - if (_SelectedProfileID != Guid.Empty) + _SelectedProfileId = _NameSelections[_NameSelection].TilePlayerId(mouseEvent); + if (_SelectedProfileId != Guid.Empty) { - for (int i = 0; i < CGame.NumPlayers; i++) + for (var i = 0; i < CGame.NumPlayers; i++) { - if (CGame.Players[i].ProfileID == Guid.Empty) + if (CGame.Players[i].ProfileId == Guid.Empty) { - if (!CProfiles.IsProfileIDValid(_SelectedProfileID)) + if (!CProfiles.IsProfileIdValid(_SelectedProfileId)) + { return true; + } - _UpdateSelectedProfile(i, _SelectedProfileID); + _UpdateSelectedProfile(i, _SelectedProfileId); break; } } @@ -522,12 +571,14 @@ namespace Vocaluxe.Screens } if (mouseEvent.RB && _SelectingFast) + { stopSelectingFast = true; + } else if (mouseEvent.RB) { - bool exit = true; + var exit = true; //Remove profile-selection - for (int i = 0; i < CConfig.Config.Game.NumPlayers; i++) + for (var i = 0; i < CConfig.Config.Game.NumPlayers; i++) { if (CHelper.IsInBounds(_Statics[_StaticPlayer[i]].Rect, mouseEvent)) { @@ -535,6 +586,7 @@ namespace Vocaluxe.Screens exit = false; } } + if (exit) { CGraphics.FadeTo(EScreen.Song); @@ -546,9 +598,13 @@ namespace Vocaluxe.Screens { _SelectingFastPlayerNr++; if (_SelectingFastPlayerNr <= CGame.NumPlayers) + { _NameSelections[_NameSelection].FastSelection(true, _SelectingFastPlayerNr); + } else + { stopSelectingFast = true; + } } else if (mouseEvent.MB) { @@ -564,7 +620,7 @@ namespace Vocaluxe.Screens { if (CHelper.IsInBounds(_NameSelections[_NameSelection].Rect, mouseEvent)) { - int offset = _NameSelections[_NameSelection].Offset + mouseEvent.Wheel; + var offset = _NameSelections[_NameSelection].Offset + mouseEvent.Wheel; _NameSelections[_NameSelection].UpdateList(offset); } } @@ -576,15 +632,18 @@ namespace Vocaluxe.Screens _SelectingKeyboardActive = false; _NameSelections[_NameSelection].FastSelection(false, -1); } + return true; } public override bool UpdateGame() { if (_ProfilesChanged || _AvatarsChanged) + { _LoadProfiles(); + } - for (int i = 1; i <= CGame.NumPlayers; i++) + for (var i = 1; i <= CGame.NumPlayers; i++) { CRecord.AnalyzeBuffer(i - 1); _Equalizers["EqualizerPlayer" + i].Update(CRecord.ToneWeigth(i - 1), CRecord.GetMaxVolume(i - 1)); @@ -620,10 +679,14 @@ namespace Vocaluxe.Screens private void _OnProfileChanged(EProfileChangedFlags flags) { if (EProfileChangedFlags.Avatar == (EProfileChangedFlags.Avatar & flags)) + { _AvatarsChanged = true; + } if (EProfileChangedFlags.Profile == (EProfileChangedFlags.Profile & flags)) + { _ProfilesChanged = true; + } } private void _LoadProfiles() @@ -635,27 +698,33 @@ namespace Vocaluxe.Screens _CheckMics(); _CheckPlayers(); - CSong firstSong = CGame.GetSong(0); + var firstSong = CGame.GetSong(0); - for (int i = 0; i < CSettings.MaxNumPlayer; i++) + for (var i = 0; i < CSettings.MaxNumPlayer; i++) { - _NameSelections[_NameSelection].UseProfile(CGame.Players[i].ProfileID); - _Statics[_StaticPlayerAvatar[i]].Texture = CProfiles.IsProfileIDValid(CGame.Players[i].ProfileID) ? - CProfiles.GetAvatarTextureFromProfile(CGame.Players[i].ProfileID) : - _OriginalPlayerAvatarTextures[i]; - _Texts[_TextPlayer[i]].Text = CProfiles.GetPlayerName(CGame.Players[i].ProfileID, i + 1); + _NameSelections[_NameSelection].UseProfile(CGame.Players[i].ProfileId); + _Statics[_StaticPlayerAvatar[i]].Texture = CProfiles.IsProfileIdValid(CGame.Players[i].ProfileId) ? + CProfiles.GetAvatarTextureFromProfile(CGame.Players[i].ProfileId) : + _OriginalPlayerAvatarTextures[i]; + _Texts[_TextPlayer[i]].Text = CProfiles.GetPlayerName(CGame.Players[i].ProfileId, i + 1); if (CGame.GetNumSongs() == 1 && firstSong.IsDuet) { _SelectSlides[_SelectSlideDuetPlayer[i]].Clear(); _SelectSlides[_SelectSlideDuetPlayer[i]].Visible = i + 1 <= CGame.NumPlayers; - for (int j = 0; j < firstSong.Notes.VoiceCount; j++) + for (var j = 0; j < firstSong.Notes.VoiceCount; j++) + { _SelectSlides[_SelectSlideDuetPlayer[i]].AddValue(firstSong.Notes.VoiceNames[j]); + } + _SelectSlides[_SelectSlideDuetPlayer[i]].Selection = i % 2; } else + { _SelectSlides[_SelectSlideDuetPlayer[i]].Visible = false; + } } + _NameSelections[_NameSelection].UpdateList(); _ProfilesChanged = false; _AvatarsChanged = false; @@ -665,17 +734,23 @@ namespace Vocaluxe.Screens { if (CGame.GetNumSongs() == 1 && CGame.GetSong(0).IsDuet) { - for (int i = 0; i < CGame.NumPlayers; i++) + for (var i = 0; i < CGame.NumPlayers; i++) + { CGame.Players[i].VoiceNr = _SelectSlides[_SelectSlideDuetPlayer[i]].Selection; + } } + CGraphics.FadeTo(EScreen.Sing); } private void _UpdateSlides() { _SelectSlides[_SelectSlidePlayerNumber].Clear(); - for (int i = 1; i <= CSettings.MaxNumPlayer; i++) + for (var i = 1; i <= CSettings.MaxNumPlayer; i++) + { _SelectSlides[_SelectSlidePlayerNumber].AddValue(CLanguage.Translate("TR_SCREENNAMES_" + i + "PLAYER")); + } + _SelectSlides[_SelectSlidePlayerNumber].Selection = CConfig.Config.Game.NumPlayers - 1; } @@ -683,7 +758,7 @@ namespace Vocaluxe.Screens { CConfig.Config.Game.NumPlayers = _SelectSlides[_SelectSlidePlayerNumber].Selection + 1; CGame.NumPlayers = _SelectSlides[_SelectSlidePlayerNumber].Selection + 1; - for (int i = 1; i <= CSettings.MaxNumPlayer; i++) + for (var i = 1; i <= CSettings.MaxNumPlayer; i++) { if (i <= CGame.NumPlayers) { @@ -691,10 +766,15 @@ namespace Vocaluxe.Screens _Statics["StaticPlayerAvatar" + i].Visible = true; _Texts["TextPlayer" + i].Visible = true; if (_Texts["TextPlayer" + i].Text == "") + { _Texts["TextPlayer" + i].Text = CProfiles.GetPlayerName(Guid.Empty, i); + } + _Equalizers["EqualizerPlayer" + i].Visible = true; if (CGame.GetNumSongs() == 1 && CGame.GetSong(0).IsDuet) + { _SelectSlides["SelectSlideDuetPlayer" + i].Visible = true; + } } else { @@ -706,6 +786,7 @@ namespace Vocaluxe.Screens _ResetPlayerSelection(i - 1); } } + CConfig.SaveConfig(); _CheckMics(); _CheckPlayers(); @@ -713,10 +794,10 @@ namespace Vocaluxe.Screens private void _UpdateSelectedProfile(int playerNum, Guid profileId) { - _NameSelections[_NameSelection].RemoveUsedProfile(CGame.Players[playerNum].ProfileID); + _NameSelections[_NameSelection].RemoveUsedProfile(CGame.Players[playerNum].ProfileId); _NameSelections[_NameSelection].UseProfile(profileId); //Update Game-infos with new player - CGame.Players[playerNum].ProfileID = profileId; + CGame.Players[playerNum].ProfileId = profileId; //Update config for default players. CConfig.Config.Game.Players[playerNum] = CProfiles.GetProfileFileName(profileId); CConfig.SaveConfig(); @@ -731,26 +812,27 @@ namespace Vocaluxe.Screens private void _ResetPlayerSelections() { - for (int i = 0; i < CGame.NumPlayers; i++) + for (var i = 0; i < CGame.NumPlayers; i++) { - _NameSelections[_NameSelection].RemoveUsedProfile(CGame.Players[i].ProfileID); - CGame.Players[i].ProfileID = Guid.Empty; + _NameSelections[_NameSelection].RemoveUsedProfile(CGame.Players[i].ProfileId); + CGame.Players[i].ProfileId = Guid.Empty; //Update config for default players. - CConfig.Config.Game.Players[i] = String.Empty; + CConfig.Config.Game.Players[i] = string.Empty; //Update texture and name _Statics[_StaticPlayerAvatar[i]].Texture = _OriginalPlayerAvatarTextures[i]; _Texts[_TextPlayer[i]].Text = CProfiles.GetPlayerName(Guid.Empty, i + 1); } + _NameSelections[_NameSelection].UpdateList(); CConfig.SaveConfig(); } private void _ResetPlayerSelection(int playerNum) { - _NameSelections[_NameSelection].RemoveUsedProfile(CGame.Players[playerNum].ProfileID); - CGame.Players[playerNum].ProfileID = Guid.Empty; + _NameSelections[_NameSelection].RemoveUsedProfile(CGame.Players[playerNum].ProfileId); + CGame.Players[playerNum].ProfileId = Guid.Empty; //Update config for default players. - CConfig.Config.Game.Players[playerNum] = String.Empty; + CConfig.Config.Game.Players[playerNum] = string.Empty; CConfig.SaveConfig(); //Update texture and name _Statics[_StaticPlayerAvatar[playerNum]].Texture = _OriginalPlayerAvatarTextures[playerNum]; @@ -764,11 +846,14 @@ namespace Vocaluxe.Screens private void _CheckMics() { var playerWithoutMicro = new List(); - for (int player = 0; player < CConfig.Config.Game.NumPlayers; player++) + for (var player = 0; player < CConfig.Config.Game.NumPlayers; player++) { if (!CConfig.IsMicConfig(player + 1)) + { playerWithoutMicro.Add(player + 1); + } } + if (playerWithoutMicro.Count > 0) { _Statics[_StaticWarningMics].Visible = true; @@ -776,21 +861,29 @@ namespace Vocaluxe.Screens if (playerWithoutMicro.Count > 1) { - string playerNums = string.Empty; - for (int i = 0; i < playerWithoutMicro.Count; i++) + var playerNums = string.Empty; + for (var i = 0; i < playerWithoutMicro.Count; i++) { if (playerWithoutMicro.Count - 1 == i) + { playerNums += playerWithoutMicro[i].ToString(); + } else if (playerWithoutMicro.Count - 2 == i) + { playerNums += playerWithoutMicro[i] + " " + CLanguage.Translate("TR_GENERAL_AND") + " "; + } else + { playerNums += playerWithoutMicro[i] + ", "; + } } _Texts[_TextWarningMics].Text = CLanguage.Translate("TR_SCREENNAMES_WARNING_MICS_PL").Replace("%v", playerNums); } else + { _Texts[_TextWarningMics].Text = CLanguage.Translate("TR_SCREENNAMES_WARNING_MICS_SG").Replace("%v", playerWithoutMicro[0].ToString()); + } } else { @@ -802,10 +895,12 @@ namespace Vocaluxe.Screens private void _CheckPlayers() { var playerWithoutProfile = new List(); - for (int player = 0; player < CConfig.Config.Game.NumPlayers; player++) + for (var player = 0; player < CConfig.Config.Game.NumPlayers; player++) { - if (CGame.Players[player].ProfileID == Guid.Empty) + if (CGame.Players[player].ProfileId == Guid.Empty) + { playerWithoutProfile.Add(player + 1); + } } if (playerWithoutProfile.Count > 0) @@ -815,21 +910,29 @@ namespace Vocaluxe.Screens if (playerWithoutProfile.Count > 1) { - string playerNums = string.Empty; - for (int i = 0; i < playerWithoutProfile.Count; i++) + var playerNums = string.Empty; + for (var i = 0; i < playerWithoutProfile.Count; i++) { if (playerWithoutProfile.Count - 1 == i) + { playerNums += playerWithoutProfile[i].ToString(); + } else if (playerWithoutProfile.Count - 2 == i) + { playerNums += playerWithoutProfile[i] + " " + CLanguage.Translate("TR_GENERAL_AND") + " "; + } else + { playerNums += playerWithoutProfile[i] + ", "; + } } _Texts[_TextWarningProfiles].Text = CLanguage.Translate("TR_SCREENNAMES_WARNING_PROFILES_PL").Replace("%v", playerNums); } else + { _Texts[_TextWarningProfiles].Text = CLanguage.Translate("TR_SCREENNAMES_WARNING_PROFILES_SG").Replace("%v", playerWithoutProfile[0].ToString()); + } } else { @@ -839,13 +942,13 @@ namespace Vocaluxe.Screens } private void _LeaveScreen() - { + { if (_WarningStream != -1) { - CSound.Close(_WarningStream); + CSound.Close(_WarningStream); _WarningStream = -1; } } #endregion private methods } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenOptions.cs b/Vocaluxe/Screens/CScreenOptions.cs index 1840afc4..0fd4de2c 100644 --- a/Vocaluxe/Screens/CScreenOptions.cs +++ b/Vocaluxe/Screens/CScreenOptions.cs @@ -15,13 +15,12 @@ // along with Vocaluxe. If not, see . #endregion -using System.Windows.Forms; -using System.Linq; using System.Collections.Generic; +using System.Linq; +using System.Windows.Forms; using Vocaluxe.Base; using VocaluxeLib; using VocaluxeLib.Menu; -using Vocaluxe.Lib.Sound; namespace Vocaluxe.Screens { @@ -32,8 +31,8 @@ namespace Vocaluxe.Screens { get { return 4; } } - - private const string _ButtonOptionsBack = "ButtonOptionsBack"; + + private const string _ButtonOptionsBack = "ButtonOptionsBack"; private const string _ButtonOptionsGame = "ButtonOptionsGame"; private const string _ButtonOptionsSound = "ButtonOptionsSound"; private const string _ButtonOptionsRecord = "ButtonOptionsRecord"; @@ -50,10 +49,10 @@ namespace Vocaluxe.Screens private int _WarningStream = -1; private bool _HasPlayedWarningSound = false; - + private static int PlaySound(ESounds sound, int volume) { - int streamId = CSound.PlaySound(sound, false); + var streamId = CSound.PlaySound(sound, false); CSound.SetStreamVolume(streamId, volume); return streamId; @@ -63,9 +62,13 @@ namespace Vocaluxe.Screens { base.Init(); - _ThemeButtons = new string[] {_ButtonOptionsBack, _ButtonOptionsGame, _ButtonOptionsSound, _ButtonOptionsRecord, _ButtonOptionsVideo, _ButtonOptionsLyrics, _ButtonOptionsTheme, _ButtonOptionsCredits, _ButtonOptionsGraphics, _ButtonOptionsServer, _ButtonSelectSongFolder}; - _ThemeTexts = new string[] {_TextWarningRestart}; - _ThemeStatics = new string[] {_StaticWarningRestart}; + _ThemeButtons = new string[] + { + _ButtonOptionsBack, _ButtonOptionsGame, _ButtonOptionsSound, _ButtonOptionsRecord, _ButtonOptionsVideo, _ButtonOptionsLyrics, _ButtonOptionsTheme, + _ButtonOptionsCredits, _ButtonOptionsGraphics, _ButtonOptionsServer, _ButtonSelectSongFolder + }; + _ThemeTexts = new string[] { _TextWarningRestart }; + _ThemeStatics = new string[] { _StaticWarningRestart }; } public override void LoadTheme(string xmlPath) @@ -75,12 +78,12 @@ namespace Vocaluxe.Screens _Texts[_TextWarningRestart].Visible = false; _Statics[_StaticWarningRestart].Visible = false; } - + public override bool HandleInput(SKeyEvent keyEvent) { base.HandleInput(keyEvent); - if (keyEvent.KeyPressed) {} + if (keyEvent.KeyPressed) { } else { switch (keyEvent.Key) @@ -163,9 +166,11 @@ namespace Vocaluxe.Screens _Texts[_TextWarningRestart].Visible = true; _Statics[_StaticWarningRestart].Visible = true; } + break; } } + return true; } @@ -247,6 +252,7 @@ namespace Vocaluxe.Screens CGraphics.FadeTo(EScreen.Main); _LeaveScreen(); } + return true; } @@ -257,7 +263,7 @@ namespace Vocaluxe.Screens _WarningStream = CScreenOptions.PlaySound(ESounds.Warning, CConfig.SoundEffectVolume); _HasPlayedWarningSound = true; } - + return true; } @@ -273,23 +279,25 @@ namespace Vocaluxe.Screens var folders = CConfig.Config.Game.SongFolder?.ToList() ?? new List(); if (!folders.Contains(dialog.SelectedPath)) { - folders.Add(dialog.SelectedPath); - CConfig.Config.Game.SongFolder = folders.ToArray(); - CConfig.SaveConfig(); + folders.Add(dialog.SelectedPath); + CConfig.Config.Game.SongFolder = folders.ToArray(); + CConfig.SaveConfig(); } + return true; // Folder was selected } } + return false; // Dialog was cancelled } - + private void _LeaveScreen() - { + { if (_WarningStream != -1) { - CSound.Close(_WarningStream); + CSound.Close(_WarningStream); _WarningStream = -1; } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenOptionsGame.cs b/Vocaluxe/Screens/CScreenOptionsGame.cs index ae09cfd9..5ac2a105 100644 --- a/Vocaluxe/Screens/CScreenOptionsGame.cs +++ b/Vocaluxe/Screens/CScreenOptionsGame.cs @@ -45,8 +45,11 @@ namespace Vocaluxe.Screens { base.Init(); - _ThemeButtons = new string[] {_ButtonExit}; - _ThemeSelectSlides = new string[] {_SelectSlideLanguage, _SelectSlideDebugLevel, _SelectSlideSongMenu, _SelectSlideSongSorting, _SelectSlideTabs, _SelectSlideTimerMode, _SelectSlideHighscoreStyle}; + _ThemeButtons = new string[] { _ButtonExit }; + _ThemeSelectSlides = new string[] + { + _SelectSlideLanguage, _SelectSlideDebugLevel, _SelectSlideSongMenu, _SelectSlideSongSorting, _SelectSlideTabs, _SelectSlideTimerMode, _SelectSlideHighscoreStyle + }; } public override void LoadTheme(string xmlPath) @@ -91,6 +94,7 @@ namespace Vocaluxe.Screens _SaveConfig(); CGraphics.FadeTo(EScreen.Options); } + break; case Keys.Left: @@ -102,6 +106,7 @@ namespace Vocaluxe.Screens break; } } + return true; } @@ -120,12 +125,12 @@ namespace Vocaluxe.Screens CGraphics.FadeTo(EScreen.Options); _SaveConfig(); } - return true; + return true; } public override bool UpdateGame() - { + { return true; } @@ -147,4 +152,4 @@ namespace Vocaluxe.Screens CSongs.Categorizer.Tabs = CConfig.Config.Game.Tabs; } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenOptionsGraphics.cs b/Vocaluxe/Screens/CScreenOptionsGraphics.cs index 35d0dfbc..ca5b9ad3 100644 --- a/Vocaluxe/Screens/CScreenOptionsGraphics.cs +++ b/Vocaluxe/Screens/CScreenOptionsGraphics.cs @@ -16,12 +16,11 @@ #endregion using System; -using System.Windows.Forms; using System.IO; +using System.Windows.Forms; using Vocaluxe.Base; using VocaluxeLib; using VocaluxeLib.Menu; -using Vocaluxe.Lib.Sound; namespace Vocaluxe.Screens { @@ -44,10 +43,10 @@ namespace Vocaluxe.Screens private int _WarningStream = -1; private bool _HasPlayedWarningSound = false; - + private static int PlaySound(ESounds sound, int volume) { - int streamId = CSound.PlaySound(sound, false); + var streamId = CSound.PlaySound(sound, false); CSound.SetStreamVolume(streamId, volume); return streamId; @@ -57,22 +56,22 @@ namespace Vocaluxe.Screens { base.Init(); - _ThemeButtons = new string[] {_ButtonExit}; - _ThemeSelectSlides = new string[] {_SelectSlideTextureQuality, _SelectSlideCoverSize, _SelectSlideFullScreen, _SelectSlideStretch}; - _ThemeTexts = new string[] {_TextWarningRestart}; - _ThemeStatics = new string[] {_StaticWarningRestart}; + _ThemeButtons = new string[] { _ButtonExit }; + _ThemeSelectSlides = new string[] { _SelectSlideTextureQuality, _SelectSlideCoverSize, _SelectSlideFullScreen, _SelectSlideStretch }; + _ThemeTexts = new string[] { _TextWarningRestart }; + _ThemeStatics = new string[] { _StaticWarningRestart }; } public override void LoadTheme(string xmlPath) { base.LoadTheme(xmlPath); _SelectSlides[_SelectSlideTextureQuality].SetValues((int)CConfig.Config.Graphics.TextureQuality); - + _SelectSlides[_SelectSlideCoverSize].AddValues(CoverSizes); - int currentCoverSize = CConfig.Config.Graphics.CoverSize; - int index = Array.IndexOf(CoverSizes, currentCoverSize.ToString()); + var currentCoverSize = CConfig.Config.Graphics.CoverSize; + var index = Array.IndexOf(CoverSizes, currentCoverSize.ToString()); _SelectSlides[_SelectSlideCoverSize].Selection = index; - + _SelectSlides[_SelectSlideFullScreen].SetValues((int)CConfig.Config.Graphics.FullScreen); _SelectSlides[_SelectSlideFullScreen].Selection = (int)CConfig.Config.Graphics.FullScreen; @@ -110,6 +109,7 @@ namespace Vocaluxe.Screens CGraphics.FadeTo(EScreen.Options); _LeaveScreen(); } + break; case Keys.Left: @@ -120,6 +120,7 @@ namespace Vocaluxe.Screens _SaveConfig(); break; } + return true; } @@ -133,6 +134,7 @@ namespace Vocaluxe.Screens CGraphics.FadeTo(EScreen.Options); _LeaveScreen(); } + if (mouseEvent.LB && _IsMouseOverCurSelection(mouseEvent)) { _SaveConfig(); @@ -142,6 +144,7 @@ namespace Vocaluxe.Screens _LeaveScreen(); } } + return true; } @@ -149,58 +152,59 @@ namespace Vocaluxe.Screens { if (_Texts[_TextWarningRestart].Visible && !_HasPlayedWarningSound) { - _WarningStream = CScreenOptionsGraphics.PlaySound(ESounds.Warning, CConfig.SoundEffectVolume); - _HasPlayedWarningSound = true; + _WarningStream = CScreenOptionsGraphics.PlaySound(ESounds.Warning, CConfig.SoundEffectVolume); + _HasPlayedWarningSound = true; } + return true; } private void _SaveConfig() { // Detect Texture quality change - ETextureQuality _currentTextureQuality = CConfig.Config.Graphics.TextureQuality; - ETextureQuality _newTextureQuality = (ETextureQuality)_SelectSlides[_SelectSlideTextureQuality].Selection; + var _currentTextureQuality = CConfig.Config.Graphics.TextureQuality; + var _newTextureQuality = (ETextureQuality)_SelectSlides[_SelectSlideTextureQuality].Selection; if (_currentTextureQuality != _newTextureQuality) { _Texts[_TextWarningRestart].Visible = true; - _Statics[_StaticWarningRestart].Visible = true; + _Statics[_StaticWarningRestart].Visible = true; CConfig.Config.Graphics.TextureQuality = _newTextureQuality; } else { CConfig.Config.Graphics.TextureQuality = _newTextureQuality; - } + } // Detect Cover size change - string selectedValue = CoverSizes[_SelectSlides[_SelectSlideCoverSize].Selection]; - int currentCoverSize = CConfig.Config.Graphics.CoverSize; - int newCoverSize = int.Parse(selectedValue); + var selectedValue = CoverSizes[_SelectSlides[_SelectSlideCoverSize].Selection]; + var currentCoverSize = CConfig.Config.Graphics.CoverSize; + var newCoverSize = int.Parse(selectedValue); if (currentCoverSize != newCoverSize) { - string flagPath = Path.Combine(CSettings.DataFolder, "DeleteCoverDB.flag"); + var flagPath = Path.Combine(CSettings.DataFolder, "DeleteCoverDB.flag"); File.Create(flagPath).Dispose(); _Texts[_TextWarningRestart].Visible = true; - _Statics[_StaticWarningRestart].Visible = true; + _Statics[_StaticWarningRestart].Visible = true; CConfig.Config.Graphics.CoverSize = newCoverSize; } else { CConfig.Config.Graphics.CoverSize = newCoverSize; - } - + } + CConfig.Config.Graphics.FullScreen = (EOffOn)_SelectSlides[_SelectSlideFullScreen].Selection; CConfig.Config.Graphics.Stretch = (EOffOn)_SelectSlides[_SelectSlideStretch].Selection; - + CConfig.SaveConfig(); } - + private void _LeaveScreen() - { + { if (_WarningStream != -1) { - CSound.Close(_WarningStream); + CSound.Close(_WarningStream); _WarningStream = -1; } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenOptionsLyrics.cs b/Vocaluxe/Screens/CScreenOptionsLyrics.cs index ed4ce6b5..377772de 100644 --- a/Vocaluxe/Screens/CScreenOptionsLyrics.cs +++ b/Vocaluxe/Screens/CScreenOptionsLyrics.cs @@ -15,9 +15,7 @@ // along with Vocaluxe. If not, see . #endregion -using System; using System.Windows.Forms; -using System.IO; using Vocaluxe.Base; using VocaluxeLib; using VocaluxeLib.Menu; @@ -40,8 +38,8 @@ namespace Vocaluxe.Screens { base.Init(); - _ThemeButtons = new string[] {_ButtonExit}; - _ThemeSelectSlides = new string[] {_SelectSlideLyricStyle, _SelectSlideLyricsPosition}; + _ThemeButtons = new string[] { _ButtonExit }; + _ThemeSelectSlides = new string[] { _SelectSlideLyricStyle, _SelectSlideLyricsPosition }; } public override void LoadTheme(string xmlPath) @@ -55,7 +53,7 @@ namespace Vocaluxe.Screens { base.HandleInput(keyEvent); - if (keyEvent.KeyPressed) {} + if (keyEvent.KeyPressed) { } else { switch (keyEvent.Key) @@ -78,6 +76,7 @@ namespace Vocaluxe.Screens _SaveConfig(); CGraphics.FadeTo(EScreen.Options); } + break; case Keys.Left: @@ -89,6 +88,7 @@ namespace Vocaluxe.Screens break; } } + return true; } @@ -101,6 +101,7 @@ namespace Vocaluxe.Screens _SaveConfig(); CGraphics.FadeTo(EScreen.Options); } + if (mouseEvent.LB && _IsMouseOverCurSelection(mouseEvent)) { _SaveConfig(); @@ -109,6 +110,7 @@ namespace Vocaluxe.Screens CGraphics.FadeTo(EScreen.Options); } } + return true; } @@ -116,7 +118,7 @@ namespace Vocaluxe.Screens { return true; } - + private void _SaveConfig() { CConfig.Config.Game.LyricsPosition = (ELyricsPosition)_SelectSlides[_SelectSlideLyricsPosition].Selection; @@ -124,4 +126,4 @@ namespace Vocaluxe.Screens CConfig.SaveConfig(); } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenOptionsRecord.cs b/Vocaluxe/Screens/CScreenOptionsRecord.cs index 38748c96..1a89a1b6 100644 --- a/Vocaluxe/Screens/CScreenOptionsRecord.cs +++ b/Vocaluxe/Screens/CScreenOptionsRecord.cs @@ -19,8 +19,6 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Windows.Forms; using Vocaluxe.Base; -using Vocaluxe.Base.ThemeSystem; -using Vocaluxe.Lib.Sound; using Vocaluxe.Lib.Sound.Record; using VocaluxeLib; using VocaluxeLib.Menu; @@ -37,7 +35,10 @@ namespace Vocaluxe.Screens private const string _SelectSlideRecordDevices = "SelectSlideRecordDevices"; - private readonly string[] _SelectSlideRecordPlayer = { "SelectSlideRecordPlayer1", "SelectSlideRecordPlayer2", "SelectSlideRecordPlayer3", "SelectSlideRecordPlayer4", "SelectSlideRecordPlayer5", "SelectSlideRecordPlayer6" }; + private readonly string[] _SelectSlideRecordPlayer = + { + "SelectSlideRecordPlayer1", "SelectSlideRecordPlayer2", "SelectSlideRecordPlayer3", "SelectSlideRecordPlayer4", "SelectSlideRecordPlayer5", "SelectSlideRecordPlayer6" + }; private const string _SelectSlideDelay = "SelectSlideDelay"; @@ -53,7 +54,8 @@ namespace Vocaluxe.Screens private readonly string[] _EqualizerPlayer = { "EqualizerPlayer1", "EqualizerPlayer2", "EqualizerPlayer3", "EqualizerPlayer4", "EqualizerPlayer5", "EqualizerPlayer6" }; - private readonly string[] _StaticEnergyPlayer = new string[] { "StaticEnergyPlayer1", "StaticEnergyPlayer2", "StaticEnergyPlayer3", "StaticEnergyPlayer4", "StaticEnergyPlayer5", "StaticEnergyPlayer6" }; + private readonly string[] _StaticEnergyPlayer = new string[] + { "StaticEnergyPlayer1", "StaticEnergyPlayer2", "StaticEnergyPlayer3", "StaticEnergyPlayer4", "StaticEnergyPlayer5", "StaticEnergyPlayer6" }; private float[] _ChannelEnergy; private ReadOnlyCollection _Devices; @@ -68,10 +70,10 @@ namespace Vocaluxe.Screens private int _WarningStream = -1; private bool _HasPlayedWarningSound = false; - + private static int PlaySound(ESounds sound, int volume) { - int streamId = CSound.PlaySound(sound, false); + var streamId = CSound.PlaySound(sound, false); CSound.SetStreamVolume(streamId, volume); return streamId; @@ -81,26 +83,36 @@ namespace Vocaluxe.Screens { base.Init(); - var values = new List {_StaticWarning}; + var values = new List { _StaticWarning }; values.AddRange(_StaticEnergyPlayer); _ThemeStatics = values.ToArray(); - _ThemeTexts = new string[] {_TextWarning, _TextPlayer[0], _TextPlayer[1], _TextPlayer[2], _TextPlayer[3], _TextPlayer[4], _TextPlayer[5], _TextDelayPlayer[0], _TextDelayPlayer[1], _TextDelayPlayer[2], _TextDelayPlayer[3], _TextDelayPlayer[4], _TextDelayPlayer[5] }; - _ThemeButtons = new string[] {_ButtonExit, _ButtonDelayTest}; - _ThemeSelectSlides = new string[] {_SelectSlideRecordDevices, _SelectSlideRecordPlayer[0], _SelectSlideRecordPlayer[1], _SelectSlideRecordPlayer[2], _SelectSlideRecordPlayer[3], _SelectSlideRecordPlayer[4], _SelectSlideRecordPlayer[5], _SelectSlideDelay }; - _ThemeEqualizers = new string[] {_EqualizerPlayer[0], _EqualizerPlayer[1], _EqualizerPlayer[2], _EqualizerPlayer[3], _EqualizerPlayer[4], _EqualizerPlayer[5]}; + _ThemeTexts = new string[] + { + _TextWarning, _TextPlayer[0], _TextPlayer[1], _TextPlayer[2], _TextPlayer[3], _TextPlayer[4], _TextPlayer[5], _TextDelayPlayer[0], _TextDelayPlayer[1], + _TextDelayPlayer[2], _TextDelayPlayer[3], _TextDelayPlayer[4], _TextDelayPlayer[5] + }; + _ThemeButtons = new string[] { _ButtonExit, _ButtonDelayTest }; + _ThemeSelectSlides = new string[] + { + _SelectSlideRecordDevices, _SelectSlideRecordPlayer[0], _SelectSlideRecordPlayer[1], _SelectSlideRecordPlayer[2], _SelectSlideRecordPlayer[3], + _SelectSlideRecordPlayer[4], _SelectSlideRecordPlayer[5], _SelectSlideDelay + }; + _ThemeEqualizers = new string[] { _EqualizerPlayer[0], _EqualizerPlayer[1], _EqualizerPlayer[2], _EqualizerPlayer[3], _EqualizerPlayer[4], _EqualizerPlayer[5] }; } public override void LoadTheme(string xmlPath) { base.LoadTheme(xmlPath); - for (int i = 0; i < 26; i++) - _SelectSlides[_SelectSlideDelay].AddValue((i * 20) + " ms"); + for (var i = 0; i < 26; i++) + { + _SelectSlides[_SelectSlideDelay].AddValue(i * 20 + " ms"); + } _ChannelEnergy = new float[_StaticEnergyPlayer.Length]; - for (int i = 0; i < _ChannelEnergy.Length; i++) + for (var i = 0; i < _ChannelEnergy.Length; i++) { _Statics[_StaticEnergyPlayer[i]].Visible = false; _ChannelEnergy[i] = 0f; @@ -111,7 +123,7 @@ namespace Vocaluxe.Screens { base.HandleInput(keyEvent); - if (keyEvent.KeyPressed) {} + if (keyEvent.KeyPressed) { } else { switch (keyEvent.Key) @@ -139,7 +151,9 @@ namespace Vocaluxe.Screens } if (_Buttons[_ButtonDelayTest].Selected) + { _TestDelay(); + } break; @@ -156,6 +170,7 @@ namespace Vocaluxe.Screens break; } } + return true; } @@ -182,28 +197,35 @@ namespace Vocaluxe.Screens } if (_Buttons[_ButtonDelayTest].Selected) + { _TestDelay(); + } } + return true; } public override bool UpdateGame() { - for (int i = 0; i < CSettings.MaxNumPlayer; i++) + for (var i = 0; i < CSettings.MaxNumPlayer; i++) + { CRecord.AnalyzeBuffer(i); + } if (_DelayTest.Running) { _DelayTest.Update(); - for (int p = 0; p < CSettings.MaxNumPlayer; ++p) - _Texts[_TextDelayPlayer[p]].Text = (_DelayTest.Delays[p] == 0) ? "??? ms" : _DelayTest.Delays[p].ToString("000") + " ms"; + for (var p = 0; p < CSettings.MaxNumPlayer; ++p) + { + _Texts[_TextDelayPlayer[p]].Text = _DelayTest.Delays[p] == 0 ? "??? ms" : _DelayTest.Delays[p].ToString("000") + " ms"; + } } if (_CheckMicConfig()) { - for (int p = 0; p < CSettings.MaxNumPlayer; ++p) + for (var p = 0; p < CSettings.MaxNumPlayer; ++p) { - if(_SelectSlides[_SelectSlideRecordPlayer[p]].Selection > 0) + if (_SelectSlides[_SelectSlideRecordPlayer[p]].Selection > 0) { _ChannelEnergy[p] = CRecord.GetMaxVolume(p); _Equalizers[_EqualizerPlayer[p]].Update(CRecord.ToneWeigth(p), CRecord.GetMaxVolume(p)); @@ -217,20 +239,25 @@ namespace Vocaluxe.Screens } else { - for (int i = 0; i < _ChannelEnergy.Length; i++) + for (var i = 0; i < _ChannelEnergy.Length; i++) + { _ChannelEnergy[i] = 0f; - for (int p = 0; p < CSettings.MaxNumPlayer; ++p) + } + + for (var p = 0; p < CSettings.MaxNumPlayer; ++p) + { _Equalizers[_EqualizerPlayer[p]].Reset(); + } } - bool showWarning = !_CheckMicConfig(); + var showWarning = !_CheckMicConfig(); _Statics[_StaticWarning].Visible = showWarning; _Texts[_TextWarning].Visible = showWarning; if (_Texts[_TextWarning].Visible && !_HasPlayedWarningSound) { - _WarningStream = CScreenOptionsRecord.PlaySound(ESounds.Warning, CConfig.SoundEffectVolume); - _HasPlayedWarningSound = true; + _WarningStream = CScreenOptionsRecord.PlaySound(ESounds.Warning, CConfig.SoundEffectVolume); + _HasPlayedWarningSound = true; } return true; @@ -242,8 +269,10 @@ namespace Vocaluxe.Screens _SelectSlides[_SelectSlideRecordDevices].Clear(); - for (int i = 0; i < _ChannelEnergy.Length; i++) + for (var i = 0; i < _ChannelEnergy.Length; i++) + { _ChannelEnergy[i] = 0f; + } _DeviceNr = -1; @@ -253,14 +282,20 @@ namespace Vocaluxe.Screens _DeviceNr = 0; _GetFirstConfiguredRecordDevice(ref _DeviceNr); - foreach (CRecordDevice device in _Devices) + foreach (var device in _Devices) + { _SelectSlides[_SelectSlideRecordDevices].AddValue(device.Name); + } + _SelectSlides[_SelectSlideRecordDevices].Selection = _DeviceNr; _UpdateChannels(); } - for (int p = 0; p < CSettings.MaxNumPlayer; ++p) + + for (var p = 0; p < CSettings.MaxNumPlayer; ++p) + { _SelectSlides[_SelectSlideRecordPlayer[p]].Visible = _Devices != null; + } _Statics[_StaticWarning].Visible = false; _Texts[_TextWarning].Visible = false; @@ -279,18 +314,18 @@ namespace Vocaluxe.Screens { base.Draw(); - for (int i = 0; i < _StaticEnergyPlayer.Length; i++) + for (var i = 0; i < _StaticEnergyPlayer.Length; i++) { if (_ChannelEnergy[i] > 0f) { var rect = new SRectF(_Statics[_StaticEnergyPlayer[i]].Rect.X, - _Statics[_StaticEnergyPlayer[i]].Rect.Y, - _Statics[_StaticEnergyPlayer[i]].Rect.W * _ChannelEnergy[i], - _Statics[_StaticEnergyPlayer[i]].Rect.H, - _Statics[_StaticEnergyPlayer[i]].Rect.Z); + _Statics[_StaticEnergyPlayer[i]].Rect.Y, + _Statics[_StaticEnergyPlayer[i]].Rect.W * _ChannelEnergy[i], + _Statics[_StaticEnergyPlayer[i]].Rect.H, + _Statics[_StaticEnergyPlayer[i]].Rect.Z); CDraw.DrawTexture(_Statics[_StaticEnergyPlayer[i]].Texture, _Statics[_StaticEnergyPlayer[i]].Rect, - new SColorF(1f, 1f, 1f, 1f), rect); + new SColorF(1f, 1f, 1f, 1f), rect); } } } @@ -321,85 +356,107 @@ namespace Vocaluxe.Screens private void _SaveMicConfig() { if (_Devices == null) + { return; + } CRecord.Stop(); _SetMicConfig(); if (_CheckMicConfig()) { - for (int p = 0; p < CConfig.Config.Record.MicConfig.Length; p++) - CConfig.Config.Record.MicConfig[p].Channel = 0; - - foreach (CRecordDevice device in _Devices) + for (var p = 0; p < CConfig.Config.Record.MicConfig.Length; p++) { - for (int ch = 0; ch < (uint)device.Channels; ++ch) + CConfig.Config.Record.MicConfig[p].Channel = 0; + } + + foreach (var device in _Devices) + { + for (var ch = 0; ch < (uint)device.Channels; ++ch) { if (device.PlayerChannel[ch] > 0) { - CConfig.Config.Record.MicConfig[device.PlayerChannel[ch] - 1].Channel = ch+1; + CConfig.Config.Record.MicConfig[device.PlayerChannel[ch] - 1].Channel = ch + 1; CConfig.Config.Record.MicConfig[device.PlayerChannel[ch] - 1].DeviceName = device.Name; CConfig.Config.Record.MicConfig[device.PlayerChannel[ch] - 1].DeviceDriver = device.Driver; } } } + CConfig.SaveConfig(); } + CRecord.Start(); } private void _SetMicConfig() { if (_DeviceNr < 0) - return; - CRecordDevice device = _Devices[_DeviceNr]; - - for (int ch = 0; ch < device.Channels; ++ch) - device.PlayerChannel[ch] = 0; - - for (int p = 0; p < CSettings.MaxNumPlayer; ++p) { - int ch = _SelectSlides[_SelectSlideRecordPlayer[p]].Selection; + return; + } + + var device = _Devices[_DeviceNr]; + + for (var ch = 0; ch < device.Channels; ++ch) + { + device.PlayerChannel[ch] = 0; + } + + for (var p = 0; p < CSettings.MaxNumPlayer; ++p) + { + var ch = _SelectSlides[_SelectSlideRecordPlayer[p]].Selection; if (ch > 0) - device.PlayerChannel[ch-1] = p+1; - + { + device.PlayerChannel[ch - 1] = p + 1; + } } } private void _SelectSlideAction() { if (_SelectSlides[_SelectSlideRecordDevices].Selected) + { _OnDeviceEvent(); + } - for (int i = 0; i < _SelectSlideRecordPlayer.Length; ++i) + for (var i = 0; i < _SelectSlideRecordPlayer.Length; ++i) + { if (_SelectSlides[_SelectSlideRecordPlayer[i]].Selected) + { _SetMicConfig(); + } + } if (_SelectSlides[_SelectSlideDelay].Selected) + { _SaveDelayConfig(); + } } private void _UpdateChannels() { - int max = _Devices[_DeviceNr].Channels + 1; + var max = _Devices[_DeviceNr].Channels + 1; - for (int p = 0; p < CSettings.MaxNumPlayer; ++p) + for (var p = 0; p < CSettings.MaxNumPlayer; ++p) { _SelectSlides[_SelectSlideRecordPlayer[p]].Clear(); _SelectSlides[_SelectSlideRecordPlayer[p]].NumVisible = max; _SelectSlides[_SelectSlideRecordPlayer[p]].AddValue(CLanguage.Translate("TR_CONFIG_OFF")); } - for (int i = 1; i <= _Devices[_DeviceNr].Channels; ++i) + for (var i = 1; i <= _Devices[_DeviceNr].Channels; ++i) { - for (int p = 0; p < CSettings.MaxNumPlayer; ++p) + for (var p = 0; p < CSettings.MaxNumPlayer; ++p) + { _SelectSlides[_SelectSlideRecordPlayer[p]].AddValue(i.ToString()); - - int pc = _Devices[_DeviceNr].PlayerChannel[i-1]; + } + + var pc = _Devices[_DeviceNr].PlayerChannel[i - 1]; if (pc > 0) { - _SelectSlides[_SelectSlideRecordPlayer[pc-1]].Selection = i; + _SelectSlides[_SelectSlideRecordPlayer[pc - 1]].Selection = i; } } @@ -409,25 +466,32 @@ namespace Vocaluxe.Screens private bool _CheckMicConfig() { var isSet = new bool[CSettings.MaxNumPlayer]; - for (int i = 0; i < CSettings.MaxNumPlayer; i++) + for (var i = 0; i < CSettings.MaxNumPlayer; i++) + { isSet[i] = false; + } if (_Devices == null) - return true; - - foreach (CRecordDevice device in _Devices) { - for (int i = 0; i < device.Channels; ++i) + return true; + } + + foreach (var device in _Devices) + { + for (var i = 0; i < device.Channels; ++i) { if (device.PlayerChannel[i] > 0) { if (isSet[device.PlayerChannel[i] - 1]) + { return false; + } isSet[device.PlayerChannel[i] - 1] = true; } } } + return true; } @@ -435,21 +499,27 @@ namespace Vocaluxe.Screens { _SaveMicConfig(); _DelayTest.Reset(); - _DelayTest.Start(new int[] {0, 1, 2, 3, 4, 5}); + _DelayTest.Start(new int[] { 0, 1, 2, 3, 4, 5 }); } private void _GetFirstConfiguredRecordDevice(ref int device) { if (_Devices == null) + { return; + } if (CConfig.Config.Record.MicConfig == null) + { return; + } if (CConfig.Config.Record.MicConfig[0].Channel <= 0) + { return; + } - for (int i = 0; i < _Devices.Count; i++) + for (var i = 0; i < _Devices.Count; i++) { if (_Devices[i].Name == CConfig.Config.Record.MicConfig[0].DeviceName && _Devices[i].Driver == CConfig.Config.Record.MicConfig[0].DeviceDriver) { @@ -460,12 +530,12 @@ namespace Vocaluxe.Screens } private void _LeaveScreen() - { + { if (_WarningStream != -1) { - CSound.Close(_WarningStream); + CSound.Close(_WarningStream); _WarningStream = -1; } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenOptionsServer.cs b/Vocaluxe/Screens/CScreenOptionsServer.cs index bf34cfcb..060d5684 100644 --- a/Vocaluxe/Screens/CScreenOptionsServer.cs +++ b/Vocaluxe/Screens/CScreenOptionsServer.cs @@ -15,13 +15,10 @@ // along with Vocaluxe. If not, see . #endregion -using System; using System.Windows.Forms; -using System.IO; using Vocaluxe.Base; using VocaluxeLib; using VocaluxeLib.Menu; -using Vocaluxe.Lib.Sound; namespace Vocaluxe.Screens { @@ -42,10 +39,10 @@ namespace Vocaluxe.Screens private int _WarningStream = -1; private bool _HasPlayedWarningSound = false; - + private static int PlaySound(ESounds sound, int volume) { - int streamId = CSound.PlaySound(sound, false); + var streamId = CSound.PlaySound(sound, false); CSound.SetStreamVolume(streamId, volume); return streamId; @@ -55,10 +52,10 @@ namespace Vocaluxe.Screens { base.Init(); - _ThemeButtons = new string[] {_ButtonExit, _ButtonServer}; - _ThemeSelectSlides = new string[] {_SelectSlideServerActive, _SelectSlideServerEncryption}; - _ThemeTexts = new string[] {_TextWarningRestart}; - _ThemeStatics = new string[] {_StaticWarningRestart}; + _ThemeButtons = new string[] { _ButtonExit, _ButtonServer }; + _ThemeSelectSlides = new string[] { _SelectSlideServerActive, _SelectSlideServerEncryption }; + _ThemeTexts = new string[] { _TextWarningRestart }; + _ThemeStatics = new string[] { _StaticWarningRestart }; } public override void LoadTheme(string xmlPath) @@ -91,7 +88,7 @@ namespace Vocaluxe.Screens _LeaveScreen(); break; - case Keys.Enter: + case Keys.Enter: if (_Buttons[_ButtonExit].Selected) { _SaveConfig(); @@ -102,6 +99,7 @@ namespace Vocaluxe.Screens { CGraphics.ShowPopup(EPopupScreens.PopupServerQR); } + break; case Keys.Left: @@ -112,6 +110,7 @@ namespace Vocaluxe.Screens _SaveConfig(); break; } + return true; } @@ -125,6 +124,7 @@ namespace Vocaluxe.Screens CGraphics.FadeTo(EScreen.Options); _LeaveScreen(); } + if (mouseEvent.LB && _IsMouseOverCurSelection(mouseEvent)) { if (_Buttons[_ButtonExit].Selected) @@ -137,7 +137,8 @@ namespace Vocaluxe.Screens { CGraphics.ShowPopup(EPopupScreens.PopupServerQR); } - } + } + return true; } @@ -145,22 +146,23 @@ namespace Vocaluxe.Screens { if (_Texts[_TextWarningRestart].Visible && !_HasPlayedWarningSound) { - _WarningStream = CScreenOptionsServer.PlaySound(ESounds.Warning, CConfig.SoundEffectVolume); - _HasPlayedWarningSound = true; + _WarningStream = CScreenOptionsServer.PlaySound(ESounds.Warning, CConfig.SoundEffectVolume); + _HasPlayedWarningSound = true; } + return true; } - + private void _SaveConfig() { // Detect server activation change - int _currentServerActive = (int)CConfig.Config.Server.ServerActive; - int _newServerActive = _SelectSlides[_SelectSlideServerActive].Selection; - + var _currentServerActive = (int)CConfig.Config.Server.ServerActive; + var _newServerActive = _SelectSlides[_SelectSlideServerActive].Selection; + if (_currentServerActive != _newServerActive) { _Texts[_TextWarningRestart].Visible = true; - _Statics[_StaticWarningRestart].Visible = true; + _Statics[_StaticWarningRestart].Visible = true; CConfig.Config.Server.ServerActive = (EOffOn)_newServerActive; } else @@ -169,30 +171,30 @@ namespace Vocaluxe.Screens } // Detect server encryption change - int _currentServerEncryption = (int)CConfig.Config.Server.ServerEncryption; - int _newServerEncryption = _SelectSlides[_SelectSlideServerEncryption].Selection; - + var _currentServerEncryption = (int)CConfig.Config.Server.ServerEncryption; + var _newServerEncryption = _SelectSlides[_SelectSlideServerEncryption].Selection; + if (_currentServerEncryption != _newServerEncryption) { _Texts[_TextWarningRestart].Visible = true; - _Statics[_StaticWarningRestart].Visible = true; + _Statics[_StaticWarningRestart].Visible = true; CConfig.Config.Server.ServerEncryption = (EOffOn)_newServerEncryption; } else { CConfig.Config.Server.ServerEncryption = (EOffOn)_newServerEncryption; } - + CConfig.SaveConfig(); } private void _LeaveScreen() - { + { if (_WarningStream != -1) { - CSound.Close(_WarningStream); + CSound.Close(_WarningStream); _WarningStream = -1; } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenOptionsSound.cs b/Vocaluxe/Screens/CScreenOptionsSound.cs index 7f98e361..53a6fb96 100644 --- a/Vocaluxe/Screens/CScreenOptionsSound.cs +++ b/Vocaluxe/Screens/CScreenOptionsSound.cs @@ -46,9 +46,12 @@ namespace Vocaluxe.Screens { base.Init(); - _ThemeButtons = new string[] {_ButtonExit}; + _ThemeButtons = new string[] { _ButtonExit }; _ThemeSelectSlides = new string[] - {_SelectSlideBackgroundMusic, _SelectSlideBackgroundMusicVolume, _SelectSlideBackgroundMusicSource, _SelectSlidePreviewMusicVolume, _SelectSlideGameMusicVolume, _SelectSlideSoundEffectVolume, _SelectSlideKaraokeEffect}; + { + _SelectSlideBackgroundMusic, _SelectSlideBackgroundMusicVolume, _SelectSlideBackgroundMusicSource, _SelectSlidePreviewMusicVolume, _SelectSlideGameMusicVolume, + _SelectSlideSoundEffectVolume, _SelectSlideKaraokeEffect + }; } public override void LoadTheme(string xmlPath) @@ -56,18 +59,18 @@ namespace Vocaluxe.Screens base.LoadTheme(xmlPath); _SelectSlides[_SelectSlideBackgroundMusic].SetValues((int)CConfig.Config.Sound.BackgroundMusic); _SelectSlides[_SelectSlideBackgroundMusicVolume].AddValues(new string[] - {"0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"}); + { "0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100" }); _SelectSlides[_SelectSlideBackgroundMusicVolume].Selection = CConfig.BackgroundMusicVolume / 5; _SelectSlides[_SelectSlideBackgroundMusicSource].SetValues((int)CConfig.Config.Sound.BackgroundMusicSource); _SelectSlides[_SelectSlideBackgroundMusicSource].Selection = (int)CConfig.Config.Sound.BackgroundMusicSource; _SelectSlides[_SelectSlidePreviewMusicVolume].AddValues(new string[] - {"0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"}); + { "0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100" }); _SelectSlides[_SelectSlidePreviewMusicVolume].Selection = CConfig.PreviewMusicVolume / 5; _SelectSlides[_SelectSlideGameMusicVolume].AddValues(new string[] - {"0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"}); + { "0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100" }); _SelectSlides[_SelectSlideGameMusicVolume].Selection = CConfig.GameMusicVolume / 5; _SelectSlides[_SelectSlideSoundEffectVolume].AddValues(new string[] - {"0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"}); + { "0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100" }); _SelectSlides[_SelectSlideSoundEffectVolume].Selection = CConfig.SoundEffectVolume / 5; if (CConfig.Config.Sound.PlayBackLib == EPlaybackLib.GstreamerSharp) { @@ -80,7 +83,7 @@ namespace Vocaluxe.Screens { base.HandleInput(keyEvent); - if (keyEvent.KeyPressed) {} + if (keyEvent.KeyPressed) { } else { switch (keyEvent.Key) @@ -103,6 +106,7 @@ namespace Vocaluxe.Screens _SaveConfig(); CGraphics.FadeTo(EScreen.Options); } + break; case Keys.Left: @@ -114,6 +118,7 @@ namespace Vocaluxe.Screens break; } } + return true; } @@ -126,19 +131,26 @@ namespace Vocaluxe.Screens _SaveConfig(); CGraphics.FadeTo(EScreen.Options); } + if (mouseEvent.LB && _IsMouseOverCurSelection(mouseEvent)) { _SaveConfig(); if (_Buttons[_ButtonExit].Selected) + { CGraphics.FadeTo(EScreen.Options); + } } + return true; } public override bool UpdateGame() { if (_BackgroundMusicVolume != CConfig.BackgroundMusicVolume) + { _SelectSlides[_SelectSlideBackgroundMusicVolume].Selection = CConfig.BackgroundMusicVolume / 5; + } + return true; } @@ -164,14 +176,19 @@ namespace Vocaluxe.Screens { CConfig.Config.Sound.KaraokeEffect = (EOffOn)_SelectSlides[_SelectSlideKaraokeEffect].Selection; } + CConfig.SaveConfig(); CBackgroundMusic.SetMusicSource(CConfig.Config.Sound.BackgroundMusicSource); CSound.SetGlobalVolume(CConfig.BackgroundMusicVolume); if (CConfig.Config.Sound.BackgroundMusic == EBackgroundMusicOffOn.TR_CONFIG_ON) + { CBackgroundMusic.Play(); + } else + { CBackgroundMusic.Stop(); + } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenOptionsTheme.cs b/Vocaluxe/Screens/CScreenOptionsTheme.cs index 7beb9a15..7c717a41 100644 --- a/Vocaluxe/Screens/CScreenOptionsTheme.cs +++ b/Vocaluxe/Screens/CScreenOptionsTheme.cs @@ -49,18 +49,18 @@ namespace Vocaluxe.Screens { base.Init(); - _ThemeButtons = new string[] {_ButtonExit}; + _ThemeButtons = new string[] { _ButtonExit }; _ThemeSelectSlides = new string[] - { - _SelectSlideTheme, - _SelectSlideSkin, - _SelectSlideCover, - _SelectSlideNoteLines, - _SelectSlideToneHelper, - _SelectSlideTimerLook, - _SelectSlideFadeInfo, - _SelectSlideCoverLoading - }; + { + _SelectSlideTheme, + _SelectSlideSkin, + _SelectSlideCover, + _SelectSlideNoteLines, + _SelectSlideToneHelper, + _SelectSlideTimerLook, + _SelectSlideFadeInfo, + _SelectSlideCoverLoading + }; } public override void LoadTheme(string xmlPath) @@ -80,7 +80,7 @@ namespace Vocaluxe.Screens { base.HandleInput(keyEvent); - if (keyEvent.KeyPressed) {} + if (keyEvent.KeyPressed) { } else { switch (keyEvent.Key) @@ -98,7 +98,10 @@ namespace Vocaluxe.Screens case Keys.Enter: if (_Buttons[_ButtonExit].Selected) + { _Close(); + } + break; case Keys.Left: @@ -110,6 +113,7 @@ namespace Vocaluxe.Screens break; } } + return true; } @@ -118,15 +122,22 @@ namespace Vocaluxe.Screens base.HandleMouse(mouseEvent); if (mouseEvent.RB) + { _Close(); + } if (mouseEvent.LB && _IsMouseOverCurSelection(mouseEvent)) { if (_Buttons[_ButtonExit].Selected) + { _Close(); + } else + { _OnChange(); + } } + return true; } @@ -173,7 +184,9 @@ namespace Vocaluxe.Screens CConfig.SaveConfig(); if (_OldCoverTheme != _SelectSlides[_SelectSlideCover].SelectedValue) + { CCover.ReloadCovers(); + } } private void _OnChange() diff --git a/Vocaluxe/Screens/CScreenOptionsVideo.cs b/Vocaluxe/Screens/CScreenOptionsVideo.cs index e06a755f..5f7e9f82 100644 --- a/Vocaluxe/Screens/CScreenOptionsVideo.cs +++ b/Vocaluxe/Screens/CScreenOptionsVideo.cs @@ -20,9 +20,9 @@ using System.Windows.Forms; using Vocaluxe.Base; using Vocaluxe.Lib.Webcam; using VocaluxeLib; -using VocaluxeLib.Menu; using VocaluxeLib.Draw; using VocaluxeLib.Log; +using VocaluxeLib.Menu; namespace Vocaluxe.Screens { @@ -58,14 +58,14 @@ namespace Vocaluxe.Screens { base.Init(); - _ThemeStatics = new string[] {_StaticWebcamOutput}; - _ThemeButtons = new string[] {_ButtonExit, _ButtonScreenAdjustments}; + _ThemeStatics = new string[] { _StaticWebcamOutput }; + _ThemeButtons = new string[] { _ButtonExit, _ButtonScreenAdjustments }; _ThemeSelectSlides = new string[] - { - _SelectSlideVideoBackgrounds, _SelectSlideVideoPreview, _SelectSlideVideosInSongs, _SelectSlideVideosToBackground, _SelectSlideWebcamDevices, - _SelectSlideWebcamCapabilities - }; - _ThemeTexts = new string[] {_TextWebcams, _TextWebcamResolution}; + { + _SelectSlideVideoBackgrounds, _SelectSlideVideoPreview, _SelectSlideVideosInSongs, _SelectSlideVideosToBackground, _SelectSlideWebcamDevices, + _SelectSlideWebcamCapabilities + }; + _ThemeTexts = new string[] { _TextWebcams, _TextWebcamResolution }; } public override void LoadTheme(string xmlPath) @@ -83,7 +83,7 @@ namespace Vocaluxe.Screens { base.HandleInput(keyEvent); - if (keyEvent.KeyPressed) {} + if (keyEvent.KeyPressed) { } else { switch (keyEvent.Key) @@ -111,25 +111,39 @@ namespace Vocaluxe.Screens _SaveConfig(); CGraphics.FadeTo(EScreen.OptionsVideoAdjustments); } + break; case Keys.Left: if (_SelectSlides[_SelectSlideWebcamDevices].Selected) + { _OnDeviceEvent(); + } + if (_SelectSlides[_SelectSlideWebcamCapabilities].Selected) + { _OnCapabilitiesEvent(); + } + _SaveConfig(); break; case Keys.Right: if (_SelectSlides[_SelectSlideWebcamDevices].Selected) + { _OnDeviceEvent(); + } + if (_SelectSlides[_SelectSlideWebcamCapabilities].Selected) + { _OnCapabilitiesEvent(); + } + _SaveConfig(); break; } } + return true; } @@ -146,22 +160,37 @@ namespace Vocaluxe.Screens if (mouseEvent.LB && _IsMouseOverCurSelection(mouseEvent)) { if (_SelectSlides[_SelectSlideWebcamDevices].Selected) + { _OnDeviceEvent(); + } + if (_SelectSlides[_SelectSlideWebcamCapabilities].Selected) + { _OnCapabilitiesEvent(); + } + _SaveConfig(); if (_Buttons[_ButtonExit].Selected) + { CGraphics.FadeTo(EScreen.Options); + } + if (_Buttons[_ButtonScreenAdjustments].Selected) + { CGraphics.FadeTo(EScreen.OptionsVideoAdjustments); + } } + return true; } public override bool UpdateGame() { if (CWebcam.GetFrame(ref _WebcamTexture)) + { _Statics[_StaticWebcamOutput].Texture = _WebcamTexture; + } + _SelectSlides[_SelectSlideVideosToBackground].Selection = (int)CConfig.Config.Video.VideosToBackground; return true; } @@ -181,15 +210,17 @@ namespace Vocaluxe.Screens _DeviceNr = -1; _CapabilityNr = -1; - SWebcamDevice[] devices = CWebcam.GetDevices(); + var devices = CWebcam.GetDevices(); - bool ssVisible = false; + var ssVisible = false; try { if (devices != null && devices.Length > 0) { - foreach (SWebcamDevice d in devices) + foreach (var d in devices) + { _SelectSlides[_SelectSlideWebcamDevices].AddValue(d.Name); + } int devNr; int capNr; @@ -236,12 +267,13 @@ namespace Vocaluxe.Screens _SelectSlides[_SelectSlideWebcamCapabilities].Clear(); _DeviceNr = _SelectSlides[_SelectSlideWebcamDevices].Selection; - SWebcamDevice d = CWebcam.GetDevices()[_DeviceNr]; - for (int i = 0; i < d.Capabilities.Count; i++) + var d = CWebcam.GetDevices()[_DeviceNr]; + for (var i = 0; i < d.Capabilities.Count; i++) { _SelectSlides[_SelectSlideWebcamCapabilities].AddValue(d.Capabilities[i].Width + " x " + d.Capabilities[i].Height + " @ " + d.Capabilities[i].Framerate + "FPS"); } + _CapabilityNr = -1; _OnCapabilitiesEvent(); } @@ -253,20 +285,22 @@ namespace Vocaluxe.Screens { _CapabilityNr = _SelectSlides[_SelectSlideWebcamCapabilities].Selection; - SWebcamDevice d = CWebcam.GetDevices()[_DeviceNr]; + var d = CWebcam.GetDevices()[_DeviceNr]; _Config.MonikerString = d.MonikerString; _Config.Width = d.Capabilities[_CapabilityNr].Width; _Config.Height = d.Capabilities[_CapabilityNr].Height; _Config.Framerate = d.Capabilities[_CapabilityNr].Framerate; if (CWebcam.Select(_Config)) + { CWebcam.Start(); + } } } private bool _GetFirstConfiguredWebcamDevice(out int device, out int capabilities) { - SWebcamDevice[] devices = CWebcam.GetDevices(); + var devices = CWebcam.GetDevices(); if (devices == null) { @@ -274,12 +308,16 @@ namespace Vocaluxe.Screens capabilities = -1; return false; } - SWebcamConfig curConfig = CConfig.Config.Video.WebcamConfig.HasValue ? CConfig.Config.Video.WebcamConfig.Value : new SWebcamConfig(); - for (int i = 0; i < devices.Length; i++) + + var curConfig = CConfig.Config.Video.WebcamConfig.HasValue ? CConfig.Config.Video.WebcamConfig.Value : new SWebcamConfig(); + for (var i = 0; i < devices.Length; i++) { if (devices[i].MonikerString != curConfig.MonikerString) + { continue; - for (int j = 0; j < devices[i].Capabilities.Count; j++) + } + + for (var j = 0; j < devices[i].Capabilities.Count; j++) { if (devices[i].Capabilities[j].Framerate == curConfig.Framerate && devices[i].Capabilities[j].Width == curConfig.Width && @@ -291,6 +329,7 @@ namespace Vocaluxe.Screens } } } + device = 0; capabilities = 0; return true; diff --git a/Vocaluxe/Screens/CScreenOptionsVideoAdjustments.cs b/Vocaluxe/Screens/CScreenOptionsVideoAdjustments.cs index b030b14e..9ce6cb33 100644 --- a/Vocaluxe/Screens/CScreenOptionsVideoAdjustments.cs +++ b/Vocaluxe/Screens/CScreenOptionsVideoAdjustments.cs @@ -36,14 +36,14 @@ namespace Vocaluxe.Screens { base.Init(); - _ThemeButtons = new string[] {_ButtonExit}; + _ThemeButtons = new string[] { _ButtonExit }; } public override bool HandleInput(SKeyEvent keyEvent) { base.HandleInput(keyEvent); - if (keyEvent.KeyPressed) {} + if (keyEvent.KeyPressed) { } else { switch (keyEvent.Key) @@ -66,9 +66,11 @@ namespace Vocaluxe.Screens _SaveConfig(); CGraphics.FadeTo(EScreen.OptionsVideo); } + break; } } + return true; } @@ -86,8 +88,11 @@ namespace Vocaluxe.Screens { _SaveConfig(); if (_Buttons[_ButtonExit].Selected) + { CGraphics.FadeTo(EScreen.OptionsVideo); + } } + return true; } diff --git a/Vocaluxe/Screens/CScreenParty.cs b/Vocaluxe/Screens/CScreenParty.cs index 7b11c376..8026beae 100644 --- a/Vocaluxe/Screens/CScreenParty.cs +++ b/Vocaluxe/Screens/CScreenParty.cs @@ -20,7 +20,6 @@ using System.Windows.Forms; using Vocaluxe.Base; using VocaluxeLib; using VocaluxeLib.Menu; -using VocaluxeLib.PartyModes; namespace Vocaluxe.Screens { @@ -49,16 +48,16 @@ namespace Vocaluxe.Screens { base.Init(); - _ThemeTexts = new string[] {_TextDescription, _TextTargetAudience, _TextNumTeams, _TextNumPlayers, _TextAuthor, _TextVersion, _TextError}; - _ThemeButtons = new string[] {_ButtonStart, _ButtonExit}; - _ThemeSelectSlides = new string[] {_SelectSlideModes}; + _ThemeTexts = new string[] { _TextDescription, _TextTargetAudience, _TextNumTeams, _TextNumPlayers, _TextAuthor, _TextVersion, _TextError }; + _ThemeButtons = new string[] { _ButtonStart, _ButtonExit }; + _ThemeSelectSlides = new string[] { _SelectSlideModes }; } public override bool HandleInput(SKeyEvent keyEvent) { base.HandleInput(keyEvent); - if (keyEvent.KeyPressed) {} + if (keyEvent.KeyPressed) { } else { switch (keyEvent.Key) @@ -70,19 +69,28 @@ namespace Vocaluxe.Screens case Keys.Enter: if (_Buttons[_ButtonStart].Selected) + { _StartPartyMode(); + } if (_Buttons[_ButtonExit].Selected) + { CGraphics.FadeTo(EScreen.Main); + } + break; case Keys.Left: case Keys.Right: if (_SelectSlides[_SelectSlideModes].Selected) + { _UpdateSelection(); + } + break; } } + return true; } @@ -93,17 +101,25 @@ namespace Vocaluxe.Screens if (mouseEvent.LB && _IsMouseOverCurSelection(mouseEvent)) { if (_Buttons[_ButtonStart].Selected) + { _StartPartyMode(); + } if (_Buttons[_ButtonExit].Selected) + { CGraphics.FadeTo(EScreen.Main); + } if (_SelectSlides[_SelectSlideModes].Selected) + { _UpdateSelection(); + } } if (mouseEvent.RB) + { CGraphics.FadeTo(EScreen.Main); + } return true; } @@ -115,8 +131,11 @@ namespace Vocaluxe.Screens _PartyModeInfos = CParty.GetPartyModeInfos(); _SelectSlides[_SelectSlideModes].Clear(); - foreach (SPartyModeInfos info in _PartyModeInfos) - _SelectSlides[_SelectSlideModes].AddValue(info.Name, info.ExtInfo.ID); + foreach (var info in _PartyModeInfos) + { + _SelectSlides[_SelectSlideModes].AddValue(info.Name, info.ExtInfo.Id); + } + _SelectSlides[_SelectSlideModes].Selection = 0; _UpdateSelection(); @@ -131,9 +150,11 @@ namespace Vocaluxe.Screens private void _UpdateSelection() { if (_PartyModeInfos.Count == 0) + { return; + } - int index = _SelectSlides[_SelectSlideModes].Selection; + var index = _SelectSlides[_SelectSlideModes].Selection; if (index >= _PartyModeInfos.Count) { index = 0; @@ -141,42 +162,52 @@ namespace Vocaluxe.Screens } //Description - SPartyModeInfos infos = _PartyModeInfos[index]; - IPartyModeInfo extInfo = infos.ExtInfo; + var infos = _PartyModeInfos[index]; + var extInfo = infos.ExtInfo; _Texts[_TextDescription].Text = infos.Description; - _Texts[_TextDescription].TranslationID = extInfo.ID; + _Texts[_TextDescription].TranslationId = extInfo.Id; //TargetAudience - _Texts[_TextTargetAudience].TranslationID = extInfo.ID; + _Texts[_TextTargetAudience].TranslationId = extInfo.Id; _Texts[_TextTargetAudience].Text = infos.TargetAudience; //NumTeams if (extInfo.MaxTeams == 1) + { _Texts[_TextNumTeams].Text = "TR_SCREENPARTY_NOTEAMS"; + } else if (extInfo.MaxTeams == extInfo.MinTeams) + { _Texts[_TextNumTeams].Text = extInfo.MaxTeams.ToString(); + } else + { _Texts[_TextNumTeams].Text = extInfo.MinTeams + " - " + extInfo.MaxTeams; + } //NumPlayers if (extInfo.MaxPlayers == extInfo.MinPlayers) + { _Texts[_TextNumPlayers].Text = extInfo.MaxTeams.ToString(); + } else + { _Texts[_TextNumPlayers].Text = extInfo.MinPlayers + " - " + extInfo.MaxPlayers; + } //Author _Texts[_TextAuthor].Text = infos.Author; - _Texts[_TextAuthor].TranslationID = extInfo.ID; + _Texts[_TextAuthor].TranslationId = extInfo.Id; //Version _Texts[_TextVersion].Text = infos.VersionMajor + "." + infos.VersionMinor; - _Texts[_TextVersion].TranslationID = extInfo.ID; + _Texts[_TextVersion].TranslationId = extInfo.Id; if (CConfig.GetMaxNumMics() < extInfo.MinMics) { _Buttons[_ButtonStart].Visible = false; _Texts[_TextError].Text = CConfig.GetMaxNumMics() == 0 - ? "TR_SCREENPARTY_ERROR_MICS" : CLanguage.Translate("TR_SCREENPARTY_ERROR_MIC_NUM").Replace("%d", extInfo.MinMics.ToString()); + ? "TR_SCREENPARTY_ERROR_MICS" : CLanguage.Translate("TR_SCREENPARTY_ERROR_MIC_NUM").Replace("%d", extInfo.MinMics.ToString()); _Texts[_TextError].Visible = true; } else @@ -189,9 +220,11 @@ namespace Vocaluxe.Screens private void _StartPartyMode() { if (_PartyModeInfos.Count == 0) + { return; + } - int index = _SelectSlides[_SelectSlideModes].Selection; + var index = _SelectSlides[_SelectSlideModes].Selection; if (index >= _PartyModeInfos.Count) { _Buttons[_ButtonStart].Visible = false; @@ -200,7 +233,7 @@ namespace Vocaluxe.Screens return; } - CParty.SetPartyMode(_PartyModeInfos[index].ExtInfo.ID); + CParty.SetPartyMode(_PartyModeInfos[index].ExtInfo.Id); CGraphics.FadeTo(CParty.GetStartScreen()); } } diff --git a/Vocaluxe/Screens/CScreenProfiles.cs b/Vocaluxe/Screens/CScreenProfiles.cs index 88ef1767..074799bc 100644 --- a/Vocaluxe/Screens/CScreenProfiles.cs +++ b/Vocaluxe/Screens/CScreenProfiles.cs @@ -16,17 +16,17 @@ #endregion using System; -using System.Linq; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; +using System.Linq; using System.Windows.Forms; using Vocaluxe.Base; using VocaluxeLib; +using VocaluxeLib.Draw; using VocaluxeLib.Menu; using VocaluxeLib.Profile; -using VocaluxeLib.Draw; namespace Vocaluxe.Screens { @@ -76,9 +76,9 @@ namespace Vocaluxe.Screens base.Init(); _ThemeButtons = new string[] - {_ButtonPlayerName, _ButtonExit, _ButtonSave, _ButtonNew, _ButtonDelete, _ButtonWebcam, _ButtonSaveSnapshot, _ButtonDiscardSnapshot, _ButtonTakeSnapshot}; - _ThemeSelectSlides = new string[] {_SelectSlideProfiles, _SelectSlideDifficulty, _SelectSlideAvatars, _SelectSlideUserRole, _SelectSlideActive}; - _ThemeStatics = new string[] {_StaticAvatar}; + { _ButtonPlayerName, _ButtonExit, _ButtonSave, _ButtonNew, _ButtonDelete, _ButtonWebcam, _ButtonSaveSnapshot, _ButtonDiscardSnapshot, _ButtonTakeSnapshot }; + _ThemeSelectSlides = new string[] { _SelectSlideProfiles, _SelectSlideDifficulty, _SelectSlideAvatars, _SelectSlideUserRole, _SelectSlideActive }; + _ThemeStatics = new string[] { _StaticAvatar }; _ThemeNameSelections = new string[] { _NameSelection }; _EditMode = EEditMode.None; @@ -115,37 +115,43 @@ namespace Vocaluxe.Screens _NameSelections[_NameSelection].HandleInput(keyEvent); return true; - case Keys.Enter: - if (_NameSelections[_NameSelection].SelectedID != Guid.Empty) - _SelectProfileById(_NameSelections[_NameSelection].SelectedID); + case Keys.Enter: + if (_NameSelections[_NameSelection].SelectedId != Guid.Empty) + { + _SelectProfileById(_NameSelections[_NameSelection].SelectedId); + } - _NameSelections[_NameSelection].FastSelection(false, -1); - _SelectingKeyboardActive = false; - _SelectElement(_Buttons[_ButtonPlayerName]); - return true; + _NameSelections[_NameSelection].FastSelection(false, -1); + _SelectingKeyboardActive = false; + _SelectElement(_Buttons[_ButtonPlayerName]); + return true; - case Keys.Escape: - case Keys.Back: - _NameSelections[_NameSelection].FastSelection(false, -1); - _SelectingKeyboardActive = false; - _SelectElement(_Buttons[_ButtonExit]); - return true; + case Keys.Escape: + case Keys.Back: + _NameSelections[_NameSelection].FastSelection(false, -1); + _SelectingKeyboardActive = false; + _SelectElement(_Buttons[_ButtonExit]); + return true; } } if (_EditMode == EEditMode.None && keyEvent.Key == Keys.Up && _Buttons[_ButtonExit].Selected) { if (CProfiles.NumProfiles <= 0) + { return true; - + } + _SelectingKeyboardActive = true; _NameSelections[_NameSelection].Init(); _NameSelections[_NameSelection].UpdateList(); _NameSelections[_NameSelection].FastSelection(true, 1); } - + if (_EditMode == EEditMode.None) + { base.HandleInput(keyEvent); + } if (keyEvent.KeyPressed && !Char.IsControl(keyEvent.Unicode)) { @@ -166,35 +172,61 @@ namespace Vocaluxe.Screens { case Keys.Escape: if (_EditMode == EEditMode.PlayerName) + { _EditMode = EEditMode.None; + } else + { CGraphics.FadeTo(EScreen.Main); + } + break; case Keys.Enter: if (_Buttons[_ButtonExit].Selected) + { CGraphics.FadeTo(EScreen.Main); + } else if (_Buttons[_ButtonSave].Selected) + { _SaveProfiles(); + } else if (_Buttons[_ButtonNew].Selected) + { _NewProfile(); + } else if (_Buttons[_ButtonPlayerName].Selected) { if (CProfiles.NumProfiles > 0 && _EditMode != EEditMode.PlayerName) + { _EditMode = EEditMode.PlayerName; + } else + { _EditMode = EEditMode.None; + } } else if (_Buttons[_ButtonDelete].Selected) + { _DeleteProfile(); + } else if (_Buttons[_ButtonWebcam].Selected) + { _OnWebcam(); + } else if (_Buttons[_ButtonSaveSnapshot].Selected) + { _OnSaveSnapshot(); + } else if (_Buttons[_ButtonDiscardSnapshot].Selected) + { _OnDiscardSnapshot(); + } else if (_Buttons[_ButtonTakeSnapshot].Selected) + { _OnTakeSnapshot(); + } + break; case Keys.Back: @@ -205,32 +237,36 @@ namespace Vocaluxe.Screens _ProfilesChanged = true; } else + { CGraphics.FadeTo(EScreen.Main); + } + break; case Keys.Delete: _DeleteProfile(); break; } + if (_SelectSlides[_SelectSlideDifficulty].Selected) { CProfiles.SetDifficulty(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag), - (EGameDifficulty)_SelectSlides[_SelectSlideDifficulty].Selection); + (EGameDifficulty)_SelectSlides[_SelectSlideDifficulty].Selection); } else if (_SelectSlides[_SelectSlideAvatars].Selected) { CProfiles.SetAvatar(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag), - _SelectSlides[_SelectSlideAvatars].SelectedTag); + _SelectSlides[_SelectSlideAvatars].SelectedTag); } else if (_SelectSlides[_SelectSlideUserRole].Selected) { CProfiles.SetUserRoleProfile(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag), - (EUserRole)_SelectSlides[_SelectSlideUserRole].Selection); + (EUserRole)_SelectSlides[_SelectSlideUserRole].Selection); } else if (_SelectSlides[_SelectSlideActive].Selected) { CProfiles.SetActive(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag), - (EOffOn)_SelectSlides[_SelectSlideActive].Selection); + (EOffOn)_SelectSlides[_SelectSlideActive].Selection); } } @@ -240,13 +276,15 @@ namespace Vocaluxe.Screens public override bool HandleMouse(SMouseEvent mouseEvent) { if (_EditMode == EEditMode.None) + { base.HandleMouse(mouseEvent); + } _NameSelections[_NameSelection].HandleMouse(mouseEvent); if (mouseEvent.LB && _NameSelections[_NameSelection].IsOverTile(mouseEvent)) { - Guid profileId = _NameSelections[_NameSelection].TilePlayerID(mouseEvent); + var profileId = _NameSelections[_NameSelection].TilePlayerId(mouseEvent); _SelectProfileById(profileId); return true; } @@ -254,61 +292,85 @@ namespace Vocaluxe.Screens if (mouseEvent.LB && _IsMouseOverCurSelection(mouseEvent)) { if (_Buttons[_ButtonExit].Selected) + { CGraphics.FadeTo(EScreen.Main); + } else if (_Buttons[_ButtonSave].Selected) + { _SaveProfiles(); + } else if (_Buttons[_ButtonNew].Selected) + { _NewProfile(); + } else if (_Buttons[_ButtonDelete].Selected) + { _DeleteProfile(); + } else if (_Buttons[_ButtonPlayerName].Selected) { if (CProfiles.NumProfiles > 0 && _EditMode != EEditMode.PlayerName) + { _EditMode = EEditMode.PlayerName; + } else + { _EditMode = EEditMode.None; + } } else if (_SelectSlides[_SelectSlideDifficulty].Selected) { CProfiles.SetDifficulty(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag), - (EGameDifficulty)_SelectSlides[_SelectSlideDifficulty].Selection); + (EGameDifficulty)_SelectSlides[_SelectSlideDifficulty].Selection); } else if (_SelectSlides[_SelectSlideAvatars].Selected) { CProfiles.SetAvatar(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag), - _SelectSlides[_SelectSlideAvatars].SelectedTag); + _SelectSlides[_SelectSlideAvatars].SelectedTag); if (CWebcam.IsDeviceAvailable() && _WebcamTexture != null) + { _OnDiscardSnapshot(); + } } else if (_SelectSlides[_SelectSlideUserRole].Selected) { CProfiles.SetUserRoleProfile(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag), - (EUserRole)_SelectSlides[_SelectSlideUserRole].Selection); + (EUserRole)_SelectSlides[_SelectSlideUserRole].Selection); } else if (_SelectSlides[_SelectSlideActive].Selected) { CProfiles.SetActive(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag), - (EOffOn)_SelectSlides[_SelectSlideActive].Selection); + (EOffOn)_SelectSlides[_SelectSlideActive].Selection); } else if (_Buttons[_ButtonWebcam].Selected) + { _OnWebcam(); + } else if (_Buttons[_ButtonSaveSnapshot].Selected) + { _OnSaveSnapshot(); + } else if (_Buttons[_ButtonDiscardSnapshot].Selected) + { _OnDiscardSnapshot(); + } else if (_Buttons[_ButtonTakeSnapshot].Selected) + { _OnTakeSnapshot(); + } } if (mouseEvent.RB) + { CGraphics.FadeTo(EScreen.Main); - + } + if (mouseEvent.Wheel != 0 && CHelper.IsInBounds(_NameSelections[_NameSelection].Rect, mouseEvent)) { - int offset = _NameSelections[_NameSelection].Offset + mouseEvent.Wheel; + var offset = _NameSelections[_NameSelection].Offset + mouseEvent.Wheel; _NameSelections[_NameSelection].UpdateList(offset); } - + return true; } @@ -330,23 +392,29 @@ namespace Vocaluxe.Screens { _Buttons[_ButtonPlayerName].Text.Text = CProfiles.GetPlayerName(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag)); if (_EditMode == EEditMode.PlayerName) + { _Buttons[_ButtonPlayerName].Text.Text += "|"; + } _SelectSlides[_SelectSlideDifficulty].Selection = (int)CProfiles.GetDifficulty(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag)); _SelectSlides[_SelectSlideUserRole].Selection = (int)CProfiles.GetUserRoleProfile(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag)); _SelectSlides[_SelectSlideActive].Selection = (int)CProfiles.GetActive(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag)); - int avatarID = CProfiles.GetAvatarID(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag)); - _SelectSlides[_SelectSlideAvatars].SelectedTag = avatarID; + var avatarId = CProfiles.GetAvatarId(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag)); + _SelectSlides[_SelectSlideAvatars].SelectedTag = avatarId; if (_Snapshot == null) { if (CWebcam.IsCapturing()) { if (CWebcam.GetFrame(ref _WebcamTexture)) + { _Statics[_StaticAvatar].Texture = _WebcamTexture; + } } else - _Statics[_StaticAvatar].Texture = CProfiles.GetAvatarTexture(avatarID); + { + _Statics[_StaticAvatar].Texture = CProfiles.GetAvatarTexture(avatarId); + } } } @@ -373,10 +441,14 @@ namespace Vocaluxe.Screens private void _OnProfileChanged(EProfileChangedFlags flags) { if (EProfileChangedFlags.Avatar == (EProfileChangedFlags.Avatar & flags)) + { _AvatarsChanged = true; + } if (EProfileChangedFlags.Profile == (EProfileChangedFlags.Profile & flags)) + { _ProfilesChanged = true; + } } private void _OnTakeSnapshot() @@ -397,7 +469,10 @@ namespace Vocaluxe.Screens CWebcam.Stop(); //Do this first to get consistent frame and bitmap _Snapshot = CWebcam.GetBitmap(); if (CWebcam.GetFrame(ref _WebcamTexture)) + { _Statics[_StaticAvatar].Texture = _WebcamTexture; + } + _Buttons[_ButtonSaveSnapshot].Visible = true; _Buttons[_ButtonDiscardSnapshot].Visible = true; _Buttons[_ButtonTakeSnapshot].Visible = false; @@ -421,7 +496,7 @@ namespace Vocaluxe.Screens private void _OnSaveSnapshot() { - string file = CHelper.GetUniqueFileName(Path.Combine(CSettings.DataFolder, CConfig.ProfileFolders[0]), "snapshot.png"); + var file = CHelper.GetUniqueFileName(Path.Combine(CSettings.DataFolder, CConfig.ProfileFolders[0]), "snapshot.png"); _Snapshot.Save(file, ImageFormat.Png); _Snapshot = null; @@ -432,7 +507,7 @@ namespace Vocaluxe.Screens _Buttons[_ButtonTakeSnapshot].Visible = false; _Buttons[_ButtonWebcam].Visible = CWebcam.IsDeviceAvailable(); - int id = CProfiles.NewAvatar(file); + var id = CProfiles.NewAvatar(file); CProfiles.SetAvatar(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag), id); _LoadAvatars(false); _NameSelections[_NameSelection].UpdateList(); @@ -447,6 +522,7 @@ namespace Vocaluxe.Screens _Buttons[_ButtonWebcam].Visible = false; return; } + _Snapshot = null; CWebcam.Start(); _Buttons[_ButtonSaveSnapshot].Visible = false; @@ -460,9 +536,9 @@ namespace Vocaluxe.Screens private void _NewProfile() { _EditMode = EEditMode.None; - Guid id = CProfiles.NewProfile(); + var id = CProfiles.NewProfile(); _LoadProfiles(false); - int num = CProfiles.NumProfiles; + var num = CProfiles.NumProfiles; _SelectSlides[_SelectSlideProfiles].SelectedTag = num; _SelectSlideGuids.Add(num, id); @@ -489,48 +565,56 @@ namespace Vocaluxe.Screens _SelectSlideGuids.Remove(_SelectSlides[_SelectSlideProfiles].SelectedTag); _NameSelections[_NameSelection].UpdateList(); - int selection = _SelectSlides[_SelectSlideProfiles].Selection; + var selection = _SelectSlides[_SelectSlideProfiles].Selection; if (_SelectSlides[_SelectSlideProfiles].NumValues - 1 > selection) + { _SelectSlides[_SelectSlideProfiles].Selection = selection + 1; + } else + { _SelectSlides[_SelectSlideProfiles].Selection = selection - 1; + } } private void _LoadProfiles(bool keep) { - string name = String.Empty; + var name = string.Empty; if (_EditMode == EEditMode.PlayerName) + { name = CProfiles.GetPlayerName(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag)); + } - Guid selectedProfileID = _GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag); + var selectedProfileId = _GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag); _SelectSlides[_SelectSlideProfiles].Clear(); _SelectSlideGuids.Clear(); - CProfile[] profiles = CProfiles.GetProfiles(); - int i = 0; - foreach (CProfile profile in profiles) + var profiles = CProfiles.GetProfiles(); + var i = 0; + foreach (var profile in profiles) { _SelectSlides[_SelectSlideProfiles].AddValue(profile.PlayerName, null, i); - _SelectSlideGuids.Add(i, profile.ID); + _SelectSlideGuids.Add(i, profile.Id); i++; } if (CProfiles.NumProfiles > 0 && CProfiles.NumAvatars > 0) { - if (selectedProfileID != Guid.Empty) - _SelectSlides[_SelectSlideProfiles].SelectedTag = _SelectSlideGuids.FirstOrDefault(x => x.Value.Equals(selectedProfileID)).Key; + if (selectedProfileId != Guid.Empty) + { + _SelectSlides[_SelectSlideProfiles].SelectedTag = _SelectSlideGuids.FirstOrDefault(x => x.Value.Equals(selectedProfileId)).Key; + } else { _SelectSlides[_SelectSlideProfiles].Selection = 0; - selectedProfileID = _GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag); + selectedProfileId = _GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag); } if (!keep) { - _SelectSlides[_SelectSlideDifficulty].Selection = (int)CProfiles.GetDifficulty(selectedProfileID); - _SelectSlides[_SelectSlideUserRole].Selection = (int)CProfiles.GetUserRoleProfile(selectedProfileID); - _SelectSlides[_SelectSlideActive].Selection = (int)CProfiles.GetActive(selectedProfileID); - _SelectSlides[_SelectSlideAvatars].SelectedTag = CProfiles.GetAvatarID(selectedProfileID); + _SelectSlides[_SelectSlideDifficulty].Selection = (int)CProfiles.GetDifficulty(selectedProfileId); + _SelectSlides[_SelectSlideUserRole].Selection = (int)CProfiles.GetUserRoleProfile(selectedProfileId); + _SelectSlides[_SelectSlideActive].Selection = (int)CProfiles.GetActive(selectedProfileId); + _SelectSlides[_SelectSlideAvatars].SelectedTag = CProfiles.GetAvatarId(selectedProfileId); } if (_EditMode == EEditMode.PlayerName) @@ -539,27 +623,32 @@ namespace Vocaluxe.Screens _NameSelections[_NameSelection].UpdateList(); } } + _ProfilesChanged = false; } private void _LoadAvatars(bool keep) { - int selectedAvatarID = _SelectSlides[_SelectSlideAvatars].SelectedTag; + var selectedAvatarId = _SelectSlides[_SelectSlideAvatars].SelectedTag; _SelectSlides[_SelectSlideAvatars].Clear(); - IEnumerable avatars = CProfiles.GetAvatars(); + var avatars = CProfiles.GetAvatars(); if (avatars != null) { - foreach (CAvatar avatar in avatars) - _SelectSlides[_SelectSlideAvatars].AddValue(avatar.GetDisplayName(), null, avatar.ID); + foreach (var avatar in avatars) + { + _SelectSlides[_SelectSlideAvatars].AddValue(avatar.GetDisplayName(), null, avatar.Id); + } } if (keep) { - _SelectSlides[_SelectSlideAvatars].SelectedTag = selectedAvatarID; - CProfiles.SetAvatar(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag), selectedAvatarID); + _SelectSlides[_SelectSlideAvatars].SelectedTag = selectedAvatarId; + CProfiles.SetAvatar(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag), selectedAvatarId); } else - _SelectSlides[_SelectSlideAvatars].SelectedTag = CProfiles.GetAvatarID(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag)); + { + _SelectSlides[_SelectSlideAvatars].SelectedTag = CProfiles.GetAvatarId(_GetIdFromTag(_SelectSlides[_SelectSlideProfiles].SelectedTag)); + } _AvatarsChanged = false; } @@ -567,19 +656,27 @@ namespace Vocaluxe.Screens private void _SelectProfileById(Guid profileId) { if (profileId == Guid.Empty) + { return; + } - KeyValuePair entry = _SelectSlideGuids.FirstOrDefault(x => x.Value.Equals(profileId)); + var entry = _SelectSlideGuids.FirstOrDefault(x => x.Value.Equals(profileId)); if (_SelectSlideGuids.ContainsKey(entry.Key)) + { _SelectSlides[_SelectSlideProfiles].SelectedTag = entry.Key; + } } - + private Guid _GetIdFromTag(int tag) { if (tag == -1 || !_SelectSlideGuids.ContainsKey(tag)) + { return Guid.Empty; + } else + { return _SelectSlideGuids[tag]; + } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenScore.cs b/Vocaluxe/Screens/CScreenScore.cs index ed3a796e..ca5487ec 100644 --- a/Vocaluxe/Screens/CScreenScore.cs +++ b/Vocaluxe/Screens/CScreenScore.cs @@ -17,17 +17,15 @@ using System; using System.Collections.Generic; -using System.Diagnostics; -using System.Windows.Forms; using System.Linq; using System.Threading.Tasks; +using System.Windows.Forms; using Vocaluxe.Base; using Vocaluxe.Base.Server; using VocaluxeLib; using VocaluxeLib.Game; using VocaluxeLib.Menu; using VocaluxeLib.Songs; -using Vocaluxe.Lib.Sound; namespace Vocaluxe.Screens { @@ -65,7 +63,7 @@ namespace Vocaluxe.Screens { base.Init(); - var texts = new List {_TextSong}; + var texts = new List { _TextSong }; _BuildTextStrings(ref texts); @@ -81,7 +79,7 @@ namespace Vocaluxe.Screens _ThemeProgressBars = progressBars.ToArray(); - _ThemeScreenSettings = new string[] {_ScreenSettingShortScore, _ScreenSettingShortRating, _ScreenSettingShortDifficulty}; + _ThemeScreenSettings = new string[] { _ScreenSettingShortScore, _ScreenSettingShortRating, _ScreenSettingShortDifficulty }; _SlideShowBG = GetNewBackground(); _AddBackground(_SlideShowBG); @@ -90,7 +88,7 @@ namespace Vocaluxe.Screens public override bool HandleInput(SKeyEvent keyEvent) { - if (keyEvent.KeyPressed) {} + if (keyEvent.KeyPressed) { } else { switch (keyEvent.Key) @@ -110,6 +108,7 @@ namespace Vocaluxe.Screens break; } } + return true; } @@ -118,13 +117,19 @@ namespace Vocaluxe.Screens base.HandleMouse(mouseEvent); if (mouseEvent.Wheel != 0) + { _ChangeRound(mouseEvent.Wheel); + } if (mouseEvent.LB) + { _LeaveScreen(); + } if (mouseEvent.RB) + { _LeaveScreen(); + } return true; } @@ -142,26 +147,36 @@ namespace Vocaluxe.Screens _UpdateRatings(); _SlideShowBG.Visible = _UpdateBackground(); - for (int p = 0; p < CGame.NumPlayers; p++) + for (var p = 0; p < CGame.NumPlayers; p++) + { _Statics[_StaticAvatar[p, CGame.NumPlayers - 1]].Aspect = EAspect.Crop; + } } public override bool UpdateGame() { var players = new SPlayer[CGame.NumPlayers]; if (_Round >= 0) + { players = _Points.GetPlayer(_Round, CGame.NumPlayers); + } else { - for (int i = 0; i < CGame.NumRounds; i++) + for (var i = 0; i < CGame.NumRounds; i++) { - SPlayer[] points = _Points.GetPlayer(i, CGame.NumPlayers); - for (int p = 0; p < players.Length; p++) + var points = _Points.GetPlayer(i, CGame.NumPlayers); + for (var p = 0; p < players.Length; p++) + { players[p].Points += points[p].Points; + } } - for (int p = 0; p < players.Length; p++) + + for (var p = 0; p < players.Length; p++) + { players[p].Points = (int)(players[p].Points / CGame.NumRounds); + } } + return true; } @@ -170,41 +185,59 @@ namespace Vocaluxe.Screens string rating; if (CScreenSong.GetAudioMode() == EAudioMode.TR_AUDIOMODE_KARAOKE) - rating = "TR_RATING_KARAOKE"; + { + rating = "TR_RATING_KARAOKE"; + } else if (points >= 9800) + { rating = "TR_RATING_VOCAL_HERO"; + } else if (points >= 8400) + { rating = "TR_RATING_SUPERSTAR"; + } else if (points >= 7000) + { rating = "TR_RATING_LEAD_SINGER"; + } else if (points >= 5600) + { rating = "TR_RATING_RISING_STAR"; + } else if (points >= 4200) + { rating = "TR_RATING_HOPEFUL"; + } else if (points >= 2800) + { rating = "TR_RATING_WANNABE"; + } else if (points >= 1400) + { rating = "TR_RATING_AMATEUR"; + } else + { rating = "TR_RATING_TONE_DEAF"; + } return rating; } private void _BuildTextStrings(ref List texts) { - _TextNames = new string[CSettings.MaxNumPlayer,CSettings.MaxNumPlayer]; - _TextScores = new string[CSettings.MaxNumPlayer,CSettings.MaxNumPlayer]; - _TextRatings = new string[CSettings.MaxNumPlayer,CSettings.MaxNumPlayer]; - _TextDifficulty = new string[CSettings.MaxNumPlayer,CSettings.MaxNumPlayer]; + _TextNames = new string[CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; + _TextScores = new string[CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; + _TextRatings = new string[CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; + _TextDifficulty = new string[CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; - for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) + for (var numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { - for (int player = 0; player < CSettings.MaxNumPlayer; player++) + for (var player = 0; player < CSettings.MaxNumPlayer; player++) { if (player <= numplayer) { - string target = "P" + (player + 1) + "N" + (numplayer + 1); + var target = "P" + (player + 1) + "N" + (numplayer + 1); _TextNames[player, numplayer] = "TextName" + target; _TextScores[player, numplayer] = "TextScore" + target; _TextRatings[player, numplayer] = "TextRating" + target; @@ -221,15 +254,18 @@ namespace Vocaluxe.Screens private void _BuildStaticStrings(ref List statics) { - _StaticAvatar = new string[CSettings.MaxNumPlayer,CSettings.MaxNumPlayer]; + _StaticAvatar = new string[CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; - for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) + for (var numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { - for (int player = 0; player < CSettings.MaxNumPlayer; player++) + for (var player = 0; player < CSettings.MaxNumPlayer; player++) { if (player > numplayer) + { continue; - string target = "P" + (player + 1) + "N" + (numplayer + 1); + } + + var target = "P" + (player + 1) + "N" + (numplayer + 1); _StaticAvatar[player, numplayer] = "StaticAvatar" + target; statics.Add(_StaticAvatar[player, numplayer]); @@ -241,13 +277,16 @@ namespace Vocaluxe.Screens { _ProgressBarPoints = new string[CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; - for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) + for (var numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { - for (int player = 0; player < CSettings.MaxNumPlayer; player++) + for (var player = 0; player < CSettings.MaxNumPlayer; player++) { if (player > numplayer) + { continue; - string target = "P" + (player + 1) + "N" + (numplayer + 1); + } + + var target = "P" + (player + 1) + "N" + (numplayer + 1); _ProgressBarPoints[player, numplayer] = "ProgressBarPoints" + target; progressBars.Add(_ProgressBarPoints[player, numplayer]); @@ -261,7 +300,9 @@ namespace Vocaluxe.Screens { // Do not play in Karaoke Mode if (CScreenSong.GetAudioMode() == EAudioMode.TR_AUDIOMODE_KARAOKE) + { return; + } // Stop any previous ProgressBar sound if (_ProgressBarSoundStream != -1) @@ -271,7 +312,7 @@ namespace Vocaluxe.Screens } // Calculate duration: 10,000 points = 5 seconds - double duration = Math.Min(maxPoints / 10000.0, 1.0) * 5; + var duration = Math.Min(maxPoints / 10000.0, 1.0) * 5; // Play the sound _ProgressBarSoundStream = PlaySound(ESounds.ProgressBar, CConfig.SoundEffectVolume); @@ -287,22 +328,22 @@ namespace Vocaluxe.Screens _PlayApplauseSound(maxPoints); } }); - } + } private int _ApplauseStream = -1; private void _PlayApplauseSound(int maxPoints) { - // Play no applause sound based on Karaoke Mode - if (CScreenSong.GetAudioMode() == EAudioMode.TR_AUDIOMODE_KARAOKE) + // Play no applause sound based on Karaoke Mode + if (CScreenSong.GetAudioMode() == EAudioMode.TR_AUDIOMODE_KARAOKE) { - return; + return; } - + // Play the appropriate applause sound based on maxPoints if (maxPoints >= 8000) { - _ApplauseStream = PlaySound(ESounds.ApplauseHigh, CConfig.SoundEffectVolume); + _ApplauseStream = PlaySound(ESounds.ApplauseHigh, CConfig.SoundEffectVolume); } else if (maxPoints >= 5000) { @@ -310,13 +351,13 @@ namespace Vocaluxe.Screens } else if (maxPoints >= 2000) { - _ApplauseStream = PlaySound(ESounds.ApplauseLow, CConfig.SoundEffectVolume); + _ApplauseStream = PlaySound(ESounds.ApplauseLow, CConfig.SoundEffectVolume); } } private static int PlaySound(ESounds sound, int volume) { - int streamId = CSound.PlaySound(sound, false); + var streamId = CSound.PlaySound(sound, false); CSound.SetStreamVolume(streamId, volume); return streamId; @@ -330,85 +371,110 @@ namespace Vocaluxe.Screens { song = CGame.GetSong(_Round); if (song == null) + { return; + } _Texts[_TextSong].Text = song.Artist + " - " + song.Title; if (_Points.NumRounds > 1) + { _Texts[_TextSong].Text += " (" + (_Round + 1) + "/" + _Points.NumRounds + ")"; + } + players = _Points.GetPlayer(_Round, CGame.NumPlayers); - int maxPoints = (int)Math.Round(players.Max(player => player.Points)); + var maxPoints = (int)Math.Round(players.Max(player => player.Points)); _PlayProgressBarSound(maxPoints); - } else { _Texts[_TextSong].Text = "TR_SCREENSCORE_OVERALLSCORE"; - for (int i = 0; i < CGame.NumRounds; i++) + for (var i = 0; i < CGame.NumRounds; i++) { - SPlayer[] points = _Points.GetPlayer(i, CGame.NumPlayers); - for (int p = 0; p < players.Length; p++) + var points = _Points.GetPlayer(i, CGame.NumPlayers); + for (var p = 0; p < players.Length; p++) { if (i < 1) - players[p].ProfileID = points[p].ProfileID; + { + players[p].ProfileId = points[p].ProfileId; + } + players[p].Points += points[p].Points; } } - for (int p = 0; p < players.Length; p++) - players[p].Points = (int)Math.Round(players[p].Points / CGame.NumRounds); - int maxPoints = (int)Math.Round(players.Max(player => player.Points)); + for (var p = 0; p < players.Length; p++) + { + players[p].Points = (int)Math.Round(players[p].Points / CGame.NumRounds); + } + + var maxPoints = (int)Math.Round(players.Max(player => player.Points)); _PlayProgressBarSound(maxPoints); } - for (int p = 0; p < players.Length; p++) + for (var p = 0; p < players.Length; p++) { - string name = CProfiles.GetPlayerName(players[p].ProfileID, p); + var name = CProfiles.GetPlayerName(players[p].ProfileId, p); if (song != null && song.IsDuet) { if (song.Notes.VoiceNames.IsSet(players[p].VoiceNr)) + { name += " (" + song.Notes.VoiceNames[players[p].VoiceNr] + ")"; + } } + _Texts[_TextNames[p, CGame.NumPlayers - 1]].Text = name; if (CGame.NumPlayers < (int)_ScreenSettings[_ScreenSettingShortScore].GetValue()) + { _Texts[_TextScores[p, CGame.NumPlayers - 1]].Text = ((int)Math.Round(players[p].Points)).ToString("0000") + " " + CLanguage.Translate("TR_SCREENSCORE_POINTS"); + } else + { _Texts[_TextScores[p, CGame.NumPlayers - 1]].Text = ((int)Math.Round(players[p].Points)).ToString("0000"); + } + if (CGame.NumPlayers < (int)_ScreenSettings[_ScreenSettingShortDifficulty].GetValue()) { _Texts[_TextDifficulty[p, CGame.NumPlayers - 1]].Text = CLanguage.Translate("TR_SCREENSCORE_GAMEDIFFICULTY") + ": " + - CLanguage.Translate(CProfiles.GetDifficulty(players[p].ProfileID).ToString()); + CLanguage.Translate(CProfiles.GetDifficulty(players[p].ProfileId).ToString()); } else - _Texts[_TextDifficulty[p, CGame.NumPlayers - 1]].Text = CLanguage.Translate(CProfiles.GetDifficulty(players[p].ProfileID).ToString()); + { + _Texts[_TextDifficulty[p, CGame.NumPlayers - 1]].Text = CLanguage.Translate(CProfiles.GetDifficulty(players[p].ProfileId).ToString()); + } + if (CGame.NumPlayers < (int)_ScreenSettings[_ScreenSettingShortRating].GetValue()) { _Texts[_TextRatings[p, CGame.NumPlayers - 1]].Text = CLanguage.Translate("TR_SCREENSCORE_RATING") + ": " + CLanguage.Translate(_GetRating((int)Math.Round(players[p].Points))); } else + { _Texts[_TextRatings[p, CGame.NumPlayers - 1]].Text = CLanguage.Translate(_GetRating((int)Math.Round(players[p].Points))); + } _ProgressBars[_ProgressBarPoints[p, CGame.NumPlayers - 1]].Progress = (float)players[p].Points / CSettings.MaxScore; - if (CProfiles.IsProfileIDValid(players[p].ProfileID)) - _Statics[_StaticAvatar[p, CGame.NumPlayers - 1]].Texture = CProfiles.GetAvatarTextureFromProfile(players[p].ProfileID); + if (CProfiles.IsProfileIdValid(players[p].ProfileId)) + { + _Statics[_StaticAvatar[p, CGame.NumPlayers - 1]].Texture = CProfiles.GetAvatarTextureFromProfile(players[p].ProfileId); + } } } private void _SetVisibility() { - bool isKaraokeMode = CScreenSong.GetAudioMode() == EAudioMode.TR_AUDIOMODE_KARAOKE; + var isKaraokeMode = CScreenSong.GetAudioMode() == EAudioMode.TR_AUDIOMODE_KARAOKE; - for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) + for (var numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { - for (int player = 0; player < CSettings.MaxNumPlayer; player++) + for (var player = 0; player < CSettings.MaxNumPlayer; player++) { if (player <= numplayer) { - bool isVisible = numplayer + 1 == CGame.NumPlayers; - + var isVisible = numplayer + 1 == CGame.NumPlayers; + _Texts[_TextNames[player, numplayer]].Visible = isVisible; _Texts[_TextScores[player, numplayer]].Visible = isVisible && !isKaraokeMode; _Texts[_TextRatings[player, numplayer]].Visible = isVisible; @@ -433,16 +499,16 @@ namespace Vocaluxe.Screens private void _SavePlayedSongs() { - for (int round = 0; round < _Points.NumRounds; round++) + for (var round = 0; round < _Points.NumRounds; round++) { - SPlayer[] players = _Points.GetPlayer(round, CGame.NumPlayers); + var players = _Points.GetPlayer(round, CGame.NumPlayers); - for (int p = 0; p < players.Length; p++) + for (var p = 0; p < players.Length; p++) { if (players[p].Points > CSettings.MinScoreForDB && players[p].SongFinished) { - CSong song = CSongs.GetSong(players[p].SongID); - CDataBase.IncreaseSongCounter(song.DataBaseSongID); + var song = CSongs.GetSong(players[p].SongId); + CDataBase.IncreaseSongCounter(song.DataBaseSongId); song.NumPlayed++; song.NumPlayedSession++; break; @@ -453,10 +519,13 @@ namespace Vocaluxe.Screens private bool _UpdateBackground() { - string[] photos = CVocaluxeServer.GetPhotosOfThisRound(); + var photos = CVocaluxeServer.GetPhotosOfThisRound(); _SlideShowBG.RemoveSlideShowTextures(); - foreach (string photo in photos) + foreach (var photo in photos) + { _SlideShowBG.AddSlideShowTexture(photo); + } + return photos.Length > 0; } @@ -464,8 +533,8 @@ namespace Vocaluxe.Screens { if (_ApplauseStream != -1) { - CSound.Close(_ApplauseStream); - _ApplauseStream = -1; + CSound.Close(_ApplauseStream); + _ApplauseStream = -1; } if (_ProgressBarSoundStream != -1) @@ -473,15 +542,15 @@ namespace Vocaluxe.Screens CSound.Close(_ProgressBarSoundStream); _ProgressBarSoundStream = -1; } - + if (CScreenSong.GetAudioMode() == EAudioMode.TR_AUDIOMODE_KARAOKE) { - CGraphics.FadeTo(EScreen.Song); + CGraphics.FadeTo(EScreen.Song); } else { - CParty.LeavingScore(); + CParty.LeavingScore(); } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenSing.cs b/Vocaluxe/Screens/CScreenSing.cs index c9dd0e72..dd3349b8 100644 --- a/Vocaluxe/Screens/CScreenSing.cs +++ b/Vocaluxe/Screens/CScreenSing.cs @@ -18,7 +18,6 @@ using System; using System.Collections.Generic; using System.Diagnostics; -using System.Drawing; using System.IO; using System.Linq; using System.Timers; @@ -30,7 +29,6 @@ using VocaluxeLib; using VocaluxeLib.Draw; using VocaluxeLib.Log; using VocaluxeLib.Menu; -using VocaluxeLib.Menu.SingNotes; using VocaluxeLib.PartyModes; using VocaluxeLib.Songs; @@ -130,7 +128,7 @@ namespace Vocaluxe.Screens private float _CurrentTime; private float _FinishTime; - + private float _PausePosition; private float _TimeToFirstNote; @@ -152,7 +150,7 @@ namespace Vocaluxe.Screens private CBackground _SlideShow; private SScreenSongOptions _Sso; - + private System.Timers.Timer _TimerShortInfoText; public override EMusicType CurrentMusicType @@ -169,20 +167,20 @@ namespace Vocaluxe.Screens _ThemeTexts = texts.ToArray(); var statics = new List - { - _StaticShortInfoTop, - _StaticSongText, - _StaticLyrics, - _StaticLyricsDuet, - _StaticLyricsTop, - _StaticTimeBar, - _StaticTimeLine, - _StaticTimeLineExpandedNormal, - _StaticTimeLineExpandedHighlighted, - _StaticTimePointer, - _StaticLyricHelper, - _StaticLyricHelperDuet, - _StaticLyricHelperTop + { + _StaticShortInfoTop, + _StaticSongText, + _StaticLyrics, + _StaticLyricsDuet, + _StaticLyricsTop, + _StaticTimeBar, + _StaticTimeLine, + _StaticTimeLineExpandedNormal, + _StaticTimeLineExpandedHighlighted, + _StaticTimePointer, + _StaticLyricHelper, + _StaticLyricHelperDuet, + _StaticLyricHelperTop }; _BuildStaticStrings(ref statics); _ThemeStatics = statics.ToArray(); @@ -241,18 +239,24 @@ namespace Vocaluxe.Screens _SelectSlidesPause = new List(); _SelectSlides[_SelectSlidePauseVocalsVolume].AddValues(new string[] - {"0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"}); + { "0", "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100" }); _SelectSlides[_SelectSlidePauseVocalsVolume].Selection = CConfig.VocalsVolume / 5; //Automatically find statics and texts with pause prefix - foreach (CStatic s in _Statics.Where(s => s.ThemeLoaded && s.GetThemeName().StartsWith("StaticPause"))) + foreach (var s in _Statics.Where(s => s.ThemeLoaded && s.GetThemeName().StartsWith("StaticPause"))) + { _StaticsPause.Add(s.GetThemeName()); + } - foreach (CText t in _Texts.Where(s => s.ThemeLoaded && s.GetThemeName().StartsWith("TextPause"))) + foreach (var t in _Texts.Where(s => s.ThemeLoaded && s.GetThemeName().StartsWith("TextPause"))) + { _TextsPause.Add(t.GetThemeName()); + } - foreach (CText t in _Texts.Where(s => s.ThemeLoaded && s.GetThemeName().StartsWith("SelectSlidePause"))) + foreach (var t in _Texts.Where(s => s.ThemeLoaded && s.GetThemeName().StartsWith("SelectSlidePause"))) + { _SelectSlidesPause.Add(t.GetThemeName()); + } } public override bool HandleInput(SKeyEvent keyEvent) @@ -266,13 +270,19 @@ namespace Vocaluxe.Screens case Keys.Escape: _TogglePause(); if (_Pause) + { _SelectElement(_Buttons[_ButtonCancel]); + } + break; case Keys.P: _TogglePause(); if (_Pause) + { _SelectElement(_Buttons[_ButtonContinue]); + } + break; case Keys.T: @@ -280,7 +290,10 @@ namespace Vocaluxe.Screens mode++; if (mode > Enum.GetNames(typeof(ETimerMode)).Length - 1) + { mode = 0; + } + CConfig.Config.Game.TimerMode = (ETimerMode)mode; CConfig.SaveConfig(); break; @@ -290,7 +303,10 @@ namespace Vocaluxe.Screens mode++; if (mode > Enum.GetNames(typeof(EPlayerInfo)).Length - 1) + { mode = 0; + } + CConfig.Config.Theme.PlayerInfo = (EPlayerInfo)mode; CConfig.SaveConfig(); _SetVisibility(); @@ -300,61 +316,89 @@ namespace Vocaluxe.Screens if (CGame.NumRounds > CGame.RoundNr) { if (keyEvent.ModCtrl) + { _NextSong(); + } } else + { _ShowInfoText(CBase.Language.Translate("TR_SCREENSING_NOMORESONGS")); + } + break; case Keys.W: if (CWebcam.IsDeviceAvailable()) { _Webcam = !CWebcam.IsCapturing(); if (_Webcam) + { CWebcam.Start(); + } else + { CWebcam.Stop(); + } } else + { _ShowInfoText(CBase.Language.Translate("TR_SCREENSING_NOWEBCAM")); + } + break; case Keys.Enter: if (_Pause) { if (_Buttons[_ButtonContinue].Selected) + { _SetPause(false); + } + if (_Buttons[_ButtonCancel].Selected) + { _Stop(); + } + if (_Buttons[_ButtonRestartGame].Selected) { _RestartGame(); _SetPause(false); } + if (_Buttons[_ButtonRestartRound].Selected) { _RestartRound(); _SetPause(false); } + if (_Buttons[_ButtonSkip].Selected) { _NextSong(); _SetPause(false); } } + break; case Keys.V: if (_VideoAspect == EAspect.Zoom2) + { _VideoAspect = EAspect.Crop; + } else + { _VideoAspect++; + } - CSong song = CGame.GetSong(); + var song = CGame.GetSong(); song.VideoAspect = _VideoAspect; _ShowInfoText(CBase.Language.Translate("TR_SCREENSING_ASPECTRATIO").Replace("%a", _VideoAspect.ToString())); if (CConfig.Config.Debug.SaveModifiedSongs == EOffOn.TR_CONFIG_ON) + { song.Save(); + } + break; // Restart Song and reload song from disk (not in party modes with multiple rounds) @@ -364,6 +408,7 @@ namespace Vocaluxe.Screens _RestartGame(); _SetPause(false); } + break; // Restart Song and reload song from disk (not in party modes with multiple rounds) @@ -373,6 +418,7 @@ namespace Vocaluxe.Screens _RestartGame(); _SetPause(false); } + break; // Skip 10/30 seconds @@ -380,20 +426,26 @@ namespace Vocaluxe.Screens if ((keyEvent.Mod == EModifier.Shift || keyEvent.Mod == EModifier.Ctrl) && !_Pause && !_Sso.Selection.PartyMode) { if (_TimerSongText.IsRunning) + { _TimerSongText.Stop(); + } - float newTime = _CurrentTime + (keyEvent.Mod == EModifier.Shift ? 10f : 30f); + var newTime = _CurrentTime + (keyEvent.Mod == EModifier.Shift ? 10f : 30f); if (CSound.GetLength(_CurrentStream) < newTime) + { newTime = CSound.GetLength(_CurrentStream) - 1f; + } + CSound.SetPosition(_CurrentStream, newTime); - + if (CScreenSong.GetAudioMode() == EAudioMode.TR_AUDIOMODE_VOCALS) { CSound.SetPosition(_CurrentStreamVocals, newTime); } - _ShowInfoText(CBase.Language.Translate("TR_SCREENSING_SKIPPEDSECONDS").Replace("%s", (keyEvent.Mod == EModifier.Shift ? "10" : "30"))); + _ShowInfoText(CBase.Language.Translate("TR_SCREENSING_SKIPPEDSECONDS").Replace("%s", keyEvent.Mod == EModifier.Shift ? "10" : "30")); } + break; } } @@ -409,25 +461,35 @@ namespace Vocaluxe.Screens { _TogglePause(); if (_Pause) + { _SelectElement(_Buttons[_ButtonContinue]); + } } if (mouseEvent.LB && _IsMouseOverCurSelection(mouseEvent) && _Pause) { if (_Buttons[_ButtonContinue].Selected) + { _SetPause(false); + } + if (_Buttons[_ButtonCancel].Selected) + { _Stop(); + } + if (_Buttons[_ButtonRestartGame].Selected) { _RestartGame(); _SetPause(false); } + if (_Buttons[_ButtonRestartRound].Selected) { _RestartRound(); _SetPause(false); - } + } + if (_Buttons[_ButtonSkip].Selected) { _NextSong(); @@ -448,9 +510,14 @@ namespace Vocaluxe.Screens _InitiateProgressBars(); _InitiateRatingPopups(); if (_StaticsExtra == null) + { _CreateExtraStatics(); + } + if (_TextsExtra == null) + { _CreateExtraTexts(); + } _FadeOut = false; @@ -480,10 +547,12 @@ namespace Vocaluxe.Screens _SingNotes[_SingBars].Init(0); _AssignPlayerElements(); - foreach (CLyric lyric in _Lyrics) + foreach (var lyric in _Lyrics) + { lyric.LyricStyle = CConfig.Config.Theme.LyricStyle; + } - for (int p = 0; p < CGame.NumPlayers; p++) + for (var p = 0; p < CGame.NumPlayers; p++) { _Statics[_PlayerStaticAvatar[p]].Aspect = EAspect.Crop; _Texts[_PlayerTextScore[p]].Color = new SColorF(CBase.Themes.GetPlayerColor(p + 1), _Texts[_PlayerTextScore[p]].Color.A); @@ -510,34 +579,44 @@ namespace Vocaluxe.Screens base.OnClose(); _CloseSong(); if (_Webcam) + { CWebcam.Stop(); + } + CBackgroundMusic.Disabled = false; } #endregion #region update game - public override bool UpdateGame() { - bool finish = false; + var finish = false; if (CSound.IsPlaying(_CurrentStream) || CSound.IsPaused(_CurrentStream)) { _CurrentTime = CSound.GetPosition(_CurrentStream); if (_FinishTime > 0.001 && _CurrentTime >= _FinishTime) + { finish = true; + } } else + { finish = true; + } if (finish && !_FadeOut && !_StartDelayed) + { _NextSong(); + } _UpdateSongText(); _UpdateDuetNames(); if (_FadeOut) + { return true; + } if (CGame.GameMode == EGameMode.TR_GAMEMODE_MEDLEY) { @@ -556,7 +635,7 @@ namespace Vocaluxe.Screens _UpdateRatingPopups(); _UpdateLyrics(); - float[] alpha = _CalcFadingAlpha(); + var alpha = _CalcFadingAlpha(); if (alpha != null) { _Lyrics[_LyricMain].Alpha = alpha[0]; @@ -571,7 +650,7 @@ namespace Vocaluxe.Screens _Statics[_StaticLyricHelper].Alpha = alpha[0]; _Statics[_StaticLyricHelperTop].Alpha = alpha[0]; - for (int p = 0; p < CGame.NumPlayers; p++) + for (var p = 0; p < CGame.NumPlayers; p++) { _SingNotes[_SingBars].PlayerNotes[p].Alpha = alpha[CGame.Players[p].VoiceNr * 2]; if (CConfig.Config.Theme.FadePlayerInfo == EFadePlayerInfo.TR_CONFIG_FADEPLAYERINFO_INFO || @@ -580,6 +659,7 @@ namespace Vocaluxe.Screens _Statics[_PlayerStaticAvatar[p]].Alpha = alpha[CGame.Players[p].VoiceNr * 2]; _Texts[_PlayerTextName[p]].Alpha = alpha[CGame.Players[p].VoiceNr * 2]; } + if (CConfig.Config.Theme.FadePlayerInfo == EFadePlayerInfo.TR_CONFIG_FADEPLAYERINFO_ALL) { _Statics[_PlayerStaticScore[p]].Alpha = alpha[CGame.Players[p].VoiceNr * 2]; @@ -602,17 +682,21 @@ namespace Vocaluxe.Screens } - for (int p = 0; p < CGame.NumPlayers; p++) + for (var p = 0; p < CGame.NumPlayers; p++) { - string fmtString = (CGame.Players[p].Points < 10000) ? "0000" : "00000"; + var fmtString = CGame.Players[p].Points < 10000 ? "0000" : "00000"; _Texts[_PlayerTextScore[p]].Text = CGame.Players[p].Points.ToString(fmtString); } if (_CurrentVideo != null && !_FadeOut && CConfig.Config.Video.VideosInSongs == EOffOn.TR_CONFIG_ON) + { CVideo.GetFrame(_CurrentVideo, _CurrentTime); + } if (_Webcam) + { CWebcam.GetFrame(ref _CurrentWebcamFrameTexture); + } return true; } @@ -620,12 +704,16 @@ namespace Vocaluxe.Screens private void _UpdateLyrics() { if (_FadeOut) + { return; + } - CSong song = CGame.GetSong(); + var song = CGame.GetSong(); if (song == null) + { return; + } _CurrentBeat = CGame.CurrentBeat; _Lyrics[_LyricSub].Update(-100); @@ -637,31 +725,35 @@ namespace Vocaluxe.Screens _Lyrics[_LyricSubTop].Update(-100); _Lyrics[_LyricMainTop].Update(CGame.CurrentBeatF); - for (int i = 0; i < song.Notes.VoiceCount; i++) + for (var i = 0; i < song.Notes.VoiceCount; i++) { if (i > 1) + { break; // for later + } - CVoice voice = song.Notes.GetVoice(i); - CSongLine[] lines = voice.Lines; + var voice = song.Notes.GetVoice(i); + var lines = voice.Lines; // find current line - int nr = _FindCurrentLine(voice, lines, song); + var nr = _FindCurrentLine(voice, lines, song); if (nr != -1) { - for (int j = 0; j < CGame.NumPlayers; j++) + for (var j = 0; j < CGame.NumPlayers; j++) { if (CGame.Players[j].VoiceNr == i) + { _SingNotes[_SingBars].PlayerNotes[j].SetLine(nr); + } } if (i == 0) { _Lyrics[_LyricMain].SetLine(lines[nr]); _Lyrics[_LyricMainTop].SetLine(lines[nr]); - _TimeToFirstNote = CGame.GetTimeFromBeats(lines[nr].FirstNoteBeat - lines[nr].StartBeat, song.BPM); - _RemainingTimeToFirstNote = CGame.GetTimeFromBeats(lines[nr].FirstNoteBeat - CGame.GetBeatFromTime(_CurrentTime, song.BPM, song.Gap), song.BPM); + _TimeToFirstNote = CGame.GetTimeFromBeats(lines[nr].FirstNoteBeat - lines[nr].StartBeat, song.Bpm); + _RemainingTimeToFirstNote = CGame.GetTimeFromBeats(lines[nr].FirstNoteBeat - CGame.GetBeatFromTime(_CurrentTime, song.Bpm, song.Gap), song.Bpm); if (lines.Length >= nr + 2) { @@ -674,16 +766,21 @@ namespace Vocaluxe.Screens _Lyrics[_LyricSubTop].Clear(); } } + if (i == 1 && song.IsDuet) { _Lyrics[_LyricMainDuet].SetLine(lines[nr]); - _TimeToFirstNoteDuet = CGame.GetTimeFromBeats(lines[nr].FirstNoteBeat - lines[nr].StartBeat, song.BPM); - _RemainingTimeToFirstNoteDuet = CGame.GetTimeFromBeats(lines[nr].FirstNoteBeat - CGame.GetBeatFromTime(_CurrentTime, song.BPM, song.Gap), song.BPM); + _TimeToFirstNoteDuet = CGame.GetTimeFromBeats(lines[nr].FirstNoteBeat - lines[nr].StartBeat, song.Bpm); + _RemainingTimeToFirstNoteDuet = CGame.GetTimeFromBeats(lines[nr].FirstNoteBeat - CGame.GetBeatFromTime(_CurrentTime, song.Bpm, song.Gap), song.Bpm); if (lines.Length >= nr + 2) + { _Lyrics[_LyricSubDuet].SetLine(lines[nr + 1]); + } else + { _Lyrics[_LyricSubDuet].Clear(); + } } } else @@ -709,56 +806,63 @@ namespace Vocaluxe.Screens private void _UpdateMedleyCountdown() { - CSong song = CGame.GetSong(); + var song = CGame.GetSong(); if (song == null) + { return; - float timeToFirstMedleyNote = CGame.GetTimeFromBeats(song.Medley.StartBeat, song.BPM) + song.Gap; + } + + var timeToFirstMedleyNote = CGame.GetTimeFromBeats(song.Medley.StartBeat, song.Bpm) + song.Gap; if (_CurrentTime < timeToFirstMedleyNote) { - float timeDiff = timeToFirstMedleyNote - _CurrentTime + 1; + var timeDiff = timeToFirstMedleyNote - _CurrentTime + 1; var fullSeconds = (float)Math.Truncate(timeDiff); - float partSeconds = timeDiff - fullSeconds; + var partSeconds = timeDiff - fullSeconds; _Texts[_TextMedleyCountdown].Visible = true; _Texts[_TextMedleyCountdown].Text = fullSeconds.ToString(); _Texts[_TextMedleyCountdown].Font.Height = Math.Max(CSettings.RenderH / 8f, partSeconds * CSettings.RenderH); - RectangleF textBounds = CFonts.GetTextBounds(_Texts[_TextMedleyCountdown]); - float x = CSettings.RenderW / 2 - textBounds.Width / 2; - float y = CSettings.RenderH / 2 - textBounds.Height / 2; + var textBounds = CFonts.GetTextBounds(_Texts[_TextMedleyCountdown]); + var x = CSettings.RenderW / 2 - textBounds.Width / 2; + var y = CSettings.RenderH / 2 - textBounds.Height / 2; _Texts[_TextMedleyCountdown].X = x; _Texts[_TextMedleyCountdown].Y = y; } else + { _Texts[_TextMedleyCountdown].Visible = false; + } } private void _UpdateStartCountdown() { if (!_StartDelayed) + { return; + } - float elapsed = _TimerStartCountdown.ElapsedMilliseconds / 1000f; - float remaining = _StartCountdownSeconds - elapsed; + var elapsed = _TimerStartCountdown.ElapsedMilliseconds / 1000f; + var remaining = _StartCountdownSeconds - elapsed; if (remaining > 0f) { - float fullSeconds = (float)Math.Ceiling(remaining); - float partSeconds = remaining - (float)Math.Floor(remaining); + var fullSeconds = (float)Math.Ceiling(remaining); + var partSeconds = remaining - (float)Math.Floor(remaining); _Texts[_TextMedleyCountdown].Visible = true; _Texts[_TextMedleyCountdown].Text = fullSeconds.ToString("0"); _Texts[_TextMedleyCountdown].Font.Height = Math.Max(CSettings.RenderH / 8f, partSeconds * CSettings.RenderH); - RectangleF textBounds = CFonts.GetTextBounds(_Texts[_TextMedleyCountdown]); - float x = CSettings.RenderW / 2f - textBounds.Width / 2f; - float y = CSettings.RenderH / 2f - textBounds.Height / 2f; + var textBounds = CFonts.GetTextBounds(_Texts[_TextMedleyCountdown]); + var x = CSettings.RenderW / 2f - textBounds.Width / 2f; + var y = CSettings.RenderH / 2f - textBounds.Height / 2f; _Texts[_TextMedleyCountdown].X = x; _Texts[_TextMedleyCountdown].Y = y; } else { _Texts[_TextMedleyCountdown].Visible = false; - _Texts[_TextMedleyCountdown].Text = String.Empty; + _Texts[_TextMedleyCountdown].Text = string.Empty; _TimerStartCountdown.Reset(); _StartSongNow(); @@ -770,13 +874,13 @@ namespace Vocaluxe.Screens { if (_TimerSongText.IsRunning) { - float t = _TimerSongText.ElapsedMilliseconds / 1000f; + var t = _TimerSongText.ElapsedMilliseconds / 1000f; if (t < _TimeShowSongTextTotal) { _Statics[_StaticSongText].Visible = true; _Texts[_TextSongName].Visible = true; - if (t < (_TimeShowSongTextTotal - 3f)) + if (t < _TimeShowSongTextTotal - 3f) { _Statics[_StaticSongText].Color.A = 1f; _Texts[_TextSongName].Color.A = 1f; @@ -805,17 +909,23 @@ namespace Vocaluxe.Screens { if (timer.IsRunning) { - float t = timer.ElapsedMilliseconds / 1000f; + var t = timer.ElapsedMilliseconds / 1000f; if (t < 10f) { textName.Visible = true; if (t < 3f) + { textName.Color.A = t / 3f; + } else if (t < 7f) + { textName.Color.A = 1f; + } else + { textName.Color.A = (10f - t) / 3f; + } } else { @@ -824,31 +934,44 @@ namespace Vocaluxe.Screens } } else if (!timer.IsRunning && timer.ElapsedMilliseconds == 0 && _Lyrics[_LyricMainTop].Alpha > 0 && CGame.GetSong().IsDuet) + { timer.Start(); + } else + { textName.Visible = false; + } } private void _UpdateDuetNames() { if (CGame.GetSong() == null) + { return; + } + //Timer for first duet-part _UpdateDuetNames(_Texts[_TextDuetName1], _TimerDuetText1); //Timer for second duet-part if (_TimerDuetText2.IsRunning) { - float t = _TimerDuetText2.ElapsedMilliseconds / 1000f; + var t = _TimerDuetText2.ElapsedMilliseconds / 1000f; if (t < 10f) { _Texts[_TextDuetName2].Visible = true; if (t < 3f) + { _Texts[_TextDuetName2].Color.A = (3f - (3f - t)) / 3f; + } else if (t < 7f) + { _Texts[_TextDuetName2].Color.A = 1f; + } else + { _Texts[_TextDuetName2].Color.A = (3f - (t - 7f)) / 3f; + } } else { @@ -857,31 +980,43 @@ namespace Vocaluxe.Screens } } else if (!_TimerDuetText2.IsRunning && _TimerDuetText2.ElapsedMilliseconds == 0 && _Lyrics[_LyricMainDuet].Alpha > 0 && CGame.GetSong().IsDuet) + { _TimerDuetText2.Start(); + } else + { _Texts[_TextDuetName2].Visible = false; + } } private void _UpdateTimeLine() { - CSong song = CGame.GetSong(); + var song = CGame.GetSong(); if (song == null) + { return; + } - float totalTime = CSound.GetLength(_CurrentStream); - if (Math.Abs(song.Finish) > 0.001) - totalTime = song.Finish; + var totalTime = CSound.GetLength(_CurrentStream); + if (Math.Abs(song.End) > 0.001) + { + totalTime = song.End; + } - float remainingTime = totalTime - _CurrentTime; + var remainingTime = totalTime - _CurrentTime; totalTime -= song.Start; - float currentTime = _CurrentTime - song.Start; + var currentTime = _CurrentTime - song.Start; if (_Length < 0 && totalTime > 0) + { _PrepareTimeLine(); + } if (totalTime <= 0f) + { return; + } switch (CConfig.Config.Game.TimerMode) { @@ -912,9 +1047,9 @@ namespace Vocaluxe.Screens break; case ETimerLook.TR_CONFIG_TIMERLOOK_EXPANDED: - CStatic stat = _Statics[_StaticTimeLine]; - int currentBeat = CGame.CurrentBeat; - for (int i = 0; i < _TimeRects.Count; i++) + var stat = _Statics[_StaticTimeLine]; + var currentBeat = CGame.CurrentBeat; + for (var i = 0; i < _TimeRects.Count; i++) { if (currentBeat >= _TimeRects[i].StartBeat && currentBeat <= _TimeRects[i].EndBeat) { @@ -927,6 +1062,7 @@ namespace Vocaluxe.Screens _TimeRects[i].Rect.Color = _Statics[_StaticTimeLineExpandedNormal].Color; } } + _Statics[_StaticTimePointer].X = stat.X + stat.W * (currentTime / totalTime); break; } @@ -934,7 +1070,7 @@ namespace Vocaluxe.Screens private void _UpdateRatingBars() { - for (int i = 0; i < CGame.NumPlayers; i++) + for (var i = 0; i < CGame.NumPlayers; i++) { _ProgressBars[_PlayerProgressBarRating[i]].Progress = (float)CGame.Players[i].Rating; } @@ -942,12 +1078,10 @@ namespace Vocaluxe.Screens private void _UpdateRatingPopups() { - - for (int i = 0; i < CGame.NumPlayers; i++) + for (var i = 0; i < CGame.NumPlayers; i++) { - - float fadeOutTime = 1f; - float showTime = 0.5f; + var fadeOutTime = 1f; + var showTime = 0.5f; var timeSinceLastLine = Math.Abs(_CurrentTime - CGame.Players[i].TimeLastLineChange); if (timeSinceLastLine < showTime) { @@ -962,7 +1096,7 @@ namespace Vocaluxe.Screens _RatingPopups[_PlayerRatingPopup[i]].Alpha = 0; } - switch(CGame.Players[i].RatingLastLine) + switch (CGame.Players[i].RatingLastLine) { case 1: _RatingPopups[_PlayerRatingPopup[i]].Text.Text = "TR_SCREENSING_RATING_1"; @@ -988,14 +1122,11 @@ namespace Vocaluxe.Screens case double rating when rating < 0.15: _RatingPopups[_PlayerRatingPopup[i]].Text.Text = "TR_SCREENSING_RATING_8"; break; - } _RatingPopups[_PlayerRatingPopup[i]].Color = new SColorF(CBase.Themes.GetPlayerColor(i + 1), 1); - } } - #endregion #region drawing @@ -1014,20 +1145,28 @@ namespace Vocaluxe.Screens background = _CurrentWebcamFrameTexture; } else + { background = _Background; + } + if (background != null) { - SRectF bounds = CSettings.RenderRect; - + var bounds = CSettings.RenderRect; + if (_VideoAspect == EAspect.Automatic) - _VideoAspect = ((background.OrigAspect <= 1.5 || background.OrigAspect >= 1.9) ? EAspect.LetterBox : EAspect.Crop); + { + _VideoAspect = background.OrigAspect <= 1.5 || background.OrigAspect >= 1.9 ? EAspect.LetterBox : EAspect.Crop; + } + aspect = _VideoAspect; - - SRectF rect = CHelper.FitInBounds(bounds, background.OrigAspect, aspect); + + var rect = CHelper.FitInBounds(bounds, background.OrigAspect, aspect); CDraw.DrawTexture(background, rect, background.Color, bounds); } else if (_SlideShow != null) + { _SlideShow.Draw(); + } } base.Draw(); @@ -1038,8 +1177,11 @@ namespace Vocaluxe.Screens CDraw.DrawTexture(_Statics[_StaticTimeLine].Texture, _Statics[_StaticTimeLine].Rect, new SColorF(1, 1, 1, 1), _TimeLineRect); break; case ETimerLook.TR_CONFIG_TIMERLOOK_EXPANDED: - for (int i = 0; i < _TimeRects.Count; i++) + for (var i = 0; i < _TimeRects.Count; i++) + { CDraw.DrawTexture(_TimeRects[i].Rect.Texture, _Statics[_StaticTimeLine].Rect, _TimeRects[i].Rect.Color, _TimeRects[i].Rect.Rect); + } + break; } @@ -1049,55 +1191,65 @@ namespace Vocaluxe.Screens private void _DrawLyricHelper() { if (_FadeOut) + { return; + } if (!CSound.IsPlaying(_CurrentStream) && !CSound.IsPaused(_CurrentStream)) + { return; + } - CSong song = CGame.GetSong(); + var song = CGame.GetSong(); if (song == null) + { return; + } - float alpha = (float)((Math.Cos(_CurrentTime * Math.PI * 2) + 1) / 2.0) / 2f + 0.5f; + var alpha = (float)((Math.Cos(_CurrentTime * Math.PI * 2) + 1) / 2.0) / 2f + 0.5f; if (_TimeToFirstNote > CSettings.LyricHelperMinTime && _RemainingTimeToFirstNote > 0f && _RemainingTimeToFirstNote < CSettings.LyricHelperEnableTime) { - float time = _RemainingTimeToFirstNote; - float totaltime = CSettings.LyricHelperMoveTime; + var time = _RemainingTimeToFirstNote; + var totaltime = CSettings.LyricHelperMoveTime; if (totaltime > _TimeToFirstNote) + { totaltime = _TimeToFirstNote; + } if (time > totaltime) + { time = totaltime; + } if (_Statics[_StaticLyrics].Visible) { - SRectF rect = _Statics[_StaticLyricHelper].Rect; + var rect = _Statics[_StaticLyricHelper].Rect; var color = new SColorF( _Statics[_StaticLyricHelper].Color.R, _Statics[_StaticLyricHelper].Color.G, _Statics[_StaticLyricHelper].Color.B, _Statics[_StaticLyricHelper].Color.A * _Statics[_StaticLyricHelper].Alpha * alpha); - float distance = _Lyrics[_LyricMain].GetCurrentLyricPosX() - rect.X - rect.W; + var distance = _Lyrics[_LyricMain].GetCurrentLyricPosX() - rect.X - rect.W; CDraw.DrawTexture(_Statics[_StaticLyricHelper].Texture, - new SRectF(rect.X + distance * (1f - time / totaltime), rect.Y, rect.W, rect.H, rect.Z), color); + new SRectF(rect.X + distance * (1f - time / totaltime), rect.Y, rect.W, rect.H, rect.Z), color); } if (_Statics[_StaticLyricsTop].Visible) { - SRectF rect = _Statics[_StaticLyricHelperTop].Rect; + var rect = _Statics[_StaticLyricHelperTop].Rect; var color = new SColorF( _Statics[_StaticLyricHelperTop].Color.R, _Statics[_StaticLyricHelperTop].Color.G, _Statics[_StaticLyricHelperTop].Color.B, _Statics[_StaticLyricHelperTop].Color.A * _Statics[_StaticLyricHelperTop].Alpha * alpha); - float distance = _Lyrics[_LyricMainTop].GetCurrentLyricPosX() - rect.X - rect.W; + var distance = _Lyrics[_LyricMainTop].GetCurrentLyricPosX() - rect.X - rect.W; CDraw.DrawTexture(_Statics[_StaticLyricHelperTop].Texture, - new SRectF(rect.X + distance * (1f - time / totaltime), rect.Y, rect.W, rect.H, rect.Z), color); + new SRectF(rect.X + distance * (1f - time / totaltime), rect.Y, rect.W, rect.H, rect.Z), color); } } @@ -1105,16 +1257,20 @@ namespace Vocaluxe.Screens { if (_TimeToFirstNoteDuet > CSettings.LyricHelperMinTime && _RemainingTimeToFirstNoteDuet > 0f && _RemainingTimeToFirstNoteDuet < CSettings.LyricHelperEnableTime) { - float time = _RemainingTimeToFirstNoteDuet; - float totaltime = CSettings.LyricHelperMoveTime; + var time = _RemainingTimeToFirstNoteDuet; + var totaltime = CSettings.LyricHelperMoveTime; if (totaltime > _TimeToFirstNoteDuet) + { totaltime = _TimeToFirstNoteDuet; + } if (time > totaltime) + { time = totaltime; + } - SRectF rect = _Statics[_StaticLyricHelperDuet].Rect; + var rect = _Statics[_StaticLyricHelperDuet].Rect; var color = new SColorF( _Statics[_StaticLyricHelperDuet].Color.R, @@ -1122,27 +1278,28 @@ namespace Vocaluxe.Screens _Statics[_StaticLyricHelperDuet].Color.B, _Statics[_StaticLyricHelperDuet].Color.A * _Statics[_StaticLyricHelperDuet].Alpha * alpha); - float distance = _Lyrics[_LyricMainDuet].GetCurrentLyricPosX() - rect.X - rect.W; + var distance = _Lyrics[_LyricMainDuet].GetCurrentLyricPosX() - rect.X - rect.W; CDraw.DrawTexture(_Statics[_StaticLyricHelperDuet].Texture, - new SRectF(rect.X + distance * (1f - time / totaltime), rect.Y, rect.W, rect.H, rect.Z), - color); + new SRectF(rect.X + distance * (1f - time / totaltime), rect.Y, rect.W, rect.H, rect.Z), + color); } } } #endregion #region game-handling - /// /// Start recording and playing current loaded song. /// private void _StartSong() { - CSong song = CGame.GetSong(); + var song = CGame.GetSong(); if (song == null) + { return; + } - bool useStartCountdown = CGame.GameMode != EGameMode.TR_GAMEMODE_MEDLEY && song.Gap <= 2f; + var useStartCountdown = CGame.GameMode != EGameMode.TR_GAMEMODE_MEDLEY && song.Gap <= 2f; if (useStartCountdown) { @@ -1150,13 +1307,13 @@ namespace Vocaluxe.Screens _TimerStartCountdown.Reset(); _TimerStartCountdown.Start(); - _Texts[_TextMedleyCountdown].Text = String.Empty; + _Texts[_TextMedleyCountdown].Text = string.Empty; _Texts[_TextMedleyCountdown].Visible = true; return; } _StartSongNow(); - } + } private void _StartSongNow() { @@ -1170,7 +1327,9 @@ namespace Vocaluxe.Screens CRecord.Start(); if (_Webcam) + { CWebcam.Start(); + } } /// @@ -1199,7 +1358,9 @@ namespace Vocaluxe.Screens CParty.FinishedSinging(); if (_Webcam) + { CWebcam.Stop(); + } } /// @@ -1243,21 +1404,28 @@ namespace Vocaluxe.Screens if (CGame.GetSong() != null && CGame.GetSong().IsDuet) { //Save duet-assignment before resetting - for (int i = 0; i < voiceAssignments.Length; i++) + for (var i = 0; i < voiceAssignments.Length; i++) + { voiceAssignments[i] = CGame.Players[i].VoiceNr; + } + CGame.ResetPlayer(); - for (int i = 0; i < voiceAssignments.Length; i++) + for (var i = 0; i < voiceAssignments.Length; i++) + { CGame.Players[i].VoiceNr = voiceAssignments[i]; - } else + } + } + else { CGame.ResetPlayer(); - } + } _LoadCurrentSong(); _StartSong(); } + private void _TogglePause() { _SetPause(!_Pause); @@ -1267,45 +1435,59 @@ namespace Vocaluxe.Screens { _Pause = paused; - foreach (String s in _StaticsPause) + foreach (var s in _StaticsPause) + { _Statics[s].Visible = _Pause; + } - foreach (String s in _TextsPause) + foreach (var s in _TextsPause) + { _Texts[s].Visible = _Pause; + } - foreach (String s in _SelectSlidesPause) + foreach (var s in _SelectSlidesPause) + { _SelectSlides[s].Visible = _Pause; + } _Buttons[_ButtonCancel].Visible = _Pause; _Buttons[_ButtonContinue].Visible = _Pause; _Buttons[_ButtonSkip].Visible = _Pause && CGame.NumRounds > CGame.RoundNr && CGame.NumRounds > 1; _Buttons[_ButtonRestartGame].Visible = _Pause; _Buttons[_ButtonRestartRound].Visible = _Pause && CGame.NumRounds > 1; - - _SelectSlides[_SelectSlidePauseVocalsVolume].Visible = _Pause && (CScreenSong.GetAudioMode() == EAudioMode.TR_AUDIOMODE_VOCALS); - _Texts[_TextPauseVocalsVolume].Visible = _Pause && (CScreenSong.GetAudioMode() == EAudioMode.TR_AUDIOMODE_VOCALS); + + _SelectSlides[_SelectSlidePauseVocalsVolume].Visible = _Pause && CScreenSong.GetAudioMode() == EAudioMode.TR_AUDIOMODE_VOCALS; + _Texts[_TextPauseVocalsVolume].Visible = _Pause && CScreenSong.GetAudioMode() == EAudioMode.TR_AUDIOMODE_VOCALS; if (_StartDelayed) { if (_Pause) { if (_TimerStartCountdown.IsRunning) + { _TimerStartCountdown.Stop(); + } } else { if (!_TimerStartCountdown.IsRunning) + { _TimerStartCountdown.Start(); + } } _Texts[_TextMedleyCountdown].Visible = !_Pause; return; } - if (_Pause && _TimerSongText.IsRunning) + if (_Pause && _TimerSongText.IsRunning) + { _TimerSongText.Stop(); - else + } + else + { _TimerSongText.Start(); + } _Texts[_TextSongName].Visible = !_Pause; @@ -1334,9 +1516,13 @@ namespace Vocaluxe.Screens else { if (_Pause) + { CSound.Pause(_CurrentStream); + } else + { CSound.Play(_CurrentStream); + } } } #endregion @@ -1353,7 +1539,7 @@ namespace Vocaluxe.Screens return; } - CSong song = CGame.GetSong(); + var song = CGame.GetSong(); if (song == null) { @@ -1362,16 +1548,21 @@ namespace Vocaluxe.Screens } if (!_Sso.Selection.PartyMode && (CGame.GameMode == EGameMode.TR_GAMEMODE_NORMAL || CGame.GameMode == EGameMode.TR_GAMEMODE_DUET)) + { song.ReloadSong(reloadNotes); - - string songname = song.Artist + " - " + song.Title; - int rounds = CGame.GetNumSongs(); + } + + var songname = song.Artist + " - " + song.Title; + var rounds = CGame.GetNumSongs(); if (rounds > 1) + { songname += " (" + CGame.RoundNr + "/" + rounds + ")"; + } + _Texts[_TextSongName].Text = songname; _Texts[_TextPauseSongName].Text = songname; - if (CScreenSong.GetAudioMode() == EAudioMode.TR_AUDIOMODE_INSTRUMENTAL || CScreenSong.GetAudioMode() == EAudioMode.TR_AUDIOMODE_KARAOKE) + if (CScreenSong.GetAudioMode() == EAudioMode.TR_AUDIOMODE_INSTRUMENTAL || CScreenSong.GetAudioMode() == EAudioMode.TR_AUDIOMODE_KARAOKE) { _CurrentStream = CSound.Load(song.GetInstrumental(), false, true, EAudioEffect.None); } @@ -1381,16 +1572,16 @@ namespace Vocaluxe.Screens _CurrentStreamVocals = CSound.Load(song.GetVocals(), false, true, EAudioEffect.None); CSound.SetStreamVolume(_CurrentStreamVocals, CConfig.VocalsVolume); CSound.SetPosition(_CurrentStreamVocals, song.Start); - } + } else { - _CurrentStream = CSound.Load(song.GetMP3(), false, true, CConfig.Config.Sound.KaraokeEffect == EOffOn.TR_CONFIG_ON ? EAudioEffect.Karaoke : EAudioEffect.None); + _CurrentStream = CSound.Load(song.GetMP3(), false, true, CConfig.Config.Sound.KaraokeEffect == EOffOn.TR_CONFIG_ON ? EAudioEffect.Karaoke : EAudioEffect.None); } - + CSound.SetStreamVolume(_CurrentStream, 100); CSound.SetPosition(_CurrentStream, song.Start); _CurrentTime = song.Start; - _FinishTime = song.Finish; + _FinishTime = song.End; _TimeToFirstNote = 0f; _TimeToFirstNoteDuet = 0f; _Length = -1f; @@ -1398,12 +1589,14 @@ namespace Vocaluxe.Screens if (song.IsDuet) { //Save duet-assignment before resetting - for (int i = 0; i < voiceAssignments.Length; i++) + for (var i = 0; i < voiceAssignments.Length; i++) + { voiceAssignments[i] = CGame.Players[i].VoiceNr; + } } _VideoAspect = song.VideoAspect; - if (!String.IsNullOrEmpty(song.VideoFileName)) + if (!string.IsNullOrEmpty(song.VideoFileName)) { _CurrentVideo = CVideo.Load(Path.Combine(song.Folder, song.VideoFileName)); CVideo.Skip(_CurrentVideo, song.Start, song.VideoGap); @@ -1413,13 +1606,17 @@ namespace Vocaluxe.Screens if (song.BackgroundFileNames.Count > 1) { _SlideShow = GetNewBackground(); - foreach (string bgFile in song.BackgroundFileNames) + foreach (var bgFile in song.BackgroundFileNames) + { _SlideShow.AddSlideShowTexture(Path.Combine(song.Folder, bgFile)); + } } else if (song.BackgroundFileNames.Count == 1) { - if (!String.IsNullOrEmpty(song.BackgroundFileNames[0])) + if (!string.IsNullOrEmpty(song.BackgroundFileNames[0])) + { _Background = CDraw.AddTexture(Path.Combine(song.Folder, song.BackgroundFileNames[0])); + } } if (song.IsDuet) @@ -1431,13 +1628,17 @@ namespace Vocaluxe.Screens //Otherwise, this is done by CScreenNames if (CGame.GetNumSongs() > 1) { - for (int i = 0; i < CGame.NumPlayers; i++) + for (var i = 0; i < CGame.NumPlayers; i++) + { CGame.Players[i].VoiceNr = (i + 1) % 2; + } } else { - for (int i = 0; i < CGame.NumPlayers; i++) + for (var i = 0; i < CGame.NumPlayers; i++) + { CGame.Players[i].VoiceNr = voiceAssignments[i]; + } } } @@ -1447,16 +1648,22 @@ namespace Vocaluxe.Screens _DynamicLyricsTop = false; _DynamicLyricsBottom = false; - foreach (CNoteBars notes in _SingNotes[_SingBars].PlayerNotes) + foreach (var notes in _SingNotes[_SingBars].PlayerNotes) { if (notes.Rect.Bottom >= CSettings.RenderH / 2) + { _DynamicLyricsBottom = true; + } else + { _DynamicLyricsTop = true; + } } - for (int p = 0; p < CGame.NumPlayers; p++) + for (var p = 0; p < CGame.NumPlayers; p++) + { _ProgressBars[_PlayerProgressBarRating[p]].Reset(); + } _SetNormalLyricsVisibility(); @@ -1466,9 +1673,9 @@ namespace Vocaluxe.Screens // Getting the real start of the first line from the first voice, no other voices are on top since #454. // Needed for displaying song name on duet game mode or lyric on top settings (implemented with #455). - CVoice voice = song.Notes.GetVoice(0); // As long as only voice 0 is on top (no matter if duet or other modes). - CSongLine[] lines = voice.Lines; - float realGap = CGame.GetTimeFromBeats(lines[0].FirstNoteBeat, song.BPM) + (song.Gap - song.Start); + var voice = song.Notes.GetVoice(0); // As long as only voice 0 is on top (no matter if duet or other modes). + var lines = voice.Lines; + var realGap = CGame.GetTimeFromBeats(lines[0].FirstNoteBeat, song.Bpm) + (song.Gap - song.Start); _TimeShowSongTextTotal = 10f; if (_Lyrics[_LyricMainDuet].Visible || _Lyrics[_LyricMainTop].Visible) { @@ -1481,9 +1688,11 @@ namespace Vocaluxe.Screens _TimeShowSongTextTotal = realGap - 7f; } } - + if (_TimeShowSongTextTotal > 0) + { _TimerSongText.Start(); + } } /// @@ -1498,13 +1707,19 @@ namespace Vocaluxe.Screens _CurrentStream = -1; _CurrentStreamVocals = -1; } + CRecord.Stop(); if (_CurrentVideo != null) + { CVideo.Close(ref _CurrentVideo); + } + CDraw.RemoveTexture(ref _Background); if (_SlideShow != null) + { _SlideShow.RemoveSlideShowTextures(); + } _Lyrics[_LyricMain].Clear(); _Lyrics[_LyricSub].Clear(); @@ -1512,12 +1727,12 @@ namespace Vocaluxe.Screens _Lyrics[_LyricSubDuet].Clear(); _Lyrics[_LyricMainTop].Clear(); _Lyrics[_LyricSubTop].Clear(); - _Texts[_TextShortInfoTop].Text = String.Empty; - _Texts[_TextSongName].Text = String.Empty; - _Texts[_TextDuetName1].Text = String.Empty; - _Texts[_TextDuetName2].Text = String.Empty; + _Texts[_TextShortInfoTop].Text = string.Empty; + _Texts[_TextSongName].Text = string.Empty; + _Texts[_TextDuetName1].Text = string.Empty; + _Texts[_TextDuetName2].Text = string.Empty; _Texts[_TextMedleyCountdown].Visible = false; - _Texts[_TextMedleyCountdown].Text = String.Empty; + _Texts[_TextMedleyCountdown].Text = string.Empty; _StartDelayed = false; _TimerStartCountdown.Reset(); } @@ -1526,15 +1741,15 @@ namespace Vocaluxe.Screens #region visibility and fading private void _SetNormalLyricsVisibility() { - bool bottomLyricsVisible = CConfig.Config.Game.LyricsPosition == ELyricsPosition.TR_CONFIG_LYRICSPOSITION_BOTTOM - || CConfig.Config.Game.LyricsPosition == ELyricsPosition.TR_CONFIG_LYRICSPOSITION_BOTH - || (CConfig.Config.Game.LyricsPosition == ELyricsPosition.TR_CONFIG_LYRICSPOSITION_DYNAMIC && _DynamicLyricsBottom); + var bottomLyricsVisible = CConfig.Config.Game.LyricsPosition == ELyricsPosition.TR_CONFIG_LYRICSPOSITION_BOTTOM + || CConfig.Config.Game.LyricsPosition == ELyricsPosition.TR_CONFIG_LYRICSPOSITION_BOTH + || (CConfig.Config.Game.LyricsPosition == ELyricsPosition.TR_CONFIG_LYRICSPOSITION_DYNAMIC && _DynamicLyricsBottom); - bool topLyricsVisible = CConfig.Config.Game.LyricsPosition == ELyricsPosition.TR_CONFIG_LYRICSPOSITION_TOP + var topLyricsVisible = CConfig.Config.Game.LyricsPosition == ELyricsPosition.TR_CONFIG_LYRICSPOSITION_TOP || CConfig.Config.Game.LyricsPosition == ELyricsPosition.TR_CONFIG_LYRICSPOSITION_BOTH || (CConfig.Config.Game.LyricsPosition == ELyricsPosition.TR_CONFIG_LYRICSPOSITION_DYNAMIC && _DynamicLyricsTop); - bool duetLyricsVisible = false; + var duetLyricsVisible = false; if (CGame.GetSong() != null && CGame.GetSong().IsDuet) { @@ -1572,12 +1787,12 @@ namespace Vocaluxe.Screens _Texts[_TextDuetName1].Visible = false; _Texts[_TextDuetName2].Visible = false; - int screenPlayers = CGame.NumPlayers / CConfig.GetNumScreens(); - int remainingScreenPlayers = CGame.NumPlayers - (screenPlayers * CConfig.GetNumScreens()); + var screenPlayers = CGame.NumPlayers / CConfig.GetNumScreens(); + var remainingScreenPlayers = CGame.NumPlayers - screenPlayers * CConfig.GetNumScreens(); - for (int screen = 0; screen < CSettings.MaxNumScreens; screen++) + for (var screen = 0; screen < CSettings.MaxNumScreens; screen++) { - int currentScreenPlayers = screenPlayers; + var currentScreenPlayers = screenPlayers; if (remainingScreenPlayers > 0) { @@ -1585,34 +1800,42 @@ namespace Vocaluxe.Screens remainingScreenPlayers--; } - string curN = "N" + currentScreenPlayers; - string curS = "S" + (screen + 1); + var curN = "N" + currentScreenPlayers; + var curS = "S" + (screen + 1); - foreach (string se in _StaticsExtra[screen]) + foreach (var se in _StaticsExtra[screen]) { - string n = se.Substring(se.Length - 2); - string s = se.Substring(0, 2); + var n = se.Substring(se.Length - 2); + var s = se.Substring(0, 2); //Make StaticExtra elements with matching player number and active screen visible if (n == curN && s == curS && screen < CConfig.GetNumScreens()) + { _Statics[se].Visible = true; + } else + { _Statics[se].Visible = false; + } } - foreach (string te in _TextsExtra[screen]) + foreach (var te in _TextsExtra[screen]) { - string n = te.Substring(te.Length - 2); - string s = te.Substring(0, 2); + var n = te.Substring(te.Length - 2); + var s = te.Substring(0, 2); //Make TextExtra elements with matching player number and active screen visible if (n == curN && s == curS && screen < CConfig.GetNumScreens()) + { _Texts[te].Visible = true; + } else + { _Texts[te].Visible = false; + } } - for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) + for (var numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { - for (int player = 0; player < CSettings.MaxNumPlayer && player <= numplayer; player++) + for (var player = 0; player < CSettings.MaxNumPlayer && player <= numplayer; player++) { _Texts[_TextScores[screen, player, numplayer]].AllMonitors = false; _Texts[_TextScores[screen, player, numplayer]].Visible = false; @@ -1629,7 +1852,7 @@ namespace Vocaluxe.Screens } } - for (int player = 0; player < CGame.NumPlayers; player++) + for (var player = 0; player < CGame.NumPlayers; player++) { if (CScreenSong.GetAudioMode() == EAudioMode.TR_AUDIOMODE_KARAOKE) { @@ -1638,7 +1861,6 @@ namespace Vocaluxe.Screens _ProgressBars[_PlayerProgressBarRating[player]].Visible = false; _RatingPopups[_PlayerRatingPopup[player]].Visible = false; _SingNotes[_SingBars].Visible = false; - } else { @@ -1648,11 +1870,11 @@ namespace Vocaluxe.Screens _RatingPopups[_PlayerRatingPopup[player]].Visible = true; _SingNotes[_SingBars].Visible = true; } - - _Texts[_PlayerTextName[player]].Visible = (CConfig.Config.Theme.PlayerInfo == EPlayerInfo.TR_CONFIG_PLAYERINFO_BOTH || - CConfig.Config.Theme.PlayerInfo == EPlayerInfo.TR_CONFIG_PLAYERINFO_NAME); - _Statics[_PlayerStaticAvatar[player]].Visible = (CConfig.Config.Theme.PlayerInfo == EPlayerInfo.TR_CONFIG_PLAYERINFO_BOTH || - CConfig.Config.Theme.PlayerInfo == EPlayerInfo.TR_CONFIG_PLAYERINFO_AVATAR); + + _Texts[_PlayerTextName[player]].Visible = CConfig.Config.Theme.PlayerInfo == EPlayerInfo.TR_CONFIG_PLAYERINFO_BOTH || + CConfig.Config.Theme.PlayerInfo == EPlayerInfo.TR_CONFIG_PLAYERINFO_NAME; + _Statics[_PlayerStaticAvatar[player]].Visible = CConfig.Config.Theme.PlayerInfo == EPlayerInfo.TR_CONFIG_PLAYERINFO_BOTH || + CConfig.Config.Theme.PlayerInfo == EPlayerInfo.TR_CONFIG_PLAYERINFO_AVATAR; } _Lyrics[_LyricMain].Alpha = 0f; @@ -1683,27 +1905,31 @@ namespace Vocaluxe.Screens const float dt = 4f; const float rt = dt * 0.8f; - CSong song = CGame.GetSong(); + var song = CGame.GetSong(); if (song == null || !song.NotesLoaded) + { return null; + } var alpha = new float[song.Notes.VoiceCount * 2]; - float currentTime = _CurrentTime - song.Gap; + var currentTime = _CurrentTime - song.Gap; - for (int i = 0; i < song.Notes.VoiceCount; i++) + for (var i = 0; i < song.Notes.VoiceCount; i++) { - CVoice voice = song.Notes.GetVoice(i); - CSongLine[] lines = voice.Lines; + var voice = song.Notes.GetVoice(i); + var lines = voice.Lines; // find current line for lyric sub fading - int currentLineSub = _FindCurrentLine(voice, lines, song); + var currentLineSub = _FindCurrentLine(voice, lines, song); // find current line for lyric main fading - int currentLine = 0; - for (int j = 0; j < lines.Length; j++) + var currentLine = 0; + for (var j = 0; j < lines.Length; j++) { if (lines[j].FirstNoteBeat <= _CurrentBeat) + { currentLine = j; + } } // default values @@ -1711,31 +1937,33 @@ namespace Vocaluxe.Screens alpha[i * 2 + 1] = 1f; // main line alpha - if (currentLine == 0 && currentTime < CGame.GetTimeFromBeats(lines[currentLine].FirstNoteBeat, song.BPM)) + if (currentLine == 0 && currentTime < CGame.GetTimeFromBeats(lines[currentLine].FirstNoteBeat, song.Bpm)) { // first main line and fist note is not reached // => fade in - float diff = CGame.GetTimeFromBeats(lines[currentLine].FirstNoteBeat, song.BPM) - currentTime; + var diff = CGame.GetTimeFromBeats(lines[currentLine].FirstNoteBeat, song.Bpm) - currentTime; if (diff > dt) + { alpha[i * 2] = 1f - (diff - dt) / rt; + } } - else if (currentLine < lines.Length - 1 && CGame.GetTimeFromBeats(lines[currentLine].LastNoteBeat, song.BPM) < currentTime && - CGame.GetTimeFromBeats(lines[currentLine + 1].FirstNoteBeat, song.BPM) > currentTime) + else if (currentLine < lines.Length - 1 && CGame.GetTimeFromBeats(lines[currentLine].LastNoteBeat, song.Bpm) < currentTime && + CGame.GetTimeFromBeats(lines[currentLine + 1].FirstNoteBeat, song.Bpm) > currentTime) { // current position is between two lines // time between the to lines - float diff = CGame.GetTimeFromBeats(lines[currentLine + 1].FirstNoteBeat, song.BPM) - - CGame.GetTimeFromBeats(lines[currentLine].LastNoteBeat, song.BPM); + var diff = CGame.GetTimeFromBeats(lines[currentLine + 1].FirstNoteBeat, song.Bpm) - + CGame.GetTimeFromBeats(lines[currentLine].LastNoteBeat, song.Bpm); // fade only if there is enough time for fading if (diff > 3.3f * dt) { // time elapsed since last line - float last = currentTime - CGame.GetTimeFromBeats(lines[currentLine].LastNoteBeat, song.BPM); + var last = currentTime - CGame.GetTimeFromBeats(lines[currentLine].LastNoteBeat, song.Bpm); // time to next line - float next = CGame.GetTimeFromBeats(lines[currentLine + 1].FirstNoteBeat, song.BPM) - currentTime; + var next = CGame.GetTimeFromBeats(lines[currentLine + 1].FirstNoteBeat, song.Bpm) - currentTime; if (last < next) { @@ -1746,32 +1974,40 @@ namespace Vocaluxe.Screens { // fade in if it is time for if (next > dt) + { alpha[i * 2] = 1f - (next - dt) / rt; + } } } } - else if (currentLine == lines.Length - 1 && CGame.GetTimeFromBeats(lines[currentLine].LastNoteBeat, song.BPM) < currentTime) + else if (currentLine == lines.Length - 1 && CGame.GetTimeFromBeats(lines[currentLine].LastNoteBeat, song.Bpm) < currentTime) { // last main line and last note was reached // => fade out - float diff = currentTime - CGame.GetTimeFromBeats(lines[currentLine].LastNoteBeat, song.BPM); + var diff = currentTime - CGame.GetTimeFromBeats(lines[currentLine].LastNoteBeat, song.Bpm); alpha[i * 2] = 1f - diff / rt; } // sub - if ((currentLineSub + 1) < lines.Length) + if (currentLineSub + 1 < lines.Length) { - float diff = CGame.GetTimeFromBeats(lines[currentLineSub + 1].FirstNoteBeat, song.BPM) - currentTime; + var diff = CGame.GetTimeFromBeats(lines[currentLineSub + 1].FirstNoteBeat, song.Bpm) - currentTime; if (diff > dt) + { alpha[i * 2 + 1] = 1f - (diff - dt) / rt; + } } if (alpha[i * 2] < 0f) + { alpha[i * 2] = 0f; + } if (alpha[i * 2 + 1] < 0f) + { alpha[i * 2 + 1] = 0f; + } } return alpha; @@ -1784,21 +2020,21 @@ namespace Vocaluxe.Screens _TextScores = new string[CSettings.MaxNumScreens, CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; _TextNames = new string[CSettings.MaxNumScreens, CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; - for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) + for (var numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { - for (int player = 0; player < CSettings.MaxNumPlayer; player++) + for (var player = 0; player < CSettings.MaxNumPlayer; player++) { if (player <= numplayer) { - string target = "P" + (player + 1) + "N" + (numplayer + 1); - for (int screen = 0; screen < CSettings.MaxNumScreens; screen++) + var target = "P" + (player + 1) + "N" + (numplayer + 1); + for (var screen = 0; screen < CSettings.MaxNumScreens; screen++) { _TextScores[screen, player, numplayer] = "TextScoreS" + (screen + 1) + target; _TextNames[screen, player, numplayer] = "TextNameS" + (screen + 1) + target; } + texts.Add("TextScore" + target); texts.Add("TextName" + target); - } } } @@ -1806,15 +2042,15 @@ namespace Vocaluxe.Screens private void _CreatePlayerStrings() { - for (int screen = 0; screen < CSettings.MaxNumScreens; screen++) + for (var screen = 0; screen < CSettings.MaxNumScreens; screen++) { - for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) + for (var numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { - for (int player = 0; player < CSettings.MaxNumPlayer; player++) + for (var player = 0; player < CSettings.MaxNumPlayer; player++) { if (player <= numplayer) { - string target = "S" + (screen + 1) + "P" + (player + 1) + "N" + (numplayer + 1); + var target = "S" + (screen + 1) + "P" + (player + 1) + "N" + (numplayer + 1); _AddText(GetNewText(), "TextScore" + target); _AddText(GetNewText(), "TextName" + target); } @@ -1825,15 +2061,15 @@ namespace Vocaluxe.Screens private void _InitiatePlayerStrings() { - for (int screen = 0; screen < CSettings.MaxNumScreens; screen++) + for (var screen = 0; screen < CSettings.MaxNumScreens; screen++) { - for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) + for (var numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { - for (int player = 0; player < CSettings.MaxNumPlayer; player++) + for (var player = 0; player < CSettings.MaxNumPlayer; player++) { if (player <= numplayer) { - string target = "P" + (player + 1) + "N" + (numplayer + 1); + var target = "P" + (player + 1) + "N" + (numplayer + 1); _Texts["TextName" + target].Visible = false; _Texts["TextNameS" + (screen + 1) + target] = GetNewText(_Texts["TextName" + target]); _Texts["TextNameS" + (screen + 1) + target].X += screen * CSettings.RenderW; @@ -1852,21 +2088,21 @@ namespace Vocaluxe.Screens _StaticScores = new string[CSettings.MaxNumScreens, CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; _StaticAvatars = new string[CSettings.MaxNumScreens, CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; - for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) + for (var numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { - for (int player = 0; player < CSettings.MaxNumPlayer; player++) + for (var player = 0; player < CSettings.MaxNumPlayer; player++) { if (player <= numplayer) { - string target = "P" + (player + 1) + "N" + (numplayer + 1); - for (int screen = 0; screen < CSettings.MaxNumScreens; screen++) + var target = "P" + (player + 1) + "N" + (numplayer + 1); + for (var screen = 0; screen < CSettings.MaxNumScreens; screen++) { _StaticScores[screen, player, numplayer] = "StaticScoreS" + (screen + 1) + target; _StaticAvatars[screen, player, numplayer] = "StaticAvatarS" + (screen + 1) + target; } + statics.Add("StaticScore" + target); statics.Add("StaticAvatar" + target); - } } } @@ -1874,15 +2110,15 @@ namespace Vocaluxe.Screens private void _CreatePlayerStatics() { - for (int screen = 0; screen < CSettings.MaxNumScreens; screen++) + for (var screen = 0; screen < CSettings.MaxNumScreens; screen++) { - for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) + for (var numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { - for (int player = 0; player < CSettings.MaxNumPlayer; player++) + for (var player = 0; player < CSettings.MaxNumPlayer; player++) { if (player <= numplayer) { - string target = "S" + (screen + 1) + "P" + (player + 1) + "N" + (numplayer + 1); + var target = "S" + (screen + 1) + "P" + (player + 1) + "N" + (numplayer + 1); _AddStatic(GetNewStatic(), "StaticScore" + target); _AddStatic(GetNewStatic(), "StaticAvatar" + target); } @@ -1893,15 +2129,15 @@ namespace Vocaluxe.Screens private void _InitiatePlayerStatics() { - for (int screen = 0; screen < CSettings.MaxNumScreens; screen++) + for (var screen = 0; screen < CSettings.MaxNumScreens; screen++) { - for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) + for (var numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { - for (int player = 0; player < CSettings.MaxNumPlayer; player++) + for (var player = 0; player < CSettings.MaxNumPlayer; player++) { if (player <= numplayer) { - string target = "P" + (player + 1) + "N" + (numplayer + 1); + var target = "P" + (player + 1) + "N" + (numplayer + 1); _Statics["StaticAvatar" + target].Visible = false; _Statics["StaticAvatarS" + (screen + 1) + target] = GetNewStatic(_Statics["StaticAvatar" + target]); _Statics["StaticAvatarS" + (screen + 1) + target].X += screen * CSettings.RenderW; @@ -1918,15 +2154,15 @@ namespace Vocaluxe.Screens private void _BuildProgressBarStrings(ref List progressbars) { _ProgressBarsRating = new string[CSettings.MaxNumScreens, CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; - for (int screen = 0; screen < CSettings.MaxNumScreens; screen++) + for (var screen = 0; screen < CSettings.MaxNumScreens; screen++) { - for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) + for (var numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { - for (int player = 0; player < CSettings.MaxNumPlayer; player++) + for (var player = 0; player < CSettings.MaxNumPlayer; player++) { if (player <= numplayer) { - string target = "P" + (player + 1) + "N" + (numplayer + 1); + var target = "P" + (player + 1) + "N" + (numplayer + 1); _ProgressBarsRating[screen, player, numplayer] = "ProgressBarRatingS" + (screen + 1) + target; progressbars.Add("ProgressBarRating" + target); } @@ -1938,15 +2174,15 @@ namespace Vocaluxe.Screens private void _BuildRatingPopupStrings(ref List ratingPopups) { _RatingPopupsStrings = new string[CSettings.MaxNumScreens, CSettings.MaxNumPlayer, CSettings.MaxNumPlayer]; - for (int screen = 0; screen < CSettings.MaxNumScreens; screen++) + for (var screen = 0; screen < CSettings.MaxNumScreens; screen++) { - for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) + for (var numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { - for (int player = 0; player < CSettings.MaxNumPlayer; player++) + for (var player = 0; player < CSettings.MaxNumPlayer; player++) { if (player <= numplayer) { - string target = "P" + (player + 1) + "N" + (numplayer + 1); + var target = "P" + (player + 1) + "N" + (numplayer + 1); _RatingPopupsStrings[screen, player, numplayer] = "RatingPopupS" + (screen + 1) + target; ratingPopups.Add("RatingPopup" + target); } @@ -1957,15 +2193,15 @@ namespace Vocaluxe.Screens private void _CreateProgressBars() { - for (int screen = 0; screen < CSettings.MaxNumScreens; screen++) + for (var screen = 0; screen < CSettings.MaxNumScreens; screen++) { - for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) + for (var numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { - for (int player = 0; player < CSettings.MaxNumPlayer; player++) + for (var player = 0; player < CSettings.MaxNumPlayer; player++) { if (player <= numplayer) { - string target = "S" + (screen + 1) + "P" + (player + 1) + "N" + (numplayer + 1); + var target = "S" + (screen + 1) + "P" + (player + 1) + "N" + (numplayer + 1); _AddProgressBar(GetNewProgressBar(), "ProgressBarRating" + target); } } @@ -1975,15 +2211,15 @@ namespace Vocaluxe.Screens private void _CreateRatingPopups() { - for (int screen = 0; screen < CSettings.MaxNumScreens; screen++) + for (var screen = 0; screen < CSettings.MaxNumScreens; screen++) { - for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) + for (var numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { - for (int player = 0; player < CSettings.MaxNumPlayer; player++) + for (var player = 0; player < CSettings.MaxNumPlayer; player++) { if (player <= numplayer) { - string target = "S" + (screen + 1) + "P" + (player + 1) + "N" + (numplayer + 1); + var target = "S" + (screen + 1) + "P" + (player + 1) + "N" + (numplayer + 1); _AddRatingPopup(GetNewRatingPopup(), "RatingPopup" + target); } } @@ -1993,15 +2229,15 @@ namespace Vocaluxe.Screens private void _InitiateProgressBars() { - for (int screen = 0; screen < CSettings.MaxNumScreens; screen++) + for (var screen = 0; screen < CSettings.MaxNumScreens; screen++) { - for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) + for (var numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { - for (int player = 0; player < CSettings.MaxNumPlayer; player++) + for (var player = 0; player < CSettings.MaxNumPlayer; player++) { if (player <= numplayer) { - string target = "P" + (player + 1) + "N" + (numplayer + 1); + var target = "P" + (player + 1) + "N" + (numplayer + 1); _ProgressBars["ProgressBarRating" + target].Visible = false; _ProgressBars["ProgressBarRatingS" + (screen + 1) + target] = GetNewProgressBar(_ProgressBars["ProgressBarRating" + target]); _ProgressBars["ProgressBarRatingS" + (screen + 1) + target].X += screen * CSettings.RenderW; @@ -2013,15 +2249,15 @@ namespace Vocaluxe.Screens private void _InitiateRatingPopups() { - for (int screen = 0; screen < CSettings.MaxNumScreens; screen++) + for (var screen = 0; screen < CSettings.MaxNumScreens; screen++) { - for (int numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) + for (var numplayer = 0; numplayer < CSettings.MaxNumPlayer; numplayer++) { - for (int player = 0; player < CSettings.MaxNumPlayer; player++) + for (var player = 0; player < CSettings.MaxNumPlayer; player++) { if (player <= numplayer) { - string target = "P" + (player + 1) + "N" + (numplayer + 1); + var target = "P" + (player + 1) + "N" + (numplayer + 1); _RatingPopups["RatingPopup" + target].Visible = false; _RatingPopups["RatingPopupS" + (screen + 1) + target] = GetNewRatingPopup(_RatingPopups["RatingPopup" + target]); _RatingPopups["RatingPopupS" + (screen + 1) + target].X += screen * CSettings.RenderW; @@ -2035,9 +2271,9 @@ namespace Vocaluxe.Screens { _StaticsExtra = new List[CSettings.MaxNumScreens]; - List extraStatics = new List(); + var extraStatics = new List(); - foreach (CStatic se in _Statics) + foreach (var se in _Statics) { if (se.GetThemeName() != null && se.GetThemeName().StartsWith("StaticExtra")) { @@ -2046,19 +2282,18 @@ namespace Vocaluxe.Screens } } - for (int screen = 0; screen < CSettings.MaxNumScreens; screen++) + for (var screen = 0; screen < CSettings.MaxNumScreens; screen++) { _StaticsExtra[screen] = new List(); - foreach (string es in extraStatics) + foreach (var es in extraStatics) { - string name = "S" + (screen + 1) + es; + var name = "S" + (screen + 1) + es; _AddStatic(GetNewStatic(), name); _Statics[name] = GetNewStatic(_Statics[es]); _Statics[name].X += screen * CSettings.RenderW; _Statics[name].AllMonitors = false; _StaticsExtra[screen].Add(name); } - } } @@ -2066,9 +2301,9 @@ namespace Vocaluxe.Screens { _TextsExtra = new List[CSettings.MaxNumScreens]; - List extraTexts = new List(); + var extraTexts = new List(); - foreach (CText te in _Texts) + foreach (var te in _Texts) { if (te.GetThemeName() != null && te.GetThemeName().StartsWith("TextExtra")) { @@ -2077,50 +2312,56 @@ namespace Vocaluxe.Screens } } - for (int screen = 0; screen < CSettings.MaxNumScreens; screen++) + for (var screen = 0; screen < CSettings.MaxNumScreens; screen++) { _TextsExtra[screen] = new List(); - foreach (string et in extraTexts) + foreach (var et in extraTexts) { - string name = "S" + (screen + 1) + et; + var name = "S" + (screen + 1) + et; _AddText(GetNewText(), name); _Texts[name] = GetNewText(_Texts[et]); _Texts[name].X += screen * CSettings.RenderW; _Texts[name].AllMonitors = false; _TextsExtra[screen].Add(name); } - } } #endregion private int _FindCurrentLine(CVoice voice, CSongLine[] lines, CSong song) { - float currentTime = _CurrentTime - song.Gap; + var currentTime = _CurrentTime - song.Gap; //We are only interested in the last matching line, so either do not check further after line[j].StartBeat > _CurrentBeat or go backwards! - int j = voice.FindPreviousLine(_CurrentBeat); + var j = voice.FindPreviousLine(_CurrentBeat); for (; j >= 0; j--) { - float firstNoteTime = CGame.GetTimeFromBeats(lines[j].FirstNoteBeat, song.BPM); + var firstNoteTime = CGame.GetTimeFromBeats(lines[j].FirstNoteBeat, song.Bpm); //Earlist possible line break is 10s before first note if (firstNoteTime <= currentTime + 10f) { //First line has no predecessor or line has to be shown if (j == 0 || firstNoteTime - CConfig.Config.Game.MinLineBreakTime <= currentTime) + { return j; - float lastNoteTime = CGame.GetTimeFromBeats(lines[j - 1].LastNoteBeat, song.BPM); + } + + var lastNoteTime = CGame.GetTimeFromBeats(lines[j - 1].LastNoteBeat, song.Bpm); //No line break if last line is not fully evaluated (with 50% tolerance -> tested so notes are drawn) if (lastNoteTime + CConfig.Config.Record.MicDelay / 1000f * 1.5f >= currentTime) + { return j - 1; + } + return j; } } + return -1; } private void _PrepareTimeLine() { - CStatic stat = _Statics[_StaticTimeLine]; + var stat = _Statics[_StaticTimeLine]; switch (CConfig.Config.Theme.TimerLook) { case ETimerLook.TR_CONFIG_TIMERLOOK_NORMAL: @@ -2132,64 +2373,80 @@ namespace Vocaluxe.Screens _TimeRects.Clear(); _Statics[_StaticTimePointer].Visible = true; - CSong song = CGame.GetSong(); + var song = CGame.GetSong(); if (song == null) + { return; + } - float totalTime = CSound.GetLength(_CurrentStream); - if (Math.Abs(song.Finish) > 0.001) - totalTime = song.Finish; + var totalTime = CSound.GetLength(_CurrentStream); + if (Math.Abs(song.End) > 0.001) + { + totalTime = song.End; + } totalTime -= song.Start; if (totalTime <= 0f) + { return; + } _Length = totalTime; - foreach (CVoice voice in song.Notes.Voices) + foreach (var voice in song.Notes.Voices) { - foreach (CSongLine line in voice.Lines.Where(line => line.VisibleInTimeLine)) + foreach (var line in voice.Lines.Where(line => line.VisibleInTimeLine)) { var trect = new STimeRect { StartBeat = line.FirstNoteBeat, EndBeat = line.EndBeat }; trect.Rect = GetNewStatic(null, - new SColorF(1f, 1f, 1f, 1f), - new SRectF( - stat.Rect.X + stat.Rect.W * ((CGame.GetTimeFromBeats(trect.StartBeat, song.BPM) + song.Gap - song.Start) / totalTime), - stat.Rect.Y, - stat.Rect.W * (CGame.GetTimeFromBeats(trect.EndBeat - trect.StartBeat, song.BPM) / totalTime), - stat.Rect.H, - stat.Rect.Z)); + new SColorF(1f, 1f, 1f, 1f), + new SRectF( + stat.Rect.X + stat.Rect.W * ((CGame.GetTimeFromBeats(trect.StartBeat, song.Bpm) + song.Gap - song.Start) / totalTime), + stat.Rect.Y, + stat.Rect.W * (CGame.GetTimeFromBeats(trect.EndBeat - trect.StartBeat, song.Bpm) / totalTime), + stat.Rect.H, + stat.Rect.Z)); _TimeRects.Add(trect); } } + break; } } private void _UpdateAvatars() { - for (int i = 0; i < CGame.NumPlayers; i++) + for (var i = 0; i < CGame.NumPlayers; i++) { - if (CProfiles.IsProfileIDValid(CGame.Players[i].ProfileID)) - _Statics[_PlayerStaticAvatar[i]].Texture = CProfiles.GetAvatarTextureFromProfile(CGame.Players[i].ProfileID); + if (CProfiles.IsProfileIdValid(CGame.Players[i].ProfileId)) + { + _Statics[_PlayerStaticAvatar[i]].Texture = CProfiles.GetAvatarTextureFromProfile(CGame.Players[i].ProfileId); + } else + { _Statics[_PlayerStaticAvatar[i]].Visible = false; + } } } private void _UpdateNames() { - for (int i = 0; i < CGame.NumPlayers; i++) + for (var i = 0; i < CGame.NumPlayers; i++) { - if (CProfiles.IsProfileIDValid(CGame.Players[i].ProfileID)) - _Texts[_PlayerTextName[i]].Text = CProfiles.GetPlayerName(CGame.Players[i].ProfileID); + if (CProfiles.IsProfileIdValid(CGame.Players[i].ProfileId)) + { + _Texts[_PlayerTextName[i]].Text = CProfiles.GetPlayerName(CGame.Players[i].ProfileId); + } else + { _Texts[_PlayerTextName[i]].Visible = false; + } } } + private void _AssignPlayerElements() { _PlayerTextScore = new String[CGame.NumPlayers]; @@ -2199,13 +2456,13 @@ namespace Vocaluxe.Screens _PlayerProgressBarRating = new String[CGame.NumPlayers]; _PlayerRatingPopup = new String[CGame.NumPlayers]; - int screenPlayers = CGame.NumPlayers / CConfig.GetNumScreens(); - int remainingPlayers = CGame.NumPlayers - (screenPlayers * CConfig.GetNumScreens()); - int player = 0; + var screenPlayers = CGame.NumPlayers / CConfig.GetNumScreens(); + var remainingPlayers = CGame.NumPlayers - screenPlayers * CConfig.GetNumScreens(); + var player = 0; - for (int s = 0; s < CConfig.GetNumScreens(); s++) + for (var s = 0; s < CConfig.GetNumScreens(); s++) { - for (int p = 0; p < screenPlayers; p++) + for (var p = 0; p < screenPlayers; p++) { if (remainingPlayers > 0) { @@ -2235,8 +2492,8 @@ namespace Vocaluxe.Screens _PlayerStaticAvatar[player] = _StaticAvatars[s, p, screenPlayers - 1]; _PlayerStaticScore[player++] = _StaticScores[s, p, screenPlayers - 1]; } - } + //Handle when players < screens if (screenPlayers == 0 && remainingPlayers > 0) { @@ -2251,4 +2508,4 @@ namespace Vocaluxe.Screens } } } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenSong.cs b/Vocaluxe/Screens/CScreenSong.cs index 666bd655..f157cf2a 100644 --- a/Vocaluxe/Screens/CScreenSong.cs +++ b/Vocaluxe/Screens/CScreenSong.cs @@ -17,7 +17,6 @@ using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Linq; using System.Timers; using System.Windows.Forms; @@ -26,7 +25,6 @@ using VocaluxeLib; using VocaluxeLib.Menu; using VocaluxeLib.Menu.SongMenu; using VocaluxeLib.PartyModes; -using VocaluxeLib.Songs; namespace Vocaluxe.Screens { @@ -87,7 +85,7 @@ namespace Vocaluxe.Screens private const string _SongMenuName = "SongMenu"; private const string _PlaylistName = "Playlist"; - private string _SearchText = String.Empty; + private string _SearchText = string.Empty; private bool _SearchActive; private int _JumpTo_lastCharTime = 0; @@ -103,7 +101,7 @@ namespace Vocaluxe.Screens private int _OldMousePosX; private int _OldMousePosY; - private int _SelectedSongID; + private int _SelectedSongId; private int _SelectedCategoryIndex; private ISongMenu _SongMenu; @@ -125,28 +123,28 @@ namespace Vocaluxe.Screens return _PlayerSelect; } - private static int _StaticSelectedCategoryIndex = -1; - - private static void SetStaticSelectedCategoryIndex(int categoryIndex) - { - _StaticSelectedCategoryIndex = categoryIndex; - } + private static int _StaticSelectedCategoryIndex = -1; - private static int GetStaticSelectedCategoryIndex() - { - return _StaticSelectedCategoryIndex; - } - - private static int _StaticSelectedSongID; - - private static void setStaticSelectedSongID(int songID) + private static void SetStaticSelectedCategoryIndex(int categoryIndex) { - _StaticSelectedSongID = songID; + _StaticSelectedCategoryIndex = categoryIndex; } - public static int getSelectedSongID() + private static int GetStaticSelectedCategoryIndex() { - return _StaticSelectedSongID; + return _StaticSelectedCategoryIndex; + } + + private static int _StaticSelectedSongId; + + private static void setStaticSelectedSongId(int songId) + { + _StaticSelectedSongId = songId; + } + + public static int getSelectedSongId() + { + return _StaticSelectedSongId; } public override EMusicType CurrentMusicType @@ -164,8 +162,11 @@ namespace Vocaluxe.Screens base.Init(); _ButtonsJoker.Clear(); - for (int i = 0; i < CSettings.MaxNumPlayer; i++) + for (var i = 0; i < CSettings.MaxNumPlayer; i++) + { _ButtonsJoker.Add("ButtonJoker" + (i + 1)); + } + var blist = new List(); blist.AddRange(_ButtonsJoker); blist.Add(_ButtonOptionsClose); @@ -183,8 +184,11 @@ namespace Vocaluxe.Screens blist.Add(_ButtonOptionsHighscore); _TextsPlayer.Clear(); - for (int i = 0; i < CSettings.MaxNumPlayer; i++) + for (var i = 0; i < CSettings.MaxNumPlayer; i++) + { _TextsPlayer.Add("TextPlayer" + (i + 1)); + } + var tlist = new List(); tlist.AddRange(_TextsPlayer); tlist.Add(_TextCategory); @@ -199,15 +203,19 @@ namespace Vocaluxe.Screens tlist.Add(_TextOptionsAudioMode); tlist.Add(_TextOptionsPlayerSelect); tlist.Add(_TextOptionsPlaylist); - + tlist.Add(_TextShortInfoTop); - _ThemeStatics = new string[] {_StaticSearchBar, _StaticOptionsBG, _StaticShortInfoTop}; + _ThemeStatics = new string[] { _StaticSearchBar, _StaticOptionsBG, _StaticShortInfoTop }; _ThemeTexts = tlist.ToArray(); _ThemeButtons = blist.ToArray(); - _ThemeSelectSlides = new string[] {_SelectSlideOptionsMode, _SelectSlideOptionsPlayerSelect, _SelectSlideOptionsAudioMode, _SelectSlideOptionsPlaylistAdd, _SelectSlideOptionsPlaylistOpen, _SelectSlideOptionsNumMedleySongs}; - _ThemeSongMenus = new string[] {_SongMenuName}; - _ThemePlaylists = new string[] {_PlaylistName}; + _ThemeSelectSlides = new string[] + { + _SelectSlideOptionsMode, _SelectSlideOptionsPlayerSelect, _SelectSlideOptionsAudioMode, _SelectSlideOptionsPlaylistAdd, _SelectSlideOptionsPlaylistOpen, + _SelectSlideOptionsNumMedleySongs + }; + _ThemeSongMenus = new string[] { _SongMenuName }; + _ThemePlaylists = new string[] { _PlaylistName }; _DragAndDropCover = GetNewStatic(); @@ -245,15 +253,20 @@ namespace Vocaluxe.Screens { //Check if playlist was closed and song menu needed to be resized if (!_Playlist.Visible) + { _SongMenu.SmallView = false; + } + return true; } + if (!keyEvent.KeyPressed && keyEvent.Key == Keys.Escape) { _ClosePlaylist(); keyEvent.Handled = true; return true; } + if (keyEvent.Key == Keys.Enter && _Playlist.isButtonPlaylistListSelected()) { _TogglePlaylistFilter(); @@ -266,14 +279,18 @@ namespace Vocaluxe.Screens base.HandleInput(keyEvent); _Playlist.Selectable = true; if (keyEvent.Handled) + { return true; + } if (_CurSongOptionsView == ESongOptionsView.None) { if (keyEvent.KeyPressed && !Char.IsControl(keyEvent.Unicode) && keyEvent.Mod != EModifier.Ctrl) { if (_SearchActive) + { _ApplyNewSearchFilter(_SearchText + keyEvent.Unicode); + } else if (!_Sso.Selection.PartyMode) { _JumpTo(keyEvent.Unicode); @@ -283,28 +300,36 @@ namespace Vocaluxe.Screens else { if (_SongMenu.HandleInput(ref keyEvent, _Sso)) + { keyEvent.Handled = true; + } if (keyEvent.Handled) + { return true; + } switch (keyEvent.Key) { case Keys.Escape: if ((CSongs.Category < 0 || _Sso.Sorting.Tabs == EOffOn.TR_CONFIG_OFF) && !_Sso.Selection.PartyMode && !_SearchActive) + { CGraphics.FadeTo(EScreen.Main); + } + if (_SearchActive) { _SearchActive = false; - _SearchText = String.Empty; + _SearchText = string.Empty; _ApplyNewSearchFilter(_SearchText); } + break; case Keys.Enter: if (_Sso.Selection.RandomOnly && _Sso.Selection.NumJokers != null) { - for (int i = 0; i < _ButtonsJoker.Count; i++) + for (var i = 0; i < _ButtonsJoker.Count; i++) { if (i < _Sso.Selection.NumJokers.Length) { @@ -315,14 +340,21 @@ namespace Vocaluxe.Screens } } } + if (_Buttons[_ButtonStart].Selected) + { _HandlePartySongSelection(_SongMenu.GetPreviewSongNr()); + } } + if (CSongs.NumSongsVisible > 0 && !_Sso.Selection.PartyMode) { if (_SongMenu.GetPreviewSongNr() != -1) + { _ToggleSongOptions(ESongOptionsView.Song); + } } + break; case Keys.Tab: @@ -331,16 +363,21 @@ namespace Vocaluxe.Screens _Playlist.Selected = !_Playlist.Selected; _SongMenu.Selected = !_Playlist.Selected; } + break; case Keys.Back: if (_SearchActive) { if (_SearchText != "") + { _ApplyNewSearchFilter(_SearchText.Remove(_SearchText.Length - 1)); + } } else if ((!CSongs.IsInCategory || _Sso.Sorting.Tabs == EOffOn.TR_CONFIG_OFF) && !_Sso.Selection.PartyMode) + { CGraphics.FadeTo(EScreen.Main); + } break; @@ -348,26 +385,38 @@ namespace Vocaluxe.Screens if (_SearchActive) { _SearchActive = false; - _SearchText = String.Empty; + _SearchText = string.Empty; _ApplyNewSearchFilter(_SearchText); } else if (!_Sso.Selection.PartyMode) + { _SearchActive = true; + } + break; case Keys.V: if (keyEvent.Mod == EModifier.Ctrl && !_Sso.Selection.PartyMode) + { _StartRandomVisibleSongs(); + } + break; case Keys.R: if (keyEvent.Mod == EModifier.Ctrl && !_Sso.Selection.RandomOnly) + { _SelectNextRandom(-1); + } + break; case Keys.S: if (keyEvent.Mod == EModifier.Ctrl && CSongs.NumSongsVisible > 0 && !_Sso.Selection.PartyMode) + { _StartMedleySong(_SongMenu.GetPreviewSongNr()); + } + break; case Keys.T: @@ -375,6 +424,7 @@ namespace Vocaluxe.Screens { _ToggleTabs(); } + break; case Keys.D0: @@ -389,14 +439,17 @@ namespace Vocaluxe.Screens case Keys.D9: if (keyEvent.Mod == EModifier.Ctrl && !_Sso.Selection.PartyMode) { - int tempSortNr = -1; + var tempSortNr = -1; int.TryParse(keyEvent.Key.ToString().Substring(1), out tempSortNr); - + if (tempSortNr == 0) + { tempSortNr = 10; + } _ToggleSort(tempSortNr); } + break; case Keys.H: @@ -404,6 +457,7 @@ namespace Vocaluxe.Screens { _ShowHighscore(); } + break; case Keys.L: @@ -411,25 +465,36 @@ namespace Vocaluxe.Screens { _TogglePlaylistFilter(); } + break; } + if (!_SearchActive) { switch (keyEvent.Key) { case Keys.Space: if (!_Sso.Selection.PartyMode && !_Playlist.isPlaylistNameEditMode()) + { _ToggleSongOptions(ESongOptionsView.General); + } + break; case Keys.A: if (keyEvent.Mod == EModifier.Ctrl && !_Sso.Selection.PartyMode) + { _StartRandomAllSongs(); + } + break; case Keys.F: if (keyEvent.Mod == EModifier.Ctrl && !_Sso.Selection.PartyMode) + { _SearchActive = true; + } + break; case Keys.D1: @@ -471,7 +536,9 @@ namespace Vocaluxe.Screens { case Keys.Enter: if (_Buttons[_ButtonOptionsClose].Selected) + { _ToggleSongOptions(ESongOptionsView.None); + } else if (_Buttons[_ButtonOptionsSing].Selected) { _ToggleSongOptions(ESongOptionsView.None); @@ -485,25 +552,41 @@ namespace Vocaluxe.Screens else if (_Buttons[_ButtonOptionsRandom].Selected) { if (CSongs.IsInCategory) + { _SongMenu.SetSelectedSong(CSongs.GetRandomSong()); + } } else if (_Buttons[_ButtonOptionsRandomCategory].Selected) { if (!CSongs.IsInCategory) + { _SongMenu.SetSelectedCategory(CSongs.GetRandomCategory()); + } } else if (_Buttons[_ButtonOptionsSingAll].Selected) + { _StartRandomAllSongs(); + } else if (_Buttons[_ButtonOptionsSingAllVisible].Selected) + { _StartRandomVisibleSongs(); + } else if (_Buttons[_ButtonOptionsOpenSelectedItem].Selected) + { _HandleSelectButton(); + } else if (_SelectSlides[_SelectSlideOptionsPlaylistOpen].Selected) + { _OpenPlaylist(_SelectSlides[_SelectSlideOptionsPlaylistOpen].SelectedTag); + } else if (_SelectSlides[_SelectSlideOptionsPlaylistAdd].Selected) + { _OpenPlaylist(_SelectSlides[_SelectSlideOptionsPlaylistAdd].SelectedTag); + } else if (_Buttons[_ButtonOptionsRandomMedley].Selected) + { _ToggleSongOptions(ESongOptionsView.Medley); + } else if (_Buttons[_ButtonOptionsStartMedley].Selected) { _ToggleSongOptions(ESongOptionsView.None); @@ -513,6 +596,7 @@ namespace Vocaluxe.Screens { _ShowHighscore(); } + break; case Keys.Escape: @@ -522,6 +606,7 @@ namespace Vocaluxe.Screens break; } } + return true; } @@ -529,29 +614,31 @@ namespace Vocaluxe.Screens { base.HandleMouse(mouseEvent); - bool overSearchBar = _Statics[_StaticSearchBar].Visible && CHelper.IsInBounds(_Statics[_StaticSearchBar].Rect, mouseEvent) && !_Sso.Selection.PartyMode; - _Texts[_TextSearchBarTitle].Selected = overSearchBar; + var overSearchBar = _Statics[_StaticSearchBar].Visible && CHelper.IsInBounds(_Statics[_StaticSearchBar].Rect, mouseEvent) && !_Sso.Selection.PartyMode; + _Texts[_TextSearchBarTitle].Selected = overSearchBar; - if (mouseEvent.LB && overSearchBar) - { - if (_SearchActive) - { - _SearchActive = false; - _SearchText = String.Empty; - _ApplyNewSearchFilter(_SearchText); - } - else if (!_Sso.Selection.PartyMode) - { - _SearchActive = true; - } - return true; - } + if (mouseEvent.LB && overSearchBar) + { + if (_SearchActive) + { + _SearchActive = false; + _SearchText = string.Empty; + _ApplyNewSearchFilter(_SearchText); + } + else if (!_Sso.Selection.PartyMode) + { + _SearchActive = true; + } + + return true; + } if (_DragAndDropCover.Visible) { _DragAndDropCover.X += mouseEvent.X - _OldMousePosX; _DragAndDropCover.Y += mouseEvent.Y - _OldMousePosY; } + _OldMousePosX = mouseEvent.X; _OldMousePosY = mouseEvent.Y; @@ -563,9 +650,13 @@ namespace Vocaluxe.Screens { //Check if playlist was closed and song menu needed to be resized if (!_Playlist.Visible) + { _SongMenu.SmallView = false; + } + return true; } + if (mouseEvent.LB && _Playlist.isButtonPlaylistListSelected()) { _TogglePlaylistFilter(); @@ -581,7 +672,7 @@ namespace Vocaluxe.Screens _ToggleSongOptions(ESongOptionsView.None); } } - + if (mouseEvent.RB) { if (_CurSongOptionsView != ESongOptionsView.None) @@ -593,7 +684,7 @@ namespace Vocaluxe.Screens if (_SearchActive) { _SearchActive = false; - _SearchText = String.Empty; + _SearchText = string.Empty; _ApplyNewSearchFilter(_SearchText); return true; } @@ -606,7 +697,9 @@ namespace Vocaluxe.Screens } if (mouseEvent.MB && !_Sso.Selection.PartyMode) + { return _SelectNextRandom(-1); + } if (mouseEvent.LD && !_Sso.Selection.PartyMode) { @@ -621,13 +714,18 @@ namespace Vocaluxe.Screens if (_CurSongOptionsView == ESongOptionsView.None) { if (_SongMenu.HandleMouse(ref mouseEvent, _Sso)) + { mouseEvent.Handled = true; + } } if (mouseEvent.Handled) { if (_CurSongOptionsView != ESongOptionsView.None) + { _ToggleSongOptions(ESongOptionsView.None); + } + return true; } @@ -640,23 +738,27 @@ namespace Vocaluxe.Screens _ToggleSongOptions(ESongOptionsView.General); return true; } + if (_Buttons[_ButtonOptionsClose].Selected) { _ToggleSongOptions(ESongOptionsView.None); return true; } + if (_Buttons[_ButtonOptionsSing].Selected) { _ToggleSongOptions(ESongOptionsView.None); _StartSong(_SongMenu.GetPreviewSongNr()); return true; } + if (_Buttons[_ButtonOptionsPlaylist].Selected) { _ToggleSongOptions(ESongOptionsView.None); _OpenAndAddPlaylistAction(); return true; } + if (_Buttons[_ButtonOptionsRandom].Selected) { if (CSongs.IsInCategory) @@ -723,7 +825,7 @@ namespace Vocaluxe.Screens return true; } - for (int i = 0; i < _ButtonsJoker.Count; i++) + for (var i = 0; i < _ButtonsJoker.Count; i++) { if (i < _Sso.Selection.NumJokers.Length) { @@ -748,13 +850,13 @@ namespace Vocaluxe.Screens { if (!_DragAndDropCover.Visible && _Playlist.Visible && CSongs.NumSongsVisible > 0 && _SongMenu.GetSelectedSongNr() != -1) { - CStatic cover = _SongMenu.GetSelectedSongCover(); + var cover = _SongMenu.GetSelectedSongCover(); _DragAndDropCover.Texture = cover.Texture; _DragAndDropCover.Aspect = cover.Aspect; _DragAndDropCover.MaxRect = cover.Rect; _DragAndDropCover.Color = cover.Color; _DragAndDropCover.Z = CSettings.ZNear; - _Playlist.DragAndDropSongID = CSongs.VisibleSongs[_SongMenu.GetSelectedSongNr()].ID; + _Playlist.DragAndDropSongId = CSongs.VisibleSongs[_SongMenu.GetSelectedSongNr()].Id; _DragAndDropCover.Visible = true; return true; } @@ -764,7 +866,7 @@ namespace Vocaluxe.Screens if (!mouseEvent.LBH && _DragAndDropCover.Visible) { _DragAndDropCover.Visible = false; - _Playlist.DragAndDropSongID = -1; + _Playlist.DragAndDropSongId = -1; return true; } @@ -776,12 +878,14 @@ namespace Vocaluxe.Screens if (CSongs.IsInCategory) { if (!_Sso.Selection.PartyMode) + { _ToggleSongOptions(ESongOptionsView.Song); + } } else if (_Sso.Selection.CategoryChangeAllowed) { _ToggleSongOptions(ESongOptionsView.None); - _SelectedCategoryIndex = _SongMenu.GetSelectedCategory(); + _SelectedCategoryIndex = _SongMenu.GetSelectedCategory(); _SongMenu.EnterSelectedCategory(); } } @@ -790,11 +894,12 @@ namespace Vocaluxe.Screens { base.OnShow(); - _SelectedSongID = -1; + _SelectedSongId = -1; _SelectedCategoryIndex = -2; _Sso = CParty.GetSongSelectionOptions(); - CSongs.Sort(_Sso.Sorting.SongSorting, _Sso.Sorting.Tabs, _Sso.Sorting.IgnoreArticles, _Sso.Sorting.SearchString, _Sso.Sorting.DuetOptions, _Sso.Sorting.FilterPlaylistID); + CSongs.Sort(_Sso.Sorting.SongSorting, _Sso.Sorting.Tabs, _Sso.Sorting.IgnoreArticles, _Sso.Sorting.SearchString, _Sso.Sorting.DuetOptions, + _Sso.Sorting.FilterPlaylistId); if (_Sso.Selection.CategoryIndex != CBase.Songs.GetCurrentCategoryIndex()) { _SelectedCategoryIndex = _Sso.Selection.CategoryIndex; @@ -808,37 +913,42 @@ namespace Vocaluxe.Screens CBase.Songs.SetCategory(-1); } } + _SearchActive = _Sso.Sorting.SearchActive; _SearchText = _Sso.Sorting.SearchString; CGame.Reset(); _SongMenu.OnShow(); - if (_Sso.Sorting.Tabs == EOffOn.TR_CONFIG_ON) - { - int lastCategoryIndex = GetStaticSelectedCategoryIndex(); + if (_Sso.Sorting.Tabs == EOffOn.TR_CONFIG_ON) + { + var lastCategoryIndex = GetStaticSelectedCategoryIndex(); - if (CBase.Songs.IsInCategory()) - CBase.Songs.SetCategory(-1); + if (CBase.Songs.IsInCategory()) + { + CBase.Songs.SetCategory(-1); + } - _SongMenu.OnShow(); + _SongMenu.OnShow(); - if (lastCategoryIndex >= 0 && lastCategoryIndex < CSongs.Categories.Count) - _SongMenu.SetSelectedCategory(lastCategoryIndex); - } + if (lastCategoryIndex >= 0 && lastCategoryIndex < CSongs.Categories.Count) + { + _SongMenu.SetSelectedCategory(lastCategoryIndex); + } + } - int lastSongId = getSelectedSongID(); - if (CSongs.IsInCategory && lastSongId >= 0) - { - for (int i = 0; i < CSongs.VisibleSongs.Count; i++) - { - if (CSongs.VisibleSongs[i].ID == lastSongId) - { - _SongMenu.SetSelectedSong(i); - break; - } - } - } + var lastSongId = getSelectedSongId(); + if (CSongs.IsInCategory && lastSongId >= 0) + { + for (var i = 0; i < CSongs.VisibleSongs.Count; i++) + { + if (CSongs.VisibleSongs[i].Id == lastSongId) + { + _SongMenu.SetSelectedSong(i); + break; + } + } + } if (_Sso.Selection.PartyMode) { @@ -850,11 +960,13 @@ namespace Vocaluxe.Screens _SongMenu.Selected = !_Playlist.Visible; _SongMenu.SmallView = _Playlist.Visible; - if (_Playlist.ActivePlaylistID != -1) - _Playlist.LoadPlaylist(_Playlist.ActivePlaylistID); + if (_Playlist.ActivePlaylistId != -1) + { + _Playlist.LoadPlaylist(_Playlist.ActivePlaylistId); + } _DragAndDropCover.Visible = false; - _Playlist.DragAndDropSongID = -1; + _Playlist.DragAndDropSongId = -1; _Statics[_StaticShortInfoTop].Visible = false; _Texts[_TextShortInfoTop].Visible = false; @@ -877,27 +989,36 @@ namespace Vocaluxe.Screens { if (_Playlist.Visible) { - if (_Playlist.ActivePlaylistID == -1) + if (_Playlist.ActivePlaylistId == -1) + { _ClosePlaylist(); + } else + { _Playlist.UpdateGame(); + } } _Texts[_TextCategory].Text = CSongs.GetCurrentCategoryName(); - string selectionText = ""; + var selectionText = ""; if (CSongs.IsInCategory) { - int song = _SongMenu.GetSelectedSongNr(); + var song = _SongMenu.GetSelectedSongNr(); if (song >= 0 && song < CSongs.VisibleSongs.Count) - selectionText = CSongs.VisibleSongs[song].Artist + " - " + CSongs.VisibleSongs[song].Title + " ( "+(song+1)+" / "+CSongs.NumSongsVisible+" )"; + { + selectionText = CSongs.VisibleSongs[song].Artist + " - " + CSongs.VisibleSongs[song].Title + " ( " + (song + 1) + " / " + CSongs.NumSongsVisible + " )"; + } } else { - int cat = _SongMenu.GetSelectedCategory(); + var cat = _SongMenu.GetSelectedCategory(); if (!CSongs.IsInCategory && cat >= 0 && cat < CSongs.Categories.Count) + { _Texts[_TextSelection].Text = CSongs.Categories[cat].Name; + } } + _Texts[_TextSelection].Text = selectionText; _Texts[_TextSearchBar].Text = _SearchText; @@ -935,18 +1056,22 @@ namespace Vocaluxe.Screens private void _HandlePartySongSelection(int songNr) { - if (CSongs.IsInCategory && (songNr >= 0)) + if (CSongs.IsInCategory && songNr >= 0) { - CSong song = CSongs.VisibleSongs[songNr]; + var song = CSongs.VisibleSongs[songNr]; if (song != null) - CParty.SongSelected(song.ID); + { + CParty.SongSelected(song.Id); + } } } private void _UpdatePartyModeOptions() { if (!CSongs.IsInCategory) - _SelectedSongID = -1; + { + _SelectedSongId = -1; + } if (_SelectedCategoryIndex != CSongs.Category) { @@ -954,21 +1079,26 @@ namespace Vocaluxe.Screens CParty.OnCategoryChange(_SelectedCategoryIndex, ref _Sso); if (_Sso.Selection.SelectNextRandomSong) + { _SelectNextRandomSong(); + } if (_Sso.Selection.SongIndex != -1) + { _SongMenu.SetSelectedSong(_Sso.Selection.SongIndex); + } } - if (_SelectedSongID != _SongMenu.GetPreviewSongNr() && CSongs.IsInCategory) + if (_SelectedSongId != _SongMenu.GetPreviewSongNr() && CSongs.IsInCategory) { - _SelectedSongID = _SongMenu.GetPreviewSongNr(); - CParty.OnSongChange(_SelectedSongID, ref _Sso); + _SelectedSongId = _SongMenu.GetPreviewSongNr(); + CParty.OnSongChange(_SelectedSongId, ref _Sso); } if (_Sso.Selection.PartyMode) { - CSongs.Sort(_Sso.Sorting.SongSorting, _Sso.Sorting.Tabs, _Sso.Sorting.IgnoreArticles, _Sso.Sorting.SearchString, _Sso.Sorting.DuetOptions, _Sso.Sorting.FilterPlaylistID); + CSongs.Sort(_Sso.Sorting.SongSorting, _Sso.Sorting.Tabs, _Sso.Sorting.IgnoreArticles, _Sso.Sorting.SearchString, _Sso.Sorting.DuetOptions, + _Sso.Sorting.FilterPlaylistId); _SearchActive = _Sso.Sorting.SearchActive; _SearchText = _Sso.Sorting.SearchString; @@ -986,7 +1116,7 @@ namespace Vocaluxe.Screens _SongMenu.SmallView = true; - for (int i = 0; i < CSettings.MaxNumPlayer; i++) + for (var i = 0; i < CSettings.MaxNumPlayer; i++) { if (i < _Sso.Selection.NumJokers.Length) { @@ -994,7 +1124,7 @@ namespace Vocaluxe.Screens _Buttons[_ButtonsJoker[i]].Text.Text = _Sso.Selection.NumJokers[i].ToString(); _Texts[_TextsPlayer[i]].Visible = true; - bool nameExists = false; + var nameExists = false; if (_Sso.Selection.TeamNames != null) { if (_Sso.Selection.TeamNames.Length > i) @@ -1005,7 +1135,9 @@ namespace Vocaluxe.Screens } if (!nameExists) + { _Texts[_TextsPlayer[i]].Text = i.ToString(); + } } else { @@ -1017,9 +1149,11 @@ namespace Vocaluxe.Screens else { if (_Sso.Selection.PartyMode) + { _SongMenu.SmallView = false; + } - for (int i = 0; i < CSettings.MaxNumPlayer; i++) + for (var i = 0; i < CSettings.MaxNumPlayer; i++) { _Buttons[_ButtonsJoker[i]].Visible = false; _Texts[_TextsPlayer[i]].Visible = false; @@ -1035,11 +1169,11 @@ namespace Vocaluxe.Screens { CBase.Songs.SetCategory(-1); } - + CSongs.Sorter.SongSorting = (ESongSorting)sortNr; CConfig.Config.Game.SongSorting = CSongs.Sorter.SongSorting; _Sso.Sorting.SongSorting = CSongs.Sorter.SongSorting; - + _SongMenu.Update(_Sso); _SongMenu.OnShow(); @@ -1063,12 +1197,16 @@ namespace Vocaluxe.Screens private void _ToggleTabs() { - EOffOn tmpStatus = CSongs.Categorizer.Tabs; + var tmpStatus = CSongs.Categorizer.Tabs; if (tmpStatus == EOffOn.TR_CONFIG_ON) + { CSongs.Categorizer.Tabs = EOffOn.TR_CONFIG_OFF; + } else + { CSongs.Categorizer.Tabs = EOffOn.TR_CONFIG_ON; + } CConfig.Config.Game.Tabs = CSongs.Categorizer.Tabs; _Sso.Sorting.Tabs = CSongs.Categorizer.Tabs; @@ -1079,23 +1217,27 @@ namespace Vocaluxe.Screens private void _ShowHighscore() { CGame.ClearSongs(); - CScreenSong.setStaticSelectedSongID(CSongs.VisibleSongs[_SongMenu.GetPreviewSongNr()].ID); + CScreenSong.setStaticSelectedSongId(CSongs.VisibleSongs[_SongMenu.GetPreviewSongNr()].Id); _SongMenu.SetSelectedSong(_SongMenu.GetPreviewSongNr()); CBase.Graphics.FadeTo(EScreen.Highscore); } private void _StartSong(int songNr) { - if (CSongs.IsInCategory && (songNr >= 0)) + if (CSongs.IsInCategory && songNr >= 0) { - SetStaticSelectedCategoryIndex(CBase.Songs.GetCurrentCategoryIndex()); - setStaticSelectedSongID(CSongs.VisibleSongs[songNr].ID); - + SetStaticSelectedCategoryIndex(CBase.Songs.GetCurrentCategoryIndex()); + setStaticSelectedSongId(CSongs.VisibleSongs[songNr].Id); + EGameMode gm; if (_AvailableGameModes.Count >= _SelectSlides[_SelectSlideOptionsMode].Selection) + { gm = _AvailableGameModes[_SelectSlides[_SelectSlideOptionsMode].Selection]; + } else + { gm = CSongs.VisibleSongs[songNr].IsDuet ? EGameMode.TR_GAMEMODE_DUET : EGameMode.TR_GAMEMODE_NORMAL; + } _AudioMode = (EAudioMode)_SelectSlides[_SelectSlideOptionsAudioMode].SelectedTag; _PlayerSelect = (EPlayerSelect)_SelectSlides[_SelectSlideOptionsPlayerSelect].Selection; @@ -1104,6 +1246,7 @@ namespace Vocaluxe.Screens CGame.ClearSongs(); if (CGame.AddVisibleSong(songNr, gm)) + { if (_PlayerSelect == EPlayerSelect.TR_SCREENSONG_PLAYERSELECT_OFF) { CGraphics.FadeTo(EScreen.Sing); @@ -1112,6 +1255,7 @@ namespace Vocaluxe.Screens { CGraphics.FadeTo(EScreen.Names); } + } } } @@ -1120,14 +1264,15 @@ namespace Vocaluxe.Screens if (CSongs.IsInCategory && songNr >= 0 && CSongs.NumSongsVisible > songNr) { SetStaticSelectedCategoryIndex(CBase.Songs.GetCurrentCategoryIndex()); - setStaticSelectedSongID(CSongs.VisibleSongs[songNr].ID); - - EGameMode gm = CSongs.VisibleSongs[songNr].IsDuet ? EGameMode.TR_GAMEMODE_DUET : EGameMode.TR_GAMEMODE_NORMAL; + setStaticSelectedSongId(CSongs.VisibleSongs[songNr].Id); + + var gm = CSongs.VisibleSongs[songNr].IsDuet ? EGameMode.TR_GAMEMODE_DUET : EGameMode.TR_GAMEMODE_NORMAL; CGame.Reset(); CGame.ClearSongs(); if (CGame.AddVisibleSong(songNr, gm)) + { if (_PlayerSelect == EPlayerSelect.TR_SCREENSONG_PLAYERSELECT_OFF) { CGraphics.FadeTo(EScreen.Sing); @@ -1136,12 +1281,13 @@ namespace Vocaluxe.Screens { CGraphics.FadeTo(EScreen.Names); } + } } } private void _StartMedleySong(int songNr) { - if (CSongs.IsInCategory && (songNr >= 0)) + if (CSongs.IsInCategory && songNr >= 0) { if (!CSongs.VisibleSongs[songNr].IsGameModeAvailable(EGameMode.TR_GAMEMODE_MEDLEY)) { @@ -1152,6 +1298,7 @@ namespace Vocaluxe.Screens CGame.Reset(); CGame.ClearSongs(); if (CGame.AddVisibleSong(songNr, EGameMode.TR_GAMEMODE_MEDLEY)) + { if (_PlayerSelect == EPlayerSelect.TR_SCREENSONG_PLAYERSELECT_OFF) { CGraphics.FadeTo(EScreen.Sing); @@ -1160,6 +1307,7 @@ namespace Vocaluxe.Screens { CGraphics.FadeTo(EScreen.Names); } + } } } @@ -1169,16 +1317,20 @@ namespace Vocaluxe.Screens CGame.ClearSongs(); var ids = new List(); - for (int i = 0; i < CSongs.AllSongs.Count; i++) + for (var i = 0; i < CSongs.AllSongs.Count; i++) + { ids.Add(i); + } while (ids.Count > 0) { - int songNr = ids[CGame.Rand.Next(ids.Count)]; + var songNr = ids[CGame.Rand.Next(ids.Count)]; var gm = EGameMode.TR_GAMEMODE_NORMAL; if (CSongs.AllSongs[songNr].IsDuet) + { gm = EGameMode.TR_GAMEMODE_DUET; + } CGame.AddSong(songNr, gm); @@ -1186,14 +1338,16 @@ namespace Vocaluxe.Screens } if (CGame.GetNumSongs() > 0) + { if (_PlayerSelect == EPlayerSelect.TR_SCREENSONG_PLAYERSELECT_OFF) - { - CGraphics.FadeTo(EScreen.Sing); - } - else - { - CGraphics.FadeTo(EScreen.Names); - } + { + CGraphics.FadeTo(EScreen.Sing); + } + else + { + CGraphics.FadeTo(EScreen.Names); + } + } } private void _StartRandomVisibleSongs() @@ -1201,15 +1355,17 @@ namespace Vocaluxe.Screens CGame.Reset(); CGame.ClearSongs(); - List ids = CSongs.VisibleSongs.Select(t => t.ID).ToList(); + var ids = CSongs.VisibleSongs.Select(t => t.Id).ToList(); while (ids.Count > 0) { - int songNr = ids[CGame.Rand.Next(ids.Count)]; + var songNr = ids[CGame.Rand.Next(ids.Count)]; var gm = EGameMode.TR_GAMEMODE_NORMAL; if (CSongs.AllSongs[songNr].IsDuet) + { gm = EGameMode.TR_GAMEMODE_DUET; + } CGame.AddSong(songNr, gm); @@ -1217,14 +1373,16 @@ namespace Vocaluxe.Screens } if (CGame.GetNumSongs() > 0) + { if (_PlayerSelect == EPlayerSelect.TR_SCREENSONG_PLAYERSELECT_OFF) - { - CGraphics.FadeTo(EScreen.Sing); - } - else - { - CGraphics.FadeTo(EScreen.Names); - } + { + CGraphics.FadeTo(EScreen.Sing); + } + else + { + CGraphics.FadeTo(EScreen.Names); + } + } } private void _StartRandomMedley(int numSongs, bool allSongs) @@ -1236,17 +1394,22 @@ namespace Vocaluxe.Screens if (allSongs) { ids = new List(); - for (int i = 0; i < CSongs.AllSongs.Count; i++) + for (var i = 0; i < CSongs.AllSongs.Count; i++) + { ids.Add(i); + } } else - ids = CSongs.VisibleSongs.Select(t => t.ID).ToList(); - int s = 0; + { + ids = CSongs.VisibleSongs.Select(t => t.Id).ToList(); + } + + var s = 0; while (s < numSongs && ids.Count > 0) { - int songNr = ids[CGame.Rand.Next(ids.Count)]; + var songNr = ids[CGame.Rand.Next(ids.Count)]; - foreach (EGameMode gm in CSongs.AllSongs[songNr].AvailableGameModes) + foreach (var gm in CSongs.AllSongs[songNr].AvailableGameModes) { if (gm == EGameMode.TR_GAMEMODE_MEDLEY) { @@ -1260,21 +1423,23 @@ namespace Vocaluxe.Screens } if (CGame.GetNumSongs() > 0) + { if (_PlayerSelect == EPlayerSelect.TR_SCREENSONG_PLAYERSELECT_OFF) - { - CGraphics.FadeTo(EScreen.Sing); - } - else - { - CGraphics.FadeTo(EScreen.Names); - } + { + CGraphics.FadeTo(EScreen.Sing); + } + else + { + CGraphics.FadeTo(EScreen.Names); + } + } } private bool _SelectNextRandom(int teamNr) { if (teamNr != -1 && _Sso.Selection.RandomOnly && _Sso.Selection.NumJokers != null) { - bool result = false; + var result = false; if (_Sso.Selection.NumJokers.Length > teamNr) { if (_Sso.Selection.NumJokers[teamNr] > 0) @@ -1284,11 +1449,14 @@ namespace Vocaluxe.Screens _Sso = CParty.GetSongSelectionOptions(); } } + return result; } if (teamNr == -1) + { return _SelectNextRandomSong() || _SelectNextRandomCategory(); + } return false; } @@ -1301,6 +1469,7 @@ namespace Vocaluxe.Screens _SongMenu.SetSelectedSong(CSongs.GetRandomSong()); return true; } + return false; } @@ -1312,21 +1481,28 @@ namespace Vocaluxe.Screens _SongMenu.SetSelectedCategory(CSongs.GetRandomCategory()); return true; } + return false; } private int _FindIndex(IList list, int start, Predicate match) { - for (int i = start; i < list.Count; i++) + for (var i = start; i < list.Count; i++) { if (match(list[i])) + { return i; + } } - for (int i = 0; i < start; i++) + + for (var i = 0; i < start; i++) { if (match(list[i])) + { return i; + } } + return -1; } @@ -1335,71 +1511,91 @@ namespace Vocaluxe.Screens // Stefan1200: Add all letters from a key press within one second to a search string. Clear search string, if last key press is older than one second. String searchString; if (Environment.TickCount - _JumpTo_lastCharTime < 1000) + { searchString = _JumpTo_lastSearchString + letter.ToString(); + } else + { searchString = letter.ToString(); + } - int start = 0; - bool firstLevel = CConfig.Config.Game.Tabs == EOffOn.TR_CONFIG_OFF && CSongs.IsInCategory; - bool secondSort = CConfig.Config.Game.Tabs == EOffOn.TR_CONFIG_ON && - (CConfig.Config.Game.SongSorting == ESongSorting.TR_CONFIG_ARTIST || - CConfig.Config.Game.SongSorting == ESongSorting.TR_CONFIG_ARTIST_LETTER || - CConfig.Config.Game.SongSorting == ESongSorting.TR_CONFIG_FOLDER || - CConfig.Config.Game.SongSorting == ESongSorting.TR_CONFIG_TITLE_LETTER); + var start = 0; + var firstLevel = CConfig.Config.Game.Tabs == EOffOn.TR_CONFIG_OFF && CSongs.IsInCategory; + var secondSort = CConfig.Config.Game.Tabs == EOffOn.TR_CONFIG_ON && + (CConfig.Config.Game.SongSorting == ESongSorting.TR_CONFIG_ARTIST || + CConfig.Config.Game.SongSorting == ESongSorting.TR_CONFIG_ARTIST_LETTER || + CConfig.Config.Game.SongSorting == ESongSorting.TR_CONFIG_FOLDER || + CConfig.Config.Game.SongSorting == ESongSorting.TR_CONFIG_TITLE_LETTER); if (firstLevel && !secondSort) { //TODO: What's to do with multiple tags? //Flamefire: What? We only sorted by one tag, sorting by multiple tags (e.g. Album) will be by e.g. the first entry. That can be used here too as otherwhise it will confuse users because it jumps randomly - ReadOnlyCollection songs = CSongs.VisibleSongs; - int visibleID = -1; + var songs = CSongs.VisibleSongs; + var visibleId = -1; switch (CConfig.Config.Game.SongSorting) { case ESongSorting.TR_CONFIG_ARTIST: case ESongSorting.TR_CONFIG_ARTIST_LETTER: - visibleID = _FindIndex(songs, start, element => (_Sso.Sorting.IgnoreArticles == EOffOn.TR_CONFIG_ON ? element.ArtistSorting.StartsWith(searchString, StringComparison.OrdinalIgnoreCase) : element.Artist.StartsWith(searchString, StringComparison.OrdinalIgnoreCase))); + visibleId = _FindIndex(songs, start, + element => _Sso.Sorting.IgnoreArticles == EOffOn.TR_CONFIG_ON ? element.ArtistSorting.StartsWith(searchString, StringComparison.OrdinalIgnoreCase) + : element.Artist.StartsWith(searchString, StringComparison.OrdinalIgnoreCase)); break; case ESongSorting.TR_CONFIG_YEAR: case ESongSorting.TR_CONFIG_DECADE: - visibleID = _FindIndex(songs, start, element => element.Year.StartsWith(searchString, StringComparison.OrdinalIgnoreCase)); + visibleId = _FindIndex(songs, start, element => element.Year.StartsWith(searchString, StringComparison.OrdinalIgnoreCase)); break; case ESongSorting.TR_CONFIG_TITLE_LETTER: - visibleID = _FindIndex(songs, start, element => (_Sso.Sorting.IgnoreArticles == EOffOn.TR_CONFIG_ON ? element.TitleSorting.StartsWith(searchString, StringComparison.OrdinalIgnoreCase) : element.Title.StartsWith(searchString, StringComparison.OrdinalIgnoreCase))); + visibleId = _FindIndex(songs, start, + element => _Sso.Sorting.IgnoreArticles == EOffOn.TR_CONFIG_ON ? element.TitleSorting.StartsWith(searchString, StringComparison.OrdinalIgnoreCase) + : element.Title.StartsWith(searchString, StringComparison.OrdinalIgnoreCase)); break; case ESongSorting.TR_CONFIG_FOLDER: - visibleID = _FindIndex(songs, start, element => element.FolderName.StartsWith(searchString, StringComparison.OrdinalIgnoreCase)); + visibleId = _FindIndex(songs, start, element => element.FolderName.StartsWith(searchString, StringComparison.OrdinalIgnoreCase)); break; } - if (visibleID > -1) - _SongMenu.SetSelectedSong(visibleID); + + if (visibleId > -1) + { + _SongMenu.SetSelectedSong(visibleId); + } } else if (secondSort && CSongs.IsInCategory) { - ReadOnlyCollection songs = CSongs.VisibleSongs; - int visibleID = -1; + var songs = CSongs.VisibleSongs; + var visibleId = -1; switch (CConfig.Config.Game.SongSorting) { case ESongSorting.TR_CONFIG_FOLDER: case ESongSorting.TR_CONFIG_TITLE_LETTER: - visibleID = _FindIndex(songs, start, element => (_Sso.Sorting.IgnoreArticles == EOffOn.TR_CONFIG_ON ? element.ArtistSorting.StartsWith(searchString, StringComparison.OrdinalIgnoreCase) : element.Artist.StartsWith(searchString, StringComparison.OrdinalIgnoreCase))); + visibleId = _FindIndex(songs, start, + element => _Sso.Sorting.IgnoreArticles == EOffOn.TR_CONFIG_ON ? element.ArtistSorting.StartsWith(searchString, StringComparison.OrdinalIgnoreCase) + : element.Artist.StartsWith(searchString, StringComparison.OrdinalIgnoreCase)); break; case ESongSorting.TR_CONFIG_ARTIST: case ESongSorting.TR_CONFIG_ARTIST_LETTER: - visibleID = _FindIndex(songs, start, element => (_Sso.Sorting.IgnoreArticles == EOffOn.TR_CONFIG_ON ? element.TitleSorting.StartsWith(searchString, StringComparison.OrdinalIgnoreCase) : element.Title.StartsWith(searchString, StringComparison.OrdinalIgnoreCase))); + visibleId = _FindIndex(songs, start, + element => _Sso.Sorting.IgnoreArticles == EOffOn.TR_CONFIG_ON ? element.TitleSorting.StartsWith(searchString, StringComparison.OrdinalIgnoreCase) + : element.Title.StartsWith(searchString, StringComparison.OrdinalIgnoreCase)); break; } - if (visibleID > -1) - _SongMenu.SetSelectedSong(visibleID); + + if (visibleId > -1) + { + _SongMenu.SetSelectedSong(visibleId); + } } else if (!CSongs.IsInCategory) { - ReadOnlyCollection categories = CSongs.Categories; - int visibleID = _FindIndex(categories, start, element => element.Name.StartsWith(searchString, StringComparison.OrdinalIgnoreCase)); - if (visibleID > -1) - _SongMenu.SetSelectedCategory(visibleID); + var categories = CSongs.Categories; + var visibleId = _FindIndex(categories, start, element => element.Name.StartsWith(searchString, StringComparison.OrdinalIgnoreCase)); + if (visibleId > -1) + { + _SongMenu.SetSelectedCategory(visibleId); + } } // Stefan1200: Remember search string and current TickCount in class variables. @@ -1409,17 +1605,22 @@ namespace Vocaluxe.Screens public void _TogglePlaylistFilter() { - if (_Sso.Sorting.FilterPlaylistID == _Playlist.ActivePlaylistID) + if (_Sso.Sorting.FilterPlaylistId == _Playlist.ActivePlaylistId) { - if (_Playlist.ActivePlaylistID == -1) + if (_Playlist.ActivePlaylistId == -1) + { return; + } - _Sso.Sorting.FilterPlaylistID = -1; + _Sso.Sorting.FilterPlaylistId = -1; } else - _Sso.Sorting.FilterPlaylistID = _Playlist.ActivePlaylistID; - - CSongs.Sort(_Sso.Sorting.SongSorting, _Sso.Sorting.Tabs, _Sso.Sorting.IgnoreArticles, _Sso.Sorting.SearchString, _Sso.Sorting.DuetOptions, _Sso.Sorting.FilterPlaylistID); + { + _Sso.Sorting.FilterPlaylistId = _Playlist.ActivePlaylistId; + } + + CSongs.Sort(_Sso.Sorting.SongSorting, _Sso.Sorting.Tabs, _Sso.Sorting.IgnoreArticles, _Sso.Sorting.SearchString, _Sso.Sorting.DuetOptions, + _Sso.Sorting.FilterPlaylistId); _SongMenu.OnShow(); } @@ -1428,13 +1629,15 @@ namespace Vocaluxe.Screens CParty.SetSearchString(newFilterString, _SearchActive); _Sso = CParty.GetSongSelectionOptions(); - bool refresh = false; + var refresh = false; _SearchText = newFilterString; - int songIndex = _SongMenu.GetSelectedSongNr(); - int songID = -1; + var songIndex = _SongMenu.GetSelectedSongNr(); + var songId = -1; if (songIndex != -1) - songID = CSongs.VisibleSongs[songIndex].ID; + { + songId = CSongs.VisibleSongs[songIndex].Id; + } if (newFilterString == "" && _Sso.Sorting.Tabs == EOffOn.TR_CONFIG_ON) { @@ -1448,13 +1651,17 @@ namespace Vocaluxe.Screens refresh = true; } - CSongs.Sort(_Sso.Sorting.SongSorting, _Sso.Sorting.Tabs, _Sso.Sorting.IgnoreArticles, newFilterString, _Sso.Sorting.DuetOptions, _Sso.Sorting.FilterPlaylistID); + CSongs.Sort(_Sso.Sorting.SongSorting, _Sso.Sorting.Tabs, _Sso.Sorting.IgnoreArticles, newFilterString, _Sso.Sorting.DuetOptions, _Sso.Sorting.FilterPlaylistId); - if (songID == -1 || CSongs.NumSongsVisible <= songIndex || CSongs.GetVisibleSongByIndex(songIndex).ID != songID) + if (songId == -1 || CSongs.NumSongsVisible <= songIndex || CSongs.GetVisibleSongByIndex(songIndex).Id != songId) + { refresh = true; + } if (refresh) + { _SongMenu.OnHide(); + } _SongMenu.OnShow(); } @@ -1484,18 +1691,26 @@ namespace Vocaluxe.Screens _Texts[_TextOptionsPlayerSelect].Visible = false; _Texts[_TextOptionsPlaylist].Visible = false; _Statics[_StaticOptionsBG].Visible = false; - _Statics[_StaticSearchBar].Visible = !_Sso.Selection.PartyMode; + _Statics[_StaticSearchBar].Visible = !_Sso.Selection.PartyMode; _Buttons[_ButtonOpenOptions].Visible = true; if (view == ESongOptionsView.None) + { _CurSongOptionsView = view; + } else if (CSongs.IsInCategory) + { _CurSongOptionsView = CSongs.VisibleSongs.Count > 0 ? view : ESongOptionsView.None; + } else + { _CurSongOptionsView = CSongs.Categories.Count > 0 ? view : ESongOptionsView.None; + } if (_CurSongOptionsView == ESongOptionsView.None) + { return; + } //Has to be done here otherwhise changed playlist names will not appear until OnShow is called! _UpdatePlaylistNames(); @@ -1508,11 +1723,17 @@ namespace Vocaluxe.Screens _Statics[_StaticOptionsBG].Visible = true; _Buttons[_ButtonOpenOptions].Visible = false; if (view == ESongOptionsView.Song) + { _ShowSongOptionsSong(); + } else if (view == ESongOptionsView.General) + { _ShowSongOptionsGeneral(); + } else if (view == ESongOptionsView.Medley) + { _ShowSongOptionsMedley(); + } } private void _CheckAndAddGameMode(EGameMode gameMode) @@ -1528,7 +1749,10 @@ namespace Vocaluxe.Screens { var lastMode = EGameMode.TR_GAMEMODE_NORMAL; if (_AvailableGameModes.Count > 0) + { lastMode = _AvailableGameModes[_SelectSlides[_SelectSlideOptionsMode].Selection]; + } + _AvailableGameModes.Clear(); _SelectSlides[_SelectSlideOptionsMode].Clear(); _CheckAndAddGameMode(EGameMode.TR_GAMEMODE_NORMAL); @@ -1540,20 +1764,20 @@ namespace Vocaluxe.Screens _SelectSlides[_SelectSlideOptionsMode].SelectedTag = (int)lastMode; _SelectSlides[_SelectSlideOptionsAudioMode].Clear(); - CSong currentSong = CSongs.VisibleSongs[_SongMenu.GetPreviewSongNr()]; + var currentSong = CSongs.VisibleSongs[_SongMenu.GetPreviewSongNr()]; if (currentSong.HasInstrumental()) { _SelectSlides[_SelectSlideOptionsAudioMode].AddValue("TR_AUDIOMODE_NORMAL", tag: (int)EAudioMode.TR_AUDIOMODE_NORMAL); _SelectSlides[_SelectSlideOptionsAudioMode].AddValue("TR_AUDIOMODE_INSTRUMENTAL", tag: (int)EAudioMode.TR_AUDIOMODE_INSTRUMENTAL); - - if (currentSong.HasVocals()) - { - _SelectSlides[_SelectSlideOptionsAudioMode].AddValue("TR_AUDIOMODE_VOCALS", tag: (int)EAudioMode.TR_AUDIOMODE_VOCALS); - } - + + if (currentSong.HasVocals()) + { + _SelectSlides[_SelectSlideOptionsAudioMode].AddValue("TR_AUDIOMODE_VOCALS", tag: (int)EAudioMode.TR_AUDIOMODE_VOCALS); + } + _SelectSlides[_SelectSlideOptionsAudioMode].AddValue("TR_AUDIOMODE_KARAOKE", tag: (int)EAudioMode.TR_AUDIOMODE_KARAOKE); - _SelectSlides[_SelectSlideOptionsAudioMode].Visible = true; + _SelectSlides[_SelectSlideOptionsAudioMode].Visible = true; _Texts[_TextOptionsAudioMode].Visible = true; } else @@ -1569,7 +1793,7 @@ namespace Vocaluxe.Screens _SelectSlides[_SelectSlideOptionsPlayerSelect].AddValue("TR_SCREENSONG_PLAYERSELECT_OFF"); _SelectSlides[_SelectSlideOptionsPlayerSelect].Visible = true; _SelectSlides[_SelectSlideOptionsPlayerSelect].Selection = (int)_PlayerSelect; - + _SelectSlides[_SelectSlideOptionsMode].Visible = true; _SelectSlides[_SelectSlideOptionsPlaylistAdd].Visible = true; _Buttons[_ButtonOptionsSing].Visible = true; @@ -1577,13 +1801,12 @@ namespace Vocaluxe.Screens _Buttons[_ButtonOptionsHighscore].Visible = true; _SelectElement(_Buttons[_ButtonOptionsSing]); _SetSelectSlidePlaylistToCurrentPlaylist(); - } private void _ShowSongOptionsGeneral() { _Texts[_TextOptionsLength].Visible = false; - _Texts[_TextOptionsPlayerSelect ].Visible = false; + _Texts[_TextOptionsPlayerSelect].Visible = false; _Texts[_TextOptionsPlaylist].Visible = false; if (CSongs.IsInCategory) @@ -1592,51 +1815,70 @@ namespace Vocaluxe.Screens _Buttons[_ButtonOptionsSingAllVisible].Visible = true; } else + { _Buttons[_ButtonOptionsRandomCategory].Visible = true; + } + _Buttons[_ButtonOptionsSingAll].Visible = true; _Buttons[_ButtonOptionsRandomMedley].Visible = true; _Buttons[_ButtonOptionsOpenSelectedItem].Visible = true; if (_SelectSlides[_SelectSlideOptionsPlaylistOpen].NumValues > 0) + { _SelectSlides[_SelectSlideOptionsPlaylistOpen].Visible = true; + } // ReSharper disable ConvertIfStatementToConditionalTernaryExpression if (_Buttons[_ButtonOptionsRandom].Visible) // ReSharper restore ConvertIfStatementToConditionalTernaryExpression + { _SelectElement(_Buttons[_ButtonOptionsRandom]); + } else + { _SelectElement(_Buttons[_ButtonOptionsRandomCategory]); + } } private void _ShowSongOptionsMedley() { _Texts[_TextOptionsLength].Visible = false; - _Texts[_TextOptionsPlayerSelect ].Visible = false; + _Texts[_TextOptionsPlayerSelect].Visible = false; _Texts[_TextOptionsPlaylist].Visible = false; - _Buttons[_ButtonOptionsStartMedley].Visible = true; + _Buttons[_ButtonOptionsStartMedley].Visible = true; _SelectSlides[_SelectSlideOptionsNumMedleySongs].Visible = true; _SelectSlides[_SelectSlideOptionsNumMedleySongs].Clear(); if (CSongs.IsInCategory) { - for (int i = 1; i <= CSongs.VisibleSongs.Count; i++) + for (var i = 1; i <= CSongs.VisibleSongs.Count; i++) + { _SelectSlides[_SelectSlideOptionsNumMedleySongs].AddValue(i.ToString()); + } } else { - for (int i = 1; i <= CSongs.AllSongs.Count; i++) + for (var i = 1; i <= CSongs.AllSongs.Count; i++) + { _SelectSlides[_SelectSlideOptionsNumMedleySongs].AddValue(i.ToString()); + } } + if (_SelectSlides[_SelectSlideOptionsNumMedleySongs].NumValues >= 5) + { _SelectSlides[_SelectSlideOptionsNumMedleySongs].SelectedValue = "5"; + } else + { _SelectSlides[_SelectSlideOptionsNumMedleySongs].SelectLastValue(); + } + _SelectElement(_Buttons[_ButtonOptionsStartMedley]); } #region Playlist Actions - private void _OpenPlaylist(int playlistID) + private void _OpenPlaylist(int playlistId) { - if (_Playlist.LoadPlaylist(playlistID)) + if (_Playlist.LoadPlaylist(playlistId)) { _SongMenu.SmallView = true; _Playlist.Visible = true; @@ -1668,57 +1910,69 @@ namespace Vocaluxe.Screens private void _OpenAndAddPlaylistAction() { - if (_Playlist.ActivePlaylistID != (_SelectSlides[_SelectSlideOptionsPlaylistAdd].SelectedTag) && - (_SelectSlides[_SelectSlideOptionsPlaylistAdd].SelectedTag) != -1) + if (_Playlist.ActivePlaylistId != _SelectSlides[_SelectSlideOptionsPlaylistAdd].SelectedTag && + _SelectSlides[_SelectSlideOptionsPlaylistAdd].SelectedTag != -1) { //Open an existing playlist and add song //Check selected game-mode EGameMode gm; if (_AvailableGameModes.Count >= _SelectSlides[_SelectSlideOptionsMode].Selection) + { gm = _AvailableGameModes[_SelectSlides[_SelectSlideOptionsMode].Selection]; + } else if (CSongs.VisibleSongs[_SongMenu.GetPreviewSongNr()].IsDuet) + { gm = EGameMode.TR_GAMEMODE_DUET; + } else + { gm = EGameMode.TR_GAMEMODE_NORMAL; + } //Check if Playlist really exists if (_SelectSlides[_SelectSlideOptionsPlaylistAdd].SelectedTag >= 0) { - _Playlist.ActivePlaylistID = _SelectSlides[_SelectSlideOptionsPlaylistAdd].SelectedTag; + _Playlist.ActivePlaylistId = _SelectSlides[_SelectSlideOptionsPlaylistAdd].SelectedTag; //Add song to playlist - CPlaylists.AddSong(_Playlist.ActivePlaylistID, CSongs.VisibleSongs[_SongMenu.GetPreviewSongNr()].ID, gm); + CPlaylists.AddSong(_Playlist.ActivePlaylistId, CSongs.VisibleSongs[_SongMenu.GetPreviewSongNr()].Id, gm); //Open playlist - _OpenPlaylist(_Playlist.ActivePlaylistID); + _OpenPlaylist(_Playlist.ActivePlaylistId); _Playlist.ScrollToBottom(); } } - else if ((_SelectSlides[_SelectSlideOptionsPlaylistAdd].SelectedTag) == -1) + else if (_SelectSlides[_SelectSlideOptionsPlaylistAdd].SelectedTag == -1) { //Create a new playlist and add song //Check selected game-mode EGameMode gm; if (_AvailableGameModes.Count >= _SelectSlides[_SelectSlideOptionsMode].Selection) + { gm = _AvailableGameModes[_SelectSlides[_SelectSlideOptionsMode].Selection]; + } else if (CSongs.VisibleSongs[_SongMenu.GetPreviewSongNr()].IsDuet) + { gm = EGameMode.TR_GAMEMODE_DUET; + } else + { gm = EGameMode.TR_GAMEMODE_NORMAL; + } //Create new playlist - _Playlist.ActivePlaylistID = CPlaylists.NewPlaylist(); + _Playlist.ActivePlaylistId = CPlaylists.NewPlaylist(); //Add song to playlist - CPlaylists.AddSong(_Playlist.ActivePlaylistID, CSongs.VisibleSongs[_SongMenu.GetPreviewSongNr()].ID, gm); + CPlaylists.AddSong(_Playlist.ActivePlaylistId, CSongs.VisibleSongs[_SongMenu.GetPreviewSongNr()].Id, gm); //Open playlist - _OpenPlaylist(_Playlist.ActivePlaylistID); + _OpenPlaylist(_Playlist.ActivePlaylistId); //Add new playlist to select-slide - _SelectSlides[_SelectSlideOptionsPlaylistAdd].AddValue(CPlaylists.GetName(_Playlist.ActivePlaylistID), _Playlist.ActivePlaylistID); - _SelectSlides[_SelectSlideOptionsPlaylistOpen].AddValue(CPlaylists.GetName(_Playlist.ActivePlaylistID), _Playlist.ActivePlaylistID); + _SelectSlides[_SelectSlideOptionsPlaylistAdd].AddValue(CPlaylists.GetName(_Playlist.ActivePlaylistId), _Playlist.ActivePlaylistId); + _SelectSlides[_SelectSlideOptionsPlaylistOpen].AddValue(CPlaylists.GetName(_Playlist.ActivePlaylistId), _Playlist.ActivePlaylistId); } else { @@ -1726,12 +1980,19 @@ namespace Vocaluxe.Screens //Check selected game-mode EGameMode gm; if (_AvailableGameModes.Count >= _SelectSlides[_SelectSlideOptionsMode].Selection) + { gm = _AvailableGameModes[_SelectSlides[_SelectSlideOptionsMode].Selection]; + } else if (CSongs.VisibleSongs[_SongMenu.GetPreviewSongNr()].IsDuet) + { gm = EGameMode.TR_GAMEMODE_DUET; + } else + { gm = EGameMode.TR_GAMEMODE_NORMAL; - CPlaylists.AddSong(_Playlist.ActivePlaylistID, CSongs.VisibleSongs[_SongMenu.GetPreviewSongNr()].ID, gm); + } + + CPlaylists.AddSong(_Playlist.ActivePlaylistId, CSongs.VisibleSongs[_SongMenu.GetPreviewSongNr()].Id, gm); _Playlist.UpdatePlaylist(); _Playlist.ScrollToBottom(); } @@ -1739,11 +2000,15 @@ namespace Vocaluxe.Screens private void _SetSelectSlidePlaylistToCurrentPlaylist() { - if (_Playlist.ActivePlaylistID > -1) - _SelectSlides[_SelectSlideOptionsPlaylistAdd].SelectedTag = _Playlist.ActivePlaylistID; + if (_Playlist.ActivePlaylistId > -1) + { + _SelectSlides[_SelectSlideOptionsPlaylistAdd].SelectedTag = _Playlist.ActivePlaylistId; + } else + { _SelectSlides[_SelectSlideOptionsPlaylistAdd].Selection = 0; + } } #endregion Playlist Actions } -} +} \ No newline at end of file diff --git a/Vocaluxe/Screens/CScreenTest.cs b/Vocaluxe/Screens/CScreenTest.cs index bfdc9827..c45ec1da 100644 --- a/Vocaluxe/Screens/CScreenTest.cs +++ b/Vocaluxe/Screens/CScreenTest.cs @@ -56,7 +56,7 @@ namespace Vocaluxe.Screens public override bool HandleInput(SKeyEvent keyEvent) { - if (keyEvent.KeyPressed && !Char.IsControl(keyEvent.Unicode)) {} + if (keyEvent.KeyPressed && !Char.IsControl(keyEvent.Unicode)) { } else { switch (keyEvent.Key) @@ -89,13 +89,18 @@ namespace Vocaluxe.Screens public override bool HandleMouse(SMouseEvent mouseEvent) { - if (mouseEvent.LB && _IsMouseOverCurSelection(mouseEvent)) {} + if (mouseEvent.LB && _IsMouseOverCurSelection(mouseEvent)) { } if (mouseEvent.LB) + { CGraphics.FadeTo(EScreen.Main); + } if (mouseEvent.RB) + { CGraphics.FadeTo(EScreen.Main); + } + return true; } diff --git a/Vocaluxe/SongQueue/CSongQueue.cs b/Vocaluxe/SongQueue/CSongQueue.cs index 969013c9..1d668e17 100644 --- a/Vocaluxe/SongQueue/CSongQueue.cs +++ b/Vocaluxe/SongQueue/CSongQueue.cs @@ -26,12 +26,12 @@ namespace Vocaluxe.SongQueue { struct SSongQueueEntry { - public readonly int SongID; + public readonly int SongId; public readonly EGameMode GameMode; - public SSongQueueEntry(int songID, EGameMode gameMode) + public SSongQueueEntry(int songId, EGameMode gameMode) { - SongID = songID; + SongId = songId; GameMode = gameMode; } } @@ -58,42 +58,48 @@ namespace Vocaluxe.SongQueue public bool AddVisibleSong(int visibleIndex, EGameMode gameMode) { - return CSongs.VisibleSongs.Count > visibleIndex && _AddSong(CSongs.VisibleSongs[visibleIndex].ID, gameMode); + return CSongs.VisibleSongs.Count > visibleIndex && _AddSong(CSongs.VisibleSongs[visibleIndex].Id, gameMode); } public bool AddSong(int absoluteIndex, EGameMode gameMode) { - return CSongs.AllSongs.Count > absoluteIndex && _AddSong(CSongs.AllSongs[absoluteIndex].ID, gameMode); + return CSongs.AllSongs.Count > absoluteIndex && _AddSong(CSongs.AllSongs[absoluteIndex].Id, gameMode); } - private bool _AddSong(int songID, EGameMode gameMode) + private bool _AddSong(int songId, EGameMode gameMode) { - if (!CSongs.GetSong(songID).IsGameModeAvailable(gameMode)) + if (!CSongs.GetSong(songId).IsGameModeAvailable(gameMode)) + { return false; + } - _SongQueue.Add(new SSongQueueEntry(songID, gameMode)); + _SongQueue.Add(new SSongQueueEntry(songId, gameMode)); return true; } public bool RemoveVisibleSong(int visibleIndex) { - return CSongs.VisibleSongs.Count > visibleIndex && _RemoveSong(CSongs.VisibleSongs[visibleIndex].ID); + return CSongs.VisibleSongs.Count > visibleIndex && _RemoveSong(CSongs.VisibleSongs[visibleIndex].Id); } public bool RemoveSong(int absoluteIndex) { - return CSongs.AllSongs.Count > absoluteIndex && _RemoveSong(CSongs.AllSongs[absoluteIndex].ID); + return CSongs.AllSongs.Count > absoluteIndex && _RemoveSong(CSongs.AllSongs[absoluteIndex].Id); } - private bool _RemoveSong(int songID) + private bool _RemoveSong(int songId) { - for (int i = 0; i < _SongQueue.Count; i++) + for (var i = 0; i < _SongQueue.Count; i++) { - if (_SongQueue[i].SongID != songID) + if (_SongQueue[i].SongId != songId) + { continue; + } + _SongQueue.RemoveAt(i); return true; } + return false; } @@ -115,17 +121,21 @@ namespace Vocaluxe.SongQueue public void StartNextRound(SPlayer[] players) { if (IsFinished()) + { return; + } + if (_CurrentRound > -1) { _Points.SetPoints( _CurrentRound, - _SongQueue[_CurrentRound].SongID, + _SongQueue[_CurrentRound].SongId, players, _SongQueue[_CurrentRound].GameMode); } + _CurrentRound++; - _CurrentSong = IsFinished() ? null : CGameModes.Get(GetCurrentGameMode()).GetSong(_SongQueue[_CurrentRound].SongID); + _CurrentSong = IsFinished() ? null : CGameModes.Get(GetCurrentGameMode()).GetSong(_SongQueue[_CurrentRound].SongId); } public bool IsFinished() @@ -173,9 +183,14 @@ namespace Vocaluxe.SongQueue public CSong GetSong(int round) { if (round == _CurrentRound) + { return _CurrentSong; + } + if (round < _SongQueue.Count && round >= 0) - return CSongs.GetSong(_SongQueue[round].SongID); + { + return CSongs.GetSong(_SongQueue[round].SongId); + } return null; } @@ -188,7 +203,9 @@ namespace Vocaluxe.SongQueue public EGameMode GetGameMode(int round) { if (round < _SongQueue.Count && round >= 0) + { return _SongQueue[round].GameMode; + } return EGameMode.TR_GAMEMODE_NORMAL; } diff --git a/Vocaluxe/Vocaluxe.csproj b/Vocaluxe/Vocaluxe.csproj index 620c2f9b..caa226b6 100644 --- a/Vocaluxe/Vocaluxe.csproj +++ b/Vocaluxe/Vocaluxe.csproj @@ -45,6 +45,7 @@ 4 Off false + 9.0 x86 @@ -57,6 +58,7 @@ WIN;ARCH_X86 Off false + 9.0 x64 @@ -70,6 +72,7 @@ Off ..\CheckingRules.ruleset false + 9.0 x64 @@ -83,6 +86,7 @@ Off false true + 9.0 x86 @@ -95,6 +99,7 @@ 4 Off false + 9.0 x86 @@ -107,6 +112,7 @@ LINUX;ARCH_X86 Off false + 9.0 x64 @@ -119,6 +125,7 @@ 4 Off false + 9.0 x64 @@ -132,6 +139,7 @@ Off false true + 9.0 x86 @@ -144,6 +152,7 @@ WIN;ARCH_X86;INSTALLER Off false + 9.0 x64 @@ -157,6 +166,7 @@ Off false true + 9.0 true @@ -175,14 +185,10 @@ - - 10.0.1 - + - - 3.0.2 - + @@ -304,7 +310,7 @@ Form - + @@ -575,4 +581,4 @@ $(SolutionDir)/.build/linuxPostBuildEvent.sh $(ProjectDir) - + \ No newline at end of file diff --git a/VocaluxeLib/CBasic.cs b/VocaluxeLib/CBasic.cs index a8f0484c..0d4d6d89 100644 --- a/VocaluxeLib/CBasic.cs +++ b/VocaluxeLib/CBasic.cs @@ -39,8 +39,8 @@ namespace VocaluxeLib public static IPlaylist Playlist; public static void Assign(IConfig config, ISettings settings, IThemes themes, IBackgroundMusic backgroundMusic, - IDrawing draw, IGraphics graphics, IFonts fonts, ILanguage language, IGame game, IProfiles profiles, IRecording record, - ISongs songs, IVideo video, ISound sound, ICover cover, IDataBase dataBase, IControllers controller, IPlaylist playlist) + IDrawing draw, IGraphics graphics, IFonts fonts, ILanguage language, IGame game, IProfiles profiles, IRecording record, + ISongs songs, IVideo video, ISound sound, ICover cover, IDataBase dataBase, IControllers controller, IPlaylist playlist) { Config = config; Settings = settings; diff --git a/VocaluxeLib/CEncoding.cs b/VocaluxeLib/CEncoding.cs index 3afdfe49..4d28fbba 100644 --- a/VocaluxeLib/CEncoding.cs +++ b/VocaluxeLib/CEncoding.cs @@ -42,13 +42,17 @@ namespace VocaluxeLib public static string GetEncodingName(this Encoding enc) { - string result = "UTF8"; + var result = "UTF8"; if (enc.CodePage == 1250) + { result = "CP1250"; + } if (enc.CodePage == 1252) + { result = "CP1252"; + } return result; } diff --git a/VocaluxeLib/CFading.cs b/VocaluxeLib/CFading.cs index e66c10db..fe7f830f 100644 --- a/VocaluxeLib/CFading.cs +++ b/VocaluxeLib/CFading.cs @@ -35,7 +35,10 @@ namespace VocaluxeLib public CFading(float fromValue, float toValue, float duration) { if (duration < 0) + { duration = 0; + } + _FromValue = fromValue; _ToValue = toValue; _Duration = duration * 1000f; @@ -52,7 +55,7 @@ namespace VocaluxeLib float result; if (_Timer.ElapsedMilliseconds < _Duration) { - result = (_Timer.ElapsedMilliseconds / _Duration) * (_ToValue - _FromValue) + _FromValue; + result = _Timer.ElapsedMilliseconds / _Duration * (_ToValue - _FromValue) + _FromValue; finished = false; } else @@ -60,6 +63,7 @@ namespace VocaluxeLib result = _ToValue; finished = true; } + return result; } } diff --git a/VocaluxeLib/CFont.cs b/VocaluxeLib/CFont.cs index 15df7ee1..2eb11107 100644 --- a/VocaluxeLib/CFont.cs +++ b/VocaluxeLib/CFont.cs @@ -47,10 +47,15 @@ namespace VocaluxeLib set { if (_Name == value) + { return; + } + _Name = value; - foreach (IFontObserver observer in _Observers) + foreach (var observer in _Observers) + { observer.FontChanged(); + } } } public EStyle Style @@ -59,10 +64,15 @@ namespace VocaluxeLib set { if (_Style == value) + { return; + } + _Style = value; - foreach (IFontObserver observer in _Observers) + foreach (var observer in _Observers) + { observer.FontChanged(); + } } } public float Height @@ -71,10 +81,15 @@ namespace VocaluxeLib set { if (Math.Abs(_Height - value) < 0.001) + { return; + } + _Height = value; - foreach (IFontObserver observer in _Observers) + foreach (var observer in _Observers) + { observer.FontChanged(); + } } } @@ -109,7 +124,9 @@ namespace VocaluxeLib public void AddObserver(IFontObserver observer) { if (!_Observers.Contains(observer)) + { _Observers.Add(observer); + } } public void RemoveObserver(IFontObserver observer) diff --git a/VocaluxeLib/CHelper.cs b/VocaluxeLib/CHelper.cs index 6164b85c..b3cc1d48 100644 --- a/VocaluxeLib/CHelper.cs +++ b/VocaluxeLib/CHelper.cs @@ -35,21 +35,32 @@ namespace VocaluxeLib public static int CombinationCount(int n, int k) { if (k > n) + { return 0; + } if (k == 0 || k == n) + { return 1; + } if (k < 0 || n <= 0) + { return 0; //is not defined + } if (k * 2 > n) + { k = n - k; + } long result = n; for (long i = 1; i <= k - 1; i++) + { result = result * (n - i) / (i + 1); + } + return (int)result; } @@ -58,12 +69,14 @@ namespace VocaluxeLib /// public static string ListStrings(string[] str) { - string result = String.Empty; - for (int i = 0; i < str.Length; i++) + var result = string.Empty; + for (var i = 0; i < str.Length; i++) { result += str[i]; if (i < str.Length - 1) + { result += ", "; + } } return result; @@ -82,9 +95,11 @@ namespace VocaluxeLib public static SRectF FitInBounds(SRectF bounds, float aspectRatio, EAspect aspect) { if (aspect == EAspect.Stretch) + { return bounds; + } - float boundsAspectRatio = bounds.W / bounds.H; + var boundsAspectRatio = bounds.W / bounds.H; float scaledWidth, scaledHeight; @@ -102,6 +117,7 @@ namespace VocaluxeLib scaledHeight = bounds.H; scaledWidth = bounds.H * aspectRatio; } + break; case EAspect.Zoom1: if (boundsAspectRatio >= aspectRatio) @@ -114,6 +130,7 @@ namespace VocaluxeLib scaledHeight = bounds.H / 1.33f; scaledWidth = bounds.H / 1.33f * aspectRatio; } + break; case EAspect.Zoom2: if (boundsAspectRatio >= aspectRatio) @@ -126,6 +143,7 @@ namespace VocaluxeLib scaledHeight = bounds.H / 1.17f; scaledWidth = bounds.H / 1.17f * aspectRatio; } + break; case EAspect.LetterBox: if (boundsAspectRatio < aspectRatio) @@ -138,6 +156,7 @@ namespace VocaluxeLib scaledHeight = bounds.H; scaledWidth = bounds.H * aspectRatio; } + break; case EAspect.PillarBox: scaledWidth = bounds.W * 0.77f; @@ -146,8 +165,9 @@ namespace VocaluxeLib default: return bounds; } - float left = (bounds.W - scaledWidth) / 2 + bounds.X; - float top = (bounds.H - scaledHeight) / 2 + bounds.Y; + + var left = (bounds.W - scaledWidth) / 2 + bounds.X; + var top = (bounds.H - scaledHeight) / 2 + bounds.Y; return new SRectF(left, top, scaledWidth, scaledHeight, bounds.Z); } @@ -162,13 +182,17 @@ namespace VocaluxeLib /// List of file names public static IEnumerable ListFiles(string path, string searchPattern, bool recursive = false, bool fullpath = false) { - IEnumerable files = Enumerable.Empty(); + var files = Enumerable.Empty(); var dir = new DirectoryInfo(path); if (!dir.Exists) + { return files; + } if (recursive && !fullpath) + { throw new NotSupportedException("recursive file listing with relative path names is not supported"); + } try { @@ -194,13 +218,17 @@ namespace VocaluxeLib /// List of file names public static IEnumerable ListFilesForExtPattern(string path, Regex extPattern, bool recursive = false, bool fullpath = false) { - IEnumerable files = Enumerable.Empty(); + var files = Enumerable.Empty(); var dir = new DirectoryInfo(path); if (!dir.Exists) + { return files; + } if (recursive && !fullpath) + { throw new NotSupportedException("recursive file listing with relative path names is not supported"); + } try { @@ -262,7 +290,7 @@ namespace VocaluxeLib result = (T)Enum.Parse(typeof(T), value, ignoreCase); return true; } - catch {} + catch { } return false; } @@ -292,17 +320,24 @@ namespace VocaluxeLib /// public static string GetUniqueFileName(string path, string filename, bool withPath = true) { - string ext = Path.GetExtension(filename); + var ext = Path.GetExtension(filename); filename = Path.GetFileNameWithoutExtension(filename) ?? "1"; if (File.Exists(Path.Combine(path, filename + ext))) { - int i = 1; + var i = 1; while (File.Exists(Path.Combine(path, filename + "_" + i + ext))) + { i++; + } + filename += "_" + i; } + if (withPath) + { filename = Path.Combine(path, filename); + } + return filename + ext; } @@ -323,6 +358,7 @@ namespace VocaluxeLib CLog.Error("Can't find File: " + filePath); return null; } + Bitmap bmp; try { @@ -333,7 +369,8 @@ namespace VocaluxeLib CLog.Error("Error loading bitmap: " + filePath); return null; } + return bmp; } } -} +} \ No newline at end of file diff --git a/VocaluxeLib/CVideoStream.cs b/VocaluxeLib/CVideoStream.cs index 9618aa52..fbfc1052 100644 --- a/VocaluxeLib/CVideoStream.cs +++ b/VocaluxeLib/CVideoStream.cs @@ -21,21 +21,21 @@ namespace VocaluxeLib { public class CVideoStream { - public int ID { get; private set; } + public int Id { get; private set; } public CTextureRef Texture; /// The actual position in s of the returned frame. Should be ~ time+VideoGap public float VideoTime; public CVideoStream(int id) { - ID = id; + Id = id; } ~CVideoStream() { - if (ID >= 0) + if (Id >= 0) { - CVideoStream tmp = this; + var tmp = this; CBase.Video.Close(ref tmp); } } @@ -46,7 +46,7 @@ namespace VocaluxeLib /// public void SetClosed() { - ID = -1; + Id = -1; CBase.Drawing.RemoveTexture(ref Texture); } @@ -56,7 +56,7 @@ namespace VocaluxeLib /// public bool IsClosed() { - return ID < 0; + return Id < 0; } } } \ No newline at end of file diff --git a/VocaluxeLib/Draw/CTextureRef.cs b/VocaluxeLib/Draw/CTextureRef.cs index 1f13444d..6389a713 100644 --- a/VocaluxeLib/Draw/CTextureRef.cs +++ b/VocaluxeLib/Draw/CTextureRef.cs @@ -25,7 +25,7 @@ namespace VocaluxeLib.Draw /// public class CTextureRef : IDisposable { - public int ID { get; private set; } + public int Id { get; private set; } /// /// Size of original image (e.g. of bmp) /// @@ -46,11 +46,11 @@ namespace VocaluxeLib.Draw /// /// Creates a new texture reference /// - /// ID of the texture + /// Id of the texture /// Original size (Bitmap size) public CTextureRef(int id, Size origSize) { - ID = id; + Id = id; OrigSize = origSize; Rect = new SRectF(0f, 0f, origSize.Width, origSize.Height, 0f); @@ -63,10 +63,10 @@ namespace VocaluxeLib.Draw public void Dispose() { - if (ID >= 0) + if (Id >= 0) { //Free textures that are no longer referenced - CTextureRef tmp = this; + var tmp = this; CBase.Drawing.RemoveTexture(ref tmp); _SetRemoved(); } @@ -78,14 +78,17 @@ namespace VocaluxeLib.Draw /// public void SetRemoved() { - if (ID < 0) + if (Id < 0) + { throw new ObjectDisposedException(GetType().Name); + } + _SetRemoved(); } private void _SetRemoved() { - ID = -1; + Id = -1; GC.SuppressFinalize(this); } } diff --git a/VocaluxeLib/Enums.cs b/VocaluxeLib/Enums.cs index bca16b53..bcb2058c 100644 --- a/VocaluxeLib/Enums.cs +++ b/VocaluxeLib/Enums.cs @@ -203,10 +203,8 @@ namespace VocaluxeLib public enum ESongMenu { // ReSharper disable InconsistentNaming - TR_CONFIG_LIST, // list of covers and artist - title - //TR_CONFIG_DREIDEL, //as in ultrastar deluxe + TR_CONFIG_LIST, // list of covers and artist - title TR_CONFIG_TILE_BOARD, //chessboard like - //TR_CONFIG_BOOK //for playlists // ReSharper restore InconsistentNaming } @@ -458,4 +456,4 @@ namespace VocaluxeLib TR_USERROLE_PROFILEEDITOR = 32 // ReSharper restore InconsistentNaming } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Extensions.cs b/VocaluxeLib/Extensions.cs index ab91177c..239a581b 100644 --- a/VocaluxeLib/Extensions.cs +++ b/VocaluxeLib/Extensions.cs @@ -41,9 +41,15 @@ namespace VocaluxeLib { Debug.Assert(min.CompareTo(max) <= 0); if (val.CompareTo(min) < 0) + { return min; + } + if (val.CompareTo(max) > 0) + { return max; + } + return val; } @@ -61,10 +67,15 @@ namespace VocaluxeLib if (min.CompareTo(max) > 0) { if (preferMin) + { max = min; + } else + { min = max; + } } + return Clamp(val, min, max); } @@ -91,11 +102,15 @@ namespace VocaluxeLib /// public static void Resize(this List list, int size, T defaultValue = default(T)) { - int curSize = list.Count; + var curSize = list.Count; if (size < curSize) + { list.RemoveRange(size, curSize - size); + } else if (size > curSize) + { list.AddRange(Enumerable.Repeat(defaultValue, size - curSize)); + } } /// @@ -107,9 +122,11 @@ namespace VocaluxeLib /// public static void EnsureSize(this List list, int size, T defaultValue) { - int curSize = list.Count; + var curSize = list.Count; if (size > curSize) + { list.AddRange(Enumerable.Repeat(defaultValue, size - curSize)); + } } /// @@ -121,7 +138,9 @@ namespace VocaluxeLib public static void EnsureSize(this List list, int size) where T : new() { if (size > list.Count) + { list.Add(new T()); + } } /// @@ -132,15 +151,19 @@ namespace VocaluxeLib public static IEnumerable GetSetBits(this int value) { var result = new List(); - int curBit = 0; + var curBit = 0; //Evaluate as bitset while (value > 0) { if ((value & 1) != 0) + { result.Add(curBit); + } + value >>= 1; curBit++; } + return result; } @@ -154,7 +177,10 @@ namespace VocaluxeLib public static string TrimMultipleWs(this string value) { if (string.IsNullOrEmpty(value)) + { return ""; + } + return _MultipleWhiteSpaceRegEx.Replace(value, " "); } @@ -180,13 +206,14 @@ namespace VocaluxeLib public static List Shuffle(this List list) { - for (int n = list.Count - 1; n >= 1; n--) + for (var n = list.Count - 1; n >= 1; n--) { - int k = CBase.Game.GetRandom(n); - T value = list[k]; + var k = CBase.Game.GetRandom(n); + var value = list[k]; list[k] = list[n]; list[n] = value; } + return list; } @@ -214,7 +241,7 @@ namespace VocaluxeLib //Create a new Bitmap with the new sizes result = new Bitmap(newSize.Width, newSize.Height); //Scale the texture - using (Graphics g = Graphics.FromImage(result)) + using (var g = Graphics.FromImage(result)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.SmoothingMode = SmoothingMode.HighQuality; @@ -229,6 +256,7 @@ namespace VocaluxeLib result = null; } } + return result; } } diff --git a/VocaluxeLib/Game/CPoints.cs b/VocaluxeLib/Game/CPoints.cs index 7326ccf6..2987da03 100644 --- a/VocaluxeLib/Game/CPoints.cs +++ b/VocaluxeLib/Game/CPoints.cs @@ -25,13 +25,13 @@ namespace VocaluxeLib.Game public CPoints(int numRounds, SPlayer[] players) { - _Rounds = new SPlayer[numRounds,players.Length]; + _Rounds = new SPlayer[numRounds, players.Length]; - for (int round = 0; round < numRounds; round++) + for (var round = 0; round < numRounds; round++) { - for (int player = 0; player < players.Length; player++) + for (var player = 0; player < players.Length; player++) { - _Rounds[round, player].ProfileID = players[player].ProfileID; + _Rounds[round, player].ProfileId = players[player].ProfileId; _Rounds[round, player].Points = 0f; _Rounds[round, player].PointsGoldenNotes = 0f; _Rounds[round, player].PointsLineBonus = 0f; @@ -41,12 +41,12 @@ namespace VocaluxeLib.Game } } - public void SetPoints(int round, int songID, SPlayer[] players, EGameMode gameMode) + public void SetPoints(int round, int songId, SPlayer[] players, EGameMode gameMode) { - long dateTicks = DateTime.Now.Ticks; - for (int player = 0; player < players.Length; player++) + var dateTicks = DateTime.Now.Ticks; + for (var player = 0; player < players.Length; player++) { - _Rounds[round, player].SongID = songID; + _Rounds[round, player].SongId = songId; _Rounds[round, player].VoiceNr = players[player].VoiceNr; _Rounds[round, player].Points = players[player].Points; _Rounds[round, player].PointsGoldenNotes = players[player].PointsGoldenNotes; @@ -70,24 +70,30 @@ namespace VocaluxeLib.Game public SPlayer[] GetPlayer(int round, int numPlayer) { if (NumPlayer == 0) + { return new SPlayer[1]; + } + if (round >= NumRounds) + { return new SPlayer[1]; + } var players = new SPlayer[numPlayer]; - for (int p = 0; p < players.Length; p++) + for (var p = 0; p < players.Length; p++) { players[p].Points = _Rounds[round, p].Points; players[p].PointsGoldenNotes = _Rounds[round, p].PointsGoldenNotes; players[p].PointsLineBonus = _Rounds[round, p].PointsLineBonus; - players[p].SongID = _Rounds[round, p].SongID; + players[p].SongId = _Rounds[round, p].SongId; players[p].VoiceNr = _Rounds[round, p].VoiceNr; players[p].GameMode = _Rounds[round, p].GameMode; players[p].DateTicks = _Rounds[round, p].DateTicks; players[p].SongFinished = _Rounds[round, p].SongFinished; - players[p].ProfileID = _Rounds[round, p].ProfileID; + players[p].ProfileId = _Rounds[round, p].ProfileId; } + return players; } } diff --git a/VocaluxeLib/IBasic.cs b/VocaluxeLib/IBasic.cs index 3631d4b2..3e5467d8 100644 --- a/VocaluxeLib/IBasic.cs +++ b/VocaluxeLib/IBasic.cs @@ -19,7 +19,6 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Drawing; -using System.Runtime.CompilerServices; using VocaluxeLib.Draw; using VocaluxeLib.Game; using VocaluxeLib.Menu; @@ -103,11 +102,11 @@ namespace VocaluxeLib public interface IThemes { - string GetThemeScreensPath(int partyModeID); - CTextureRef GetSkinTexture(string textureName, int partyModeID); - CVideoStream GetSkinVideo(string videoName, int partyModeID, bool loop); + string GetThemeScreensPath(int partyModeId); + CTextureRef GetSkinTexture(string textureName, int partyModeId); + CVideoStream GetSkinVideo(string videoName, int partyModeId, bool loop); - bool GetColor(string colorName, int partyModeID, out SColorF color); + bool GetColor(string colorName, int partyModeId, out SColorF color); SColorF GetPlayerColor(int playerNr); void Reload(); } @@ -178,7 +177,7 @@ namespace VocaluxeLib public interface ILanguage { string Translate(string keyWord); - string Translate(string keyWord, int partyModeID); + string Translate(string keyWord, int partyModeId); bool TranslationExists(string keyWord); } @@ -198,7 +197,7 @@ namespace VocaluxeLib float GetTimeFromBeats(float beat, float bpm); float GetBeatFromTime(float time, float bpm, float gap); - void AddSong(int songID, EGameMode gameMode); + void AddSong(int songId, EGameMode gameMode); void Reset(); void ClearSongs(); int GetNumSongs(); @@ -220,12 +219,12 @@ namespace VocaluxeLib { CProfile[] GetProfiles(); int GetNum(); - EGameDifficulty GetDifficulty(Guid profileID); - string GetPlayerName(Guid profileID, int playerNum = 0); - CTextureRef GetAvatar(Guid profileID); + EGameDifficulty GetDifficulty(Guid profileId); + string GetPlayerName(Guid profileId, int playerNum = 0); + CTextureRef GetAvatar(Guid profileId); CAvatar GetAvatarByFilename(string fileName); - bool IsProfileIDValid(Guid profileID); - bool IsGuest(Guid profileID); + bool IsProfileIdValid(Guid profileId); + bool IsGuest(Guid profileId); void AddProfileChangedCallback(ProfileChangedCallback notification); } @@ -246,15 +245,15 @@ namespace VocaluxeLib void UpdateRandomSongList(); CSong GetVisibleSong(int visibleIndex); - CSong GetSongByID(int songID); + CSong GetSongById(int songId); ReadOnlyCollection GetSongs(); ReadOnlyCollection GetVisibleSongs(); CCategory GetCategory(int index); - void AddPartySongSung(int songID); + void AddPartySongSung(int songId); void ResetSongSung(int catIndex = -1); - void SortSongs(ESongSorting sorting, EOffOn tabs, EOffOn ignoreArticles, String searchString, EDuetOptions duetOptions, int playlistID); + void SortSongs(ESongSorting sorting, EOffOn tabs, EOffOn ignoreArticles, String searchString, EDuetOptions duetOptions, int playlistId); void NextCategory(); void PrevCategory(); @@ -275,18 +274,18 @@ namespace VocaluxeLib public interface ISound { int Load(string soundFile, bool loop = false, bool prescan = false); - void SetPosition(int streamID, float newPosition); - void Play(int streamID); - void Fade(int streamID, int targetVolume, float duration, EStreamAction afterFadeAction = EStreamAction.Nothing); - void Close(int streamID); + void SetPosition(int streamId, float newPosition); + void Play(int streamId); + void Fade(int streamId, int targetVolume, float duration, EStreamAction afterFadeAction = EStreamAction.Nothing); + void Close(int streamId); - bool IsFinished(int streamID); - float GetPosition(int streamID); - float GetLength(int streamID); + bool IsFinished(int streamId); + float GetPosition(int streamId); + float GetLength(int streamId); - void SetStreamVolume(int streamID, int volume); + void SetStreamVolume(int streamId, int volume); void SetGlobalVolume(int volume); - bool IsPaused(int streamID); + bool IsPaused(int streamId); } public interface ICover @@ -298,7 +297,7 @@ namespace VocaluxeLib public interface IDataBase { bool GetCover(string fileName, ref CTextureRef texture, int coverSize); - bool GetDataBaseSongInfos(string artist, string title, out int numPlayed, out DateTime dateAdded, out int highscoreID); + bool GetDataBaseSongInfos(string artist, string title, out int numPlayed, out DateTime dateAdded, out int highscoreId); } public interface IControllers @@ -308,28 +307,28 @@ namespace VocaluxeLib public interface IPlaylist { - bool Exists(int playlistID); - string GetName(int playlistID); + bool Exists(int playlistId); + string GetName(int playlistId); List GetIds(); List GetNames(); - void SetName(int playlistID, string name); - void Delete(int playlistID); - void Save(int playlistID); + void SetName(int playlistId, string name); + void Delete(int playlistId); + void Save(int playlistId); int GetNumPlaylists(); - void AddSong(int playlistID, int songID); - void AddSong(int playlistID, int songID, EGameMode gameMode); - void InsertSong(int playlistID, int positionIndex, int songID, EGameMode gameMode); + void AddSong(int playlistId, int songId); + void AddSong(int playlistId, int songId, EGameMode gameMode); + void InsertSong(int playlistId, int positionIndex, int songId, EGameMode gameMode); - void MoveSong(int playlistID, int sourceIndex, int destIndex); - void MoveSongDown(int playlistID, int songIndex); - void MoveSongUp(int playlistID, int songIndex); - void DeleteSong(int playlistID, int songIndex); + void MoveSong(int playlistId, int sourceIndex, int destIndex); + void MoveSongDown(int playlistId, int songIndex); + void MoveSongUp(int playlistId, int songIndex); + void DeleteSong(int playlistId, int songIndex); - int GetSongCount(int playlistID); - CPlaylistSong GetSong(int playlistID, int songIndex); - bool ContainsSong(int playlistID, int songIndex); + int GetSongCount(int playlistId); + CPlaylistSong GetSong(int playlistId, int songIndex); + bool ContainsSong(int playlistId, int songIndex); } public interface IPreviewPlayer @@ -343,4 +342,4 @@ namespace VocaluxeLib bool IsPlaying(); float GetLength(); } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Log/CBenchmark.cs b/VocaluxeLib/Log/CBenchmark.cs index 89482654..b490714c 100644 --- a/VocaluxeLib/Log/CBenchmark.cs +++ b/VocaluxeLib/Log/CBenchmark.cs @@ -29,7 +29,7 @@ namespace VocaluxeLib.Log { // Pool of stop watches shared between all instances (we can get more than 5 but it only keeps 5) private static readonly CObjectPool _WatchesPool = new CObjectPool(() => new Stopwatch(), 5); - private static readonly double _NanosecPerTick = (1000.0 * 1000.0 * 1000.0) / Stopwatch.Frequency; + private static readonly double _NanosecPerTick = 1000.0 * 1000.0 * 1000.0 / Stopwatch.Frequency; // The stop watch used by this instance private Stopwatch _Watch = null; @@ -51,7 +51,10 @@ namespace VocaluxeLib.Log public void Start() { if (_Watch != null) + { throw new InvalidOperationException("Timer is already running."); + } + _Watch = _WatchesPool.GetObject(); _Watch.Restart(); CLog.Information("Started {StartedOperation}", CLog.Params(_OperationName)); @@ -64,16 +67,23 @@ namespace VocaluxeLib.Log public void Stop(bool success = true) { if (_Watch == null) + { return; + } + _Watch.Stop(); - double duration = _GetElapsedTime(_Watch); + var duration = _GetElapsedTime(_Watch); _WatchesPool.PutObject(_Watch); _Watch = null; if (success) + { CLog.Information("Finished {StartedOperation} successfully in {Duration:#,##0.00}ms", CLog.Params(_OperationName, duration)); + } else + { CLog.Information("Failed {StartedOperation} in {Duration:#,##0.00}ms", CLog.Params(_OperationName, duration)); + } } /// @@ -84,9 +94,13 @@ namespace VocaluxeLib.Log private double _GetElapsedTime(Stopwatch watch) { if (Stopwatch.IsHighResolution && _NanosecPerTick > 0) - return (float)((_NanosecPerTick * watch.ElapsedTicks) / (1000.0 * 1000.0)); + { + return (float)(_NanosecPerTick * watch.ElapsedTicks / (1000.0 * 1000.0)); + } else + { return watch.ElapsedMilliseconds; + } } /// @@ -95,11 +109,12 @@ namespace VocaluxeLib.Log public void Dispose() { if (_Watch != null) + { Stop(); + } } #region Static functions - /// /// Logs the time from now to disposal of the returned object. /// @@ -114,7 +129,7 @@ namespace VocaluxeLib.Log /// public static IDisposable Time(string operationName) { - CBenchmark benchmark = new CBenchmark(operationName); + var benchmark = new CBenchmark(operationName); benchmark.Start(); return benchmark; } @@ -134,13 +149,12 @@ namespace VocaluxeLib.Log /// public static COperation Begin(string operationName) { - CBenchmark benchmark = new CBenchmark(operationName); + var benchmark = new CBenchmark(operationName); benchmark.Start(); return new COperation(benchmark); } #region Helper class for operation - /// /// Helper object to end a benchmark (End() for success and Dispose() for failure). /// @@ -155,7 +169,6 @@ namespace VocaluxeLib.Log internal COperation(CBenchmark benchmark) { _Benchmark = benchmark; - } /// @@ -174,9 +187,7 @@ namespace VocaluxeLib.Log _Benchmark.Stop(false); } } - #endregion - #endregion } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Log/CLog.cs b/VocaluxeLib/Log/CLog.cs index 6d1d3535..a1eac06b 100644 --- a/VocaluxeLib/Log/CLog.cs +++ b/VocaluxeLib/Log/CLog.cs @@ -51,7 +51,8 @@ namespace VocaluxeLib.Log /// The current version tag as it is displayed in the main menu. /// Delegate to the function which should be called if the reporter have to been shown. /// The log level for log messages. - public static void Init(string logFolder, string fileNameMainLog, string fileNameSongInfoLog, string fileNameCrashMarker, string currentVersion, ShowReporterDelegate showReporterFunc, ELogLevel logLevel) + public static void Init(string logFolder, string fileNameMainLog, string fileNameSongInfoLog, string fileNameCrashMarker, string currentVersion, + ShowReporterDelegate showReporterFunc, ELogLevel logLevel) { _LogFolder = logFolder; _ShowReporterFunc = showReporterFunc; @@ -61,7 +62,9 @@ namespace VocaluxeLib.Log // Creates the log directory if it does not exist if (!Directory.Exists(_LogFolder)) + { Directory.CreateDirectory(_LogFolder); + } var mainLogFilePath = Path.Combine(_LogFolder, fileNameMainLog); var songLogFilePath = Path.Combine(_LogFolder, fileNameSongInfoLog); @@ -71,7 +74,7 @@ namespace VocaluxeLib.Log { // There was a crash in the last run -> check version tag of the crashed application instance string versionTag; - using (StreamReader reader = new StreamReader(_CrashMarkerFilePath, Encoding.UTF8)) + using (var reader = new StreamReader(_CrashMarkerFilePath, Encoding.UTF8)) { versionTag = (reader.ReadLine() ?? "").Trim(); } @@ -91,7 +94,7 @@ namespace VocaluxeLib.Log } #endif } - + // Write new marker File.WriteAllText(_CrashMarkerFilePath, _CurrentVersion, Encoding.UTF8); @@ -116,7 +119,7 @@ namespace VocaluxeLib.Log _SongLog = new LoggerConfiguration() .MinimumLevel.Is(logLevel.ToSerilogLogLevel()) - .WriteTo.File(songLogFilePath, + .WriteTo.File(songLogFilePath, flushToDiskInterval: TimeSpan.FromSeconds(60), outputTemplate: _SongLogTemplate) #if DEBUG @@ -125,10 +128,10 @@ namespace VocaluxeLib.Log .CreateLogger(); // Adding first line to log with information about this run - Information("Starting to log", - Params( new { Version = _CurrentVersion}, - new { StartDate = DateTime.Now}, - new { Id = Guid.NewGuid() } ) ); + Information("Starting to log", + Params(new { Version = _CurrentVersion }, + new { StartDate = DateTime.Now }, + new { Id = Guid.NewGuid() })); } /// @@ -138,7 +141,7 @@ namespace VocaluxeLib.Log { if (!(_MainLog is CSilentLogger)) { - ILogger loggerToDispose = _MainLog; + var loggerToDispose = _MainLog; _MainLog = new CSilentLogger(); (loggerToDispose as IDisposable)?.Dispose(); @@ -146,7 +149,7 @@ namespace VocaluxeLib.Log if (!(_SongLog is CSilentLogger)) { - ILogger loggerToDispose = _SongLog; + var loggerToDispose = _SongLog; _SongLog = new CSilentLogger(); (loggerToDispose as IDisposable)?.Dispose(); @@ -154,7 +157,6 @@ namespace VocaluxeLib.Log // Delete the crash marker File.Delete(_CrashMarkerFilePath); - } /// @@ -169,7 +171,8 @@ namespace VocaluxeLib.Log // Flush the _MainLogStringWriter to get the latest entries to _MainLogStringBuilder _MainLogStringWriter.Flush(); // Show the Reporter - _ShowReporterFunc(crash: crash, showContinue: showContinue, vocaluxeVersionTag: _CurrentVersion, log: _MainLogStringBuilder.ToString(), lastError: _FormatMessageTemplate(messageTemplate, propertyValues)); + _ShowReporterFunc(crash: crash, showContinue: showContinue, vocaluxeVersionTag: _CurrentVersion, log: _MainLogStringBuilder.ToString(), + lastError: _FormatMessageTemplate(messageTemplate, propertyValues)); // Delete the crash marker (we do not want to show this error again on the next restart) if (!showContinue) @@ -191,16 +194,18 @@ namespace VocaluxeLib.Log return template; } - Regex theRegex = new Regex(@"{[^}]+}"); - - int i = 0; + var theRegex = new Regex(@"{[^}]+}"); + + var i = 0; return theRegex.Replace(template, delegate(Match match) { if (i >= propertyValues.Length) + { return match.Value; + } + return "\"" + propertyValues[i++] + "\""; }); } - } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Log/CLogFunctions.cs b/VocaluxeLib/Log/CLogFunctions.cs index 7b857921..156ee18e 100644 --- a/VocaluxeLib/Log/CLogFunctions.cs +++ b/VocaluxeLib/Log/CLogFunctions.cs @@ -34,9 +34,7 @@ namespace VocaluxeLib.Log return propertyValues; } - #region Verbose functions - /// /// Write an event with the Verbose level to the Verbose log. /// @@ -46,14 +44,18 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Verbose(string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Verbose(string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) - { - _MainLog.Verbose(messageTemplate); + { + _MainLog.Verbose(messageTemplate); } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, null); + } } /// @@ -66,11 +68,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Verbose(string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Verbose(string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); if (propertyValues.Length > usedPropertiesCount) { @@ -84,8 +87,11 @@ namespace VocaluxeLib.Log _MainLog.Verbose(messageTemplate, propertyValues); } } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, propertyValues); + } } /// @@ -98,14 +104,18 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Verbose(Exception exception, string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Verbose(Exception exception, string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - _MainLog.Verbose( exception, messageTemplate); + _MainLog.Verbose(exception, messageTemplate); } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, null); + } } /// @@ -119,11 +129,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Verbose(Exception exception, string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Verbose(Exception exception, string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); if (propertyValues.Length > usedPropertiesCount) { @@ -137,14 +148,15 @@ namespace VocaluxeLib.Log _MainLog.Verbose(exception, messageTemplate, propertyValues); } } - if(show) - ShowLogAssistant(messageTemplate, propertyValues); - } + if (show) + { + ShowLogAssistant(messageTemplate, propertyValues); + } + } #endregion #region Debug functions - /// /// Write an event with the Debug level to the Debug log. /// @@ -154,14 +166,18 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Debug(string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Debug(string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) - { - _MainLog.Debug(messageTemplate); + { + _MainLog.Debug(messageTemplate); } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, null); + } } /// @@ -174,11 +190,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Debug(string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Debug(string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); if (propertyValues.Length > usedPropertiesCount) { @@ -192,8 +209,11 @@ namespace VocaluxeLib.Log _MainLog.Debug(messageTemplate, propertyValues); } } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, propertyValues); + } } /// @@ -206,14 +226,18 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Debug(Exception exception, string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Debug(Exception exception, string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - _MainLog.Debug( exception, messageTemplate); + _MainLog.Debug(exception, messageTemplate); } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, null); + } } /// @@ -227,11 +251,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Debug(Exception exception, string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Debug(Exception exception, string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); if (propertyValues.Length > usedPropertiesCount) { @@ -245,14 +270,15 @@ namespace VocaluxeLib.Log _MainLog.Debug(exception, messageTemplate, propertyValues); } } - if(show) - ShowLogAssistant(messageTemplate, propertyValues); - } + if (show) + { + ShowLogAssistant(messageTemplate, propertyValues); + } + } #endregion #region Information functions - /// /// Write an event with the Information level to the Information log. /// @@ -262,14 +288,18 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Information(string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Information(string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) - { - _MainLog.Information(messageTemplate); + { + _MainLog.Information(messageTemplate); } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, null); + } } /// @@ -282,11 +312,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Information(string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Information(string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); if (propertyValues.Length > usedPropertiesCount) { @@ -300,8 +331,11 @@ namespace VocaluxeLib.Log _MainLog.Information(messageTemplate, propertyValues); } } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, propertyValues); + } } /// @@ -314,14 +348,18 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Information(Exception exception, string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Information(Exception exception, string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - _MainLog.Information( exception, messageTemplate); + _MainLog.Information(exception, messageTemplate); } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, null); + } } /// @@ -335,11 +373,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Information(Exception exception, string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Information(Exception exception, string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); if (propertyValues.Length > usedPropertiesCount) { @@ -353,14 +392,15 @@ namespace VocaluxeLib.Log _MainLog.Information(exception, messageTemplate, propertyValues); } } - if(show) - ShowLogAssistant(messageTemplate, propertyValues); - } + if (show) + { + ShowLogAssistant(messageTemplate, propertyValues); + } + } #endregion #region Warning functions - /// /// Write an event with the Warning level to the Warning log. /// @@ -370,14 +410,18 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Warning(string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Warning(string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) - { - _MainLog.Warning(messageTemplate); + { + _MainLog.Warning(messageTemplate); } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, null); + } } /// @@ -390,11 +434,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Warning(string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Warning(string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); if (propertyValues.Length > usedPropertiesCount) { @@ -408,8 +453,11 @@ namespace VocaluxeLib.Log _MainLog.Warning(messageTemplate, propertyValues); } } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, propertyValues); + } } /// @@ -422,14 +470,18 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Warning(Exception exception, string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Warning(Exception exception, string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - _MainLog.Warning( exception, messageTemplate); + _MainLog.Warning(exception, messageTemplate); } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, null); + } } /// @@ -443,11 +495,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Warning(Exception exception, string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Warning(Exception exception, string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); if (propertyValues.Length > usedPropertiesCount) { @@ -461,14 +514,15 @@ namespace VocaluxeLib.Log _MainLog.Warning(exception, messageTemplate, propertyValues); } } - if(show) - ShowLogAssistant(messageTemplate, propertyValues); - } + if (show) + { + ShowLogAssistant(messageTemplate, propertyValues); + } + } #endregion #region Error functions - /// /// Write an event with the Error level to the Error log. /// @@ -478,14 +532,18 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Error(string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Error(string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) - { - _MainLog.Error(messageTemplate); + { + _MainLog.Error(messageTemplate); } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, null); + } } /// @@ -498,11 +556,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Error(string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Error(string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); if (propertyValues.Length > usedPropertiesCount) { @@ -516,8 +575,11 @@ namespace VocaluxeLib.Log _MainLog.Error(messageTemplate, propertyValues); } } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, propertyValues); + } } /// @@ -530,14 +592,18 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Error(Exception exception, string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Error(Exception exception, string messageTemplate, bool show = false, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - _MainLog.Error( exception, messageTemplate); + _MainLog.Error(exception, messageTemplate); } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, null); + } } /// @@ -551,11 +617,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Error(Exception exception, string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Error(Exception exception, string messageTemplate, object[] propertyValues, bool show = false, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); if (propertyValues.Length > usedPropertiesCount) { @@ -569,14 +636,15 @@ namespace VocaluxeLib.Log _MainLog.Error(exception, messageTemplate, propertyValues); } } - if(show) - ShowLogAssistant(messageTemplate, propertyValues); - } + if (show) + { + ShowLogAssistant(messageTemplate, propertyValues); + } + } #endregion #region Fatal functions - /// /// Write an event with the Fatal level to the Fatal log and TERMINATES the appication. /// @@ -586,14 +654,18 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Fatal(string messageTemplate, bool show = true, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Fatal(string messageTemplate, bool show = true, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) - { - _MainLog.Fatal(messageTemplate); + { + _MainLog.Fatal(messageTemplate); } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, null, true, false); + } // Close logs and exit Close(); @@ -610,11 +682,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Fatal(string messageTemplate, object[] propertyValues, bool show = true, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Fatal(string messageTemplate, object[] propertyValues, bool show = true, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); if (propertyValues.Length > usedPropertiesCount) { @@ -628,8 +701,11 @@ namespace VocaluxeLib.Log _MainLog.Fatal(messageTemplate, propertyValues); } } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, propertyValues, true, false); + } // Close logs and exit Close(); @@ -646,14 +722,18 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Fatal(Exception exception, string messageTemplate, bool show = true, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Fatal(Exception exception, string messageTemplate, bool show = true, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - _MainLog.Fatal( exception, messageTemplate); + _MainLog.Fatal(exception, messageTemplate); } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, null, true, false); + } // Close logs and exit Close(); @@ -671,11 +751,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Fatal(Exception exception, string messageTemplate, object[] propertyValues, bool show = true, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Fatal(Exception exception, string messageTemplate, object[] propertyValues, bool show = true, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); if (propertyValues.Length > usedPropertiesCount) { @@ -689,22 +770,22 @@ namespace VocaluxeLib.Log _MainLog.Fatal(exception, messageTemplate, propertyValues); } } - if(show) + + if (show) + { ShowLogAssistant(messageTemplate, propertyValues, true, false); + } // Close logs and exit Close(); Environment.Exit(Environment.ExitCode); } - #endregion - + [SuppressMessage("ReSharper", "MemberHidesStaticFromOuterClass")] - public static class CSongLog + public static class CSongLog { - #region Verbose functions - /// /// Write an event with the Verbose level to the Verbose log. /// @@ -713,11 +794,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Verbose(string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Verbose(string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) - { - _SongLog.Verbose(messageTemplate); + { + _SongLog.Verbose(messageTemplate); } } @@ -730,12 +812,13 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Verbose(string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Verbose(string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); - + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + if (propertyValues.Length > usedPropertiesCount) { using (LogContext.PushProperty("AdditionalData", propertyValues.Skip(usedPropertiesCount))) @@ -759,11 +842,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Verbose(Exception exception, string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Verbose(Exception exception, string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - _SongLog.Verbose( exception, messageTemplate); + _SongLog.Verbose(exception, messageTemplate); } } @@ -777,12 +861,13 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Verbose(Exception exception, string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Verbose(Exception exception, string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); - + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + if (propertyValues.Length > usedPropertiesCount) { using (LogContext.PushProperty("AdditionalData", propertyValues.Skip(usedPropertiesCount))) @@ -796,11 +881,9 @@ namespace VocaluxeLib.Log } } } - #endregion #region Debug functions - /// /// Write an event with the Debug level to the Debug log. /// @@ -809,11 +892,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Debug(string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Debug(string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) - { - _SongLog.Debug(messageTemplate); + { + _SongLog.Debug(messageTemplate); } } @@ -826,12 +910,13 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Debug(string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Debug(string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); - + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + if (propertyValues.Length > usedPropertiesCount) { using (LogContext.PushProperty("AdditionalData", propertyValues.Skip(usedPropertiesCount))) @@ -855,11 +940,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Debug(Exception exception, string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Debug(Exception exception, string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - _SongLog.Debug( exception, messageTemplate); + _SongLog.Debug(exception, messageTemplate); } } @@ -873,12 +959,13 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Debug(Exception exception, string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Debug(Exception exception, string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); - + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + if (propertyValues.Length > usedPropertiesCount) { using (LogContext.PushProperty("AdditionalData", propertyValues.Skip(usedPropertiesCount))) @@ -892,11 +979,9 @@ namespace VocaluxeLib.Log } } } - #endregion #region Information functions - /// /// Write an event with the Information level to the Information log. /// @@ -905,11 +990,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Information(string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Information(string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) - { - _SongLog.Information(messageTemplate); + { + _SongLog.Information(messageTemplate); } } @@ -922,12 +1008,13 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Information(string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Information(string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); - + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + if (propertyValues.Length > usedPropertiesCount) { using (LogContext.PushProperty("AdditionalData", propertyValues.Skip(usedPropertiesCount))) @@ -951,11 +1038,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Information(Exception exception, string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Information(Exception exception, string messageTemplate, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - _SongLog.Information( exception, messageTemplate); + _SongLog.Information(exception, messageTemplate); } } @@ -969,12 +1057,13 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Information(Exception exception, string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Information(Exception exception, string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); - + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + if (propertyValues.Length > usedPropertiesCount) { using (LogContext.PushProperty("AdditionalData", propertyValues.Skip(usedPropertiesCount))) @@ -988,11 +1077,9 @@ namespace VocaluxeLib.Log } } } - #endregion #region Warning functions - /// /// Write an event with the Warning level to the Warning log. /// @@ -1001,11 +1088,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Warning(string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Warning(string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) - { - _SongLog.Warning(messageTemplate); + { + _SongLog.Warning(messageTemplate); } } @@ -1018,12 +1106,13 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Warning(string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Warning(string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); - + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + if (propertyValues.Length > usedPropertiesCount) { using (LogContext.PushProperty("AdditionalData", propertyValues.Skip(usedPropertiesCount))) @@ -1047,11 +1136,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Warning(Exception exception, string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Warning(Exception exception, string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - _SongLog.Warning( exception, messageTemplate); + _SongLog.Warning(exception, messageTemplate); } } @@ -1065,12 +1155,13 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Warning(Exception exception, string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Warning(Exception exception, string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); - + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + if (propertyValues.Length > usedPropertiesCount) { using (LogContext.PushProperty("AdditionalData", propertyValues.Skip(usedPropertiesCount))) @@ -1084,11 +1175,9 @@ namespace VocaluxeLib.Log } } } - #endregion #region Error functions - /// /// Write an event with the Error level to the Error log. /// @@ -1097,11 +1186,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Error(string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Error(string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) - { - _SongLog.Error(messageTemplate); + { + _SongLog.Error(messageTemplate); } } @@ -1114,12 +1204,13 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Error(string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Error(string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); - + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + if (propertyValues.Length > usedPropertiesCount) { using (LogContext.PushProperty("AdditionalData", propertyValues.Skip(usedPropertiesCount))) @@ -1143,11 +1234,12 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Error(Exception exception, string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Error(Exception exception, string messageTemplate, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - _SongLog.Error( exception, messageTemplate); + _SongLog.Error(exception, messageTemplate); } } @@ -1161,12 +1253,13 @@ namespace VocaluxeLib.Log /// Don't use! The filepath of the caller will be filled automatically by the compiler. /// Don't use! The line number of the caller will be filled automatically by the compiler. [MessageTemplateFormatMethod("messageTemplate")] - public static void Error(Exception exception, string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) + public static void Error(Exception exception, string messageTemplate, object[] propertyValues, [CallerMemberName] string callerMethodeName = "", + [CallerFilePath] string callerFilePath = "", [CallerLineNumber] int callerLineNumber = -1) { using (LogContext.PushProperty("CallingContext", new { callerMethodeName, callerFilePath, callerLineNumber })) { - int usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); - + var usedPropertiesCount = _PropertiesRegex.Matches(messageTemplate).Cast().Select(m => m.Value).Distinct().Count(); + if (propertyValues.Length > usedPropertiesCount) { using (LogContext.PushProperty("AdditionalData", propertyValues.Skip(usedPropertiesCount))) @@ -1180,7 +1273,6 @@ namespace VocaluxeLib.Log } } } - #endregion } } diff --git a/VocaluxeLib/Log/ELogLevel.cs b/VocaluxeLib/Log/ELogLevel.cs index d9ebc627..b0fb4e1f 100644 --- a/VocaluxeLib/Log/ELogLevel.cs +++ b/VocaluxeLib/Log/ELogLevel.cs @@ -53,4 +53,4 @@ namespace VocaluxeLib.Log } } } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Log/Enricher/CTimeStampFromStartEnricher.cs b/VocaluxeLib/Log/Enricher/CTimeStampFromStartEnricher.cs index 825285cc..ab95f8fb 100644 --- a/VocaluxeLib/Log/Enricher/CTimeStampFromStartEnricher.cs +++ b/VocaluxeLib/Log/Enricher/CTimeStampFromStartEnricher.cs @@ -42,4 +42,4 @@ namespace VocaluxeLib.Log.Enricher } } } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Log/Rolling/CLogFileRoller.cs b/VocaluxeLib/Log/Rolling/CLogFileRoller.cs index e417d6d0..ff7b933a 100644 --- a/VocaluxeLib/Log/Rolling/CLogFileRoller.cs +++ b/VocaluxeLib/Log/Rolling/CLogFileRoller.cs @@ -16,7 +16,6 @@ #endregion using System; -using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; @@ -28,12 +27,12 @@ namespace VocaluxeLib.Log.Rolling { _DeleteOldLogs(mainLogFile, numLogsToKeep); - string currentSourceFile = _GenerateRollLogFileName(mainLogFile, numLogsToKeep); + var currentSourceFile = _GenerateRollLogFileName(mainLogFile, numLogsToKeep); for (var i = numLogsToKeep; i > 1; i--) { - string currentTargetFile = currentSourceFile; + var currentTargetFile = currentSourceFile; currentSourceFile = _GenerateRollLogFileName(mainLogFile, i - 1); if (File.Exists(currentSourceFile)) @@ -57,9 +56,13 @@ namespace VocaluxeLib.Log.Rolling try { if (numLogsToKeep > 0) + { File.Move(mainLogFile, currentSourceFile); + } else + { File.Delete(mainLogFile); + } } catch (Exception e) { @@ -73,14 +76,16 @@ namespace VocaluxeLib.Log.Rolling private static void _DeleteOldLogs(string mainLogFile, int numLogsToKeep) { - Regex r = new Regex($"{Regex.Escape(Path.GetDirectoryName(mainLogFile)??"")}\\{Path.DirectorySeparatorChar}{Regex.Escape(Path.GetFileNameWithoutExtension(mainLogFile)??"")}_([0-9]+){Path.GetExtension(mainLogFile)}", RegexOptions.IgnoreCase); - IEnumerable logFiles = Directory.EnumerateFiles($"{Path.GetDirectoryName(mainLogFile)}", $"{Path.GetFileNameWithoutExtension(mainLogFile)}*{Path.GetExtension(mainLogFile)}"); - foreach (string file in logFiles) + var r = new Regex( + $"{Regex.Escape(Path.GetDirectoryName(mainLogFile) ?? "")}\\{Path.DirectorySeparatorChar}{Regex.Escape(Path.GetFileNameWithoutExtension(mainLogFile) ?? "")}_([0-9]+){Path.GetExtension(mainLogFile)}", + RegexOptions.IgnoreCase); + var logFiles = Directory.EnumerateFiles($"{Path.GetDirectoryName(mainLogFile)}", $"{Path.GetFileNameWithoutExtension(mainLogFile)}*{Path.GetExtension(mainLogFile)}"); + foreach (var file in logFiles) { - Match m = r.Match(file); + var m = r.Match(file); if (m.Success) { - int logNum = -1; + var logNum = -1; Int32.TryParse(m.Groups[1].Value, out logNum); if (logNum < 0 || logNum > numLogsToKeep - 1) @@ -96,7 +101,6 @@ namespace VocaluxeLib.Log.Rolling Console.WriteLine($"Error deleting old log file: {e.Message}"); #endif } - } } } @@ -104,7 +108,7 @@ namespace VocaluxeLib.Log.Rolling private static string _GenerateRollLogFileName(string mainLogFile, int number) { - return $"{ Path.GetDirectoryName(mainLogFile) }{ Path.DirectorySeparatorChar }{ Path.GetFileNameWithoutExtension(mainLogFile) }_{ number }{ Path.GetExtension(mainLogFile) }"; + return $"{Path.GetDirectoryName(mainLogFile)}{Path.DirectorySeparatorChar}{Path.GetFileNameWithoutExtension(mainLogFile)}_{number}{Path.GetExtension(mainLogFile)}"; } } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Log/Serilog/CSilentLogger.cs b/VocaluxeLib/Log/Serilog/CSilentLogger.cs index d7c1a244..10c4c8db 100644 --- a/VocaluxeLib/Log/Serilog/CSilentLogger.cs +++ b/VocaluxeLib/Log/Serilog/CSilentLogger.cs @@ -49,294 +49,152 @@ namespace VocaluxeLib.Log.Serilog return this; } - public void Write(LogEvent logEvent) - { - } + public void Write(LogEvent logEvent) { } - public void Write(LogEventLevel level, string messageTemplate) - { - } + public void Write(LogEventLevel level, string messageTemplate) { } - public void Write(LogEventLevel level, string messageTemplate, T propertyValue) - { - } + public void Write(LogEventLevel level, string messageTemplate, T propertyValue) { } - public void Write(LogEventLevel level, string messageTemplate, T0 propertyValue0, T1 propertyValue1) - { - } + public void Write(LogEventLevel level, string messageTemplate, T0 propertyValue0, T1 propertyValue1) { } - public void Write(LogEventLevel level, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) - { - } + public void Write(LogEventLevel level, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) { } - public void Write(LogEventLevel level, string messageTemplate, params object[] propertyValues) - { - } + public void Write(LogEventLevel level, string messageTemplate, params object[] propertyValues) { } - public void Write(LogEventLevel level, Exception exception, string messageTemplate) - { - } + public void Write(LogEventLevel level, Exception exception, string messageTemplate) { } - public void Write(LogEventLevel level, Exception exception, string messageTemplate, T propertyValue) - { - } + public void Write(LogEventLevel level, Exception exception, string messageTemplate, T propertyValue) { } - public void Write(LogEventLevel level, Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) - { - } + public void Write(LogEventLevel level, Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) { } - public void Write(LogEventLevel level, Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) - { - } + public void Write(LogEventLevel level, Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) { } - public void Write(LogEventLevel level, Exception exception, string messageTemplate, params object[] propertyValues) - { - } + public void Write(LogEventLevel level, Exception exception, string messageTemplate, params object[] propertyValues) { } public bool IsEnabled(LogEventLevel level) { return false; } - public void Verbose(string messageTemplate) - { - } + public void Verbose(string messageTemplate) { } - public void Verbose(string messageTemplate, T propertyValue) - { - } + public void Verbose(string messageTemplate, T propertyValue) { } - public void Verbose(string messageTemplate, T0 propertyValue0, T1 propertyValue1) - { - } + public void Verbose(string messageTemplate, T0 propertyValue0, T1 propertyValue1) { } - public void Verbose(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) - { - } + public void Verbose(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) { } - public void Verbose(string messageTemplate, params object[] propertyValues) - { - } + public void Verbose(string messageTemplate, params object[] propertyValues) { } - public void Verbose(Exception exception, string messageTemplate) - { - } + public void Verbose(Exception exception, string messageTemplate) { } - public void Verbose(Exception exception, string messageTemplate, T propertyValue) - { - } + public void Verbose(Exception exception, string messageTemplate, T propertyValue) { } - public void Verbose(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) - { - } + public void Verbose(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) { } - public void Verbose(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) - { - } + public void Verbose(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) { } - public void Verbose(Exception exception, string messageTemplate, params object[] propertyValues) - { - } + public void Verbose(Exception exception, string messageTemplate, params object[] propertyValues) { } - public void Debug(string messageTemplate) - { - } + public void Debug(string messageTemplate) { } - public void Debug(string messageTemplate, T propertyValue) - { - } + public void Debug(string messageTemplate, T propertyValue) { } - public void Debug(string messageTemplate, T0 propertyValue0, T1 propertyValue1) - { - } + public void Debug(string messageTemplate, T0 propertyValue0, T1 propertyValue1) { } - public void Debug(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) - { - } + public void Debug(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) { } - public void Debug(string messageTemplate, params object[] propertyValues) - { - } + public void Debug(string messageTemplate, params object[] propertyValues) { } - public void Debug(Exception exception, string messageTemplate) - { - } + public void Debug(Exception exception, string messageTemplate) { } - public void Debug(Exception exception, string messageTemplate, T propertyValue) - { - } + public void Debug(Exception exception, string messageTemplate, T propertyValue) { } - public void Debug(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) - { - } + public void Debug(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) { } - public void Debug(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) - { - } + public void Debug(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) { } - public void Debug(Exception exception, string messageTemplate, params object[] propertyValues) - { - } + public void Debug(Exception exception, string messageTemplate, params object[] propertyValues) { } - public void Information(string messageTemplate) - { - } + public void Information(string messageTemplate) { } - public void Information(string messageTemplate, T propertyValue) - { - } + public void Information(string messageTemplate, T propertyValue) { } - public void Information(string messageTemplate, T0 propertyValue0, T1 propertyValue1) - { - } + public void Information(string messageTemplate, T0 propertyValue0, T1 propertyValue1) { } - public void Information(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) - { - } + public void Information(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) { } - public void Information(string messageTemplate, params object[] propertyValues) - { - } + public void Information(string messageTemplate, params object[] propertyValues) { } - public void Information(Exception exception, string messageTemplate) - { - } + public void Information(Exception exception, string messageTemplate) { } - public void Information(Exception exception, string messageTemplate, T propertyValue) - { - } + public void Information(Exception exception, string messageTemplate, T propertyValue) { } - public void Information(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) - { - } + public void Information(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) { } - public void Information(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) - { - } + public void Information(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) { } - public void Information(Exception exception, string messageTemplate, params object[] propertyValues) - { - } + public void Information(Exception exception, string messageTemplate, params object[] propertyValues) { } - public void Warning(string messageTemplate) - { - } + public void Warning(string messageTemplate) { } - public void Warning(string messageTemplate, T propertyValue) - { - } + public void Warning(string messageTemplate, T propertyValue) { } - public void Warning(string messageTemplate, T0 propertyValue0, T1 propertyValue1) - { - } + public void Warning(string messageTemplate, T0 propertyValue0, T1 propertyValue1) { } - public void Warning(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) - { - } + public void Warning(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) { } - public void Warning(string messageTemplate, params object[] propertyValues) - { - } + public void Warning(string messageTemplate, params object[] propertyValues) { } - public void Warning(Exception exception, string messageTemplate) - { - } + public void Warning(Exception exception, string messageTemplate) { } - public void Warning(Exception exception, string messageTemplate, T propertyValue) - { - } + public void Warning(Exception exception, string messageTemplate, T propertyValue) { } - public void Warning(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) - { - } + public void Warning(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) { } - public void Warning(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) - { - } + public void Warning(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) { } - public void Warning(Exception exception, string messageTemplate, params object[] propertyValues) - { - } + public void Warning(Exception exception, string messageTemplate, params object[] propertyValues) { } - public void Error(string messageTemplate) - { - } + public void Error(string messageTemplate) { } - public void Error(string messageTemplate, T propertyValue) - { - } + public void Error(string messageTemplate, T propertyValue) { } - public void Error(string messageTemplate, T0 propertyValue0, T1 propertyValue1) - { - } + public void Error(string messageTemplate, T0 propertyValue0, T1 propertyValue1) { } - public void Error(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) - { - } + public void Error(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) { } - public void Error(string messageTemplate, params object[] propertyValues) - { - } + public void Error(string messageTemplate, params object[] propertyValues) { } - public void Error(Exception exception, string messageTemplate) - { - } + public void Error(Exception exception, string messageTemplate) { } - public void Error(Exception exception, string messageTemplate, T propertyValue) - { - } + public void Error(Exception exception, string messageTemplate, T propertyValue) { } - public void Error(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) - { - } + public void Error(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) { } - public void Error(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) - { - } + public void Error(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) { } - public void Error(Exception exception, string messageTemplate, params object[] propertyValues) - { - } + public void Error(Exception exception, string messageTemplate, params object[] propertyValues) { } - public void Fatal(string messageTemplate) - { - } + public void Fatal(string messageTemplate) { } - public void Fatal(string messageTemplate, T propertyValue) - { - } + public void Fatal(string messageTemplate, T propertyValue) { } - public void Fatal(string messageTemplate, T0 propertyValue0, T1 propertyValue1) - { - } + public void Fatal(string messageTemplate, T0 propertyValue0, T1 propertyValue1) { } - public void Fatal(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) - { - } + public void Fatal(string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) { } - public void Fatal(string messageTemplate, params object[] propertyValues) - { - } + public void Fatal(string messageTemplate, params object[] propertyValues) { } - public void Fatal(Exception exception, string messageTemplate) - { - } + public void Fatal(Exception exception, string messageTemplate) { } - public void Fatal(Exception exception, string messageTemplate, T propertyValue) - { - } + public void Fatal(Exception exception, string messageTemplate, T propertyValue) { } - public void Fatal(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) - { - } + public void Fatal(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1) { } - public void Fatal(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) - { - } + public void Fatal(Exception exception, string messageTemplate, T0 propertyValue0, T1 propertyValue1, T2 propertyValue2) { } - public void Fatal(Exception exception, string messageTemplate, params object[] propertyValues) - { - } + public void Fatal(Exception exception, string messageTemplate, params object[] propertyValues) { } [MessageTemplateFormatMethod("messageTemplate")] public bool BindMessageTemplate(string messageTemplate, object[] propertyValues, out MessageTemplate parsedTemplate, out IEnumerable boundProperties) diff --git a/VocaluxeLib/Log/ShowReporterDelegate.cs b/VocaluxeLib/Log/ShowReporterDelegate.cs index 8edf6025..a81320a8 100644 --- a/VocaluxeLib/Log/ShowReporterDelegate.cs +++ b/VocaluxeLib/Log/ShowReporterDelegate.cs @@ -26,4 +26,4 @@ namespace VocaluxeLib.Log /// The log to submit. /// The last error message. public delegate void ShowReporterDelegate(bool crash, bool showContinue, string vocaluxeVersionTag, string log, string lastError); -} +} \ No newline at end of file diff --git a/VocaluxeLib/Menu/CBackground.cs b/VocaluxeLib/Menu/CBackground.cs index 2035612e..ebb3da62 100644 --- a/VocaluxeLib/Menu/CBackground.cs +++ b/VocaluxeLib/Menu/CBackground.cs @@ -15,10 +15,9 @@ // along with Vocaluxe. If not, see . #endregion -using System; -using System.Xml.Serialization; -using System.Diagnostics; using System.Collections.Generic; +using System.Diagnostics; +using System.Xml.Serialization; using VocaluxeLib.Draw; namespace VocaluxeLib.Menu @@ -35,17 +34,20 @@ namespace VocaluxeLib.Menu [XmlType("Background")] public struct SThemeBackground { - [XmlAttribute(AttributeName = "Name")] public string Name; + [XmlAttribute(AttributeName = "Name")] + public string Name; public EBackgroundTypes Type; - [XmlArray] public List SlideShowTextures; - [XmlElement("Video")] public string VideoName; + [XmlArray] + public List SlideShowTextures; + [XmlElement("Video")] + public string VideoName; public string Skin; public SThemeColor Color; } public class CBackground : CMenuElementBase, IMenuElement, IThemeable { - private readonly int _PartyModeID; + private readonly int _PartyModeId; private SThemeBackground _Theme; private int _SlideShowCurrent; @@ -68,41 +70,44 @@ namespace VocaluxeLib.Menu } #region Constructors - public CBackground(int partyModeID) + public CBackground(int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; ThemeLoaded = false; - _Theme = new SThemeBackground {SlideShowTextures = new List()}; + _Theme = new SThemeBackground { SlideShowTextures = new List() }; Color = new SColorF(0f, 0f, 0f, 1f); } - public CBackground(SThemeBackground theme, int partyModeID) + public CBackground(SThemeBackground theme, int partyModeId) { _Theme = theme; - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; ThemeLoaded = true; } #endregion Constructors #region public - public void Resume() { if (_VideoStream != null) + { CBase.Video.Resume(_VideoStream); + } } public void Pause() { if (_VideoStream != null) + { CBase.Video.Pause(_VideoStream); + } } public void Draw() { - bool ok = false; + var ok = false; if (_Theme.Type == EBackgroundTypes.Video && CBase.Config.GetVideoBackgrounds() == EOffOn.TR_CONFIG_ON) { if (CBase.Config.GetVideosToBackground() == EOffOn.TR_CONFIG_ON && CBase.BackgroundMusic.IsPlaying() && CBase.BackgroundMusic.SongHasVideo() && @@ -118,19 +123,28 @@ namespace VocaluxeLib.Menu } } else if (_Theme.Type == EBackgroundTypes.SlideShow && _SlideShowTextures.Count > 0) + { ok = _DrawSlideShow(); + } - if (!String.IsNullOrEmpty(_Theme.Skin) && (_Theme.Type == EBackgroundTypes.Texture || !ok)) + if (!string.IsNullOrEmpty(_Theme.Skin) && (_Theme.Type == EBackgroundTypes.Texture || !ok)) + { ok = _DrawTexture(); + } if (_Theme.Type == EBackgroundTypes.Color || !ok) + { _DrawColor(); + } } public void UnloadSkin() { if (!ThemeLoaded) + { return; + } + _SlideShowTextures.Clear(); CBase.Video.Close(ref _VideoStream); } @@ -138,37 +152,47 @@ namespace VocaluxeLib.Menu public void LoadSkin() { if (!ThemeLoaded) + { return; - _Theme.Color.Get(_PartyModeID, out Color); + } + + _Theme.Color.Get(_PartyModeId, out Color); if (_Theme.Type == EBackgroundTypes.SlideShow) { - foreach (string s in _Theme.SlideShowTextures) - _SlideShowTextures.Add(CBase.Themes.GetSkinTexture(s, _PartyModeID)); + foreach (var s in _Theme.SlideShowTextures) + { + _SlideShowTextures.Add(CBase.Themes.GetSkinTexture(s, _PartyModeId)); + } } if (_Theme.Type == EBackgroundTypes.Video) - _VideoStream = CBase.Themes.GetSkinVideo(_Theme.VideoName, _PartyModeID, true); + { + _VideoStream = CBase.Themes.GetSkinVideo(_Theme.VideoName, _PartyModeId, true); + } } public void AddSlideShowTexture(string image) { _Theme.Type = EBackgroundTypes.SlideShow; - if (!String.IsNullOrEmpty(image)) + if (!string.IsNullOrEmpty(image)) { - CTextureRef texture = _SlideShowTextures.Count == 0 ? CBase.Drawing.AddTexture(image) : CBase.Drawing.EnqueueTexture(image); + var texture = _SlideShowTextures.Count == 0 ? CBase.Drawing.AddTexture(image) : CBase.Drawing.EnqueueTexture(image); if (texture != null) + { _SlideShowTextures.Add(texture); + } } } public void RemoveSlideShowTextures() { - foreach (CTextureRef tex in _SlideShowTextures) + foreach (var tex in _SlideShowTextures) { - CTextureRef texture = tex; + var texture = tex; CBase.Drawing.RemoveTexture(ref texture); } + _SlideShowTextures.Clear(); } @@ -213,12 +237,13 @@ namespace VocaluxeLib.Menu private bool _DrawTexture() { - CTextureRef texture = CBase.Themes.GetSkinTexture(_Theme.Skin, _PartyModeID); + var texture = CBase.Themes.GetSkinTexture(_Theme.Skin, _PartyModeId); if (texture != null) { CBase.Drawing.DrawTexture(texture, Rect, EAspect.Crop); return true; } + return false; } @@ -232,34 +257,46 @@ namespace VocaluxeLib.Menu _SlideShowCurrent = 0; } - if (_SlideShowTimer.ElapsedMilliseconds >= (CBase.Settings.GetSlideShowFadeTime() + CBase.Settings.GetSlideShowImageTime())) + if (_SlideShowTimer.ElapsedMilliseconds >= CBase.Settings.GetSlideShowFadeTime() + CBase.Settings.GetSlideShowImageTime()) { _SlideShowTimer.Restart(); if (_SlideShowCurrent + 1 < _SlideShowTextures.Count) + { _SlideShowCurrent++; + } else + { _SlideShowCurrent = 0; + } } - CTextureRef texture = _SlideShowTextures[_SlideShowCurrent]; + var texture = _SlideShowTextures[_SlideShowCurrent]; if (texture == null) + { return false; + } CBase.Drawing.DrawTexture(texture, Rect, EAspect.Crop); if (_SlideShowTimer.ElapsedMilliseconds >= CBase.Settings.GetSlideShowImageTime()) { if (_SlideShowCurrent + 1 < _SlideShowTextures.Count) + { texture = _SlideShowTextures[_SlideShowCurrent + 1]; + } else if (_SlideShowCurrent != 0) + { texture = _SlideShowTextures[0]; + } else + { texture = null; + } if (texture != null) { - SColorF color = texture.Color; + var color = texture.Color; color.A = (_SlideShowTimer.ElapsedMilliseconds - CBase.Settings.GetSlideShowImageTime()) / CBase.Settings.GetSlideShowFadeTime(); CBase.Drawing.DrawTexture(texture, Rect, EAspect.Crop, color); } @@ -267,6 +304,7 @@ namespace VocaluxeLib.Menu return true; } + return false; } @@ -280,27 +318,30 @@ namespace VocaluxeLib.Menu CBase.Drawing.DrawTexture(_VideoStream.Texture, Rect, EAspect.Crop); return true; } + return false; } + return false; } private bool _DrawBackgroundMusicVideo() { - CTextureRef videoTexture = CBase.BackgroundMusic.GetVideoTexture(); + var videoTexture = CBase.BackgroundMusic.GetVideoTexture(); if (videoTexture != null) { CBase.Drawing.DrawTexture(videoTexture, Rect, EAspect.Crop); return true; } + return false; } #endregion internal #region ThemeEdit - public void MoveElement(int stepX, int stepY) {} + public void MoveElement(int stepX, int stepY) { } - public void ResizeElement(int stepW, int stepH) {} + public void ResizeElement(int stepW, int stepH) { } #endregion ThemeEdit } } \ No newline at end of file diff --git a/VocaluxeLib/Menu/CButton.cs b/VocaluxeLib/Menu/CButton.cs index 8b0288f6..16a0fe38 100644 --- a/VocaluxeLib/Menu/CButton.cs +++ b/VocaluxeLib/Menu/CButton.cs @@ -24,7 +24,8 @@ namespace VocaluxeLib.Menu [XmlType("Button")] public struct SThemeButton { - [XmlAttribute(AttributeName = "Name")] public string Name; + [XmlAttribute(AttributeName = "Name")] + public string Name; public string Skin; public string SkinSelected; @@ -40,7 +41,7 @@ namespace VocaluxeLib.Menu public sealed class CButton : CMenuElementBase, IMenuElement, IThemeable { private SThemeButton _Theme; - private readonly int _PartyModeID; + private readonly int _PartyModeId; public CTextureRef Texture; public CTextureRef SelTexture; @@ -67,7 +68,9 @@ namespace VocaluxeLib.Menu { Text.EditMode = value; if (_SelText != null) + { _SelText.EditMode = value; + } } } @@ -88,7 +91,9 @@ namespace VocaluxeLib.Menu { _Selectable = value; if (!_Selectable) + { Selected = false; + } } } @@ -99,22 +104,22 @@ namespace VocaluxeLib.Menu public bool ThemeLoaded { get; private set; } - public CButton(int partyModeID) + public CButton(int partyModeId) { - _PartyModeID = partyModeID; - Text = new CText(_PartyModeID); - _SelText = new CText(_PartyModeID); + _PartyModeId = partyModeId; + Text = new CText(_PartyModeId); + _SelText = new CText(_PartyModeId); Selected = false; EditMode = false; } - public CButton(SThemeButton theme, int partyModeID, bool buttonText = false) + public CButton(SThemeButton theme, int partyModeId, bool buttonText = false) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = theme; - Text = new CText(_Theme.Text, _PartyModeID, buttonText); - _SelText = _Theme.SelText.HasValue ? new CText(_Theme.SelText.Value, _PartyModeID, buttonText) : null; + Text = new CText(_Theme.Text, _PartyModeId, buttonText); + _SelText = _Theme.SelText.HasValue ? new CText(_Theme.SelText.Value, _PartyModeId, buttonText) : null; Selected = false; EditMode = false; @@ -124,12 +129,12 @@ namespace VocaluxeLib.Menu public CButton(CButton button) { - _PartyModeID = button._PartyModeID; + _PartyModeId = button._PartyModeId; _Theme = new SThemeButton - { - Skin = button._Theme.Skin, - SkinSelected = button._Theme.SkinSelected - }; + { + Skin = button._Theme.Skin, + SkinSelected = button._Theme.SkinSelected + }; MaxRect = button.MaxRect; Color = button.Color; @@ -156,21 +161,27 @@ namespace VocaluxeLib.Menu { _Theme.Text = (SThemeText)Text.GetTheme(); if (_SelText == null) + { _Theme.SelText = null; + } else + { _Theme.SelText = (SThemeText)_SelText.GetTheme(); + } } public void Draw() { if (!Visible && CBase.Settings.GetProgramState() != EProgramState.EditTheme) + { return; + } CTextureRef texture; if (!Selected && !Pressed || !_Selectable) { - texture = Texture ?? CBase.Themes.GetSkinTexture(_Theme.Skin, _PartyModeID); + texture = Texture ?? CBase.Themes.GetSkinTexture(_Theme.Skin, _PartyModeId); CBase.Drawing.DrawTexture(texture, Rect, Color); @@ -180,11 +191,13 @@ namespace VocaluxeLib.Menu Text.DrawRelative(Rect.X, Rect.Y, _ReflectionHeight, _ReflectionSpace, Rect.H); } else + { Text.DrawRelative(Rect.X, Rect.Y); + } } else if (_SelText == null) { - texture = SelTexture ?? CBase.Themes.GetSkinTexture(_Theme.SkinSelected, _PartyModeID); + texture = SelTexture ?? CBase.Themes.GetSkinTexture(_Theme.SkinSelected, _PartyModeId); CBase.Drawing.DrawTexture(texture, Rect, SelColor); @@ -194,11 +207,13 @@ namespace VocaluxeLib.Menu Text.DrawRelative(Rect.X, Rect.Y, _ReflectionHeight, _ReflectionSpace, Rect.H); } else + { Text.DrawRelative(Rect.X, Rect.Y); + } } else { - texture = SelTexture ?? CBase.Themes.GetSkinTexture(_Theme.SkinSelected, _PartyModeID); + texture = SelTexture ?? CBase.Themes.GetSkinTexture(_Theme.SkinSelected, _PartyModeId); CBase.Drawing.DrawTexture(texture, Rect, SelColor); @@ -208,33 +223,41 @@ namespace VocaluxeLib.Menu _SelText.DrawRelative(Rect.X, Rect.Y, _ReflectionHeight, _ReflectionSpace, Rect.H); } else + { _SelText.DrawRelative(Rect.X, Rect.Y); + } } } public void UnloadSkin() { if (!ThemeLoaded) + { return; + } + Text.UnloadSkin(); } public void LoadSkin() { if (!ThemeLoaded) + { return; - Text = new CText(_Theme.Text, _PartyModeID); + } + + Text = new CText(_Theme.Text, _PartyModeId); Text.LoadSkin(); Text.Selected = Selected; if (_Theme.SelText.HasValue) { - _SelText = new CText(_Theme.SelText.Value, _PartyModeID); + _SelText = new CText(_Theme.SelText.Value, _PartyModeId); _SelText.LoadSkin(); } - _Theme.Color.Get(_PartyModeID, out Color); - _Theme.SelColor.Get(_PartyModeID, out SelColor); + _Theme.Color.Get(_PartyModeId, out Color); + _Theme.SelColor.Get(_PartyModeId, out SelColor); MaxRect = _Theme.Rect; @@ -255,7 +278,9 @@ namespace VocaluxeLib.Menu } if (_Theme.Rect.Z < Text.Z) + { Text.Z = _Theme.Rect.Z; + } } public void ReloadSkin() @@ -284,11 +309,15 @@ namespace VocaluxeLib.Menu { W += stepW; if (W <= 0) + { W = 1; + } H += stepH; if (H <= 0) + { H = 1; + } _Theme.Rect.W = Rect.W; _Theme.Rect.H = Rect.H; diff --git a/VocaluxeLib/Menu/CEqualizer.cs b/VocaluxeLib/Menu/CEqualizer.cs index cb4f6afe..9eafbe33 100644 --- a/VocaluxeLib/Menu/CEqualizer.cs +++ b/VocaluxeLib/Menu/CEqualizer.cs @@ -28,7 +28,8 @@ namespace VocaluxeLib.Menu [XmlType("Equalizer")] public struct SThemeEqualizer { - [XmlAttribute(AttributeName = "Name")] public string Name; + [XmlAttribute(AttributeName = "Name")] + public string Name; public string Skin; @@ -46,7 +47,7 @@ namespace VocaluxeLib.Menu public class CEqualizer : CMenuElementBase, IMenuElement, IThemeable { - private readonly int _PartyModeID; + private readonly int _PartyModeId; private SThemeEqualizer _Theme; public SColorF Color; @@ -73,9 +74,9 @@ namespace VocaluxeLib.Menu get { return false; } } - public CEqualizer(int partyModeID) + public CEqualizer(int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = new SThemeEqualizer(); ThemeLoaded = false; @@ -87,9 +88,9 @@ namespace VocaluxeLib.Menu ReflectionHeight = 0f; } - public CEqualizer(SThemeEqualizer theme, int partyModeID) + public CEqualizer(SThemeEqualizer theme, int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = theme; ThemeLoaded = true; @@ -98,23 +99,35 @@ namespace VocaluxeLib.Menu public void Update(float[] weights, float volume) { if (weights == null || weights.Length == 0 || _Bars == null) - return; - if (volume < 0.001) { - for (int i = 0; i < _Bars.Length; i++) - _Bars[i] = 0f; return; } + + if (volume < 0.001) + { + for (var i = 0; i < _Bars.Length; i++) + { + _Bars[i] = 0f; + } + + return; + } + if (volume > _MaxVolume) + { _MaxVolume = volume; + } + _MaxBar = 0; - float maxVal = -99f; - for (int i = 0; i < _Bars.Length; i++) + var maxVal = -99f; + for (var i = 0; i < _Bars.Length; i++) { if (i < weights.Length) { if (_Theme.DrawNegative == EOffOn.TR_CONFIG_OFF && weights[i] < 0) + { _Bars[i] = 0f; + } else { _Bars[i] = weights[i] * volume / _MaxVolume; @@ -126,17 +139,24 @@ namespace VocaluxeLib.Menu } } else + { _Bars[i] = 0f; + } } } public void Reset() { if (_Bars == null || _Bars.Length == 0) + { return; + } - for (int i = 0; i < _Bars.Length; i++) + for (var i = 0; i < _Bars.Length; i++) + { _Bars[i] = 0f; + } + _MaxBar = 0; _MaxVolume = 0f; } @@ -144,32 +164,38 @@ namespace VocaluxeLib.Menu public void Draw() { if (_Bars == null || _Theme.Style != EEqualizerStyle.Columns) - return; - - float dx = Rect.W / _Bars.Length; - float scaleVal = (_Bars[_MaxBar] < 0.00001f) ? 0f : 1 / _Bars[_MaxBar]; - - for (int i = 0; i < _Bars.Length; i++) { - float value = _Bars[i] * scaleVal; + return; + } + + var dx = Rect.W / _Bars.Length; + var scaleVal = _Bars[_MaxBar] < 0.00001f ? 0f : 1 / _Bars[_MaxBar]; + + for (var i = 0; i < _Bars.Length; i++) + { + var value = _Bars[i] * scaleVal; var bar = new SRectF(Rect.X + dx * i, Rect.Y + Rect.H - value * Rect.H, dx - Space, value * Rect.H, Rect.Z); - SColorF color = Color; + var color = Color; if (i == _MaxBar) + { color = MaxColor; + } CBase.Drawing.DrawRect(color, bar); if (Reflection) + { CBase.Drawing.DrawRectReflection(color, bar, ReflectionSpace, ReflectionHeight); + } } } - public void UnloadSkin() {} + public void UnloadSkin() { } public void LoadSkin() { - _Theme.Color.Get(_PartyModeID, out Color); - _Theme.MaxColor.Get(_PartyModeID, out MaxColor); + _Theme.Color.Get(_PartyModeId, out Color); + _Theme.MaxColor.Get(_PartyModeId, out MaxColor); MaxRect = _Theme.Rect; Space = _Theme.Space; @@ -182,8 +208,10 @@ namespace VocaluxeLib.Menu } _Bars = new float[_Theme.NumBars]; - for (int i = 0; i < _Bars.Length; i++) + for (var i = 0; i < _Bars.Length; i++) + { _Bars[i] = 0f; + } } public void ReloadSkin() @@ -211,13 +239,17 @@ namespace VocaluxeLib.Menu { W += stepW; if (W <= 0) + { W = 1; + } _Theme.Rect.W = Rect.W; H += stepH; if (H <= 0) + { H = 1; + } _Theme.Rect.H = Rect.H; } diff --git a/VocaluxeLib/Menu/CLyric.cs b/VocaluxeLib/Menu/CLyric.cs index 7e3e1a56..a2eaa9e8 100644 --- a/VocaluxeLib/Menu/CLyric.cs +++ b/VocaluxeLib/Menu/CLyric.cs @@ -15,7 +15,6 @@ // along with Vocaluxe. If not, see . #endregion -using System; using System.Xml.Serialization; using VocaluxeLib.Songs; @@ -24,7 +23,8 @@ namespace VocaluxeLib.Menu [XmlType("Lyric")] public struct SThemeLyrics { - [XmlAttribute(AttributeName = "Name")] public string Name; + [XmlAttribute(AttributeName = "Name")] + public string Name; public SRectF Rect; @@ -34,7 +34,7 @@ namespace VocaluxeLib.Menu public class CLyric : CMenuElementBase, IMenuElement, IThemeable { - private readonly int _PartyModeID; + private readonly int _PartyModeId; private SThemeLyrics _Theme; /// @@ -76,27 +76,27 @@ namespace VocaluxeLib.Menu public ELyricStyle LyricStyle { get; set; } - public CLyric(int partyModeID) + public CLyric(int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = new SThemeLyrics(); ThemeLoaded = false; _Color = new SColorF(); _ColorProcessed = new SColorF(); _Line = new CSongLine(); - _Text = new CText(_PartyModeID); + _Text = new CText(_PartyModeId); LyricStyle = ELyricStyle.TR_CONFIG_LYRICSTYLE_FILL; } - public CLyric(SThemeLyrics theme, int partyModeID) + public CLyric(SThemeLyrics theme, int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = theme; _Line = new CSongLine(); - _Text = new CText(_PartyModeID); + _Text = new CText(_PartyModeId); _Width = 1f; LyricStyle = ELyricStyle.TR_CONFIG_LYRICSTYLE_FILL; @@ -108,7 +108,7 @@ namespace VocaluxeLib.Menu { _Line = line; _Width = 0f; - foreach (CSongNote note in line.Notes) + foreach (var note in line.Notes) { _SetText(note); _Width += _Text.Rect.W; @@ -117,21 +117,20 @@ namespace VocaluxeLib.Menu private void _SetText(CSongNote note) { - _Text.Text = note.Text; - - if (note.Type == ENoteType.Freestyle) - { - _Text.Font.Style = EStyle.Italic; - } - else if (note.Type == ENoteType.Rap || note.Type == ENoteType.RapGolden) - { - _Text.Font.Style = EStyle.BoldItalic; - } - else - { - _Text.Font.Style = EStyle.Bold; - } + _Text.Text = note.Text; + if (note.Type == ENoteType.Freestyle) + { + _Text.Font.Style = EStyle.Italic; + } + else if (note.Type == ENoteType.Rap || note.Type == ENoteType.RapGolden) + { + _Text.Font.Style = EStyle.BoldItalic; + } + else + { + _Text.Font.Style = EStyle.Bold; + } } public void Clear() @@ -175,9 +174,9 @@ namespace VocaluxeLib.Menu private void _DrawSlide() { - float x = X - _Width / 2; + var x = X - _Width / 2; - foreach (CSongNote note in _Line.Notes) + foreach (var note in _Line.Notes) { _Text.X = x; _SetText(note); @@ -188,12 +187,14 @@ namespace VocaluxeLib.Menu { _Text.Color = _ColorProcessed; - int diff = note.Duration; + var diff = note.Duration; if (diff <= 0) + { _Text.Draw(0f, 1f); + } else { - float p = (_CurrentBeat - note.StartBeat) / diff; + var p = (_CurrentBeat - note.StartBeat) / diff; _Text.Draw(0f, p); _Text.Color = _Color; _Text.Draw(p, 1f); @@ -217,9 +218,9 @@ namespace VocaluxeLib.Menu private void _DrawFill() { - float x = X - _Width / 2; // most left position + var x = X - _Width / 2; // most left position - foreach (CSongNote note in _Line.Notes) + foreach (var note in _Line.Notes) { _Text.X = x; _SetText(note); @@ -244,17 +245,21 @@ namespace VocaluxeLib.Menu { float diff = endBeat - zoomNote.StartBeat; if (diff <= 0f) + { diff = 1f; + } - float p = 1f - (_CurrentBeat - zoomNote.StartBeat) / diff; + var p = 1f - (_CurrentBeat - zoomNote.StartBeat) / diff; if (p < 0) + { p = 0; + } - float ty = _Text.Y; - float th = _Text.Font.Height; - float tz = _Text.Z; + var ty = _Text.Y; + var th = _Text.Font.Height; + var tz = _Text.Z; - SRectF normalRect = _Text.Rect; + var normalRect = _Text.Rect; _Text.Font.Height *= 1f + p * 0.4f; _Text.X -= (_Text.Rect.W - normalRect.W) / 2f; _Text.Y -= (_Text.Rect.H - normalRect.H) / 2f; @@ -273,17 +278,21 @@ namespace VocaluxeLib.Menu { _Text.Color = _ColorProcessed; - int diff = jumpNote.Duration; + var diff = jumpNote.Duration; if (diff <= 0) + { diff = 1; + } - float p = 1f - (_CurrentBeat - jumpNote.StartBeat) / diff; + var p = 1f - (_CurrentBeat - jumpNote.StartBeat) / diff; if (p < 0.001) + { _Text.Draw(); + } else { - float y = _Text.Y; + var y = _Text.Y; _Text.Y -= _Text.Font.Height * 0.1f * p; _Text.Draw(); _Text.Y = y; @@ -292,24 +301,26 @@ namespace VocaluxeLib.Menu private void _DrawZoomOrJump() { - float x = X - _Width / 2; // most left position + var x = X - _Width / 2; // most left position - int lastNote = _Line.FindPreviousNote((int)_CurrentBeat); + var lastNote = _Line.FindPreviousNote((int)_CurrentBeat); CSongNote highlightNote = null; - int hEndBeat = 0; + var hEndBeat = 0; float hX = 0; - for (int note = 0; note < _Line.Notes.Length; note++) + for (var note = 0; note < _Line.Notes.Length; note++) { _Text.X = x; - CSongNote curNote = _Line.Notes[note]; + var curNote = _Line.Notes[note]; _SetText(curNote); if (_CurrentBeat >= curNote.StartBeat) { - int curEndBeat = curNote.EndBeat; + var curEndBeat = curNote.EndBeat; if (note < _Line.Notes.Length - 1) + { curEndBeat = _Line.Notes[note + 1].StartBeat - 1; + } if (_CurrentBeat <= curEndBeat) { @@ -336,25 +347,32 @@ namespace VocaluxeLib.Menu // Draw the highlighted note after all others because we want it to be above those! (transparency won't work well otherwhise) if (highlightNote == null) + { return; + } + _SetText(highlightNote); _Text.X = hX; if (LyricStyle == ELyricStyle.TR_CONFIG_LYRICSTYLE_JUMP) + { _DrawJumpingNode(highlightNote); + } else + { _DrawZoomedNote(highlightNote, hEndBeat); + } } #endregion draw - public void UnloadSkin() {} + public void UnloadSkin() { } public void LoadSkin() { - _Theme.Color.Get(_PartyModeID, out _Color); - _Theme.ProcessedColor.Get(_PartyModeID, out _ColorProcessed); + _Theme.Color.Get(_PartyModeId, out _Color); + _Theme.ProcessedColor.Get(_PartyModeId, out _ColorProcessed); MaxRect = _Theme.Rect; - _Text = new CText(X, Y, Z, H, W, EAlignment.Left, EStyle.Bold, "Normal", _Color, String.Empty); + _Text = new CText(X, Y, Z, H, W, EAlignment.Left, EStyle.Bold, "Normal", _Color, string.Empty); } public void ReloadSkin() @@ -381,15 +399,19 @@ namespace VocaluxeLib.Menu { W += stepW; if (W <= 0) + { W = 1; + } H += stepH; if (H <= 0) + { H = 1; + } _Theme.Rect.W = Rect.W; _Theme.Rect.H = Rect.H; } #endregion ThemeEdit } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Menu/CMenu.cs b/VocaluxeLib/Menu/CMenu.cs index 78f4d2e3..6f570231 100644 --- a/VocaluxeLib/Menu/CMenu.cs +++ b/VocaluxeLib/Menu/CMenu.cs @@ -39,26 +39,41 @@ namespace VocaluxeLib.Menu public struct SThemeScreen { public SScreenInformation Informations; - [XmlArray("Backgrounds")] public List Backgrounds; - [XmlArray("Statics")] public List Statics; - [XmlArray("Texts")] public List Texts; - [XmlArray("Buttons")] public List Buttons; - [XmlArray("SongMenus")] public List SongMenus; - [XmlArray("Lyrics")] public List Lyrics; - [XmlArray("SelectSlides")] public List SelectSlides; - [XmlArray("SingNotes")] public List SingNotes; - [XmlArray("NameSelections")] public List NameSelections; - [XmlArray("Equalizers")] public List Equalizers; - [XmlArray("Playlists")] public List Playlists; - [XmlArray("ParticleEffects")] public List ParticleEffects; - [XmlArray("ScreenSettings")] public List ScreenSettings; - [XmlArray("ProgressBars")] public List ProgressBars; - [XmlArray("RatingPopups")] public List RatingPopups; + [XmlArray("Backgrounds")] + public List Backgrounds; + [XmlArray("Statics")] + public List Statics; + [XmlArray("Texts")] + public List Texts; + [XmlArray("Buttons")] + public List Buttons; + [XmlArray("SongMenus")] + public List SongMenus; + [XmlArray("Lyrics")] + public List Lyrics; + [XmlArray("SelectSlides")] + public List SelectSlides; + [XmlArray("SingNotes")] + public List SingNotes; + [XmlArray("NameSelections")] + public List NameSelections; + [XmlArray("Equalizers")] + public List Equalizers; + [XmlArray("Playlists")] + public List Playlists; + [XmlArray("ParticleEffects")] + public List ParticleEffects; + [XmlArray("ScreenSettings")] + public List ScreenSettings; + [XmlArray("ProgressBars")] + public List ProgressBars; + [XmlArray("RatingPopups")] + public List RatingPopups; } struct SZSort { - public int ID; + public int Id; public float Z; } @@ -67,7 +82,7 @@ namespace VocaluxeLib.Menu public string ThemePath { get; private set; } protected abstract int _ScreenVersion { get; } - public int PartyModeID { get; protected set; } + public int PartyModeId { get; protected set; } public string ThemeName { get; private set; } public SThemeScreen Theme; @@ -93,7 +108,7 @@ namespace VocaluxeLib.Menu protected CMenu() { - PartyModeID = -1; + PartyModeId = -1; CBase.Config.AddSongMenuListener(_OnSongMenuChanged); } @@ -107,7 +122,9 @@ namespace VocaluxeLib.Menu base.Init(); ThemeName = GetType().Name; if (ThemeName[0] == 'C' && Char.IsUpper(ThemeName[1])) + { ThemeName = ThemeName.Remove(0, 1); + } _ThemeBackgrounds = null; _ThemeStatics = null; @@ -128,10 +145,10 @@ namespace VocaluxeLib.Menu protected virtual void _OnSongMenuChanged() { - for (int i = 0; i < _SongMenus.Count; i++) + for (var i = 0; i < _SongMenus.Count; i++) { - SThemeSongMenu theme = (SThemeSongMenu)_SongMenus[i].GetTheme(); - _SongMenus[i] = CSongMenuFactory.CreateSongMenu(theme, PartyModeID); + var theme = (SThemeSongMenu)_SongMenus[i].GetTheme(); + _SongMenus[i] = CSongMenuFactory.CreateSongMenu(theme, PartyModeId); _SongMenus[i].LoadSkin(); } } @@ -145,24 +162,26 @@ namespace VocaluxeLib.Menu private delegate void AddElementHandler(T element, String key); - private class CLoadThemeErrorHandler : CXmlDeserializer.CXmlDefaultErrorHandler { private static readonly string[] _AllowedMissing = new string[] - { - "Backgrounds", "Statics", "Texts", "Buttons", "SongMenus", "Lyrics", "SelectSlides", "SingNotes", - "NameSelections", "Equalizers", "Playlists", "ParticleEffects", "ScreenSettings", "ProgressBars", - "RatingPopups" - }; + { + "Backgrounds", "Statics", "Texts", "Buttons", "SongMenus", "Lyrics", "SelectSlides", "SingNotes", + "NameSelections", "Equalizers", "Playlists", "ParticleEffects", "ScreenSettings", "ProgressBars", + "RatingPopups" + }; public override void HandleError(CXmlException e) { - CXmlMissingElementException missingEx = e as CXmlMissingElementException; + var missingEx = e as CXmlMissingElementException; if (missingEx != null) { if (_AllowedMissing.Contains(missingEx.Field.Name)) + { return; + } } + base.HandleError(e); } } @@ -171,71 +190,108 @@ namespace VocaluxeLib.Menu { ThemePath = xmlPath; - string file = Path.Combine(xmlPath, ThemeName + ".xml"); + var file = Path.Combine(xmlPath, ThemeName + ".xml"); try { - CXmlDeserializer deserializer = new CXmlDeserializer(new CLoadThemeErrorHandler()); + var deserializer = new CXmlDeserializer(new CLoadThemeErrorHandler()); Theme = deserializer.Deserialize(file); - foreach (SThemeBackground bg in Theme.Backgrounds) - _AddBackground(new CBackground(bg, PartyModeID), bg.Name); + foreach (var bg in Theme.Backgrounds) + { + _AddBackground(new CBackground(bg, PartyModeId), bg.Name); + } - foreach (SThemeButton bt in Theme.Buttons) - _AddButton(new CButton(bt, PartyModeID), bt.Name); + foreach (var bt in Theme.Buttons) + { + _AddButton(new CButton(bt, PartyModeId), bt.Name); + } - foreach (SThemeEqualizer eq in Theme.Equalizers) - _AddEqualizer(new CEqualizer(eq, PartyModeID), eq.Name); + foreach (var eq in Theme.Equalizers) + { + _AddEqualizer(new CEqualizer(eq, PartyModeId), eq.Name); + } - foreach (SThemeLyrics ly in Theme.Lyrics) - _AddLyric(new CLyric(ly, PartyModeID), ly.Name); + foreach (var ly in Theme.Lyrics) + { + _AddLyric(new CLyric(ly, PartyModeId), ly.Name); + } - foreach (SThemeNameSelection ns in Theme.NameSelections) - _AddNameSelection(new CNameSelection(ns, PartyModeID), ns.Name); + foreach (var ns in Theme.NameSelections) + { + _AddNameSelection(new CNameSelection(ns, PartyModeId), ns.Name); + } - foreach (SThemeParticleEffect pe in Theme.ParticleEffects) - _AddParticleEffect(new CParticleEffect(pe, PartyModeID), pe.Name); + foreach (var pe in Theme.ParticleEffects) + { + _AddParticleEffect(new CParticleEffect(pe, PartyModeId), pe.Name); + } - foreach (SThemePlaylist pl in Theme.Playlists) - _AddPlaylist(new CPlaylist(pl, PartyModeID), pl.Name); + foreach (var pl in Theme.Playlists) + { + _AddPlaylist(new CPlaylist(pl, PartyModeId), pl.Name); + } - foreach (SThemeProgressBar pb in Theme.ProgressBars) - _AddProgressBar(new CProgressBar(pb, PartyModeID), pb.Name); + foreach (var pb in Theme.ProgressBars) + { + _AddProgressBar(new CProgressBar(pb, PartyModeId), pb.Name); + } - foreach (SThemeRatingPopup rp in Theme.RatingPopups) - _AddRatingPopup(new CRatingPopup(rp, PartyModeID), rp.Name); + foreach (var rp in Theme.RatingPopups) + { + _AddRatingPopup(new CRatingPopup(rp, PartyModeId), rp.Name); + } - foreach (SThemeScreenSetting ss in Theme.ScreenSettings) - _AddScreenSetting(new CScreenSetting(ss, PartyModeID), ss.Name); + foreach (var ss in Theme.ScreenSettings) + { + _AddScreenSetting(new CScreenSetting(ss, PartyModeId), ss.Name); + } - foreach (SThemeSelectSlide sl in Theme.SelectSlides) - _AddSelectSlide(new CSelectSlide(sl, PartyModeID), sl.Name); + foreach (var sl in Theme.SelectSlides) + { + _AddSelectSlide(new CSelectSlide(sl, PartyModeId), sl.Name); + } - foreach (SThemeSingBar sb in Theme.SingNotes) - _AddSingNote(new CSingNotes(sb, PartyModeID), sb.Name); + foreach (var sb in Theme.SingNotes) + { + _AddSingNote(new CSingNotes(sb, PartyModeId), sb.Name); + } - foreach (SThemeSongMenu sm in Theme.SongMenus) - _AddSongMenu(CSongMenuFactory.CreateSongMenu(sm, PartyModeID), sm.Name); + foreach (var sm in Theme.SongMenus) + { + _AddSongMenu(CSongMenuFactory.CreateSongMenu(sm, PartyModeId), sm.Name); + } - foreach (SThemeStatic st in Theme.Statics) - _AddStatic(new CStatic(st, PartyModeID), st.Name); + foreach (var st in Theme.Statics) + { + _AddStatic(new CStatic(st, PartyModeId), st.Name); + } - foreach (SThemeText te in Theme.Texts) - _AddText(new CText(te, PartyModeID), te.Name); + foreach (var te in Theme.Texts) + { + _AddText(new CText(te, PartyModeId), te.Name); + } if (_ScreenVersion != Theme.Informations.ScreenVersion) { - string msg = "Can't load screen file of screen \"" + ThemeName + "\", "; + var msg = "Can't load screen file of screen \"" + ThemeName + "\", "; if (Theme.Informations.ScreenVersion < _ScreenVersion) + { msg += "the file ist outdated! "; + } else + { msg += "the file is for newer program versions! "; + } msg += "Current screen version is " + _ScreenVersion; CLog.Error(msg); } - foreach (IThemeable el in _Elements.Select(_GetElement).OfType()) + + foreach (var el in _Elements.Select(_GetElement).OfType()) + { el.LoadSkin(); + } } catch (Exception e) { @@ -251,19 +307,24 @@ namespace VocaluxeLib.Menu private static void _AddThemeablesToList(ICollection themeList, IEnumerable objects) where T : IThemeable { themeList.Clear(); - foreach (T el in objects.Where(el => el.ThemeLoaded)) + foreach (var el in objects.Where(el => el.ThemeLoaded)) + { themeList.Add((TT)el.GetTheme()); + } } public virtual void SaveTheme() { if (string.IsNullOrEmpty(ThemePath)) + { return; + } + _ReadThemeSubElements(); try { - CXmlSerializer serializer = new CXmlSerializer(); + var serializer = new CXmlSerializer(); serializer.Serialize(Path.Combine(ThemePath, ThemeName + ".xml"), Theme); } catch (Exception e) @@ -294,20 +355,26 @@ namespace VocaluxeLib.Menu public virtual void ReloadSkin() { - foreach (IThemeable el in _Elements.Select(_GetElement).OfType()) + foreach (var el in _Elements.Select(_GetElement).OfType()) + { el.ReloadSkin(); + } } public virtual void UnloadSkin() { - foreach (IThemeable el in _Elements.Select(_GetElement).OfType()) + foreach (var el in _Elements.Select(_GetElement).OfType()) + { el.UnloadSkin(); + } } public virtual void ReloadTheme(string xmlPath) { if (ThemePath == "") + { return; + } _ReadThemeSubElements(); UnloadSkin(); @@ -321,7 +388,7 @@ namespace VocaluxeLib.Menu // ReSharper disable MemberCanBeProtected.Global public CButton GetNewButton() { - return new CButton(PartyModeID); + return new CButton(PartyModeId); } public static CButton GetNewButton(CButton button) @@ -331,7 +398,7 @@ namespace VocaluxeLib.Menu public CText GetNewText() { - return new CText(PartyModeID); + return new CText(PartyModeId); } public static CText GetNewText(CText text) @@ -346,12 +413,12 @@ namespace VocaluxeLib.Menu public CBackground GetNewBackground() { - return new CBackground(PartyModeID); + return new CBackground(PartyModeId); } public CStatic GetNewStatic() { - return new CStatic(PartyModeID); + return new CStatic(PartyModeId); } public static CStatic GetNewStatic(CStatic oldStatic) @@ -361,12 +428,12 @@ namespace VocaluxeLib.Menu public CStatic GetNewStatic(CTextureRef texture, SColorF color, SRectF rect) { - return new CStatic(PartyModeID, texture, color, rect); + return new CStatic(PartyModeId, texture, color, rect); } public CSelectSlide GetNewSelectSlide() { - return new CSelectSlide(PartyModeID); + return new CSelectSlide(PartyModeId); } public static CSelectSlide GetNewSelectSlide(CSelectSlide slide) @@ -376,37 +443,37 @@ namespace VocaluxeLib.Menu public CLyric GetNewLyric() { - return new CLyric(PartyModeID); + return new CLyric(PartyModeId); } public CSingNotes GetNewSingNotes() { - return new CSingNotes(PartyModeID); + return new CSingNotes(PartyModeId); } public CNameSelection GetNewNameSelection() { - return new CNameSelection(PartyModeID); + return new CNameSelection(PartyModeId); } public CEqualizer GetNewEqualizer() { - return new CEqualizer(PartyModeID); + return new CEqualizer(PartyModeId); } public CPlaylist GetNewPlaylist() { - return new CPlaylist(PartyModeID); + return new CPlaylist(PartyModeId); } public CParticleEffect GetNewParticleEffect(int maxNumber, SColorF color, SRectF area, CTextureRef texture, float size, EParticleType type) { - return new CParticleEffect(PartyModeID, maxNumber, color, area, texture, size, type); + return new CParticleEffect(PartyModeId, maxNumber, color, area, texture, size, type); } public CProgressBar GetNewProgressBar() { - return new CProgressBar(PartyModeID); + return new CProgressBar(PartyModeId); } public CProgressBar GetNewProgressBar(CProgressBar pb) @@ -416,7 +483,7 @@ namespace VocaluxeLib.Menu public CRatingPopup GetNewRatingPopup() { - return new CRatingPopup(PartyModeID); + return new CRatingPopup(PartyModeId); } public static CRatingPopup GetNewRatingPopup(CRatingPopup rp) @@ -442,12 +509,13 @@ namespace VocaluxeLib.Menu return true; } } + return base.HandleInputThemeEditor(keyEvent); } public abstract bool UpdateGame(); - public virtual void ApplyVolume() {} + public virtual void ApplyVolume() { } public virtual void OnShow() { @@ -478,14 +546,18 @@ namespace VocaluxeLib.Menu protected void _ResumeBG() { - foreach (CBackground bg in _Backgrounds) + foreach (var bg in _Backgrounds) + { bg.Resume(); + } } protected void _PauseBG() { - foreach (CBackground bg in _Backgrounds) + foreach (var bg in _Backgrounds) + { bg.Pause(); + } } #region Theme Handling diff --git a/VocaluxeLib/Menu/CMenuParty.cs b/VocaluxeLib/Menu/CMenuParty.cs index 1e65a45b..e7974e39 100644 --- a/VocaluxeLib/Menu/CMenuParty.cs +++ b/VocaluxeLib/Menu/CMenuParty.cs @@ -26,7 +26,7 @@ namespace VocaluxeLib.Menu public void AssignPartyMode(IPartyMode partyMode) { _PartyMode = partyMode; - PartyModeID = partyMode.ID; + PartyModeId = partyMode.Id; } } } \ No newline at end of file diff --git a/VocaluxeLib/Menu/CMenuPartyNameSelection.cs b/VocaluxeLib/Menu/CMenuPartyNameSelection.cs index faa0e484..9b0f7642 100644 --- a/VocaluxeLib/Menu/CMenuPartyNameSelection.cs +++ b/VocaluxeLib/Menu/CMenuPartyNameSelection.cs @@ -18,7 +18,6 @@ using System; using System.Collections.Generic; using System.Windows.Forms; -using VocaluxeLib.Draw; using VocaluxeLib.Profile; namespace VocaluxeLib.Menu @@ -29,11 +28,14 @@ namespace VocaluxeLib.Menu { get { - for (int team = 0; team < _NumTeams; team++) + for (var team = 0; team < _NumTeams; team++) { if (_TeamList[team].Count < _NumPlayerTeams[team]) + { return false; + } } + return true; } } @@ -54,7 +56,7 @@ namespace VocaluxeLib.Menu private bool _SelectingKeyboardActive; private bool _SelectingFast; private int _SelectingFastPlayerNr; - private Guid _SelectedProfileID = Guid.Empty; + private Guid _SelectedProfileId = Guid.Empty; private CStatic _ChooseAvatarStatic; private int _OldMouseX; @@ -76,9 +78,9 @@ namespace VocaluxeLib.Menu public override void Init() { base.Init(); - _ThemeButtons = new string[] {_ButtonBack, _ButtonNext, _ButtonRandom, _ButtonIncreaseTeams, _ButtonDecreaseTeams, _ButtonIncreasePlayer, _ButtonDecreasePlayer}; - _ThemeSelectSlides = new string[] {_SelectSlideTeams, _SelectSlidePlayer}; - _ThemeNameSelections = new string[] {_NameSelection}; + _ThemeButtons = new string[] { _ButtonBack, _ButtonNext, _ButtonRandom, _ButtonIncreaseTeams, _ButtonDecreaseTeams, _ButtonIncreasePlayer, _ButtonDecreasePlayer }; + _ThemeSelectSlides = new string[] { _SelectSlideTeams, _SelectSlidePlayer }; + _ThemeNameSelections = new string[] { _NameSelection }; _ChooseAvatarStatic = GetNewStatic(); _ChooseAvatarStatic.Visible = false; @@ -89,7 +91,7 @@ namespace VocaluxeLib.Menu public void SetPartyModeData(int numPlayer) { - SetPartyModeData(1, numPlayer, new int[] {numPlayer}); + SetPartyModeData(1, numPlayer, new int[] { numPlayer }); _CurrentTeam = 0; } @@ -102,10 +104,14 @@ namespace VocaluxeLib.Menu _TeamList = new List[_NumTeams > 0 ? _NumTeams : 1]; if (_NumTeams != _NumPlayerTeams.Length) + { _NumPlayerTeams = new int[_NumTeams]; + } - for (int i = 0; i < _TeamList.Length; i++) + for (var i = 0; i < _TeamList.Length; i++) + { _TeamList[i] = new List(); + } _UpdateSlides(); _LoadProfiles(); @@ -118,10 +124,12 @@ namespace VocaluxeLib.Menu { _TeamList = teamProfiles; - for (int t = 0; t < _TeamList.Length; t++) + for (var t = 0; t < _TeamList.Length; t++) { - foreach (Guid id in _TeamList[t]) + foreach (var id in _TeamList[t]) + { _NameSelections[_NameSelection].UseProfile(id); + } } _UpdateSlides(); @@ -135,31 +143,41 @@ namespace VocaluxeLib.Menu { //Handle left/right/up/down _NameSelections[_NameSelection].HandleInput(keyEvent); - int numPressed = -1; - bool resetSelection = false; + var numPressed = -1; + var resetSelection = false; switch (keyEvent.Key) { case Keys.Enter: //Check, if a player is selected - if (_NameSelections[_NameSelection].SelectedID != Guid.Empty) + if (_NameSelections[_NameSelection].SelectedId != Guid.Empty) { - _SelectedProfileID = _NameSelections[_NameSelection].SelectedID; + _SelectedProfileId = _NameSelections[_NameSelection].SelectedId; - if (!CBase.Profiles.IsProfileIDValid(_SelectedProfileID)) + if (!CBase.Profiles.IsProfileIdValid(_SelectedProfileId)) + { return true; + } - _AddPlayer(_CurrentTeam, _SelectedProfileID); + _AddPlayer(_CurrentTeam, _SelectedProfileId); } + //Started selecting with 'P' if (_SelectingFast) { if (!_ChangePlayerNumDynamic && _TeamList[_CurrentTeam].Count == _NumPlayerTeams[_CurrentTeam]) + { resetSelection = true; + } else if (_TeamList[_CurrentTeam].Count == _PartyMode.MaxPlayersPerTeam) + { resetSelection = true; + } } else if (!_SelectingFast) + { resetSelection = true; + } + break; case Keys.Escape: @@ -212,6 +230,7 @@ namespace VocaluxeLib.Menu numPressed = 9; break; } + if (numPressed > 0 || resetSelection) { if (numPressed == _SelectingFastPlayerNr || resetSelection) @@ -226,6 +245,7 @@ namespace VocaluxeLib.Menu _SelectingFastPlayerNr = numPressed; _NameSelections[_NameSelection].FastSelection(true, numPressed); } + _SelectingFast = false; } } @@ -233,7 +253,7 @@ namespace VocaluxeLib.Menu { base.HandleInput(keyEvent); - int numPressed = 0; + var numPressed = 0; switch (keyEvent.Key) { @@ -244,50 +264,69 @@ namespace VocaluxeLib.Menu case Keys.Enter: if (_Buttons[_ButtonBack].Selected) + { Back(); + } if (_Buttons[_ButtonNext].Selected) + { Next(); + } if (_Buttons[_ButtonRandom].Selected) + { _SelectRandom(); + } if (_Buttons[_ButtonIncreaseTeams].Selected) + { IncreaseTeamNum(); + } if (_Buttons[_ButtonDecreaseTeams].Selected) + { DecreaseTeamNum(); + } if (_Buttons[_ButtonIncreasePlayer].Selected) + { IncreasePlayerNum(_CurrentTeam); + } if (_Buttons[_ButtonDecreasePlayer].Selected) + { DecreasePlayerNum(_CurrentTeam); + } break; case Keys.Delete: if (_SelectSlides[_SelectSlidePlayer].Selected && _SelectSlides[_SelectSlidePlayer].NumValues > 0) { - int index = _SelectSlides[_SelectSlidePlayer].Selection; + var index = _SelectSlides[_SelectSlidePlayer].Selection; _RemovePlayerByIndex(_CurrentTeam, index); _UpdatePlayerSlide(); } + break; case Keys.Left: case Keys.Right: if (_SelectSlides[_SelectSlideTeams].Selected) + { _OnChangeTeamSlide(); + } + break; case Keys.P: if (!_SelectingKeyboardActive) { - _SelectingFastPlayerNr = (_CurrentTeam + 1); + _SelectingFastPlayerNr = _CurrentTeam + 1; _SelectingFast = true; //_ResetPlayerSelections(); } + break; case Keys.D1: @@ -337,16 +376,26 @@ namespace VocaluxeLib.Menu case Keys.Subtract: if (_SelectSlides[_SelectSlideTeams].Selected) + { DecreaseTeamNum(); + } else if (_SelectSlides[_SelectSlidePlayer].Selected) + { DecreasePlayerNum(_CurrentTeam); + } + break; case Keys.Add: if (_SelectSlides[_SelectSlideTeams].Selected) + { IncreaseTeamNum(); + } else if (_SelectSlides[_SelectSlidePlayer].Selected) + { IncreasePlayerNum(_CurrentTeam); + } + break; } @@ -355,31 +404,42 @@ namespace VocaluxeLib.Menu if (_ChangeTeamNumDynamic && numPressed < _PartyMode.MaxTeams && numPressed > _SelectSlides[_SelectSlideTeams].NumValues) { while (numPressed < _PartyMode.MaxTeams) + { IncreaseTeamNum(); + } } + if (numPressed <= _SelectSlides[_SelectSlideTeams].NumValues) + { _SelectSlides[_SelectSlideTeams].SelectedTag = numPressed; + } } } + if (_SelectingFastPlayerNr > 0 && _SelectingFastPlayerNr <= _NumPlayerTeams[_CurrentTeam]) { _SelectingKeyboardActive = true; _NameSelections[_NameSelection].FastSelection(true, _SelectingFastPlayerNr); } + return true; } public override bool HandleMouse(SMouseEvent mouseEvent) { - bool stopSelectingFast = false; + var stopSelectingFast = false; if (_SelectingFast) + { _NameSelections[_NameSelection].HandleMouse(mouseEvent); + } else + { base.HandleMouse(mouseEvent); + } //Check if LeftButton is hold and Select-Mode inactive - if (mouseEvent.LBH && _SelectedProfileID == Guid.Empty && !_SelectingFast) + if (mouseEvent.LBH && _SelectedProfileId == Guid.Empty && !_SelectingFast) { //Save mouse-coords _OldMouseX = mouseEvent.X; @@ -388,11 +448,11 @@ namespace VocaluxeLib.Menu if (_NameSelections[_NameSelection].IsOverTile(mouseEvent)) { //Get player-number of tile - _SelectedProfileID = _NameSelections[_NameSelection].TilePlayerID(mouseEvent); - if (_SelectedProfileID != Guid.Empty) + _SelectedProfileId = _NameSelections[_NameSelection].TilePlayerId(mouseEvent); + if (_SelectedProfileId != Guid.Empty) { //Update of Drag/Drop-Texture - CStatic selectedPlayer = _NameSelections[_NameSelection].TilePlayerAvatar(mouseEvent); + var selectedPlayer = _NameSelections[_NameSelection].TilePlayerAvatar(mouseEvent); _ChooseAvatarStatic.Visible = true; _ChooseAvatarStatic.MaxRect = selectedPlayer.Rect; _ChooseAvatarStatic.Z = CBase.Settings.GetZNear(); @@ -401,8 +461,9 @@ namespace VocaluxeLib.Menu } } } + //Check if LeftButton is hold and Select-Mode active - if (mouseEvent.LBH && _SelectedProfileID != Guid.Empty && !_SelectingFast) + if (mouseEvent.LBH && _SelectedProfileId != Guid.Empty && !_SelectingFast) { //Update coords for Drag/Drop-Texture _ChooseAvatarStatic.X += mouseEvent.X - _OldMouseX; @@ -410,70 +471,97 @@ namespace VocaluxeLib.Menu _OldMouseX = mouseEvent.X; _OldMouseY = mouseEvent.Y; } - // LeftButton isn't hold anymore, but Select-Mode is still active -> "Drop" of Avatar - else if (_SelectedProfileID != Guid.Empty && !_SelectingFast) + // LeftButton isn't hold anymore, but Select-Mode is still active -> "Drop" of Avatar + else if (_SelectedProfileId != Guid.Empty && !_SelectingFast) { //Check if mouse is in drop-area if (CHelper.IsInBounds(_SelectSlides[_SelectSlidePlayer].Rect, mouseEvent)) { - if (!CBase.Profiles.IsProfileIDValid(_SelectedProfileID)) + if (!CBase.Profiles.IsProfileIdValid(_SelectedProfileId)) + { return true; + } - _AddPlayer(_CurrentTeam, _SelectedProfileID); + _AddPlayer(_CurrentTeam, _SelectedProfileId); } //Reset variables - _SelectedProfileID = Guid.Empty; + _SelectedProfileId = Guid.Empty; _ChooseAvatarStatic.Visible = false; } + if (mouseEvent.LB && _SelectingFast) { if (_NameSelections[_NameSelection].IsOverTile(mouseEvent)) { //Get player-number of tile - _SelectedProfileID = _NameSelections[_NameSelection].TilePlayerID(mouseEvent); - if (_SelectedProfileID != Guid.Empty) + _SelectedProfileId = _NameSelections[_NameSelection].TilePlayerId(mouseEvent); + if (_SelectedProfileId != Guid.Empty) { - if (!CBase.Profiles.IsProfileIDValid(_SelectedProfileID)) + if (!CBase.Profiles.IsProfileIdValid(_SelectedProfileId)) + { return true; + } - _AddPlayer(_CurrentTeam, _SelectedProfileID); + _AddPlayer(_CurrentTeam, _SelectedProfileId); if (!_ChangePlayerNumDynamic && _TeamList[_CurrentTeam].Count == _NumPlayerTeams[_CurrentTeam]) + { stopSelectingFast = true; + } else if (_TeamList[_CurrentTeam].Count == _PartyMode.MaxPlayersPerTeam) + { stopSelectingFast = true; + } } else + { stopSelectingFast = true; + } } } else if (mouseEvent.LB && _IsMouseOverCurSelection(mouseEvent)) { if (_Buttons[_ButtonBack].Selected) + { Back(); + } if (_Buttons[_ButtonNext].Selected) + { Next(); + } if (_Buttons[_ButtonRandom].Selected) + { _SelectRandom(); + } if (_Buttons[_ButtonIncreaseTeams].Selected) + { IncreaseTeamNum(); + } if (_Buttons[_ButtonDecreaseTeams].Selected) + { DecreaseTeamNum(); + } if (_Buttons[_ButtonIncreasePlayer].Selected) + { IncreasePlayerNum(_CurrentTeam); + } if (_Buttons[_ButtonDecreasePlayer].Selected) + { DecreasePlayerNum(_CurrentTeam); + } if (_SelectSlides[_SelectSlideTeams].Selected) + { _OnChangeTeamSlide(); + } //Update Tiles-List _NameSelections[_NameSelection].UpdateList(); @@ -481,45 +569,55 @@ namespace VocaluxeLib.Menu if (mouseEvent.LD && _NameSelections[_NameSelection].IsOverTile(mouseEvent) && !_SelectingFast) { - _SelectedProfileID = _NameSelections[_NameSelection].TilePlayerID(mouseEvent); - if (_SelectedProfileID != Guid.Empty) + _SelectedProfileId = _NameSelections[_NameSelection].TilePlayerId(mouseEvent); + if (_SelectedProfileId != Guid.Empty) { - if (!CBase.Profiles.IsProfileIDValid(_SelectedProfileID)) + if (!CBase.Profiles.IsProfileIdValid(_SelectedProfileId)) + { return true; + } - _AddPlayer(_CurrentTeam, _SelectedProfileID); + _AddPlayer(_CurrentTeam, _SelectedProfileId); } } if (mouseEvent.RB && _SelectingFast) + { stopSelectingFast = true; + } else if (mouseEvent.RB) { - bool exit = true; + var exit = true; if (_SelectSlides[_SelectSlidePlayer].Selected && _TeamList[_CurrentTeam].Count > _SelectSlides[_SelectSlidePlayer].Selection) { - int currentSelection = _SelectSlides[_SelectSlidePlayer].Selection; - Guid id = _TeamList[_CurrentTeam][currentSelection]; + var currentSelection = _SelectSlides[_SelectSlidePlayer].Selection; + var id = _TeamList[_CurrentTeam][currentSelection]; _RemovePlayer(_CurrentTeam, id); _UpdatePlayerSlide(); exit = false; } if (exit) + { Back(); + } } if (mouseEvent.MB && _SelectingFast) { if (!_ChangePlayerNumDynamic && _TeamList[_CurrentTeam].Count == _NumPlayerTeams[_CurrentTeam]) + { stopSelectingFast = true; + } else if (_TeamList[_CurrentTeam].Count == _PartyMode.MaxPlayersPerTeam) + { stopSelectingFast = true; + } } else if (mouseEvent.MB) { _SelectingFast = true; - _SelectingFastPlayerNr = (_CurrentTeam + 1); + _SelectingFastPlayerNr = _CurrentTeam + 1; _SelectingKeyboardActive = true; _NameSelections[_NameSelection].FastSelection(true, _SelectingFastPlayerNr); } @@ -529,7 +627,7 @@ namespace VocaluxeLib.Menu { if (CHelper.IsInBounds(_NameSelections[_NameSelection].Rect, mouseEvent)) { - int offset = _NameSelections[_NameSelection].Offset + mouseEvent.Wheel; + var offset = _NameSelections[_NameSelection].Offset + mouseEvent.Wheel; _NameSelections[_NameSelection].UpdateList(offset); } } @@ -541,6 +639,7 @@ namespace VocaluxeLib.Menu _SelectingKeyboardActive = false; _NameSelections[_NameSelection].FastSelection(false, -1); } + return true; } @@ -555,7 +654,9 @@ namespace VocaluxeLib.Menu public override bool UpdateGame() { if (_ProfilesChanged || _AvatarsChanged) + { _LoadProfiles(); + } return true; } @@ -577,16 +678,18 @@ namespace VocaluxeLib.Menu public void IncreaseTeamNum() { if (!_AllowChangeTeamNum) + { return; + } if (_NumTeams + 1 <= _PartyMode.MaxTeams) { _NumTeams++; - int[] numPlayerTeams = _NumPlayerTeams; - List[] teamList = _TeamList; + var numPlayerTeams = _NumPlayerTeams; + var teamList = _TeamList; _NumPlayerTeams = new int[_NumTeams]; _TeamList = new List[_NumTeams]; - for (int i = 0; i < _NumPlayerTeams.Length; i++) + for (var i = 0; i < _NumPlayerTeams.Length; i++) { if (i < numPlayerTeams.Length) { @@ -602,6 +705,7 @@ namespace VocaluxeLib.Menu } } } + _UpdateButtonState(); _UpdateTeamSlide(); } @@ -609,10 +713,15 @@ namespace VocaluxeLib.Menu public void DecreaseTeamNum() { if (!_AllowChangeTeamNum) + { return; + } if (_NumTeams - 1 >= _PartyMode.MinTeams) + { _NumTeams--; + } + _UpdateButtonState(); _UpdateTeamSlide(); } @@ -620,13 +729,20 @@ namespace VocaluxeLib.Menu public void IncreasePlayerNum(int team) { if (!_AllowChangePlayerNum) + { return; + } + if (_NumPlayerTeams.Length > team) { if (_NumPlayerTeams[team] + 1 <= _PartyMode.MaxPlayersPerTeam) + { _NumPlayerTeams[team]++; + } + _UpdatePlayerSlide(); } + _UpdateButtonState(); _UpdateNextButtonVisibility(); } @@ -634,15 +750,25 @@ namespace VocaluxeLib.Menu public void DecreasePlayerNum(int team) { if (!_AllowChangePlayerNum) + { return; + } + if (_NumPlayerTeams.Length > team) { if (_NumPlayerTeams[team] - 1 >= _PartyMode.MinPlayersPerTeam) + { _NumPlayerTeams[team]--; + } + if (_TeamList[team].Count > _NumPlayerTeams[team]) + { _RemovePlayerByIndex(team, _NumPlayerTeams[team] - 1); + } + _UpdatePlayerSlide(); } + _UpdateButtonState(); _UpdateNextButtonVisibility(); } @@ -651,10 +777,14 @@ namespace VocaluxeLib.Menu private void _OnProfileChanged(EProfileChangedFlags flags) { if (EProfileChangedFlags.Avatar == (EProfileChangedFlags.Avatar & flags)) + { _AvatarsChanged = true; + } if (EProfileChangedFlags.Profile == (EProfileChangedFlags.Profile & flags)) + { _ProfilesChanged = true; + } } private void _LoadProfiles() @@ -677,7 +807,9 @@ namespace VocaluxeLib.Menu private void _OnChangeTeamSlide() { if (_CurrentTeam == _SelectSlides[_SelectSlideTeams].Selection) + { return; + } _CurrentTeam = _SelectSlides[_SelectSlideTeams].Selection; _UpdatePlayerSlide(); @@ -686,35 +818,41 @@ namespace VocaluxeLib.Menu private void _UpdatePlayerSlide() { - int selection = _SelectSlides[_SelectSlidePlayer].Selection; + var selection = _SelectSlides[_SelectSlidePlayer].Selection; _SelectSlides[_SelectSlidePlayer].Clear(); - int maxPlayers = Math.Min(_TeamList[_CurrentTeam].Count, _NumPlayerTeams[_CurrentTeam]); + var maxPlayers = Math.Min(_TeamList[_CurrentTeam].Count, _NumPlayerTeams[_CurrentTeam]); - for (int i = 0; i < maxPlayers; i++) + for (var i = 0; i < maxPlayers; i++) { - string name = CBase.Profiles.GetPlayerName(_TeamList[_CurrentTeam][i]); - CTextureRef avatar = CBase.Profiles.GetAvatar(_TeamList[_CurrentTeam][i]); + var name = CBase.Profiles.GetPlayerName(_TeamList[_CurrentTeam][i]); + var avatar = CBase.Profiles.GetAvatar(_TeamList[_CurrentTeam][i]); _SelectSlides[_SelectSlidePlayer].AddValue(name, avatar); } - for (int i = maxPlayers; i < _NumPlayerTeams[_CurrentTeam]; i++) + for (var i = maxPlayers; i < _NumPlayerTeams[_CurrentTeam]; i++) + { _SelectSlides[_SelectSlidePlayer].AddValue("", _NameSelections[_NameSelection].TextureEmptyTile); + } if (selection >= maxPlayers) + { selection = maxPlayers - 1; + } _SelectSlides[_SelectSlidePlayer].Selection = selection; } private void _UpdateTeamSlide() { - int sel = _SelectSlides[_SelectSlideTeams].Selection; + var sel = _SelectSlides[_SelectSlideTeams].Selection; _SelectSlides[_SelectSlideTeams].Visible = _Teams; _SelectSlides[_SelectSlideTeams].Clear(); - for (int i = 1; i <= _NumTeams; i++) + for (var i = 1; i <= _NumTeams; i++) + { _SelectSlides[_SelectSlideTeams].AddValue("Team " + i, null, i); + } _SelectSlides[_SelectSlideTeams].Selection = Math.Min(sel, _SelectSlides[_SelectSlideTeams].NumValues - 1); } @@ -743,21 +881,29 @@ namespace VocaluxeLib.Menu } } - private void _AddPlayer(int team, Guid profileID, bool updateElements=true) + private void _AddPlayer(int team, Guid profileId, bool updateElements = true) { - if (profileID == Guid.Empty) + if (profileId == Guid.Empty) + { return; + } - if (!CBase.Profiles.IsProfileIDValid(profileID)) + if (!CBase.Profiles.IsProfileIdValid(profileId)) + { return; + } - if (_TeamList[team].Contains(profileID)) + if (_TeamList[team].Contains(profileId)) + { return; + } if (_TeamList[team].Count >= _PartyMode.MaxPlayersPerTeam) + { return; + } - int targetIndex = -1; + var targetIndex = -1; if (_TeamList[team].Count < _NumPlayerTeams[team]) { @@ -768,24 +914,28 @@ namespace VocaluxeLib.Menu targetIndex = _SelectSlides[_SelectSlidePlayer].Selection; if (targetIndex < 0 || targetIndex >= _NumPlayerTeams[team]) + { targetIndex = _NumPlayerTeams[team] - 1; + } } if (targetIndex < 0) + { return; + } if (targetIndex < _TeamList[team].Count) { - Guid oldId = _TeamList[team][targetIndex]; + var oldId = _TeamList[team][targetIndex]; _NameSelections[_NameSelection].RemoveUsedProfile(oldId); - _TeamList[team][targetIndex] = profileID; + _TeamList[team][targetIndex] = profileId; } else { - _TeamList[team].Add(profileID); + _TeamList[team].Add(profileId); } - _NameSelections[_NameSelection].UseProfile(profileID); + _NameSelections[_NameSelection].UseProfile(profileId); if (updateElements) { @@ -797,12 +947,14 @@ namespace VocaluxeLib.Menu private void _RemoveAllPlayer() { - for (int t = 0; t < _TeamList.Length; t++) + for (var t = 0; t < _TeamList.Length; t++) { - List ids = new List(); + var ids = new List(); ids.AddRange(_TeamList[t]); - foreach (Guid id in ids) + foreach (var id in ids) + { _RemovePlayer(t, id); + } } } @@ -810,7 +962,7 @@ namespace VocaluxeLib.Menu { if (_TeamList[team].Count > index) { - Guid id = _TeamList[team][index]; + var id = _TeamList[team][index]; _TeamList[team].RemoveAt(index); _NameSelections[_NameSelection].RemoveUsedProfile(id); } @@ -818,10 +970,10 @@ namespace VocaluxeLib.Menu _UpdateNextButtonVisibility(); } - private void _RemovePlayer(int team, Guid profileID) + private void _RemovePlayer(int team, Guid profileId) { - _TeamList[team].Remove(profileID); - _NameSelections[_NameSelection].RemoveUsedProfile(profileID); + _TeamList[team].Remove(profileId); + _NameSelections[_NameSelection].RemoveUsedProfile(profileId); _UpdateNextButtonVisibility(); } @@ -829,13 +981,15 @@ namespace VocaluxeLib.Menu private void _SelectRandom() { _RemoveAllPlayer(); - for (int t = 0; t < _NumPlayerTeams.Length; t++) + for (var t = 0; t < _NumPlayerTeams.Length; t++) { - for (int p = 0; p < _NumPlayerTeams[t]; p++) + for (var p = 0; p < _NumPlayerTeams[t]; p++) { - Guid profileID = _NameSelections[_NameSelection].GetRandomUnusedProfile(); - if(profileID != Guid.Empty) - _AddPlayer(t, profileID); + var profileId = _NameSelections[_NameSelection].GetRandomUnusedProfile(); + if (profileId != Guid.Empty) + { + _AddPlayer(t, profileId); + } } } @@ -849,4 +1003,4 @@ namespace VocaluxeLib.Menu } #endregion } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Menu/CMenuPartySongSelection.cs b/VocaluxeLib/Menu/CMenuPartySongSelection.cs index 44e609e9..f5df07c6 100644 --- a/VocaluxeLib/Menu/CMenuPartySongSelection.cs +++ b/VocaluxeLib/Menu/CMenuPartySongSelection.cs @@ -18,8 +18,6 @@ using System; using System.Collections.Generic; using System.Windows.Forms; -using VocaluxeLib.Draw; -using VocaluxeLib.Songs; namespace VocaluxeLib.Menu { @@ -42,7 +40,7 @@ namespace VocaluxeLib.Menu set { _SongMode = 0; - for (int i = 0; i < AllowedSongModes.Length; i++) + for (var i = 0; i < AllowedSongModes.Length; i++) { if (AllowedSongModes[i] == value) { @@ -60,7 +58,7 @@ namespace VocaluxeLib.Menu set { _Source = 0; - for (int i = 0; i < AllowedSongSources.Length; i++) + for (var i = 0; i < AllowedSongSources.Length; i++) { if (AllowedSongSources[i] == value) { @@ -78,7 +76,7 @@ namespace VocaluxeLib.Menu set { _Sorting = 0; - for (int i = 0; i < AllowedSongSorting.Length; i++) + for (var i = 0; i < AllowedSongSorting.Length; i++) { if (AllowedSongSorting[i] == value) { @@ -100,14 +98,15 @@ namespace VocaluxeLib.Menu protected int NumMinMedleySongs = 3; protected int NumMaxMedleySongs = 10; - private List _PlaylistIDs; + private List _PlaylistIds; public override void Init() { base.Init(); - _ThemeButtons = new string[]{ _ButtonNext, _ButtonBack}; - _ThemeSelectSlides = new string[] { _SelectSlideSongMode, _SelectSlideSource, _SelectSlidePlaylist, _SelectSlideSorting, _SelectSlideCategory, _SelectSlideNumMedleySongs }; + _ThemeButtons = new string[] { _ButtonNext, _ButtonBack }; + _ThemeSelectSlides = new string[] + { _SelectSlideSongMode, _SelectSlideSource, _SelectSlidePlaylist, _SelectSlideSorting, _SelectSlideCategory, _SelectSlideNumMedleySongs }; _SetAllowedOptions(); } @@ -124,9 +123,14 @@ namespace VocaluxeLib.Menu break; case Keys.Enter: if (_Buttons[_ButtonNext].Selected) + { Next(); + } else if (_Buttons[_ButtonBack].Selected) + { Back(); + } + break; case Keys.Left: @@ -146,9 +150,13 @@ namespace VocaluxeLib.Menu if (mouseEvent.LB && _IsMouseOverCurSelection(mouseEvent)) { if (_Buttons[_ButtonBack].Selected) + { Back(); + } else if (_Buttons[_ButtonNext].Selected) + { Next(); + } else { _GetSelectedOptions(); @@ -156,7 +164,9 @@ namespace VocaluxeLib.Menu } } else if (mouseEvent.RB) + { Back(); + } return true; } @@ -178,31 +188,37 @@ namespace VocaluxeLib.Menu private void _FillSlides() { _SelectSlides[_SelectSlideSongMode].Clear(); - foreach (EGameMode gm in AllowedSongModes) + foreach (var gm in AllowedSongModes) + { _SelectSlides[_SelectSlideSongMode].AddValue(gm.ToString()); + } _SelectSlides[_SelectSlideSource].Clear(); - foreach (ESongSource ss in AllowedSongSources) + foreach (var ss in AllowedSongSources) + { _SelectSlides[_SelectSlideSource].AddValue(ss.ToString()); + } _SelectSlides[_SelectSlideSorting].Clear(); - foreach (ESongSorting ss in AllowedSongSorting) + foreach (var ss in AllowedSongSorting) + { _SelectSlides[_SelectSlideSorting].AddValue(ss.ToString()); + } _SelectSlides[_SelectSlidePlaylist].Clear(); - _SelectSlides[_SelectSlidePlaylist].NumVisible = 1; // Make sure that only one playlist at a time will be displayed (or the names overlap) - _PlaylistIDs = CBase.Playlist.GetIds(); - List playlists = CBase.Playlist.GetNames(); - for (int i = 0; i < playlists.Count; i++) + _SelectSlides[_SelectSlidePlaylist].NumVisible = 1; // Make sure that only one playlist at a time will be displayed (or the names overlap) + _PlaylistIds = CBase.Playlist.GetIds(); + var playlists = CBase.Playlist.GetNames(); + for (var i = 0; i < playlists.Count; i++) { - string value = playlists[i] + " (" + CBase.Playlist.GetSongCount(i) + " " + CBase.Language.Translate("TR_SONGS", PartyModeID) + ")"; + var value = playlists[i] + " (" + CBase.Playlist.GetSongCount(i) + " " + CBase.Language.Translate("TR_SONGS", PartyModeId) + ")"; _SelectSlides[_SelectSlidePlaylist].AddValue(value); } _SelectSlides[_SelectSlideNumMedleySongs].Clear(); - for(int num = NumMinMedleySongs; num <= NumMaxMedleySongs; num++) + for (var num = NumMinMedleySongs; num <= NumMaxMedleySongs; num++) { - _SelectSlides[_SelectSlideNumMedleySongs].AddValue(num + " " + CBase.Language.Translate("TR_SONGS", PartyModeID)); + _SelectSlides[_SelectSlideNumMedleySongs].AddValue(num + " " + CBase.Language.Translate("TR_SONGS", PartyModeId)); } _FillCategorySlide(); @@ -211,10 +227,10 @@ namespace VocaluxeLib.Menu private void _FillCategorySlide() { _SelectSlides[_SelectSlideCategory].Clear(); - for (int i = 0; i < CBase.Songs.GetNumCategories(); i++) + for (var i = 0; i < CBase.Songs.GetNumCategories(); i++) { - CCategory cat = CBase.Songs.GetCategory(i); - string value = cat.Name + " (" + cat.GetNumSongsNotSung() + " " + CBase.Language.Translate("TR_SONGS", PartyModeID) + ")"; + var cat = CBase.Songs.GetCategory(i); + var value = cat.Name + " (" + cat.GetNumSongsNotSung() + " " + CBase.Language.Translate("TR_SONGS", PartyModeId) + ")"; _SelectSlides[_SelectSlideCategory].AddValue(value); } } @@ -225,11 +241,15 @@ namespace VocaluxeLib.Menu _Source = _SelectSlides[_SelectSlideSource].Selection; NumMedleySongs = NumMinMedleySongs + _SelectSlides[_SelectSlideNumMedleySongs].Selection; - int playlistSelection = _SelectSlides[_SelectSlidePlaylist].Selection; - if (playlistSelection >= 0 && playlistSelection < _PlaylistIDs.Count) - Playlist = _PlaylistIDs[playlistSelection]; + var playlistSelection = _SelectSlides[_SelectSlidePlaylist].Selection; + if (playlistSelection >= 0 && playlistSelection < _PlaylistIds.Count) + { + Playlist = _PlaylistIds[playlistSelection]; + } else + { Playlist = -1; + } if (_SelectSlides[_SelectSlideSorting].Selection != _Sorting) { @@ -238,8 +258,8 @@ namespace VocaluxeLib.Menu _FillCategorySlide(); _SelectSlides[_SelectSlideCategory].Selection = 0; - } - + } + Category = _SelectSlides[_SelectSlideCategory].Selection; } @@ -268,4 +288,4 @@ namespace VocaluxeLib.Menu AllowedSongSorting = (ESongSorting[])Enum.GetValues(typeof(ESongSorting)); } } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Menu/CNameSelection.cs b/VocaluxeLib/Menu/CNameSelection.cs index 44050f02..971745c3 100644 --- a/VocaluxeLib/Menu/CNameSelection.cs +++ b/VocaluxeLib/Menu/CNameSelection.cs @@ -16,19 +16,19 @@ #endregion using System; -using System.Linq; using System.Collections.Generic; +using System.Linq; using System.Windows.Forms; using System.Xml.Serialization; using VocaluxeLib.Draw; -using VocaluxeLib.Profile; namespace VocaluxeLib.Menu { [XmlType("NameSelection")] public struct SThemeNameSelection { - [XmlAttribute(AttributeName = "Name")] public string Name; + [XmlAttribute(AttributeName = "Name")] + public string Name; public SRectF Rect; public string SkinEmptyTile; public SThemeColor ColorEmptyTile; @@ -50,7 +50,8 @@ namespace VocaluxeLib.Menu public struct SThemeNameSelectionName { public float Space; - [XmlElement("H")] public float Height; + [XmlElement("H")] + public float Height; public string Font; public EStyle Style; public SThemeColor Color; @@ -60,19 +61,19 @@ namespace VocaluxeLib.Menu { private class CTile { - public Guid ProfileID; + public Guid ProfileId; public readonly CStatic Avatar; public readonly CText Name; - public CTile(CStatic av, CText tex, Guid pID) + public CTile(CStatic av, CText tex, Guid pId) { Avatar = av; Name = tex; - ProfileID = pID; + ProfileId = pId; } } - private readonly int _PartyModeID; + private readonly int _PartyModeId; private SThemeNameSelection _Theme; public string GetThemeName() @@ -84,19 +85,15 @@ namespace VocaluxeLib.Menu private readonly List _Tiles; - private CTextureRef _TextureEmptyTile; private CTextureRef _TextureTileSelected; - public CTextureRef TextureEmptyTile - { - get { return _TextureEmptyTile; } - } + public CTextureRef TextureEmptyTile { get; private set; } private SColorF _ColorEmptyTile; private SColorF _ColorNameTile; public int Offset; private int _ActualSelection = -1; - public Guid SelectedID = Guid.Empty; + public Guid SelectedId = Guid.Empty; private int _Player = -1; @@ -116,19 +113,19 @@ namespace VocaluxeLib.Menu get { return Visible; } } - public CNameSelection(int partyModeID) + public CNameSelection(int partyModeId) { - _PartyModeID = partyModeID; - _Theme = new SThemeNameSelection {Tiles = new SThemeNameSelectionTiles {Name = new SThemeNameSelectionName()}}; + _PartyModeId = partyModeId; + _Theme = new SThemeNameSelection { Tiles = new SThemeNameSelectionTiles { Name = new SThemeNameSelectionName() } }; _Tiles = new List(); _VisibleProfiles = new List(); _UsedProfiles = new List(); } - public CNameSelection(SThemeNameSelection theme, int partyModeID) + public CNameSelection(SThemeNameSelection theme, int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = theme; _Tiles = new List(); @@ -142,8 +139,8 @@ namespace VocaluxeLib.Menu { _UsedProfiles.Clear(); _PrepareTiles(); - - _PlayerSelector = new CStatic(_PartyModeID, _TextureTileSelected, new SColorF(), new SRectF(0, 0, _Theme.Tiles.W + 10, _Theme.Tiles.H + 10, Rect.Z - 0.5f)) + + _PlayerSelector = new CStatic(_PartyModeId, _TextureTileSelected, new SColorF(), new SRectF(0, 0, _Theme.Tiles.W + 10, _Theme.Tiles.H + 10, Rect.Z - 0.5f)) { Visible = true }; @@ -151,14 +148,14 @@ namespace VocaluxeLib.Menu _UpdateVisibleProfiles(); UpdateList(0); - _ActualSelection = _Tiles.FindIndex(t => t.ProfileID != Guid.Empty); - SelectedID = _ActualSelection >= 0 ? _Tiles[_ActualSelection].ProfileID : Guid.Empty; + _ActualSelection = _Tiles.FindIndex(t => t.ProfileId != Guid.Empty); + SelectedId = _ActualSelection >= 0 ? _Tiles[_ActualSelection].ProfileId : Guid.Empty; } public void Draw() { - int i = 0; - foreach (CTile tile in _Tiles) + var i = 0; + foreach (var tile in _Tiles) { tile.Avatar.Draw(); tile.Name.Draw(); @@ -175,6 +172,7 @@ namespace VocaluxeLib.Menu i++; } + if (_PlayerSelector.Visible) { //Draw PlayerSelector @@ -185,116 +183,140 @@ namespace VocaluxeLib.Menu public void HandleInput(SKeyEvent kevent) { if (_Tiles.Count == 0 || _VisibleProfiles.Count == 0) + { + _ActualSelection = -1; + SelectedId = Guid.Empty; + return; + } + + if (_ActualSelection < 0 || _ActualSelection >= _Tiles.Count || _Tiles[_ActualSelection].ProfileId == Guid.Empty) + { + _ActualSelection = _Tiles.FindIndex(t => t.ProfileId != Guid.Empty); + if (_ActualSelection < 0) { - _ActualSelection = -1; - SelectedID = Guid.Empty; + SelectedId = Guid.Empty; return; } + } - if (_ActualSelection < 0 || _ActualSelection >= _Tiles.Count || _Tiles[_ActualSelection].ProfileID == Guid.Empty) - { - _ActualSelection = _Tiles.FindIndex(t => t.ProfileID != Guid.Empty); - if (_ActualSelection < 0) + switch (kevent.Key) + { + case Keys.Right: + if (_ActualSelection + 1 < _Tiles.Count) { - SelectedID = Guid.Empty; - return; + if (_Tiles[_ActualSelection + 1].ProfileId != Guid.Empty) + { + _ActualSelection++; + } + } + else + { + var oldOffset = Offset; + UpdateList(Offset + 1); + if (oldOffset != Offset) + { + _ActualSelection = Math.Max(0, _ActualSelection - (_Theme.Tiles.NumW - 1)); + } } - } - - switch (kevent.Key) - { - case Keys.Right: - if (_ActualSelection + 1 < _Tiles.Count) - { - if (_Tiles[_ActualSelection + 1].ProfileID != Guid.Empty) - _ActualSelection++; - } - else - { - int oldOffset = Offset; - UpdateList(Offset + 1); - if (oldOffset != Offset) - _ActualSelection = Math.Max(0, _ActualSelection - (_Theme.Tiles.NumW - 1)); - } - break; - case Keys.Left: - if (_ActualSelection - 1 >= 0) - { - _ActualSelection--; - } - else if (Offset > 0) - { - UpdateList(Offset - 1); - _ActualSelection = Math.Min(_Tiles.Count - 1, _ActualSelection + (_Theme.Tiles.NumW - 1)); - while (_ActualSelection >= 0 && _Tiles[_ActualSelection].ProfileID == Guid.Empty) - _ActualSelection--; - } - break; + break; - case Keys.Up: - if (_ActualSelection - _Theme.Tiles.NumW >= 0) - { - _ActualSelection -= _Theme.Tiles.NumW; - } - else if (Offset > 0) - { - int currentColumn = _ActualSelection % _Theme.Tiles.NumW; - UpdateList(Offset - 1); - _ActualSelection = currentColumn; - if (_ActualSelection >= _Tiles.Count) - _ActualSelection = _Tiles.Count - 1; - while (_ActualSelection >= 0 && _Tiles[_ActualSelection].ProfileID == Guid.Empty) - _ActualSelection--; - } - break; + case Keys.Left: + if (_ActualSelection - 1 >= 0) + { + _ActualSelection--; + } + else if (Offset > 0) + { + UpdateList(Offset - 1); + _ActualSelection = Math.Min(_Tiles.Count - 1, _ActualSelection + (_Theme.Tiles.NumW - 1)); + while (_ActualSelection >= 0 && _Tiles[_ActualSelection].ProfileId == Guid.Empty) + { + _ActualSelection--; + } + } - case Keys.Down: - if (_ActualSelection + _Theme.Tiles.NumW < _Tiles.Count && - _Tiles[_ActualSelection + _Theme.Tiles.NumW].ProfileID != Guid.Empty) - { - _ActualSelection += _Theme.Tiles.NumW; - } - else - { - int oldOffset = Offset; - int currentColumn = _ActualSelection % _Theme.Tiles.NumW; - UpdateList(Offset + 1); + break; - if (oldOffset != Offset) - { - _ActualSelection = currentColumn; - while (_ActualSelection < _Tiles.Count && _Tiles[_ActualSelection].ProfileID == Guid.Empty) - _ActualSelection++; - if (_ActualSelection >= _Tiles.Count || _Tiles[_ActualSelection].ProfileID == Guid.Empty) - _ActualSelection = _Tiles.FindLastIndex(t => t.ProfileID != Guid.Empty); - } - } - break; - } + case Keys.Up: + if (_ActualSelection - _Theme.Tiles.NumW >= 0) + { + _ActualSelection -= _Theme.Tiles.NumW; + } + else if (Offset > 0) + { + var currentColumn = _ActualSelection % _Theme.Tiles.NumW; + UpdateList(Offset - 1); + _ActualSelection = currentColumn; + if (_ActualSelection >= _Tiles.Count) + { + _ActualSelection = _Tiles.Count - 1; + } - if (_ActualSelection >= 0 && _ActualSelection < _Tiles.Count && _Tiles[_ActualSelection].ProfileID != Guid.Empty) - { - SelectedID = _Tiles[_ActualSelection].ProfileID; - } - else - { - SelectedID = Guid.Empty; - } - } + while (_ActualSelection >= 0 && _Tiles[_ActualSelection].ProfileId == Guid.Empty) + { + _ActualSelection--; + } + } + + break; + + case Keys.Down: + if (_ActualSelection + _Theme.Tiles.NumW < _Tiles.Count && + _Tiles[_ActualSelection + _Theme.Tiles.NumW].ProfileId != Guid.Empty) + { + _ActualSelection += _Theme.Tiles.NumW; + } + else + { + var oldOffset = Offset; + var currentColumn = _ActualSelection % _Theme.Tiles.NumW; + UpdateList(Offset + 1); + + if (oldOffset != Offset) + { + _ActualSelection = currentColumn; + while (_ActualSelection < _Tiles.Count && _Tiles[_ActualSelection].ProfileId == Guid.Empty) + { + _ActualSelection++; + } + + if (_ActualSelection >= _Tiles.Count || _Tiles[_ActualSelection].ProfileId == Guid.Empty) + { + _ActualSelection = _Tiles.FindLastIndex(t => t.ProfileId != Guid.Empty); + } + } + } + + break; + } + + if (_ActualSelection >= 0 && _ActualSelection < _Tiles.Count && _Tiles[_ActualSelection].ProfileId != Guid.Empty) + { + SelectedId = _Tiles[_ActualSelection].ProfileId; + } + else + { + SelectedId = Guid.Empty; + } + } public void HandleMouse(SMouseEvent mevent) { - for (int i = 0; i < _Tiles.Count; i++) + for (var i = 0; i < _Tiles.Count; i++) { - if (CHelper.IsInBounds(_Tiles[i].Avatar.Rect, mevent) && _Tiles[i].ProfileID != Guid.Empty) + if (CHelper.IsInBounds(_Tiles[i].Avatar.Rect, mevent) && _Tiles[i].ProfileId != Guid.Empty) { _ActualSelection = i; if (Offset * _Theme.Tiles.NumW + _ActualSelection < _VisibleProfiles.Count) - SelectedID = _VisibleProfiles.ElementAt(Offset * _Theme.Tiles.NumW + _ActualSelection); + { + SelectedId = _VisibleProfiles.ElementAt(Offset * _Theme.Tiles.NumW + _ActualSelection); + } else - SelectedID = Guid.Empty; + { + SelectedId = Guid.Empty; + } } } } @@ -302,32 +324,33 @@ namespace VocaluxeLib.Menu public void FastSelection(bool active, int player) { //Overwrite player-selection; Same profile, but other player - if (active && SelectedID != Guid.Empty) + if (active && SelectedId != Guid.Empty) { _Player = player; _PlayerSelector.Color = CBase.Themes.GetPlayerColor(player); } - //Normal activation + //Normal activation else if (active) { if (_VisibleProfiles.Count > 0) { - SelectedID = _VisibleProfiles.ElementAt(0); + SelectedId = _VisibleProfiles.ElementAt(0); _ActualSelection = 0; } else { - SelectedID = Guid.Empty; + SelectedId = Guid.Empty; _ActualSelection = -1; } + _Player = player; _PlayerSelector.Color = CBase.Themes.GetPlayerColor(player); _PlayerSelector.Visible = true; } - //Deactivate + //Deactivate else { - SelectedID = Guid.Empty; + SelectedId = Guid.Empty; _ActualSelection = -1; _Player = -1; _PlayerSelector.Visible = false; @@ -338,52 +361,62 @@ namespace VocaluxeLib.Menu { _UpdateVisibleProfiles(); if (_Theme.Tiles.NumW * (Offset + 1) - _VisibleProfiles.Count >= _Theme.Tiles.NumW * Offset) + { UpdateList(Offset - 1); + } else + { UpdateList(Offset); + } } public void UpdateList(int offset) { offset = offset.Clamp(0, _GetMaxOffset()); - for (int i = 0; i < _Tiles.Count; i++) + for (var i = 0; i < _Tiles.Count; i++) { - if ((i + offset * _Theme.Tiles.NumW) < _VisibleProfiles.Count) + if (i + offset * _Theme.Tiles.NumW < _VisibleProfiles.Count) { _Tiles[i].Avatar.Texture = CBase.Profiles.GetAvatar(_VisibleProfiles[i + offset * _Theme.Tiles.NumW]); _Tiles[i].Avatar.Color = new SColorF(1, 1, 1, 1); _Tiles[i].Name.Text = CBase.Profiles.GetPlayerName(_VisibleProfiles[i + offset * _Theme.Tiles.NumW]); - _Tiles[i].ProfileID = _VisibleProfiles.ElementAt(i + offset * _Theme.Tiles.NumW); + _Tiles[i].ProfileId = _VisibleProfiles.ElementAt(i + offset * _Theme.Tiles.NumW); } else { - _Tiles[i].Avatar.Texture = _TextureEmptyTile; + _Tiles[i].Avatar.Texture = TextureEmptyTile; _Tiles[i].Avatar.Color = _ColorEmptyTile; _Tiles[i].Name.Text = ""; - _Tiles[i].ProfileID = Guid.Empty; + _Tiles[i].ProfileId = Guid.Empty; } } + Offset = offset; } public bool IsOverTile(SMouseEvent mevent) { - bool isOver = false; - foreach (CTile tile in _Tiles) + var isOver = false; + foreach (var tile in _Tiles) { if (CHelper.IsInBounds(tile.Avatar.Rect, mevent)) + { isOver = true; + } } + return isOver; } - public Guid TilePlayerID(SMouseEvent mevent) + public Guid TilePlayerId(SMouseEvent mevent) { - foreach (CTile tile in _Tiles) + foreach (var tile in _Tiles) { if (CHelper.IsInBounds(tile.Avatar.Rect, mevent)) - return tile.ProfileID; + { + return tile.ProfileId; + } } return Guid.Empty; @@ -391,24 +424,26 @@ namespace VocaluxeLib.Menu public CStatic TilePlayerAvatar(SMouseEvent mevent) { - foreach (CTile tile in _Tiles) + foreach (var tile in _Tiles) { if (CHelper.IsInBounds(tile.Avatar.Rect, mevent)) + { return tile.Avatar; + } } - return new CStatic(_PartyModeID); + return new CStatic(_PartyModeId); } - public void UnloadSkin() {} + public void UnloadSkin() { } public void LoadSkin() { - _TextureEmptyTile = CBase.Themes.GetSkinTexture(_Theme.SkinEmptyTile, _PartyModeID); - _TextureTileSelected = CBase.Themes.GetSkinTexture(_Theme.SkinTileSelected, _PartyModeID); + TextureEmptyTile = CBase.Themes.GetSkinTexture(_Theme.SkinEmptyTile, _PartyModeId); + _TextureTileSelected = CBase.Themes.GetSkinTexture(_Theme.SkinTileSelected, _PartyModeId); - _Theme.ColorEmptyTile.Get(_PartyModeID, out _ColorEmptyTile); - _Theme.Tiles.Name.Color.Get(_PartyModeID, out _ColorNameTile); + _Theme.ColorEmptyTile.Get(_PartyModeId, out _ColorEmptyTile); + _Theme.Tiles.Name.Color.Get(_PartyModeId, out _ColorNameTile); MaxRect = _Theme.Rect; } @@ -425,7 +460,7 @@ namespace VocaluxeLib.Menu { if (id != Guid.Empty) { - if (!_UsedProfiles.Contains(id) && CBase.Profiles.IsProfileIDValid(id) && !CBase.Profiles.IsGuest(id)) + if (!_UsedProfiles.Contains(id) && CBase.Profiles.IsProfileIdValid(id) && !CBase.Profiles.IsGuest(id)) { _UsedProfiles.Add(id); UpdateList(); @@ -444,19 +479,26 @@ namespace VocaluxeLib.Menu public Guid GetRandomUnusedProfile() { - Guid id = Guid.Empty; + var id = Guid.Empty; if (_VisibleProfiles.Count == 0) + { return id; + } if (_VisibleProfiles.Count == _UsedProfiles.Count) + { return id; + } while (id == Guid.Empty) { - int rand = CBase.Game.GetRandom(_VisibleProfiles.Count); + var rand = CBase.Game.GetRandom(_VisibleProfiles.Count); if (_UsedProfiles.Contains(_VisibleProfiles[rand])) + { continue; + } + id = _VisibleProfiles.ElementAt(rand); } @@ -466,18 +508,19 @@ namespace VocaluxeLib.Menu private void _PrepareTiles() { _Tiles.Clear(); - for (int i = 0; i < _Theme.Tiles.NumH; i++) + for (var i = 0; i < _Theme.Tiles.NumH; i++) { - for (int j = 0; j < _Theme.Tiles.NumW; j++) + for (var j = 0; j < _Theme.Tiles.NumW; j++) { var rect = new SRectF(MaxRect.X + j * (_Theme.Tiles.W + _Theme.Tiles.SpaceW), MaxRect.Y + i * (_Theme.Tiles.H + _Theme.Tiles.SpaceH), - _Theme.Tiles.W, _Theme.Tiles.H, MaxRect.Z); - var tileStatic = new CStatic(_PartyModeID, _TextureEmptyTile, _ColorEmptyTile, rect) {Aspect = EAspect.Crop}; + _Theme.Tiles.W, _Theme.Tiles.H, MaxRect.Z); + var tileStatic = new CStatic(_PartyModeId, TextureEmptyTile, _ColorEmptyTile, rect) { Aspect = EAspect.Crop }; var tileText = new CText(rect.X + rect.W / 2, rect.Y + rect.H + _Theme.Tiles.Name.Space, rect.Z, _Theme.Tiles.Name.Height, rect.W, EAlignment.Center, - _Theme.Tiles.Name.Style, _Theme.Tiles.Name.Font, _ColorNameTile, ""); + _Theme.Tiles.Name.Style, _Theme.Tiles.Name.Font, _ColorNameTile, ""); _Tiles.Add(new CTile(tileStatic, tileText, Guid.Empty)); } } + _Rect.X = MaxRect.X; _Rect.Y = MaxRect.Y; _Rect.Right = _Tiles[_Tiles.Count - 1].Avatar.Rect.Right; @@ -488,28 +531,34 @@ namespace VocaluxeLib.Menu private void _UpdateVisibleProfiles() { _VisibleProfiles.Clear(); - CProfile[] profiles = CBase.Profiles.GetProfiles(); + var profiles = CBase.Profiles.GetProfiles(); - foreach (CProfile profile in profiles) + foreach (var profile in profiles) { - bool visible = profile.Active == EOffOn.TR_CONFIG_ON; + var visible = profile.Active == EOffOn.TR_CONFIG_ON; if (visible) { - if (_UsedProfiles.Contains(profile.ID) && ((int)profile.UserRole) >= ((int)EUserRole.TR_USERROLE_NORMAL)) + if (_UsedProfiles.Contains(profile.Id) && (int)profile.UserRole >= (int)EUserRole.TR_USERROLE_NORMAL) + { visible = false; + } } + if (visible) - _VisibleProfiles.Add(profile.ID); + { + _VisibleProfiles.Add(profile.Id); + } } } private int _GetMaxOffset() { - int maxOffset = (int)Math.Ceiling((decimal)(_VisibleProfiles.Count - _Tiles.Count) / _Theme.Tiles.NumW); + var maxOffset = (int)Math.Ceiling((decimal)(_VisibleProfiles.Count - _Tiles.Count) / _Theme.Tiles.NumW); if (maxOffset < 0) { return 0; } + return maxOffset; } @@ -532,15 +581,19 @@ namespace VocaluxeLib.Menu { W += stepW; if (W <= 0) + { W = 1; + } H += stepH; if (H <= 0) + { H = 1; + } _Theme.Rect.W = W; _Theme.Rect.H = H; } #endregion ThemeEdit } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Menu/CObjectInteractions.cs b/VocaluxeLib/Menu/CObjectInteractions.cs index 340635d0..2fb7c948 100644 --- a/VocaluxeLib/Menu/CObjectInteractions.cs +++ b/VocaluxeLib/Menu/CObjectInteractions.cs @@ -96,22 +96,33 @@ namespace VocaluxeLib.Menu private void _SetSelected(int newSelection) { - IMenuElement el = _GetElement(_Selection); + var el = _GetElement(_Selection); if (newSelection == _Selection) { // Don't change current selection if (el == null) + { _Selection = -1; + } else if (!el.Selected) + { el.Selected = true; + } + return; } + if (el != null) + { el.Selected = false; + } + _Selection = newSelection; el = _GetElement(_Selection); if (el != null) + { el.Selected = true; + } } #region MenuHandler @@ -122,18 +133,26 @@ namespace VocaluxeLib.Menu if (keyEvent.Key == Keys.Left) { if (_IsSelectionValid() && _Elements[_Selection].Type == EType.SelectSlide && keyEvent.Mod != EModifier.Shift) + { keyEvent.Handled = PrevValue(); + } else + { keyEvent.Handled = _NextElement(keyEvent); + } return true; } else if (keyEvent.Key == Keys.Right) { if (_IsSelectionValid() && _Elements[_Selection].Type == EType.SelectSlide && keyEvent.Mod != EModifier.Shift) + { keyEvent.Handled = NextValue(); + } else + { keyEvent.Handled = _NextElement(keyEvent); + } return true; } @@ -149,9 +168,13 @@ namespace VocaluxeLib.Menu if (keyEvent.Key == Keys.Tab) { if (keyEvent.Mod == EModifier.Shift) + { PrevElement(); + } else + { NextElement(); + } return true; } @@ -178,7 +201,9 @@ namespace VocaluxeLib.Menu ProcessMouseMove(mouseEvent.X, mouseEvent.Y); if (mouseEvent.LB) + { ProcessMouseClick(mouseEvent.X, mouseEvent.Y); + } _PrevMouse.X = mouseEvent.X; _PrevMouse.Y = mouseEvent.Y; @@ -188,8 +213,8 @@ namespace VocaluxeLib.Menu public virtual bool HandleInputThemeEditor(SKeyEvent keyEvent) { - int dx = 0; - int dy = 0; + var dx = 0; + var dy = 0; if (!keyEvent.KeyPressed) { switch (keyEvent.Key) @@ -214,7 +239,9 @@ namespace VocaluxeLib.Menu } } else + { return false; + } if ((keyEvent.Mod & EModifier.Ctrl) != EModifier.Ctrl) { @@ -223,15 +250,24 @@ namespace VocaluxeLib.Menu } if ((keyEvent.Mod & EModifier.Alt) == EModifier.Alt) + { _MoveElement(dx, dy); + } else if ((keyEvent.Mod & EModifier.Shift) == EModifier.Shift) + { _ResizeElement(dx, dy); + } else { if (_IsSelectionValid()) + { _GetElement(_Selection).Highlighted = false; + } + if (_NextElement(keyEvent)) + { _GetElement(_Selection).Highlighted = true; + } } return true; @@ -240,9 +276,11 @@ namespace VocaluxeLib.Menu public virtual bool HandleMouseThemeEditor(SMouseEvent mouseEvent) { if (_IsSelectionValid()) + { _GetElement(_Selection).Highlighted = false; + } - Point mouse = new Point(mouseEvent.X, mouseEvent.Y); + var mouse = new Point(mouseEvent.X, mouseEvent.Y); if ((mouseEvent.Mod & EModifier.Ctrl) != EModifier.Ctrl) { // Clip to raster @@ -250,8 +288,8 @@ namespace VocaluxeLib.Menu mouse.Y = (int)(Math.Round((double)mouse.Y / 5) * 5); } - int mouseDX = mouse.X - _PrevMouse.X; - int mouseDY = mouse.Y - _PrevMouse.Y; + var mouseDX = mouse.X - _PrevMouse.X; + var mouseDY = mouse.Y - _PrevMouse.Y; _PrevMouse.X = mouseEvent.X; _PrevMouse.Y = mouseEvent.Y; @@ -259,12 +297,18 @@ namespace VocaluxeLib.Menu if (mouseEvent.LBH) { if (mouseEvent.Mod == EModifier.Shift) + { _ResizeElement(mouseDX, mouseDX); + } else + { _MoveElement(mouseDX, mouseDY); + } } else + { ProcessMouseMove(mouseEvent.X, mouseEvent.Y); + } return true; } @@ -308,44 +352,55 @@ namespace VocaluxeLib.Menu case EType.RatingPopup: return _RatingPopups[element.Num]; } + throw new ArgumentException("Invalid element type: " + element.Type); } private IMenuElement _GetElement(int element) { - return (element >= 0 && element < _Elements.Count) ? _GetElement(_Elements[element]) : null; + return element >= 0 && element < _Elements.Count ? _GetElement(_Elements[element]) : null; } #region Drawing public virtual void Draw() { if (!_Active) + { return; + } + if (_Elements.Count <= 0) + { return; + } var items = new List(); - for (int i = 0; i < _Elements.Count; i++) + for (var i = 0; i < _Elements.Count; i++) { if (_IsVisible(i)) { - var zs = new SZSort {ID = i, Z = _GetZValue(i)}; + var zs = new SZSort { Id = i, Z = _GetZValue(i) }; items.Add(zs); } } if (items.Count <= 0) + { return; + } items.Sort((s1, s2) => s2.Z.CompareTo(s1.Z)); - for (int i = 0; i < items.Count; i++) + for (var i = 0; i < items.Count; i++) { - IMenuElement el = _GetElement(items[i].ID); + var el = _GetElement(items[i].Id); if (el.Highlighted) + { CBase.Drawing.DrawRect(_HighlightColor, el.MaxRect); + } + el.Draw(); } } @@ -427,8 +482,11 @@ namespace VocaluxeLib.Menu protected void _SelectElement(IMenuElement element) { if (!element.Visible) + { return; - for (int i = 0; i < _Elements.Count; i++) + } + + for (var i = 0; i < _Elements.Count; i++) { if (_GetElement(i) == element) { @@ -441,12 +499,16 @@ namespace VocaluxeLib.Menu public void ProcessMouseClick(int x, int y) { if (!_IsSelectionValid()) + { return; + } if (_Elements[_Selection].Type == EType.SelectSlide) { if (_SelectSlides[_Elements[_Selection].Num].Visible) + { _SelectSlides[_Elements[_Selection].Num].ProcessMouseLBClick(x, y); + } } } @@ -455,80 +517,112 @@ namespace VocaluxeLib.Menu _SelectByMouse(x, y); if (!_IsSelectionValid()) + { return; + } if (_Elements[_Selection].Type == EType.SelectSlide) { if (_SelectSlides[_Elements[_Selection].Num].Visible) + { _SelectSlides[_Elements[_Selection].Num].ProcessMouseMove(x, y); + } } } private void _SelectByMouse(int x, int y) { - float z = CBase.Settings.GetZFar(); - int element = -1; - for (int i = 0; i < _Elements.Count; i++) + var z = CBase.Settings.GetZFar(); + var element = -1; + for (var i = 0; i < _Elements.Count; i++) { if (!_IsSelectable(i)) + { continue; + } + if (!_IsMouseOverElement(x, y, _Elements[i])) + { continue; + } + if (_GetZValue(i) > z) + { continue; + } + z = _GetZValue(i); element = i; } + _SetSelected(element); } protected bool _IsMouseOverCurSelection(SMouseEvent mouseEvent) { if (!_IsSelectionValid()) + { return false; + } return _IsMouseOverElement(mouseEvent.X, mouseEvent.Y, _Elements[_Selection]); } private bool _IsMouseOverElement(int x, int y, CInteraction interact) { - bool result = CHelper.IsInBounds(_GetRect(interact), x, y); + var result = CHelper.IsInBounds(_GetRect(interact), x, y); if (result) + { return true; + } + if (interact.Type == EType.SelectSlide) { return CHelper.IsInBounds(_SelectSlides[interact.Num].RectArrowLeft, x, y) || CHelper.IsInBounds(_SelectSlides[interact.Num].RectArrowRight, x, y); } + return false; } public void NextElement() { - int element = _Selection; - for (int i = 0; i < _Elements.Count; i++) + var element = _Selection; + for (var i = 0; i < _Elements.Count; i++) { element++; if (element >= _Elements.Count) + { element = 0; + } + if (_IsSelectable(element)) + { break; + } } + _SetSelected(element); } public void PrevElement() { Debug.Assert(_Selection == 0 || _Selection < _Elements.Count); - int element = _Selection; - for (int i = 0; i < _Elements.Count; i++) + var element = _Selection; + for (var i = 0; i < _Elements.Count; i++) { element--; if (element < 0) + { element = _Elements.Count - 1; + } + if (_IsSelectable(element)) + { break; + } } + _SetSelected(element); } @@ -556,15 +650,23 @@ namespace VocaluxeLib.Menu break; case Keys.Tab: if (key.Mod == EModifier.Shift) + { PrevElement(); + } else + { NextElement(); + } + return true; default: return false; } + if (element < 0) + { return false; + } // select the new element _SetSelected(element); @@ -573,15 +675,15 @@ namespace VocaluxeLib.Menu private int _GetNextElement(EDirection direction) { - float distance = float.MaxValue; - int min = -1; - SRectF currentRect = _IsSelectionValid() ? _GetRect(_Selection) : new SRectF(_PrevMouse.X, _PrevMouse.Y, 1, 1, 1); + var distance = float.MaxValue; + var min = -1; + var currentRect = _IsSelectionValid() ? _GetRect(_Selection) : new SRectF(_PrevMouse.X, _PrevMouse.Y, 1, 1, 1); - for (int i = 0; i < _Elements.Count; i++) + for (var i = 0; i < _Elements.Count; i++) { if (i != _Selection && _IsSelectable(i)) { - float dist = _GetDistanceDirect(direction, currentRect, _GetRect(i)); + var dist = _GetDistanceDirect(direction, currentRect, _GetRect(i)); if (dist >= 0f && dist < distance) { distance = dist; @@ -589,14 +691,17 @@ namespace VocaluxeLib.Menu } } } - if (min >= 0) - return min; - for (int i = 0; i < _Elements.Count; i++) + if (min >= 0) + { + return min; + } + + for (var i = 0; i < _Elements.Count; i++) { if (i != _Selection && _IsSelectable(i)) { - float dist = _GetDistance180(direction, currentRect, _GetRect(i)); + var dist = _GetDistance180(direction, currentRect, _GetRect(i)); if (dist >= 0f && dist < distance) { distance = dist; @@ -604,8 +709,11 @@ namespace VocaluxeLib.Menu } } } + if (min >= 0) + { return min; + } switch (direction) { @@ -623,11 +731,11 @@ namespace VocaluxeLib.Menu break; } - for (int i = 0; i < _Elements.Count; i++) + for (var i = 0; i < _Elements.Count; i++) { if (i != _Selection && _IsSelectable(i)) { - float dist = _GetDistance180(direction, currentRect, _GetRect(i)); + var dist = _GetDistance180(direction, currentRect, _GetRect(i)); if (dist >= 0f && dist < distance) { distance = dist; @@ -635,6 +743,7 @@ namespace VocaluxeLib.Menu } } } + return min; } @@ -645,15 +754,22 @@ namespace VocaluxeLib.Menu case EDirection.Up: case EDirection.Down: if (!other.X.IsInRange(current.X, current.Right) && !other.Right.IsInRange(current.X, current.Right) && !current.X.IsInRange(other.X, other.Right)) + { return float.MaxValue; + } + break; case EDirection.Left: case EDirection.Right: if (!other.Y.IsInRange(current.Y, current.Bottom) && !other.Bottom.IsInRange(current.Y, current.Bottom) && !current.Y.IsInRange(other.Y, other.Bottom)) + { return float.MaxValue; + } + break; } + return _GetDistance180(direction, current, other); } @@ -668,24 +784,37 @@ namespace VocaluxeLib.Menu { case EDirection.Up: if (vector.Y < 0f) + { return distance; + } + break; case EDirection.Down: if (vector.Y > 0f) + { return distance; + } + break; case EDirection.Left: if (vector.X < 0f) + { return distance; + } + break; case EDirection.Right: if (vector.X > 0f) + { return distance; + } + break; } + return float.MaxValue; } @@ -696,7 +825,9 @@ namespace VocaluxeLib.Menu public bool NextValue() { if (_IsSelectionValid() && _Elements[_Selection].Type == EType.SelectSlide) + { return _SelectSlides[_Elements[_Selection].Num].SelectNextValue(); + } return false; } @@ -710,7 +841,9 @@ namespace VocaluxeLib.Menu public bool PrevValue() { if (_IsSelectionValid() && _Elements[_Selection].Type == EType.SelectSlide) + { return _SelectSlides[_Elements[_Selection].Num].SelectPrevValue(); + } return false; } @@ -719,22 +852,26 @@ namespace VocaluxeLib.Menu { _Elements.Add(new CInteraction(num, type)); if (_IsSelectable(_Selection)) + { _SetSelected(_Selection); + } else + { NextElement(); + } } #endregion InteractionHandling #region Element-property getters private bool _IsVisible(int element) { - IMenuElement el = _GetElement(element); + var el = _GetElement(element); return el != null && el.Visible; } private bool _IsSelectable(int element) { - IMenuElement el = _GetElement(element); + var el = _GetElement(element); return el != null && (el.Selectable || CBase.Settings.GetProgramState() == EProgramState.EditTheme); } @@ -757,16 +894,20 @@ namespace VocaluxeLib.Menu #region Theme Handling private void _MoveElement(int stepX, int stepY) { - IMenuElement el = _GetElement(_Selection); + var el = _GetElement(_Selection); if (el != null) + { el.MoveElement(stepX, stepY); + } } private void _ResizeElement(int stepW, int stepH) { - IMenuElement el = _GetElement(_Selection); + var el = _GetElement(_Selection); if (el != null) + { el.ResizeElement(stepW, stepH); + } } #endregion Theme Handling } diff --git a/VocaluxeLib/Menu/COrderedDictionaryLite.cs b/VocaluxeLib/Menu/COrderedDictionaryLite.cs index da8a2cbe..17290fb9 100644 --- a/VocaluxeLib/Menu/COrderedDictionaryLite.cs +++ b/VocaluxeLib/Menu/COrderedDictionaryLite.cs @@ -34,7 +34,9 @@ namespace VocaluxeLib.Menu _HtIndex = new Dictionary(); _ParentName = parent.GetType().Name; if (_ParentName[0] == 'C' && Char.IsUpper(_ParentName[1])) + { _ParentName = _ParentName.Remove(0, 1); + } } public int Count @@ -70,14 +72,19 @@ namespace VocaluxeLib.Menu _Items.Add(value); } else + { _Items[_HtIndex[key]] = value; + } } } public int Add(T item, String key = null) { if (key != null) + { _HtIndex.Add(key, _Items.Count); + } + _Items.Add(item); return _Items.Count - 1; } diff --git a/VocaluxeLib/Menu/CParticle.cs b/VocaluxeLib/Menu/CParticle.cs index 580380a2..a4ffe9f5 100644 --- a/VocaluxeLib/Menu/CParticle.cs +++ b/VocaluxeLib/Menu/CParticle.cs @@ -24,13 +24,12 @@ namespace VocaluxeLib.Menu class CParticle { #region private vars - private readonly int _PartyModeID; + private readonly int _PartyModeId; private readonly string _TextureName; private readonly CTextureRef _Texture; private SRectF _Rect; private float _Size; private SColorF _Color; - private float _Alpha = 1; private float _Angle; //0..360° private readonly float _MaxAge; //[s] private float _Age; //[s] @@ -72,11 +71,7 @@ namespace VocaluxeLib.Menu } } - public float Alpha - { - get { return _Alpha; } - set { _Alpha = value; } - } + public float Alpha { get; set; } = 1; public SColorF Color { @@ -91,10 +86,10 @@ namespace VocaluxeLib.Menu #endregion public vars #region Constructors - public CParticle(int partyModeID, string textureName, SColorF color, float x, float y, float size, float maxage, float z, float vx, float vy, float vr, float vsize, - EParticleType type) + public CParticle(int partyModeId, string textureName, SColorF color, float x, float y, float size, float maxage, float z, float vx, float vy, float vr, float vsize, + EParticleType type) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _TextureName = textureName; _Color = color; _Rect = new SRectF(x, y, size, size, z); @@ -109,11 +104,11 @@ namespace VocaluxeLib.Menu _Rotation = (float)(CBase.Game.GetRandomDouble() * 360.0); } - public CParticle(int partyModeID, CTextureRef texture, SColorF color, float x, float y, float size, float maxage, float z, float vx, float vy, float vr, float vsize, - EParticleType type) + public CParticle(int partyModeId, CTextureRef texture, SColorF color, float x, float y, float size, float maxage, float z, float vx, float vy, float vr, float vsize, + EParticleType type) { - _PartyModeID = partyModeID; - _TextureName = String.Empty; + _PartyModeId = partyModeId; + _TextureName = string.Empty; _Texture = texture; _Color = color; _Rect = new SRectF(x, y, size, size, z); @@ -132,13 +127,17 @@ namespace VocaluxeLib.Menu public void Update() { if (!IsAlive) + { return; + } if (!_Timer.IsRunning) + { _Timer.Start(); + } - float currentTime = _Timer.ElapsedMilliseconds / 1000f; - float timediff = currentTime - _LastTime; + var currentTime = _Timer.ElapsedMilliseconds / 1000f; + var timediff = currentTime - _LastTime; _Age = currentTime; @@ -148,23 +147,23 @@ namespace VocaluxeLib.Menu switch (_Type) { case EParticleType.Twinkle: - _Alpha = 1f - _Age / _MaxAge; + Alpha = 1f - _Age / _MaxAge; break; case EParticleType.Star: - _Alpha = 1f - _Age / _MaxAge; + Alpha = 1f - _Age / _MaxAge; break; case EParticleType.Snow: - _Alpha = (float)Math.Sqrt((Math.Sin(_Age / _MaxAge * Math.PI * 2 - 0.5 * Math.PI) + 1) / 2); + Alpha = (float)Math.Sqrt((Math.Sin(_Age / _MaxAge * Math.PI * 2 - 0.5 * Math.PI) + 1) / 2); break; case EParticleType.Flare: - _Alpha = 1f - _Age / _MaxAge; + Alpha = 1f - _Age / _MaxAge; break; case EParticleType.PerfNoteStar: - _Alpha = 1f - _Age / _MaxAge; + Alpha = 1f - _Age / _MaxAge; break; } } @@ -187,16 +186,21 @@ namespace VocaluxeLib.Menu if (Math.Round(Y) < maxy) { - float vdx = 0f; + var vdx = 0f; if (Math.Abs(_Vx) > float.Epsilon) + { vdx = (float)Math.Sin(currentTime / _Vx * Math.PI); + } X += _Vx * timediff * (0.5f + vdx); Y += _Vy * timediff * (vdx * vdx / 2f + 0.5f); if (Y >= maxy) + { Y = maxy; + } } + break; case EParticleType.Flare: @@ -214,7 +218,7 @@ namespace VocaluxeLib.Menu // update size if (Math.Abs(_Vsize) > float.Epsilon) { - float size = _Size; + var size = _Size; switch (_Type) { case EParticleType.Twinkle: @@ -247,7 +251,7 @@ namespace VocaluxeLib.Menu // update rotation if (Math.Abs(_Vr) > 0.01) { - float r = currentTime * _Vr / 60f; + var r = currentTime * _Vr / 60f; _Angle = _Rotation + 360f * (r - (float)Math.Floor(r)); _Rect.Rotation = _Angle; } @@ -268,11 +272,16 @@ namespace VocaluxeLib.Menu public void Draw(bool allMonitors = true) { // ReSharper disable ConvertIfStatementToConditionalTernaryExpression - if (!String.IsNullOrEmpty(_TextureName)) + if (!string.IsNullOrEmpty(_TextureName)) // ReSharper restore ConvertIfStatementToConditionalTernaryExpression - CBase.Drawing.DrawTexture(CBase.Themes.GetSkinTexture(_TextureName, _PartyModeID), _Rect, new SColorF(_Color.R, _Color.G, _Color.B, _Color.A * Alpha2 * _Alpha), allMonitors); + { + CBase.Drawing.DrawTexture(CBase.Themes.GetSkinTexture(_TextureName, _PartyModeId), _Rect, new SColorF(_Color.R, _Color.G, _Color.B, _Color.A * Alpha2 * Alpha), + allMonitors); + } else - CBase.Drawing.DrawTexture(_Texture, _Rect, new SColorF(_Color.R, _Color.G, _Color.B, _Color.A * Alpha2 * _Alpha), allMonitors); + { + CBase.Drawing.DrawTexture(_Texture, _Rect, new SColorF(_Color.R, _Color.G, _Color.B, _Color.A * Alpha2 * Alpha), allMonitors); + } } } } \ No newline at end of file diff --git a/VocaluxeLib/Menu/CParticleEffect.cs b/VocaluxeLib/Menu/CParticleEffect.cs index 7f158ce8..132be6da 100644 --- a/VocaluxeLib/Menu/CParticleEffect.cs +++ b/VocaluxeLib/Menu/CParticleEffect.cs @@ -49,7 +49,7 @@ namespace VocaluxeLib.Menu public sealed class CParticleEffect : CMenuElementBase, IMenuElement, IThemeable { - private readonly int _PartyModeID; + private readonly int _PartyModeId; private SThemeParticleEffect _Theme; public CTextureRef Texture; @@ -75,9 +75,9 @@ namespace VocaluxeLib.Menu get { return _Stars.Count > 0 || !_SpawnTimer.IsRunning; } } - public CParticleEffect(int partyModeID) + public CParticleEffect(int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = new SThemeParticleEffect(); _Stars = new List(); _SpawnTimer = new Stopwatch(); @@ -85,9 +85,9 @@ namespace VocaluxeLib.Menu Visible = true; } - public CParticleEffect(int partyModeID, int maxNumber, SColorF color, SRectF rect, string skin, float size, EParticleType type) + public CParticleEffect(int partyModeId, int maxNumber, SColorF color, SRectF rect, string skin, float size, EParticleType type) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = new SThemeParticleEffect(); _Stars = new List(); MaxRect = rect; @@ -101,14 +101,14 @@ namespace VocaluxeLib.Menu Visible = true; } - public CParticleEffect(int partyModeID, int maxNumber, SColorF color, SRectF rect, CTextureRef texture, float size, EParticleType type) + public CParticleEffect(int partyModeId, int maxNumber, SColorF color, SRectF rect, CTextureRef texture, float size, EParticleType type) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = new SThemeParticleEffect(); _Stars = new List(); MaxRect = rect; Color = color; - _Theme.Skin = String.Empty; + _Theme.Skin = string.Empty; Texture = texture; _Theme.MaxNumber = maxNumber; _Theme.Size = size; @@ -118,9 +118,9 @@ namespace VocaluxeLib.Menu Visible = true; } - public CParticleEffect(SThemeParticleEffect theme, int partyModeID) + public CParticleEffect(SThemeParticleEffect theme, int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = theme; _Stars = new List(); _SpawnTimer = new Stopwatch(); @@ -132,7 +132,7 @@ namespace VocaluxeLib.Menu public void Update() { - bool doSpawn = false; + var doSpawn = false; if (!_SpawnTimer.IsRunning) { _SpawnTimer.Start(); @@ -149,12 +149,12 @@ namespace VocaluxeLib.Menu while (_Stars.Count < _Theme.MaxNumber && doSpawn) { - float size = CBase.Game.GetRandom((int)_Theme.Size / 2) + _Theme.Size / 2; - float lifetime = 0f; - float vx = 0f; - float vy = 0f; - float vr = 0f; - float vsize = 0f; + var size = CBase.Game.GetRandom((int)_Theme.Size / 2) + _Theme.Size / 2; + var lifetime = 0f; + var vx = 0f; + var vy = 0f; + var vr = 0f; + var vsize = 0f; _NextSpawnTime = 0f; switch (_Theme.Type) @@ -212,60 +212,74 @@ namespace VocaluxeLib.Menu var h = (int)(Rect.H - size / 4f); if (w < 0) + { w = 0; + } if (h < 0) + { h = 0; + } CParticle star; - if (!String.IsNullOrEmpty(_Theme.Skin)) + if (!string.IsNullOrEmpty(_Theme.Skin)) { - star = new CParticle(_PartyModeID, _Theme.Skin, Color, - CBase.Game.GetRandom(w) + Rect.X - size / 4f, - CBase.Game.GetRandom(h) + Rect.Y - size / 4f, - size, lifetime, Rect.Z, vx, vy, vr, vsize, _Theme.Type); + star = new CParticle(_PartyModeId, _Theme.Skin, Color, + CBase.Game.GetRandom(w) + Rect.X - size / 4f, + CBase.Game.GetRandom(h) + Rect.Y - size / 4f, + size, lifetime, Rect.Z, vx, vy, vr, vsize, _Theme.Type); } else { - star = new CParticle(_PartyModeID, Texture, Color, - CBase.Game.GetRandom(w) + Rect.X - size / 4f, - CBase.Game.GetRandom(h) + Rect.Y - size / 4f, - size, lifetime, Rect.Z, vx, vy, vr, vsize, _Theme.Type); + star = new CParticle(_PartyModeId, Texture, Color, + CBase.Game.GetRandom(w) + Rect.X - size / 4f, + CBase.Game.GetRandom(h) + Rect.Y - size / 4f, + size, lifetime, Rect.Z, vx, vy, vr, vsize, _Theme.Type); } _Stars.Add(star); } if (_Theme.Type == EParticleType.Flare || _Theme.Type == EParticleType.PerfNoteStar || _Theme.Type == EParticleType.Twinkle) + { _NextSpawnTime = -1f; + } - int i = 0; + var i = 0; while (i < _Stars.Count) { _Stars[i].Update(); if (!_Stars[i].IsAlive) + { _Stars.RemoveAt(i); + } else + { i++; + } } } public void Pause() { - foreach (CParticle star in _Stars) + foreach (var star in _Stars) + { star.Pause(); + } } public void Resume() { - foreach (CParticle star in _Stars) + foreach (var star in _Stars) + { star.Resume(); + } } public void Draw() { Update(); - foreach (CParticle star in _Stars) + foreach (var star in _Stars) { star.Alpha2 = Alpha; star.Draw(AllMonitors); @@ -279,10 +293,12 @@ namespace VocaluxeLib.Menu public void LoadSkin() { - _Theme.Color.Get(_PartyModeID, out Color); + _Theme.Color.Get(_PartyModeId, out Color); - if (!String.IsNullOrEmpty(_Theme.Skin)) - Texture = CBase.Themes.GetSkinTexture(_Theme.Skin, _PartyModeID); + if (!string.IsNullOrEmpty(_Theme.Skin)) + { + Texture = CBase.Themes.GetSkinTexture(_Theme.Skin, _PartyModeId); + } MaxRect = _Theme.Rect; } @@ -317,11 +333,15 @@ namespace VocaluxeLib.Menu { W += stepW; if (W <= 0) + { W = 1; + } H += stepH; if (H <= 0) + { H = 1; + } _Theme.Rect.W = Rect.W; _Theme.Rect.H = Rect.H; diff --git a/VocaluxeLib/Menu/CPlaylist.cs b/VocaluxeLib/Menu/CPlaylist.cs index 13388a46..eb1555f7 100644 --- a/VocaluxeLib/Menu/CPlaylist.cs +++ b/VocaluxeLib/Menu/CPlaylist.cs @@ -19,7 +19,6 @@ using System; using System.Collections.Generic; using System.Windows.Forms; using System.Xml.Serialization; -using VocaluxeLib.Songs; namespace VocaluxeLib.Menu { @@ -32,12 +31,12 @@ namespace VocaluxeLib.Menu public class CPlaylistSong { - public int SongID; + public int SongId; public EGameMode GameMode; - public CPlaylistSong(int songID, EGameMode gm) + public CPlaylistSong(int songId, EGameMode gm) { - SongID = songID; + SongId = songId; GameMode = gm; } @@ -48,17 +47,21 @@ namespace VocaluxeLib.Menu public SPlaylistSong ToStruct() { - CSong song = CBase.Songs.GetSongByID(SongID); + var song = CBase.Songs.GetSongById(SongId); if (song == null) + { throw new Exception("Can't find Song. This should never happen!"); - return new SPlaylistSong {Artist = song.Artist, Title = song.Title, GameMode = GameMode}; + } + + return new SPlaylistSong { Artist = song.Artist, Title = song.Title, GameMode = GameMode }; } } [XmlType("Playlist")] public struct SThemePlaylist { - [XmlAttribute(AttributeName = "Name")] public string Name; + [XmlAttribute(AttributeName = "Name")] + public string Name; public SRectF Rect; @@ -92,7 +95,7 @@ namespace VocaluxeLib.Menu private class CPlaylistElementContent { public IList Modes; - public int SongID; + public int SongId; public EGameMode Mode; } @@ -104,7 +107,7 @@ namespace VocaluxeLib.Menu public CSelectSlide SelectSlide; public int Content; - public CPlaylistElement() {} + public CPlaylistElement() { } public CPlaylistElement(CPlaylistElement pe) { @@ -125,8 +128,8 @@ namespace VocaluxeLib.Menu public void MouseMove(int posX, int posY, int oldPosX, int oldPosY) { - int diffX = posX - oldPosX; - int diffY = posY - oldPosY; + var diffX = posX - oldPosX; + var diffY = posY - oldPosY; Cover.X += diffX; Cover.Y += diffY; @@ -142,7 +145,7 @@ namespace VocaluxeLib.Menu } } - private readonly int _PartyModeID; + private readonly int _PartyModeId; private SThemePlaylist _Theme; public string GetThemeName() @@ -200,20 +203,23 @@ namespace VocaluxeLib.Menu { if (_EditMode == EEditMode.ChangeOrder && _ChangeOrderSource != -1 && _PlaylistElements.Count > _ChangeOrderSource) { - CBase.Playlist.DeleteSong(ActivePlaylistID, _PlaylistElements[_ChangeOrderSource].Content); + CBase.Playlist.DeleteSong(ActivePlaylistId, _PlaylistElements[_ChangeOrderSource].Content); UpdatePlaylist(); } + _ChangeOrderSource = -1; _ChangeOrderElement = null; _EditMode = EEditMode.None; } else if (_CurrentPlaylistElement == -1 && _PlaylistElements.Count > 0) + { _SelectElement(_PlaylistElements[0].SelectSlide); + } } } private EEditMode _EditMode; - public int ActivePlaylistID = -1; + public int ActivePlaylistId = -1; private int _Offset; private int _CurrentPlaylistElement = -1; @@ -222,43 +228,43 @@ namespace VocaluxeLib.Menu private int _OldMousePosX; private int _OldMousePosY; - public int DragAndDropSongID = -1; + public int DragAndDropSongId = -1; //private static - public CPlaylist(int partyModeID) + public CPlaylist(int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; - _Text1 = new CText(_PartyModeID); - _StaticPlaylistFooter = new CStatic(_PartyModeID); - _StaticPlaylistHeader = new CStatic(_PartyModeID); - _ButtonPlaylistName = new CButton(_PartyModeID); - _ButtonPlaylistClose = new CButton(_PartyModeID); - _ButtonPlaylistDelete = new CButton(_PartyModeID); - _ButtonPlaylistSave = new CButton(_PartyModeID); - _ButtonPlaylistSing = new CButton(_PartyModeID); - _ButtonPlaylistList = new CButton(_PartyModeID); - _SelectSlideGameMode = new CSelectSlide(_PartyModeID); + _Text1 = new CText(_PartyModeId); + _StaticPlaylistFooter = new CStatic(_PartyModeId); + _StaticPlaylistHeader = new CStatic(_PartyModeId); + _ButtonPlaylistName = new CButton(_PartyModeId); + _ButtonPlaylistClose = new CButton(_PartyModeId); + _ButtonPlaylistDelete = new CButton(_PartyModeId); + _ButtonPlaylistSave = new CButton(_PartyModeId); + _ButtonPlaylistSing = new CButton(_PartyModeId); + _ButtonPlaylistList = new CButton(_PartyModeId); + _SelectSlideGameMode = new CSelectSlide(_PartyModeId); Visible = false; Selected = false; } - public CPlaylist(SThemePlaylist theme, int partyModeID) + public CPlaylist(SThemePlaylist theme, int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = theme; - _Text1 = new CText(_Theme.Text1, _PartyModeID); - _StaticPlaylistFooter = new CStatic(_Theme.StaticPlaylistFooter, _PartyModeID); - _StaticPlaylistHeader = new CStatic(_Theme.StaticPlaylistHeader, _PartyModeID); - _ButtonPlaylistName = new CButton(_Theme.ButtonPlaylistName, _PartyModeID); - _ButtonPlaylistClose = new CButton(_Theme.ButtonPlaylistClose, _PartyModeID); - _ButtonPlaylistDelete = new CButton(_Theme.ButtonPlaylistDelete, _PartyModeID); - _ButtonPlaylistSave = new CButton(_Theme.ButtonPlaylistSave, _PartyModeID); - _ButtonPlaylistSing = new CButton(_Theme.ButtonPlaylistSing, _PartyModeID); - _ButtonPlaylistList = new CButton(_Theme.ButtonPlaylistList, _PartyModeID); - _SelectSlideGameMode = new CSelectSlide(_Theme.SelectSlideGameMode, _PartyModeID); + _Text1 = new CText(_Theme.Text1, _PartyModeId); + _StaticPlaylistFooter = new CStatic(_Theme.StaticPlaylistFooter, _PartyModeId); + _StaticPlaylistHeader = new CStatic(_Theme.StaticPlaylistHeader, _PartyModeId); + _ButtonPlaylistName = new CButton(_Theme.ButtonPlaylistName, _PartyModeId); + _ButtonPlaylistClose = new CButton(_Theme.ButtonPlaylistClose, _PartyModeId); + _ButtonPlaylistDelete = new CButton(_Theme.ButtonPlaylistDelete, _PartyModeId); + _ButtonPlaylistSave = new CButton(_Theme.ButtonPlaylistSave, _PartyModeId); + _ButtonPlaylistSing = new CButton(_Theme.ButtonPlaylistSing, _PartyModeId); + _ButtonPlaylistList = new CButton(_Theme.ButtonPlaylistList, _PartyModeId); + _SelectSlideGameMode = new CSelectSlide(_Theme.SelectSlideGameMode, _PartyModeId); _AddStatic(_StaticPlaylistFooter); _AddStatic(_StaticPlaylistHeader); @@ -290,17 +296,20 @@ namespace VocaluxeLib.Menu public void UpdateGame() { if (_PlaylistElements.Count <= 0) + { LoadPlaylist(0); - for (int i = 0; i < _PlaylistElements.Count; i++) + } + + for (var i = 0; i < _PlaylistElements.Count; i++) { if (i == _CurrentPlaylistElement && _Selected) { - _PlaylistElements[i].Background.Texture = CBase.Themes.GetSkinTexture(_Theme.SkinBackgroundSelected, _PartyModeID); + _PlaylistElements[i].Background.Texture = CBase.Themes.GetSkinTexture(_Theme.SkinBackgroundSelected, _PartyModeId); _PlaylistElements[i].Background.Color = _BackgroundSelColor; } else { - _PlaylistElements[i].Background.Texture = CBase.Themes.GetSkinTexture(_Theme.SkinBackground, _PartyModeID); + _PlaylistElements[i].Background.Texture = CBase.Themes.GetSkinTexture(_Theme.SkinBackground, _PartyModeId); _PlaylistElements[i].Background.Color = _BackgroundColor; } } @@ -311,7 +320,9 @@ namespace VocaluxeLib.Menu base.Draw(); if (_ChangeOrderElement != null) + { _ChangeOrderElement.Draw(); + } } public bool IsMouseOver(SMouseEvent mouseEvent) @@ -338,8 +349,8 @@ namespace VocaluxeLib.Menu public void LoadSkin() { - _Theme.ColorBackground.Get(_PartyModeID, out _BackgroundColor); - _Theme.SelColorBackground.Get(_PartyModeID, out _BackgroundSelColor); + _Theme.ColorBackground.Get(_PartyModeId, out _BackgroundColor); + _Theme.SelColorBackground.Get(_PartyModeId, out _BackgroundSelColor); MaxRect = _Theme.Rect; @@ -370,51 +381,63 @@ namespace VocaluxeLib.Menu public override bool HandleInput(SKeyEvent keyEvent) { if (!Selected) + { return false; + } + //Active EditMode ignores other input! if (_EditMode == EEditMode.PlaylistName) { if (keyEvent.KeyPressed && !Char.IsControl(keyEvent.Unicode)) + { _ButtonPlaylistName.Text.Text = _ButtonPlaylistName.Text.Text + keyEvent.Unicode; + } else { switch (keyEvent.Key) { case Keys.Enter: - CBase.Playlist.SetName(ActivePlaylistID, _ButtonPlaylistName.Text.Text); - CBase.Playlist.Save(ActivePlaylistID); + CBase.Playlist.SetName(ActivePlaylistId, _ButtonPlaylistName.Text.Text); + CBase.Playlist.Save(ActivePlaylistId); _EditMode = EEditMode.None; _ButtonPlaylistName.EditMode = false; break; case Keys.Escape: - _ButtonPlaylistName.Text.Text = CBase.Playlist.GetName(ActivePlaylistID); + _ButtonPlaylistName.Text.Text = CBase.Playlist.GetName(ActivePlaylistId); _EditMode = EEditMode.None; _ButtonPlaylistName.EditMode = false; break; case Keys.Delete: case Keys.Back: - if (!String.IsNullOrEmpty(_ButtonPlaylistName.Text.Text)) + if (!string.IsNullOrEmpty(_ButtonPlaylistName.Text.Text)) + { _ButtonPlaylistName.Text.Text = _ButtonPlaylistName.Text.Text.Remove(_ButtonPlaylistName.Text.Text.Length - 1); + } + break; default: return false; } } + return true; } + if (_CurrentPlaylistElement == -1 || _PlaylistElementContents.Count == 0) { //no song is selected - bool handled = base.HandleInput(keyEvent); + var handled = base.HandleInput(keyEvent); _CurrentPlaylistElement = _GetSelectedElementNr(); if (_CurrentPlaylistElement != -1 || handled) + { return true; + } } else if (_CurrentPlaylistElement != -1) { //a song is selected - int scrollLimit = _PlaylistElements.Count / 2; + var scrollLimit = _PlaylistElements.Count / 2; //special actions if a song is selected switch (keyEvent.Key) @@ -444,12 +467,13 @@ namespace VocaluxeLib.Menu _CurrentPlaylistElement = _GetSelectedElementNr(); } } + break; case Keys.Down: if (keyEvent.ModShift) { - for (int i = _PlaylistElements.Count - 1; i >= 0; i--) + for (var i = _PlaylistElements.Count - 1; i >= 0; i--) { if (_PlaylistElements[i].SelectSlide.Visible) { @@ -477,22 +501,30 @@ namespace VocaluxeLib.Menu base.HandleInput(keyEvent); _CurrentPlaylistElement = _GetSelectedElementNr(); } + break; case Keys.Delete: - CBase.Playlist.DeleteSong(ActivePlaylistID, _PlaylistElements[_CurrentPlaylistElement].Content); + CBase.Playlist.DeleteSong(ActivePlaylistId, _PlaylistElements[_CurrentPlaylistElement].Content); UpdatePlaylist(); if (_Offset > 0) + { _Offset--; + } _Update(); if (_PlaylistElementContents.Count - 1 < _CurrentPlaylistElement) + { _CurrentPlaylistElement = _PlaylistElementContents.Count - 1; + } if (_CurrentPlaylistElement != -1) + { _SelectElement(_PlaylistElements[_CurrentPlaylistElement].SelectSlide); + } + break; case Keys.Back: @@ -506,10 +538,10 @@ namespace VocaluxeLib.Menu case Keys.Add: //move the selected song up if (_PlaylistElementContents.Count > 1 && (_CurrentPlaylistElement > 0 || _Offset > 0)) { - CBase.Playlist.MoveSongUp(ActivePlaylistID, _CurrentPlaylistElement + _Offset); + CBase.Playlist.MoveSongUp(ActivePlaylistId, _CurrentPlaylistElement + _Offset); UpdatePlaylist(); - var key = new SKeyEvent {Key = Keys.Up}; + var key = new SKeyEvent { Key = Keys.Up }; if (_CurrentPlaylistElement > scrollLimit) { @@ -530,15 +562,16 @@ namespace VocaluxeLib.Menu } } } + break; case Keys.Subtract: //move the selected song down if (_PlaylistElementContents.Count > 1 && _CurrentPlaylistElement + _Offset < _PlaylistElementContents.Count - 1) { - CBase.Playlist.MoveSongDown(ActivePlaylistID, _CurrentPlaylistElement + _Offset); + CBase.Playlist.MoveSongDown(ActivePlaylistId, _CurrentPlaylistElement + _Offset); UpdatePlaylist(); - var key = new SKeyEvent {Key = Keys.Down}; + var key = new SKeyEvent { Key = Keys.Down }; if (_CurrentPlaylistElement >= scrollLimit) { @@ -559,6 +592,7 @@ namespace VocaluxeLib.Menu _CurrentPlaylistElement = _GetSelectedElementNr(); } } + break; case Keys.PageUp: //scroll up @@ -567,11 +601,14 @@ namespace VocaluxeLib.Menu _Offset -= _PlaylistElements.Count; if (_Offset < 0) + { _Offset = 0; + } _Update(); _CurrentPlaylistElement = 0; } + break; case Keys.PageDown: //scroll down @@ -580,14 +617,18 @@ namespace VocaluxeLib.Menu _Offset += _PlaylistElements.Count; if (_Offset > _PlaylistElementContents.Count - _PlaylistElements.Count) + { _Offset = _PlaylistElementContents.Count - _PlaylistElements.Count; + } if (_Offset < 0) + { _Offset = 0; + } _Update(); - for (int i = _PlaylistElements.Count - 1; i >= 0; i--) + for (var i = _PlaylistElements.Count - 1; i >= 0; i--) { if (_PlaylistElements[i].SelectSlide.Visible) { @@ -596,6 +637,7 @@ namespace VocaluxeLib.Menu } } } + break; case Keys.Left: @@ -604,10 +646,11 @@ namespace VocaluxeLib.Menu if (_CurrentPlaylistElement != -1) { - CBase.Playlist.GetSong(ActivePlaylistID, _CurrentPlaylistElement + _Offset).GameMode = + CBase.Playlist.GetSong(ActivePlaylistId, _CurrentPlaylistElement + _Offset).GameMode = _PlaylistElementContents[_CurrentPlaylistElement + _Offset].Modes[_PlaylistElements[_CurrentPlaylistElement].SelectSlide.Selection]; UpdatePlaylist(); } + break; case Keys.Right: @@ -616,14 +659,16 @@ namespace VocaluxeLib.Menu if (_CurrentPlaylistElement != -1) { - CBase.Playlist.GetSong(ActivePlaylistID, _CurrentPlaylistElement + _Offset).GameMode = + CBase.Playlist.GetSong(ActivePlaylistId, _CurrentPlaylistElement + _Offset).GameMode = _PlaylistElementContents[_CurrentPlaylistElement + _Offset].Modes[_PlaylistElements[_CurrentPlaylistElement].SelectSlide.Selection]; UpdatePlaylist(); } + break; default: return false; } + return true; } @@ -638,21 +683,32 @@ namespace VocaluxeLib.Menu _ChangeOrderElement = null; } else + { ClosePlaylist(); + } + break; case Keys.Enter: if (_ButtonPlaylistClose.Selected) + { ClosePlaylist(); + } else if (_ButtonPlaylistSing.Selected) + { _StartPlaylistSongs(); + } else if (_ButtonPlaylistSave.Selected) - CBase.Playlist.Save(ActivePlaylistID); + { + CBase.Playlist.Save(ActivePlaylistId); + } else if (isButtonPlaylistListSelected()) + { return false; // Currently CScreenSong do this event! + } else if (_ButtonPlaylistDelete.Selected) { - CBase.Playlist.Delete(ActivePlaylistID); + CBase.Playlist.Delete(ActivePlaylistId); ClosePlaylist(); } else if (_ButtonPlaylistName.Selected) @@ -669,6 +725,7 @@ namespace VocaluxeLib.Menu _ButtonPlaylistName.EditMode = false; } } + break; case Keys.PageDown: _SetSelectionToLastEntry(); @@ -679,6 +736,7 @@ namespace VocaluxeLib.Menu default: return false; } + return true; } @@ -690,14 +748,16 @@ namespace VocaluxeLib.Menu private void _SetSelectionToLastEntry() { if (_PlaylistElementContents.Count == 0) + { return; + } - int off = _PlaylistElementContents.Count - _PlaylistElements.Count; + var off = _PlaylistElementContents.Count - _PlaylistElements.Count; _Offset = off >= 0 ? off : 0; _Update(); - for (int i = _PlaylistElements.Count - 1; i >= 0; i--) + for (var i = _PlaylistElements.Count - 1; i >= 0; i--) { if (_PlaylistElements[i].SelectSlide.Visible) { @@ -710,7 +770,9 @@ namespace VocaluxeLib.Menu private void _SetSelectionToFirstEntry() { if (_PlaylistElementContents.Count == 0) + { return; + } _Offset = 0; _Update(); @@ -720,20 +782,25 @@ namespace VocaluxeLib.Menu private int _GetSelectedElementNr() { - for (int i = 0; i < _PlaylistElements.Count; i++) + for (var i = 0; i < _PlaylistElements.Count; i++) { if (_PlaylistElements[i].SelectSlide.Selected) + { return i; + } } + return -1; } public void ScrollToBottom() { if (_PlaylistElementContents.Count == 0) + { return; + } - int off = _PlaylistElementContents.Count - _PlaylistElements.Count; + var off = _PlaylistElementContents.Count - _PlaylistElements.Count; _Offset = off >= 0 ? off : 0; _Update(); @@ -753,8 +820,10 @@ namespace VocaluxeLib.Menu _Offset += mouseEvent.Wheel; _Update(); } + return true; } + if (mouseEvent.Wheel < 0) { if (_Offset + mouseEvent.Wheel >= 0) @@ -762,11 +831,12 @@ namespace VocaluxeLib.Menu _Offset += mouseEvent.Wheel; _Update(); } + return true; } - bool hoverSet = false; - for (int i = 0; i < _PlaylistElements.Count; i++) + var hoverSet = false; + for (var i = 0; i < _PlaylistElements.Count; i++) { //Hover for playlist-element if (_PlaylistElementContents.Count - 1 >= i && CHelper.IsInBounds(_PlaylistElements[i].Background.Rect, mouseEvent)) @@ -780,51 +850,62 @@ namespace VocaluxeLib.Menu //Delete Entry with RB if (CHelper.IsInBounds(_PlaylistElements[i].Background.Rect, mouseEvent) && mouseEvent.RB && _PlaylistElements[i].Content != -1) { - CBase.Playlist.DeleteSong(ActivePlaylistID, _PlaylistElements[i].Content); + CBase.Playlist.DeleteSong(ActivePlaylistId, _PlaylistElements[i].Content); UpdatePlaylist(); return true; } } + if (!hoverSet) + { _CurrentPlaylistElement = -1; + } switch (_EditMode) { - //Normal mode + //Normal mode case EEditMode.None: //LB actions if (mouseEvent.LB) { if (isButtonPlaylistListSelected()) + { return false; // Currently CScreenSong do this event! + } + if (_CurrentPlaylistElement != -1) { - CBase.Playlist.GetSong(ActivePlaylistID, _CurrentPlaylistElement + _Offset).GameMode = + CBase.Playlist.GetSong(ActivePlaylistId, _CurrentPlaylistElement + _Offset).GameMode = _PlaylistElementContents[_CurrentPlaylistElement + _Offset].Modes[_PlaylistElements[_CurrentPlaylistElement].SelectSlide.Selection]; UpdatePlaylist(); } + if (_ButtonPlaylistClose.Selected) { ClosePlaylist(); return true; } + if (_ButtonPlaylistSing.Selected) { _StartPlaylistSongs(); return true; } + if (_ButtonPlaylistSave.Selected) { - CBase.Playlist.Save(ActivePlaylistID); + CBase.Playlist.Save(ActivePlaylistId); return true; } + if (_ButtonPlaylistDelete.Selected) { - CBase.Playlist.Delete(ActivePlaylistID); + CBase.Playlist.Delete(ActivePlaylistId); ClosePlaylist(); return true; } + if (_ButtonPlaylistName.Selected) { _EditMode = EEditMode.PlaylistName; @@ -835,26 +916,30 @@ namespace VocaluxeLib.Menu //Start selected song with double click if (mouseEvent.LD && _CurrentPlaylistElement != -1) + { _StartPlaylistSong(_CurrentPlaylistElement + _Offset); + } //Change order with holding LB - if (mouseEvent.LBH && _CurrentPlaylistElement != -1 && _PlaylistElementContents.Count > 0 && DragAndDropSongID == -1) + if (mouseEvent.LBH && _CurrentPlaylistElement != -1 && _PlaylistElementContents.Count > 0 && DragAndDropSongId == -1) { _ChangeOrderSource = _CurrentPlaylistElement + _Offset; //Update of Drag/Drop-Texture if (_ChangeOrderSource >= _PlaylistElementContents.Count) + { return true; + } _ChangeOrderElement = new CPlaylistElement(_PlaylistElements[_CurrentPlaylistElement]) - { - Background = {Z = CBase.Settings.GetZNear()}, - Cover = {Z = CBase.Settings.GetZNear()}, - SelectSlide = {Z = CBase.Settings.GetZNear()}, - Text1 = {Z = CBase.Settings.GetZNear()} - }; + { + Background = { Z = CBase.Settings.GetZNear() }, + Cover = { Z = CBase.Settings.GetZNear() }, + SelectSlide = { Z = CBase.Settings.GetZNear() }, + Text1 = { Z = CBase.Settings.GetZNear() } + }; - _ChangeOrderElement.Background.Texture = CBase.Themes.GetSkinTexture(_Theme.SkinBackground, _PartyModeID); + _ChangeOrderElement.Background.Texture = CBase.Themes.GetSkinTexture(_Theme.SkinBackground, _PartyModeId); _ChangeOrderElement.Background.Color = _BackgroundColor; _OldMousePosX = mouseEvent.X; @@ -863,34 +948,36 @@ namespace VocaluxeLib.Menu _EditMode = EEditMode.ChangeOrder; } - if (!mouseEvent.LBH && DragAndDropSongID != -1) + if (!mouseEvent.LBH && DragAndDropSongId != -1) { - CSong song = CBase.Songs.GetSongByID(DragAndDropSongID); + var song = CBase.Songs.GetSongById(DragAndDropSongId); if (song != null) { var gm = EGameMode.TR_GAMEMODE_NORMAL; if (song.IsDuet) + { gm = EGameMode.TR_GAMEMODE_DUET; + } if (_CurrentPlaylistElement != -1) { - CBase.Playlist.InsertSong(ActivePlaylistID, _CurrentPlaylistElement + _Offset, DragAndDropSongID, gm); + CBase.Playlist.InsertSong(ActivePlaylistId, _CurrentPlaylistElement + _Offset, DragAndDropSongId, gm); UpdatePlaylist(); } else { if (mouseEvent.Y < _PlaylistElements[0].Background.Rect.Y && _Offset == 0) { - CBase.Playlist.InsertSong(ActivePlaylistID, 0, DragAndDropSongID, gm); + CBase.Playlist.InsertSong(ActivePlaylistId, 0, DragAndDropSongId, gm); UpdatePlaylist(); } else { if (_PlaylistElements.Count + _Offset >= _PlaylistElementContents.Count) { - float min = 0f; - for (int i = _PlaylistElements.Count - 1; i >= 0; i--) + var min = 0f; + for (var i = _PlaylistElements.Count - 1; i >= 0; i--) { if (_PlaylistElements[i].SelectSlide.Visible) { @@ -901,13 +988,14 @@ namespace VocaluxeLib.Menu if (mouseEvent.Y > min) { - CBase.Playlist.AddSong(ActivePlaylistID, DragAndDropSongID, gm); + CBase.Playlist.AddSong(ActivePlaylistId, DragAndDropSongId, gm); UpdatePlaylist(); ScrollToBottom(); } } } - DragAndDropSongID = -1; + + DragAndDropSongId = -1; UpdatePlaylist(); } } @@ -922,8 +1010,8 @@ namespace VocaluxeLib.Menu { if (_ButtonPlaylistName.Selected) { - CBase.Playlist.SetName(ActivePlaylistID, _ButtonPlaylistName.Text.Text); - CBase.Playlist.Save(ActivePlaylistID); + CBase.Playlist.SetName(ActivePlaylistId, _ButtonPlaylistName.Text.Text); + CBase.Playlist.Save(ActivePlaylistId); _EditMode = EEditMode.None; return true; } @@ -932,12 +1020,13 @@ namespace VocaluxeLib.Menu { if (_ButtonPlaylistName.Selected) { - _ButtonPlaylistName.Text.Text = CBase.Playlist.GetName(ActivePlaylistID); + _ButtonPlaylistName.Text.Text = CBase.Playlist.GetName(ActivePlaylistId); _EditMode = EEditMode.None; _ButtonPlaylistName.EditMode = false; return true; } } + break; case EEditMode.ChangeOrder: @@ -952,19 +1041,21 @@ namespace VocaluxeLib.Menu { if (_CurrentPlaylistElement != -1 && _CurrentPlaylistElement + _Offset != _ChangeOrderSource) { - CBase.Playlist.MoveSong(ActivePlaylistID, _ChangeOrderSource, _CurrentPlaylistElement + _Offset); + CBase.Playlist.MoveSong(ActivePlaylistId, _ChangeOrderSource, _CurrentPlaylistElement + _Offset); UpdatePlaylist(); } else if (_CurrentPlaylistElement == -1) { if (mouseEvent.Y < _PlaylistElements[0].Background.Rect.Y && _Offset == 0) - CBase.Playlist.MoveSong(ActivePlaylistID, _ChangeOrderSource, 0); + { + CBase.Playlist.MoveSong(ActivePlaylistId, _ChangeOrderSource, 0); + } else { if (_PlaylistElements.Count + _Offset >= _PlaylistElementContents.Count) { - float min = 0f; - for (int i = _PlaylistElements.Count - 1; i >= 0; i--) + var min = 0f; + for (var i = _PlaylistElements.Count - 1; i >= 0; i--) { if (_PlaylistElements[i].SelectSlide.Visible) { @@ -974,18 +1065,23 @@ namespace VocaluxeLib.Menu } if (mouseEvent.Y > min) - CBase.Playlist.MoveSong(ActivePlaylistID, _ChangeOrderSource, _PlaylistElementContents.Count - 1); + { + CBase.Playlist.MoveSong(ActivePlaylistId, _ChangeOrderSource, _PlaylistElementContents.Count - 1); + } } } UpdatePlaylist(); } + _EditMode = EEditMode.None; _ChangeOrderElement = null; } + break; } } + return false; } @@ -998,27 +1094,27 @@ namespace VocaluxeLib.Menu { _PlaylistElements.Clear(); - for (int i = 0; i < Math.Floor(_Theme.Rect.H / _Theme.EntryHeight); i++) + for (var i = 0; i < Math.Floor(_Theme.Rect.H / _Theme.EntryHeight); i++) { var en = new CPlaylistElement - { - Background = new CStatic(_PartyModeID, _Theme.SkinBackground, _BackgroundColor, - new SRectF(_Theme.Rect.X, _Theme.Rect.Y + (i * _Theme.EntryHeight), _Theme.Rect.W, _Theme.EntryHeight, _Theme.Rect.Z)), - Cover = new CStatic(_Theme.StaticCover, _PartyModeID) - }; + { + Background = new CStatic(_PartyModeId, _Theme.SkinBackground, _BackgroundColor, + new SRectF(_Theme.Rect.X, _Theme.Rect.Y + i * _Theme.EntryHeight, _Theme.Rect.W, _Theme.EntryHeight, _Theme.Rect.Z)), + Cover = new CStatic(_Theme.StaticCover, _PartyModeId) + }; en.Cover.LoadSkin(); - en.Cover.Y += _Theme.Rect.Y + (i * _Theme.EntryHeight); + en.Cover.Y += _Theme.Rect.Y + i * _Theme.EntryHeight; en.Cover.X += _Theme.Rect.X; en.Text1 = new CText(_Text1); en.Text1.X += _Theme.Rect.X; - en.Text1.Y += _Theme.Rect.Y + (i * _Theme.EntryHeight); + en.Text1.Y += _Theme.Rect.Y + i * _Theme.EntryHeight; en.SelectSlide = new CSelectSlide(_SelectSlideGameMode); en.SelectSlide.LoadSkin(); en.SelectSlide.X += _Theme.Rect.X; - en.SelectSlide.Y += _Theme.Rect.Y + (i * _Theme.EntryHeight); + en.SelectSlide.Y += _Theme.Rect.Y + i * _Theme.EntryHeight; en.Content = -1; @@ -1030,23 +1126,27 @@ namespace VocaluxeLib.Menu } } - public bool LoadPlaylist(int playlistID) + public bool LoadPlaylist(int playlistId) { - if (!CBase.Playlist.Exists(playlistID)) + if (!CBase.Playlist.Exists(playlistId)) + { return false; - ActivePlaylistID = playlistID; - _ButtonPlaylistName.Text.Text = CBase.Playlist.GetName(ActivePlaylistID); + } + + ActivePlaylistId = playlistId; + _ButtonPlaylistName.Text.Text = CBase.Playlist.GetName(ActivePlaylistId); _PlaylistElementContents.Clear(); - for (int i = 0; i < CBase.Playlist.GetSongCount(ActivePlaylistID); i++) + for (var i = 0; i < CBase.Playlist.GetSongCount(ActivePlaylistId); i++) { var pec = new CPlaylistElementContent - { - SongID = CBase.Playlist.GetSong(ActivePlaylistID, i).SongID, - Modes = CBase.Songs.GetSongByID(CBase.Playlist.GetSong(ActivePlaylistID, i).SongID).AvailableGameModes, - Mode = CBase.Playlist.GetSong(ActivePlaylistID, i).GameMode - }; + { + SongId = CBase.Playlist.GetSong(ActivePlaylistId, i).SongId, + Modes = CBase.Songs.GetSongById(CBase.Playlist.GetSong(ActivePlaylistId, i).SongId).AvailableGameModes, + Mode = CBase.Playlist.GetSong(ActivePlaylistId, i).GameMode + }; _PlaylistElementContents.Add(pec); } + _SetSelectionToFirstEntry(); _Update(); return true; @@ -1055,11 +1155,11 @@ namespace VocaluxeLib.Menu public void UpdatePlaylist() { _PlaylistElementContents.Clear(); - for (int i = 0; i < CBase.Playlist.GetSongCount(ActivePlaylistID); i++) + for (var i = 0; i < CBase.Playlist.GetSongCount(ActivePlaylistId); i++) { - var pec = new CPlaylistElementContent {SongID = CBase.Playlist.GetSong(ActivePlaylistID, i).SongID}; - pec.Modes = CBase.Songs.GetSongByID(pec.SongID).AvailableGameModes; - pec.Mode = CBase.Playlist.GetSong(ActivePlaylistID, i).GameMode; + var pec = new CPlaylistElementContent { SongId = CBase.Playlist.GetSong(ActivePlaylistId, i).SongId }; + pec.Modes = CBase.Songs.GetSongById(pec.SongId).AvailableGameModes; + pec.Mode = CBase.Playlist.GetSong(ActivePlaylistId, i).GameMode; _PlaylistElementContents.Add(pec); } @@ -1070,7 +1170,7 @@ namespace VocaluxeLib.Menu { Visible = false; Selected = false; - ActivePlaylistID = -1; + ActivePlaylistId = -1; } private void _StartPlaylistSongs() @@ -1079,12 +1179,17 @@ namespace VocaluxeLib.Menu CBase.Game.Reset(); CBase.Game.ClearSongs(); - if (CBase.Playlist.Exists(ActivePlaylistID)) + if (CBase.Playlist.Exists(ActivePlaylistId)) { - for (int i = 0; i < CBase.Playlist.GetSongCount(ActivePlaylistID); i++) - CBase.Game.AddSong(CBase.Playlist.GetSong(ActivePlaylistID, i).SongID, CBase.Playlist.GetSong(ActivePlaylistID, i).GameMode); + for (var i = 0; i < CBase.Playlist.GetSongCount(ActivePlaylistId); i++) + { + CBase.Game.AddSong(CBase.Playlist.GetSong(ActivePlaylistId, i).SongId, CBase.Playlist.GetSong(ActivePlaylistId, i).GameMode); + } + if (CBase.Game.GetNumSongs() > 0) + { CBase.Graphics.FadeTo(EScreen.Names); + } } } @@ -1093,17 +1198,22 @@ namespace VocaluxeLib.Menu CBase.Game.Reset(); CBase.Game.ClearSongs(); - CBase.Game.AddSong(CBase.Playlist.GetSong(ActivePlaylistID, selected).SongID, CBase.Playlist.GetSong(ActivePlaylistID, selected).GameMode); + CBase.Game.AddSong(CBase.Playlist.GetSong(ActivePlaylistId, selected).SongId, CBase.Playlist.GetSong(ActivePlaylistId, selected).GameMode); if (CBase.Game.GetNumSongs() > 0) + { CBase.Graphics.FadeTo(EScreen.Names); + } } private void _Update() { - if (!CBase.Playlist.Exists(ActivePlaylistID)) + if (!CBase.Playlist.Exists(ActivePlaylistId)) + { return; - for (int i = 0; i < _PlaylistElements.Count; i++) + } + + for (var i = 0; i < _PlaylistElements.Count; i++) { if (_Offset + i < _PlaylistElementContents.Count) { @@ -1112,14 +1222,17 @@ namespace VocaluxeLib.Menu _PlaylistElements[i].Cover.Visible = true; _PlaylistElements[i].SelectSlide.Visible = true; _PlaylistElements[i].Text1.Visible = true; - CPlaylistElementContent pec = _PlaylistElementContents[_Offset + i]; - CSong song = CBase.Songs.GetSongByID(pec.SongID); + var pec = _PlaylistElementContents[_Offset + i]; + var song = CBase.Songs.GetSongById(pec.SongId); _PlaylistElements[i].Cover.Texture = song.CoverTextureSmall; - string t1 = CBase.Language.Translate(_Text1.Text).Replace("%a", song.Artist).Replace("%t", song.Title); + var t1 = CBase.Language.Translate(_Text1.Text).Replace("%a", song.Artist).Replace("%t", song.Title); _PlaylistElements[i].Text1.Text = /*(Offset + i + 1) + ") " + */ t1; //TODO: Add text field for the number _PlaylistElements[i].SelectSlide.Clear(); - foreach (EGameMode gm in pec.Modes) + foreach (var gm in pec.Modes) + { _PlaylistElements[i].SelectSlide.AddValue(Enum.GetName(typeof(EGameMode), gm), null, (int)gm); + } + _PlaylistElements[i].SelectSlide.SelectedTag = (int)pec.Mode; } else @@ -1145,64 +1258,135 @@ namespace VocaluxeLib.Menu _CompleteRect = _Theme.Rect; //ButtonPlaylistClose if (_ButtonPlaylistClose.Rect.X < _CompleteRect.X) + { _CompleteRect.X = _ButtonPlaylistClose.Rect.X; + } + if (_ButtonPlaylistClose.Rect.Y < _CompleteRect.Y) + { _CompleteRect.Y = _ButtonPlaylistClose.Rect.Y; + } + if (_ButtonPlaylistClose.Rect.W + _ButtonPlaylistClose.Rect.X > _CompleteRect.W + _CompleteRect.X) + { _CompleteRect.W = _ButtonPlaylistClose.Rect.W + _ButtonPlaylistClose.Rect.X - _CompleteRect.X; + } + if (_ButtonPlaylistClose.Rect.Y + _ButtonPlaylistClose.Rect.H > _CompleteRect.Y + _CompleteRect.H) + { _CompleteRect.H = _ButtonPlaylistClose.Rect.H + _ButtonPlaylistClose.Rect.Y - _CompleteRect.Y; + } + //ButtonPlaylistName if (_ButtonPlaylistName.Rect.X < _CompleteRect.X) + { _CompleteRect.X = _ButtonPlaylistName.Rect.X; + } + if (_ButtonPlaylistName.Rect.Y < _CompleteRect.Y) + { _CompleteRect.Y = _ButtonPlaylistName.Rect.Y; + } + if (_ButtonPlaylistName.Rect.W + _ButtonPlaylistName.Rect.X > _CompleteRect.W + _CompleteRect.X) + { _CompleteRect.W = _ButtonPlaylistName.Rect.W + _ButtonPlaylistName.Rect.X - _CompleteRect.X; + } + if (_ButtonPlaylistName.Rect.Y + _ButtonPlaylistName.Rect.H > _CompleteRect.Y + _CompleteRect.H) + { _CompleteRect.H = _ButtonPlaylistName.Rect.H + _ButtonPlaylistName.Rect.Y - _CompleteRect.Y; + } + //ButtonPlaylistSing if (_ButtonPlaylistSing.Rect.X < _CompleteRect.X) + { _CompleteRect.X = _ButtonPlaylistSing.Rect.X; + } + if (_ButtonPlaylistSing.Rect.Y < _CompleteRect.Y) + { _CompleteRect.Y = _ButtonPlaylistSing.Rect.Y; + } + if (_ButtonPlaylistSing.Rect.W + _ButtonPlaylistSing.Rect.X > _CompleteRect.W + _CompleteRect.X) + { _CompleteRect.W = _ButtonPlaylistSing.Rect.W + _ButtonPlaylistSing.Rect.X - _CompleteRect.X; + } + if (_ButtonPlaylistSing.Rect.Y + _ButtonPlaylistSing.Rect.H > _CompleteRect.Y + _CompleteRect.H) + { _CompleteRect.H = _ButtonPlaylistSing.Rect.H + _ButtonPlaylistSing.Rect.Y - _CompleteRect.Y; + } + //ButtonPlaylistSave if (_ButtonPlaylistSave.Rect.X < _CompleteRect.X) + { _CompleteRect.X = _ButtonPlaylistSave.Rect.X; + } + if (_ButtonPlaylistSave.Rect.Y < _CompleteRect.Y) + { _CompleteRect.Y = _ButtonPlaylistSave.Rect.Y; + } + if (_ButtonPlaylistSave.Rect.W + _ButtonPlaylistSave.Rect.X > _CompleteRect.W + _CompleteRect.X) + { _CompleteRect.W = _ButtonPlaylistSave.Rect.W + _ButtonPlaylistSave.Rect.X - _CompleteRect.X; + } + if (_ButtonPlaylistSave.Rect.Y + _ButtonPlaylistSave.Rect.H > _CompleteRect.Y + _CompleteRect.H) + { _CompleteRect.H = _ButtonPlaylistSave.Rect.H + _ButtonPlaylistSave.Rect.Y - _CompleteRect.Y; + } + //ButtonPlaylistDelete if (_ButtonPlaylistDelete.Rect.X < _CompleteRect.X) + { _CompleteRect.X = _ButtonPlaylistDelete.Rect.X; + } + if (_ButtonPlaylistDelete.Rect.Y < _CompleteRect.Y) + { _CompleteRect.Y = _ButtonPlaylistDelete.Rect.Y; + } + if (_ButtonPlaylistDelete.Rect.W + _ButtonPlaylistDelete.Rect.X > _CompleteRect.W + _CompleteRect.X) + { _CompleteRect.W = _ButtonPlaylistDelete.Rect.W + _ButtonPlaylistDelete.Rect.X - _CompleteRect.X; + } + if (_ButtonPlaylistDelete.Rect.Y + _ButtonPlaylistDelete.Rect.H > _CompleteRect.Y + _CompleteRect.H) + { _CompleteRect.H = _ButtonPlaylistDelete.Rect.H + _ButtonPlaylistDelete.Rect.Y - _CompleteRect.Y; + } + //ButtonPlaylistList if (_ButtonPlaylistList.Rect.X < _CompleteRect.X) + { _CompleteRect.X = _ButtonPlaylistList.Rect.X; + } + if (_ButtonPlaylistList.Rect.Y < _CompleteRect.Y) + { _CompleteRect.Y = _ButtonPlaylistList.Rect.Y; + } + if (_ButtonPlaylistList.Rect.W + _ButtonPlaylistList.Rect.X > _CompleteRect.W + _CompleteRect.X) + { _CompleteRect.W = _ButtonPlaylistList.Rect.W + _ButtonPlaylistList.Rect.X - _CompleteRect.X; + } + if (_ButtonPlaylistList.Rect.Y + _ButtonPlaylistList.Rect.H > _CompleteRect.Y + _CompleteRect.H) + { _CompleteRect.H = _ButtonPlaylistList.Rect.H + _ButtonPlaylistList.Rect.Y - _CompleteRect.Y; + } } #region ThemeEdit public void MoveElement(int stepX, int stepY) { - SRectF rect = MaxRect; + var rect = MaxRect; rect.X += stepX; rect.Y += stepY; MaxRect = rect; @@ -1213,14 +1397,19 @@ namespace VocaluxeLib.Menu public void ResizeElement(int stepW, int stepH) { - SRectF rect = MaxRect; + var rect = MaxRect; rect.W += stepW; if (rect.W <= 0) + { rect.W = 1; + } rect.H += stepH; if (rect.H <= 0) + { rect.H = 1; + } + MaxRect = rect; _Theme.Rect.W = Rect.W; @@ -1228,4 +1417,4 @@ namespace VocaluxeLib.Menu } #endregion ThemeEdit } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Menu/CProgressBar.cs b/VocaluxeLib/Menu/CProgressBar.cs index b95826b3..6108ee83 100644 --- a/VocaluxeLib/Menu/CProgressBar.cs +++ b/VocaluxeLib/Menu/CProgressBar.cs @@ -20,7 +20,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Xml.Serialization; using VocaluxeLib.Draw; -using VocaluxeLib.Xml; namespace VocaluxeLib.Menu { @@ -34,7 +33,8 @@ namespace VocaluxeLib.Menu [XmlType("ProgressBar")] public struct SThemeProgressBar { - [XmlAttribute(AttributeName = "Name")] public string Name; + [XmlAttribute(AttributeName = "Name")] + public string Name; public string SkinBackground; public string SkinForeground; public string SkinProgressLeft; @@ -46,14 +46,15 @@ namespace VocaluxeLib.Menu public EOffOn AnimateMovement; public EOffOn AnimateColoring; public SRectF Rect; - [XmlArrayItem("ProgressColor"), XmlArray] public List ProgressColors; + [XmlArrayItem("ProgressColor"), XmlArray] + public List ProgressColors; public SReflection? Reflection; public bool? AllMonitors; } public sealed class CProgressBar : CMenuElementBase, IMenuElement, IThemeable { - private readonly int _PartyModeID; + private readonly int _PartyModeId; private SThemeProgressBar _Theme; @@ -72,7 +73,7 @@ namespace VocaluxeLib.Menu private CTextureRef _TextureBackground; public CTextureRef TextureBackground { - get { return _TextureBackground ?? CBase.Themes.GetSkinTexture(_Theme.SkinBackground, _PartyModeID); } + get { return _TextureBackground ?? CBase.Themes.GetSkinTexture(_Theme.SkinBackground, _PartyModeId); } set { _TextureBackground = value; } } @@ -80,7 +81,7 @@ namespace VocaluxeLib.Menu private CTextureRef _TextureForeground; public CTextureRef TextureForeground { - get { return _TextureForeground ?? CBase.Themes.GetSkinTexture(_Theme.SkinForeground, _PartyModeID); } + get { return _TextureForeground ?? CBase.Themes.GetSkinTexture(_Theme.SkinForeground, _PartyModeId); } set { _TextureForeground = value; } } @@ -88,7 +89,7 @@ namespace VocaluxeLib.Menu private CTextureRef _TextureProgressLeft; public CTextureRef TextureProgressLeft { - get { return _TextureProgressLeft ?? CBase.Themes.GetSkinTexture(_Theme.SkinProgressLeft, _PartyModeID); } + get { return _TextureProgressLeft ?? CBase.Themes.GetSkinTexture(_Theme.SkinProgressLeft, _PartyModeId); } set { _TextureProgressLeft = value; } } @@ -96,7 +97,7 @@ namespace VocaluxeLib.Menu private CTextureRef _TextureProgressMid; public CTextureRef TextureProgressMid { - get { return _TextureProgressMid ?? CBase.Themes.GetSkinTexture(_Theme.SkinProgressMid, _PartyModeID); } + get { return _TextureProgressMid ?? CBase.Themes.GetSkinTexture(_Theme.SkinProgressMid, _PartyModeId); } set { _TextureProgressMid = value; } } @@ -104,7 +105,7 @@ namespace VocaluxeLib.Menu private CTextureRef _TextureProgressRight; public CTextureRef TextureProgressRight { - get { return _TextureProgressRight ?? CBase.Themes.GetSkinTexture(_Theme.SkinProgressRight, _PartyModeID); } + get { return _TextureProgressRight ?? CBase.Themes.GetSkinTexture(_Theme.SkinProgressRight, _PartyModeId); } set { _TextureProgressRight = value; } } @@ -134,11 +135,12 @@ namespace VocaluxeLib.Menu _ProgressLast = 0; _AnimTimer.Reset(); //Animation is still running, so use current state for calculations - if(_ProgressCurrent != _ProgressTarget) + if (_ProgressCurrent != _ProgressTarget) { _ProgressLast = _ProgressCurrent; _ColorProgressLast = _ColorProgressCurrent; } + _ProgressTarget = value; } } @@ -160,15 +162,15 @@ namespace VocaluxeLib.Menu private float _AnimDuration; private bool _Animate; - public CProgressBar(int partyModeID) + public CProgressBar(int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _AnimTimer = new Stopwatch(); } public CProgressBar(CProgressBar pb) { - _PartyModeID = pb._PartyModeID; + _PartyModeId = pb._PartyModeId; _TextureBackground = pb.TextureBackground; _TextureForeground = pb.TextureForeground; @@ -196,9 +198,9 @@ namespace VocaluxeLib.Menu _AnimTimer = new Stopwatch(); } - public CProgressBar(SThemeProgressBar theme, int partyModeID) + public CProgressBar(SThemeProgressBar theme, int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = theme; _Theme.ProgressColors.Sort((x, y) => x.From.CompareTo(y.From)); _ProgressColors = _Theme.ProgressColors; @@ -220,7 +222,7 @@ namespace VocaluxeLib.Menu _ProgressLast = 0f; _ProgressTarget = 0f; - _ProgressColors[0].Color.Get(_PartyModeID, out _ColorProgressLast); + _ProgressColors[0].Color.Get(_PartyModeId, out _ColorProgressLast); _AnimTimer.Reset(); _AnimDuration = 0f; @@ -234,19 +236,23 @@ namespace VocaluxeLib.Menu public void Draw(float scale = 1f, float zModify = 0f, bool forceDraw = false) { if (scale <= 0) + { return; + } - if (Visible || forceDraw || (CBase.Settings.GetProgramState() == EProgramState.EditTheme)) + if (Visible || forceDraw || CBase.Settings.GetProgramState() == EProgramState.EditTheme) { _UpdateProgress(); //Draw background - SColorF color = new SColorF(ColorBackground.R, ColorBackground.G, ColorBackground.B, ColorBackground.A * Alpha); + var color = new SColorF(ColorBackground.R, ColorBackground.G, ColorBackground.B, ColorBackground.A * Alpha); if (_TextureBackground != null) { CBase.Drawing.DrawTexture(_TextureBackground, Rect, color, AllMonitors); if (Reflection) + { CBase.Drawing.DrawTextureReflection(_TextureBackground, Rect, color, Rect, ReflectionSpace, ReflectionHeight, AllMonitors); + } } //Draw progress @@ -255,23 +261,31 @@ namespace VocaluxeLib.Menu { CBase.Drawing.DrawTexture(_TextureProgressBegin, _RectProgressBegin, color, AllMonitors); if (Reflection) + { CBase.Drawing.DrawTextureReflection(_TextureProgressBegin, _RectProgressBegin, color, _RectProgressBegin, ReflectionSpace, ReflectionHeight, AllMonitors); + } } if (_TextureProgressMid != null) { CBase.Drawing.DrawTexture(_TextureProgressMid, _RectProgressMid, color, AllMonitors); if (Reflection) + { CBase.Drawing.DrawTextureReflection(_TextureProgressMid, _RectProgressMid, color, _RectProgressMid, ReflectionSpace, ReflectionHeight, AllMonitors); + } } else + { CBase.Drawing.DrawRect(_ColorProgressCurrent, _RectProgressMid); + } if (_TextureProgressEnd != null) { CBase.Drawing.DrawTexture(_TextureProgressEnd, _RectProgressEnd, color, AllMonitors); if (Reflection) + { CBase.Drawing.DrawTextureReflection(_TextureProgressEnd, _RectProgressEnd, color, _RectProgressEnd, ReflectionSpace, ReflectionHeight, AllMonitors); + } } //Draw foreground @@ -280,28 +294,35 @@ namespace VocaluxeLib.Menu { CBase.Drawing.DrawTexture(_TextureForeground, Rect, color, AllMonitors); if (Reflection) + { CBase.Drawing.DrawTextureReflection(_TextureForeground, Rect, color, Rect, ReflectionSpace, ReflectionHeight, AllMonitors); + } } } - if (Selected && (CBase.Settings.GetProgramState() == EProgramState.EditTheme)) + if (Selected && CBase.Settings.GetProgramState() == EProgramState.EditTheme) + { CBase.Drawing.DrawRect(new SColorF(1f, 1f, 1f, 0.5f), Rect); + } } - public void UnloadSkin() {} + public void UnloadSkin() { } public void LoadSkin() { if (!ThemeLoaded) + { return; - _Theme.ColorBackground.Get(_PartyModeID, out ColorBackground); - _Theme.ColorForeground.Get(_PartyModeID, out ColorForeground); + } - TextureBackground = CBase.Themes.GetSkinTexture(_Theme.SkinBackground, _PartyModeID); - TextureForeground = CBase.Themes.GetSkinTexture(_Theme.SkinForeground, _PartyModeID); - TextureProgressLeft = CBase.Themes.GetSkinTexture(_Theme.SkinProgressLeft, _PartyModeID); - TextureProgressMid = CBase.Themes.GetSkinTexture(_Theme.SkinProgressMid, _PartyModeID); - TextureProgressRight = CBase.Themes.GetSkinTexture(_Theme.SkinProgressRight, _PartyModeID); + _Theme.ColorBackground.Get(_PartyModeId, out ColorBackground); + _Theme.ColorForeground.Get(_PartyModeId, out ColorForeground); + + TextureBackground = CBase.Themes.GetSkinTexture(_Theme.SkinBackground, _PartyModeId); + TextureForeground = CBase.Themes.GetSkinTexture(_Theme.SkinForeground, _PartyModeId); + TextureProgressLeft = CBase.Themes.GetSkinTexture(_Theme.SkinProgressLeft, _PartyModeId); + TextureProgressMid = CBase.Themes.GetSkinTexture(_Theme.SkinProgressMid, _PartyModeId); + TextureProgressRight = CBase.Themes.GetSkinTexture(_Theme.SkinProgressRight, _PartyModeId); MaxRect = _Theme.Rect; Reflection = _Theme.Reflection.HasValue; @@ -327,12 +348,18 @@ namespace VocaluxeLib.Menu private void _UpdateProgress() { if (_ProgressCurrent == _ProgressTarget) + { return; + } if (_Animate) + { _CheckAnimation(); + } else + { _ProgressCurrent = _ProgressLast = _ProgressTarget; + } _UpdateProgressColor(); @@ -351,14 +378,21 @@ namespace VocaluxeLib.Menu _AnimTimer.Restart(); //Calc animation duration in ms based on rect size and progress change if (_Direction == EDirection.Left || _Direction == EDirection.Right) - _AnimDuration = Math.Max(100f, (Rect.W * 0.015f * 1000) * Math.Abs(_ProgressTarget - _ProgressCurrent) * 0.6f); + { + _AnimDuration = Math.Max(100f, Rect.W * 0.015f * 1000 * Math.Abs(_ProgressTarget - _ProgressCurrent) * 0.6f); + } else - _AnimDuration = Math.Max(100f, (Rect.H * 0.015f * 1000) * Math.Abs(_ProgressTarget - _ProgressCurrent) * 0.6f); - } + { + _AnimDuration = Math.Max(100f, Rect.H * 0.015f * 1000 * Math.Abs(_ProgressTarget - _ProgressCurrent) * 0.6f); + } + } } + //Movement animation if (_AnimateMovement == EOffOn.TR_CONFIG_ON) + { _ProgressCurrent = _ProgressLast + (_AnimTimer.ElapsedMilliseconds / _AnimDuration).Clamp(0, 1) * (_ProgressTarget - _ProgressLast); + } //Check if animation needs to be stopped if (_ProgressCurrent == _ProgressTarget) @@ -374,13 +408,17 @@ namespace VocaluxeLib.Menu private void _UpdateProgressColor() { - foreach (SThemeProgressBarColor col in _ProgressColors) - if (col.From < _ProgressTarget) - col.Color.Get(_PartyModeID, out _ColorProgressTarget); - - if(_Animate && _AnimateColoring == EOffOn.TR_CONFIG_ON) + foreach (var col in _ProgressColors) { - float animFactor = (_AnimTimer.ElapsedMilliseconds / _AnimDuration).Clamp(0, 1); + if (col.From < _ProgressTarget) + { + col.Color.Get(_PartyModeId, out _ColorProgressTarget); + } + } + + if (_Animate && _AnimateColoring == EOffOn.TR_CONFIG_ON) + { + var animFactor = (_AnimTimer.ElapsedMilliseconds / _AnimDuration).Clamp(0, 1); _ColorProgressCurrent.R = _ColorProgressLast.R + animFactor * (_ColorProgressTarget.R - _ColorProgressLast.R); _ColorProgressCurrent.G = _ColorProgressLast.G + animFactor * (_ColorProgressTarget.G - _ColorProgressLast.G); @@ -388,7 +426,9 @@ namespace VocaluxeLib.Menu _ColorProgressCurrent.A = _ColorProgressLast.A + animFactor * (_ColorProgressTarget.A - _ColorProgressLast.A); } else + { _ColorProgressCurrent = _ColorProgressLast = _ColorProgressTarget; + } } private void _UpdateProgressLeft() @@ -398,33 +438,55 @@ namespace VocaluxeLib.Menu case EDirection.Right: _TextureProgressBegin = TextureProgressLeft; if (_TextureProgressBegin == null) + { _RectProgressBegin = new SRectF(Rect.X, Rect.Y, 0, 0, Rect.Z); + } else + { _RectProgressBegin = new SRectF(Rect.X, Rect.Y, Rect.H * _TextureProgressBegin.OrigAspect, Rect.H, Rect.Z); + } + break; case EDirection.Up: _TextureProgressBegin = TextureProgressRight; if (_TextureProgressBegin == null) + { _RectProgressBegin = new SRectF(Rect.X, Rect.Y + Rect.H, 0, 0, Rect.Z); + } else - _RectProgressBegin = new SRectF(Rect.X, Rect.Y + Rect.H - Rect.W * _TextureProgressBegin.OrigAspect, Rect.W, Rect.W * _TextureProgressBegin.OrigAspect, Rect.Z); + { + _RectProgressBegin = new SRectF(Rect.X, Rect.Y + Rect.H - Rect.W * _TextureProgressBegin.OrigAspect, Rect.W, Rect.W * _TextureProgressBegin.OrigAspect, + Rect.Z); + } + break; case EDirection.Left: _TextureProgressBegin = TextureProgressRight; if (_TextureProgressBegin == null) + { _RectProgressBegin = new SRectF(Rect.X + Rect.W, Rect.Y, 0, 0, Rect.Z); + } else - _RectProgressBegin = new SRectF(Rect.X + Rect.W - Rect.H * _TextureProgressBegin.OrigAspect, Rect.Y, Rect.H *_TextureProgressBegin.OrigAspect, Rect.H, Rect.Z); + { + _RectProgressBegin = new SRectF(Rect.X + Rect.W - Rect.H * _TextureProgressBegin.OrigAspect, Rect.Y, Rect.H * _TextureProgressBegin.OrigAspect, Rect.H, + Rect.Z); + } + break; case EDirection.Down: _TextureProgressBegin = TextureProgressLeft; if (_TextureProgressBegin == null) + { _RectProgressBegin = new SRectF(Rect.X, Rect.Y, 0, 0, Rect.Z); + } else + { _RectProgressBegin = new SRectF(Rect.X, Rect.Y, Rect.W, Rect.W * _TextureProgressBegin.OrigAspect, Rect.Z); + } + break; } } @@ -438,12 +500,12 @@ namespace VocaluxeLib.Menu break; case EDirection.Up: - float newHeight = (Rect.H - 2 * _RectProgressBegin.H) * _ProgressCurrent; + var newHeight = (Rect.H - 2 * _RectProgressBegin.H) * _ProgressCurrent; _RectProgressMid = new SRectF(Rect.X, _RectProgressBegin.Y - newHeight, Rect.W, newHeight, Rect.Z); break; case EDirection.Left: - float newWidth = (Rect.W - 2 * _RectProgressBegin.H) * _ProgressCurrent; + var newWidth = (Rect.W - 2 * _RectProgressBegin.H) * _ProgressCurrent; _RectProgressMid = new SRectF(_RectProgressBegin.X - newWidth, Rect.Y, newWidth, Rect.H, Rect.Z); break; @@ -460,33 +522,53 @@ namespace VocaluxeLib.Menu case EDirection.Right: _TextureProgressEnd = _TextureProgressRight; if (_TextureProgressEnd == null) + { _RectProgressEnd = new SRectF(_RectProgressMid.X + _RectProgressMid.W, Rect.Y, 0, 0, Rect.Z); + } else + { _RectProgressEnd = new SRectF(_RectProgressMid.X + _RectProgressMid.W, Rect.Y, Rect.H * _TextureProgressBegin.OrigAspect, Rect.H, Rect.Z); + } + break; case EDirection.Up: _TextureProgressEnd = _TextureProgressLeft; if (_TextureProgressEnd == null) + { _RectProgressEnd = new SRectF(Rect.X, _RectProgressMid.Y + Rect.W, 0, 0, Rect.Z); + } else + { _RectProgressEnd = new SRectF(Rect.X, _RectProgressMid.Y + Rect.W, Rect.W, Rect.W * _TextureProgressBegin.OrigAspect, Rect.Z); + } + break; case EDirection.Left: _TextureProgressEnd = _TextureProgressLeft; if (_TextureProgressEnd == null) + { _RectProgressEnd = new SRectF(_RectProgressMid.X - Rect.H, Rect.Y, 0, 0, Rect.Z); + } else + { _RectProgressEnd = new SRectF(_RectProgressMid.X - Rect.H, Rect.Y, Rect.H * _TextureProgressBegin.OrigAspect, Rect.H, Rect.Z); + } + break; case EDirection.Down: _TextureProgressEnd = _TextureProgressRight; if (_TextureProgressEnd == null) + { _RectProgressEnd = new SRectF(Rect.X, _RectProgressMid.Y + _RectProgressMid.H, 0, 0, Rect.Z); + } else + { _RectProgressEnd = new SRectF(Rect.X, _RectProgressMid.Y + _RectProgressMid.H, Rect.W, Rect.W * _TextureProgressBegin.OrigAspect, Rect.Z); + } + break; } } @@ -505,15 +587,19 @@ namespace VocaluxeLib.Menu { W += stepW; if (W <= 0) + { W = 1; + } H += stepH; if (H <= 0) + { H = 1; + } _Theme.Rect.W = Rect.W; _Theme.Rect.H = Rect.H; } #endregion ThemeEdit } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Menu/CRatingPopup.cs b/VocaluxeLib/Menu/CRatingPopup.cs index c4233e64..c3a23d73 100644 --- a/VocaluxeLib/Menu/CRatingPopup.cs +++ b/VocaluxeLib/Menu/CRatingPopup.cs @@ -6,7 +6,8 @@ namespace VocaluxeLib.Menu [XmlType("RatingPopup")] public struct SThemeRatingPopup { - [XmlAttribute(AttributeName = "Name")] public string Name; + [XmlAttribute(AttributeName = "Name")] + public string Name; public string SkinRatingPopup; public SRectF Rect; public SThemeText Text; @@ -14,12 +15,12 @@ namespace VocaluxeLib.Menu public sealed class CRatingPopup : CMenuElementBase, IMenuElement, IThemeable { - private readonly int _PartyModeID; + private readonly int _PartyModeId; private SThemeRatingPopup _Theme; private CTextureRef _TextureRatingPopup; public CTextureRef TextureRatingPopup { - get { return _TextureRatingPopup ?? CBase.Themes.GetSkinTexture(_Theme.SkinRatingPopup, _PartyModeID); } + get { return _TextureRatingPopup ?? CBase.Themes.GetSkinTexture(_Theme.SkinRatingPopup, _PartyModeId); } set { _TextureRatingPopup = value; } } @@ -30,17 +31,17 @@ namespace VocaluxeLib.Menu public float Alpha = 1; public SColorF Color; - public CRatingPopup(int partyModeID) + public CRatingPopup(int partyModeId) { - _PartyModeID = partyModeID; - Text = new CText(partyModeID); + _PartyModeId = partyModeId; + Text = new CText(partyModeId); Text.AllMonitors = false; Visible = false; } public CRatingPopup(CRatingPopup rp) { - _PartyModeID = rp._PartyModeID; + _PartyModeId = rp._PartyModeId; _TextureRatingPopup = rp._TextureRatingPopup; Text = new CText(rp.Text); Text.AllMonitors = false; @@ -48,26 +49,25 @@ namespace VocaluxeLib.Menu MaxRect = rp.MaxRect; } - public CRatingPopup(SThemeRatingPopup theme, int partyModeID) + public CRatingPopup(SThemeRatingPopup theme, int partyModeId) { _Theme = theme; - _PartyModeID = partyModeID; - Text = new CText(theme.Text, partyModeID); + _PartyModeId = partyModeId; + Text = new CText(theme.Text, partyModeId); Text.AllMonitors = false; Visible = false; ThemeLoaded = true; } - public void Draw() { - SColorF color = Color; + var color = Color; color.A = Alpha; Text.Color.A = Alpha; if (_TextureRatingPopup != null) { - CBase.Drawing.DrawTexture(_TextureRatingPopup , Rect, color, false); + CBase.Drawing.DrawTexture(_TextureRatingPopup, Rect, color, false); } Text.DrawRelative(Rect.X, Rect.Y); @@ -87,17 +87,17 @@ namespace VocaluxeLib.Menu public void LoadSkin() { if (!ThemeLoaded) + { return; + } - TextureRatingPopup = CBase.Themes.GetSkinTexture(_Theme.SkinRatingPopup, _PartyModeID); - Text = new CText(_Theme.Text, _PartyModeID); + TextureRatingPopup = CBase.Themes.GetSkinTexture(_Theme.SkinRatingPopup, _PartyModeId); + Text = new CText(_Theme.Text, _PartyModeId); Text.LoadSkin(); MaxRect = _Theme.Rect; } - public void UnloadSkin() - { - } + public void UnloadSkin() { } public void ReloadSkin() { @@ -118,14 +118,18 @@ namespace VocaluxeLib.Menu { W += stepW; if (W <= 0) + { W = 1; + } H += stepH; if (H <= 0) + { H = 1; + } _Theme.Rect.W = Rect.W; _Theme.Rect.H = Rect.H; } } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Menu/CScreenSetting.cs b/VocaluxeLib/Menu/CScreenSetting.cs index 56dfc7c7..cbde82c1 100644 --- a/VocaluxeLib/Menu/CScreenSetting.cs +++ b/VocaluxeLib/Menu/CScreenSetting.cs @@ -32,7 +32,8 @@ namespace VocaluxeLib.Menu [XmlType("ScreenSetting")] public struct SThemeScreenSetting { - [XmlAttribute(AttributeName = "Name")] public string Name; + [XmlAttribute(AttributeName = "Name")] + public string Name; public string Value; public ESettingType Type; } @@ -40,33 +41,29 @@ namespace VocaluxeLib.Menu // ReSharper disable ClassNeverInstantiated.Global //Instantiated by reflection public class CScreenSetting : IThemeable - // ReSharper restore ClassNeverInstantiated.Global + // ReSharper restore ClassNeverInstantiated.Global { - private readonly int _PartyModeID; + private readonly int _PartyModeId; private SThemeScreenSetting _Theme; - private bool _ThemeLoaded; public string GetThemeName() { return _Theme.Name; } - public bool ThemeLoaded - { - get { return _ThemeLoaded; } - } + public bool ThemeLoaded { get; } - public CScreenSetting(int partyModeID) + public CScreenSetting(int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = new SThemeScreenSetting(); - _ThemeLoaded = false; + ThemeLoaded = false; } - public CScreenSetting(SThemeScreenSetting theme, int partyModeID) + public CScreenSetting(SThemeScreenSetting theme, int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = theme; } @@ -109,22 +106,22 @@ namespace VocaluxeLib.Menu private CTextureRef _GetTextureValue() { - return CBase.Themes.GetSkinTexture(_Theme.Value, _PartyModeID); + return CBase.Themes.GetSkinTexture(_Theme.Value, _PartyModeId); } private SColorF _GetColorValue() { SColorF color; - CBase.Themes.GetColor(_Theme.Value, _PartyModeID, out color); + CBase.Themes.GetColor(_Theme.Value, _PartyModeId, out color); return color; } #region Dummy methods for interface - public void UnloadSkin() {} + public void UnloadSkin() { } - public void LoadSkin() {} + public void LoadSkin() { } - public void ReloadSkin() {} + public void ReloadSkin() { } #endregion } } \ No newline at end of file diff --git a/VocaluxeLib/Menu/CSelectSlide.cs b/VocaluxeLib/Menu/CSelectSlide.cs index 33e4caa9..5a5f0013 100644 --- a/VocaluxeLib/Menu/CSelectSlide.cs +++ b/VocaluxeLib/Menu/CSelectSlide.cs @@ -28,7 +28,8 @@ namespace VocaluxeLib.Menu [XmlType("SelectSlide")] public struct SThemeSelectSlide { - [XmlAttribute(AttributeName = "Name")] public string Name; + [XmlAttribute(AttributeName = "Name")] + public string Name; public string Skin; public string SkinArrowLeft; @@ -52,8 +53,10 @@ namespace VocaluxeLib.Menu public SThemeColor TextSelColor; public float TextH; - [DefaultValue(0.0f)] public float TextRelativeX; - [DefaultValue(0.0f)] public float TextRelativeY; + [DefaultValue(0.0f)] + public float TextRelativeX; + [DefaultValue(0.0f)] + public float TextRelativeY; public float TextMaxW; public string TextFont; @@ -79,7 +82,7 @@ namespace VocaluxeLib.Menu public SRectF Bounds; } - private readonly int _PartyModeID; + private readonly int _PartyModeId; private SThemeSelectSlide _Theme; public string GetThemeName() @@ -114,7 +117,7 @@ namespace VocaluxeLib.Menu { set { - float delta = value - X; + var delta = value - X; RectArrowLeft.X += delta; RectArrowRight.X += delta; base.X = value; @@ -124,7 +127,7 @@ namespace VocaluxeLib.Menu { set { - float delta = value - Y; + var delta = value - Y; RectArrowLeft.Y += delta; RectArrowRight.Y += delta; base.Y = value; @@ -134,7 +137,7 @@ namespace VocaluxeLib.Menu { set { - float delta = value - Z; + var delta = value - Z; RectArrowLeft.Z += delta; RectArrowRight.Z += delta; base.Z = value; @@ -173,7 +176,10 @@ namespace VocaluxeLib.Menu { value = value.Clamp(0, _Values.Count - 1, false); if (value == _Selection) + { return; + } + _Selection = value; _Invalidate(); } @@ -214,16 +220,19 @@ namespace VocaluxeLib.Menu set { if (value <= 0 || value == _NumVisible) + { return; + } + _NumVisible = value; _Invalidate(); } } - public CSelectSlide(int partyModeID) + public CSelectSlide(int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; ThemeLoaded = false; _TextH = 1f; _MaxW = 0f; @@ -231,7 +240,7 @@ namespace VocaluxeLib.Menu public CSelectSlide(CSelectSlide slide) { - _PartyModeID = slide._PartyModeID; + _PartyModeId = slide._PartyModeId; _Theme = slide._Theme; ThemeLoaded = false; @@ -261,9 +270,9 @@ namespace VocaluxeLib.Menu Visible = slide.Visible; } - public CSelectSlide(SThemeSelectSlide theme, int partyModeID) + public CSelectSlide(SThemeSelectSlide theme, int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = theme; ThemeLoaded = true; @@ -291,7 +300,7 @@ namespace VocaluxeLib.Menu /// User value (e.g. id of entry) public void AddValue(string text, CTextureRef texture = null, int tag = 0) { - AddValue(text, _PartyModeID, texture, tag); + AddValue(text, _PartyModeId, texture, tag); } /// @@ -303,20 +312,24 @@ namespace VocaluxeLib.Menu /// User value (e.g. id of entry) public void AddValue(string text, int translationId, CTextureRef texture = null, int tag = 0) { - SValue value = new SValue {Text = text, TranslationId = translationId, Tag = tag, Texture = texture}; + var value = new SValue { Text = text, TranslationId = translationId, Tag = tag, Texture = texture }; _Values.Add(value); if (Selection < 0) + { Selection = 0; + } _Invalidate(); } public void AddValues(IEnumerable values) { - foreach (string value in values) + foreach (var value in values) + { AddValue(value); + } } public void AddValues(IEnumerable values, IEnumerable tags) @@ -328,6 +341,7 @@ namespace VocaluxeLib.Menu { AddValue(e1.Current, tag: e2.Current); } + if (e1.MoveNext() || e2.MoveNext()) { throw new ArgumentException("the lists must have the same length"); @@ -339,18 +353,26 @@ namespace VocaluxeLib.Menu { Debug.Assert(values.Length == textures.Length); - for (int i = 0; i < values.Length; i++) + for (var i = 0; i < values.Length; i++) + { AddValue(values[i], textures[i]); + } } public void RemoveValue(string text) { - int idx = _Values.FindIndex(val => val.Text == text); + var idx = _Values.FindIndex(val => val.Text == text); if (idx < 0) + { return; + } + _Values.RemoveAt(idx); if (Selection >= idx) + { Selection--; + } + _Invalidate(); } @@ -368,9 +390,11 @@ namespace VocaluxeLib.Menu public void RenameValue(int index, string newName, CTextureRef newTexture = null) { if (index < 0 && index >= _Values.Count) + { return; + } - SValue value = _Values[index]; + var value = _Values[index]; value.Text = newName; value.Texture = newTexture; _Values[index] = value; @@ -383,6 +407,7 @@ namespace VocaluxeLib.Menu Selection++; return true; } + return false; } @@ -393,19 +418,24 @@ namespace VocaluxeLib.Menu Selection--; return true; } + return false; } public void SelectFirstValue() { if (_Values.Count > 0) + { Selection = 0; + } } public void SelectLastValue() { if (_Values.Count > 0) + { Selection = _Values.Count - 1; + } } public void Clear() @@ -417,17 +447,23 @@ namespace VocaluxeLib.Menu private int _GetCurOffset() { - int offset = _Selection - _NumVisible / 2; + var offset = _Selection - _NumVisible / 2; return offset.Clamp(0, _Values.Count - _NumVisible, true); } private void _SelectAtPos(int x, int y) { if (_NeedsRevalidate) + { _Revalidate(); - int index = _VisibleElements.FindIndex(el => CHelper.IsInBounds(el.Bounds, x, y)); + } + + var index = _VisibleElements.FindIndex(el => CHelper.IsInBounds(el.Bounds, x, y)); if (index < 0) + { return; + } + Selection = index + _GetCurOffset(); } @@ -437,7 +473,9 @@ namespace VocaluxeLib.Menu _ArrowRightSelected = CHelper.IsInBounds(RectArrowRight, x, y) && _Selection < _Values.Count - 1; if (SelectByHovering) + { _SelectAtPos(x, y); + } } public void ProcessMouseLBClick(int x, int y) @@ -445,10 +483,14 @@ namespace VocaluxeLib.Menu ProcessMouseMove(x, y); if (_ArrowLeftSelected) + { SelectPrevValue(); + } if (_ArrowRightSelected) + { SelectNextValue(); + } _SelectAtPos(x, y); } @@ -456,38 +498,44 @@ namespace VocaluxeLib.Menu private void _Revalidate() { if (!_NeedsRevalidate) + { return; + } + _NeedsRevalidate = false; - int numvis = Math.Min(_NumVisible, _Values.Count); + var numvis = Math.Min(_NumVisible, _Values.Count); if (numvis != _VisibleElements.Count) { _VisibleElements.Clear(); - for (int i = 0; i < numvis; i++) + for (var i = 0; i < numvis; i++) { var el = new CElement { - Text = new CText(0, 0, 0, _TextH, _MaxW, EAlignment.Center, _Theme.TextStyle, _Theme.TextFont, _TextColor, "T", _PartyModeID), - Img = new CStatic(_PartyModeID) + Text = new CText(0, 0, 0, _TextH, _MaxW, EAlignment.Center, _Theme.TextStyle, _Theme.TextFont, _TextColor, "T", _PartyModeId), + Img = new CStatic(_PartyModeId) }; el.Img.Aspect = EAspect.Crop; _VisibleElements.Add(el); } } + if (numvis == 0) - return; - - float elWidth = (Rect.W - _TextRelativeX * 2) / numvis; - //Center point of the first entry - float xStart = Rect.X + _TextRelativeX + elWidth / 2f; - - int offset = _GetCurOffset(); - - for (int i = 0; i < numvis; i++) { - CText text = _VisibleElements[i].Text; + return; + } + + var elWidth = (Rect.W - _TextRelativeX * 2) / numvis; + //Center point of the first entry + var xStart = Rect.X + _TextRelativeX + elWidth / 2f; + + var offset = _GetCurOffset(); + + for (var i = 0; i < numvis; i++) + { + var text = _VisibleElements[i].Text; RectangleF textBounds; - float curX = xStart + elWidth * i; - if (String.IsNullOrEmpty(_Values[i + offset].Text)) + var curX = xStart + elWidth * i; + if (string.IsNullOrEmpty(_Values[i + offset].Text)) { text.Visible = false; textBounds = new RectangleF(); @@ -496,18 +544,21 @@ namespace VocaluxeLib.Menu { text.Visible = true; text.Text = _Values[i + offset].Text; - text.TranslationID = _Values[i + offset].TranslationId; - text.Color = (i + offset == Selection) ? _SelTextColor : _TextColor; + text.TranslationId = _Values[i + offset].TranslationId; + text.Color = i + offset == Selection ? _SelTextColor : _TextColor; textBounds = CBase.Fonts.GetTextBounds(text); text.X = curX; text.Z = Rect.Z; } - CStatic img = _VisibleElements[i].Img; + var img = _VisibleElements[i].Img; if (!DrawTextures || _Values[i + offset].Texture == null) { if (text.Visible) + { text.Y = Rect.Y + (Rect.H - textBounds.Height) / 2 - _TextRelativeY; + } + img.Visible = false; _VisibleElements[i].Bounds = new SRectF(text.X - textBounds.Width / 2f, text.Y, textBounds.Width, textBounds.Height, Rect.Z); } @@ -515,11 +566,14 @@ namespace VocaluxeLib.Menu { text.Y = (int)(Rect.Y + Rect.H - textBounds.Height - _TextRelativeY); img.Texture = _Values[i + offset].Texture; - float alpha = (i + offset == _Selection) ? 1f : 0.35f; + var alpha = i + offset == _Selection ? 1f : 0.35f; img.Color = new SColorF(1f, 1f, 1f, alpha); - float size = Rect.H - textBounds.Height - 2 * _TextRelativeY; + var size = Rect.H - textBounds.Height - 2 * _TextRelativeY; if (size > elWidth) + { size = elWidth; + } + var imgRect = new SRectF(curX - size / 2, Rect.Y + _TextRelativeY, size, size, Rect.Z); img.MaxRect = imgRect; _VisibleElements[i].Bounds = imgRect; @@ -530,32 +584,49 @@ namespace VocaluxeLib.Menu public void Draw() { if (!Visible && CBase.Settings.GetProgramState() != EProgramState.EditTheme) + { return; + } if (Selected) + { CBase.Drawing.DrawTexture(_SelTexture, Rect, _SelColor); + } else + { CBase.Drawing.DrawTexture(_Texture, Rect, _Color); + } if (_Selection > 0 || CBase.Settings.GetProgramState() == EProgramState.EditTheme) { if (_ArrowLeftSelected) + { CBase.Drawing.DrawTexture(_SelTextureArrowLeft, RectArrowLeft, _SelColorArrow); + } else + { CBase.Drawing.DrawTexture(_TextureArrowLeft, RectArrowLeft, _ColorArrow); + } } if (_Selection < _Values.Count - 1 || CBase.Settings.GetProgramState() == EProgramState.EditTheme) { if (_ArrowRightSelected) + { CBase.Drawing.DrawTexture(_SelTextureArrowRight, RectArrowRight, _SelColorArrow); + } else + { CBase.Drawing.DrawTexture(_TextureArrowRight, RectArrowRight, _ColorArrow); + } } if (_NeedsRevalidate) + { _Revalidate(); - foreach (CElement element in _VisibleElements) + } + + foreach (var element in _VisibleElements) { element.Text.Draw(); element.Img.Draw(); @@ -567,16 +638,16 @@ namespace VocaluxeLib.Menu return _Theme; } - public void UnloadSkin() {} + public void UnloadSkin() { } public void LoadSkin() { - _Theme.Color.Get(_PartyModeID, out _Color); - _Theme.SelColor.Get(_PartyModeID, out _SelColor); - _Theme.ArrowColor.Get(_PartyModeID, out _ColorArrow); - _Theme.ArrowSelColor.Get(_PartyModeID, out _SelColorArrow); - _Theme.TextColor.Get(_PartyModeID, out _TextColor); - _Theme.TextSelColor.Get(_PartyModeID, out _SelTextColor); + _Theme.Color.Get(_PartyModeId, out _Color); + _Theme.SelColor.Get(_PartyModeId, out _SelColor); + _Theme.ArrowColor.Get(_PartyModeId, out _ColorArrow); + _Theme.ArrowSelColor.Get(_PartyModeId, out _SelColorArrow); + _Theme.TextColor.Get(_PartyModeId, out _TextColor); + _Theme.TextSelColor.Get(_PartyModeId, out _SelTextColor); MaxRect = _Theme.Rect; RectArrowLeft = _Theme.RectArrowLeft; @@ -589,13 +660,13 @@ namespace VocaluxeLib.Menu _TextRelativeY = _Theme.TextRelativeY; _MaxW = _Theme.TextMaxW; - _Texture = CBase.Themes.GetSkinTexture(_Theme.Skin, _PartyModeID); - _TextureArrowLeft = CBase.Themes.GetSkinTexture(_Theme.SkinArrowLeft, _PartyModeID); - _TextureArrowRight = CBase.Themes.GetSkinTexture(_Theme.SkinArrowRight, _PartyModeID); + _Texture = CBase.Themes.GetSkinTexture(_Theme.Skin, _PartyModeId); + _TextureArrowLeft = CBase.Themes.GetSkinTexture(_Theme.SkinArrowLeft, _PartyModeId); + _TextureArrowRight = CBase.Themes.GetSkinTexture(_Theme.SkinArrowRight, _PartyModeId); - _SelTexture = CBase.Themes.GetSkinTexture(_Theme.SkinSelected, _PartyModeID); - _SelTextureArrowLeft = CBase.Themes.GetSkinTexture(_Theme.SkinArrowLeftSelected, _PartyModeID); - _SelTextureArrowRight = CBase.Themes.GetSkinTexture(_Theme.SkinArrowRightSelected, _PartyModeID); + _SelTexture = CBase.Themes.GetSkinTexture(_Theme.SkinSelected, _PartyModeId); + _SelTextureArrowLeft = CBase.Themes.GetSkinTexture(_Theme.SkinArrowLeftSelected, _PartyModeId); + _SelTextureArrowRight = CBase.Themes.GetSkinTexture(_Theme.SkinArrowRightSelected, _PartyModeId); _Invalidate(); } @@ -644,11 +715,15 @@ namespace VocaluxeLib.Menu { W += stepW; if (W <= 0) + { W = 1; + } H += stepH; if (H <= 0) + { H = 1; + } _Theme.Rect.W = Rect.W; _Theme.Rect.H = Rect.H; @@ -658,11 +733,15 @@ namespace VocaluxeLib.Menu { RectArrowLeft.W += stepW; if (RectArrowLeft.W <= 0) + { RectArrowLeft.W = 1; + } RectArrowLeft.H += stepH; if (RectArrowLeft.H <= 0) + { RectArrowLeft.H = 1; + } _Theme.RectArrowLeft.W = RectArrowLeft.W; _Theme.RectArrowLeft.H = RectArrowLeft.H; @@ -672,11 +751,15 @@ namespace VocaluxeLib.Menu { RectArrowRight.W += stepW; if (RectArrowRight.W <= 0) + { RectArrowRight.W = 1; + } RectArrowRight.H += stepH; if (RectArrowRight.H <= 0) + { RectArrowRight.H = 1; + } _Theme.RectArrowRight.W = RectArrowRight.W; _Theme.RectArrowRight.H = RectArrowRight.H; diff --git a/VocaluxeLib/Menu/CStatic.cs b/VocaluxeLib/Menu/CStatic.cs index 0834d794..996d954f 100644 --- a/VocaluxeLib/Menu/CStatic.cs +++ b/VocaluxeLib/Menu/CStatic.cs @@ -35,7 +35,7 @@ namespace VocaluxeLib.Menu public sealed class CStatic : CMenuElementBase, IMenuElement, IThemeable { - private readonly int _PartyModeID; + private readonly int _PartyModeId; private SThemeStatic _Theme; @@ -54,7 +54,7 @@ namespace VocaluxeLib.Menu private CTextureRef _Texture; public CTextureRef Texture { - get { return _Texture ?? CBase.Themes.GetSkinTexture(_Theme.Skin, _PartyModeID); } + get { return _Texture ?? CBase.Themes.GetSkinTexture(_Theme.Skin, _PartyModeId); } set { _Texture = value; } } @@ -80,14 +80,14 @@ namespace VocaluxeLib.Menu /// public float ModH = -1f; - public CStatic(int partyModeID) + public CStatic(int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; } public CStatic(CStatic s) { - _PartyModeID = s._PartyModeID; + _PartyModeId = s._PartyModeId; _Texture = s.Texture; Color = s.Color; @@ -101,26 +101,26 @@ namespace VocaluxeLib.Menu Visible = s.Visible; } - public CStatic(int partyModeID, CTextureRef texture, SColorF color, SRectF rect) + public CStatic(int partyModeId, CTextureRef texture, SColorF color, SRectF rect) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Texture = texture; Color = color; MaxRect = rect; } - public CStatic(int partyModeID, string textureSkinName, SColorF color, SRectF rect) + public CStatic(int partyModeId, string textureSkinName, SColorF color, SRectF rect) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme.Skin = textureSkinName; Color = color; MaxRect = rect; } - public CStatic(SThemeStatic theme, int partyModeID) + public CStatic(SThemeStatic theme, int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = theme; ThemeLoaded = true; } @@ -132,38 +132,51 @@ namespace VocaluxeLib.Menu public void Draw(EAspect aspect, float scale = 1f, float zModify = 0f, bool forceDraw = false) { - CTextureRef texture = Texture; - SRectF bounds = Rect.Scale(scale); + var texture = Texture; + var bounds = Rect.Scale(scale); //Change bounds if rect size should be modified without adjusting texture if (ModH != -1) + { bounds.H = ModH * scale; + } + if (ModW != -1) + { bounds.W = ModW * scale; + } bounds.Z += zModify; - SRectF rect = texture == null ? bounds : CHelper.FitInBounds(bounds, texture.OrigAspect, aspect); + var rect = texture == null ? bounds : CHelper.FitInBounds(bounds, texture.OrigAspect, aspect); //Use original rect if (ModH != -1 || ModW != -1) + { rect = Rect.Scale(scale); + } var color = new SColorF(Color.R, Color.G, Color.B, Color.A * Alpha); - if (Visible || forceDraw || (CBase.Settings.GetProgramState() == EProgramState.EditTheme)) + if (Visible || forceDraw || CBase.Settings.GetProgramState() == EProgramState.EditTheme) { if (texture != null) { CBase.Drawing.DrawTexture(texture, rect, color, bounds, false, AllMonitors); if (Reflection) + { CBase.Drawing.DrawTextureReflection(texture, rect, color, bounds, ReflectionSpace, ReflectionHeight, AllMonitors); + } } else + { CBase.Drawing.DrawRect(color, rect); + } } - if (Selected && (CBase.Settings.GetProgramState() == EProgramState.EditTheme)) + if (Selected && CBase.Settings.GetProgramState() == EProgramState.EditTheme) + { CBase.Drawing.DrawRect(new SColorF(1f, 1f, 1f, 0.5f), rect); + } } public void UnloadSkin() { } @@ -171,8 +184,11 @@ namespace VocaluxeLib.Menu public void LoadSkin() { if (!ThemeLoaded) + { return; - _Theme.Color.Get(_PartyModeID, out Color); + } + + _Theme.Color.Get(_PartyModeId, out Color); MaxRect = _Theme.Rect; Reflection = _Theme.Reflection.HasValue; @@ -209,11 +225,15 @@ namespace VocaluxeLib.Menu { W += stepW; if (W <= 0) + { W = 1; + } H += stepH; if (H <= 0) + { H = 1; + } _Theme.Rect.W = Rect.W; _Theme.Rect.H = Rect.H; diff --git a/VocaluxeLib/Menu/CText.cs b/VocaluxeLib/Menu/CText.cs index fb96624a..e3b4132f 100644 --- a/VocaluxeLib/Menu/CText.cs +++ b/VocaluxeLib/Menu/CText.cs @@ -16,7 +16,6 @@ #endregion using System; -using System.Drawing; using System.Xml.Serialization; namespace VocaluxeLib.Menu @@ -50,8 +49,8 @@ namespace VocaluxeLib.Menu public sealed class CText : CMenuElementBase, IMenuElement, IThemeable, IFontObserver { private SThemeText _Theme; - private readonly int _PartyModeID = -1; - private int _TranslationID = -1; + private readonly int _PartyModeId = -1; + private int _TranslationId = -1; public string GetThemeName() { @@ -169,37 +168,36 @@ namespace VocaluxeLib.Menu public bool AllMonitors = true; - private string _Text = String.Empty; public string Text { get { return _Theme.Text; } set { - string translation = CBase.Language.Translate(value, _TranslationID); - if (_Theme.Text != value || translation != _Text) + var translation = CBase.Language.Translate(value, _TranslationId); + if (_Theme.Text != value || translation != TranslatedText) { _Theme.Text = value; - _Text = translation; + TranslatedText = translation; if (_EditMode) - _Text += "|"; + { + TranslatedText += "|"; + } + _PositionNeedsUpdate = true; } } } - public string TranslatedText - { - get { return _Text; } - } + public string TranslatedText { get; private set; } = string.Empty; - public int TranslationID + public int TranslationId { - get { return _TranslationID; } + get { return _TranslationId; } set { - if (_TranslationID != value) + if (_TranslationId != value) { - _Text = CBase.Language.Translate(_Text, value); - _TranslationID = value; + TranslatedText = CBase.Language.Translate(TranslatedText, value); + _TranslationId = value; _PositionNeedsUpdate = true; } } @@ -213,7 +211,7 @@ namespace VocaluxeLib.Menu { if (_EditMode != value) { - _Text = value ? _Text + "|" : _Text.Substring(0, _Text.Length - 1); + TranslatedText = value ? TranslatedText + "|" : TranslatedText.Substring(0, TranslatedText.Length - 1); _EditMode = value; _PositionNeedsUpdate = true; } @@ -228,22 +226,25 @@ namespace VocaluxeLib.Menu get { if (_PositionNeedsUpdate) + { _UpdateTextPosition(); + } + return _CalculatedFont; } } - public CText(int partyModeID) + public CText(int partyModeId) { - _PartyModeID = partyModeID; - _TranslationID = _PartyModeID; + _PartyModeId = partyModeId; + _TranslationId = _PartyModeId; _Font.AddObserver(this); } public CText(CText text) { - _PartyModeID = text._PartyModeID; - _TranslationID = text._TranslationID; + _PartyModeId = text._PartyModeId; + _TranslationId = text._TranslationId; MaxRect = text.MaxRect; _Rect = text._Rect; @@ -265,9 +266,9 @@ namespace VocaluxeLib.Menu _EditMode = text._EditMode; } - public CText(float x, float y, float z, float h, float mw, EAlignment align, EStyle style, string fontFamily, SColorF col, string text, int partyModeID = -1, - float rheight = 0, - float rspace = 0) : this(partyModeID) + public CText(float x, float y, float z, float h, float mw, EAlignment align, EStyle style, string fontFamily, SColorF col, string text, int partyModeId = -1, + float rheight = 0, + float rspace = 0) : this(partyModeId) { _Theme = new SThemeText { FontFamily = fontFamily, FontStyle = style, FontHeight = h, Text = text, Color = { A = col.A, B = col.B, G = col.G, R = col.R } }; ThemeLoaded = false; @@ -291,10 +292,10 @@ namespace VocaluxeLib.Menu _ReflectionHeight = rheight; } - public CText(SThemeText theme, int partyModeID, bool buttonText = false) + public CText(SThemeText theme, int partyModeId, bool buttonText = false) { - _PartyModeID = partyModeID; - _TranslationID = partyModeID; + _PartyModeId = partyModeId; + _TranslationId = partyModeId; _Theme = theme; _ButtonText = buttonText; @@ -310,26 +311,32 @@ namespace VocaluxeLib.Menu private void _Draw(bool force) { if (!force && !Visible && CBase.Settings.GetProgramState() != EProgramState.EditTheme) + { return; + } // Update Text Text = Text; - SColorF currentColor = (Selected) ? SelColor : Color; + var currentColor = Selected ? SelColor : Color; var color = new SColorF(currentColor.R, currentColor.G, currentColor.B, currentColor.A * Alpha); - CBase.Fonts.DrawText(_Text, CalculatedFont, Rect.X, Rect.Y, Z, color, AllMonitors); + CBase.Fonts.DrawText(TranslatedText, CalculatedFont, Rect.X, Rect.Y, Z, color, AllMonitors); if (_ReflectionHeight > 0) - CBase.Fonts.DrawTextReflection(_Text, CalculatedFont, Rect.X, Rect.Y, Z, color, _ReflectionSpace, _ReflectionHeight); + { + CBase.Fonts.DrawTextReflection(TranslatedText, CalculatedFont, Rect.X, Rect.Y, Z, color, _ReflectionSpace, _ReflectionHeight); + } - if (Selected && (CBase.Settings.GetProgramState() == EProgramState.EditTheme)) + if (Selected && CBase.Settings.GetProgramState() == EProgramState.EditTheme) + { CBase.Drawing.DrawRect(new SColorF(0.5f, 1f, 0.5f, 0.5f), new SRectF(Rect.X, Rect.Y, Rect.W, Rect.H, Z)); + } } public void Draw(float begin, float end) { - SColorF currentColor = (Selected) ? SelColor : Color; + var currentColor = Selected ? SelColor : Color; var color = new SColorF(currentColor.R, currentColor.G, currentColor.B, currentColor.A * Alpha); CBase.Fonts.DrawText(Text, CalculatedFont, Rect.X, Rect.Y, Z, color, begin, end); @@ -339,21 +346,26 @@ namespace VocaluxeLib.Menu // TODO } - if (Selected && (CBase.Settings.GetProgramState() == EProgramState.EditTheme)) + if (Selected && CBase.Settings.GetProgramState() == EProgramState.EditTheme) + { CBase.Drawing.DrawRect(new SColorF(0.5f, 1f, 0.5f, 0.5f), new SRectF(X, Y, Rect.W, Rect.H, Z)); + } } public void DrawRelative(float rx, float ry, float reflectionHeight = 0f, float reflectionSpace = 0f, float rectHeight = 0f) { - float oldReflectionSpace = _ReflectionSpace; - float oldReflectionHeight = _ReflectionHeight; + var oldReflectionSpace = _ReflectionSpace; + var oldReflectionHeight = _ReflectionHeight; if (reflectionHeight > 0) { _ReflectionSpace = (rectHeight - Rect.Y - Rect.H) * 2 + reflectionSpace; _ReflectionHeight = reflectionHeight - (rectHeight - Rect.Y) + Rect.H; } else + { _ReflectionHeight = 0; + } + X += rx; Y += ry; _Draw(true); @@ -368,14 +380,20 @@ namespace VocaluxeLib.Menu public void LoadSkin() { if (!ThemeLoaded) + { return; - _Theme.Color.Get(_PartyModeID, out Color); - _Theme.SelColor.Get(_PartyModeID, out SelColor); + } + + _Theme.Color.Get(_PartyModeId, out Color); + _Theme.SelColor.Get(_PartyModeId, out SelColor); X = _Theme.X; Y = _Theme.Y; if (!_ButtonText) + { Z = _Theme.Z; + } + W = _Theme.MaxWidth; H = _Theme.FontHeight; _Align = _Theme.Align; @@ -417,7 +435,10 @@ namespace VocaluxeLib.Menu { _Theme.FontHeight += stepH; if (_Theme.FontHeight <= 0) + { _Theme.FontHeight = 1; + } + _Font.Height = _Theme.FontHeight; } #endregion ThemeEdit @@ -425,23 +446,27 @@ namespace VocaluxeLib.Menu private void _UpdateTextPosition() { if (!_PositionNeedsUpdate) + { return; + } _CalculatedFont = new CFont(Font); _Rect = MaxRect; _PositionNeedsUpdate = false; - if (_Text == "") + if (TranslatedText == "") + { return; + } - float h = _CalculatedFont.Height; - float y = Y; - RectangleF bounds = CBase.Fonts.GetTextBounds(this); + var h = _CalculatedFont.Height; + var y = Y; + var bounds = CBase.Fonts.GetTextBounds(this); if (W > 0f && bounds.Width > W && bounds.Width > 0f) { - float factor = W / bounds.Width; - float step = h * (1 - factor); + var factor = W / bounds.Width; + var step = h * (1 - factor); h *= factor; switch (ResizeAlign) { @@ -455,11 +480,12 @@ namespace VocaluxeLib.Menu y += step * 0.75f; break; } + _CalculatedFont.Height = h; bounds = CBase.Fonts.GetTextBounds(this); } - float x = X; + var x = X; switch (Align) { case EAlignment.Center: diff --git a/VocaluxeLib/Menu/IMenu.cs b/VocaluxeLib/Menu/IMenu.cs index 2f55edb3..f473711d 100644 --- a/VocaluxeLib/Menu/IMenu.cs +++ b/VocaluxeLib/Menu/IMenu.cs @@ -19,7 +19,7 @@ namespace VocaluxeLib.Menu { public interface IMenu { - int PartyModeID { get; } + int PartyModeId { get; } void Init(); diff --git a/VocaluxeLib/Menu/IThemeable.cs b/VocaluxeLib/Menu/IThemeable.cs index 3039bb9c..f92c7a44 100644 --- a/VocaluxeLib/Menu/IThemeable.cs +++ b/VocaluxeLib/Menu/IThemeable.cs @@ -15,8 +15,6 @@ // along with Vocaluxe. If not, see . #endregion -using VocaluxeLib.Xml; - namespace VocaluxeLib.Menu { public interface IThemeable diff --git a/VocaluxeLib/Menu/SingNotes/CNoteBars.cs b/VocaluxeLib/Menu/SingNotes/CNoteBars.cs index c3e36354..a086bc56 100644 --- a/VocaluxeLib/Menu/SingNotes/CNoteBars.cs +++ b/VocaluxeLib/Menu/SingNotes/CNoteBars.cs @@ -28,7 +28,7 @@ namespace VocaluxeLib.Menu.SingNotes public class CNoteBars { private readonly SThemeSingBar _Theme; - private readonly int _PartyModeID; + private readonly int _PartyModeId; private readonly int _Player; public readonly SRectF Rect; private readonly SColorF _Color; @@ -54,59 +54,72 @@ namespace VocaluxeLib.Menu.SingNotes private readonly List _PerfectNoteEffect = new List(); private readonly List _PerfectLineTwinkle = new List(); - public CNoteBars(int partyModeID, int player, SRectF rect, SThemeSingBar theme) + public CNoteBars(int partyModeId, int player, SRectF rect, SThemeSingBar theme) { _Player = player; _Theme = theme; - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; Rect = rect; _Color = CBase.Themes.GetPlayerColor(player + 1); - if (!CBase.Themes.GetColor("NoteLinesColor", _PartyModeID, out _NoteLinesColor)) + if (!CBase.Themes.GetColor("NoteLinesColor", _PartyModeId, out _NoteLinesColor)) + { _NoteLinesColor = new SColorF(Color.Gray, 0.5f); + } - if (!CBase.Themes.GetColor("NoteBaseColor", _PartyModeID, out _NoteBaseColor)) + if (!CBase.Themes.GetColor("NoteBaseColor", _PartyModeId, out _NoteBaseColor)) + { _NoteBaseColor = new SColorF(Color.White); + } - SPlayer playerData = CBase.Game.GetPlayers()[player]; + var playerData = CBase.Game.GetPlayers()[player]; _Lines = CBase.Game.GetSong().Notes.GetVoice(playerData.VoiceNr).Lines; _NoteLineHeight = Rect.H / CBase.Settings.GetNumNoteLines(); - _AddNoteHeight = _NoteLineHeight / 2f * (2f - (int)CBase.Profiles.GetDifficulty(playerData.ProfileID)); + _AddNoteHeight = _NoteLineHeight / 2f * (2f - (int)CBase.Profiles.GetDifficulty(playerData.ProfileId)); } public void SetLine(int line) { if (_CurrentLine == line) + { return; + } + _CurrentLine = line; _GoldenStars.Clear(); _Flares.Clear(); _PerfectNoteEffect.Clear(); - foreach (CSongNote note in _Lines[_CurrentLine].Notes.Where(note => (note.IsGoldenNote))) + foreach (var note in _Lines[_CurrentLine].Notes.Where(note => note.IsGoldenNote)) + { _AddGoldenNote(_GetNoteRect(note)); + } } public void Draw() { if (_CurrentLine == -1 || _CurrentLine >= _Lines.Length) + { return; + } - CSongLine line = _Lines[_CurrentLine]; + var line = _Lines[_CurrentLine]; if (CBase.Config.GetDrawNoteLines() == EOffOn.TR_CONFIG_ON) + { _DrawNoteLines(new SColorF(_NoteLinesColor, _NoteLinesColor.A * Alpha)); + } float beats = line.LastNoteBeat - line.FirstNoteBeat + 1; var color = new SColorF(_Color, _Color.A * Alpha); - foreach (CSongNote note in line.Notes) + foreach (var note in line.Notes) { if (note.Type != ENoteType.Freestyle) { - SRectF rect = _GetNoteRect(note); + var rect = _GetNoteRect(note); _DrawNoteBG(rect, color, note.IsRapNote); _DrawNoteBase(rect, new SColorF(_NoteBaseColor, _NoteBaseColor.A * Alpha), 1f, note.IsRapNote); @@ -114,24 +127,28 @@ namespace VocaluxeLib.Menu.SingNotes } if (CBase.Config.GetDrawToneHelper() == EOffOn.TR_CONFIG_ON) + { _DrawToneHelper(line, (CBase.Game.GetMidRecordedBeat() - line.FirstNoteBeat) / beats * Rect.W); + } - List sungLines = CBase.Game.GetPlayers()[_Player].SungLines; + var sungLines = CBase.Game.GetPlayers()[_Player].SungLines; if (_CurrentLine >= 0 && _CurrentLine < sungLines.Count) { - foreach (CSungNote note in sungLines[_CurrentLine].Notes) + foreach (var note in sungLines[_CurrentLine].Notes) { - SRectF rect = _GetNoteRect(note); + var rect = _GetNoteRect(note); if (note.EndBeat == CBase.Game.GetRecordedBeat()) + { rect.W -= (1 - (CBase.Game.GetMidRecordedBeat() - CBase.Game.GetRecordedBeat())) * Rect.W / beats; + } - float factor = (note.Hit) ? 1f : 0.6f; + var factor = note.Hit ? 1f : 0.6f; _DrawNoteFill(rect, color, factor, note.IsRapNote); if (note.EndBeat >= CBase.Game.GetRecordedBeat() && note.Hit && note.IsGoldenNote) { - SRectF re = rect; + var re = rect; re.W = (CBase.Game.GetMidRecordedBeat() - note.StartBeat) / beats * Rect.W; _AddFlare(re); } @@ -154,31 +171,37 @@ namespace VocaluxeLib.Menu.SingNotes _PerfectNoteEffect.RemoveAll(el => !el.IsAlive); _PerfectLineTwinkle.RemoveAll(el => !el.IsAlive); - foreach (CParticleEffect perfline in _PerfectLineTwinkle) + foreach (var perfline in _PerfectLineTwinkle) + { perfline.Draw(); + } - foreach (CParticleEffect stars in _GoldenStars) + foreach (var stars in _GoldenStars) { stars.Alpha = Alpha; stars.Draw(); } - foreach (CParticleEffect flare in _Flares) + foreach (var flare in _Flares) + { flare.Draw(); + } - foreach (CParticleEffect perfnote in _PerfectNoteEffect) + foreach (var perfnote in _PerfectNoteEffect) + { perfnote.Draw(); + } } private SRectF _GetNoteRect(CBaseNote note) { - CSongLine line = _Lines[_CurrentLine]; + var line = _Lines[_CurrentLine]; float beats = line.LastNoteBeat - line.FirstNoteBeat + 1; - bool isRapNote = note.IsRapNote; + var isRapNote = note.IsRapNote; - float width = note.Duration * Rect.W / beats; - float y = Rect.Y + (CBase.Settings.GetNumNoteLines() - 1 - (note.Tone - line.BaseLine) / 2f) * _NoteLineHeight - _AddNoteHeight / 2; - float height = _NoteLineHeight + _AddNoteHeight; + var width = note.Duration * Rect.W / beats; + var y = Rect.Y + (CBase.Settings.GetNumNoteLines() - 1 - (note.Tone - line.BaseLine) / 2f) * _NoteLineHeight - _AddNoteHeight / 2; + var height = _NoteLineHeight + _AddNoteHeight; var noteRect = new SRectF( Rect.X + (note.StartBeat - line.FirstNoteBeat) * Rect.W / beats, @@ -186,38 +209,46 @@ namespace VocaluxeLib.Menu.SingNotes width, height, Rect.Z - ); + ); return noteRect; } private void _DrawNoteLines(SColorF color) { - SRectF lineRect = Rect; + var lineRect = Rect; lineRect.H = 1.5f; - for (int i = 0; i < CBase.Settings.GetNumNoteLines(); i++) + for (var i = 0; i < CBase.Settings.GetNumNoteLines(); i++) { - lineRect.Y = (Rect.Y + Rect.H / CBase.Settings.GetNumNoteLines() * (i + 1)) - (lineRect.H / 2); + lineRect.Y = Rect.Y + Rect.H / CBase.Settings.GetNumNoteLines() * (i + 1) - lineRect.H / 2; CBase.Drawing.DrawRect(color, lineRect, false); } } private void _DrawToneHelper(CSongLine line, float offsetX) { - int tonePlayer = CBase.Record.GetToneAbs(_Player); - int noteIndex = line.FindPreviousNote(CBase.Game.GetCurrentBeat()).Clamp(0,line.Notes.Count()-1); - int note = line.Notes[noteIndex].Tone; + var tonePlayer = CBase.Record.GetToneAbs(_Player); + var noteIndex = line.FindPreviousNote(CBase.Game.GetCurrentBeat()).Clamp(0, line.Notes.Count() - 1); + var note = line.Notes[noteIndex].Tone; while (tonePlayer - note < -6) + { tonePlayer += 12; + } while (tonePlayer - note > 6) + { tonePlayer -= 12; + } if (offsetX < 0f) + { offsetX = 0f; + } if (offsetX > Rect.W) + { offsetX = Rect.W; + } var drawRect = new SRectF( Rect.X - _NoteLineHeight + offsetX, @@ -225,67 +256,68 @@ namespace VocaluxeLib.Menu.SingNotes _NoteLineHeight, _NoteLineHeight, Rect.Z - ); + ); var color = new SColorF(_Color, _Color.A * Alpha); - CTextureRef toneHelper = CBase.Themes.GetSkinTexture(_Theme.SkinToneHelper, _PartyModeID); + var toneHelper = CBase.Themes.GetSkinTexture(_Theme.SkinToneHelper, _PartyModeId); CBase.Drawing.DrawTexture(toneHelper, drawRect, color, false); } private static void _DrawNote(SRectF rect, SColorF color, CTextureRef noteBegin, CTextureRef noteMiddle, CTextureRef noteEnd, float factor) { if (factor <= 0) + { return; + } //Width-related variables rounded and then floored to prevent 1px gaps in notes rect.X = (float)Math.Round(rect.X); rect.W = (float)Math.Round(rect.W); - int dh = (int)((1f - factor) * rect.H / 2); - int dw = (int)Math.Min(dh, rect.W / 2); + var dh = (int)((1f - factor) * rect.H / 2); + var dw = (int)Math.Min(dh, rect.W / 2); var noteRect = new SRectF(rect.X + dw, rect.Y + dh, rect.W - 2 * dw, rect.H - 2 * dh, rect.Z); //Width of each of the ends (round parts) //Need 2 of them so use minimum - int endsW = (int)Math.Min(noteRect.H * noteBegin.OrigAspect, noteRect.W / 2); + var endsW = (int)Math.Min(noteRect.H * noteBegin.OrigAspect, noteRect.W / 2); CBase.Drawing.DrawTexture(noteBegin, new SRectF(noteRect.X, noteRect.Y, endsW, noteRect.H, noteRect.Z), color, false); - SRectF middleRect = new SRectF(noteRect.X + endsW, noteRect.Y, noteRect.W - 2 * endsW, noteRect.H, noteRect.Z); + var middleRect = new SRectF(noteRect.X + endsW, noteRect.Y, noteRect.W - 2 * endsW, noteRect.H, noteRect.Z); - int midW = (int)Math.Round(noteRect.H * noteMiddle.OrigAspect); + var midW = (int)Math.Round(noteRect.H * noteMiddle.OrigAspect); - int midCount = (int)middleRect.W / midW; + var midCount = (int)middleRect.W / midW; - for (int i = 0; i < midCount; ++i) + for (var i = 0; i < midCount; ++i) { - CBase.Drawing.DrawTexture(noteMiddle, new SRectF(middleRect.X + (i * midW), noteRect.Y, midW, noteRect.H, noteRect.Z), color, false); + CBase.Drawing.DrawTexture(noteMiddle, new SRectF(middleRect.X + i * midW, noteRect.Y, midW, noteRect.H, noteRect.Z), color, false); } - SRectF lastMidRect = new SRectF(middleRect.X + midCount * midW, noteRect.Y, middleRect.W - (midCount * midW), noteRect.H, noteRect.Z); + var lastMidRect = new SRectF(middleRect.X + midCount * midW, noteRect.Y, middleRect.W - midCount * midW, noteRect.H, noteRect.Z); - CBase.Drawing.DrawTexture(noteMiddle, new SRectF(middleRect.X + (midCount * midW), middleRect.Y, midW, middleRect.H, middleRect.Z), color, lastMidRect, false, false); + CBase.Drawing.DrawTexture(noteMiddle, new SRectF(middleRect.X + midCount * midW, middleRect.Y, midW, middleRect.H, middleRect.Z), color, lastMidRect, false, false); CBase.Drawing.DrawTexture(noteEnd, new SRectF(noteRect.X + noteRect.W - endsW, noteRect.Y, endsW, noteRect.H, noteRect.Z), color, false); } private void _DrawNoteBase(SRectF rect, SColorF color, float factor, bool isRapNote = false) { - CTextureRef noteBegin = CBase.Themes.GetSkinTexture(isRapNote ? _Theme.SkinRapLeft : _Theme.SkinLeft, _PartyModeID); - CTextureRef noteMiddle = CBase.Themes.GetSkinTexture(isRapNote ? _Theme.SkinRapMiddle : _Theme.SkinMiddle, _PartyModeID); - CTextureRef noteEnd = CBase.Themes.GetSkinTexture(isRapNote ? _Theme.SkinRapRight : _Theme.SkinRight, _PartyModeID); + var noteBegin = CBase.Themes.GetSkinTexture(isRapNote ? _Theme.SkinRapLeft : _Theme.SkinLeft, _PartyModeId); + var noteMiddle = CBase.Themes.GetSkinTexture(isRapNote ? _Theme.SkinRapMiddle : _Theme.SkinMiddle, _PartyModeId); + var noteEnd = CBase.Themes.GetSkinTexture(isRapNote ? _Theme.SkinRapRight : _Theme.SkinRight, _PartyModeId); _DrawNote(rect, color, noteBegin, noteMiddle, noteEnd, factor); } private void _DrawNoteFill(SRectF rect, SColorF color, float factor, bool isRapNote = false) { - - CTextureRef noteBegin = CBase.Themes.GetSkinTexture(isRapNote ? _Theme.SkinRapFillLeft : _Theme.SkinFillLeft, _PartyModeID); - CTextureRef noteMiddle = CBase.Themes.GetSkinTexture(isRapNote ? _Theme.SkinRapFillMiddle : _Theme.SkinFillMiddle, _PartyModeID); - CTextureRef noteEnd = CBase.Themes.GetSkinTexture(isRapNote ? _Theme.SkinRapFillRight : _Theme.SkinFillRight, _PartyModeID); + var noteBegin = CBase.Themes.GetSkinTexture(isRapNote ? _Theme.SkinRapFillLeft : _Theme.SkinFillLeft, _PartyModeId); + var noteMiddle = CBase.Themes.GetSkinTexture(isRapNote ? _Theme.SkinRapFillMiddle : _Theme.SkinFillMiddle, _PartyModeId); + var noteEnd = CBase.Themes.GetSkinTexture(isRapNote ? _Theme.SkinRapFillRight : _Theme.SkinFillRight, _PartyModeId); _DrawNote(rect, color, noteBegin, noteMiddle, noteEnd, factor); } @@ -295,18 +327,22 @@ namespace VocaluxeLib.Menu.SingNotes const float period = 1500; //[ms] if (!_Timer.IsRunning) + { _Timer.Start(); + } if (_Timer.ElapsedMilliseconds > period) + { _Timer.Restart(); + } - float alpha = (float)(Math.Cos(_Timer.ElapsedMilliseconds / period * Math.PI * 2) + 1) / 4 + 0.5f; + var alpha = (float)(Math.Cos(_Timer.ElapsedMilliseconds / period * Math.PI * 2) + 1) / 4 + 0.5f; var col = new SColorF(color, color.A * alpha); - CTextureRef noteBegin = CBase.Themes.GetSkinTexture(isRapNote ? _Theme.SkinRapBackgroundLeft : _Theme.SkinBackgroundLeft, _PartyModeID); - CTextureRef noteMiddle = CBase.Themes.GetSkinTexture(isRapNote ? _Theme.SkinRapBackgroundMiddle : _Theme.SkinBackgroundMiddle, _PartyModeID); - CTextureRef noteEnd = CBase.Themes.GetSkinTexture(isRapNote ? _Theme.SkinRapBackgroundRight : _Theme.SkinBackgroundRight, _PartyModeID); + var noteBegin = CBase.Themes.GetSkinTexture(isRapNote ? _Theme.SkinRapBackgroundLeft : _Theme.SkinBackgroundLeft, _PartyModeId); + var noteMiddle = CBase.Themes.GetSkinTexture(isRapNote ? _Theme.SkinRapBackgroundMiddle : _Theme.SkinBackgroundMiddle, _PartyModeId); + var noteEnd = CBase.Themes.GetSkinTexture(isRapNote ? _Theme.SkinRapBackgroundRight : _Theme.SkinBackgroundRight, _PartyModeId); _DrawNote(rect, col, noteBegin, noteMiddle, noteEnd, 1f); } @@ -314,7 +350,7 @@ namespace VocaluxeLib.Menu.SingNotes private void _AddGoldenNote(SRectF noteRect) { var numstars = (int)(noteRect.W * 0.25f); - var stars = new CParticleEffect(_PartyModeID, numstars, new SColorF(Color.Yellow), noteRect, _Theme.SkinGoldenStar, 20, EParticleType.Star); + var stars = new CParticleEffect(_PartyModeId, numstars, new SColorF(Color.Yellow), noteRect, _Theme.SkinGoldenStar, 20, EParticleType.Star); stars.AllMonitors = false; _GoldenStars.Add(stars); } @@ -323,31 +359,33 @@ namespace VocaluxeLib.Menu.SingNotes { var rect = new SRectF(noteRect.Right, noteRect.Y, 0f, noteRect.H, noteRect.Z); - var flares = new CParticleEffect(_PartyModeID, 15, new SColorF(Color.White), rect, _Theme.SkinGoldenStar, 20, EParticleType.Flare); + var flares = new CParticleEffect(_PartyModeId, 15, new SColorF(Color.White), rect, _Theme.SkinGoldenStar, 20, EParticleType.Flare); flares.AllMonitors = false; _Flares.Add(flares); } private void _AddPerfectNote(SRectF noteRect) { - CTextureRef noteBegin = CBase.Themes.GetSkinTexture(_Theme.SkinRight, _PartyModeID); - float dx = noteRect.H * noteBegin.OrigAspect; + var noteBegin = CBase.Themes.GetSkinTexture(_Theme.SkinRight, _PartyModeId); + var dx = noteRect.H * noteBegin.OrigAspect; if (2 * dx > noteRect.W) + { dx = noteRect.W / 2; + } - SRectF r = new SRectF(noteRect.Right - dx, noteRect.Y, dx * 0.5f, dx * 0.2f, noteRect.Z); + var r = new SRectF(noteRect.Right - dx, noteRect.Y, dx * 0.5f, dx * 0.2f, noteRect.Z); - var stars = new CParticleEffect(_PartyModeID, CBase.Game.GetRandom(2) + 1, new SColorF(Color.White), r, _Theme.SkinPerfectNoteStart, 35, - EParticleType.PerfNoteStar); + var stars = new CParticleEffect(_PartyModeId, CBase.Game.GetRandom(2) + 1, new SColorF(Color.White), r, _Theme.SkinPerfectNoteStart, 35, + EParticleType.PerfNoteStar); stars.AllMonitors = false; _PerfectNoteEffect.Add(stars); } private void _AddPerfectLine() { - var twinkle = new CParticleEffect(_PartyModeID, 200, _Color, Rect, _Theme.SkinGoldenStar, 25, EParticleType.Twinkle); + var twinkle = new CParticleEffect(_PartyModeId, 200, _Color, Rect, _Theme.SkinGoldenStar, 25, EParticleType.Twinkle); twinkle.AllMonitors = false; _PerfectLineTwinkle.Add(twinkle); } } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Menu/SingNotes/CSingNotes.cs b/VocaluxeLib/Menu/SingNotes/CSingNotes.cs index 4d49befc..59ef2917 100644 --- a/VocaluxeLib/Menu/SingNotes/CSingNotes.cs +++ b/VocaluxeLib/Menu/SingNotes/CSingNotes.cs @@ -71,7 +71,7 @@ namespace VocaluxeLib.Menu.SingNotes public class CSingNotes : CMenuElementBase, IMenuElement, IThemeable { - private readonly int _PartyModeID; + private readonly int _PartyModeId; private SThemeSingBar _Theme; public readonly List PlayerNotes = new List(); @@ -95,16 +95,16 @@ namespace VocaluxeLib.Menu.SingNotes /// private SRectF[,,] _BarPos { get; set; } - public CSingNotes(int partyModeID) + public CSingNotes(int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = new SThemeSingBar { BarPos = new SBarPosition[CHelper.Sum(CBase.Settings.GetMaxNumPlayer() * CBase.Settings.GetMaxNumScreens())] }; ThemeLoaded = false; } - public CSingNotes(SThemeSingBar theme, int partyModeID) + public CSingNotes(SThemeSingBar theme, int partyModeId) { - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = theme; _BarPos = new SRectF[CBase.Settings.GetMaxNumScreens(), CBase.Settings.GetMaxNumPlayer(), CBase.Settings.GetMaxNumPlayer()]; @@ -121,45 +121,46 @@ namespace VocaluxeLib.Menu.SingNotes public void Init(int numPlayers, int numScreens = 0) { - PlayerNotes.Clear(); if (numPlayers > 0 && numScreens > 0) { - int[] screenAssignment = new int[numPlayers]; - int screenPlayers = numPlayers / numScreens; - int remainingPlayers = numPlayers - (screenPlayers * numScreens); - int player = 0; + var screenAssignment = new int[numPlayers]; + var screenPlayers = numPlayers / numScreens; + var remainingPlayers = numPlayers - screenPlayers * numScreens; + var player = 0; - for (int s = 0; s < numScreens; s++) + for (var s = 0; s < numScreens; s++) { - for (int p = 0; p < screenPlayers; p++) + for (var p = 0; p < screenPlayers; p++) { if (remainingPlayers > 0) { - PlayerNotes.Add(new CNoteBars(_PartyModeID, player++, _BarPos[s, p, screenPlayers], _Theme)); + PlayerNotes.Add(new CNoteBars(_PartyModeId, player++, _BarPos[s, p, screenPlayers], _Theme)); if (p == screenPlayers - 1) { - PlayerNotes.Add(new CNoteBars(_PartyModeID, player++, _BarPos[s, p + 1, screenPlayers], _Theme)); + PlayerNotes.Add(new CNoteBars(_PartyModeId, player++, _BarPos[s, p + 1, screenPlayers], _Theme)); remainingPlayers--; } } else { - PlayerNotes.Add(new CNoteBars(_PartyModeID, player++, _BarPos[s, p, screenPlayers - 1], _Theme)); + PlayerNotes.Add(new CNoteBars(_PartyModeId, player++, _BarPos[s, p, screenPlayers - 1], _Theme)); } - } + //Handle when players < screens if (screenPlayers == 0 && remainingPlayers > 0) { - PlayerNotes.Add(new CNoteBars(_PartyModeID, player++, _BarPos[s, 0, 0], _Theme)); + PlayerNotes.Add(new CNoteBars(_PartyModeId, player++, _BarPos[s, 0, 0], _Theme)); remainingPlayers--; } } } if (numPlayers == 0) + { _Rect = new SRectF(0, 0, 0, 0, Rect.Z); + } else { _Rect.X = PlayerNotes.Select(bp => bp.Rect.X).Min(); @@ -172,8 +173,10 @@ namespace VocaluxeLib.Menu.SingNotes public void Draw() { - foreach (CNoteBars noteBars in PlayerNotes) + foreach (var noteBars in PlayerNotes) + { noteBars.Draw(); + } } public void UnloadSkin() { } @@ -186,11 +189,11 @@ namespace VocaluxeLib.Menu.SingNotes W = X - _Theme.BarPos.Select(bp => bp.Rect.Right).Max(); H = Y - _Theme.BarPos.Select(bp => bp.Rect.Bottom).Max(); Z = _Theme.BarPos.Select(bp => bp.Rect.Z).Average(); - foreach (SBarPosition bp in _Theme.BarPos) + foreach (var bp in _Theme.BarPos) { - int n = Int32.Parse(bp.Name.Substring(3, 1)) - 1; - int p = Int32.Parse(bp.Name.Substring(1, 1)) - 1; - for (int s = 0; s < CBase.Settings.GetMaxNumScreens(); s++) + var n = Int32.Parse(bp.Name.Substring(3, 1)) - 1; + var p = Int32.Parse(bp.Name.Substring(1, 1)) - 1; + for (var s = 0; s < CBase.Settings.GetMaxNumScreens(); s++) { _BarPos[s, p, n] = bp.Rect; _BarPos[s, p, n].X += s * CBase.Settings.GetRenderW(); @@ -215,4 +218,4 @@ namespace VocaluxeLib.Menu.SingNotes public void ResizeElement(int stepW, int stepH) { } #endregion ThemeEdit } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Menu/SongMenu/CSongMenuFactory.cs b/VocaluxeLib/Menu/SongMenu/CSongMenuFactory.cs index fe4bbb73..a0838773 100644 --- a/VocaluxeLib/Menu/SongMenu/CSongMenuFactory.cs +++ b/VocaluxeLib/Menu/SongMenu/CSongMenuFactory.cs @@ -21,34 +21,27 @@ namespace VocaluxeLib.Menu.SongMenu { public static class CSongMenuFactory { - public static ISongMenu CreateSongMenu(SThemeSongMenu theme, int partyModeID) + public static ISongMenu CreateSongMenu(SThemeSongMenu theme, int partyModeId) { switch (CBase.Config.GetSongMenuType()) { case ESongMenu.TR_CONFIG_LIST: - return new CSongMenuList(theme, partyModeID); - - //case ESongMenu.TR_CONFIG_DREIDEL: - // _SongMenu = new CSongMenuDreidel(); - // break; + return new CSongMenuList(theme, partyModeId); case ESongMenu.TR_CONFIG_TILE_BOARD: - return new CSongMenuTileBoard(theme, partyModeID); - - //case ESongMenu.TR_CONFIG_BOOK: - // _SongMenu = new CSongMenuBook(); - // break; + return new CSongMenuTileBoard(theme, partyModeId); } + throw new ArgumentException("Invalid songmenu type: " + CBase.Config.GetSongMenuType()); } /// /// Deprecated! Only used for old theme loading. /// - /// + /// /// - public static ISongMenu CreateSongMenu(int partyModeID) + public static ISongMenu CreateSongMenu(int partyModeId) { - return new CSongMenuTileBoard(partyModeID); + return new CSongMenuTileBoard(partyModeId); } } } \ No newline at end of file diff --git a/VocaluxeLib/Menu/SongMenu/CSongMenuFramework.cs b/VocaluxeLib/Menu/SongMenu/CSongMenuFramework.cs index f25f5c30..0be434ee 100644 --- a/VocaluxeLib/Menu/SongMenu/CSongMenuFramework.cs +++ b/VocaluxeLib/Menu/SongMenu/CSongMenuFramework.cs @@ -18,14 +18,14 @@ using System.Diagnostics; using System.Xml.Serialization; using VocaluxeLib.PartyModes; -using VocaluxeLib.Songs; namespace VocaluxeLib.Menu.SongMenu { [XmlType("SongMenu")] public struct SThemeSongMenu { - [XmlAttribute(AttributeName = "Name")] public string Name; + [XmlAttribute(AttributeName = "Name")] + public string Name; public string CoverBackground; public string CoverBigBackground; @@ -43,6 +43,7 @@ namespace VocaluxeLib.Menu.SongMenu public SThemeSongMenuList SongMenuList; public SThemeSongMenuTileBoard SongMenuTileBoard; } + public struct SThemeSongMenuList { /// @@ -79,7 +80,6 @@ namespace VocaluxeLib.Menu.SongMenu public SThemeStatic StaticMedleyTagIcon; } - public struct SThemeSongMenuTileBoard { /// @@ -133,7 +133,7 @@ namespace VocaluxeLib.Menu.SongMenu public abstract class CSongMenuFramework : CMenuElementBase, ISongMenu { - protected readonly int _PartyModeID; + protected readonly int _PartyModeId; protected SThemeSongMenu _Theme; public bool ThemeLoaded { get; private set; } @@ -152,11 +152,17 @@ namespace VocaluxeLib.Menu.SongMenu set { if (_PreviewNrInternal == value) + { return; + } + if (CBase.Songs.IsInCategory()) { if (value >= CBase.Songs.GetNumSongsVisible()) + { value = -1; + } + _PlaySong(value); } else if (value >= CBase.Songs.GetNumCategories()) @@ -188,16 +194,16 @@ namespace VocaluxeLib.Menu.SongMenu // This is the nr of the current selection (song or category) protected virtual int _SelectionNr { get; set; } - protected CSongMenuFramework(int partyModeID) + protected CSongMenuFramework(int partyModeId) { Visible = true; - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; } - protected CSongMenuFramework(SThemeSongMenu theme, int partyModeID) + protected CSongMenuFramework(SThemeSongMenu theme, int partyModeId) { Visible = true; - _PartyModeID = partyModeID; + _PartyModeId = partyModeId; _Theme = theme; ThemeLoaded = true; @@ -228,11 +234,16 @@ namespace VocaluxeLib.Menu.SongMenu public virtual void OnHide() { - EScreen check = CBase.Graphics.GetNextScreenType(); + var check = CBase.Graphics.GetNextScreenType(); if (CBase.Graphics.GetNextScreenType() == EScreen.Sing) + { _ResetPreview(false); - else if ((CBase.Graphics.GetNextScreenType() != EScreen.Names && CBase.Graphics.GetNextScreenType() != EScreen.Highscore) || CBase.Config.GetBackgroundMusicStatus() == EBackgroundMusicOffOn.TR_CONFIG_OFF) + } + else if ((CBase.Graphics.GetNextScreenType() != EScreen.Names && CBase.Graphics.GetNextScreenType() != EScreen.Highscore) || + CBase.Config.GetBackgroundMusicStatus() == EBackgroundMusicOffOn.TR_CONFIG_OFF) + { _ResetPreview(); + } } public abstract bool HandleInput(ref SKeyEvent keyEvent, SScreenSongOptions options); @@ -242,29 +253,39 @@ namespace VocaluxeLib.Menu.SongMenu public virtual void Draw() { if (!_Initialized || !Visible) + { return; + } if (CBase.BackgroundMusic.IsPlaying()) + { CBase.Drawing.DrawTexture(CBase.BackgroundMusic.GetVideoTexture(), new SRectF(0, 0, 1920, 1080, 0)); + } } public virtual bool IsMouseOverSelectedSong(SMouseEvent mEvent) { - CStatic selCov = GetSelectedSongCover(); + var selCov = GetSelectedSongCover(); return selCov != null && CHelper.IsInBounds(selCov.Rect.Scale(SelectedTileZoomFactor), mEvent); } public int GetPreviewSongNr() { if (CBase.Songs.IsInCategory()) + { return _PreviewNr; + } + return -1; } public int GetSelectedSongNr() { if (CBase.Songs.IsInCategory()) + { return _SelectionNr; + } + return -1; } @@ -273,7 +294,10 @@ namespace VocaluxeLib.Menu.SongMenu public int GetSelectedCategory() { if (!CBase.Songs.IsInCategory()) + { return _SelectionNr; + } + return -1; } @@ -281,9 +305,14 @@ namespace VocaluxeLib.Menu.SongMenu { Debug.Assert(CBase.Songs.IsInCategory()); if (visibleSongNr >= 0 && visibleSongNr < CBase.Songs.GetNumSongsVisible()) + { _SelectionNr = visibleSongNr; + } else + { _SelectionNr = -1; + } + _PreviewNr = _SelectionNr; } @@ -291,33 +320,44 @@ namespace VocaluxeLib.Menu.SongMenu { Debug.Assert(!CBase.Songs.IsInCategory()); if (categoryNr >= 0 && categoryNr < CBase.Songs.GetNumCategories()) + { _SelectionNr = categoryNr; + } else + { _SelectionNr = -1; + } + _PreviewNr = _SelectionNr; } public void LeaveSelectedCategory() { if (!CBase.Songs.IsInCategory()) + { return; + } - int oldCategory = CBase.Songs.GetCurrentCategoryIndex(); + var oldCategory = CBase.Songs.GetCurrentCategoryIndex(); _LeaveCategory(); if (oldCategory >= 0 && oldCategory < CBase.Songs.GetNumCategories()) + { SetSelectedCategory(oldCategory); + } else if (CBase.Songs.GetNumCategories() > 0) + { SetSelectedCategory(0); + } } - public virtual void UnloadSkin() {} + public virtual void UnloadSkin() { } public virtual void LoadSkin() { Init(); - _Theme.Color.Get(_PartyModeID, out _ColorInternal); + _Theme.Color.Get(_PartyModeId, out _ColorInternal); } public void ReloadSkin() @@ -329,9 +369,15 @@ namespace VocaluxeLib.Menu.SongMenu public bool EnterSelectedCategory() { if (!_Initialized) + { return false; + } + if (CBase.Songs.IsInCategory() || GetSelectedCategory() < 0 || GetSelectedCategory() >= CBase.Songs.GetNumCategories()) + { return false; + } + _EnterCategory(GetSelectedCategory()); return true; } @@ -339,10 +385,14 @@ namespace VocaluxeLib.Menu.SongMenu protected virtual void _EnterCategory(int categoryNr) { if (!_Initialized) + { return; + } if (categoryNr >= CBase.Songs.GetNumCategories()) + { return; + } _ResetPreview(false); CBase.Songs.SetCategory(categoryNr); @@ -351,10 +401,14 @@ namespace VocaluxeLib.Menu.SongMenu protected virtual void _LeaveCategory() { if (!_Initialized) + { return; + } if (!CBase.Songs.IsInCategory()) + { return; + } _ResetPreview(); CBase.Songs.SetCategory(-1); @@ -364,9 +418,11 @@ namespace VocaluxeLib.Menu.SongMenu { _PreviewNrInternal = -1; - CSong song = CBase.Songs.GetVisibleSong(nr); + var song = CBase.Songs.GetVisibleSong(nr); if (song == null) + { return; + } CBase.BackgroundMusic.LoadPreview(song, song.Preview.StartTime); } @@ -374,12 +430,16 @@ namespace VocaluxeLib.Menu.SongMenu protected void _ResetPreview(bool playBGagain = true) { if (_PreviewNrInternal == -1) + { return; + } CBase.BackgroundMusic.StopPreview(); CBase.Sound.SetGlobalVolume(CBase.Config.GetMusicVolume(EMusicType.Background)); if (playBGagain) + { CBase.BackgroundMusic.Play(); + } //Make sure we don't have a preview here otherwise a change won't be recognized //(e.g. leave a category with one song and set preview to 0 --> previewOld=previewNew=0 --> No change --> Old data shown @@ -396,10 +456,7 @@ namespace VocaluxeLib.Menu.SongMenu { _AutoplayTimer.Interval = _AutoplayDelayinMs; _AutoplayTimer.AutoReset = false; - _AutoplayTimer.Elapsed += (object sender, System.Timers.ElapsedEventArgs e) => - { - _PreviewSelectedSong(); - }; + _AutoplayTimer.Elapsed += (object sender, System.Timers.ElapsedEventArgs e) => { _PreviewSelectedSong(); }; } protected void _AutoplayPreviewIfEnabled() @@ -408,7 +465,7 @@ namespace VocaluxeLib.Menu.SongMenu { _PlayPreviewAfterDelay(); } - } + } protected void _PlayPreviewAfterDelay() { @@ -435,14 +492,18 @@ namespace VocaluxeLib.Menu.SongMenu { W += stepW; if (W < 100) + { W = 100; + } H += stepH; if (H < 100) + { H = 100; + } Init(); } #endregion ThemeEdit } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Menu/SongMenu/CSongMenuList.cs b/VocaluxeLib/Menu/SongMenu/CSongMenuList.cs index f449993d..299946a9 100644 --- a/VocaluxeLib/Menu/SongMenu/CSongMenuList.cs +++ b/VocaluxeLib/Menu/SongMenu/CSongMenuList.cs @@ -77,7 +77,7 @@ namespace VocaluxeLib.Menu.SongMenu { set { - int max = CBase.Songs.IsInCategory() ? CBase.Songs.GetNumSongsVisible() : CBase.Songs.GetNumCategories(); + var max = CBase.Songs.IsInCategory() ? CBase.Songs.GetNumSongsVisible() : CBase.Songs.GetNumCategories(); base._SelectionNr = value.Clamp(-1, max - 1, true); //Update list in case we scrolled _UpdateList(); @@ -91,7 +91,10 @@ namespace VocaluxeLib.Menu.SongMenu set { if (SmallView == value) + { return; + } + base.SmallView = value; _InitTiles(); _UpdateList(true); @@ -106,33 +109,38 @@ namespace VocaluxeLib.Menu.SongMenu if (value == base._PreviewNr) { if (!CBase.BackgroundMusic.IsPlaying() && value != -1) + { CBase.BackgroundMusic.Play(); + } + return; } + base._PreviewNr = value; _UpdatePreview(); } } - public CSongMenuList(SThemeSongMenu theme, int partyModeID) : base(theme, partyModeID) + public CSongMenuList(SThemeSongMenu theme, int partyModeId) : base(theme, partyModeId) { _ListLength = _Theme.SongMenuList.ListLength; _SpaceW = _Theme.SongMenuList.SpaceW; _SpaceH = _Theme.SongMenuList.SpaceH; - _Artist = new CText(_Theme.SongMenuList.TextArtist, _PartyModeID); - _Title = new CText(_Theme.SongMenuList.TextTitle, _PartyModeID); - _SongLength = new CText(_Theme.SongMenuList.TextSongLength, _PartyModeID); - _SongYear = new CText(_Theme.SongMenuList.TextSongYear, _PartyModeID); - _CoverBig = new CStatic(_Theme.SongMenuList.StaticCoverBig, _PartyModeID); - _TextBG = new CStatic(_Theme.SongMenuList.StaticTextBG, _PartyModeID); - _DuetIcon = new CStatic(_Theme.SongMenuList.StaticDuetIcon, _PartyModeID); - _RapIcon = new CStatic(_Theme.SongMenuList.StaticRapIcon, _PartyModeID); - _VideoIcon = new CStatic(_Theme.SongMenuList.StaticVideoIcon, _PartyModeID); - _MedleyCalcIcon = new CStatic(_Theme.SongMenuList.StaticMedleyCalcIcon, _PartyModeID); - _MedleyTagIcon = new CStatic(_Theme.SongMenuList.StaticMedleyTagIcon, _PartyModeID); - _InstrumentalIcon = new CStatic(_Theme.SongMenuList.StaticInstrumentalIcon, _PartyModeID); - _VocalsIcon = new CStatic(_Theme.SongMenuList.StaticVocalsIcon, _PartyModeID); - _SubElements.AddRange(new IMenuElement[] {_Artist, _Title, _SongLength, _SongYear, _DuetIcon, _RapIcon, _VideoIcon, _MedleyCalcIcon, _MedleyTagIcon, _InstrumentalIcon, _VocalsIcon}); + _Artist = new CText(_Theme.SongMenuList.TextArtist, _PartyModeId); + _Title = new CText(_Theme.SongMenuList.TextTitle, _PartyModeId); + _SongLength = new CText(_Theme.SongMenuList.TextSongLength, _PartyModeId); + _SongYear = new CText(_Theme.SongMenuList.TextSongYear, _PartyModeId); + _CoverBig = new CStatic(_Theme.SongMenuList.StaticCoverBig, _PartyModeId); + _TextBG = new CStatic(_Theme.SongMenuList.StaticTextBG, _PartyModeId); + _DuetIcon = new CStatic(_Theme.SongMenuList.StaticDuetIcon, _PartyModeId); + _RapIcon = new CStatic(_Theme.SongMenuList.StaticRapIcon, _PartyModeId); + _VideoIcon = new CStatic(_Theme.SongMenuList.StaticVideoIcon, _PartyModeId); + _MedleyCalcIcon = new CStatic(_Theme.SongMenuList.StaticMedleyCalcIcon, _PartyModeId); + _MedleyTagIcon = new CStatic(_Theme.SongMenuList.StaticMedleyTagIcon, _PartyModeId); + _InstrumentalIcon = new CStatic(_Theme.SongMenuList.StaticInstrumentalIcon, _PartyModeId); + _VocalsIcon = new CStatic(_Theme.SongMenuList.StaticVocalsIcon, _PartyModeId); + _SubElements.AddRange(new IMenuElement[] + { _Artist, _Title, _SongLength, _SongYear, _DuetIcon, _RapIcon, _VideoIcon, _MedleyCalcIcon, _MedleyTagIcon, _InstrumentalIcon, _VocalsIcon }); } private void _ReadSubTheme() @@ -173,36 +181,36 @@ namespace VocaluxeLib.Menu.SongMenu _TileW = (int)((MaxRect.H - _SpaceH * (_ListLength - 1)) / _ListLength); _TileH = _TileW; - float _ListTextWidth = MaxRect.W - (_TileW + _SpaceW); + var _ListTextWidth = MaxRect.W - (_TileW + _SpaceW); - _CoverBGTexture = CBase.Themes.GetSkinTexture(_Theme.CoverBackground, _PartyModeID); - _CoverBigBGTexture = CBase.Themes.GetSkinTexture(_Theme.CoverBigBackground, _PartyModeID); + _CoverBGTexture = CBase.Themes.GetSkinTexture(_Theme.CoverBackground, _PartyModeId); + _CoverBigBGTexture = CBase.Themes.GetSkinTexture(_Theme.CoverBigBackground, _PartyModeId); //Create cover tiles _RowBackgrounds = new List(); _Tiles = new List(); _Texts = new List(); - for (int i = 0; i < _ListLength; i++) + for (var i = 0; i < _ListLength; i++) { //Create Cover - float y = Rect.Y + i * (_TileH + _SpaceH); + var y = Rect.Y + i * (_TileH + _SpaceH); - float bgHeight = _TileH + 8f; + var bgHeight = _TileH + 8f; var rowRect = new SRectF(Rect.X, y - 4f, Rect.W, bgHeight, Rect.Z + 0.05f); - var rowBackground = new CStatic(_PartyModeID, _CoverBGTexture, _Color, rowRect); + var rowBackground = new CStatic(_PartyModeId, _CoverBGTexture, _Color, rowRect); rowBackground.Color = new SColorF(1f, 1f, 1f, 0f); _RowBackgrounds.Add(rowBackground); var rect = new SRectF(Rect.X, y, _TileW, _TileH, Rect.Z); - var tile = new CStatic(_PartyModeID, _CoverBGTexture, _Color, rect); + var tile = new CStatic(_PartyModeId, _CoverBGTexture, _Color, rect); _Tiles.Add(tile); //Create text var textRect = new SRectF(MaxRect.X + (_TileW + _SpaceW), y, _ListTextWidth, _TileH, Rect.Z); - CText text = new CText(textRect.X, textRect.Y, textRect.Z, textRect.H, textRect.W, EAlignment.Left, EStyle.Normal, "Normal", _Artist.Color, ""); - + var text = new CText(textRect.X, textRect.Y, textRect.Z, textRect.H, textRect.W, EAlignment.Left, EStyle.Normal, "Normal", _Artist.Color, ""); + text.MaxRect = new SRectF(text.MaxRect.X, text.MaxRect.Y, MaxRect.W + MaxRect.X - text.Rect.X - 5f, text.MaxRect.H, text.MaxRect.Z); text.ResizeAlign = EHAlignment.Center; @@ -213,42 +221,50 @@ namespace VocaluxeLib.Menu.SongMenu } private void _UpdateTileSelection() -{ - for (int i = 0; i < _Tiles.Count; i++) - { - _Tiles[i].Selected = false; + { + for (var i = 0; i < _Tiles.Count; i++) + { + _Tiles[i].Selected = false; - if (i < _RowBackgrounds.Count) - _RowBackgrounds[i].Color = new SColorF(1f, 1f, 1f, 0f); - } + if (i < _RowBackgrounds.Count) + { + _RowBackgrounds[i].Color = new SColorF(1f, 1f, 1f, 0f); + } + } - int tileNr = _SelectionNr - _Offset; - if (tileNr >= 0 && tileNr < _Tiles.Count) - { - _Tiles[tileNr].Selected = true; + var tileNr = _SelectionNr - _Offset; + if (tileNr >= 0 && tileNr < _Tiles.Count) + { + _Tiles[tileNr].Selected = true; - if (tileNr < _RowBackgrounds.Count) - _RowBackgrounds[tileNr].Color = new SColorF(1f, 1f, 1f, 0.25f); - } -} + if (tileNr < _RowBackgrounds.Count) + { + _RowBackgrounds[tileNr].Color = new SColorF(1f, 1f, 1f, 0.25f); + } + } + } public override void Update(SScreenSongOptions songOptions) { if (songOptions.Selection.RandomOnly) + { _PreviewSelectedSong(); + } if (_Length < 0 && CBase.Songs.IsInCategory() && CBase.BackgroundMusic.GetLength() > 0) + { _UpdateLength(CBase.Songs.GetVisibleSong(_PreviewNr)); + } } private void _UpdatePreview() { //First hide everything so we just have to set what we actually want _CoverBig.Texture = _CoverBigBGTexture; - _Artist.Text = String.Empty; - _Title.Text = String.Empty; - _SongLength.Text = String.Empty; - _SongYear.Text = String.Empty; + _Artist.Text = string.Empty; + _Title.Text = string.Empty; + _SongLength.Text = string.Empty; + _SongYear.Text = string.Empty; _DuetIcon.Visible = false; _RapIcon.Visible = false; _VideoIcon.Visible = false; @@ -260,23 +276,29 @@ namespace VocaluxeLib.Menu.SongMenu //Check if nothing is selected (for preview) if (_PreviewNr < 0) + { return; + } if (CBase.Songs.IsInCategory()) { - CSong song = CBase.Songs.GetVisibleSong(_PreviewNr); + var song = CBase.Songs.GetVisibleSong(_PreviewNr); //Check if we have a valid song (song still visible, index >=0 etc is checked by framework) if (song == null) { //Display at least the category - CCategory category = CBase.Songs.GetCategory(CBase.Songs.GetCurrentCategoryIndex()); + var category = CBase.Songs.GetCategory(CBase.Songs.GetCurrentCategoryIndex()); //Check if we have a valid category if (category == null) + { return; + } + _CoverBig.Texture = category.CoverTextureBig; _Artist.Text = category.Name; return; } + _CoverBig.Texture = song.CoverTextureBig; _Artist.Text = song.Artist; _Title.Text = song.Title; @@ -293,15 +315,18 @@ namespace VocaluxeLib.Menu.SongMenu } else { - CCategory category = CBase.Songs.GetCategory(_PreviewNr); + var category = CBase.Songs.GetCategory(_PreviewNr); //Check if we have a valid category if (category == null) + { return; + } + _CoverBig.Texture = category.CoverTextureBig; _Artist.Text = category.Name; - int num = category.GetNumSongsNotSung(); - String songOrSongs = (num == 1) ? "TR_SCREENSONG_NUMSONG" : "TR_SCREENSONG_NUMSONGS"; + var num = category.GetNumSongsNotSung(); + var songOrSongs = num == 1 ? "TR_SCREENSONG_NUMSONG" : "TR_SCREENSONG_NUMSONGS"; _Title.Text = CBase.Language.Translate(songOrSongs).Replace("%v", num.ToString()); } } @@ -309,10 +334,15 @@ namespace VocaluxeLib.Menu.SongMenu private void _UpdateLength(CSong song) { if (song == null) + { return; - float time = CBase.BackgroundMusic.GetLength(); - if (Math.Abs(song.Finish) > 0.001) - time = song.Finish; + } + + var time = CBase.BackgroundMusic.GetLength(); + if (Math.Abs(song.End) > 0.001) + { + time = song.End; + } // The audiobackend is ready to return the length if (time > 0) @@ -324,7 +354,9 @@ namespace VocaluxeLib.Menu.SongMenu _Length = time; } else + { _SongLength.Text = "..."; + } } public override void OnShow() @@ -333,12 +365,20 @@ namespace VocaluxeLib.Menu.SongMenu if (!CBase.Songs.IsInCategory()) { if ((CBase.Songs.GetTabs() == EOffOn.TR_CONFIG_OFF && CBase.Songs.GetNumCategories() > 0) || CBase.Songs.GetNumCategories() == 1) + { _EnterCategory(0); + } } + if (CBase.Songs.IsInCategory()) + { SetSelectedSong(_SelectionNr < 0 ? 0 : _SelectionNr); + } else + { SetSelectedCategory(_SelectionNr < 0 ? 0 : _SelectionNr); + } + _PreviewSelectedSong(); _UpdateListIfRequired(); } @@ -346,14 +386,18 @@ namespace VocaluxeLib.Menu.SongMenu public override bool HandleInput(ref SKeyEvent keyEvent, SScreenSongOptions options) { if (keyEvent.KeyPressed) + { return false; + } - bool moveAllowed = !options.Selection.RandomOnly || (options.Selection.CategoryChangeAllowed && !CBase.Songs.IsInCategory()); - bool catChangePossible = CBase.Songs.GetTabs() == EOffOn.TR_CONFIG_ON && options.Selection.CategoryChangeAllowed; + var moveAllowed = !options.Selection.RandomOnly || (options.Selection.CategoryChangeAllowed && !CBase.Songs.IsInCategory()); + var catChangePossible = CBase.Songs.GetTabs() == EOffOn.TR_CONFIG_ON && options.Selection.CategoryChangeAllowed; //If nothing selected set a reasonable default value if (keyEvent.IsArrowKey() && moveAllowed && _SelectionNr < 0) - _SelectionNr = (_PreviewNr < 0) ? _Offset : _PreviewNr; + { + _SelectionNr = _PreviewNr < 0 ? _Offset : _PreviewNr; + } switch (keyEvent.Key) { @@ -371,6 +415,7 @@ namespace VocaluxeLib.Menu.SongMenu _EnterCategory(_PreviewNr); keyEvent.Handled = true; } + break; case Keys.Escape: @@ -380,6 +425,7 @@ namespace VocaluxeLib.Menu.SongMenu LeaveSelectedCategory(); keyEvent.Handled = true; } + break; case Keys.PageUp: @@ -390,12 +436,18 @@ namespace VocaluxeLib.Menu.SongMenu } else if (moveAllowed) { - if ((_SelectionNr - _ListLength) <= 0) + if (_SelectionNr - _ListLength <= 0) + { _SelectionNr = 0; + } else + { _SelectionNr = _SelectionNr - _ListLength; + } + keyEvent.Handled = true; } + break; case Keys.PageDown: @@ -406,13 +458,20 @@ namespace VocaluxeLib.Menu.SongMenu } else if (moveAllowed) { - int maxCount_PageDown = (CBase.Songs.GetTabs() == EOffOn.TR_CONFIG_ON && !CBase.Songs.IsInCategory() ? CBase.Songs.GetNumCategories() : CBase.Songs.GetNumSongsVisible()); - if ((_SelectionNr + _ListLength) >= maxCount_PageDown) + var maxCount_PageDown = CBase.Songs.GetTabs() == EOffOn.TR_CONFIG_ON && !CBase.Songs.IsInCategory() ? CBase.Songs.GetNumCategories() + : CBase.Songs.GetNumSongsVisible(); + if (_SelectionNr + _ListLength >= maxCount_PageDown) + { _SelectionNr = maxCount_PageDown - 1; + } else + { _SelectionNr = _SelectionNr + _ListLength; + } + keyEvent.Handled = true; } + break; case Keys.Home: @@ -421,15 +480,18 @@ namespace VocaluxeLib.Menu.SongMenu _SelectionNr = 0; keyEvent.Handled = true; } + break; case Keys.End: - int maxCount_End = (CBase.Songs.GetTabs() == EOffOn.TR_CONFIG_ON && !CBase.Songs.IsInCategory() ? CBase.Songs.GetNumCategories() : CBase.Songs.GetNumSongsVisible()); + var maxCount_End = CBase.Songs.GetTabs() == EOffOn.TR_CONFIG_ON && !CBase.Songs.IsInCategory() ? CBase.Songs.GetNumCategories() + : CBase.Songs.GetNumSongsVisible(); if (moveAllowed) { _SelectionNr = maxCount_End - 1; keyEvent.Handled = true; } + break; case Keys.Left: @@ -440,6 +502,7 @@ namespace VocaluxeLib.Menu.SongMenu _AutoplayPreviewIfEnabled(); keyEvent.Handled = true; } + break; case Keys.Right: @@ -449,6 +512,7 @@ namespace VocaluxeLib.Menu.SongMenu _AutoplayPreviewIfEnabled(); keyEvent.Handled = true; } + break; case Keys.Up: @@ -466,6 +530,7 @@ namespace VocaluxeLib.Menu.SongMenu _AutoplayPreviewIfEnabled(); keyEvent.Handled = true; } + break; case Keys.Down: @@ -483,10 +548,15 @@ namespace VocaluxeLib.Menu.SongMenu _AutoplayPreviewIfEnabled(); keyEvent.Handled = true; } + break; } + if (!CBase.Songs.IsInCategory()) + { _PreviewSelectedSong(); + } + return keyEvent.Handled; } @@ -495,33 +565,46 @@ namespace VocaluxeLib.Menu.SongMenu if (!songOptions.Selection.RandomOnly || (!CBase.Songs.IsInCategory() && songOptions.Selection.CategoryChangeAllowed)) { if (mouseEvent.Wheel != 0 && CHelper.IsInBounds(_ScrollRect, mouseEvent)) - _UpdateList(_Offset + mouseEvent.Wheel); + { + _UpdateList(_Offset + mouseEvent.Wheel); + } - int lastSelection = _SelectionNr; - int i = 0; - bool somethingSelected = false; + var lastSelection = _SelectionNr; + var i = 0; + var somethingSelected = false; - foreach (CStatic tile in _Tiles) + foreach (var tile in _Tiles) { //create a rect including the cover and text of the song. //(this way mouse over text should make a selection as well) - SRectF songRect = new SRectF(tile.Rect.X, tile.Rect.Y, Rect.W, tile.Rect.H, tile.Rect.Z); + var songRect = new SRectF(tile.Rect.X, tile.Rect.Y, Rect.W, tile.Rect.H, tile.Rect.Z); if (tile.Texture != _CoverBGTexture && CHelper.IsInBounds(songRect, mouseEvent) && tile.Color.A != 0) { somethingSelected = true; _SelectionNr = i + _Offset; if (!CBase.Songs.IsInCategory()) + { _PreviewNr = i + _Offset; + } + break; } + i++; } + //Reset selection only if we moved out of the rect to avoid loosing it when selecting random songs if (_MouseWasInRect && !somethingSelected) + { _SelectionNr = -1; + } + if (mouseEvent.Sender == ESender.WiiMote && _SelectionNr != lastSelection && _SelectionNr != -1) + { CBase.Controller.SetRumble(0.050f); + } } + _MouseWasInRect = CHelper.IsInBounds(Rect, mouseEvent); if (mouseEvent.RB) @@ -532,6 +615,7 @@ namespace VocaluxeLib.Menu.SongMenu LeaveSelectedCategory(); return true; } + if (CBase.Songs.GetTabs() == EOffOn.TR_CONFIG_OFF && !songOptions.Selection.PartyMode) { CBase.Graphics.FadeTo(EScreen.Main); @@ -545,64 +629,93 @@ namespace VocaluxeLib.Menu.SongMenu if (CBase.Songs.IsInCategory()) { if (_PreviewNr == _SelectionNr) + { return false; + } + _PreviewSelectedSong(); } else + { EnterSelectedCategory(); + } + return true; } } + return false; } public override void Draw() { - foreach (CStatic rowBackground in _RowBackgrounds) + foreach (var rowBackground in _RowBackgrounds) + { rowBackground.Draw(EAspect.Stretch); - foreach (CStatic tile in _Tiles) + } + + foreach (var tile in _Tiles) { if (tile.Selected) + { tile.Draw(EAspect.Crop, SelectedTileZoomFactor, -0.1f); + } else { - EAspect aspect = (tile.Texture != _CoverBGTexture) ? EAspect.Crop : EAspect.Stretch; + var aspect = tile.Texture != _CoverBGTexture ? EAspect.Crop : EAspect.Stretch; tile.Draw(aspect); } } //highlight the text of the selected song - int i = 0; - foreach (CText text in _Texts) + var i = 0; + foreach (var text in _Texts) { if (i < _Tiles.Count && _Tiles[i].Selected) + { text.Font.Style = EStyle.Bold; + } else if (i < _Tiles.Count) + { text.Font.Style = EStyle.Normal; + } else + { text.Text = ""; + } + text.Draw(); i++; } + _TextBG.Draw(); CTextureRef vidtex = null; if (CBase.Config.GetVideoPreview() == EOffOn.TR_CONFIG_ON) - vidtex = (CBase.BackgroundMusic.IsPlayingPreview() ? CBase.BackgroundMusic.GetVideoTexture() : null); + { + vidtex = CBase.BackgroundMusic.IsPlayingPreview() ? CBase.BackgroundMusic.GetVideoTexture() : null; + } if (vidtex != null) { if (vidtex.Color.A < 1) + { _CoverBig.Draw(EAspect.Crop); - SRectF rect = CHelper.FitInBounds(_CoverBig.Rect, vidtex.OrigAspect, EAspect.Crop); + } + + var rect = CHelper.FitInBounds(_CoverBig.Rect, vidtex.OrigAspect, EAspect.Crop); CBase.Drawing.DrawTexture(vidtex, rect, vidtex.Color, _CoverBig.Rect); CBase.Drawing.DrawTextureReflection(vidtex, rect, vidtex.Color, _CoverBig.Rect, _CoverBig.ReflectionSpace, _CoverBig.ReflectionHeight); } else + { _CoverBig.Draw(EAspect.Crop); + } - foreach (IMenuElement element in _SubElements) + foreach (var element in _SubElements) + { element.Draw(); + } } public override CStatic GetSelectedSongCover() @@ -612,12 +725,16 @@ namespace VocaluxeLib.Menu.SongMenu public override bool IsMouseOverSelectedSong(SMouseEvent mEvent) { - for (int i = 0; i < _Tiles.Count; i++) + for (var i = 0; i < _Tiles.Count; i++) { if (!_Tiles[i].Selected) + { continue; + } + return CHelper.IsInBounds(_Tiles[i].Rect, mEvent) || CHelper.IsInBounds(_Texts[i].Rect, mEvent); } + return false; } @@ -655,9 +772,11 @@ namespace VocaluxeLib.Menu.SongMenu private void _UpdateListIfRequired() { - int curElements = CBase.Songs.IsInCategory() ? CBase.Songs.GetNumSongsVisible() : CBase.Songs.GetNumCategories(); - if ((_LastKnownElements == curElements) && (_LastKnownCategory == CBase.Songs.GetCurrentCategoryIndex())) + var curElements = CBase.Songs.IsInCategory() ? CBase.Songs.GetNumSongsVisible() : CBase.Songs.GetNumCategories(); + if (_LastKnownElements == curElements && _LastKnownCategory == CBase.Songs.GetCurrentCategoryIndex()) + { return; + } _LastKnownCategory = CBase.Songs.GetCurrentCategoryIndex(); _LastKnownElements = curElements; @@ -667,63 +786,79 @@ namespace VocaluxeLib.Menu.SongMenu private void _UpdateList(bool force = false) { - bool isInCategory = CBase.Songs.IsInCategory(); - int itemCount = isInCategory ? CBase.Songs.GetNumSongsVisible() : CBase.Songs.GetNumCategories(); - int halfListLength = _ListLength / 2; + var isInCategory = CBase.Songs.IsInCategory(); + var itemCount = isInCategory ? CBase.Songs.GetNumSongsVisible() : CBase.Songs.GetNumCategories(); + var halfListLength = _ListLength / 2; int offset; if (_SelectionNr < _Offset && _SelectionNr >= 0) { if (_SelectionNr - halfListLength >= 0) + { offset = _SelectionNr - halfListLength; + } else + { offset = 0; + } } else if (_SelectionNr >= _Offset + _ListLength) { if (_SelectionNr + halfListLength > itemCount) + { offset = itemCount - _ListLength; + } else + { offset = _SelectionNr - halfListLength; + } } else + { offset = _Offset; + } _UpdateList(offset, force); } private void _UpdateList(int offset, bool force = false) { - bool isInCategory = CBase.Songs.IsInCategory(); - int itemCount = isInCategory ? CBase.Songs.GetNumSongsVisible() : CBase.Songs.GetNumCategories(); - int totalSongNumber = CBase.Songs.GetNumSongs(); + var isInCategory = CBase.Songs.IsInCategory(); + var itemCount = isInCategory ? CBase.Songs.GetNumSongsVisible() : CBase.Songs.GetNumCategories(); + var totalSongNumber = CBase.Songs.GetNumSongs(); offset = offset.Clamp(0, itemCount - _ListLength, true); if (offset == _Offset && !force) + { return; + } - for (int i = 0; i < _Tiles.Count; i++) + for (var i = 0; i < _Tiles.Count; i++) { if (i + offset < itemCount) { _Tiles[i].Color = new SColorF(1f, 1f, 1f, 1f); if (isInCategory) { - CSong currentSong = CBase.Songs.GetVisibleSong(i + offset); + var currentSong = CBase.Songs.GetVisibleSong(i + offset); _Tiles[i].Texture = currentSong.CoverTextureSmall; - + if (CBase.Config.GetSongSorting() == ESongSorting.TR_CONFIG_TITLE_LETTER) + { _Texts[i].Text = currentSong.Title + " - " + currentSong.Artist; + } else + { _Texts[i].Text = currentSong.Artist + " - " + currentSong.Title; + } } else { - CCategory currentCat = CBase.Songs.GetCategory(i + offset); + var currentCat = CBase.Songs.GetCategory(i + offset); _Tiles[i].Texture = currentCat.CoverTextureSmall; - int num = currentCat.GetNumSongsNotSung(); - String songOrSongs = (num == 1) ? "TR_SCREENSONG_NUMSONG" : "TR_SCREENSONG_NUMSONGS"; + var num = currentCat.GetNumSongsNotSung(); + var songOrSongs = num == 1 ? "TR_SCREENSONG_NUMSONG" : "TR_SCREENSONG_NUMSONGS"; _Texts[i].Text = currentCat.Name + " " + CBase.Language.Translate(songOrSongs).Replace("%v", num.ToString()); } } @@ -734,14 +869,18 @@ namespace VocaluxeLib.Menu.SongMenu _Texts[i].Text = ""; } } + _Offset = offset; _UpdateTileSelection(); } public override void LoadSkin() { - foreach (IThemeable themeable in _SubElements.OfType()) + foreach (var themeable in _SubElements.OfType()) + { themeable.LoadSkin(); + } + // Those are drawn seperately so they are not in the above list _CoverBig.LoadSkin(); _TextBG.LoadSkin(); @@ -749,4 +888,4 @@ namespace VocaluxeLib.Menu.SongMenu base.LoadSkin(); } } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Menu/SongMenu/CSongMenuTileBoard.cs b/VocaluxeLib/Menu/SongMenu/CSongMenuTileBoard.cs index d94e6d7c..e28e7831 100644 --- a/VocaluxeLib/Menu/SongMenu/CSongMenuTileBoard.cs +++ b/VocaluxeLib/Menu/SongMenu/CSongMenuTileBoard.cs @@ -73,7 +73,7 @@ namespace VocaluxeLib.Menu.SongMenu { set { - int max = CBase.Songs.IsInCategory() ? CBase.Songs.GetNumSongsVisible() : CBase.Songs.GetNumCategories(); + var max = CBase.Songs.IsInCategory() ? CBase.Songs.GetNumSongsVisible() : CBase.Songs.GetNumCategories(); base._SelectionNr = value.Clamp(-1, max - 1, true); //Update list in case we scrolled _UpdateList(); @@ -87,7 +87,10 @@ namespace VocaluxeLib.Menu.SongMenu set { if (SmallView == value) + { return; + } + base.SmallView = value; _InitTiles(); _UpdateList(true); @@ -102,41 +105,51 @@ namespace VocaluxeLib.Menu.SongMenu if (value == base._PreviewNr) { if (!CBase.BackgroundMusic.IsPlaying() && value != -1) + { CBase.BackgroundMusic.Play(); + } + return; } + base._PreviewNr = value; _UpdatePreview(); } } - public CSongMenuTileBoard(int partyModeID) : base(partyModeID) {} + public CSongMenuTileBoard(int partyModeId) : base(partyModeId) { } - public CSongMenuTileBoard(SThemeSongMenu theme, int partyModeID) : base(theme, partyModeID) + public CSongMenuTileBoard(SThemeSongMenu theme, int partyModeId) : base(theme, partyModeId) { - _Artist = new CText(_Theme.SongMenuTileBoard.TextArtist, _PartyModeID); - _Title = new CText(_Theme.SongMenuTileBoard.TextTitle, _PartyModeID); - _SongLength = new CText(_Theme.SongMenuTileBoard.TextSongLength, _PartyModeID); - _SongYear = new CText(_Theme.SongMenuTileBoard.TextSongYear, _PartyModeID); - _CoverBig = new CStatic(_Theme.SongMenuTileBoard.StaticCoverBig, _PartyModeID); - _TextBG = new CStatic(_Theme.SongMenuTileBoard.StaticTextBG, _PartyModeID); - _DuetIcon = new CStatic(_Theme.SongMenuTileBoard.StaticDuetIcon, _PartyModeID); - _RapIcon = new CStatic(_Theme.SongMenuTileBoard.StaticRapIcon, _PartyModeID); - _VideoIcon = new CStatic(_Theme.SongMenuTileBoard.StaticVideoIcon, _PartyModeID); - _MedleyCalcIcon = new CStatic(_Theme.SongMenuTileBoard.StaticMedleyCalcIcon, _PartyModeID); - _MedleyTagIcon = new CStatic(_Theme.SongMenuTileBoard.StaticMedleyTagIcon, _PartyModeID); - _InstrumentalIcon = new CStatic(_Theme.SongMenuTileBoard.StaticInstrumentalIcon, _PartyModeID); - _VocalsIcon = new CStatic(_Theme.SongMenuTileBoard.StaticVocalsIcon, _PartyModeID); - _SubElements.AddRange(new IMenuElement[] {_Artist, _Title, _SongLength, _SongYear, _DuetIcon, _RapIcon, _VideoIcon, _MedleyCalcIcon, _MedleyTagIcon, _InstrumentalIcon, _VocalsIcon}); + _Artist = new CText(_Theme.SongMenuTileBoard.TextArtist, _PartyModeId); + _Title = new CText(_Theme.SongMenuTileBoard.TextTitle, _PartyModeId); + _SongLength = new CText(_Theme.SongMenuTileBoard.TextSongLength, _PartyModeId); + _SongYear = new CText(_Theme.SongMenuTileBoard.TextSongYear, _PartyModeId); + _CoverBig = new CStatic(_Theme.SongMenuTileBoard.StaticCoverBig, _PartyModeId); + _TextBG = new CStatic(_Theme.SongMenuTileBoard.StaticTextBG, _PartyModeId); + _DuetIcon = new CStatic(_Theme.SongMenuTileBoard.StaticDuetIcon, _PartyModeId); + _RapIcon = new CStatic(_Theme.SongMenuTileBoard.StaticRapIcon, _PartyModeId); + _VideoIcon = new CStatic(_Theme.SongMenuTileBoard.StaticVideoIcon, _PartyModeId); + _MedleyCalcIcon = new CStatic(_Theme.SongMenuTileBoard.StaticMedleyCalcIcon, _PartyModeId); + _MedleyTagIcon = new CStatic(_Theme.SongMenuTileBoard.StaticMedleyTagIcon, _PartyModeId); + _InstrumentalIcon = new CStatic(_Theme.SongMenuTileBoard.StaticInstrumentalIcon, _PartyModeId); + _VocalsIcon = new CStatic(_Theme.SongMenuTileBoard.StaticVocalsIcon, _PartyModeId); + _SubElements.AddRange(new IMenuElement[] + { _Artist, _Title, _SongLength, _SongYear, _DuetIcon, _RapIcon, _VideoIcon, _MedleyCalcIcon, _MedleyTagIcon, _InstrumentalIcon, _VocalsIcon }); } private void _UpdateTileSelection() { - foreach (CStatic tile in _Tiles) + foreach (var tile in _Tiles) + { tile.Selected = false; - int tileNr = _SelectionNr - _Offset; + } + + var tileNr = _SelectionNr - _Offset; if (tileNr >= 0 && tileNr < _Tiles.Count) + { _Tiles[tileNr].Selected = true; + } } private void _ReadSubTheme() @@ -188,39 +201,44 @@ namespace VocaluxeLib.Menu.SongMenu _TileW = (int)((Rect.W - _Theme.SongMenuTileBoard.SpaceW * (_NumW - 1)) / _NumW); _TileH = (int)((Rect.H - _Theme.SongMenuTileBoard.SpaceH * (_NumH - 1)) / _NumH); - _CoverBGTexture = CBase.Themes.GetSkinTexture(_Theme.CoverBackground, _PartyModeID); - _CoverBigBGTexture = CBase.Themes.GetSkinTexture(_Theme.CoverBigBackground, _PartyModeID); + _CoverBGTexture = CBase.Themes.GetSkinTexture(_Theme.CoverBackground, _PartyModeId); + _CoverBigBGTexture = CBase.Themes.GetSkinTexture(_Theme.CoverBigBackground, _PartyModeId); _Tiles = new List(); - for (int i = 0; i < _NumH; i++) + for (var i = 0; i < _NumH; i++) { - for (int j = 0; j < _NumW; j++) + for (var j = 0; j < _NumW; j++) { var rect = new SRectF(Rect.X + j * (_TileW + _Theme.SongMenuTileBoard.SpaceW), Rect.Y + i * (_TileH + _Theme.SongMenuTileBoard.SpaceH), _TileW, _TileH, Rect.Z); - var tile = new CStatic(_PartyModeID, _CoverBGTexture, _Color, rect); + var tile = new CStatic(_PartyModeId, _CoverBGTexture, _Color, rect); _Tiles.Add(tile); } } + _ScrollRect = CBase.Settings.GetRenderRect(); } public override void Update(SScreenSongOptions songOptions) { if (songOptions.Selection.RandomOnly) + { _PreviewSelectedSong(); + } if (_Length < 0 && CBase.Songs.IsInCategory() && CBase.BackgroundMusic.GetLength() > 0) + { _UpdateLength(CBase.Songs.GetVisibleSong(_PreviewNr)); + } } private void _UpdatePreview() { //First hide everything so we just have to set what we actually want _CoverBig.Texture = _CoverBigBGTexture; - _Artist.Text = String.Empty; - _Title.Text = String.Empty; - _SongLength.Text = String.Empty; - _SongYear.Text = String.Empty; + _Artist.Text = string.Empty; + _Title.Text = string.Empty; + _SongLength.Text = string.Empty; + _SongYear.Text = string.Empty; _DuetIcon.Visible = false; _RapIcon.Visible = false; _VideoIcon.Visible = false; @@ -232,23 +250,29 @@ namespace VocaluxeLib.Menu.SongMenu //Check if nothing is selected (for preview) if (_PreviewNr < 0) + { return; + } if (CBase.Songs.IsInCategory()) { - CSong song = CBase.Songs.GetVisibleSong(_PreviewNr); + var song = CBase.Songs.GetVisibleSong(_PreviewNr); //Check if we have a valid song (song still visible, index >=0 etc is checked by framework) if (song == null) { //Display at least the category - CCategory category = CBase.Songs.GetCategory(CBase.Songs.GetCurrentCategoryIndex()); + var category = CBase.Songs.GetCategory(CBase.Songs.GetCurrentCategoryIndex()); //Check if we have a valid category if (category == null) + { return; + } + _CoverBig.Texture = category.CoverTextureBig; _Artist.Text = category.Name; return; } + _CoverBig.Texture = song.CoverTextureBig; _Artist.Text = song.Artist; _Title.Text = song.Title; @@ -265,15 +289,18 @@ namespace VocaluxeLib.Menu.SongMenu } else { - CCategory category = CBase.Songs.GetCategory(_PreviewNr); + var category = CBase.Songs.GetCategory(_PreviewNr); //Check if we have a valid category if (category == null) + { return; + } + _CoverBig.Texture = category.CoverTextureBig; _Artist.Text = category.Name; - int num = category.GetNumSongsNotSung(); - String songOrSongs = (num == 1) ? "TR_SCREENSONG_NUMSONG" : "TR_SCREENSONG_NUMSONGS"; + var num = category.GetNumSongsNotSung(); + var songOrSongs = num == 1 ? "TR_SCREENSONG_NUMSONG" : "TR_SCREENSONG_NUMSONGS"; _Title.Text = CBase.Language.Translate(songOrSongs).Replace("%v", num.ToString()); } } @@ -281,10 +308,15 @@ namespace VocaluxeLib.Menu.SongMenu private void _UpdateLength(CSong song) { if (song == null) + { return; - float time = CBase.BackgroundMusic.GetLength(); - if (Math.Abs(song.Finish) > 0.001) - time = song.Finish; + } + + var time = CBase.BackgroundMusic.GetLength(); + if (Math.Abs(song.End) > 0.001) + { + time = song.End; + } // The audiobackend is ready to return the length if (time > 0) @@ -296,7 +328,9 @@ namespace VocaluxeLib.Menu.SongMenu _Length = time; } else + { _SongLength.Text = "..."; + } } public override void OnShow() @@ -305,12 +339,20 @@ namespace VocaluxeLib.Menu.SongMenu if (!CBase.Songs.IsInCategory()) { if ((CBase.Songs.GetTabs() == EOffOn.TR_CONFIG_OFF && CBase.Songs.GetNumCategories() > 0) || CBase.Songs.GetNumCategories() == 1) + { _EnterCategory(0); + } } + if (CBase.Songs.IsInCategory()) + { SetSelectedSong(_SelectionNr < 0 ? 0 : _SelectionNr); + } else + { SetSelectedCategory(_SelectionNr < 0 ? 0 : _SelectionNr); + } + _PreviewSelectedSong(); _UpdateListIfRequired(); } @@ -318,14 +360,18 @@ namespace VocaluxeLib.Menu.SongMenu public override bool HandleInput(ref SKeyEvent keyEvent, SScreenSongOptions options) { if (keyEvent.KeyPressed) + { return false; + } - bool moveAllowed = !options.Selection.RandomOnly || (options.Selection.CategoryChangeAllowed && !CBase.Songs.IsInCategory()); - bool catChangePossible = CBase.Songs.GetTabs() == EOffOn.TR_CONFIG_ON && options.Selection.CategoryChangeAllowed; + var moveAllowed = !options.Selection.RandomOnly || (options.Selection.CategoryChangeAllowed && !CBase.Songs.IsInCategory()); + var catChangePossible = CBase.Songs.GetTabs() == EOffOn.TR_CONFIG_ON && options.Selection.CategoryChangeAllowed; //If nothing selected set a reasonable default value if (keyEvent.IsArrowKey() && moveAllowed && _SelectionNr < 0) - _SelectionNr = (_PreviewNr < 0) ? _Offset : _PreviewNr; + { + _SelectionNr = _PreviewNr < 0 ? _Offset : _PreviewNr; + } switch (keyEvent.Key) { @@ -343,6 +389,7 @@ namespace VocaluxeLib.Menu.SongMenu _EnterCategory(_PreviewNr); keyEvent.Handled = true; } + break; case Keys.Escape: @@ -352,6 +399,7 @@ namespace VocaluxeLib.Menu.SongMenu LeaveSelectedCategory(); keyEvent.Handled = true; } + break; case Keys.PageUp: @@ -362,13 +410,19 @@ namespace VocaluxeLib.Menu.SongMenu } else if (moveAllowed) { - int numSongsPerPage = _NumH * _NumW; - if ((_SelectionNr - numSongsPerPage) <= 0) + var numSongsPerPage = _NumH * _NumW; + if (_SelectionNr - numSongsPerPage <= 0) + { _SelectionNr = 0; + } else + { _SelectionNr = _SelectionNr - numSongsPerPage; + } + keyEvent.Handled = true; } + break; case Keys.PageDown: @@ -379,14 +433,21 @@ namespace VocaluxeLib.Menu.SongMenu } else if (moveAllowed) { - int numSongsPerPage = _NumH * _NumW; - int maxCount_PageDown = (CBase.Songs.GetTabs() == EOffOn.TR_CONFIG_ON && !CBase.Songs.IsInCategory() ? CBase.Songs.GetNumCategories() : CBase.Songs.GetNumSongsVisible()); - if ((_SelectionNr + numSongsPerPage) >= maxCount_PageDown) + var numSongsPerPage = _NumH * _NumW; + var maxCount_PageDown = CBase.Songs.GetTabs() == EOffOn.TR_CONFIG_ON && !CBase.Songs.IsInCategory() ? CBase.Songs.GetNumCategories() + : CBase.Songs.GetNumSongsVisible(); + if (_SelectionNr + numSongsPerPage >= maxCount_PageDown) + { _SelectionNr = maxCount_PageDown - 1; + } else + { _SelectionNr = _SelectionNr + numSongsPerPage; + } + keyEvent.Handled = true; } + break; case Keys.Home: @@ -395,15 +456,18 @@ namespace VocaluxeLib.Menu.SongMenu _SelectionNr = 0; keyEvent.Handled = true; } + break; case Keys.End: - int maxCount_End = (CBase.Songs.GetTabs() == EOffOn.TR_CONFIG_ON && !CBase.Songs.IsInCategory() ? CBase.Songs.GetNumCategories() : CBase.Songs.GetNumSongsVisible()); + var maxCount_End = CBase.Songs.GetTabs() == EOffOn.TR_CONFIG_ON && !CBase.Songs.IsInCategory() ? CBase.Songs.GetNumCategories() + : CBase.Songs.GetNumSongsVisible(); if (moveAllowed) { _SelectionNr = maxCount_End - 1; keyEvent.Handled = true; } + break; case Keys.Left: @@ -414,6 +478,7 @@ namespace VocaluxeLib.Menu.SongMenu _AutoplayPreviewIfEnabled(); keyEvent.Handled = true; } + break; case Keys.Right: @@ -423,6 +488,7 @@ namespace VocaluxeLib.Menu.SongMenu _AutoplayPreviewIfEnabled(); keyEvent.Handled = true; } + break; case Keys.Up: @@ -440,6 +506,7 @@ namespace VocaluxeLib.Menu.SongMenu _AutoplayPreviewIfEnabled(); keyEvent.Handled = true; } + break; case Keys.Down: @@ -457,10 +524,15 @@ namespace VocaluxeLib.Menu.SongMenu _AutoplayPreviewIfEnabled(); keyEvent.Handled = true; } + break; } + if (!CBase.Songs.IsInCategory()) + { _PreviewSelectedSong(); + } + return keyEvent.Handled; } @@ -469,29 +541,42 @@ namespace VocaluxeLib.Menu.SongMenu if (!songOptions.Selection.RandomOnly || (!CBase.Songs.IsInCategory() && songOptions.Selection.CategoryChangeAllowed)) { if (mouseEvent.Wheel != 0 && CHelper.IsInBounds(_ScrollRect, mouseEvent)) + { _UpdateList(_Offset + _NumW * mouseEvent.Wheel); + } - int lastSelection = _SelectionNr; - int i = 0; - bool somethingSelected = false; - foreach (CStatic tile in _Tiles) + var lastSelection = _SelectionNr; + var i = 0; + var somethingSelected = false; + foreach (var tile in _Tiles) { if (tile.Texture != _CoverBGTexture && CHelper.IsInBounds(tile.Rect, mouseEvent)) { somethingSelected = true; _SelectionNr = i + _Offset; if (!CBase.Songs.IsInCategory()) + { _PreviewNr = i + _Offset; + } + break; } + i++; } + //Reset selection only if we moved out of the rect to avoid loosing it when selecting random songs if (_MouseWasInRect && !somethingSelected) + { _SelectionNr = -1; + } + if (mouseEvent.Sender == ESender.WiiMote && _SelectionNr != lastSelection && _SelectionNr != -1) + { CBase.Controller.SetRumble(0.050f); + } } + _MouseWasInRect = CHelper.IsInBounds(Rect, mouseEvent); if (mouseEvent.RB) @@ -502,6 +587,7 @@ namespace VocaluxeLib.Menu.SongMenu LeaveSelectedCategory(); return true; } + if (CBase.Songs.GetTabs() == EOffOn.TR_CONFIG_OFF && !songOptions.Selection.PartyMode) { CBase.Graphics.FadeTo(EScreen.Main); @@ -515,26 +601,35 @@ namespace VocaluxeLib.Menu.SongMenu if (CBase.Songs.IsInCategory()) { if (_PreviewNr == _SelectionNr) + { return false; + } + _PreviewSelectedSong(); } else + { EnterSelectedCategory(); + } + return true; } } + return false; } public override void Draw() { - foreach (CStatic tile in _Tiles) + foreach (var tile in _Tiles) { if (tile.Selected) + { tile.Draw(EAspect.Crop, SelectedTileZoomFactor, -0.1f); + } else { - EAspect aspect = (tile.Texture != _CoverBGTexture) ? EAspect.Crop : EAspect.Stretch; + var aspect = tile.Texture != _CoverBGTexture ? EAspect.Crop : EAspect.Stretch; tile.Draw(aspect); } } @@ -543,21 +638,30 @@ namespace VocaluxeLib.Menu.SongMenu CTextureRef vidtex = null; if (CBase.Config.GetVideoPreview() == EOffOn.TR_CONFIG_ON) - vidtex = (CBase.BackgroundMusic.IsPlayingPreview() ? CBase.BackgroundMusic.GetVideoTexture() : null); + { + vidtex = CBase.BackgroundMusic.IsPlayingPreview() ? CBase.BackgroundMusic.GetVideoTexture() : null; + } if (vidtex != null) { if (vidtex.Color.A < 1) + { _CoverBig.Draw(EAspect.Crop); - SRectF rect = CHelper.FitInBounds(_CoverBig.Rect, vidtex.OrigAspect, EAspect.Crop); + } + + var rect = CHelper.FitInBounds(_CoverBig.Rect, vidtex.OrigAspect, EAspect.Crop); CBase.Drawing.DrawTexture(vidtex, rect, vidtex.Color, _CoverBig.Rect); CBase.Drawing.DrawTextureReflection(vidtex, rect, vidtex.Color, _CoverBig.Rect, _CoverBig.ReflectionSpace, _CoverBig.ReflectionHeight); } else + { _CoverBig.Draw(EAspect.Crop); + } - foreach (IMenuElement element in _SubElements) + foreach (var element in _SubElements) + { element.Draw(); + } } public override CStatic GetSelectedSongCover() @@ -599,9 +703,11 @@ namespace VocaluxeLib.Menu.SongMenu private void _UpdateListIfRequired() { - int curElements = CBase.Songs.IsInCategory() ? CBase.Songs.GetNumSongsVisible() : CBase.Songs.GetNumCategories(); - if ((_LastKnownElements == curElements) && (_LastKnownCategory == CBase.Songs.GetCurrentCategoryIndex())) + var curElements = CBase.Songs.IsInCategory() ? CBase.Songs.GetNumSongsVisible() : CBase.Songs.GetNumCategories(); + if (_LastKnownElements == curElements && _LastKnownCategory == CBase.Songs.GetCurrentCategoryIndex()) + { return; + } _LastKnownCategory = CBase.Songs.GetCurrentCategoryIndex(); _LastKnownElements = curElements; @@ -611,32 +717,41 @@ namespace VocaluxeLib.Menu.SongMenu private int _GetOffsetForPosition(int index, int rowNum = 0) { - return (index / _NumW) * _NumW - (_NumW * rowNum.Clamp(0, _NumH - 1, true)); + return index / _NumW * _NumW - _NumW * rowNum.Clamp(0, _NumH - 1, true); } private void _UpdateList(bool force = false) { int offset; if (_SelectionNr < _Offset && _SelectionNr >= 0) + { offset = _GetOffsetForPosition(_SelectionNr); + } else if (_SelectionNr >= _Offset + _NumW * _NumH) + { offset = _GetOffsetForPosition(_SelectionNr, _NumH); + } else + { offset = _Offset; + } + _UpdateList(offset, force); } private void _UpdateList(int offset, bool force = false) { - bool isInCategory = CBase.Songs.IsInCategory(); - int itemCount = isInCategory ? CBase.Songs.GetNumSongsVisible() : CBase.Songs.GetNumCategories(); + var isInCategory = CBase.Songs.IsInCategory(); + var itemCount = isInCategory ? CBase.Songs.GetNumSongsVisible() : CBase.Songs.GetNumCategories(); offset = offset.Clamp(0, _GetOffsetForPosition(itemCount, _NumH - 1), true); if (offset == _Offset && !force) + { return; + } - for (int i = 0; i < _Tiles.Count; i++) + for (var i = 0; i < _Tiles.Count; i++) { if (itemCount > i + offset) { @@ -649,14 +764,18 @@ namespace VocaluxeLib.Menu.SongMenu _Tiles[i].Color = _Color; } } + _Offset = offset; } public override void LoadSkin() { base.LoadSkin(); - foreach (IThemeable themeable in _SubElements.OfType()) + foreach (var themeable in _SubElements.OfType()) + { themeable.LoadSkin(); + } + // Those are drawn seperately so they are not in the above list _CoverBig.LoadSkin(); _TextBG.LoadSkin(); @@ -664,4 +783,4 @@ namespace VocaluxeLib.Menu.SongMenu Init(); } } -} +} \ No newline at end of file diff --git a/VocaluxeLib/PartyModes/CPartyMode.cs b/VocaluxeLib/PartyModes/CPartyMode.cs index 7fb529c0..6097975e 100644 --- a/VocaluxeLib/PartyModes/CPartyMode.cs +++ b/VocaluxeLib/PartyModes/CPartyMode.cs @@ -23,20 +23,16 @@ namespace VocaluxeLib.PartyModes { public abstract class CPartyMode : IPartyMode { - private readonly int _ID; - protected SScreenSongOptions _ScreenSongOptions = new SScreenSongOptions {Selection = new SSelectionOptions(), Sorting = new SSortingOptions()}; + protected SScreenSongOptions _ScreenSongOptions = new SScreenSongOptions { Selection = new SSelectionOptions(), Sorting = new SSortingOptions() }; protected readonly Dictionary _Screens = new Dictionary(); protected CPartyMode(int id) { - _ID = id; + Id = id; } #region Implementation - public int ID - { - get { return _ID; } - } + public int Id { get; } public int NumPlayers { get; set; } public int NumTeams { get; set; } @@ -55,8 +51,8 @@ namespace VocaluxeLib.PartyModes public void LoadTheme() { - string xmlPath = CBase.Themes.GetThemeScreensPath(ID); - foreach (CMenuParty menu in _Screens.Values) + var xmlPath = CBase.Themes.GetThemeScreensPath(Id); + foreach (var menu in _Screens.Values) { menu.Init(); menu.LoadTheme(xmlPath); @@ -65,15 +61,19 @@ namespace VocaluxeLib.PartyModes public void ReloadSkin() { - foreach (CMenuParty menu in _Screens.Values) + foreach (var menu in _Screens.Values) + { menu.ReloadSkin(); + } } public void ReloadTheme() { - string xmlPath = CBase.Themes.GetThemeScreensPath(ID); - foreach (CMenuParty menu in _Screens.Values) + var xmlPath = CBase.Themes.GetThemeScreensPath(Id); + foreach (var menu in _Screens.Values) + { menu.ReloadTheme(xmlPath); + } } public void AddScreen(CMenuParty screen, string screenName) @@ -83,20 +83,28 @@ namespace VocaluxeLib.PartyModes public void SaveScreens() { - foreach (KeyValuePair entry in _Screens) + foreach (var entry in _Screens) + { entry.Value.SaveTheme(); + } } public virtual void JokerUsed(int teamNr) { if (_ScreenSongOptions.Selection.NumJokers == null) + { return; + } if (_ScreenSongOptions.Selection.NumJokers.Length < teamNr) + { return; + } if (_ScreenSongOptions.Selection.NumJokers[teamNr] > 0) + { _ScreenSongOptions.Selection.NumJokers[teamNr]--; + } } public virtual void FinishedSinging() @@ -132,7 +140,7 @@ namespace VocaluxeLib.PartyModes public abstract void OnCategoryChange(int categoryIndex, ref SScreenSongOptions screenSongOptions); public abstract void SetSearchString(string searchString, bool visible); - public abstract void SongSelected(int songID); + public abstract void SongSelected(int songId); #endregion Abstract members } } \ No newline at end of file diff --git a/VocaluxeLib/PartyModes/CPartyModeNormal.cs b/VocaluxeLib/PartyModes/CPartyModeNormal.cs index 9c62e884..5dcdbb8a 100644 --- a/VocaluxeLib/PartyModes/CPartyModeNormal.cs +++ b/VocaluxeLib/PartyModes/CPartyModeNormal.cs @@ -15,7 +15,6 @@ // along with Vocaluxe. If not, see . #endregion -using System; using VocaluxeLib.Menu; namespace VocaluxeLib.PartyModes @@ -65,10 +64,10 @@ namespace VocaluxeLib.PartyModes _ScreenSongOptions.Selection.SongIndex = -1; _ScreenSongOptions.Selection.CategoryIndex = -1; - _ScreenSongOptions.Sorting.SearchString = String.Empty; + _ScreenSongOptions.Sorting.SearchString = string.Empty; _ScreenSongOptions.Sorting.SearchActive = false; _ScreenSongOptions.Sorting.DuetOptions = EDuetOptions.All; - _ScreenSongOptions.Sorting.FilterPlaylistID = -1; + _ScreenSongOptions.Sorting.FilterPlaylistId = -1; } public override bool Init() @@ -76,7 +75,7 @@ namespace VocaluxeLib.PartyModes return true; } - public override void UpdateGame() {} + public override void UpdateGame() { } public override IMenu GetStartScreen() { @@ -89,16 +88,18 @@ namespace VocaluxeLib.PartyModes _ScreenSongOptions.Sorting.Tabs = CBase.Config.GetTabs(); if (_ScreenSongOptions.Sorting.SearchActive) + { _ScreenSongOptions.Sorting.Tabs = EOffOn.TR_CONFIG_OFF; + } _ScreenSongOptions.Sorting.IgnoreArticles = CBase.Config.GetIgnoreArticles(); return _ScreenSongOptions; } - public override void OnSongChange(int songIndex, ref SScreenSongOptions screenSongOptions) {} + public override void OnSongChange(int songIndex, ref SScreenSongOptions screenSongOptions) { } - public override void OnCategoryChange(int categoryIndex, ref SScreenSongOptions screenSongOptions) {} + public override void OnCategoryChange(int categoryIndex, ref SScreenSongOptions screenSongOptions) { } public override void SetSearchString(string searchString, bool visible) { @@ -106,7 +107,7 @@ namespace VocaluxeLib.PartyModes _ScreenSongOptions.Sorting.SearchActive = visible; } - public override void SongSelected(int songID) + public override void SongSelected(int songId) { CBase.Graphics.FadeTo(EScreen.Sing); } diff --git a/VocaluxeLib/PartyModes/IPartyMode.cs b/VocaluxeLib/PartyModes/IPartyMode.cs index a4bad99e..eac166f1 100644 --- a/VocaluxeLib/PartyModes/IPartyMode.cs +++ b/VocaluxeLib/PartyModes/IPartyMode.cs @@ -19,7 +19,6 @@ using VocaluxeLib.Menu; namespace VocaluxeLib.PartyModes { - #region Structs public struct SScreenSongOptions { @@ -34,7 +33,7 @@ namespace VocaluxeLib.PartyModes public EOffOn IgnoreArticles; public string SearchString; public bool SearchActive; - public int FilterPlaylistID; //show only songs that are in this playlist, -1 for all songs + public int FilterPlaylistId; //show only songs that are in this playlist, -1 for all songs public EDuetOptions DuetOptions; } @@ -87,7 +86,7 @@ namespace VocaluxeLib.PartyModes public interface IPartyModeInfo { - int ID { get; } + int Id { get; } int MinMics { get; } int MaxMics { get; } int MinPlayers { get; } @@ -124,7 +123,7 @@ namespace VocaluxeLib.PartyModes void SetSearchString(string searchString, bool visible); void JokerUsed(int teamNr); - void SongSelected(int songID); + void SongSelected(int songId); void FinishedSinging(); void LeavingScore(); void LeavingHighscore(); diff --git a/VocaluxeLib/Profile/CAvatar.cs b/VocaluxeLib/Profile/CAvatar.cs index dc0325e9..55738d82 100644 --- a/VocaluxeLib/Profile/CAvatar.cs +++ b/VocaluxeLib/Profile/CAvatar.cs @@ -23,8 +23,7 @@ namespace VocaluxeLib.Profile { public class CAvatar { - public int ID; - private readonly string _FileName = ""; + public int Id; private CTextureRef _Texture; private const int _MaxNameLen = 12; @@ -32,28 +31,25 @@ namespace VocaluxeLib.Profile { get { return _Texture; } } - public string FileName - { - get { return _FileName; } - } + public string FileName { get; } = ""; public static CAvatar GetAvatar(string fileName) { - CTextureRef texture = CBase.Drawing.AddTexture(fileName); + var texture = CBase.Drawing.AddTexture(fileName); return texture == null ? null : new CAvatar(texture, fileName); } private CAvatar(CTextureRef texture, string fileName, int id = -1) { _Texture = texture; - _FileName = fileName; - ID = id; + FileName = fileName; + Id = id; } public bool Reload() { Unload(); - _Texture = CBase.Drawing.AddTexture(_FileName); + _Texture = CBase.Drawing.AddTexture(FileName); return _Texture != null; } @@ -65,10 +61,13 @@ namespace VocaluxeLib.Profile public string GetDisplayName() { - string name = Path.GetFileNameWithoutExtension(_FileName); + var name = Path.GetFileNameWithoutExtension(FileName); Debug.Assert(name != null); if (name.Length > _MaxNameLen) + { name = name.Substring(0, _MaxNameLen); + } + return name; } } diff --git a/VocaluxeLib/Profile/CProfile.cs b/VocaluxeLib/Profile/CProfile.cs index 1f2e60ea..3590c8e5 100644 --- a/VocaluxeLib/Profile/CProfile.cs +++ b/VocaluxeLib/Profile/CProfile.cs @@ -43,12 +43,16 @@ namespace VocaluxeLib.Profile #pragma warning restore 649 } - [DefaultValue(null)] public Guid ID; + [DefaultValue(null)] + public Guid Id; public string PlayerName; - [XmlIgnore] public string FilePath; - [DefaultValue(null)] public byte[] PasswordHash; - [DefaultValue(null)] public byte[] PasswordSalt; + [XmlIgnore] + public string FilePath; + [DefaultValue(null)] + public byte[] PasswordHash; + [DefaultValue(null)] + public byte[] PasswordSalt; public EGameDifficulty Difficulty; @@ -68,14 +72,16 @@ namespace VocaluxeLib.Profile { Avatar = CBase.Profiles.GetAvatarByFilename(value); if (Avatar == null) + { CLog.Error("Avatar '" + value + "' not found"); + } } } public CProfile() { - ID = Guid.NewGuid(); - PlayerName = String.Empty; + Id = Guid.NewGuid(); + PlayerName = string.Empty; Difficulty = EGameDifficulty.TR_CONFIG_EASY; UserRole = EUserRole.TR_USERROLE_NORMAL; Active = EOffOn.TR_CONFIG_ON; @@ -94,20 +100,24 @@ namespace VocaluxeLib.Profile try { xml.Deserialize(FilePath, this); - //If ID couldn't be loaded, generate a new one and save it - if (ID == Guid.Empty) + //If Id couldn't be loaded, generate a new one and save it + if (Id == Guid.Empty) { - ID = Guid.NewGuid(); + Id = Guid.NewGuid(); SaveProfile(); } } catch (Exception e) { if (_ConvertProfile(ref e)) + { return true; + } + CLog.Error("Error loading profile file " + Path.GetFileName(FilePath) + ": " + e.Message); return false; } + return true; } @@ -118,37 +128,47 @@ namespace VocaluxeLib.Profile try { var old = xml.Deserialize(FilePath); - string newXml = ser.Serialize(old.Info); + var newXml = ser.Serialize(old.Info); xml.DeserializeString(newXml, this); - if (ID == null) - ID = Guid.NewGuid(); - ser.Serialize(FilePath, this); + if (Id == null) + { + Id = Guid.NewGuid(); + } + ser.Serialize(FilePath, this); } catch (Exception e2) { if (!(e2 is CXmlException)) + { e = e2; + } + return false; } + return true; } public void SaveProfile() { - if (String.IsNullOrEmpty(FilePath)) + if (string.IsNullOrEmpty(FilePath)) { - string filename = string.Empty; + var filename = string.Empty; // ReSharper disable LoopCanBeConvertedToQuery - foreach (char chr in PlayerName) + foreach (var chr in PlayerName) // ReSharper restore LoopCanBeConvertedToQuery { if (char.IsLetter(chr)) + { filename += chr.ToString(); + } } if (filename == "") + { filename = "1"; + } FilePath = CHelper.GetUniqueFileName(Path.Combine(CBase.Settings.GetDataPath(), CBase.Settings.GetFolderProfiles()), filename + ".xml"); } diff --git a/VocaluxeLib/Properties/AssemblyInfo.cs b/VocaluxeLib/Properties/AssemblyInfo.cs index 019205d7..545f9c0e 100644 --- a/VocaluxeLib/Properties/AssemblyInfo.cs +++ b/VocaluxeLib/Properties/AssemblyInfo.cs @@ -38,7 +38,7 @@ using System.Runtime.InteropServices; [assembly: ComVisible(false)] -// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird +// Die folgende GUId bestimmt die Id der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("3fb7cd34-186d-4f89-beb5-8830b8e5593b")] diff --git a/VocaluxeLib/Songs/CBaseNote.cs b/VocaluxeLib/Songs/CBaseNote.cs index 7fc2f281..e99f877d 100644 --- a/VocaluxeLib/Songs/CBaseNote.cs +++ b/VocaluxeLib/Songs/CBaseNote.cs @@ -41,7 +41,9 @@ namespace VocaluxeLib.Songs Duration = duration; Tone = tone; if (Duration < 1) + { throw new Exception("Note to short. All notes should be at least 1 beat long!"); + } } #endregion Constructors @@ -62,7 +64,9 @@ namespace VocaluxeLib.Songs set { if (value > 0) + { _Duration = value; + } } } @@ -72,13 +76,18 @@ namespace VocaluxeLib.Songs { // Always return 0 for Rap notes if (IsRapNote) + { return 0; + } + return _Tone; } set { - if ((value >= CBase.Settings.GetToneMin()) && (value <= CBase.Settings.GetToneMax())) + if (value >= CBase.Settings.GetToneMin() && value <= CBase.Settings.GetToneMax()) + { _Tone = value; + } } } @@ -104,4 +113,4 @@ namespace VocaluxeLib.Songs public abstract bool IsNoteType(params ENoteType[] noteTypes); #endregion Methods } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Songs/CCategory.cs b/VocaluxeLib/Songs/CCategory.cs index 1fec7346..5d2b31b7 100644 --- a/VocaluxeLib/Songs/CCategory.cs +++ b/VocaluxeLib/Songs/CCategory.cs @@ -16,15 +16,14 @@ #endregion using System.Collections.Generic; -using VocaluxeLib.Draw; using System.Linq; +using VocaluxeLib.Draw; namespace VocaluxeLib.Songs { public class CCategory { public readonly string Name; - private CTextureRef _CoverTextureSmall; private CTextureRef _CoverTextureBig; public readonly List Songs = new List(); @@ -33,20 +32,18 @@ namespace VocaluxeLib.Songs Name = name; } - public CTextureRef CoverTextureSmall - { - get { return _CoverTextureSmall; } - - set { _CoverTextureSmall = value; } - } + public CTextureRef CoverTextureSmall { get; set; } public CTextureRef CoverTextureBig { - get { return _CoverTextureBig ?? _CoverTextureSmall; } + get { return _CoverTextureBig ?? CoverTextureSmall; } set { if (value == null) + { return; + } + _CoverTextureBig = value; } } @@ -59,7 +56,10 @@ namespace VocaluxeLib.Songs public CSong GetSong(int numInCategory) { if (numInCategory >= 0 && numInCategory < Songs.Count) - return CBase.Songs.GetSongByID(Songs[numInCategory].SongID); + { + return CBase.Songs.GetSongById(Songs[numInCategory].SongId); + } + return null; } } diff --git a/VocaluxeLib/Songs/CLineBase.cs b/VocaluxeLib/Songs/CLineBase.cs index 577f732e..421d2ec4 100644 --- a/VocaluxeLib/Songs/CLineBase.cs +++ b/VocaluxeLib/Songs/CLineBase.cs @@ -27,12 +27,12 @@ namespace VocaluxeLib.Songs #region Properties public int FirstNoteBeat { - get { return (NoteCount == 0) ? int.MaxValue : _Notes[0].StartBeat; } + get { return NoteCount == 0 ? int.MaxValue : _Notes[0].StartBeat; } } public int LastNoteBeat { - get { return (NoteCount == 0) ? int.MinValue : _Notes[NoteCount - 1].EndBeat; } + get { return NoteCount == 0 ? int.MinValue : _Notes[NoteCount - 1].EndBeat; } } public int NoteCount @@ -64,9 +64,12 @@ namespace VocaluxeLib.Songs get { if (_Notes.Count == 0) + { return 0; - int min = _Notes.Min(note => note.Tone); - int max = _Notes.Max(note => note.Tone); + } + + var min = _Notes.Min(note => note.Tone); + var max = _Notes.Max(note => note.Tone); return min - (max - min) / 4; } @@ -83,35 +86,52 @@ namespace VocaluxeLib.Songs { //If no notes -> No previous note if (_Notes.Count == 0) + { return -1; - int start = 0; - int end = _Notes.Count - 1; + } + + var start = 0; + var end = _Notes.Count - 1; //Ensure that start.StartBeat<=Beat && end.StartBeat>Beat if (_Notes[0].StartBeat > beat) + { return -1; + } + if (_Notes[end].StartBeat <= beat) + { return end; + } + //Binary search while (end - start > 1) { - int mid = (start + end) / 2; + var mid = (start + end) / 2; if (_Notes[mid].StartBeat <= beat) + { start = mid; + } else + { end = mid; + } } + return start; } public virtual bool AddNote(T note) { if (_Notes.Count == 0) + { _Notes.Add(note); + } else { - int insPos = FindPreviousNote(note.StartBeat); + var insPos = FindPreviousNote(note.StartBeat); _Notes.Insert(insPos + 1, note); } + return true; } @@ -122,6 +142,7 @@ namespace VocaluxeLib.Songs _Notes.RemoveAt(index); return true; } + return false; } @@ -132,13 +153,16 @@ namespace VocaluxeLib.Songs _Notes.RemoveAt(index); return AddNote(note); } + return false; } public void IncLastNoteLength() { if (_Notes.Count > 0) + { _Notes[NoteCount - 1].Duration++; + } } public void DeleteAllNotes() diff --git a/VocaluxeLib/Songs/CNotes.cs b/VocaluxeLib/Songs/CNotes.cs index 0f8188ae..f96e24e9 100644 --- a/VocaluxeLib/Songs/CNotes.cs +++ b/VocaluxeLib/Songs/CNotes.cs @@ -25,7 +25,7 @@ namespace VocaluxeLib.Songs { private readonly List _Names = new List(); - public CVoiceNames() {} + public CVoiceNames() { } public CVoiceNames(CVoiceNames names) { @@ -37,7 +37,10 @@ namespace VocaluxeLib.Songs get { if (IsSet(index)) + { return _Names[index]; + } + return "Part " + (index + 1); } set @@ -61,12 +64,15 @@ namespace VocaluxeLib.Songs private readonly List _Voices = new List(); public readonly CVoiceNames VoiceNames = new CVoiceNames(); - public CNotes() {} + public CNotes() { } public CNotes(CNotes notes) { - foreach (CVoice voice in notes._Voices) + foreach (var voice in notes._Voices) + { _Voices.Add(new CVoice(voice)); + } + VoiceNames = new CVoiceNames(notes.VoiceNames); } @@ -85,10 +91,14 @@ namespace VocaluxeLib.Songs if (add) { while (index >= _Voices.Count) + { _Voices.Add(new CVoice()); + } } else if (index >= _Voices.Count) + { return null; + } return _Voices[index]; } @@ -96,7 +106,9 @@ namespace VocaluxeLib.Songs public int GetPoints(int index) { if (index >= _Voices.Count) + { return 0; + } return _Voices[index].Points; } @@ -104,7 +116,9 @@ namespace VocaluxeLib.Songs public int GetNumLinesWithPoints(int index) { if (index >= _Voices.Count) + { return 0; + } return _Voices[index].NumLinesWithPoints; } @@ -117,7 +131,9 @@ namespace VocaluxeLib.Songs public bool ReplaceVoiceAt(int index, CVoice voice) { if (index >= _Voices.Count) + { return false; + } _Voices[index] = voice; return true; @@ -127,13 +143,17 @@ namespace VocaluxeLib.Songs { _Voices.Clear(); if (resetVoices) + { VoiceNames.Reset(); + } } public void SetMedley(int startBeat, int endBeat) { - foreach (CVoice voice in _Voices) + foreach (var voice in _Voices) + { voice.SetMedley(startBeat, endBeat); + } } } } \ No newline at end of file diff --git a/VocaluxeLib/Songs/CSong.cs b/VocaluxeLib/Songs/CSong.cs index 66fe5061..2788a85d 100644 --- a/VocaluxeLib/Songs/CSong.cs +++ b/VocaluxeLib/Songs/CSong.cs @@ -27,13 +27,13 @@ namespace VocaluxeLib.Songs { public class CSongPointer { - public readonly int SongID; + public readonly int SongId; public string SortString; public bool IsSung; public CSongPointer(int id, string sortString) { - SongID = id; + SongId = id; SortString = sortString; } } @@ -46,7 +46,7 @@ namespace VocaluxeLib.Songs MP3 = 4, Instrumental = 5, Vocals = 6, - BPM = 8, + Bpm = 8, MedleyStartBeat = 16, MedleyEndBeat = 32 } @@ -93,17 +93,17 @@ namespace VocaluxeLib.Songs public Encoding Encoding = new UTF8Encoding(); public bool ManualEncoding; - public string Folder = String.Empty; - public string FolderName = String.Empty; - public string FileName = String.Empty; + public string Folder = string.Empty; + public string FolderName = string.Empty; + public string FileName = string.Empty; public bool Relative; - public string MP3FileName = String.Empty; - public string InstrumentalFileName = String.Empty; - public string VocalsFileName = String.Empty; - public string CoverFileName = String.Empty; + public string MP3FileName = string.Empty; + public string InstrumentalFileName = string.Empty; + public string VocalsFileName = string.Empty; + public string CoverFileName = string.Empty; public readonly List BackgroundFileNames = new List(); - public string VideoFileName = String.Empty; + public string VideoFileName = string.Empty; public EAspect VideoAspect = EAspect.Automatic; @@ -114,7 +114,10 @@ namespace VocaluxeLib.Songs get { if (_CoverTextureSmall == null) + { LoadSmallCover(); + } + return _CoverTextureSmall; } @@ -127,11 +130,11 @@ namespace VocaluxeLib.Songs set { _CoverTextureBig = value; } } - public string Title = String.Empty; - public string Artist = String.Empty; + public string Title = string.Empty; + public string Artist = string.Empty; - public string TitleSorting = String.Empty; - public string ArtistSorting = String.Empty; + public string TitleSorting = string.Empty; + public string ArtistSorting = string.Empty; public string Creator = ""; public string Version = ""; @@ -146,9 +149,9 @@ namespace VocaluxeLib.Songs /// /// End of the song in s (ms in txt) /// - public float Finish; + public float End; - public float BPM = 1f; + public float Bpm = 1f; /// /// Gap of the mp3 in s (ms in txt) /// @@ -161,7 +164,7 @@ namespace VocaluxeLib.Songs private string _Comment = ""; // Sorting - public int ID; + public int Id; private readonly bool _Visible = true; private readonly int _CatIndex = -1; private readonly bool _Selected; @@ -179,7 +182,7 @@ namespace VocaluxeLib.Songs public readonly List Languages = new List(); - public int DataBaseSongID = -1; + public int DataBaseSongId = -1; public DateTime DateAdded = DateTime.Today; public int NumPlayed; public int NumPlayedSession; @@ -191,11 +194,16 @@ namespace VocaluxeLib.Songs { get { - var gms = new List {IsDuet ? EGameMode.TR_GAMEMODE_DUET : EGameMode.TR_GAMEMODE_NORMAL}; + var gms = new List { IsDuet ? EGameMode.TR_GAMEMODE_DUET : EGameMode.TR_GAMEMODE_NORMAL }; if (Medley.Source != EDataSource.None) + { gms.Add(EGameMode.TR_GAMEMODE_MEDLEY); + } + if (ShortEnd.Source != EDataSource.None) + { gms.Add(EGameMode.TR_GAMEMODE_SHORTSONG); + } return gms; } @@ -212,7 +220,7 @@ namespace VocaluxeLib.Songs } //No point creating a song without a text file --> Use factory method LoadSong - private CSong() {} + private CSong() { } public CSong(CSong song) { @@ -255,15 +263,15 @@ namespace VocaluxeLib.Songs UnknownTags = new List(song.UnknownTags); Start = song.Start; - Finish = song.Finish; + End = song.End; - BPM = song.BPM; + Bpm = song.Bpm; Gap = song.Gap; VideoGap = song.VideoGap; _Comment = song._Comment; - ID = song.ID; + Id = song.Id; _Visible = song._Visible; _CatIndex = song._CatIndex; _Selected = song._Selected; @@ -276,7 +284,7 @@ namespace VocaluxeLib.Songs Languages = new List(song.Languages); - DataBaseSongID = song.DataBaseSongID; + DataBaseSongId = song.DataBaseSongId; DateAdded = song.DateAdded; NumPlayed = song.NumPlayed; NumPlayedSession = song.NumPlayedSession; @@ -300,9 +308,11 @@ namespace VocaluxeLib.Songs public bool ReloadSong(bool reloadNotes) { var loader = new CSongLoader(this); - bool retValue = loader.ReadHeader(); + var retValue = loader.ReadHeader(); if (!retValue) + { return false; + } retValue = loader.ReadNotes(reloadNotes); return retValue; @@ -352,12 +362,18 @@ namespace VocaluxeLib.Songs public void LoadSmallCover() { if (_CoverTextureSmall != null) + { return; + } + if (CoverFileName != "") { if (CBase.DataBase.GetCover(Path.Combine(Folder, CoverFileName), ref _CoverTextureSmall, CBase.Config.GetCoverSize())) + { return; + } } + _CoverTextureSmall = CBase.Cover.GenerateCover(Title, ECoverGeneratorType.Song, null); } @@ -365,33 +381,39 @@ namespace VocaluxeLib.Songs { if (CoverFileName == "") { - IEnumerable files = CHelper.ListImageFiles(Folder); - foreach (String file in files) + var files = CHelper.ListImageFiles(Folder); + foreach (var file in files) { if (file.ContainsIgnoreCase("[CO]") && (file.ContainsIgnoreCase(Title) || file.ContainsIgnoreCase(Artist))) + { CoverFileName = file; + } } } if (BackgroundFileNames.Count == 0) { - IEnumerable files = CHelper.ListImageFiles(Folder); - foreach (String file in files) + var files = CHelper.ListImageFiles(Folder); + foreach (var file in files) { if (file.ContainsIgnoreCase("[BG]") && (file.ContainsIgnoreCase(Title) || file.ContainsIgnoreCase(Artist))) + { BackgroundFileNames.Add(file); + } } } } private void _CheckDuet() { - for (int i = 0; i < Notes.VoiceCount; i++) + for (var i = 0; i < Notes.VoiceCount; i++) { if (!Notes.VoiceNames.IsSet(i)) + { CLog.Error("Warning: Can't find #P" + (i + 1) + "-tag for duets in \"" + Artist + " - " + Title + "\"."); + } } } @@ -404,42 +426,56 @@ namespace VocaluxeLib.Songs private List _GetSeries() { - CVoice voice = Notes.GetVoice(0); + var voice = Notes.GetVoice(0); if (voice.NumLines == 0) + { return null; + } // build sentences list - List sentences = voice.Lines.Select(line => line.Points != 0 ? line.Lyrics : String.Empty).ToList(); + var sentences = voice.Lines.Select(line => line.Points != 0 ? line.Lyrics : string.Empty).ToList(); // find equal sentences series var series = new List(); - for (int i = 0; i < voice.NumLines - 1; i++) + for (var i = 0; i < voice.NumLines - 1; i++) { - for (int j = i + 1; j < voice.NumLines; j++) + for (var j = i + 1; j < voice.NumLines; j++) { if (sentences[i] != sentences[j] || sentences[i] == "") + { continue; - var tempSeries = new SSeries {Start = i, End = i}; + } + + var tempSeries = new SSeries { Start = i, End = i }; int max; if (j + j - i > voice.NumLines) + { max = voice.NumLines - 1 - j; + } else + { max = j - i - 1; + } - for (int k = 1; k <= max; k++) + for (var k = 1; k <= max; k++) { if (sentences[i + k] == sentences[j + k] && sentences[i + k] != "") + { tempSeries.End = i + k; + } else + { break; + } } tempSeries.Length = tempSeries.End - tempSeries.Start + 1; series.Add(tempSeries); } } + return series; } @@ -452,21 +488,27 @@ namespace VocaluxeLib.Songs } if (!_CalculateMedley || Medley.Source != EDataSource.None) - return; - - List series = _GetSeries(); - if (series == null) - return; - - // search for longest series - int longest = 0; - for (int i = 0; i < series.Count; i++) { - if (series[i].Length > series[longest].Length) - longest = i; + return; } - CVoice voice = Notes.GetVoice(0); + var series = _GetSeries(); + if (series == null) + { + return; + } + + // search for longest series + var longest = 0; + for (var i = 0; i < series.Count; i++) + { + if (series[i].Length > series[longest].Length) + { + longest = i; + } + } + + var voice = Notes.GetVoice(0); // set medley vars if (series.Count > 0 && series[longest].Length > CBase.Settings.GetMedleyMinSeriesLength()) @@ -474,15 +516,15 @@ namespace VocaluxeLib.Songs Medley.StartBeat = voice.Lines[series[longest].Start].FirstNoteBeat; Medley.EndBeat = voice.Lines[series[longest].End].LastNoteBeat; - bool foundEnd = CBase.Game.GetTimeFromBeats(Medley.EndBeat, BPM) - CBase.Game.GetTimeFromBeats(Medley.StartBeat, BPM) < CBase.Settings.GetMedleyMinDuration(); + var foundEnd = CBase.Game.GetTimeFromBeats(Medley.EndBeat, Bpm) - CBase.Game.GetTimeFromBeats(Medley.StartBeat, Bpm) < CBase.Settings.GetMedleyMinDuration(); // set end if duration < MedleyMinDuration if (!foundEnd) { - for (int i = series[longest].End + 1; i < voice.NumLines - 1; i++) + for (var i = series[longest].End + 1; i < voice.NumLines - 1; i++) { - if (CBase.Game.GetTimeFromBeats(voice.Lines[i].LastNoteBeat, BPM) - CBase.Game.GetTimeFromBeats(Medley.StartBeat, BPM) < + if (CBase.Game.GetTimeFromBeats(voice.Lines[i].LastNoteBeat, Bpm) - CBase.Game.GetTimeFromBeats(Medley.StartBeat, Bpm) < CBase.Settings.GetMedleyMinDuration()) { foundEnd = true; @@ -504,10 +546,13 @@ namespace VocaluxeLib.Songs private void _CheckPreview() { if (Preview.Source != EDataSource.None) + { return; + } + if (Medley.Source != EDataSource.None) { - Preview.StartTime = CBase.Game.GetTimeFromBeats(Medley.StartBeat, BPM); + Preview.StartTime = CBase.Game.GetTimeFromBeats(Medley.StartBeat, Bpm); Preview.Source = EDataSource.Calculated; } } @@ -515,28 +560,33 @@ namespace VocaluxeLib.Songs private void _FindShortEnd() { if (ShortEnd.Source != EDataSource.None) + { return; + } - List series = _GetSeries(); + var series = _GetSeries(); if (series == null) + { return; + } - CVoice voice = Notes.GetVoice(0); + var voice = Notes.GetVoice(0); //Calculate length of singing - int stop = (voice.Lines[voice.Lines.Length - 1].LastNoteBeat - voice.Lines[0].FirstNote.StartBeat) / 2 + voice.Lines[0].FirstNote.StartBeat; + var stop = (voice.Lines[voice.Lines.Length - 1].LastNoteBeat - voice.Lines[0].FirstNote.StartBeat) / 2 + voice.Lines[0].FirstNote.StartBeat; //Check if stop is in series - for (int i = 0; i < series.Count; i++) + for (var i = 0; i < series.Count; i++) { if (voice.Lines[series[i].Start].FirstNoteBeat < stop && voice.Lines[series[i].End].LastNoteBeat > stop) { - if (stop < (voice.Lines[series[i].Start].FirstNoteBeat + ((voice.Lines[series[i].End].LastNoteBeat - voice.Lines[series[i].Start].FirstNoteBeat) / 2))) + if (stop < voice.Lines[series[i].Start].FirstNoteBeat + (voice.Lines[series[i].End].LastNoteBeat - voice.Lines[series[i].Start].FirstNoteBeat) / 2) { ShortEnd.EndBeat = voice.Lines[series[i].Start - 1].LastNote.EndBeat; ShortEnd.Source = EDataSource.Calculated; return; } + ShortEnd.EndBeat = voice.Lines[series[i].End].LastNote.EndBeat; ShortEnd.Source = EDataSource.Calculated; return; @@ -544,7 +594,7 @@ namespace VocaluxeLib.Songs } //Check if stop is in line - foreach (CSongLine line in voice.Lines) + foreach (var line in voice.Lines) { if (line.FirstNoteBeat < stop && line.LastNoteBeat > stop) { @@ -558,4 +608,4 @@ namespace VocaluxeLib.Songs ShortEnd.Source = EDataSource.Calculated; } } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Songs/CSongLine.cs b/VocaluxeLib/Songs/CSongLine.cs index 4dffe501..7c348793 100644 --- a/VocaluxeLib/Songs/CSongLine.cs +++ b/VocaluxeLib/Songs/CSongLine.cs @@ -33,8 +33,11 @@ namespace VocaluxeLib.Songs public CSongLine(CSongLine line) { - foreach (CSongNote note in line._Notes) + foreach (var note in line._Notes) + { _Notes.Add(new CSongNote(note)); + } + _StartBeat = line._StartBeat; _EndBeat = line._EndBeat; VisibleInTimeLine = line.VisibleInTimeLine; @@ -50,7 +53,9 @@ namespace VocaluxeLib.Songs set { if (value <= FirstNoteBeat) + { _StartBeat = value; + } } } @@ -60,13 +65,15 @@ namespace VocaluxeLib.Songs set { if (value >= LastNoteBeat) + { _EndBeat = value; + } } } public string Lyrics { - get { return _Notes.Aggregate(String.Empty, (current, note) => current + note.Text); } + get { return _Notes.Aggregate(string.Empty, (current, note) => current + note.Text); } } #endregion Properties @@ -74,31 +81,42 @@ namespace VocaluxeLib.Songs public override bool AddNote(CSongNote note) { if (_Notes.Count == 0) + { _Notes.Add(note); + } else { //Insert AFTER this note - int insPos = FindPreviousNote(note.StartBeat); + var insPos = FindPreviousNote(note.StartBeat); //Check for overlapping notes if (insPos >= 0) //Check note before { if (_Notes[insPos].EndBeat >= note.StartBeat) + { return false; + } } + if (insPos < _Notes.Count - 1) //Check note after { if (_Notes[insPos + 1].StartBeat <= note.EndBeat) + { return false; + } } + _Notes.Insert(insPos + 1, note); } + return true; } public void SetMedley(int startBeat, int endBeat) { - foreach (CSongNote note in _Notes.Where(note => note.StartBeat < startBeat || note.EndBeat > endBeat)) + foreach (var note in _Notes.Where(note => note.StartBeat < startBeat || note.EndBeat > endBeat)) + { note.Type = ENoteType.Freestyle; + } VisibleInTimeLine = FirstNoteBeat >= startBeat && LastNoteBeat <= endBeat; } diff --git a/VocaluxeLib/Songs/CSongLoader.cs b/VocaluxeLib/Songs/CSongLoader.cs index 2dffc39c..bb1bd175 100644 --- a/VocaluxeLib/Songs/CSongLoader.cs +++ b/VocaluxeLib/Songs/CSongLoader.cs @@ -18,7 +18,6 @@ using System; using System.IO; using System.Linq; -using System.Text; using VocaluxeLib.Log; namespace VocaluxeLib.Songs @@ -31,7 +30,7 @@ namespace VocaluxeLib.Songs /// /// Factor the bpm given in the txt is multiplied with /// - private const int _BPMFactor = 4; + private const int _BpmFactor = 4; private class CSongLoader { @@ -46,38 +45,48 @@ namespace VocaluxeLib.Songs public bool InitPaths(string filePath) { if (!File.Exists(filePath)) + { return false; + } _Song.Folder = Path.GetDirectoryName(filePath); if (_Song.Folder == null) + { return false; + } - foreach (string folder in CBase.Config.GetSongFolders().Where(folder => _Song.Folder.StartsWith(folder))) + foreach (var folder in CBase.Config.GetSongFolders().Where(folder => _Song.Folder.StartsWith(folder))) { if (_Song.Folder.Length == folder.Length) + { _Song.FolderName = "Songs"; + } else { _Song.FolderName = _Song.Folder.Substring(folder.Length + 1); - int pos = _Song.FolderName.IndexOf("\\", StringComparison.Ordinal); + var pos = _Song.FolderName.IndexOf("\\", StringComparison.Ordinal); if (pos >= 0) + { _Song.FolderName = _Song.FolderName.Substring(0, pos); + } } + break; } _Song.FileName = Path.GetFileName(filePath); return true; } - public bool ReadHeader(bool useSetEncoding = false) { - string filePath = Path.Combine(_Song.Folder, _Song.FileName); + var filePath = Path.Combine(_Song.Folder, _Song.FileName); if (!File.Exists(filePath)) + { return false; + } _Song.Languages.Clear(); _Song.Genres.Clear(); @@ -101,52 +110,61 @@ namespace VocaluxeLib.Songs sr = new StreamReader(filePath, _Song.Encoding, true); while (!sr.EndOfStream) { - string line = sr.ReadLine(); + var line = sr.ReadLine(); _LineNr++; if (line == "") + { continue; - if (!line[0].Equals('#')) - break; + } - int pos = line.IndexOf(":", StringComparison.Ordinal); + if (!line[0].Equals('#')) + { + break; + } + + var pos = line.IndexOf(":", StringComparison.Ordinal); if (pos <= 1) { _Song.UnknownTags.Add(line); continue; } - string identifier = line.Substring(1, pos - 1).Trim().ToUpper(); + + var identifier = line.Substring(1, pos - 1).Trim().ToUpper(); if (identifier.Contains(" ")) { _Song.UnknownTags.Add(line); continue; } - string value = line.Substring(pos + 1).Trim(); + + var value = line.Substring(pos + 1).Trim(); if (value == "") { _Song.UnknownTags.Add(line); - CLog.CSongLog.Warning("[{SongFileName}] Empty value skipped", CLog.Params(_Song.FileName)); + CLog.CSongLog.Warning("[{SongFileName}] Empty value skipped", CLog.Params(_Song.FileName)); continue; } switch (identifier) { case "ENCODING": - Encoding newEncoding = value.GetEncoding(); + var newEncoding = value.GetEncoding(); _Song.ManualEncoding = true; if (!newEncoding.Equals(sr.CurrentEncoding)) { if (useSetEncoding) { - CLog.CSongLog.Warning("[{SongFileName}] Duplicate encoding ignored", CLog.Params(_Song.FileName)); + CLog.CSongLog.Warning("[{SongFileName}] Duplicate encoding ignored", CLog.Params(_Song.FileName)); continue; } + sr.Dispose(); sr = null; _Song.Encoding = newEncoding; return ReadHeader(true); } + break; case "TITLE": _Song.Title = value; @@ -190,6 +208,7 @@ namespace VocaluxeLib.Songs CLog.CSongLog.Error("[{SongFileName}] Can't find audio file: {AudioFile}", CLog.Params(_Song.FileName, Path.Combine(_Song.Folder, value))); return false; } + break; case "INSTRUMENTAL": if (File.Exists(Path.Combine(_Song.Folder, value))) @@ -199,9 +218,11 @@ namespace VocaluxeLib.Songs } else { - CLog.CSongLog.Error("[{SongFileName}] Can't find instrumental audio file: {AudioFile}", CLog.Params(_Song.FileName, Path.Combine(_Song.Folder, value))); + CLog.CSongLog.Error("[{SongFileName}] Can't find instrumental audio file: {AudioFile}", + CLog.Params(_Song.FileName, Path.Combine(_Song.Folder, value))); return false; } + break; case "VOCALS": if (File.Exists(Path.Combine(_Song.Folder, value))) @@ -211,36 +232,56 @@ namespace VocaluxeLib.Songs } else { - CLog.CSongLog.Error("[{SongFileName}] Can't find vocal audio file: {AudioFile}", CLog.Params(_Song.FileName, Path.Combine(_Song.Folder, value))); + CLog.CSongLog.Error("[{SongFileName}] Can't find vocal audio file: {AudioFile}", + CLog.Params(_Song.FileName, Path.Combine(_Song.Folder, value))); return false; } + break; case "BPM": - if (CHelper.TryParse(value, out _Song.BPM)) + if (CHelper.TryParse(value, out _Song.Bpm)) { - _Song.BPM *= _BPMFactor; - headerFlags |= EHeaderFlags.BPM; + _Song.Bpm *= _BpmFactor; + headerFlags |= EHeaderFlags.Bpm; } else + { CLog.CSongLog.Warning("[{SongFileName}] Invalid BPM value: {Value}", CLog.Params(_Song.FileName, value)); + } + break; case "EDITION": if (value.Length > 1) + { _Song.Editions.Add(value); + } else + { CLog.CSongLog.Warning("[{SongFileName}] Invalid edition: {Value}", CLog.Params(_Song.FileName, value)); + } + break; case "GENRE": if (value.Length > 1) + { _Song.Genres.Add(value); + } else + { CLog.CSongLog.Warning("[{SongFileName}] Invalid genre: {Value}", CLog.Params(_Song.FileName, value)); + } + break; case "TAGS": if (value.Length > 1) + { _Song.Tags.AddRange(value.Split(',')); + } else + { CLog.CSongLog.Warning("[{SongFileName}] Invalid tags: {Value}", CLog.Params(_Song.FileName, value)); + } + break; case "ALBUM": _Song.Album = value; @@ -248,68 +289,121 @@ namespace VocaluxeLib.Songs case "YEAR": int num; if (value.Length == 4 && int.TryParse(value, out num) && num > 0) + { _Song.Year = value; + } else + { CLog.CSongLog.Warning("[{SongFileName}] Invalid year: {Value}", CLog.Params(_Song.FileName, value)); + } + break; case "LANGUAGE": if (value.Length > 1) + { _Song.Languages.Add(_UnifyLanguage(value)); + } else + { CLog.CSongLog.Warning("[{SongFileName}] Invalid language: {Value}", CLog.Params(_Song.FileName, value)); + } + break; case "COMMENT": - if (!String.IsNullOrEmpty(_Song._Comment)) + if (!string.IsNullOrEmpty(_Song._Comment)) + { _Song._Comment += "\r\n"; + } + _Song._Comment += value; break; case "GAP": if (CHelper.TryParse(value, out _Song.Gap)) + { _Song.Gap /= 1000f; + } else + { CLog.CSongLog.Warning("[{SongFileName}] Invalid gap: {Value}", CLog.Params(_Song.FileName, value)); + } + break; case "COVER": if (File.Exists(Path.Combine(_Song.Folder, value))) + { _Song.CoverFileName = value; + } else + { CLog.CSongLog.Warning("[{SongFileName}] Can't find cover file: {MissingFile}", CLog.Params(_Song.FileName, Path.Combine(_Song.Folder, value))); + } + break; case "BACKGROUND": if (File.Exists(Path.Combine(_Song.Folder, value))) + { _Song.BackgroundFileNames.Add(value); + } else - CLog.CSongLog.Warning("[{SongFileName}] Can't find background file: {MissingFile}", CLog.Params(_Song.FileName, Path.Combine(_Song.Folder, value))); + { + CLog.CSongLog.Warning("[{SongFileName}] Can't find background file: {MissingFile}", + CLog.Params(_Song.FileName, Path.Combine(_Song.Folder, value))); + } + break; case "VIDEO": if (File.Exists(Path.Combine(_Song.Folder, value))) + { _Song.VideoFileName = value; + } else + { CLog.CSongLog.Warning("[{SongFileName}] Can't find video file: {MissingFile}", CLog.Params(_Song.FileName, Path.Combine(_Song.Folder, value))); + } + break; case "VIDEOGAP": if (!CHelper.TryParse(value, out _Song.VideoGap)) + { CLog.CSongLog.Warning("[{SongFileName}] Invalid videogap: {Value}", CLog.Params(_Song.FileName, value)); + } + break; case "VIDEOASPECT": if (!CHelper.TryParse(value, out _Song.VideoAspect, true)) + { CLog.CSongLog.Warning("[{SongFileName}] Invalid videoaspect: {Value}", CLog.Params(_Song.FileName, value)); + } + break; case "START": if (!CHelper.TryParse(value, out _Song.Start)) + { CLog.CSongLog.Warning("[{SongFileName}] Invalid start: {Value}", CLog.Params(_Song.FileName, value)); + } + break; case "END": - if (CHelper.TryParse(value, out _Song.Finish)) - _Song.Finish /= 1000f; + if (CHelper.TryParse(value, out _Song.End)) + { + _Song.End /= 1000f; + } else + { CLog.CSongLog.Warning("[{SongFileName}] Invalid end: {Value}", CLog.Params(_Song.FileName, value)); + } + break; case "PREVIEWSTART": if (CHelper.TryParse(value, out _Song.Preview.StartTime) && _Song.Preview.StartTime >= 0f) + { _Song.Preview.Source = EDataSource.Tag; + } else + { CLog.CSongLog.Warning("[{SongFileName}] Invalid previewstart: {Value}", CLog.Params(_Song.FileName, value)); + } + break; case "PREVIEW": if (CHelper.TryParse(value, out _Song.Preview.StartTime) && _Song.Preview.StartTime >= 0f) @@ -319,40 +413,62 @@ namespace VocaluxeLib.Songs _Song.Preview.Source = EDataSource.Tag; } else + { CLog.CSongLog.Warning("[{SongFileName}] Invalid previewstart: {Value}", CLog.Params(_Song.FileName, value)); + } + break; case "MEDLEYSTARTBEAT": if (int.TryParse(value, out _Song.Medley.StartBeat)) + { headerFlags |= EHeaderFlags.MedleyStartBeat; + } else + { CLog.CSongLog.Warning("[{SongFileName}] Invalid medleystartbeat: {Value}", CLog.Params(_Song.FileName, value)); + } + break; case "MEDLEYENDBEAT": if (int.TryParse(value, out _Song.Medley.EndBeat)) + { headerFlags |= EHeaderFlags.MedleyEndBeat; + } else + { CLog.CSongLog.Warning("[{SongFileName}] Invalid medleyendbeat: {Value}", CLog.Params(_Song.FileName, value)); + } + break; case "ENDSHORT": - if ((headerFlags & EHeaderFlags.BPM) != 0) + if ((headerFlags & EHeaderFlags.Bpm) != 0) { int endTime; if (int.TryParse(value, out endTime) || endTime < 0) { - _Song.ShortEnd.EndBeat = (int)CBase.Game.GetBeatFromTime(endTime / 1000f, _Song.BPM, _Song.Gap); + _Song.ShortEnd.EndBeat = (int)CBase.Game.GetBeatFromTime(endTime / 1000f, _Song.Bpm, _Song.Gap); _Song.ShortEnd.Source = EDataSource.Tag; } else + { CLog.CSongLog.Warning("[{SongFileName}] Invalid shortendbeat: {Value}", CLog.Params(_Song.FileName, value)); + } } + break; case "CALCMEDLEY": if (value.ToUpper() == "OFF") + { _Song._CalculateMedley = false; + } + break; case "RELATIVE": if (value.ToUpper() == "YES") + { _Song.Relative = true; + } + break; case "RESOLUTION": case "NOTESGAP": @@ -364,15 +480,20 @@ namespace VocaluxeLib.Songs { identifier = identifier.Substring(10); if (!identifier.StartsWith("P")) // fix for missing "P" + { identifier = "P" + identifier; + } } + if (identifier.StartsWith("P")) { int player; if (int.TryParse(identifier.Substring(1).Trim(), out player)) { - foreach (int curPlayer in player.GetSetBits()) + foreach (var curPlayer in player.GetSetBits()) + { _Song.Notes.VoiceNames[curPlayer] = value; + } } } else @@ -388,32 +509,32 @@ namespace VocaluxeLib.Songs if (sr.EndOfStream) { //No other data then header - CLog.CSongLog.Error("[{SongFileName}] Lyrics/Notes missing", CLog.Params(_Song.FileName)); + CLog.CSongLog.Error("[{SongFileName}] Lyrics/Notes missing", CLog.Params(_Song.FileName)); return false; } if ((headerFlags & EHeaderFlags.Title) == 0) { - CLog.CSongLog.Error("[{SongFileName}] Title tag missing", CLog.Params(_Song.FileName)); + CLog.CSongLog.Error("[{SongFileName}] Title tag missing", CLog.Params(_Song.FileName)); return false; } if ((headerFlags & EHeaderFlags.Artist) == 0) { - CLog.CSongLog.Error("[{SongFileName}] Artist tag missing", CLog.Params(_Song.FileName)); + CLog.CSongLog.Error("[{SongFileName}] Artist tag missing", CLog.Params(_Song.FileName)); return false; } if ((headerFlags & EHeaderFlags.MP3) == 0) { - CLog.CSongLog.Error("[{SongFileName}] MP3 or AUDIO tag missing", CLog.Params(_Song.FileName)); + CLog.CSongLog.Error("[{SongFileName}] MP3 or AUDIO tag missing", CLog.Params(_Song.FileName)); return false; } - if ((headerFlags & EHeaderFlags.BPM) == 0) + if ((headerFlags & EHeaderFlags.Bpm) == 0) { - CLog.CSongLog.Error("[{SongFileName}] BPM tag missing", CLog.Params(_Song.FileName)); + CLog.CSongLog.Error("[{SongFileName}] Bpm tag missing", CLog.Params(_Song.FileName)); return false; } @@ -422,7 +543,8 @@ namespace VocaluxeLib.Songs { if (_Song.Medley.StartBeat > _Song.Medley.EndBeat) { - CLog.CSongLog.Error("[{SongFileName}] MedleyStartBeat is bigger than MedleyEndBeat in file: {StartBeat} > {EndBeat}", CLog.Params(_Song.FileName, _Song.Medley.StartBeat > _Song.Medley.EndBeat)); + CLog.CSongLog.Error("[{SongFileName}] MedleyStartBeat is bigger than MedleyEndBeat in file: {StartBeat} > {EndBeat}", + CLog.Params(_Song.FileName, _Song.Medley.StartBeat > _Song.Medley.EndBeat)); headerFlags = headerFlags - EHeaderFlags.MedleyStartBeat - EHeaderFlags.MedleyEndBeat; } } @@ -430,7 +552,7 @@ namespace VocaluxeLib.Songs if (_Song.Preview.Source == EDataSource.None) { //PreviewStart is not set or <=0 - _Song.Preview.StartTime = (headerFlags & EHeaderFlags.MedleyStartBeat) != 0 ? CBase.Game.GetTimeFromBeats(_Song.Medley.StartBeat, _Song.BPM) : 0f; + _Song.Preview.StartTime = (headerFlags & EHeaderFlags.MedleyStartBeat) != 0 ? CBase.Game.GetTimeFromBeats(_Song.Medley.StartBeat, _Song.Bpm) : 0f; // ReSharper disable CompareOfFloatsByEqualityOperator _Song.Preview.Source = _Song.Preview.StartTime == 0 ? EDataSource.None : EDataSource.Calculated; // ReSharper restore CompareOfFloatsByEqualityOperator @@ -447,22 +569,30 @@ namespace VocaluxeLib.Songs catch (Exception e) { if (sr != null) + { sr.Dispose(); + } + CLog.CSongLog.Error(e, "[{SongFileName}] Error reading txt header with Message: {ExceptionMessage}", CLog.Params(e.Message, _Song.FileName)); return false; } + _Song.Encoding = sr.CurrentEncoding; sr.Dispose(); _Song._CheckFiles(); - CBase.DataBase.GetDataBaseSongInfos(_Song.Artist, _Song.Title, out _Song.NumPlayed, out _Song.DateAdded, out _Song.DataBaseSongID); + CBase.DataBase.GetDataBaseSongInfos(_Song.Artist, _Song.Title, out _Song.NumPlayed, out _Song.DateAdded, out _Song.DataBaseSongId); //Before saving this tags to .txt: Check, if ArtistSorting and Artist are equal, then don't save this tag. - if (String.IsNullOrEmpty(_Song.ArtistSorting)) + if (string.IsNullOrEmpty(_Song.ArtistSorting)) + { _Song.ArtistSorting = _Song.Artist; + } - if (String.IsNullOrEmpty(_Song.TitleSorting)) + if (string.IsNullOrEmpty(_Song.TitleSorting)) + { _Song.TitleSorting = _Song.Title; + } return true; } @@ -485,6 +615,7 @@ namespace VocaluxeLib.Songs break; } } + return lang; } @@ -511,15 +642,25 @@ namespace VocaluxeLib.Songs public override string ToString() { - string result = ""; - int skippedNotesCt = ZeroLengthNoteCt + OverlapNoteCt + NoTextNoteCt; + var result = ""; + var skippedNotesCt = ZeroLengthNoteCt + OverlapNoteCt + NoTextNoteCt; if (skippedNotesCt > 0) - result += "Skipped " + skippedNotesCt + " notes (0-Length: " + ZeroLengthNoteCt + ", Overlapping: " + OverlapNoteCt + ", No text: " + NoTextNoteCt + ")\r\n"; + { + result += "Skipped " + skippedNotesCt + " notes (0-Length: " + ZeroLengthNoteCt + ", Overlapping: " + OverlapNoteCt + ", No text: " + NoTextNoteCt + + ")\r\n"; + } + if (InvalidPosBreakCt > 0) + { result += "Skipped " + InvalidPosBreakCt + " line breaks (Invalid position)\r\n"; - int adjustedBreakCt = AjustedBreakCt + NoLengthBreakCt; + } + + var adjustedBreakCt = AjustedBreakCt + NoLengthBreakCt; if (adjustedBreakCt > 0) + { result += "Adjusted " + adjustedBreakCt + " line breaks (Overlapping previous note: " + AjustedBreakCt + ", No length: " + NoLengthBreakCt + ")\r\n"; + } + return result; } } @@ -539,25 +680,27 @@ namespace VocaluxeLib.Songs { //Skip loading if already done and no reload is forced if (_Song.NotesLoaded && !forceReload) + { return true; + } - string filePath = Path.Combine(_Song.Folder, _Song.FileName); + var filePath = Path.Combine(_Song.Folder, _Song.FileName); if (!File.Exists(filePath)) { - CLog.CSongLog.Error("[{SongFileName}] The file songfile does not exist", CLog.Params(_Song.FileName)); + CLog.CSongLog.Error("[{SongFileName}] The file songfile does not exist", CLog.Params(_Song.FileName)); return false; } - int currentBeat = 0; //Used for relative songs + var currentBeat = 0; //Used for relative songs CSongNote lastNote = null; //Holds last parsed note. Get's reset on player change - bool endFound = false; // True if end tag was found + var endFound = false; // True if end tag was found - int player = 1; + var player = 1; _LineNr = 0; - char[] trimChars = {' ', ':'}; - char[] splitChars = {' '}; + char[] trimChars = { ' ', ':' }; + char[] splitChars = { ' ' }; var changesMade = new CAutoChanges(); @@ -571,15 +714,17 @@ namespace VocaluxeLib.Songs //Search for Note Beginning while (!sr.EndOfStream && !endFound) { - string line = sr.ReadLine(); + var line = sr.ReadLine(); _LineNr++; - if (String.IsNullOrEmpty(line)) + if (string.IsNullOrEmpty(line)) + { continue; + } - char tag = line[0]; + var tag = line[0]; //Remove tag and potential space - line = (line.Length >= 2 && line[1] == ' ') ? line.Substring(2) : line.Substring(1); + line = line.Length >= 2 && line[1] == ' ' ? line.Substring(2) : line.Substring(1); int beat, length; switch (tag) @@ -597,6 +742,7 @@ namespace VocaluxeLib.Songs CLog.CSongLog.Error("[{SongFileName}] Wrong or missing number after \"P\" (in line {LineNr})", CLog.Params(_Song.FileName, _LineNr)); return false; } + currentBeat = 0; lastNote = null; break; @@ -605,7 +751,7 @@ namespace VocaluxeLib.Songs case 'R': case 'G': case 'F': - string[] noteData = line.Split(splitChars, 4); + var noteData = line.Split(splitChars, 4); if (noteData.Length < 4) { if (noteData.Length == 3) @@ -614,36 +760,46 @@ namespace VocaluxeLib.Songs changesMade.NoTextNoteCt++; continue; } + CLog.CSongLog.Error("[{SongFileName}] Invalid note found (in line {LineNr}): {noteData}", CLog.Params(_Song.FileName, _LineNr, noteData)); sr.Dispose(); return false; } + int tone; if (!int.TryParse(noteData[0], out beat) || !int.TryParse(noteData[1], out length) || !int.TryParse(noteData[2], out tone)) { - CLog.CSongLog.Error("[{SongFileName}] Invalid note found (non-numeric values) (in line {LineNr}): {noteData}", CLog.Params(_Song.FileName, _LineNr, noteData)); + CLog.CSongLog.Error("[{SongFileName}] Invalid note found (non-numeric values) (in line {LineNr}): {noteData}", + CLog.Params(_Song.FileName, _LineNr, noteData)); sr.Dispose(); return false; } - string text = noteData[3].TrimMultipleWs(); + + var text = noteData[3].TrimMultipleWs(); if (text == "") { CLog.CSongLog.Warning("[{SongFileName}] Ignored note without text (in line {LineNr})", CLog.Params(_Song.FileName, _LineNr)); changesMade.NoTextNoteCt++; continue; } + if (_CurrentReadMode == ENoteReadMode.ZeroBased) + { length++; + } + if (length < 1) { changesMade.ZeroLengthNoteCt++; if (_CurrentReadMode == ENoteReadMode.Normal && changesMade.ZeroLengthNoteCt > _MaxZeroNoteCt && changesMade.OverlapNoteCt <= _MaxOverlapNoteCt) { - CLog.CSongLog.Warning("[{SongFileName}] Found more than {MaxZeroNoteCt} notes with length < 1. Trying alternative read mode.", CLog.Params(_Song.FileName, _MaxZeroNoteCt)); + CLog.CSongLog.Warning("[{SongFileName}] Found more than {MaxZeroNoteCt} notes with length < 1. Trying alternative read mode.", + CLog.Params(_Song.FileName, _MaxZeroNoteCt)); _CurrentReadMode = ENoteReadMode.ZeroBased; sr.Dispose(); return ReadNotes(true); } + CLog.CSongLog.Warning("[{SongFileName}] Ignored note with length < 1 (in line {LineNr})", CLog.Params(_Song.FileName, _LineNr)); } else @@ -651,9 +807,13 @@ namespace VocaluxeLib.Songs ENoteType noteType; if (tag.Equals('*')) + { noteType = ENoteType.Golden; + } else if (tag.Equals('F')) + { noteType = ENoteType.Freestyle; + } else if (tag.Equals('R')) { noteType = ENoteType.Rap; @@ -665,13 +825,17 @@ namespace VocaluxeLib.Songs _Song.IsRap = true; } else + { noteType = ENoteType.Normal; + } if (_Song.Relative) + { beat += currentBeat; + } - bool ignored = false; - foreach (int curPlayer in player.GetSetBits()) + var ignored = false; + foreach (var curPlayer in player.GetSetBits()) { //Create the note here as we want independent instances in the lines. Otherwhise we can't modify them later lastNote = new CSongNote(beat, length, tone, text, noteType); @@ -683,28 +847,36 @@ namespace VocaluxeLib.Songs changesMade.OverlapNoteCt++; if (changesMade.OverlapNoteCt > _MaxOverlapNoteCt && _CurrentReadMode == ENoteReadMode.ZeroBased) { - CLog.CSongLog.Warning("[{SongFileName}] Found more than {MaxOverlapNoteCt} overlapping notes. Using standard mode.", CLog.Params(_Song.FileName, _MaxOverlapNoteCt)); + CLog.CSongLog.Warning("[{SongFileName}] Found more than {MaxOverlapNoteCt} overlapping notes. Using standard mode.", + CLog.Params(_Song.FileName, _MaxOverlapNoteCt)); _CurrentReadMode = ENoteReadMode.OneBased; sr.Dispose(); return ReadNotes(true); } } - CLog.CSongLog.Warning("[{SongFileName}] Ignored note for player {CurrentPlayerNumber} because it overlaps with other note (in line {LineNr})", CLog.Params(_Song.FileName, (curPlayer + 1), _LineNr)); + + CLog.CSongLog.Warning( + "[{SongFileName}] Ignored note for player {CurrentPlayerNumber} because it overlaps with other note (in line {LineNr})", + CLog.Params(_Song.FileName, curPlayer + 1, _LineNr)); } } } + break; case '-': - string[] lineBreakData = line.Split(splitChars); + var lineBreakData = line.Split(splitChars); if (lineBreakData.Length < 1) { - CLog.CSongLog.Error("[{SongFileName}] Invalid line break found (No beat) (in line {LineNr}): {LineBreakData}", CLog.Params(_Song.FileName, _LineNr, lineBreakData)); + CLog.CSongLog.Error("[{SongFileName}] Invalid line break found (No beat) (in line {LineNr}): {LineBreakData}", + CLog.Params(_Song.FileName, _LineNr, lineBreakData)); sr.Dispose(); return false; } + if (!int.TryParse(lineBreakData[0], out beat)) { - CLog.CSongLog.Error("[{SongFileName}] Invalid line break found (Non-numeric value) (in line {LineNr}): {LineBreakData}", CLog.Params(_Song.FileName, _LineNr, lineBreakData)); + CLog.CSongLog.Error("[{SongFileName}] Invalid line break found (Non-numeric value) (in line {LineNr}): {LineBreakData}", + CLog.Params(_Song.FileName, _LineNr, lineBreakData)); sr.Dispose(); return false; } @@ -714,21 +886,28 @@ namespace VocaluxeLib.Songs beat += currentBeat; if (lineBreakData.Length < 2 || !int.TryParse(lineBreakData[1], out length)) { - CLog.CSongLog.Warning("[{SongFileName}] Missing line break length (in line {LineNr}):{LineBreakData}", CLog.Params(_Song.FileName, _LineNr, lineBreakData)); + CLog.CSongLog.Warning("[{SongFileName}] Missing line break length (in line {LineNr}):{LineBreakData}", + CLog.Params(_Song.FileName, _LineNr, lineBreakData)); changesMade.NoLengthBreakCt++; currentBeat = beat; } else + { currentBeat += length; + } } if (lastNote != null && beat <= lastNote.EndBeat) { - CLog.CSongLog.Warning("[{SongFileName}] Line break is before previous note end. Adjusted. (in line {LineNr})", CLog.Params(_Song.FileName, _LineNr)); - + CLog.CSongLog.Warning("[{SongFileName}] Line break is before previous note end. Adjusted. (in line {LineNr})", + CLog.Params(_Song.FileName, _LineNr)); + changesMade.AjustedBreakCt++; if (_Song.Relative) + { currentBeat += lastNote.EndBeat - beat + 1; + } + beat = lastNote.EndBeat + 1; } @@ -739,12 +918,16 @@ namespace VocaluxeLib.Songs } else { - foreach (int curPlayer in player.GetSetBits()) + foreach (var curPlayer in player.GetSetBits()) { if (!_NewSentence(curPlayer, beat)) - CLog.CSongLog.Warning("[{SongFileName}] Ignored line break for player {CurPlayerNr} (Overlapping or duplicate) (in line {LineNr})", CLog.Params(_Song.FileName, (curPlayer + 1) , _LineNr)); + { + CLog.CSongLog.Warning("[{SongFileName}] Ignored line break for player {CurPlayerNr} (Overlapping or duplicate) (in line {LineNr})", + CLog.Params(_Song.FileName, curPlayer + 1, _LineNr)); + } } } + break; default: CLog.CSongLog.Error("[{SongFileName}] Unexpected or missing character ({Tag})", CLog.Params(_Song.FileName, tag)); @@ -752,12 +935,16 @@ namespace VocaluxeLib.Songs } } - for (int i = 0; i < _Song.Notes.VoiceCount; i++) + for (var i = 0; i < _Song.Notes.VoiceCount; i++) { - CVoice voice = _Song.Notes.GetVoice(i); - int emptyLines = voice.RemoveEmptyLines(); + var voice = _Song.Notes.GetVoice(i); + var emptyLines = voice.RemoveEmptyLines(); if (emptyLines > 0) - CLog.CSongLog.Warning("[{SongFileName}] Removed {NumEmptyLines} empty lines from P .This often indicates a problem with the line breaks in the file", CLog.Params(_Song.FileName, emptyLines)); + { + CLog.CSongLog.Warning("[{SongFileName}] Removed {NumEmptyLines} empty lines from P .This often indicates a problem with the line breaks in the file", + CLog.Params(_Song.FileName, emptyLines)); + } + voice.UpdateTimings(); } } @@ -765,9 +952,13 @@ namespace VocaluxeLib.Songs { CLog.CSongLog.Error(e, "[{SongFileName}] An unhandled exception occured: {ExceptionMessage}", CLog.Params(_Song.FileName, e.Message)); if (sr != null) + { sr.Dispose(); + } + return false; } + sr.Dispose(); try { @@ -776,7 +967,9 @@ namespace VocaluxeLib.Songs _Song._FindShortEnd(); _Song.NotesLoaded = true; if (_Song.IsDuet) + { _Song._CheckDuet(); + } } catch (Exception e) { @@ -786,27 +979,28 @@ namespace VocaluxeLib.Songs if (changesMade.IsModified) { - CLog.Warning("Automatic changes have been made to {FilePath} Please check result!\r\n{ChangesMade}" , CLog.Params(filePath, changesMade)); + CLog.Warning("Automatic changes have been made to {FilePath} Please check result!\r\n{ChangesMade}", CLog.Params(filePath, changesMade)); if (CBase.Config.GetSaveModifiedSongs() == EOffOn.TR_CONFIG_ON) { - string name = Path.GetFileNameWithoutExtension(_Song.FileName); + var name = Path.GetFileNameWithoutExtension(_Song.FileName); _Song.Save(Path.Combine(_Song.Folder, name + ".fix")); } } + return true; } private bool _AddNote(int player, CSongNote note) { - CVoice voice = _Song.Notes.GetVoice(player, true); + var voice = _Song.Notes.GetVoice(player, true); return voice.AddNote(note, false); } private bool _NewSentence(int player, int start) { - CVoice voice = _Song.Notes.GetVoice(player, true); + var voice = _Song.Notes.GetVoice(player, true); return voice.AddLine(start); } } } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Songs/CSongWriter.cs b/VocaluxeLib/Songs/CSongWriter.cs index f9a7591f..df40b29a 100644 --- a/VocaluxeLib/Songs/CSongWriter.cs +++ b/VocaluxeLib/Songs/CSongWriter.cs @@ -36,56 +36,79 @@ namespace VocaluxeLib.Songs private void _WriteHeaderEntry(string id, string value) { - if (!String.IsNullOrEmpty(value)) + if (!string.IsNullOrEmpty(value)) + { _Tw.WriteLine("#" + id.ToUpper() + ":" + value); + } } private void _WriteHeaderEntry(string id, bool value) { if (value) + { _WriteHeaderEntry(id, "YES"); + } } private void _WriteHeaderEntry(string id, float value, float def = 0f) { if (Math.Abs(value - def) > 0.0001) + { _WriteHeaderEntry(id, value.ToInvariantString()); + } } private void _WriteHeaderEntry(string id, int value, int def = 0) { if (value != def) + { _WriteHeaderEntry(id, value.ToString()); + } } private void _WriteHeaderEntrys(string id, ICollection value) { if (value == null || value.Count <= 0) + { return; - foreach (String val in value) + } + + foreach (var val in value) + { _WriteHeaderEntry(id, val); + } } private void _WriteHeader() { if (_Song.ManualEncoding) + { _WriteHeaderEntry("ENCODING", _Song.Encoding.GetEncodingName()); + } + _WriteHeaderEntry("CREATOR", _Song.Creator); _WriteHeaderEntry("VERSION", _Song.Version); _WriteHeaderEntry("LENGTH", _Song.Length); _WriteHeaderEntry("SOURCE", _Song.Source); - if (!String.IsNullOrEmpty(_Song._Comment)) + if (!string.IsNullOrEmpty(_Song._Comment)) { - string comment = _Song._Comment.Replace("\r\n", "\n").Replace('\r', '\n'); - char[] splitChar = {'\n'}; + var comment = _Song._Comment.Replace("\r\n", "\n").Replace('\r', '\n'); + char[] splitChar = { '\n' }; _WriteHeaderEntrys("COMMENT", comment.Split(splitChar)); } + _WriteHeaderEntry("TITLE", _Song.Title); _WriteHeaderEntry("ARTIST", _Song.Artist); if (!_Song.Title.Equals(_Song.TitleSorting)) + { _WriteHeaderEntry("TITLE-ON-SORTING", _Song.TitleSorting); + } + if (!_Song.Artist.Equals(_Song.ArtistSorting)) + { _WriteHeaderEntry("ARTIST-ON-SORTING", _Song.ArtistSorting); + } + _WriteHeaderEntrys("EDITION", _Song.Editions); _WriteHeaderEntrys("GENRE", _Song.Genres); _WriteHeaderEntry("TAGS", String.Join(",", _Song.Tags.ToArray())); @@ -98,30 +121,48 @@ namespace VocaluxeLib.Songs _WriteHeaderEntry("VIDEO", _Song.VideoFileName); _WriteHeaderEntry("VIDEOGAP", _Song.VideoGap); if (_Song.VideoAspect != EAspect.Crop) + { _WriteHeaderEntry("VIDEOASPECT", _Song.VideoAspect.ToString()); + } + _WriteHeaderEntry("RELATIVE", _Song.Relative); - _WriteHeaderEntry("BPM", _Song.BPM / _BPMFactor); + _WriteHeaderEntry("BPM", _Song.Bpm / _BpmFactor); _WriteHeaderEntry("GAP", (int)(_Song.Gap * 1000f)); if (_Song.Preview.Source == EDataSource.Tag) + { _WriteHeaderEntry("PREVIEWSTART", _Song.Preview.StartTime); + } + _WriteHeaderEntry("START", _Song.Start); - _WriteHeaderEntry("END", (int)(_Song.Finish * 1000f)); + _WriteHeaderEntry("END", (int)(_Song.End * 1000f)); if (_Song.ShortEnd.Source == EDataSource.Tag) - _WriteHeaderEntry("ENDSHORT", (int)(CBase.Game.GetTimeFromBeats(_Song.ShortEnd.EndBeat, _Song.BPM) + _Song.Gap) * 1000); + { + _WriteHeaderEntry("ENDSHORT", (int)(CBase.Game.GetTimeFromBeats(_Song.ShortEnd.EndBeat, _Song.Bpm) + _Song.Gap) * 1000); + } + if (!_Song._CalculateMedley) + { _WriteHeaderEntry("CALCMEDLEY", "OFF"); + } + if (_Song.Medley.Source == EDataSource.Tag) { _WriteHeaderEntry("MEDLEYSTARTBEAT", _Song.Medley.StartBeat); _WriteHeaderEntry("MEDLEYENDBEAT", _Song.Medley.EndBeat); } - for (int i = 0; i < _Song.Notes.VoiceCount; i++) + + for (var i = 0; i < _Song.Notes.VoiceCount; i++) { if (_Song.Notes.VoiceNames.IsSet(i)) + { _WriteHeaderEntry("P" + i, _Song.Notes.VoiceNames[i]); + } } - foreach (string addLine in _Song.UnknownTags) + + foreach (var addLine in _Song.UnknownTags) + { _Tw.WriteLine(addLine); + } } /// @@ -134,47 +175,67 @@ namespace VocaluxeLib.Songs private int _GetBreakBeat(int firstPossibleBeat, int firstNoteBeat) { int breakBeat; - int diff = firstNoteBeat - firstPossibleBeat; - float timeDiff = CBase.Game.GetTimeFromBeats(diff, _Song.BPM); + var diff = firstNoteBeat - firstPossibleBeat; + var timeDiff = CBase.Game.GetTimeFromBeats(diff, _Song.Bpm); if (timeDiff > 4f) - breakBeat = firstPossibleBeat + (int)CBase.Game.GetBeatFromTime(2f, _Song.BPM, 0f); + { + breakBeat = firstPossibleBeat + (int)CBase.Game.GetBeatFromTime(2f, _Song.Bpm, 0f); + } else if (timeDiff > 2f) - breakBeat = firstPossibleBeat + (int)CBase.Game.GetBeatFromTime(1f, _Song.BPM, 0f); + { + breakBeat = firstPossibleBeat + (int)CBase.Game.GetBeatFromTime(1f, _Song.Bpm, 0f); + } else if (diff < 2) + { breakBeat = firstPossibleBeat; + } else if (diff < 9) + { breakBeat = firstNoteBeat - 2; + } else if (diff < 13) + { breakBeat = firstNoteBeat - 3; + } else if (diff < 17) + { breakBeat = firstNoteBeat - 4; + } else + { breakBeat = firstPossibleBeat + 12; + } + return breakBeat; } private void _WriteNotes() { - for (int i = 0; i < _Song.Notes.VoiceCount; i++) + for (var i = 0; i < _Song.Notes.VoiceCount; i++) { - CVoice voice = _Song.Notes.GetVoice(i); + var voice = _Song.Notes.GetVoice(i); if (_Song.Notes.VoiceCount > 1) + { _Tw.WriteLine("P" + Math.Pow(2, i)); - int currentBeat = 0; + } + + var currentBeat = 0; CSongLine lastLine = null; - foreach (CSongLine line in voice.Lines) + foreach (var line in voice.Lines) { if (lastLine != null) { - string lineTxt = "- " + (_GetBreakBeat(lastLine.EndBeat + 1, line.FirstNoteBeat) - currentBeat); + var lineTxt = "- " + (_GetBreakBeat(lastLine.EndBeat + 1, line.FirstNoteBeat) - currentBeat); if (_Song.Relative) { lineTxt += " " + (line.FirstNoteBeat - currentBeat); currentBeat = line.FirstNoteBeat; } + _Tw.WriteLine(lineTxt); } - foreach (CSongNote note in line.Notes) + + foreach (var note in line.Notes) { string tag; switch (note.Type) @@ -197,11 +258,14 @@ namespace VocaluxeLib.Songs default: throw new NotImplementedException("Note type " + note.Type); } + _Tw.WriteLine(tag + " " + (note.StartBeat - currentBeat) + " " + note.Duration + " " + note.Tone + " " + note.Text); } + lastLine = line; } } + _Tw.WriteLine("E"); } @@ -226,8 +290,11 @@ namespace VocaluxeLib.Songs finally { if (_Tw != null) + { _Tw.Dispose(); + } } + return true; } } diff --git a/VocaluxeLib/Songs/CSungNote.cs b/VocaluxeLib/Songs/CSungNote.cs index d010722c..463c5966 100644 --- a/VocaluxeLib/Songs/CSungNote.cs +++ b/VocaluxeLib/Songs/CSungNote.cs @@ -66,16 +66,17 @@ namespace VocaluxeLib.Songs #region Methods public void CheckPerfect() { - bool result = HitNote != null; + var result = HitNote != null; if (result) { - result = (StartBeat == HitNote.StartBeat); - result &= (EndBeat == HitNote.EndBeat); - result &= (Tone == HitNote.Tone); + result = StartBeat == HitNote.StartBeat; + result &= EndBeat == HitNote.EndBeat; + result &= Tone == HitNote.Tone; } Perfect = result; } + public override bool IsNoteType(params ENoteType[] noteTypes) { return HitNote != null && noteTypes.Contains(HitNote.Type); @@ -84,7 +85,7 @@ namespace VocaluxeLib.Songs public override int PointsForBeat { - get { return (HitNote == null) ? 0 : HitNote.PointsForBeat; } + get { return HitNote == null ? 0 : HitNote.PointsForBeat; } } } } \ No newline at end of file diff --git a/VocaluxeLib/Songs/CVoice.cs b/VocaluxeLib/Songs/CVoice.cs index c9784a3a..1c353da8 100644 --- a/VocaluxeLib/Songs/CVoice.cs +++ b/VocaluxeLib/Songs/CVoice.cs @@ -25,12 +25,14 @@ namespace VocaluxeLib.Songs { private readonly List _Lines = new List(); - public CVoice() {} + public CVoice() { } public CVoice(CVoice voice) { - foreach (CSongLine line in voice._Lines) + foreach (var line in voice._Lines) + { _Lines.Add(new CSongLine(line)); + } } public CSongLine[] Lines @@ -50,9 +52,11 @@ namespace VocaluxeLib.Songs get { if (_Lines.Count == 0) + { return 0; + } - int result = _Lines[_Lines.Count - 1].EndBeat - _Lines[0].StartBeat; + var result = _Lines[_Lines.Count - 1].EndBeat - _Lines[0].StartBeat; return result > 0 ? result : 0; } } @@ -77,59 +81,91 @@ namespace VocaluxeLib.Songs { //If no line -> No previous line if (_Lines.Count == 0) + { return -1; - int start = 0; - int end = _Lines.Count - 1; + } + + var start = 0; + var end = _Lines.Count - 1; //Ensure that start.StartBeat<=Beat && end.StartBeat>Beat if (_Lines[0].StartBeat > beat) + { return -1; + } + if (_Lines[end].StartBeat <= beat) + { return end; + } + //Binary search while (end - start > 1) { - int mid = (start + end) / 2; + var mid = (start + end) / 2; if (_Lines[mid].StartBeat <= beat) + { start = mid; + } else + { end = mid; + } } + return start; } public bool AddLine(CSongLine line, bool updateTimings = true) { if (_Lines.Count == 0) + { _Lines.Add(line); + } else { - int insPos = FindPreviousLine(line.StartBeat); + var insPos = FindPreviousLine(line.StartBeat); //Check if previous line ends before this one if (insPos >= 0 && _Lines[insPos].LastNoteBeat > line.StartBeat) + { return false; + } + //Check if next line starts before this one ends if (insPos + 1 < _Lines.Count && _Lines[insPos + 1].FirstNoteBeat < line.LastNoteBeat) + { return false; + } + _Lines.Insert(insPos + 1, line); } + if (updateTimings) + { UpdateTimings(); + } + return true; } public bool AddLine(int startBeat) { - int insPos = FindPreviousLine(startBeat); + var insPos = FindPreviousLine(startBeat); //Check for actual notes (startbeat may be lower than first note) while (insPos >= 0 && _Lines[insPos].NoteCount > 0 && _Lines[insPos].FirstNoteBeat > startBeat) + { insPos--; - CSongLine line = new CSongLine {StartBeat = startBeat}; + } + + var line = new CSongLine { StartBeat = startBeat }; if (insPos >= 0) { - CSongLine prevLine = _Lines[insPos]; + var prevLine = _Lines[insPos]; //We already have a line break here if (prevLine.StartBeat == startBeat && (prevLine.NoteCount == 0 || prevLine.FirstNoteBeat == startBeat)) + { return false; + } + //Maybe we have to split the previous line while (prevLine.NoteCount > 0 && prevLine.LastNote.StartBeat >= startBeat) { @@ -138,6 +174,7 @@ namespace VocaluxeLib.Songs prevLine.DeleteNote(prevLine.NoteCount - 1); } } + _Lines.Insert(insPos + 1, line); return true; } @@ -150,6 +187,7 @@ namespace VocaluxeLib.Songs UpdateTimings(); return true; } + return false; } @@ -160,9 +198,12 @@ namespace VocaluxeLib.Songs public bool AddNote(CSongNote note, bool updateTimings = true) { - int lineIndex = FindPreviousLine(note.StartBeat); + var lineIndex = FindPreviousLine(note.StartBeat); if (lineIndex + 1 < _Lines.Count && _Lines[lineIndex + 1].FirstNoteBeat < note.EndBeat) //First note in next line starts before this one ends + { return false; + } + if (lineIndex < 0) { //Note is before ALL lines @@ -170,7 +211,9 @@ namespace VocaluxeLib.Songs { //Add to first line if (!_Lines[0].AddNote(note)) + { return false; + } } else { @@ -182,10 +225,16 @@ namespace VocaluxeLib.Songs else { if (!_Lines[lineIndex].AddNote(note)) + { return false; + } } + if (updateTimings) + { UpdateTimings(); + } + return true; } @@ -206,18 +255,21 @@ namespace VocaluxeLib.Songs public void UpdateTimings() { if (_Lines.Count == 0) + { return; + } + _Lines[0].StartBeat = -10000; - for (int i = 1; i < _Lines.Count; i++) + for (var i = 1; i < _Lines.Count; i++) { - CSongNote lastNote = _Lines[i - 1].LastNote; - CSongNote firstNote = _Lines[i].FirstNote; + var lastNote = _Lines[i - 1].LastNote; + var firstNote = _Lines[i].FirstNote; - if ((lastNote != null) && (firstNote != null)) + if (lastNote != null && firstNote != null) { - int min = lastNote.EndBeat; - int max = firstNote.StartBeat; + var min = lastNote.EndBeat; + var max = firstNote.StartBeat; int s; switch (max - min) @@ -264,8 +316,10 @@ namespace VocaluxeLib.Songs public void SetMedley(int startBeat, int endBeat) { - foreach (CSongLine line in _Lines) + foreach (var line in _Lines) + { line.SetMedley(startBeat, endBeat); + } } #endregion Methods diff --git a/VocaluxeLib/Structs.cs b/VocaluxeLib/Structs.cs index 166e4c65..815967a2 100644 --- a/VocaluxeLib/Structs.cs +++ b/VocaluxeLib/Structs.cs @@ -30,12 +30,17 @@ namespace VocaluxeLib { public struct SMargin { - [XmlAttribute] public int Default; + [XmlAttribute] + public int Default; public int? Left, Right, Top, Bottom; - [XmlIgnore] public bool LeftSpecified; - [XmlIgnore] public bool RightSpecified; - [XmlIgnore] public bool TopSpecified; - [XmlIgnore] public bool BottomSpecified; + [XmlIgnore] + public bool LeftSpecified; + [XmlIgnore] + public bool RightSpecified; + [XmlIgnore] + public bool TopSpecified; + [XmlIgnore] + public bool BottomSpecified; } public struct SThemeCoverGeneratorText @@ -49,33 +54,41 @@ namespace VocaluxeLib public struct SThemeCoverGenerator { - [XmlAttribute] public ECoverGeneratorType Type; + [XmlAttribute] + public ECoverGeneratorType Type; public SThemeCoverGeneratorText Text; public SThemeColor BackgroundColor; - [XmlElement(IsNullable = true)] public string Image; - [DefaultValue(0.5f)] public float ImageAlpha; - [DefaultValue(false)] public bool ShowFirstCover; + [XmlElement(IsNullable = true)] + public string Image; + [DefaultValue(0.5f)] + public float ImageAlpha; + [DefaultValue(false)] + public bool ShowFirstCover; } public struct SThemeCoverInfo { public string Name; public string Folder; - [XmlElement(IsNullable = true)] public string Author; + [XmlElement(IsNullable = true)] + public string Author; } [XmlRoot("root")] public struct SThemeCover { - [XmlIgnore] public string FolderPath; + [XmlIgnore] + public string FolderPath; public SThemeCoverInfo Info; - [XmlElement("CoverGenerator", IsNullable = false)] public List CoverGenerators; + [XmlElement("CoverGenerator", IsNullable = false)] + public List CoverGenerators; } #region Drawing public struct SColorF { - [XmlNormalized] public float R, G, B, A; + [XmlNormalized] + public float R, G, B, A; public SColorF(float r, float g, float b, float a) { @@ -87,8 +100,8 @@ namespace VocaluxeLib A = a; } - public SColorF(SColorF color, float a) : this(color.R, color.G, color.B, a) {} - public SColorF(Color color, float a) : this(color.R / 255f, color.G / 255f, color.B / 255f, a) {} + public SColorF(SColorF color, float a) : this(color.R, color.G, color.B, a) { } + public SColorF(Color color, float a) : this(color.R / 255f, color.G / 255f, color.B / 255f, a) { } public SColorF(Color color) { @@ -109,16 +122,21 @@ namespace VocaluxeLib [XmlRoot("Color")] public struct SThemeColor { - [DefaultValue(null), XmlAttribute] public string Name; - [XmlNormalized] public float? R; - [XmlNormalized] public float? G; - [XmlNormalized] public float? B; - [XmlNormalized] public float? A; + [DefaultValue(null), XmlAttribute] + public string Name; + [XmlNormalized] + public float? R; + [XmlNormalized] + public float? G; + [XmlNormalized] + public float? B; + [XmlNormalized] + public float? A; //Needed for serialization public bool NameSpecified { - get { return !String.IsNullOrEmpty(Name); } + get { return !string.IsNullOrEmpty(Name); } } public bool RSpecified { @@ -140,22 +158,37 @@ namespace VocaluxeLib public bool Get(int partyModeId, out SColorF color) { bool ok; - if (!String.IsNullOrEmpty(Name)) + if (!string.IsNullOrEmpty(Name)) + { ok = CBase.Themes.GetColor(Name, partyModeId, out color); + } else { Debug.Assert(R.HasValue || G.HasValue || B.HasValue); ok = true; color = new SColorF(1, 1, 1, 1); } + if (R.HasValue) + { color.R = R.Value; + } + if (G.HasValue) + { color.G = G.Value; + } + if (B.HasValue) + { color.B = B.Value; + } + if (A.HasValue) + { color.A = A.Value; + } + return ok; } } @@ -167,7 +200,8 @@ namespace VocaluxeLib public float W; public float H; public float Z; - [XmlIgnore] public float Rotation; //0..360° + [XmlIgnore] + public float Rotation; //0..360° [XmlIgnore] public float Right @@ -279,11 +313,19 @@ namespace VocaluxeLib Mod = EModifier.None; if (alt) + { Mod |= EModifier.Alt; + } + if (shift) + { Mod |= EModifier.Shift; + } + if (ctrl) + { Mod |= EModifier.Ctrl; + } } /// @@ -341,7 +383,7 @@ namespace VocaluxeLib #region Game public struct SPlayer { - public Guid ProfileID; + public Guid ProfileId; public double Points; public double PointsLineBonus; public double PointsGoldenNotes; @@ -355,7 +397,7 @@ namespace VocaluxeLib public float TimeLastLineChange; - public int SongID; + public int SongId; public EGameMode GameMode; public long DateTicks; public bool SongFinished; @@ -368,7 +410,7 @@ namespace VocaluxeLib public string Date; public EGameDifficulty Difficulty; public int VoiceNr; - public int ID; + public int Id; } #endregion Game } \ No newline at end of file diff --git a/VocaluxeLib/Utils/CWavFile.cs b/VocaluxeLib/Utils/CWavFile.cs index 35a83d2e..943460ac 100644 --- a/VocaluxeLib/Utils/CWavFile.cs +++ b/VocaluxeLib/Utils/CWavFile.cs @@ -34,7 +34,7 @@ namespace VocaluxeLib.Utils //Number of samples (per channel) public int NumSamples { - get { return (DataSize / (BitsPerSample / 8 * NumChannels)); } + get { return DataSize / (BitsPerSample / 8 * NumChannels); } } //Number of samples left to be read (per channel) public int NumSamplesLeft { get; private set; } @@ -57,7 +57,10 @@ namespace VocaluxeLib.Utils public void Create(string fileName, short numChannels, int sampleRate, short bitsPerSample) { if (IsOpen) + { Close(); + } + _File = new FileStream(fileName, FileMode.Create); FileName = fileName; NumChannels = numChannels; @@ -73,15 +76,19 @@ namespace VocaluxeLib.Utils public void Close() { if (!IsOpen) + { return; + } + if (_IsWritable) { - BinaryWriter writer = new BinaryWriter(_File); + var writer = new BinaryWriter(_File); writer.Seek(4, SeekOrigin.Begin); writer.Write((int)_File.Length - 8); writer.Seek(_DataPos - 4, SeekOrigin.Begin); writer.Write(DataSize); } + _File.Dispose(); _File = null; IsOpen = false; @@ -90,40 +97,70 @@ namespace VocaluxeLib.Utils public bool Open(string fileName) { if (IsOpen) + { Close(); + } + if (!File.Exists(fileName)) + { return false; + } + FileName = fileName; _File = new FileStream(FileName, FileMode.Open); try { - BinaryReader reader = new BinaryReader(_File); + var reader = new BinaryReader(_File); if (Encoding.ASCII.GetString(reader.ReadBytes(4)) != "RIFF") + { return false; + } + reader.ReadInt32(); //Chunksize (file) if (Encoding.ASCII.GetString(reader.ReadBytes(4)) != "WAVE") + { return false; - long curPos = _File.Position; + } + + var curPos = _File.Position; if (_SeekTo(reader, "fmt ") < 0) + { return false; - short audioFormat = reader.ReadInt16(); + } + + var audioFormat = reader.ReadInt16(); if (audioFormat != 1) //PCM + { return false; + } + NumChannels = reader.ReadInt16(); SampleRate = reader.ReadInt32(); - int bytesPerSec = reader.ReadInt32(); - short blockAlign = reader.ReadInt16(); + var bytesPerSec = reader.ReadInt32(); + var blockAlign = reader.ReadInt16(); BitsPerSample = reader.ReadInt16(); if (BitsPerSample != 8 && BitsPerSample != 16) + { return false; + } + if (blockAlign != NumChannels * (BitsPerSample / 8)) + { return false; + } + if (bytesPerSec != blockAlign * SampleRate) + { return false; + } + _File.Position = curPos; DataSize = _SeekTo(reader, "data"); if (DataSize <= 0) + { return false; + } + _DataPos = (int)_File.Position; DataSize = Math.Min(DataSize, (int)_File.Length - _DataPos); NumSamplesLeft = NumSamples; @@ -133,6 +170,7 @@ namespace VocaluxeLib.Utils _File.Dispose(); throw; } + IsOpen = true; return true; } @@ -146,23 +184,32 @@ namespace VocaluxeLib.Utils public byte[] GetNextSamples8Bit(int numSamples, int channel = 0) { if (channel < 0 || channel > NumChannels || BitsPerSample != 8) + { return null; + } + if (numSamples > NumSamplesLeft) + { return null; + } + byte[] result; - BinaryReader reader = new BinaryReader(_File); + var reader = new BinaryReader(_File); if (channel == 0 || NumChannels == 1) + { result = reader.ReadBytes(numSamples * NumChannels); + } else { result = new byte[numSamples]; - for (int i = 0; i < numSamples; i++) + for (var i = 0; i < numSamples; i++) { _File.Seek(channel - 1, SeekOrigin.Current); result[i] = reader.ReadByte(); _File.Seek(NumChannels - channel, SeekOrigin.Current); } } + NumSamplesLeft -= numSamples; return result; } @@ -176,29 +223,38 @@ namespace VocaluxeLib.Utils public short[] GetNextSamples16Bit(int numSamples, int channel = 0) { if (channel < 0 || channel > NumChannels || BitsPerSample != 16) + { return null; + } + if (numSamples > NumSamplesLeft) + { return null; + } + short[] result; - BinaryReader reader = new BinaryReader(_File); + var reader = new BinaryReader(_File); try { if (channel == 0 || NumChannels == 1) { result = new short[numSamples * NumChannels]; - for (int i = 0; i < numSamples * NumChannels; i++) + for (var i = 0; i < numSamples * NumChannels; i++) + { result[i] = reader.ReadInt16(); + } } else { result = new short[numSamples]; - for (int i = 0; i < numSamples; i++) + for (var i = 0; i < numSamples; i++) { _File.Seek((channel - 1) * 2, SeekOrigin.Current); result[i] = reader.ReadInt16(); _File.Seek((NumChannels - channel) * 2, SeekOrigin.Current); } } + NumSamplesLeft -= numSamples; } catch (EndOfStreamException e) @@ -206,15 +262,19 @@ namespace VocaluxeLib.Utils Console.WriteLine("Error: " + e); return null; } + return result; } public byte[] GetNextSamples16BitAsBytes(int numSamples, int channel = 0) { - short[] samples = GetNextSamples16Bit(numSamples, channel); + var samples = GetNextSamples16Bit(numSamples, channel); if (samples == null) + { return null; - byte[] samplesByte = new byte[samples.Length * 2]; + } + + var samplesByte = new byte[samples.Length * 2]; Buffer.BlockCopy(samples, 0, samplesByte, 0, samplesByte.Length); return samplesByte; } @@ -222,19 +282,25 @@ namespace VocaluxeLib.Utils public bool WriteSamples(byte[] samples, int channel = 0) { if (!_IsWritable || channel < 0 || channel > NumChannels || BitsPerSample != 8) + { return false; - BinaryWriter writer = new BinaryWriter(_File); + } + + var writer = new BinaryWriter(_File); if (channel == 0 || NumChannels == 1) + { writer.Write(samples); + } else { - foreach (byte sample in samples) + foreach (var sample in samples) { _File.Seek(channel - 1, SeekOrigin.Current); writer.Write(sample); _File.Seek(NumChannels - channel, SeekOrigin.Current); } } + DataSize += samples.Length; return true; } @@ -242,22 +308,28 @@ namespace VocaluxeLib.Utils public bool Write16BitSamples(short[] samples, int channel = 0) { if (!_IsWritable || channel < 0 || channel > NumChannels || BitsPerSample != 16) + { return false; - BinaryWriter writer = new BinaryWriter(_File); + } + + var writer = new BinaryWriter(_File); if (channel == 0 || NumChannels == 1) { - foreach (short sample in samples) + foreach (var sample in samples) + { writer.Write(sample); + } } else { - foreach (short sample in samples) + foreach (var sample in samples) { _File.Seek((channel - 1) * 2, SeekOrigin.Current); writer.Write(sample); _File.Seek((NumChannels - channel) * 2, SeekOrigin.Current); } } + DataSize += samples.Length * 2; return true; } @@ -265,8 +337,11 @@ namespace VocaluxeLib.Utils public bool Write16BitSamples(byte[] samples, int channel = 0) { if (samples.Length == 0) + { return true; - short[] samplesShort = new short[samples.Length / 2]; + } + + var samplesShort = new short[samples.Length / 2]; Buffer.BlockCopy(samples, 0, samplesShort, 0, samples.Length); return Write16BitSamples(samplesShort, channel); } @@ -274,8 +349,11 @@ namespace VocaluxeLib.Utils private void _WriteHeader() { if (!IsOpen || !_IsWritable) + { return; - BinaryWriter writer = new BinaryWriter(_File); + } + + var writer = new BinaryWriter(_File); writer.Write(Encoding.ASCII.GetBytes("RIFF")); writer.Write(0); writer.Write(Encoding.ASCII.GetBytes("WAVE")); @@ -285,7 +363,7 @@ namespace VocaluxeLib.Utils writer.Write(NumChannels); // Channels writer.Write(SampleRate); // Sample rate writer.Write(SampleRate * NumChannels * (BitsPerSample / 8)); // Average bytes per second - writer.Write((short)((BitsPerSample / 8) * NumChannels)); // block align + writer.Write((short)(BitsPerSample / 8 * NumChannels)); // block align writer.Write(BitsPerSample); // bits per sample writer.Write(Encoding.ASCII.GetBytes("data")); writer.Write(DataSize); @@ -299,12 +377,16 @@ namespace VocaluxeLib.Utils { do { - string curChunkId = Encoding.ASCII.GetString(reader.ReadBytes(4)); - int chunkSize = reader.ReadInt32(); + var curChunkId = Encoding.ASCII.GetString(reader.ReadBytes(4)); + var chunkSize = reader.ReadInt32(); if (curChunkId == chunkId) + { return chunkSize; + } + reader.BaseStream.Seek(chunkSize, SeekOrigin.Current); } while (reader.BaseStream.Position < reader.BaseStream.Length); + return -1; } } diff --git a/VocaluxeLib/Utils/Combinatorics/CCombinations.cs b/VocaluxeLib/Utils/Combinatorics/CCombinations.cs index 78e5c0b7..fca88d51 100644 --- a/VocaluxeLib/Utils/Combinatorics/CCombinations.cs +++ b/VocaluxeLib/Utils/Combinatorics/CCombinations.cs @@ -40,14 +40,25 @@ namespace VocaluxeLib.Utils.Combinatorics public static int Count(int n, int k) { if (n < 0 || k < 0) + { throw new ArgumentException("Parameters must not be negative"); + } + if (n < k) + { return 0; + } + // Try to optimize because (n k) = (n n-k) if (n - k < k) + { k = n - k; + } + if (k == 0) // or k == n but both are the same after the optimization above + { return 1; + } long result = n; for (long i = 1; i < k; i++) @@ -57,6 +68,7 @@ namespace VocaluxeLib.Utils.Combinatorics result = result * (n - i) / (i + 1); } } + return (int)result; } @@ -75,7 +87,7 @@ namespace VocaluxeLib.Utils.Combinatorics /// public List> GetAll() { - List> result = new List>(Count()); + var result = new List>(Count()); result.AddRange(this); return result; } @@ -105,32 +117,46 @@ namespace VocaluxeLib.Utils.Combinatorics Debug.Assert(_N >= 0 && _K >= 0); } - public void Dispose() {} + public void Dispose() { } public bool MoveNext() { if (_N < _K) + { return false; + } if (_CurSet == null) { _CurSet = new int[_K]; - for (int i = 0; i < _K; i++) + for (var i = 0; i < _K; i++) + { _CurSet[i] = i; + } + return true; } // Check if we reached the end if (_K == 0 || _CurSet[0] == _N - _K) + { return false; + } + // Search for element to increment - int idx = _K - 1; + var idx = _K - 1; while (idx > 0 && _CurSet[idx] == _N - _K + idx) + { idx--; + } + _CurSet[idx]++; // Increment all elements "right" of this to 1+their left neighbour - for (int j = idx; j < _K - 1; j++) + for (var j = idx; j < _K - 1; j++) + { _CurSet[j + 1] = _CurSet[j] + 1; + } + return true; } @@ -143,7 +169,7 @@ namespace VocaluxeLib.Utils.Combinatorics { get { - List result = new List(_K); + var result = new List(_K); result.AddRange(_CurSet.Select(i => _Parent._Values[i])); return result; } diff --git a/VocaluxeLib/Utils/ObjectPool.cs b/VocaluxeLib/Utils/ObjectPool.cs index 7f1b75fb..065be160 100644 --- a/VocaluxeLib/Utils/ObjectPool.cs +++ b/VocaluxeLib/Utils/ObjectPool.cs @@ -1,9 +1,5 @@ using System; using System.Collections.Concurrent; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace VocaluxeLib.Utils { @@ -27,9 +23,15 @@ namespace VocaluxeLib.Utils public CObjectPool(Func objectGenerator, int poolSize) { if (objectGenerator == null) + { throw new ArgumentNullException(nameof(objectGenerator)); + } + if (poolSize <= 0) + { throw new ArgumentNullException(nameof(poolSize)); + } + _Objects = new ConcurrentBag(); _ObjectGenerator = objectGenerator; _Poolsize = poolSize; @@ -42,7 +44,11 @@ namespace VocaluxeLib.Utils public T GetObject() { T item; - if (_Objects.TryTake(out item)) return item; + if (_Objects.TryTake(out item)) + { + return item; + } + return _ObjectGenerator(); } @@ -52,10 +58,14 @@ namespace VocaluxeLib.Utils /// The object instance that is given back to the pool. public void PutObject(T item) { - if(_Objects.Count < _Poolsize) + if (_Objects.Count < _Poolsize) + { _Objects.Add(item); + } else + { (item as IDisposable)?.Dispose(); + } } } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Utils/Player/CSongPlayer.cs b/VocaluxeLib/Utils/Player/CSongPlayer.cs index 7f166ea1..f5aee6bf 100644 --- a/VocaluxeLib/Utils/Player/CSongPlayer.cs +++ b/VocaluxeLib/Utils/Player/CSongPlayer.cs @@ -35,25 +35,32 @@ namespace VocaluxeLib.Utils.Player set { if (_VideoEnabled == value) + { return; + } + _VideoEnabled = value; if (_VideoEnabled) + { _LoadVideo(); + } else + { _CloseVideo(); + } } } - public int SongID + public int SongId { - get { return _Song == null ? -1 : _Song.ID; } + get { return _Song == null ? -1 : _Song.Id; } } public bool SongHasVideo { get { - return _Song != null && !String.IsNullOrEmpty(_Song.Folder) && !String.IsNullOrEmpty(_Song.VideoFileName) && + return _Song != null && !string.IsNullOrEmpty(_Song.Folder) && !string.IsNullOrEmpty(_Song.VideoFileName) && File.Exists(Path.Combine(_Song.Folder, _Song.VideoFileName)); } } @@ -62,8 +69,11 @@ namespace VocaluxeLib.Utils.Player { get { - if (_Song != null && !String.IsNullOrEmpty(_Song.Artist) && !String.IsNullOrEmpty(_Song.Title)) + if (_Song != null && !string.IsNullOrEmpty(_Song.Artist) && !string.IsNullOrEmpty(_Song.Title)) + { return _Song.Artist + " - " + _Song.Title; + } + return base.ArtistAndTitle; } } @@ -73,30 +83,39 @@ namespace VocaluxeLib.Utils.Player get { return _Song == null ? CBase.Cover.GetNoCover() : _Song.CoverTextureBig; } } - public CSongPlayer(bool loop = false) : base(loop) {} + public CSongPlayer(bool loop = false) : base(loop) { } public CTextureRef GetVideoTexture() { if (_Video == null || _Song == null) + { return null; - if (CBase.Video.GetFrame(_Video, CBase.Sound.GetPosition(_StreamID))) + } + + if (CBase.Video.GetFrame(_Video, CBase.Sound.GetPosition(_StreamId))) { if (_VideoFading != null) { bool finished; _Video.Texture.Color.A = _VideoFading.GetValue(out finished); if (finished) + { _VideoFading = null; + } } + return _Video.Texture; } + return null; } public void Load(CSong song, float position = 0f, bool autoplay = false) { if (song == null) + { throw new ArgumentNullException("song"); + } Load(song.GetMP3(), position, autoplay); _Song = song; @@ -106,15 +125,21 @@ namespace VocaluxeLib.Utils.Player private void _LoadVideo() { if (_Song == null) + { return; + } if (_Video != null || !SongHasVideo) + { return; + } - string videoFilePath = Path.Combine(_Song.Folder, _Song.VideoFileName); + var videoFilePath = Path.Combine(_Song.Folder, _Song.VideoFileName); _Video = CBase.Video.Load(videoFilePath); if (_Video == null) + { return; + } _VideoFading = new CFading(0f, 1f, 3f); @@ -124,48 +149,64 @@ namespace VocaluxeLib.Utils.Player CBase.Video.Resume(_Video); } else + { CBase.Video.Skip(_Video, 0f, _Song.VideoGap); + } } public override bool Play() { if (!base.Play()) + { return false; + } if (_Video != null) { CBase.Video.Skip(_Video, Position, _Song.VideoGap); CBase.Video.Resume(_Video); } + return true; } public override bool Pause() { if (!base.Pause()) + { return false; + } if (_Video != null) + { CBase.Video.Pause(_Video); + } + return true; } public override bool Stop() { if (!base.Stop()) + { return false; + } + if (_Video != null) { CBase.Video.Pause(_Video); CBase.Video.Skip(_Video, 0f, _Song.VideoGap); } + return true; } private void _CloseVideo() { if (_Video != null) + { CBase.Video.Close(ref _Video); + } } public override void Close() @@ -176,4 +217,4 @@ namespace VocaluxeLib.Utils.Player _CloseVideo(); } } -} +} \ No newline at end of file diff --git a/VocaluxeLib/Utils/Player/CSoundPlayer.cs b/VocaluxeLib/Utils/Player/CSoundPlayer.cs index cf3f524e..9f2832d6 100644 --- a/VocaluxeLib/Utils/Player/CSoundPlayer.cs +++ b/VocaluxeLib/Utils/Player/CSoundPlayer.cs @@ -21,7 +21,7 @@ namespace VocaluxeLib.Utils.Player { public class CSoundPlayer { - protected int _StreamID = -1; + protected int _StreamId = -1; protected readonly float _FadeTime = CBase.Settings.GetSoundPlayerFadeTime(); public string FilePath { get; private set; } @@ -35,27 +35,30 @@ namespace VocaluxeLib.Utils.Player set { if (!SoundLoaded) + { return; - CBase.Sound.SetPosition(_StreamID, value); + } + + CBase.Sound.SetPosition(_StreamId, value); } - get { return !SoundLoaded ? -1 : CBase.Sound.GetPosition(_StreamID); } + get { return !SoundLoaded ? -1 : CBase.Sound.GetPosition(_StreamId); } } public float Length { - get { return !SoundLoaded ? -1 : CBase.Sound.GetLength(_StreamID); } + get { return !SoundLoaded ? -1 : CBase.Sound.GetLength(_StreamId); } } public bool IsPlaying { get; private set; } public bool IsFinished { - get { return !Loop && (CBase.Sound.IsFinished(_StreamID) || !IsPlaying); } + get { return !Loop && (CBase.Sound.IsFinished(_StreamId) || !IsPlaying); } } public bool SoundLoaded { - get { return _StreamID != -1; } + get { return _StreamId != -1; } } public virtual string ArtistAndTitle @@ -72,14 +75,22 @@ namespace VocaluxeLib.Utils.Player { Close(); - _StreamID = CBase.Sound.Load(file, false, true); - if (_StreamID < 0) + _StreamId = CBase.Sound.Load(file, false, true); + if (_StreamId < 0) + { return; + } + FilePath = file; if (position > 0f) + { Position = position; + } + if (autoplay) + { Play(); + } } /// @@ -89,11 +100,13 @@ namespace VocaluxeLib.Utils.Player public virtual bool Play() { if (!SoundLoaded || IsPlaying) + { return false; + } - CBase.Sound.SetStreamVolume(_StreamID, 0); - CBase.Sound.Fade(_StreamID, 100, _FadeTime); - CBase.Sound.Play(_StreamID); + CBase.Sound.SetStreamVolume(_StreamId, 0); + CBase.Sound.Fade(_StreamId, 100, _FadeTime); + CBase.Sound.Play(_StreamId); IsPlaying = true; return true; } @@ -104,10 +117,12 @@ namespace VocaluxeLib.Utils.Player /// True if state changed, false if nothing loaded or already paused public virtual bool Pause() { - if (!SoundLoaded || CBase.Sound.IsPaused(_StreamID)) + if (!SoundLoaded || CBase.Sound.IsPaused(_StreamId)) + { return false; + } - CBase.Sound.Fade(_StreamID, 0, _FadeTime, EStreamAction.Pause); + CBase.Sound.Fade(_StreamId, 0, _FadeTime, EStreamAction.Pause); IsPlaying = false; return true; } @@ -119,9 +134,11 @@ namespace VocaluxeLib.Utils.Player public virtual bool Stop() { if (!SoundLoaded) + { return false; + } - CBase.Sound.Fade(_StreamID, 0, _FadeTime, EStreamAction.Stop); + CBase.Sound.Fade(_StreamId, 0, _FadeTime, EStreamAction.Stop); IsPlaying = false; return true; } @@ -129,10 +146,12 @@ namespace VocaluxeLib.Utils.Player public virtual void Close() { if (!SoundLoaded) + { return; + } - CBase.Sound.Fade(_StreamID, 0, _FadeTime, EStreamAction.Close); - _StreamID = -1; + CBase.Sound.Fade(_StreamId, 0, _FadeTime, EStreamAction.Close); + _StreamId = -1; FilePath = ""; IsPlaying = false; } @@ -140,9 +159,11 @@ namespace VocaluxeLib.Utils.Player public void Update() { if (!IsPlaying) + { return; + } - bool finished = CBase.Sound.IsFinished(_StreamID); + var finished = CBase.Sound.IsFinished(_StreamId); if (Loop) { if (finished) @@ -151,14 +172,17 @@ namespace VocaluxeLib.Utils.Player Stop(); Play(); } + return; } - float len = CBase.Sound.GetLength(_StreamID); - float timeToPlay = (len > 0f) ? len - CBase.Sound.GetPosition(_StreamID) : _FadeTime + 1f; + var len = CBase.Sound.GetLength(_StreamId); + var timeToPlay = len > 0f ? len - CBase.Sound.GetPosition(_StreamId) : _FadeTime + 1f; if (timeToPlay <= _FadeTime || finished) + { Stop(); + } } } } \ No newline at end of file diff --git a/VocaluxeLib/VocaluxeLib.csproj b/VocaluxeLib/VocaluxeLib.csproj index 8d939302..eb9f4923 100644 --- a/VocaluxeLib/VocaluxeLib.csproj +++ b/VocaluxeLib/VocaluxeLib.csproj @@ -29,6 +29,7 @@ Off ..\CheckingRules.ruleset false + 9.0 AnyCPU @@ -42,6 +43,7 @@ Off false true + 9.0 AnyCPU @@ -54,6 +56,7 @@ 4 Off false + 9.0 AnyCPU @@ -67,6 +70,7 @@ Off false true + 9.0 ..\Output\libs\managed @@ -80,6 +84,7 @@ false pdbonly true + 9.0 @@ -89,7 +94,7 @@ - + @@ -203,4 +208,4 @@ --> - + \ No newline at end of file diff --git a/VocaluxeLib/Xml/CTypeExtensions.cs b/VocaluxeLib/Xml/CTypeExtensions.cs index 9ae85ad9..508e2caa 100644 --- a/VocaluxeLib/Xml/CTypeExtensions.cs +++ b/VocaluxeLib/Xml/CTypeExtensions.cs @@ -46,7 +46,7 @@ namespace VocaluxeLib.Xml [AttributeUsage(AttributeTargets.Field)] public class XmlNormalizedAttribute : XmlRangedAttribute { - public XmlNormalizedAttribute() : base(0, 1) {} + public XmlNormalizedAttribute() : base(0, 1) { } } /// @@ -67,11 +67,20 @@ namespace VocaluxeLib.Xml public bool IsValid(Type type, object value) { if (type == typeof(int)) + { return ((int)value).IsInRange(Min, Max); + } + if (type == typeof(float)) + { return ((float)value).IsInRange(Min, Max); + } + if (type == typeof(double)) + { return ((double)value).IsInRange(Min, Max); + } + Debug.Assert(false, "Ranged attribute has invalid type"); return false; } @@ -99,11 +108,18 @@ namespace VocaluxeLib.Xml { Type subType; if (type.IsGenericType) + { subType = type.GetGenericArguments().Last(); + } else if (type.IsArray) + { subType = type.GetElementType(); + } else + { return null; + } + return subType.GetTypeName(); } @@ -114,7 +130,7 @@ namespace VocaluxeLib.Xml /// Field descrived by the struct private static void _FillInfo(ref SFieldInfo info, MemberInfo field) { - XmlAttributeAttribute attribute = field.GetAttribute(); + var attribute = field.GetAttribute(); if (attribute != null) { info.IsAttribute = true; @@ -122,12 +138,14 @@ namespace VocaluxeLib.Xml } else { - XmlElementAttribute element = field.GetAttribute(); + var element = field.GetAttribute(); if (element != null) + { info.Name = element.ElementName; + } else { - XmlArrayAttribute array = field.GetAttribute(); + var array = field.GetAttribute(); if (array != null) { Debug.Assert(info.Type.IsList() || info.Type.IsArray, "Only lists and arrays can have the array attribute"); @@ -137,35 +155,54 @@ namespace VocaluxeLib.Xml } } } + if (string.IsNullOrEmpty(info.Name)) + { info.Name = field.Name; - XmlAltNameAttribute altName = field.GetAttribute(); + } + + var altName = field.GetAttribute(); if (altName != null) + { info.AltName = altName.AltName; + } if (info.Type.IsGenericType) + { info.SubType = info.Type.GetGenericArguments().Last(); + } else if (info.Type.IsArray) + { info.SubType = info.Type.GetElementType(); + } + if (info.Type.IsList() || info.Type.IsArray) { if (!info.IsList) { Debug.Assert(!field.HasAttribute(), "A field cannot have an XmlElement- and XmlArray-Attribute"); if (info.Type.IsArray && info.SubType == typeof(byte)) + { info.IsByteArray = true; + } else + { info.IsEmbeddedList = true; + } } else { - XmlArrayItemAttribute arrayItem = field.GetAttribute(); + var arrayItem = field.GetAttribute(); if (arrayItem != null && !string.IsNullOrEmpty(arrayItem.ElementName)) + { info.ArrayItemName = arrayItem.ElementName; + } } } else if (info.Type.IsNullable()) + { info.IsNullable = true; + } else if (info.Type.IsDictionary()) { Debug.Assert(info.Type.GetGenericArguments()[0] == typeof(string), "Keys of dictionaries must be strings"); @@ -173,13 +210,16 @@ namespace VocaluxeLib.Xml } if (field.HasAttribute()) + { Debug.Assert(info.Type == typeof(float) || (info.IsNullable && info.SubType == typeof(float)), "Only floats can be normalized"); - info.Ranged = field.GetAttribute(); - Type tmpType = info.IsNullable ? info.SubType : info.Type; - Debug.Assert(info.Ranged == null || tmpType == typeof(int) || tmpType == typeof(float) || tmpType == typeof(double), - "Only ints,floats and double can be ranged"); + } - DefaultValueAttribute defAttr = field.GetAttribute(); + info.Ranged = field.GetAttribute(); + var tmpType = info.IsNullable ? info.SubType : info.Type; + Debug.Assert(info.Ranged == null || tmpType == typeof(int) || tmpType == typeof(float) || tmpType == typeof(double), + "Only ints,floats and double can be ranged"); + + var defAttr = field.GetAttribute(); if (defAttr != null) { Debug.Assert(!info.Type.IsList(), "Lists cannot have a default value"); @@ -202,26 +242,37 @@ namespace VocaluxeLib.Xml { List result; if (_CacheFields.TryGetValue(type, out result)) + { return result; + } + result = new List(); - FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); - foreach (FieldInfo field in fields) + var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); + foreach (var field in fields) { if (field.HasAttribute() || field.Name.EndsWith("Specified")) + { continue; - SFieldInfo info = new SFieldInfo(field); + } + + var info = new SFieldInfo(field); _FillInfo(ref info, field); result.Add(info); } - PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); - foreach (PropertyInfo property in properties) + + var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); + foreach (var property in properties) { if (property.HasAttribute() || property.Name.EndsWith("Specified") || !property.CanRead || !property.CanWrite) + { continue; - SFieldInfo info = new SFieldInfo(property); + } + + var info = new SFieldInfo(property); _FillInfo(ref info, property); result.Add(info); } + _CacheFields.Add(type, result); return result; } @@ -246,16 +297,24 @@ namespace VocaluxeLib.Xml { string name; if (_CacheTypeName.TryGetValue(type, out name)) + { return name; - XmlTypeAttribute att = type.GetAttribute(); + } + + var att = type.GetAttribute(); if (att != null) { name = att.TypeName; if (string.IsNullOrEmpty(name)) + { name = type.Name; + } } else + { name = type.Name; + } + _CacheTypeName.Add(type, name); return name; } @@ -279,7 +338,7 @@ namespace VocaluxeLib.Xml /// public static T GetAttribute(this ICustomAttributeProvider field) where T : class { - object[] attributes = field.GetCustomAttributes(typeof(T), false); + var attributes = field.GetCustomAttributes(typeof(T), false); return attributes.Length == 0 ? null : (T)attributes[0]; } diff --git a/VocaluxeLib/Xml/CXmlDeserializer.cs b/VocaluxeLib/Xml/CXmlDeserializer.cs index c835dff4..3bb129bb 100644 --- a/VocaluxeLib/Xml/CXmlDeserializer.cs +++ b/VocaluxeLib/Xml/CXmlDeserializer.cs @@ -39,7 +39,7 @@ namespace VocaluxeLib.Xml /// private string _GetXPath(XmlNode node) { - StringBuilder builder = new StringBuilder(); + var builder = new StringBuilder(); while (node != null) { switch (node.NodeType) @@ -49,7 +49,7 @@ namespace VocaluxeLib.Xml node = ((XmlAttribute)node).OwnerElement; break; case XmlNodeType.Element: - string index = _FindElementIndex(node); + var index = _FindElementIndex(node); builder.Insert(0, "/" + node.Name + index); node = node.ParentNode; break; @@ -59,6 +59,7 @@ namespace VocaluxeLib.Xml throw new ArgumentException("Only elements and attributes are supported"); } } + throw new ArgumentException("Node was not in a document"); } @@ -69,21 +70,28 @@ namespace VocaluxeLib.Xml /// private string _FindElementIndex(XmlNode element) { - XmlNode parentNode = element.ParentNode; + var parentNode = element.ParentNode; if (parentNode is XmlDocument) + { return ""; - XmlElement parent = (XmlElement)parentNode; - int index = 1; + } + + var parent = (XmlElement)parentNode; + var index = 1; if (parent != null) { - XmlNode[] siblings = parent.ChildNodes.Cast().Where(candidate => candidate is XmlElement && candidate.Name == element.Name).ToArray(); - foreach (XmlNode candidate in siblings) + var siblings = parent.ChildNodes.Cast().Where(candidate => candidate is XmlElement && candidate.Name == element.Name).ToArray(); + foreach (var candidate in siblings) { if (candidate == element) + { return siblings.Length > 1 ? "[" + index + "]" : ""; + } + index++; } } + throw new ArgumentException("Couldn't find element within parent"); } #endregion Debug Helpers @@ -105,8 +113,8 @@ namespace VocaluxeLib.Xml public override String ToString() { - string xPath = Node == null ? "" : _GetXPath(Node); - string type = IsError ? "Error" : "Warning"; + var xPath = Node == null ? "" : _GetXPath(Node); + var type = IsError ? "Error" : "Warning"; return type + ": " + base.Message.Replace("%n", xPath); } } @@ -174,7 +182,10 @@ namespace VocaluxeLib.Xml public virtual void HandleError(CXmlException e) { if (e.IsError) + { throw e; + } + CLog.Error(e.ToString()); } } @@ -192,7 +203,6 @@ namespace VocaluxeLib.Xml _UnescapeStringValues = unescapeStringValues; } - /// /// Creates a new XmlDeserializer /// @@ -217,8 +227,11 @@ namespace VocaluxeLib.Xml if (type.IsEnum) { if (node == null) + { return null; - string stringValue = node.InnerText; + } + + var stringValue = node.InnerText; try { return Enum.Parse(type, stringValue); @@ -229,84 +242,134 @@ namespace VocaluxeLib.Xml return value; } } + if (type == typeof(Guid)) + { return Guid.Parse(node.InnerText); - if (type == typeof(string)) { - if(node == null) { + } + + if (type == typeof(string)) + { + if (node == null) + { return null; - } else if(_UnescapeStringValues) { + } + else if (_UnescapeStringValues) + { return Regex.Unescape(node.InnerText); - } else { + } + else + { return node.InnerText; } } + if (type.IsPrimitive) + { return _GetPrimitiveValue(node, type) ?? value; + } + if (type.IsNullable()) { if (node == null || !node.HasChildNodes) + { return null; - Type subType = type.GetGenericArguments()[0]; + } + + var subType = type.GetGenericArguments()[0]; return _GetValue(node, subType, subName, value); } + if (type.IsList() || type.IsArray) { - Type subType = type.IsArray ? type.GetElementType() : type.GetGenericArguments()[0]; + var subType = type.IsArray ? type.GetElementType() : type.GetGenericArguments()[0]; if (subName == null) + { subName = subType.GetTypeName(); + } + subName = subName.ToLowerInvariant(); - List subValues = new List(); + var subValues = new List(); if (node != null) { foreach (XmlNode subNode in node.ChildNodes) { if (subNode is XmlComment) + { continue; + } + if (subName == subNode.Name.ToLowerInvariant() && !subNode.Name.ToLowerInvariant().StartsWith(subName)) + { _ErrorHandler.HandleError(new CXmlException("Invalid list entry '" + subNode.Name + "' in %n; Expected: " + subName, node)); - object subValue = _GetValue(subNode, subType); + } + + var subValue = _GetValue(subNode, subType); if (subValue != null) + { subValues.Add(subValue); + } } } + if (value == null) + { return _CreateList(type, subValues); + } + _FillList(value, type, subValues); return value; } + if (type.IsDictionary()) { - Type subType = type.GetGenericArguments()[1]; - object dict = value ?? Activator.CreateInstance(type); - MethodInfo add = type.GetMethod("Add"); + var subType = type.GetGenericArguments()[1]; + var dict = value ?? Activator.CreateInstance(type); + var add = type.GetMethod("Add"); if (subName != null) + { subName = subName.ToLowerInvariant(); + } + if (node != null) { foreach (XmlNode subNode in node.ChildNodes) { if (subNode is XmlComment) + { continue; + } + string key; if (subName != null) { if (subName != subNode.Name.ToLowerInvariant() && !subNode.Name.ToLowerInvariant().StartsWith(subName)) + { _ErrorHandler.HandleError(new CXmlException("Invalid dictionary entry '" + subNode.Name + "' in %n; Expected: " + subName, node)); - XmlNode nameAtt = (subNode.Attributes == null) ? null : subNode.Attributes.GetNamedItem("name"); + } + + var nameAtt = subNode.Attributes == null ? null : subNode.Attributes.GetNamedItem("name"); if (nameAtt == null) { _ErrorHandler.HandleError(new CXmlException("'name' attribute is missing in %n", subNode)); continue; } + key = nameAtt.Value; } else + { key = subNode.Name; - object subValue = _GetValue(subNode, subType); + } + + var subValue = _GetValue(subNode, subType); if (subValue != null) - add.Invoke(dict, new object[] {key, subValue}); + { + add.Invoke(dict, new object[] { key, subValue }); + } } } + return dict; } @@ -322,6 +385,7 @@ namespace VocaluxeLib.Xml return null; } } + _ReadChildNodes(node, value, true); _ReadChildNodes(node, value, false); return value; @@ -336,19 +400,23 @@ namespace VocaluxeLib.Xml private object _GetPrimitiveValue(XmlNode node, Type type) { if (node == null) + { return null; + } + object value; - string nodeVal = node.InnerText; + var nodeVal = node.InnerText; try { - int p = nodeVal.IndexOf(','); + var p = nodeVal.IndexOf(','); if (p > 0 && p >= nodeVal.Length - 3) { _ErrorHandler.HandleError(new CXmlInvalidValueException("German number format converted to English in %n", node, nodeVal, false)); - char[] tmp = nodeVal.ToCharArray(); + var tmp = nodeVal.ToCharArray(); tmp[p] = '.'; nodeVal = new string(tmp); } + value = Convert.ChangeType(nodeVal, type, CultureInfo.InvariantCulture); } catch (FormatException e) @@ -361,6 +429,7 @@ namespace VocaluxeLib.Xml _ErrorHandler.HandleError(new CXmlInvalidValueException(e.Message + " in %n: '%v'", node, nodeVal)); return null; } + return value; } @@ -377,8 +446,12 @@ namespace VocaluxeLib.Xml _AddList(result, field, new List()); return true; } + if (!field.HasDefaultValue) + { return false; + } + field.SetValue(result, field.DefaultValue); return true; } @@ -392,19 +465,26 @@ namespace VocaluxeLib.Xml private static void _FillList(object list, Type type, ICollection values) { if (values.Count <= 0) + { return; + } + if (type.IsArray) { - Array array = (Array)list; - int i = 0; - foreach (object value in values) + var array = (Array)list; + var i = 0; + foreach (var value in values) + { array.SetValue(value, i++); + } } else { - MethodInfo addMethod = type.GetMethod("Add"); - foreach (object value in values) - addMethod.Invoke(list, new object[] {value}); + var addMethod = type.GetMethod("Add"); + foreach (var value in values) + { + addMethod.Invoke(list, new object[] { value }); + } } } @@ -416,7 +496,7 @@ namespace VocaluxeLib.Xml /// Newly created collection private static object _CreateList(Type type, ICollection values) { - object list = type.IsArray ? Array.CreateInstance(type.GetElementType(), values.Count) : Activator.CreateInstance(type, new object[] {values.Count}); + var list = type.IsArray ? Array.CreateInstance(type.GetElementType(), values.Count) : Activator.CreateInstance(type, new object[] { values.Count }); _FillList(list, type, values); return list; } @@ -442,36 +522,50 @@ namespace VocaluxeLib.Xml { IEnumerable nodes; if (parent == null) + { nodes = null; + } else if (attributes) + { nodes = parent.Attributes; + } else + { nodes = parent.ChildNodes; + } - List fields = o.GetType().GetFields(attributes); + var fields = o.GetType().GetFields(attributes); if (nodes != null) { //Dictionary of all embedded lists to allow interleaved/mixed elements - Dictionary>> embLists = new Dictionary>>(); + var embLists = new Dictionary>>(); foreach (XmlNode node in nodes) { if (node is XmlComment || node.LocalName == "xsd" || node.LocalName == "xsi") + { continue; + } - SFieldInfo field = new SFieldInfo(); + var field = new SFieldInfo(); int curField; for (curField = 0; curField < fields.Count; curField++) { field = fields[curField]; if (field.Name == node.Name || field.AltName == node.Name || (field.IsEmbeddedList && node.Name.StartsWith(field.Name))) + { break; + } } + if (curField >= fields.Count) { - string msg = "Unexpected element: %n"; + var msg = "Unexpected element: %n"; if (fields.Count > 0) + { msg += " Expected: " + string.Join(", ", fields.Select(f => f.Name)); + } + _ErrorHandler.HandleError(new CXmlException(msg, node)); continue; } @@ -488,9 +582,13 @@ namespace VocaluxeLib.Xml { _ErrorHandler.HandleError(new CXmlInvalidValueException("Invalid value in %n: %v", node, node.InnerText)); if (!_CheckAndSetDefaultValue(o, field)) + { _ErrorHandler.HandleError(new CXmlException("No default value for %n", node)); + } + continue; } + field.SetValue(o, value); } else if (field.IsEmbeddedList) @@ -501,24 +599,31 @@ namespace VocaluxeLib.Xml entry = new Tuple>(field, new List()); embLists.Add(field.Name, entry); } - object subValue = _GetValue(node, field.SubType); + + var subValue = _GetValue(node, field.SubType); if (subValue != null) + { entry.Item2.Add(subValue); + } } else { fields.RemoveAt(curField); //Do this also on error - object value = _GetValue(node, field.Type, field.ArrayItemName); + var value = _GetValue(node, field.Type, field.ArrayItemName); if (value == null) { if (_CheckAndSetDefaultValue(o, field)) + { continue; + } + if (!field.IsNullable) { _ErrorHandler.HandleError(new CXmlException("No default value for unset field at %n", node)); continue; } } + if (field.Ranged != null && value != null && !field.Ranged.IsValid(field.IsNullable ? field.SubType : field.Type, value)) { _ErrorHandler.HandleError(new CXmlInvalidValueException("Value in %n is not in the range " + field.Ranged + @@ -528,22 +633,29 @@ namespace VocaluxeLib.Xml field.SetValue(o, value); } } + //Add embedded lists - foreach (Tuple> entry in embLists.Values) + foreach (var entry in embLists.Values) { _AddList(o, entry.Item1, entry.Item2); fields.Remove(entry.Item1); } } - foreach (SFieldInfo field in fields) + + foreach (var field in fields) { if (!_CheckAndSetDefaultValue(o, field)) { if (parent != null) + { _ErrorHandler.HandleError(new CXmlMissingElementException(parent, field)); - object value = _GetValue(null, field.Type, field.ArrayItemName, field.GetValue(o)); + } + + var value = _GetValue(null, field.Type, field.ArrayItemName, field.GetValue(o)); if (value != null) + { field.SetValue(o, value); + } } } } @@ -563,13 +675,14 @@ namespace VocaluxeLib.Xml return (T)o; } - XmlDocument xDoc = new XmlDocument(); + var xDoc = new XmlDocument(); xDoc.Load(reader); if (xDoc.DocumentElement == null) { _ErrorHandler.HandleError(new CXmlException("Root element not found!", null)); return (T)o; } + try { o = _GetValue(xDoc.DocumentElement, o.GetType(), o.GetType().GetSubTypeName(), o); @@ -578,6 +691,7 @@ namespace VocaluxeLib.Xml { throw e.InnerException ?? e; } + return (T)o; } @@ -603,11 +717,11 @@ namespace VocaluxeLib.Xml public T DeserializeString(string xml, T o) where T : new() { var reader = new XmlTextReader(new StringReader(xml)) - { - WhitespaceHandling = WhitespaceHandling.Significant, - Normalization = true, - XmlResolver = null - }; + { + WhitespaceHandling = WhitespaceHandling.Significant, + Normalization = true, + XmlResolver = null + }; try { return _Deserialize(reader, o); @@ -640,13 +754,16 @@ namespace VocaluxeLib.Xml public T Deserialize(string filePath, T o) where T : new() { if (!File.Exists(filePath)) + { throw new FileNotFoundException(filePath); + } + var reader = new XmlTextReader(filePath) - { - WhitespaceHandling = WhitespaceHandling.Significant, - Normalization = true, - XmlResolver = null - }; + { + WhitespaceHandling = WhitespaceHandling.Significant, + Normalization = true, + XmlResolver = null + }; try { return _Deserialize(reader, o); diff --git a/VocaluxeLib/Xml/CXmlSerializer.cs b/VocaluxeLib/Xml/CXmlSerializer.cs index 05188013..1488cdd2 100644 --- a/VocaluxeLib/Xml/CXmlSerializer.cs +++ b/VocaluxeLib/Xml/CXmlSerializer.cs @@ -17,7 +17,6 @@ using System; using System.Collections; -using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; @@ -49,11 +48,11 @@ namespace VocaluxeLib.Xml /// Uniform settings for writing XML files. ALWAYS use this! /// private readonly XmlWriterSettings _XmlSettings = new XmlWriterSettings - { - Indent = true, - Encoding = Encoding.UTF8, - ConformanceLevel = ConformanceLevel.Document - }; + { + Indent = true, + Encoding = Encoding.UTF8, + ConformanceLevel = ConformanceLevel.Document + }; /// /// Writes a value as a node or attribute @@ -69,10 +68,13 @@ namespace VocaluxeLib.Xml { if (!isAttribute && _GetCommentCallback != null) { - string comment = _GetCommentCallback(name); + var comment = _GetCommentCallback(name); if (!string.IsNullOrEmpty(comment)) + { writer.WriteComment(comment); + } } + if (type.IsEnum || type == typeof(string) || type.IsPrimitive) { string strVal; @@ -84,15 +86,24 @@ namespace VocaluxeLib.Xml { throw new XmlException("Cannot convert value of type " + type.Name + " to string in node " + name + " (" + e.Message + ")"); } + if (isAttribute) + { writer.WriteAttributeString(name, strVal); + } else { writer.WriteStartElement(name); if (nameAttribute != null) + { writer.WriteAttributeString("name", nameAttribute); + } + if (!string.IsNullOrEmpty(strVal)) + { writer.WriteValue(strVal); + } + writer.WriteEndElement(); } } @@ -101,18 +112,26 @@ namespace VocaluxeLib.Xml writer.WriteElementString(name, value.ToString()); } else if (type.IsNullable()) + { _WriteValue(writer, name, type.GetGenericArguments()[0], value, isAttribute, arrayItemName, nameAttribute); + } else if (type.IsList() || type.IsArray) { Debug.Assert(!isAttribute, "Lists cannot be attributes"); writer.WriteStartElement(name); if (nameAttribute != null) + { writer.WriteAttributeString("name", nameAttribute); - Type subType = type.IsArray ? type.GetElementType() : type.GetGenericArguments()[0]; - String subName = arrayItemName ?? subType.GetTypeName(); - IEnumerable list = (IEnumerable)value; - foreach (object subValue in list) + } + + var subType = type.IsArray ? type.GetElementType() : type.GetGenericArguments()[0]; + var subName = arrayItemName ?? subType.GetTypeName(); + var list = (IEnumerable)value; + foreach (var subValue in list) + { _WriteValue(writer, subName, subType, subValue, false); + } + writer.WriteEndElement(); } else if (type.IsDictionary()) @@ -120,9 +139,12 @@ namespace VocaluxeLib.Xml Debug.Assert(!isAttribute, "Dictionaries cannot be attributes"); writer.WriteStartElement(name); if (nameAttribute != null) + { writer.WriteAttributeString("name", nameAttribute); - Type subType = type.GetGenericArguments()[1]; - IDictionary dict = (IDictionary)value; + } + + var subType = type.GetGenericArguments()[1]; + var dict = (IDictionary)value; foreach (DictionaryEntry entry in dict) { string subName; @@ -137,8 +159,10 @@ namespace VocaluxeLib.Xml subName = arrayItemName; subNameAttribute = (string)entry.Key; } + _WriteValue(writer, subName, subType, entry.Value, false, null, subNameAttribute); } + writer.WriteEndElement(); } else @@ -146,9 +170,15 @@ namespace VocaluxeLib.Xml Debug.Assert(!isAttribute, "Complex types cannot be attributes"); writer.WriteStartElement(name); if (nameAttribute != null) + { writer.WriteAttributeString("name", nameAttribute); + } + if (value != null) + { _WriteFields(writer, value); + } + writer.WriteEndElement(); } } @@ -160,28 +190,38 @@ namespace VocaluxeLib.Xml /// Object to process private void _WriteFields(XmlWriter writer, object o) { - IEnumerable fields = o.GetType().GetFieldInfos(); - foreach (SFieldInfo field in fields) + var fields = o.GetType().GetFieldInfos(); + foreach (var field in fields) { - object value = field.GetValue(o); + var value = field.GetValue(o); if (!_WriteDefaults && field.HasDefaultValue && Equals(value, field.DefaultValue)) + { continue; + } + if (field.IsEmbeddedList) { - IEnumerable values = (IEnumerable)value; - bool empty = true; - foreach (object subValue in values) + var values = (IEnumerable)value; + var empty = true; + foreach (var subValue in values) { _WriteValue(writer, field.Name, field.SubType, subValue, field.IsAttribute); empty = false; } + if (empty && _WriteDefaults) + { writer.WriteElementString(field.Name, ""); + } } else if (field.IsByteArray) + { writer.WriteElementString(field.Name, Convert.ToBase64String((byte[])value)); + } else + { _WriteValue(writer, field.Name, field.Type, value, field.IsAttribute, field.ArrayItemName); + } } } @@ -195,18 +235,25 @@ namespace VocaluxeLib.Xml { if (string.IsNullOrEmpty(rootNodeName)) { - XmlRootAttribute root = o.GetType().GetAttribute(); + var root = o.GetType().GetAttribute(); if (root != null && !string.IsNullOrEmpty(root.ElementName)) + { rootNodeName = root.ElementName; + } else { - XmlTypeAttribute typeAtt = o.GetType().GetAttribute(); + var typeAtt = o.GetType().GetAttribute(); if (typeAtt != null && !string.IsNullOrEmpty(typeAtt.TypeName)) + { rootNodeName = typeAtt.TypeName; + } else + { rootNodeName = "root"; + } } } + try { writer.WriteStartDocument(); @@ -227,8 +274,10 @@ namespace VocaluxeLib.Xml /// Name of the root node (overwrites default value specified by XmlRoot/XmlTypeAttributes which defaults to "root") public void Serialize(string filePath, object o, string rootNodeName = null) { - using (XmlWriter writer = XmlWriter.Create(filePath, _XmlSettings)) + using (var writer = XmlWriter.Create(filePath, _XmlSettings)) + { _Serialize(writer, o, rootNodeName); + } } /// @@ -239,9 +288,12 @@ namespace VocaluxeLib.Xml /// Serialized object public string Serialize(object o, string rootNodeName = null) { - MemoryStream result = new MemoryStream(); - using (XmlWriter writer = XmlWriter.Create(result, _XmlSettings)) + var result = new MemoryStream(); + using (var writer = XmlWriter.Create(result, _XmlSettings)) + { _Serialize(writer, o, rootNodeName); + } + result.Position = 0; return new StreamReader(result).ReadToEnd(); } diff --git a/VocaluxeLib/Xml/SFieldInfo.cs b/VocaluxeLib/Xml/SFieldInfo.cs index bf9eaad3..f48d4904 100644 --- a/VocaluxeLib/Xml/SFieldInfo.cs +++ b/VocaluxeLib/Xml/SFieldInfo.cs @@ -80,14 +80,18 @@ namespace VocaluxeLib.Xml public void SetValue(object o, object value) { if (_Field != null) + { _Field.SetValue(o, value); + } else - _Property.SetValue(o, value, new object[] {}); + { + _Property.SetValue(o, value, new object[] { }); + } } public object GetValue(object o) { - return (_Field != null) ? _Field.GetValue(o) : _Property.GetValue(o, new object[] {}); + return _Field != null ? _Field.GetValue(o) : _Property.GetValue(o, new object[] { }); } } } \ No newline at end of file diff --git a/VocaluxeLib/XmlStructs.cs b/VocaluxeLib/XmlStructs.cs index c999193a..ccbc0292 100644 --- a/VocaluxeLib/XmlStructs.cs +++ b/VocaluxeLib/XmlStructs.cs @@ -24,6 +24,7 @@ namespace VocaluxeLib public struct SPlaylistSong { public string Artist, Title; - [DefaultValue(EGameMode.TR_GAMEMODE_NORMAL)] public EGameMode GameMode; + [DefaultValue(EGameMode.TR_GAMEMODE_NORMAL)] + public EGameMode GameMode; } } \ No newline at end of file diff --git a/WebserverInitalConfig/CConfigHttpApi.cs b/WebserverInitalConfig/CConfigHttpApi.cs index 90bdfc2b..2ff46f5f 100644 --- a/WebserverInitalConfig/CConfigHttpApi.cs +++ b/WebserverInitalConfig/CConfigHttpApi.cs @@ -15,27 +15,27 @@ // along with Vocaluxe. If not, see . #endregion -using System.Security.Authentication; -using System.Security.Principal; -using System.Windows.Forms; -using Security.Cryptography; -using Security.Cryptography.X509Certificates; using System; using System.Linq; using System.Net; +using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; +using System.Security.Principal; +using System.Windows.Forms; using NetFwTypeLib; +using Security.Cryptography; +using Security.Cryptography.X509Certificates; namespace WebserverInitalConfig { public class CConfigHttpApi { // ReSharper disable InconsistentNaming - private const String CLSID_NetFwMgr = "{304CE942-6E39-40D8-943A-B913C40C9CD4}"; - private const String CLSID_NetAuthApp = "{EC9846B3-2762-4A6B-A214-6ACB603462D2}"; - private const String CLSID_NetOpenPort = "{0CA545C6-37AD-4A6C-BF92-9F7610067EF5}"; - private const string _AppGUID = "{7baf41f1-48b7-42cb-b145-f815499cb48f}"; + private const String CLSId_NetFwMgr = "{304CE942-6E39-40D8-943A-B913C40C9CD4}"; + private const String CLSId_NetAuthApp = "{EC9846B3-2762-4A6B-A214-6ACB603462D2}"; + private const String CLSId_NetOpenPort = "{0CA545C6-37AD-4A6C-BF92-9F7610067EF5}"; + private const string _AppGUId = "{7baf41f1-48b7-42cb-b145-f815499cb48f}"; // ReSharper restore InconsistentNaming private readonly string _RuleName; @@ -56,41 +56,49 @@ namespace WebserverInitalConfig private static void _ReserveUrl(string networkString) { if (!IsAdministrator()) + { throw new AuthenticationException(); + } + HttpApi.ReserveURL(networkString, "D:(A;;GX;;;S-1-1-0)"); } public void ReserveUrl(bool secure) { - string http = secure ? "https" : "http"; + var http = secure ? "https" : "http"; _ReserveUrl(http + "://+:" + _Port + "/"); } private void _BindCert(X509Certificate cert) { - IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(_IP), _Port); - HttpApi.SslCertificateInfo certificateInfo = HttpApi.QuerySslCertificateInfo(endpoint); + var endpoint = new IPEndPoint(IPAddress.Parse(_IP), _Port); + var certificateInfo = HttpApi.QuerySslCertificateInfo(endpoint); if (certificateInfo != null && !certificateInfo.Hash.SequenceEqual(cert.GetCertHash())) { if (!IsAdministrator()) + { throw new AuthenticationException(); + } + HttpApi.DeleteCertificateBinding(endpoint); - HttpApi.BindCertificate(endpoint, cert.GetCertHash(), StoreName.My, new Guid(_AppGUID)); + HttpApi.BindCertificate(endpoint, cert.GetCertHash(), StoreName.My, new Guid(_AppGUId)); } } private static void _AddCertToStore(X509Certificate2 cert) { - X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); + var store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadWrite); // ReSharper disable AssignNullToNotNullAttribute - X509Certificate2Collection oldCerts = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.SubjectName.Name, false); + var oldCerts = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, cert.SubjectName.Name, false); // ReSharper restore AssignNullToNotNullAttribute - foreach (X509Certificate2 oldCert in oldCerts) + foreach (var oldCert in oldCerts) + { store.Remove(oldCert); + } store.Add(cert); store.Close(); @@ -99,15 +107,17 @@ namespace WebserverInitalConfig private static X509Certificate2 _GetCert(string name) { X509Certificate2 result = null; - X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); + var store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); var name2 = new X500DistinguishedName(name); // ReSharper disable AssignNullToNotNullAttribute - X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, name2.Name, false); + var certs = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, name2.Name, false); // ReSharper restore AssignNullToNotNullAttribute if (certs.Count > 0) + { result = certs[0]; + } store.Close(); @@ -117,12 +127,12 @@ namespace WebserverInitalConfig private X509Certificate2 _GetSelfSignedCert(string subjectName) { var keyParam = new CngKeyCreationParameters - { - ExportPolicy = CngExportPolicies.AllowExport, - KeyCreationOptions = CngKeyCreationOptions.MachineKey | CngKeyCreationOptions.OverwriteExistingKey, - KeyUsage = CngKeyUsages.AllUsages, - Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider, - }; + { + ExportPolicy = CngExportPolicies.AllowExport, + KeyCreationOptions = CngKeyCreationOptions.MachineKey | CngKeyCreationOptions.OverwriteExistingKey, + KeyUsage = CngKeyUsages.AllUsages, + Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider, + }; keyParam.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None)); @@ -143,59 +153,70 @@ namespace WebserverInitalConfig } } - X509CertificateCreationParameters param = new X509CertificateCreationParameters(new X500DistinguishedName(subjectName)) - { - SubjectName = new X500DistinguishedName(subjectName), - EndTime = DateTime.Today.AddYears(20) //,SignatureAlgorithm = X509CertificateSignatureAlgorithm.RsaSha512 - }; + var param = new X509CertificateCreationParameters(new X500DistinguishedName(subjectName)) + { + SubjectName = new X500DistinguishedName(subjectName), + EndTime = DateTime.Today.AddYears(20) //,SignatureAlgorithm = X509CertificateSignatureAlgorithm.RsaSha512 + }; - OidCollection oc = new OidCollection {new Oid("1.3.6.1.5.5.7.3.1")}; + var oc = new OidCollection { new Oid("1.3.6.1.5.5.7.3.1") }; X509Extension eku = new X509EnhancedKeyUsageExtension(oc, true); param.Extensions.Add(eku); param.TakeOwnershipOfKey = true; - byte[] rawData = key.CreateSelfSignedCertificate(param).Export(X509ContentType.Pfx, ""); + var rawData = key.CreateSelfSignedCertificate(param).Export(X509ContentType.Pfx, ""); var cert = new X509Certificate2(rawData, "", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet) - { - FriendlyName = _RuleName + " Server Certificate" - }; + { + FriendlyName = _RuleName + " Server Certificate" + }; return cert; } public void CreateAndAddCert(string hostName) { - string certName = "CN=" + hostName + ", C=DE, O=" + _RuleName + ", OU=" + _RuleName + " Server"; + var certName = "CN=" + hostName + ", C=DE, O=" + _RuleName + ", OU=" + _RuleName + " Server"; - X509Certificate2 cert = _GetCert(certName); + var cert = _GetCert(certName); if (cert == null) { if (!IsAdministrator()) + { throw new AuthenticationException(); + } + cert = _GetSelfSignedCert(certName); if (cert == null) { MessageBox.Show("Could not create certificate. Secure server connection may not work. Disable it if required."); return; } + _AddCertToStore(cert); } + _BindCert(cert); } private bool _IsAppAuthorized(INetFwProfile profile) { if (!profile.FirewallEnabled) + { return true; + } + return profile.AuthorizedApplications.Cast().Any(a => a.ProcessImageFileName == _ExePath); } private bool _IsPortOpen(INetFwProfile profile) { - NET_FW_IP_PROTOCOL_ protocol = _GetProtocol(); + var protocol = _GetProtocol(); if (!profile.FirewallEnabled) + { return true; + } + return profile.GloballyOpenPorts.Cast().Any(p => p.Protocol == protocol && p.Port == _Port); } @@ -206,21 +227,28 @@ namespace WebserverInitalConfig private void _AddFirewallRuleForProfile(INetFwProfile profile) { - bool isAppAuthorized = _IsAppAuthorized(profile); - bool isPortOpen = _IsPortOpen(profile); + var isAppAuthorized = _IsAppAuthorized(profile); + var isPortOpen = _IsPortOpen(profile); if ((!isAppAuthorized || !isPortOpen) && !IsAdministrator()) + { throw new AuthenticationException(); + } + if (!isAppAuthorized) + { _AddAppToFirewall(profile); + } if (!isPortOpen) + { _AddPortToFirewall(profile); + } } private void _AddPortToFirewall(INetFwProfile profile) { - INetFwOpenPort openPort = (INetFwOpenPort)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(CLSID_NetOpenPort))); + var openPort = (INetFwOpenPort)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(CLSId_NetOpenPort))); openPort.Enabled = true; openPort.Port = _Port; openPort.Protocol = _GetProtocol(); @@ -232,8 +260,8 @@ namespace WebserverInitalConfig private void _AddAppToFirewall(INetFwProfile profile) { - INetFwAuthorizedApplication application = (INetFwAuthorizedApplication)Activator.CreateInstance( - Type.GetTypeFromCLSID(new Guid(CLSID_NetAuthApp))); + var application = (INetFwAuthorizedApplication)Activator.CreateInstance( + Type.GetTypeFromCLSID(new Guid(CLSId_NetAuthApp))); application.Name = _RuleName; application.ProcessImageFileName = _ExePath; @@ -244,16 +272,16 @@ namespace WebserverInitalConfig public static bool IsAdministrator() { - WindowsIdentity identity = WindowsIdentity.GetCurrent(); + var identity = WindowsIdentity.GetCurrent(); // ReSharper disable AssignNullToNotNullAttribute - WindowsPrincipal principal = new WindowsPrincipal(identity); + var principal = new WindowsPrincipal(identity); // ReSharper restore AssignNullToNotNullAttribute return principal.IsInRole(WindowsBuiltInRole.Administrator); } public void AddFirewallRule() { - INetFwMgr manage = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(CLSID_NetFwMgr))); + var manage = (INetFwMgr)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid(CLSId_NetFwMgr))); //_AddFirewallRuleForProfile(manage.LocalPolicy.CurrentProfile); //if (manage.CurrentProfileType != NET_FW_PROFILE_TYPE_.NET_FW_PROFILE_STANDARD) //Add to Home/Work(Private) and current net @@ -267,8 +295,8 @@ namespace WebserverInitalConfig RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); Mono.Security.Authenticode.PrivateKey key = new Mono.Security.Authenticode.PrivateKey { RSA=RSA.Create()}; - - + + Mono.Security.X509.X509CertificateBuilder x509 = new Mono.Security.X509.X509CertificateBuilder(); x509.IssuerName = "CN=Vocaluxe Server"; x509.NotAfter = DateTime.Today.AddYears(20); diff --git a/WebserverInitalConfig/HttpApi.cs b/WebserverInitalConfig/HttpApi.cs index 5d62b305..3482dbdb 100644 --- a/WebserverInitalConfig/HttpApi.cs +++ b/WebserverInitalConfig/HttpApi.cs @@ -40,7 +40,7 @@ namespace WebserverInitalConfig [DllImport("httpapi.dll", SetLastError = true)] private static extern uint HttpSetServiceConfiguration( IntPtr serviceIntPtr, - HTTP_SERVICE_CONFIG_ID configId, + HTTP_SERVICE_CONFIG_Id configId, IntPtr pConfigInformation, int configInformationLength, IntPtr pOverlapped); @@ -48,7 +48,7 @@ namespace WebserverInitalConfig [DllImport("httpapi.dll", SetLastError = true)] private static extern uint HttpDeleteServiceConfiguration( IntPtr serviceIntPtr, - HTTP_SERVICE_CONFIG_ID configId, + HTTP_SERVICE_CONFIG_Id configId, IntPtr pConfigInformation, int configInformationLength, IntPtr pOverlapped); @@ -61,7 +61,7 @@ namespace WebserverInitalConfig [DllImport("httpapi.dll", SetLastError = true)] private static extern uint HttpQueryServiceConfiguration( IntPtr serviceIntPtr, - HTTP_SERVICE_CONFIG_ID configId, + HTTP_SERVICE_CONFIG_Id configId, IntPtr pInputConfigInfo, int inputConfigInfoLength, IntPtr pOutputConfigInfo, @@ -69,7 +69,7 @@ namespace WebserverInitalConfig [Optional] out int pReturnLength, IntPtr pOverlapped); - private enum HTTP_SERVICE_CONFIG_ID + private enum HTTP_SERVICE_CONFIG_Id { HttpServiceConfigIPListenList = 0, HttpServiceConfigSSLCertInfo, @@ -101,12 +101,15 @@ namespace WebserverInitalConfig public int SslHashLength; public IntPtr pSslHash; public Guid AppId; - [MarshalAs(UnmanagedType.LPWStr)] public string pSslCertStoreName; + [MarshalAs(UnmanagedType.LPWStr)] + public string pSslCertStoreName; public uint DefaultCertCheckMode; public int DefaultRevocationFreshnessTime; public int DefaultRevocationUrlRetrievalTimeout; - [MarshalAs(UnmanagedType.LPWStr)] public string pDefaultSslCtlIdentifier; - [MarshalAs(UnmanagedType.LPWStr)] public string pDefaultSslCtlStoreName; + [MarshalAs(UnmanagedType.LPWStr)] + public string pDefaultSslCtlIdentifier; + [MarshalAs(UnmanagedType.LPWStr)] + public string pDefaultSslCtlStoreName; public uint DefaultFlags; } @@ -156,7 +159,8 @@ namespace WebserverInitalConfig [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct HTTP_SERVICE_CONFIG_URLACL_KEY { - [MarshalAs(UnmanagedType.LPWStr)] public string pUrlPrefix; + [MarshalAs(UnmanagedType.LPWStr)] + public string pUrlPrefix; public HTTP_SERVICE_CONFIG_URLACL_KEY(string urlPrefix) { @@ -167,7 +171,8 @@ namespace WebserverInitalConfig [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private struct HTTP_SERVICE_CONFIG_URLACL_PARAM { - [MarshalAs(UnmanagedType.LPWStr)] public string pStringSecurityDescriptor; + [MarshalAs(UnmanagedType.LPWStr)] + public string pStringSecurityDescriptor; public HTTP_SERVICE_CONFIG_URLACL_PARAM(string securityDescriptor) { @@ -202,83 +207,89 @@ namespace WebserverInitalConfig uint retVal; CallHttpApi(delegate + { + var sockAddrHandle = CreateSockaddrStructure(ipPort); + var pIpPort = sockAddrHandle.AddrOfPinnedObject(); + var sslKey = new HTTP_SERVICE_CONFIG_SSL_KEY(pIpPort); + + var inputConfigInfoQuery = + new HTTP_SERVICE_CONFIG_SSL_QUERY + { + QueryDesc = HTTP_SERVICE_CONFIG_QUERY_TYPE.HttpServiceConfigQueryExact, + KeyDesc = sslKey + }; + + var pInputConfigInfo = + Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_SSL_QUERY))); + Marshal.StructureToPtr(inputConfigInfoQuery, pInputConfigInfo, false); + + var pOutputConfigInfo = IntPtr.Zero; + var returnLength = 0; + + try { - GCHandle sockAddrHandle = CreateSockaddrStructure(ipPort); - IntPtr pIpPort = sockAddrHandle.AddrOfPinnedObject(); - HTTP_SERVICE_CONFIG_SSL_KEY sslKey = new HTTP_SERVICE_CONFIG_SSL_KEY(pIpPort); - - HTTP_SERVICE_CONFIG_SSL_QUERY inputConfigInfoQuery = - new HTTP_SERVICE_CONFIG_SSL_QUERY - { - QueryDesc = HTTP_SERVICE_CONFIG_QUERY_TYPE.HttpServiceConfigQueryExact, - KeyDesc = sslKey - }; - - IntPtr pInputConfigInfo = - Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_SSL_QUERY))); - Marshal.StructureToPtr(inputConfigInfoQuery, pInputConfigInfo, false); - - IntPtr pOutputConfigInfo = IntPtr.Zero; - int returnLength = 0; - - try + var queryType = HTTP_SERVICE_CONFIG_Id.HttpServiceConfigSSLCertInfo; + var inputConfigInfoSize = Marshal.SizeOf(inputConfigInfoQuery); + retVal = HttpQueryServiceConfiguration(IntPtr.Zero, + queryType, + pInputConfigInfo, + inputConfigInfoSize, + pOutputConfigInfo, + returnLength, + out returnLength, + IntPtr.Zero); + if (retVal == ERROR_FILE_NOT_FOUND) { - HTTP_SERVICE_CONFIG_ID queryType = HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo; - int inputConfigInfoSize = Marshal.SizeOf(inputConfigInfoQuery); - retVal = HttpQueryServiceConfiguration(IntPtr.Zero, - queryType, - pInputConfigInfo, - inputConfigInfoSize, - pOutputConfigInfo, - returnLength, - out returnLength, - IntPtr.Zero); - if (retVal == ERROR_FILE_NOT_FOUND) - return; + return; + } - if (ERROR_INSUFFICIENT_BUFFER == retVal) + if (ERROR_INSUFFICIENT_BUFFER == retVal) + { + pOutputConfigInfo = Marshal.AllocCoTaskMem(returnLength); + + try { - pOutputConfigInfo = Marshal.AllocCoTaskMem(returnLength); - - try - { - retVal = HttpQueryServiceConfiguration(IntPtr.Zero, - queryType, - pInputConfigInfo, - inputConfigInfoSize, - pOutputConfigInfo, - returnLength, - out returnLength, - IntPtr.Zero); - ThrowWin32ExceptionIfError(retVal); - - var outputConfigInfo = - (HTTP_SERVICE_CONFIG_SSL_SET) - Marshal.PtrToStructure(pOutputConfigInfo, typeof(HTTP_SERVICE_CONFIG_SSL_SET)); - - byte[] hash = new byte[outputConfigInfo.ParamDesc.SslHashLength]; - Marshal.Copy(outputConfigInfo.ParamDesc.pSslHash, hash, 0, hash.Length); - - Guid appId = outputConfigInfo.ParamDesc.AppId; - string storeName = outputConfigInfo.ParamDesc.pSslCertStoreName; - - result = new SslCertificateInfo {AppId = appId, Hash = hash, StoreName = storeName, IpPort = ipPort}; - } - finally - { - Marshal.FreeCoTaskMem(pOutputConfigInfo); - } - } - else + retVal = HttpQueryServiceConfiguration(IntPtr.Zero, + queryType, + pInputConfigInfo, + inputConfigInfoSize, + pOutputConfigInfo, + returnLength, + out returnLength, + IntPtr.Zero); ThrowWin32ExceptionIfError(retVal); + + var outputConfigInfo = + (HTTP_SERVICE_CONFIG_SSL_SET) + Marshal.PtrToStructure(pOutputConfigInfo, typeof(HTTP_SERVICE_CONFIG_SSL_SET)); + + var hash = new byte[outputConfigInfo.ParamDesc.SslHashLength]; + Marshal.Copy(outputConfigInfo.ParamDesc.pSslHash, hash, 0, hash.Length); + + var appId = outputConfigInfo.ParamDesc.AppId; + var storeName = outputConfigInfo.ParamDesc.pSslCertStoreName; + + result = new SslCertificateInfo { AppId = appId, Hash = hash, StoreName = storeName, IpPort = ipPort }; + } + finally + { + Marshal.FreeCoTaskMem(pOutputConfigInfo); + } } - finally + else { - Marshal.FreeCoTaskMem(pInputConfigInfo); - if (sockAddrHandle.IsAllocated) - sockAddrHandle.Free(); + ThrowWin32ExceptionIfError(retVal); } - }); + } + finally + { + Marshal.FreeCoTaskMem(pInputConfigInfo); + if (sockAddrHandle.IsAllocated) + { + sockAddrHandle.Free(); + } + } + }); return result; } @@ -286,117 +297,133 @@ namespace WebserverInitalConfig public static void BindCertificate(IPEndPoint ipPort, byte[] hash, StoreName storeName, Guid appId) { if (ipPort == null) + { throw new ArgumentNullException("ipPort"); + } + if (hash == null) + { throw new ArgumentNullException("hash"); + } CallHttpApi( delegate + { + var configSslSet = new HTTP_SERVICE_CONFIG_SSL_SET(); + + var sockAddrHandle = CreateSockaddrStructure(ipPort); + var pIpPort = sockAddrHandle.AddrOfPinnedObject(); + var httpServiceConfigSslKey = + new HTTP_SERVICE_CONFIG_SSL_KEY(pIpPort); + var configSslParam = new HTTP_SERVICE_CONFIG_SSL_PARAM(); + + + var handleHash = GCHandle.Alloc(hash, GCHandleType.Pinned); + configSslParam.AppId = appId; + configSslParam.DefaultCertCheckMode = 0; + configSslParam.DefaultFlags = 0; //HTTP_SERVICE_CONFIG_SSL_FLAG_NEGOTIATE_CLIENT_CERT; + configSslParam.DefaultRevocationFreshnessTime = 0; + configSslParam.DefaultRevocationUrlRetrievalTimeout = 0; + configSslParam.pSslCertStoreName = storeName.ToString(); + configSslParam.pSslHash = handleHash.AddrOfPinnedObject(); + configSslParam.SslHashLength = hash.Length; + configSslSet.ParamDesc = configSslParam; + configSslSet.KeyDesc = httpServiceConfigSslKey; + + var pInputConfigInfo = + Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_SSL_SET))); + Marshal.StructureToPtr(configSslSet, pInputConfigInfo, false); + + try { - HTTP_SERVICE_CONFIG_SSL_SET configSslSet = new HTTP_SERVICE_CONFIG_SSL_SET(); + var retVal = HttpSetServiceConfiguration(IntPtr.Zero, + HTTP_SERVICE_CONFIG_Id.HttpServiceConfigSSLCertInfo, + pInputConfigInfo, + Marshal.SizeOf(configSslSet), + IntPtr.Zero); - GCHandle sockAddrHandle = CreateSockaddrStructure(ipPort); - IntPtr pIpPort = sockAddrHandle.AddrOfPinnedObject(); - HTTP_SERVICE_CONFIG_SSL_KEY httpServiceConfigSslKey = - new HTTP_SERVICE_CONFIG_SSL_KEY(pIpPort); - HTTP_SERVICE_CONFIG_SSL_PARAM configSslParam = new HTTP_SERVICE_CONFIG_SSL_PARAM(); - - - GCHandle handleHash = GCHandle.Alloc(hash, GCHandleType.Pinned); - configSslParam.AppId = appId; - configSslParam.DefaultCertCheckMode = 0; - configSslParam.DefaultFlags = 0; //HTTP_SERVICE_CONFIG_SSL_FLAG_NEGOTIATE_CLIENT_CERT; - configSslParam.DefaultRevocationFreshnessTime = 0; - configSslParam.DefaultRevocationUrlRetrievalTimeout = 0; - configSslParam.pSslCertStoreName = storeName.ToString(); - configSslParam.pSslHash = handleHash.AddrOfPinnedObject(); - configSslParam.SslHashLength = hash.Length; - configSslSet.ParamDesc = configSslParam; - configSslSet.KeyDesc = httpServiceConfigSslKey; - - IntPtr pInputConfigInfo = - Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_SSL_SET))); - Marshal.StructureToPtr(configSslSet, pInputConfigInfo, false); - - try + if (ERROR_ALREADY_EXISTS != retVal) { - uint retVal = HttpSetServiceConfiguration(IntPtr.Zero, - HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, - pInputConfigInfo, - Marshal.SizeOf(configSslSet), - IntPtr.Zero); - - if (ERROR_ALREADY_EXISTS != retVal) - ThrowWin32ExceptionIfError(retVal); - else - { - retVal = HttpDeleteServiceConfiguration(IntPtr.Zero, - HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, - pInputConfigInfo, - Marshal.SizeOf(configSslSet), - IntPtr.Zero); - ThrowWin32ExceptionIfError(retVal); - - retVal = HttpSetServiceConfiguration(IntPtr.Zero, - HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, - pInputConfigInfo, - Marshal.SizeOf(configSslSet), - IntPtr.Zero); - ThrowWin32ExceptionIfError(retVal); - } + ThrowWin32ExceptionIfError(retVal); } - finally + else { - Marshal.FreeCoTaskMem(pInputConfigInfo); - if (handleHash.IsAllocated) - handleHash.Free(); - if (sockAddrHandle.IsAllocated) - sockAddrHandle.Free(); + retVal = HttpDeleteServiceConfiguration(IntPtr.Zero, + HTTP_SERVICE_CONFIG_Id.HttpServiceConfigSSLCertInfo, + pInputConfigInfo, + Marshal.SizeOf(configSslSet), + IntPtr.Zero); + ThrowWin32ExceptionIfError(retVal); + + retVal = HttpSetServiceConfiguration(IntPtr.Zero, + HTTP_SERVICE_CONFIG_Id.HttpServiceConfigSSLCertInfo, + pInputConfigInfo, + Marshal.SizeOf(configSslSet), + IntPtr.Zero); + ThrowWin32ExceptionIfError(retVal); } - }); + } + finally + { + Marshal.FreeCoTaskMem(pInputConfigInfo); + if (handleHash.IsAllocated) + { + handleHash.Free(); + } + + if (sockAddrHandle.IsAllocated) + { + sockAddrHandle.Free(); + } + } + }); } public static void DeleteCertificateBinding(params IPEndPoint[] ipPorts) { if (ipPorts == null || ipPorts.Length == 0) + { return; + } CallHttpApi( delegate + { + foreach (var ipPort in ipPorts) { - foreach (IPEndPoint ipPort in ipPorts) + var configSslSet = + new HTTP_SERVICE_CONFIG_SSL_SET(); + + var sockAddrHandle = CreateSockaddrStructure(ipPort); + var pIpPort = sockAddrHandle.AddrOfPinnedObject(); + var httpServiceConfigSslKey = + new HTTP_SERVICE_CONFIG_SSL_KEY(pIpPort); + configSslSet.KeyDesc = httpServiceConfigSslKey; + + var pInputConfigInfo = + Marshal.AllocCoTaskMem( + Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_SSL_SET))); + Marshal.StructureToPtr(configSslSet, pInputConfigInfo, false); + + try { - HTTP_SERVICE_CONFIG_SSL_SET configSslSet = - new HTTP_SERVICE_CONFIG_SSL_SET(); - - GCHandle sockAddrHandle = CreateSockaddrStructure(ipPort); - IntPtr pIpPort = sockAddrHandle.AddrOfPinnedObject(); - HTTP_SERVICE_CONFIG_SSL_KEY httpServiceConfigSslKey = - new HTTP_SERVICE_CONFIG_SSL_KEY(pIpPort); - configSslSet.KeyDesc = httpServiceConfigSslKey; - - IntPtr pInputConfigInfo = - Marshal.AllocCoTaskMem( - Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_SSL_SET))); - Marshal.StructureToPtr(configSslSet, pInputConfigInfo, false); - - try + var retVal = HttpDeleteServiceConfiguration(IntPtr.Zero, + HTTP_SERVICE_CONFIG_Id.HttpServiceConfigSSLCertInfo, + pInputConfigInfo, + Marshal.SizeOf(configSslSet), + IntPtr.Zero); + ThrowWin32ExceptionIfError(retVal); + } + finally + { + Marshal.FreeCoTaskMem(pInputConfigInfo); + if (sockAddrHandle.IsAllocated) { - uint retVal = HttpDeleteServiceConfiguration(IntPtr.Zero, - HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo, - pInputConfigInfo, - Marshal.SizeOf(configSslSet), - IntPtr.Zero); - ThrowWin32ExceptionIfError(retVal); - } - finally - { - Marshal.FreeCoTaskMem(pInputConfigInfo); - if (sockAddrHandle.IsAllocated) - sockAddrHandle.Free(); + sockAddrHandle.Free(); } } - }); + } + }); } public static SslCertificateInfo[] QuerySslCertificateInfo() @@ -405,253 +432,285 @@ namespace WebserverInitalConfig CallHttpApi( delegate + { + uint token = 0; + + uint retVal; + do { - uint token = 0; + var inputConfigInfoQuery = + new HTTP_SERVICE_CONFIG_SSL_QUERY + { + QueryDesc = HTTP_SERVICE_CONFIG_QUERY_TYPE.HttpServiceConfigQueryNext, + dwToken = token, + }; - uint retVal; - do + var pInputConfigInfo = + Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_SSL_QUERY))); + Marshal.StructureToPtr(inputConfigInfoQuery, pInputConfigInfo, false); + + var pOutputConfigInfo = IntPtr.Zero; + var returnLength = 0; + + const HTTP_SERVICE_CONFIG_Id queryType = HTTP_SERVICE_CONFIG_Id.HttpServiceConfigSSLCertInfo; + + try { - HTTP_SERVICE_CONFIG_SSL_QUERY inputConfigInfoQuery = - new HTTP_SERVICE_CONFIG_SSL_QUERY - { - QueryDesc = HTTP_SERVICE_CONFIG_QUERY_TYPE.HttpServiceConfigQueryNext, - dwToken = token, - }; - - IntPtr pInputConfigInfo = - Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_SSL_QUERY))); - Marshal.StructureToPtr(inputConfigInfoQuery, pInputConfigInfo, false); - - IntPtr pOutputConfigInfo = IntPtr.Zero; - int returnLength = 0; - - const HTTP_SERVICE_CONFIG_ID queryType = HTTP_SERVICE_CONFIG_ID.HttpServiceConfigSSLCertInfo; - - try + var inputConfigInfoSize = Marshal.SizeOf(inputConfigInfoQuery); + retVal = HttpQueryServiceConfiguration(IntPtr.Zero, + queryType, + pInputConfigInfo, + inputConfigInfoSize, + pOutputConfigInfo, + returnLength, + out returnLength, + IntPtr.Zero); + if (ERROR_NO_MORE_ITEMS == retVal) { - int inputConfigInfoSize = Marshal.SizeOf(inputConfigInfoQuery); - retVal = HttpQueryServiceConfiguration(IntPtr.Zero, - queryType, - pInputConfigInfo, - inputConfigInfoSize, - pOutputConfigInfo, - returnLength, - out returnLength, - IntPtr.Zero); - if (ERROR_NO_MORE_ITEMS == retVal) - break; - if (ERROR_INSUFFICIENT_BUFFER == retVal) + break; + } + + if (ERROR_INSUFFICIENT_BUFFER == retVal) + { + pOutputConfigInfo = Marshal.AllocCoTaskMem(returnLength); + + try { - pOutputConfigInfo = Marshal.AllocCoTaskMem(returnLength); - - try - { - retVal = HttpQueryServiceConfiguration(IntPtr.Zero, - queryType, - pInputConfigInfo, - inputConfigInfoSize, - pOutputConfigInfo, - returnLength, - out returnLength, - IntPtr.Zero); - ThrowWin32ExceptionIfError(retVal); - - var outputConfigInfo = (HTTP_SERVICE_CONFIG_SSL_SET)Marshal.PtrToStructure( - pOutputConfigInfo, typeof(HTTP_SERVICE_CONFIG_SSL_SET)); - - byte[] hash = new byte[outputConfigInfo.ParamDesc.SslHashLength]; - Marshal.Copy(outputConfigInfo.ParamDesc.pSslHash, hash, 0, hash.Length); - - Guid appId = outputConfigInfo.ParamDesc.AppId; - string storeName = outputConfigInfo.ParamDesc.pSslCertStoreName; - IPEndPoint ipPort = ReadSockaddrStructure(outputConfigInfo.KeyDesc.pIpPort); - - var resultItem = new SslCertificateInfo - { - AppId = appId, - Hash = hash, - StoreName = storeName, - IpPort = ipPort - }; - result.Add(resultItem); - token++; - } - finally - { - Marshal.FreeCoTaskMem(pOutputConfigInfo); - } - } - else + retVal = HttpQueryServiceConfiguration(IntPtr.Zero, + queryType, + pInputConfigInfo, + inputConfigInfoSize, + pOutputConfigInfo, + returnLength, + out returnLength, + IntPtr.Zero); ThrowWin32ExceptionIfError(retVal); + + var outputConfigInfo = (HTTP_SERVICE_CONFIG_SSL_SET)Marshal.PtrToStructure( + pOutputConfigInfo, typeof(HTTP_SERVICE_CONFIG_SSL_SET)); + + var hash = new byte[outputConfigInfo.ParamDesc.SslHashLength]; + Marshal.Copy(outputConfigInfo.ParamDesc.pSslHash, hash, 0, hash.Length); + + var appId = outputConfigInfo.ParamDesc.AppId; + var storeName = outputConfigInfo.ParamDesc.pSslCertStoreName; + var ipPort = ReadSockaddrStructure(outputConfigInfo.KeyDesc.pIpPort); + + var resultItem = new SslCertificateInfo + { + AppId = appId, + Hash = hash, + StoreName = storeName, + IpPort = ipPort + }; + result.Add(resultItem); + token++; + } + finally + { + Marshal.FreeCoTaskMem(pOutputConfigInfo); + } } - finally + else { - Marshal.FreeCoTaskMem(pInputConfigInfo); + ThrowWin32ExceptionIfError(retVal); } - } while (NOERROR == retVal); - }); + } + finally + { + Marshal.FreeCoTaskMem(pInputConfigInfo); + } + } while (NOERROR == retVal); + }); return result.ToArray(); } private static HTTP_SERVICE_CONFIG_URLACL_SET QueryReservation(string networkURL) { - if (String.IsNullOrEmpty(networkURL)) + if (string.IsNullOrEmpty(networkURL)) + { throw new ArgumentNullException("networkURL"); - HTTP_SERVICE_CONFIG_URLACL_SET res = new HTTP_SERVICE_CONFIG_URLACL_SET {KeyDesc = new HTTP_SERVICE_CONFIG_URLACL_KEY("")}; + } + + var res = new HTTP_SERVICE_CONFIG_URLACL_SET { KeyDesc = new HTTP_SERVICE_CONFIG_URLACL_KEY("") }; CallHttpApi( delegate + { + var inputquery = new HTTP_SERVICE_CONFIG_URLACL_QUERY { - HTTP_SERVICE_CONFIG_URLACL_QUERY inputquery = new HTTP_SERVICE_CONFIG_URLACL_QUERY - { - QueryDesc = HTTP_SERVICE_CONFIG_QUERY_TYPE.HttpServiceConfigQueryExact, - KeyDesc = new HTTP_SERVICE_CONFIG_URLACL_KEY(networkURL) - }; + QueryDesc = HTTP_SERVICE_CONFIG_QUERY_TYPE.HttpServiceConfigQueryExact, + KeyDesc = new HTTP_SERVICE_CONFIG_URLACL_KEY(networkURL) + }; - IntPtr pInputQuery = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_URLACL_QUERY))); - Marshal.StructureToPtr(inputquery, pInputQuery, false); - IntPtr pOutputConfigInfo = IntPtr.Zero; - int returnLength = 0; - try + var pInputQuery = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_URLACL_QUERY))); + Marshal.StructureToPtr(inputquery, pInputQuery, false); + var pOutputConfigInfo = IntPtr.Zero; + var returnLength = 0; + try + { + var retVal = HttpQueryServiceConfiguration(IntPtr.Zero, + HTTP_SERVICE_CONFIG_Id.HttpServiceConfigUrlAclInfo, + pInputQuery, + Marshal.SizeOf(inputquery), + pOutputConfigInfo, + returnLength, + out returnLength, + IntPtr.Zero); + if (ERROR_INSUFFICIENT_BUFFER == retVal) { - uint retVal = HttpQueryServiceConfiguration(IntPtr.Zero, - HTTP_SERVICE_CONFIG_ID.HttpServiceConfigUrlAclInfo, - pInputQuery, - Marshal.SizeOf(inputquery), - pOutputConfigInfo, - returnLength, - out returnLength, - IntPtr.Zero); - if (ERROR_INSUFFICIENT_BUFFER == retVal) + pOutputConfigInfo = Marshal.AllocCoTaskMem(returnLength); + retVal = HttpQueryServiceConfiguration(IntPtr.Zero, + HTTP_SERVICE_CONFIG_Id.HttpServiceConfigUrlAclInfo, + pInputQuery, + Marshal.SizeOf(inputquery), + pOutputConfigInfo, + returnLength, + out returnLength, + IntPtr.Zero); + if (ERROR_FILE_NOT_FOUND == retVal) { - pOutputConfigInfo = Marshal.AllocCoTaskMem(returnLength); - retVal = HttpQueryServiceConfiguration(IntPtr.Zero, - HTTP_SERVICE_CONFIG_ID.HttpServiceConfigUrlAclInfo, - pInputQuery, - Marshal.SizeOf(inputquery), - pOutputConfigInfo, - returnLength, - out returnLength, - IntPtr.Zero); - if (ERROR_FILE_NOT_FOUND == retVal) - return; - ThrowWin32ExceptionIfError(retVal); - res = (HTTP_SERVICE_CONFIG_URLACL_SET)Marshal.PtrToStructure(pOutputConfigInfo, typeof(HTTP_SERVICE_CONFIG_URLACL_SET)); + return; } - else if (ERROR_FILE_NOT_FOUND != retVal) - ThrowWin32ExceptionIfError(retVal); + + ThrowWin32ExceptionIfError(retVal); + res = (HTTP_SERVICE_CONFIG_URLACL_SET)Marshal.PtrToStructure(pOutputConfigInfo, typeof(HTTP_SERVICE_CONFIG_URLACL_SET)); } - finally + else if (ERROR_FILE_NOT_FOUND != retVal) { - Marshal.FreeCoTaskMem(pInputQuery); - if (pOutputConfigInfo != IntPtr.Zero) - Marshal.FreeCoTaskMem(pOutputConfigInfo); + ThrowWin32ExceptionIfError(retVal); } } - ); + finally + { + Marshal.FreeCoTaskMem(pInputQuery); + if (pOutputConfigInfo != IntPtr.Zero) + { + Marshal.FreeCoTaskMem(pOutputConfigInfo); + } + } + } + ); return res; } public static uint DeleteReservation(string networkURL) { - uint retVal = NOERROR; - if (String.IsNullOrEmpty(networkURL)) + var retVal = NOERROR; + if (string.IsNullOrEmpty(networkURL)) + { throw new ArgumentNullException("networkURL"); - HTTP_SERVICE_CONFIG_URLACL_SET oldReservation = QueryReservation(networkURL); + } + + var oldReservation = QueryReservation(networkURL); if (oldReservation.KeyDesc.pUrlPrefix == "" && networkURL.Contains("+")) { networkURL = networkURL.Replace('+', '*'); oldReservation = QueryReservation(networkURL); } + if (oldReservation.KeyDesc.pUrlPrefix == "") + { return ERROR_FILE_NOT_FOUND; + } + CallHttpApi( delegate + { + var pInputConfigInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_URLACL_SET))); + Marshal.StructureToPtr(oldReservation, pInputConfigInfo, false); + try { - IntPtr pInputConfigInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_URLACL_SET))); - Marshal.StructureToPtr(oldReservation, pInputConfigInfo, false); - try - { - retVal = HttpDeleteServiceConfiguration(IntPtr.Zero, - HTTP_SERVICE_CONFIG_ID.HttpServiceConfigUrlAclInfo, - pInputConfigInfo, - Marshal.SizeOf(oldReservation), - IntPtr.Zero); - } - finally - { - Marshal.FreeCoTaskMem(pInputConfigInfo); - } - }); + retVal = HttpDeleteServiceConfiguration(IntPtr.Zero, + HTTP_SERVICE_CONFIG_Id.HttpServiceConfigUrlAclInfo, + pInputConfigInfo, + Marshal.SizeOf(oldReservation), + IntPtr.Zero); + } + finally + { + Marshal.FreeCoTaskMem(pInputConfigInfo); + } + }); return retVal; } public static void ReserveURL(string networkURL, string securityDescriptor) { - if (String.IsNullOrEmpty(networkURL)) + if (string.IsNullOrEmpty(networkURL)) + { throw new ArgumentNullException("networkURL"); - if (String.IsNullOrEmpty(securityDescriptor)) + } + + if (string.IsNullOrEmpty(securityDescriptor)) + { throw new ArgumentNullException("securityDescriptor"); + } CallHttpApi( delegate + { + uint retVal; + + var keyDesc = new HTTP_SERVICE_CONFIG_URLACL_KEY(networkURL); + var paramDesc = new HTTP_SERVICE_CONFIG_URLACL_PARAM(securityDescriptor); + + var inputConfigInfoSet = new HTTP_SERVICE_CONFIG_URLACL_SET { KeyDesc = keyDesc, ParamDesc = paramDesc }; + + var pInputConfigInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_URLACL_SET))); + Marshal.StructureToPtr(inputConfigInfoSet, pInputConfigInfo, false); + try { - uint retVal; + retVal = HttpSetServiceConfiguration(IntPtr.Zero, + HTTP_SERVICE_CONFIG_Id.HttpServiceConfigUrlAclInfo, + pInputConfigInfo, + Marshal.SizeOf(inputConfigInfoSet), + IntPtr.Zero); - HTTP_SERVICE_CONFIG_URLACL_KEY keyDesc = new HTTP_SERVICE_CONFIG_URLACL_KEY(networkURL); - HTTP_SERVICE_CONFIG_URLACL_PARAM paramDesc = new HTTP_SERVICE_CONFIG_URLACL_PARAM(securityDescriptor); - - HTTP_SERVICE_CONFIG_URLACL_SET inputConfigInfoSet = new HTTP_SERVICE_CONFIG_URLACL_SET {KeyDesc = keyDesc, ParamDesc = paramDesc}; - - IntPtr pInputConfigInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(HTTP_SERVICE_CONFIG_URLACL_SET))); - Marshal.StructureToPtr(inputConfigInfoSet, pInputConfigInfo, false); - try + if (ERROR_ALREADY_EXISTS == retVal) { - retVal = HttpSetServiceConfiguration(IntPtr.Zero, - HTTP_SERVICE_CONFIG_ID.HttpServiceConfigUrlAclInfo, - pInputConfigInfo, - Marshal.SizeOf(inputConfigInfoSet), - IntPtr.Zero); - - if (ERROR_ALREADY_EXISTS == retVal) + retVal = DeleteReservation(networkURL); + if (ERROR_FILE_NOT_FOUND == retVal) { - retVal = DeleteReservation(networkURL); - if (ERROR_FILE_NOT_FOUND == retVal) - { - string networkURLOld = networkURL.Contains("https") ? networkURL.Replace("https", "http") : - networkURL.Replace("http", "https"); - retVal = DeleteReservation(networkURLOld); - } + var networkURLOld = networkURL.Contains("https") ? networkURL.Replace("https", "http") : + networkURL.Replace("http", "https"); + retVal = DeleteReservation(networkURLOld); + } - if (NOERROR == retVal) - { - retVal = HttpSetServiceConfiguration(IntPtr.Zero, - HTTP_SERVICE_CONFIG_ID.HttpServiceConfigUrlAclInfo, - pInputConfigInfo, - Marshal.SizeOf(inputConfigInfoSet), - IntPtr.Zero); - } + if (NOERROR == retVal) + { + retVal = HttpSetServiceConfiguration(IntPtr.Zero, + HTTP_SERVICE_CONFIG_Id.HttpServiceConfigUrlAclInfo, + pInputConfigInfo, + Marshal.SizeOf(inputConfigInfoSet), + IntPtr.Zero); } } - finally - { - Marshal.FreeCoTaskMem(pInputConfigInfo); - } - if (NOERROR != retVal) - ThrowWin32ExceptionIfError(retVal); - }); + } + finally + { + Marshal.FreeCoTaskMem(pInputConfigInfo); + } + + if (NOERROR != retVal) + { + ThrowWin32ExceptionIfError(retVal); + } + }); } #endregion private static void ThrowWin32ExceptionIfError(uint retVal) { if (NOERROR != retVal) + { throw new Win32Exception(Convert.ToInt32(retVal)); + } } private static void CallHttpApi(Action body) { - uint retVal = HttpInitialize(HttpApiVersion, HTTP_INITIALIZE_CONFIG, IntPtr.Zero); + var retVal = HttpInitialize(HttpApiVersion, HTTP_INITIALIZE_CONFIG, IntPtr.Zero); ThrowWin32ExceptionIfError(retVal); try @@ -672,13 +731,16 @@ namespace WebserverInitalConfig /// When the handle goes out of scope you must explicitly release it by calling the Free method; otherwise, memory leaks may occur. private static GCHandle CreateSockaddrStructure(IPEndPoint ipEndPoint) { - SocketAddress socketAddress = ipEndPoint.Serialize(); + var socketAddress = ipEndPoint.Serialize(); // use an array of bytes instead of the sockaddr structure - byte[] sockAddrStructureBytes = new byte[socketAddress.Size]; - GCHandle sockAddrHandle = GCHandle.Alloc(sockAddrStructureBytes, GCHandleType.Pinned); - for (int i = 0; i < socketAddress.Size; ++i) + var sockAddrStructureBytes = new byte[socketAddress.Size]; + var sockAddrHandle = GCHandle.Alloc(sockAddrStructureBytes, GCHandleType.Pinned); + for (var i = 0; i < socketAddress.Size; ++i) + { sockAddrStructureBytes[i] = socketAddress[i]; + } + return sockAddrHandle; } @@ -689,8 +751,8 @@ namespace WebserverInitalConfig /// IP address and port number private static IPEndPoint ReadSockaddrStructure(IntPtr pSockaddrStructure) { - short sAddressFamily = Marshal.ReadInt16(pSockaddrStructure); - AddressFamily addressFamily = (AddressFamily)sAddressFamily; + var sAddressFamily = Marshal.ReadInt16(pSockaddrStructure); + var addressFamily = (AddressFamily)sAddressFamily; int sockAddrSructureSize; IPEndPoint ipEndPointAny; @@ -712,16 +774,18 @@ namespace WebserverInitalConfig // get bytes of the sockadrr structure - byte[] sockAddrSructureBytes = new byte[sockAddrSructureSize]; + var sockAddrSructureBytes = new byte[sockAddrSructureSize]; Marshal.Copy(pSockaddrStructure, sockAddrSructureBytes, 0, sockAddrSructureSize); // create SocketAddress from bytes var socketAddress = new SocketAddress(AddressFamily.Unspecified, sockAddrSructureSize); - for (int i = 0; i < sockAddrSructureSize; i++) + for (var i = 0; i < sockAddrSructureSize; i++) + { socketAddress[i] = sockAddrSructureBytes[i]; + } // create IPEndPoint from SocketAddress - IPEndPoint result = (IPEndPoint)ipEndPointAny.Create(socketAddress); + var result = (IPEndPoint)ipEndPointAny.Create(socketAddress); return result; } diff --git a/WebserverInitalConfig/Program.cs b/WebserverInitalConfig/Program.cs index 2223c5e8..8c83c27a 100644 --- a/WebserverInitalConfig/Program.cs +++ b/WebserverInitalConfig/Program.cs @@ -30,7 +30,7 @@ namespace WebserverInitalConfig private static void Main(string[] args) // ReSharper restore InconsistentNaming { - int result = 0; + var result = 0; try { int port; @@ -41,35 +41,39 @@ namespace WebserverInitalConfig } else { - String exeName = args[0]; - bool isSecure = (args[2].ToLower() == "true"); - bool doReserve = (args.Length >= 4 && args[3].ToLower() == "true"); - CConfigHttpApi config = new CConfigHttpApi(exeName, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, exeName), "0.0.0.0", port, true); + var exeName = args[0]; + var isSecure = args[2].ToLower() == "true"; + var doReserve = args.Length >= 4 && args[3].ToLower() == "true"; + var config = new CConfigHttpApi(exeName, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, exeName), "0.0.0.0", port, true); try { config.AddFirewallRule(); if (isSecure) + { config.CreateAndAddCert(Dns.GetHostName()); + } if (doReserve || CConfigHttpApi.IsAdministrator()) + { config.ReserveUrl(isSecure); + } } catch (AuthenticationException) { - ProcessStartInfo proc = new ProcessStartInfo - { - UseShellExecute = true, - WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory, - FileName = AppDomain.CurrentDomain.FriendlyName, - Arguments = String.Join(" ", args), - Verb = "runas", - CreateNoWindow = true, - WindowStyle = ProcessWindowStyle.Hidden, - }; + var proc = new ProcessStartInfo + { + UseShellExecute = true, + WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory, + FileName = AppDomain.CurrentDomain.FriendlyName, + Arguments = String.Join(" ", args), + Verb = "runas", + CreateNoWindow = true, + WindowStyle = ProcessWindowStyle.Hidden, + }; try { - using (Process p = Process.Start(proc)) + using (var p = Process.Start(proc)) { p.WaitForExit(); result = p.ExitCode; @@ -90,6 +94,7 @@ namespace WebserverInitalConfig MessageBox.Show("Error while installing server: " + e.Message + "\r\n\r\nIn " + e.TargetSite + "\r\nBacktrace: " + e.StackTrace); result = -4; } + Environment.Exit(result); } } diff --git a/WebserverInitalConfig/Properties/AssemblyInfo.cs b/WebserverInitalConfig/Properties/AssemblyInfo.cs index 4a79c1a6..288bcc8b 100644 --- a/WebserverInitalConfig/Properties/AssemblyInfo.cs +++ b/WebserverInitalConfig/Properties/AssemblyInfo.cs @@ -37,7 +37,7 @@ using System.Runtime.InteropServices; [assembly: ComVisible(false)] -// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird +// Die folgende GUId bestimmt die Id der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("b2df9255-3927-4125-ab3c-23c35794b04d")] diff --git a/WebserverInitalConfig/WebserverInitalConfig.csproj b/WebserverInitalConfig/WebserverInitalConfig.csproj index 6f94b8c0..0e2ae10e 100644 --- a/WebserverInitalConfig/WebserverInitalConfig.csproj +++ b/WebserverInitalConfig/WebserverInitalConfig.csproj @@ -24,6 +24,7 @@ prompt 4 false + 9.0 AnyCPU @@ -34,6 +35,7 @@ prompt 4 false + 9.0 Vocaluxe.ico @@ -80,4 +82,4 @@ --> - + \ No newline at end of file