機能追加: Bakin・NW.jsエンジンおよびセーブ編集対応、ES3パスワード解決機能とRPGツクールMZ修正サービスの追加

This commit is contained in:
armonica committed 2026-11-20 19:55:34 +09:00
1 parent f50976a6c0
commit 152abae1f8
33 files changed
+11356 -175

No files matched your search

+295 -52
View File
@@ -9,6 +9,7 @@ using System.Text.Json;
using System.Text.Json.Nodes;
using GameLauncher.Engines.Unity;
using GameLauncher.Models;
using GameLauncher.Services.Codecs.Es3;
namespace GameLauncher.Services.Codecs
{
@@ -24,19 +25,63 @@ namespace GameLauncher.Services.Codecs
/// <summary>
/// パスワード入力が必要かどうかを取得します。
/// 暗号化の有無はファイルごとに異なるため、実際の要否は <see cref="NeedsPassword"/> で判定します。
/// </summary>
public bool RequiresPassword => false;
public bool RequiresPassword => true;
/// <summary>
/// パスワード入力ダイアログに表示する案内メッセージを取得します。
/// </summary>
public string? PasswordPromptMessage => "暗号化パスワードが設定されている場合は入力してください(未設定・既定の場合は空欄):";
// キャッシュ用の最新平文JSONノード
private JsonNode? _cachedRootNode;
/// <summary>
/// 直近の読み込み時に使用した解析ドキュメント(編集・書き戻し用)。
/// </summary>
private Es3SaveDocument? _document;
/// <summary>直近の読み込み対象ファイルの絶対パス。</summary>
private string? _loadedFilePath;
/// <summary>直近の読み込み時に暗号化されていたか。</summary>
private bool _wasEncrypted;
/// <summary>直近の読み込み時に復号に使用したパスワード。</summary>
private string? _usedPassword;
/// <summary>直近の読み込み時に Gzip 圧縮されていたか。</summary>
private bool _wasGzip;
/// <summary>直近の読み込み時の診断メッセージ(未対応時の案内表示に使用)。</summary>
private readonly List<string> _diagnostics = [];
/// <summary>
/// 直近の読み込みに関する診断メッセージを取得します。
/// </summary>
public IReadOnlyList<string> Diagnostics => this._diagnostics;
/// <summary>
/// 指定ファイルがパスワード入力(復号)を必要とするかを判定します。
/// </summary>
/// <param name="filePath">セーブファイルの絶対パス</param>
/// <returns>暗号化されており復号が必要な場合 true</returns>
public bool NeedsPassword(string filePath)
{
try
{
if (!File.Exists(filePath))
{
return false;
}
var bytes = File.ReadAllBytes(filePath);
return Es3PasswordResolver.LooksEncrypted(bytes);
}
catch
{
return false;
}
}
/// <summary>
/// 指定されたセーブファイルが本コーデックで処理可能かを判定します。
/// </summary>
@@ -67,14 +112,19 @@ namespace GameLauncher.Services.Codecs
public List<SaveDataPropertyEntry> LoadProperties(string filePath, string? optionalPassword = null)
{
var list = new List<SaveDataPropertyEntry>();
this._diagnostics.Clear();
this._document = null;
this._loadedFilePath = filePath;
this._wasEncrypted = false;
this._usedPassword = null;
this._wasGzip = false;
if (!File.Exists(filePath)) return list;
byte[] fileBytes = File.ReadAllBytes(filePath);
if (fileBytes.Length == 0) return list;
string? jsonText = null;
this._wasEncrypted = false;
this._usedPassword = null;
// 1. まず平文 JSON または Gzip 解凍を試みる
try
@@ -83,6 +133,7 @@ namespace GameLauncher.Services.Codecs
if (text.TrimStart().StartsWith("{") || text.TrimStart().StartsWith("["))
{
jsonText = text;
this._diagnostics.Add("平文 JSON として読み込みました。");
}
}
catch { }
@@ -96,60 +147,142 @@ namespace GameLauncher.Services.Codecs
using var gzip = new GZipStream(ms, CompressionMode.Decompress);
using var reader = new StreamReader(gzip, Encoding.UTF8);
jsonText = reader.ReadToEnd();
this._wasGzip = true;
this._diagnostics.Add("Gzip 圧縮を解凍して読み込みました。");
}
catch { }
}
// 3. パスワード指定または既定パスワードによる AES 復号を試みる
// 3. パスワードを多段フォールバックで解決して AES 復号する
if (jsonText == null)
{
var candidatePasswords = new List<string>();
if (!string.IsNullOrEmpty(optionalPassword))
{
candidatePasswords.Add(optionalPassword);
}
candidatePasswords.AddRange(new[] { "Moodkie", "password", "", "SaveData" });
var gameRoot = Path.GetDirectoryName(filePath);
var resolution = Es3PasswordResolver.Instance.Resolve(
filePath,
gameRootDirectory: gameRoot,
gameKey: gameRoot,
explicitPassword: optionalPassword);
foreach (var pwd in candidatePasswords)
this._diagnostics.AddRange(resolution.Diagnostics);
if (resolution.Success && !string.IsNullOrEmpty(resolution.Password))
{
var decrypted = this.TryDecryptAes(fileBytes, pwd);
if (!string.IsNullOrEmpty(decrypted))
jsonText = Es3PasswordResolver.TryDecrypt(fileBytes, resolution.Password);
if (!string.IsNullOrEmpty(jsonText))
{
jsonText = decrypted;
this._wasEncrypted = true;
this._usedPassword = pwd;
break;
this._usedPassword = resolution.Password;
}
}
}
if (string.IsNullOrEmpty(jsonText))
{
// JSON展開ができなかった場合、バイナリキー・バリュー形式として先頭・重要オフセットを抽出
this._diagnostics.Add("復号できませんでした。パスワードを手動で入力してください。");
return this.ExtractBinaryPropertiesFallback(fileBytes);
}
// JSON からプロパティを再帰的に展開
try
{
this._cachedRootNode = JsonNode.Parse(jsonText);
if (this._cachedRootNode is JsonObject rootObj)
{
this.FlattenJsonObject(rootObj, "", list);
}
else if (this._cachedRootNode is JsonArray rootArr)
{
this.FlattenJsonArray(rootArr, "Array", list);
}
}
catch
// 4. ES3 の型付き形式を解析してプロパティへ展開
var document = Es3SaveDocument.Parse(jsonText);
if (!document.IsLoaded)
{
this._diagnostics.AddRange(document.Warnings);
return this.ExtractBinaryPropertiesFallback(fileBytes);
}
this._document = document;
this._diagnostics.AddRange(document.Warnings);
this.FlattenNodes(document.RootNodes, string.Empty, list);
return list;
}
/// <summary>
/// 型付きノードを平坦化してプロパティ一覧へ変換します(型タグ付きで編集可能にします)。
/// </summary>
/// <param name="nodes">変換対象のノード</param>
/// <param name="prefix">現在の階層プレフィックス</param>
/// <param name="list">追加先のプロパティリスト</param>
private void FlattenNodes(List<Es3Node> nodes, string prefix, List<SaveDataPropertyEntry> list)
{
foreach (var node in nodes)
{
var key = string.IsNullOrEmpty(prefix) ? node.Key : $"{prefix}.{node.Key}";
var category = string.IsNullOrEmpty(prefix) ? "基本変数" : prefix;
if (node.HasChildren)
{
list.Add(new SaveDataPropertyEntry
{
Key = key,
Category = category,
Type = FormatKindLabel(node),
EditValue = node.DisplayValue,
Description = $"JSON パス: {node.Path}",
RawData = node,
Kind = MapToValueKind(node.Kind)
});
this.FlattenNodes(node.Children, key, list);
continue;
}
list.Add(new SaveDataPropertyEntry
{
Key = key,
Category = category,
Type = FormatKindLabel(node),
EditValue = node.DisplayValue,
Description = $"JSON パス: {node.Path}",
RawData = node,
Kind = MapToValueKind(node.Kind)
});
}
}
/// <summary>
/// ES3 の値種別を、GUI の型別エディタ用の種別へ変換します。
/// </summary>
/// <param name="kind">ES3 の値種別</param>
/// <returns>GUI 用の値種別</returns>
private static SaveDataPropertyEntry.ValueKind MapToValueKind(Es3ValueKind kind)
{
return kind switch
{
Es3ValueKind.Boolean => SaveDataPropertyEntry.ValueKind.Boolean,
Es3ValueKind.Integer => SaveDataPropertyEntry.ValueKind.Integer,
Es3ValueKind.Float => SaveDataPropertyEntry.ValueKind.Float,
Es3ValueKind.String => SaveDataPropertyEntry.ValueKind.String,
Es3ValueKind.Enum => SaveDataPropertyEntry.ValueKind.Enum,
Es3ValueKind.Array or Es3ValueKind.Dictionary or Es3ValueKind.Object
=> SaveDataPropertyEntry.ValueKind.Complex,
_ => SaveDataPropertyEntry.ValueKind.Unknown
};
}
/// <summary>
/// ノードの型名を表示用ラベルに整形します。
/// </summary>
/// <param name="node">対象ノード</param>
/// <returns>表示用の型ラベル</returns>
private static string FormatKindLabel(Es3Node node)
{
var kind = node.Kind switch
{
Es3ValueKind.Boolean => "bool",
Es3ValueKind.Integer => "int",
Es3ValueKind.Float => "float",
Es3ValueKind.String => "string",
Es3ValueKind.Enum => "enum",
Es3ValueKind.Array => "array",
Es3ValueKind.Dictionary => "dictionary",
Es3ValueKind.Object => "object",
_ => "unknown"
};
return string.IsNullOrEmpty(node.TypeName) ? kind : $"{kind} ({node.TypeName})";
}
/// <summary>
/// JSONオブジェクトを再帰的に走査し、プロパティ一覧に追加します。
/// </summary>
@@ -312,40 +445,71 @@ namespace GameLauncher.Services.Codecs
{
try
{
if (this._cachedRootNode != null)
if (this._document is { IsLoaded: true } document)
{
// JSON の値を更新
// 編集値を解析ツリーへ適用する
foreach (var prop in properties)
{
if (prop.RawData is string keyPath)
if (!prop.IsModified || prop.RawData is not Es3Node node)
{
this.UpdateJsonNodeByPath(this._cachedRootNode, keyPath, prop.EditValue, prop.Type);
continue;
}
if (!node.IsEditable)
{
continue;
}
if (document.TrySetValue(node.Path, prop.EditValue, out var applyError))
{
node.DisplayValue = prop.EditValue;
}
else
{
this._diagnostics.Add($"'{prop.Key}' の適用をスキップしました: {applyError}");
}
}
var options = new JsonSerializerOptions
// 変更がなければ書き込まない
if (!document.HasChanges())
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
string updatedJson = this._cachedRootNode.ToJsonString(options);
byte[] outputBytes = Encoding.UTF8.GetBytes(updatedJson);
// もともと暗号化されていた場合は再暗号化
if (this._wasEncrypted)
{
string pwd = !string.IsNullOrEmpty(optionalPassword) ? optionalPassword : (this._usedPassword ?? "Moodkie");
outputBytes = this.EncryptAes(outputBytes, pwd);
this._diagnostics.Add("変更点がないため保存をスキップしました。");
return true;
}
// バックアップ作成
byte[] outputBytes = Encoding.UTF8.GetBytes(document.ToJson());
// もともと Gzip 圧縮されていた場合は再圧縮する
if (this._wasGzip)
{
outputBytes = CompressGzip(outputBytes);
}
// もともと暗号化されていた場合は同一パスワードで再暗号化する
if (this._wasEncrypted)
{
var pwd = !string.IsNullOrEmpty(optionalPassword)
? optionalPassword!
: this._usedPassword ?? string.Empty;
outputBytes = Es3PasswordResolver.Encrypt(outputBytes, pwd);
}
// 往復検証: 書き込み前に「出力バイト列を読み直して構造が一致するか」を確認する
if (!this.VerifyRoundTrip(outputBytes, document, out var verifyError))
{
this._diagnostics.Add($"往復検証に失敗したため保存を中止しました: {verifyError}");
return false;
}
// バックアップ作成(既存規約に従い .bak を残す)
if (File.Exists(filePath))
{
File.Copy(filePath, filePath + ".bak", overwrite: true);
}
File.WriteAllBytes(filePath, outputBytes);
this._diagnostics.Add($"保存しました({outputBytes.Length} bytes)。");
return true;
}
else
@@ -372,12 +536,91 @@ namespace GameLauncher.Services.Codecs
return true;
}
}
catch
catch (Exception ex)
{
this._diagnostics.Add($"保存中に例外が発生しました: {ex.Message}");
return false;
}
}
/// <summary>
/// 出力バイト列を読み直して編集内容が保持されているかを検証します(往復検証)。
/// 検証に失敗した場合はファイルへ書き込まず、元データを温存します。
/// </summary>
/// <param name="outputBytes">書き込み予定のバイト列</param>
/// <param name="document">編集済みドキュメント</param>
/// <param name="error">検証失敗の理由</param>
/// <returns>検証に成功した場合 true</returns>
private bool VerifyRoundTrip(byte[] outputBytes, Es3SaveDocument document, out string error)
{
error = string.Empty;
try
{
string? verifiedJson;
if (this._wasEncrypted)
{
var pwd = this._usedPassword ?? string.Empty;
verifiedJson = Es3PasswordResolver.TryDecrypt(outputBytes, pwd);
}
else if (this._wasGzip)
{
using var ms = new MemoryStream(outputBytes);
using var gzip = new GZipStream(ms, CompressionMode.Decompress);
using var reader = new StreamReader(gzip, Encoding.UTF8);
verifiedJson = reader.ReadToEnd();
}
else
{
verifiedJson = Encoding.UTF8.GetString(outputBytes);
}
if (string.IsNullOrEmpty(verifiedJson))
{
error = "出力データを復号・解凍できませんでした。";
return false;
}
var reparsed = Es3SaveDocument.Parse(verifiedJson);
if (!reparsed.IsLoaded)
{
error = "出力データを再解析できませんでした。";
return false;
}
// ルート直下の要素数が一致することを最低条件とする
if (reparsed.RootNodes.Count != document.RootNodes.Count)
{
error = $"要素数が一致しません(期待 {document.RootNodes.Count} / 実際 {reparsed.RootNodes.Count})。";
return false;
}
return true;
}
catch (Exception ex)
{
error = ex.Message;
return false;
}
}
/// <summary>
/// バイト列を Gzip 圧縮します(元が Gzip だった場合に元形式を維持するため)。
/// </summary>
/// <param name="plainBytes">平文バイト列</param>
/// <returns>圧縮済みバイト列</returns>
private static byte[] CompressGzip(byte[] plainBytes)
{
using var output = new MemoryStream();
using (var gzip = new GZipStream(output, CompressionLevel.Optimal, leaveOpen: true))
{
gzip.Write(plainBytes, 0, plainBytes.Length);
}
return output.ToArray();
}
/// <summary>
/// キーパスに基づいてJSONノードの値を更新します。
/// </summary>
+585
View File
@@ -0,0 +1,585 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace GameLauncher.Services.Codecs.Es3
{
/// <summary>
/// ゲームのバイナリから ES3 のパスワード候補文字列を抽出する汎用ヘルパー。
///
/// Easy Save 3 のパスワードは <c>new ES3Settings(ES3.EncryptionType.AES, "password")</c> のように
/// コード中の文字列リテラルとして埋め込まれることが多いため、
/// マネージドアセンブリ(Mono)/IL2CPP メタデータの双方から文字列を回収します。
/// 特定のゲーム名に依存しない汎用実装です。
/// </summary>
public static class Es3PasswordExtractor
{
/// <summary>文字列抽出対象とする最大ファイルサイズ(バイト)。巨大ファイルの全走査を避けます。</summary>
private const long MaxScanFileSize = 512L * 1024 * 1024;
/// <summary>1 ファイルあたりに保持する候補の上限。</summary>
private const int MaxCandidatesPerFile = 4000;
/// <summary>抽出する文字列の最小長。</summary>
private const int MinCandidateLength = 3;
/// <summary>抽出する文字列の最大長。</summary>
private const int MaxCandidateLength = 64;
/// <summary>ES3 の既定設定アセットにおいて暗号化パスワードを保持するフィールド名。</summary>
private const string FieldNameEncryptionPassword = "encryptionPassword";
/// <summary>
/// パスワードらしい文字列のみを通すための許可パターン(英数字記号のみ、空白・制御文字を除外)。
/// </summary>
private static readonly Regex CandidatePattern =
new(@"^[\x21-\x7E]{3,64}$", RegexOptions.Compiled);
/// <summary>
/// ES3 のパスワード指定箇所の近傍を示す手がかりキーワード。
/// これらを含む文字列は優先的に候補の先頭へ寄せます。
/// </summary>
private static readonly string[] PasswordHints =
[
"password", "Password", "PASSWORD",
"pass", "Pass", "pwd", "Pwd",
"encrypt", "Encrypt", "encryption", "Encryption",
"ES3Settings", "ES3", "es3"
];
/// <summary>
/// 明らかにパスワードではない文字列(Unity の内部名・型名・UI ラベルなど)を除外するパターン。
///
/// 実ゲーム検証では "GUILayoutPasswordField" のような UI クラス名や
/// "The password Text" のような説明文が大量に抽出され、真のパスワードが埋もれていました。
/// それらを除外して候補の精度を上げます。
/// </summary>
private static readonly Regex NoisePattern = new(
@"^(Unity|UnityEngine|UnityEditor|System|Microsoft|Mono|mscorlib|netstandard|" +
@"Assembly-CSharp|Library|Packages|Assets|Resources|StreamingAssets|" +
@"com\.unity|Unity\.|UnityEngine\.|System\.)" +
@"|PasswordField|passwordField|TextField|password Text|Password Text" +
@"|GUILayout|OnGUI|m_[A-Z]|get_|set_|<[A-Za-z]",
RegexOptions.Compiled);
/// <summary>
/// 空白を含む文字列は UI ラベル・説明文である可能性が高いため、
/// パスワード候補としては扱いません(パスワードは通常 1 トークン)。
/// </summary>
private static readonly Regex SentenceLikePattern = new(
@"\s{1,}.*\s|[.!?]$",
RegexOptions.Compiled);
/// <summary>
/// ゲームルートディレクトリから ES3 パスワード候補を抽出します。
/// </summary>
/// <param name="gameRootDirectory">ゲームのルートディレクトリ</param>
/// <param name="diagnostics">診断メッセージの追加先(null 可)</param>
/// <returns>優先度順に並んだパスワード候補</returns>
public static List<string> ExtractCandidates(string gameRootDirectory, List<string>? diagnostics = null)
{
var result = new List<string>();
if (string.IsNullOrWhiteSpace(gameRootDirectory) || !Directory.Exists(gameRootDirectory))
{
diagnostics?.Add($"ゲームフォルダが見つかりません: {gameRootDirectory}");
return result;
}
var scanTargets = CollectScanTargets(gameRootDirectory);
if (scanTargets.Count == 0)
{
diagnostics?.Add("文字列抽出の対象ファイル(マネージドアセンブリ/IL2CPPメタデータ)が見つかりませんでした。");
return result;
}
diagnostics?.Add($"文字列抽出対象: {scanTargets.Count} ファイル");
// 「パスワード指定の近傍にある文字列」を高優先、「その他の文字列」を低優先として収集する
var settingsDerived = new List<string>();
var highPriority = new List<string>();
var lowPriority = new List<string>();
var seen = new HashSet<string>(StringComparer.Ordinal);
foreach (var path in scanTargets)
{
try
{
var info = new FileInfo(path);
if (!info.Exists || info.Length == 0 || info.Length > MaxScanFileSize)
{
continue;
}
var bytes = File.ReadAllBytes(path);
// ES3Defaults の encryptionPassword フィールドを持つアセットは、
// 値域に格納された文字列をパスワード候補として最優先で回収する
CollectFromEs3DefaultSettings(bytes, settingsDerived, seen);
CollectFromBytes(bytes, highPriority, lowPriority, seen);
}
catch (Exception ex)
{
diagnostics?.Add($"読み込み失敗: {Path.GetFileName(path)} ({ex.Message})");
}
}
if (settingsDerived.Count > 0)
{
diagnostics?.Add($"ES3Defaults の encryptionPassword 近傍から {settingsDerived.Count} 件の候補を抽出しました。");
}
// ES3Defaults 由来 → 高優先 → 低優先の順で連結
foreach (var candidate in settingsDerived.Concat(highPriority).Concat(lowPriority))
{
if (result.Count >= 512)
{
break;
}
result.Add(candidate);
}
diagnostics?.Add(
$"抽出候補数: {result.Count}(設定由来 {settingsDerived.Count} / 高優先 {highPriority.Count} / 低優先 {lowPriority.Count})");
return result;
}
/// <summary>
/// ES3 の既定設定(<c>ES3Defaults</c>)を持つアセットから、<c>encryptionPassword</c> の値候補を抽出します。
///
/// Unity のアセットは「フィールド名テーブル」と「値テーブル」が分離しており、
/// フィールド名の直後に値があるとは限りません。そのため、フィールド名が存在するアセットでは
/// ファイル全体の文字列を候補化しつつ、パスワードらしい短い文字列を優先的に先頭へ寄せます。
/// </summary>
/// <param name="bytes">アセットのバイト列</param>
/// <param name="settingsDerived">設定由来の候補の追加先</param>
/// <param name="seen">重複排除用の集合</param>
private static void CollectFromEs3DefaultSettings(
byte[] bytes,
List<string> settingsDerived,
HashSet<string> seen)
{
if (bytes.Length == 0)
{
return;
}
// 高速化のため、まず encryptionPassword の存在を確認する
bool hasField;
try
{
var probeLength = Math.Min(bytes.Length, 4 * 1024 * 1024);
var probe = Encoding.ASCII.GetString(bytes, 0, probeLength);
hasField = probe.Contains(FieldNameEncryptionPassword, StringComparison.Ordinal);
}
catch
{
return;
}
if (!hasField)
{
// 巨大アセットでは先頭 4MB に無いことが多いため、全体を再度確認する
try
{
var all = Encoding.ASCII.GetString(bytes);
hasField = all.Contains(FieldNameEncryptionPassword, StringComparison.Ordinal);
}
catch
{
return;
}
}
if (!hasField)
{
return;
}
// フィールド名が存在するアセットの文字列を候補化する
var asciiCandidates = new List<string>();
var utf16Candidates = new List<string>();
CollectAsciiStrings(bytes, asciiCandidates, asciiCandidates, seen, 0);
CollectUtf16Strings(bytes, utf16Candidates, utf16Candidates, seen, 0);
// 実ゲーム検証では、PlayMaker アクションのスキーマ定義に encryptionPassword が
// 並ぶだけで実際の値は別領域にあり、無関係な文字列が大量に候補化されました。
// パスワード指定の手がかり(password / encrypt 等)を含む文字列だけに絞り込みます。
foreach (var candidate in asciiCandidates.Concat(utf16Candidates))
{
if (!ContainsPasswordHint(candidate))
{
continue;
}
if (LooksLikePasswordValue(candidate) && !settingsDerived.Contains(candidate))
{
settingsDerived.Add(candidate);
}
}
}
/// <summary>
/// 文字列がパスワード値そのものらしいかを判定します(フィールド名や型名を除外)。
/// </summary>
/// <param name="candidate">候補文字列</param>
/// <returns>パスワード値らしい場合 true</returns>
private static bool LooksLikePasswordValue(string candidate)
{
if (candidate.Length < 3 || candidate.Length > 32)
{
return false;
}
// ES3 の設定フィールド名・型名は値ではない
if (candidate.Equals(FieldNameEncryptionPassword, StringComparison.OrdinalIgnoreCase) ||
candidate.Equals("encryptionType", StringComparison.OrdinalIgnoreCase) ||
candidate.Equals("compressionType", StringComparison.OrdinalIgnoreCase) ||
candidate.Equals("bufferSize", StringComparison.OrdinalIgnoreCase) ||
candidate.Equals("errorMessage", StringComparison.OrdinalIgnoreCase) ||
candidate.Equals("overrideDefaultSettings", StringComparison.OrdinalIgnoreCase) ||
candidate.StartsWith("ES3", StringComparison.Ordinal))
{
return false;
}
// 空白・記号のみのものは除外
if (candidate.Contains(' '))
{
return false;
}
return IsPlausibleCandidate(candidate);
}
/// <summary>
/// 走査対象のファイル一覧を収集します。
/// Mono の場合は Managed 配下の DLL、IL2CPP の場合は GameAssembly.dll と global-metadata.dat を対象にします。
/// </summary>
/// <param name="gameRootDirectory">ゲームのルートディレクトリ</param>
/// <returns>走査対象ファイルの絶対パス一覧</returns>
private static List<string> CollectScanTargets(string gameRootDirectory)
{
var targets = new List<string>();
try
{
// 1. Mono: <Game>_Data\Managed\*.dll(Assembly-CSharp.dll を最優先)
foreach (var dataDir in Directory.GetDirectories(gameRootDirectory))
{
if (!Path.GetFileName(dataDir).EndsWith("_Data", StringComparison.OrdinalIgnoreCase))
{
continue;
}
var managedDir = Path.Combine(dataDir, "Managed");
if (Directory.Exists(managedDir))
{
var dlls = Directory.GetFiles(managedDir, "*.dll", SearchOption.TopDirectoryOnly)
.Where(f =>
{
var name = Path.GetFileName(f);
return !name.StartsWith("Unity", StringComparison.OrdinalIgnoreCase) &&
!name.StartsWith("System", StringComparison.OrdinalIgnoreCase) &&
!name.StartsWith("Mono", StringComparison.OrdinalIgnoreCase) &&
!name.StartsWith("mscorlib", StringComparison.OrdinalIgnoreCase) &&
!name.StartsWith("netstandard", StringComparison.OrdinalIgnoreCase);
})
.OrderByDescending(f =>
Path.GetFileName(f).StartsWith("Assembly-CSharp", StringComparison.OrdinalIgnoreCase))
.ToList();
targets.AddRange(dlls);
}
// 2. IL2CPP: il2cpp_data\Metadata\global-metadata.dat
var metadata = Path.Combine(dataDir, "il2cpp_data", "Metadata", "global-metadata.dat");
if (File.Exists(metadata))
{
targets.Add(metadata);
}
// 3. ES3 の既定設定(ES3Defaults ScriptableObject)はアセットに格納されるため、
// アセット内の文字列も走査対象に含める。コード側にパスワードリテラルが
// 存在しないゲームでは、ここが唯一の手がかりになる。
targets.AddRange(CollectAssetTargets(dataDir));
}
// 3. IL2CPP: ルート直下の GameAssembly.dll
var gameAssembly = Path.Combine(gameRootDirectory, "GameAssembly.dll");
if (File.Exists(gameAssembly))
{
targets.Add(gameAssembly);
}
}
catch
{
// 列挙失敗時は取得できた分だけ返す
}
return targets;
}
/// <summary>
/// ES3 の既定設定(<c>ES3Defaults</c> ScriptableObject)が格納され得るアセットファイルを収集します。
///
/// 実ゲーム検証ではコード側にパスワードリテラルが存在せず(<c>encryption</c> 文字列すら無い)、
/// 既定設定アセットにのみパスワードが入っているケースがありました。
/// 巨大な .resS / .bundle を避け、テキスト情報を持つ .assets 系に限定します。
/// </summary>
/// <param name="dataDirectory">ゲームの *_Data ディレクトリ</param>
/// <returns>走査対象アセットの絶対パス一覧</returns>
private static List<string> CollectAssetTargets(string dataDirectory)
{
var targets = new List<string>();
try
{
var extensionSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
".assets", ".asset", ".json", ".bytes", ".dat"
};
foreach (var file in Directory.GetFiles(dataDirectory, "*", SearchOption.TopDirectoryOnly))
{
var ext = Path.GetExtension(file);
if (!extensionSet.Contains(ext))
{
continue;
}
var info = new FileInfo(file);
if (info.Length == 0 || info.Length > MaxScanFileSize)
{
continue;
}
targets.Add(file);
}
}
catch
{
// 列挙失敗時は取得できた分だけ返す
}
return targets;
}
/// <summary>
/// バイト列から ASCII 文字列を抽出し、優先度別のリストへ振り分けます。
///
/// .NET アセンブリ(Assembly-CSharp.dll 等)の文字列定数は UTF-16LE で格納されるため、
/// 8bit ASCII 走査に加えて 16bit 走査も行います。これを行わないと
/// コード中のパスワードリテラルを取り逃がします。
/// </summary>
/// <param name="bytes">対象バイト列</param>
/// <param name="highPriority">パスワード指定近傍の候補の追加先</param>
/// <param name="lowPriority">その他の候補の追加先</param>
/// <param name="seen">重複排除用の集合</param>
private static void CollectFromBytes(
byte[] bytes,
List<string> highPriority,
List<string> lowPriority,
HashSet<string> seen)
{
int count = 0;
count = CollectAsciiStrings(bytes, highPriority, lowPriority, seen, count);
if (count >= MaxCandidatesPerFile)
{
return;
}
// UTF-16LE(.NET の文字列定数)としても走査する
CollectUtf16Strings(bytes, highPriority, lowPriority, seen, count);
}
/// <summary>
/// 8bit ASCII 文字列を抽出します。
/// </summary>
/// <param name="bytes">対象バイト列</param>
/// <param name="highPriority">高優先候補の追加先</param>
/// <param name="lowPriority">低優先候補の追加先</param>
/// <param name="seen">重複排除用の集合</param>
/// <param name="count">既に追加済みの件数</param>
/// <returns>追加後の件数</returns>
private static int CollectAsciiStrings(
byte[] bytes,
List<string> highPriority,
List<string> lowPriority,
HashSet<string> seen,
int count)
{
var current = new StringBuilder(MaxCandidateLength);
for (int i = 0; i < bytes.Length; i++)
{
byte b = bytes[i];
// 印字可能な ASCII のみを文字列として扱う
if (b >= 0x21 && b <= 0x7E)
{
if (current.Length < MaxCandidateLength)
{
current.Append((char)b);
}
continue;
}
count = FlushCandidate(current, highPriority, lowPriority, seen, count);
if (count >= MaxCandidatesPerFile)
{
return count;
}
current.Clear();
}
return FlushCandidate(current, highPriority, lowPriority, seen, count);
}
/// <summary>
/// UTF-16LE(下位バイトが印字可能 ASCII、上位バイトが 0x00)の文字列を抽出します。
/// </summary>
/// <param name="bytes">対象バイト列</param>
/// <param name="highPriority">高優先候補の追加先</param>
/// <param name="lowPriority">低優先候補の追加先</param>
/// <param name="seen">重複排除用の集合</param>
/// <param name="count">既に追加済みの件数</param>
/// <returns>追加後の件数</returns>
private static int CollectUtf16Strings(
byte[] bytes,
List<string> highPriority,
List<string> lowPriority,
HashSet<string> seen,
int count)
{
var current = new StringBuilder(MaxCandidateLength);
for (int i = 0; i + 1 < bytes.Length; i += 2)
{
byte lo = bytes[i];
byte hi = bytes[i + 1];
if (lo >= 0x21 && lo <= 0x7E && hi == 0x00)
{
if (current.Length < MaxCandidateLength)
{
current.Append((char)lo);
}
continue;
}
count = FlushCandidate(current, highPriority, lowPriority, seen, count);
if (count >= MaxCandidatesPerFile)
{
return count;
}
current.Clear();
}
return FlushCandidate(current, highPriority, lowPriority, seen, count);
}
/// <summary>
/// 蓄積中の文字列を候補として確定し、優先度別リストへ追加します。
/// </summary>
/// <param name="buffer">蓄積中の文字列バッファ</param>
/// <param name="highPriority">高優先候補の追加先</param>
/// <param name="lowPriority">低優先候補の追加先</param>
/// <param name="seen">重複排除用の集合</param>
/// <param name="count">既に追加済みの件数</param>
/// <returns>追加後の件数</returns>
private static int FlushCandidate(
StringBuilder buffer,
List<string> highPriority,
List<string> lowPriority,
HashSet<string> seen,
int count)
{
if (buffer.Length < MinCandidateLength || buffer.Length > MaxCandidateLength)
{
return count;
}
var candidate = buffer.ToString();
if (!IsPlausibleCandidate(candidate) || !seen.Add(candidate))
{
return count;
}
if (ContainsPasswordHint(candidate))
{
highPriority.Add(candidate);
}
else
{
lowPriority.Add(candidate);
}
return count + 1;
}
/// <summary>
/// 抽出した文字列がパスワード候補として妥当かどうかを判定します。
/// </summary>
/// <param name="candidate">候補文字列</param>
/// <returns>妥当な場合 true</returns>
private static bool IsPlausibleCandidate(string candidate)
{
if (!CandidatePattern.IsMatch(candidate))
{
return false;
}
// 空白を含む説明文・UI ラベルは除外
if (SentenceLikePattern.IsMatch(candidate))
{
return false;
}
// Unity の内部名・名前空間などはノイズとして除外
if (NoisePattern.IsMatch(candidate))
{
return false;
}
// 拡張子付きファイル名は除外
if (candidate.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ||
candidate.EndsWith(".dat", StringComparison.OrdinalIgnoreCase) ||
candidate.EndsWith(".es3", StringComparison.OrdinalIgnoreCase) ||
candidate.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
{
return false;
}
return true;
}
/// <summary>
/// 文字列がパスワード指定箇所の手がかりを含むかを判定します。
/// </summary>
/// <param name="candidate">候補文字列</param>
/// <returns>手がかりを含む場合 true</returns>
private static bool ContainsPasswordHint(string candidate)
{
foreach (var hint in PasswordHints)
{
if (candidate.Contains(hint, StringComparison.Ordinal))
{
return true;
}
}
return false;
}
}
}
+559
View File
@@ -0,0 +1,559 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace GameLauncher.Services.Codecs.Es3
{
/// <summary>
/// "どの段階でパスワードが判明したか" を表す解決手段の種別。
/// </summary>
public enum Es3PasswordSource
{
/// <summary>学習キャッシュ(過去に解決済みのパスワード)から復元。</summary>
LearnedCache,
/// <summary>呼び出し元が明示指定したパスワード。</summary>
Explicit,
/// <summary>ゲーム内のマネージドアセンブリ(Assembly-CSharp.dll 等)の文字列リテラルから抽出。</summary>
GameBinaryStrings,
/// <summary>ゲーム内バイナリ(IL2CPP の GameAssembly.dll / global-metadata.dat)から抽出。</summary>
GameIl2CppMetadata,
/// <summary>ユーザー辞書ファイル/既定の候補リストからの探索。</summary>
Dictionary,
/// <summary>平文のまま(暗号化されていない)。</summary>
PlainText
}
/// <summary>
/// ES3 パスワード解決の結果。<see cref="Success"/> が false の場合は <see cref="Diagnostics"/> に理由が入ります。
/// </summary>
public sealed class Es3PasswordResolution
{
/// <summary>解決に成功したか。</summary>
public bool Success { get; init; }
/// <summary>解決したパスワード(平文・暗号化なしの場合は空文字)。</summary>
public string Password { get; init; } = string.Empty;
/// <summary>解決手段の種別。</summary>
public Es3PasswordSource Source { get; init; }
/// <summary>試行した候補数。</summary>
public int TriedCandidates { get; init; }
/// <summary>診断用のメッセージ一覧(失敗理由・各段階の結果)。</summary>
public IReadOnlyList<string> Diagnostics { get; init; } = [];
/// <summary>失敗結果を生成します。</summary>
public static Es3PasswordResolution Fail(List<string> diagnostics, int tried)
=> new() { Success = false, Diagnostics = diagnostics, TriedCandidates = tried };
/// <summary>成功結果を生成します。</summary>
public static Es3PasswordResolution Ok(string password, Es3PasswordSource source, int tried)
=> new() { Success = true, Password = password, Source = source, TriedCandidates = tried };
}
/// <summary>
/// ES3 (Easy Save 3) の暗号化セーブデータからパスワードを多段フォールバックで特定する汎用リゾルバ。
///
/// 解決順序:
/// 1. 学習キャッシュ(<see cref="Es3PasswordStore"/>)
/// 2. 呼び出し元の明示指定
/// 3. ゲームのマネージドアセンブリ文字列リテラル抽出(Mono)
/// 4. 既定候補 + ユーザー辞書による探索
///
/// すべての候補は実際に AES 復号して妥当性を検証し、成功したものだけを採用します。
/// これにより「誤ったパスワードで復号して壊れたデータを書く」事故を防止します。
/// </summary>
public sealed class Es3PasswordResolver
{
/// <summary>ES3 が AES 暗号化時にファイル先頭へ埋め込む IV の長さ(バイト)。</summary>
public const int AesIvLength = 16;
/// <summary>復号結果が「ES3 の平文 JSON」らしいかを判定する際の最小文字数。</summary>
private const int MinimumPlainTextLength = 2;
private readonly Es3PasswordStore _store;
/// <summary>
/// 既定のストアを用いて <see cref="Es3PasswordResolver"/> を初期化します。
/// </summary>
public Es3PasswordResolver()
: this(Es3PasswordStore.Instance)
{
}
/// <summary>
/// 任意のストアを指定して <see cref="Es3PasswordResolver"/> を初期化します(テスト用途を含む)。
/// </summary>
/// <param name="store">学習済みパスワードの永続ストア</param>
public Es3PasswordResolver(Es3PasswordStore store)
{
this._store = store ?? throw new ArgumentNullException(nameof(store));
}
/// <summary>
/// 既定のシングルトンインスタンス。
/// </summary>
public static Es3PasswordResolver Instance { get; } = new();
/// <summary>
/// ES3 のファイルが暗号化されているかどうかを統計的に判定します。
/// 平文 JSON / Gzip はもちろん「暗号化されていない」と判定します。
/// </summary>
/// <param name="bytes">ファイル全体のバイト列</param>
/// <returns>暗号化されている可能性が高い場合 true</returns>
public static bool LooksEncrypted(byte[] bytes)
{
if (bytes == null || bytes.Length < AesIvLength * 2)
{
return false;
}
// 平文 JSON はそのまま読める
if (IsLikelyJson(bytes))
{
return false;
}
// Gzip マジック
if (bytes[0] == 0x1F && bytes[1] == 0x8B)
{
return false;
}
// AES ブロック境界に一致し、かつ高エントロピーなら暗号化とみなす
if (bytes.Length % AesIvLength != 0)
{
return false;
}
return CalculateEntropy(bytes) >= 7.5;
}
/// <summary>
/// パスワードを多段フォールバックで解決します。
/// </summary>
/// <param name="saveFilePath">対象の .es3 ファイルの絶対パス</param>
/// <param name="gameRootDirectory">ゲームのルートディレクトリ(文字列抽出元の探索に使用)</param>
/// <param name="gameKey">学習キャッシュのキー(通常はゲームのルートディレクトリ)</param>
/// <param name="explicitPassword">呼び出し元が既に知っているパスワード(任意)</param>
/// <param name="userDictionaryPath">追加候補を列挙したテキストファイルのパス(任意)</param>
/// <returns>解決結果</returns>
public Es3PasswordResolution Resolve(
string saveFilePath,
string? gameRootDirectory = null,
string? gameKey = null,
string? explicitPassword = null,
string? userDictionaryPath = null)
{
var diagnostics = new List<string>();
int tried = 0;
byte[] fileBytes;
try
{
fileBytes = File.ReadAllBytes(saveFilePath);
}
catch (Exception ex)
{
diagnostics.Add($"セーブファイルを読み込めません: {ex.Message}");
return Es3PasswordResolution.Fail(diagnostics, tried);
}
if (fileBytes.Length == 0)
{
diagnostics.Add("セーブファイルが空です。");
return Es3PasswordResolution.Fail(diagnostics, tried);
}
// 暗号化されていない場合はパスワード不要
if (!LooksEncrypted(fileBytes))
{
diagnostics.Add("暗号化は検出されませんでした(平文または Gzip)。");
return Es3PasswordResolution.Ok(string.Empty, Es3PasswordSource.PlainText, tried);
}
diagnostics.Add($"暗号化を検出しました({fileBytes.Length} bytes / AES-128-CBC 相当)。");
// ---- 段階 1: 学習キャッシュ ----
var cacheKey = this.BuildCacheKey(gameKey, saveFilePath);
if (!string.IsNullOrEmpty(cacheKey))
{
var learned = this._store.TryGet(cacheKey);
if (!string.IsNullOrEmpty(learned))
{
tried++;
if (this.VerifyPassword(fileBytes, learned, out _))
{
diagnostics.Add("学習キャッシュのパスワードで復号に成功しました。");
return Es3PasswordResolution.Ok(learned, Es3PasswordSource.LearnedCache, tried);
}
diagnostics.Add("学習キャッシュのパスワードは無効でした(破棄します)。");
this._store.Remove(cacheKey);
}
}
// ---- 段階 2: 明示指定 ----
if (!string.IsNullOrEmpty(explicitPassword))
{
tried++;
if (this.VerifyPassword(fileBytes, explicitPassword, out _))
{
diagnostics.Add("指定されたパスワードで復号に成功しました。");
this.Remember(cacheKey, explicitPassword);
return Es3PasswordResolution.Ok(explicitPassword, Es3PasswordSource.Explicit, tried);
}
diagnostics.Add("指定されたパスワードでは復号できませんでした。");
}
// ---- 段階 3: ゲームバイナリの文字列リテラル抽出 ----
if (!string.IsNullOrEmpty(gameRootDirectory) && Directory.Exists(gameRootDirectory))
{
var extracted = Es3PasswordExtractor.ExtractCandidates(gameRootDirectory, diagnostics);
foreach (var candidate in extracted)
{
tried++;
if (this.VerifyPassword(fileBytes, candidate, out _))
{
diagnostics.Add($"ゲームバイナリから抽出した候補で復号に成功しました(候補: {Mask(candidate)})。");
this.Remember(cacheKey, candidate);
return Es3PasswordResolution.Ok(candidate, Es3PasswordSource.GameBinaryStrings, tried);
}
}
if (extracted.Count == 0)
{
diagnostics.Add("ゲームバイナリから有効なパスワード候補を抽出できませんでした。");
}
}
// ---- 段階 4: 既定候補 + ユーザー辞書 ----
foreach (var candidate in this.EnumerateDictionaryCandidates(userDictionaryPath, diagnostics))
{
tried++;
if (this.VerifyPassword(fileBytes, candidate, out _))
{
diagnostics.Add($"辞書探索で復号に成功しました(候補: {Mask(candidate)})。");
this.Remember(cacheKey, candidate);
return Es3PasswordResolution.Ok(candidate, Es3PasswordSource.Dictionary, tried);
}
}
diagnostics.Add($"すべての段階で復号に失敗しました(試行候補数: {tried})。パスワードを手動で入力してください。");
return Es3PasswordResolution.Fail(diagnostics, tried);
}
/// <summary>
/// 指定パスワードで ES3 ファイルを復号し、平文 JSON 文字列を取得します。
/// </summary>
/// <param name="fileBytes">ファイル全体のバイト列</param>
/// <param name="password">パスワード</param>
/// <param name="plainText">復号された平文 JSON</param>
/// <returns>復号に成功した場合 true</returns>
public bool VerifyPassword(byte[] fileBytes, string password, out string plainText)
{
plainText = string.Empty;
var plain = TryDecrypt(fileBytes, password);
if (plain == null)
{
return false;
}
plainText = plain;
return true;
}
/// <summary>
/// ES3 の AES-128-CBC 形式で復号を試みます。
/// ファイル先頭 16 バイトを IV、残りを暗号文として扱い、鍵はパスワード UTF-8 の先頭 16 バイトをゼロ埋めします。
/// </summary>
/// <param name="fileBytes">ファイル全体のバイト列</param>
/// <param name="password">パスワード</param>
/// <returns>復号された平文 JSON。失敗時は null</returns>
public static string? TryDecrypt(byte[] fileBytes, string password)
{
if (fileBytes == null || fileBytes.Length <= AesIvLength)
{
return null;
}
try
{
var iv = new byte[AesIvLength];
Array.Copy(fileBytes, 0, iv, 0, AesIvLength);
var cipher = new byte[fileBytes.Length - AesIvLength];
Array.Copy(fileBytes, AesIvLength, cipher, 0, cipher.Length);
using var aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = DeriveKey(password);
aes.IV = iv;
using var decryptor = aes.CreateDecryptor();
var plain = decryptor.TransformFinalBlock(cipher, 0, cipher.Length);
var text = Encoding.UTF8.GetString(plain);
return IsPlausiblePlainText(text) ? text : null;
}
catch
{
return null;
}
}
/// <summary>
/// 平文バイト列を ES3 の AES-128-CBC 形式で暗号化します(IV を先頭に付与)。
/// </summary>
/// <param name="plainBytes">平文バイト列</param>
/// <param name="password">パスワード</param>
/// <returns>IV + 暗号文のバイト列</returns>
public static byte[] Encrypt(byte[] plainBytes, string password)
{
using var aes = Aes.Create();
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = DeriveKey(password);
aes.GenerateIV();
using var encryptor = aes.CreateEncryptor();
var cipher = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
var result = new byte[aes.IV.Length + cipher.Length];
Array.Copy(aes.IV, 0, result, 0, aes.IV.Length);
Array.Copy(cipher, 0, result, aes.IV.Length, cipher.Length);
return result;
}
/// <summary>
/// パスワード文字列から AES-128 用の 16 バイト鍵を導出します。
/// </summary>
/// <param name="password">パスワード</param>
/// <returns>16 バイトの鍵</returns>
private static byte[] DeriveKey(string password)
{
var raw = Encoding.UTF8.GetBytes(password ?? string.Empty);
var key = new byte[16];
Array.Copy(raw, key, Math.Min(raw.Length, key.Length));
return key;
}
/// <summary>
/// 復号結果が ES3 の平文として妥当かを判定します。
/// </summary>
/// <param name="text">復号された文字列</param>
/// <returns>妥当な場合 true</returns>
private static bool IsPlausiblePlainText(string text)
{
if (string.IsNullOrWhiteSpace(text) || text.Length < MinimumPlainTextLength)
{
return false;
}
var trimmed = text.TrimStart();
if (trimmed.StartsWith('{') || trimmed.StartsWith('['))
{
return true;
}
// ES3 の内部シリアライズ形式は "__type" を必ず含む
return text.Contains("__type", StringComparison.Ordinal);
}
/// <summary>
/// バイト列が平文 JSON かどうかを判定します。
/// </summary>
/// <param name="bytes">対象バイト列</param>
/// <returns>平文 JSON と判断できる場合 true</returns>
private static bool IsLikelyJson(byte[] bytes)
{
try
{
int length = Math.Min(bytes.Length, 64);
var head = Encoding.UTF8.GetString(bytes, 0, length).TrimStart();
return head.StartsWith('{') || head.StartsWith('[');
}
catch
{
return false;
}
}
/// <summary>
/// バイト列のシャノンエントロピー(bits/byte)を算出します。
/// </summary>
/// <param name="bytes">対象バイト列</param>
/// <returns>エントロピー値</returns>
private static double CalculateEntropy(byte[] bytes)
{
var frequency = new int[256];
foreach (var b in bytes)
{
frequency[b]++;
}
double entropy = 0.0;
foreach (var count in frequency)
{
if (count == 0)
{
continue;
}
double p = (double)count / bytes.Length;
entropy -= p * Math.Log2(p);
}
return entropy;
}
/// <summary>
/// 学習キャッシュ用のキーを生成します。
/// </summary>
/// <param name="gameKey">ゲーム識別キー</param>
/// <param name="saveFilePath">セーブファイルパス</param>
/// <returns>キャッシュキー</returns>
private string BuildCacheKey(string? gameKey, string saveFilePath)
{
var key = !string.IsNullOrWhiteSpace(gameKey)
? gameKey!
: Path.GetDirectoryName(saveFilePath) ?? string.Empty;
return key.Trim();
}
/// <summary>
/// 解決済みパスワードを学習キャッシュへ保存します。
/// </summary>
/// <param name="cacheKey">キャッシュキー</param>
/// <param name="password">パスワード</param>
private void Remember(string? cacheKey, string password)
{
if (string.IsNullOrEmpty(cacheKey))
{
return;
}
this._store.Set(cacheKey, password);
}
/// <summary>
/// 辞書段階で試行する候補列挙子を返します(既定候補 → ユーザー辞書の順)。
/// </summary>
/// <param name="userDictionaryPath">ユーザー辞書ファイルのパス</param>
/// <param name="diagnostics">診断メッセージの追加先</param>
/// <returns>候補の列挙</returns>
private IEnumerable<string> EnumerateDictionaryCandidates(string? userDictionaryPath, List<string> diagnostics)
{
var seen = new HashSet<string>(StringComparer.Ordinal);
foreach (var candidate in GetBuiltInCandidates())
{
if (seen.Add(candidate))
{
yield return candidate;
}
}
if (string.IsNullOrWhiteSpace(userDictionaryPath))
{
yield break;
}
if (!File.Exists(userDictionaryPath))
{
diagnostics.Add($"ユーザー辞書が見つかりません: {userDictionaryPath}");
yield break;
}
string[] lines;
try
{
lines = File.ReadAllLines(userDictionaryPath, Encoding.UTF8);
}
catch (Exception ex)
{
diagnostics.Add($"ユーザー辞書の読み込みに失敗しました: {ex.Message}");
yield break;
}
diagnostics.Add($"ユーザー辞書を適用します({lines.Length} 行): {userDictionaryPath}");
foreach (var line in lines)
{
var candidate = line.Trim();
if (candidate.Length == 0 || candidate.StartsWith('#'))
{
continue;
}
if (seen.Add(candidate))
{
yield return candidate;
}
}
}
/// <summary>
/// Easy Save 3 でよく使われる既定のパスワード候補を返します。
/// </summary>
/// <returns>既定候補の並び</returns>
private static IEnumerable<string> GetBuiltInCandidates()
{
// 空文字(パスワード未設定のまま暗号化されたケース)を最初に試す
yield return string.Empty;
yield return "password";
yield return "Password";
yield return "PASSWORD";
yield return "Moodkie";
yield return "moodkie";
yield return "EasySave";
yield return "easysave";
yield return "EasySave3";
yield return "es3";
yield return "ES3";
yield return "SaveData";
yield return "savedata";
yield return "Save";
yield return "save";
yield return "secret";
yield return "Secret";
yield return "123456";
yield return "1234567890";
yield return "admin";
yield return "test";
yield return "game";
yield return "Game";
}
/// <summary>
/// 診断ログ用にパスワードをマスクします(先頭 2 文字のみ残す)。
/// </summary>
/// <param name="password">パスワード</param>
/// <returns>マスク済み文字列</returns>
private static string Mask(string password)
{
if (string.IsNullOrEmpty(password))
{
return "(空)";
}
if (password.Length <= 2)
{
return new string('*', password.Length);
}
return password[..2] + new string('*', Math.Min(password.Length - 2, 8));
}
}
}
+214
View File
@@ -0,0 +1,214 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
using GameLauncher.Helpers;
namespace GameLauncher.Services.Codecs.Es3
{
/// <summary>
/// ES3 のパスワード特定結果を「ゲーム単位」で永続化する学習キャッシュ。
///
/// 一度解決したパスワードを保存しておくことで、次回以降は自動適用できます。
/// 保存先は exe 直下の <c>es3-passwords.json</c> で、キャッシュ破棄やブックマークとは独立に管理します。
/// </summary>
public sealed class Es3PasswordStore
{
/// <summary>永続化ファイル名。</summary>
private const string FileName = "es3-passwords.json";
/// <summary>既定のシングルトンインスタンス。</summary>
public static Es3PasswordStore Instance { get; } = new();
private readonly object _syncRoot = new();
private readonly string _filePath;
private Dictionary<string, string>? _entries;
/// <summary>
/// exe 直下の既定パスを用いて <see cref="Es3PasswordStore"/> を初期化します。
/// </summary>
public Es3PasswordStore()
: this(Path.Combine(AppPathHelper.GetExeDirectory(), FileName))
{
}
/// <summary>
/// 任意のファイルパスを指定して <see cref="Es3PasswordStore"/> を初期化します(テスト用途を含む)。
/// </summary>
/// <param name="filePath">永続化ファイルの絶対パス</param>
public Es3PasswordStore(string filePath)
{
this._filePath = filePath;
}
/// <summary>
/// 永続化ファイルのパスを取得します。
/// </summary>
public string FilePath => this._filePath;
/// <summary>
/// 指定キーに対応する学習済みパスワードを取得します。
/// </summary>
/// <param name="key">ゲーム単位のキー(通常はゲームのルートディレクトリ)</param>
/// <returns>保存済みパスワード。未登録の場合は null</returns>
public string? TryGet(string key)
{
if (string.IsNullOrWhiteSpace(key))
{
return null;
}
lock (this._syncRoot)
{
var entries = this.LoadEntries();
return entries.TryGetValue(Normalize(key), out var password) ? password : null;
}
}
/// <summary>
/// 学習済みパスワードを保存します。
/// </summary>
/// <param name="key">ゲーム単位のキー</param>
/// <param name="password">保存するパスワード(空文字も有効な値として保存します)</param>
public void Set(string key, string password)
{
if (string.IsNullOrWhiteSpace(key))
{
return;
}
lock (this._syncRoot)
{
var entries = this.LoadEntries();
entries[Normalize(key)] = password ?? string.Empty;
this.SaveEntries(entries);
}
}
/// <summary>
/// 指定キーの学習済みパスワードを削除します。
/// </summary>
/// <param name="key">ゲーム単位のキー</param>
/// <returns>削除できた場合 true</returns>
public bool Remove(string key)
{
if (string.IsNullOrWhiteSpace(key))
{
return false;
}
lock (this._syncRoot)
{
var entries = this.LoadEntries();
if (!entries.Remove(Normalize(key)))
{
return false;
}
this.SaveEntries(entries);
return true;
}
}
/// <summary>
/// 保存済みエントリのスナップショットを取得します(表示・診断用)。
/// </summary>
/// <returns>キーとパスワードの読み取り専用ディクショナリ</returns>
public IReadOnlyDictionary<string, string> Snapshot()
{
lock (this._syncRoot)
{
return new Dictionary<string, string>(this.LoadEntries(), StringComparer.OrdinalIgnoreCase);
}
}
/// <summary>
/// 永続化ファイルを読み込みます。壊れている場合は空のディクショナリを返します。
/// </summary>
/// <returns>読み込んだエントリ</returns>
private Dictionary<string, string> LoadEntries()
{
if (this._entries != null)
{
return this._entries;
}
var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
try
{
if (File.Exists(this._filePath))
{
var json = File.ReadAllText(this._filePath, Encoding.UTF8);
if (!string.IsNullOrWhiteSpace(json))
{
var loaded = JsonSerializer.Deserialize<Dictionary<string, string>>(json);
if (loaded != null)
{
foreach (var kvp in loaded)
{
if (!string.IsNullOrWhiteSpace(kvp.Key))
{
result[Normalize(kvp.Key)] = kvp.Value ?? string.Empty;
}
}
}
}
}
}
catch
{
// 破損ファイルは無視し、空の状態から再構築する
result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
this._entries = result;
return this._entries;
}
/// <summary>
/// エントリを永続化ファイルへ書き出します。
/// </summary>
/// <param name="entries">書き出すエントリ</param>
private void SaveEntries(Dictionary<string, string> entries)
{
try
{
var directory = Path.GetDirectoryName(this._filePath);
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
var options = new JsonSerializerOptions { WriteIndented = true };
var json = JsonSerializer.Serialize(entries, options);
// BOM なし UTF-8 で保存する
File.WriteAllText(this._filePath, json, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
}
catch
{
// 保存失敗は致命的ではないため握りつぶす(次回再度解決を試みる)
}
}
/// <summary>
/// キーを比較用に正規化します(パス区切りと大文字小文字の揺れを吸収)。
/// </summary>
/// <param name="key">元のキー</param>
/// <returns>正規化済みキー</returns>
private static string Normalize(string key)
{
var trimmed = key.Trim();
try
{
return Path.GetFullPath(trimmed).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
catch
{
return trimmed;
}
}
}
}
+891
View File
@@ -0,0 +1,891 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace GameLauncher.Services.Codecs.Es3
{
/// <summary>
/// ES3 のシリアライズ要素が持つ「型」の種別。
/// ES3 は <c>{ "__type": "System.Int32", "value": 42 }</c> 形式で値を格納するため、
/// この列挙子で GUI 側へ型情報を伝えます。
/// </summary>
public enum Es3ValueKind
{
/// <summary>不明・未判定。</summary>
Unknown,
/// <summary>真偽値。</summary>
Boolean,
/// <summary>整数(Int32 / Int64 / UInt32 等)。</summary>
Integer,
/// <summary>浮動小数(Single / Double / Decimal)。</summary>
Float,
/// <summary>文字列。</summary>
String,
/// <summary>列挙体。</summary>
Enum,
/// <summary>配列。</summary>
Array,
/// <summary>辞書(キーと値の組)。</summary>
Dictionary,
/// <summary>入れ子オブジェクト。</summary>
Object
}
/// <summary>
/// ES3 ファイル内の 1 項目を表す型付きノード。
/// JSON ツリー上の位置(<see cref="Path"/>)を保持するため、編集後の書き戻しが安全に行えます。
/// </summary>
public sealed class Es3Node
{
/// <summary>キー名(辞書・オブジェクトの子の場合)。</summary>
public string Key { get; set; } = string.Empty;
/// <summary>親をたどる JSON パス(例: <c>$.player.stats.hp</c>)。</summary>
public string Path { get; set; } = "$";
/// <summary>ES3 が示す型名(例: <c>System.Int32</c>、<c>System.Collections.Generic.List`1</c>)。</summary>
public string TypeName { get; set; } = string.Empty;
/// <summary>判定した値種別。</summary>
public Es3ValueKind Kind { get; set; } = Es3ValueKind.Unknown;
/// <summary>現在の値(文字列化した表示・編集用の値)。</summary>
public string DisplayValue { get; set; } = string.Empty;
/// <summary>元の JSON 値(書き戻し時の型再現に使用)。</summary>
public JsonNode? OriginalNode { get; set; }
/// <summary>配列・辞書・オブジェクトの場合の子要素。</summary>
public List<Es3Node> Children { get; } = [];
/// <summary>子要素を持つか。</summary>
public bool HasChildren => this.Children.Count > 0;
/// <summary>エディタで直接値を編集できる型か。</summary>
public bool IsEditable => this.Kind is Es3ValueKind.Boolean
or Es3ValueKind.Integer
or Es3ValueKind.Float
or Es3ValueKind.String
or Es3ValueKind.Enum;
}
/// <summary>
/// ES3 (Easy Save 3) のセーブデータ本体(復号後の JSON)を解析し、
/// キー名・型・値を読み取るとともに、編集結果を安全に書き戻すパーサ/ライタ。
///
/// ES3 の内部形式は次の 2 通りが混在します:
/// <c>{ "key": { "__type": "System.Int32", "value": 100 } }</c>
/// <c>{ "key": { "__type": "System.Collections.Generic.Dictionary`2[...]", "value": { ... } } }</c>
/// 本クラスは両形式を展開し、編集後は元の型情報を保持したまま再構築します。
/// </summary>
public sealed class Es3SaveDocument
{
/// <summary>ES3 が型情報を格納するプロパティ名。</summary>
public const string TypePropertyName = "__type";
/// <summary>ES3 が値を格納するプロパティ名。</summary>
public const string ValuePropertyName = "value";
/// <summary>解析対象のルート JSON オブジェクト(編集はこのインスタンスを直接書き換えます)。</summary>
private JsonNode? _root;
/// <summary>復号直後の JSON 文字列(差分検出・バックアップ用)。</summary>
public string OriginalJson { get; private set; } = string.Empty;
/// <summary>解析に成功したか。</summary>
public bool IsLoaded => this._root != null;
/// <summary>解析時の警告(解釈できなかった要素など)。</summary>
public List<string> Warnings { get; } = [];
/// <summary>ルート直下の項目一覧。</summary>
public List<Es3Node> RootNodes { get; } = [];
/// <summary>
/// ES3 の平文 JSON 文字列を解析してドキュメントを構築します。
/// </summary>
/// <param name="json">復号済みの平文 JSON</param>
/// <returns>解析されたドキュメント</returns>
public static Es3SaveDocument Parse(string json)
{
var document = new Es3SaveDocument { OriginalJson = json ?? string.Empty };
if (string.IsNullOrWhiteSpace(json))
{
document.Warnings.Add("平文 JSON が空です。");
return document;
}
JsonNode? root;
try
{
root = JsonNode.Parse(json, documentOptions: new JsonDocumentOptions
{
AllowTrailingCommas = true,
CommentHandling = JsonCommentHandling.Skip,
MaxDepth = 256
});
}
catch (JsonException ex)
{
document.Warnings.Add($"JSON 解析に失敗しました: {ex.Message}");
return document;
}
if (root == null)
{
document.Warnings.Add("JSON のルートが null です。");
return document;
}
document._root = root;
document.BuildTree(root, "$", string.Empty);
return document;
}
/// <summary>
/// 解析ツリーを走査してルート直下の項目一覧を構築します。
/// </summary>
/// <param name="root">JSON ルート</param>
/// <param name="path">ルートパス</param>
/// <param name="key">キー名</param>
private void BuildTree(JsonNode root, string path, string key)
{
if (root is JsonObject rootObject)
{
foreach (var kvp in rootObject)
{
var childPath = $"{path}.{kvp.Key}";
var node = this.CreateNode(kvp.Key, childPath, kvp.Value);
if (node != null)
{
this.RootNodes.Add(node);
}
}
return;
}
if (root is JsonArray rootArray)
{
for (int i = 0; i < rootArray.Count; i++)
{
var childPath = $"{path}[{i}]";
var node = this.CreateNode($"[{i}]", childPath, rootArray[i]);
if (node != null)
{
this.RootNodes.Add(node);
}
}
return;
}
this.Warnings.Add($"ルート要素を解釈できませんでした({root.GetValueKind()})。");
}
/// <summary>
/// JSON ノードから型付きの <see cref="Es3Node"/> を生成します。
/// </summary>
/// <param name="key">キー名</param>
/// <param name="path">JSON パス</param>
/// <param name="node">対象ノード</param>
/// <returns>生成されたノード。解釈不能な場合は null</returns>
private Es3Node? CreateNode(string key, string path, JsonNode? node)
{
var result = new Es3Node
{
Key = key,
Path = path,
OriginalNode = node
};
if (node == null)
{
result.Kind = Es3ValueKind.Unknown;
result.DisplayValue = "null";
return result;
}
switch (node.GetValueKind())
{
case JsonValueKind.Object:
this.PopulateObject(result, path, node.AsObject());
return result;
case JsonValueKind.Array:
result.Kind = Es3ValueKind.Array;
result.TypeName = "System.Array";
PopulateArray(result, path, node.AsArray());
return result;
case JsonValueKind.String:
result.Kind = Es3ValueKind.String;
result.TypeName = "System.String";
result.DisplayValue = node.GetValue<string>();
return result;
case JsonValueKind.Number:
PopulateNumber(result, node);
return result;
case JsonValueKind.True:
case JsonValueKind.False:
result.Kind = Es3ValueKind.Boolean;
result.TypeName = "System.Boolean";
result.DisplayValue = node.GetValue<bool>() ? "true" : "false";
return result;
case JsonValueKind.Null:
result.Kind = Es3ValueKind.Unknown;
result.DisplayValue = "null";
return result;
default:
result.Kind = Es3ValueKind.Unknown;
result.DisplayValue = node.ToJsonString();
return result;
}
}
/// <summary>
/// JSON オブジェクトが ES3 の型付き要素か、単なる入れ子オブジェクトかを判定して展開します。
/// </summary>
/// <param name="target">構築対象のノード</param>
/// <param name="path">JSON パス</param>
/// <param name="jsonObject">対象の JSON オブジェクト</param>
private void PopulateObject(Es3Node target, string path, JsonObject jsonObject)
{
// ES3 の型付き要素(__type と value を持つ)か判定
bool isTyped = jsonObject.ContainsKey(TypePropertyName);
if (isTyped)
{
target.TypeName = jsonObject[TypePropertyName]?.GetValue<string>() ?? string.Empty;
var inner = jsonObject[ValuePropertyName];
if (inner == null)
{
target.Kind = MapTypeNameToKind(target.TypeName);
target.DisplayValue = "null";
return;
}
var innerKind = inner.GetValueKind();
if (innerKind == JsonValueKind.Object)
{
// 辞書・入れ子オブジェクト
var innerObject = inner.AsObject();
target.Kind = LooksLikeDictionary(innerObject, target.TypeName)
? Es3ValueKind.Dictionary
: Es3ValueKind.Object;
foreach (var kvp in innerObject)
{
var childPath = $"{path}.{kvp.Key}";
var child = this.CreateNode(kvp.Key, childPath, kvp.Value);
if (child != null)
{
target.Children.Add(child);
}
}
target.DisplayValue = $"({target.Children.Count} 項目)";
return;
}
if (innerKind == JsonValueKind.Array)
{
target.Kind = Es3ValueKind.Array;
PopulateArray(target, path, inner.AsArray());
return;
}
// プリミティブ値
target.Kind = MapTypeNameToKind(target.TypeName);
target.DisplayValue = FormatScalar(inner, target.Kind);
return;
}
// 型情報なしの入れ子オブジェクト
target.Kind = Es3ValueKind.Object;
target.TypeName = "System.Object";
foreach (var kvp in jsonObject)
{
var childPath = $"{path}.{kvp.Key}";
var child = this.CreateNode(kvp.Key, childPath, kvp.Value);
if (child != null)
{
target.Children.Add(child);
}
}
target.DisplayValue = $"({target.Children.Count} 項目)";
}
/// <summary>
/// 配列を走査して子要素を追加します。
/// </summary>
/// <param name="target">構築対象のノード</param>
/// <param name="path">JSON パス</param>
/// <param name="array">対象の JSON 配列</param>
private static void PopulateArray(Es3Node target, string path, JsonArray array)
{
for (int i = 0; i < array.Count; i++)
{
var childPath = $"{path}[{i}]";
var elementNode = array[i];
var child = new Es3Node
{
Key = $"[{i}]",
Path = childPath,
OriginalNode = elementNode
};
if (elementNode == null)
{
child.Kind = Es3ValueKind.Unknown;
child.DisplayValue = "null";
}
else if (elementNode.GetValueKind() == JsonValueKind.Object &&
elementNode.AsObject().ContainsKey(TypePropertyName))
{
// 配列要素が型付き要素の場合は再帰的に展開する
var innerObject = elementNode.AsObject();
child.TypeName = innerObject[TypePropertyName]?.GetValue<string>() ?? string.Empty;
var inner = innerObject[ValuePropertyName];
if (inner != null && inner.GetValueKind() == JsonValueKind.Object)
{
child.Kind = Es3ValueKind.Object;
foreach (var kvp in inner.AsObject())
{
var grandChild = new Es3Node
{
Key = kvp.Key,
Path = $"{childPath}.{kvp.Key}",
OriginalNode = kvp.Value,
Kind = MapValueKind(kvp.Value),
DisplayValue = FormatScalar(kvp.Value, MapValueKind(kvp.Value))
};
child.Children.Add(grandChild);
}
child.DisplayValue = $"({child.Children.Count} 項目)";
}
else
{
child.Kind = MapTypeNameToKind(child.TypeName);
child.DisplayValue = inner == null ? "null" : FormatScalar(inner, child.Kind);
}
}
else
{
child.Kind = MapValueKind(elementNode);
child.DisplayValue = FormatScalar(elementNode, child.Kind);
}
target.Children.Add(child);
}
target.DisplayValue = $"({target.Children.Count} 件)";
}
/// <summary>
/// 数値ノードの型情報と表示値を設定します。
/// </summary>
/// <param name="target">構築対象のノード</param>
/// <param name="node">数値ノード</param>
private void PopulateNumber(Es3Node target, JsonNode node)
{
var raw = node.ToJsonString();
if (raw.Contains('.') || raw.Contains('e', StringComparison.OrdinalIgnoreCase) &&
!raw.Contains("0x", StringComparison.OrdinalIgnoreCase))
{
target.Kind = Es3ValueKind.Float;
target.TypeName = "System.Single";
}
else
{
target.Kind = Es3ValueKind.Integer;
target.TypeName = "System.Int32";
}
target.DisplayValue = raw;
}
/// <summary>
/// ES3 の型名から値種別を推定します。
/// </summary>
/// <param name="typeName">ES3 の型名</param>
/// <returns>推定した値種別</returns>
public static Es3ValueKind MapTypeNameToKind(string typeName)
{
if (string.IsNullOrEmpty(typeName))
{
return Es3ValueKind.Unknown;
}
var normalized = typeName.Replace(" ", string.Empty);
if (normalized.Contains("System.Boolean", StringComparison.Ordinal))
{
return Es3ValueKind.Boolean;
}
if (normalized.Contains("System.Single", StringComparison.Ordinal) ||
normalized.Contains("System.Double", StringComparison.Ordinal) ||
normalized.Contains("System.Decimal", StringComparison.Ordinal))
{
return Es3ValueKind.Float;
}
if (normalized.Contains("System.Int", StringComparison.Ordinal) ||
normalized.Contains("System.UInt", StringComparison.Ordinal) ||
normalized.Contains("System.Byte", StringComparison.Ordinal) ||
normalized.Contains("System.Int64", StringComparison.Ordinal) ||
normalized.Contains("System.Int16", StringComparison.Ordinal))
{
return Es3ValueKind.Integer;
}
if (normalized.Contains("System.String", StringComparison.Ordinal) ||
normalized.Contains("System.Char", StringComparison.Ordinal))
{
return Es3ValueKind.String;
}
if (normalized.Contains("Dictionary", StringComparison.Ordinal))
{
return Es3ValueKind.Dictionary;
}
if (normalized.Contains("[]", StringComparison.Ordinal) ||
normalized.Contains("List`1", StringComparison.Ordinal) ||
normalized.Contains("HashSet", StringComparison.Ordinal))
{
return Es3ValueKind.Array;
}
if (normalized.Contains("System.Enum", StringComparison.Ordinal))
{
return Es3ValueKind.Enum;
}
return Es3ValueKind.Object;
}
/// <summary>
/// 辞書形式(キーと値の組)かどうかを推定します。
/// </summary>
/// <param name="jsonObject">対象オブジェクト</param>
/// <param name="typeName">型名</param>
/// <returns>辞書と判断できる場合 true</returns>
private static bool LooksLikeDictionary(JsonObject jsonObject, string typeName)
{
if (!string.IsNullOrEmpty(typeName) &&
typeName.Contains("Dictionary", StringComparison.Ordinal))
{
return true;
}
// ES3 の辞書は {"key": "...", "value": ...} の対を持つ
return jsonObject.ContainsKey("key") && jsonObject.ContainsKey(ValuePropertyName);
}
/// <summary>
/// JSON 値の種別を簡易判定します。
/// </summary>
/// <param name="node">対象ノード</param>
/// <returns>判定した値種別</returns>
private static Es3ValueKind MapValueKind(JsonNode? node)
{
if (node == null)
{
return Es3ValueKind.Unknown;
}
return node.GetValueKind() switch
{
JsonValueKind.Object => Es3ValueKind.Object,
JsonValueKind.Array => Es3ValueKind.Array,
JsonValueKind.String => Es3ValueKind.String,
JsonValueKind.Number => node.ToJsonString().Contains('.')
? Es3ValueKind.Float
: Es3ValueKind.Integer,
JsonValueKind.True or JsonValueKind.False => Es3ValueKind.Boolean,
_ => Es3ValueKind.Unknown
};
}
/// <summary>
/// スカラー値を表示用文字列へ整形します。
/// </summary>
/// <param name="node">対象ノード</param>
/// <param name="kind">値種別</param>
/// <returns>表示用文字列</returns>
private static string FormatScalar(JsonNode? node, Es3ValueKind kind)
{
if (node == null)
{
return "null";
}
try
{
return kind switch
{
Es3ValueKind.Boolean => node.GetValue<bool>() ? "true" : "false",
Es3ValueKind.String => node.GetValue<string>(),
Es3ValueKind.Enum => node.GetValueKind() == JsonValueKind.Number
? node.ToJsonString()
: node.GetValue<string>(),
_ => node.ToJsonString()
};
}
catch
{
return node.ToJsonString();
}
}
/// <summary>
/// 指定パスのノードへ編集値を適用します。
/// </summary>
/// <param name="path">JSON パス(<see cref="Es3Node.Path"/>)</param>
/// <param name="newValue">新しい値(表示文字列)</param>
/// <param name="error">失敗理由</param>
/// <returns>適用に成功した場合 true</returns>
public bool TrySetValue(string path, string newValue, out string error)
{
error = string.Empty;
if (this._root == null)
{
error = "ドキュメントが読み込まれていません。";
return false;
}
if (!this.TryResolveParent(path, out var parent, out var key, out error))
{
return false;
}
// 既存ノードから型情報を取得
var existing = this.FindNode(path);
var kind = existing?.Kind ?? Es3ValueKind.String;
var typeName = existing?.TypeName ?? "System.String";
if (existing != null && !existing.IsEditable)
{
error = $"型 {typeName} は直接編集できません。";
return false;
}
JsonNode? parsed = this.BuildValueNode(newValue, kind, typeName, out error);
if (parsed == null)
{
return false;
}
try
{
// ES3 の型付き要素として書き戻す
if (parent is JsonObject parentObject && parentObject.ContainsKey(TypePropertyName))
{
parentObject[ValuePropertyName] = parsed;
}
else if (parent is JsonObject plainObject)
{
plainObject[key] = parsed;
}
else if (parent is JsonArray array && int.TryParse(key, out int index) &&
index >= 0 && index < array.Count)
{
array[index] = parsed;
}
else
{
error = "書き戻し先の親要素を特定できませんでした。";
return false;
}
return true;
}
catch (Exception ex)
{
error = $"書き戻しに失敗しました: {ex.Message}";
return false;
}
}
/// <summary>
/// 編集後の JSON を文字列として取得します。
/// </summary>
/// <returns>整形済み JSON 文字列</returns>
public string ToJson()
{
if (this._root == null)
{
return this.OriginalJson;
}
return this._root.ToJsonString(new JsonSerializerOptions { WriteIndented = false });
}
/// <summary>
/// 元の JSON から変更があったかを判定します。
/// </summary>
/// <returns>変更がある場合 true</returns>
public bool HasChanges()
{
if (this._root == null)
{
return false;
}
return !string.Equals(this.ToJson(), this.OriginalJson, StringComparison.Ordinal);
}
/// <summary>
/// パスから親ノードと最終キーを解決します。
/// </summary>
/// <param name="path">JSON パス</param>
/// <param name="parent">親ノード</param>
/// <param name="key">最終キー(配列の場合はインデックス文字列)</param>
/// <param name="error">失敗理由</param>
/// <returns>解決に成功した場合 true</returns>
private bool TryResolveParent(string path, out JsonNode? parent, out string key, out string error)
{
parent = null;
key = string.Empty;
error = string.Empty;
if (path == "$")
{
error = "ルート要素は編集できません。";
return false;
}
var segments = SplitPath(path);
if (segments.Count < 2)
{
error = $"パスの解析に失敗しました: {path}";
return false;
}
JsonNode? current = this._root;
for (int i = 1; i < segments.Count - 1; i++)
{
if (current == null)
{
break;
}
current = Descend(current, segments[i], out _);
}
if (current == null)
{
error = $"パス {path} を解決できませんでした。";
return false;
}
key = segments[^1];
parent = current;
return true;
}
/// <summary>
/// パス文字列をセグメントへ分割します。
/// </summary>
/// <param name="path">JSON パス</param>
/// <returns>セグメント一覧(先頭は "$")</returns>
private static List<string> SplitPath(string path)
{
var segments = new List<string>();
var buffer = new StringBuilder();
foreach (var ch in path)
{
if (ch == '.' || ch == '[' || ch == ']')
{
if (buffer.Length > 0)
{
segments.Add(buffer.ToString());
buffer.Clear();
}
continue;
}
buffer.Append(ch);
}
if (buffer.Length > 0)
{
segments.Add(buffer.ToString());
}
return segments;
}
/// <summary>
/// 指定キーで子要素へ降下します(ES3 の型付き要素は value を透過します)。
/// </summary>
/// <param name="current">現在のノード</param>
/// <param name="key">キー</param>
/// <param name="found">見つかった子ノード</param>
/// <returns>降下先ノード。見つからない場合は null</returns>
private static JsonNode? Descend(JsonNode current, string key, out JsonNode? found)
{
found = null;
if (current is JsonObject obj)
{
// ES3 の型付き要素は value の中身を透過的に扱う
if (obj.ContainsKey(TypePropertyName) && obj[ValuePropertyName] is JsonNode inner)
{
return Descend(inner, key, out found);
}
if (obj.TryGetPropertyValue(key, out var child))
{
found = child;
return child;
}
return null;
}
if (current is JsonArray array && int.TryParse(key, out int index) &&
index >= 0 && index < array.Count)
{
found = array[index];
return array[index];
}
return null;
}
/// <summary>
/// 指定パスに対応するノードを探索します。
/// </summary>
/// <param name="path">JSON パス</param>
/// <returns>見つかったノード。見つからない場合は null</returns>
private Es3Node? FindNode(string path)
{
return FindNodeRecursive(this.RootNodes, path);
}
/// <summary>
/// ノードツリーを再帰的に探索します。
/// </summary>
/// <param name="nodes">探索対象</param>
/// <param name="path">JSON パス</param>
/// <returns>見つかったノード</returns>
private static Es3Node? FindNodeRecursive(List<Es3Node> nodes, string path)
{
foreach (var node in nodes)
{
if (node.Path == path)
{
return node;
}
var found = FindNodeRecursive(node.Children, path);
if (found != null)
{
return found;
}
}
return null;
}
/// <summary>
/// 編集値から実際の JSON ノードを構築します。
/// </summary>
/// <param name="newValue">編集された値文字列</param>
/// <param name="kind">型種別</param>
/// <param name="typeName">ES3 の型名</param>
/// <param name="error">失敗理由</param>
/// <returns>構築された JSON ノード。失敗時は null</returns>
private JsonNode? BuildValueNode(string newValue, Es3ValueKind kind, string typeName, out string error)
{
error = string.Empty;
switch (kind)
{
case Es3ValueKind.Boolean:
if (bool.TryParse(newValue, out var boolValue))
{
return JsonValue.Create(boolValue);
}
if (newValue.Trim() == "1")
{
return JsonValue.Create(true);
}
if (newValue.Trim() == "0")
{
return JsonValue.Create(false);
}
error = $"真偽値として解釈できません: {newValue}";
return null;
case Es3ValueKind.Integer:
if (long.TryParse(newValue.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var longValue))
{
return JsonValue.Create(longValue);
}
error = $"整数として解釈できません: {newValue}";
return null;
case Es3ValueKind.Float:
if (double.TryParse(newValue.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var doubleValue))
{
return JsonValue.Create(doubleValue);
}
error = $"小数として解釈できません: {newValue}";
return null;
case Es3ValueKind.Enum:
// 列挙体は元が数値なら数値、文字列なら文字列として保持する
if (long.TryParse(newValue.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var enumNumeric))
{
return JsonValue.Create(enumNumeric);
}
return JsonValue.Create(newValue);
case Es3ValueKind.String:
return JsonValue.Create(newValue);
default:
error = $"型 {typeName} は直接編集できません。";
return null;
}
}
}
}
+407 -80
View File
@@ -22,6 +22,7 @@ using GameLauncher.Engines.Tyrano;
using GameLauncher.Engines.Wolf;
using GameLauncher.Engines.Unity;
using GameLauncher.Engines.Nwjs;
using GameLauncher.Engines.Bakin;
using GameLauncher.Engines.Common;
using GameLauncher.Engines.Evb;
@@ -66,6 +67,8 @@ namespace GameLauncher.Services
public string? RgssArchivePath { get; set; }
public bool HasWolfArchive { get; set; }
public bool IsWolfExtracted { get; set; }
public bool MzPixiErrorFix { get; set; } = true;
public bool MzSpineErrorFix { get; set; } = true;
public bool WolfProxyDll { get; set; }
public double WolfSpeedMultiplier { get; set; } = 3.0;
public bool HasSrpgArchive { get; set; }
@@ -118,8 +121,10 @@ namespace GameLauncher.Services
/// <summary>
/// エンジン判定ロジックのバージョン。判定条件を変更したらこの値をインクリメントすると、
/// 既存キャッシュは自動的に無効化され、次回起動時に再スキャンされます。
/// v3: Unity製ゲームが「その他」として誤分類されたままキャッシュに残る問題を解消するため、
/// Unity証拠(UnityPlayer.dll / *_Data / UnityCrashHandler*.exe)を再評価して再分類します。
/// </summary>
private const int CurrentEngineLogicVersion = 2;
private const int CurrentEngineLogicVersion = 3;
static GameScannerService()
{
@@ -162,42 +167,63 @@ namespace GameLauncher.Services
}
if (entries != null)
{
bool cacheRepaired = false;
foreach (var entry in entries)
{
if (entry.EngineKind == (int)GameEngineKind.Unity)
{
var exePath = entry.ExecutablePath;
if (!string.IsNullOrEmpty(exePath) && IsExcludedExe(exePath))
{
exePath = FindGameExecutable(entry.RootDirectory) ?? string.Empty;
if (exePath != entry.ExecutablePath)
{
cacheRepaired = true;
}
}
list.Add(new UnityGameItem
{
Title = entry.Title,
FolderName = entry.FolderName,
RootDirectory = entry.RootDirectory,
ExecutablePath = entry.ExecutablePath,
ExecutablePath = exePath,
DataDirectoryPath = entry.DataDirectoryPath,
CompanyName = entry.CompanyName,
ProductName = entry.ProductName,
BackendType = (UnityBackendType)entry.UnityBackendType,
UnityVersion = entry.UnityVersion,
LastLaunched = entry.LastLaunched,
FolderLastModified = entry.FolderLastModified,
FolderLastModified = exePath != entry.ExecutablePath ? null : entry.FolderLastModified,
IsBookmarked = entry.IsBookmarked,
HasSaveData = entry.HasSaveData
});
}
else
{
var exePath = entry.ExecutablePath;
if (!string.IsNullOrEmpty(exePath) && IsExcludedExe(exePath))
{
exePath = FindGameExecutable(entry.RootDirectory) ?? string.Empty;
if (exePath != entry.ExecutablePath)
{
cacheRepaired = true;
}
}
var item = new TkoolGameItem
{
Title = entry.Title,
FolderName = entry.FolderName,
RootDirectory = entry.RootDirectory,
ExecutablePath = entry.ExecutablePath,
ExecutablePath = exePath,
PluginsJsPath = entry.PluginsJsPath,
PluginsDirPath = entry.PluginsDirPath,
EngineType = (TkoolEngineType)entry.TkoolEngineType,
HasCustomApplyMod = entry.HasCustomApplyMod,
ApplyMod = entry.ApplyMod,
LastLaunched = entry.LastLaunched,
FolderLastModified = entry.FolderLastModified,
FolderLastModified = exePath != entry.ExecutablePath ? null : entry.FolderLastModified,
IsBookmarked = entry.IsBookmarked,
IsModded = entry.IsModded,
IsAsar = entry.IsAsar,
@@ -210,6 +236,8 @@ namespace GameLauncher.Services
RgssArchivePath = entry.RgssArchivePath,
HasWolfArchive = entry.HasWolfArchive,
IsWolfExtracted = entry.IsWolfExtracted,
MzPixiErrorFix = entry.MzPixiErrorFix,
MzSpineErrorFix = entry.MzSpineErrorFix,
WolfProxyDll = entry.WolfProxyDll,
WolfSpeedMultiplier = entry.WolfSpeedMultiplier > 0 ? entry.WolfSpeedMultiplier : 3.0,
HasSrpgArchive = entry.HasSrpgArchive,
@@ -223,18 +251,53 @@ namespace GameLauncher.Services
IsEvbExtracted = entry.IsEvbExtracted,
EvbExtractedDirPath = entry.EvbExtractedDirPath,
EvbBackupPath = entry.EvbBackupPath,
EvbUnderlyingEngine = entry.EvbUnderlyingEngine
EvbUnderlyingEngine = entry.EvbUnderlyingEngine,
HasSaveData = entry.HasSaveData
};
if (entry.PluginSettings != null)
{
item.PluginSettings = new Dictionary<string, bool>(entry.PluginSettings, StringComparer.OrdinalIgnoreCase);
}
if (item.IsOther && BakinDetector.IsBakinGame(item.RootDirectory))
{
item.EngineType = TkoolEngineType.Bakin;
item.HasSaveData = BakinSaveService.HasAnySaveData(item.RootDirectory);
var bakinExe = BakinDetector.FindBakinExecutable(item.RootDirectory, item.FolderName);
if (!string.IsNullOrEmpty(bakinExe))
{
item.ExecutablePath = bakinExe;
}
cacheRepaired = true;
}
else if (item.IsBakin)
{
bool bakinHasSave = BakinSaveService.HasAnySaveData(item.RootDirectory);
if (item.HasSaveData != bakinHasSave)
{
item.HasSaveData = bakinHasSave;
cacheRepaired = true;
}
}
if (item.IsNwjs && string.IsNullOrEmpty(item.PluginsJsPath))
{
item.PluginsJsPath = NwjsDetector.ResolveEntryHtmlPath(item.RootDirectory);
if (!string.IsNullOrEmpty(item.PluginsJsPath))
{
item.PluginsDirPath = Path.GetDirectoryName(item.PluginsJsPath) ?? item.RootDirectory;
item.IsModded = NwjsModService.CheckIsModded(item.PluginsJsPath);
cacheRepaired = true;
}
}
// 起動時のUIブロックを防ぐため、ディスクI/O(実在検証・誤判定修正)はバックグラウンドの
// VerifyAndEnrichGamesAsync に任せ、ここではキャッシュJSONから純粋にメモリ復元します。
list.Add(item);
}
}
if (cacheRepaired)
{
this.SaveCache(list);
}
return list;
}
}
@@ -484,6 +547,8 @@ namespace GameLauncher.Services
RgssArchivePath = tg.RgssArchivePath,
HasWolfArchive = tg.HasWolfArchive,
IsWolfExtracted = tg.IsWolfExtracted,
MzPixiErrorFix = tg.MzPixiErrorFix,
MzSpineErrorFix = tg.MzSpineErrorFix,
WolfProxyDll = tg.WolfProxyDll,
WolfSpeedMultiplier = tg.WolfSpeedMultiplier,
HasSrpgArchive = tg.HasSrpgArchive,
@@ -500,7 +565,8 @@ namespace GameLauncher.Services
IsEvbExtracted = tg.IsEvbExtracted,
EvbExtractedDirPath = tg.EvbExtractedDirPath,
EvbBackupPath = tg.EvbBackupPath,
EvbUnderlyingEngine = tg.EvbUnderlyingEngine
EvbUnderlyingEngine = tg.EvbUnderlyingEngine,
HasSaveData = tg.HasSaveData
});
}
}
@@ -521,6 +587,27 @@ namespace GameLauncher.Services
/// ブックマーク対象ゲームの識別キーを正規化します。
/// タイトル変動に耐えるため、RootDirectory をフルパス化し末尾セパレータを除去した文字列をキーとします。
/// </summary>
private static bool NwjsEnsureMeta(TkoolGameItem tg, ref int cacheNeedsSave)
{
if (string.IsNullOrEmpty(tg.PluginsJsPath) || !File.Exists(tg.PluginsJsPath))
{
tg.PluginsJsPath = NwjsDetector.ResolveEntryHtmlPath(tg.RootDirectory);
tg.PluginsDirPath = !string.IsNullOrEmpty(tg.PluginsJsPath)
? (Path.GetDirectoryName(tg.PluginsJsPath) ?? tg.RootDirectory)
: tg.RootDirectory;
Interlocked.Exchange(ref cacheNeedsSave, 1);
}
bool nwjsHasSave = NwjsSaveService.HasAnySaveData(tg.RootDirectory, tg.FolderName);
if (tg.HasSaveData != nwjsHasSave)
{
tg.HasSaveData = nwjsHasSave;
Interlocked.Exchange(ref cacheNeedsSave, 1);
}
return true;
}
private static string NormalizeBookmarkKey(string rootDirectory)
{
if (string.IsNullOrWhiteSpace(rootDirectory))
@@ -656,9 +743,14 @@ namespace GameLauncher.Services
return;
}
// キャッシュのフォルダ更新日時と完全一致している場合、内部構成(exe/plugins/アーカイブ/EVB等)は不変のため
// 重いディスクI/O(EVBバイナリ解析、plugins.js読み取り、wolf走査等)を完全にスキップして超高速化
bool isUnchanged = game.FolderLastModified.HasValue && game.FolderLastModified.Value == currentLastWrite;
// キャッシュのフォルダ更新日時と完全一致しており、かつ実行ファイルが有効(除外対象でない)な場合、
// 内部構成(exe/plugins/アーカイブ/EVB等)は不変のため重いディスクI/Oをスキップして超高速化
bool hasInvalidExe = string.IsNullOrEmpty(game.ExecutablePath) ||
!File.Exists(game.ExecutablePath) ||
IsExcludedExe(game.ExecutablePath);
bool isUnchanged = !hasInvalidExe &&
game.FolderLastModified.HasValue &&
game.FolderLastModified.Value == currentLastWrite;
if (isUnchanged)
{
// 未ロードのアイコンのみ必要に応じてロード
@@ -674,18 +766,19 @@ namespace GameLauncher.Services
return;
}
// 更新があった、または初回検証の場合は更新日時を最新化
// 更新があった、または初回検証・実行ファイル修復が必要な場合は更新日時を最新化
game.FolderLastModified = currentLastWrite;
Interlocked.Exchange(ref cacheNeedsSave, 1);
if (game is UnityGameItem ug)
{
if (!File.Exists(ug.ExecutablePath))
if (!File.Exists(ug.ExecutablePath) || IsExcludedExe(ug.ExecutablePath))
{
var recovered = FindGameExecutable(ug.RootDirectory);
var recovered = this.FindUnityExecutable(ug.RootDirectory, ug.DataDirectoryPath);
if (!string.IsNullOrEmpty(recovered))
{
ug.ExecutablePath = recovered;
ug.IconImage = null;
Interlocked.Exchange(ref cacheNeedsSave, 1);
}
else
@@ -777,15 +870,16 @@ namespace GameLauncher.Services
onGameUpdated(tg);
}
// 実在検証
// 実在検証および除外対象exe(notification_helper.exe等)からの自動修復
if (tg.IsWolf)
{
if (!File.Exists(tg.ExecutablePath))
if (!File.Exists(tg.ExecutablePath) || IsExcludedExe(tg.ExecutablePath))
{
var recovered = FindGameExecutable(tg.RootDirectory);
if (!string.IsNullOrEmpty(recovered))
{
tg.ExecutablePath = recovered;
tg.IconImage = null;
Interlocked.Exchange(ref cacheNeedsSave, 1);
}
else
@@ -814,12 +908,13 @@ namespace GameLauncher.Services
}
else if (tg.IsSrpgStudio)
{
if (!File.Exists(tg.ExecutablePath))
if (!File.Exists(tg.ExecutablePath) || IsExcludedExe(tg.ExecutablePath))
{
var recovered = FindGameExecutable(tg.RootDirectory);
if (!string.IsNullOrEmpty(recovered))
{
tg.ExecutablePath = recovered;
tg.IconImage = null;
Interlocked.Exchange(ref cacheNeedsSave, 1);
}
else
@@ -874,6 +969,17 @@ namespace GameLauncher.Services
Interlocked.Exchange(ref cacheNeedsSave, 1);
onGameUpdated(tg);
}
if (string.IsNullOrEmpty(tg.ExecutablePath) || !File.Exists(tg.ExecutablePath) || IsExcludedExe(tg.ExecutablePath))
{
var recovered = this.FindTkoolExecutable(tg.RootDirectory, tg.AsarExtractedDirPath ?? tg.RootDirectory);
if (!string.IsNullOrEmpty(recovered))
{
tg.ExecutablePath = recovered;
tg.IconImage = null;
Interlocked.Exchange(ref cacheNeedsSave, 1);
onGameUpdated(tg);
}
}
}
else if (tg.IsRgss)
{
@@ -887,6 +993,18 @@ namespace GameLauncher.Services
return;
}
if (string.IsNullOrEmpty(tg.ExecutablePath) || !File.Exists(tg.ExecutablePath) || IsExcludedExe(tg.ExecutablePath))
{
var recovered = FindRgssExecutable(tg.RootDirectory, tg.RootDirectory) ?? FindGameExecutable(tg.RootDirectory);
if (!string.IsNullOrEmpty(recovered))
{
tg.ExecutablePath = recovered;
tg.IconImage = null;
Interlocked.Exchange(ref cacheNeedsSave, 1);
onGameUpdated(tg);
}
}
if (tg.IsRgssExtracted != scriptExists)
{
tg.IsRgssExtracted = scriptExists;
@@ -894,23 +1012,77 @@ namespace GameLauncher.Services
onGameUpdated(tg);
}
}
else if (tg.IsNwjs)
else if (tg.IsNwjs && NwjsEnsureMeta(tg, ref cacheNeedsSave))
{
if (!File.Exists(tg.ExecutablePath) && !File.Exists(Path.Combine(tg.RootDirectory, "package.json")))
{
onGameRemoved(tg);
Interlocked.Exchange(ref cacheNeedsSave, 1);
return;
}
}
else if (tg.IsEvbPacked || tg.IsStandaloneExePackage || tg.IsOther)
{
if (!File.Exists(tg.ExecutablePath))
if (!File.Exists(tg.ExecutablePath) || IsExcludedExe(tg.ExecutablePath))
{
var recovered = FindGameExecutable(tg.RootDirectory);
if (!string.IsNullOrEmpty(recovered))
{
tg.ExecutablePath = recovered;
tg.IconImage = null;
Interlocked.Exchange(ref cacheNeedsSave, 1);
}
else if (!File.Exists(Path.Combine(tg.RootDirectory, "package.json")))
{
onGameRemoved(tg);
Interlocked.Exchange(ref cacheNeedsSave, 1);
return;
}
}
}
else if (tg.IsBakin)
{
if (!File.Exists(tg.ExecutablePath) || IsExcludedExe(tg.ExecutablePath))
{
var recovered = BakinDetector.FindBakinExecutable(tg.RootDirectory, tg.FolderName) ?? FindGameExecutable(tg.RootDirectory);
if (!string.IsNullOrEmpty(recovered))
{
tg.ExecutablePath = recovered;
tg.IconImage = null;
Interlocked.Exchange(ref cacheNeedsSave, 1);
}
else if (!BakinDetector.IsBakinGame(tg.RootDirectory))
{
onGameRemoved(tg);
Interlocked.Exchange(ref cacheNeedsSave, 1);
return;
}
}
bool bakinSave = BakinSaveService.HasAnySaveData(tg.RootDirectory);
if (tg.HasSaveData != bakinSave)
{
tg.HasSaveData = bakinSave;
Interlocked.Exchange(ref cacheNeedsSave, 1);
onGameUpdated(tg);
}
}
else if (tg.IsEvbPacked || tg.IsStandaloneExePackage || tg.IsOther)
{
// 「その他」としてキャッシュされていても、Unityの強い証拠があれば Unity として再分類する。
// (旧バージョンの判定でその他扱いになったまま残った項目の自己修復用)
if (tg.IsOther && HasStrongUnityEvidence(tg.RootDirectory))
{
var promoted = this.DetectUnityGameInDirectory(tg.RootDirectory);
if (promoted != null)
{
// ユーザー設定(ブックマーク・ラベル等)は従来の項目から引き継ぐ
promoted.IsBookmarked = tg.IsBookmarked;
promoted.LastLaunched = tg.LastLaunched;
promoted.FolderLastModified = tg.FolderLastModified;
Interlocked.Exchange(ref cacheNeedsSave, 1);
onGameUpdated(promoted);
return;
}
}
if (!File.Exists(tg.ExecutablePath) || IsExcludedExe(tg.ExecutablePath))
{
var recovered = FindGameExecutable(tg.RootDirectory);
if (!string.IsNullOrEmpty(recovered))
{
tg.ExecutablePath = recovered;
tg.IconImage = null;
Interlocked.Exchange(ref cacheNeedsSave, 1);
}
else
@@ -929,6 +1101,19 @@ namespace GameLauncher.Services
Interlocked.Exchange(ref cacheNeedsSave, 1);
return;
}
if (string.IsNullOrEmpty(tg.ExecutablePath) || !File.Exists(tg.ExecutablePath) || IsExcludedExe(tg.ExecutablePath))
{
var jsDir = Path.GetDirectoryName(tg.PluginsJsPath) ?? tg.RootDirectory;
var recovered = this.FindTkoolExecutable(tg.RootDirectory, jsDir);
if (!string.IsNullOrEmpty(recovered))
{
tg.ExecutablePath = recovered;
tg.IconImage = null;
Interlocked.Exchange(ref cacheNeedsSave, 1);
onGameUpdated(tg);
}
}
}
// フォルダ更新日時
@@ -944,7 +1129,7 @@ namespace GameLauncher.Services
}
// 改造状態の確認
if (tg.IsWolf || tg.IsNwjs)
if (tg.IsWolf)
{
tg.IsModded = false;
}
@@ -958,7 +1143,11 @@ namespace GameLauncher.Services
}
else if (File.Exists(tg.PluginsJsPath))
{
if (tg.EngineType == TkoolEngineType.Tyrano)
if (tg.IsNwjs)
{
tg.IsModded = NwjsModService.CheckIsModded(tg.PluginsJsPath);
}
else if (tg.EngineType == TkoolEngineType.Tyrano)
{
tg.IsModded = TyranoModService.CheckIsModded(tg.PluginsJsPath);
}
@@ -1604,6 +1793,12 @@ namespace GameLauncher.Services
}
// 8. 汎用 NW.js ゲームの検出
// 8. 汎用 NW.js ゲームの検出 / 9. RPG Developer Bakin ゲームの検出
var bakinGame = BakinDetector.DetectBakinGame(dirPath, folderName, folderModified, (exe, dir) => LoadIcon(exe, dir));
if (bakinGame != null)
{
return bakinGame;
}
var nwjsGame = NwjsDetector.DetectNwjsGame(dirPath, folderName, folderModified, (exe, dir) => LoadIcon(exe, dir));
if (nwjsGame != null)
{
@@ -1738,11 +1933,10 @@ namespace GameLauncher.Services
}
}
// unins* を除外した最初のexe
// 除外対象以外の最初のexe
foreach (var exe in exes)
{
var name = Path.GetFileName(exe);
if (name.StartsWith("unins", StringComparison.OrdinalIgnoreCase))
if (IsExcludedExe(exe))
{
continue;
}
@@ -1993,11 +2187,7 @@ namespace GameLauncher.Services
var exes = Directory.GetFiles(targetDir, "*.exe", SearchOption.TopDirectoryOnly);
foreach (var exe in exes)
{
var name = Path.GetFileName(exe);
if (!name.Contains("unins", StringComparison.OrdinalIgnoreCase) &&
!name.Contains("config", StringComparison.OrdinalIgnoreCase) &&
!name.Contains("setup", StringComparison.OrdinalIgnoreCase) &&
!name.Contains("patch", StringComparison.OrdinalIgnoreCase))
if (!IsExcludedExe(exe))
{
exePath = exe;
break;
@@ -2185,11 +2375,7 @@ namespace GameLauncher.Services
var exes = Directory.GetFiles(targetDir, "*.exe", SearchOption.TopDirectoryOnly);
foreach (var exe in exes)
{
var name = Path.GetFileName(exe);
if (!name.Contains("unins", StringComparison.OrdinalIgnoreCase) &&
!name.Contains("config", StringComparison.OrdinalIgnoreCase) &&
!name.Contains("setup", StringComparison.OrdinalIgnoreCase) &&
!name.Contains("patch", StringComparison.OrdinalIgnoreCase))
if (!IsExcludedExe(exe))
{
exePath = exe;
break;
@@ -2576,10 +2762,7 @@ namespace GameLauncher.Services
var exes = Directory.GetFiles(searchDir, "*.exe", SearchOption.TopDirectoryOnly);
foreach (var exe in exes)
{
var name = Path.GetFileName(exe);
if (!name.Contains("unins", StringComparison.OrdinalIgnoreCase) &&
!name.Contains("extractor", StringComparison.OrdinalIgnoreCase) &&
!name.Contains("patch", StringComparison.OrdinalIgnoreCase))
if (!IsExcludedExe(exe))
{
return exe;
}
@@ -2814,8 +2997,15 @@ namespace GameLauncher.Services
if (File.Exists(p)) return p;
}
var folderName = Path.GetFileName(rootDir.TrimEnd('\\', '/'));
if (!string.IsNullOrEmpty(folderName))
{
var namedExe = Path.Combine(rootDir, folderName + ".exe");
if (File.Exists(namedExe) && !IsExcludedExe(namedExe)) return namedExe;
}
var exes = Directory.GetFiles(rootDir, "*.exe", SearchOption.TopDirectoryOnly)
.Where(f => !Path.GetFileName(f).StartsWith("unins", StringComparison.OrdinalIgnoreCase))
.Where(f => !IsExcludedExe(f))
.ToList();
if (exes.Count > 0) return exes[0];
@@ -2823,8 +3013,14 @@ namespace GameLauncher.Services
var parent = Path.GetDirectoryName(jsDir);
if (parent != null && parent != rootDir)
{
foreach (var cand in candidates)
{
var p = Path.Combine(parent, cand);
if (File.Exists(p)) return p;
}
var pExes = Directory.GetFiles(parent, "*.exe", SearchOption.TopDirectoryOnly)
.Where(f => !Path.GetFileName(f).StartsWith("unins", StringComparison.OrdinalIgnoreCase))
.Where(f => !IsExcludedExe(f))
.ToList();
if (pExes.Count > 0) return pExes[0];
}
@@ -2950,7 +3146,7 @@ namespace GameLauncher.Services
if (File.Exists(standardGameExe)) return standardGameExe;
var exeFiles = Directory.GetFiles(gameRoot, "*.exe", SearchOption.TopDirectoryOnly)
.Where(f => !Regex.IsMatch(Path.GetFileName(f), @"(unins|setup|crash|handler|UnityCrash|設定|アンインストール)", RegexOptions.IgnoreCase))
.Where(f => !IsExcludedExe(f))
.ToList();
if (exeFiles.Count > 0)
@@ -3122,6 +3318,11 @@ namespace GameLauncher.Services
/// </summary>
public static ImageSource? LoadCachedThumbnailFast(string? exePath, string? fallbackDir = null)
{
if (!string.IsNullOrEmpty(exePath) && IsExcludedExe(exePath) && !string.IsNullOrEmpty(fallbackDir))
{
exePath = FindGameExecutable(fallbackDir);
}
var keyPath = !string.IsNullOrEmpty(exePath) ? exePath : fallbackDir;
if (string.IsNullOrEmpty(keyPath))
{
@@ -3138,6 +3339,13 @@ namespace GameLauncher.Services
if (File.Exists(thumbPath))
{
// 過去に汎用白紙アイコン(<=600 bytes)がキャッシュされており、かつフォルダ内に公式アイコン画像がある場合は再生成させる
var fi = new FileInfo(thumbPath);
if (fi.Length <= 600 && TryFindGameIconPng(fallbackDir, exePath) != null)
{
return null;
}
var bmp = new BitmapImage();
bmp.BeginInit();
bmp.UriSource = new Uri(thumbPath);
@@ -3155,12 +3363,26 @@ namespace GameLauncher.Services
public static ImageSource? LoadIcon(string? exePath, string? fallbackDir = null)
{
if ((!string.IsNullOrEmpty(exePath) && IsExcludedExe(exePath)) || (string.IsNullOrEmpty(exePath) && !string.IsNullOrEmpty(fallbackDir)))
{
if (!string.IsNullOrEmpty(fallbackDir))
{
var resolved = FindGameExecutable(fallbackDir);
if (!string.IsNullOrEmpty(resolved))
{
exePath = resolved;
}
}
}
var keyPath = !string.IsNullOrEmpty(exePath) ? exePath : fallbackDir;
if (string.IsNullOrEmpty(keyPath))
{
return null;
}
var gameIconPng = TryFindGameIconPng(fallbackDir, exePath);
// 1. サムネイルキャッシュフォルダから即座にロードを試行
string? thumbPath = null;
try
@@ -3173,22 +3395,45 @@ namespace GameLauncher.Services
if (File.Exists(thumbPath))
{
var bmp = new BitmapImage();
bmp.BeginInit();
bmp.UriSource = new Uri(thumbPath);
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.DecodePixelWidth = 88;
bmp.EndInit();
bmp.Freeze();
return bmp;
var fi = new FileInfo(thumbPath);
// キャッシュが600バイト超、または代替アイコンPNGが存在しない場合はキャッシュを使用
if (fi.Length > 600 || gameIconPng == null)
{
var bmp = new BitmapImage();
bmp.BeginInit();
bmp.UriSource = new Uri(thumbPath);
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.DecodePixelWidth = 88;
bmp.EndInit();
bmp.Freeze();
return bmp;
}
}
}
catch { }
// 2. キャッシュに存在しない場合はアイコンまたは画像を抽出
// 2. キャッシュに存在しない(または白紙キャッシュ更新)場合はアプリアイコンPNGまたはexeアイコンを抽出
BitmapSource? bitmapSource = null;
if (!string.IsNullOrEmpty(exePath) && File.Exists(exePath))
// 2-1. ゲームフォルダ内の高解像度アイコンPNG (www/icon/icon.png, icon/icon.png, package.json指定等) を優先試行
if (!string.IsNullOrEmpty(gameIconPng) && File.Exists(gameIconPng))
{
try
{
var bmp = new BitmapImage();
bmp.BeginInit();
bmp.UriSource = new Uri(gameIconPng);
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.DecodePixelWidth = 88;
bmp.EndInit();
bmp.Freeze();
bitmapSource = bmp;
}
catch { }
}
// 2-2. 実行ファイルから関連付けアイコンを抽出
if (bitmapSource == null && !string.IsNullOrEmpty(exePath) && File.Exists(exePath))
{
try
{
@@ -3205,25 +3450,6 @@ namespace GameLauncher.Services
catch { }
}
if (bitmapSource == null && !string.IsNullOrEmpty(fallbackDir) && Directory.Exists(fallbackDir))
{
var png = Path.Combine(fallbackDir, "icon.png");
if (File.Exists(png))
{
try
{
var bmp = new BitmapImage();
bmp.BeginInit();
bmp.UriSource = new Uri(png);
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.EndInit();
bmp.Freeze();
bitmapSource = bmp;
}
catch { }
}
}
// 3. 取得できたアイコンをサムネイルキャッシュフォルダへ保存
if (bitmapSource != null && !string.IsNullOrEmpty(thumbPath))
{
@@ -3237,6 +3463,91 @@ namespace GameLauncher.Services
return bitmapSource;
}
/// <summary>
/// ゲームディレクトリ内からアプリアイコン画像(package.jsonのicon指定、www/icon/icon.png、icon/icon.png、icon.png等)を探索します。
/// </summary>
private static string? TryFindGameIconPng(string? fallbackDir, string? exePath)
{
var searchDirs = new List<string>();
if (!string.IsNullOrEmpty(fallbackDir) && Directory.Exists(fallbackDir))
{
searchDirs.Add(fallbackDir);
}
if (!string.IsNullOrEmpty(exePath))
{
var exeDir = Path.GetDirectoryName(exePath);
if (!string.IsNullOrEmpty(exeDir) && Directory.Exists(exeDir) &&
!searchDirs.Contains(exeDir, StringComparer.OrdinalIgnoreCase))
{
searchDirs.Add(exeDir);
}
}
foreach (var baseDir in searchDirs)
{
try
{
// 1. package.json の window.icon 指定を確認
var pkgPaths = new[]
{
Path.Combine(baseDir, "package.json"),
Path.Combine(baseDir, "www", "package.json")
};
foreach (var pkgPath in pkgPaths)
{
if (File.Exists(pkgPath))
{
try
{
using var doc = JsonDocument.Parse(File.ReadAllText(pkgPath));
if (doc.RootElement.TryGetProperty("window", out var win) &&
win.ValueKind == JsonValueKind.Object &&
win.TryGetProperty("icon", out var iconProp) &&
iconProp.ValueKind == JsonValueKind.String)
{
var relIcon = iconProp.GetString();
if (!string.IsNullOrWhiteSpace(relIcon))
{
var pkgDir = Path.GetDirectoryName(pkgPath)!;
var resolvedFromPkg = Path.Combine(pkgDir, relIcon.Replace('/', Path.DirectorySeparatorChar));
if (File.Exists(resolvedFromPkg))
{
return resolvedFromPkg;
}
var resolvedFromBase = Path.Combine(baseDir, relIcon.Replace('/', Path.DirectorySeparatorChar));
if (File.Exists(resolvedFromBase))
{
return resolvedFromBase;
}
}
}
}
catch { }
}
}
// 2. 定型のアイコン配置パスを確認
var candidates = new[]
{
Path.Combine(baseDir, "www", "icon", "icon.png"),
Path.Combine(baseDir, "icon", "icon.png"),
Path.Combine(baseDir, "www", "icon.png"),
Path.Combine(baseDir, "icon.png")
};
foreach (var cand in candidates)
{
if (File.Exists(cand))
{
return cand;
}
}
}
catch { }
}
return null;
}
private static void SaveBitmapSourceToPng(BitmapSource source, string filePath)
{
try
@@ -3353,10 +3664,26 @@ namespace GameLauncher.Services
return null;
}
private static bool IsExcludedExe(string filePath)
/// <summary>
/// ゲーム本体ではない補助ツール・インストーラ・通知ヘルパー・設定用実行ファイルかどうかを判定します。
/// </summary>
public static bool IsExcludedExe(string? filePath)
{
if (string.IsNullOrWhiteSpace(filePath))
{
return true;
}
var fileName = Path.GetFileName(filePath);
return Regex.IsMatch(fileName, @"^(unins|setup|install|crash|handler|UnityCrash|設定|Config|updater|patch)", RegexOptions.IgnoreCase);
if (string.IsNullOrWhiteSpace(fileName))
{
return true;
}
return Regex.IsMatch(
fileName,
@"^(unins|setup|install|crash|handler|UnityCrash|notification_helper|crashpad_handler|elevate|nacl64|nwjc|payload|minidump_stackwalk|extractor|設定|環境設定|エンジン設定|Config|updater|patch|アンインストール)|((設定|環境設定|エンジン設定|Config|Setup|Installer|Updater)\.exe$)",
RegexOptions.IgnoreCase);
}
#endregion