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 string? _currentPassword;
///
/// コーデックからプロパティ一覧を読み込み、パスワードバーの表示を更新します。
///
private void LoadGuiPropertiesFromCodec(ISaveDataCodec codec, string filePath)
{
this._guiProperties.Clear();
var props = codec.LoadProperties(filePath, this._currentPassword);
foreach (var p in props)
{
this._guiProperties.Add(p);
}
this.lblGuiPropCount.Text = $"{props.Count} 項目";
if (props.Count > 0)
{
this.dgGuiProperties.SelectedIndex = 0;
}
this.UpdatePasswordBar(codec, filePath, props.Count);
}
///
/// パスワードバーの表示要否と内容を更新します。
///
/// 使用中のコーデック
/// 対象セーブファイルのパス
/// 読み込めたプロパティ数
private void UpdatePasswordBar(ISaveDataCodec codec, string filePath, int propertyCount)
{
// ES3 コーデックかつ暗号化されている場合のみパスワードバーを表示する
if (codec is EasySave3Codec es3Codec && es3Codec.NeedsPassword(filePath))
{
this.pnlPasswordBar.Visibility = Visibility.Visible;
this.txtPassword.Text = this._currentPassword ?? string.Empty;
if (this.txtPassword.Text.Length == 0)
{
this.txtPassword.ToolTip = es3Codec.PasswordPromptMessage;
}
var diagnostics = es3Codec.Diagnostics;
if (propertyCount <= 1 && diagnostics.Count > 0)
{
this.lblStatus.Text = "復号できませんでした。パスワードを入力するか「自動特定」を試してください。";
}
return;
}
this.pnlPasswordBar.Visibility = Visibility.Collapsed;
}
///
/// 入力されたパスワードでセーブファイルを再読み込みします。
///
private void btnApplyPassword_Click(object sender, RoutedEventArgs e)
{
if (this._currentSelectedFile == null || this._currentCodec == null)
{
return;
}
this._currentPassword = this.txtPassword.Text;
this.LoadGuiPropertiesFromCodec(this._currentCodec, this._currentSelectedFile.FilePath);
this.lblStatus.Text = $"パスワードを適用して再読み込みしました: {this._currentSelectedFile.FileName}";
}
///
/// パスワード入力欄で Enter を押した際に適用します。
///
private void txtPassword_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
this.btnApplyPassword_Click(sender, e);
}
}
///
/// パスワードの多段自動特定を実行します。
///
private void btnAutoDetectPassword_Click(object sender, RoutedEventArgs e)
{
if (this._currentSelectedFile is not { } entry)
{
return;
}
var resolver = new GameLauncher.Services.Codecs.Es3.Es3PasswordResolver();
var result = resolver.Resolve(
entry.FilePath,
gameRootDirectory: string.IsNullOrEmpty(this.Game.RootDirectory) ? null : this.Game.RootDirectory,
gameKey: entry.FilePath);
if (result.Success)
{
this._currentPassword = result.Password;
this.txtPassword.Text = result.Password;
if (this._currentCodec != null)
{
this.LoadGuiPropertiesFromCodec(this._currentCodec, entry.FilePath);
}
var sourceLabel = result.Source switch
{
GameLauncher.Services.Codecs.Es3.Es3PasswordSource.LearnedCache => "学習済みキャッシュ",
GameLauncher.Services.Codecs.Es3.Es3PasswordSource.Explicit => "指定値",
GameLauncher.Services.Codecs.Es3.Es3PasswordSource.GameBinaryStrings => "ゲームバイナリの文字列",
GameLauncher.Services.Codecs.Es3.Es3PasswordSource.GameIl2CppMetadata => "IL2CPP メタデータ",
GameLauncher.Services.Codecs.Es3.Es3PasswordSource.Dictionary => "辞書探索",
_ => "平文"
};
this.lblStatus.Text = $"パスワードを特定しました({sourceLabel} / 試行 {result.TriedCandidates} 件)。";
return;
}
var detail = result.Diagnostics.Count > 0
? string.Join("\n", result.Diagnostics)
: "診断情報がありません。";
MessageBox.Show(
$"パスワードを自動特定できませんでした。\n(試行候補数: {result.TriedCandidates})\n\n{detail}",
"自動特定の結果",
MessageBoxButton.OK,
MessageBoxImage.Warning);
}
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