Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 87 additions & 23 deletions src/BmsConfig/Core/CfgDocument.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ public enum CfgLineKind
Set,
/// <summary>The Launcher's cut line, in Falcon BMS User.cfg.</summary>
CutLine,
/// <summary>A commented-out "set" line, eg. "// set {name} {value} // note".</summary>
CommentedSet,
}

/// <summary>
Expand All @@ -27,7 +29,7 @@ public sealed class CfgLine
public string Text { get; internal set; }
public CfgLineKind Kind { get; internal set; }

// Kind == Set
// Kind == Set or CommentedSet
public string Name { get; internal set; }
public string RawValue { get; internal set; }
public string Description { get; internal set; }
Expand All @@ -54,6 +56,11 @@ public sealed class CfgDocument
@"^\s*set\s+(?<name>[A-Za-z_][A-Za-z0-9_]*)\s+(?<value>""[^""]*""|[^\s""]+)\s*(?:(?://|#)\s?(?<desc>.*))?$",
RegexOptions.CultureInvariant);

// A commented-out set line: the comment marker, then a well-formed set line.
static readonly Regex s_commentedSetLine = new Regex(
@"^(?<indent>\s*)(?://|#)\s*(?<body>set\s.*)$",
RegexOptions.CultureInvariant);

readonly List<CfgLine> _lines = new List<CfgLine>();

public string FilePath { get; private set; }
Expand Down Expand Up @@ -122,6 +129,14 @@ public static CfgLine ParseLine(string text)
return line;
}

// Checked before categories: "// set g_bFoo 1 //" is a commented-out param, not a category header.
Match commented = s_commentedSetLine.Match(text);
if (commented.Success && TryParseSet(line, text, commented.Groups["body"].Index))
{
line.Kind = CfgLineKind.CommentedSet;
return line;
}

if (trimmed.Length >= 4
&& trimmed.StartsWith("//", StringComparison.Ordinal)
&& trimmed.EndsWith("//", StringComparison.Ordinal))
Expand All @@ -136,27 +151,57 @@ public static CfgLine ParseLine(string text)
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;

if (TryParseSet(line, text, 0))
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;
}

/// <summary>
/// Parses the set statement starting at text[start], filling in the line's Name, RawValue etc.
/// (but not its Kind). Returns false if it isn't a well-formed set statement.
/// </summary>
static bool TryParseSet(CfgLine line, string text, int start)
{
Match m = s_setLine.Match(text.Substring(start));
if (!m.Success)
return false;

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 false;

line.Name = name;
line.RawValue = value;
line.ValueStart = start + m.Groups["value"].Index;
line.ValueLength = m.Groups["value"].Length;
line.Description = m.Groups["desc"].Success ? m.Groups["desc"].Value.Trim() : null;
return true;
}

/// <summary>True if the set line has a non-empty trailing comment, eg. a note the user wrote.</summary>
static bool HasTrailingComment(CfgLine line)
{
return !string.IsNullOrEmpty(line.Description);
}

/// <summary>"set x 1 // note" -> "// set x 1 // note", keeping the indentation.</summary>
static string CommentOut(string text)
{
int indent = text.Length - text.TrimStart().Length;
return text.Substring(0, indent) + "// " + text.Substring(indent);
}

/// <summary>"// set x 1 // note" -> "set x 1 // note", keeping the indentation.</summary>
static string Uncomment(string text)
{
Match m = s_commentedSetLine.Match(text);
return m.Groups["indent"].Value + m.Groups["body"].Value;
}

/// <summary>Index of the Launcher cut line, or -1 if none.</summary>
public int CutLineIndex
{
Expand All @@ -179,7 +224,14 @@ public CfgLine FindLast(string name, bool aboveCutLine = false)
return index >= 0 ? _lines[index] : null;
}

int FindLastIndex(string name, bool aboveCutLine)
/// <summary>The last commented-out set line for the given param, or null.</summary>
public CfgLine FindLastCommented(string name, bool aboveCutLine = false)
{
int index = FindLastIndex(name, aboveCutLine, CfgLineKind.CommentedSet);
return index >= 0 ? _lines[index] : null;
}

int FindLastIndex(string name, bool aboveCutLine, CfgLineKind kind = CfgLineKind.Set)
{
int end = _lines.Count;
if (aboveCutLine)
Expand All @@ -192,22 +244,30 @@ int FindLastIndex(string name, bool aboveCutLine)
for (int i = end - 1; i >= 0; i--)
{
CfgLine line = _lines[i];
if (line.Kind == CfgLineKind.Set && string.Equals(line.Name, name, StringComparison.OrdinalIgnoreCase))
if (line.Kind == kind && string.Equals(line.Name, name, StringComparison.OrdinalIgnoreCase))
return i;
}
return -1;
}

/// <summary>
/// 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.
/// whitespace and trailing comment). Failing that, if a commented-out set line exists (eg. from
/// RemoveValue), it is uncommented and its value replaced. Otherwise a new line is inserted -- above
/// the Launcher cut line if there is one, else at the end of the file.
/// </summary>
/// <param name="serializedValue">The value as it should appear in the file (eg. already quoted for strings).</param>
/// <param name="respectCutLine">If true, never edit or insert at/below the Launcher cut line.</param>
public void SetValue(string name, string serializedValue, bool respectCutLine)
{
int index = FindLastIndex(name, respectCutLine);
if (index < 0)
{
index = FindLastIndex(name, respectCutLine, CfgLineKind.CommentedSet);
if (index >= 0)
_lines[index] = ParseLine(Uncomment(_lines[index].Text));
}

if (index >= 0)
{
CfgLine old = _lines[index];
Expand All @@ -230,15 +290,19 @@ public void SetValue(string name, string serializedValue, bool respectCutLine)

/// <summary>
/// Removes all set lines for the given param (only those above the cut line, if respectCutLine).
/// Returns the number of lines removed.
/// Lines with a trailing comment are commented out rather than deleted, so the user's notes are kept.
/// Returns the number of lines removed or commented out.
/// </summary>
public int RemoveValue(string name, bool respectCutLine)
{
int removed = 0;
int index;
while ((index = FindLastIndex(name, respectCutLine)) >= 0)
{
_lines.RemoveAt(index);
if (HasTrailingComment(_lines[index]))
_lines[index] = ParseLine(CommentOut(_lines[index].Text));
else
_lines.RemoveAt(index);
removed++;
}
return removed;
Expand Down
23 changes: 22 additions & 1 deletion src/BmsConfig/Core/ConfigSet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ public sealed class ParamEntry
/// <summary>Effective value in Falcon BMS VR.cfg, or null.</summary>
public string VrValue { get; internal set; }

/// <summary>True if User.cfg has a commented-out set line for this param (above the cut line).</summary>
public bool UserCommentedOut { get; internal set; }
/// <summary>True if VR.cfg has a commented-out set line for this param.</summary>
public bool VrCommentedOut { get; internal set; }

/// <summary>Order of first appearance (Falcon BMS.cfg first, then User.cfg, then VR.cfg).</summary>
public int Ordinal { get; internal set; }

Expand Down Expand Up @@ -182,6 +187,14 @@ void Merge()
if (e.Category == OtherCategory)
hasOther = true;
}
else if (line.Kind == CfgLineKind.CommentedSet && !belowCut)
{
// Listed even if it's not in Falcon BMS.cfg, so the user can set it again.
ParamEntry e = GetOrAdd(line, OtherCategory);
e.UserCommentedOut = true;
if (e.Category == OtherCategory)
hasOther = true;
}
}

// Falcon BMS VR.cfg: overrides, only when launched in VR.
Expand All @@ -194,6 +207,13 @@ void Merge()
if (e.Category == OtherCategory)
hasOther = true;
}
else if (line.Kind == CfgLineKind.CommentedSet)
{
ParamEntry e = GetOrAdd(line, OtherCategory);
e.VrCommentedOut = true;
if (e.Category == OtherCategory)
hasOther = true;
}
}

foreach (ParamEntry e in _entries)
Expand Down Expand Up @@ -252,7 +272,8 @@ public static void WriteValue(string folder, CfgFile file, string name, string c

/// <summary>
/// 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.
/// Lines with a trailing comment (eg. the user's notes) are commented out rather than deleted.
/// In User.cfg, only lines above the Launcher cut line are affected.
/// </summary>
public static bool RemoveValue(string folder, CfgFile file, string name)
{
Expand Down
2 changes: 1 addition & 1 deletion src/BmsConfig/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@
<Button x:Name="FillDefaultButton" Content="Fill with default" MinWidth="150" Margin="0,0,12,8" Click="OnFillDefaultClick"
ToolTip="Put the default value (from Falcon BMS.cfg) into the editor" />
<Button x:Name="RevertButton" Content="Remove override" MinWidth="150" Margin="0,0,12,8" Click="OnRevertClick"
ToolTip="Remove this param from the selected file(s), reverting it to the default" />
ToolTip="Remove this param from the selected file(s), reverting it to the default. Lines with a trailing comment are commented out, rather than deleted." />
</WrapPanel>

<TextBlock x:Name="SaveFeedback" Style="{StaticResource SecondaryText}" Margin="0,6,0,0" TextWrapping="Wrap" />
Expand Down
8 changes: 5 additions & 3 deletions src/BmsConfig/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -488,12 +488,14 @@ void ShowDetail(ParamItem item)
DetailDefault.Text = entry.BmsValue != null ? item.Default : "(none)";
ValueSource source;
string current = entry.GetEffectiveValue(includeVr, out source);
DetailCurrent.Text = ValueConverter.ToDisplay(entry.Type, current, c);
DetailCurrent.Text = current != null ? ValueConverter.ToDisplay(entry.Type, current, c) : "(none)";
DetailCurrentSource.Text = source != ValueSource.None ? "[from " + ParamItem.SourceToText(source) + "]" : "";
DetailUser.Text = entry.UserValue != null
? ValueConverter.ToDisplay(entry.Type, entry.UserValue, c) + (entry.UserValueFromLauncher ? " (Launcher section)" : "")
: "(not set)";
DetailVr.Text = entry.VrValue != null ? ValueConverter.ToDisplay(entry.Type, entry.VrValue, c) : "(not set)";
: (entry.UserCommentedOut ? "(none; commented out)" : "(none)");
DetailVr.Text = entry.VrValue != null
? ValueConverter.ToDisplay(entry.Type, entry.VrValue, c)
: (entry.VrCommentedOut ? "(none; commented out)" : "(none)");

// Editor
_suppressEvents = true;
Expand Down
93 changes: 93 additions & 0 deletions tests/BmsConfig.Tests/CfgDocumentTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,67 @@ public void RemoveValueRespectsCutLine()
doc.ToText());
}

[Fact]
public void RemoveValueCommentsOutLinesWithNotes()
{
string user =
"set g_bPlain 1\n" +
" set g_bNoted 1 // NOTE: turn this off before multiplayer\n" +
"set g_bEmptyComment 1 //\n";

CfgDocument doc = CfgDocument.Parse(user);
Assert.Equal(1, doc.RemoveValue("g_bPlain", respectCutLine: true));
Assert.Equal(1, doc.RemoveValue("g_bNoted", respectCutLine: true));
Assert.Equal(1, doc.RemoveValue("g_bEmptyComment", respectCutLine: true));

Assert.Equal(" // set g_bNoted 1 // NOTE: turn this off before multiplayer\n", doc.ToText());
Assert.Null(doc.FindLast("g_bNoted"));
Assert.NotNull(doc.FindLastCommented("g_bNoted"));
Assert.Equal(0, doc.RemoveValue("g_bNoted", respectCutLine: true));
}

[Fact]
public void SetValueUncommentsCommentedOutLine()
{
string user =
" // set g_bNoted 1 // NOTE: turn this off before multiplayer\n" +
"#set g_nHash 5\n" +
"// LAUNCHER OVERRIDES BEGIN HERE - DO NOT EDIT OR ADD BELOW THIS LINE\n" +
"// set g_nBelow 1 // launcher\n";

CfgDocument doc = CfgDocument.Parse(user);
doc.SetValue("g_bNoted", "0", respectCutLine: true);
doc.SetValue("g_nHash", "7", respectCutLine: true);
doc.SetValue("g_nBelow", "2", respectCutLine: true); // the commented line below the cut is left alone

Assert.Equal(
" set g_bNoted 0 // NOTE: turn this off before multiplayer\n" +
"set g_nHash 7\n" +
"set g_nBelow 2\n" +
"// LAUNCHER OVERRIDES BEGIN HERE - DO NOT EDIT OR ADD BELOW THIS LINE\n" +
"// set g_nBelow 1 // launcher\n",
doc.ToText());
}

[Fact]
public void RemoveThenSetRoundTrips()
{
const string line = "set g_bNoted 1 // NOTE: turn this off before multiplayer\r\n";
CfgDocument doc = CfgDocument.Parse(line);
doc.RemoveValue("g_bNoted", respectCutLine: true);
doc.SetValue("g_bNoted", "1", respectCutLine: true);
Assert.Equal(line, doc.ToText());
}

[Fact]
public void CommentedSetIsNotACategory()
{
CfgDocument doc = CfgDocument.Parse("// set g_bFoo 1 //\n// Real Category //\n// set g_nBad abc // not an int\n");
Assert.Equal(CfgLineKind.CommentedSet, doc.Lines[0].Kind);
Assert.Equal(CfgLineKind.Category, doc.Lines[1].Kind);
Assert.Equal(CfgLineKind.Other, doc.Lines[2].Kind);
}

[Fact]
public void SavesWithoutBom()
{
Expand All @@ -128,6 +189,38 @@ public void SavesWithoutBom()

public class ConfigSetTests
{
[Fact]
public void ListsCommentedOutParams()
{
CfgDocument bms = CfgDocument.Parse("// GENERAL //\nset g_bKnown 1 // Known\n// set g_bBmsCommented 1 // ignored in Falcon BMS.cfg\n");
CfgDocument user = CfgDocument.Parse(
"// set g_bKnown 0 // my note\n" +
"// set g_bExperimental 1 // NOTE: off before MP\n" +
"// LAUNCHER OVERRIDES BEGIN HERE - DO NOT EDIT OR ADD BELOW THIS LINE\n" +
"// set g_bBelowCut 1 // x\n");
CfgDocument vr = CfgDocument.Parse("// set g_nVrOnly 2 // vr note\n");

ConfigSet set = ConfigSet.FromDocuments("x", bms, user, vr);

ParamEntry known = set.Find("g_bKnown");
Assert.Equal("GENERAL", known.Category);
Assert.True(known.UserCommentedOut);
Assert.Null(known.UserValue);
Assert.Equal("1", known.GetEffectiveValue(true));

ParamEntry experimental = set.Find("g_bExperimental");
Assert.Equal("Other", experimental.Category);
Assert.Equal("NOTE: off before MP", experimental.Description);
Assert.True(experimental.UserCommentedOut);
Assert.Null(experimental.BmsValue);
Assert.Null(experimental.GetEffectiveValue(true));

Assert.True(set.Find("g_nVrOnly").VrCommentedOut);
Assert.Null(set.Find("g_bBmsCommented"));
Assert.Null(set.Find("g_bBelowCut"));
Assert.Contains("Other", set.Categories);
}

[Fact]
public void ParsesRealWorldHeader()
{
Expand Down
Loading