1447 lines
58 KiB
C#
1447 lines
58 KiB
C#
// Engines/Nwjs/NwjsSaveService.cs — NW.js セーブデータ検出・復号・暗号化・編集サービス
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.ComponentModel;
|
|
using System.Globalization;
|
|
using System.IO;
|
|
using System.IO.Compression;
|
|
using System.Linq;
|
|
using System.Runtime.CompilerServices;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using System.Text.Encodings.Web;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Nodes;
|
|
using GameLauncher.Helpers;
|
|
|
|
namespace GameLauncher.Engines.Nwjs
|
|
{
|
|
/// <summary>
|
|
/// NW.js セーブデータのフォーマット種別を表します。
|
|
/// </summary>
|
|
public enum NwjsSaveFormatKind
|
|
{
|
|
/// <summary>
|
|
/// プレーンな JSON 形式のセーブデータ(save1.json, gallery.json 等)。
|
|
/// </summary>
|
|
PlainJson = 0,
|
|
|
|
/// <summary>
|
|
/// GameCreator エンジンの WinZip AE-2 (AES-256-CTR + Deflate) 暗号化セーブデータ(.gcdata)。
|
|
/// </summary>
|
|
GameCreatorGcData = 1
|
|
}
|
|
|
|
/// <summary>
|
|
/// 検出された NW.js セーブファイル1件の情報を保持するモデルクラス。
|
|
/// </summary>
|
|
public sealed class NwjsSaveFileInfo
|
|
{
|
|
#region □プロパティ(Public)
|
|
|
|
/// <summary>
|
|
/// セーブファイルのフルパスを取得または設定します。
|
|
/// </summary>
|
|
public string FilePath { get; set; } = string.Empty;
|
|
|
|
/// <summary>
|
|
/// UI 一覧上に表示するセーブファイル名を取得または設定します。
|
|
/// </summary>
|
|
public string DisplayName { get; set; } = string.Empty;
|
|
|
|
/// <summary>
|
|
/// セーブファイルのフォーマット種別を取得または設定します。
|
|
/// </summary>
|
|
public NwjsSaveFormatKind FormatKind { get; set; } = NwjsSaveFormatKind.PlainJson;
|
|
|
|
/// <summary>
|
|
/// ファイルの最終更新日時を取得または設定します。
|
|
/// </summary>
|
|
public DateTime LastWriteTime { get; set; }
|
|
|
|
/// <summary>
|
|
/// バックアップファイルの保存先フルパスを取得または設定します。
|
|
/// </summary>
|
|
public string BackupFilePath { get; set; } = string.Empty;
|
|
|
|
/// <summary>
|
|
/// バックアップが存在するかどうかを取得します。
|
|
/// </summary>
|
|
public bool HasBackup => !string.IsNullOrEmpty(this.BackupFilePath) && File.Exists(this.BackupFilePath);
|
|
|
|
/// <summary>
|
|
/// コンボボックス等での表示用テキストを取得します。
|
|
/// </summary>
|
|
public string SummaryText => string.Format(
|
|
CultureInfo.InvariantCulture,
|
|
"{0} ({1:yyyy/MM/dd HH:mm:ss}){2}",
|
|
this.DisplayName,
|
|
this.LastWriteTime,
|
|
this.HasBackup ? " [バックアップ有]" : string.Empty);
|
|
|
|
#endregion
|
|
}
|
|
|
|
/// <summary>
|
|
/// セーブエディタ GUI 上で1つの編集項目(ステータス・変数・スイッチ・アイテム等)を表すバインディングモデル。
|
|
/// </summary>
|
|
public sealed class NwjsSaveEntryItem : INotifyPropertyChanged
|
|
{
|
|
#region □変数(Private)
|
|
|
|
private string _valueText = string.Empty;
|
|
private bool _isModified;
|
|
|
|
#endregion
|
|
|
|
#region □プロパティ(Public)
|
|
|
|
/// <summary>
|
|
/// 項目のカテゴリ名(例: "💰 基本・ステータス", "🔢 プレイヤー変数" 等)を取得または設定します。
|
|
/// </summary>
|
|
public string Category { get; set; } = string.Empty;
|
|
|
|
/// <summary>
|
|
/// JSON ツリー内の識別パスを取得または設定します。
|
|
/// </summary>
|
|
public string JsonPath { get; set; } = string.Empty;
|
|
|
|
/// <summary>
|
|
/// 画面に表示する分かりやすい項目名を取得または設定します。
|
|
/// </summary>
|
|
public string DisplayKey { get; set; } = string.Empty;
|
|
|
|
/// <summary>
|
|
/// 値の型種別("Number", "Boolean", "String")を取得または設定します。
|
|
/// </summary>
|
|
public string ValueType { get; set; } = "Number";
|
|
|
|
/// <summary>
|
|
/// 読み込み時点の初期値文字列を取得または設定します。
|
|
/// </summary>
|
|
public string OriginalValueText { get; set; } = string.Empty;
|
|
|
|
/// <summary>
|
|
/// 現在の編集値文字列を取得または設定します。
|
|
/// </summary>
|
|
public string ValueText
|
|
{
|
|
get => this._valueText;
|
|
set
|
|
{
|
|
if (this._valueText != value)
|
|
{
|
|
this._valueText = value ?? string.Empty;
|
|
this.IsModified = !string.Equals(this._valueText, this.OriginalValueText, StringComparison.Ordinal);
|
|
this.OnPropertyChanged();
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 初期値から変更されているかどうかを取得または設定します。
|
|
/// </summary>
|
|
public bool IsModified
|
|
{
|
|
get => this._isModified;
|
|
private set
|
|
{
|
|
if (this._isModified != value)
|
|
{
|
|
this._isModified = value;
|
|
this.OnPropertyChanged();
|
|
}
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region □イベント
|
|
|
|
/// <summary>
|
|
/// プロパティ値が変更されたときに発生します。
|
|
/// </summary>
|
|
public event PropertyChangedEventHandler? PropertyChanged;
|
|
|
|
#endregion
|
|
|
|
#region □メソッド(Public)
|
|
|
|
/// <summary>
|
|
/// 初期値を設定し、変更フラグをリセットします。
|
|
/// </summary>
|
|
/// <param name="initialValue">初期値文字列</param>
|
|
public void InitializeValue(string initialValue)
|
|
{
|
|
this.OriginalValueText = initialValue ?? string.Empty;
|
|
this._valueText = this.OriginalValueText;
|
|
this.IsModified = false;
|
|
this.OnPropertyChanged(nameof(this.OriginalValueText));
|
|
this.OnPropertyChanged(nameof(this.ValueText));
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region □メソッド(Private)
|
|
|
|
private void OnPropertyChanged([CallerMemberName] string? propertyName = null)
|
|
{
|
|
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
|
|
/// <summary>
|
|
/// 読み込まれたセーブファイル1件の展開結果を保持するクラス。
|
|
/// </summary>
|
|
public sealed class NwjsLoadedSaveDocument
|
|
{
|
|
#region □プロパティ(Public)
|
|
|
|
/// <summary>
|
|
/// 対象のセーブファイル情報を取得または設定します。
|
|
/// </summary>
|
|
public NwjsSaveFileInfo FileInfo { get; set; } = new NwjsSaveFileInfo();
|
|
|
|
/// <summary>
|
|
/// パースされた JSON ルートノードを取得または設定します。
|
|
/// </summary>
|
|
public JsonNode? RootNode { get; set; }
|
|
|
|
/// <summary>
|
|
/// 整形済みの生 JSON 文字列を取得または設定します。
|
|
/// </summary>
|
|
public string FormattedJson { get; set; } = string.Empty;
|
|
|
|
/// <summary>
|
|
/// GUI 編集用に抽出されたエントリ一覧を取得または設定します。
|
|
/// </summary>
|
|
public List<NwjsSaveEntryItem> Entries { get; set; } = new List<NwjsSaveEntryItem>();
|
|
|
|
/// <summary>
|
|
/// GameCreator の登録アイテム辞書(ID → アイテム名)を取得または設定します。
|
|
/// </summary>
|
|
public Dictionary<int, string> GcItemNames { get; set; } = new Dictionary<int, string>();
|
|
|
|
#endregion
|
|
}
|
|
|
|
/// <summary>
|
|
/// NW.js ゲームのセーブデータ検索・復号・暗号化・プロパティ抽出・保存を行うサービスクラス。
|
|
/// </summary>
|
|
public static class NwjsSaveService
|
|
{
|
|
#region □定数(Private)
|
|
|
|
/// <summary>
|
|
/// GameCreator の startup.json 用固定パスワード。
|
|
/// </summary>
|
|
private const string GcStartupZipPassword = "gc_zip";
|
|
|
|
/// <summary>
|
|
/// カスタム HTML5/JS ゲーム等でよく使われる英語プロパティ名の日本語補足辞書。
|
|
/// </summary>
|
|
private static readonly Dictionary<string, string> KnownPropertyLabels = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
|
|
{
|
|
{ "money", "💰 所持金 (money)" },
|
|
{ "gold", "💰 所持金 (gold)" },
|
|
{ "debt", "🧾 借金残高 (debt)" },
|
|
{ "day", "📅 経過日数 (day)" },
|
|
{ "timeSlot", "⏰ 時間帯 (timeSlot)" },
|
|
{ "stamina", "❤️ 現在スタミナ (stamina)" },
|
|
{ "maxStamina", "💗 最大スタミナ (maxStamina)" },
|
|
{ "debtClearedCount", "🏆 借金完済回数 (debtClearedCount)" },
|
|
{ "selectedHerb", "🌿 選択中の薬草 (selectedHerb)" },
|
|
{ "currentCostume", "👗 現在の衣装 (currentCostume)" },
|
|
{ "userUnlockAll", "🔓 ギャラリー全解放フラグ (userUnlockAll)" },
|
|
{ "hp", "❤️ HP" },
|
|
{ "maxHp", "💗 最大HP" },
|
|
{ "mp", "💧 MP" },
|
|
{ "maxMp", "💠 最大MP" },
|
|
{ "atk", "⚔️ 攻撃力 (atk)" },
|
|
{ "def", "🛡️ 防御力 (def)" },
|
|
{ "lv", "⭐ レベル (lv)" },
|
|
{ "level", "⭐ レベル (level)" },
|
|
{ "exp", "✨ 経験値 (exp)" },
|
|
{ "moveSpeed", "🏃 移動速度 (moveSpeed)" }
|
|
};
|
|
|
|
#endregion
|
|
|
|
#region □メソッド(Public)
|
|
|
|
/// <summary>
|
|
/// 指定された NW.js ゲームにセーブデータが1件以上存在するかどうかを判定します。
|
|
/// </summary>
|
|
/// <param name="rootDir">ゲームのルートディレクトリ</param>
|
|
/// <param name="folderName">ゲームのフォルダ名</param>
|
|
/// <returns>セーブデータが存在する場合は true</returns>
|
|
public static bool HasAnySaveData(string rootDir, string folderName)
|
|
{
|
|
return NwjsSaveService.FindSaveFiles(rootDir, folderName).Count > 0;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 指定された NW.js ゲームに関連するすべてのセーブファイル(.gcdata / .json)を検出します。
|
|
/// </summary>
|
|
/// <param name="rootDir">ゲームのルートディレクトリ</param>
|
|
/// <param name="folderName">ゲームのフォルダ名</param>
|
|
/// <returns>検出されたセーブファイル情報のリスト</returns>
|
|
public static List<NwjsSaveFileInfo> FindSaveFiles(string rootDir, string folderName)
|
|
{
|
|
var results = new List<NwjsSaveFileInfo>();
|
|
if (string.IsNullOrEmpty(rootDir) || !Directory.Exists(rootDir))
|
|
{
|
|
return results;
|
|
}
|
|
|
|
var seenPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
|
string backupDir = AppPathHelper.GetGameBackupDirectory(
|
|
string.IsNullOrEmpty(folderName) ? Path.GetFileName(rootDir) : folderName,
|
|
rootDir);
|
|
|
|
// 1. ゲームフォルダ内の savedata / save / SavesDir / www/save 等
|
|
string[] localSaveDirs = new[]
|
|
{
|
|
Path.Combine(rootDir, "savedata"),
|
|
Path.Combine(rootDir, "save"),
|
|
Path.Combine(rootDir, "saves"),
|
|
Path.Combine(rootDir, "SavesDir"),
|
|
Path.Combine(rootDir, "www", "save"),
|
|
Path.Combine(rootDir, "www", "savedata")
|
|
};
|
|
|
|
foreach (string dir in localSaveDirs)
|
|
{
|
|
if (!Directory.Exists(dir))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
NwjsSaveService.CollectSaveFilesFromDirectory(dir, "[ゲーム内]", backupDir, seenPaths, results);
|
|
}
|
|
|
|
// 2. GameLauncher プロファイルディレクトリ (Profiles/<Game>/Default/save 等)
|
|
try
|
|
{
|
|
string profileDir = AppPathHelper.GetGameProfileDirectory(
|
|
string.IsNullOrEmpty(folderName) ? Path.GetFileName(rootDir) : folderName,
|
|
rootDir);
|
|
string[] profileSaveDirs = new[]
|
|
{
|
|
Path.Combine(profileDir, "Default", "save"),
|
|
Path.Combine(profileDir, "Default", "savedata"),
|
|
Path.Combine(profileDir, "save"),
|
|
Path.Combine(profileDir, "savedata")
|
|
};
|
|
|
|
foreach (string dir in profileSaveDirs)
|
|
{
|
|
if (Directory.Exists(dir))
|
|
{
|
|
NwjsSaveService.CollectSaveFilesFromDirectory(dir, "[プロファイル]", backupDir, seenPaths, results);
|
|
}
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
}
|
|
|
|
// 3. %LOCALAPPDATA%/<package.name>/User Data/Default/save 等
|
|
try
|
|
{
|
|
string? pkgName = NwjsSaveService.TryReadPackageName(rootDir);
|
|
if (!string.IsNullOrEmpty(pkgName))
|
|
{
|
|
string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
|
|
string[] appDataSaveDirs = new[]
|
|
{
|
|
Path.Combine(localAppData, pkgName, "User Data", "Default", "save"),
|
|
Path.Combine(localAppData, pkgName, "User Data", "Default", "savedata"),
|
|
Path.Combine(localAppData, pkgName, "Default", "save"),
|
|
Path.Combine(localAppData, pkgName, "save")
|
|
};
|
|
|
|
foreach (string dir in appDataSaveDirs)
|
|
{
|
|
if (Directory.Exists(dir))
|
|
{
|
|
NwjsSaveService.CollectSaveFilesFromDirectory(dir, "[AppData]", backupDir, seenPaths, results);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
}
|
|
|
|
return results
|
|
.OrderByDescending(f => f.FilePath.EndsWith(".gcdata", StringComparison.OrdinalIgnoreCase) && !f.FilePath.EndsWith("life.gcdata", StringComparison.OrdinalIgnoreCase))
|
|
.ThenBy(f => f.DisplayName, StringComparer.OrdinalIgnoreCase)
|
|
.ToList();
|
|
}
|
|
|
|
/// <summary>
|
|
/// セーブファイルを復号・パースして編集用ドキュメントとして読み込みます。
|
|
/// </summary>
|
|
/// <param name="fileInfo">対象のセーブファイル情報</param>
|
|
/// <param name="rootDir">ゲームのルートディレクトリ</param>
|
|
/// <returns>読み込まれたセーブドキュメント</returns>
|
|
public static NwjsLoadedSaveDocument LoadSaveFile(NwjsSaveFileInfo fileInfo, string rootDir)
|
|
{
|
|
if (fileInfo == null || string.IsNullOrEmpty(fileInfo.FilePath) || !File.Exists(fileInfo.FilePath))
|
|
{
|
|
throw new FileNotFoundException("指定されたセーブファイルが見つかりません。", fileInfo?.FilePath);
|
|
}
|
|
|
|
var doc = new NwjsLoadedSaveDocument
|
|
{
|
|
FileInfo = fileInfo
|
|
};
|
|
|
|
string rawJsonText;
|
|
if (fileInfo.FormatKind == NwjsSaveFormatKind.GameCreatorGcData)
|
|
{
|
|
var gcMeta = NwjsSaveService.LoadGameCreatorMetadata(rootDir);
|
|
doc.GcItemNames = gcMeta.ItemNames;
|
|
byte[] gcBytes = File.ReadAllBytes(fileInfo.FilePath);
|
|
rawJsonText = NwjsSaveService.DecryptGcZipBytes(gcBytes, gcMeta.SavePassword);
|
|
}
|
|
else
|
|
{
|
|
rawJsonText = File.ReadAllText(fileInfo.FilePath, Encoding.UTF8);
|
|
}
|
|
|
|
JsonNode? rootNode = JsonNode.Parse(rawJsonText);
|
|
doc.RootNode = rootNode;
|
|
|
|
var serializerOptions = new JsonSerializerOptions
|
|
{
|
|
WriteIndented = true,
|
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
|
};
|
|
doc.FormattedJson = rootNode != null ? rootNode.ToJsonString(serializerOptions) : rawJsonText;
|
|
|
|
if (rootNode != null)
|
|
{
|
|
if (fileInfo.FormatKind == NwjsSaveFormatKind.GameCreatorGcData)
|
|
{
|
|
NwjsSaveService.ExtractGameCreatorEntries(rootNode, doc.Entries, doc.GcItemNames);
|
|
}
|
|
else
|
|
{
|
|
NwjsSaveService.ExtractPlainJsonEntries(rootNode, doc.Entries);
|
|
}
|
|
}
|
|
|
|
return doc;
|
|
}
|
|
|
|
/// <summary>
|
|
/// GUI エントリ一覧での変更を JSON ルートノードへ反映し、最新の整形済み JSON 文字列を返します。
|
|
/// </summary>
|
|
/// <param name="doc">対象のセーブドキュメント</param>
|
|
/// <returns>更新された整形済み JSON 文字列</returns>
|
|
public static string ApplyEntriesToDocument(NwjsLoadedSaveDocument doc)
|
|
{
|
|
if (doc?.RootNode == null)
|
|
{
|
|
return doc?.FormattedJson ?? string.Empty;
|
|
}
|
|
|
|
foreach (NwjsSaveEntryItem entry in doc.Entries)
|
|
{
|
|
if (!entry.IsModified)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
NwjsSaveService.ApplySingleEntryToNode(doc.RootNode, entry);
|
|
}
|
|
|
|
var serializerOptions = new JsonSerializerOptions
|
|
{
|
|
WriteIndented = true,
|
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
|
};
|
|
doc.FormattedJson = doc.RootNode.ToJsonString(serializerOptions);
|
|
return doc.FormattedJson;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 編集後の JSON 文字列をセーブファイルへ保存します(必要に応じて自動バックアップを作成し、.gcdata の場合は再暗号化します)。
|
|
/// </summary>
|
|
/// <param name="fileInfo">保存対象のセーブファイル情報</param>
|
|
/// <param name="rootDir">ゲームのルートディレクトリ</param>
|
|
/// <param name="jsonText">保存する JSON テキスト</param>
|
|
/// <param name="createBackup">保存前に初回バックアップを作成するかどうか</param>
|
|
public static void SaveToFile(NwjsSaveFileInfo fileInfo, string rootDir, string jsonText, bool createBackup = true)
|
|
{
|
|
if (fileInfo == null || string.IsNullOrEmpty(fileInfo.FilePath))
|
|
{
|
|
throw new ArgumentNullException(nameof(fileInfo));
|
|
}
|
|
|
|
// JSON 構文チェックおよびコンパクト化(.gcdata は1行または整形JSONどちらでも可だが、サイズ削減のため検証兼ねてパース)
|
|
JsonNode? parsedNode = JsonNode.Parse(jsonText);
|
|
if (parsedNode == null)
|
|
{
|
|
throw new InvalidDataException("JSON データが空または不正です。");
|
|
}
|
|
|
|
if (createBackup && File.Exists(fileInfo.FilePath) && !string.IsNullOrEmpty(fileInfo.BackupFilePath))
|
|
{
|
|
string? bDir = Path.GetDirectoryName(fileInfo.BackupFilePath);
|
|
if (!string.IsNullOrEmpty(bDir) && !Directory.Exists(bDir))
|
|
{
|
|
Directory.CreateDirectory(bDir);
|
|
}
|
|
|
|
// 初回バックアップが存在しない場合はオリジナルを保護するため上書きせず保存、既にある場合は直前バックアップも残す
|
|
if (!File.Exists(fileInfo.BackupFilePath))
|
|
{
|
|
File.Copy(fileInfo.FilePath, fileInfo.BackupFilePath, overwrite: false);
|
|
}
|
|
}
|
|
|
|
if (fileInfo.FormatKind == NwjsSaveFormatKind.GameCreatorGcData)
|
|
{
|
|
var gcMeta = NwjsSaveService.LoadGameCreatorMetadata(rootDir);
|
|
var compactOptions = new JsonSerializerOptions
|
|
{
|
|
WriteIndented = true,
|
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
|
};
|
|
string normalizedJson = parsedNode.ToJsonString(compactOptions);
|
|
byte[] existingTemplate = File.Exists(fileInfo.FilePath) ? File.ReadAllBytes(fileInfo.FilePath) : Array.Empty<byte>();
|
|
byte[] encryptedBytes = NwjsSaveService.EncryptGcZipBytes(normalizedJson, gcMeta.SavePassword, existingTemplate);
|
|
File.WriteAllBytes(fileInfo.FilePath, encryptedBytes);
|
|
}
|
|
else
|
|
{
|
|
var prettyOptions = new JsonSerializerOptions
|
|
{
|
|
WriteIndented = true,
|
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
|
};
|
|
string normalizedJson = parsedNode.ToJsonString(prettyOptions);
|
|
File.WriteAllText(fileInfo.FilePath, normalizedJson, new UTF8Encoding(false));
|
|
}
|
|
|
|
fileInfo.LastWriteTime = File.GetLastWriteTime(fileInfo.FilePath);
|
|
}
|
|
|
|
/// <summary>
|
|
/// バックアップファイルから元のセーブファイルを復元します。
|
|
/// </summary>
|
|
/// <param name="fileInfo">復元対象のセーブファイル情報</param>
|
|
/// <returns>復元に成功した場合は true</returns>
|
|
public static bool RestoreBackup(NwjsSaveFileInfo fileInfo)
|
|
{
|
|
if (fileInfo == null || !fileInfo.HasBackup)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
File.Copy(fileInfo.BackupFilePath, fileInfo.FilePath, overwrite: true);
|
|
fileInfo.LastWriteTime = File.GetLastWriteTime(fileInfo.FilePath);
|
|
return true;
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region □メソッド(Private)
|
|
|
|
private static void CollectSaveFilesFromDirectory(
|
|
string dirPath,
|
|
string locationPrefix,
|
|
string backupDir,
|
|
HashSet<string> seenPaths,
|
|
List<NwjsSaveFileInfo> results)
|
|
{
|
|
try
|
|
{
|
|
foreach (string file in Directory.EnumerateFiles(dirPath, "*.*", SearchOption.AllDirectories))
|
|
{
|
|
string ext = Path.GetExtension(file);
|
|
if (!ext.Equals(".gcdata", StringComparison.OrdinalIgnoreCase) &&
|
|
!ext.Equals(".json", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
if (!seenPaths.Add(file))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
string fileName = Path.GetFileName(file);
|
|
bool isGcData = ext.Equals(".gcdata", StringComparison.OrdinalIgnoreCase);
|
|
|
|
string typeTag;
|
|
if (isGcData)
|
|
{
|
|
typeTag = fileName.Equals("life.gcdata", StringComparison.OrdinalIgnoreCase)
|
|
? "🌍 GC永続・回想"
|
|
: "💾 GCセーブ";
|
|
}
|
|
else
|
|
{
|
|
if (fileName.Contains("gallery", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
typeTag = "🖼 ギャラリー";
|
|
}
|
|
else if (fileName.Contains("config", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
typeTag = "⚙ 設定";
|
|
}
|
|
else
|
|
{
|
|
typeTag = "💾 セーブ";
|
|
}
|
|
}
|
|
|
|
string safeBackupName = locationPrefix.Trim('[', ']') + "_" + fileName + ".original_backup";
|
|
string backupFilePath = Path.Combine(backupDir, "SaveBackups", safeBackupName);
|
|
|
|
results.Add(new NwjsSaveFileInfo
|
|
{
|
|
FilePath = file,
|
|
DisplayName = string.Format(CultureInfo.InvariantCulture, "{0} {1} ({2})", locationPrefix, fileName, typeTag),
|
|
FormatKind = isGcData ? NwjsSaveFormatKind.GameCreatorGcData : NwjsSaveFormatKind.PlainJson,
|
|
LastWriteTime = File.GetLastWriteTime(file),
|
|
BackupFilePath = backupFilePath
|
|
});
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
}
|
|
}
|
|
|
|
private static string? TryReadPackageName(string rootDir)
|
|
{
|
|
string pkgPath = Path.Combine(rootDir, "package.json");
|
|
if (!File.Exists(pkgPath))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
try
|
|
{
|
|
using JsonDocument doc = JsonDocument.Parse(File.ReadAllText(pkgPath, Encoding.UTF8));
|
|
if (doc.RootElement.TryGetProperty("name", out JsonElement nameEl) && nameEl.ValueKind == JsonValueKind.String)
|
|
{
|
|
return nameEl.GetString();
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// GameCreator の startup.json または config.json からセーブデータの暗号化パスワードとアイテム名一覧を取得します。
|
|
/// </summary>
|
|
private static (string SavePassword, Dictionary<int, string> ItemNames) LoadGameCreatorMetadata(string rootDir)
|
|
{
|
|
string password = NwjsSaveService.GcStartupZipPassword;
|
|
var itemNames = new Dictionary<int, string>();
|
|
|
|
try
|
|
{
|
|
// 1. 非圧縮の asset/json/config.json があるか確認
|
|
string plainConfigPath = Path.Combine(rootDir, "asset", "json", "config.json");
|
|
if (File.Exists(plainConfigPath))
|
|
{
|
|
using JsonDocument cfgDoc = JsonDocument.Parse(File.ReadAllText(plainConfigPath, Encoding.UTF8));
|
|
if (cfgDoc.RootElement.TryGetProperty("z1", out JsonElement z1El) && z1El.ValueKind == JsonValueKind.String)
|
|
{
|
|
string? rawZ1 = z1El.GetString();
|
|
if (!string.IsNullOrEmpty(rawZ1))
|
|
{
|
|
password = NwjsSaveService.DecodeGcZ1Password(rawZ1);
|
|
}
|
|
}
|
|
}
|
|
|
|
// 2. 圧縮された asset/json/startup.json から config.json の z1 とアイテム定義を取得
|
|
string startupPath = Path.Combine(rootDir, "asset", "json", "startup.json");
|
|
if (File.Exists(startupPath))
|
|
{
|
|
byte[] startupBytes = File.ReadAllBytes(startupPath);
|
|
string startupJsonText = NwjsSaveService.DecryptGcZipBytes(startupBytes, NwjsSaveService.GcStartupZipPassword);
|
|
using JsonDocument startupDoc = JsonDocument.Parse(startupJsonText);
|
|
|
|
if (startupDoc.RootElement.TryGetProperty("asset/json/config.json", out JsonElement cfgObj) &&
|
|
cfgObj.ValueKind == JsonValueKind.Object &&
|
|
cfgObj.TryGetProperty("z1", out JsonElement z1El) &&
|
|
z1El.ValueKind == JsonValueKind.String)
|
|
{
|
|
string? rawZ1 = z1El.GetString();
|
|
if (!string.IsNullOrEmpty(rawZ1))
|
|
{
|
|
password = NwjsSaveService.DecodeGcZ1Password(rawZ1);
|
|
}
|
|
}
|
|
|
|
if (startupDoc.RootElement.TryGetProperty("asset/json/custom/customModule/customModuleDataList1.json", out JsonElement mod1El) &&
|
|
mod1El.ValueKind == JsonValueKind.Object &&
|
|
mod1El.TryGetProperty("typeTreeNode", out JsonElement treeEl) &&
|
|
treeEl.ValueKind == JsonValueKind.Object &&
|
|
treeEl.TryGetProperty("children", out JsonElement childrenEl) &&
|
|
childrenEl.ValueKind == JsonValueKind.Array)
|
|
{
|
|
foreach (JsonElement itemNode in childrenEl.EnumerateArray())
|
|
{
|
|
if (itemNode.ValueKind == JsonValueKind.Object &&
|
|
itemNode.TryGetProperty("id", out JsonElement idEl) &&
|
|
idEl.TryGetInt32(out int id) &&
|
|
itemNode.TryGetProperty("name", out JsonElement nameEl) &&
|
|
nameEl.ValueKind == JsonValueKind.String)
|
|
{
|
|
string? name = nameEl.GetString();
|
|
if (!string.IsNullOrEmpty(name))
|
|
{
|
|
itemNames[id] = name;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
}
|
|
|
|
return (password, itemNames);
|
|
}
|
|
|
|
/// <summary>
|
|
/// GameCreator の Config.z1 文字列('|' 区切り)から実際の ZIP パスワードを算出します。
|
|
/// </summary>
|
|
private static string DecodeGcZ1Password(string rawZ1)
|
|
{
|
|
if (string.IsNullOrEmpty(rawZ1) || !rawZ1.Contains('|'))
|
|
{
|
|
return rawZ1;
|
|
}
|
|
|
|
string[] parts = rawZ1.Split('|');
|
|
var sb = new StringBuilder(parts.Length);
|
|
foreach (string part in parts)
|
|
{
|
|
if (!string.IsNullOrEmpty(part))
|
|
{
|
|
sb.Append((char)(part[0] - 1));
|
|
}
|
|
}
|
|
|
|
return sb.ToString();
|
|
}
|
|
|
|
/// <summary>
|
|
/// WinZip AE-2 (AES-256-CTR + Deflate) 形式のバイト列を復号して UTF-8 テキストを返します。
|
|
/// </summary>
|
|
private static string DecryptGcZipBytes(byte[] bytes, string password)
|
|
{
|
|
if (bytes == null || bytes.Length < 4)
|
|
{
|
|
throw new InvalidDataException("データが空です。");
|
|
}
|
|
|
|
// もしプレーンな JSON の場合はそのまま UTF-8 として返す
|
|
if (bytes[0] == (byte)'{' || bytes[0] == (byte)'[')
|
|
{
|
|
return Encoding.UTF8.GetString(bytes);
|
|
}
|
|
|
|
if (bytes[0] != 0x50 || bytes[1] != 0x4B || bytes[2] != 0x03 || bytes[3] != 0x04)
|
|
{
|
|
throw new InvalidDataException("有効な ZIP / .gcdata ヘッダではありません。");
|
|
}
|
|
|
|
int fnLen = BitConverter.ToUInt16(bytes, 26);
|
|
int exLen = BitConverter.ToUInt16(bytes, 28);
|
|
int dataOffset = 30 + fnLen + exLen;
|
|
|
|
int cdOffset = -1;
|
|
for (int i = bytes.Length - 22; i >= dataOffset + 18; i--)
|
|
{
|
|
if (bytes[i] == 0x50 && bytes[i + 1] == 0x4B && bytes[i + 2] == 0x01 && bytes[i + 3] == 0x02)
|
|
{
|
|
cdOffset = i;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (cdOffset < 0)
|
|
{
|
|
throw new InvalidDataException("Central Directory ヘッダが見つかりません。");
|
|
}
|
|
|
|
uint compSize = BitConverter.ToUInt32(bytes, cdOffset + 20);
|
|
int cipherLen = (int)compSize - 16 - 2 - 10;
|
|
if (cipherLen <= 0 || dataOffset + 18 + cipherLen > bytes.Length)
|
|
{
|
|
// フォールバック計算
|
|
cipherLen = (cdOffset - 10) - (dataOffset + 18);
|
|
}
|
|
|
|
byte[] salt = new byte[16];
|
|
Buffer.BlockCopy(bytes, dataOffset, salt, 0, 16);
|
|
|
|
byte[] cipher = new byte[cipherLen];
|
|
Buffer.BlockCopy(bytes, dataOffset + 18, cipher, 0, cipherLen);
|
|
|
|
byte[] keyMat = Rfc2898DeriveBytes.Pbkdf2(password, salt, 1000, HashAlgorithmName.SHA1, 66);
|
|
byte[] aesKey = new byte[32];
|
|
Buffer.BlockCopy(keyMat, 0, aesKey, 0, 32);
|
|
|
|
byte[] plainDeflate = NwjsSaveService.TransformAes256Ctr(cipher, aesKey);
|
|
|
|
using var ms = new MemoryStream(plainDeflate);
|
|
using var ds = new DeflateStream(ms, CompressionMode.Decompress);
|
|
using var sr = new StreamReader(ds, Encoding.UTF8);
|
|
return sr.ReadToEnd();
|
|
}
|
|
|
|
/// <summary>
|
|
/// UTF-8 JSON テキストを WinZip AE-2 (AES-256-CTR + Deflate) 形式の .gcdata バイナリへ暗号化します。
|
|
/// </summary>
|
|
private static byte[] EncryptGcZipBytes(string jsonText, string password, byte[] existingTemplate)
|
|
{
|
|
byte[] utf8Bytes = Encoding.UTF8.GetBytes(jsonText);
|
|
|
|
byte[] compressedBytes;
|
|
using (var compMs = new MemoryStream())
|
|
{
|
|
using (var ds = new DeflateStream(compMs, CompressionLevel.Optimal, leaveOpen: true))
|
|
{
|
|
ds.Write(utf8Bytes, 0, utf8Bytes.Length);
|
|
}
|
|
|
|
compressedBytes = compMs.ToArray();
|
|
}
|
|
|
|
// 既存テンプレートがあればそこから Local File Header、Salt、Central Directory を引き継ぐ
|
|
byte[] salt = new byte[16];
|
|
byte[] lfhHeader;
|
|
byte[] cdAndEocdTemplate;
|
|
bool hasDataDescriptor = true;
|
|
|
|
if (existingTemplate != null && existingTemplate.Length > 120 &&
|
|
existingTemplate[0] == 0x50 && existingTemplate[1] == 0x4B)
|
|
{
|
|
int fnLen = BitConverter.ToUInt16(existingTemplate, 26);
|
|
int exLen = BitConverter.ToUInt16(existingTemplate, 28);
|
|
int dataOffset = 30 + fnLen + exLen;
|
|
ushort flags = BitConverter.ToUInt16(existingTemplate, 6);
|
|
hasDataDescriptor = (flags & 0x0008) != 0;
|
|
|
|
lfhHeader = new byte[dataOffset];
|
|
Buffer.BlockCopy(existingTemplate, 0, lfhHeader, 0, dataOffset);
|
|
Buffer.BlockCopy(existingTemplate, dataOffset, salt, 0, 16);
|
|
|
|
int cdOffset = -1;
|
|
for (int i = existingTemplate.Length - 22; i >= dataOffset + 18; i--)
|
|
{
|
|
if (existingTemplate[i] == 0x50 && existingTemplate[i + 1] == 0x4B &&
|
|
existingTemplate[i + 2] == 0x01 && existingTemplate[i + 3] == 0x02)
|
|
{
|
|
cdOffset = i;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (cdOffset > 0)
|
|
{
|
|
int tailLen = existingTemplate.Length - cdOffset;
|
|
cdAndEocdTemplate = new byte[tailLen];
|
|
Buffer.BlockCopy(existingTemplate, cdOffset, cdAndEocdTemplate, 0, tailLen);
|
|
}
|
|
else
|
|
{
|
|
cdAndEocdTemplate = Array.Empty<byte>();
|
|
}
|
|
}
|
|
else
|
|
{
|
|
RandomNumberGenerator.Fill(salt);
|
|
lfhHeader = Array.Empty<byte>();
|
|
cdAndEocdTemplate = Array.Empty<byte>();
|
|
}
|
|
|
|
byte[] keyMat = Rfc2898DeriveBytes.Pbkdf2(password, salt, 1000, HashAlgorithmName.SHA1, 66);
|
|
byte[] aesKey = new byte[32];
|
|
byte[] hmacKey = new byte[32];
|
|
byte[] pwv = new byte[2];
|
|
Buffer.BlockCopy(keyMat, 0, aesKey, 0, 32);
|
|
Buffer.BlockCopy(keyMat, 32, hmacKey, 0, 32);
|
|
Buffer.BlockCopy(keyMat, 64, pwv, 0, 2);
|
|
|
|
byte[] cipherBytes = NwjsSaveService.TransformAes256Ctr(compressedBytes, aesKey);
|
|
|
|
byte[] authCode = new byte[10];
|
|
using (var hmac = new HMACSHA1(hmacKey))
|
|
{
|
|
byte[] fullHash = hmac.ComputeHash(cipherBytes);
|
|
Buffer.BlockCopy(fullHash, 0, authCode, 0, 10);
|
|
}
|
|
|
|
uint totalCompSize = (uint)(16 + 2 + cipherBytes.Length + 10);
|
|
uint totalUncompSize = (uint)utf8Bytes.Length;
|
|
|
|
using var outMs = new MemoryStream();
|
|
using var bw = new BinaryWriter(outMs);
|
|
|
|
if (lfhHeader.Length > 0 && cdAndEocdTemplate.Length > 0)
|
|
{
|
|
if (!hasDataDescriptor)
|
|
{
|
|
BitConverter.GetBytes(totalCompSize).CopyTo(lfhHeader, 18);
|
|
BitConverter.GetBytes(totalUncompSize).CopyTo(lfhHeader, 22);
|
|
}
|
|
|
|
bw.Write(lfhHeader);
|
|
bw.Write(salt);
|
|
bw.Write(pwv);
|
|
bw.Write(cipherBytes);
|
|
bw.Write(authCode);
|
|
|
|
if (hasDataDescriptor)
|
|
{
|
|
bw.Write((uint)0); // CRC-32 (AE-2 は 0)
|
|
bw.Write(totalCompSize);
|
|
bw.Write(totalUncompSize);
|
|
}
|
|
|
|
uint newCdOffset = (uint)outMs.Position;
|
|
|
|
// Central Directory 内の compSize (offset 20) と uncompSize (offset 24) を更新
|
|
BitConverter.GetBytes(totalCompSize).CopyTo(cdAndEocdTemplate, 20);
|
|
BitConverter.GetBytes(totalUncompSize).CopyTo(cdAndEocdTemplate, 24);
|
|
|
|
// EOCD (50 4B 05 06) を探して cdOffset (offset +16) を更新
|
|
for (int i = cdAndEocdTemplate.Length - 22; i >= 0; i--)
|
|
{
|
|
if (cdAndEocdTemplate[i] == 0x50 && cdAndEocdTemplate[i + 1] == 0x4B &&
|
|
cdAndEocdTemplate[i + 2] == 0x05 && cdAndEocdTemplate[i + 3] == 0x06)
|
|
{
|
|
BitConverter.GetBytes(newCdOffset).CopyTo(cdAndEocdTemplate, i + 16);
|
|
break;
|
|
}
|
|
}
|
|
|
|
bw.Write(cdAndEocdTemplate);
|
|
}
|
|
|
|
return outMs.ToArray();
|
|
}
|
|
|
|
/// <summary>
|
|
/// WinZip AE-2 仕様の AES-256-CTR(リトルエンディアンカウンタ 1 開始)で暗号化・復号を行います。
|
|
/// </summary>
|
|
private static byte[] TransformAes256Ctr(byte[] input, byte[] aesKey)
|
|
{
|
|
byte[] output = new byte[input.Length];
|
|
using var aes = Aes.Create();
|
|
aes.Mode = CipherMode.ECB;
|
|
aes.Padding = PaddingMode.None;
|
|
aes.Key = aesKey;
|
|
|
|
using ICryptoTransform encryptor = aes.CreateEncryptor();
|
|
byte[] counter = new byte[16];
|
|
byte[] keystream = new byte[16];
|
|
int blockCount = (input.Length + 15) / 16;
|
|
|
|
for (int b = 0; b < blockCount; b++)
|
|
{
|
|
int cVal = b + 1;
|
|
counter[0] = (byte)(cVal & 0xFF);
|
|
counter[1] = (byte)((cVal >> 8) & 0xFF);
|
|
counter[2] = (byte)((cVal >> 16) & 0xFF);
|
|
counter[3] = (byte)((cVal >> 24) & 0xFF);
|
|
|
|
encryptor.TransformBlock(counter, 0, 16, keystream, 0);
|
|
int offset = b * 16;
|
|
int rem = Math.Min(16, input.Length - offset);
|
|
for (int j = 0; j < rem; j++)
|
|
{
|
|
output[offset + j] = (byte)(input[offset + j] ^ keystream[j]);
|
|
}
|
|
}
|
|
|
|
return output;
|
|
}
|
|
|
|
/// <summary>
|
|
/// GameCreator のセーブデータ(gamedataX.gcdata または life.gcdata)から GUI 編集用エントリを抽出します。
|
|
/// </summary>
|
|
private static void ExtractGameCreatorEntries(
|
|
JsonNode rootNode,
|
|
List<NwjsSaveEntryItem> entries,
|
|
Dictionary<int, string> itemNames)
|
|
{
|
|
// パターンA: life.gcdata ({"variable": {"variables": [...], "switchs": [...], "strings": [...]}})
|
|
if (rootNode is JsonObject rootObj && rootObj["variable"] is JsonObject lifeVarObj)
|
|
{
|
|
NwjsSaveService.ExtractGcVariableObjectEntries(
|
|
lifeVarObj,
|
|
"variable",
|
|
"🌍 ワールド永続変数 (life.gcdata)",
|
|
"🌍 ワールド永続スイッチ (CG・回想)",
|
|
"🌍 ワールド永続文字列",
|
|
entries);
|
|
return;
|
|
}
|
|
|
|
// パターンB: gamedataX.gcdata (トップレベル配列 [0..16])
|
|
if (rootNode is JsonArray rootArr)
|
|
{
|
|
// [2] 現在のシーンID
|
|
if (rootArr.Count > 2 && rootArr[2] is JsonValue sceneVal)
|
|
{
|
|
entries.Add(NwjsSaveService.CreateEntry(
|
|
"💰 基本・ステータス",
|
|
"[2]",
|
|
"🗺️ 現在のマップ・シーンID ([2])",
|
|
"Number",
|
|
sceneVal.ToString()));
|
|
}
|
|
|
|
// [5] Player Data (gold, package, party, sceneObject, カスタム属性)
|
|
if (rootArr.Count > 5 && rootArr[5] is JsonObject pData)
|
|
{
|
|
foreach (var kv in pData)
|
|
{
|
|
if (kv.Value is JsonValue jv)
|
|
{
|
|
string vType = NwjsSaveService.GetJsonValueTypeString(jv);
|
|
string label = NwjsSaveService.GetFriendlyPropertyLabel(kv.Key);
|
|
entries.Add(NwjsSaveService.CreateEntry(
|
|
"💰 基本・ステータス",
|
|
"[5]." + kv.Key,
|
|
label,
|
|
vType,
|
|
NwjsSaveService.GetJsonValueDisplayString(jv)));
|
|
}
|
|
}
|
|
|
|
// sceneObject の移動速度・座標など
|
|
if (pData["sceneObject"] is JsonObject soObj)
|
|
{
|
|
string[] soKeys = new[] { "moveSpeed", "x", "y", "avatarID", "avatarFPS", "through" };
|
|
foreach (string sk in soKeys)
|
|
{
|
|
if (soObj[sk] is JsonValue sjv)
|
|
{
|
|
entries.Add(NwjsSaveService.CreateEntry(
|
|
"💰 基本・ステータス",
|
|
"[5].sceneObject." + sk,
|
|
"🏃 プレイヤーキャラ: " + NwjsSaveService.GetFriendlyPropertyLabel(sk),
|
|
NwjsSaveService.GetJsonValueTypeString(sjv),
|
|
NwjsSaveService.GetJsonValueDisplayString(sjv)));
|
|
}
|
|
}
|
|
}
|
|
|
|
// package (所持アイテム)
|
|
if (pData["package"] is JsonArray pkgArr)
|
|
{
|
|
for (int i = 0; i < pkgArr.Count; i++)
|
|
{
|
|
if (pkgArr[i] is JsonObject pkgItem && pkgItem["number"] is JsonValue numVal)
|
|
{
|
|
int itemId = -1;
|
|
if (pkgItem["item"] is JsonObject innerItem && innerItem["id"] is JsonValue idV)
|
|
{
|
|
int.TryParse(idV.ToString(), out itemId);
|
|
}
|
|
else if (pkgItem["id"] is JsonValue idV2)
|
|
{
|
|
int.TryParse(idV2.ToString(), out itemId);
|
|
}
|
|
|
|
string itemName = (itemId > 0 && itemNames.TryGetValue(itemId, out string? n))
|
|
? n
|
|
: $"アイテム ID:{itemId}";
|
|
|
|
entries.Add(NwjsSaveService.CreateEntry(
|
|
"🎒 所持アイテム",
|
|
$"[5].package[{i}].number",
|
|
$"🎒 [{itemId}] {itemName} の所持数",
|
|
"Number",
|
|
numVal.ToString()));
|
|
}
|
|
}
|
|
}
|
|
|
|
// party (パーティメンバー)
|
|
if (pData["party"] is JsonArray partyArr)
|
|
{
|
|
for (int i = 0; i < partyArr.Count; i++)
|
|
{
|
|
if (partyArr[i] is JsonObject memberObj)
|
|
{
|
|
foreach (var kv in memberObj)
|
|
{
|
|
if (kv.Value is JsonValue mjv)
|
|
{
|
|
entries.Add(NwjsSaveService.CreateEntry(
|
|
"💰 基本・ステータス",
|
|
$"[5].party[{i}].{kv.Key}",
|
|
$"⚔️ パーティ[{i}] {NwjsSaveService.GetFriendlyPropertyLabel(kv.Key)}",
|
|
NwjsSaveService.GetJsonValueTypeString(mjv),
|
|
NwjsSaveService.GetJsonValueDisplayString(mjv)));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// [4] Player Variable (variables, switchs, strings)
|
|
if (rootArr.Count > 4 && rootArr[4] is JsonObject pVarObj)
|
|
{
|
|
NwjsSaveService.ExtractGcVariableObjectEntries(
|
|
pVarObj,
|
|
"[4]",
|
|
"🔢 プレイヤー数値変数",
|
|
"🔘 プレイヤースイッチ",
|
|
"📝 プレイヤー文字列",
|
|
entries);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static void ExtractGcVariableObjectEntries(
|
|
JsonObject varContainer,
|
|
string basePath,
|
|
string numCat,
|
|
string swCat,
|
|
string strCat,
|
|
List<NwjsSaveEntryItem> entries)
|
|
{
|
|
JsonArray? strsArr = varContainer["strings"] as JsonArray;
|
|
|
|
if (varContainer["variables"] is JsonArray varsArr)
|
|
{
|
|
for (int i = 0; i < varsArr.Count; i++)
|
|
{
|
|
if (varsArr[i] is JsonValue jv)
|
|
{
|
|
string hint = string.Empty;
|
|
if (strsArr != null && i < strsArr.Count && strsArr[i] is JsonValue sv)
|
|
{
|
|
string sText = sv.ToString();
|
|
if (!string.IsNullOrWhiteSpace(sText) && sText.Length <= 25)
|
|
{
|
|
hint = $" ({sText})";
|
|
}
|
|
}
|
|
|
|
entries.Add(NwjsSaveService.CreateEntry(
|
|
numCat,
|
|
$"{basePath}.variables[{i}]",
|
|
$"変数 [{i:D4}]{hint}",
|
|
"Number",
|
|
NwjsSaveService.GetJsonValueDisplayString(jv)));
|
|
}
|
|
}
|
|
}
|
|
|
|
string swPropName = varContainer.ContainsKey("switches") ? "switches" : "switchs";
|
|
if (varContainer[swPropName] is JsonArray swArr)
|
|
{
|
|
for (int i = 0; i < swArr.Count; i++)
|
|
{
|
|
if (swArr[i] is JsonValue jv)
|
|
{
|
|
entries.Add(NwjsSaveService.CreateEntry(
|
|
swCat,
|
|
$"{basePath}.{swPropName}[{i}]",
|
|
$"スイッチ [{i:D4}]",
|
|
"Number",
|
|
NwjsSaveService.GetJsonValueDisplayString(jv)));
|
|
}
|
|
}
|
|
}
|
|
|
|
if (strsArr != null)
|
|
{
|
|
for (int i = 0; i < strsArr.Count; i++)
|
|
{
|
|
if (strsArr[i] is JsonValue jv)
|
|
{
|
|
entries.Add(NwjsSaveService.CreateEntry(
|
|
strCat,
|
|
$"{basePath}.strings[{i}]",
|
|
$"文字列 [{i:D4}]",
|
|
"String",
|
|
NwjsSaveService.GetJsonValueDisplayString(jv)));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// プレーンな JSON セーブデータから GUI 編集用エントリを再帰的に抽出します。
|
|
/// </summary>
|
|
private static void ExtractPlainJsonEntries(JsonNode rootNode, List<NwjsSaveEntryItem> entries)
|
|
{
|
|
NwjsSaveService.WalkJsonNode(rootNode, string.Empty, 0, entries);
|
|
}
|
|
|
|
private static void WalkJsonNode(JsonNode? node, string currentPath, int depth, List<NwjsSaveEntryItem> entries)
|
|
{
|
|
if (node == null || depth > 5)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (node is JsonObject obj)
|
|
{
|
|
foreach (var kv in obj)
|
|
{
|
|
string childPath = string.IsNullOrEmpty(currentPath) ? kv.Key : (currentPath + "." + kv.Key);
|
|
if (kv.Value is JsonValue jv)
|
|
{
|
|
string category = depth == 0
|
|
? "💰 基本・ステータス"
|
|
: (currentPath.Contains("inventory", StringComparison.OrdinalIgnoreCase) || currentPath.Contains("item", StringComparison.OrdinalIgnoreCase)
|
|
? "🎒 所持アイテム"
|
|
: (currentPath.Contains("flag", StringComparison.OrdinalIgnoreCase) || currentPath.Contains("switch", StringComparison.OrdinalIgnoreCase)
|
|
? "🔘 スイッチ・フラグ"
|
|
: "📦 JSONプロパティ"));
|
|
|
|
string displayKey = depth == 0
|
|
? NwjsSaveService.GetFriendlyPropertyLabel(kv.Key)
|
|
: $"{currentPath}.{NwjsSaveService.GetFriendlyPropertyLabel(kv.Key)}";
|
|
|
|
entries.Add(NwjsSaveService.CreateEntry(
|
|
category,
|
|
childPath,
|
|
displayKey,
|
|
NwjsSaveService.GetJsonValueTypeString(jv),
|
|
NwjsSaveService.GetJsonValueDisplayString(jv)));
|
|
}
|
|
else if (kv.Value is JsonObject || kv.Value is JsonArray)
|
|
{
|
|
NwjsSaveService.WalkJsonNode(kv.Value, childPath, depth + 1, entries);
|
|
}
|
|
}
|
|
}
|
|
else if (node is JsonArray arr)
|
|
{
|
|
for (int i = 0; i < arr.Count && i < 500; i++)
|
|
{
|
|
string childPath = $"{currentPath}[{i}]";
|
|
if (arr[i] is JsonValue jv)
|
|
{
|
|
entries.Add(NwjsSaveService.CreateEntry(
|
|
"📦 JSONプロパティ",
|
|
childPath,
|
|
childPath,
|
|
NwjsSaveService.GetJsonValueTypeString(jv),
|
|
NwjsSaveService.GetJsonValueDisplayString(jv)));
|
|
}
|
|
else if (arr[i] is JsonObject || arr[i] is JsonArray)
|
|
{
|
|
NwjsSaveService.WalkJsonNode(arr[i], childPath, depth + 1, entries);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private static NwjsSaveEntryItem CreateEntry(string category, string jsonPath, string displayKey, string valueType, string valText)
|
|
{
|
|
var item = new NwjsSaveEntryItem
|
|
{
|
|
Category = category,
|
|
JsonPath = jsonPath,
|
|
DisplayKey = displayKey,
|
|
ValueType = valueType
|
|
};
|
|
item.InitializeValue(valText);
|
|
return item;
|
|
}
|
|
|
|
private static string GetFriendlyPropertyLabel(string key)
|
|
{
|
|
if (NwjsSaveService.KnownPropertyLabels.TryGetValue(key, out string? label))
|
|
{
|
|
return label;
|
|
}
|
|
|
|
return key;
|
|
}
|
|
|
|
private static string GetJsonValueTypeString(JsonValue jv)
|
|
{
|
|
JsonElement el = jv.GetValue<JsonElement>();
|
|
return el.ValueKind switch
|
|
{
|
|
JsonValueKind.Number => "Number",
|
|
JsonValueKind.True => "Boolean",
|
|
JsonValueKind.False => "Boolean",
|
|
_ => "String"
|
|
};
|
|
}
|
|
|
|
private static string GetJsonValueDisplayString(JsonValue jv)
|
|
{
|
|
JsonElement el = jv.GetValue<JsonElement>();
|
|
return el.ValueKind switch
|
|
{
|
|
JsonValueKind.String => el.GetString() ?? string.Empty,
|
|
JsonValueKind.True => "true",
|
|
JsonValueKind.False => "false",
|
|
_ => el.GetRawText()
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// 単一の NwjsSaveEntryItem の変更を JsonNode ツリーへ反映します。
|
|
/// </summary>
|
|
private static void ApplySingleEntryToNode(JsonNode rootNode, NwjsSaveEntryItem entry)
|
|
{
|
|
try
|
|
{
|
|
string path = entry.JsonPath;
|
|
if (string.IsNullOrEmpty(path))
|
|
{
|
|
return;
|
|
}
|
|
|
|
// パスをドットとブラケットでトークン分解 (例: "[5].package[0].number" -> "[5]", "package", "[0]", "number")
|
|
var tokens = new List<string>();
|
|
int i = 0;
|
|
while (i < path.Length)
|
|
{
|
|
if (path[i] == '.')
|
|
{
|
|
i++;
|
|
continue;
|
|
}
|
|
|
|
if (path[i] == '[')
|
|
{
|
|
int closeIdx = path.IndexOf(']', i);
|
|
if (closeIdx > i)
|
|
{
|
|
tokens.Add(path.Substring(i, closeIdx - i + 1));
|
|
i = closeIdx + 1;
|
|
continue;
|
|
}
|
|
}
|
|
|
|
int nextDot = path.IndexOf('.', i);
|
|
int nextBracket = path.IndexOf('[', i);
|
|
int end = path.Length;
|
|
if (nextDot >= 0 && nextDot < end)
|
|
{
|
|
end = nextDot;
|
|
}
|
|
|
|
if (nextBracket >= 0 && nextBracket < end)
|
|
{
|
|
end = nextBracket;
|
|
}
|
|
|
|
tokens.Add(path.Substring(i, end - i));
|
|
i = end;
|
|
}
|
|
|
|
if (tokens.Count == 0)
|
|
{
|
|
return;
|
|
}
|
|
|
|
JsonNode? current = rootNode;
|
|
for (int t = 0; t < tokens.Count - 1; t++)
|
|
{
|
|
if (current == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
string tk = tokens[t];
|
|
if (tk.StartsWith('[') && tk.EndsWith(']'))
|
|
{
|
|
if (int.TryParse(tk.AsSpan(1, tk.Length - 2), out int arrIdx) && current is JsonArray arr && arrIdx >= 0 && arrIdx < arr.Count)
|
|
{
|
|
current = arr[arrIdx];
|
|
}
|
|
else
|
|
{
|
|
return;
|
|
}
|
|
}
|
|
else if (current is JsonObject obj)
|
|
{
|
|
current = obj[tk];
|
|
}
|
|
else
|
|
{
|
|
return;
|
|
}
|
|
}
|
|
|
|
string lastToken = tokens[tokens.Count - 1];
|
|
JsonNode? newValueNode = NwjsSaveService.CreateJsonValueNode(entry.ValueType, entry.ValueText);
|
|
|
|
if (lastToken.StartsWith('[') && lastToken.EndsWith(']'))
|
|
{
|
|
if (int.TryParse(lastToken.AsSpan(1, lastToken.Length - 2), out int arrIdx) &&
|
|
current is JsonArray targetArr &&
|
|
arrIdx >= 0 && arrIdx < targetArr.Count)
|
|
{
|
|
targetArr[arrIdx] = newValueNode;
|
|
}
|
|
}
|
|
else if (current is JsonObject targetObj)
|
|
{
|
|
targetObj[lastToken] = newValueNode;
|
|
}
|
|
}
|
|
catch
|
|
{
|
|
}
|
|
}
|
|
|
|
private static JsonNode? CreateJsonValueNode(string valueType, string text)
|
|
{
|
|
if (string.Equals(valueType, "Boolean", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
bool b = string.Equals(text?.Trim(), "true", StringComparison.OrdinalIgnoreCase) ||
|
|
string.Equals(text?.Trim(), "1", StringComparison.OrdinalIgnoreCase);
|
|
return JsonValue.Create(b);
|
|
}
|
|
|
|
if (string.Equals(valueType, "Number", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
string trimmed = text?.Trim() ?? "0";
|
|
if (long.TryParse(trimmed, NumberStyles.Integer, CultureInfo.InvariantCulture, out long lVal))
|
|
{
|
|
return JsonValue.Create(lVal);
|
|
}
|
|
|
|
if (double.TryParse(trimmed, NumberStyles.Float, CultureInfo.InvariantCulture, out double dVal))
|
|
{
|
|
return JsonValue.Create(dVal);
|
|
}
|
|
|
|
return JsonValue.Create(0);
|
|
}
|
|
|
|
return JsonValue.Create(text ?? string.Empty);
|
|
}
|
|
|
|
#endregion
|
|
}
|
|
}
|