diff --git a/.editorconfig b/.editorconfig index fc58240a..96958cfa 100644 --- a/.editorconfig +++ b/.editorconfig @@ -164,3 +164,5 @@ dotnet_diagnostic.IDE0052.severity = none # Disable "IDE0130: Namespace does not match folder structure" because VS Code Cleanup applies it automatically and breaks things. dotnet_style_namespace_match_folder = false + +spelling_exclusion_path = exclusion.dic diff --git a/FactorioCalc.sln b/FactorioCalc.sln index 477a63bc..32a136cb 100644 --- a/FactorioCalc.sln +++ b/FactorioCalc.sln @@ -19,6 +19,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution ProjectSection(SolutionItems) = preProject changelog.txt = changelog.txt Directory.Build.props = Directory.Build.props + exclusion.dic = exclusion.dic EndProjectSection EndProject Global diff --git a/Yafc.Model.Tests/Data/DataUtils.cs b/Yafc.Model.Tests/Data/DataUtils.cs index 0d290946..9bbfd740 100644 --- a/Yafc.Model.Tests/Data/DataUtils.cs +++ b/Yafc.Model.Tests/Data/DataUtils.cs @@ -4,9 +4,7 @@ namespace Yafc.Model.Data.Tests; public class DataUtilsTests { - public DataUtilsTests() { - Project.current = new(); - } + public DataUtilsTests() => Project.current = new(); [Fact] public void TryParseAmount_IsInverseOfFormatValue() { @@ -49,7 +47,7 @@ public void TryParseAmount_IsInverseOfFormatValue() { [Fact] public void TryParseAmount_IsInverseOfFormatValue_WithBeltsAndPipes() { // Hammer the formatter and parser with lots of random but repeatable values, making sure TryParseAmount can correctly read anything FormatAmount generates. - // This time, include b and p suffixes. These suffixes noticably reduce precision, so do them separately. + // This time, include b and p suffixes. These suffixes noticeably reduce precision, so do them separately. Random r = new Random(0); byte[] bytes = new byte[4]; for (int i = 0; i < 1000; i++) { diff --git a/Yafc.Model.Tests/Data/LocalisedStringParserTests.cs b/Yafc.Model.Tests/Data/LocalisedStringParserTests.cs index a0db9e41..c1312057 100644 --- a/Yafc.Model.Tests/Data/LocalisedStringParserTests.cs +++ b/Yafc.Model.Tests/Data/LocalisedStringParserTests.cs @@ -4,63 +4,61 @@ namespace Yafc.Model.Data.Tests; public class LocalisedStringParserTests { - public LocalisedStringParserTests() { - FactorioLocalization.Initialize(new System.Collections.Generic.Dictionary() { - ["hours"] = "__1__ __plural_for_parameter__1__{1=hour|rest=hours}__", - ["si-unit-kilometer-per-hour"] = "__1__ km/h", - ["not-enough-ingredients"] = "Not enough ingredients.", - ["item-name.iron-plate"] = "Iron plate", - ["item-name.big-iron-plate"] = "Big __ITEM__iron-plate__", - ["connecting"] = "__plural_for_parameter__1__{1=__1__ player is|rest=__1__ players are}__ connecting", - ["ends.in"] = "__plural_for_parameter__1__{ends in 12=option 1|ends in 2=option 2|rest=option 3}__" - }); - } + public LocalisedStringParserTests() => FactorioLocalization.Initialize(new System.Collections.Generic.Dictionary() { + ["hours"] = "__1__ __plural_for_parameter__1__{1=hour|rest=hours}__", + ["si-unit-kilometer-per-hour"] = "__1__ km/h", + ["not-enough-ingredients"] = "Not enough ingredients.", + ["item-name.iron-plate"] = "Iron plate", + ["item-name.big-iron-plate"] = "Big __ITEM__iron-plate__", + ["connecting"] = "__plural_for_parameter__1__{1=__1__ player is|rest=__1__ players are}__ connecting", + ["ends.in"] = "__plural_for_parameter__1__{ends in 12=option 1|ends in 2=option 2|rest=option 3}__" + }); [Fact] public void Parse_JustString() { - var localised = LocalisedStringParser.Parse("test"); + string localised = LocalisedStringParser.Parse("test"); Assert.Equal("test", localised); } [Fact] public void Parse_RemoveRichText() { - var localised = LocalisedStringParser.Parse("[color=#ffffff]iron[/color] [color=1,0,0]plate[.color] [item=iron-plate]"); + string localised = LocalisedStringParser.Parse("[color=#ffffff]iron[/color] [color=1,0,0]plate[.color] [item=iron-plate]"); Assert.Equal("iron plate ", localised); } [Fact] public void Parse_NoParameters() { - var localised = LocalisedStringParser.Parse("not-enough-ingredients", []); + string localised = LocalisedStringParser.Parse("not-enough-ingredients", []); Assert.Equal("Not enough ingredients.", localised); } [Fact] public void Parse_Parameter() { - var localised = LocalisedStringParser.Parse("si-unit-kilometer-per-hour", ["100"]); + string localised = LocalisedStringParser.Parse("si-unit-kilometer-per-hour", ["100"]); Assert.Equal("100 km/h", localised); } [Fact] public void Parse_LinkItem() { - var localised = LocalisedStringParser.Parse("item-name.big-iron-plate", []); + string localised = LocalisedStringParser.Parse("item-name.big-iron-plate", []); Assert.Equal("Big Iron plate", localised); } [Fact] public void Parse_PluralSpecial() { - var localised = LocalisedStringParser.Parse("hours", ["1"]); + string localised = LocalisedStringParser.Parse("hours", ["1"]); Assert.Equal("1 hour", localised); } [Fact] public void Parse_PluralRest() { - var localised = LocalisedStringParser.Parse("hours", ["2"]); + string localised = LocalisedStringParser.Parse("hours", ["2"]); Assert.Equal("2 hours", localised); } [Fact] public void Parse_PluralWithParameter() { - var localised = LocalisedStringParser.Parse("connecting", ["1"]); + string localised = LocalisedStringParser.Parse("connecting", ["1"]); Assert.Equal("1 player is connecting", localised); } @@ -69,7 +67,7 @@ public void Parse_PluralWithParameter() { [InlineData(22, "option 2")] [InlineData(5, "option 3")] public void Parse_PluralEndsIn(int n, string expectedResult) { - var localised = LocalisedStringParser.Parse("ends.in", [n.ToString()]); + string localised = LocalisedStringParser.Parse("ends.in", [n.ToString()]); Assert.Equal(expectedResult, localised); } } diff --git a/Yafc.Model.Tests/LuaDependentTestHelper.cs b/Yafc.Model.Tests/LuaDependentTestHelper.cs index c00b400b..83210444 100644 --- a/Yafc.Model.Tests/LuaDependentTestHelper.cs +++ b/Yafc.Model.Tests/LuaDependentTestHelper.cs @@ -33,7 +33,7 @@ static LuaDependentTestHelper() { /// Do not use require in the embedded files. /// The name of the embedded resource to load, if the default name selection does not work for you. internal static Project GetProjectForLua(string targetStreamName = null) { - // Verify correct non-parallel declaration for tests, to accomodate the singleton analyses. + // Verify correct non-parallel declaration for tests, to accommodate the singleton analyses. StackTrace stack = new(); for (int i = 1; i < stack.FrameCount; i++) { diff --git a/Yafc.Model.Tests/Model/ProductionTableContentTests.cs b/Yafc.Model.Tests/Model/ProductionTableContentTests.cs index 3437aa73..30ab5de2 100644 --- a/Yafc.Model.Tests/Model/ProductionTableContentTests.cs +++ b/Yafc.Model.Tests/Model/ProductionTableContentTests.cs @@ -79,7 +79,7 @@ void testCombinations(RecipeRow row, ProductionTable table, Action assert) { for (int beaconCount = 0; beaconCount < 13; beaconCount++) { for (float payback = 1; payback < float.MaxValue; payback *= 16) { if (table.GetType().GetProperty("modules").SetMethod is MethodInfo method) { - // Pre-emptive code for if ProductionTable.modules is made writable. + // Preemptive code for if ProductionTable.modules is made writable. // The ProductionTable.modules setter must notify all relevant recipes if it is added. _ = method.Invoke(table, [new ModuleFillerParameters(table) { beacon = new(beacon, Quality.Normal), @@ -103,7 +103,7 @@ void testCombinations(RecipeRow row, ProductionTable table, Action assert) { } /// - /// Run the preceeding tests for fixed buildings, fuel, ingredients, and products. + /// Run the preceding tests for fixed buildings, fuel, ingredients, and products. /// /// The row containing the recipe to test with fixed amounts. /// An action that loops through the various combinations of entities, beacons, etc, and calls its third parameter for each combination. diff --git a/Yafc.Model.Tests/Model/RecipeParametersTests.cs b/Yafc.Model.Tests/Model/RecipeParametersTests.cs index e2263695..c6b8b077 100644 --- a/Yafc.Model.Tests/Model/RecipeParametersTests.cs +++ b/Yafc.Model.Tests/Model/RecipeParametersTests.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Xunit; namespace Yafc.Model.Tests.Model; @@ -7,7 +8,7 @@ namespace Yafc.Model.Tests.Model; [Collection("LuaDependentTests")] public class RecipeParametersTests { [Fact] - public void FluidBoilingRecipes_HaveCorrectConsumption() { + public async Task FluidBoilingRecipes_HaveCorrectConsumption() { Project project = LuaDependentTestHelper.GetProjectForLua(); ProjectPage page = new(project, typeof(ProductionTable)); @@ -22,7 +23,7 @@ public void FluidBoilingRecipes_HaveCorrectConsumption() { RecipeRow heatExchanger = table.recipes[1]; boiler.fixedBuildings = 1; heatExchanger.fixedBuildings = 1; - table.Solve((ProjectPage)table.owner).Wait(); // Initial Solve to set RecipeRow.Ingredients + await table.Solve((ProjectPage)table.owner); // Initial Solve to set RecipeRow.Ingredients for (int i = 0; i < 3; i++) { if (i != 0) { @@ -32,7 +33,7 @@ public void FluidBoilingRecipes_HaveCorrectConsumption() { boiler.ChangeVariant(boiler.Ingredients.Single().Goods, water[i]); heatExchanger.ChangeVariant(boiler.Ingredients.Single().Goods, water[i]); - table.Solve((ProjectPage)table.owner).Wait(); + await table.Solve((ProjectPage)table.owner); // boil 60, 78.26, 120 water per second from 15, 50, 90° to 165° float expectedBoilerAmount = 1800 / .2f / (165 - water[i].temperature); diff --git a/Yafc.Model.Tests/Model/SelectableVariantsTests.cs b/Yafc.Model.Tests/Model/SelectableVariantsTests.cs index 0a919ac6..d2cb75a1 100644 --- a/Yafc.Model.Tests/Model/SelectableVariantsTests.cs +++ b/Yafc.Model.Tests/Model/SelectableVariantsTests.cs @@ -1,4 +1,5 @@ using System.Linq; +using System.Threading.Tasks; using Xunit; namespace Yafc.Model.Tests.Model; @@ -6,7 +7,7 @@ namespace Yafc.Model.Tests.Model; [Collection("LuaDependentTests")] public class SelectableVariantsTests { [Fact] - public void CanSelectVariantFuel_VariantFuelChanges() { + public async Task CanSelectVariantFuel_VariantFuelChanges() { Project project = LuaDependentTestHelper.GetProjectForLua(); ProjectPage page = new ProjectPage(project, typeof(ProductionTable)); @@ -15,16 +16,16 @@ public void CanSelectVariantFuel_VariantFuelChanges() { RecipeRow row = table.GetAllRecipes().Single(); // Solve is not necessary in this test, but I'm calling it in case we decide to hide the fuel on disabled recipes. - table.Solve((ProjectPage)table.owner).Wait(); + await table.Solve((ProjectPage)table.owner); Assert.Equal("steam@165", row.FuelInformation.Goods.name); row.fuel = row.FuelInformation.Variants[1]; - table.Solve((ProjectPage)table.owner).Wait(); + await table.Solve((ProjectPage)table.owner); Assert.Equal("steam@500", row.FuelInformation.Goods.name); } [Fact] - public void CanSelectVariantFuelWithFavorites_VariantFuelChanges() { + public async Task CanSelectVariantFuelWithFavorites_VariantFuelChanges() { Project project = LuaDependentTestHelper.GetProjectForLua(); project.preferences.ToggleFavorite(Database.fluids.all.Single(c => c.name == "steam@500")); @@ -34,16 +35,16 @@ public void CanSelectVariantFuelWithFavorites_VariantFuelChanges() { RecipeRow row = table.GetAllRecipes().Single(); // Solve is not necessary in this test, but I'm calling it in case we decide to hide the fuel on disabled recipes. - table.Solve((ProjectPage)table.owner).Wait(); + await table.Solve((ProjectPage)table.owner); Assert.Equal("steam@500", row.FuelInformation.Goods.name); row.fuel = row.FuelInformation.Variants[0]; - table.Solve((ProjectPage)table.owner).Wait(); + await table.Solve((ProjectPage)table.owner); Assert.Equal("steam@165", row.FuelInformation.Goods.name); } [Fact] - public void CanSelectVariantIngredient_VariantIngredientChanges() { + public async Task CanSelectVariantIngredient_VariantIngredientChanges() { Project project = LuaDependentTestHelper.GetProjectForLua(); ProjectPage page = new ProjectPage(project, typeof(ProductionTable)); @@ -52,11 +53,11 @@ public void CanSelectVariantIngredient_VariantIngredientChanges() { RecipeRow row = table.GetAllRecipes().Single(); // Solve is necessary here: Disabled recipes have null ingredients (and products), and Solve is the call that updates hierarchyEnabled. - table.Solve((ProjectPage)table.owner).Wait(); + await table.Solve((ProjectPage)table.owner); Assert.Equal("steam@165", row.Ingredients.Single().Goods.name); row.ChangeVariant(row.Ingredients.Single().Goods, row.Ingredients.Single().Variants[1]); - table.Solve((ProjectPage)table.owner).Wait(); + await table.Solve((ProjectPage)table.owner); Assert.Equal("steam@500", row.Ingredients.Single().Goods.name); } diff --git a/Yafc.Model.Tests/PrepareForTests.cs b/Yafc.Model.Tests/PrepareForTests.cs index 4ae2628c..f8731cc3 100644 --- a/Yafc.Model.Tests/PrepareForTests.cs +++ b/Yafc.Model.Tests/PrepareForTests.cs @@ -10,7 +10,5 @@ namespace Yafc.Model.Tests; public class PrepareForTests : XunitTestFramework { public PrepareForTests(IMessageSink messageSink) - : base(messageSink) { - Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; - } + : base(messageSink) => Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; } diff --git a/Yafc.Model.Tests/Yafc.Model.Tests.csproj b/Yafc.Model.Tests/Yafc.Model.Tests.csproj index eb607963..0abfb0f1 100644 --- a/Yafc.Model.Tests/Yafc.Model.Tests.csproj +++ b/Yafc.Model.Tests/Yafc.Model.Tests.csproj @@ -5,9 +5,9 @@ - - - + + + runtime; build; native; contentfiles; analyzers; buildtransitive all diff --git a/Yafc.Model/Analysis/Dependencies.cs b/Yafc.Model/Analysis/Dependencies.cs index e843e146..32e394a4 100644 --- a/Yafc.Model/Analysis/Dependencies.cs +++ b/Yafc.Model/Analysis/Dependencies.cs @@ -31,8 +31,8 @@ public enum Flags { } public static class Dependencies { - public static Mapping dependencyList; - public static Mapping> reverseDependencies; + public static Mapping dependencyList { get; private set; } + public static Mapping> reverseDependencies { get; private set; } public static void Calculate() { dependencyList = Database.objects.CreateMapping(); diff --git a/Yafc.Model/Data/DataUtils.cs b/Yafc.Model/Data/DataUtils.cs index 875dbcca..c709474e 100644 --- a/Yafc.Model/Data/DataUtils.cs +++ b/Yafc.Model/Data/DataUtils.cs @@ -592,7 +592,7 @@ public static string FormatAmountRaw(float amount, float unitMultiplier, string? /// True if the string could be parsed as the specified unit, false otherwise. /// Thrown when is . public static bool TryParseAmount(string str, out float amount, UnitOfMeasure unit) { - if (unit is UnitOfMeasure.Celsius) { throw new ArgumentException("Parsing to UnitOfMeasure.Celcius is not supported.", nameof(unit)); } + if (unit is UnitOfMeasure.Celsius) { throw new ArgumentException("Parsing to UnitOfMeasure.Celsius is not supported.", nameof(unit)); } var (mul, _) = Project.current.ResolveUnitOfMeasure(unit); float multiplier = unit is UnitOfMeasure.Megawatt or UnitOfMeasure.Megajoule ? 1e6f : 1f; diff --git a/Yafc.Model/Model/ProductionTable.cs b/Yafc.Model/Model/ProductionTable.cs index c3b6b47a..d4fce67c 100644 --- a/Yafc.Model/Model/ProductionTable.cs +++ b/Yafc.Model/Model/ProductionTable.cs @@ -316,7 +316,7 @@ private void CalculateFlow(RecipeRow? include) { /// Add/update the variable value for the constraint with the given amount, and store the recipe to the production link. /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - private static void AddLinkCoef(Constraint cst, Variable var, ProductionLink link, RecipeRow recipe, float amount) { + private static void AddLinkCoefficient(Constraint cst, Variable var, ProductionLink link, RecipeRow recipe, float amount) { // GetCoefficient will return 0 when the variable is not available in the constraint amount += (float)cst.GetCoefficient(var); _ = link.capturedRecipes.Add(recipe); @@ -331,7 +331,7 @@ private static void AddLinkCoef(Constraint cst, Variable var, ProductionLink lin List allLinks = []; Setup(allRecipes, allLinks); Variable[] vars = new Variable[allRecipes.Count]; - float[] objCoefs = new float[allRecipes.Count]; + float[] objCoefficients = new float[allRecipes.Count]; for (int i = 0; i < allRecipes.Count; i++) { var recipe = allRecipes[i]; @@ -372,11 +372,11 @@ private static void AddLinkCoef(Constraint cst, Variable var, ProductionLink lin if (recipe.FindLink(product.goods, out var link)) { link.flags |= ProductionLink.Flags.HasProduction; float added = product.GetAmountPerRecipe(recipe.parameters.productivity); - AddLinkCoef(constraints[link.solverIndex], recipeVar, link, recipe, added); + AddLinkCoefficient(constraints[link.solverIndex], recipeVar, link, recipe, added); float cost = product.goods.Cost(); if (cost > 0f) { - objCoefs[i] += added * cost; + objCoefficients[i] += added * cost; } } @@ -389,7 +389,7 @@ private static void AddLinkCoef(Constraint cst, Variable var, ProductionLink lin if (recipe.FindLink(option, out var link)) { link.flags |= ProductionLink.Flags.HasConsumption; - AddLinkCoef(constraints[link.solverIndex], recipeVar, link, recipe, -ingredient.amount); + AddLinkCoefficient(constraints[link.solverIndex], recipeVar, link, recipe, -ingredient.amount); } links.ingredients[j] = link; @@ -404,16 +404,16 @@ private static void AddLinkCoef(Constraint cst, Variable var, ProductionLink lin if (recipe.FindLink(recipe.fuel, out var link)) { links.fuel = link; link.flags |= ProductionLink.Flags.HasConsumption; - AddLinkCoef(constraints[link.solverIndex], recipeVar, link, recipe, -fuelAmount); + AddLinkCoefficient(constraints[link.solverIndex], recipeVar, link, recipe, -fuelAmount); } if (recipe.fuel.HasSpentFuel(out var spentFuel) && recipe.FindLink(spentFuel, out link)) { links.spentFuel = link; link.flags |= ProductionLink.Flags.HasProduction; - AddLinkCoef(constraints[link.solverIndex], recipeVar, link, recipe, fuelAmount); + AddLinkCoefficient(constraints[link.solverIndex], recipeVar, link, recipe, fuelAmount); if (spentFuel.Cost() > 0f) { - objCoefs[i] += fuelAmount * spentFuel.Cost(); + objCoefficients[i] += fuelAmount * spentFuel.Cost(); } } } diff --git a/Yafc.Model/Model/ProductionTableContent.cs b/Yafc.Model/Model/ProductionTableContent.cs index e2e202e2..baa443cf 100644 --- a/Yafc.Model/Model/ProductionTableContent.cs +++ b/Yafc.Model/Model/ProductionTableContent.cs @@ -612,7 +612,7 @@ public ChangeModulesOrEntity(RecipeRow row) { oldFuel = row.fuel; row.fuel = Database.voidEnergy; // step 1 } - // Store the current state of the target RecipeRow for the calcualations in Dispose + // Store the current state of the target RecipeRow for the calculations in Dispose oldParameters = RecipeParameters.CalculateParameters(row); } diff --git a/Yafc.Model/Model/Project.cs b/Yafc.Model/Model/Project.cs index c6dd8064..43bb8893 100644 --- a/Yafc.Model/Model/Project.cs +++ b/Yafc.Model/Model/Project.cs @@ -72,50 +72,50 @@ protected internal override void ThisChanged(bool visualOnly) { } public static Project ReadFromFile(string path, ErrorCollector collector) { - Project? proj; + Project? project; if (!string.IsNullOrEmpty(path) && File.Exists(path)) { - proj = Read(File.ReadAllBytes(path), collector); + project = Read(File.ReadAllBytes(path), collector); } else { - proj = new Project(); + project = new Project(); } - proj.attachedFileName = path; - proj.lastSavedVersion = proj.projectVersion; + project.attachedFileName = path; + project.lastSavedVersion = project.projectVersion; - return proj; + return project; } public static Project Read(byte[] bytes, ErrorCollector collector) { - Project? proj; + Project? project; Utf8JsonReader reader = new Utf8JsonReader(bytes); _ = reader.Read(); DeserializationContext context = new DeserializationContext(collector); - proj = SerializationMap.DeserializeFromJson(null, ref reader, context); + project = SerializationMap.DeserializeFromJson(null, ref reader, context); if (!reader.IsFinalBlock) { collector.Error("Json was not consumed to the end!", ErrorSeverity.MajorDataLoss); } - if (proj == null) { + if (project == null) { throw new SerializationException("Unable to load project file"); } - proj.justCreated = false; - Version version = new Version(proj.yafcVersion ?? "0.0"); + project.justCreated = false; + Version version = new Version(project.yafcVersion ?? "0.0"); if (version != currentYafcVersion) { if (version > currentYafcVersion) { collector.Error("This file was created with future YAFC version. This may lose data.", ErrorSeverity.Important); } - proj.yafcVersion = currentYafcVersion.ToString(); + project.yafcVersion = currentYafcVersion.ToString(); } context.Notify(); - return proj; + return project; } public void Save(string fileName) { diff --git a/Yafc.Model/Serialization/SerializationMap.cs b/Yafc.Model/Serialization/SerializationMap.cs index 9b7c37df..e6d81aa6 100644 --- a/Yafc.Model/Serialization/SerializationMap.cs +++ b/Yafc.Model/Serialization/SerializationMap.cs @@ -312,7 +312,7 @@ public bool Deserialize(ref Utf8JsonReader reader, DeserializationContext contex if (typeof(ICustomJsonDeserializer).IsAssignableFrom(typeof(T))) { // I want to do `((ICustomJsonDeserializer)T).Deserialize(...)`, but that isn't supported. // This and its helper types call ICustomJsonDeserializer.Deserialize by the least obscure method I could come up with. - var helper = (ICustomDeserializerHelper)Activator.CreateInstance(typeof(CustomDeserializerHelper<>).MakeGenericType(typeof(T), typeof(T)))!; + ICustomDeserializerHelper helper = (ICustomDeserializerHelper)Activator.CreateInstance(typeof(CustomDeserializerHelper<>).MakeGenericType(typeof(T), typeof(T)))!; Utf8JsonReader savedState = reader; if (helper.Deserialize(ref reader, context, out T? result)) { // The custom deserializer was successful; return its result. diff --git a/Yafc.Model/Yafc.Model.csproj b/Yafc.Model/Yafc.Model.csproj index 189756ff..c92c8a84 100644 --- a/Yafc.Model/Yafc.Model.csproj +++ b/Yafc.Model/Yafc.Model.csproj @@ -7,7 +7,7 @@ - + diff --git a/Yafc.Parser/Data/FactorioDataDeserializer.cs b/Yafc.Parser/Data/FactorioDataDeserializer.cs index ccede5be..d3f50c6d 100644 --- a/Yafc.Parser/Data/FactorioDataDeserializer.cs +++ b/Yafc.Parser/Data/FactorioDataDeserializer.cs @@ -237,13 +237,13 @@ private unsafe Icon CreateIconFromSpec(Dictionary<(string mod, string path), Int _ = SDL.SDL_SetSurfaceBlendMode(targetSurface, SDL.SDL_BlendMode.SDL_BLENDMODE_BLEND); foreach (var icon in spec) { - var modpath = FactorioDataSource.ResolveModPath("", icon.path); + var modPath = FactorioDataSource.ResolveModPath("", icon.path); - if (!cache.TryGetValue(modpath, out nint image)) { - byte[] imageSource = FactorioDataSource.ReadModFile(modpath.mod, modpath.path); + if (!cache.TryGetValue(modPath, out nint image)) { + byte[] imageSource = FactorioDataSource.ReadModFile(modPath.mod, modPath.path); if (imageSource == null) { - image = cache[modpath] = IntPtr.Zero; + image = cache[modPath] = IntPtr.Zero; } else { fixed (byte* data = imageSource) { @@ -265,7 +265,7 @@ private unsafe Icon CreateIconFromSpec(Dictionary<(string mod, string path), Int image = SoftwareScaler.DownscaleIcon(image, iconSize); } } - cache[modpath] = image; + cache[modPath] = image; } } } @@ -347,15 +347,13 @@ private static float ParseEnergy(string? energy) { return float.Parse(energy[..^1]) * 1e-6f; } - private static Effect ParseEffect(LuaTable table) { - return new Effect { - consumption = table.Get("consumption", 0f), - speed = table.Get("speed", 0f), - productivity = table.Get("productivity", 0f), - pollution = table.Get("pollution", 0f), - quality = table.Get("quality", 0f), - }; - } + private static Effect ParseEffect(LuaTable table) => new Effect { + consumption = table.Get("consumption", 0f), + speed = table.Get("speed", 0f), + productivity = table.Get("productivity", 0f), + pollution = table.Get("pollution", 0f), + quality = table.Get("quality", 0f), + }; private static EffectReceiver ParseEffectReceiver(LuaTable? table) { if (table == null) { diff --git a/Yafc.Parser/Data/FactorioDataDeserializer_Context.cs b/Yafc.Parser/Data/FactorioDataDeserializer_Context.cs index 33494f46..71c4a880 100644 --- a/Yafc.Parser/Data/FactorioDataDeserializer_Context.cs +++ b/Yafc.Parser/Data/FactorioDataDeserializer_Context.cs @@ -345,7 +345,7 @@ private void CalculateMaps(bool netProduction) { entityPlacers.Add(GetObject(name), item); } } - if (plantResults.TryGetValue(item, out var plantResultName)) { + if (plantResults.TryGetValue(item, out string? plantResultName)) { item.plantResult = GetObject(plantResultName); entityPlacers.Add(GetObject(plantResultName), item); } diff --git a/Yafc.Parser/Data/FactorioDataDeserializer_Entity.cs b/Yafc.Parser/Data/FactorioDataDeserializer_Entity.cs index c0052317..9dd12536 100644 --- a/Yafc.Parser/Data/FactorioDataDeserializer_Entity.cs +++ b/Yafc.Parser/Data/FactorioDataDeserializer_Entity.cs @@ -266,9 +266,9 @@ private void DeserializeEntity(LuaTable table, ErrorCollector errorCollector) { recipeCrafters.Add(boiler, category); recipe.flags |= RecipeFlags.UsesFluidTemperature; // TODO: input fluid amount now depends on its temperature, using min temperature should be OK for non-modded - var inputEnergyPerOneFluid = (targetTemp - acceptTemperature.min) * input.heatCapacity; + float inputEnergyPerOneFluid = (targetTemp - acceptTemperature.min) * input.heatCapacity; recipe.ingredients = [new Ingredient(input, boiler.basePower / inputEnergyPerOneFluid) { temperature = acceptTemperature }]; - var outputEnergyPerOneFluid = (targetTemp - output.temperatureRange.min) * output.heatCapacity; + float outputEnergyPerOneFluid = (targetTemp - output.temperatureRange.min) * output.heatCapacity; recipe.products = [new Product(output, boiler.basePower / outputEnergyPerOneFluid)]; recipe.time = 1f; boiler.baseCraftingSpeed = 1f; @@ -547,13 +547,13 @@ private float EstimateNoiseExpression(LuaTable expression) { switch (type) { case "variable": - string varname = expression.Get("variable_name", ""); + string varName = expression.Get("variable_name", ""); - if (varname is "x" or "y" or "distance") { + if (varName is "x" or "y" or "distance") { return EstimationDistanceFromCenter; } - if (((LuaTable?)raw["noise-expression"]).Get(varname, out LuaTable? noiseExpr)) { + if (((LuaTable?)raw["noise-expression"]).Get(varName, out LuaTable? noiseExpr)) { return EstimateArgument(noiseExpr, "expression"); } diff --git a/Yafc.Parser/Data/FactorioDataDeserializer_RecipeAndTechnology.cs b/Yafc.Parser/Data/FactorioDataDeserializer_RecipeAndTechnology.cs index 072fee75..a70cbe07 100644 --- a/Yafc.Parser/Data/FactorioDataDeserializer_RecipeAndTechnology.cs +++ b/Yafc.Parser/Data/FactorioDataDeserializer_RecipeAndTechnology.cs @@ -107,7 +107,7 @@ private void UpdateRecipeIngredientFluids() { private void LoadTechnologyData(Technology technology, LuaTable table, ErrorCollector errorCollector) { if (table.Get("unit", out LuaTable? unit)) { - technology.ingredients = LoadResearchIngredientList(unit, technology.typeDotName, errorCollector); + technology.ingredients = LoadResearchIngredientList(unit); recipeCategories.Add(SpecialNames.Labs, technology); } else if (table.Get("research_trigger", out LuaTable? researchTriggerTable)) { @@ -256,7 +256,7 @@ private Ingredient[] LoadIngredientList(LuaTable table, string typeDotName, Erro }).Where(x => x is not null).ToArray() ?? []; } - private Ingredient[] LoadResearchIngredientList(LuaTable table, string typeDotName, ErrorCollector errorCollector) { + private Ingredient[] LoadResearchIngredientList(LuaTable table) { _ = table.Get("ingredients", out LuaTable? ingredientsList); return ingredientsList?.ArrayElements().Select(table => { if (table.Get(1, out string? name) && table.Get(2, out int amount)) { diff --git a/Yafc.Parser/Data/LocalisedStringParser.cs b/Yafc.Parser/Data/LocalisedStringParser.cs index 88725de8..d76cec62 100644 --- a/Yafc.Parser/Data/LocalisedStringParser.cs +++ b/Yafc.Parser/Data/LocalisedStringParser.cs @@ -37,9 +37,9 @@ internal static class LocalisedStringParser { private static string? ParseKey(string key, object[] parameters) { if (key == "") { - var builder = new StringBuilder(); - foreach (var subString in parameters) { - var localisedSubString = ParseStringOrArray(subString!); + StringBuilder builder = new StringBuilder(); + foreach (object subString in parameters) { + string? localisedSubString = ParseStringOrArray(subString); if (localisedSubString == null) { return null; } @@ -50,8 +50,8 @@ internal static class LocalisedStringParser { return builder.ToString(); } else if (key == "?") { - foreach (var alternative in parameters) { - var localisedAlternative = ParseStringOrArray(alternative!); + foreach (object alternative in parameters) { + string? localisedAlternative = ParseStringOrArray(alternative); if (localisedAlternative != null) { return localisedAlternative; } @@ -60,7 +60,7 @@ internal static class LocalisedStringParser { return null; } else if (FactorioLocalization.Localize(key) is { } localisedString) { - var localisedParameters = parameters.Select(ParseStringOrArray!).ToArray(); + string?[] localisedParameters = parameters.Select(ParseStringOrArray).ToArray(); return ReplaceBuiltInParameters(localisedString, localisedParameters); } @@ -72,10 +72,10 @@ internal static class LocalisedStringParser { return format; } - var result = new StringBuilder(); - var cursor = 0; + StringBuilder result = new StringBuilder(); + int cursor = 0; while (true) { - var start = format.IndexOf("__", cursor); + int start = format.IndexOf("__", cursor); if (start == -1) { result.Append(format[cursor..]); return result.ToString(); @@ -84,8 +84,8 @@ internal static class LocalisedStringParser { result.Append(format[cursor..start]); } - var end = format.IndexOf("__", start + 2); - var type = format[(start + 2)..end]; + int end = format.IndexOf("__", start + 2); + string type = format[(start + 2)..end]; switch (type) { case "CONTROL_STYLE_BEGIN": case "CONTROL_STYLE_END": @@ -103,35 +103,35 @@ internal static class LocalisedStringParser { case "CONTROL_MODIFIER": case "ALT_CONTROL_LEFT_CLICK": case "ALT_CONTROL_RIGHT_CLICK": - ReadExtraParameter(); + readExtraParameter(); result.Append(format[start..(end + 2)]); break; case "ALT_CONTROL": - ReadExtraParameter(); - ReadExtraParameter(); + readExtraParameter(); + readExtraParameter(); result.Append(format[start..(end + 2)]); break; case "ENTITY": case "ITEM": case "TILE": case "FLUID": - var name = ReadExtraParameter(); + string name = readExtraParameter(); result.Append(ParseKey($"{type.ToLower()}-name.{name}", [])); break; case "plural_for_parameter": - var deciderIdx = ReadExtraParameter(); - var decider = parameters[int.Parse(deciderIdx) - 1]; + string deciderIdx = readExtraParameter(); + string? decider = parameters[int.Parse(deciderIdx) - 1]; if (decider == null) { return null; } - var plurals = ReadPluralOptions(); - var selected = SelectPluralOption(decider, plurals); + var plurals = readPluralOptions(); + string? selected = selectPluralOption(decider, plurals); if (selected == null) { return null; } - var innerReplaced = ReplaceBuiltInParameters(selected, parameters); + string? innerReplaced = ReplaceBuiltInParameters(selected, parameters); if (innerReplaced == null) { return null; } @@ -139,7 +139,7 @@ internal static class LocalisedStringParser { result.Append(innerReplaced); break; default: - if (int.TryParse(type, out var idx) && idx >= 1 && idx <= parameters.Length) { + if (int.TryParse(type, out int idx) && idx >= 1 && idx <= parameters.Length) { result.Append(parameters[idx - 1]); } else { @@ -150,33 +150,33 @@ internal static class LocalisedStringParser { } cursor = end + 2; - string ReadExtraParameter() { - var end2 = format.IndexOf("__", end + 2); - var result = format[(end + 2)..end2]; + string readExtraParameter() { + int end2 = format.IndexOf("__", end + 2); + string result = format[(end + 2)..end2]; end = end2; return result; } - (Func Pattern, string Result)[] ReadPluralOptions() { - var end2 = format.IndexOf("}__", end + 3); - var options = format[(end + 3)..end2].Split('|'); + (Func Pattern, string Result)[] readPluralOptions() { + int end2 = format.IndexOf("}__", end + 3); + string[] options = format[(end + 3)..end2].Split('|'); end = end2 + 1; - return options.Select(ReadPluralOption).ToArray(); + return options.Select(readPluralOption).ToArray(); } - (Func Pattern, string Result) ReadPluralOption(string option) { - var sides = option.Split('='); + (Func Pattern, string Result) readPluralOption(string option) { + string[] sides = option.Split('='); if (sides.Length != 2) { throw new FormatException($"Invalid plural format: {option}"); } - var pattern = sides[0]; - var result = sides[1]; - var alternatives = pattern.Split(','); - return (x => alternatives.Any(a => Match(a, x)), result); + string pattern = sides[0]; + string result = sides[1]; + string[] alternatives = pattern.Split(','); + return (x => alternatives.Any(a => match(a, x)), result); } - string? SelectPluralOption(string decider, (Func Pattern, string Result)[] options) { + string? selectPluralOption(string decider, (Func Pattern, string Result)[] options) { foreach (var option in options) { if (option.Pattern(decider)) { return option.Result; @@ -186,7 +186,7 @@ string ReadExtraParameter() { return null; } - static bool Match(string pattern, string text) { + static bool match(string pattern, string text) { const string ends_in_prefix = "ends in "; if (pattern == "rest") { return true; @@ -206,7 +206,7 @@ static bool Match(string pattern, string text) { return null; } - var localeBuilder = new StringBuilder(text); + StringBuilder localeBuilder = new StringBuilder(text); _ = localeBuilder.Replace("\\n", "\n"); // Cleaning up tags using simple state machine diff --git a/Yafc.Parser/FactorioDataSource.cs b/Yafc.Parser/FactorioDataSource.cs index c694a063..656649a9 100644 --- a/Yafc.Parser/FactorioDataSource.cs +++ b/Yafc.Parser/FactorioDataSource.cs @@ -89,17 +89,17 @@ public static byte[] ReadModFile(string modName, string path) { return []; } - byte[] bytearr = new byte[entry.Length]; + byte[] bytes = new byte[entry.Length]; using (var stream = entry.Open()) { int read = 0; - while (read < bytearr.Length) { - read += stream.Read(bytearr, read, bytearr.Length - read); + while (read < bytes.Length) { + read += stream.Read(bytes, read, bytes.Length - read); } } - return bytearr; + return bytes; } string fileName = Path.Combine(info.folder, path); diff --git a/Yafc.Parser/FactorioPropertyTree.cs b/Yafc.Parser/FactorioPropertyTree.cs index 6a65e707..42bf98fb 100644 --- a/Yafc.Parser/FactorioPropertyTree.cs +++ b/Yafc.Parser/FactorioPropertyTree.cs @@ -27,9 +27,9 @@ private static string ReadString(BinaryReader reader) { } public static object? ReadModSettings(BinaryReader reader, LuaContext context) { - var major = reader.ReadInt16(); - var minor = reader.ReadInt16(); - var patch = reader.ReadInt32(); + short major = reader.ReadInt16(); + short minor = reader.ReadInt16(); + int patch = reader.ReadInt32(); _ = reader.ReadBoolean(); if (major != 2) { diff --git a/Yafc.Parser/LuaContext.cs b/Yafc.Parser/LuaContext.cs index ffd867db..cce09f06 100644 --- a/Yafc.Parser/LuaContext.cs +++ b/Yafc.Parser/LuaContext.cs @@ -37,7 +37,6 @@ private enum Type { LUA_TTHREAD = 8, } - private const int LUA_REFNIL = -1; private const int REGISTRY = -1001000; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int LuaCFunction(IntPtr lua); private const string LUA = "lua52"; diff --git a/Yafc.UI/Core/DrawingSurface.cs b/Yafc.UI/Core/DrawingSurface.cs index 751b1ec5..b5f7ef57 100644 --- a/Yafc.UI/Core/DrawingSurface.cs +++ b/Yafc.UI/Core/DrawingSurface.cs @@ -118,7 +118,7 @@ internal override void DrawIcon(SDL.SDL_Rect position, Icon icon, SchemeColor co nint iconSurface = IconCollection.GetIconSurface(icon); _ = SDL.SDL_SetSurfaceColorMod(iconSurface, sdlColor.r, sdlColor.g, sdlColor.b); _ = SDL.SDL_SetSurfaceAlphaMod(iconSurface, sdlColor.a); - _ = SDL.SDL_BlitScaled(iconSurface, ref IconCollection.IconRect, surface, ref position); + _ = SDL.SDL_BlitScaled(iconSurface, ref IconCollection.iconRect, surface, ref position); } internal override void DrawBorder(SDL.SDL_Rect position, RectangleBorder border) { diff --git a/Yafc.UI/Core/ExceptionScreen.cs b/Yafc.UI/Core/ExceptionScreen.cs index 18b25fa6..b97c101d 100644 --- a/Yafc.UI/Core/ExceptionScreen.cs +++ b/Yafc.UI/Core/ExceptionScreen.cs @@ -14,7 +14,7 @@ public static void ShowException(Exception ex) { if (!exists && !ignoreAll) { exists = true; - Ui.DispatchInMainThread(state => new ExceptionScreen(ex), null); + Ui.DispatchInMainThread(state => _ = new ExceptionScreen(ex), null); } } diff --git a/Yafc.UI/Core/IconCollection.cs b/Yafc.UI/Core/IconCollection.cs index 0f3b01f3..613c79df 100644 --- a/Yafc.UI/Core/IconCollection.cs +++ b/Yafc.UI/Core/IconCollection.cs @@ -6,7 +6,7 @@ namespace Yafc.UI; public static class IconCollection { public const int IconSize = 32; - public static SDL.SDL_Rect IconRect = new SDL.SDL_Rect { w = IconSize, h = IconSize }; + internal static SDL.SDL_Rect iconRect = new SDL.SDL_Rect { w = IconSize, h = IconSize }; private static readonly List icons = []; @@ -37,7 +37,7 @@ public static Icon AddIcon(IntPtr surface) { else { nint blit = SDL.SDL_CreateRGBSurfaceWithFormat(0, IconSize, IconSize, 0, SDL.SDL_PIXELFORMAT_RGBA8888); SDL.SDL_Rect srcRect = new SDL.SDL_Rect { w = surfaceData.w, h = surfaceData.h }; - _ = SDL.SDL_LowerBlitScaled(surface, ref srcRect, blit, ref IconRect); + _ = SDL.SDL_LowerBlitScaled(surface, ref srcRect, blit, ref iconRect); icons.Add(blit); SDL.SDL_FreeSurface(surface); } diff --git a/Yafc.UI/Core/Rect.cs b/Yafc.UI/Core/Rect.cs index 9f376bf1..72b7b52a 100644 --- a/Yafc.UI/Core/Rect.cs +++ b/Yafc.UI/Core/Rect.cs @@ -97,16 +97,7 @@ public static Rect Intersect(Rect a, Rect b) { public override readonly bool Equals(object? obj) => obj is Rect other && Equals(other); - public override readonly int GetHashCode() { - unchecked { - int hashCode = X.GetHashCode(); - hashCode = (hashCode * 397) ^ Y.GetHashCode(); - hashCode = (hashCode * 397) ^ Width.GetHashCode(); - hashCode = (hashCode * 397) ^ Height.GetHashCode(); - - return hashCode; - } - } + public override readonly int GetHashCode() => HashCode.Combine(X, Y, Width, Height); public static Rect operator +(in Rect source, Vector2 offset) => new Rect(source.Position + offset, source.Size); diff --git a/Yafc.UI/Core/Structs.cs b/Yafc.UI/Core/Structs.cs index bf9415d1..30723a90 100644 --- a/Yafc.UI/Core/Structs.cs +++ b/Yafc.UI/Core/Structs.cs @@ -109,9 +109,9 @@ public enum Icon { Warning, Add, DropDown, - ShevronDown, - ShevronUp, - ShevronRight, + ChevronDown, + ChevronUp, + ChevronRight, Menu, ArrowRight, ArrowDownRight, diff --git a/Yafc.UI/Core/Ui.cs b/Yafc.UI/Core/Ui.cs index 0215704b..9a730467 100644 --- a/Yafc.UI/Core/Ui.cs +++ b/Yafc.UI/Core/Ui.cs @@ -38,13 +38,13 @@ public static void Start() { _ = SDL_image.IMG_Init(SDL_image.IMG_InitFlags.IMG_INIT_PNG | SDL_image.IMG_InitFlags.IMG_INIT_JPG); asyncCallbacksAdded = SDL.SDL_RegisterEvents(1); SynchronizationContext.SetSynchronizationContext(new UiSynchronizationContext()); - mainThreadId = Thread.CurrentThread.ManagedThreadId; + mainThreadId = Environment.CurrentManagedThreadId; } public static long time { get; private set; } private static readonly Stopwatch timeWatch = Stopwatch.StartNew(); - public static bool IsMainThread() => Thread.CurrentThread.ManagedThreadId == mainThreadId; + public static bool IsMainThread() => Environment.CurrentManagedThreadId == mainThreadId; private static int mainThreadId; private static uint asyncCallbacksAdded; @@ -276,7 +276,7 @@ public static void UnregisterWindow(Window window) { } } - public static void CloseWidowOfType(Type type) { + public static void CloseWindowOfType(Type type) { foreach (var (_, v) in windows) { if (v.GetType() == type) { v.Close(); diff --git a/Yafc.UI/Core/Window.cs b/Yafc.UI/Core/Window.cs index 9e4faffc..eb2f0e22 100644 --- a/Yafc.UI/Core/Window.cs +++ b/Yafc.UI/Core/Window.cs @@ -26,6 +26,8 @@ public abstract class Window : IDisposable { protected DropDownPanel? dropDown; private SimpleDropDown? simpleDropDown; private ImGui.DragOverlay? draggingOverlay; + private bool disposedValue; + public DrawingSurface? surface { get; protected set; } public int displayIndex => SDL.SDL_GetWindowDisplayIndex(window); @@ -45,7 +47,7 @@ internal void Create() { _ = SDL.SDL_SetRenderDrawBlendMode(surface.renderer, SDL.SDL_BlendMode.SDL_BLENDMODE_BLEND); id = SDL.SDL_GetWindowID(window); - Ui.CloseWidowOfType(GetType()); + Ui.CloseWindowOfType(GetType()); Ui.RegisterWindow(id, this); visible = true; } @@ -237,9 +239,24 @@ private void Build(ImGui gui) { } protected abstract void BuildContents(ImGui gui); - public virtual void Dispose() => rootGui.Dispose(); internal ImGui.DragOverlay GetDragOverlay() => draggingOverlay ??= new ImGui.DragOverlay(); protected internal virtual void WindowMaximized() { } protected internal virtual void WindowRestored() { } + + protected virtual void Dispose(bool disposing) { + if (!disposedValue) { + if (disposing) { + rootGui.Dispose(); + } + + disposedValue = true; + } + } + + public void Dispose() { + // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method + Dispose(disposing: true); + GC.SuppressFinalize(this); + } } diff --git a/Yafc.UI/Core/WindowMain.cs b/Yafc.UI/Core/WindowMain.cs index 35287334..9352ab41 100644 --- a/Yafc.UI/Core/WindowMain.cs +++ b/Yafc.UI/Core/WindowMain.cs @@ -84,7 +84,7 @@ internal class MainWindowDrawingSurface : DrawingSurface { /// /// This seems like something that SDL2 should do on its own, since the point of SDL2 is to abstract across platform render /// APIs, and it sort of does - but SDL2 has been around for a really long time and its defaults reflect that. On Windows, - /// it will autoselect DirectX/Direct3D 9 if given half a chance; DX9 was of course the version that shipped in 2002 and + /// it will auto-select DirectX/Direct3D 9 if given half a chance; DX9 was of course the version that shipped in 2002 and /// supported Windows 98. This is despite the fact that SDL2 supports DX12 and DX11 where possible, and in 2024 "where possible" /// is really going to be "everywhere" - it just doesn't seem to default select them. /// @@ -99,7 +99,7 @@ internal class MainWindowDrawingSurface : DrawingSurface { /// If set, always return the appropriate index for the software renderer. This can be useful if your graphics hardware doesn't support /// the rendering API that would otherwise be returned. /// - /// The index of the selected render driver, including 0 (SDL autoselect) if no known-best driver exists on this machine. + /// The index of the selected render driver, including 0 (SDL auto-select) if no known-best driver exists on this machine. /// This value should be fed to the second argument of SDL_CreateRenderer() private static int PickRenderDriver(SDL.SDL_RendererFlags flags, bool forceSoftwareRenderer) { nint numRenderDrivers = SDL.SDL_GetNumRenderDrivers(); diff --git a/Yafc.UI/ImGui/ImGui.cs b/Yafc.UI/ImGui/ImGui.cs index f3a9de74..f0552599 100644 --- a/Yafc.UI/ImGui/ImGui.cs +++ b/Yafc.UI/ImGui/ImGui.cs @@ -217,8 +217,8 @@ internal void InternalPresent(DrawingSurface surface, Rect position, Rect screen renderable.Render(surface, ToSdlRect(pos, screenOffset), color.ToSdlColor()); } - foreach (var (srect, type) in borders) { - surface.DrawBorder(srect, type); + foreach (var (rect, type) in borders) { + surface.DrawBorder(rect, type); } foreach (var (rect, batch, _) in panels) { diff --git a/Yafc.UI/ImGui/ImGuiBuilding.cs b/Yafc.UI/ImGui/ImGuiBuilding.cs index dc6e82d1..d3fc73d5 100644 --- a/Yafc.UI/ImGui/ImGuiBuilding.cs +++ b/Yafc.UI/ImGui/ImGuiBuilding.cs @@ -366,7 +366,7 @@ public bool ConsumeMouseOver(Rect rect, IntPtr cursor = default, bool rebuild = return false; } - public bool ConsumeMouseUp(Rect rect, bool inside = true, uint button = SDL.SDL_BUTTON_LEFT) { + public bool ConsumeMouseUp(Rect rect, bool inside = true) { if (action == ImGuiAction.MouseUp && rect == mouseDownRect && (!inside || rect.Contains(mousePosition))) { action = ImGuiAction.Consumed; Rebuild(); diff --git a/Yafc.UI/ImGui/ImGuiCache.cs b/Yafc.UI/ImGui/ImGuiCache.cs index 5477a98c..e24f62fd 100644 --- a/Yafc.UI/ImGui/ImGuiCache.cs +++ b/Yafc.UI/ImGui/ImGuiCache.cs @@ -8,7 +8,7 @@ namespace Yafc.UI; public abstract class ImGuiCache : IDisposable where T : ImGuiCache where TKey : IEquatable { private static readonly T Constructor = (T)RuntimeHelpers.GetUninitializedObject(typeof(T)); - public class Cache : IDisposable { + public sealed class Cache : IDisposable { private readonly Dictionary activeCached = []; private readonly HashSet unused = []; @@ -45,7 +45,7 @@ public void Dispose() { public abstract void Dispose(); } -public class TextCache : ImGuiCache, IRenderable { +public sealed class TextCache : ImGuiCache, IRenderable { public TextureHandle texture; private IntPtr surface; internal SDL.SDL_Rect texRect; diff --git a/Yafc.UI/ImGui/ImGuiLayout.cs b/Yafc.UI/ImGui/ImGuiLayout.cs index 238215ee..2aab97ca 100644 --- a/Yafc.UI/ImGui/ImGuiLayout.cs +++ b/Yafc.UI/ImGui/ImGuiLayout.cs @@ -207,20 +207,20 @@ public Rect EncapsulateRect(Rect rect) { public readonly struct Context : IDisposable { private readonly ImGui gui; - private readonly CopyableState state; + private readonly CopyableState oldState; private readonly Padding padding; public Context(ImGui gui, Padding padding) { this.gui = gui; this.padding = padding; - ref var cstate = ref gui.state; - state = cstate; - cstate.contextRect = default; - cstate.hasContent = false; - cstate.left += padding.left; - cstate.right -= padding.right; - cstate.top += padding.top; - cstate.bottom -= padding.bottom; + ref CopyableState state = ref gui.state; + oldState = state; + state.contextRect = default; + state.hasContent = false; + state.left += padding.left; + state.right -= padding.right; + state.top += padding.top; + state.bottom -= padding.bottom; } public void Dispose() { @@ -230,7 +230,7 @@ public void Dispose() { var rect = gui.state.contextRect; bool hasContent = gui.state.hasContent; - gui.state = state; + gui.state = oldState; rect.X -= padding.left; rect.Y -= padding.top; rect.Width += padding.left + padding.right; @@ -246,7 +246,7 @@ public void Dispose() { } public void SetManualRect(Rect rect, RectAllocator allocator = RectAllocator.FixedRect) { - rect += new Vector2(state.left, state.top); + rect += new Vector2(oldState.left, oldState.top); gui.spacing = 0f; SetManualRectRaw(rect, allocator); } @@ -254,12 +254,12 @@ public void SetManualRect(Rect rect, RectAllocator allocator = RectAllocator.Fix public void SetWidth(float width) => gui.state.right = gui.state.left + width; public void SetManualRectRaw(Rect rect, RectAllocator allocator = RectAllocator.FixedRect) { - ref var cstate = ref gui.state; - cstate.left = rect.X + padding.left; - cstate.right = cstate.left + rect.Width; - cstate.top = rect.Y + padding.top; - cstate.bottom = cstate.top + rect.Height; - cstate.allocator = allocator; + ref CopyableState state = ref gui.state; + state.left = rect.X + padding.left; + state.right = state.left + rect.Width; + state.top = rect.Y + padding.top; + state.bottom = state.top + rect.Height; + state.allocator = allocator; } } diff --git a/Yafc.UI/ImGui/ImGuiUtils.cs b/Yafc.UI/ImGui/ImGuiUtils.cs index 5fea0240..eed55b89 100644 --- a/Yafc.UI/ImGui/ImGuiUtils.cs +++ b/Yafc.UI/ImGui/ImGuiUtils.cs @@ -53,7 +53,7 @@ public static ButtonEvent BuildButton(this ImGui gui, Rect rect, SchemeColor nor case ImGuiAction.MouseDown: return gui.actionParameter == button && gui.ConsumeMouseDown(rect, button) ? ButtonEvent.MouseDown : ButtonEvent.None; case ImGuiAction.MouseUp: - return gui.actionParameter == button && gui.ConsumeMouseUp(rect, true, button) ? ButtonEvent.Click : ButtonEvent.None; + return gui.actionParameter == button && gui.ConsumeMouseUp(rect) ? ButtonEvent.Click : ButtonEvent.None; case ImGuiAction.Build: var color = gui.IsMouseOver(rect) ? (down != SchemeColor.None && gui.IsMouseDown(rect, button)) ? down : over : normal; gui.DrawRectangle(rect, color); diff --git a/Yafc.UI/ImGui/ScrollArea.cs b/Yafc.UI/ImGui/ScrollArea.cs index cca222ad..897b96c3 100644 --- a/Yafc.UI/ImGui/ScrollArea.cs +++ b/Yafc.UI/ImGui/ScrollArea.cs @@ -75,11 +75,12 @@ public void Build(ImGui gui, float availableHeight, bool useBottomPadding = fals } if (gui.action == ImGuiAction.MouseScroll) { - if (vertical && !InputSystem.Instance.control && gui.ConsumeEvent(rect)) + if (vertical && !InputSystem.Instance.control && gui.ConsumeEvent(rect)) { scrollY += gui.actionParameter * 3f; - - else if (horizontal && InputSystem.Instance.control && gui.ConsumeEvent(rect)) + } + else if (horizontal && InputSystem.Instance.control && gui.ConsumeEvent(rect)) { scrollX += gui.actionParameter * 3f; + } } else { if (horizontal && maxScroll.X > 0f) { @@ -308,13 +309,13 @@ public VirtualScrollList(float height, Vector2 elementSize, Drawer drawer, Paddi this.reorder = reorder; } - private int CalcFirstBlock() => Math.Max(0, MathUtils.Floor((scrollY - contents.initialPadding.top) / (elementSize.Y * bufferRows))); + private int CalculateFirstBlock() => Math.Max(0, MathUtils.Floor((scrollY - contents.initialPadding.top) / (elementSize.Y * bufferRows))); public override Vector2 scroll { get => base.scroll; set { base.scroll = value; - int row = CalcFirstBlock(); + int row = CalculateFirstBlock(); if (row != firstVisibleBlock) { RebuildContents(); @@ -330,7 +331,7 @@ protected override void BuildContents(ImGui gui) { } int rowCount = ((_data.Count - 1) / elementsPerRow) + 1; - firstVisibleBlock = CalcFirstBlock(); + firstVisibleBlock = CalculateFirstBlock(); // Scroll up until there are maxRowsVisible, or to the top. int firstRow = Math.Max(0, Math.Min(firstVisibleBlock * bufferRows, rowCount - maxRowsVisible)); int index = firstRow * elementsPerRow; diff --git a/Yafc.UI/Rendering/Font.cs b/Yafc.UI/Rendering/Font.cs index 47730f12..c7a1f9b5 100644 --- a/Yafc.UI/Rendering/Font.cs +++ b/Yafc.UI/Rendering/Font.cs @@ -30,7 +30,7 @@ public FontFile.FontSize GetFontSize(float pixelsPreUnit) { public void Dispose() => file.Dispose(); } -public class FontFile(string fileName) : IDisposable { +public sealed class FontFile(string fileName) : IDisposable { public readonly string fileName = fileName; private readonly Dictionary sizes = []; diff --git a/Yafc/Data/Icons/ShevronDown.png b/Yafc/Data/Icons/ChevronDown.png similarity index 100% rename from Yafc/Data/Icons/ShevronDown.png rename to Yafc/Data/Icons/ChevronDown.png diff --git a/Yafc/Data/Icons/ShevronRight.png b/Yafc/Data/Icons/ChevronRight.png similarity index 100% rename from Yafc/Data/Icons/ShevronRight.png rename to Yafc/Data/Icons/ChevronRight.png diff --git a/Yafc/Data/Icons/ShevronUp.png b/Yafc/Data/Icons/ChevronUp.png similarity index 100% rename from Yafc/Data/Icons/ShevronUp.png rename to Yafc/Data/Icons/ChevronUp.png diff --git a/Yafc/Program.cs b/Yafc/Program.cs index 4f9e035d..109ff82c 100644 --- a/Yafc/Program.cs +++ b/Yafc/Program.cs @@ -6,7 +6,7 @@ namespace Yafc; public static class Program { - public static bool hasOverriddenFont; + internal static bool hasOverriddenFont { get; private set; } private static void Main(string[] args) { YafcLib.RegisterDefaultAnalysis(); diff --git a/Yafc/Widgets/DataGrid.cs b/Yafc/Widgets/DataGrid.cs index 29c1634b..085f3405 100644 --- a/Yafc/Widgets/DataGrid.cs +++ b/Yafc/Widgets/DataGrid.cs @@ -79,20 +79,15 @@ public override void BuildHeader(ImGui gui) { public virtual void BuildMenu(ImGui gui) { } } -public class DataGrid where TData : class { - public readonly List> columns; +public class DataGrid(params DataColumn[] columns) where TData : class { + public readonly List> columns = new(columns); public static readonly Padding innerPadding = new Padding(0.2f); public float width { get; private set; } - private readonly float spacing; + private readonly float spacing = innerPadding.left + innerPadding.right; private Vector2 buildingStart; private ImGui? contentGui; public float headerHeight = 1.3f; - public DataGrid(params DataColumn[] columns) { - this.columns = new List>(columns); - spacing = innerPadding.left + innerPadding.right; - } - private void BuildHeaderResizer(ImGui gui, DataColumn column, Rect rect) { switch (gui.action) { case ImGuiAction.Build: diff --git a/Yafc/Widgets/ImmediateWidgets.cs b/Yafc/Widgets/ImmediateWidgets.cs index 319958e2..acc5e612 100644 --- a/Yafc/Widgets/ImmediateWidgets.cs +++ b/Yafc/Widgets/ImmediateWidgets.cs @@ -80,9 +80,9 @@ public static void BuildFactorioObjectIcon(this ImGui gui, IFactorioObjectWrappe bool contain = (displayStyle.MilestoneDisplay & MilestoneDisplay.Contained) != 0; FactorioObject? milestone = Milestones.Instance.GetHighest(obj.target, displayStyle.MilestoneDisplay >= MilestoneDisplay.Always); if (milestone != null) { - Vector2 psize = new Vector2(displayStyle.Size / 2f); - var delta = contain ? psize : psize / 2f; - Rect milestoneIcon = new Rect(gui.lastRect.BottomRight - delta, psize); + Vector2 size = new Vector2(displayStyle.Size / 2f); + var delta = contain ? size : size / 2f; + Rect milestoneIcon = new Rect(gui.lastRect.BottomRight - delta, size); var icon = milestone == Database.voidEnergy ? DataUtils.HandIcon : milestone.icon; gui.DrawIcon(milestoneIcon, icon, color); } @@ -90,9 +90,9 @@ public static void BuildFactorioObjectIcon(this ImGui gui, IFactorioObjectWrappe Quality? quality = (obj as IObjectWithQuality)?.quality; if (gui.isBuilding && quality != null && quality != Quality.Normal) { - Vector2 psize = new Vector2(displayStyle.Size / 2.5f); - Vector2 delta = new(0, psize.Y); - Rect qualityRect = new Rect(gui.lastRect.BottomLeft - delta, psize); + Vector2 size = new Vector2(displayStyle.Size / 2.5f); + Vector2 delta = new(0, size.Y); + Rect qualityRect = new Rect(gui.lastRect.BottomLeft - delta, size); gui.DrawIcon(qualityRect, quality.icon, SchemeColor.Source); } @@ -367,7 +367,7 @@ public static GoodsWithAmountEvent BuildFactorioObjectWithEditableAmount(this Im /// The to initially display selected, if any. /// The selected by the user. /// The header text to draw, defaults to "Select quality" - /// if the user selected a quality. if they did not, or if the loaded mods do not provide multiple qualitites. + /// if the user selected a quality. if they did not, or if the loaded mods do not provide multiple qualities. public static bool BuildQualityList(this ImGui gui, Quality? quality, [NotNullWhen(true), NotNullIfNotNull(nameof(quality))] out Quality? newQuality, string header = "Select quality", bool drawCentered = false) { newQuality = quality; if (Quality.Normal.nextQuality == null) { diff --git a/Yafc/Widgets/ObjectTooltip.cs b/Yafc/Widgets/ObjectTooltip.cs index def451b4..aa6eab52 100644 --- a/Yafc/Widgets/ObjectTooltip.cs +++ b/Yafc/Widgets/ObjectTooltip.cs @@ -218,7 +218,7 @@ private static void BuildEntity(Entity entity, Quality quality, ImGui gui) { gui.BuildText(DataUtils.FormatAmount(crafter.CraftingSpeed(quality), UnitOfMeasure.Percent, "Crafting speed: ")); } - var productivity = crafter.effectReceiver?.baseEffect.productivity ?? 0; + float productivity = crafter.effectReceiver?.baseEffect.productivity ?? 0; if (productivity != 0f) { gui.BuildText(DataUtils.FormatAmount(productivity, UnitOfMeasure.Percent, "Crafting productivity: ")); } @@ -391,7 +391,7 @@ private void BuildGoods(Goods goods, Quality quality, ImGui gui) { } } - private void BuildRecipe(RecipeOrTechnology recipe, ImGui gui) { + private static void BuildRecipe(RecipeOrTechnology recipe, ImGui gui) { using (gui.EnterGroup(contentPadding, RectAllocator.LeftRow)) { gui.BuildIcon(Icon.Time, 2f, SchemeColor.BackgroundText); gui.BuildText(DataUtils.FormatAmount(recipe.time, UnitOfMeasure.Second)); @@ -446,7 +446,7 @@ private void BuildRecipe(RecipeOrTechnology recipe, ImGui gui) { BuildIconRow(gui, recipe.crafters, 2); } - var allowedModules = Database.allModules.Where(recipe.CanAcceptModule).ToList(); + List allowedModules = Database.allModules.Where(recipe.CanAcceptModule).ToList(); if (allowedModules.Count > 0) { BuildSubHeader(gui, "Allowed modules"); @@ -497,7 +497,7 @@ private void BuildRecipe(RecipeOrTechnology recipe, ImGui gui) { } } - private void BuildTechnology(Technology technology, ImGui gui) { + private static void BuildTechnology(Technology technology, ImGui gui) { bool isResearchTriggerCraft = (technology.flags & RecipeFlags.HasResearchTriggerCraft) == RecipeFlags.HasResearchTriggerCraft; if (!isResearchTriggerCraft) { BuildRecipe(technology, gui); diff --git a/Yafc/Windows/DependencyExplorer.cs b/Yafc/Windows/DependencyExplorer.cs index fdff6ec9..32973fb0 100644 --- a/Yafc/Windows/DependencyExplorer.cs +++ b/Yafc/Windows/DependencyExplorer.cs @@ -30,21 +30,21 @@ public class DependencyExplorer : PseudoScreen { public DependencyExplorer(FactorioObject current) : base(60f) { dependencies = new ScrollArea(30f, DrawDependencies); - dependents = new ScrollArea(30f, DrawDependants); + dependents = new ScrollArea(30f, DrawDependents); this.current = current; } public static void Show(FactorioObject target) => _ = MainScreen.Instance.ShowPseudoScreen(new DependencyExplorer(target)); private void DrawFactorioObject(ImGui gui, FactorioId id) { - var fobj = Database.objects[id]; + FactorioObject obj = Database.objects[id]; using (gui.EnterGroup(listPad, RectAllocator.LeftRow)) { - gui.BuildFactorioObjectIcon(fobj); - string text = fobj.locName + " (" + fobj.type + ")"; - gui.RemainingRow(0.5f).BuildText(text, TextBlockDisplayStyle.WrappedText with { Color = fobj.IsAccessible() ? SchemeColor.BackgroundText : SchemeColor.BackgroundTextFaint }); + gui.BuildFactorioObjectIcon(obj); + string text = obj.locName + " (" + obj.type + ")"; + gui.RemainingRow(0.5f).BuildText(text, TextBlockDisplayStyle.WrappedText with { Color = obj.IsAccessible() ? SchemeColor.BackgroundText : SchemeColor.BackgroundTextFaint }); } - if (gui.BuildFactorioObjectButtonBackground(gui.lastRect, fobj, tooltipOptions: new() { ShowTypeInHeader = true }) == Click.Left) { - Change(fobj); + if (gui.BuildFactorioObjectButtonBackground(gui.lastRect, obj, tooltipOptions: new() { ShowTypeInHeader = true }) == Click.Left) { + Change(obj); } } @@ -86,7 +86,7 @@ private void DrawDependencies(ImGui gui) { } } - private void DrawDependants(ImGui gui) { + private void DrawDependents(ImGui gui) { gui.spacing = 0f; foreach (var reverseDependency in Dependencies.reverseDependencies[current].OrderByDescending(x => CostAnalysis.Instance.flow[x])) { DrawFactorioObject(gui, reverseDependency); diff --git a/Yafc/Windows/PreferencesScreen.cs b/Yafc/Windows/PreferencesScreen.cs index adad1845..b828312d 100644 --- a/Yafc/Windows/PreferencesScreen.cs +++ b/Yafc/Windows/PreferencesScreen.cs @@ -30,25 +30,25 @@ public override void Build(ImGui gui) { } private static void DrawProgression(ImGui gui) { - var prefs = Project.current.preferences; + ProjectPreferences preferences = Project.current.preferences; - ChooseObject(gui, "Default belt:", Database.allBelts, prefs.defaultBelt, s => { - prefs.RecordUndo().defaultBelt = s; + ChooseObject(gui, "Default belt:", Database.allBelts, preferences.defaultBelt, s => { + preferences.RecordUndo().defaultBelt = s; gui.Rebuild(); }); - ChooseObject(gui, "Default inserter:", Database.allInserters, prefs.defaultInserter, s => { - prefs.RecordUndo().defaultInserter = s; + ChooseObject(gui, "Default inserter:", Database.allInserters, preferences.defaultInserter, s => { + preferences.RecordUndo().defaultInserter = s; gui.Rebuild(); }); using (gui.EnterRow()) { gui.BuildText("Inserter capacity:", topOffset: 0.5f); - if (gui.BuildIntegerInput(prefs.inserterCapacity, out int newCapacity)) { - prefs.RecordUndo().inserterCapacity = newCapacity; + if (gui.BuildIntegerInput(preferences.inserterCapacity, out int newCapacity)) { + preferences.RecordUndo().inserterCapacity = newCapacity; } } - ChooseObjectWithNone(gui, "Target technology for cost analysis: ", Database.technologies.all, prefs.targetTechnology, x => { - prefs.RecordUndo().targetTechnology = x; + ChooseObjectWithNone(gui, "Target technology for cost analysis: ", Database.technologies.all, preferences.targetTechnology, x => { + preferences.RecordUndo().targetTechnology = x; gui.Rebuild(); }, width: 25f); @@ -91,36 +91,36 @@ private static void DrawProgression(ImGui gui) { } private static void DrawGeneral(ImGui gui) { - var prefs = Project.current.preferences; - var settings = Project.current.settings; + ProjectPreferences preferences = Project.current.preferences; + ProjectSettings settings = Project.current.settings; gui.BuildText("Unit of time:", Font.subheader); using (gui.EnterRow()) { - if (gui.BuildRadioButton("Second", prefs.time == 1)) { - prefs.RecordUndo(true).time = 1; + if (gui.BuildRadioButton("Second", preferences.time == 1)) { + preferences.RecordUndo(true).time = 1; } - if (gui.BuildRadioButton("Minute", prefs.time == 60)) { - prefs.RecordUndo(true).time = 60; + if (gui.BuildRadioButton("Minute", preferences.time == 60)) { + preferences.RecordUndo(true).time = 60; } - if (gui.BuildRadioButton("Hour", prefs.time == 3600)) { - prefs.RecordUndo(true).time = 3600; + if (gui.BuildRadioButton("Hour", preferences.time == 3600)) { + preferences.RecordUndo(true).time = 3600; } - if (gui.BuildRadioButton("Custom", prefs.time is not 1 and not 60 and not 3600)) { - prefs.RecordUndo(true).time = 0; + if (gui.BuildRadioButton("Custom", preferences.time is not 1 and not 60 and not 3600)) { + preferences.RecordUndo(true).time = 0; } - if (gui.BuildIntegerInput(prefs.time, out int newTime)) { - prefs.RecordUndo(true).time = newTime; + if (gui.BuildIntegerInput(preferences.time, out int newTime)) { + preferences.RecordUndo(true).time = newTime; } } gui.AllocateSpacing(1f); gui.BuildText("Item production/consumption:", Font.subheader); - BuildUnitPerTime(gui, false, prefs); + BuildUnitPerTime(gui, false, preferences); gui.BuildText("Fluid production/consumption:", Font.subheader); - BuildUnitPerTime(gui, true, prefs); + BuildUnitPerTime(gui, true, preferences); using (gui.EnterRowWithHelpIcon("0% for off, 100% for old default")) { gui.BuildText("Pollution cost modifier", topOffset: 0.5f); @@ -135,9 +135,9 @@ private static void DrawGeneral(ImGui gui) { using (gui.EnterRowWithHelpIcon(iconScaleMessage)) { gui.BuildText("Display scale for linkable icons", topOffset: 0.5f); - DisplayAmount amount = new(prefs.iconScale, UnitOfMeasure.Percent); + DisplayAmount amount = new(preferences.iconScale, UnitOfMeasure.Percent); if (gui.BuildFloatInput(amount, TextBoxDisplayStyle.DefaultTextInput) && amount.Value > 0 && amount.Value <= 1) { - prefs.RecordUndo().iconScale = amount.Value; + preferences.RecordUndo().iconScale = amount.Value; gui.Rebuild(); } } diff --git a/Yafc/Windows/WelcomeScreen.cs b/Yafc/Windows/WelcomeScreen.cs index f88e6797..089507d1 100644 --- a/Yafc/Windows/WelcomeScreen.cs +++ b/Yafc/Windows/WelcomeScreen.cs @@ -245,7 +245,7 @@ private void LanguageSelection(ImGui gui) { if (!Program.hasOverriddenFont) { gui.AllocateSpacing(0.5f); - string nonEuLanguageMessage = "To select languages with non-european glyphs you need to override used font first. Download or locate a font that has your language glyphs."; + string nonEuLanguageMessage = "To select languages with non-European glyphs you need to override used font first. Download or locate a font that has your language glyphs."; gui.BuildText(nonEuLanguageMessage, TextBlockDisplayStyle.WrappedText); gui.AllocateSpacing(0.5f); } diff --git a/Yafc/Workspace/ProductionSummary/ProductionSummaryView.cs b/Yafc/Workspace/ProductionSummary/ProductionSummaryView.cs index 46487365..716d5565 100644 --- a/Yafc/Workspace/ProductionSummary/ProductionSummaryView.cs +++ b/Yafc/Workspace/ProductionSummary/ProductionSummaryView.cs @@ -30,7 +30,7 @@ public override void BuildElement(ImGui gui, ProductionSummaryEntry row) { gui.allocator = RectAllocator.Center; gui.spacing = 0f; if (row.subgroup != null) { - if (gui.BuildButton(row.subgroup.expanded ? Icon.ShevronDown : Icon.ShevronRight)) { + if (gui.BuildButton(row.subgroup.expanded ? Icon.ChevronDown : Icon.ChevronRight)) { row.subgroup.RecordChange().expanded = !row.subgroup.expanded; view.flatHierarchy.SetData(view.model.group); } diff --git a/Yafc/Workspace/ProductionTable/ModuleFillerParametersScreen.cs b/Yafc/Workspace/ProductionTable/ModuleFillerParametersScreen.cs index 4dab0324..3674b785 100644 --- a/Yafc/Workspace/ProductionTable/ModuleFillerParametersScreen.cs +++ b/Yafc/Workspace/ProductionTable/ModuleFillerParametersScreen.cs @@ -122,7 +122,7 @@ public override void Build(ImGui gui) { gui.AllocateSpacing(); gui.BuildText("Filler module:", Font.subheader); - gui.BuildText("Use this module when aufofill doesn't add anything (for example when productivity modules doesn't fit)", TextBlockDisplayStyle.WrappedText); + gui.BuildText("Use this module when autofill doesn't add anything (for example when productivity modules doesn't fit)", TextBlockDisplayStyle.WrappedText); if (gui.BuildFactorioObjectButtonWithText(modules.fillerModule) == Click.Left) { SelectSingleObjectPanel.SelectQualityWithNone(Database.allModules, "Select filler module", select => modules.fillerModule = select, modules.fillerModule?.quality); } diff --git a/Yafc/Workspace/ProductionTable/ProductionTableFlatHierarchy.cs b/Yafc/Workspace/ProductionTable/ProductionTableFlatHierarchy.cs index ad743631..1eb1dc26 100644 --- a/Yafc/Workspace/ProductionTable/ProductionTableFlatHierarchy.cs +++ b/Yafc/Workspace/ProductionTable/ProductionTableFlatHierarchy.cs @@ -84,14 +84,6 @@ private void MoveFlatHierarchy(TRow from, TRow to) { flatGroups.MoveListElementIndex(indexFrom, indexTo); } - private void MoveFlatHierarchy(TRow from, TGroup to) { - draggingRecipe = from; - int indexFrom = flatRecipes.IndexOf(from); - int indexTo = flatGroups.IndexOf(to); - flatRecipes.MoveListElementIndex(indexFrom, indexTo); - flatGroups.MoveListElementIndex(indexFrom, indexTo); - } - private readonly Stack depthStart = new Stack(); /// diff --git a/Yafc/Workspace/ProductionTable/ProductionTableView.cs b/Yafc/Workspace/ProductionTable/ProductionTableView.cs index e22f60e7..84801f84 100644 --- a/Yafc/Workspace/ProductionTable/ProductionTableView.cs +++ b/Yafc/Workspace/ProductionTable/ProductionTableView.cs @@ -35,7 +35,7 @@ public override void BuildElement(ImGui gui, RecipeRow row) { gui.spacing = 0f; if (row.subgroup != null) { - if (gui.BuildButton(row.subgroup.expanded ? Icon.ShevronDown : Icon.ShevronRight)) { + if (gui.BuildButton(row.subgroup.expanded ? Icon.ChevronDown : Icon.ChevronRight)) { if (InputSystem.Instance.control) { toggleAll(!row.subgroup.expanded, view.model); } @@ -1311,9 +1311,9 @@ private static List GetRecipesRecursive(RecipeRow recipeRoot) { private void BuildShoppingList(RecipeRow? recipeRoot) => ShoppingListScreen.Show(recipeRoot == null ? GetRecipesRecursive() : GetRecipesRecursive(recipeRoot)); private static void BuildBeltInserterInfo(ImGui gui, float amount, float buildingCount) { - var prefs = Project.current.preferences; - var belt = prefs.defaultBelt; - var inserter = prefs.defaultInserter; + var preferences = Project.current.preferences; + var belt = preferences.defaultBelt; + var inserter = preferences.defaultInserter; if (belt == null || inserter == null) { return; @@ -1333,7 +1333,7 @@ private static void BuildBeltInserterInfo(ImGui gui, float amount, float buildin } using (gui.EnterRow()) { - int capacity = prefs.inserterCapacity; + int capacity = preferences.inserterCapacity; float inserterBase = inserter.inserterSwingTime * amount / capacity; click |= gui.BuildFactorioObjectButton(inserter, ButtonDisplayStyle.Default) == Click.Left; string text = DataUtils.FormatAmount(inserterBase, UnitOfMeasure.None); diff --git a/Yafc/Yafc.csproj b/Yafc/Yafc.csproj index 212d52ac..251c21cb 100644 --- a/Yafc/Yafc.csproj +++ b/Yafc/Yafc.csproj @@ -53,6 +53,6 @@ - + diff --git a/Yafc/YafcLib.cs b/Yafc/YafcLib.cs index a8fb0656..2aa05f21 100644 --- a/Yafc/YafcLib.cs +++ b/Yafc/YafcLib.cs @@ -12,8 +12,8 @@ namespace Yafc; public static class YafcLib { - public static Version version { get; private set; } - public static string initialWorkDir; + internal static Version version { get; private set; } + internal static string initialWorkDir { get; private set; } static YafcLib() { initialWorkDir = Directory.GetCurrentDirectory(); @@ -29,31 +29,31 @@ static YafcLib() { } } - private static string GetLinuxMappedLibraryName(string libraryname) => libraryname switch { + private static string GetLinuxMappedLibraryName(string libraryName) => libraryName switch { "lua52" => "liblua52.so", "SDL2.dll" => "SDL2-2.0.so.0", "SDL2_ttf.dll" => "SDL2_ttf-2.0.so.0", "SDL2_image.dll" => "SDL2_image-2.0.so.0", - _ => libraryname, + _ => libraryName, }; - private static string GetOsxMappedLibraryName(string libraryname) => libraryname switch { + private static string GetOsxMappedLibraryName(string libraryName) => libraryName switch { "lua52" => "liblua52.dylib", "SDL2.dll" => "libSDL2.dylib", "SDL2_ttf.dll" => "libSDL2_ttf.dylib", "SDL2_image.dll" => "libSDL2_image.dylib", - _ => libraryname, + _ => libraryName, }; - private static IntPtr DllResolver(string libraryname, Assembly assembly, DllImportSearchPath? searchpath) { + private static IntPtr DllResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { - libraryname = GetLinuxMappedLibraryName(libraryname); + libraryName = GetLinuxMappedLibraryName(libraryName); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { - libraryname = GetOsxMappedLibraryName(libraryname); + libraryName = GetOsxMappedLibraryName(libraryName); } - return NativeLibrary.Load(libraryname, assembly, DllImportSearchPath.SafeDirectories); + return NativeLibrary.Load(libraryName, assembly, DllImportSearchPath.SafeDirectories); } public static void RegisterDefaultAnalysis() { diff --git a/exclusion.dic b/exclusion.dic new file mode 100644 index 00000000..e46b1852 --- /dev/null +++ b/exclusion.dic @@ -0,0 +1,20 @@ +Deserialize +deserialized +Deserializer +Deserializing +dylib +Factorio +Floodfill +foreach +imgui +Kovarex +liblua +localised +naive +Nauvis +renderable +Serializer +shaders +unbarreling +Utils +Yafc