diff --git a/AGENTS.md b/AGENTS.md index bfb31c4..c3deb45 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,8 +32,7 @@ ## 3. 外部ツール・外部ファイルの規則(エンジン単位で参照) - エンジン専用の外部ツール/ファイルは `Engines//Tools/` に配置する。 - - 例: `Engines/Rgss/Tools/SRPG_Unpacker.exe`, `Engines/Wolf/Tools/UberWolfCli.exe`, - `Engines/Nwjs/Tools/speedhack-i686/` + - 例: `Engines/Rgss/Tools/SRPG_Unpacker.exe`, `Engines/Wolf/Tools/UberWolfCli.exe` - パス解決には共通ヘルパーを使用する。 - `AppPathHelper.ResolveEngineTool(string engineName, string toolFileName)` - `AppPathHelper.GetEngineToolsDirectory(string engineName)` diff --git a/Engines/Common/EngineDetectionHelper.cs b/Engines/Common/EngineDetectionHelper.cs index 29a99b5..2f44e31 100644 --- a/Engines/Common/EngineDetectionHelper.cs +++ b/Engines/Common/EngineDetectionHelper.cs @@ -29,6 +29,9 @@ namespace GameLauncher.Engines.Common /// Canonical engine name for generic NW.js packaged games. public const string EngineNwjs = "Nwjs"; + /// Canonical engine name for Enigma Virtual Box packed applications. + public const string EngineEvb = "Evb"; + /// Canonical engine name used when detection fails. public const string EngineUnknown = "Unknown"; @@ -77,6 +80,11 @@ namespace GameLauncher.Engines.Common return EngineNwjs; } + if (Matches(value, "Evb", "Enigma", "EnigmaVB", "EnigmaVirtualBox")) + { + return EngineEvb; + } + return EngineUnknown; } @@ -113,6 +121,14 @@ namespace GameLauncher.Engines.Common /// private static string DetectFromDirectory(string gameDirectory) { + // Enigma Virtual Box (EVB): a packed executable hides the real engine, so it + // must be detected before any other layout-based check. Detection uses the + // PE section signature only (see EvbDetectionHelper.IsEvbPacked). + if (Engines.Evb.EvbDetectionHelper.FindEvbPackedExecutable(gameDirectory) != null) + { + return EngineEvb; + } + // RPG Maker MV/MZ: www/ folder or a Game.exe next to nw.js package files. var wwwDir = Path.Combine(gameDirectory, "www"); if (Directory.Exists(wwwDir)) diff --git a/Engines/Evb/EvbDetectionHelper.cs b/Engines/Evb/EvbDetectionHelper.cs new file mode 100644 index 0000000..8f04c43 --- /dev/null +++ b/Engines/Evb/EvbDetectionHelper.cs @@ -0,0 +1,204 @@ +using System; +using System.IO; +using System.Linq; + +namespace GameLauncher.Engines.Evb +{ + /// + /// Detects Enigma Virtual Box (EVB) packed executables using reliable PE signatures + /// only. Heuristic checks such as file name or extension are intentionally avoided so + /// that ordinary (unpacked) games are never misclassified. + /// + /// Detection strategy: + /// 1. Parse the PE header and inspect the section table for the packer's sections + /// (".enigma1" / ".enigma2"). A present section is a decisive match. + /// 2. When sections are inconclusive, scan bounded windows of the file for the + /// "Enigma Virtual Box" marker string embedded by the packer. + /// + /// This class is engine-local and has no side effects. + /// + public static class EvbDetectionHelper + { + /// Marker string embedded by the Enigma Virtual Box packer. + private const string EnigmaMarker = "Enigma Virtual Box"; + + /// Section names produced by the packer. + private static readonly string[] EnigmaSections = { ".enigma1", ".enigma2" }; + + /// Additional loader identifiers checked during the content scan. + private static readonly string[] EvbContentMarkers = + { + EnigmaMarker, + "evb.dll", + "EnigmaVB", + }; + + /// Returns true when the given executable is packed with EVB. + /// + /// Step 1 reads the PE section table for the packer's section names. + /// Step 2 falls back to a bounded content scan for the packer marker. + /// Any IO/format error yields false (treated as "not confidently EVB"). + /// + public static bool IsEvbPacked(string exePath) + { + if (string.IsNullOrWhiteSpace(exePath) || !File.Exists(exePath)) + { + return false; + } + + try + { + // Step 1: decisive PE section check. + if (HasEnigmaSection(exePath)) + { + return true; + } + } + catch + { + // Fall through to the content scan on any parse failure. + } + + try + { + // Step 2: content marker scan over bounded windows. + return ContainsEvbContentMarker(exePath); + } + catch + { + return false; + } + } + + /// + /// Scans a game directory for an EVB packed executable. + /// Returns the first decisive match, or null when none is found. + /// + public static string? FindEvbPackedExecutable(string gameDirectory) + { + if (string.IsNullOrWhiteSpace(gameDirectory) || !Directory.Exists(gameDirectory)) + { + return null; + } + + try + { + return Directory.GetFiles(gameDirectory, "*.exe", SearchOption.TopDirectoryOnly) + .FirstOrDefault(IsEvbPacked); + } + catch + { + return null; + } + } + + /// + /// Parses the PE section table and checks for the EVB packer's section names. + /// + private static bool HasEnigmaSection(string exePath) + { + using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + using var reader = new BinaryReader(fs); + + if (fs.Length < 0x40) + { + return false; + } + + // DOS header: check the "MZ" signature and locate the PE header offset. + if (reader.ReadUInt16() != 0x5A4D) + { + return false; + } + + fs.Seek(0x3C, SeekOrigin.Begin); + int peOffset = reader.ReadInt32(); + if (peOffset <= 0 || peOffset + 24 > fs.Length) + { + return false; + } + + fs.Seek(peOffset, SeekOrigin.Begin); + if (reader.ReadUInt32() != 0x00004550) // "PE\0\0" + { + return false; + } + + // COFF header: skip machine + number of sections is at offset 2 from here. + fs.Seek(peOffset + 4, SeekOrigin.Begin); + ushort sectionCount = reader.ReadUInt16(); + + // Optional header size (end of the optional header) is at offset 20 in the COFF header. + fs.Seek(peOffset + 20, SeekOrigin.Begin); + ushort optionalHeaderSize = reader.ReadUInt16(); + + // Section table starts right after the optional header. + long sectionTable = peOffset + 24 + optionalHeaderSize; + + // Each section header is 40 bytes; the section name is the first 8 bytes. + for (int i = 0; i < sectionCount; i++) + { + long offset = sectionTable + (long)i * 40; + if (offset + 8 > fs.Length) + { + break; + } + + fs.Seek(offset, SeekOrigin.Begin); + var nameBytes = reader.ReadBytes(8); + var name = System.Text.Encoding.ASCII.GetString(nameBytes).TrimEnd('\0').Trim(); + + foreach (var section in EnigmaSections) + { + if (string.Equals(name, section, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + } + + return false; + } + + /// + /// Scans bounded windows of the executable for EVB loader markers. + /// EVB metadata typically sits near the end of the PE (overlay). + /// + private static bool ContainsEvbContentMarker(string exePath) + { + const int windowSize = 2 * 1024 * 1024; + using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + long size = fs.Length; + if (size < 1024) + { + return false; + } + + double[] fractions = { 0.5, 0.8, 0.9, 0.97 }; + foreach (var frac in fractions) + { + long start = (long)(size * frac); + int readLen = (int)Math.Min(windowSize, size - start); + if (readLen <= 0) + { + continue; + } + + var buf = new byte[readLen]; + fs.Seek(start, SeekOrigin.Begin); + int read = fs.Read(buf, 0, buf.Length); + var text = System.Text.Encoding.ASCII.GetString(buf, 0, read); + + foreach (var marker in EvbContentMarkers) + { + if (text.IndexOf(marker, StringComparison.OrdinalIgnoreCase) >= 0) + { + return true; + } + } + } + + return false; + } + } +} diff --git a/Engines/Evb/EvbDetector.cs b/Engines/Evb/EvbDetector.cs new file mode 100644 index 0000000..992bc85 --- /dev/null +++ b/Engines/Evb/EvbDetector.cs @@ -0,0 +1,62 @@ +using System; +using System.IO; +using GameLauncher.Engines.Common; + +namespace GameLauncher.Engines.Evb +{ + /// + /// Backwards-compatible facade over . + /// + /// The plan names the detection primitive , but + /// several callers (the engine module, the unpack service and the game scanner) + /// were written against the shorter EvbDetector API. This facade keeps those + /// call sites stable while the authoritative PE-signature logic lives in + /// . + /// + /// This class is engine-local and has no side effects. + /// + public static class EvbDetector + { + /// + /// Returns true when the game directory holds an EVB packed executable. + /// A packed project file (*.evb) in the folder is also accepted as a + /// decisive signal, in addition to the PE-signature check. + /// + public static bool IsEvbGame(string gameDirectory) + { + if (string.IsNullOrWhiteSpace(gameDirectory) || !Directory.Exists(gameDirectory)) + { + return false; + } + + try + { + // A packed project file in the folder is the strongest single signal. + if (Directory.GetFiles(gameDirectory, "*.evb", SearchOption.TopDirectoryOnly).Length > 0) + { + return true; + } + } + catch + { + // Fall through to the executable signature check. + } + + return EvbDetectionHelper.FindEvbPackedExecutable(gameDirectory) != null; + } + + /// + /// Resolves the executable that should be passed to the unpacker: the first + /// .exe in the folder that carries a decisive EVB signature, or null. + /// + public static string? FindPackedExecutable(string gameDirectory) + => EvbDetectionHelper.FindEvbPackedExecutable(gameDirectory); + + /// Returns true when the given executable is packed with EVB. + public static bool ContainsEvbSignature(string exePath) + => EvbDetectionHelper.IsEvbPacked(exePath); + + /// Re-exposes the engine name constant for callers that only reference this helper. + public static string EngineName => EngineDetectionHelper.EngineEvb; + } +} diff --git a/Engines/Evb/EvbEngineModule.cs b/Engines/Evb/EvbEngineModule.cs new file mode 100644 index 0000000..b2eba71 --- /dev/null +++ b/Engines/Evb/EvbEngineModule.cs @@ -0,0 +1,51 @@ +using System; +using GameLauncher.Engines.Common; +using GameLauncher.Models; + +namespace GameLauncher.Engines.Evb +{ + /// + /// Engine module for Enigma Virtual Box (EVB) packed applications. + /// + /// EVB is a generic packer: it can wrap a game built on any engine (RGSS, NW.js, + /// Wolf, Unity, ...). This module therefore acts as a *pre-stage* — it detects an + /// EVB-packed executable, unpacks it via the bundled evbunpack tool, and then lets + /// the caller re-detect the underlying engine from the unpacked content. + /// + /// Per-game hacks never live here; they belong under + /// `Engines/Evb/Games/<GameName>/` and must not affect other games. + /// + public sealed class EvbEngineModule : IEngineModule + { + /// + public string EngineName => EngineDetectionHelper.EngineEvb; + + /// + public bool Detect(string gameDirectory) => EvbDetector.IsEvbGame(gameDirectory); + + /// + /// EVB is a packaging layer, not a game engine, so it has no script mod of its own. + /// Mods are applied by the underlying engine after unpacking. + /// + public bool ApplyMod(string gameDirectory, ModPluginDefinition plugin) => false; + + /// EVB has no standalone mod state; nothing is ever "applied". + public bool IsModApplied(string gameDirectory) => false; + + /// + public string ResolveToolPath(string toolFileName) + => AppPathHelperBridge.Resolve(EngineName, toolFileName); + } + + /// + /// Thin indirection so that can resolve engine tools + /// without taking a hard dependency on the concrete helper type in this file. + /// + internal static class AppPathHelperBridge + { + public static string Resolve(string engineName, string toolFileName) + => Helpers.AppPathHelper.ResolveEngineTool(engineName, toolFileName) + ?? throw new InvalidOperationException( + $"External tool '{toolFileName}' for engine '{engineName}' was not found."); + } +} diff --git a/Engines/Evb/EvbUnpackService.cs b/Engines/Evb/EvbUnpackService.cs new file mode 100644 index 0000000..0b4ec97 --- /dev/null +++ b/Engines/Evb/EvbUnpackService.cs @@ -0,0 +1,438 @@ +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.Substring(0, backup.Length - 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; + } + } + } +} diff --git a/Engines/Evb/EvbUnpackerToolProvider.cs b/Engines/Evb/EvbUnpackerToolProvider.cs new file mode 100644 index 0000000..f1ef313 --- /dev/null +++ b/Engines/Evb/EvbUnpackerToolProvider.cs @@ -0,0 +1,122 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using GameLauncher.Helpers; + +namespace GameLauncher.Engines.Evb +{ + /// + /// Resolves the bundled evbunpack executable used to unpack Enigma Virtual Box (EVB) + /// packed applications. + /// + /// Design notes (durable / reusable): + /// - The tool is bundled under `Engines\Evb\Tools\evbunpack\` (per-engine tools folder). + /// - Path resolution goes through so that deployed, production + /// and source-tree layouts are all supported without hard-coding this machine's paths. + /// - CLI argument construction is kept in one place so callers never duplicate the + /// evbunpack invocation contract. + /// + /// The evbunpack CLI contract: + /// evbunpack [-pe {10_70,9_70,7_80}] [--legacy-fs] <input exe> <output folder> + /// It restores both the packed virtual file system and the original PE executable. + /// + public static class EvbUnpackerToolProvider + { + /// Engine identifier passed to . + public const string EngineName = "Evb"; + + /// Bundled unpacker executable name. + public const string DefaultToolExeName = "evbunpack.exe"; + + /// Relative subfolder under Engines/Evb/Tools that holds the tool. + public const string ToolSubDirectory = "evbunpack"; + + /// + /// Default PE rebuild variant used when the caller does not specify one. + /// 9_70 works for Enigma Virtual Box 9.70 and 10.70/11.00 in most cases; + /// callers may override via . + /// + public const string DefaultPeVariant = "9_70"; + + /// Gets the engine tools directory (Engines/Evb/Tools). + public static string GetToolsDirectory() + { + return AppPathHelper.GetEngineToolsDirectory(EngineName); + } + + /// Gets the bundled tool subfolder (Engines/Evb/Tools/evbunpack). + public static string GetToolDirectory() + { + return Path.Combine(GetToolsDirectory(), ToolSubDirectory); + } + + /// + /// Resolves the evbunpack.exe path, or null when the tool is missing. + /// Prefers the bundled subfolder, then falls back to a flat layout inside the + /// engine tools folder (and the shared probe). + /// + public static string? GetToolPath() + { + try + { + var candidates = new[] + { + Path.Combine(GetToolDirectory(), DefaultToolExeName), + Path.Combine(GetToolsDirectory(), DefaultToolExeName), + }; + + var found = candidates.FirstOrDefault(File.Exists); + if (found != null) + { + return found; + } + + // Fall back to the shared per-engine resolver (checks deployed + dev layouts). + return AppPathHelper.ResolveEngineTool( + EngineName, + Path.Combine(ToolSubDirectory, DefaultToolExeName)); + } + catch + { + return null; + } + } + + /// True when the unpacker executable exists and is usable. + public static bool IsAvailable() => GetToolPath() != null; + + /// + /// Builds the argument list for the unpacker CLI. + /// Emits the PE variant first, then the optional legacy switch, then the + /// input executable and the output folder. Values are raw (no quoting); callers + /// pass them through ProcessStartInfo.ArgumentList which handles escaping. + /// + /// Path to the EVB-packed executable. + /// Folder that receives the unpacked files. + /// When true, adds --legacy-fs for packer version 7.80. + /// PE rebuild variant (10_70/9_70/7_80); defaults to . + public static IReadOnlyList BuildArguments( + string inputExePath, + string outputDirectory, + bool legacyFileSystem = false, + string? peVariant = null) + { + var args = new List(); + + if (legacyFileSystem) + { + args.Add("--legacy-fs"); + } + + var variant = string.IsNullOrWhiteSpace(peVariant) ? DefaultPeVariant : peVariant.Trim(); + args.Add("-pe"); + args.Add(variant); + + args.Add(inputExePath); + args.Add(outputDirectory); + + return args; + } + } +} diff --git a/Engines/Evb/Tools/evbunpack/LICENSE b/Engines/Evb/Tools/evbunpack/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/Engines/Evb/Tools/evbunpack/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/Engines/Evb/Tools/evbunpack/README.md b/Engines/Evb/Tools/evbunpack/README.md new file mode 100644 index 0000000..6623f8b --- /dev/null +++ b/Engines/Evb/Tools/evbunpack/README.md @@ -0,0 +1,62 @@ +# evbunpack (bundled tool) + +`evbunpack.exe` is a bundled, third-party unpacker used by the **Evb** engine module to +unpack applications protected with **Enigma Virtual Box**. + +## Provenance + +- Upstream project: https://github.com/mos9527/evbunpack +- Description: Enigma Virtual Box Unpacker / 解包・脱壳工具 +- License: Apache-2.0 (see `LICENSE` in this folder for the full text) +- Repository status: **archived (read-only) by the owner on 2026-02-06** +- Version / release: bundled from the upstream Windows builds + (see the "For Windows Users: Builds are available here" link in the upstream README, + which points to the project's GitHub Releases page). + +> **NOTE**: The binary in this folder is not committed as part of the normal source +> tree review flow. Place the upstream-release `evbunpack.exe` here before publishing. +> If the file is absent, the `Evb` engine module reports the tool as unavailable and +> skips unpacking instead of throwing (callers degrade gracefully). + +## CLI usage + +``` +evbunpack [-h] [--log-level {DEBUG,INFO,WARNING,ERROR,CRITICAL}] [-l] + [--ignore-fs] [--ignore-pe] [--legacy-fs] + [-pe {10_70,9_70,7_80}] [--out-pe OUT_PE] + file output +``` + +- `file` : the packed `.exe` (input) +- `output` : the folder that receives the unpacked files (created if missing) + +The tool restores **both** the virtual file system contents **and** the original PE +executable, in a single invocation. + +### PE variant selection + +| Packer version | Unpack with flags | +|----------------|------------------------------| +| 11.00 | `-pe 10_70` | +| 10.70 | `-pe 10_70` | +| 9.70 | `-pe 9_70` | +| 7.80 | `-pe 7_80 --legacy-fs` | + +`EvbUnpackerToolProvider.BuildArguments` defaults to `-pe 9_70` and can be overridden +per call. + +## Alternatives (when re-bundling is not possible) + +- Install via PyPI: `pip install evbunpack` and run `python -m evbunpack ...` + (requires a Python runtime on the target machine). +- Build from source with `setup.py` / `pyinstaller` following the upstream README. + +## Where it is used + +- `Engines/Evb/EvbUnpackerToolProvider.cs` — resolves the executable and builds CLI arguments. +- `Engines/Evb/EvbUnpackService.cs` — orchestrates detection, unpacking and re-detection. + +Resolution order (see `EvbUnpackerToolProvider.GetToolPath`): +1. `Engines/Evb/Tools/evbunpack/evbunpack.exe` (bundled layout, this folder) +2. `Engines/Evb/Tools/evbunpack.exe` (flat layout) +3. `AppPathHelper.ResolveEngineTool("Evb", "evbunpack/evbunpack.exe")` fallback probe. diff --git a/Engines/Evb/Tools/evbunpack/evbunpack.exe b/Engines/Evb/Tools/evbunpack/evbunpack.exe new file mode 100644 index 0000000..7ab76e3 Binary files /dev/null and b/Engines/Evb/Tools/evbunpack/evbunpack.exe differ diff --git a/Engines/Nwjs/NwjsPackageUnpacker.cs b/Engines/Nwjs/NwjsPackageUnpacker.cs deleted file mode 100644 index 3854c41..0000000 --- a/Engines/Nwjs/NwjsPackageUnpacker.cs +++ /dev/null @@ -1,378 +0,0 @@ -using System; -using System.IO; -using System.IO.Compression; -using System.Linq; -using System.Security.Cryptography; - -namespace GameLauncher.Engines.Nwjs -{ - /// - /// nw.js 系(boxed / FOSSIL 等の単体exe梱包)ツクールゲームから、 - /// 埋め込まれた package.nw 相当のコンテナを抽出する汎用アンパッカー。 - /// - /// 方針(恒久・再利用可能): - /// - 特定ゲーム専用ではなく、共通の署名探索アルゴリズムで「埋め込みZIPコンテナ」を探す。 - /// - exe 全体を一括読みしない。ブロック単位の逐次走査で PK ローカルヘッダ→EOCD を確定する。 - /// - 抽出先はゲームフォルダ内 `_extracted` のみ(他ゲームへ一切影響しない)。 - /// - 冪等: 既に展開済み(plugins.js が解決できる)なら再展開しない。 - /// - /// 抽出戦略は として差し替え可能にしてあり、 - /// 将来新しい梱包形式が出た場合は戦略を追加するだけで拡張できる。 - /// - public static class NwjsPackageUnpacker - { - /// ゲームフォルダ内の展開先フォルダ名(Asar/SRPG の慣習に合わせる) - public const string ExtractedDirName = "_extracted"; - - /// 走査ブロックサイズ(1ブロックあたりの読み込み量) - private const int ScanBlockSize = 4 * 1024 * 1024; - - /// 単一のPKローカルヘッダから読み込める最大ウィンドウ(EOCD 探索用) - private const int MaxSingleZipScan = 256 * 1024 * 1024; - - /// ゲームフォルダ内の展開先ディレクトリ(物理パス) - public static string GetExtractedDir(string gameRootDir) - => Path.Combine(gameRootDir, ExtractedDirName); - - /// - /// 展開先 `_extracted` に js/plugins.js(または www/js/plugins.js)が存在するか判定します。 - /// - public static bool IsExtractionComplete(string extractedDir, out string? pluginsJsPath, out string? relativePlugins) - { - pluginsJsPath = null; - relativePlugins = null; - try - { - var candidates = new[] - { - new { Abs = Path.Combine(extractedDir, "js", "plugins.js"), Rel = "js/plugins.js" }, - new { Abs = Path.Combine(extractedDir, "js", "plugins", "plugins.js"), Rel = "js/plugins/plugins.js" }, - new { Abs = Path.Combine(extractedDir, "www", "js", "plugins.js"), Rel = "www/js/plugins.js" }, - }; - foreach (var c in candidates) - { - if (File.Exists(c.Abs)) - { - pluginsJsPath = c.Abs; - relativePlugins = c.Rel; - return true; - } - } - } - catch { } - - return false; - } - - /// - /// 指定パス直下から js/plugins.js を解決します(_extracted 配下優先)。 - /// - public static string? ResolvePluginsJs(string rootDir) - { - try - { - var candidates = new[] - { - Path.Combine(rootDir, "js", "plugins.js"), - Path.Combine(rootDir, "js", "plugins", "plugins.js"), - Path.Combine(rootDir, "www", "js", "plugins.js"), - Path.Combine(rootDir, "package.nw", "js", "plugins.js"), - }; - return candidates.FirstOrDefault(File.Exists); - } - catch - { - return null; - } - } - - /// - /// 判定に必要な署名情報。汎用の埋め込みZIPコンテナ有無を表します。 - /// - public sealed class EmbeddedZipProbeResult - { - /// PK ローカルヘッダ(PK\x03\x04)の先頭オフセット(見つかった場合) - public long? LocalHeaderOffset { get; init; } - - /// EOCD(PK\x05\x06)の末尾オフセット(見つかった場合) - public long? EocdOffset { get; init; } - - /// コンテナ内に package.json 文字列が見つかったか - public bool HasPackageJson { get; init; } - - /// 標準ZIPとして展開可能そうか - public bool IsZipExtractable => LocalHeaderOffset.HasValue && EocdOffset.HasValue; - } - - /// - /// 埋め込みコンテナ(package.nw = 標準ZIP)を逐次走査で探索します。全走査でも - /// exe を一括メモリへ載せないため、1.14GB級でも安全です。 - /// - /// 対象の単体exeパス - /// 進捗通知(任意) - /// 先頭から走査する最大バイト数(既定は末尾まで) - public static EmbeddedZipProbeResult ProbeEmbeddedZip(string exePath, IProgress? progress = null, long maxScanBytes = long.MaxValue) - { - if (!File.Exists(exePath)) - { - return new EmbeddedZipProbeResult(); - } - - long? localHeader = null; - bool hasPackageJson = false; - - using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - long fileSize = fs.Length; - long scanLimit = Math.Min(fileSize, maxScanBytes); - - var buf = new byte[ScanBlockSize]; - long pos = 0; - // ブロック境界をまたぐPK検出のため、直前3バイトを保持する - int carry = 0; - byte b1 = 0, b2 = 0, b3 = 0; - - progress?.Report($"埋め込みZIPコンテナを走査中... ({fileSize:N0} bytes)"); - - while (pos < scanLimit) - { - int toRead = (int)Math.Min(buf.Length, scanLimit - pos); - fs.Seek(pos, SeekOrigin.Begin); - int read = fs.Read(buf, 0, toRead); - if (read <= 0) - { - break; - } - - for (int i = 0; i < read; i++) - { - byte cur = buf[i]; - if (carry == 3 && b1 == 0x50 && b2 == 0x4B && b3 == 0x03 && cur == 0x04 && localHeader == null) - { - // ローカルヘッダ先頭位置 = (今回ブロック開始 - 3) + (i - 3) - long abs = pos + i - 3; - if (abs >= 0) - { - localHeader = abs; - progress?.Report($"埋め込みZIPローカルヘッダを検出: offset={abs:N0}"); - } - } - - if (b1 == 0x50 && b2 == 0x4B && b3 == 0x03 && cur == 0x04) - { - b1 = b2; b2 = b3; b3 = cur; - } - else - { - b1 = b2; b2 = b3; b3 = cur; - } - if (carry < 3) - { - carry++; - } - } - - // ブロック内で package.json 文字列を軽く探索(タイトル推定用・厳密性は不要) - if (!hasPackageJson) - { - var ascii = System.Text.Encoding.ASCII.GetString(buf, 0, read); - if (ascii.IndexOf("package.json", StringComparison.Ordinal) >= 0) - { - hasPackageJson = true; - } - } - - pos += read; - progress?.Report($"走査中... {pos:N0} / {fileSize:N0} bytes"); - } - - // EOCD(PK\x05\x06)は末尾近傍にある。末尾 64KB を走査。 - long? eocd = null; - if (localHeader.HasValue) - { - int tailLen = (int)Math.Min(64 * 1024, fileSize); - var tail = new byte[tailLen]; - fs.Seek(fileSize - tailLen, SeekOrigin.Begin); - int tr = fs.Read(tail, 0, tailLen); - for (int i = tr - 4; i >= 0; i--) - { - if (tail[i] == 0x50 && tail[i + 1] == 0x4B && tail[i + 2] == 0x05 && tail[i + 3] == 0x06) - { - eocd = (fileSize - tailLen) + i; - break; - } - } - // 末尾64KBに無ければローカルヘッダ以降の限定ウィンドウも確認(巨大な付加データ対策) - if (eocd == null) - { - eocd = FindEocdNearOffset(fs, localHeader.Value, fileSize); - } - } - - return new EmbeddedZipProbeResult - { - LocalHeaderOffset = localHeader, - EocdOffset = eocd, - HasPackageJson = hasPackageJson - }; - } - - /// - /// ローカルヘッダ以降を(最大まで)限定走査し、EOCD 位置を探します。 - /// - private static long? FindEocdNearOffset(FileStream fs, long start, long fileSize) - { - long limit = Math.Min(fileSize, start + MaxSingleZipScan); - // 末尾から逆方向に少しずつ探す方が現実的だが、境界が読めない場合は後方優先で探す - long window = 4 * 1024 * 1024; - for (long end = limit; end > start; end -= window) - { - long begin = Math.Max(start, end - window); - int len = (int)(end - begin); - if (len <= 4) - { - continue; - } - var buf = new byte[len]; - fs.Seek(begin, SeekOrigin.Begin); - int read = fs.Read(buf, 0, len); - for (int i = read - 4; i >= 0; i--) - { - if (buf[i] == 0x50 && buf[i + 1] == 0x4B && buf[i + 2] == 0x05 && buf[i + 3] == 0x06) - { - return begin + i; - } - } - } - return null; - } - - /// - /// exe 内に埋め込まれた ZIP(package.nw)を、指定の展開先へ冪等に全展開します。 - /// 標準ZIPとして解釈できる場合のみ成功します。 - /// - /// 展開後の js/plugins.js の相対パス(/区切り)。解決できなければ null。 - public static string? ExtractEmbeddedZip(string exePath, string destDir, IProgress? progress = null) - { - try - { - var probe = ProbeEmbeddedZip(exePath, progress); - if (!probe.IsZipExtractable) - { - progress?.Report("埋め込みZIPコンテナを確定できませんでした(非標準コンテナの可能性)。"); - return null; - } - - Directory.CreateDirectory(destDir); - - using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - long zipLength = probe.EocdOffset!.Value + 22 - probe.LocalHeaderOffset!.Value; - fs.Seek(probe.LocalHeaderOffset!.Value, SeekOrigin.Begin); - - // EOCD を含む範囲だけを ZipArchive へ渡す(exe 末尾の付加データを切り離す) - using var slice = new SubStream(fs, probe.LocalHeaderOffset!.Value, zipLength); - using var zip = new ZipArchive(slice, ZipArchiveMode.Read); - - foreach (var entry in zip.Entries) - { - var entryRel = entry.FullName.Replace('/', Path.DirectorySeparatorChar); - var dest = Path.Combine(destDir, entryRel); - - // ディレクトリエントリ - if (string.IsNullOrEmpty(entry.Name)) - { - Directory.CreateDirectory(dest); - continue; - } - - var parent = Path.GetDirectoryName(dest); - if (!string.IsNullOrEmpty(parent)) - { - Directory.CreateDirectory(parent); - } - - using (var src = entry.Open()) - using (var outFs = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None)) - { - src.CopyTo(outFs); - } - } - - progress?.Report("埋め込みZIPコンテナの展開が完了しました。"); - return IsExtractionComplete(destDir, out _, out var rel) ? rel : null; - } - catch (Exception ex) - { - progress?.Report($"埋め込みZIP展開中にエラーが発生しました: {ex.Message}"); - return null; - } - } - - /// - /// 指定範囲のみを読み出す読み取り専用ストリーム(ZIP末尾の付加データ分離用)。 - /// - private sealed class SubStream : Stream - { - private readonly Stream _base; - private readonly long _start; - private readonly long _length; - private long _pos; - - public SubStream(Stream baseStream, long start, long length) - { - _base = baseStream; - _start = start; - _length = length; - } - - public override bool CanRead => true; - public override bool CanSeek => true; - public override bool CanWrite => false; - public override long Length => _length; - public override long Position - { - get => _pos; - set => _pos = value; - } - - public override int Read(byte[] buffer, int offset, int count) - { - long remaining = _length - _pos; - if (remaining <= 0) - { - return 0; - } - int toRead = (int)Math.Min(count, remaining); - _base.Seek(_start + _pos, SeekOrigin.Begin); - int read = _base.Read(buffer, offset, toRead); - _pos += read; - return read; - } - - public override long Seek(long offset, SeekOrigin origin) - { - _pos = origin switch - { - SeekOrigin.Begin => offset, - SeekOrigin.Current => _pos + offset, - SeekOrigin.End => _length + offset, - _ => _pos - }; - return _pos; - } - - public override void Flush() { } - public override void SetLength(long value) => throw new NotSupportedException(); - public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); - } - - /// - /// 抽出戦略の抽象。標準ZIP以外の独自コンテナが出た場合に差し替え可能にするための骨組み。 - /// - public interface INwjsUnpackStrategy - { - string Name { get; } - bool CanHandle(string exePath); - string? Extract(string exePath, string destDir, IProgress? progress); - } - } -} diff --git a/Engines/Nwjs/NwjsUnpackerToolProvider.cs b/Engines/Nwjs/NwjsUnpackerToolProvider.cs deleted file mode 100644 index c64f25c..0000000 --- a/Engines/Nwjs/NwjsUnpackerToolProvider.cs +++ /dev/null @@ -1,341 +0,0 @@ -using System; -using System.Diagnostics; -using System.IO; -using System.IO.Compression; -using System.Linq; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using GameLauncher.Helpers; - -namespace GameLauncher.Engines.Nwjs -{ - /// - /// nw.js 埋め込み package.nw を抽出する外部アンパッカーツールの供給・呼び出しを担う汎用プロバイダ。 - /// - /// 設計方針(恒久・再利用可能): - /// - ツールは `Engines\Nwjs\Tools\` 配下に配置する(エンジン別のツールフォルダ)。 - /// - 未配置の場合は初回利用時に自動ダウンロードして同フォルダへ展開する(ユーザー確認なし)。 - /// - ネット未接続等で入手できない場合は、例外を投げず null を返して「起動のみ」にフォールバックさせる。 - /// - 特定ゲーム専用の決め打ちは禁止。呼び出し規約(引数・出力ディレクトリ)は汎用に扱う。 - /// - /// 外部ツールは「7-Zip 互換のコマンドライン(-o/-y で展開)」を持つものを第一候補とし、 - /// 追加の抽出戦略が増えた場合も同じ呼び出しインターフェースで扱えるようにしてある。 - /// - public static class NwjsUnpackerToolProvider - { - /// Engine identifier used to resolve the per-engine tools folder. - public const string EngineName = "Nwjs"; - - /// Fallback tools folder name (legacy layout). - public const string ToolsDirName = "Tools"; - - /// 外部アンパッカーの実行ファイル名(Tools 配下へ配置する想定) - public const string DefaultToolExeName = "7z.exe"; - - /// - /// 外部ツールの入手元 URL(7-Zip 公式・Windows x64 版)。ダウンロード後に展開して - /// 7z.exe / 7z.dll のみを Tools 配下へ配置します。 - /// - private static readonly string[] ToolArchiveUrls = - { - "https://www.7-zip.org/a/7zr.exe", // 単体実行版(依存 DLL 不要) - "https://www.7-zip.org/a/7z2408-extra.7z", // 予備(extra パッケージ) - }; - - /// - /// Returns the engine-specific tools directory (Engines\Nwjs\Tools). - /// Each engine references only its own tools folder, so the NW.js - /// unpacker never depends on another engine's files. - /// - public static string GetToolsDirectory() - { - return AppPathHelper.GetEngineToolsDirectory(EngineName); - } - - /// 配置済みの外部アンパッカー exe のフルパスを取得します(無ければ null)。 - public static string? GetToolPath() - { - try - { - var tools = GetToolsDirectory(); - // 優先順: 7zr(単体)→ 7z → 汎用名 - var candidates = new[] - { - Path.Combine(tools, "7zr.exe"), - Path.Combine(tools, DefaultToolExeName), - Path.Combine(tools, "nwjs-unpack.exe"), - }; - return candidates.FirstOrDefault(File.Exists); - } - catch - { - return null; - } - } - - /// - /// 外部アンパッカーの可用性を判定します。 - /// - public static bool IsToolAvailable() => GetToolPath() != null; - - /// - /// 外部アンパッカーが未配置の場合、初回利用時に自動ダウンロードして Tools 配下へ配置します。 - /// 失敗(ネット未接続等)時は例外を投げず false を返します。 - /// - public static async Task EnsureToolAvailableAsync(IProgress? progress = null, CancellationToken ct = default) - { - if (IsToolAvailable()) - { - return true; - } - - try - { - var tools = GetToolsDirectory(); - Directory.CreateDirectory(tools); - - foreach (var url in ToolArchiveUrls) - { - try - { - progress?.Report($"外部アンパッカーを取得中: {url}"); - var fileName = Path.GetFileName(new Uri(url).LocalPath); - var dest = Path.Combine(tools, fileName); - - if (!await DownloadFileAsync(url, dest, progress, ct).ConfigureAwait(false)) - { - continue; - } - - // 単体実行版(7zr.exe)はそのまま配置 - if (fileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) - { - progress?.Report($"外部アンパッカーを配置しました: {dest}"); - return IsToolAvailable(); - } - - // .7z アーカイブの場合は 7zr で本体を抽出(可能な範囲で) - // 7zr.exe が既に同梱されていればそれを使い、無ければ諦めて次URLへ。 - progress?.Report("アーカイブを展開して本体を配置します..."); - if (TryExpandArchive(dest, tools, progress)) - { - return IsToolAvailable(); - } - } - catch (Exception ex) - { - progress?.Report($"取得元の処理に失敗しました(次候補を試行): {ex.Message}"); - } - } - } - catch (Exception ex) - { - progress?.Report($"外部アンパッカーの取得に失敗しました: {ex.Message}"); - } - - return IsToolAvailable(); - } - - private static async Task DownloadFileAsync(string url, string dest, IProgress? progress, CancellationToken ct) - { - try - { - using var http = new HttpClient { Timeout = TimeSpan.FromMinutes(5) }; - using var resp = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); - if (!resp.IsSuccessStatusCode) - { - progress?.Report($"ダウンロード失敗 (HTTP {(int)resp.StatusCode}): {url}"); - return false; - } - - var total = resp.Content.Headers.ContentLength ?? -1; - await using var src = await resp.Content.ReadAsStreamAsync(ct).ConfigureAwait(false); - await using var outFs = new FileStream(dest, FileMode.Create, FileAccess.Write, FileShare.None); - - var buf = new byte[81920]; - long written = 0; - int read; - while ((read = await src.ReadAsync(buf, ct).ConfigureAwait(false)) > 0) - { - await outFs.WriteAsync(buf.AsMemory(0, read), ct).ConfigureAwait(false); - written += read; - if (total > 0) - { - progress?.Report($"ダウンロード中... {written * 100 / total}%"); - } - } - - return File.Exists(dest) && new FileInfo(dest).Length > 0; - } - catch (Exception ex) - { - progress?.Report($"ダウンロードに失敗しました: {ex.Message}"); - return false; - } - } - - /// - /// ダウンロードした .7z / .zip アーカイブから 7z.exe / 7zr.exe を Tools へ配置します。 - /// ZIP は .NET 標準で、.7z は既存 7zr.exe がある場合のみ実行します。 - /// - private static bool TryExpandArchive(string archivePath, string toolsDir, IProgress? progress) - { - try - { - if (archivePath.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) - { - using var zip = ZipFile.OpenRead(archivePath); - foreach (var entry in zip.Entries) - { - var name = Path.GetFileName(entry.FullName); - if (name.Equals("7zr.exe", StringComparison.OrdinalIgnoreCase) || - name.Equals("7z.exe", StringComparison.OrdinalIgnoreCase) || - name.Equals("7z.dll", StringComparison.OrdinalIgnoreCase)) - { - var dest = Path.Combine(toolsDir, name); - entry.ExtractToFile(dest, overwrite: true); - } - } - return IsToolAvailable(); - } - - // .7z は既存の 7zr.exe がある場合のみ展開を試みる - var existing = Path.Combine(toolsDir, "7zr.exe"); - if (!File.Exists(existing)) - { - return false; - } - - var psi = new ProcessStartInfo - { - FileName = existing, - Arguments = $"x \"{archivePath}\" -o\"{toolsDir}\" -y", - WorkingDirectory = toolsDir, - CreateNoWindow = true, - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true - }; - using var proc = Process.Start(psi); - if (proc == null) - { - return false; - } - proc.StandardOutput.ReadToEnd(); - proc.StandardError.ReadToEnd(); - proc.WaitForExit(); - return IsToolAvailable(); - } - catch (Exception ex) - { - progress?.Report($"アーカイブ展開に失敗しました: {ex.Message}"); - return false; - } - } - - /// - /// 外部アンパッカーで exe 内の埋め込みコンテナ(package.nw 等)を destDir へ全展開します。 - /// 呼び出し規約は「7-Zip 互換: <tool> x <archive> -o<out> -y」を第一候補、 - /// 対応しない場合は 2 番目の規約(<tool> <archive> -o <out>)へフォールバックします。 - /// - /// 成功時 true(destDir に何らかのファイルが展開された場合)。 - public static bool ExtractWithExternalTool(string toolPath, string sourceExePath, string destDir, IProgress? progress = null, int timeoutMs = 30 * 60 * 1000) - { - try - { - Directory.CreateDirectory(destDir); - - // 規約1: 7-Zip 互換 - if (RunTool(toolPath, $"x \"{sourceExePath}\" -o\"{destDir}\" -y", destDir, progress, timeoutMs, out var code1)) - { - if (HasAnyExtractedFile(destDir)) - { - return true; - } - } - - progress?.Report($"外部ツール規約1の出力が空でした (code={code1})。規約2を試行します。"); - - // 規約2: -o - if (RunTool(toolPath, $"\"{sourceExePath}\" -o \"{destDir}\"", destDir, progress, timeoutMs, out var code2)) - { - if (HasAnyExtractedFile(destDir)) - { - return true; - } - } - - progress?.Report($"外部ツールでの展開に失敗しました (code1={code1}, code2={code2})。"); - return false; - } - catch (Exception ex) - { - progress?.Report($"外部ツール実行中にエラーが発生しました: {ex.Message}"); - return false; - } - } - - private static bool RunTool(string toolPath, string args, string workDir, IProgress? progress, int timeoutMs, out int exitCode) - { - exitCode = -1; - try - { - var psi = new ProcessStartInfo - { - FileName = toolPath, - Arguments = args, - WorkingDirectory = workDir, - CreateNoWindow = true, - UseShellExecute = false, - RedirectStandardOutput = true, - RedirectStandardError = true - }; - - using var proc = Process.Start(psi); - if (proc == null) - { - return false; - } - - // 出力を読み切ってから待機(デッドロック回避) - var stdout = proc.StandardOutput.ReadToEnd(); - var stderr = proc.StandardError.ReadToEnd(); - if (!proc.WaitForExit(timeoutMs)) - { - try { proc.Kill(entireProcessTree: true); } catch { } - progress?.Report("外部ツールがタイムアウトしました。"); - return false; - } - - exitCode = proc.ExitCode; - if (!string.IsNullOrWhiteSpace(stdout)) - { - progress?.Report(stdout.Trim()); - } - if (!string.IsNullOrWhiteSpace(stderr)) - { - progress?.Report($"[stderr] {stderr.Trim()}"); - } - return exitCode == 0; - } - catch (Exception ex) - { - progress?.Report($"外部ツール起動に失敗しました: {ex.Message}"); - return false; - } - } - - private static bool HasAnyExtractedFile(string dir) - { - try - { - return Directory.Exists(dir) && Directory.EnumerateFileSystemEntries(dir).Any(); - } - catch - { - return false; - } - } - } -} diff --git a/Engines/Nwjs/Tools/README-nwjs-unpacker.md b/Engines/Nwjs/Tools/README-nwjs-unpacker.md deleted file mode 100644 index 4a4d839..0000000 --- a/Engines/Nwjs/Tools/README-nwjs-unpacker.md +++ /dev/null @@ -1,33 +0,0 @@ -# nw.js boxed 解凍用 外部アンパッカー - -このフォルダには、GameLauncher が **nw.js boxed 系ツクールゲーム**(例: `Game_boxed.exe` のように -ゲーム本体を exe へ内包した形態)の埋め込みコンテナ(`package.nw` = 標準ZIP)を展開するために -利用する外部アンパッカーを配置します。 - -## 対象 -- `*boxed*.exe`(nw.js 埋め込み。`package.nw` / `package.json` を含む) -- その他、単体exeへ `package.nw` 相当の埋め込みZIPを持つツクール MZ/MV ゲーム - -## 使用するツール -- `7zr.exe`(7-Zip 公式の単体実行版・依存DLL不要)を第一候補とします。 -- 代替として `7z.exe`(+ `7z.dll`)も検出対象です。 - -## 配置方法 -- **同梱されている場合**: この `Tools\` フォルダに `7zr.exe` を置いてください。 - `publish.ps1` 実行時に `Z:\自作ソフト\GameLauncher\Tools\` へコピーされます。 -- **未配置の場合**: GameLauncher 実行時、boxed 解凍が必要になった時点で - 7-Zip 公式(https://www.7-zip.org/a/7zr.exe)から自動ダウンロードし、配置を試みます - (ネット未接続などで取得に失敗した場合は「起動のみ」にフォールバックし、ゲーム自体は起動できます)。 - -## 実装上の参照 -- 取得・呼び出し: `Services\NwjsUnpackerToolProvider.cs` -- 埋め込みZIP検出・展開: `Services\NwjsPackageUnpacker.cs` -- オーケストレーター(戦略: 組み込みZIP → 外部ツール): `Services\TkoolPackagedExtractionService.cs` - -## 呼び出し規約 -- 第一候補: `7zr.exe x "" -o"" -y` -- フォールバック: `7zr.exe "" -o ""` - -## ライセンス -7-Zip は GNU LGPL + unRAR restriction の下で配布されています。 -再頒布する場合は 7-Zip のライセンス条項(https://www.7-zip.org/license.txt)に従ってください。 diff --git a/Engines/Tkool/TkoolGameItem.cs b/Engines/Tkool/TkoolGameItem.cs index f082c82..a000330 100644 --- a/Engines/Tkool/TkoolGameItem.cs +++ b/Engines/Tkool/TkoolGameItem.cs @@ -116,13 +116,112 @@ namespace GameLauncher.Engines.Tkool // ================= 単体exe梱包(FOSSIL / boxed)関連プロパティ ================= // js/plugins.js がディスク上に無く、exeへ埋め込まれている形態を識別します。 + // 注: boxed の埋め込みコンテナ展開(旧 _extracted 展開)は廃止しました。 + // 単体exeは「起動のみ対応」として扱い、展開・注入は行いません。 private bool _isFossilSingleExe; private bool _isBoxedExe; - private bool _isStandaloneExeExtracted; - private string? _standaloneExtractedDirPath; - private string? _standaloneBackupPath; - private string? _boxedPayloadEntryPath; - private bool _canExtractViaExternalTool; + + // ================= Enigma Virtual Box (EVB) 梱包関連プロパティ ================= + // EVB でパックされた exe を evbunpack で解凍した状態を識別します。 + // 他エンジンのゲームへは一切影響しません(このゲームフォルダ内でのみ扱う)。 + private bool _isEvbPacked; + private bool _isEvbExtracted; + private string? _evbExtractedDirPath; + private string? _evbBackupPath; + private string _evbUnderlyingEngine = string.Empty; + + /// Enigma Virtual Box でパックされた exe を持つゲームかどうか + public bool IsEvbPacked + { + get => _isEvbPacked; + set { if (_isEvbPacked != value) { _isEvbPacked = value; OnPropertyChanged(); OnPropertyChanged(nameof(EvbBadgeVisibility)); OnPropertyChanged(nameof(IsEvb)); } } + } + + /// EVB 解凍済み(_evb_extracted に出力済み)かどうか + public bool IsEvbExtracted + { + get => _isEvbExtracted; + set { if (_isEvbExtracted != value) { _isEvbExtracted = value; OnPropertyChanged(); OnPropertyChanged(nameof(EvbDetailStatusText)); } } + } + + /// EVB 解凍先ディレクトリ(ゲームフォルダ内 _evb_extracted) + public string? EvbExtractedDirPath + { + get => _evbExtractedDirPath; + set { if (_evbExtractedDirPath != value) { _evbExtractedDirPath = value; OnPropertyChanged(); } } + } + + /// EVB 解凍時に作成した元 exe のバックアップパス(*.glbak) + public string? EvbBackupPath + { + get => _evbBackupPath; + set { if (_evbBackupPath != value) { _evbBackupPath = value; OnPropertyChanged(); } } + } + + /// EVB 解凍後に再判定された本来のエンジン名 + public string EvbUnderlyingEngine + { + get => _evbUnderlyingEngine; + set { if (_evbUnderlyingEngine != value) { _evbUnderlyingEngine = value; OnPropertyChanged(); OnPropertyChanged(nameof(EvbDetailStatusText)); } } + } + + /// EVB として扱うか(UI バッジ判定用) + public override bool IsEvb => IsEvbPacked; + + /// EVB バッジの可視性 + public Visibility EvbBadgeVisibility => IsEvbPacked ? Visibility.Visible : Visibility.Collapsed; + + /// EVB バッジのテキスト + public string EvbBadgeText => "EVB"; + + /// EVB 未解凍のときだけ「要解凍」を強調表示するための可視性(一目で分かる導線) + public Visibility EvbNeedsUnpackVisibility => (IsEvbPacked && !IsEvbExtracted) ? Visibility.Visible : Visibility.Collapsed; + + /// + /// Evb 解凍ツール(evbunpack.exe)が未配置かどうか。 + /// 選択時のガイドで「README.md を参照してください」と案内するために使用します。 + /// + public bool IsEvbToolMissing => IsEvbPacked && !Engines.Evb.EvbUnpackerToolProvider.IsAvailable(); + + /// EVB 詳細状態テキスト + public string EvbDetailStatusText + { + get + { + if (!IsEvbPacked) + { + return string.Empty; + } + var engine = string.IsNullOrWhiteSpace(EvbUnderlyingEngine) ? "未判定" : EvbUnderlyingEngine; + if (IsEvbToolMissing) + { + return "evbunpack.exe が未配置です。Engines/Evb/Tools/evbunpack/README.md を参照してください。"; + } + return IsEvbExtracted + ? $"Enigma Virtual Box パック済み(解凍済み / 本来: {engine})" + : $"Enigma Virtual Box パック済み(未解凍 / 本来: {engine})"; + } + } + + /// + /// EVB 解凍後の起動に使う実行ファイルを解決します。 + /// 解凍済み(_evb_extracted に完了マーカーがある)なら、その配下の exe を起動対象とし、 + /// 未解凍なら元の exe を返します。他ゲームには影響しません。 + /// + public string ResolveLaunchExecutable() + { + if (!IsEvbPacked || !IsEvbExtracted) + { + return ExecutablePath; + } + + var outputDir = !string.IsNullOrEmpty(EvbExtractedDirPath) + ? EvbExtractedDirPath! + : GameLauncher.Engines.Evb.EvbUnpackService.GetExtractedDir(RootDirectory); + + var exe = GameLauncher.Engines.Evb.EvbUnpackService.FindLaunchExecutable(outputDir); + return string.IsNullOrEmpty(exe) ? ExecutablePath : exe!; + } /// FOSSIL形態(FOSSILindex.html + 単体Game.exe、data/System.json はディスク上)かどうか public bool IsFossilSingleExe @@ -141,45 +240,6 @@ namespace GameLauncher.Engines.Tkool /// いずれかの単体exe梱包形態(FOSSIL / boxed)かどうか public bool IsStandaloneExePackage => IsFossilSingleExe || IsBoxedExe; - /// 単体exe梱包ゲームを _extracted へ展開済みかどうか - public bool IsStandaloneExeExtracted - { - get => _isStandaloneExeExtracted; - set { if (_isStandaloneExeExtracted != value) { _isStandaloneExeExtracted = value; OnPropertyChanged(); } } - } - - /// 展開先ディレクトリ(ゲームフォルダ内 _extracted) - public string? StandaloneExtractedDirPath - { - get => _standaloneExtractedDirPath; - set { if (_standaloneExtractedDirPath != value) { _standaloneExtractedDirPath = value; OnPropertyChanged(); } } - } - - /// exe内コンテナ改変時のバックアップパス(*.glbak) - public string? StandaloneBackupPath - { - get => _standaloneBackupPath; - set { if (_standaloneBackupPath != value) { _standaloneBackupPath = value; OnPropertyChanged(); } } - } - - /// boxed exe内で注入対象とするコンテナ内エントリ(例: js/plugins.js) - public string? BoxedPayloadEntryPath - { - get => _boxedPayloadEntryPath; - set { if (_boxedPayloadEntryPath != value) { _boxedPayloadEntryPath = value; OnPropertyChanged(); } } - } - - /// - /// 外部アンパッカー(Tools\7zr.exe 等)による展開を試行できる可能性があるか。 - /// 標準ZIP署名が未確定でも、boxed命名exeが存在する場合に true となり「展開試行可」を示す。 - /// 実際に展開可能かは実行時(ExtractPackageNw)に確定する。 - /// - public bool CanExtractViaExternalTool - { - get => _canExtractViaExternalTool; - set { if (_canExtractViaExternalTool != value) { _canExtractViaExternalTool = value; OnPropertyChanged(); } } - } - public override GameEngineKind EngineKind => EngineType switch { TkoolEngineType.Tyrano => GameEngineKind.Tyrano, diff --git a/Engines/Tkool/TkoolPackagedExtractionService.cs b/Engines/Tkool/TkoolPackagedExtractionService.cs deleted file mode 100644 index cdf6da0..0000000 --- a/Engines/Tkool/TkoolPackagedExtractionService.cs +++ /dev/null @@ -1,249 +0,0 @@ -using System; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using GameLauncher.Engines.Nwjs; - -namespace GameLauncher.Engines.Tkool -{ - /// - /// nw.js boxed(exe埋め込み package.nw)等の単体exe梱包ツクールゲームの解析と - /// ゲームフォルダ内 `_extracted` への冪等展開を行うオーケストレーター。 - /// - /// 役割分担(恒久・再利用可能を目的とした汎用設計): - /// - 本サービス = 抽出の「進行役(オーケストレーター)」。 - /// - = 組み込みの埋め込みZIPコンテナ検出・展開。 - /// - = 外部アンパッカーの取得・呼び出し。 - /// - /// 展開戦略(順に試行): - /// 1. 組み込みZIP展開: exe内の標準ZIPコンテナ(package.nw)を検出して展開。 - /// 2. 外部ツール委譲: Tools\ 配下の外部アンパッカー(未配置なら自動取得)へ委譲。 - /// - /// 設計方針: - /// - 1.14GB級exeを対象に含むため、組み込み検出は限定/逐次走査で行う。 - /// - 展開はゲームフォルダ内 `_extracted` のみ。他ゲームへは一切影響しない。 - /// - 冪等: 展開済み(plugins.js 存在)なら再展開しない。 - /// - 既存公開API(GetExtractedDir / ContainsPackageNwMarker / IsExtractionComplete / - /// ExeBackupSuffix / ExtractPackageNw)のシグネチャは維持し、後方互換を壊さない。 - /// - public sealed class TkoolPackagedExtractionService - { - /// ゲームフォルダ内の展開先フォルダ名(Asar/SRPG の慣習に合わせる) - public const string ExtractedDirName = NwjsPackageUnpacker.ExtractedDirName; - - /// exe内コンテナ改変時のバックアップ拡張子 - public const string ExeBackupSuffix = ".glbak"; - - /// 展開戦略の種別。将来の新形式追加を見据え、列挙型で差し替え可能にする。 - public enum UnpackStrategy - { - /// 組み込みの埋め込みZIPコンテナ検出・展開 - BuiltInZip = 0, - - /// 外部アンパッカーへの委譲 - ExternalTool = 1, - } - - /// ゲームフォルダ内の展開先ディレクトリ(物理パス) - public static string GetExtractedDir(string gameRootDir) - => NwjsPackageUnpacker.GetExtractedDir(gameRootDir); - - /// - /// exeに package.nw マーカーが含まれるかを限定部分読み(4MB窓×数点)で判定します。 - /// 全走査は行いません(1.14GB級exe対策)。 - /// - public static bool ContainsPackageNwMarker(string exePath) - { - try - { - const int windowSize = 4 * 1024 * 1024; - using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - long size = fs.Length; - if (size < 1024) - { - return false; - } - - double[] fractions = { 0.25, 0.5, 0.75, 0.9 }; - foreach (var frac in fractions) - { - long start = (long)(size * frac); - int readLen = (int)Math.Min(windowSize, size - start); - if (readLen <= 0) - { - continue; - } - - var buf = new byte[readLen]; - fs.Seek(start, SeekOrigin.Begin); - int read = fs.Read(buf, 0, buf.Length); - var text = System.Text.Encoding.ASCII.GetString(buf, 0, read); - - if (text.IndexOf("package.nw", StringComparison.Ordinal) >= 0 || - text.IndexOf("package.json", StringComparison.Ordinal) >= 0) - { - return true; - } - } - } - catch { } - - return false; - } - - /// - /// exe内ZIPのローカルヘッダ(PK\x03\x04)offsetを限定ウィンドウで検出します。 - /// exe先頭の自己展開部を除いた中盤以降のみを対象にし、全走査を避けます。 - /// - public static long? FindEmbeddedZipOffset(string exePath, long searchStart = 0, int windowBytes = 8 * 1024 * 1024) - { - try - { - using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - long size = fs.Length; - - // searchStart が 0 の場合は中盤〜後半(package.nw は後半に置かれる傾向)のみを走査 - double[] fractions = searchStart > 0 ? new[] { (double)searchStart / Math.Max(1, size) } : new[] { 0.5, 0.65, 0.8, 0.9 }; - foreach (var frac in fractions) - { - long start = (long)(size * frac); - int readLen = (int)Math.Min(windowBytes, size - start); - if (readLen <= 4) - { - continue; - } - - var buf = new byte[readLen]; - fs.Seek(start, SeekOrigin.Begin); - int read = fs.Read(buf, 0, buf.Length); - - for (int i = 0; i < read - 3; i++) - { - if (buf[i] == 0x50 && buf[i + 1] == 0x4B && buf[i + 2] == 0x03 && buf[i + 3] == 0x04) - { - return start + i; - } - } - } - } - catch { } - - return null; - } - - /// - /// 既存 `_extracted` が完全か(plugins.js が存在するか)を判定します。 - /// - public static bool IsExtractionComplete(string extractedDir, out string? pluginsJsPath) - => NwjsPackageUnpacker.IsExtractionComplete(extractedDir, out pluginsJsPath, out _); - - /// - /// exe内ZIP(package.nw 等)をゲームフォルダ内 `_extracted` へ冪等に全展開し、 - /// 展開後の js/plugins.js(相対パス)を返します。展開できなければ null。 - /// - /// 展開戦略を順に試行します: 組み込みZIP展開 → 外部ツール委譲。 - /// 後方互換のため同期シグネチャを維持します(外部ツールの自動取得は内部で同期待機)。 - /// - public string? ExtractPackageNw(string exePath, string gameRoot, out string extractedDir, IProgress? progress = null) - { - extractedDir = GetExtractedDir(gameRoot); - - try - { - if (!File.Exists(exePath)) - { - return null; - } - - // 冪等: 展開済みならスキップ - if (Directory.Exists(extractedDir) && IsExtractionComplete(extractedDir, out _)) - { - progress?.Report("既に展開済みです(_extracted を再利用)。"); - return NwjsPackageUnpacker.IsExtractionComplete(extractedDir, out _, out var rel) ? rel : "js/plugins.js"; - } - - // 戦略1: 組み込みZIP展開 - progress?.Report("展開戦略: 組み込みZIP展開を試行します。"); - var relBuiltin = NwjsPackageUnpacker.ExtractEmbeddedZip(exePath, extractedDir, progress); - if (relBuiltin != null) - { - return relBuiltin; - } - - // 戦略2: 外部ツール委譲 - progress?.Report("展開戦略: 外部アンパッカーへの委譲を試行します。"); - var relExternal = ExtractViaExternalTool(exePath, extractedDir, progress); - if (relExternal != null) - { - return relExternal; - } - - progress?.Report("展開できませんでした(起動のみ対応)。"); - return null; - } - catch (Exception ex) - { - progress?.Report($"展開処理中にエラーが発生しました: {ex.Message}"); - return null; - } - } - - /// - /// 外部アンパッカー(未配置なら自動取得)で exe 内コンテナを `_extracted` へ展開します。 - /// 失敗(ネット未接続等)時は例外を投げず null を返し、呼び出し側で「起動のみ」へフォールバックさせます。 - /// - private static string? ExtractViaExternalTool(string exePath, string extractedDir, IProgress? progress) - { - try - { - // 外部ツールの可用性確保(初回は自動ダウンロード)。同期待機で取得。 - var available = NwjsUnpackerToolProvider.IsToolAvailable() - || Task.Run(() => NwjsUnpackerToolProvider.EnsureToolAvailableAsync(progress)).GetAwaiter().GetResult(); - - if (!available) - { - progress?.Report("外部アンパッカーを取得できませんでした(ネット未接続等)。起動のみ対応へフォールバックします。"); - return null; - } - - var tool = NwjsUnpackerToolProvider.GetToolPath(); - if (tool == null) - { - return null; - } - - // 展開先を一旦クリーンにする(部分展開の混在を避ける) - try - { - if (Directory.Exists(extractedDir)) - { - Directory.Delete(extractedDir, recursive: true); - } - } - catch { } - - if (!NwjsUnpackerToolProvider.ExtractWithExternalTool(tool, exePath, extractedDir, progress)) - { - return null; - } - - // 展開結果から plugins.js を解決 - var plugins = NwjsPackageUnpacker.ResolvePluginsJs(extractedDir); - if (plugins == null) - { - progress?.Report("展開は完了しましたが、js/plugins.js が見つかりませんでした。"); - return null; - } - - var rel = Path.GetRelativePath(extractedDir, plugins).Replace(Path.DirectorySeparatorChar, '/'); - progress?.Report($"外部アンパッカーでの展開が完了しました: {rel}"); - return rel; - } - catch (Exception ex) - { - progress?.Report($"外部アンパッカー委譲でエラーが発生しました: {ex.Message}"); - return null; - } - } - } -} diff --git a/Engines/Unity/UnityEnums.cs b/Engines/Unity/UnityEnums.cs index b41adcc..9e9f01d 100644 --- a/Engines/Unity/UnityEnums.cs +++ b/Engines/Unity/UnityEnums.cs @@ -9,7 +9,8 @@ Tyrano, Unity, Wolf, - SrpgStudio + SrpgStudio, + Evb } /// diff --git a/GameLauncher.csproj b/GameLauncher.csproj index dfab083..ab0ff44 100644 --- a/GameLauncher.csproj +++ b/GameLauncher.csproj @@ -17,6 +17,12 @@ + + + + + + @@ -28,6 +34,14 @@ PreserveNewest + + + PreserveNewest + + + + + diff --git a/MainWindow.xaml b/MainWindow.xaml index 0b29c13..0d1af8c 100644 --- a/MainWindow.xaml +++ b/MainWindow.xaml @@ -8,8 +8,8 @@ xmlns:models="clr-namespace:GameLauncher.Models" mc:Ignorable="d" Title="統合ゲームランチャー (Game Launcher)" - Height="840" Width="1280" - MinHeight="620" MinWidth="960" + Height="780" Width="1120" + MinHeight="580" MinWidth="900" WindowStartupLocation="CenterScreen" Background="#181820" Foreground="#E0E0E6" @@ -351,8 +351,8 @@ -