diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..88001db --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,27 @@ +name: Build + +on: + push: + pull_request: + workflow_dispatch: + +jobs: + build: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: 8.0.x + + - name: Test + run: dotnet test tests/BmsConfig.Tests -c Release + + - name: Build Config.exe + run: dotnet build src/BmsConfig -c Release + + - uses: actions/upload-artifact@v4 + with: + name: Config + path: src/BmsConfig/bin/Release/net48/Config.exe diff --git a/BmsConfig.sln b/BmsConfig.sln new file mode 100644 index 0000000..5e84b38 --- /dev/null +++ b/BmsConfig.sln @@ -0,0 +1,33 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BmsConfig", "src\BmsConfig\BmsConfig.csproj", "{3F6A1E2B-7C4D-4B8E-9A21-5D0C8E7F1A34}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{7C1BC3C5-1EFA-4868-96B2-A8BC16B97E68}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BmsConfig.Tests", "tests\BmsConfig.Tests\BmsConfig.Tests.csproj", "{5CA0860D-108F-425E-BD4A-DDB5459AF34C}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3F6A1E2B-7C4D-4B8E-9A21-5D0C8E7F1A34}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3F6A1E2B-7C4D-4B8E-9A21-5D0C8E7F1A34}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3F6A1E2B-7C4D-4B8E-9A21-5D0C8E7F1A34}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3F6A1E2B-7C4D-4B8E-9A21-5D0C8E7F1A34}.Release|Any CPU.Build.0 = Release|Any CPU + {5CA0860D-108F-425E-BD4A-DDB5459AF34C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5CA0860D-108F-425E-BD4A-DDB5459AF34C}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5CA0860D-108F-425E-BD4A-DDB5459AF34C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5CA0860D-108F-425E-BD4A-DDB5459AF34C}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {5CA0860D-108F-425E-BD4A-DDB5459AF34C} = {7C1BC3C5-1EFA-4868-96B2-A8BC16B97E68} + EndGlobalSection +EndGlobal diff --git a/README.md b/README.md index 3066cb5..a7824aa 100644 --- a/README.md +++ b/README.md @@ -12,4 +12,32 @@ New Config tool for Falcon BMS -- replacement for the legacy F4Patch-based Confi ![Opening Screen](.github/images/Mockup1.png) -![Listview Screen](.github/images/Mockup2.png) \ No newline at end of file +![Listview Screen](.github/images/Mockup2.png) +### Building + +Requires the .NET SDK (8.0 or later) on Windows -- or Visual Studio 2022 -- and produces a single, dependency-free `Config.exe` targeting .NET Framework 4.8 (AnyCPU, 64-bit preferred): + +``` +dotnet build src/BmsConfig -c Release +``` + +Output: `src/BmsConfig/bin/Release/net48/Config.exe`. Copy it into the root of a BMS install (the registry `baseDir`), next to the `User` folder. + +Unit tests for the cfg parser/model run anywhere (including Linux): + +``` +dotnet test tests/BmsConfig.Tests +``` + +Every push is built on GitHub Actions (`.github/workflows/build.yml`); `Config.exe` is attached to each run as an artifact. + +### Source layout + +| Path | Purpose | +| --- | --- | +| `src/BmsConfig/Core/CfgDocument.cs` | Line-preserving cfg parser/editor: comments, blank lines and ordering round-trip untouched; edits replace only the value token; new lines go above the Launcher cut line. UTF-8, written without BOM. | +| `src/BmsConfig/Core/ValueConverter.cs` | Datatypes (from the `g_b`/`g_n`/`g_f`/`g_s` name prefix), `Range:[..]` and `Enum:[..]` parsing, input validation/conversion (hex ints, no float exponents/NaN/Inf, fancy-quote stripping), and the feature-flag regexes. | +| `src/BmsConfig/Core/ConfigSet.cs` | Merges `Falcon BMS.cfg` → `User.cfg` → `VR.cfg` (last writer wins), assigns categories, and writes edits back to disk immediately. | +| `src/BmsConfig/Core/BmsInstalls.cs` | Finds side-by-side installs under `HKLM\SOFTWARE\WOW6432Node\Benchmark Sims`. | +| `src/BmsConfig/MainWindow.xaml(.cs)` | The master/detail UI. | +| `src/BmsConfig/Themes/` | Dark / Light palettes, and the control styles. | diff --git a/src/BmsConfig/App.xaml b/src/BmsConfig/App.xaml new file mode 100644 index 0000000..b4083cf --- /dev/null +++ b/src/BmsConfig/App.xaml @@ -0,0 +1,14 @@ + + + + + + + + + + + diff --git a/src/BmsConfig/App.xaml.cs b/src/BmsConfig/App.xaml.cs new file mode 100644 index 0000000..2e2b98b --- /dev/null +++ b/src/BmsConfig/App.xaml.cs @@ -0,0 +1,24 @@ +using System.Windows; +using System.Windows.Threading; + +namespace BmsConfig +{ + public partial class App : Application + { + protected override void OnStartup(StartupEventArgs e) + { + // Dark.xaml is loaded statically (so the designer has a palette); replace it with the user's choice. + Resources.MergedDictionaries.RemoveAt(0); + ThemeManager.Initialize(); + + DispatcherUnhandledException += OnUnhandledException; + base.OnStartup(e); + } + + void OnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) + { + MessageBox.Show(e.Exception.ToString(), "Unexpected error", MessageBoxButton.OK, MessageBoxImage.Error); + e.Handled = true; + } + } +} diff --git a/src/BmsConfig/BmsConfig.csproj b/src/BmsConfig/BmsConfig.csproj new file mode 100644 index 0000000..820c4d2 --- /dev/null +++ b/src/BmsConfig/BmsConfig.csproj @@ -0,0 +1,42 @@ + + + + WinExe + net48 + true + Config + BmsConfig + 7.3 + + + AnyCPU + false + + app.manifest + Config.ico + + Falcon BMS Config Editor + Benchmark Sims + 1.0.0 + + + false + false + en + embedded + + + true + + + + + + + + + + + + + diff --git a/src/BmsConfig/Config.ico b/src/BmsConfig/Config.ico new file mode 100644 index 0000000..974dfb5 Binary files /dev/null and b/src/BmsConfig/Config.ico differ diff --git a/src/BmsConfig/Core/BmsInstalls.cs b/src/BmsConfig/Core/BmsInstalls.cs new file mode 100644 index 0000000..02a1e62 --- /dev/null +++ b/src/BmsConfig/Core/BmsInstalls.cs @@ -0,0 +1,99 @@ +using System; +using System.Collections.Generic; +using System.IO; +using Microsoft.Win32; + +namespace BmsConfig.Core +{ + public sealed class BmsInstall + { + public string Name { get; private set; } + public string BaseDir { get; private set; } + public string ConfigFolder { get { return Path.Combine(BaseDir, "User", "Config"); } } + + public BmsInstall(string name, string baseDir) + { + Name = name; + BaseDir = baseDir; + } + + public override string ToString() { return Name + " - " + BaseDir; } + } + + /// + /// Finds the side-by-side BMS installs, listed under HKLM\SOFTWARE\WOW6432Node\Benchmark Sims. + /// + public static class BmsInstalls + { + public static List Discover() + { + List installs = new List(); + try + { + // The 32-bit registry view maps to WOW6432Node from a 64-bit process, and to the + // native hive from a 32-bit process -- so this works regardless of process bitness. + using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)) + using (RegistryKey root = hklm.OpenSubKey(@"SOFTWARE\Benchmark Sims")) + { + if (root != null) + { + foreach (string subKeyName in root.GetSubKeyNames()) + { + using (RegistryKey sub = root.OpenSubKey(subKeyName)) + { + string baseDir = (sub != null) ? sub.GetValue("baseDir") as string : null; + if (!string.IsNullOrWhiteSpace(baseDir)) + installs.Add(new BmsInstall(subKeyName, baseDir.Trim())); + } + } + } + } + } + catch (Exception) + { + // No registry (or no access) -- the user can still browse to a folder. + } + + installs.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); + return installs; + } + + /// The install whose baseDir contains the given exe directory, if any. + public static BmsInstall FindContaining(IEnumerable installs, string exeDir) + { + string dir = NormalizeDir(exeDir); + if (dir == null) + return null; + + BmsInstall best = null; + foreach (BmsInstall install in installs) + { + string baseDir = NormalizeDir(install.BaseDir); + if (baseDir == null) + continue; + + if (string.Equals(dir, baseDir, StringComparison.OrdinalIgnoreCase) + || dir.StartsWith(baseDir + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) + { + if (best == null || baseDir.Length > NormalizeDir(best.BaseDir).Length) + best = install; + } + } + return best; + } + + static string NormalizeDir(string dir) + { + if (string.IsNullOrWhiteSpace(dir)) + return null; + try + { + return Path.GetFullPath(dir).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + } + catch (Exception) + { + return null; + } + } + } +} diff --git a/src/BmsConfig/Core/CfgDocument.cs b/src/BmsConfig/Core/CfgDocument.cs new file mode 100644 index 0000000..39d8e9b --- /dev/null +++ b/src/BmsConfig/Core/CfgDocument.cs @@ -0,0 +1,270 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; + +namespace BmsConfig.Core +{ + public enum CfgLineKind + { + /// Blank line, comment, or anything that doesn't conform to the grammar. + Other, + /// A comment line of the form "// Some Category //". + Category, + /// A well-formed "set {name} {value}" line. + Set, + /// The Launcher's cut line, in Falcon BMS User.cfg. + CutLine, + } + + /// + /// One physical line of a cfg file. The original text is always retained verbatim, + /// so that unmodified lines round-trip byte-for-byte. + /// + public sealed class CfgLine + { + public string Text { get; internal set; } + public CfgLineKind Kind { get; internal set; } + + // Kind == Set + public string Name { get; internal set; } + public string RawValue { get; internal set; } + public string Description { get; internal set; } + internal int ValueStart { get; set; } + internal int ValueLength { get; set; } + + // Kind == Category + public string CategoryName { get; internal set; } + + public override string ToString() { return Text; } + } + + /// + /// A cfg file, as an ordered list of lines. This is an *editor* model: comments, blank lines, + /// unknown lines and ordering are all preserved; edits touch only the value token of a line, + /// or insert/remove whole "set" lines. + /// + public sealed class CfgDocument + { + public const string CutLineMarker = "LAUNCHER OVERRIDES BEGIN HERE"; + + // set {name} {value} [// description | # description] + static readonly Regex s_setLine = new Regex( + @"^\s*set\s+(?[A-Za-z_][A-Za-z0-9_]*)\s+(?""[^""]*""|[^\s""]+)\s*(?:(?://|#)\s?(?.*))?$", + RegexOptions.CultureInvariant); + + readonly List _lines = new List(); + + public string FilePath { get; private set; } + public IReadOnlyList Lines { get { return _lines; } } + + string _eol = "\r\n"; + bool _trailingNewline = true; + + public CfgDocument() { } + + public static CfgDocument Load(string path) + { + byte[] bytes = File.ReadAllBytes(path); + CfgDocument doc = Parse(DecodeUtf8(bytes)); + doc.FilePath = path; + return doc; + } + + /// Loads the file if it exists, otherwise returns an empty document bound to that path. + public static CfgDocument LoadOrCreate(string path) + { + if (File.Exists(path)) + return Load(path); + + return new CfgDocument { FilePath = path }; + } + + public static CfgDocument Parse(string text) + { + CfgDocument doc = new CfgDocument(); + if (string.IsNullOrEmpty(text)) + return doc; + + doc._eol = text.Contains("\r\n") ? "\r\n" : "\n"; + doc._trailingNewline = text.EndsWith("\n", StringComparison.Ordinal); + + string[] rawLines = text.Split('\n'); + int count = rawLines.Length; + if (doc._trailingNewline) + count--; // final empty element after the trailing newline + + for (int i = 0; i < count; i++) + doc._lines.Add(ParseLine(rawLines[i].TrimEnd('\r'))); + + return doc; + } + + static string DecodeUtf8(byte[] bytes) + { + int offset = 0; + if (bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF) + offset = 3; + + return new UTF8Encoding(false, false).GetString(bytes, offset, bytes.Length - offset); + } + + public static CfgLine ParseLine(string text) + { + CfgLine line = new CfgLine { Text = text, Kind = CfgLineKind.Other }; + string trimmed = text.Trim(); + + if (trimmed.IndexOf(CutLineMarker, StringComparison.OrdinalIgnoreCase) >= 0 + && (trimmed.StartsWith("//", StringComparison.Ordinal) || trimmed.StartsWith("#", StringComparison.Ordinal))) + { + line.Kind = CfgLineKind.CutLine; + return line; + } + + if (trimmed.Length >= 4 + && trimmed.StartsWith("//", StringComparison.Ordinal) + && trimmed.EndsWith("//", StringComparison.Ordinal)) + { + // Strip the surrounding ascii-art slashes; an empty remainder (eg. "// //" or "/////") is just decoration. + string inner = trimmed.Trim('/', ' ', '\t'); + if (inner.Length > 0) + { + line.Kind = CfgLineKind.Category; + line.CategoryName = inner; + } + return line; + } + + Match m = s_setLine.Match(text); + if (m.Success) + { + string name = m.Groups["name"].Value; + string value = m.Groups["value"].Value; + + // Values that don't conform to the param's datatype are ignored (treated as comments). + if (!ValueConverter.IsValidCfgToken(ParamTypes.FromName(name), value)) + return line; + + line.Kind = CfgLineKind.Set; + line.Name = name; + line.RawValue = value; + line.ValueStart = m.Groups["value"].Index; + line.ValueLength = m.Groups["value"].Length; + line.Description = m.Groups["desc"].Success ? m.Groups["desc"].Value.Trim() : null; + } + + return line; + } + + /// Index of the Launcher cut line, or -1 if none. + public int CutLineIndex + { + get + { + for (int i = 0; i < _lines.Count; i++) + if (_lines[i].Kind == CfgLineKind.CutLine) + return i; + return -1; + } + } + + /// + /// The effective (last-writer-wins) set line for the given param, or null. + /// If aboveCutLine is true, lines at or below the Launcher cut line are not considered. + /// + public CfgLine FindLast(string name, bool aboveCutLine = false) + { + int index = FindLastIndex(name, aboveCutLine); + return index >= 0 ? _lines[index] : null; + } + + int FindLastIndex(string name, bool aboveCutLine) + { + int end = _lines.Count; + if (aboveCutLine) + { + int cut = CutLineIndex; + if (cut >= 0) + end = cut; + } + + for (int i = end - 1; i >= 0; i--) + { + CfgLine line = _lines[i]; + if (line.Kind == CfgLineKind.Set && string.Equals(line.Name, name, StringComparison.OrdinalIgnoreCase)) + return i; + } + return -1; + } + + /// + /// Sets a param's value. If a set line already exists, only its value token is replaced (preserving + /// whitespace and trailing comment). Otherwise a new line is inserted -- above the Launcher cut line + /// if there is one, else at the end of the file. + /// + /// The value as it should appear in the file (eg. already quoted for strings). + /// If true, never edit or insert at/below the Launcher cut line. + public void SetValue(string name, string serializedValue, bool respectCutLine) + { + int index = FindLastIndex(name, respectCutLine); + if (index >= 0) + { + CfgLine old = _lines[index]; + string text = old.Text.Substring(0, old.ValueStart) + serializedValue + old.Text.Substring(old.ValueStart + old.ValueLength); + _lines[index] = ParseLine(text); + return; + } + + CfgLine newLine = ParseLine("set " + name + " " + serializedValue); + + int cut = respectCutLine ? CutLineIndex : -1; + int insertAt = (cut >= 0) ? cut : _lines.Count; + + // Keep any blank lines separating the block above, from the cut line (or end of file). + while (insertAt > 0 && _lines[insertAt - 1].Text.Trim().Length == 0) + insertAt--; + + _lines.Insert(insertAt, newLine); + } + + /// + /// Removes all set lines for the given param (only those above the cut line, if respectCutLine). + /// Returns the number of lines removed. + /// + public int RemoveValue(string name, bool respectCutLine) + { + int removed = 0; + int index; + while ((index = FindLastIndex(name, respectCutLine)) >= 0) + { + _lines.RemoveAt(index); + removed++; + } + return removed; + } + + public string ToText() + { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < _lines.Count; i++) + { + sb.Append(_lines[i].Text); + if (i < _lines.Count - 1 || _trailingNewline) + sb.Append(_eol); + } + return sb.ToString(); + } + + /// Saves as UTF-8, without BOM. + public void Save(string path = null) + { + path = path ?? FilePath; + if (path == null) + throw new InvalidOperationException("No file path specified."); + + File.WriteAllText(path, ToText(), new UTF8Encoding(false)); + FilePath = path; + } + } +} diff --git a/src/BmsConfig/Core/ConfigSet.cs b/src/BmsConfig/Core/ConfigSet.cs new file mode 100644 index 0000000..a492d9c --- /dev/null +++ b/src/BmsConfig/Core/ConfigSet.cs @@ -0,0 +1,274 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace BmsConfig.Core +{ + public enum CfgFile + { + Bms, + User, + Vr, + } + + public enum ValueSource + { + None, + Bms, + User, + /// From Falcon BMS User.cfg, below the Launcher cut line. + Launcher, + Vr, + } + + /// + /// One param, merged across the 3 cfg files. + /// + public sealed class ParamEntry + { + public string Name { get; internal set; } + public ParamType Type { get; internal set; } + public string Category { get; internal set; } + public string Description { get; internal set; } + public ParamConstraints Constraints { get; internal set; } + public bool IsFeatureFlag { get { return FeatureFlags.IsFeatureFlag(Name); } } + + /// Value in Falcon BMS.cfg (the baseline default), or null if not present there. + public string BmsValue { get; internal set; } + /// Effective value in Falcon BMS User.cfg (including the Launcher section), or null. + public string UserValue { get; internal set; } + /// True if the effective User.cfg value comes from below the Launcher cut line. + public bool UserValueFromLauncher { get; internal set; } + /// Effective value in Falcon BMS VR.cfg, or null. + public string VrValue { get; internal set; } + + /// Order of first appearance (Falcon BMS.cfg first, then User.cfg, then VR.cfg). + public int Ordinal { get; internal set; } + + public string GetEffectiveValue(bool includeVr) + { + ValueSource source; + return GetEffectiveValue(includeVr, out source); + } + + public string GetEffectiveValue(bool includeVr, out ValueSource source) + { + if (includeVr && VrValue != null) + { + source = ValueSource.Vr; + return VrValue; + } + if (UserValue != null) + { + source = UserValueFromLauncher ? ValueSource.Launcher : ValueSource.User; + return UserValue; + } + if (BmsValue != null) + { + source = ValueSource.Bms; + return BmsValue; + } + source = ValueSource.None; + return null; + } + } + + /// + /// The set of 3 cfg files in a BMS config folder, plus the merged (last-writer-wins) view of all params. + /// + public sealed class ConfigSet + { + public const string BmsFileName = "Falcon BMS.cfg"; + public const string UserFileName = "Falcon BMS User.cfg"; + public const string VrFileName = "Falcon BMS VR.cfg"; + public const string OtherCategory = "Other"; + + public string Folder { get; private set; } + public CfgDocument Bms { get; private set; } + public CfgDocument User { get; private set; } + public CfgDocument Vr { get; private set; } + + public IReadOnlyList Entries { get { return _entries; } } + public IReadOnlyList Categories { get { return _categories; } } + + readonly List _entries = new List(); + readonly List _categories = new List(); + readonly Dictionary _byName = new Dictionary(StringComparer.OrdinalIgnoreCase); + + public static string GetPath(string folder, CfgFile file) + { + switch (file) + { + case CfgFile.Bms: return Path.Combine(folder, BmsFileName); + case CfgFile.User: return Path.Combine(folder, UserFileName); + default: return Path.Combine(folder, VrFileName); + } + } + + /// A folder is usable if it contains Falcon BMS.cfg (the other two are optional). + public static bool IsConfigFolder(string folder) + { + return !string.IsNullOrEmpty(folder) && File.Exists(GetPath(folder, CfgFile.Bms)); + } + + public static ConfigSet Load(string folder) + { + return FromDocuments( + folder, + CfgDocument.Load(GetPath(folder, CfgFile.Bms)), + CfgDocument.LoadOrCreate(GetPath(folder, CfgFile.User)), + CfgDocument.LoadOrCreate(GetPath(folder, CfgFile.Vr))); + } + + public static ConfigSet FromDocuments(string folder, CfgDocument bms, CfgDocument user, CfgDocument vr) + { + ConfigSet set = new ConfigSet { Folder = folder, Bms = bms, User = user, Vr = vr }; + set.Merge(); + return set; + } + + public ParamEntry Find(string name) + { + ParamEntry e; + return _byName.TryGetValue(name, out e) ? e : null; + } + + public CfgDocument GetDocument(CfgFile file) + { + switch (file) + { + case CfgFile.Bms: return Bms; + case CfgFile.User: return User; + default: return Vr; + } + } + + void Merge() + { + bool hasOther = false; + + // Falcon BMS.cfg: the manifest of params, defaults, categories and descriptions. + string category = OtherCategory; + foreach (CfgLine line in Bms.Lines) + { + if (line.Kind == CfgLineKind.Category) + { + category = line.CategoryName; + } + else if (line.Kind == CfgLineKind.Set) + { + ParamEntry e = GetOrAdd(line, category); + e.BmsValue = line.RawValue; + if (!string.IsNullOrEmpty(line.Description)) + e.Description = line.Description; + if (category == OtherCategory) + hasOther = true; + } + } + + // Falcon BMS User.cfg: user overrides; unknown params get filed under "Other". + bool belowCut = false; + foreach (CfgLine line in User.Lines) + { + if (line.Kind == CfgLineKind.CutLine) + { + belowCut = true; + } + else if (line.Kind == CfgLineKind.Set) + { + ParamEntry e = GetOrAdd(line, OtherCategory); + e.UserValue = line.RawValue; + e.UserValueFromLauncher = belowCut; + if (e.Category == OtherCategory) + hasOther = true; + } + } + + // Falcon BMS VR.cfg: overrides, only when launched in VR. + foreach (CfgLine line in Vr.Lines) + { + if (line.Kind == CfgLineKind.Set) + { + ParamEntry e = GetOrAdd(line, OtherCategory); + e.VrValue = line.RawValue; + if (e.Category == OtherCategory) + hasOther = true; + } + } + + foreach (ParamEntry e in _entries) + { + e.Constraints = ParamConstraints.Parse(e.Description); + if (!_categories.Contains(e.Category) && e.Category != OtherCategory) + _categories.Add(e.Category); + } + if (hasOther) + _categories.Add(OtherCategory); + } + + ParamEntry GetOrAdd(CfgLine line, string category) + { + ParamEntry e; + if (!_byName.TryGetValue(line.Name, out e)) + { + e = new ParamEntry + { + Name = line.Name, + Type = ParamTypes.FromName(line.Name), + Category = category, + Description = line.Description, + Ordinal = _entries.Count, + }; + _byName.Add(line.Name, e); + _entries.Add(e); + } + else if (string.IsNullOrEmpty(e.Description) && !string.IsNullOrEmpty(line.Description)) + { + e.Description = line.Description; + } + return e; + } + + // ---- editing ----------------------------------------------------------------------------- + + /// + /// Writes a value to one cfg file, and saves it immediately. The file is re-read from disk first, + /// so that changes made by other tools (eg. the Launcher) since we loaded it are not clobbered. + /// + public static void WriteValue(string folder, CfgFile file, string name, string cfgToken) + { + if (file != CfgFile.Bms && FeatureFlags.IsFeatureFlag(name)) + throw new InvalidOperationException(name + " may only be set in " + BmsFileName + "."); + if (file == CfgFile.Bms && !FeatureFlags.IsFeatureFlag(name)) + throw new InvalidOperationException(BmsFileName + " is read-only, except for the feature-flag params."); + + CfgDocument doc = (file == CfgFile.Bms) + ? CfgDocument.Load(GetPath(folder, file)) + : CfgDocument.LoadOrCreate(GetPath(folder, file)); + + doc.SetValue(name, cfgToken, respectCutLine: file == CfgFile.User); + doc.Save(); + } + + /// + /// Removes a param from User.cfg or VR.cfg (reverting it to the default), and saves immediately. + /// In User.cfg, only lines above the Launcher cut line are removed. + /// + public static bool RemoveValue(string folder, CfgFile file, string name) + { + if (file == CfgFile.Bms) + throw new InvalidOperationException(BmsFileName + " is read-only."); + + string path = GetPath(folder, file); + if (!File.Exists(path)) + return false; + + CfgDocument doc = CfgDocument.Load(path); + if (doc.RemoveValue(name, respectCutLine: file == CfgFile.User) == 0) + return false; + + doc.Save(); + return true; + } + } +} diff --git a/src/BmsConfig/Core/ValueConverter.cs b/src/BmsConfig/Core/ValueConverter.cs new file mode 100644 index 0000000..358a1fd --- /dev/null +++ b/src/BmsConfig/Core/ValueConverter.cs @@ -0,0 +1,478 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.RegularExpressions; + +namespace BmsConfig.Core +{ + public enum ParamType + { + Unknown, + Bool, + Int, + Float, + String, + } + + public static class ParamTypes + { + /// The datatype is implied by the param name: g_bXxx, g_nXxx, g_fXxx, g_sXxx. + public static ParamType FromName(string name) + { + if (name == null || name.Length < 3 || !name.StartsWith("g_", StringComparison.OrdinalIgnoreCase)) + return ParamType.Unknown; + + switch (name[2]) + { + case 'b': return ParamType.Bool; + case 'n': return ParamType.Int; + case 'f': return ParamType.Float; + case 's': return ParamType.String; + default: return ParamType.Unknown; + } + } + + public static string DisplayName(ParamType type) + { + switch (type) + { + case ParamType.Bool: return "Boolean"; + case ParamType.Int: return "Integer"; + case ParamType.Float: return "Float"; + case ParamType.String: return "String"; + default: return "Unknown"; + } + } + } + + /// + /// Constraints parsed from a param's description text: "Range:[0-100]", "Range:[0-]", "Enum:[Low,Medium,High]". + /// + public sealed class ParamConstraints + { + static readonly Regex s_range = new Regex( + @"Range:\s*\[\s*(?[+-]?\d+(?:\.\d+)?)?\s*(?:-|\.\.|,)\s*(?[+-]?\d+(?:\.\d+)?)?\s*\]", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + static readonly Regex s_enum = new Regex( + @"Enum:\s*\[(?[^\]]*)\]", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + public static readonly ParamConstraints None = new ParamConstraints(); + + public double? Min { get; private set; } + public double? Max { get; private set; } + public IReadOnlyList EnumLabels { get; private set; } + + public bool HasRange { get { return Min.HasValue || Max.HasValue; } } + public bool IsEnum { get { return EnumLabels != null && EnumLabels.Count > 0; } } + + public static ParamConstraints Parse(string description) + { + if (string.IsNullOrEmpty(description)) + return None; + + ParamConstraints c = new ParamConstraints(); + + Match m = s_range.Match(description); + if (m.Success) + { + if (m.Groups["min"].Success) + c.Min = double.Parse(m.Groups["min"].Value, CultureInfo.InvariantCulture); + if (m.Groups["max"].Success) + c.Max = double.Parse(m.Groups["max"].Value, CultureInfo.InvariantCulture); + } + + m = s_enum.Match(description); + if (m.Success) + { + List labels = new List(); + foreach (string s in m.Groups["labels"].Value.Split(',')) + labels.Add(s.Trim()); + if (labels.Count > 0 && !(labels.Count == 1 && labels[0].Length == 0)) + c.EnumLabels = labels; + } + + return c; + } + + public string Describe() + { + if (!HasRange) + return null; + + string min = Min.HasValue ? Min.Value.ToString(CultureInfo.InvariantCulture) : ""; + string max = Max.HasValue ? Max.Value.ToString(CultureInfo.InvariantCulture) : ""; + if (Max.HasValue) + return "Range: [" + min + " to " + max + "]"; + return Min == 0 ? "Range: [0 or greater]" : "Range: [" + min + " or greater]"; + } + } + + /// + /// Conversions between cfg-file tokens, user input, and display text. + /// + public static class ValueConverter + { + static readonly Regex s_decimalInt = new Regex(@"^[+-]?\d+$", RegexOptions.CultureInvariant); + static readonly Regex s_hexInt = new Regex(@"^0[xX](?[0-9A-Fa-f]{1,16})$", RegexOptions.CultureInvariant); + static readonly Regex s_float = new Regex(@"^[+-]?(\d+\.?\d*|\.\d+)$", RegexOptions.CultureInvariant); + + // Quote characters users commonly paste in, by mistake: straight, curly ("smart") and low-9 quotes, primes, backticks. + const string OpenQuotes = "\"“”„‟″«»'‘’‚‛′`´"; + + // ---- reading cfg files -------------------------------------------------------------- + + /// Does the token from a cfg file conform to the datatype? Non-conforming lines are ignored. + public static bool IsValidCfgToken(ParamType type, string token) + { + switch (type) + { + case ParamType.Bool: + return ParseCfgBool(token).HasValue; + case ParamType.Int: + return ParseCfgInt(token).HasValue; + case ParamType.Float: + return ParseCfgFloat(token).HasValue; + default: + return token.Length > 0; + } + } + + public static bool? ParseCfgBool(string token) + { + token = token.Trim(); + if (token == "1" || token.Equals("true", StringComparison.OrdinalIgnoreCase)) + return true; + if (token == "0" || token.Equals("false", StringComparison.OrdinalIgnoreCase)) + return false; + return null; + } + + public static long? ParseCfgInt(string token) + { + long value; + token = token.Trim(); + if (s_decimalInt.IsMatch(token) && long.TryParse(token, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out value)) + return value; + + Match m = s_hexInt.Match(token); + ulong hex; + if (m.Success && ulong.TryParse(m.Groups["hex"].Value, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out hex) && hex <= long.MaxValue) + return (long)hex; + + return null; + } + + public static double? ParseCfgFloat(string token) + { + double value; + token = token.Trim(); + if (s_float.IsMatch(token) && double.TryParse(token, NumberStyles.Float, CultureInfo.InvariantCulture, out value) && !double.IsInfinity(value)) + return value; + return null; + } + + /// Removes the surrounding doublequotes from a cfg string token. + public static string UnquoteCfgString(string token) + { + if (token != null && token.Length >= 2 && token[0] == '"' && token[token.Length - 1] == '"') + return token.Substring(1, token.Length - 2); + return token; + } + + // ---- display --------------------------------------------------------------------------- + + public static string ToDisplay(ParamType type, string rawValue, ParamConstraints constraints = null) + { + if (rawValue == null) + return ""; + + switch (type) + { + case ParamType.Bool: + bool? b = ParseCfgBool(rawValue); + return b.HasValue ? (b.Value ? "ON" : "Off") : rawValue; + + case ParamType.Int: + long? n = ParseCfgInt(rawValue); + if (n.HasValue && constraints != null && constraints.IsEnum && n.Value >= 0 && n.Value < constraints.EnumLabels.Count) + return constraints.EnumLabels[(int)n.Value]; + return n.HasValue ? n.Value.ToString(CultureInfo.InvariantCulture) : rawValue; + + case ParamType.String: + return "\"" + UnquoteCfgString(rawValue) + "\""; + + default: + return rawValue; + } + } + + /// The text to pre-fill into an editor textbox, for a cfg value. + public static string ToEditText(ParamType type, string rawValue) + { + if (rawValue == null) + return ""; + + switch (type) + { + case ParamType.String: + return UnquoteCfgString(rawValue); + case ParamType.Int: + long? n = ParseCfgInt(rawValue); + return n.HasValue ? n.Value.ToString(CultureInfo.InvariantCulture) : rawValue; + default: + return rawValue; + } + } + + /// Are two cfg tokens semantically equal (eg. "5" vs "5.0" for a float; "0x10" vs "16" for an int)? + public static bool AreEquivalent(ParamType type, string a, string b) + { + if (a == null || b == null) + return a == b; + + switch (type) + { + case ParamType.Bool: return ParseCfgBool(a) == ParseCfgBool(b); + case ParamType.Int: return ParseCfgInt(a) == ParseCfgInt(b); + case ParamType.Float: return ParseCfgFloat(a) == ParseCfgFloat(b); + case ParamType.String: return UnquoteCfgString(a) == UnquoteCfgString(b); + default: return a == b; + } + } + + // ---- user input -> cfg token ------------------------------------------------------------- + + /// + /// Validates user input and converts it to the token to be written into the cfg file. + /// Returns false (with an error message) if the input is invalid. + /// + public static bool TryConvertInput(string name, ParamType type, ParamConstraints constraints, string input, out string cfgToken, out string error) + { + cfgToken = null; + error = null; + constraints = constraints ?? ParamConstraints.None; + input = (input ?? "").Trim(); + + switch (type) + { + case ParamType.Bool: + return TryConvertBool(input, out cfgToken, out error); + case ParamType.Int: + return TryConvertInt(input, constraints, out cfgToken, out error); + case ParamType.Float: + return TryConvertFloat(input, constraints, out cfgToken, out error); + case ParamType.String: + return TryConvertString(name, input, out cfgToken, out error); + default: + if (input.Length == 0 || HasWhitespace(input) || input.IndexOf('"') >= 0) + { + error = "Value must be a single word, without spaces or quotes."; + return false; + } + cfgToken = input; + return true; + } + } + + static bool TryConvertBool(string input, out string cfgToken, out string error) + { + cfgToken = null; + error = null; + switch (input.ToLowerInvariant()) + { + case "1": case "on": case "true": case "yes": + cfgToken = "1"; + return true; + case "0": case "off": case "false": case "no": + cfgToken = "0"; + return true; + } + error = "Value must be ON or Off."; + return false; + } + + static bool TryConvertInt(string input, ParamConstraints constraints, out string cfgToken, out string error) + { + cfgToken = null; + error = null; + long value; + + if (constraints.IsEnum) + { + for (int i = 0; i < constraints.EnumLabels.Count; i++) + { + if (string.Equals(constraints.EnumLabels[i], input, StringComparison.OrdinalIgnoreCase)) + { + cfgToken = i.ToString(CultureInfo.InvariantCulture); + return true; + } + } + } + + Match m = s_hexInt.Match(input); + if (m.Success) + { + ulong hex; + if (!ulong.TryParse(m.Groups["hex"].Value, NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out hex) || hex > uint.MaxValue) + { + error = "Hexadecimal value is too large (max 0xFFFFFFFF)."; + return false; + } + + // Hex input is a bit pattern: for a param that may be negative, reinterpret as a signed 32-bit value. + bool unsigned = constraints.Min.HasValue && constraints.Min.Value >= 0; + value = (!unsigned && hex > int.MaxValue) ? (long)unchecked((int)(uint)hex) : (long)hex; + } + else if (!s_decimalInt.IsMatch(input) || !long.TryParse(input, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out value)) + { + error = constraints.IsEnum + ? "Value must be one of: " + string.Join(", ", constraints.EnumLabels) + "." + : "Value must be a whole number (decimal, or hexadecimal with a 0x prefix)."; + return false; + } + + if (value < int.MinValue || value > uint.MaxValue) + { + error = "Value is out of range for a 32-bit integer."; + return false; + } + + if (!CheckRange(value, constraints, out error)) + return false; + + if (constraints.IsEnum && (value < 0 || value >= constraints.EnumLabels.Count)) + { + error = "Value must be one of: " + string.Join(", ", constraints.EnumLabels) + "."; + return false; + } + + cfgToken = value.ToString(CultureInfo.InvariantCulture); + return true; + } + + static bool TryConvertFloat(string input, ParamConstraints constraints, out string cfgToken, out string error) + { + cfgToken = null; + error = null; + double value; + + if (!s_float.IsMatch(input) || !double.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out value) || double.IsInfinity(value) || double.IsNaN(value)) + { + error = "Value must be a decimal number, like 1.5 (no exponents, Infinity or NaN)."; + return false; + } + + if (!CheckRange(value, constraints, out error)) + return false; + + // Normalize the text a little, but otherwise keep what the user typed (eg. "5.0" stays "5.0"). + string text = input.TrimStart('+'); + bool negative = text.StartsWith("-", StringComparison.Ordinal); + if (negative) + text = text.Substring(1); + if (text.StartsWith(".", StringComparison.Ordinal)) + text = "0" + text; + if (text.EndsWith(".", StringComparison.Ordinal)) + text = text + "0"; + text = text.TrimStart('0'); + if (text.Length == 0 || text[0] == '.') + text = "0" + text; + if (negative && value != 0) + text = "-" + text; + + cfgToken = text; + return true; + } + + static bool TryConvertString(string name, string input, out string cfgToken, out string error) + { + cfgToken = null; + error = null; + + // Strip one layer of surrounding quotes -- straight, curly, or single -- commonly pasted by mistake. + if (input.Length >= 2 && OpenQuotes.IndexOf(input[0]) >= 0 && OpenQuotes.IndexOf(input[input.Length - 1]) >= 0) + input = input.Substring(1, input.Length - 2); + + if (input.IndexOf('"') >= 0) + { + error = "String values cannot contain doublequote characters."; + return false; + } + if (input.IndexOf('\r') >= 0 || input.IndexOf('\n') >= 0) + { + error = "String values cannot contain line breaks."; + return false; + } + + string featureError; + if (!FeatureFlags.Validate(name, input, out featureError)) + { + error = featureError; + return false; + } + + cfgToken = "\"" + input + "\""; + return true; + } + + static bool CheckRange(double value, ParamConstraints constraints, out string error) + { + error = null; + if ((constraints.Min.HasValue && value < constraints.Min.Value) + || (constraints.Max.HasValue && value > constraints.Max.Value)) + { + error = "Value is out of range. " + constraints.Describe(); + return false; + } + return true; + } + + static bool HasWhitespace(string s) + { + foreach (char c in s) + if (char.IsWhiteSpace(c)) + return true; + return false; + } + } + + /// + /// The 4 special "feature flag" params. These may ONLY exist in Falcon BMS.cfg, and are strictly validated. + /// + public static class FeatureFlags + { + static readonly Regex s_allMinus = new Regex(@"^all(\-([A-Z0-9_]+))*$", RegexOptions.CultureInvariant); + static readonly Regex s_nonePlus = new Regex(@"^none(\+([A-Z0-9_]+))*$", RegexOptions.CultureInvariant); + + static readonly Dictionary s_flags = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + { "g_sCpuPerfOptimizations", s_allMinus }, + { "g_sPriorityFixes", s_allMinus }, + { "g_sCompatibleChanges", s_allMinus }, + { "g_sNonCompatibleChanges", s_nonePlus }, + }; + + public static bool IsFeatureFlag(string name) + { + return name != null && s_flags.ContainsKey(name); + } + + public static bool Validate(string name, string value, out string error) + { + error = null; + Regex regex; + if (name == null || !s_flags.TryGetValue(name, out regex)) + return true; + + if (regex.IsMatch(value)) + return true; + + error = (regex == s_allMinus) + ? "Must be \"all\", optionally followed by -FLAG items (uppercase), eg. all-FOO-BAR_2" + : "Must be \"none\", optionally followed by +FLAG items (uppercase), eg. none+FOO+BAR_2"; + return false; + } + } +} diff --git a/src/BmsConfig/Logo.png b/src/BmsConfig/Logo.png new file mode 100644 index 0000000..3d40959 Binary files /dev/null and b/src/BmsConfig/Logo.png differ diff --git a/src/BmsConfig/MainWindow.xaml b/src/BmsConfig/MainWindow.xaml new file mode 100644 index 0000000..20f98c3 --- /dev/null +++ b/src/BmsConfig/MainWindow.xaml @@ -0,0 +1,269 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + FALCON BMS + CONFIG + + + + + + + +