// Engines/Nwjs/NwjsSaveEditorDialog.xaml.cs — NW.js セーブデータ改造エディタダイアログ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Windows; using System.Windows.Controls; using GameLauncher.Engines.Tkool; namespace GameLauncher.Engines.Nwjs { /// /// NW.js 分類ゲーム(GameCreator .gcdata 暗号化セーブおよびカスタム HTML5/JS .json セーブ)の /// ステータス・変数・所持品・フラグを編集・バックアップ・復元するダイアログウィンドウ。 /// public partial class NwjsSaveEditorDialog : Window { #region □定数(Private) /// /// カテゴリフィルタの「すべて表示」項目文字列。 /// private const string AllCategoriesLabel = "すべて表示"; #endregion #region □変数(Private) private readonly TkoolGameItem _game; private List _saveFiles = new List(); private NwjsLoadedSaveDocument? _currentDoc; private List _filteredEntries = new List(); private bool _isSuppressingEvents; #endregion #region □コンストラクタ /// /// クラスの新しいインスタンスを初期化します。 /// /// 編集対象の NW.js ゲームアイテム public NwjsSaveEditorDialog(TkoolGameItem game) { this._game = game ?? throw new ArgumentNullException(nameof(game)); this.InitializeComponent(); this.GameTitleText.Text = $"— {this._game.Title}"; this.LoadSaveFileList(); } #endregion #region □イベント private void SaveFileComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (this._isSuppressingEvents) { return; } if (this.SaveFileComboBox.SelectedItem is NwjsSaveFileInfo selectedFile) { this.LoadSelectedSaveFile(selectedFile); } } private void ReloadButton_Click(object sender, RoutedEventArgs e) { this.LoadSaveFileList(); } private void OpenFolderButton_Click(object sender, RoutedEventArgs e) { string targetDir = this._game.RootDirectory; if (this.SaveFileComboBox.SelectedItem is NwjsSaveFileInfo selectedFile && !string.IsNullOrEmpty(selectedFile.FilePath)) { string? dir = Path.GetDirectoryName(selectedFile.FilePath); if (!string.IsNullOrEmpty(dir) && Directory.Exists(dir)) { targetDir = dir; } } if (Directory.Exists(targetDir)) { try { Process.Start(new ProcessStartInfo { FileName = targetDir, UseShellExecute = true }); } catch (Exception ex) { MessageBox.Show(this, $"フォルダを開けませんでした:\n{ex.Message}", "エラー", MessageBoxButton.OK, MessageBoxImage.Error); } } } private void FilterChanged(object sender, EventArgs e) { if (this._isSuppressingEvents) { return; } this.ApplyFilter(); } private void EditorTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (this._isSuppressingEvents || this._currentDoc == null) { return; } if (!ReferenceEquals(e.Source, this.EditorTabControl)) { return; } // タブ2 (JSON直接編集) に切り替えた際、GUIテーブルでの変更をJSON文字列に同期する if (this.EditorTabControl.SelectedIndex == 1) { string updatedJson = NwjsSaveService.ApplyEntriesToDocument(this._currentDoc); this.RawJsonTextBox.Text = updatedJson; } } private void QuickMaxGold_Click(object sender, RoutedEventArgs e) { if (this._currentDoc == null) { return; } int count = 0; foreach (NwjsSaveEntryItem item in this._currentDoc.Entries) { if (item.ValueType == "Number" && (item.JsonPath.EndsWith("money", StringComparison.OrdinalIgnoreCase) || item.JsonPath.EndsWith("gold", StringComparison.OrdinalIgnoreCase) || item.DisplayKey.Contains("所持金", StringComparison.OrdinalIgnoreCase))) { item.ValueText = "9999999"; count++; } } this.RefreshGridAndStatus(count > 0 ? $"💰 所持金項目 ({count} 件) を 9,999,999 に設定しました。「💾 変更をセーブデータに保存」で確定します。" : "ℹ️ このセーブファイル内に直接の所持金プロパティ (gold / money) が見つかりませんでした。数値変数またはゲーム内チート [F10] をご利用ください。"); } private void QuickZeroDebt_Click(object sender, RoutedEventArgs e) { if (this._currentDoc == null) { return; } int count = 0; foreach (NwjsSaveEntryItem item in this._currentDoc.Entries) { if (item.ValueType == "Number" && (item.JsonPath.EndsWith("debt", StringComparison.OrdinalIgnoreCase) || item.DisplayKey.Contains("借金残高", StringComparison.OrdinalIgnoreCase))) { item.ValueText = "0"; count++; } } this.RefreshGridAndStatus(count > 0 ? $"🧾 借金項目 ({count} 件) を 0 に設定しました。「💾 変更をセーブデータに保存」で確定します。" : "ℹ️ このセーブファイル内に借金プロパティ (debt) はありません。"); } private void QuickMaxStamina_Click(object sender, RoutedEventArgs e) { if (this._currentDoc == null) { return; } int count = 0; foreach (NwjsSaveEntryItem item in this._currentDoc.Entries) { if (item.ValueType == "Number" && (item.JsonPath.EndsWith("stamina", StringComparison.OrdinalIgnoreCase) || item.JsonPath.EndsWith("maxStamina", StringComparison.OrdinalIgnoreCase) || item.JsonPath.EndsWith(".hp", StringComparison.OrdinalIgnoreCase) || item.JsonPath.EndsWith(".maxHp", StringComparison.OrdinalIgnoreCase) || item.JsonPath.EndsWith(".mp", StringComparison.OrdinalIgnoreCase) || item.JsonPath.EndsWith(".maxMp", StringComparison.OrdinalIgnoreCase))) { item.ValueText = "999"; count++; } } this.RefreshGridAndStatus(count > 0 ? $"❤️ スタミナ・HP/MP 項目 ({count} 件) を 999 に設定しました。「💾 変更をセーブデータに保存」で確定します。" : "ℹ️ 該当するスタミナ・HPプロパティが見つかりませんでした。変数検索またはゲーム内チート [F10] をご利用ください。"); } private void QuickMaxItems_Click(object sender, RoutedEventArgs e) { if (this._currentDoc == null) { return; } int count = 0; foreach (NwjsSaveEntryItem item in this._currentDoc.Entries) { if (item.Category == "🎒 所持アイテム" && item.ValueType == "Number") { item.ValueText = "99"; count++; } } this.RefreshGridAndStatus(count > 0 ? $"🎒 所持アイテム ({count} 件) の個数を 99 に設定しました。「💾 変更をセーブデータに保存」で確定します。" : "ℹ️ 現在所持しているアイテムエントリが 0 件です(新規アイテムの入手はゲーム内チートメニュー [F10] から行えます)。"); } private void QuickUnlockAllSwitches_Click(object sender, RoutedEventArgs e) { if (this._currentDoc == null) { return; } int count = 0; foreach (NwjsSaveEntryItem item in this._currentDoc.Entries) { if (item.JsonPath.Equals("userUnlockAll", StringComparison.OrdinalIgnoreCase)) { item.ValueText = "true"; count++; } else if (item.Category.Contains("スイッチ", StringComparison.OrdinalIgnoreCase) || item.Category.Contains("フラグ", StringComparison.OrdinalIgnoreCase)) { item.ValueText = item.ValueType == "Boolean" ? "true" : "1"; count++; } } this.RefreshGridAndStatus(count > 0 ? $"🔓 スイッチ・解放フラグ ({count} 件) を ON に設定しました。「💾 変更をセーブデータに保存」で確定します。" : "ℹ️ 対象のスイッチ・解放フラグ項目が見つかりませんでした。"); } private void ApplyBulkValue_Click(object sender, RoutedEventArgs e) { if (this._currentDoc == null || this._filteredEntries.Count == 0) { return; } string bulkVal = this.BulkValueTextBox.Text?.Trim() ?? string.Empty; if (string.IsNullOrEmpty(bulkVal)) { return; } int count = 0; foreach (NwjsSaveEntryItem item in this._filteredEntries) { item.ValueText = bulkVal; count++; } this.RefreshGridAndStatus($"✏️ 現在表示中の {count} 件の項目に「{bulkVal}」を一括設定しました。"); } private void SaveButton_Click(object sender, RoutedEventArgs e) { if (this._currentDoc == null) { return; } try { this.EntriesDataGrid.CommitEdit(DataGridEditingUnit.Cell, true); this.EntriesDataGrid.CommitEdit(DataGridEditingUnit.Row, true); string jsonToSave; if (this.EditorTabControl.SelectedIndex == 1) { jsonToSave = this.RawJsonTextBox.Text; } else { jsonToSave = NwjsSaveService.ApplyEntriesToDocument(this._currentDoc); this.RawJsonTextBox.Text = jsonToSave; } NwjsSaveService.SaveToFile(this._currentDoc.FileInfo, this._game.RootDirectory, jsonToSave, createBackup: true); foreach (NwjsSaveEntryItem entry in this._currentDoc.Entries) { if (entry.IsModified) { entry.InitializeValue(entry.ValueText); } } this.RestoreBackupButton.IsEnabled = this._currentDoc.FileInfo.HasBackup; this.StatusTextBlock.Text = $"✔ 保存完了: {this._currentDoc.FileInfo.DisplayName} (初回バックアップ保護済み)"; MessageBox.Show( this, $"セーブデータを保存しました!\n\n対象: {this._currentDoc.FileInfo.DisplayName}\n※元のセーブデータは自動バックアップされています。", "セーブデータ保存完了", MessageBoxButton.OK, MessageBoxImage.Information); } catch (Exception ex) { MessageBox.Show( this, $"セーブデータの保存中にエラーが発生しました:\n{ex.Message}", "保存エラー", MessageBoxButton.OK, MessageBoxImage.Error); } } private void RestoreBackupButton_Click(object sender, RoutedEventArgs e) { if (this._currentDoc == null || !this._currentDoc.FileInfo.HasBackup) { return; } MessageBoxResult res = MessageBox.Show( this, $"バックアップから元のセーブデータを復元しますか?\n\n対象: {this._currentDoc.FileInfo.DisplayName}", "バックアップ復元の確認", MessageBoxButton.YesNo, MessageBoxImage.Question); if (res != MessageBoxResult.Yes) { return; } try { if (NwjsSaveService.RestoreBackup(this._currentDoc.FileInfo)) { this.LoadSelectedSaveFile(this._currentDoc.FileInfo); this.StatusTextBlock.Text = $"⏪ バックアップから復元しました: {this._currentDoc.FileInfo.DisplayName}"; } } catch (Exception ex) { MessageBox.Show( this, $"バックアップの復元に失敗しました:\n{ex.Message}", "復元エラー", MessageBoxButton.OK, MessageBoxImage.Error); } } private void CloseButton_Click(object sender, RoutedEventArgs e) { this.Close(); } #endregion #region □メソッド(Private) private void LoadSaveFileList() { this._isSuppressingEvents = true; try { string? previousPath = (this.SaveFileComboBox.SelectedItem as NwjsSaveFileInfo)?.FilePath; this._saveFiles = NwjsSaveService.FindSaveFiles(this._game.RootDirectory, this._game.FolderName); this.SaveFileComboBox.ItemsSource = this._saveFiles; if (this._saveFiles.Count == 0) { this._currentDoc = null; this.EntriesDataGrid.ItemsSource = null; this.RawJsonTextBox.Text = string.Empty; this.SaveButton.IsEnabled = false; this.RestoreBackupButton.IsEnabled = false; this.StatusTextBlock.Text = "⚠️ セーブファイルが見つかりません。ゲームを起動して一度セーブを作成するか、ゲーム内チート [F10] をご利用ください。"; return; } NwjsSaveFileInfo? target = null; if (!string.IsNullOrEmpty(previousPath)) { target = this._saveFiles.FirstOrDefault(f => string.Equals(f.FilePath, previousPath, StringComparison.OrdinalIgnoreCase)); } target ??= this._saveFiles[0]; this.SaveFileComboBox.SelectedItem = target; this._isSuppressingEvents = false; this.LoadSelectedSaveFile(target); } finally { this._isSuppressingEvents = false; } } private void LoadSelectedSaveFile(NwjsSaveFileInfo fileInfo) { try { this._currentDoc = NwjsSaveService.LoadSaveFile(fileInfo, this._game.RootDirectory); this.RawJsonTextBox.Text = this._currentDoc.FormattedJson; this.SaveButton.IsEnabled = true; this.RestoreBackupButton.IsEnabled = fileInfo.HasBackup; // カテゴリ一覧を更新 this._isSuppressingEvents = true; var categories = new List { NwjsSaveEditorDialog.AllCategoriesLabel }; categories.AddRange(this._currentDoc.Entries.Select(x => x.Category).Distinct()); this.CategoryFilterComboBox.ItemsSource = categories; this.CategoryFilterComboBox.SelectedIndex = 0; this._isSuppressingEvents = false; this.ApplyFilter(); string formatLabel = fileInfo.FormatKind == NwjsSaveFormatKind.GameCreatorGcData ? "GameCreator 暗号化セーブ (.gcdata 復号済)" : "JSON セーブデータ"; this.StatusTextBlock.Text = $"✔ 読込完了: {fileInfo.DisplayName} [{formatLabel}] — 全 {this._currentDoc.Entries.Count} 項目"; } catch (Exception ex) { this._currentDoc = null; this.EntriesDataGrid.ItemsSource = null; this.RawJsonTextBox.Text = string.Empty; this.SaveButton.IsEnabled = false; this.RestoreBackupButton.IsEnabled = false; this.StatusTextBlock.Text = $"❌ 読込エラー: {ex.Message}"; } } private void ApplyFilter() { if (this._currentDoc == null) { this._filteredEntries = new List(); this.EntriesDataGrid.ItemsSource = null; return; } string selectedCategory = this.CategoryFilterComboBox.SelectedItem as string ?? NwjsSaveEditorDialog.AllCategoriesLabel; string keyword = this.KeywordFilterTextBox.Text?.Trim() ?? string.Empty; string exactVal = this.ExactValueFilterTextBox.Text?.Trim() ?? string.Empty; IEnumerable query = this._currentDoc.Entries; if (!string.Equals(selectedCategory, NwjsSaveEditorDialog.AllCategoriesLabel, StringComparison.Ordinal)) { query = query.Where(x => string.Equals(x.Category, selectedCategory, StringComparison.Ordinal)); } if (!string.IsNullOrEmpty(keyword)) { query = query.Where(x => x.DisplayKey.Contains(keyword, StringComparison.OrdinalIgnoreCase) || x.JsonPath.Contains(keyword, StringComparison.OrdinalIgnoreCase) || x.ValueText.Contains(keyword, StringComparison.OrdinalIgnoreCase)); } if (!string.IsNullOrEmpty(exactVal)) { query = query.Where(x => string.Equals(x.ValueText.Trim(), exactVal, StringComparison.OrdinalIgnoreCase)); } this._filteredEntries = query.ToList(); this.EntriesDataGrid.ItemsSource = this._filteredEntries; } private void RefreshGridAndStatus(string message) { this.EntriesDataGrid.Items.Refresh(); if (this._currentDoc != null && this.EditorTabControl.SelectedIndex == 1) { this.RawJsonTextBox.Text = NwjsSaveService.ApplyEntriesToDocument(this._currentDoc); } this.StatusTextBlock.Text = message; } #endregion } }