using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using GameLauncher.Engines.Common; namespace GameLauncher.Engines.Evb { /// /// Orchestrates detection and unpacking of Enigma Virtual Box (EVB) packed games, /// then re-detects the real engine from the unpacked content. /// /// Design (per AGENTS.md): /// - Everything engine-local lives under `Engines/Evb/`. /// - The original packed exe is backed up (`.glbak`) before being replaced, so the /// operation can always be restored (Enigma recovery / manual restore). /// - Unpacked output is written into a game-local `_evb_extracted` folder, so no /// other game is ever affected. /// - The bundled evbunpack tool (see ) does the work; /// if it is missing the operation degrades gracefully (returns a failed result). /// public sealed class EvbUnpackService { /// Game-local folder that receives the unpacked files. public const string ExtractedDirName = "_evb_extracted"; /// Marker file written last when an extraction finished successfully. public const string CompleteMarkerName = ".evb_complete"; /// Backup suffix applied to the original packed executable. public const string ExeBackupSuffix = ".glbak"; /// Result of an unpack attempt. public sealed class UnpackResult { /// True when unpacking produced usable output. public bool Success { get; init; } /// Folder that contains the unpacked files (null on failure). public string? OutputDirectory { get; init; } /// Absolute path of the original packed executable (null when not found). public string? SourceExePath { get; init; } /// Absolute path of the backed-up original executable (null when no backup was made). public string? BackupExePath { get; init; } /// Engine name re-detected from the unpacked content (canonical name). public string UnderlyingEngine { get; init; } = EngineDetectionHelper.EngineUnknown; /// Human-readable message describing the outcome. public string Message { get; init; } = string.Empty; /// True when output was already present and re-used (idempotent skip). public bool ReusedExisting { get; init; } } /// Game-local extraction folder for the given game root. public static string GetExtractedDir(string gameRootDir) => Path.Combine(gameRootDir, ExtractedDirName); /// Marker file path inside the extraction folder. public static string GetCompleteMarkerPath(string outputDirectory) => Path.Combine(outputDirectory, CompleteMarkerName); /// /// Resolves the executable to launch from an unpacked output folder. /// Prefers a well-known game exe name, then the first `.exe` found (top level first, /// then one level deep). Returns null when nothing usable is found. /// public static string? FindLaunchExecutable(string? outputDirectory) { if (string.IsNullOrWhiteSpace(outputDirectory) || !Directory.Exists(outputDirectory)) { return null; } try { // Preferred names commonly used by NW.js / RPG Maker / Tyrano bundles. string[] preferred = ["Game.exe", "game.exe", "nw.exe", "Game_boxed.exe"]; foreach (var name in preferred) { var direct = Path.Combine(outputDirectory, name); if (File.Exists(direct)) { return direct; } } // First exe at the top level, then one level deeper. var top = Directory.GetFiles(outputDirectory, "*.exe", SearchOption.TopDirectoryOnly); if (top.Length > 0) { return top[0]; } foreach (var sub in Directory.GetDirectories(outputDirectory)) { var nested = Directory.GetFiles(sub, "*.exe", SearchOption.TopDirectoryOnly); if (nested.Length > 0) { return nested[0]; } } } catch { // Ignore IO errors and fall back to no result. } return null; } /// /// True when the game folder already holds a completed EVB extraction. /// A non-empty output folder is NOT enough: the run may have been interrupted, /// so the presence of the completion marker is required. /// public static bool IsExtractionComplete(string gameRootDir, out string? outputDirectory) { outputDirectory = GetExtractedDir(gameRootDir); try { return Directory.Exists(outputDirectory) && File.Exists(GetCompleteMarkerPath(outputDirectory)); } catch { return false; } } /// /// Unpacks the EVB-packed executable in the game folder and re-detects the /// underlying engine. Idempotent: a completed prior extraction is re-used. /// /// Game root folder containing the packed exe. /// Optional progress sink. public UnpackResult Unpack( string gameRootDir, IProgress? progress = null, bool legacyFileSystem = false, string? peVariant = null) { if (string.IsNullOrWhiteSpace(gameRootDir) || !Directory.Exists(gameRootDir)) { return new UnpackResult { Success = false, Message = "ゲームフォルダが見つかりません。" }; } // Idempotent: reuse a previous successful extraction. if (IsExtractionComplete(gameRootDir, out var existingDir) && existingDir != null) { var reusedEngine = EngineDetectionHelper.RepairMisdetection( existingDir, EngineDetectionHelper.EngineUnknown); return new UnpackResult { Success = true, OutputDirectory = existingDir, UnderlyingEngine = reusedEngine, ReusedExisting = true, Message = $"既に解凍済みです({ExtractedDirName} を再利用)。", }; } var sourceExe = EvbDetectionHelper.FindEvbPackedExecutable(gameRootDir); if (sourceExe == null) { return new UnpackResult { Success = false, Message = "EVB パック済みの実行ファイルが見つかりませんでした。", }; } var toolPath = EvbUnpackerToolProvider.GetToolPath(); if (toolPath == null) { return new UnpackResult { Success = false, SourceExePath = sourceExe, Message = "解凍ツール (evbunpack) が見つかりません。Engines\\Evb\\Tools\\evbunpack\\ に配置してください。", }; } var outputDir = GetExtractedDir(gameRootDir); try { // Start clean so partial output never mixes with a fresh run. if (Directory.Exists(outputDir)) { Directory.Delete(outputDir, recursive: true); } Directory.CreateDirectory(outputDir); progress?.Report($"EVB 解凍を開始します: {Path.GetFileName(sourceExe)}"); var args = EvbUnpackerToolProvider.BuildArguments(sourceExe, outputDir, legacyFileSystem, peVariant); if (!RunTool(toolPath, args, gameRootDir, progress, out var exitCode)) { return new UnpackResult { Success = false, SourceExePath = sourceExe, OutputDirectory = outputDir, Message = $"evbunpack の実行に失敗しました (exit code={exitCode})。", }; } if (!Directory.EnumerateFileSystemEntries(outputDir).Any()) { return new UnpackResult { Success = false, SourceExePath = sourceExe, OutputDirectory = outputDir, Message = "解凍は実行されましたが出力が空でした。PE バリアント (-pe 10_70 / 7_80) を変えて再試行してください。", }; } // Move the original packed exe out of the way so it is no longer recognized // as an executable by the scanner (`.glbak` is not scanned as `*.exe`). string? backupPath = null; try { backupPath = sourceExe + ExeBackupSuffix; if (File.Exists(backupPath)) { // A previous backup exists; remove it so the move can succeed. File.Delete(backupPath); } File.Move(sourceExe, backupPath); progress?.Report($"元の実行ファイルを退避しました: {Path.GetFileName(backupPath)}"); } catch (Exception ex) { progress?.Report($"バックアップに失敗しました(解凍自体は成功): {ex.Message}"); } // Completion marker is written last, so an interrupted run is detectable. File.WriteAllText(GetCompleteMarkerPath(outputDir), DateTime.UtcNow.ToString("o")); // Re-detect the real engine from the unpacked content. var underlying = ReDetectUnderlyingEngine(outputDir); progress?.Report($"解凍後のエンジン再判定: {underlying}"); return new UnpackResult { Success = true, OutputDirectory = outputDir, SourceExePath = sourceExe, BackupExePath = backupPath, UnderlyingEngine = underlying, Message = $"EVB 解凍が完了しました(再判定エンジン: {underlying})。", }; } catch (Exception ex) { return new UnpackResult { Success = false, SourceExePath = sourceExe, OutputDirectory = outputDir, Message = $"EVB 解凍中にエラーが発生しました: {ex.Message}", }; } } /// /// Restores a previously unpacked game by removing the extraction output and /// the backup copy is kept intact for the user. Returns true when something /// was restored. /// public static bool Restore(string gameRootDir, IProgress? progress = null) { if (string.IsNullOrWhiteSpace(gameRootDir) || !Directory.Exists(gameRootDir)) { return false; } var restored = false; var outputDir = GetExtractedDir(gameRootDir); try { if (Directory.Exists(outputDir)) { Directory.Delete(outputDir, recursive: true); progress?.Report($"解凍フォルダを削除しました: {ExtractedDirName}"); restored = true; } } catch (Exception ex) { progress?.Report($"解凍フォルダの削除に失敗しました: {ex.Message}"); } // Restore the renamed backup back to its original `.exe` name. try { foreach (var backup in Directory.GetFiles(gameRootDir, "*" + ExeBackupSuffix)) { var original = backup[..^ExeBackupSuffix.Length]; if (!File.Exists(original)) { File.Move(backup, original); progress?.Report($"元の実行ファイルを復元しました: {Path.GetFileName(original)}"); restored = true; } } } catch (Exception ex) { progress?.Report($"元の実行ファイルの復元に失敗しました: {ex.Message}"); } return restored; } /// /// Runs the detection helper against the unpacked folder to determine the real engine. /// private static string ReDetectUnderlyingEngine(string outputDir) { var engine = EngineDetectionHelper.RepairMisdetection( outputDir, EngineDetectionHelper.EngineUnknown); // If the flat output still hides the engine, probe its immediate subfolders // (evbunpack may keep the original layout one level down). if (engine == EngineDetectionHelper.EngineUnknown) { try { foreach (var sub in Directory.GetDirectories(outputDir)) { var candidate = EngineDetectionHelper.RepairMisdetection( sub, EngineDetectionHelper.EngineUnknown); if (candidate != EngineDetectionHelper.EngineUnknown) { return candidate; } } } catch { } } return engine; } /// Runs evbunpack with ArgumentList (no manual quoting) and waits for exit. private static bool RunTool( string toolPath, System.Collections.Generic.IReadOnlyList args, string workingDir, IProgress? progress, out int exitCode) { exitCode = -1; try { var psi = new ProcessStartInfo { FileName = toolPath, WorkingDirectory = workingDir, CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, }; foreach (var arg in args) { psi.ArgumentList.Add(arg); } // Throttle progress reporting: evbunpack emits thousands of lines on large // bundles, and every Report() is marshalled onto the UI thread. Reporting // each line saturates the UI and makes the window appear frozen, so only the // latest line is reported at most a few times per second. var throttle = Stopwatch.StartNew(); var lastReportUtc = DateTime.MinValue; var lastLine = string.Empty; void ReportThrottled(string? data) { if (string.IsNullOrWhiteSpace(data)) { return; } lastLine = data!; var now = DateTime.UtcNow; if (now - lastReportUtc >= TimeSpan.FromMilliseconds(400)) { lastReportUtc = now; progress?.Report(data!); } } using var proc = Process.Start(psi); if (proc == null) { return false; } proc.OutputDataReceived += (_, e) => ReportThrottled(e.Data); proc.ErrorDataReceived += (_, e) => ReportThrottled(e.Data); proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); // evbunpack can take a while on large bundles, but a shorter bound keeps the // operation from looking hung if the tool never terminates. if (!proc.WaitForExit(10 * 60 * 1000)) { try { proc.Kill(entireProcessTree: true); } catch { } progress?.Report("evbunpack がタイムアウトしました(10分)。処理を中断しました。"); exitCode = -1; return false; } // Flush the final line that throttling may have skipped. if (!string.IsNullOrWhiteSpace(lastLine)) { progress?.Report(lastLine); } exitCode = proc.ExitCode; return exitCode == 0; } catch (Exception ex) { progress?.Report($"evbunpack の起動に失敗しました: {ex.Message}"); return false; } } } }