Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Fix ini sanitization #19

Merged
merged 1 commit into from
Oct 1, 2024
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
2 changes: 2 additions & 0 deletions Memoria.Launcher/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ public void InitializeComponent2()
[DebuggerNonUserCode]
public static void Main()
{
IniFile.SanitizeMemoriaIni();

App app = new App();
app.InitializeComponent();
app.Run();
Expand Down
118 changes: 18 additions & 100 deletions Memoria.Launcher/Launcher/IniFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public String ReadValue(String Section, String Key)
private const Int32 _bufferSize = 10000;
private StringBuilder _retBuffer = new StringBuilder(_bufferSize);

private static readonly String _iniPath = AppDomain.CurrentDomain.BaseDirectory + @"Memoria.ini";
public const String IniPath = @"./Memoria.ini";


public static void SanitizeMemoriaIni()
Expand All @@ -51,16 +51,13 @@ public static void SanitizeMemoriaIni()
text = reader.ReadToEnd();
}

if (!File.Exists(_iniPath))
if (!File.Exists(IniPath))
{
File.WriteAllText(_iniPath, text);
File.WriteAllText(IniPath, text);
return;
}

File.WriteAllLines(_iniPath, MergeIniFiles(text.Replace("\r", "").Split('\n'), File.ReadAllLines(_iniPath)));

MakeSureSpacesAroundEqualsigns();
RemoveDuplicateKeys(_iniPath);
File.WriteAllLines(IniPath, MergeIniFiles(text.Replace("\r", "").Split('\n'), File.ReadAllLines(IniPath)));
}

private static String[] MergeIniFiles(String[] newIni, String[] previousIni)
Expand All @@ -74,6 +71,16 @@ private static String[] MergeIniFiles(String[] newIni, String[] previousIni)
{
mergedIni.RemoveAt(i--);
}
// Make sure spaces are present around =
if (!mergedIni[i].Trim().StartsWith(";"))
{
var split = mergedIni[i].Split('=');
for(Int32 j=0; j < split.Length; j++)
{
split[j] = split[j].Trim();
}
mergedIni[i] = String.Join(" = ", split);
}
}
String currentSection = "";
Int32 sectionFirstLine = 0;
Expand Down Expand Up @@ -103,6 +110,9 @@ private static String[] MergeIniFiles(String[] newIni, String[] previousIni)
}
else
{
if(mergedIni.Count > 0 && mergedIni.Last().Length > 0)
mergedIni.Add("");

mergedIni.Add("[" + currentSection + "]");
sectionFirstLine = mergedIni.Count;
sectionLastLine = sectionFirstLine;
Expand All @@ -123,7 +133,7 @@ private static String[] MergeIniFiles(String[] newIni, String[] previousIni)
Boolean fieldKnown = false;
for (Int32 i = sectionFirstLine; i < sectionLastLine; i++)
{
if (mergedIni[i].Trim().StartsWith(fieldName))
if (mergedIni[i].Trim().StartsWith(fieldName + " ="))
{
fieldKnown = true;
break;
Expand All @@ -132,104 +142,12 @@ private static String[] MergeIniFiles(String[] newIni, String[] previousIni)
if (!fieldKnown)
{
mergedIni.Insert(sectionLastLine, line);
sectionFirstLine++;
sectionLastLine++;
}
}
}
return mergedIni.ToArray();
}

private static async void MakeSureSpacesAroundEqualsigns()
{
try
{
if (File.Exists(_iniPath))
{
string wholeFile = File.ReadAllText(_iniPath);
wholeFile = wholeFile.Replace("=", " = ");
wholeFile = wholeFile.Replace(" ", " ");
wholeFile = wholeFile.Replace(" ", " ");
File.WriteAllText(_iniPath, wholeFile);
}
}
catch (Exception ex)
{
UiHelper.ShowError(Application.Current.MainWindow, ex);
}
}

private static async void MakeIniNotNull(String Category, String Setting, String Defaultvalue)
{
IniFile iniFile = new(_iniPath);
String value = iniFile.ReadValue(Category, Setting);
if (String.IsNullOrEmpty(value))
{
iniFile.WriteValue(Category, Setting + " ", " " + Defaultvalue);
}
}

public static void RemoveDuplicateKeys(string iniPath)
{
string wholeFile = File.ReadAllText(iniPath);
string cleanedContent = RemoveDuplicateKeysFromContent(wholeFile);
File.WriteAllText(iniPath, cleanedContent);
}

private static string RemoveDuplicateKeysFromContent(string content)
{
var sections = new Dictionary<string, Dictionary<string, string>>(StringComparer.OrdinalIgnoreCase);
string[] lines = content.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
string currentSection = "";

foreach (var line in lines)
{
if (string.IsNullOrWhiteSpace(line))
continue;
if (line.StartsWith("[") && line.EndsWith("]"))
{
currentSection = line.Trim('[', ']');
if (!sections.ContainsKey(currentSection))
{
sections[currentSection] = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
}
else if (!line.Contains(";") && line.Contains("=") && !line.StartsWith("="))
{
var keyValue = line.Split(['='], 2);
sections[currentSection][keyValue[0].Trim()] = keyValue[1].Trim();
}
else
{
sections[currentSection][line] = "zzz";
}
}

return GenerateContentFromSections(sections);
}

private static string GenerateContentFromSections(Dictionary<string, Dictionary<string, string>> sections)
{
var result = new List<string>();

foreach (var section in sections)
{
result.Add($"[{section.Key}]");
foreach (var keyValue in section.Value)
{
if (keyValue.Value != "zzz")
{
result.Add($"{keyValue.Key} = {keyValue.Value}");
}
else
{
result.Add($"{keyValue.Key}");
}
}
result.Add(""); // Add a blank line after each section for readability
}
return string.Join(Environment.NewLine, result);
}
}

public class IniReader
Expand Down
5 changes: 2 additions & 3 deletions Memoria.Launcher/Launcher/Settings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -627,7 +627,7 @@ private async void OnPropertyChanged([CallerMemberName] String propertyName = nu
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

IniFile iniFile = new IniFile(_iniPath);
IniFile iniFile = new IniFile(IniFile.IniPath);

foreach (Object[] item in SettingsList) {
if (item[0] is String property && property == propertyName && item[2] is String name_ini && item[3] is String category && item[4] is Int32 valueZero && item[5] is Int32 valueOne) //
Expand Down Expand Up @@ -843,7 +843,7 @@ public void LoadSettings()
{
try
{
IniFile iniFile = new(_iniPath);
IniFile iniFile = new(IniFile.IniPath);

/*foreach (Object[] item in SettingsList2)
{
Expand All @@ -865,7 +865,6 @@ public void LoadSettings()
Int16 value4;
Int16 value5;

String value = iniFile.ReadValue("Graphics", nameof(WidescreenSupport));
value = iniFile.ReadValue("Graphics", nameof(WidescreenSupport));
if (String.IsNullOrEmpty(value))
{
Expand Down
2 changes: 0 additions & 2 deletions Memoria.Launcher/Launcher/SettingsGrid_Main.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,6 @@ public SettingsGrid_Main()
//CreateTextbloc(Lang.Settings.BattleTPS, Lang.Settings.BattleTPS_Tooltip);
CreateSlider("BattleTPSDividedBy10", "BattleTPS", 15, 75, 1, "{0}x", 50, Lang.Settings.BattleTPS, Lang.Settings.BattleTPS_Tooltip);


IniFile.SanitizeMemoriaIni();
LoadSettings();
}

Expand Down
2 changes: 1 addition & 1 deletion Memoria.Launcher/ModManager/Mod.cs
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ public void TryApplyPreset()
{
if (PresetIni == null) return;
if (memoriaIni == null)
memoriaIni = new IniReader(@"./Memoria.ini");
memoriaIni = new IniReader(IniFile.IniPath);

StringBuilder sb = new StringBuilder();
IniReader.Key presetNameKey = new IniReader.Key("Preset", "Name");
Expand Down
2 changes: 1 addition & 1 deletion Memoria.Launcher/ModManager/ModManagerWindow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1273,7 +1273,7 @@ private void SetupFrameLang()
private WebClient downloadCatalogClient;
private object ascendingSortedColumn = null;

private const String INI_PATH = "./Memoria.ini";
private const String INI_PATH = IniFile.IniPath;
private const String CATALOG_PATH = "./ModCatalog.xml";
private const String CATALOG_URL = "https://raw.githubusercontent.com/Albeoris/Memoria/main/Memoria.Launcher/Catalogs/MemoriaCatalog.xml";
}
Expand Down
12 changes: 11 additions & 1 deletion Memoria.Patcher/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,16 @@ private static String[] MergeIniFiles(String[] newIni, String[] previousIni)
{
mergedIni.RemoveAt(i--);
}
// Make sure spaces are present around =
if (!mergedIni[i].Trim().StartsWith(";"))
{
var split = mergedIni[i].Split('=');
for (Int32 j = 0; j < split.Length; j++)
{
split[j] = split[j].Trim();
}
mergedIni[i] = String.Join(" = ", split);
}
}
String currentSection = "";
Int32 sectionFirstLine = 0;
Expand Down Expand Up @@ -420,6 +430,7 @@ private static String[] MergeIniFiles(String[] newIni, String[] previousIni)
}
else
{
mergedIni.Add("");
mergedIni.Add("[" + currentSection + "]");
sectionFirstLine = mergedIni.Count;
sectionLastLine = sectionFirstLine;
Expand Down Expand Up @@ -449,7 +460,6 @@ private static String[] MergeIniFiles(String[] newIni, String[] previousIni)
if (!fieldKnown)
{
mergedIni.Insert(sectionLastLine, line);
sectionFirstLine++;
sectionLastLine++;
}
}
Expand Down