Files
GameLauncher/Services/UnitySaveManagerService.cs
T

684 lines
26 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.RegularExpressions;
using Microsoft.Win32;
using GameLauncher.Helpers;
using GameLauncher.Models;
namespace GameLauncher.Services
{
/// <summary>
/// UnityのPlayerPrefs(レジストリ)およびセーブファイル(LocalLow / ゲームフォルダ)の編集・バックアップを行うサービス
/// </summary>
public class UnitySaveManagerService
{
// ====================================================================
// 1. PlayerPrefs (レジストリ) 管理機能
// ====================================================================
/// <summary>
/// レジストリ(HKCU\Software\[CompanyName]\[ProductName])からPlayerPrefsエントリ一覧を取得します。
/// </summary>
public List<PlayerPrefsEntry> GetPlayerPrefs(string registryPath)
{
var list = new List<PlayerPrefsEntry>();
if (string.IsNullOrEmpty(registryPath)) return list;
try
{
using var key = Registry.CurrentUser.OpenSubKey(registryPath, writable: false);
if (key == null) return list;
var valueNames = key.GetValueNames();
foreach (var name in valueNames)
{
try
{
var kind = key.GetValueKind(name);
var rawValue = key.GetValue(name);
// キー名から "_h[数字]" のハッシュサフィックスを抽出・除去
string cleanKey = name;
var match = Regex.Match(name, @"^(.*)_h\d+$");
if (match.Success)
{
cleanKey = match.Groups[1].Value;
}
PlayerPrefsType type = PlayerPrefsType.Int;
if (kind == RegistryValueKind.DWord)
{
type = PlayerPrefsType.Int;
}
else if (kind == RegistryValueKind.String)
{
type = PlayerPrefsType.String;
}
else if (kind == RegistryValueKind.Binary)
{
type = PlayerPrefsType.Binary;
}
var entry = new PlayerPrefsEntry
{
RawKey = name,
CleanKey = cleanKey,
Type = type,
Value = rawValue
};
list.Add(entry);
}
catch { }
}
}
catch { }
// キー名昇順でソート
return list.OrderBy(e => e.CleanKey, StringComparer.OrdinalIgnoreCase).ToList();
}
/// <summary>
/// PlayerPrefsのエントリ値をレジストリに更新保存します。
/// </summary>
public bool SavePlayerPref(string registryPath, PlayerPrefsEntry entry)
{
if (string.IsNullOrEmpty(registryPath) || string.IsNullOrEmpty(entry.RawKey))
return false;
try
{
using var key = Registry.CurrentUser.CreateSubKey(registryPath, writable: true);
if (key == null) return false;
switch (entry.Type)
{
case PlayerPrefsType.Int:
if (int.TryParse(entry.EditValue, out int intVal))
{
key.SetValue(entry.RawKey, intVal, RegistryValueKind.DWord);
entry.Value = intVal;
entry.IsModified = false;
return true;
}
break;
case PlayerPrefsType.Float:
if (float.TryParse(entry.EditValue, out float floatVal))
{
// UnityのPlayerPrefsではfloatは4バイトバイナリとして格納される
byte[] floatBytes = BitConverter.GetBytes(floatVal);
key.SetValue(entry.RawKey, floatBytes, RegistryValueKind.Binary);
entry.Value = floatBytes;
entry.IsModified = false;
return true;
}
break;
case PlayerPrefsType.String:
// 文字列として直接格納するか、UTF-8バイト列(末尾0)として格納
// 既存のレジストリ型に合わせる
var existingKind = RegistryValueKind.Unknown;
try { existingKind = key.GetValueKind(entry.RawKey); } catch { }
if (existingKind == RegistryValueKind.Binary)
{
var bytes = Encoding.UTF8.GetBytes(entry.EditValue + "\0");
key.SetValue(entry.RawKey, bytes, RegistryValueKind.Binary);
entry.Value = bytes;
}
else
{
key.SetValue(entry.RawKey, entry.EditValue, RegistryValueKind.String);
entry.Value = entry.EditValue;
}
entry.IsModified = false;
return true;
case PlayerPrefsType.Binary:
// Hex文字列のパース(例: "AA BB CC" または "AABBCC")
var hexClean = entry.EditValue.Replace(" ", "").Replace("-", "");
if (hexClean.Length % 2 == 0)
{
byte[] rawBytes = Convert.FromHexString(hexClean);
key.SetValue(entry.RawKey, rawBytes, RegistryValueKind.Binary);
entry.Value = rawBytes;
entry.IsModified = false;
return true;
}
break;
}
}
catch { }
return false;
}
/// <summary>
/// PlayerPrefsに新規キーを追加します。
/// </summary>
public bool AddPlayerPref(string registryPath, string keyName, PlayerPrefsType type, string value, out string outRawKey)
{
outRawKey = string.Empty;
if (string.IsNullOrEmpty(registryPath) || string.IsNullOrWhiteSpace(keyName))
return false;
try
{
// Unityハッシュの付加
uint hash = CalculateUnityHash(keyName);
string rawKey = $"{keyName}_h{hash}";
outRawKey = rawKey;
using var key = Registry.CurrentUser.CreateSubKey(registryPath, writable: true);
if (key == null) return false;
switch (type)
{
case PlayerPrefsType.Int:
int.TryParse(value, out int intVal);
key.SetValue(rawKey, intVal, RegistryValueKind.DWord);
return true;
case PlayerPrefsType.Float:
float.TryParse(value, out float floatVal);
byte[] floatBytes = BitConverter.GetBytes(floatVal);
key.SetValue(rawKey, floatBytes, RegistryValueKind.Binary);
return true;
case PlayerPrefsType.String:
var bytes = Encoding.UTF8.GetBytes(value + "\0");
key.SetValue(rawKey, bytes, RegistryValueKind.Binary);
return true;
case PlayerPrefsType.Binary:
var hexClean = value.Replace(" ", "").Replace("-", "");
if (hexClean.Length % 2 == 0)
{
byte[] rawBytes = Convert.FromHexString(hexClean);
key.SetValue(rawKey, rawBytes, RegistryValueKind.Binary);
return true;
}
break;
}
}
catch { }
return false;
}
/// <summary>
/// PlayerPrefsのエントリをレジストリから削除します。
/// </summary>
public bool DeletePlayerPref(string registryPath, string rawKey)
{
if (string.IsNullOrEmpty(registryPath) || string.IsNullOrEmpty(rawKey))
return false;
try
{
using var key = Registry.CurrentUser.OpenSubKey(registryPath, writable: true);
if (key != null)
{
key.DeleteValue(rawKey, throwOnMissingValue: false);
return true;
}
}
catch { }
return false;
}
/// <summary>
/// UnityのPlayerPrefsキー用ハッシュ値(MurmurHash2 32bit)を算出します。
/// </summary>
public static uint CalculateUnityHash(string key)
{
byte[] data = Encoding.UTF8.GetBytes(key);
const uint m = 0x5bd1e995;
const int r = 24;
uint h = (uint)data.Length;
int length = data.Length;
int currentIndex = 0;
while (length >= 4)
{
uint k = BitConverter.ToUInt32(data, currentIndex);
k *= m;
k ^= k >> r;
k *= m;
h *= m;
h ^= k;
currentIndex += 4;
length -= 4;
}
switch (length)
{
case 3:
h ^= (uint)(data[currentIndex + 2] << 16);
h ^= (uint)(data[currentIndex + 1] << 8);
h ^= data[currentIndex];
h *= m;
break;
case 2:
h ^= (uint)(data[currentIndex + 1] << 8);
h ^= data[currentIndex];
h *= m;
break;
case 1:
h ^= data[currentIndex];
h *= m;
break;
}
h ^= h >> 13;
h *= m;
h ^= h >> 15;
return h;
}
/// <summary>
/// PlayerPrefsレジストリキー全体を .reg ファイルおよび JSON ファイルとしてバックアップします。
/// </summary>
public string? BackupRegistry(string registryPath, string backupDir)
{
if (string.IsNullOrEmpty(registryPath)) return null;
try
{
if (!Directory.Exists(backupDir))
{
Directory.CreateDirectory(backupDir);
}
var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
var regBackupFile = Path.Combine(backupDir, $"PlayerPrefs_{timestamp}.reg");
// reg.exe を用いて .reg ファイルを正確に出力
var fullRegKey = $@"HKEY_CURRENT_USER\{registryPath}";
var psi = new ProcessStartInfo
{
FileName = "reg.exe",
Arguments = $"export \"{fullRegKey}\" \"{regBackupFile}\" /y",
CreateNoWindow = true,
UseShellExecute = false
};
using var proc = Process.Start(psi);
proc?.WaitForExit(3000);
// JSONバックアップも併せて出力
var entries = GetPlayerPrefs(registryPath);
var jsonBackupFile = Path.Combine(backupDir, $"PlayerPrefs_{timestamp}.json");
var serializableList = entries.Select(e => new
{
e.RawKey,
e.CleanKey,
Type = e.Type.ToString(),
e.EditValue
});
var json = JsonSerializer.Serialize(serializableList, new JsonSerializerOptions { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping });
File.WriteAllText(jsonBackupFile, json);
return File.Exists(regBackupFile) ? regBackupFile : jsonBackupFile;
}
catch
{
return null;
}
}
/// <summary>
/// .reg ファイルからレジストリを復元します。
/// </summary>
public bool RestoreRegistry(string regFilePath)
{
if (!File.Exists(regFilePath)) return false;
try
{
var psi = new ProcessStartInfo
{
FileName = "reg.exe",
Arguments = $"import \"{regFilePath}\"",
CreateNoWindow = true,
UseShellExecute = false
};
using var proc = Process.Start(psi);
proc?.WaitForExit(3000);
return proc?.ExitCode == 0;
}
catch
{
return false;
}
}
/// <summary>
/// Windows標準のレジストリエディタ(regedit)を起動して該当キーを表示します。
/// </summary>
public void OpenRegistryEditor(string registryPath)
{
try
{
// regedit の「前回開いたキー」を更新
var fullKey = $@"Computer\HKEY_CURRENT_USER\{registryPath}";
using (var lastKey = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Applets\Regedit"))
{
lastKey?.SetValue("LastKey", fullKey);
}
Process.Start(new ProcessStartInfo("regedit.exe") { UseShellExecute = true });
}
catch { }
}
// ====================================================================
// 2. ディスク上のセーブファイル(LocalLow / ゲームフォルダ)管理機能
// ====================================================================
/// <summary>
/// ゲームに関連するディスク上のセーブファイルをすべて探索して取得します。
/// </summary>
public List<SaveFileEntry> GetSaveFiles(UnityGameItem game)
{
var list = new List<SaveFileEntry>();
// 1. LocalLow フォルダ
if (!string.IsNullOrEmpty(game.LocalLowPath) && Directory.Exists(game.LocalLowPath))
{
try
{
var files = Directory.EnumerateFiles(game.LocalLowPath, "*", SearchOption.AllDirectories);
foreach (var f in files)
{
var fileName = Path.GetFileName(f);
// ログファイルは除外(Player.log, Player-prev.log)
if (fileName.StartsWith("Player", StringComparison.OrdinalIgnoreCase) && fileName.EndsWith(".log", StringComparison.OrdinalIgnoreCase))
continue;
var fi = new FileInfo(f);
list.Add(new SaveFileEntry
{
FileName = fileName,
FilePath = f,
FileSize = fi.Length,
LastModified = fi.LastWriteTime,
LocationType = "LocalLow",
IsTextOrJson = CheckIsTextOrJson(f)
});
}
}
catch { }
}
// 2. ゲーム本体フォルダ及びサブフォルダ
if (Directory.Exists(game.RootDirectory))
{
try
{
// ルート直下
CollectCandidateFiles(game.RootDirectory, "ゲームフォルダ", list);
// Save / SaveData / saves / savedata サブフォルダ
var subNames = new[] { "Save", "SaveData", "saves", "savedata", "Save_Data" };
foreach (var sub in subNames)
{
var subPath = Path.Combine(game.RootDirectory, sub);
if (Directory.Exists(subPath))
{
CollectCandidateFiles(subPath, "ゲームフォルダ/" + sub, list, isStrict: false);
}
}
// Dataフォルダ直下のセーブファイル候補
if (!string.IsNullOrEmpty(game.DataDirectoryPath) && Directory.Exists(game.DataDirectoryPath))
{
CollectCandidateFiles(game.DataDirectoryPath, "Dataフォルダ", list);
}
}
catch { }
}
// 更新日時降順でソート
return list.OrderByDescending(f => f.LastModified).ToList();
}
private void CollectCandidateFiles(string dir, string locationLabel, List<SaveFileEntry> list, bool isStrict = true)
{
try
{
var files = Directory.EnumerateFiles(dir);
foreach (var f in files)
{
var fileName = Path.GetFileName(f);
// 既に同パスが登録されていればスキップ
if (list.Any(x => x.FilePath.Equals(f, StringComparison.OrdinalIgnoreCase)))
continue;
// システムファイルや実行ファイル等は除外
var ext = Path.GetExtension(f).ToLowerInvariant();
if (ext is ".exe" or ".dll" or ".config" or ".manifest" or ".txt" or ".log" or ".info" or ".resS" or ".assets")
{
// readmeやapp.info等はセーブファイルではない
if (!fileName.Contains("save", StringComparison.OrdinalIgnoreCase))
continue;
}
if (isStrict)
{
// セーブファイル候補のフィルタ
bool isCandidate = fileName.Contains("save", StringComparison.OrdinalIgnoreCase) ||
ext is ".sav" or ".save" or ".savegame" or ".dat";
if (!isCandidate) continue;
}
var fi = new FileInfo(f);
list.Add(new SaveFileEntry
{
FileName = fileName,
FilePath = f,
FileSize = fi.Length,
LastModified = fi.LastWriteTime,
LocationType = locationLabel,
IsTextOrJson = CheckIsTextOrJson(f)
});
}
}
catch { }
}
/// <summary>
/// ファイルがテキストまたはJSON形式か判定します。
/// </summary>
public bool CheckIsTextOrJson(string filePath)
{
try
{
var ext = Path.GetExtension(filePath).ToLowerInvariant();
if (ext is ".json" or ".xml" or ".txt" or ".ini" or ".yaml" or ".yml")
return true;
// ファイルの先頭512バイトを検査
using var fs = File.OpenRead(filePath);
var buffer = new byte[Math.Min(512, fs.Length)];
int read = fs.Read(buffer, 0, buffer.Length);
if (read == 0) return true;
// ヌル文字がほとんど無ければテキスト判定
int nullCount = buffer.Take(read).Count(b => b == 0);
return nullCount == 0;
}
catch
{
return false;
}
}
/// <summary>
/// セーブファイルをテキストとして読み出します。
/// </summary>
public string ReadSaveFileText(string filePath)
{
if (!File.Exists(filePath)) return string.Empty;
return File.ReadAllText(filePath, Encoding.UTF8);
}
/// <summary>
/// セーブファイルにテキストを書き込みます(書き込み前に自動で .bak バックアップを作成)。
/// </summary>
public bool WriteSaveFileText(string filePath, string newContent)
{
try
{
if (File.Exists(filePath))
{
// 自動バックアップ作成
var bakPath = filePath + ".bak";
File.Copy(filePath, bakPath, overwrite: true);
}
File.WriteAllText(filePath, newContent, Encoding.UTF8);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 単一のセーブファイルをバックアップフォルダへコピー保存します。
/// </summary>
public string? BackupSaveFile(string filePath, string backupDir)
{
if (!File.Exists(filePath)) return null;
try
{
if (!Directory.Exists(backupDir))
{
Directory.CreateDirectory(backupDir);
}
var fileName = Path.GetFileName(filePath);
var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
var destName = $"{Path.GetFileNameWithoutExtension(fileName)}_{timestamp}{Path.GetExtension(fileName)}";
var destPath = Path.Combine(backupDir, destName);
File.Copy(filePath, destPath, overwrite: true);
return destPath;
}
catch
{
return null;
}
}
/// <summary>
/// バックアップファイルからセーブファイルを復元します。
/// </summary>
public bool RestoreSaveFile(string backupFilePath, string targetFilePath)
{
if (!File.Exists(backupFilePath)) return false;
try
{
// 現在のファイルを退避
if (File.Exists(targetFilePath))
{
var tempBak = targetFilePath + ".pre_restore_bak";
File.Copy(targetFilePath, tempBak, overwrite: true);
}
File.Copy(backupFilePath, targetFilePath, overwrite: true);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// ゲーム専用のバックアップ一覧を取得します。
/// </summary>
public List<SaveBackupEntry> GetBackupList(UnityGameItem game)
{
var list = new List<SaveBackupEntry>();
var backupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory);
if (!Directory.Exists(backupDir)) return list;
try
{
var files = Directory.EnumerateFiles(backupDir);
foreach (var f in files)
{
var fi = new FileInfo(f);
var ext = fi.Extension.ToLowerInvariant();
string type = ext switch
{
".reg" => "レジストリ (.reg)",
".json" => "JSONバックアップ",
_ => "ファイルバックアップ"
};
list.Add(new SaveBackupEntry
{
Name = fi.Name,
BackupPath = f,
Timestamp = fi.LastWriteTime,
BackupType = type,
Note = $"{fi.Length / 1024.0:F1} KB"
});
}
}
catch { }
return list.OrderByDescending(b => b.Timestamp).ToList();
}
/// <summary>
/// エクスプローラーで指定フォルダを開きます。
/// </summary>
public static void OpenFolderInExplorer(string folderPath)
{
try
{
if (Directory.Exists(folderPath))
{
Process.Start(new ProcessStartInfo
{
FileName = folderPath,
UseShellExecute = true
});
}
else if (File.Exists(folderPath))
{
Process.Start(new ProcessStartInfo
{
FileName = "explorer.exe",
Arguments = $"/select,\"{folderPath}\"",
UseShellExecute = true
});
}
}
catch { }
}
}
}