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
124 changes: 118 additions & 6 deletions src/BmsConfig/Core/ValueConverter.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;

namespace BmsConfig.Core
Expand Down Expand Up @@ -46,14 +47,21 @@ public static string DisplayName(ParamType type)
}

/// <summary>
/// Constraints parsed from a param's description text: "Range: [0-100]", "Range: [0-]", "Values: [Low,Medium,High]".
/// Constraints parsed from a param's description text:
/// "Range: [0-100]", "Range: [0-]", "Range: [20-120, by 20]",
/// "Values: [Low,Medium,High]" (labels for 0,1,2...), "Values: [8,9,10,12,16]" (the allowed numbers).
/// </summary>
public sealed class ParamConstraints
{
/// <summary>Discrete values are offered as buttons, when there are at most this many.</summary>
public const int MaxChoices = 21;

static readonly Regex s_range = new Regex(
@"Range:\s*\[\s*(?<min>[+-]?\d+(?:\.\d+)?)?\s*(?:-|\.\.|,)\s*(?<max>[+-]?\d+(?:\.\d+)?)?\s*\]",
@"Range:\s*\[\s*(?<min>[+-]?\d+(?:\.\d+)?)?\s*(?:-|\.\.|,)\s*(?<max>[+-]?\d+(?:\.\d+)?)?\s*(?:,\s*by\s+(?<step>\+?\d+(?:\.\d+)?)\s*)?\]",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

static readonly Regex s_number = new Regex(@"^[+-]?(\d+\.?\d*|\.\d+)$", RegexOptions.CultureInvariant);

static readonly Regex s_enum = new Regex(
@"Values:\s*\[(?<labels>[^\]]*)\]",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
Expand All @@ -62,7 +70,12 @@ public sealed class ParamConstraints

public double? Min { get; private set; }
public double? Max { get; private set; }
/// <summary>From "Range: [min-max, by step]": allowed values are min, min+step, min+2*step... (up to max).</summary>
public double? Step { get; private set; }
/// <summary>From "Values: [Low,Medium,High]": labels for the integer values 0,1,2...</summary>
public IReadOnlyList<string> EnumLabels { get; private set; }
/// <summary>From an all-numeric "Values: [8,9,10,12,16]": the only allowed values.</summary>
public IReadOnlyList<double> NumericValues { get; private set; }

public bool HasRange { get { return Min.HasValue || Max.HasValue; } }
public bool IsEnum { get { return EnumLabels != null && EnumLabels.Count > 0; } }
Expand All @@ -81,6 +94,12 @@ public static ParamConstraints Parse(string description)
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);

// A step needs a starting point; a zero step is meaningless.
double step;
if (m.Groups["step"].Success && c.Min.HasValue
&& double.TryParse(m.Groups["step"].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out step) && step > 0)
c.Step = step;
}

m = s_enum.Match(description);
Expand All @@ -90,22 +109,94 @@ public static ParamConstraints Parse(string description)
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;
{
// All numbers -> the allowed values themselves; otherwise labels for 0,1,2...
if (labels.TrueForAll(l => s_number.IsMatch(l)))
c.NumericValues = labels.ConvertAll(l => double.Parse(l, NumberStyles.Float, CultureInfo.InvariantCulture));
else
c.EnumLabels = labels;
}
}

return c;
}

/// <summary>
/// The discrete values allowed for an int or float param (from "Values: [numbers]", or a Range with a
/// step), as cfg tokens -- or null if there are none, or more than MaxChoices.
/// </summary>
public IReadOnlyList<string> GetChoices(ParamType type)
{
if (type != ParamType.Int && type != ParamType.Float)
return null;

List<double> values = new List<double>();
if (NumericValues != null)
{
values.AddRange(NumericValues);
}
else if (Step.HasValue && Max.HasValue)
{
for (int i = 0; i <= MaxChoices; i++)
{
double v = Math.Round(Min.Value + i * Step.Value, 9);
if (v > Max.Value + 1e-9)
break;
values.Add(v);
}
}

if (values.Count == 0 || values.Count > MaxChoices)
return null;

List<string> tokens = new List<string>();
foreach (double v in values)
{
if (type == ParamType.Int && v != Math.Floor(v))
continue; // eg. "Values: [1.5]" on an int param
string token = ValueConverter.FormatNumber(type, v);
if (!tokens.Contains(token))
tokens.Add(token);
}
return tokens.Count > 0 ? tokens : null;
}

/// <summary>Is the value one of the NumericValues, and on the Step grid (if those apply)?</summary>
public bool IsAllowedValue(double value, out string error)
{
error = null;
const double tolerance = 1e-9;

if (NumericValues != null && !NumericValues.Any(v => Math.Abs(v - value) <= tolerance * Math.Max(1, Math.Abs(v))))
{
error = "Value must be one of: " + string.Join(", ", NumericValues.Select(v => v.ToString(CultureInfo.InvariantCulture))) + ".";
return false;
}

if (Step.HasValue)
{
double steps = (value - Min.Value) / Step.Value;
if (Math.Abs(steps - Math.Round(steps)) > 1e-6)
{
error = "Value must be a multiple of " + Step.Value.ToString(CultureInfo.InvariantCulture)
+ " from " + Min.Value.ToString(CultureInfo.InvariantCulture) + ". " + Describe();
return false;
}
}
return true;
}

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) : "";
string step = Step.HasValue ? ", by " + Step.Value.ToString(CultureInfo.InvariantCulture) : "";
if (Max.HasValue)
return "Range: [" + min + " to " + max + "]";
return Min == 0 ? "Range: [0 or greater]" : "Range: [" + min + " or greater]";
return "Range: [" + min + " to " + max + step + "]";
return Min == 0 ? "Range: [0 or greater" + step + "]" : "Range: [" + min + " or greater" + step + "]";
}
}

Expand Down Expand Up @@ -276,6 +367,19 @@ public static bool TryConvertInput(string name, ParamType type, ParamConstraints
}
}

/// <summary>
/// Checks a value already in a cfg file against the param's constraints (range, step, allowed values,
/// feature-flag syntax). Such values are kept as-is, but flagged in the UI. Returns the problem, or null.
/// </summary>
public static string CheckCfgValue(string name, ParamType type, ParamConstraints constraints, string rawValue)
{
if (rawValue == null || type == ParamType.Bool || type == ParamType.Unknown)
return null;

string token, error;
return TryConvertInput(name, type, constraints, ToEditText(type, rawValue), out token, out error) ? null : error;
}

static bool TryConvertBool(string input, out string cfgToken, out string error)
{
cfgToken = null;
Expand Down Expand Up @@ -426,7 +530,15 @@ static bool CheckRange(double value, ParamConstraints constraints, out string er
error = "Value is out of range. " + constraints.Describe();
return false;
}
return true;
return constraints.IsAllowedValue(value, out error);
}

/// <summary>Formats a number as a cfg token: integers in decimal; floats with at least one decimal place.</summary>
public static string FormatNumber(ParamType type, double value)
{
if (type == ParamType.Int)
return ((long)Math.Round(value)).ToString(CultureInfo.InvariantCulture);
return Math.Round(value, 9).ToString("0.0########", CultureInfo.InvariantCulture);
}

static bool HasWhitespace(string s)
Expand Down
22 changes: 21 additions & 1 deletion src/BmsConfig/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,15 @@
<GridViewColumn Header="VALUE" Width="230">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock x:Name="Value" Text="{Binding Value}" Margin="8,0,0,0" TextTrimming="CharacterEllipsis" />
<StackPanel Orientation="Horizontal" Margin="8,0,0,0">
<TextBlock x:Name="Value" Text="{Binding Value}" TextTrimming="CharacterEllipsis" />
<Path x:Name="WarningIcon" Style="{StaticResource WarningIcon}" Margin="8,0,0,0"
Visibility="Collapsed" ToolTip="{Binding Warning}" />
</StackPanel>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding HasWarning}" Value="True">
<Setter TargetName="WarningIcon" Property="Visibility" Value="Visible" />
</DataTrigger>
<DataTrigger Binding="{Binding IsModified}" Value="True">
<Setter TargetName="Value" Property="Foreground" Value="{DynamicResource ModifiedForeground}" />
<Setter TargetName="Value" Property="FontWeight" Value="SemiBold" />
Expand Down Expand Up @@ -210,6 +217,16 @@
<TextBlock Grid.Row="3" Grid.Column="1" x:Name="DetailVr" Margin="0,2" Style="{StaticResource SecondaryText}" TextWrapping="Wrap" />
</Grid>

<Grid x:Name="DetailWarningPanel" Margin="0,8,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Path Style="{StaticResource WarningIcon}" VerticalAlignment="Top" Margin="0,4,8,0" />
<TextBlock x:Name="DetailWarning" Grid.Column="1" TextWrapping="Wrap"
Foreground="{DynamicResource ModifiedForeground}" />
</Grid>

<TextBlock Text="NEW VALUE" Style="{StaticResource SectionLabel}" />

<!-- Boolean editor -->
Expand All @@ -225,6 +242,9 @@
<!-- Enum editor -->
<ComboBox x:Name="EnumEditor" HorizontalAlignment="Stretch" SelectionChanged="OnEnumChanged" />

<!-- Choice editor: buttons for a small set of discrete numbers (Values: [8,9,10] or Range: [a-b, by c]) -->
<WrapPanel x:Name="ChoiceEditor" />

<!-- Text editor (int / float / string) -->
<TextBox x:Name="TextEditor" KeyDown="OnTextEditorKeyDown" TextChanged="OnTextEditorChanged" MinHeight="40"
ToolTip="Press Enter to apply" />
Expand Down
49 changes: 48 additions & 1 deletion src/BmsConfig/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,8 @@ void ShowDetail(ParamItem item)
string typeText = "Type: " + ParamTypes.DisplayName(entry.Type);
if (c.IsEnum)
typeText += " Values: " + string.Join(", ", c.EnumLabels.Select((l, i) => i + " = " + l));
else if (c.NumericValues != null)
typeText += " Values: " + string.Join(", ", c.NumericValues.Select(v => ValueConverter.FormatNumber(entry.Type, v)));
else if (c.HasRange)
typeText += " " + c.Describe();
if (entry.Category == ConfigSet.UnknownCategory && entry.BmsValue == null)
Expand Down Expand Up @@ -497,13 +499,37 @@ void ShowDetail(ParamItem item)
? ValueConverter.ToDisplay(entry.Type, entry.VrValue, c)
: (entry.VrCommentedOut ? "(none; commented out)" : "(none)");

// Values already in the files that break the constraints are kept, but flagged.
List<string> warnings = new List<string>();
AddWarning(warnings, entry, "Default", entry.BmsValue);
AddWarning(warnings, entry, "User.cfg", entry.UserValue);
AddWarning(warnings, entry, "VR.cfg", entry.VrValue);
DetailWarning.Text = string.Join("\n", warnings);
DetailWarningPanel.Visibility = warnings.Count > 0 ? Visibility.Visible : Visibility.Collapsed;

// Editor
_suppressEvents = true;
bool isBool = entry.Type == ParamType.Bool;
bool isEnum = entry.Type == ParamType.Int && c.IsEnum;
IReadOnlyList<string> choices = (!isBool && !isEnum) ? c.GetChoices(entry.Type) : null;
bool isChoice = choices != null;
BoolEditor.Visibility = isBool ? Visibility.Visible : Visibility.Collapsed;
EnumEditor.Visibility = isEnum ? Visibility.Visible : Visibility.Collapsed;
TextEditor.Visibility = (!isBool && !isEnum) ? Visibility.Visible : Visibility.Collapsed;
ChoiceEditor.Visibility = isChoice ? Visibility.Visible : Visibility.Collapsed;
TextEditor.Visibility = (!isBool && !isEnum && !isChoice) ? Visibility.Visible : Visibility.Collapsed;

ChoiceEditor.Children.Clear();
if (isChoice)
{
Style style = (Style)FindResource("ChoiceButton");
foreach (string token in choices)
{
RadioButton button = new RadioButton { Content = token, Tag = token, GroupName = "ChoiceValue", Style = style };
button.Click += (s, e) => OnEditorChoiceChanged();
ChoiceEditor.Children.Add(button);
}
SelectChoice(entry.Type, current); // off-grid values (eg. hand-edited) leave no button selected
}

if (isBool)
{
Expand Down Expand Up @@ -543,6 +569,13 @@ void ShowDetail(ParamItem item)
UpdateButtons();
}

static void AddWarning(List<string> warnings, ParamEntry entry, string label, string rawValue)
{
string problem = ValueConverter.CheckCfgValue(entry.Name, entry.Type, entry.Constraints, rawValue);
if (problem != null)
warnings.Add(label + " value " + ValueConverter.ToDisplay(entry.Type, rawValue, entry.Constraints) + " is not allowed. " + problem);
}

IEnumerable<CfgFile> SaveTargets
{
get
Expand Down Expand Up @@ -612,10 +645,19 @@ string EditorInput
return BoolOn.IsChecked == true ? "1" : BoolOff.IsChecked == true ? "0" : null;
if (EnumEditor.Visibility == Visibility.Visible)
return EnumEditor.SelectedIndex >= 0 ? EnumEditor.SelectedIndex.ToString() : null;
if (ChoiceEditor.Visibility == Visibility.Visible)
return ChoiceEditor.Children.OfType<RadioButton>().Where(b => b.IsChecked == true).Select(b => (string)b.Tag).FirstOrDefault();
return TextEditor.Text;
}
}

/// <summary>Checks the value button equivalent to the given cfg value (eg. "1" matches "1.0"), if any.</summary>
void SelectChoice(ParamType type, string value)
{
foreach (RadioButton button in ChoiceEditor.Children.OfType<RadioButton>())
button.IsChecked = value != null && ValueConverter.AreEquivalent(type, (string)button.Tag, value);
}

void OnApplyClick(object sender, RoutedEventArgs e)
{
string input = EditorInput;
Expand Down Expand Up @@ -654,6 +696,11 @@ void OnFillDefaultClick(object sender, RoutedEventArgs e)
long? n = ValueConverter.ParseCfgInt(entry.BmsValue);
EnumEditor.SelectedIndex = (n.HasValue && n.Value >= 0 && n.Value < EnumEditor.Items.Count) ? (int)n.Value : -1;
}
else if (ChoiceEditor.Visibility == Visibility.Visible)
{
SelectChoice(entry.Type, entry.BmsValue);
OnEditorChoiceChanged();
}
else
{
TextEditor.Text = ValueConverter.ToEditText(entry.Type, entry.BmsValue);
Expand Down
8 changes: 8 additions & 0 deletions src/BmsConfig/ParamItem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ public ValueSource Source

public string SourceText { get { return SourceToText(Source); } }

/// <summary>Why the current value violates the param's constraints (eg. out of range), or null.</summary>
public string Warning
{
get { return ValueConverter.CheckCfgValue(Entry.Name, Entry.Type, Entry.Constraints, Entry.GetEffectiveValue(_includeVr)); }
}

public bool HasWarning { get { return Warning != null; } }

/// <summary>True if the value is overridden by User.cfg (or VR.cfg, when included in the view).</summary>
public bool IsModified
{
Expand Down
Loading
Loading