using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.Encodings.Web; using System.Text.Json; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; using Microsoft.Win32; using GameLauncher.Helpers; using GameLauncher.Models; using GameLauncher.Services; using GameLauncher.Services.Codecs; using GameLauncher.Engines.Unity; using GameLauncher.Engines.Nwjs; using GameLauncher.Engines.Wolf; using GameLauncher.Engines.Rgss; using GameLauncher.Engines.Tkool; namespace GameLauncher { /// /// Unityゲームのセーブデータ(PlayerPrefs & ファイル)統合エディタウィンドウ /// public partial class SaveEditorWindow : Window { private readonly UnitySaveManagerService _saveService = new(); public UnityGameItem Game { get; } // PlayerPrefs データ private readonly ObservableCollection _allPrefs = []; private readonly ListCollectionView _prefsView = null!; // ファイル一覧データ private readonly ObservableCollection _saveFiles = []; private SaveFileEntry? _currentSelectedFile; // GUIセーブプロパティデータ private readonly ObservableCollection _guiProperties = []; private readonly ListCollectionView _guiPropsView = null!; private ISaveDataCodec? _currentCodec; // バックアップ一覧データ private readonly ObservableCollection _backups = []; public SaveEditorWindow(UnityGameItem game) { this.InitializeComponent(); this.Game = game; this.lblGameTitle.Text = game.Title; this.lblGameInfo.Text = $"{game.CompanyName} / {game.ProductName} ({game.BackendBadgeText})"; // PlayerPrefs ビュー this._prefsView = (ListCollectionView)CollectionViewSource.GetDefaultView(this._allPrefs); this._prefsView.Filter = this.FilterPrefs; this.dgPlayerPrefs.ItemsSource = this._prefsView; // ファイル一覧 this.lstSaveFiles.ItemsSource = this._saveFiles; // GUI プロパティビュー this._guiPropsView = (ListCollectionView)CollectionViewSource.GetDefaultView(this._guiProperties); this._guiPropsView.Filter = this.FilterGuiProperties; this.dgGuiProperties.ItemsSource = this._guiPropsView; // バックアップ一覧 this.dgBackups.ItemsSource = this._backups; Loaded += this.SaveEditorWindow_Loaded; } private void SaveEditorWindow_Loaded(object sender, RoutedEventArgs e) { this.ReloadPlayerPrefs(); this.ReloadSaveFiles(); this.ReloadBackups(); } // ==================================================================== // PlayerPrefs タブ処理 // ==================================================================== public void ReloadPlayerPrefs() { this._allPrefs.Clear(); if (string.IsNullOrEmpty(this.Game.RegistryPath)) { this.lblStatus.Text = "レジストリ情報が設定されていません (app.info が見つかりませんでした)"; return; } var entries = this._saveService.GetPlayerPrefs(this.Game.RegistryPath); foreach (var entry in entries) { this._allPrefs.Add(entry); } this.lblStatus.Text = $"PlayerPrefs: {entries.Count} 件のキーを読み込みました (HKCU\\{this.Game.RegistryPath})"; } private bool FilterPrefs(object obj) { if (obj is not PlayerPrefsEntry entry) return false; var query = this.txtSearchPrefs.Text.Trim(); if (string.IsNullOrEmpty(query)) return true; return entry.CleanKey.Contains(query, StringComparison.OrdinalIgnoreCase) || entry.RawKey.Contains(query, StringComparison.OrdinalIgnoreCase) || entry.EditValue.Contains(query, StringComparison.OrdinalIgnoreCase); } private void txtSearchPrefs_TextChanged(object sender, TextChangedEventArgs e) { this._prefsView.Refresh(); } private void dgPlayerPrefs_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (this.dgPlayerPrefs.SelectedItem is PlayerPrefsEntry entry) { this.lblSelectedKeyName.Text = entry.CleanKey; this.txtEditValueBar.Text = entry.EditValue; this.txtEditValueBar.IsEnabled = true; this.btnSaveCurrentPref.IsEnabled = true; this.btnDeleteCurrentPref.IsEnabled = true; } else { this.lblSelectedKeyName.Text = "(なし)"; this.txtEditValueBar.Text = string.Empty; this.txtEditValueBar.IsEnabled = false; this.btnSaveCurrentPref.IsEnabled = false; this.btnDeleteCurrentPref.IsEnabled = false; } } private void txtEditValueBar_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { this.SaveCurrentSelectedPref(); } } private void btnSaveCurrentPref_Click(object sender, RoutedEventArgs e) { this.SaveCurrentSelectedPref(); } private void SaveCurrentSelectedPref() { if (this.dgPlayerPrefs.SelectedItem is not PlayerPrefsEntry entry) return; entry.EditValue = this.txtEditValueBar.Text; bool success = this._saveService.SavePlayerPref(this.Game.RegistryPath, entry); if (success) { this.lblStatus.Text = $"キー '{entry.CleanKey}' の値を正常に更新しました。"; this.dgPlayerPrefs.Items.Refresh(); } else { MessageBox.Show($"キー '{entry.CleanKey}' の値の更新に失敗しました。型が正しいか確認してください。", "保存失敗", MessageBoxButton.OK, MessageBoxImage.Error); } } private void btnDeleteCurrentPref_Click(object sender, RoutedEventArgs e) { if (this.dgPlayerPrefs.SelectedItem is not PlayerPrefsEntry entry) return; var res = MessageBox.Show($"キー '{entry.CleanKey}' ({entry.RawKey}) をレジストリから削除しますか?", "キー削除の確認", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (res != MessageBoxResult.Yes) return; if (this._saveService.DeletePlayerPref(this.Game.RegistryPath, entry.RawKey)) { this._allPrefs.Remove(entry); this.lblStatus.Text = $"キー '{entry.CleanKey}' を削除しました。"; } else { MessageBox.Show("キーの削除に失敗しました。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error); } } private void btnAddPref_Click(object sender, RoutedEventArgs e) { var dlg = new AddKeyDialog { Owner = this }; if (dlg.ShowDialog() == true) { if (this._saveService.AddPlayerPref(this.Game.RegistryPath, dlg.KeyName, dlg.KeyType, dlg.KeyValue, out string rawKey)) { this.ReloadPlayerPrefs(); this.lblStatus.Text = $"新規キー '{dlg.KeyName}' ({rawKey}) を追加しました。"; } else { MessageBox.Show("キーの追加に失敗しました。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error); } } } private void btnBackupPrefs_Click(object sender, RoutedEventArgs e) { var backupDir = AppPathHelper.GetGameBackupDirectory(this.Game.FolderName, this.Game.RootDirectory); var result = this._saveService.BackupRegistry(this.Game.RegistryPath, backupDir); if (result != null) { this.ReloadBackups(); this.lblStatus.Text = $"レジストリをバックアップしました: {Path.GetFileName(result)}"; MessageBox.Show($"レジストリをバックアップしました:\n\n{result}", "バックアップ完了", MessageBoxButton.OK, MessageBoxImage.Information); } else { MessageBox.Show("レジストリのバックアップに失敗しました。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error); } } private void btnRestorePrefs_Click(object sender, RoutedEventArgs e) { var backupDir = AppPathHelper.GetGameBackupDirectory(this.Game.FolderName, this.Game.RootDirectory); var dlg = new OpenFileDialog { Title = "復元する .reg ファイルを選択", InitialDirectory = Directory.Exists(backupDir) ? backupDir : AppPathHelper.GetBackupsDirectory(), Filter = "レジストリファイル (*.reg)|*.reg|すべてのファイル (*.*)|*.*" }; if (dlg.ShowDialog() == true) { var res = MessageBox.Show($"ファイル '{Path.GetFileName(dlg.FileName)}' からレジストリを復元しますか?\n現在のPlayerPrefs値は上書きされます。", "復元の確認", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (res != MessageBoxResult.Yes) return; if (this._saveService.RestoreRegistry(dlg.FileName)) { this.ReloadPlayerPrefs(); this.lblStatus.Text = "レジストリを正常に復元しました。"; MessageBox.Show("レジストリを正常に復元しました。", "復元完了", MessageBoxButton.OK, MessageBoxImage.Information); } else { MessageBox.Show("レジストリの復元に失敗しました。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error); } } } private void btnReloadPrefs_Click(object sender, RoutedEventArgs e) { this.ReloadPlayerPrefs(); } private void ctxSavePref_Click(object sender, RoutedEventArgs e) { this.SaveCurrentSelectedPref(); } private void ctxCopyKey_Click(object sender, RoutedEventArgs e) { if (this.dgPlayerPrefs.SelectedItem is PlayerPrefsEntry entry) { Clipboard.SetText(entry.CleanKey); } } private void ctxCopyValue_Click(object sender, RoutedEventArgs e) { if (this.dgPlayerPrefs.SelectedItem is PlayerPrefsEntry entry) { Clipboard.SetText(entry.EditValue); } } private void ctxDeletePref_Click(object sender, RoutedEventArgs e) { this.btnDeleteCurrentPref_Click(sender, e); } // ==================================================================== // セーブファイル タブ処理(GUI / テキスト / 未対応プロンプト) // ==================================================================== public void ReloadSaveFiles() { this._saveFiles.Clear(); var files = this._saveService.GetSaveFiles(this.Game); foreach (var f in files) { this._saveFiles.Add(f); } if (this._saveFiles.Count > 0) { this.lstSaveFiles.SelectedIndex = 0; } else { this.lblCurrentFileName.Text = "セーブファイルは見つかりませんでした"; this.lblCurrentFilePath.Text = string.Empty; this.txtFileContent.Text = string.Empty; this.HideAllEditorPanels(); } } private void HideAllEditorPanels() { this.pnlGuiEditor.Visibility = Visibility.Collapsed; this.pnlTextEditor.Visibility = Visibility.Collapsed; this.pnlUnsupportedBinary.Visibility = Visibility.Collapsed; this.btnFormatJson.Visibility = Visibility.Collapsed; this.btnSaveFileContent.Visibility = Visibility.Collapsed; this.btnSaveGuiProperties.Visibility = Visibility.Collapsed; this.badgeCodec.Visibility = Visibility.Collapsed; } private void lstSaveFiles_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (this.lstSaveFiles.SelectedItem is not SaveFileEntry entry) return; this._currentSelectedFile = entry; this.lblCurrentFileName.Text = entry.FileName; this.lblCurrentFilePath.Text = entry.FilePath; this.HideAllEditorPanels(); // 1. コーデック(対応形式)が存在するか判定 var codec = SaveDataCodecManager.Instance.FindCodec(this.Game, entry); if (codec != null) { // GUI エディタモードをアクティブ化 this._currentCodec = codec; this.badgeCodec.Visibility = Visibility.Visible; this.lblCodecName.Text = codec.CodecName; this.LoadGuiPropertiesFromCodec(codec, entry.FilePath); this.pnlGuiEditor.Visibility = Visibility.Visible; this.btnSaveGuiProperties.Visibility = Visibility.Visible; this.lblStatus.Text = $"{codec.CodecName} で読み込みました: {entry.FileName}"; return; } // 2. プレーンテキスト/JSON形式の場合 if (entry.IsTextOrJson) { this.pnlTextEditor.Visibility = Visibility.Visible; this.txtFileContent.Text = this._saveService.ReadSaveFileText(entry.FilePath); this.btnFormatJson.Visibility = Visibility.Visible; this.btnSaveFileContent.Visibility = Visibility.Visible; this.lblStatus.Text = $"テキストとして開きました: {entry.FileName}"; return; } // 3. 未対応のバイナリセーブデータ形式の場合 this.pnlUnsupportedBinary.Visibility = Visibility.Visible; this.DisplayUnsupportedBinaryInfo(entry); this.lblStatus.Text = $"未対応のバイナリセーブデータ: {entry.FileName}"; } private void LoadGuiPropertiesFromCodec(ISaveDataCodec codec, string filePath) { this._guiProperties.Clear(); var props = codec.LoadProperties(filePath); foreach (var p in props) { this._guiProperties.Add(p); } this.lblGuiPropCount.Text = $"{props.Count} 項目"; if (props.Count > 0) { this.dgGuiProperties.SelectedIndex = 0; } } private bool FilterGuiProperties(object obj) { if (obj is not SaveDataPropertyEntry prop) return false; var query = this.txtSearchGuiProps.Text.Trim(); if (string.IsNullOrEmpty(query)) return true; return prop.Key.Contains(query, StringComparison.OrdinalIgnoreCase) || prop.Category.Contains(query, StringComparison.OrdinalIgnoreCase) || prop.EditValue.Contains(query, StringComparison.OrdinalIgnoreCase); } private void txtSearchGuiProps_TextChanged(object sender, TextChangedEventArgs e) { this._guiPropsView.Refresh(); int visibleCount = this._guiPropsView.Cast().Count(); this.lblGuiPropCount.Text = $"{visibleCount} / {this._guiProperties.Count} 項目"; } private void dgGuiProperties_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (this.dgGuiProperties.SelectedItem is SaveDataPropertyEntry prop) { this.lblSelectedPropKey.Text = prop.Key; this.txtEditPropValueBar.Text = prop.EditValue; this.txtEditPropValueBar.IsEnabled = true; this.btnApplyPropValue.IsEnabled = true; } else { this.lblSelectedPropKey.Text = "(未選択)"; this.txtEditPropValueBar.Text = string.Empty; this.txtEditPropValueBar.IsEnabled = false; this.btnApplyPropValue.IsEnabled = false; } } private void txtEditPropValueBar_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { this.btnApplyPropValue_Click(sender, e); } } private void btnApplyPropValue_Click(object sender, RoutedEventArgs e) { if (this.dgGuiProperties.SelectedItem is SaveDataPropertyEntry prop) { prop.EditValue = this.txtEditPropValueBar.Text; this.dgGuiProperties.Items.Refresh(); this.lblStatus.Text = $"項目 '{prop.Key}' の値を変更しました。(「変更を保存」ボタンでファイルへ書き戻せます)"; } } private void btnSaveGuiProperties_Click(object sender, RoutedEventArgs e) { if (this._currentSelectedFile == null || this._currentCodec == null) return; bool success = this._currentCodec.SaveProperties(this._currentSelectedFile.FilePath, [.. this._guiProperties]); if (success) { this.lblStatus.Text = $"セーブファイルを正常に更新しました (自動バックアップ .bak 作成済み): {this._currentSelectedFile.FileName}"; MessageBox.Show("セーブファイルを正常に更新・保存しました。\n(元のファイルは同階層に .bak として自動バックアップされています)", "保存完了", MessageBoxButton.OK, MessageBoxImage.Information); } else { MessageBox.Show("セーブデータの保存・再エンコードに失敗しました。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error); } } private void DisplayUnsupportedBinaryInfo(SaveFileEntry entry) { try { if (File.Exists(entry.FilePath)) { byte[] bytes = File.ReadAllBytes(entry.FilePath); int count = Math.Min(32, bytes.Length); var hexList = new List(); for (int i = 0; i < count; i++) { hexList.Add(bytes[i].ToString("X2")); } this.lblHexPreview.Text = string.Join(" ", hexList) + (bytes.Length > 32 ? " ..." : ""); } } catch { this.lblHexPreview.Text = "(読み込み失敗)"; } } private void btnCopyIdePrompt_Click(object sender, RoutedEventArgs e) { if (this._currentSelectedFile == null) return; string prompt = SaveDataCodecManager.Instance.GenerateAntigravityPrompt(this.Game, this._currentSelectedFile); Clipboard.SetText(prompt); this.lblStatus.Text = "📋 Antigravity IDE 用の解析依頼プロンプトをクリップボードにコピーしました!"; MessageBox.Show("Antigravity IDE 解析用プロンプトをコピーしました!\n\nAntigravity IDE のチャット欄に貼り付けて送信すると、AIがこのゲームのセーブデータ構造を解析し、GUI編集プラグインを自動で追加してくれます。", "プロンプトをコピーしました", MessageBoxButton.OK, MessageBoxImage.Information); } private void btnForceShowBinary_Click(object sender, RoutedEventArgs e) { if (this._currentSelectedFile == null) return; this.pnlUnsupportedBinary.Visibility = Visibility.Collapsed; this.pnlTextEditor.Visibility = Visibility.Visible; this.btnSaveFileContent.Visibility = Visibility.Visible; this.txtFileContent.Text = this._saveService.ReadSaveFileText(this._currentSelectedFile.FilePath); } private void btnFormatJson_Click(object sender, RoutedEventArgs e) { try { var raw = this.txtFileContent.Text; if (string.IsNullOrWhiteSpace(raw)) return; using var doc = JsonDocument.Parse(raw); var formatted = JsonSerializer.Serialize(doc.RootElement, new JsonSerializerOptions { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); this.txtFileContent.Text = formatted; this.lblStatus.Text = "JSONを整形しました。"; } catch (Exception ex) { MessageBox.Show($"JSONの解析に失敗しました:\n\n{ex.Message}", "フォーマット失敗", MessageBoxButton.OK, MessageBoxImage.Warning); } } private void btnSaveFileContent_Click(object sender, RoutedEventArgs e) { if (this._currentSelectedFile == null) return; bool success = this._saveService.WriteSaveFileText(this._currentSelectedFile.FilePath, this.txtFileContent.Text); if (success) { this.lblStatus.Text = $"ファイルを保存しました (自動バックアップ .bak 作成済み): {this._currentSelectedFile.FileName}"; MessageBox.Show("ファイルを保存しました。\n(元のファイルは同階層に .bak としてバックアップされています)", "保存完了", MessageBoxButton.OK, MessageBoxImage.Information); } else { MessageBox.Show("ファイルの保存に失敗しました。書き込み権限等を確認してください。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error); } } private void btnBackupSingleFile_Click(object sender, RoutedEventArgs e) { if (this._currentSelectedFile == null) return; var backupDir = AppPathHelper.GetGameBackupDirectory(this.Game.FolderName, this.Game.RootDirectory); var result = this._saveService.BackupSaveFile(this._currentSelectedFile.FilePath, backupDir); if (result != null) { this.ReloadBackups(); this.lblStatus.Text = $"ファイルをバックアップしました: {Path.GetFileName(result)}"; MessageBox.Show($"ファイルをバックアップしました:\n\n{result}", "バックアップ完了", MessageBoxButton.OK, MessageBoxImage.Information); } else { MessageBox.Show("ファイルのバックアップに失敗しました。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error); } } private void btnReloadSaveFiles_Click(object sender, RoutedEventArgs e) { this.ReloadSaveFiles(); } // ==================================================================== // バックアップ履歴 タブ処理 // ==================================================================== public void ReloadBackups() { this._backups.Clear(); var list = this._saveService.GetBackupList(this.Game); foreach (var b in list) { this._backups.Add(b); } } private void btnReloadBackups_Click(object sender, RoutedEventArgs e) { this.ReloadBackups(); } private void btnOpenBackupDir_Click(object sender, RoutedEventArgs e) { var backupDir = AppPathHelper.GetGameBackupDirectory(this.Game.FolderName, this.Game.RootDirectory); UnitySaveManagerService.OpenFolderInExplorer(backupDir); } private void btnRestoreFromBackupRow_Click(object sender, RoutedEventArgs e) { if (sender is not Button btn || btn.DataContext is not SaveBackupEntry backup) return; if (backup.BackupPath.EndsWith(".reg", StringComparison.OrdinalIgnoreCase)) { var res = MessageBox.Show($"レジストリバックアップ '{backup.Name}' を復元しますか?", "復元の確認", MessageBoxButton.YesNo, MessageBoxImage.Warning); if (res == MessageBoxResult.Yes) { if (this._saveService.RestoreRegistry(backup.BackupPath)) { this.ReloadPlayerPrefs(); MessageBox.Show("レジストリを正常に復元しました。", "復元完了", MessageBoxButton.OK, MessageBoxImage.Information); } else { MessageBox.Show("復元に失敗しました。", "エラー", MessageBoxButton.OK, MessageBoxImage.Error); } } } else { MessageBox.Show($"バックアップファイル:\n{backup.BackupPath}\n\nバックアップフォルダから復元したい場所へコピーしてください。", "バックアップファイルの復元", MessageBoxButton.OK, MessageBoxImage.Information); UnitySaveManagerService.OpenFolderInExplorer(Path.GetDirectoryName(backup.BackupPath)!); } } // ==================================================================== // ヘッダークイックオープン // ==================================================================== private void btnOpenLocalLow_Click(object sender, RoutedEventArgs e) { if (!string.IsNullOrEmpty(this.Game.LocalLowPath)) { if (!Directory.Exists(this.Game.LocalLowPath)) { var parent = Path.GetDirectoryName(this.Game.LocalLowPath); if (parent != null && Directory.Exists(parent)) { UnitySaveManagerService.OpenFolderInExplorer(parent); return; } } UnitySaveManagerService.OpenFolderInExplorer(this.Game.LocalLowPath); } } private void btnOpenGameFolder_Click(object sender, RoutedEventArgs e) { UnitySaveManagerService.OpenFolderInExplorer(this.Game.RootDirectory); } private void btnOpenRegedit_Click(object sender, RoutedEventArgs e) { this._saveService.OpenRegistryEditor(this.Game.RegistryPath); } } }