private static void CreateConfigFile() { // TODO: Make magic numbers for configs into constants defined in this class TomlTable tomlConfigTable = Toml.Create(); Dictionary <string, object> touchConfigDict = new Dictionary <string, object>(); touchConfigDict.Add("WidthAxis", 1); touchConfigDict.Add("CalMinX", 0); touchConfigDict.Add("CalMaxX", 1280); touchConfigDict.Add("CalMinY", 0); touchConfigDict.Add("CalMaxY", 720); touchConfigDict.Add("AbsX", 1024); touchConfigDict.Add("AbsY", 1024); tomlConfigTable.Add("TouchConfig", touchConfigDict); Dictionary <string, object> gameConfigDict = new Dictionary <string, object>(); gameConfigDict.Add("Language", 0); gameConfigDict.Add("Resolution", 0); gameConfigDict.Add("TouchScreenOrientation", 1); gameConfigDict.Add("EnableFreePlay", true); gameConfigDict.Add("AutoMode", 0); tomlConfigTable.Add("GameConfig", gameConfigDict); Toml.WriteFile(tomlConfigTable, Defines.ConfigFile); }
private static void CreateConfigFile() { // TODO: Make magic numbers for configs into constants defined in this class TomlTable tomlConfigTable = Toml.Create(); Rect screenRect = Util.GetScreenRect(); Boolean bEmptyRect = screenRect.width == 0 || screenRect.height == 0; Dictionary <string, object> touchConfigDict = new Dictionary <string, object>(); touchConfigDict.Add("WidthAxis", 0 /*along positive x-axis*/); touchConfigDict.Add("CalMinX", !bEmptyRect ? screenRect.xMin : 0); touchConfigDict.Add("CalMaxX", !bEmptyRect ? screenRect.xMax : 1280); touchConfigDict.Add("CalMinY", !bEmptyRect ? screenRect.yMin : 0); touchConfigDict.Add("CalMaxY", !bEmptyRect ? screenRect.yMax : 720); touchConfigDict.Add("AbsX", !bEmptyRect ? screenRect.width : 1024); touchConfigDict.Add("AbsY", !bEmptyRect ? screenRect.height : 1024); tomlConfigTable.Add("TouchConfig", touchConfigDict); Dictionary <string, object> gameConfigDict = new Dictionary <string, object>(); gameConfigDict.Add("Language", 0); gameConfigDict.Add("Resolution", 0); gameConfigDict.Add("TouchScreenOrientation", 0); gameConfigDict.Add("EnableFreePlay", true); gameConfigDict.Add("AutoMode", 0); tomlConfigTable.Add("GameConfig", gameConfigDict); Toml.WriteFile(tomlConfigTable, Defines.ConfigFile); }
public static TomlTable DictToTomlTable(Dictionary <string, string> dict) { var result = new TomlTable(); foreach (var kvp in dict) { result.Add(kvp.Key, kvp.Value); } return(result); }
public static TomlTable Apply(ITomlRoot root, TokenBuffer tokens) { TomlTable inlineTable = new TomlTable(root, TomlTable.TableTypes.Inline); tokens.ExpectAndConsume(TokenType.LCurly); if (!tokens.TryExpect(TokenType.RBrac)) { var kvp = KeyValuePairProduction.Apply(root, tokens); inlineTable.Add(kvp.Item1, kvp.Item2); while (tokens.TryExpect(TokenType.Comma)) { tokens.Consume(); kvp = KeyValuePairProduction.Apply(root, tokens); inlineTable.Add(kvp.Item1, kvp.Item2); } } tokens.ExpectAndConsume(TokenType.RCurly); return inlineTable; }
static CombineTablesTests() { X = Toml.Create(); X.Add(XKey, XVal); X.Add(SameKey, XVal); var xs = X.Add(SubTableKey, Toml.Create()); xs.Add(SubTableValueKey, XSubTableVal); Y = Toml.Create(); Y.Add(YKey, YVal); Y.Add(SameKey, YVal); var ys = Y.Add(SubTableKey, X.CreateEmptyAttachedTable()); ys.Add(SubTableValueKey, YSubTableVal); Dx = Toml.Create(); Dx.Add("a", (long)1); Dx.Add("c", (long)3).AddComment("xcc"); Dy = Toml.Create(); Dy.Add("b", (long)2).AddComment("ybc"); Dy.Add("c", (long)4).AddComment("ycc"); }
public void VerifyIssue29_WhenConversionHasError_TheErrorMessgeIsSomewhatUseful() { // Arrange var cfg = TomlSettings.Create(c => c .ConfigureType <Item>(type => type .WithConversionFor <TomlString>(conv => conv .FromToml(s => Item.Parse(s.Value))))); TomlTable tbl = Toml.Create(cfg); tbl.Add("Item", "Item Parse Value"); // Act Action a = () => tbl.Get <ItmRoot>(); // Assert a.ShouldThrow <InvalidOperationException>().WithMessage( "Failed to convert TOML object with key 'Item', type 'string' and value 'Item Parse Value' " + "to object property with name 'Item' and type 'Nett.Tests.VerifyIssuesTests+Item'.") .WithInnerMessage("Simulate conversion error"); }
private void SaveConfig() { TomlTable appSettings = Toml.Create(); appSettings.Add("ListenPort", ServerPort); if (ConfigTable.ContainsKey("Application")) { ConfigTable.Remove("Application"); } ConfigTable.Add("Application", appSettings); foreach (var item in Items) { (item as IConfigViewModel).SaveConfig(ConfigTable); } Toml.WriteFile(ConfigTable, CONFIG_FILE); }
public void ReplaceOrAdd(string dottedKey, string value) { string[] segments = dottedKey.Split("."); TomlTable table = this.document; for (int i = 0; i < segments.Length - 1; i++) { string tableKey = segments[i]; try { table = (TomlTable)table[tableKey]; } catch (KeyNotFoundException) { // Nett does not provide a function to easily add table subkeys. // A hack workaround is to serialize the table, append the new table as a string, then deserialize. // This only needs to be done once to create the new subtable. // After that, Nett functions can be used to modify the subtable. string tableName = string.Join(".", segments.Take(segments.Length - 1)); this.AddTable(tableName, segments[segments.Length - 1], value); return; } } string key = segments[segments.Length - 1]; if (table.ContainsKey(key)) { table.Update(key, value); } else { table.Add(key, value); } }
private static TomlTableArray GetExistingOrCreateAndAdd(TomlTable target, string name, Token errorPosition) { TomlObject existing = target.TryGetValue(name); var typed = existing as TomlTableArray; if (existing != null && typed == null) { throw Parser.CreateParseError( errorPosition, $"Cannot create array of tables with name '{name}' because there already is an row with that key of type '{existing.ReadableTypeName}'."); } else if (typed != null) { return typed; } var newTableArray = new TomlTableArray(target.Root); target.Add(name, newTableArray); return newTableArray; }
public static TomlTable TryApply(TomlTable current, TomlTable.RootTable root, TokenBuffer tokens) { tokens.ConsumeAllNewlines(); var preComments = CommentProduction.TryParsePreExpressionCommenst(tokens); var expressionToken = tokens.Peek(); tokens.ConsumeAllNewlines(); var arrayKeyChain = TomlArrayTableProduction.TryApply(tokens); if (arrayKeyChain != null) { var addTo = GetTargetTable(root, arrayKeyChain, CreateImplicitelyType.Table); var arr = GetExistingOrCreateAndAdd(addTo, arrayKeyChain.Last(), errorPosition: expressionToken); arr.Comments.AddRange(preComments); arr.Comments.AddRange(CommentProduction.TryParseAppendExpressionComments(expressionToken, tokens)); var newArrayEntry = new TomlTable(root); arr.Add(newArrayEntry); return newArrayEntry; } var tableKeyChain = TomlTableProduction.TryApply(tokens); if (tableKeyChain != null) { var newTable = new TomlTable(root) { IsDefined = true }; newTable.Comments.AddRange(preComments); newTable.Comments.AddRange(CommentProduction.TryParseAppendExpressionComments(expressionToken, tokens)); var addTo = GetTargetTable(root, tableKeyChain, CreateImplicitelyType.Table); string name = tableKeyChain.Last(); var existingRow = addTo.TryGetValue(name); if (existingRow == null) { addTo.Add(name, newTable); } else { var tbl = existingRow as TomlTable; if (tbl.IsDefined) { throw new Exception($"Failed to add new table because the target table already contains a row with the key '{name}' of type '{existingRow.ReadableTypeName}'."); } else { tbl.IsDefined = true; return tbl; } } return newTable; } if (!tokens.End) { var kvp = KeyValuePairProduction.Apply(root, tokens); if (kvp != null) { kvp.Item2.Comments.AddRange(preComments); kvp.Item2.Comments.AddRange(CommentProduction.TryParseAppendExpressionComments(expressionToken, tokens)); current.Add(kvp.Item1, kvp.Item2); return current; } } root.Comments.AddRange(preComments); return null; }
private static TomlTable GetExistingOrCreateAndAddTableArray(TomlTable tbl, string key) { Func<TomlTable, TomlTable> createNew = (e) => { var array = new TomlTableArray(tbl.Root); var newTable = new TomlTable(tbl.Root); array.Add(newTable); tbl.Add(key, array); return newTable; }; return GetExistinOrCreateAndAdd(tbl, key, createNew); }
// *** Convenience method for setting values to a toml object. *** public static TomlObject Set <T>(this TomlTable tomlTable, string key, T value) { if (tomlTable is null) { throw new ArgumentNullException(nameof(tomlTable)); } if (key is null) { throw new ArgumentNullException(nameof(key)); } // I literally have no idea how to write it better with this toml library. // Note for TimeSpan: since TimeSpan as Nett (de)serializes it is not standartized we have to cast it manually TomlObject retobj = tomlTable.TryGetValue(key); if (retobj is null) { if (typeof(T) == typeof(bool)) { return(tomlTable.Add(key, (bool)(object)value).Added); } else if (typeof(T) == typeof(string)) { return(tomlTable.Add(key, (string)(object)value).Added); } else if (typeof(T) == typeof(double)) { return(tomlTable.Add(key, (double)(object)value).Added); } else if (typeof(T) == typeof(float)) { return(tomlTable.Add(key, (float)(object)value).Added); } else if (typeof(T) == typeof(ushort)) { return(tomlTable.Add(key, /*auto*/ (ushort)(object)value).Added); } else if (typeof(T) == typeof(int)) { return(tomlTable.Add(key, (int)(object)value).Added); } else if (typeof(T) == typeof(long)) { return(tomlTable.Add(key, (long)(object)value).Added); } else if (typeof(T) == typeof(ulong)) { return(tomlTable.Add(key, (long)(ulong)(object)value).Added); } else if (typeof(T) == typeof(TimeSpan)) { return(tomlTable.Add(key, SerializeTime((TimeSpan)(object)value)).Added); } else if (typeof(T) == typeof(DateTime)) { return(tomlTable.Add(key, (DateTime)(object)value).Added); } else if (typeof(T).IsEnum) { return(tomlTable.Add(key, value.ToString()).Added); } else if (value is IEnumerable <bool> enubool) { return(tomlTable.Add(key, enubool).Added); } else if (value is IEnumerable <string> enustring) { return(tomlTable.Add(key, enustring).Added); } else if (value is IEnumerable <double> enudouble) { return(tomlTable.Add(key, enudouble).Added); } else if (value is IEnumerable <float> enufloat) { return(tomlTable.Add(key, enufloat).Added); } else if (value is IEnumerable <ushort> enuushort) { return(tomlTable.Add(key, enuushort.Select(x => (int)x)).Added); } else if (value is IEnumerable <int> enuint) { return(tomlTable.Add(key, enuint).Added); } else if (value is IEnumerable <long> enulong) { return(tomlTable.Add(key, enulong).Added); } else if (value is IEnumerable <ulong> enuulong) { return(tomlTable.Add(key, enuulong.Select(x => (long)x)).Added); } else if (value is IEnumerable <TimeSpan> enuTimeSpan) { return(tomlTable.Add(key, enuTimeSpan.Select(SerializeTime)).Added); } else if (value is IEnumerable <DateTime> enuDateTime) { return(tomlTable.Add(key, enuDateTime).Added); } } else { TomlComment[] docs = null; if (retobj.Comments.Any()) { docs = retobj.Comments.ToArray(); } if (typeof(T) == typeof(bool)) { retobj = tomlTable.Update(key, (bool)(object)value).Added; } else if (typeof(T) == typeof(string)) { retobj = tomlTable.Update(key, (string)(object)value).Added; } else if (typeof(T) == typeof(double)) { retobj = tomlTable.Update(key, (double)(object)value).Added; } else if (typeof(T) == typeof(float)) { retobj = tomlTable.Update(key, (float)(object)value).Added; } else if (typeof(T) == typeof(ushort)) { retobj = tomlTable.Update(key, /*auto*/ (ushort)(object)value).Added; } else if (typeof(T) == typeof(int)) { retobj = tomlTable.Update(key, /*auto*/ (int)(object)value).Added; } else if (typeof(T) == typeof(long)) { retobj = tomlTable.Update(key, (long)(object)value).Added; } else if (typeof(T) == typeof(ulong)) { retobj = tomlTable.Update(key, (long)(ulong)(object)value).Added; } else if (typeof(T) == typeof(TimeSpan)) { retobj = tomlTable.Update(key, SerializeTime((TimeSpan)(object)value)).Added; } else if (typeof(T) == typeof(DateTime)) { retobj = tomlTable.Update(key, (DateTime)(object)value).Added; } else if (typeof(T).IsEnum) { retobj = tomlTable.Update(key, value.ToString()).Added; } else if (value is IEnumerable <bool> enubool) { return(tomlTable.Update(key, enubool).Added); } else if (value is IEnumerable <string> enustring) { return(tomlTable.Update(key, enustring).Added); } else if (value is IEnumerable <double> enudouble) { return(tomlTable.Update(key, enudouble).Added); } else if (value is IEnumerable <float> enufloat) { return(tomlTable.Update(key, enufloat).Added); } else if (value is IEnumerable <ushort> enuushort) { return(tomlTable.Update(key, enuushort.Select(x => (int)x)).Added); } else if (value is IEnumerable <int> enuint) { return(tomlTable.Update(key, enuint).Added); } else if (value is IEnumerable <long> enulong) { return(tomlTable.Update(key, enulong).Added); } else if (value is IEnumerable <ulong> enuulong) { return(tomlTable.Update(key, enuulong.Select(x => (long)x)).Added); } else if (value is IEnumerable <TimeSpan> enuTimeSpan) { return(tomlTable.Update(key, enuTimeSpan.Select(SerializeTime)).Added); } else if (value is IEnumerable <DateTime> enuDateTime) { return(tomlTable.Update(key, enuDateTime).Added); } else { throw new NotSupportedException("The type is not supported"); } if (docs != null) { retobj.AddComments(docs); } return(retobj); } throw new NotSupportedException("The type is not supported"); }
// Seriously, f**k this TOML Library. // WHY DOESN'T IT SUPPORT GENERICS public TomlObject SetValueInternal <T>(string key, T value, string comment) { TomlObject field; if (value is bool) { bool v = (bool)(object)value; field = _settings.ContainsKey(key) ? _settings.Update(key, v) : field = _settings.Add(key, v); } else if (value is string) { string v = (string)(object)value; field = _settings.ContainsKey(key) ? _settings.Update(key, v) : field = _settings.Add(key, v); } else if (value is int) { int v = (int)(object)value; field = _settings.ContainsKey(key) ? _settings.Update(key, v) : field = _settings.Add(key, v); } else if (value is float) { float v = (float)(object)value; field = _settings.ContainsKey(key) ? _settings.Update(key, v) : field = _settings.Add(key, v); } else { throw new NotSupportedException(); } AttatchComments(field, comment); Flush(); return(field); }
/// <summary> /// Saves the current configuration out to the config file. /// </summary> public void Save() { // Physical Paramters TomlTable physicalParameters = Toml.Create(); // Passes TomlInt passes = physicalParameters.Add("Passes", Passes).Added; passes.AddComment(" The number of times to run the complete etching path", CommentLocation.Append); // PixelSize TomlFloat pixelSize = physicalParameters.Add("PixelSize", PixelSize).Added; pixelSize.AddComment(" The size of each pixel (mm per pixel)", CommentLocation.Append); // OriginX TomlFloat originX = physicalParameters.Add("OriginX", OriginX).Added; originX.AddComment(" The X coordinate of the top-left corner, in mm", CommentLocation.Append); // OriginY TomlFloat originY = physicalParameters.Add("OriginY", OriginY).Added; originY.AddComment(" The Y coordinate of the top-left corner, in mm", CommentLocation.Append); // ZHeight TomlFloat zHeight = physicalParameters.Add("ZHeight", ZHeight).Added; zHeight.AddComment(" The Z height to set the laser cutter during etching, in mm", CommentLocation.Append); // TravelSpeed TomlFloat travelSpeed = physicalParameters.Add("TravelSpeed", TravelSpeed).Added; travelSpeed.AddComment(" The speed to move the head between etching operations (when the laser is off), in mm per minute", CommentLocation.Append); // EtchSpeed TomlFloat etchSpeed = physicalParameters.Add("EtchSpeed", EtchSpeed).Added; etchSpeed.AddComment(" The speed to move the head during etching operations (when the laser is on), in mm per minute", CommentLocation.Append); // G-code Commands TomlTable gCodeCommands = Toml.Create(); // LaserOffCommand TomlString laserOffCommand = gCodeCommands.Add("LaserOffCommand", LaserOffCommand).Added; laserOffCommand.AddComment(" The G-code command to turn the laser off", CommentLocation.Append); // LaserLowCommand TomlString laserLowCommand = gCodeCommands.Add("LaserLowCommand", LaserLowCommand).Added; laserLowCommand.AddComment(" The G-code command to turn the laser on, but at a low power level (used for the pre-etch trace preview)", CommentLocation.Append); // LaserHighCommand TomlString laserHighCommand = gCodeCommands.Add("LaserHighCommand", LaserHighCommand).Added; laserHighCommand.AddComment(" The G-code command to turn the laser on full power during etching", CommentLocation.Append); // MoveCommand TomlString moveCommand = gCodeCommands.Add("MoveCommand", MoveCommand).Added; moveCommand.AddComment(" The G-code command to use during moves", CommentLocation.Append); // CommentMode TomlString commentMode = gCodeCommands.Add("CommentMode", CommentMode.ToString()).Added; commentMode.AddComment(" The G-code comment format to use (Semicolon or Parentheses)", CommentLocation.Append); // HomeXY TomlBool homeXY = gCodeCommands.Add("HomeXY", HomeXY).Added; homeXY.AddComment(" True to home the X and Y axes at the start, false to leave them where they were and assume that they are already homed", CommentLocation.Append); // Pre-Etch Trace Preview TomlTable preEtchTracePreview = Toml.Create(); // IsBoundaryPreviewEnabled TomlBool isBoundaryPreviewEnabled = preEtchTracePreview.Add("IsBoundaryPreviewEnabled", IsBoundaryPreviewEnabled).Added; isBoundaryPreviewEnabled.AddComment(" True to perform the pre-etch boundary trace preview, false to disable it and get right to etching", CommentLocation.Append); // PreviewDelay TomlInt previewDelay = preEtchTracePreview.Add("PreviewDelay", PreviewDelay).Added; previewDelay.AddComment(" The delay, in milliseconds, to wait at the start and end of the pre-etch trace preview", CommentLocation.Append); TomlTable settingsTable = Toml.Create(); settingsTable.Add("Physical-Parameters", physicalParameters); settingsTable.Add("G-Code-Commands", gCodeCommands); settingsTable.Add("Pre-Etch-Trace-Preview", preEtchTracePreview); Toml.WriteFile(settingsTable, ConfigFileName); }