From f43623d864f0155606a2832a04db094618d08ec7 Mon Sep 17 00:00:00 2001 From: DefKorns Date: Mon, 20 Oct 2025 19:51:47 +0000 Subject: [PATCH 01/39] Committing pending changes before starting .NET 8.0 upgrade. --- (S)NES Mini - Lua Compiler .csproj | 136 +- .gitignore | 2 + AppUtils.cs | 221 -- MainForm.cs | 495 ++-- MsgBox.cs | 609 ++-- Program.cs | 60 +- Properties/AssemblyInfo.cs | 2 +- Properties/Resources.Designer.cs | 2 +- Properties/Settings.Designer.cs | 2 +- Resources/modulesss/decompiler | 1 + Resources/modulesss/luajit | 1 + Utils/AppUtils.cs | 176 ++ Utils/ExceptionUtils.cs | 100 + Utils/FileUtils.cs | 372 +++ Utils/ProcessUtils.cs | 255 ++ app.config | 3 + lib/decompiler/LICENSE | 674 +++++ lib/decompiler/LICENSE-upstream | 20 + lib/decompiler/README.md | 124 + lib/decompiler/ljd/__init__.py | 6 + lib/decompiler/ljd/ast/__init__.py | 3 + lib/decompiler/ljd/ast/builder.py | 1354 +++++++++ lib/decompiler/ljd/ast/helpers.py | 125 + lib/decompiler/ljd/ast/locals.py | 317 ++ lib/decompiler/ljd/ast/mutator.py | 358 +++ lib/decompiler/ljd/ast/nodes.py | 692 +++++ lib/decompiler/ljd/ast/printast.py | 152 + lib/decompiler/ljd/ast/slotworks.py | 1015 +++++++ lib/decompiler/ljd/ast/traverse.py | 251 ++ lib/decompiler/ljd/ast/unwarper.py | 2544 +++++++++++++++++ lib/decompiler/ljd/ast/validator.py | 366 +++ lib/decompiler/ljd/bytecode/__init__.py | 3 + lib/decompiler/ljd/bytecode/constants.py | 23 + lib/decompiler/ljd/bytecode/debuginfo.py | 51 + lib/decompiler/ljd/bytecode/helpers.py | 6 + lib/decompiler/ljd/bytecode/instructions.py | 316 ++ lib/decompiler/ljd/bytecode/prototype.py | 31 + lib/decompiler/ljd/lua/__init__.py | 3 + lib/decompiler/ljd/lua/writer.py | 1139 ++++++++ lib/decompiler/ljd/pseudoasm/__init__.py | 3 + lib/decompiler/ljd/pseudoasm/constants.py | 52 + lib/decompiler/ljd/pseudoasm/instructions.py | 700 +++++ lib/decompiler/ljd/pseudoasm/prototype.py | 60 + lib/decompiler/ljd/pseudoasm/writer.py | 45 + lib/decompiler/ljd/rawdump/__init__.py | 3 + lib/decompiler/ljd/rawdump/code.py | 76 + lib/decompiler/ljd/rawdump/constants.py | 176 ++ lib/decompiler/ljd/rawdump/debuginfo.py | 97 + lib/decompiler/ljd/rawdump/header.py | 96 + .../ljd/rawdump/luajit/v2_0/luajit_opcode.py | 159 ++ .../ljd/rawdump/luajit/v2_1/luajit_opcode.py | 163 ++ lib/decompiler/ljd/rawdump/parser.py | 84 + lib/decompiler/ljd/rawdump/prototype.py | 146 + lib/decompiler/ljd/util/__init__.py | 3 + lib/decompiler/ljd/util/binstream.py | 163 ++ lib/decompiler/ljd/util/indentedstream.py | 76 + lib/decompiler/ljd/util/log.py | 20 + lib/decompiler/main.py | 456 +++ lib/luajit/jit/bc.lua | 191 ++ lib/luajit/jit/bcsave.lua | 659 +++++ lib/luajit/jit/dis_arm.lua | 689 +++++ lib/luajit/jit/dis_mips.lua | 428 +++ lib/luajit/jit/dis_mipsel.lua | 20 + lib/luajit/jit/dis_ppc.lua | 591 ++++ lib/luajit/jit/dis_x64.lua | 20 + lib/luajit/jit/dis_x86.lua | 836 ++++++ lib/luajit/jit/dump.lua | 700 +++++ lib/luajit/jit/v.lua | 167 ++ lib/luajit/jit/vmdef.lua | 331 +++ lib/luajit/lua51.dll | Bin 0 -> 347136 bytes lib/luajit/luajit.exe | Bin 0 -> 14336 bytes packages.config | 8 +- 72 files changed, 18368 insertions(+), 860 deletions(-) delete mode 100644 AppUtils.cs create mode 160000 Resources/modulesss/decompiler create mode 160000 Resources/modulesss/luajit create mode 100644 Utils/AppUtils.cs create mode 100644 Utils/ExceptionUtils.cs create mode 100644 Utils/FileUtils.cs create mode 100644 Utils/ProcessUtils.cs create mode 100644 app.config create mode 100644 lib/decompiler/LICENSE create mode 100644 lib/decompiler/LICENSE-upstream create mode 100644 lib/decompiler/README.md create mode 100644 lib/decompiler/ljd/__init__.py create mode 100644 lib/decompiler/ljd/ast/__init__.py create mode 100644 lib/decompiler/ljd/ast/builder.py create mode 100644 lib/decompiler/ljd/ast/helpers.py create mode 100644 lib/decompiler/ljd/ast/locals.py create mode 100644 lib/decompiler/ljd/ast/mutator.py create mode 100644 lib/decompiler/ljd/ast/nodes.py create mode 100644 lib/decompiler/ljd/ast/printast.py create mode 100644 lib/decompiler/ljd/ast/slotworks.py create mode 100644 lib/decompiler/ljd/ast/traverse.py create mode 100644 lib/decompiler/ljd/ast/unwarper.py create mode 100644 lib/decompiler/ljd/ast/validator.py create mode 100644 lib/decompiler/ljd/bytecode/__init__.py create mode 100644 lib/decompiler/ljd/bytecode/constants.py create mode 100644 lib/decompiler/ljd/bytecode/debuginfo.py create mode 100644 lib/decompiler/ljd/bytecode/helpers.py create mode 100644 lib/decompiler/ljd/bytecode/instructions.py create mode 100644 lib/decompiler/ljd/bytecode/prototype.py create mode 100644 lib/decompiler/ljd/lua/__init__.py create mode 100644 lib/decompiler/ljd/lua/writer.py create mode 100644 lib/decompiler/ljd/pseudoasm/__init__.py create mode 100644 lib/decompiler/ljd/pseudoasm/constants.py create mode 100644 lib/decompiler/ljd/pseudoasm/instructions.py create mode 100644 lib/decompiler/ljd/pseudoasm/prototype.py create mode 100644 lib/decompiler/ljd/pseudoasm/writer.py create mode 100644 lib/decompiler/ljd/rawdump/__init__.py create mode 100644 lib/decompiler/ljd/rawdump/code.py create mode 100644 lib/decompiler/ljd/rawdump/constants.py create mode 100644 lib/decompiler/ljd/rawdump/debuginfo.py create mode 100644 lib/decompiler/ljd/rawdump/header.py create mode 100644 lib/decompiler/ljd/rawdump/luajit/v2_0/luajit_opcode.py create mode 100644 lib/decompiler/ljd/rawdump/luajit/v2_1/luajit_opcode.py create mode 100644 lib/decompiler/ljd/rawdump/parser.py create mode 100644 lib/decompiler/ljd/rawdump/prototype.py create mode 100644 lib/decompiler/ljd/util/__init__.py create mode 100644 lib/decompiler/ljd/util/binstream.py create mode 100644 lib/decompiler/ljd/util/indentedstream.py create mode 100644 lib/decompiler/ljd/util/log.py create mode 100644 lib/decompiler/main.py create mode 100644 lib/luajit/jit/bc.lua create mode 100644 lib/luajit/jit/bcsave.lua create mode 100644 lib/luajit/jit/dis_arm.lua create mode 100644 lib/luajit/jit/dis_mips.lua create mode 100644 lib/luajit/jit/dis_mipsel.lua create mode 100644 lib/luajit/jit/dis_ppc.lua create mode 100644 lib/luajit/jit/dis_x64.lua create mode 100644 lib/luajit/jit/dis_x86.lua create mode 100644 lib/luajit/jit/dump.lua create mode 100644 lib/luajit/jit/v.lua create mode 100644 lib/luajit/jit/vmdef.lua create mode 100644 lib/luajit/lua51.dll create mode 100644 lib/luajit/luajit.exe diff --git a/(S)NES Mini - Lua Compiler .csproj b/(S)NES Mini - Lua Compiler .csproj index 6343443..ffaeb30 100644 --- a/(S)NES Mini - Lua Compiler .csproj +++ b/(S)NES Mini - Lua Compiler .csproj @@ -1,11 +1,5 @@  - - - - - - Debug @@ -14,7 +8,7 @@ WinExe SNESMiniLuaCompiler %28S%29NES Mini - Lua Compiler - v4.7.2 + v4.8 512 true false @@ -22,7 +16,7 @@ - publish\ + E:\Desktop\canais\ false Disk false @@ -32,7 +26,7 @@ false false true - 2 + 4 1.0.0.%2a false true @@ -85,9 +79,6 @@ Properties/app.manifest - - packages\LibGit2Sharp.0.26.2\lib\net46\LibGit2Sharp.dll - C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2\System.dll @@ -105,6 +96,9 @@ + + + Form @@ -119,7 +113,7 @@ - + MainForm.cs Designer @@ -133,6 +127,7 @@ Resources.Designer.cs + SettingsSingleFileGenerator @@ -152,6 +147,98 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -2028,28 +2115,11 @@ - - - - - - - - - + + + - - - This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - - - - - - diff --git a/.gitignore b/.gitignore index d2b709e..a67bab1 100644 --- a/.gitignore +++ b/.gitignore @@ -426,3 +426,5 @@ MigrationBackup/ .vscode/settings.json (S)NES Mini - Lua Compiler .sln lib/hashes +/bin-- +/modules diff --git a/AppUtils.cs b/AppUtils.cs deleted file mode 100644 index 0181f51..0000000 --- a/AppUtils.cs +++ /dev/null @@ -1,221 +0,0 @@ -using System; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Security.Cryptography; -using System.Windows.Forms; - - -namespace SNESMiniLuaCompiler -{ - public static class AppUtils - { - private const ProcessWindowStyle hidden = ProcessWindowStyle.Hidden; - private static Cursor Cursor; - - public static readonly string appPath = Path.GetDirectoryName(Application.ExecutablePath); - public static readonly string modulesPath = Path.Combine(appPath, "modules"); - public static readonly string decodedPath = Path.Combine(appPath, "decoded"); - public static readonly string recodedPath = Path.Combine(appPath, "recoded"); - public static readonly string originalPath = Path.Combine("lib", "original"); - public static readonly string luaJitPath = Path.Combine("modules", "luajit"); - public static readonly string decompilerPath = Path.Combine("modules", "decompiler"); - public static readonly string decompilerScript = Path.Combine(decompilerPath, "main.py"); - public static readonly string decodedHashFile = Path.Combine("lib", "hashes"); - public static readonly string firstRun = Path.Combine("lib", "firstRun"); - public static readonly string batFile = "encode.bat"; - - public static void CopyAssets(string sourceFolder, string destFolder) - { - CreatePath(destFolder); - string[] files = Directory.GetFiles(sourceFolder); - foreach (string file in files) - { - string name = Path.GetFileName(file); - string dest = Path.Combine(destFolder, name); - File.Copy(file, dest, true); - } - string[] folders = Directory.GetDirectories(sourceFolder); - foreach (string folder in folders) - { - string name = Path.GetFileName(folder); - string dest = Path.Combine(destFolder, name); - CopyAssets(folder, dest); - } - } - - public static string FindExePath(string exe) - { - exe = Environment.ExpandEnvironmentVariables(exe); - if (!File.Exists(exe)) - { - if (string.IsNullOrEmpty(Path.GetDirectoryName(exe))) - { - foreach (string arg in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(';')) - { - string path = arg.Trim(); - if (!string.IsNullOrEmpty(path) && File.Exists(path = Path.Combine(path, exe))) - return Path.GetFullPath(path); - } - } - } - return ""; - } - - public static void RunCmd(string cmd, string args) - { - ProcessStartInfo start = new ProcessStartInfo - { - FileName = cmd, - Arguments = args, - UseShellExecute = false, - RedirectStandardOutput = true - }; - using (Process process = Process.Start(start)) - { - using (StreamReader reader = process.StandardOutput) - { - string result = reader.ReadToEnd(); - } - } - } - - public static void CreateLuaJitLauncher() - { - if (!File.Exists(batFile)) - { - StreamWriter w = new StreamWriter(batFile); - w.WriteLine("@setlocal enableextensions enabledelayedexpansion"); - w.WriteLine("@echo off"); - w.WriteLine("set LuaJit=modules\\luajit"); - w.WriteLine("set LUA_DIR=%LuaJit%"); - w.WriteLine("set LUA_CPATH=?.dll;%LUA_DIR%\\?.dll"); - w.WriteLine("set LUA_PATH=?.lua;%LUA_DIR%\\jit\\?.lua;%LUA_DIR%\\?.lua"); - w.WriteLine("%LuaJit%\\luajit.exe -b %1 %2"); - w.Close(); - } - } - - public static string GetSHA256HashFromFile(string fileName) - { - using (var sha256 = SHA256.Create()) - { - using (var stream = File.OpenRead(fileName)) - { - return BitConverter.ToString(sha256.ComputeHash(stream)).Replace("-", string.Empty).ToLower(CultureInfo.CurrentCulture); - } - } - } - - public static void GenerateFileHash(string fileName) - { - string fileHash = GetSHA256HashFromFile(fileName); - - using (StreamWriter sw = File.AppendText(decodedHashFile)) - { - sw.WriteLine(fileHash); - } - } - - public static bool HasEditedFiles(string hash) - { - foreach (var line in File.ReadAllLines(decodedHashFile)) - { - if (line.Contains(hash)) - { - return false; - } - - } - return true; - } - - public static void RunLuaJit(string args) - { - ProcessStartInfo startInfo = new ProcessStartInfo - { - WorkingDirectory = appPath, - CreateNoWindow = false, - FileName = "encode.bat", - WindowStyle = hidden, - Arguments = args - }; - - using (Process batProcess = Process.Start(startInfo)) - { - batProcess.WaitForExit(); - } - - } - - public static void LoadSpinner(bool displayLoader, PictureBox loaderImage, Form form) - { - ThrowArgNull(loaderImage); - ThrowArgNull(form); - - if (displayLoader) - { - form.Invoke((MethodInvoker)delegate - { - loaderImage.Visible = true; - loaderImage.BringToFront(); - Cursor = Cursors.WaitCursor; - }); - } - else - { - form.Invoke((MethodInvoker)delegate - { - loaderImage.Visible = false; - Cursor = Cursors.Default; - }); - } - } - - public static void CreatePath(string path) - { - bool folderExists = Directory.Exists(path); - if (!folderExists) - Directory.CreateDirectory(path); - } - - public static void DeletePath(string path) - { - bool folderExists = Directory.Exists(path); - if (folderExists) - { - Directory.Delete(path, true); - } - } - - public static void DeleteEmptyDirectories(string startLocation) - { - foreach (var directory in Directory.GetDirectories(startLocation)) - { - DeleteEmptyDirectories(directory); - if (Directory.GetFiles(directory).Length == 0 && - Directory.GetDirectories(directory).Length == 0) - { - Directory.Delete(directory, false); - } - } - } - - public static void DeleteFile(string file) - { - bool fileExists = File.Exists(file); - if (fileExists) - { - File.Delete(file); - } - } - - public static void ThrowArgNull(object arg) - { - if (arg == null) throw new ArgumentNullException(nameof(arg), "There is no expression with which to test the object's value."); - } - - } - - -} diff --git a/MainForm.cs b/MainForm.cs index e5162cf..8c58e50 100644 --- a/MainForm.cs +++ b/MainForm.cs @@ -1,11 +1,10 @@ -using System; -using System.Windows.Forms; +using SNESMiniLuaCompiler.Utils; +using System; using System.Drawing; using System.IO; using System.Text.RegularExpressions; -using System.Threading; -using System.Diagnostics; using System.Threading.Tasks; +using System.Windows.Forms; namespace SNESMiniLuaCompiler { @@ -13,75 +12,90 @@ public partial class MainForm : Form { private bool _dragging; private Point _start_point = new Point(0, 0); - private readonly Image backgroundImage; - private string SelectecSystem { get; set; } - private bool ActiveButton { get; set; } + private readonly Image _backgroundImage; + private string _selectedSystem; + private bool _activeButton { get; set; } + delegate void SetButtonCallback(Button button); public MainForm() { - InitializeComponent(); - var name = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name; - var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; - app_title.Text = name + " " + version.Major + "." + version.Minor + " (build " + version.Build + ")"; - backgroundImage = Properties.Resources.app_bg; - DoubleBuffered = true; - picLoader.Visible = false; - - if (File.Exists(AppUtils.firstRun)) - { - MsgBox.Show("Make sure you have python 3.x installed!\n\nPlease download it from python.org", "Requirement", MsgBox.ButtonType.OK, MsgBox.Ico.Application, MsgBox.AnimateStyle.FadeIn); - File.Delete(AppUtils.firstRun); - } - + InitializeAppTitle(); + _backgroundImage = Properties.Resources.app_bg; + InitializeBackground(); + InitializeFirstRunCheck(); SetStyle(ControlStyles.ResizeRedraw, true); - - if (!ActiveButton) - { - if (!Directory.Exists(AppUtils.recodedPath) || !Directory.Exists(AppUtils.decodedPath)) - { - DisableControls(recode_button); - recode_button.FlatAppearance.BorderSize = 0; - } - DisableControls(decode_button); - decode_button.FlatAppearance.BorderSize = 0; - } + InitializeButtonStates(); } + #region Initialization /// - /// The methods Title_Header_Mouse* allows dragging and move the app around + /// Sets the application title with the assembly name and version. /// - private void Title_Header_MouseDown(object sender, MouseEventArgs e) + private void InitializeAppTitle() { - _dragging = true; - _start_point = new Point(e.X, e.Y); + var assembly = System.Reflection.Assembly.GetExecutingAssembly().GetName(); + app_title.Text = $"{assembly.Name} {AppUtils.GetAppVersion()}"; } - private void Title_Header_MouseUp(object sender, MouseEventArgs e) + + /// + /// Sets the default background image and enables double buffering. + /// + private void InitializeBackground() { - _dragging = false; + DoubleBuffered = true; + picLoader.Visible = false; } - private void Title_Header_MouseMove(object sender, MouseEventArgs e) + + /// + /// Initializes the state of buttons based on directory existence and active button status. + /// + private void InitializeButtonStates() { - if (_dragging) + if (_activeButton) return; + + if (!Directory.Exists(AppUtils.RecodedPath) || !Directory.Exists(AppUtils.DecodedPath)) { - Point p = PointToScreen(e.Location); - Location = new Point(p.X - _start_point.X, p.Y - _start_point.Y); + ConfigureButtonState(recode_button, 0); } + + ConfigureButtonState(decode_button, 0); } + /// - /// Close application by clicking on the 'X' + /// Checks if this is the first run and verifies Python installation. /// - private void App_Exit_MouseClick(object sender, MouseEventArgs e) + private static void InitializeFirstRunCheck() { - DialogResult dialog = MsgBox.Show("Are you sure you want to exit?", "Exit application", MsgBox.ButtonType.YesNo, MsgBox.Ico.Warning, MsgBox.AnimateStyle.FadeIn); + const string PythonRequirementMessage = "Make sure you have python 3.x installed!\n\nPlease download it from python.org"; - if (dialog == DialogResult.Yes) + ExceptionUtils.GlobalTryCatch(() => { - fadeOutTimer.Start(); - } + // Check if Python 3.x is installed + if (!ProcessUtils.PythonVersion()) + { + MsgBox.Show( + PythonRequirementMessage, + "Requirement", + MsgBox.ButtonType.OK, + MsgBox.Ico.Application, + style: MsgBox.AnimateStyle.FadeInHelp + ); + } + // Remove the first-run marker file if it exists + if (FileUtils.SafeFileExists(AppUtils.FirstRun)) + { + File.Delete(AppUtils.FirstRun); + } + }, + "An error occurred during the first run check.", + "MainForm.InitializeFirstRunCheck"); } + #endregion + + #region UI Event Handlers private void MainForm_Load(object sender, EventArgs e) { @@ -91,12 +105,18 @@ private void MainForm_Load(object sender, EventArgs e) fadeInTimer.Start(); } - void FadeIn(object sender, EventArgs e) + /// + /// Close application by clicking on the 'X' + /// + private void App_Exit_MouseClick(object sender, MouseEventArgs e) { - if (Opacity >= 1) - fadeInTimer.Stop(); - else - Opacity += 0.05; + DialogResult dialog = MsgBox.Show("Are you sure you want to exit?", "Exit application", MsgBox.ButtonType.YesNo, MsgBox.Ico.Warning, MsgBox.AnimateStyle.FadeIn); + + if (dialog == DialogResult.Yes) + { + fadeOutTimer.Start(); + } + } private void FadeOutTimer_Tick(object sender, EventArgs e) @@ -112,47 +132,52 @@ private void FadeOutTimer_Tick(object sender, EventArgs e) Application.Exit(); } } - /// - /// Acts as angular disable atribute - /// - /// Control to be disabled - private void DisableControls(Control con) + + void FadeIn(object sender, EventArgs e) { - if (con.InvokeRequired) - { - SetButtonCallback d = new SetButtonCallback(DisableControls); - Invoke(d, new object[] { con }); - } + if (Opacity >= 1) + fadeInTimer.Stop(); else - { - con.Enabled = false; - } + Opacity += 0.05; } + /// - /// Acts as angular disable="false" atribute + /// The methods Title_Header_Mouse* allows dragging and move the app around /// - /// Control to be enabled - private void EnableControls(Control con) + private void Title_Header_MouseDown(object sender, MouseEventArgs e) { - if (con.InvokeRequired) - { - SetButtonCallback d = new SetButtonCallback(EnableControls); - Invoke(d, new object[] { con }); - } - else - { - con.Enabled = true; - } + _dragging = true; + _start_point = new Point(e.X, e.Y); + } + + private void Title_Header_MouseMove(object sender, MouseEventArgs e) + { + if (!_dragging) return; + + Point p = PointToScreen(e.Location); + Location = new Point(p.X - _start_point.X, p.Y - _start_point.Y); + } + + private void Title_Header_MouseUp(object sender, MouseEventArgs e) + { + _dragging = false; + } + private void HelpButton_Click(object sender, EventArgs e) + { + MsgBox.Show("- Select the icon for your desired system\n\n- Press the \"Decode\" button to proceed\n\n- After conclusion, navigate to the \"decoded\" folder and edit the lua files as desired\n\n- With all your files saved press the \"Encode\" button\n\n- Copy all the edited files to you theme's location", "Instructions", MsgBox.ButtonType.OK, MsgBox.Ico.Application, MsgBox.AnimateStyle.FadeInHelp); } + private void BtnRestore_EnabledChanged(object sender, EventArgs e) { recode_button.ForeColor = recode_button.Enabled ? Color.FromArgb(68, 140, 203) : Color.FromArgb(81, 113, 127); } + private void BtnBackup_EnabledChanged(object sender, EventArgs e) { decode_button.ForeColor = decode_button.Enabled ? Color.FromArgb(81, 172, 56) : Color.FromArgb(93, 129, 83); } + private void Button_Paint(object sender, PaintEventArgs e) { var btn = (Button)sender; @@ -163,6 +188,23 @@ private void Button_Paint(object sender, PaintEventArgs e) drawBrush.Dispose(); sf.Dispose(); } + + #endregion + + #region Button State Management + + /// + /// Configures the state and border size of a button. + /// + /// The button to configure. + /// The border size to apply to the button. + private static void ConfigureButtonState(Button button, int borderSize) + { + //EnableControls(new Control[] { button }, false); + //button.FlatAppearance.BorderSize = borderSize; + AppUtils.SetButtonState(button, false, borderSize); + } + /// /// Restore default backgroundcolor to buttons /// @@ -172,191 +214,226 @@ private void ResetButtonBackColor() { if (item is Button button) { - button.FlatAppearance.BorderSize = 0; + //button.FlatAppearance.BorderSize = 0; + AppUtils.SetButtonState(button, button.Enabled, 0); } } } - private void HelpButton_Click(object sender, EventArgs e) - { - MsgBox.Show("- Select the icon for your desired system\n\n- Press the \"Decode\" button to proceed\n\n- After conclusion, navigate to the \"decoded\" folder and edit the lua files as desired\n\n- With all your files saved press the \"Encode\" button\n\n- Copy all the edited files to you theme's location", "Instructions", MsgBox.ButtonType.OK, MsgBox.Ico.Application, MsgBox.AnimateStyle.FadeInHelp); - } + private void SelectedSystem_Click(object sender, EventArgs e) { ResetButtonBackColor(); - Button btn = (sender as Button); - btn.FlatAppearance.BorderColor = Color.FromArgb(215, 152, 43);//Color.FromArgb(110, 86, 48); - btn.FlatAppearance.BorderSize = 2; - decode_button.FlatAppearance.BorderSize = 2; - recode_button.FlatAppearance.BorderSize = 2; - EnableControls(decode_button); - EnableControls(recode_button); - if (!Directory.Exists(AppUtils.decodedPath) || !Directory.Exists(AppUtils.recodedPath)) - { - recode_button.FlatAppearance.BorderSize = 0; - DisableControls(recode_button); - } - ActiveButton = true; + if (!(sender is Button btn)) return; - switch (btn.Name) - { - case "famicomButton": - SelectecSystem = Path.Combine(AppUtils.originalPath, "hvc"); - break; - case "famicom50Button": - SelectecSystem = Path.Combine(AppUtils.originalPath, "hvcj"); - break; - case "sFamicomButton": - SelectecSystem = Path.Combine(AppUtils.originalPath, "shvc"); - break; - case "nesButton": - SelectecSystem = Path.Combine(AppUtils.originalPath, "nes"); - break; - case "snesPALButton": - SelectecSystem = Path.Combine(AppUtils.originalPath, "snes-eur"); - break; - default: - SelectecSystem = Path.Combine(AppUtils.originalPath, "snes-usa"); - break; + const int BorderSize = 2; + var activeBorderColor = Color.FromArgb(215, 152, 43); + var inactiveBorderSize = 0; - } - } - private void DecryptButton_Click(object sender, EventArgs e) - { - ThreadLauncher(DecryptFiles); + // Set button styles + SetButtonStyle(btn, activeBorderColor, BorderSize); + SetButtonStyle(decode_button, Color.FromArgb(81, 172, 56), BorderSize); + SetButtonStyle(recode_button, Color.FromArgb(18, 108, 182), BorderSize); - } - private void EncryptButton_Click(object sender, EventArgs e) - { - ThreadLauncher(EncryptFiles); - } - private void Decrypt(string sDir) - { - foreach (string d in Directory.GetDirectories(sDir)) + EnableControls(new Control[] { decode_button, recode_button }, true); + + //if (!Directory.Exists(DecodedPath) || !Directory.Exists(RecodedPath)) + if (!AppUtils.AreDecodedAndRecodedDirsPresent()) { - Decrypt(d); + SetButtonStyle(recode_button, activeBorderColor, inactiveBorderSize); + EnableControls(new Control[] { recode_button }, false); } - foreach (string file in Directory.GetFiles(sDir)) - { - string decFile = file + ".dec"; - AppUtils.RunCmd(AppUtils.FindExePath("pythonw.exe"), AppUtils.decompilerScript + " --file " + file + " --output " + decFile + " --catch_asserts"); - File.Delete(file); - File.Move(decFile, file); - AppUtils.GenerateFileHash(file); - } + _activeButton = true; + _selectedSystem = AppUtils.GetSystemPath(btn.Name); } - private void Encrypt(string sDir) - { - foreach (string d in Directory.GetDirectories(sDir)) - { - Encrypt(d); - } - - foreach (string decodedFile in Directory.GetFiles(sDir)) - { - string decodedFullPath = Path.GetDirectoryName(decodedFile); - string recodedFullPath = Regex.Replace(decodedFullPath, "decoded", "recoded"); - string recodedFile = Regex.Replace(decodedFile, "decoded", "recoded"); + private static void SetButtonStyle(Button button, Color borderColor, int borderSize) + { + AppUtils.SetButtonState(button, button.Enabled, borderSize, borderColor); + } - AppUtils.CreatePath(recodedFullPath); - AppUtils.CreateLuaJitLauncher(); + private void EnableAllButtons(bool enable) + { + EnableControls(new Control[] { recode_button, famicomButton, famicom50Button, sFamicomButton, nesButton, snesPALButton, snesButton, decode_button }, enable); + } - if (AppUtils.HasEditedFiles(AppUtils.GetSHA256HashFromFile(decodedFile))) + /// + /// Acts as angular disable="false" atribute + /// + /// Control to be enabled + private void EnableControls(Control[] controls, bool enable) + { + foreach (var con in controls) + { + if (con.InvokeRequired) + { + SetButtonCallback d = new SetButtonCallback(c => EnableControls(new[] { c }, enable)); + Invoke(d, new object[] { con }); + } + else { - AppUtils.RunLuaJit(decodedFile + " " + recodedFile); + con.Enabled = enable; + if (con is Button btn) + { + if (btn != recode_button && btn != decode_button) + { + btn.FlatAppearance.MouseOverBackColor = Color.FromArgb(186, 132, 37); + } + } } } - AppUtils.DeleteFile(AppUtils.batFile); - AppUtils.DeleteEmptyDirectories(AppUtils.recodedPath); } - private void DisableAllButtons() + #endregion + + #region Decrypt/Encrypt Logic + + private async void DecryptButton_Click(object sender, EventArgs e) { - DisableControls(recode_button); - DisableControls(decode_button); - DisableControls(famicomButton); - DisableControls(famicom50Button); - DisableControls(sFamicomButton); - DisableControls(nesButton); - DisableControls(snesPALButton); - DisableControls(snesButton); + await DecryptFilesAsync().ConfigureAwait(false); } - private void EnableAllButtons() + + private async void EncryptButton_Click(object sender, EventArgs e) { - EnableControls(recode_button); - EnableControls(famicomButton); - EnableControls(famicom50Button); - EnableControls(sFamicomButton); - EnableControls(nesButton); - EnableControls(snesPALButton); - EnableControls(snesButton); - EnableControls(decode_button); + await EncryptFilesAsync().ConfigureAwait(false); } - private void DecryptFiles() - { - DisableAllButtons(); - if (!string.IsNullOrEmpty(AppUtils.FindExePath("python.exe"))) + private async Task DecryptFilesAsync() + { + EnableAllButtons(false); + if (string.IsNullOrEmpty(ProcessUtils.FindExePath("python.exe"))) { - AppUtils.LoadSpinner(true, picLoader, this); - AppUtils.DeletePath(AppUtils.decodedPath); - AppUtils.CopyAssets(SelectecSystem, AppUtils.decodedPath); - AppUtils.DeleteFile(AppUtils.decodedHashFile); + MsgBox.Show("Python 3.x wasn't found on your system's PATH.\nPlease install it from python.org", "Error", MsgBox.ButtonType.OK, MsgBox.Ico.Warning); + return; + } + AppUtils.LoadSpinner(true, picLoader, this); + await Task.Run(() => + { + FileUtils.DeletePath(AppUtils.DecodedPath); + FileUtils.CopyAssets(_selectedSystem, AppUtils.DecodedPath); + FileUtils.DeleteFile(FileUtils.DecodedHashFile); Decrypt("decoded"); + }).ConfigureAwait(false); + EnableAllButtons(true); + decode_button.FlatAppearance.BorderSize = 2; + recode_button.FlatAppearance.BorderSize = 2; + AppUtils.LoadSpinner(false, picLoader, this); + FileUtils.CreatePath(AppUtils.RecodedPath); - EnableAllButtons(); - decode_button.FlatAppearance.BorderSize = 2; - recode_button.FlatAppearance.BorderSize = 2; - AppUtils.LoadSpinner(false, picLoader, this); - AppUtils.CreatePath(AppUtils.recodedPath); - DialogResult dialog = MsgBox.Show("The decrytion has finished.\n\nDo you want to navigate to the output directory?", "Success", MsgBox.ButtonType.YesNo, MsgBox.Ico.Application, MsgBox.AnimateStyle.FadeIn); - - if (dialog == DialogResult.Yes) - { - Process.Start(@AppUtils.decodedPath); - } - } + Action showDialog = ShowDecryptionFinishedDialog; + if (InvokeRequired) + Invoke(showDialog); else + showDialog(); + } + + private void ShowDecryptionFinishedDialog() + { + DialogResult dialog = MsgBox.Show(this, + "The decryption process is complete.\n\nWould you like to open the output directory now?", + "Success", + MsgBox.ButtonType.YesNo, + MsgBox.Ico.Application, + MsgBox.AnimateStyle.FadeIn + ); + + if (dialog == DialogResult.Yes) { - MsgBox.Show("Python 3.x wasn't found on your system's PATH.\nPlease install it from python.org", "Error", MsgBox.ButtonType.OK, MsgBox.Ico.Warning); + ProcessUtils.OpenDirectory(AppUtils.DecodedPath); } - } - private void EncryptFiles() + + private async Task EncryptFilesAsync() { ResetButtonBackColor(); - AppUtils.DeletePath(AppUtils.recodedPath); - ActiveButton = false; + FileUtils.DeletePath(AppUtils.RecodedPath); + _activeButton = false; - DisableAllButtons(); + EnableAllButtons(false); AppUtils.LoadSpinner(true, picLoader, this); - Encrypt("decoded"); + // Run Encrypt on a background thread to make the method truly async + await Task.Run(() => Encrypt("decoded")).ConfigureAwait(false); AppUtils.LoadSpinner(false, picLoader, this); - EnableAllButtons(); - DisableControls(decode_button); + EnableAllButtons(true); + EnableControls(new Control[] { decode_button }, false); recode_button.FlatAppearance.BorderSize = 2; } - private static void ThreadLauncher(ThreadStart data) + + private void Decrypt(string sDir) { - try + foreach (string d in Directory.GetDirectories(sDir)) + { + ExceptionUtils.GlobalTryCatch( + () => Decrypt(d), + $"Error decrypting directory '{d}'.", + "MainForm.Decrypt" + ); + } + + foreach (string file in Directory.GetFiles(sDir)) { - Thread threadInput = new Thread(data); - threadInput.Start(); + string decFile = file + ".dec"; + ExceptionUtils.GlobalTryCatch( + () => + { + ProcessUtils.RunCmd(ProcessUtils.FindExePath("pythonw.exe"), AppUtils.DecompilerScript + " --file " + file + " --output " + decFile + " --catch_asserts"); + File.Delete(file); + File.Move(decFile, file); + FileUtils.GenerateFileHash(file); + }, + $"Error decrypting file '{file}'.", + "MainForm.Decrypt" + ); + } + } + private void Encrypt(string sDir) + { + foreach (string d in Directory.GetDirectories(sDir)) + { + ExceptionUtils.GlobalTryCatch( + () => Encrypt(d), + $"Error encrypting directory '{d}'.", + "MainForm.Encrypt" + ); } - catch (ThreadStateException ex) + + foreach (string decodedFile in Directory.GetFiles(sDir)) { - MsgBox.Show(ex.Message, "Error", MsgBox.ButtonType.OK, MsgBox.Ico.Warning); + string decodedFullPath = Path.GetFullPath(decodedFile); + string recodedFullPath = Path.GetFullPath(Regex.Replace(decodedFullPath, "decoded", "recoded")); + string recodedFile = Path.GetFullPath(Regex.Replace(decodedFullPath, "decoded", "recoded")); + + ExceptionUtils.GlobalTryCatch( + () => + { + FileUtils.CreatePath(Path.GetDirectoryName(recodedFullPath)); + + if (FileUtils.HasEditedFiles(FileUtils.GetSHA256HashFromFile(decodedFullPath))) + { + ProcessUtils.RunLuaJit(decodedFullPath, recodedFile); + } + }, + $"Error encrypting file '{decodedFile}'.", + "MainForm.Encrypt" + ); } + + ExceptionUtils.GlobalTryCatch( + () => FileUtils.DeleteEmptyDirectories(AppUtils.RecodedPath), + $"Error deleting empty directories in '{AppUtils.RecodedPath}'.", + "MainForm.Encrypt" + ); } + + #endregion } } diff --git a/MsgBox.cs b/MsgBox.cs index 3d6cd78..39a8c89 100644 --- a/MsgBox.cs +++ b/MsgBox.cs @@ -1,20 +1,19 @@ -using System; +using SNESMiniLuaCompiler.Utils; +using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; -using System.Linq; +using System.Globalization; using System.Runtime.InteropServices; -using System.Text.RegularExpressions; using System.Windows.Forms; using Timer = System.Windows.Forms.Timer; namespace SNESMiniLuaCompiler { -public partial class MsgBox : Form + public partial class MsgBox : Form { private const int CS_DROPSHADOW = 0x00020000; - private static MsgBox _msgBox; private readonly Panel _plHeader = new Panel(); private readonly Panel _plFooter = new Panel(); private readonly Panel _plIcon = new Panel(); @@ -23,21 +22,19 @@ public partial class MsgBox : Form private readonly Label _lblTitle; private readonly Label _lblMessage; private readonly List