Files
GameLauncher/MainWindow.xaml.cs
T
armonica 8cea2a147d 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/ の再帰配置に対応
2026-10-07 02:30:49 +09:00

1967 lines
83 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.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
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.Engines.Rgss;
using GameLauncher.Engines.Tkool;
using GameLauncher.Engines.Tyrano;
using GameLauncher.Engines.Wolf;
using GameLauncher.Engines.Unity;
using GameLauncher.Engines.Nwjs;
namespace GameLauncher
{
/// <summary>
/// メインウィンドウの相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
private readonly GameScannerService _scannerService = new();
private readonly TkoolModService _modService = new();
private readonly TyranoModService _tyranoModService = new();
private readonly AsarArchiveService _asarService = new();
private readonly UnitySaveManagerService _unitySaveService = new();
private readonly RgssModService _rgssModService = new();
private readonly WolfSaveService _wolfSaveService = new();
private readonly WolfArchiveService _wolfArchiveService = new();
private readonly WolfModService _wolfModService = new();
private readonly SrpgArchiveService _srpgArchiveService = new();
private readonly SrpgModService _srpgModService = new();
private readonly TkoolPackagedExtractionService _extractionService = new();
private readonly TkoolInjectionService _injectionService = new();
private readonly WindowResizeService _windowResizeService = new();
/// <summary>直近に起動したゲームプロセス(起動後の外部連携処理で使用)</summary>
private Process? _lastStartedProcess;
private readonly ObservableCollection<GameItemBase> _games = [];
private ListCollectionView _gamesView = null!;
private readonly GameItemComparer _gameComparer = new() { SortOrder = GameSortOrder.LastLaunchedDesc };
private readonly HashSet<string> _scannedPaths = new(StringComparer.OrdinalIgnoreCase);
private CancellationTokenSource? _scanCts;
private int _scannedCountSinceLastSave;
private readonly string _configFilePath;
private LauncherConfig _config = new();
private bool _isInitialized;
public MainWindow()
{
InitializeComponent();
_configFilePath = Path.Combine(AppPathHelper.GetExeDirectory(), "config.json");
_gamesView = (ListCollectionView)CollectionViewSource.GetDefaultView(_games);
_gamesView.Filter = FilterGameItem;
_gamesView.CustomSort = _gameComparer;
lstGames.ItemsSource = _gamesView;
// 初期ソート順
ApplySortOrderToComboBox(GameSortOrder.LastLaunchedDesc);
// 保存された設定の読み込み
LoadConfig();
_isInitialized = true;
// ウィンドウ描画後に初期処理(即時一覧作成&裏での更新監視)を開始
ContentRendered += MainWindow_ContentRendered;
Closing += MainWindow_Closing;
}
#region 設定のロード & セーブ
private void btnOpenConfig_Click(object sender, RoutedEventArgs e)
{
var dialog = new ConfigDialog(_config)
{
Owner = this
};
if (dialog.ShowDialog() == true)
{
SaveConfig();
AppendLog($"[設定変更] 設定を保存しました。(RGSS Extractor: {_config.RgssExtractorPath})");
}
}
private void LoadConfig()
{
try
{
if (File.Exists(_configFilePath))
{
string json = File.ReadAllText(_configFilePath);
var config = JsonSerializer.Deserialize<LauncherConfig>(json);
if (config != null)
{
_config = config;
_gameComparer.SortOrder = _config.SortOrder;
ApplySortOrderToComboBox(_config.SortOrder);
// フィルター設定の復元
RestoreFilterSettings();
}
}
}
catch { }
SyncDefaultPluginSettingsWithAvailablePlugins();
}
private void RestoreFilterSettings()
{
switch (_config.SelectedTab)
{
case 1: tabMV.IsChecked = true; break;
case 2: tabMZ.IsChecked = true; break;
case 3: tabVXAce.IsChecked = true; break;
case 4: tabVX.IsChecked = true; break;
case 5: tabTyrano.IsChecked = true; break;
case 6: tabUnity.IsChecked = true; break;
case 7: tabWolf.IsChecked = true; break;
case 8: tabSrpg.IsChecked = true; break;
default: tabAll.IsChecked = true; break;
}
if (pnlUnityBackendFilter != null)
{
pnlUnityBackendFilter.Visibility = tabUnity.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
}
// Unityフィルター
if (_config.UnityBackendFilter == "IL2CPP") rbUnityIL2CPP.IsChecked = true;
else if (_config.UnityBackendFilter == "Mono") rbUnityMono.IsChecked = true;
else rbUnityAll.IsChecked = true;
chkFilterModdedOnly.IsChecked = _config.TkoolFilterModdedOnly;
chkFilterAsarOnly.IsChecked = _config.TkoolFilterAsarOnly;
chkFilterRgssOnly.IsChecked = _config.TkoolFilterRgssOnly;
chkFilterSaveOnly.IsChecked = _config.UnityFilterSaveOnly;
}
private void SaveConfig()
{
if (!_isInitialized) return;
try
{
_config.SortOrder = _gameComparer.SortOrder;
int tabIndex = 0;
if (tabMV.IsChecked == true) tabIndex = 1;
else if (tabMZ.IsChecked == true) tabIndex = 2;
else if (tabVXAce.IsChecked == true) tabIndex = 3;
else if (tabVX.IsChecked == true) tabIndex = 4;
else if (tabTyrano.IsChecked == true) tabIndex = 5;
else if (tabUnity.IsChecked == true) tabIndex = 6;
else if (tabWolf.IsChecked == true) tabIndex = 7;
else if (tabSrpg.IsChecked == true) tabIndex = 8;
_config.SelectedTab = tabIndex;
_config.UnityBackendFilter = rbUnityIL2CPP.IsChecked == true ? "IL2CPP" : (rbUnityMono.IsChecked == true ? "Mono" : "All");
_config.TkoolFilterModdedOnly = chkFilterModdedOnly.IsChecked == true;
_config.TkoolFilterAsarOnly = chkFilterAsarOnly.IsChecked == true;
_config.TkoolFilterRgssOnly = chkFilterRgssOnly.IsChecked == true;
_config.UnityFilterSaveOnly = chkFilterSaveOnly.IsChecked == true;
var options = new JsonSerializerOptions
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
string json = JsonSerializer.Serialize(_config, options);
File.WriteAllText(_configFilePath, json);
}
catch { }
}
private void SyncDefaultPluginSettingsWithAvailablePlugins()
{
try
{
bool modified = false;
if (_modService.AvailablePlugins.Count == 0)
{
_modService.LoadAvailablePlugins();
}
foreach (var plugin in _modService.AvailablePlugins)
{
if (!_config.DefaultPluginSettings.ContainsKey(plugin.Id))
{
_config.DefaultPluginSettings[plugin.Id] = true;
modified = true;
}
}
foreach (var tyranoPlugin in TkoolGameItem.DefaultTyranoPlugins)
{
if (!_config.DefaultPluginSettings.ContainsKey(tyranoPlugin.Id))
{
_config.DefaultPluginSettings[tyranoPlugin.Id] = true;
modified = true;
}
}
foreach (var rgssPlugin in TkoolGameItem.DefaultRgssPlugins)
{
if (!_config.DefaultPluginSettings.ContainsKey(rgssPlugin.Id))
{
_config.DefaultPluginSettings[rgssPlugin.Id] = true;
modified = true;
}
}
if (modified || !File.Exists(_configFilePath))
{
SaveConfig();
}
}
catch { }
}
private void ApplySortOrderToComboBox(GameSortOrder order)
{
foreach (ComboBoxItem item in cmbSortOrder.Items)
{
if (item.Tag is string tag && Enum.TryParse<GameSortOrder>(tag, out var parsed) && parsed == order)
{
cmbSortOrder.SelectedItem = item;
break;
}
}
}
#endregion
#region ウィンドウ起動 & スキャンパイプライン
private async void MainWindow_ContentRendered(object? sender, EventArgs e)
{
ContentRendered -= MainWindow_ContentRendered;
AppendLog("統合ゲームランチャー (Game Launcher) を起動しました。");
// 0. ツクール改造プラグインの動的検出
_modService.LoadAvailablePlugins();
AppendLog($"ツクールプラグインフォルダから {_modService.AvailablePlugins.Count} 件のプラグインを認識しました。");
// 1. キャッシュから全ゲームを瞬時にロードし、0秒で一覧に表示
var cached = _scannerService.LoadCachedGamesFast();
foreach (var item in cached)
{
if (item is TkoolGameItem tg)
{
tg.SetDefaultApplyMod(_config.DefaultApplyMod);
}
_games.Add(item);
_scannedPaths.Add(item.RootDirectory);
}
_gamesView.Refresh();
UpdateStatusLabels();
if (_games.Count > 0)
{
int tkoolCount = _games.Count(g => g is TkoolGameItem tg && tg.EngineType != TkoolEngineType.Tyrano && !tg.IsRgss && !tg.IsWolf);
int rgssCount = _games.Count(g => g is TkoolGameItem tg && tg.IsRgss);
int tyranoCount = _games.Count(g => g is TkoolGameItem tg && tg.EngineType == TkoolEngineType.Tyrano);
int wolfCount = _games.Count(g => g is TkoolGameItem tg && tg.IsWolf);
int unityCount = _games.Count(g => g is UnityGameItem);
AppendLog($"キャッシュから計 {_games.Count} 件(ツクールMV/MZ: {tkoolCount}, ツクールVX系: {rgssCount}, ティラノ: {tyranoCount}, ウディタ: {wolfCount}, Unity: {unityCount})を即時表示しました。(待たずに即起動可能です)");
lblStatusEngine.Text = "裏で更新・実在検証を実行中...";
}
else
{
AppendLog("キャッシュは見つかりませんでした。初回フルスキャンを実行します。");
lblStatusEngine.Text = "初回スキャンを実行中...";
}
// 2. 裏で実在検証・差分スキャンを実行
await RunVerificationAndScanAsync();
}
private async Task RunVerificationAndScanAsync()
{
_scanCts?.Cancel();
_scanCts = new CancellationTokenSource();
var ct = _scanCts.Token;
try
{
lblLogActivity.Text = "● スキャン中...";
// 2-1. 実在検証 & アイコン・セーブ情報エンリッチ
if (_games.Count > 0)
{
await _scannerService.VerifyAndEnrichGamesAsync(
_games.ToList(),
onGameUpdated: game =>
{
Dispatcher.Invoke(() =>
{
if (lstGames.SelectedItem == game)
{
UpdateSelectedPanel(game);
}
});
},
onGameRemoved: game =>
{
Dispatcher.Invoke(() =>
{
_games.Remove(game);
_scannedPaths.Remove(game.RootDirectory);
UpdateStatusLabels();
});
},
ct: ct);
}
// 2-2. 差分スキャン(新規フォルダの走査)
var targetDirs = new List<string>(GameScannerService.DefaultTargetDirectories);
if (_config.TargetDirectories != null)
{
targetDirs.AddRange(_config.TargetDirectories);
}
var progress = new Progress<GameItemBase>(newGame =>
{
Dispatcher.Invoke(() =>
{
if (newGame is TkoolGameItem tg)
{
tg.SetDefaultApplyMod(_config.DefaultApplyMod);
tg.SyncPluginOptions(_modService.AvailablePlugins, _config.DefaultPluginSettings);
}
_games.Add(newGame);
_scannedPaths.Add(newGame.RootDirectory);
UpdateStatusLabels();
_scannedCountSinceLastSave++;
if (_scannedCountSinceLastSave >= 5)
{
_scannedCountSinceLastSave = 0;
_scannerService.SaveCache(_games);
}
});
});
await _scannerService.ScanDirectoriesAsync(targetDirs, progress, _scannedPaths, ct);
// キャッシュの最終同期
_scannerService.SaveCache(_games);
lblStatusEngine.Text = "準備完了";
lblLogActivity.Text = "";
AppendLog($"スキャンが完了しました。総ゲーム数: {_games.Count} 件。");
}
catch (OperationCanceledException)
{
lblStatusEngine.Text = "スキャン中断";
lblLogActivity.Text = "";
}
catch (Exception ex)
{
lblStatusEngine.Text = "スキャンエラー";
lblLogActivity.Text = "";
AppendLog($"スキャン中にエラーが発生しました: {ex.Message}");
}
}
private async void btnRescan_Click(object sender, RoutedEventArgs e)
{
btnRescan.IsEnabled = false;
AppendLog("手動再スキャンを開始します...");
_scannedPaths.Clear();
foreach (var g in _games)
{
_scannedPaths.Add(g.RootDirectory);
}
await RunVerificationAndScanAsync();
btnRescan.IsEnabled = true;
}
private void MainWindow_Closing(object? sender, CancelEventArgs e)
{
_scanCts?.Cancel();
SaveConfig();
_scannerService.SaveCache(_games);
}
#endregion
#region フィルタリング & ソート
private bool FilterGameItem(object item)
{
if (item is not GameItemBase game) return false;
// 1. テキスト検索
string query = txtSearch.Text.Trim();
if (!string.IsNullOrEmpty(query))
{
bool matchesTitle = game.Title.Contains(query, StringComparison.OrdinalIgnoreCase);
bool matchesFolder = game.FolderName.Contains(query, StringComparison.OrdinalIgnoreCase);
bool matchesCompany = false;
bool matchesProduct = false;
if (game is UnityGameItem ug)
{
matchesCompany = !string.IsNullOrEmpty(ug.CompanyName) && ug.CompanyName.Contains(query, StringComparison.OrdinalIgnoreCase);
matchesProduct = !string.IsNullOrEmpty(ug.ProductName) && ug.ProductName.Contains(query, StringComparison.OrdinalIgnoreCase);
}
if (!matchesTitle && !matchesFolder && !matchesCompany && !matchesProduct)
{
return false;
}
}
// 2. エンジンの種類フィルター
if (tabMV.IsChecked == true)
{
if (game is not TkoolGameItem tg || tg.EngineType != TkoolEngineType.MV) return false;
}
else if (tabMZ.IsChecked == true)
{
if (game is not TkoolGameItem tg || tg.EngineType != TkoolEngineType.MZ) return false;
}
else if (tabVXAce.IsChecked == true)
{
if (game is not TkoolGameItem tg || tg.EngineType != TkoolEngineType.VXAce) return false;
}
else if (tabVX.IsChecked == true)
{
if (game is not TkoolGameItem tg || tg.EngineType != TkoolEngineType.VX) return false;
}
else if (tabTyrano.IsChecked == true)
{
if (game is not TkoolGameItem tg || tg.EngineType != TkoolEngineType.Tyrano) return false;
}
else if (tabWolf.IsChecked == true)
{
if (game is not TkoolGameItem tg || tg.EngineType != TkoolEngineType.Wolf) return false;
}
else if (tabSrpg.IsChecked == true)
{
if (game is not TkoolGameItem tg || tg.EngineType != TkoolEngineType.SrpgStudio) return false;
}
else if (tabUnity.IsChecked == true)
{
if (game is not UnityGameItem ug) return false;
if (rbUnityIL2CPP.IsChecked == true && ug.BackendType != UnityBackendType.IL2CPP) return false;
if (rbUnityMono.IsChecked == true && ug.BackendType != UnityBackendType.Mono) return false;
}
// 3. 追加属性フィルター(全タブ共通)
if (chkFilterModdedOnly.IsChecked == true && !game.IsModded) return false;
if (chkFilterAsarOnly.IsChecked == true && (game is not TkoolGameItem tgAsar || !tgAsar.IsAsar)) return false;
if (chkFilterRgssOnly.IsChecked == true && (game is not TkoolGameItem tgRgss || !tgRgss.HasRgssArchive)) return false;
if (chkFilterSrpgOnly.IsChecked == true && (game is not TkoolGameItem tgSrpg || !tgSrpg.HasSrpgArchive)) return false;
if (chkFilterSaveOnly.IsChecked == true && (game is not UnityGameItem ugSave || !ugSave.HasSaveData)) return false;
return true;
}
private void EngineTab_Checked(object sender, RoutedEventArgs e)
{
if (!_isInitialized) return;
if (pnlUnityBackendFilter != null)
{
pnlUnityBackendFilter.Visibility = tabUnity.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
}
_gamesView?.Refresh();
UpdateStatusLabels();
SaveConfig();
}
private void FilterChanged(object sender, RoutedEventArgs e)
{
if (!_isInitialized) return;
_gamesView?.Refresh();
UpdateStatusLabels();
SaveConfig();
}
private void txtSearch_TextChanged(object sender, TextChangedEventArgs e)
{
if (!_isInitialized) return;
_gamesView?.Refresh();
UpdateStatusLabels();
}
private void btnClearSearch_Click(object sender, RoutedEventArgs e)
{
txtSearch.Text = string.Empty;
}
private void cmbSortOrder_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!_isInitialized) return;
if (cmbSortOrder.SelectedItem is ComboBoxItem item &&
item.Tag is string tag &&
Enum.TryParse<GameSortOrder>(tag, out var order))
{
_gameComparer.SortOrder = order;
_gamesView?.Refresh();
SaveConfig();
}
}
private void UpdateStatusLabels()
{
if (lblStatusSummary == null || lblStatusBreakdown == null) return;
int total = _games.Count;
int visible = _gamesView?.Count ?? 0;
int tkoolCount = _games.Count(g => g is TkoolGameItem tg && tg.EngineType != TkoolEngineType.Tyrano && !tg.IsRgss && !tg.IsWolf && !tg.IsSrpgStudio);
int rgssCount = _games.Count(g => g is TkoolGameItem tg && tg.IsRgss);
int tyranoCount = _games.Count(g => g is TkoolGameItem tg && tg.EngineType == TkoolEngineType.Tyrano);
int wolfCount = _games.Count(g => g is TkoolGameItem tg && tg.IsWolf);
int srpgCount = _games.Count(g => g is TkoolGameItem tg && tg.IsSrpgStudio);
int unityCount = _games.Count(g => g is UnityGameItem);
lblStatusSummary.Text = $"総ゲーム数: {total} 件 | 表示: {visible} 件";
lblStatusBreakdown.Text = $"(ツクールMV/MZ: {tkoolCount}, ツクールVX系: {rgssCount}, ティラノ: {tyranoCount}, ウディタ: {wolfCount}, SRPG Studio: {srpgCount}, Unity: {unityCount})";
}
#endregion
#region 詳細パネル & 選択制御
private void lstGames_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selected = lstGames.SelectedItem as GameItemBase;
if (selected == null)
{
pnlNoSelection.Visibility = Visibility.Visible;
pnlSelectedContent.Visibility = Visibility.Collapsed;
return;
}
pnlNoSelection.Visibility = Visibility.Collapsed;
pnlSelectedContent.Visibility = Visibility.Visible;
UpdateSelectedPanel(selected);
}
private void UpdateSelectedPanel(GameItemBase game)
{
if (game is TkoolGameItem tg)
{
pnlTkoolDetails.Visibility = Visibility.Visible;
pnlUnityDetails.Visibility = Visibility.Collapsed;
// プラグイン設定の同期(未初期化の場合)
if (tg.PluginOptions.Count == 0)
{
tg.SyncPluginOptions(_modService.AvailablePlugins, _config.DefaultPluginSettings);
}
}
else if (game is UnityGameItem)
{
pnlTkoolDetails.Visibility = Visibility.Collapsed;
pnlUnityDetails.Visibility = Visibility.Visible;
}
}
private async void lstGames_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
if (lstGames.SelectedItem is GameItemBase game)
{
await LaunchGameAsync(game);
}
}
#endregion
#region ゲーム起動
private async void btnLaunchGame_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is GameItemBase game)
{
await LaunchGameAsync(game);
}
}
private async void MenuLaunch_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is GameItemBase game)
{
await LaunchGameAsync(game);
}
}
private async Task LaunchGameAsync(GameItemBase game)
{
if (string.IsNullOrEmpty(game.ExecutablePath) || !File.Exists(game.ExecutablePath))
{
MessageBox.Show($"実行ファイルが見つかりません:\n{game.ExecutablePath}", "起動エラー", MessageBoxButton.OK, MessageBoxImage.Warning);
AppendLog($"[起動失敗] 実行ファイルが見つかりません: {game.ExecutablePath}");
return;
}
try
{
if (game is TkoolGameItem tg)
{
await LaunchTkoolGameAsync(tg);
}
else if (game is UnityGameItem ug)
{
LaunchUnityGame(ug);
}
}
catch (Exception ex)
{
MessageBox.Show($"ゲーム起動中にエラーが発生しました:\n{ex.Message}", "起動エラー", MessageBoxButton.OK, MessageBoxImage.Error);
AppendLog($"[起動エラー] {game.Title}: {ex.Message}");
}
}
private async Task LaunchTkoolGameAsync(TkoolGameItem tg)
{
// ウディタゲームの場合の起動処理
if (tg.IsWolf)
{
// プロキシDLLの適用または解除の同期
if (tg.WolfProxyDll)
{
var (pSuccess, pMsg) = _wolfModService.ApplyProxyDll(tg, 1.0, tg.WolfSpeedMultiplier > 0 ? tg.WolfSpeedMultiplier : 3.0, 5.0);
AppendLog($"[ウディタ プロキシDLL] {pMsg.Replace("\n", " ")}");
}
else if (_wolfModService.IsProxyDllInstalled(tg))
{
var (pSuccess, pMsg) = _wolfModService.RemoveProxyDll(tg);
AppendLog($"[ウディタ プロキシDLL] {pMsg}");
}
AppendLog($"[ウディタ起動] {tg.Title} を起動します...");
StartGameProcess(tg);
return;
}
// SRPG Studioゲームの場合の起動処理
if (tg.IsSrpgStudio)
{
// プロキシDLLの適用または解除の同期
if (tg.SrpgProxyDll)
{
bool ok = _srpgModService.EnableProxyDll(tg.RootDirectory, tg.SrpgSpeedMultiplier > 0 ? tg.SrpgSpeedMultiplier : 3.0);
AppendLog($"[SRPG Studio プロキシDLL] 倍速プロキシDLLを配置しました (倍率: {(tg.SrpgSpeedMultiplier > 0 ? tg.SrpgSpeedMultiplier : 3.0):F1}x)");
}
else if (SrpgModService.IsProxyDllEnabled(tg.RootDirectory))
{
_srpgModService.DisableProxyDll(tg.RootDirectory);
AppendLog("[SRPG Studio プロキシDLL] プロキシDLLを解除しました");
}
AppendLog($"[SRPG Studio起動] {tg.Title} を起動します...");
StartGameProcess(tg);
return;
}
// 単体exe梱包ゲーム(FOSSIL / boxed)の場合の起動処理
if (tg.IsStandaloneExePackage)
{
await LaunchStandaloneExeGameAsync(tg);
return;
}
// ASAR形式ゲームで未解凍かつ改造適用ONの場合、解凍を促す
if (tg.IsAsar && !tg.IsAsarExtracted && tg.ApplyMod)
{
var ask = MessageBox.Show(
"このゲームは app.asar 形式でパッケージされています。\n" +
"スクリプト改造を適用するには、事前に解凍が必要です。\n\n" +
"今すぐ ASAR を自動解凍して改造を適用し、起動しますか?",
"ASAR 解凍の確認",
MessageBoxButton.YesNoCancel,
MessageBoxImage.Question);
if (ask == MessageBoxResult.Yes)
{
await ExtractAsarForGame(tg, autoLaunchAfter: true);
return;
}
else if (ask == MessageBoxResult.Cancel)
{
return;
}
}
// RGSSゲーム(ツクールVX / VX Ace)の場合
if (tg.IsRgss)
{
var (success, msg) = await _rgssModService.ApplyOrRestoreModAsync(tg, tg.PluginSettings, _config.RgssExtractorPath);
AppendLog($"[RGSS改造処理] {tg.Title}: {msg}");
if (!success && tg.ApplyMod)
{
var res = MessageBox.Show(
$"スクリプト改造の適用中に警告/エラーが発生しました:\n{msg}\n\nこのまま通常(未改造)でゲームを起動しますか?",
"RGSS改造警告",
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (res != MessageBoxResult.Yes) return;
}
}
// スクリプト改造の適用または復元(ティラノ)
else if (tg.EngineType == TkoolEngineType.Tyrano)
{
if (tg.ApplyMod)
{
var (success, msg) = _tyranoModService.ApplyMod(tg, tg.PluginSettings);
AppendLog($"[ティラノ改造] {tg.Title}: {msg}");
}
else
{
var (success, msg) = _tyranoModService.RestoreOriginal(tg);
AppendLog($"[ティラノ復元] {tg.Title}: {msg}");
}
}
// スクリプト改造の適用または復元(ツクールMV/MZ)
else
{
var (success, msg) = _modService.ApplyOrRestoreMod(tg, _config.DefaultPluginSettings);
AppendLog($"[ツクール改造処理] {tg.Title}: {msg}");
}
StartGameProcess(tg);
// RGSSゲーム(ツクールVX / VX Ace)で外部ツール方式のウィンドウ拡大がONの場合、起動後に拡大を適用
if (tg.IsRgss && tg.IsPluginEnabled("RgssWindowResizeExternal", tg.PluginSettings, false))
{
var resizeProc = _lastStartedProcess;
if (resizeProc != null)
{
var (resizeOk, resizeMsg) = await _windowResizeService.ApplyResizeAsync(resizeProc, _config.WindowResizeToolPath);
AppendLog($"[ウィンドウ拡大] {tg.Title}: {resizeMsg}");
}
}
}
/// <summary>
/// 単体exe梱包ゲーム(FOSSIL / boxed)の起動処理。
/// ディスク上に js 実体が無い形態は、改造適用ON時に _extracted へ展開してから注入し、
/// 展開先が無い/展開不可の場合はそのままexeを起動する(起動対応のみ)。
/// </summary>
private async Task LaunchStandaloneExeGameAsync(TkoolGameItem tg)
{
// 1. 改造適用ON時は埋め込みコンテナを _extracted へ展開を試行(冪等)
// 展開戦略: 組み込みZIP展開 → 外部アンパッカー委譲(未配置なら自動取得)の順で試行。
if (tg.ApplyMod)
{
var progress = new Progress<string>(m => AppendLog($"[単体exe展開] {m}"));
var relPlugins = _extractionService.ExtractPackageNw(tg.ExecutablePath, tg.RootDirectory, out var extractedDir, progress);
if (relPlugins != null)
{
tg.IsStandaloneExeExtracted = true;
tg.StandaloneExtractedDirPath = extractedDir;
}
else if (tg.IsBoxedExe)
{
AppendLog($"[単体exe展開] {tg.Title}: 埋め込み/外部いずれの展開も不可でした(起動のみ対応)。");
}
// 2. 注入可能な plugins.js が得られた場合のみ注入を適用(可逆)
var injectable = ResolveInjectablePluginsJs(tg.RootDirectory);
if (injectable != null)
{
var modPluginPath = Path.Combine(TkoolModService.GetPluginsDirectory(), TkoolInjectionService.ModPluginFileName);
var pluginsDir = Path.GetDirectoryName(injectable)!;
var ok = _injectionService.Apply(injectable, Path.Combine(pluginsDir, "plugins"), modPluginPath);
AppendLog($"[単体exe改造] {tg.Title}: {(ok ? "注入しました(可逆)" : "注入に失敗しました")}");
if (ok)
{
tg.IsModded = true;
tg.StandaloneBackupPath = injectable + TkoolInjectionService.ExeBackupSuffix;
}
}
else
{
AppendLog($"[単体exe改造] {tg.Title}: exe内にJSが埋め込まれているため注入不可(起動のみ)。");
}
_scannerService.SaveCache(_games);
}
else
{
// 改造OFF時は復元を試行
var injectable = ResolveInjectablePluginsJs(tg.RootDirectory);
if (injectable != null)
{
var pluginsDir = Path.Combine(Path.GetDirectoryName(injectable)!, "plugins");
var ok = _injectionService.Restore(injectable, pluginsDir);
AppendLog($"[単体exe復元] {tg.Title}: {(ok ? "オリジナルへ復元しました" : "復元に失敗しました")}");
}
tg.IsModded = false;
_scannerService.SaveCache(_games);
}
AppendLog($"[単体exe起動] {tg.Title} を起動します...");
StartGameProcess(tg);
}
/// <summary>
/// 単体exe梱包ゲームで注入/復元の対象となる plugins.js を解決します。
/// 優先順: `_extracted` 内 → ディスク上(js / www/js)。無ければ null。
/// </summary>
private static string? ResolveInjectablePluginsJs(string gameRootDir)
{
try
{
var candidates = new[]
{
Path.Combine(gameRootDir, TkoolPackagedExtractionService.ExtractedDirName, "js", "plugins.js"),
Path.Combine(gameRootDir, TkoolPackagedExtractionService.ExtractedDirName, "js", "plugins", "plugins.js"),
Path.Combine(gameRootDir, TkoolPackagedExtractionService.ExtractedDirName, "www", "js", "plugins.js"),
Path.Combine(gameRootDir, "js", "plugins.js"),
Path.Combine(gameRootDir, "www", "js", "plugins.js"),
};
return candidates.FirstOrDefault(File.Exists);
}
catch
{
return null;
}
}
private void LaunchUnityGame(UnityGameItem ug)
{
AppendLog($"[Unity起動] {ug.Title} (Backend: {ug.BackendBadgeText}) を起動します...");
StartGameProcess(ug);
}
private void StartGameProcess(GameItemBase game)
{
var workingDir = Path.GetDirectoryName(game.ExecutablePath) ?? game.RootDirectory;
var startInfo = new ProcessStartInfo
{
FileName = game.ExecutablePath,
WorkingDirectory = workingDir,
UseShellExecute = true
};
// ツクール/ティラノ等のWebランタイム(NW.js / Chromium)ゲームの場合、
// GameLauncher.exe のあるフォルダ配下の Profiles フォルダに隔離した専用プロファイルディレクトリを指定して起動
// ※RGSS(DirectX/Ruby)やウディタ、Unity等のネイティブアプリには引数を付与しない
if (game is TkoolGameItem tg && !tg.IsRgss && !tg.IsWolf)
{
try
{
var profileDir = AppPathHelper.GetGameProfileDirectory(tg.FolderName, tg.RootDirectory);
if (!Directory.Exists(profileDir))
{
Directory.CreateDirectory(profileDir);
}
startInfo.Arguments = $"--user-data-dir=\"{profileDir}\"";
AppendLog($"[プロファイル] 専用プロファイルを指定: {Path.GetFileName(profileDir)}");
}
catch (Exception pEx)
{
AppendLog($"[警告] 専用プロファイルの準備に失敗しました(通常引数で起動します): {pEx.Message}");
}
}
_lastStartedProcess = Process.Start(startInfo);
game.LastLaunched = DateTime.Now;
_scannerService.SaveCache(_games);
AppendLog($"🚀 {game.Title} を起動しました。");
}
#endregion
#region コンテキストメニュー制御
private void listContextMenu_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
var selected = lstGames.SelectedItem as GameItemBase;
if (selected == null)
{
e.Handled = true;
return;
}
bool isTkool = selected is TkoolGameItem;
bool isUnity = selected is UnityGameItem;
// ツクール専用メニュー
menuTkoolOpenFolder.Visibility = isTkool ? Visibility.Visible : Visibility.Collapsed;
menuTkoolRestoreOriginal.Visibility = isTkool ? Visibility.Visible : Visibility.Collapsed;
if (selected is TkoolGameItem tg)
{
// ASAR メニュー
if (tg.IsAsar)
{
menuTkoolExtractAsar.Visibility = !tg.IsAsarExtracted ? Visibility.Visible : Visibility.Collapsed;
menuTkoolRestoreAsar.Visibility = tg.IsAsarExtracted ? Visibility.Visible : Visibility.Collapsed;
}
else
{
menuTkoolExtractAsar.Visibility = Visibility.Collapsed;
menuTkoolRestoreAsar.Visibility = Visibility.Collapsed;
}
// RGSS メニュー
if (tg.IsRgss && tg.HasRgssArchive)
{
menuTkoolExtractRgss.Visibility = !tg.IsRgssExtracted ? Visibility.Visible : Visibility.Collapsed;
menuTkoolRestoreRgss.Visibility = tg.IsRgssExtracted ? Visibility.Visible : Visibility.Collapsed;
}
else
{
menuTkoolExtractRgss.Visibility = Visibility.Collapsed;
menuTkoolRestoreRgss.Visibility = Visibility.Collapsed;
}
// plugins.js は MV/MZ のみ
menuTkoolOpenPluginsJs.Visibility = (tg.IsMV || tg.IsMZ) && File.Exists(tg.PluginsJsPath) ? Visibility.Visible : Visibility.Collapsed;
// 専用プロファイルフォルダは Chromium/NW.js 系(MV/MZ/Tyrano)のみ
menuTkoolOpenProfile.Visibility = !tg.IsRgss ? Visibility.Visible : Visibility.Collapsed;
}
else
{
menuTkoolExtractAsar.Visibility = Visibility.Collapsed;
menuTkoolRestoreAsar.Visibility = Visibility.Collapsed;
menuTkoolExtractRgss.Visibility = Visibility.Collapsed;
menuTkoolRestoreRgss.Visibility = Visibility.Collapsed;
menuTkoolOpenPluginsJs.Visibility = Visibility.Collapsed;
menuTkoolOpenProfile.Visibility = Visibility.Collapsed;
}
// Unity専用メニュー
menuUnitySaveEditor.Visibility = isUnity ? Visibility.Visible : Visibility.Collapsed;
menuUnityOpenFolder.Visibility = isUnity ? Visibility.Visible : Visibility.Collapsed;
menuUnityOpenLocalLow.Visibility = isUnity ? Visibility.Visible : Visibility.Collapsed;
menuUnityOpenRegedit.Visibility = isUnity ? Visibility.Visible : Visibility.Collapsed;
menuUnityBackupSave.Visibility = isUnity ? Visibility.Visible : Visibility.Collapsed;
}
#endregion
#region ツクール専用機能 (ASAR解凍・復元・RGSS抽出・復元・MOD解除・Profile)
private async void btnExtractAsar_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is TkoolGameItem tg)
{
await ExtractAsarForGame(tg, autoLaunchAfter: false);
}
}
private async void MenuExtractAsar_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is TkoolGameItem tg)
{
await ExtractAsarForGame(tg, autoLaunchAfter: false);
}
}
private async Task ExtractAsarForGame(TkoolGameItem tg, bool autoLaunchAfter)
{
if (!tg.IsAsar || string.IsNullOrEmpty(tg.AsarPath)) return;
btnExtractAsar.IsEnabled = false;
pbAsarProgress.Visibility = Visibility.Visible;
lblAsarProgressStatus.Visibility = Visibility.Visible;
pbAsarProgress.Value = 0;
lblAsarProgressStatus.Text = "ASAR を解凍中...";
AppendLog($"[ASAR解凍開始] {tg.Title} ({tg.AsarPath})");
var outputDir = tg.AsarExtractedDirPath;
if (string.IsNullOrEmpty(outputDir))
{
var dir = Path.GetDirectoryName(tg.AsarPath) ?? tg.RootDirectory;
outputDir = Path.Combine(dir, "app");
}
var progress = new Progress<(long extractedBytes, long totalBytes, int currentFileIndex, int totalFiles, string currentFileName)>(p =>
{
int pct = p.totalFiles > 0 ? (int)((double)p.currentFileIndex / p.totalFiles * 100) : 0;
pbAsarProgress.Value = pct;
lblAsarProgressStatus.Text = $"解凍中 ({p.currentFileIndex}/{p.totalFiles}): {p.currentFileName}";
});
var (success, message) = await _asarService.ExtractAsarAsync(tg.AsarPath, outputDir, progress);
pbAsarProgress.Visibility = Visibility.Collapsed;
lblAsarProgressStatus.Visibility = Visibility.Collapsed;
btnExtractAsar.IsEnabled = true;
if (success)
{
tg.IsAsarExtracted = true;
tg.AsarExtractedDirPath = outputDir;
// plugins.js または index.html のパスを特定
var relJs = tg.RelativePluginsJsInAsar ?? (tg.EngineType == TkoolEngineType.Tyrano ? "index.html" : "project/js/plugins.js");
tg.PluginsJsPath = Path.Combine(outputDir, relJs.Replace('/', Path.DirectorySeparatorChar));
tg.PluginsDirPath = Path.Combine(Path.GetDirectoryName(tg.PluginsJsPath)!, "plugins");
_scannerService.SaveCache(_games);
AppendLog($"[ASAR解凍成功] {message}");
MessageBox.Show(message, "ASAR 解凍完了", MessageBoxButton.OK, MessageBoxImage.Information);
if (autoLaunchAfter)
{
await LaunchGameAsync(tg);
}
}
else
{
AppendLog($"[ASAR解凍失敗] {message}");
MessageBox.Show(message, "ASAR 解凍エラー", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private async void btnRestoreAsar_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is TkoolGameItem tg)
{
await RestoreAsarForGame(tg);
}
}
private async void MenuRestoreAsar_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is TkoolGameItem tg)
{
await RestoreAsarForGame(tg);
}
}
/// <summary>
/// 単体exe梱包ゲーム(FOSSIL / boxed)の埋め込みコンテナを _extracted へ展開します。
/// </summary>
private async void btnExtractStandalone_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsStandaloneExePackage) return;
btnExtractStandalone.IsEnabled = false;
AppendLog($"[単体exe展開開始] {tg.Title}");
try
{
var progress = new Progress<string>(m => AppendLog($"[単体exe展開] {m}"));
var relPlugins = await Task.Run(() =>
_extractionService.ExtractPackageNw(tg.ExecutablePath, tg.RootDirectory, out var dir, progress));
if (relPlugins != null)
{
tg.IsStandaloneExeExtracted = true;
tg.StandaloneExtractedDirPath = TkoolPackagedExtractionService.GetExtractedDir(tg.RootDirectory);
_scannerService.SaveCache(_games);
AppendLog($"[単体exe展開成功] {tg.Title}: {relPlugins}");
MessageBox.Show("埋め込みコンテナを _extracted へ展開しました。", "埋め込み展開",
MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
AppendLog($"[単体exe展開失敗] {tg.Title}: exe内に展開可能なZIPコンテナを検出できませんでした。");
MessageBox.Show("exe内に展開可能なZIPコンテナを検出できませんでした。起動対応のみ可能です。",
"埋め込み展開", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
finally
{
btnExtractStandalone.IsEnabled = true;
}
}
/// <summary>
/// 単体exe梱包ゲームの改造プラグイン注入を除去し、オリジナル状態へ復元します(可逆)。
/// </summary>
private void btnRestoreStandalone_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsStandaloneExePackage) return;
var injectable = ResolveInjectablePluginsJs(tg.RootDirectory);
if (injectable == null)
{
AppendLog($"[単体exe復元] {tg.Title}: 復元対象の plugins.js が見つかりません。");
MessageBox.Show("復元対象の plugins.js が見つかりません。", "改造の復元",
MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
var pluginsDir = Path.Combine(Path.GetDirectoryName(injectable)!, "plugins");
var ok = _injectionService.Restore(injectable, pluginsDir);
if (ok)
{
tg.IsModded = false;
tg.StandaloneBackupPath = null;
_scannerService.SaveCache(_games);
}
AppendLog($"[単体exe復元{(ok ? "成功" : "失敗")}] {tg.Title}");
MessageBox.Show(ok ? "ゲームを改造前のオリジナル状態へ復元しました。" : "復元に失敗しました。",
"改造の復元", MessageBoxButton.OK,
ok ? MessageBoxImage.Information : MessageBoxImage.Warning);
}
private async Task RestoreAsarForGame(TkoolGameItem tg)
{
if (!tg.IsAsar || string.IsNullOrEmpty(tg.AsarPath) || string.IsNullOrEmpty(tg.AsarExtractedDirPath)) return;
var confirm = MessageBox.Show(
"解凍されたフォルダをクリーンアップし、元の圧縮された app.asar の状態に戻しますか?\n(解凍先に行った変更は失われます)",
"ASAR状態への復元確認",
MessageBoxButton.YesNo,
MessageBoxImage.Question);
if (confirm != MessageBoxResult.Yes) return;
btnRestoreAsar.IsEnabled = false;
AppendLog($"[ASAR復元開始] {tg.Title}");
var (success, message) = await _asarService.RestoreAsarAsync(tg.AsarPath, tg.AsarExtractedDirPath);
btnRestoreAsar.IsEnabled = true;
if (success)
{
tg.IsAsarExtracted = false;
tg.IsModded = false;
_scannerService.SaveCache(_games);
AppendLog($"[ASAR復元成功] {message}");
MessageBox.Show(message, "ASAR 復元完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
AppendLog($"[ASAR復元失敗] {message}");
MessageBox.Show(message, "ASAR 復元エラー", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
#region RGSS スクリプト抽出・復元
private async void btnExtractRgss_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is TkoolGameItem tg)
{
await ExtractRgssForGame(tg);
}
}
private async void MenuExtractRgss_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is TkoolGameItem tg)
{
await ExtractRgssForGame(tg);
}
}
private async Task ExtractRgssForGame(TkoolGameItem tg)
{
if (!tg.IsRgss) return;
btnExtractRgss.IsEnabled = false;
pbRgssProgress.Visibility = Visibility.Visible;
pbRgssProgress.IsIndeterminate = true;
lblRgssProgressStatus.Visibility = Visibility.Visible;
lblRgssProgressStatus.Text = "RGSSスクリプトを抽出中...";
AppendLog($"[RGSS抽出開始] {tg.Title} (アーカイブ: {tg.RgssArchivePath})");
var (success, message) = await _rgssModService.ExtractScriptsAsync(tg, _config.RgssExtractorPath);
pbRgssProgress.Visibility = Visibility.Collapsed;
lblRgssProgressStatus.Visibility = Visibility.Collapsed;
btnExtractRgss.IsEnabled = true;
if (success)
{
_scannerService.SaveCache(_games);
AppendLog($"[RGSS抽出成功] {message}");
MessageBox.Show(message, "RGSS スクリプト抽出完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
AppendLog($"[RGSS抽出失敗] {message}");
MessageBox.Show(message, "RGSS スクリプト抽出エラー", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void btnRestoreRgss_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is TkoolGameItem tg)
{
RestoreRgssForGame(tg);
}
}
private void MenuRestoreRgss_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is TkoolGameItem tg)
{
RestoreRgssForGame(tg);
}
}
private void RestoreRgssForGame(TkoolGameItem tg)
{
if (!tg.IsRgss) return;
var confirm = MessageBox.Show(
"抽出したスクリプト(Data\\Scripts)や改造を元に戻し、元のアーカイブ暗号化状態に戻しますか?",
"RGSSスクリプト復元の確認",
MessageBoxButton.YesNo,
MessageBoxImage.Question);
if (confirm != MessageBoxResult.Yes) return;
AppendLog($"[RGSS復元開始] {tg.Title}");
var (success, message) = _rgssModService.RestoreOriginal(tg);
if (success)
{
tg.IsModded = false;
_scannerService.SaveCache(_games);
AppendLog($"[RGSS復元成功] {message}");
MessageBox.Show(message, "RGSS 復元完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
AppendLog($"[RGSS復元失敗] {message}");
MessageBox.Show(message, "RGSS 復元エラー", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
#endregion
private void btnRestoreOriginal_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is TkoolGameItem tg)
{
RestoreOriginalMod(tg);
}
}
private void MenuRestoreOriginal_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is TkoolGameItem tg)
{
RestoreOriginalMod(tg);
}
}
private void RestoreOriginalMod(TkoolGameItem tg)
{
var result = tg.IsRgss
? _rgssModService.RestoreOriginal(tg)
: (tg.EngineType == TkoolEngineType.Tyrano
? _tyranoModService.RestoreOriginal(tg)
: _modService.RestoreOriginal(tg));
tg.IsModded = false;
AppendLog($"[改造解除] {tg.Title}: {result.Message}");
if (result.Success)
{
MessageBox.Show(result.Message, "改造解除・復元完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
MessageBox.Show(result.Message, "復元エラー", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
private void MenuOpenProfileFolder_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is TkoolGameItem tg)
{
var dir = AppPathHelper.GetGameProfileDirectory(tg.FolderName, tg.RootDirectory);
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
Process.Start(new ProcessStartInfo { FileName = dir, UseShellExecute = true });
}
}
private void MenuOpenPluginsJs_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is TkoolGameItem tg && File.Exists(tg.PluginsJsPath))
{
Process.Start(new ProcessStartInfo { FileName = tg.PluginsJsPath, UseShellExecute = true });
}
}
#endregion
#region Unity専用機能 (セーブエディタ・LocalLow・regedit・即時バックアップ)
private void btnOpenSaveEditor_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is UnityGameItem ug)
{
OpenSaveEditor(ug);
}
}
private void MenuOpenSaveEditor_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is UnityGameItem ug)
{
OpenSaveEditor(ug);
}
}
private void OpenSaveEditor(UnityGameItem ug)
{
try
{
AppendLog($"[セーブエディタ起動] {ug.Title} のセーブエディタを開きます...");
var win = new SaveEditorWindow(ug)
{
Owner = this
};
win.ShowDialog();
// セーブ状態の再チェック
ug.HasSaveData = _scannerService.CheckHasSaveData(ug);
_scannerService.SaveCache(_games);
AppendLog($"[セーブエディタ終了] {ug.Title} のセーブエディタを閉じました。");
}
catch (Exception ex)
{
MessageBox.Show($"セーブエディタの起動中にエラーが発生しました:\n{ex.Message}", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
AppendLog($"[セーブエディタエラー] {ex.Message}");
}
}
private void btnOpenLocalLow_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is UnityGameItem ug)
{
OpenLocalLow(ug);
}
}
private void MenuOpenLocalLow_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is UnityGameItem ug)
{
OpenLocalLow(ug);
}
}
private void OpenLocalLow(UnityGameItem ug)
{
var path = ug.LocalLowPath;
if (!string.IsNullOrEmpty(path) && Directory.Exists(path))
{
Process.Start(new ProcessStartInfo { FileName = path, UseShellExecute = true });
}
else
{
var localLowRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "AppData", "LocalLow");
if (Directory.Exists(localLowRoot))
{
Process.Start(new ProcessStartInfo { FileName = localLowRoot, UseShellExecute = true });
}
else
{
MessageBox.Show("LocalLow フォルダが見つかりません。", "案内", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
}
private void btnOpenRegedit_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is UnityGameItem ug)
{
OpenRegedit(ug);
}
}
private void MenuOpenRegedit_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is UnityGameItem ug)
{
OpenRegedit(ug);
}
}
private void OpenRegedit(UnityGameItem ug)
{
try
{
// regedit の LastKey を設定して対象キーを直接開く
if (!string.IsNullOrEmpty(ug.RegistryPath))
{
using var key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Applets\Regedit");
if (key != null)
{
key.SetValue("LastKey", $@"HKEY_CURRENT_USER\{ug.RegistryPath}");
}
}
Process.Start(new ProcessStartInfo { FileName = "regedit.exe", UseShellExecute = true });
}
catch (Exception ex)
{
MessageBox.Show($"レジストリエディタの起動に失敗しました:\n{ex.Message}", "エラー", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
private void btnQuickBackup_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is UnityGameItem ug)
{
PerformUnityQuickBackup(ug);
}
}
private void MenuBackupSave_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is UnityGameItem ug)
{
PerformUnityQuickBackup(ug);
}
}
private void PerformUnityQuickBackup(UnityGameItem ug)
{
try
{
var backupDir = AppPathHelper.GetGameBackupDirectory(ug.FolderName, ug.RootDirectory);
int backedUpCount = 0;
// 1. レジストリ (PlayerPrefs)
if (!string.IsNullOrEmpty(ug.RegistryPath))
{
var regRes = _unitySaveService.BackupRegistry(ug.RegistryPath, backupDir);
if (regRes != null) backedUpCount++;
}
// 2. ディスクセーブファイル
var files = _unitySaveService.GetSaveFiles(ug);
foreach (var f in files)
{
var fileRes = _unitySaveService.BackupSaveFile(f.FilePath, backupDir);
if (fileRes != null) backedUpCount++;
}
if (backedUpCount > 0)
{
ug.HasSaveData = true;
AppendLog($"[セーブバックアップ完了] {ug.Title}: {backedUpCount} 個の項目を保存しました。(保存先: {backupDir})");
MessageBox.Show($"セーブデータのバックアップが完了しました!({backedUpCount} 個のファイル/レジストリ)\n\n保存先:\n{backupDir}",
"バックアップ完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
AppendLog($"[セーブバックアップ警告] {ug.Title}: バックアップ対象が見つかりませんでした。");
MessageBox.Show("バックアップ対象のセーブデータ(レジストリまたはファイル)が見つかりませんでした。",
"バックアップ確認", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
catch (Exception ex)
{
AppendLog($"[セーブバックアップ失敗] {ex.Message}");
MessageBox.Show($"バックアップ中にエラーが発生しました:\n{ex.Message}", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
#endregion
#region WOLF RPGエディター専用アクション
private void btnOpenWolfSaveEditor_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is TkoolGameItem tg && tg.IsWolf)
{
var dialog = new WolfSaveEditorDialog(tg, _wolfSaveService)
{
Owner = this
};
dialog.ShowDialog();
}
}
private void chkWolfProxyDll_Checked(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is TkoolGameItem tg && tg.IsWolf)
{
var (success, msg) = _wolfModService.ApplyProxyDll(tg, 1.0, tg.WolfSpeedMultiplier > 0 ? tg.WolfSpeedMultiplier : 3.0, 5.0);
AppendLog($"[ウディタ プロキシDLL] {msg.Replace("\n", " ")}");
_scannerService.SaveCache(_games);
}
}
private void chkWolfProxyDll_Unchecked(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is TkoolGameItem tg && tg.IsWolf)
{
var (success, msg) = _wolfModService.RemoveProxyDll(tg);
AppendLog($"[ウディタ プロキシDLL] {msg}");
_scannerService.SaveCache(_games);
}
}
private void btnApplyWolfProxyDll_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is TkoolGameItem tg && tg.IsWolf)
{
var (success, msg) = _wolfModService.ApplyProxyDll(tg, 1.0, tg.WolfSpeedMultiplier > 0 ? tg.WolfSpeedMultiplier : 3.0, 5.0);
tg.WolfProxyDll = true;
AppendLog($"[ウディタ プロキシDLL] {msg.Replace("\n", " ")}");
MessageBox.Show(msg, "プロキシDLL適用", MessageBoxButton.OK, MessageBoxImage.Information);
_scannerService.SaveCache(_games);
}
}
private void btnRemoveWolfProxyDll_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is TkoolGameItem tg && tg.IsWolf)
{
var (success, msg) = _wolfModService.RemoveProxyDll(tg);
tg.WolfProxyDll = false;
AppendLog($"[ウディタ プロキシDLL] {msg}");
MessageBox.Show(msg, "プロキシDLL解除", MessageBoxButton.OK, MessageBoxImage.Information);
_scannerService.SaveCache(_games);
}
}
private async void btnExtractWolf_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsWolf) return;
var confirm = MessageBox.Show(
$"Data.wolf アーカイブを解凍・抽出しますか?\n\n対象: {tg.Title}\n展開先: {Path.Combine(tg.RootDirectory, "Data")}\n\n解凍すると、ウディタのエディタやファイル直接編集によるデータ改造が可能になります。",
"Data.wolf 解凍の確認", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (confirm != MessageBoxResult.Yes) return;
pbWolfProgress.Visibility = Visibility.Visible;
pbWolfProgress.IsIndeterminate = true;
lblWolfProgressStatus.Visibility = Visibility.Visible;
lblWolfProgressStatus.Text = "Data.wolf を解凍しています...";
btnExtractWolf.IsEnabled = false;
var progress = new Progress<string>(status =>
{
Dispatcher.Invoke(() =>
{
lblWolfProgressStatus.Text = status;
AppendLog($"[ウディタ解凍] {status}");
});
});
try
{
var (success, msg) = await _wolfArchiveService.ExtractArchiveAsync(tg, _config.WolfExtractorPath, progress);
if (success)
{
tg.IsWolfExtracted = true;
MessageBox.Show(msg, "解凍完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
MessageBox.Show(msg, "解凍エラー", MessageBoxButton.OK, MessageBoxImage.Warning);
}
_scannerService.SaveCache(_games);
}
finally
{
pbWolfProgress.Visibility = Visibility.Collapsed;
lblWolfProgressStatus.Visibility = Visibility.Collapsed;
btnExtractWolf.IsEnabled = true;
}
}
private void btnRestoreWolfArchive_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsWolf) return;
var confirm = MessageBox.Show(
"解凍された Data フォルダを Backups フォルダへ退避し、元の Data.wolf アーカイブ優先読み込みに復元しますか?",
"アーカイブ状態復元の確認", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (confirm != MessageBoxResult.Yes) return;
var (success, msg) = _wolfArchiveService.RestoreArchiveState(tg);
if (success)
{
tg.IsWolfExtracted = false;
AppendLog($"[ウディタ復元] {tg.Title}: {msg.Replace("\n", " ")}");
MessageBox.Show(msg, "復元完了", MessageBoxButton.OK, MessageBoxImage.Information);
_scannerService.SaveCache(_games);
}
else
{
MessageBox.Show(msg, "復元エラー", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
private void btnRestoreWolfAll_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsWolf) return;
var confirm = MessageBox.Show(
$"【完全復元】\n{tg.Title} に対するすべての改造(プロキシDLL、パッチ等)を解除し、元の状態に戻しますか?\n※セーブデータはそのまま維持されます。",
"完全復元の確認", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (confirm != MessageBoxResult.Yes) return;
var (success, msg) = _wolfModService.RestoreAllMods(tg);
tg.WolfProxyDll = false;
AppendLog($"[ウディタ完全復元] {tg.Title}:\n{msg}");
MessageBox.Show($"すべての改造を解除しました:\n\n{msg}", "復元完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
#endregion
#region SRPG Studio関連イベント
private void chkSrpgProxyDll_Checked(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsSrpgStudio) return;
tg.SrpgProxyDll = true;
bool ok = _srpgModService.EnableProxyDll(tg.RootDirectory, tg.SrpgSpeedMultiplier > 0 ? tg.SrpgSpeedMultiplier : 3.0);
if (ok)
{
AppendLog($"[SRPG Studio 倍速] {tg.Title}: プロキシDLLを有効化しました (F6で倍速切替)");
}
_scannerService.SaveCache(_games);
}
private void chkSrpgProxyDll_Unchecked(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsSrpgStudio) return;
tg.SrpgProxyDll = false;
_srpgModService.DisableProxyDll(tg.RootDirectory);
AppendLog($"[SRPG Studio 倍速] {tg.Title}: プロキシDLLを解除しました");
_scannerService.SaveCache(_games);
}
private void btnApplySrpgProxyDll_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsSrpgStudio) return;
tg.SrpgProxyDll = true;
bool ok = _srpgModService.EnableProxyDll(tg.RootDirectory, tg.SrpgSpeedMultiplier > 0 ? tg.SrpgSpeedMultiplier : 3.0);
if (ok)
{
AppendLog($"[SRPG Studio 倍速] {tg.Title}: プロキシDLL (version.dll) を配置しました");
MessageBox.Show("プロキシDLL (version.dll) を配置しました。\nゲーム起動後、[F6] キーで倍速切替、[Ctrl] キー押し続けで早送りができます。", "プロキシDLL配置完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
MessageBox.Show("プロキシDLLの配置に失敗しました。\nEngines/Rgss/Tools/speedhack-i686/version.dll が存在するか確認してください。", "エラー", MessageBoxButton.OK, MessageBoxImage.Warning);
}
_scannerService.SaveCache(_games);
}
private void btnRemoveSrpgProxyDll_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsSrpgStudio) return;
tg.SrpgProxyDll = false;
bool ok = _srpgModService.DisableProxyDll(tg.RootDirectory);
AppendLog($"[SRPG Studio 倍速] {tg.Title}: プロキシDLL (version.dll) を解除しました");
MessageBox.Show("プロキシDLL (version.dll) を解除しました。", "プロキシDLL解除完了", MessageBoxButton.OK, MessageBoxImage.Information);
_scannerService.SaveCache(_games);
}
private async void btnApplySrpgMod_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsSrpgStudio) return;
var enabledMods = tg.SrpgModOptions.Where(m => m.IsEnabled).ToList();
if (enabledMods.Count == 0)
{
MessageBox.Show("適用する改造項目にチェックを入れてください。", "改造項目の選択", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
var confirm = MessageBox.Show(
$"選択された {enabledMods.Count} 件の改造項目を適用し、data.dts を再構築しますか?\n(元の data.dts は Backups フォルダに自動保存されます)\n\n対象: {tg.Title}",
"改造プラグイン適用&再構築の確認", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (confirm != MessageBoxResult.Yes) return;
pbSrpgProgress.Visibility = Visibility.Visible;
pbSrpgProgress.IsIndeterminate = true;
lblSrpgProgressStatus.Visibility = Visibility.Visible;
lblSrpgProgressStatus.Text = "改造プラグインを適用・再パック中...";
btnApplySrpgMod.IsEnabled = false;
var progress = new Progress<string>(status =>
{
Dispatcher.Invoke(() =>
{
lblSrpgProgressStatus.Text = status;
AppendLog($"[SRPG Studio 改造] {status}");
});
});
try
{
var (success, msg) = await _srpgModService.ApplyModAndRepackAsync(tg, progress);
if (success)
{
AppendLog($"[SRPG Studio 改造成功] {tg.Title}: {msg}");
MessageBox.Show(msg, "改造適用完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
AppendLog($"[SRPG Studio 改造失敗] {tg.Title}: {msg}");
MessageBox.Show(msg, "改造適用エラー", MessageBoxButton.OK, MessageBoxImage.Warning);
}
_scannerService.SaveCache(_games);
}
finally
{
pbSrpgProgress.Visibility = Visibility.Collapsed;
lblSrpgProgressStatus.Visibility = Visibility.Collapsed;
btnApplySrpgMod.IsEnabled = true;
}
}
private async void btnRemoveSrpgMod_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsSrpgStudio) return;
var confirm = MessageBox.Show(
$"改造プラグインを解除し、元のアーカイブへ復元しますか?\n\n対象: {tg.Title}",
"改造プラグイン解除の確認", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (confirm != MessageBoxResult.Yes) return;
pbSrpgProgress.Visibility = Visibility.Visible;
pbSrpgProgress.IsIndeterminate = true;
lblSrpgProgressStatus.Visibility = Visibility.Visible;
lblSrpgProgressStatus.Text = "改造プラグインを解除中...";
btnRemoveSrpgMod.IsEnabled = false;
var progress = new Progress<string>(status =>
{
Dispatcher.Invoke(() =>
{
lblSrpgProgressStatus.Text = status;
AppendLog($"[SRPG Studio 解除] {status}");
});
});
try
{
var (success, msg) = await _srpgModService.RemoveModAndRepackAsync(tg, progress);
if (success)
{
// チェックをすべてオフにする
foreach (var mod in tg.SrpgModOptions) mod.IsEnabled = false;
AppendLog($"[SRPG Studio 解除成功] {tg.Title}: {msg}");
MessageBox.Show(msg, "改造解除完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
AppendLog($"[SRPG Studio 解除失敗] {tg.Title}: {msg}");
MessageBox.Show(msg, "改造解除エラー", MessageBoxButton.OK, MessageBoxImage.Warning);
}
_scannerService.SaveCache(_games);
}
finally
{
pbSrpgProgress.Visibility = Visibility.Collapsed;
lblSrpgProgressStatus.Visibility = Visibility.Collapsed;
btnRemoveSrpgMod.IsEnabled = true;
}
}
private async void btnUnpackSrpg_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsSrpgStudio) return;
var confirm = MessageBox.Show(
$"data.dts アーカイブを解凍・抽出しますか?\n\n対象: {tg.Title}\n展開先: {Path.Combine(tg.RootDirectory, SrpgArchiveService.ExtractedDirName)}\n\n解凍すると、ゲーム内のスクリプト (Script) やプラグイン (Plugin) を自由に編集できるようになります。",
"data.dts 解凍の確認", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (confirm != MessageBoxResult.Yes) return;
pbSrpgProgress.Visibility = Visibility.Visible;
pbSrpgProgress.IsIndeterminate = true;
lblSrpgProgressStatus.Visibility = Visibility.Visible;
lblSrpgProgressStatus.Text = "data.dts を解凍しています...";
btnUnpackSrpg.IsEnabled = false;
var progress = new Progress<string>(status =>
{
Dispatcher.Invoke(() =>
{
lblSrpgProgressStatus.Text = status;
AppendLog($"[SRPG Studio 解凍] {status}");
});
});
try
{
var (success, msg) = await _srpgArchiveService.UnpackDataDtsAsync(tg.RootDirectory, progress);
if (success)
{
tg.IsSrpgExtracted = true;
AppendLog($"[SRPG Studio 解凍成功] {tg.Title}: {msg.Replace("\n", " ")}");
MessageBox.Show(msg, "解凍完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
AppendLog($"[SRPG Studio 解凍失敗] {tg.Title}: {msg}");
MessageBox.Show(msg, "解凍エラー", MessageBoxButton.OK, MessageBoxImage.Warning);
}
_scannerService.SaveCache(_games);
}
finally
{
pbSrpgProgress.Visibility = Visibility.Collapsed;
lblSrpgProgressStatus.Visibility = Visibility.Collapsed;
btnUnpackSrpg.IsEnabled = true;
}
}
private async void btnRepackSrpg_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsSrpgStudio) return;
var confirm = MessageBox.Show(
$"解凍フォルダの内容から data.dts を再構築(再パック)しますか?\n(現在の data.dts は Backups フォルダに自動保存されます)\n\n対象: {tg.Title}",
"data.dts 再構築の確認", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (confirm != MessageBoxResult.Yes) return;
pbSrpgProgress.Visibility = Visibility.Visible;
pbSrpgProgress.IsIndeterminate = true;
lblSrpgProgressStatus.Visibility = Visibility.Visible;
lblSrpgProgressStatus.Text = "data.dts を再構築中...";
btnRepackSrpg.IsEnabled = false;
var progress = new Progress<string>(status =>
{
Dispatcher.Invoke(() =>
{
lblSrpgProgressStatus.Text = status;
AppendLog($"[SRPG Studio 再構築] {status}");
});
});
try
{
var (success, msg) = await _srpgArchiveService.RepackDataDtsAsync(tg.RootDirectory, progress);
if (success)
{
AppendLog($"[SRPG Studio 再構築成功] {tg.Title}: {msg.Replace("\n", " ")}");
MessageBox.Show(msg, "再構築完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
AppendLog($"[SRPG Studio 再構築失敗] {tg.Title}: {msg}");
MessageBox.Show(msg, "再構築エラー", MessageBoxButton.OK, MessageBoxImage.Warning);
}
_scannerService.SaveCache(_games);
}
finally
{
pbSrpgProgress.Visibility = Visibility.Collapsed;
lblSrpgProgressStatus.Visibility = Visibility.Collapsed;
btnRepackSrpg.IsEnabled = true;
}
}
private async void btnRestoreSrpgAll_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsSrpgStudio) return;
var confirm = MessageBox.Show(
$"【完全復元】\n{tg.Title} に対するすべての改造(プロキシDLL・Modプラグイン・解凍フォルダ退避等)を解除し、元の安全な状態に戻しますか?\n※セーブデータはそのまま維持されます。\n※解凍データは Backups フォルダに安全退避されます。",
"完全復元の確認", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (confirm != MessageBoxResult.Yes) return;
pbSrpgProgress.Visibility = Visibility.Visible;
pbSrpgProgress.IsIndeterminate = true;
lblSrpgProgressStatus.Visibility = Visibility.Visible;
lblSrpgProgressStatus.Text = "すべての改造を解除中...";
var progress = new Progress<string>(status =>
{
Dispatcher.Invoke(() =>
{
lblSrpgProgressStatus.Text = status;
AppendLog($"[SRPG Studio 完全復元] {status}");
});
});
try
{
var (success, msg) = await _srpgModService.RestoreAllModsAsync(tg, progress);
foreach (var mod in tg.SrpgModOptions) mod.IsEnabled = false;
AppendLog($"[SRPG Studio 完全復元] {tg.Title}:\n{msg}");
MessageBox.Show($"すべての改造を解除しました:\n\n{msg}", "復元完了", MessageBoxButton.OK, MessageBoxImage.Information);
_scannerService.SaveCache(_games);
}
finally
{
pbSrpgProgress.Visibility = Visibility.Collapsed;
lblSrpgProgressStatus.Visibility = Visibility.Collapsed;
}
}
#endregion
#region 共通アクション (フォルダを開く・ログ操作)
private void btnOpenFolder_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is GameItemBase game && Directory.Exists(game.RootDirectory))
{
Process.Start(new ProcessStartInfo { FileName = game.RootDirectory, UseShellExecute = true });
}
}
private void MenuOpenFolder_Click(object sender, RoutedEventArgs e)
{
if (lstGames.SelectedItem is GameItemBase game && Directory.Exists(game.RootDirectory))
{
Process.Start(new ProcessStartInfo { FileName = game.RootDirectory, UseShellExecute = true });
}
}
private void AppendLog(string message)
{
Dispatcher.Invoke(() =>
{
string timestamp = DateTime.Now.ToString("HH:mm:ss");
txtLog.AppendText($"[{timestamp}] {message}\n");
scrollLog.ScrollToEnd();
});
}
private void btnClearLog_Click(object sender, RoutedEventArgs e)
{
txtLog.Clear();
}
#endregion
}
}