refactor: reorganize engine-based structure and add agent rules

- Engines/ 配下へエンジン別に再編 (Common/Rgss/Tkool/Tyrano/Wolf/Unity/Nwjs)
- ゲーム個別処理を Engines/<Engine>/Games/<GameName>/ へ分離し、共通処理から明示呼び出し
- 外部ツールを Engines/<Engine>/Tools/ へ移動し、AppPathHelper 経由で解決
- 旧 Tools/ 直下参照と不要な参照ファイル/バックアップを削除
- エージェント規則 AGENTS.md を追加し、README から参照
- publish.ps1 を Engines/<Engine>/Tools/ の再帰配置に対応
This commit is contained in:
armonica committed 2026-10-07 02:30:49 +09:00
1 parent 0d11039ee9
commit 8cea2a147d
47 files changed
+2976 -176

No files matched your search

+86
View File
@@ -0,0 +1,86 @@
namespace GameLauncher.Engines.Unity
{
/// <summary>
/// ゲームエンジンの大分類
/// </summary>
public enum GameEngineKind
{
Tkool,
Tyrano,
Unity,
Wolf,
SrpgStudio
}
/// <summary>
/// エンジンの種類
/// </summary>
public enum TkoolEngineType
{
MV,
MZ,
Tyrano,
VX,
VXAce,
Wolf,
SrpgStudio,
Unknown
}
/// <summary>
/// Unityのビルドバックエンド形式
/// </summary>
public enum UnityBackendType
{
Unknown = 0,
Mono = 1,
IL2CPP = 2
}
/// <summary>
/// ゲーム一覧のソート順
/// </summary>
public enum GameSortOrder
{
LastLaunchedDesc = 0, // 最終実行 (新しい順)
LastLaunchedAsc = 1, // 最終実行 (古い順)
FolderLastModifiedDesc = 2, // フォルダ更新日時 (新しい順)
FolderLastModifiedAsc = 3, // フォルダ更新日時 (古い順)
TitleAsc = 4, // タイトル (昇順)
TitleDesc = 5, // タイトル (降順)
FolderNameAsc = 6 // フォルダ名 (昇順)
}
/// <summary>
/// セーブデータの格納ソース種別
/// </summary>
public enum SaveSourceType
{
RegistryPlayerPrefs = 0,
LocalLowFile = 1,
GameFolderFile = 2
}
/// <summary>
/// PlayerPrefs値のデータ型
/// </summary>
public enum PlayerPrefsType
{
Int = 0,
Float = 1,
String = 2,
Binary = 3
}
/// <summary>
/// セーブデータコーデック種別
/// </summary>
public enum SaveCodecType
{
RawText = 0,
Json = 1,
EasySave3 = 2,
YurisSave = 3,
Binary = 4
}
}
+134
View File
@@ -0,0 +1,134 @@
using System;
using System.IO;
using GameLauncher.Models;
namespace GameLauncher.Engines.Unity
{
/// <summary>
/// Unityゲームのデータモデル
/// </summary>
public class UnityGameItem : GameItemBase
{
private string _dataDirectoryPath = string.Empty;
private string _companyName = string.Empty;
private string _productName = string.Empty;
private UnityBackendType _backendType = UnityBackendType.Unknown;
private string _unityVersion = string.Empty;
private bool _hasSaveData;
public override GameEngineKind EngineKind => GameEngineKind.Unity;
/// <summary>[Game]_Data ディレクトリ絶対パス</summary>
public string DataDirectoryPath
{
get => _dataDirectoryPath;
set { if (_dataDirectoryPath != value) { _dataDirectoryPath = value; OnPropertyChanged(); } }
}
/// <summary>app.info 由来の会社名/開発者名</summary>
public string CompanyName
{
get => _companyName;
set
{
if (_companyName != value)
{
_companyName = value;
OnPropertyChanged();
OnPropertyChanged(nameof(RegistryPath));
OnPropertyChanged(nameof(LocalLowPath));
}
}
}
/// <summary>app.info 由来の製品名</summary>
public string ProductName
{
get => _productName;
set
{
if (_productName != value)
{
_productName = value;
OnPropertyChanged();
OnPropertyChanged(nameof(RegistryPath));
OnPropertyChanged(nameof(LocalLowPath));
}
}
}
public override bool IsIL2CPP => BackendType == UnityBackendType.IL2CPP;
public override bool IsMono => BackendType == UnityBackendType.Mono;
/// <summary>バックエンド形式 (IL2CPP / Mono)</summary>
public UnityBackendType BackendType
{
get => _backendType;
set
{
if (_backendType != value)
{
_backendType = value;
OnPropertyChanged();
OnPropertyChanged(nameof(BackendBadgeText));
OnPropertyChanged(nameof(IsIL2CPP));
OnPropertyChanged(nameof(IsMono));
}
}
}
/// <summary>Unityバージョン文字列</summary>
public override string UnityVersion
{
get => _unityVersion;
set { if (_unityVersion != value) { _unityVersion = value; OnPropertyChanged(); } }
}
/// <summary>セーブデータ(レジストリまたはファイル)が検出されたかどうか</summary>
public override bool HasSaveData
{
get => _hasSaveData;
set { if (_hasSaveData != value) { _hasSaveData = value; OnPropertyChanged(); } }
}
/// <summary>
/// レジストリ (PlayerPrefs) のキーパス
/// HKCU\Software\[CompanyName]\[ProductName]
/// </summary>
public override string RegistryPath
{
get
{
if (string.IsNullOrEmpty(CompanyName) || string.IsNullOrEmpty(ProductName))
return string.Empty;
return $@"Software\{CompanyName}\{ProductName}";
}
}
/// <summary>
/// LocalLow のセーブデータ保存ディレクトリ
/// %USERPROFILE%\AppData\LocalLow\[CompanyName]\[ProductName]
/// </summary>
public override string LocalLowPath
{
get
{
if (string.IsNullOrEmpty(CompanyName) || string.IsNullOrEmpty(ProductName))
return string.Empty;
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var appData = Path.GetDirectoryName(localAppData);
if (string.IsNullOrEmpty(appData)) return string.Empty;
return Path.Combine(appData, "LocalLow", CompanyName, ProductName);
}
}
public override string BackendBadgeText => BackendType switch
{
UnityBackendType.IL2CPP => "IL2CPP",
UnityBackendType.Mono => "Mono",
_ => "Unity"
};
}
}
+177
View File
@@ -0,0 +1,177 @@
using System;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using GameLauncher.Models;
namespace GameLauncher.Engines.Unity
{
/// <summary>
/// PlayerPrefs(レジストリ)の1エントリを表すモデル
/// </summary>
public class PlayerPrefsEntry : INotifyPropertyChanged
{
private string _rawKey = string.Empty;
private string _cleanKey = string.Empty;
private PlayerPrefsType _type = PlayerPrefsType.Int;
private object? _value;
private string _editValue = string.Empty;
private bool _isModified;
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>レジストリの生キー名(例: ClearedLevel_h1378399435)</summary>
public string RawKey
{
get => _rawKey;
set { if (_rawKey != value) { _rawKey = value; OnPropertyChanged(); } }
}
/// <summary>Unityのハッシュを除去した整形式キー名(例: ClearedLevel)</summary>
public string CleanKey
{
get => _cleanKey;
set { if (_cleanKey != value) { _cleanKey = value; OnPropertyChanged(); } }
}
/// <summary>値のデータ型</summary>
public PlayerPrefsType Type
{
get => _type;
set { if (_type != value) { _type = value; OnPropertyChanged(); OnPropertyChanged(nameof(TypeDisplay)); } }
}
/// <summary>実際の値(int, float, string, byte[])</summary>
public object? Value
{
get => _value;
set
{
if (!Equals(_value, value))
{
_value = value;
OnPropertyChanged();
UpdateEditValue();
}
}
}
/// <summary>UI表示・編集用の文字列値</summary>
public string EditValue
{
get => _editValue;
set
{
if (_editValue != value)
{
_editValue = value;
_isModified = true;
OnPropertyChanged();
OnPropertyChanged(nameof(IsModified));
}
}
}
/// <summary>値が変更されたかどうか</summary>
public bool IsModified
{
get => _isModified;
set { if (_isModified != value) { _isModified = value; OnPropertyChanged(); } }
}
public string TypeDisplay => Type switch
{
PlayerPrefsType.Int => "Int (数値)",
PlayerPrefsType.Float => "Float (小数)",
PlayerPrefsType.String => "String (文字列)",
PlayerPrefsType.Binary => "Binary (バイナリ)",
_ => "Unknown"
};
private void UpdateEditValue()
{
if (_value == null)
{
_editValue = string.Empty;
}
else if (_value is byte[] bytes)
{
try
{
var text = System.Text.Encoding.UTF8.GetString(bytes).TrimEnd('\0');
if (text.All(c => !char.IsControl(c) || c == '\r' || c == '\n' || c == '\t'))
{
_editValue = text;
_type = PlayerPrefsType.String;
return;
}
}
catch { }
if (bytes.Length == 4)
{
float f = BitConverter.ToSingle(bytes, 0);
if (!float.IsNaN(f) && !float.IsInfinity(f))
{
_editValue = f.ToString("G");
_type = PlayerPrefsType.Float;
return;
}
}
_editValue = BitConverter.ToString(bytes).Replace("-", " ");
}
else
{
_editValue = _value.ToString() ?? string.Empty;
}
_isModified = false;
OnPropertyChanged(nameof(EditValue));
OnPropertyChanged(nameof(IsModified));
}
}
/// <summary>
/// ディスク上のセーブファイル(LocalLow または ゲームフォルダ内)を表すモデル
/// </summary>
public class SaveFileEntry
{
public string FileName { get; set; } = string.Empty;
public string FilePath { get; set; } = string.Empty;
public long FileSize { get; set; }
public DateTime LastModified { get; set; }
public string LocationType { get; set; } = string.Empty; // "LocalLow" または "ゲームフォルダ"
public bool IsTextOrJson { get; set; }
public string FileSizeDisplay
{
get
{
if (FileSize < 1024) return $"{FileSize} B";
if (FileSize < 1024 * 1024) return $"{FileSize / 1024.0:F1} KB";
return $"{FileSize / (1024.0 * 1024.0):F2} MB";
}
}
public string LastModifiedDisplay => LastModified.ToString("yyyy/MM/dd HH:mm:ss");
}
/// <summary>
/// セーブデータのバックアップ履歴モデル
/// </summary>
public class SaveBackupEntry
{
public string Name { get; set; } = string.Empty;
public string BackupPath { get; set; } = string.Empty;
public DateTime Timestamp { get; set; }
public string BackupType { get; set; } = string.Empty; // "Registry (.reg)" または "ファイル"
public string Note { get; set; } = string.Empty;
public string TimestampDisplay => Timestamp.ToString("yyyy/MM/dd HH:mm:ss");
}
}
+683
View File
@@ -0,0 +1,683 @@
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.Engines.Unity
{
/// <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 { }
}
}
}