feat: 初回コミット (GameLauncher)
This commit is contained in:
commit
7ac4dbc825
45 files changed
+9779
No files matched your search
@@ -0,0 +1,456 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using GameLauncher.Helpers;
|
||||
using GameLauncher.Models;
|
||||
|
||||
namespace GameLauncher.Services
|
||||
{
|
||||
/// <summary>
|
||||
/// ツクールスクリプト改造プラグインの動的検出・適用・復元・管理を行うサービス
|
||||
/// </summary>
|
||||
public class TkoolModService
|
||||
{
|
||||
/// <summary>バックアップファイルのサフィックス</summary>
|
||||
public const string BackupSuffix = ".original_launcher_backup";
|
||||
|
||||
/// <summary>
|
||||
/// 過去のバージョンで使用されていたレガシープラグイン名一覧(完全削除・復元互換用)
|
||||
/// 以前改造されたゲームの検知、復元時のクリーンアップ、新改造適用時の旧ゴミ削除に使用します。
|
||||
/// </summary>
|
||||
public static readonly string[] LegacyPluginNames =
|
||||
[
|
||||
"SpeedUp",
|
||||
"Antigravity_GameTweaks",
|
||||
"DropItem99",
|
||||
"TurnStartFullRecover",
|
||||
"BattleTurnRecover",
|
||||
"MaxGainGold",
|
||||
"MaxGainExp",
|
||||
"InstantMessage"
|
||||
];
|
||||
|
||||
private List<ModPluginDefinition> _availablePlugins = [];
|
||||
|
||||
/// <summary>現在認識されている利用可能なプラグイン一覧</summary>
|
||||
public IReadOnlyList<ModPluginDefinition> AvailablePlugins => _availablePlugins;
|
||||
|
||||
public TkoolModService()
|
||||
{
|
||||
LoadAvailablePlugins();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// exe と同一階層にある plugins フォルダの物理パスを取得します。
|
||||
/// </summary>
|
||||
public static string GetPluginsDirectory()
|
||||
{
|
||||
// 1. 実行ファイルと同じ物理ディレクトリ
|
||||
var exeDir = AppPathHelper.GetExeDirectory();
|
||||
var primary = Path.Combine(exeDir, "plugins");
|
||||
if (Directory.Exists(primary))
|
||||
{
|
||||
return primary;
|
||||
}
|
||||
|
||||
// 2. 本番配置フォルダ(Z:\自作ソフト\GameLauncher\plugins)
|
||||
const string prodPath = @"Z:\自作ソフト\GameLauncher\plugins";
|
||||
if (Directory.Exists(prodPath))
|
||||
{
|
||||
return prodPath;
|
||||
}
|
||||
|
||||
// 3. AppContext.BaseDirectory 配下のフォールバック
|
||||
var baseDir = AppContext.BaseDirectory;
|
||||
var cand1 = Path.Combine(baseDir, "plugins");
|
||||
if (Directory.Exists(cand1)) return cand1;
|
||||
|
||||
return primary;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// exe と同階層の plugins フォルダから動的にプラグイン一覧を読み込みます。
|
||||
/// </summary>
|
||||
public List<ModPluginDefinition> LoadAvailablePlugins()
|
||||
{
|
||||
var list = new List<ModPluginDefinition>();
|
||||
var pluginsDir = GetPluginsDirectory();
|
||||
|
||||
if (Directory.Exists(pluginsDir))
|
||||
{
|
||||
foreach (var file in Directory.EnumerateFiles(pluginsDir, "*.js"))
|
||||
{
|
||||
try
|
||||
{
|
||||
list.Add(ModPluginDefinition.FromFile(file));
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
}
|
||||
|
||||
_availablePlugins = list;
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 現在有効なプラグイン名と旧レガシープラグイン名のすべてを合算した除去対象プラグイン名セットを取得します。
|
||||
/// </summary>
|
||||
public static HashSet<string> GetAllManagedPluginNames(IEnumerable<ModPluginDefinition>? currentPlugins = null)
|
||||
{
|
||||
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
// 過去のレガシープラグイン名をすべて含める
|
||||
foreach (var leg in LegacyPluginNames)
|
||||
{
|
||||
set.Add(leg);
|
||||
}
|
||||
|
||||
// 現在のプラグイン群を含める
|
||||
if (currentPlugins != null)
|
||||
{
|
||||
foreach (var p in currentPlugins)
|
||||
{
|
||||
set.Add(p.Id);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var dir = GetPluginsDirectory();
|
||||
if (Directory.Exists(dir))
|
||||
{
|
||||
foreach (var file in Directory.EnumerateFiles(dir, "*.js"))
|
||||
{
|
||||
set.Add(Path.GetFileNameWithoutExtension(file));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return set;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定されたゲームに対して、現在のチェック状態に応じた改造の適用または復元を行います。
|
||||
/// </summary>
|
||||
public (bool Success, string Message) ApplyOrRestoreMod(TkoolGameItem game, Dictionary<string, bool>? defaultSettings = null)
|
||||
{
|
||||
if (string.IsNullOrEmpty(game.PluginsJsPath) || !File.Exists(game.PluginsJsPath))
|
||||
{
|
||||
return (false, "plugins.js が見つかりません。");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (game.ApplyMod)
|
||||
{
|
||||
return ApplyMod(game, defaultSettings);
|
||||
}
|
||||
else
|
||||
{
|
||||
return RestoreOriginal(game);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return (false, $"スクリプト処理中にエラーが発生しました: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 改造プラグインを適用します。
|
||||
/// </summary>
|
||||
public (bool Success, string Message) ApplyMod(TkoolGameItem game, Dictionary<string, bool>? defaultSettings = null)
|
||||
{
|
||||
var pluginsJsPath = game.PluginsJsPath;
|
||||
var pluginsDir = game.PluginsDirPath;
|
||||
|
||||
if (string.IsNullOrEmpty(pluginsDir))
|
||||
{
|
||||
pluginsDir = Path.Combine(Path.GetDirectoryName(pluginsJsPath)!, "plugins");
|
||||
game.PluginsDirPath = pluginsDir;
|
||||
}
|
||||
|
||||
if (!Directory.Exists(pluginsDir))
|
||||
{
|
||||
Directory.CreateDirectory(pluginsDir);
|
||||
}
|
||||
|
||||
var backupPath = pluginsJsPath + BackupSuffix;
|
||||
|
||||
// 1. バックアップが存在しない場合、バックアップを作成する
|
||||
if (!File.Exists(backupPath))
|
||||
{
|
||||
string currentContent = File.ReadAllText(pluginsJsPath, Encoding.UTF8);
|
||||
// 既に改造プラグイン(新旧問わず)が埋め込まれている場合はクリーンアップしたものをバックアップとして保持
|
||||
string cleanContent = CleanManagedPluginsFromContent(currentContent);
|
||||
File.WriteAllText(backupPath, cleanContent, new UTF8Encoding(false));
|
||||
}
|
||||
|
||||
// 2. バックアップ(クリーン状態)を元に編集を開始
|
||||
string baseContent = File.ReadAllText(backupPath, Encoding.UTF8);
|
||||
|
||||
// 最新の動的プラグイン一覧を取得
|
||||
if (_availablePlugins.Count == 0)
|
||||
{
|
||||
LoadAvailablePlugins();
|
||||
}
|
||||
|
||||
// 有効化対象のプラグインを取得
|
||||
var pluginsToEnable = _availablePlugins
|
||||
.Where(p => game.IsPluginEnabled(p.Id, defaultSettings, fallbackVal: true))
|
||||
.ToList();
|
||||
|
||||
// 3. ゲーム側の plugins ディレクトリから不要な旧プラグインや無効プラグインを安全に掃除
|
||||
var allManaged = GetAllManagedPluginNames(_availablePlugins);
|
||||
var enabledIds = new HashSet<string>(pluginsToEnable.Select(p => p.Id), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
foreach (var pluginId in allManaged)
|
||||
{
|
||||
// 有効対象ではないプラグインファイル(旧プラグインや今回OFFにしたプラグイン)を削除
|
||||
if (!enabledIds.Contains(pluginId))
|
||||
{
|
||||
var targetFile = Path.Combine(pluginsDir, $"{pluginId}.js");
|
||||
if (File.Exists(targetFile))
|
||||
{
|
||||
try { File.Delete(targetFile); } catch { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 有効対象のプラグインファイルをゲーム側へ配置
|
||||
foreach (var plugin in pluginsToEnable)
|
||||
{
|
||||
CopyPluginToGame(plugin, pluginsDir);
|
||||
}
|
||||
|
||||
// 5. plugins.js をパース・再構築して有効プラグインを追加
|
||||
var pluginNamesToAdd = pluginsToEnable.Select(p => p.Id).ToList();
|
||||
string updatedContent = RebuildPluginsJs(baseContent, pluginNamesToAdd);
|
||||
|
||||
// 6. 保存
|
||||
File.WriteAllText(pluginsJsPath, updatedContent, new UTF8Encoding(false));
|
||||
game.IsModded = true;
|
||||
|
||||
return (true, $"ツクールスクリプト改造を正常に適用しました。(有効プラグイン: {pluginsToEnable.Count}個)");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 改造を解除し、ゲームを改造前のオリジナル状態に復元します。
|
||||
/// 旧レガシープラグインも含めて完全にクリーンアップします。
|
||||
/// </summary>
|
||||
public (bool Success, string Message) RestoreOriginal(TkoolGameItem game)
|
||||
{
|
||||
var pluginsJsPath = game.PluginsJsPath;
|
||||
var pluginsDir = game.PluginsDirPath;
|
||||
var backupPath = pluginsJsPath + BackupSuffix;
|
||||
|
||||
// 1. バックアップが存在する場合はバックアップから復元(再構築を通すことで壊れたバックアップも修復)
|
||||
if (File.Exists(backupPath))
|
||||
{
|
||||
string backupContent = File.ReadAllText(backupPath, Encoding.UTF8);
|
||||
string cleanContent = RebuildPluginsJs(backupContent, null);
|
||||
File.WriteAllText(pluginsJsPath, cleanContent, new UTF8Encoding(false));
|
||||
}
|
||||
else
|
||||
{
|
||||
// バックアップがなくても、現在の plugins.js から新旧すべての管理プラグインを綺麗に除去
|
||||
string currentContent = File.ReadAllText(pluginsJsPath, Encoding.UTF8);
|
||||
string cleanContent = RebuildPluginsJs(currentContent, null);
|
||||
File.WriteAllText(pluginsJsPath, cleanContent, new UTF8Encoding(false));
|
||||
}
|
||||
|
||||
// 2. ゲーム側の plugins フォルダから新旧すべてのプラグインファイルを安全に削除(ゴミを残さない)
|
||||
if (!string.IsNullOrEmpty(pluginsDir) && Directory.Exists(pluginsDir))
|
||||
{
|
||||
var allManaged = GetAllManagedPluginNames(_availablePlugins);
|
||||
foreach (var pluginName in allManaged)
|
||||
{
|
||||
var targetFile = Path.Combine(pluginsDir, $"{pluginName}.js");
|
||||
if (File.Exists(targetFile))
|
||||
{
|
||||
try { File.Delete(targetFile); } catch { /* 削除不可時は無視 */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
game.IsModded = false;
|
||||
return (true, "ゲームを改造前のオリジナル状態に正常に復元しました。(旧プラグインも完全削除済み)");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// plugins.js のテキストから新旧すべての管理対象プラグインの登録記述を除去します。
|
||||
/// </summary>
|
||||
public static string CleanManagedPluginsFromContent(string content)
|
||||
{
|
||||
return RebuildPluginsJs(content, null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// plugins.js の内容を構文レベルで解析し、新旧管理対象プラグインの完全除去および新規追加を行って
|
||||
/// 正常な JavaScript 配列構文として再構築します。
|
||||
/// </summary>
|
||||
public static string RebuildPluginsJs(string content, IReadOnlyList<string>? pluginsToAdd = null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(content))
|
||||
{
|
||||
return content;
|
||||
}
|
||||
|
||||
int arrayStart = content.IndexOf('[');
|
||||
int arrayEnd = content.LastIndexOf(']');
|
||||
if (arrayStart == -1 || arrayEnd == -1 || arrayEnd <= arrayStart)
|
||||
{
|
||||
return content;
|
||||
}
|
||||
|
||||
string prefix = content.Substring(0, arrayStart + 1);
|
||||
string inner = content.Substring(arrayStart + 1, arrayEnd - arrayStart - 1);
|
||||
string suffix = content.Substring(arrayEnd);
|
||||
|
||||
// 新旧すべてのプラグイン名を除去対象とする
|
||||
var managedSet = GetAllManagedPluginNames();
|
||||
var keptObjects = new List<string>();
|
||||
|
||||
int i = 0;
|
||||
while (i < inner.Length)
|
||||
{
|
||||
// 次のオブジェクト開始 '{' を探す
|
||||
while (i < inner.Length && inner[i] != '{')
|
||||
{
|
||||
i++;
|
||||
}
|
||||
if (i >= inner.Length) break;
|
||||
|
||||
int objStart = i;
|
||||
int depth = 0;
|
||||
bool inString = false;
|
||||
bool isEscaped = false;
|
||||
|
||||
while (i < inner.Length)
|
||||
{
|
||||
char c = inner[i];
|
||||
if (isEscaped)
|
||||
{
|
||||
isEscaped = false;
|
||||
}
|
||||
else if (c == '\\')
|
||||
{
|
||||
if (inString) isEscaped = true;
|
||||
}
|
||||
else if (c == '"')
|
||||
{
|
||||
inString = !inString;
|
||||
}
|
||||
else if (!inString)
|
||||
{
|
||||
if (c == '{') depth++;
|
||||
else if (c == '}')
|
||||
{
|
||||
depth--;
|
||||
if (depth == 0)
|
||||
{
|
||||
i++; // '}' を含める
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
if (depth == 0)
|
||||
{
|
||||
string objText = inner.Substring(objStart, i - objStart).Trim();
|
||||
// このオブジェクトが新旧管理対象プラグインかどうか判定
|
||||
var match = Regex.Match(objText, @"""name""\s*:\s*""([^""]+)""");
|
||||
if (match.Success && managedSet.Contains(match.Groups[1].Value))
|
||||
{
|
||||
// 管理対象プラグインのため除外
|
||||
continue;
|
||||
}
|
||||
keptObjects.Add(objText);
|
||||
}
|
||||
}
|
||||
|
||||
// 追加対象のプラグインを登録
|
||||
if (pluginsToAdd != null)
|
||||
{
|
||||
foreach (var pluginName in pluginsToAdd)
|
||||
{
|
||||
keptObjects.Add($"{{\"name\":\"{pluginName}\",\"status\":true,\"description\":\"\",\"parameters\":{{}}}}");
|
||||
}
|
||||
}
|
||||
|
||||
// 綺麗な JavaScript 配列として再構築
|
||||
var sb = new StringBuilder();
|
||||
sb.Append(prefix.TrimEnd()).AppendLine();
|
||||
for (int k = 0; k < keptObjects.Count; k++)
|
||||
{
|
||||
sb.Append(keptObjects[k]);
|
||||
if (k < keptObjects.Count - 1)
|
||||
{
|
||||
sb.Append(",");
|
||||
}
|
||||
sb.AppendLine();
|
||||
}
|
||||
sb.Append(suffix.TrimStart());
|
||||
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// プラグインファイルをゲーム側の plugins ディレクトリへコピーします。
|
||||
/// </summary>
|
||||
private void CopyPluginToGame(ModPluginDefinition plugin, string targetDir)
|
||||
{
|
||||
var destinationPath = Path.Combine(targetDir, plugin.FileName);
|
||||
|
||||
// 1. 指定ファイルの物理パスからコピー
|
||||
if (!string.IsNullOrEmpty(plugin.FilePath) && File.Exists(plugin.FilePath))
|
||||
{
|
||||
File.Copy(plugin.FilePath, destinationPath, true);
|
||||
return;
|
||||
}
|
||||
|
||||
// 2. plugins ディレクトリからのコピーを試行
|
||||
var localPluginPath = Path.Combine(GetPluginsDirectory(), plugin.FileName);
|
||||
if (File.Exists(localPluginPath))
|
||||
{
|
||||
File.Copy(localPluginPath, destinationPath, true);
|
||||
return;
|
||||
}
|
||||
|
||||
throw new FileNotFoundException($"プラグインファイルが見つかりません: {plugin.FileName} (参照先: {GetPluginsDirectory()})");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 現在 plugins.js に改造プラグイン(新旧問わず)が記述されているか判定します。
|
||||
/// </summary>
|
||||
public static bool CheckIsModded(string pluginsJsPath)
|
||||
{
|
||||
if (string.IsNullOrEmpty(pluginsJsPath) || !File.Exists(pluginsJsPath))
|
||||
return false;
|
||||
|
||||
try
|
||||
{
|
||||
string content = File.ReadAllText(pluginsJsPath);
|
||||
var allManaged = GetAllManagedPluginNames();
|
||||
foreach (var pluginName in allManaged)
|
||||
{
|
||||
if (content.Contains($"\"name\":\"{pluginName}\""))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 読み取り失敗時は false
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user