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; 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; using GameLauncher.Engines.Common; using GameLauncher.Engines.Evb; namespace GameLauncher { /// /// メインウィンドウの相互作用ロジック /// 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 WindowResizeService _windowResizeService = new(); private readonly TkoolResourceRepairService _tkoolResourceRepairService = new(); /// 直近に起動したゲームプロセス(起動後の外部連携処理で使用) private Process? _lastStartedProcess; private readonly ObservableCollection _games = []; private readonly ListCollectionView _gamesView = null!; private readonly GameItemComparer _gameComparer = new() { SortOrder = GameSortOrder.LastLaunchedDesc }; private readonly HashSet _scannedPaths = new(StringComparer.OrdinalIgnoreCase); private CancellationTokenSource? _scanCts; private int _scannedCountSinceLastSave; private readonly string _configFilePath; private LauncherConfig _config = new(); private readonly bool _isInitialized; private readonly System.Collections.Concurrent.ConcurrentQueue _logQueue = new(); private readonly System.Windows.Threading.DispatcherTimer? _logFlushTimer; public MainWindow() { this.InitializeComponent(); this._configFilePath = Path.Combine(AppPathHelper.GetExeDirectory(), "config.json"); this._gamesView = (ListCollectionView)CollectionViewSource.GetDefaultView(this._games); this._gamesView.Filter = this.FilterGameItem; this._gamesView.CustomSort = this._gameComparer; this.lstGames.ItemsSource = this._gamesView; // 初期ソート順 this.ApplySortOrderToComboBox(GameSortOrder.LastLaunchedDesc); // 保存された設定の読み込み this.LoadConfig(); this._isInitialized = true; // ログの非同期バッファリング更新タイマー(100ms周期で一括フラッシュしUI負荷をゼロ化) this._logFlushTimer = new System.Windows.Threading.DispatcherTimer { Interval = TimeSpan.FromMilliseconds(100) }; this._logFlushTimer.Tick += (s, e) => this.FlushLogQueue(); this._logFlushTimer.Start(); // ウィンドウ描画後に初期処理(即時一覧作成&裏での更新監視)を開始 ContentRendered += this.MainWindow_ContentRendered; Closing += this.MainWindow_Closing; } #region 設定のロード & セーブ private void btnOpenConfig_Click(object sender, RoutedEventArgs e) { var dialog = new ConfigDialog(this._config) { Owner = this }; if (dialog.ShowDialog() == true) { this.SaveConfig(); this.AppendLog($"[設定変更] 設定を保存しました。(RGSS Extractor: {this._config.RgssExtractorPath})"); } } private void LoadConfig() { try { if (File.Exists(this._configFilePath)) { string json = File.ReadAllText(this._configFilePath); var config = JsonSerializer.Deserialize(json); if (config != null) { this._config = config; this._gameComparer.SortOrder = this._config.SortOrder; this.ApplySortOrderToComboBox(this._config.SortOrder); // フィルター設定の復元 this.RestoreFilterSettings(); } } } catch { } this.SyncDefaultPluginSettingsWithAvailablePlugins(); } private void RestoreFilterSettings() { switch (this._config.SelectedTab) { case 1: this.tabMV.IsChecked = true; break; case 2: this.tabMZ.IsChecked = true; break; case 3: this.tabVXAce.IsChecked = true; break; case 4: this.tabVX.IsChecked = true; break; case 5: this.tabTyrano.IsChecked = true; break; case 6: this.tabUnity.IsChecked = true; break; case 7: this.tabWolf.IsChecked = true; break; case 8: this.tabSrpg.IsChecked = true; break; case 9: this.tabNwjs.IsChecked = true; break; case 10: this.tabOther.IsChecked = true; break; default: this.tabAll.IsChecked = true; break; } this.pnlUnityBackendFilter?.Visibility = this.tabUnity.IsChecked == true ? Visibility.Visible : Visibility.Collapsed; // Unityフィルター if (this._config.UnityBackendFilter == "IL2CPP") this.rbUnityIL2CPP.IsChecked = true; else if (this._config.UnityBackendFilter == "Mono") this.rbUnityMono.IsChecked = true; else this.rbUnityAll.IsChecked = true; this.chkFilterModdedOnly.IsChecked = this._config.TkoolFilterModdedOnly; this.chkFilterAsarOnly.IsChecked = this._config.TkoolFilterAsarOnly; this.chkFilterRgssOnly.IsChecked = this._config.TkoolFilterRgssOnly; this.chkFilterSaveOnly.IsChecked = this._config.UnityFilterSaveOnly; this.chkFilterBookmarkedOnly.IsChecked = this._config.FilterBookmarkedOnly; } private void SaveConfig() { if (!this._isInitialized) return; try { this._config.SortOrder = this._gameComparer.SortOrder; int tabIndex = 0; if (this.tabMV.IsChecked == true) tabIndex = 1; else if (this.tabMZ.IsChecked == true) tabIndex = 2; else if (this.tabVXAce.IsChecked == true) tabIndex = 3; else if (this.tabVX.IsChecked == true) tabIndex = 4; else if (this.tabTyrano.IsChecked == true) tabIndex = 5; else if (this.tabUnity.IsChecked == true) tabIndex = 6; else if (this.tabWolf.IsChecked == true) tabIndex = 7; else if (this.tabSrpg.IsChecked == true) tabIndex = 8; else if (this.tabNwjs.IsChecked == true) tabIndex = 9; else if (this.tabOther.IsChecked == true) tabIndex = 10; this._config.SelectedTab = tabIndex; this._config.UnityBackendFilter = this.rbUnityIL2CPP.IsChecked == true ? "IL2CPP" : (this.rbUnityMono.IsChecked == true ? "Mono" : "All"); this._config.TkoolFilterModdedOnly = this.chkFilterModdedOnly.IsChecked == true; this._config.TkoolFilterAsarOnly = this.chkFilterAsarOnly.IsChecked == true; this._config.TkoolFilterRgssOnly = this.chkFilterRgssOnly.IsChecked == true; this._config.UnityFilterSaveOnly = this.chkFilterSaveOnly.IsChecked == true; this._config.FilterBookmarkedOnly = this.chkFilterBookmarkedOnly.IsChecked == true; var options = new JsonSerializerOptions { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; string json = JsonSerializer.Serialize(this._config, options); File.WriteAllText(this._configFilePath, json); } catch { } } private void SyncDefaultPluginSettingsWithAvailablePlugins() { try { bool modified = false; if (this._modService.AvailablePlugins.Count == 0) { this._modService.LoadAvailablePlugins(); } foreach (var plugin in this._modService.AvailablePlugins) { if (!this._config.DefaultPluginSettings.ContainsKey(plugin.Id)) { this._config.DefaultPluginSettings[plugin.Id] = plugin.DefaultEnabled; modified = true; } } // 削除対象の旧Modプラグイン設定を除去 if (this._config.DefaultPluginSettings.Remove("GameLauncher_Mod")) { modified = true; } if (this._config.DefaultPluginSettings.Remove("GameLauncher_StandaloneMod")) { modified = true; } foreach (var tyranoPlugin in TkoolGameItem.DefaultTyranoPlugins) { if (!this._config.DefaultPluginSettings.ContainsKey(tyranoPlugin.Id)) { this._config.DefaultPluginSettings[tyranoPlugin.Id] = tyranoPlugin.DefaultEnabled; modified = true; } } foreach (var rgssPlugin in TkoolGameItem.DefaultRgssPlugins) { if (!this._config.DefaultPluginSettings.ContainsKey(rgssPlugin.Id)) { this._config.DefaultPluginSettings[rgssPlugin.Id] = rgssPlugin.DefaultEnabled; modified = true; } } if (modified || !File.Exists(this._configFilePath)) { this.SaveConfig(); } } catch { } } private void ApplySortOrderToComboBox(GameSortOrder order) { foreach (ComboBoxItem item in this.cmbSortOrder.Items) { if (item.Tag is string tag && Enum.TryParse(tag, out var parsed) && parsed == order) { this.cmbSortOrder.SelectedItem = item; break; } } } #endregion #region ウィンドウ起動 & スキャンパイプライン private async void MainWindow_ContentRendered(object? sender, EventArgs e) { ContentRendered -= this.MainWindow_ContentRendered; this.AppendLog("統合ゲームランチャー (Game Launcher) を起動しました。"); // 0. ツクール改造プラグインの動的検出 this._modService.LoadAvailablePlugins(); this.AppendLog($"ツクールプラグインフォルダから {this._modService.AvailablePlugins.Count} 件のプラグインを認識しました。"); // 1. キャッシュから全ゲームを瞬時にロードし、0秒で一覧に表示 var cached = this._scannerService.LoadCachedGamesFast(); foreach (var item in cached) { if (item is TkoolGameItem tg) { tg.SetDefaultApplyMod(this._config.DefaultApplyMod); } this._games.Add(item); this._scannedPaths.Add(item.RootDirectory); } this._gamesView.Refresh(); this.UpdateStatusLabels(); if (this._games.Count > 0) { int tkoolCount = this._games.Count(g => g is TkoolGameItem tg && tg.EngineType != TkoolEngineType.Tyrano && !tg.IsRgss && !tg.IsWolf && !tg.IsSrpgStudio && !tg.IsNwjs); int rgssCount = this._games.Count(g => g is TkoolGameItem tg && tg.IsRgss); int tyranoCount = this._games.Count(g => g is TkoolGameItem tg && tg.EngineType == TkoolEngineType.Tyrano); int wolfCount = this._games.Count(g => g is TkoolGameItem tg && tg.IsWolf); int srpgCount = this._games.Count(g => g is TkoolGameItem tg && tg.IsSrpgStudio); int nwjsCount = this._games.Count(g => g is TkoolGameItem tg && tg.IsNwjs); int unityCount = this._games.Count(g => g is UnityGameItem); this.AppendLog($"キャッシュから計 {this._games.Count} 件(ツクールMV/MZ: {tkoolCount}, ツクールVX系: {rgssCount}, ティラノ: {tyranoCount}, ウディタ: {wolfCount}, SRPG Studio: {srpgCount}, NW.js: {nwjsCount}, Unity: {unityCount})を即時表示しました。(待たずに即起動可能です)"); this.lblStatusEngine.Text = "裏で更新・実在検証を実行中..."; } else { this.AppendLog("キャッシュは見つかりませんでした。初回フルスキャンを実行します。"); this.lblStatusEngine.Text = "初回スキャンを実行中..."; } // 2. 裏で実在検証・差分スキャンを実行 await this.RunVerificationAndScanAsync(); } private async Task RunVerificationAndScanAsync() { this._scanCts?.Cancel(); this._scanCts = new CancellationTokenSource(); var ct = this._scanCts.Token; try { this.lblLogActivity.Text = "● スキャン中..."; // 2-1. 実在検証 & アイコン・セーブ情報エンリッチ if (this._games.Count > 0) { await this._scannerService.VerifyAndEnrichGamesAsync( [.. this._games], onGameUpdated: game => { this.Dispatcher.Invoke(() => { if (this.lstGames.SelectedItem == game) { this.UpdateSelectedPanel(game); } }); }, onGameRemoved: game => { this.Dispatcher.Invoke(() => { this._games.Remove(game); this._scannedPaths.Remove(game.RootDirectory); this.UpdateStatusLabels(); }); }, ct: ct); } // 2-2. 差分スキャン(新規フォルダの走査) var targetDirs = new List(GameScannerService.DefaultTargetDirectories); if (this._config.TargetDirectories != null) { targetDirs.AddRange(this._config.TargetDirectories); } var progress = new Progress(newGame => { this.Dispatcher.Invoke(() => { if (newGame is TkoolGameItem tg) { tg.SetDefaultApplyMod(this._config.DefaultApplyMod); tg.SyncPluginOptions(this._modService.AvailablePlugins, this._config.DefaultPluginSettings); } this._games.Add(newGame); this._scannedPaths.Add(newGame.RootDirectory); this.UpdateStatusLabels(); this._scannedCountSinceLastSave++; if (this._scannedCountSinceLastSave >= 5) { this._scannedCountSinceLastSave = 0; this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); } }); }); await this._scannerService.ScanDirectoriesAsync(targetDirs, progress, this._scannedPaths, ct); // キャッシュの最終同期(削除されたゲームのブックマークもここで除去する) this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); this.lblStatusEngine.Text = "準備完了"; this.lblLogActivity.Text = ""; this.AppendLog($"スキャンが完了しました。総ゲーム数: {this._games.Count} 件。"); } catch (OperationCanceledException) { this.lblStatusEngine.Text = "スキャン中断"; this.lblLogActivity.Text = ""; } catch (Exception ex) { this.lblStatusEngine.Text = "スキャンエラー"; this.lblLogActivity.Text = ""; this.AppendLog($"スキャン中にエラーが発生しました: {ex.Message}"); } } private async void btnRescan_Click(object sender, RoutedEventArgs e) { this.btnRescan.IsEnabled = false; this.AppendLog("手動再スキャンを開始します..."); this._scannedPaths.Clear(); foreach (var g in this._games) { this._scannedPaths.Add(g.RootDirectory); } await this.RunVerificationAndScanAsync(); this.btnRescan.IsEnabled = true; } private void MainWindow_Closing(object? sender, CancelEventArgs e) { this._scanCts?.Cancel(); this.SaveConfig(); this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); } #endregion #region フィルタリング & ソート private bool FilterGameItem(object item) { if (item is not GameItemBase game) return false; // 1. テキスト検索 string query = this.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 (this.tabMV.IsChecked == true) { if (game is not TkoolGameItem tg || tg.EngineType != TkoolEngineType.MV) return false; } else if (this.tabMZ.IsChecked == true) { if (game is not TkoolGameItem tg || tg.EngineType != TkoolEngineType.MZ) return false; } else if (this.tabVXAce.IsChecked == true) { if (game is not TkoolGameItem tg || tg.EngineType != TkoolEngineType.VXAce) return false; } else if (this.tabVX.IsChecked == true) { if (game is not TkoolGameItem tg || tg.EngineType != TkoolEngineType.VX) return false; } else if (this.tabTyrano.IsChecked == true) { if (game is not TkoolGameItem tg || tg.EngineType != TkoolEngineType.Tyrano) return false; } else if (this.tabWolf.IsChecked == true) { if (game is not TkoolGameItem tg || tg.EngineType != TkoolEngineType.Wolf) return false; } else if (this.tabSrpg.IsChecked == true) { if (game is not TkoolGameItem tg || tg.EngineType != TkoolEngineType.SrpgStudio) return false; } else if (this.tabUnity.IsChecked == true) { if (game is not UnityGameItem ug) return false; if (this.rbUnityIL2CPP.IsChecked == true && ug.BackendType != UnityBackendType.IL2CPP) return false; if (this.rbUnityMono.IsChecked == true && ug.BackendType != UnityBackendType.Mono) return false; } else if (this.tabNwjs.IsChecked == true) { if (game is not TkoolGameItem tg || tg.EngineType != TkoolEngineType.Nwjs) return false; } else if (this.tabOther.IsChecked == true) { if (!game.IsOther) return false; } // 3. 追加属性フィルター(全タブ共通) if (this.chkFilterBookmarkedOnly.IsChecked == true && !game.IsBookmarked) return false; if (this.chkFilterModdedOnly.IsChecked == true && !game.IsModded) return false; if (this.chkFilterAsarOnly.IsChecked == true && (game is not TkoolGameItem tgAsar || !tgAsar.IsAsar)) return false; if (this.chkFilterRgssOnly.IsChecked == true && (game is not TkoolGameItem tgRgss || !tgRgss.HasRgssArchive)) return false; if (this.chkFilterSrpgOnly.IsChecked == true && (game is not TkoolGameItem tgSrpg || !tgSrpg.HasSrpgArchive)) return false; if (this.chkFilterSaveOnly.IsChecked == true && (game is not UnityGameItem ugSave || !ugSave.HasSaveData)) return false; return true; } private void EngineTab_Checked(object sender, RoutedEventArgs e) { if (!this._isInitialized) return; this.pnlUnityBackendFilter?.Visibility = this.tabUnity.IsChecked == true ? Visibility.Visible : Visibility.Collapsed; this._gamesView?.Refresh(); this.UpdateStatusLabels(); this.SaveConfig(); } private void FilterChanged(object sender, RoutedEventArgs e) { if (!this._isInitialized) return; this._gamesView?.Refresh(); this.UpdateStatusLabels(); this.SaveConfig(); } private void txtSearch_TextChanged(object sender, TextChangedEventArgs e) { if (!this._isInitialized) return; this._gamesView?.Refresh(); this.UpdateStatusLabels(); } private void btnClearSearch_Click(object sender, RoutedEventArgs e) { this.txtSearch.Text = string.Empty; } private void cmbSortOrder_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (!this._isInitialized) return; if (this.cmbSortOrder.SelectedItem is ComboBoxItem item && item.Tag is string tag && Enum.TryParse(tag, out var order)) { this._gameComparer.SortOrder = order; this._gamesView?.Refresh(); this.SaveConfig(); } } private void UpdateStatusLabels() { if (this.lblStatusSummary == null || this.lblStatusBreakdown == null) return; int total = this._games.Count; int visible = this._gamesView?.Count ?? 0; int tkoolCount = this._games.Count(g => g is TkoolGameItem tg && tg.EngineType != TkoolEngineType.Tyrano && !tg.IsRgss && !tg.IsWolf && !tg.IsSrpgStudio && !tg.IsNwjs && !tg.IsOther); int rgssCount = this._games.Count(g => g is TkoolGameItem tg && tg.IsRgss); int tyranoCount = this._games.Count(g => g is TkoolGameItem tg && tg.EngineType == TkoolEngineType.Tyrano); int wolfCount = this._games.Count(g => g is TkoolGameItem tg && tg.IsWolf); int srpgCount = this._games.Count(g => g is TkoolGameItem tg && tg.IsSrpgStudio); int nwjsCount = this._games.Count(g => g is TkoolGameItem tg && tg.IsNwjs); int unityCount = this._games.Count(g => g is UnityGameItem); int otherCount = this._games.Count(g => g.IsOther); int bookmarkCount = this._games.Count(g => g.IsBookmarked); this.lblStatusSummary.Text = $"総ゲーム数: {total} 件 | 表示: {visible} 件 | ★ ブックマーク: {bookmarkCount} 件"; this.lblStatusBreakdown.Text = $"(ツクールMV/MZ: {tkoolCount}, ツクールVX系: {rgssCount}, ティラノ: {tyranoCount}, ウディタ: {wolfCount}, SRPG Studio: {srpgCount}, NW.js: {nwjsCount}, Unity: {unityCount}, その他: {otherCount})"; } #endregion #region 詳細パネル & 選択制御 private void lstGames_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (this.lstGames.SelectedItem is not GameItemBase selected) { this.pnlNoSelection.Visibility = Visibility.Visible; this.pnlSelectedContent.Visibility = Visibility.Collapsed; return; } this.pnlNoSelection.Visibility = Visibility.Collapsed; this.pnlSelectedContent.Visibility = Visibility.Visible; this.UpdateSelectedPanel(selected); } private void UpdateSelectedPanel(GameItemBase game) { if (game is TkoolGameItem tg) { this.pnlTkoolDetails.Visibility = Visibility.Visible; this.pnlUnityDetails.Visibility = Visibility.Collapsed; // プラグイン設定の同期(未初期化の場合) if (tg.PluginOptions.Count == 0) { tg.SyncPluginOptions(this._modService.AvailablePlugins, this._config.DefaultPluginSettings); } } else if (game is UnityGameItem) { this.pnlTkoolDetails.Visibility = Visibility.Collapsed; this.pnlUnityDetails.Visibility = Visibility.Visible; } } private async void lstGames_MouseDoubleClick(object sender, MouseButtonEventArgs e) { if (this.lstGames.SelectedItem is GameItemBase game) { await this.LaunchGameAsync(game); } } #endregion #region ゲーム起動 private async void btnLaunchGame_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is GameItemBase game) { await this.LaunchGameAsync(game); } } private async void MenuLaunch_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is GameItemBase game) { await this.LaunchGameAsync(game); } } private async Task LaunchGameAsync(GameItemBase game) { // EVB 解凍済みゲームは、保存済みパスが空でも解凍後の exe を解決して起動対象にする。 // 実効パス(解決後)で存在判定を行い、非 EVB ゲームの挙動は変えない。 var effectiveExe = game is TkoolGameItem tkoolItem ? tkoolItem.ResolveLaunchExecutable() : game.ExecutablePath; // 直下にexeが無い場合やパスが変わっていた場合はサブフォルダ内を再探索して救済 if (string.IsNullOrEmpty(effectiveExe) || !File.Exists(effectiveExe)) { var foundExe = GameScannerService.FindGameExecutable(game.RootDirectory); if (!string.IsNullOrEmpty(foundExe) && File.Exists(foundExe)) { effectiveExe = foundExe; game.ExecutablePath = foundExe; } } if (string.IsNullOrEmpty(effectiveExe) || !File.Exists(effectiveExe)) { MessageBox.Show($"実行ファイルが見つかりません:\n{effectiveExe}", "起動エラー", MessageBoxButton.OK, MessageBoxImage.Warning); this.AppendLog($"[起動失敗] 実行ファイルが見つかりません: {effectiveExe}"); return; } try { if (game is TkoolGameItem tg) { await this.LaunchTkoolGameAsync(tg); } else if (game is UnityGameItem ug) { this.LaunchUnityGame(ug); } else { this.StartGameProcess(game); } } catch (Exception ex) { MessageBox.Show($"ゲーム起動中にエラーが発生しました:\n{ex.Message}", "起動エラー", MessageBoxButton.OK, MessageBoxImage.Error); this.AppendLog($"[起動エラー] {game.Title}: {ex.Message}"); } } private async Task LaunchTkoolGameAsync(TkoolGameItem tg) { // ウディタゲームの場合の起動処理 if (tg.IsWolf) { // プロキシDLLの適用または解除の同期 if (tg.WolfProxyDll) { var (pSuccess, pMsg) = this._wolfModService.ApplyProxyDll(tg, 1.0, tg.WolfSpeedMultiplier > 0 ? tg.WolfSpeedMultiplier : 3.0, 5.0); this.AppendLog($"[ウディタ プロキシDLL] {pMsg.Replace("\n", " ")}"); } else if (this._wolfModService.IsProxyDllInstalled(tg)) { var (pSuccess, pMsg) = this._wolfModService.RemoveProxyDll(tg); this.AppendLog($"[ウディタ プロキシDLL] {pMsg}"); } this.AppendLog($"[ウディタ起動] {tg.Title} を起動します..."); this.StartGameProcess(tg); return; } // SRPG Studioゲームの場合の起動処理 if (tg.IsSrpgStudio) { // プロキシDLLの適用または解除の同期 if (tg.SrpgProxyDll) { bool ok = this._srpgModService.EnableProxyDll(tg.RootDirectory, tg.SrpgSpeedMultiplier > 0 ? tg.SrpgSpeedMultiplier : 3.0); this.AppendLog($"[SRPG Studio プロキシDLL] 倍速プロキシDLLを配置しました (倍率: {(tg.SrpgSpeedMultiplier > 0 ? tg.SrpgSpeedMultiplier : 3.0):F1}x)"); } else if (SrpgModService.IsProxyDllEnabled(tg.RootDirectory)) { this._srpgModService.DisableProxyDll(tg.RootDirectory); this.AppendLog("[SRPG Studio プロキシDLL] プロキシDLLを解除しました"); } this.AppendLog($"[SRPG Studio起動] {tg.Title} を起動します..."); this.StartGameProcess(tg); return; } // 単体exe梱包ゲーム(FOSSIL / boxed)の場合の起動処理(起動のみ対応)。 // EVB 解凍済みなら解凍後の exe を起動対象に切り替えます。 if (tg.IsStandaloneExePackage) { this.AppendLog($"[単体exe起動] {tg.Title}: 起動のみ対応(埋め込み展開機能は廃止)。"); this.StartGameProcess(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 this.ExtractAsarForGame(tg, autoLaunchAfter: true); return; } else if (ask == MessageBoxResult.Cancel) { return; } } // RGSSゲーム(ツクールVX / VX Ace)の場合 if (tg.IsRgss) { var (success, msg) = await this._rgssModService.ApplyOrRestoreModAsync(tg, tg.PluginSettings, this._config.RgssExtractorPath); this.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) = this._tyranoModService.ApplyMod(tg, tg.PluginSettings); this.AppendLog($"[ティラノ改造] {tg.Title}: {msg}"); } else { var (success, msg) = this._tyranoModService.RestoreOriginal(tg); this.AppendLog($"[ティラノ復元] {tg.Title}: {msg}"); } } // その他のゲーム(ツクール以外のゲーム) else if (tg.IsOther) { this.AppendLog($"[その他起動] {tg.Title} を起動します..."); } // スクリプト改造の適用または復元(ツクールMV/MZ) else { var (success, msg) = this._modService.ApplyOrRestoreMod(tg, this._config.DefaultPluginSettings); this.AppendLog($"[ツクール改造処理] {tg.Title}: {msg}"); } this.StartGameProcess(tg); // RGSSゲーム(ツクールVX / VX Ace)で外部ツール方式のウィンドウ拡大がONの場合、起動後に拡大を適用 if (tg.IsRgss && tg.IsPluginEnabled("RgssWindowResizeExternal", tg.PluginSettings, false)) { var resizeProc = this._lastStartedProcess; if (resizeProc != null) { var (resizeOk, resizeMsg) = await this._windowResizeService.ApplyResizeAsync(resizeProc, this._config.WindowResizeToolPath); this.AppendLog($"[ウィンドウ拡大] {tg.Title}: {resizeMsg}"); } } } private void LaunchUnityGame(UnityGameItem ug) { this.AppendLog($"[Unity起動] {ug.Title} (Backend: {ug.BackendBadgeText}) を起動します..."); this.StartGameProcess(ug); } private void StartGameProcess(GameItemBase game) { // EVB 解凍済みのゲームは、解凍後の exe を起動対象に切り替えます // (元 exe は .glbak に退避済み。他ゲームには影響しません)。 var launchExe = game is TkoolGameItem evbItem ? evbItem.ResolveLaunchExecutable() : game.ExecutablePath; // 直下にexeが無い場合やパスが変わっていた場合はサブフォルダ内を探索して救済 if (string.IsNullOrEmpty(launchExe) || !File.Exists(launchExe)) { var foundExe = GameScannerService.FindGameExecutable(game.RootDirectory); if (!string.IsNullOrEmpty(foundExe) && File.Exists(foundExe)) { launchExe = foundExe; game.ExecutablePath = foundExe; } } if (game is TkoolGameItem && launchExe != game.ExecutablePath) { this.AppendLog($"[EVB起動] 解凍後の実行ファイルを使用: {Path.GetFileName(launchExe)}"); } var workingDir = Path.GetDirectoryName(launchExe) ?? game.RootDirectory; var startInfo = new ProcessStartInfo { FileName = launchExe, 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}\" --allow-file-access-from-files"; this.AppendLog($"[プロファイル] 専用プロファイルを指定: {Path.GetFileName(profileDir)}"); } catch (Exception pEx) { this.AppendLog($"[警告] 専用プロファイルの準備に失敗しました(通常引数で起動します): {pEx.Message}"); } } this._lastStartedProcess = Process.Start(startInfo); game.LastLaunched = DateTime.Now; this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); this.AppendLog($"🚀 {game.Title} を起動しました。"); } #endregion #region コンテキストメニュー制御 private void listContextMenu_ContextMenuOpening(object sender, ContextMenuEventArgs e) { if (this.lstGames.SelectedItem is not GameItemBase selected) { e.Handled = true; return; } bool isTkool = selected is TkoolGameItem; bool isUnity = selected is UnityGameItem; // ツクール専用メニュー this.menuTkoolOpenFolder.Visibility = isTkool ? Visibility.Visible : Visibility.Collapsed; this.menuTkoolRepairResources.Visibility = isTkool ? Visibility.Visible : Visibility.Collapsed; this.menuTkoolRestoreOriginal.Visibility = isTkool ? Visibility.Visible : Visibility.Collapsed; if (selected is TkoolGameItem tg) { // ASAR メニュー if (tg.IsAsar) { this.menuTkoolExtractAsar.Visibility = !tg.IsAsarExtracted ? Visibility.Visible : Visibility.Collapsed; this.menuTkoolRestoreAsar.Visibility = tg.IsAsarExtracted ? Visibility.Visible : Visibility.Collapsed; } else { this.menuTkoolExtractAsar.Visibility = Visibility.Collapsed; this.menuTkoolRestoreAsar.Visibility = Visibility.Collapsed; } // RGSS メニュー if (tg.IsRgss && tg.HasRgssArchive) { this.menuTkoolExtractRgss.Visibility = !tg.IsRgssExtracted ? Visibility.Visible : Visibility.Collapsed; this.menuTkoolRestoreRgss.Visibility = tg.IsRgssExtracted ? Visibility.Visible : Visibility.Collapsed; } else { this.menuTkoolExtractRgss.Visibility = Visibility.Collapsed; this.menuTkoolRestoreRgss.Visibility = Visibility.Collapsed; } // plugins.js は MV/MZ のみ this.menuTkoolOpenPluginsJs.Visibility = (tg.IsMV || tg.IsMZ) && File.Exists(tg.PluginsJsPath) ? Visibility.Visible : Visibility.Collapsed; // 専用プロファイルフォルダは Chromium/NW.js 系(MV/MZ/Tyrano)のみ this.menuTkoolOpenProfile.Visibility = !tg.IsRgss ? Visibility.Visible : Visibility.Collapsed; } else { this.menuTkoolExtractAsar.Visibility = Visibility.Collapsed; this.menuTkoolRestoreAsar.Visibility = Visibility.Collapsed; this.menuTkoolExtractRgss.Visibility = Visibility.Collapsed; this.menuTkoolRestoreRgss.Visibility = Visibility.Collapsed; this.menuTkoolRepairResources.Visibility = Visibility.Collapsed; this.menuTkoolOpenPluginsJs.Visibility = Visibility.Collapsed; this.menuTkoolOpenProfile.Visibility = Visibility.Collapsed; } // Unity専用メニュー this.menuUnitySaveEditor.Visibility = isUnity ? Visibility.Visible : Visibility.Collapsed; this.menuUnityOpenFolder.Visibility = isUnity ? Visibility.Visible : Visibility.Collapsed; this.menuUnityOpenLocalLow.Visibility = isUnity ? Visibility.Visible : Visibility.Collapsed; this.menuUnityOpenRegedit.Visibility = isUnity ? Visibility.Visible : Visibility.Collapsed; this.menuUnityBackupSave.Visibility = isUnity ? Visibility.Visible : Visibility.Collapsed; } #endregion #region ツクール専用機能 (ASAR解凍・復元・RGSS抽出・復元・MOD解除・Profile) private async void btnExtractAsar_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is TkoolGameItem tg) { await this.ExtractAsarForGame(tg, autoLaunchAfter: false); } } private async void MenuExtractAsar_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is TkoolGameItem tg) { await this.ExtractAsarForGame(tg, autoLaunchAfter: false); } } private async Task ExtractAsarForGame(TkoolGameItem tg, bool autoLaunchAfter) { if (!tg.IsAsar || string.IsNullOrEmpty(tg.AsarPath)) return; this.btnExtractAsar.IsEnabled = false; this.pbAsarProgress.Visibility = Visibility.Visible; this.lblAsarProgressStatus.Visibility = Visibility.Visible; this.pbAsarProgress.Value = 0; this.lblAsarProgressStatus.Text = "ASAR を解凍中..."; this.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; this.pbAsarProgress.Value = pct; this.lblAsarProgressStatus.Text = $"解凍中 ({p.currentFileIndex}/{p.totalFiles}): {p.currentFileName}"; }); var (success, message) = await this._asarService.ExtractAsarAsync(tg.AsarPath, outputDir, progress); this.pbAsarProgress.Visibility = Visibility.Collapsed; this.lblAsarProgressStatus.Visibility = Visibility.Collapsed; this.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"); this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); this.AppendLog($"[ASAR解凍成功] {message}"); MessageBox.Show(message, "ASAR 解凍完了", MessageBoxButton.OK, MessageBoxImage.Information); if (autoLaunchAfter) { await this.LaunchGameAsync(tg); } } else { this.AppendLog($"[ASAR解凍失敗] {message}"); MessageBox.Show(message, "ASAR 解凍エラー", MessageBoxButton.OK, MessageBoxImage.Error); } } private async void btnRestoreAsar_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is TkoolGameItem tg) { await this.RestoreAsarForGame(tg); } } private async void MenuRestoreAsar_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is TkoolGameItem tg) { await this.RestoreAsarForGame(tg); } } /// /// Enigma Virtual Box (EVB) でパックされたゲームを evbunpack で解凍し、 /// 本来のエンジンを再判定します。元の exe は .glbak としてバックアップされます。 /// private async void btnEvbUnpack_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsEvbPacked) return; this.btnEvbUnpack.IsEnabled = false; this.AppendLog($"[EVB解凍開始] {tg.Title}"); try { var progress = new Progress(m => this.AppendLog($"[EVB解凍] {m}")); var result = await Task.Run(() => new EvbUnpackService().Unpack(tg.RootDirectory, progress)); if (result.Success) { tg.IsEvbExtracted = true; tg.EvbExtractedDirPath = result.OutputDirectory; tg.EvbBackupPath = result.BackupExePath; tg.EvbUnderlyingEngine = result.UnderlyingEngine == EngineDetectionHelper.EngineUnknown ? string.Empty : result.UnderlyingEngine; this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); this.AppendLog("[EVB解凍完了] =============================="); this.AppendLog($" ・対象 : {tg.Title}"); this.AppendLog($" ・出力先 : {result.OutputDirectory}"); if (!string.IsNullOrEmpty(result.BackupExePath)) { this.AppendLog($" ・元exe : {Path.GetFileName(result.BackupExePath)}(.glbak に退避済み)"); } this.AppendLog($" ・本来のエンジン: {(string.IsNullOrEmpty(tg.EvbUnderlyingEngine) ? "未判定" : tg.EvbUnderlyingEngine)}"); this.AppendLog(" ・次の操作: 再スキャンすると解凍後の内容で起動できます。"); this.AppendLog("[EVB解凍完了] =============================="); } else { this.AppendLog("[EVB解凍失敗] =============================="); this.AppendLog($" ・対象 : {tg.Title}"); this.AppendLog($" ・原因 : {result.Message}"); this.AppendLog(" ・対処 : evbunpack.exe の配置確認、または -pe 10_70 / 7_80 を変えて再試行してください。"); this.AppendLog("[EVB解凍失敗] =============================="); } } finally { this.btnEvbUnpack.IsEnabled = true; } } /// /// EVB 解凍の出力フォルダを削除して元の状態へ戻します(元 exe のバックアップは保持)。 /// private void btnEvbRestore_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsEvbPacked) return; var progress = new Progress(m => this.AppendLog($"[EVB復元] {m}")); var restored = EvbUnpackService.Restore(tg.RootDirectory, progress); if (restored) { tg.IsEvbExtracted = false; tg.EvbExtractedDirPath = null; tg.EvbUnderlyingEngine = string.Empty; this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); this.AppendLog("[EVB復元完了] =============================="); this.AppendLog($" ・対象 : {tg.Title}"); this.AppendLog(" ・内容 : 解凍フォルダを削除し、元 exe(.glbak)を復元しました。"); this.AppendLog("[EVB復元完了] =============================="); } else { this.AppendLog("[EVB復元] =============================="); this.AppendLog($" ・対象 : {tg.Title}"); this.AppendLog(" ・内容 : 復元対象(解凍フォルダ / .glbak)がありません。"); this.AppendLog("[EVB復元] =============================="); } } /// /// 右側の詳細設定セクションを折りたたみ/展開します。 /// タイトルおよび起動ボタンは上部に固定されたまま、詳細エリアのみを開閉します。 /// private void btnToggleDetails_Click(object sender, RoutedEventArgs e) { bool collapse = this.scvDetails.Visibility == Visibility.Visible; this.scvDetails.Visibility = collapse ? Visibility.Collapsed : Visibility.Visible; this.btnToggleDetails.Content = collapse ? "▸ 詳細設定を展開" : "▾ 詳細設定を折りたたむ"; } /// /// 指定ゲームのブックマーク状態を切り替え、キャッシュに即時永続化します。 /// /// 対象ゲーム private void ToggleGameBookmark(GameItemBase? game) { if (game == null) return; game.IsBookmarked = !game.IsBookmarked; this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); if (this.chkFilterBookmarkedOnly.IsChecked == true || this._gameComparer.SortOrder == GameSortOrder.BookmarkedFirst) { this._gamesView?.Refresh(); } this.UpdateStatusLabels(); this.AppendLog($"[ブックマーク{(game.IsBookmarked ? "登録" : "解除")}] {game.Title}"); } /// 一覧カード内のブックマークボタン クリック時 private void btnCardBookmark_Click(object sender, RoutedEventArgs e) { if (sender is Button btn && btn.DataContext is GameItemBase game) { this.ToggleGameBookmark(game); } } /// 詳細パネル固定ヘッダーのブックマークボタン クリック時 private void btnDetailBookmark_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is GameItemBase game) { this.ToggleGameBookmark(game); } } /// コンテキストメニューのブックマーク切り替え クリック時 private void MenuToggleBookmark_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is GameItemBase game) { this.ToggleGameBookmark(game); } } 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; this.btnRestoreAsar.IsEnabled = false; this.AppendLog($"[ASAR復元開始] {tg.Title}"); var (success, message) = await this._asarService.RestoreAsarAsync(tg.AsarPath, tg.AsarExtractedDirPath); this.btnRestoreAsar.IsEnabled = true; if (success) { tg.IsAsarExtracted = false; tg.IsModded = false; this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); this.AppendLog($"[ASAR復元成功] {message}"); MessageBox.Show(message, "ASAR 復元完了", MessageBoxButton.OK, MessageBoxImage.Information); } else { this.AppendLog($"[ASAR復元失敗] {message}"); MessageBox.Show(message, "ASAR 復元エラー", MessageBoxButton.OK, MessageBoxImage.Error); } } #region RGSS スクリプト抽出・復元 private async void btnExtractRgss_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is TkoolGameItem tg) { await this.ExtractRgssForGame(tg); } } private async void MenuExtractRgss_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is TkoolGameItem tg) { await this.ExtractRgssForGame(tg); } } private async Task ExtractRgssForGame(TkoolGameItem tg) { if (!tg.IsRgss) return; this.btnExtractRgss.IsEnabled = false; this.pbRgssProgress.Visibility = Visibility.Visible; this.pbRgssProgress.IsIndeterminate = true; this.lblRgssProgressStatus.Visibility = Visibility.Visible; this.lblRgssProgressStatus.Text = "RGSSスクリプトを抽出中..."; this.AppendLog($"[RGSS抽出開始] {tg.Title} (アーカイブ: {tg.RgssArchivePath})"); var (success, message) = await this._rgssModService.ExtractScriptsAsync(tg, this._config.RgssExtractorPath); this.pbRgssProgress.Visibility = Visibility.Collapsed; this.lblRgssProgressStatus.Visibility = Visibility.Collapsed; this.btnExtractRgss.IsEnabled = true; if (success) { this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); this.AppendLog($"[RGSS抽出成功] {message}"); MessageBox.Show(message, "RGSS スクリプト抽出完了", MessageBoxButton.OK, MessageBoxImage.Information); } else { this.AppendLog($"[RGSS抽出失敗] {message}"); MessageBox.Show(message, "RGSS スクリプト抽出エラー", MessageBoxButton.OK, MessageBoxImage.Error); } } private void btnRestoreRgss_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is TkoolGameItem tg) { this.RestoreRgssForGame(tg); } } private void MenuRestoreRgss_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is TkoolGameItem tg) { this.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; this.AppendLog($"[RGSS復元開始] {tg.Title}"); var (success, message) = this._rgssModService.RestoreOriginal(tg); if (success) { tg.IsModded = false; this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); this.AppendLog($"[RGSS復元成功] {message}"); MessageBox.Show(message, "RGSS 復元完了", MessageBoxButton.OK, MessageBoxImage.Information); } else { this.AppendLog($"[RGSS復元失敗] {message}"); MessageBox.Show(message, "RGSS 復元エラー", MessageBoxButton.OK, MessageBoxImage.Error); } } #endregion private void btnRestoreOriginal_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is TkoolGameItem tg) { this.RestoreOriginalMod(tg); } } private void MenuRestoreOriginal_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is TkoolGameItem tg) { this.RestoreOriginalMod(tg); } } private void RestoreOriginalMod(TkoolGameItem tg) { var (Success, Message) = tg.IsRgss ? this._rgssModService.RestoreOriginal(tg) : (tg.EngineType == TkoolEngineType.Tyrano ? this._tyranoModService.RestoreOriginal(tg) : this._modService.RestoreOriginal(tg)); tg.IsModded = false; this.AppendLog($"[改造解除] {tg.Title}: {Message}"); if (Success) { MessageBox.Show(Message, "改造解除・復元完了", MessageBoxButton.OK, MessageBoxImage.Information); } else { MessageBox.Show(Message, "復元エラー", MessageBoxButton.OK, MessageBoxImage.Warning); } } private void MenuOpenProfileFolder_Click(object sender, RoutedEventArgs e) { if (this.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 (this.lstGames.SelectedItem is TkoolGameItem tg && File.Exists(tg.PluginsJsPath)) { Process.Start(new ProcessStartInfo { FileName = tg.PluginsJsPath, UseShellExecute = true }); } } /// /// ツクールゲームのリソース文字化け・URLエンコード修復メニュー クリック時 /// private async void MenuRepairResources_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is TkoolGameItem tg) { this.AppendLog($"[リソース修復] {tg.Title}: 手動での完全再検査を開始します..."); this.pbGlobalProgress.Visibility = Visibility.Visible; this.pbGlobalProgress.IsIndeterminate = true; this.lblGlobalProgressText.Visibility = Visibility.Visible; this.lblGlobalProgressText.Text = "ファイル一覧を収集中..."; this.lblStatusEngine.Text = "リソース修復中..."; var progress = new Progress(p => { if (p.Total > 0) { this.pbGlobalProgress.IsIndeterminate = false; this.pbGlobalProgress.Maximum = p.Total; this.pbGlobalProgress.Value = p.Current; this.lblGlobalProgressText.Text = $"リソース修復中: {p.Current}/{p.Total} (修復: {p.RepairedCount})"; } else { this.lblGlobalProgressText.Text = p.CurrentStatus; } }); try { var result = await this._tkoolResourceRepairService.RepairGameResourcesAsync( tg, forceRescan: true, progress: progress, uiLogCallback: msg => this.AppendLog(msg)); this.AppendLog($"[リソース修復完了] {tg.Title}: {result.Message}"); var askOpenLog = MessageBox.Show( $"{result.Message}\n\n詳細ログファイルを出力しました:\n{result.LogFilePath}\n\nログファイルを開きますか?", "リソース修復結果", MessageBoxButton.YesNo, result.Success ? MessageBoxImage.Information : MessageBoxImage.Warning); if (askOpenLog == MessageBoxResult.Yes && !string.IsNullOrEmpty(result.LogFilePath) && File.Exists(result.LogFilePath)) { Process.Start(new ProcessStartInfo { FileName = result.LogFilePath, UseShellExecute = true }); } } catch (Exception ex) { this.AppendLog($"[リソース修復エラー] {tg.Title}: {ex.Message}"); MessageBox.Show($"リソース修復中にエラーが発生しました:\n{ex.Message}", "修復エラー", MessageBoxButton.OK, MessageBoxImage.Error); } finally { this.pbGlobalProgress.Visibility = Visibility.Collapsed; this.lblGlobalProgressText.Visibility = Visibility.Collapsed; this.lblStatusEngine.Text = "待機中"; } } } #endregion #region Unity専用機能 (セーブエディタ・LocalLow・regedit・即時バックアップ) private void btnOpenSaveEditor_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is UnityGameItem ug) { this.OpenSaveEditor(ug); } } private void MenuOpenSaveEditor_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is UnityGameItem ug) { this.OpenSaveEditor(ug); } } private void OpenSaveEditor(UnityGameItem ug) { try { this.AppendLog($"[セーブエディタ起動] {ug.Title} のセーブエディタを開きます..."); var win = new SaveEditorWindow(ug) { Owner = this }; win.ShowDialog(); // セーブ状態の再チェック ug.HasSaveData = this._scannerService.CheckHasSaveData(ug); this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); this.AppendLog($"[セーブエディタ終了] {ug.Title} のセーブエディタを閉じました。"); } catch (Exception ex) { MessageBox.Show($"セーブエディタの起動中にエラーが発生しました:\n{ex.Message}", "エラー", MessageBoxButton.OK, MessageBoxImage.Error); this.AppendLog($"[セーブエディタエラー] {ex.Message}"); } } private void btnOpenLocalLow_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is UnityGameItem ug) { this.OpenLocalLow(ug); } } private void MenuOpenLocalLow_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is UnityGameItem ug) { this.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 (this.lstGames.SelectedItem is UnityGameItem ug) { this.OpenRegedit(ug); } } private void MenuOpenRegedit_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is UnityGameItem ug) { this.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"); 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 (this.lstGames.SelectedItem is UnityGameItem ug) { this.PerformUnityQuickBackup(ug); } } private void MenuBackupSave_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is UnityGameItem ug) { this.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 = this._unitySaveService.BackupRegistry(ug.RegistryPath, backupDir); if (regRes != null) backedUpCount++; } // 2. ディスクセーブファイル var files = this._unitySaveService.GetSaveFiles(ug); foreach (var f in files) { var fileRes = this._unitySaveService.BackupSaveFile(f.FilePath, backupDir); if (fileRes != null) backedUpCount++; } if (backedUpCount > 0) { ug.HasSaveData = true; this.AppendLog($"[セーブバックアップ完了] {ug.Title}: {backedUpCount} 個の項目を保存しました。(保存先: {backupDir})"); MessageBox.Show($"セーブデータのバックアップが完了しました!({backedUpCount} 個のファイル/レジストリ)\n\n保存先:\n{backupDir}", "バックアップ完了", MessageBoxButton.OK, MessageBoxImage.Information); } else { this.AppendLog($"[セーブバックアップ警告] {ug.Title}: バックアップ対象が見つかりませんでした。"); MessageBox.Show("バックアップ対象のセーブデータ(レジストリまたはファイル)が見つかりませんでした。", "バックアップ確認", MessageBoxButton.OK, MessageBoxImage.Information); } } catch (Exception ex) { this.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 (this.lstGames.SelectedItem is TkoolGameItem tg && tg.IsWolf) { var dialog = new WolfSaveEditorDialog(tg, this._wolfSaveService) { Owner = this }; dialog.ShowDialog(); } } private void chkWolfProxyDll_Checked(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is TkoolGameItem tg && tg.IsWolf) { var (success, msg) = this._wolfModService.ApplyProxyDll(tg, 1.0, tg.WolfSpeedMultiplier > 0 ? tg.WolfSpeedMultiplier : 3.0, 5.0); this.AppendLog($"[ウディタ プロキシDLL] {msg.Replace("\n", " ")}"); this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); } } private void chkWolfProxyDll_Unchecked(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is TkoolGameItem tg && tg.IsWolf) { var (success, msg) = this._wolfModService.RemoveProxyDll(tg); this.AppendLog($"[ウディタ プロキシDLL] {msg}"); this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); } } private void btnApplyWolfProxyDll_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is TkoolGameItem tg && tg.IsWolf) { var (success, msg) = this._wolfModService.ApplyProxyDll(tg, 1.0, tg.WolfSpeedMultiplier > 0 ? tg.WolfSpeedMultiplier : 3.0, 5.0); tg.WolfProxyDll = true; this.AppendLog($"[ウディタ プロキシDLL] {msg.Replace("\n", " ")}"); MessageBox.Show(msg, "プロキシDLL適用", MessageBoxButton.OK, MessageBoxImage.Information); this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); } } private void btnRemoveWolfProxyDll_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is TkoolGameItem tg && tg.IsWolf) { var (success, msg) = this._wolfModService.RemoveProxyDll(tg); tg.WolfProxyDll = false; this.AppendLog($"[ウディタ プロキシDLL] {msg}"); MessageBox.Show(msg, "プロキシDLL解除", MessageBoxButton.OK, MessageBoxImage.Information); this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); } } private async void btnExtractWolf_Click(object sender, RoutedEventArgs e) { if (this.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; this.pbWolfProgress.Visibility = Visibility.Visible; this.pbWolfProgress.IsIndeterminate = true; this.lblWolfProgressStatus.Visibility = Visibility.Visible; this.lblWolfProgressStatus.Text = "Data.wolf を解凍しています..."; this.btnExtractWolf.IsEnabled = false; var progress = new Progress(status => { this.Dispatcher.Invoke(() => { this.lblWolfProgressStatus.Text = status; this.AppendLog($"[ウディタ解凍] {status}"); }); }); try { var (success, msg) = await this._wolfArchiveService.ExtractArchiveAsync(tg, this._config.WolfExtractorPath, progress); if (success) { tg.IsWolfExtracted = true; MessageBox.Show(msg, "解凍完了", MessageBoxButton.OK, MessageBoxImage.Information); } else { MessageBox.Show(msg, "解凍エラー", MessageBoxButton.OK, MessageBoxImage.Warning); } this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); } finally { this.pbWolfProgress.Visibility = Visibility.Collapsed; this.lblWolfProgressStatus.Visibility = Visibility.Collapsed; this.btnExtractWolf.IsEnabled = true; } } private void btnRestoreWolfArchive_Click(object sender, RoutedEventArgs e) { if (this.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) = this._wolfArchiveService.RestoreArchiveState(tg); if (success) { tg.IsWolfExtracted = false; this.AppendLog($"[ウディタ復元] {tg.Title}: {msg.Replace("\n", " ")}"); MessageBox.Show(msg, "復元完了", MessageBoxButton.OK, MessageBoxImage.Information); this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); } else { MessageBox.Show(msg, "復元エラー", MessageBoxButton.OK, MessageBoxImage.Warning); } } private void btnRestoreWolfAll_Click(object sender, RoutedEventArgs e) { if (this.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) = this._wolfModService.RestoreAllMods(tg); tg.WolfProxyDll = false; this.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 (this.lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsSrpgStudio) return; tg.SrpgProxyDll = true; bool ok = this._srpgModService.EnableProxyDll(tg.RootDirectory, tg.SrpgSpeedMultiplier > 0 ? tg.SrpgSpeedMultiplier : 3.0); if (ok) { this.AppendLog($"[SRPG Studio 倍速] {tg.Title}: プロキシDLLを有効化しました (F6で倍速切替)"); } this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); } private void chkSrpgProxyDll_Unchecked(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsSrpgStudio) return; tg.SrpgProxyDll = false; this._srpgModService.DisableProxyDll(tg.RootDirectory); this.AppendLog($"[SRPG Studio 倍速] {tg.Title}: プロキシDLLを解除しました"); this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); } private void btnApplySrpgProxyDll_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsSrpgStudio) return; tg.SrpgProxyDll = true; bool ok = this._srpgModService.EnableProxyDll(tg.RootDirectory, tg.SrpgSpeedMultiplier > 0 ? tg.SrpgSpeedMultiplier : 3.0); if (ok) { this.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); } this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); } private void btnRemoveSrpgProxyDll_Click(object sender, RoutedEventArgs e) { if (this.lstGames.SelectedItem is not TkoolGameItem tg || !tg.IsSrpgStudio) return; tg.SrpgProxyDll = false; bool ok = this._srpgModService.DisableProxyDll(tg.RootDirectory); this.AppendLog($"[SRPG Studio 倍速] {tg.Title}: プロキシDLL (version.dll) を解除しました"); MessageBox.Show("プロキシDLL (version.dll) を解除しました。", "プロキシDLL解除完了", MessageBoxButton.OK, MessageBoxImage.Information); this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); } private async void btnApplySrpgMod_Click(object sender, RoutedEventArgs e) { if (this.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; this.pbSrpgProgress.Visibility = Visibility.Visible; this.pbSrpgProgress.IsIndeterminate = true; this.lblSrpgProgressStatus.Visibility = Visibility.Visible; this.lblSrpgProgressStatus.Text = "改造プラグインを適用・再パック中..."; this.btnApplySrpgMod.IsEnabled = false; var progress = new Progress(status => { this.Dispatcher.Invoke(() => { this.lblSrpgProgressStatus.Text = status; this.AppendLog($"[SRPG Studio 改造] {status}"); }); }); try { var (success, msg) = await this._srpgModService.ApplyModAndRepackAsync(tg, progress); if (success) { this.AppendLog($"[SRPG Studio 改造成功] {tg.Title}: {msg}"); MessageBox.Show(msg, "改造適用完了", MessageBoxButton.OK, MessageBoxImage.Information); } else { this.AppendLog($"[SRPG Studio 改造失敗] {tg.Title}: {msg}"); MessageBox.Show(msg, "改造適用エラー", MessageBoxButton.OK, MessageBoxImage.Warning); } this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); } finally { this.pbSrpgProgress.Visibility = Visibility.Collapsed; this.lblSrpgProgressStatus.Visibility = Visibility.Collapsed; this.btnApplySrpgMod.IsEnabled = true; } } private async void btnRemoveSrpgMod_Click(object sender, RoutedEventArgs e) { if (this.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; this.pbSrpgProgress.Visibility = Visibility.Visible; this.pbSrpgProgress.IsIndeterminate = true; this.lblSrpgProgressStatus.Visibility = Visibility.Visible; this.lblSrpgProgressStatus.Text = "改造プラグインを解除中..."; this.btnRemoveSrpgMod.IsEnabled = false; var progress = new Progress(status => { this.Dispatcher.Invoke(() => { this.lblSrpgProgressStatus.Text = status; this.AppendLog($"[SRPG Studio 解除] {status}"); }); }); try { var (success, msg) = await this._srpgModService.RemoveModAndRepackAsync(tg, progress); if (success) { // チェックをすべてオフにする foreach (var mod in tg.SrpgModOptions) mod.IsEnabled = false; this.AppendLog($"[SRPG Studio 解除成功] {tg.Title}: {msg}"); MessageBox.Show(msg, "改造解除完了", MessageBoxButton.OK, MessageBoxImage.Information); } else { this.AppendLog($"[SRPG Studio 解除失敗] {tg.Title}: {msg}"); MessageBox.Show(msg, "改造解除エラー", MessageBoxButton.OK, MessageBoxImage.Warning); } this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); } finally { this.pbSrpgProgress.Visibility = Visibility.Collapsed; this.lblSrpgProgressStatus.Visibility = Visibility.Collapsed; this.btnRemoveSrpgMod.IsEnabled = true; } } private async void btnUnpackSrpg_Click(object sender, RoutedEventArgs e) { if (this.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; this.pbSrpgProgress.Visibility = Visibility.Visible; this.pbSrpgProgress.IsIndeterminate = true; this.lblSrpgProgressStatus.Visibility = Visibility.Visible; this.lblSrpgProgressStatus.Text = "data.dts を解凍しています..."; this.btnUnpackSrpg.IsEnabled = false; var progress = new Progress(status => { this.Dispatcher.Invoke(() => { this.lblSrpgProgressStatus.Text = status; this.AppendLog($"[SRPG Studio 解凍] {status}"); }); }); try { var (success, msg) = await this._srpgArchiveService.UnpackDataDtsAsync(tg.RootDirectory, progress); if (success) { tg.IsSrpgExtracted = true; this.AppendLog($"[SRPG Studio 解凍成功] {tg.Title}: {msg.Replace("\n", " ")}"); MessageBox.Show(msg, "解凍完了", MessageBoxButton.OK, MessageBoxImage.Information); } else { this.AppendLog($"[SRPG Studio 解凍失敗] {tg.Title}: {msg}"); MessageBox.Show(msg, "解凍エラー", MessageBoxButton.OK, MessageBoxImage.Warning); } this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); } finally { this.pbSrpgProgress.Visibility = Visibility.Collapsed; this.lblSrpgProgressStatus.Visibility = Visibility.Collapsed; this.btnUnpackSrpg.IsEnabled = true; } } private async void btnRepackSrpg_Click(object sender, RoutedEventArgs e) { if (this.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; this.pbSrpgProgress.Visibility = Visibility.Visible; this.pbSrpgProgress.IsIndeterminate = true; this.lblSrpgProgressStatus.Visibility = Visibility.Visible; this.lblSrpgProgressStatus.Text = "data.dts を再構築中..."; this.btnRepackSrpg.IsEnabled = false; var progress = new Progress(status => { this.Dispatcher.Invoke(() => { this.lblSrpgProgressStatus.Text = status; this.AppendLog($"[SRPG Studio 再構築] {status}"); }); }); try { var (success, msg) = await this._srpgArchiveService.RepackDataDtsAsync(tg.RootDirectory, progress); if (success) { this.AppendLog($"[SRPG Studio 再構築成功] {tg.Title}: {msg.Replace("\n", " ")}"); MessageBox.Show(msg, "再構築完了", MessageBoxButton.OK, MessageBoxImage.Information); } else { this.AppendLog($"[SRPG Studio 再構築失敗] {tg.Title}: {msg}"); MessageBox.Show(msg, "再構築エラー", MessageBoxButton.OK, MessageBoxImage.Warning); } this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); } finally { this.pbSrpgProgress.Visibility = Visibility.Collapsed; this.lblSrpgProgressStatus.Visibility = Visibility.Collapsed; this.btnRepackSrpg.IsEnabled = true; } } private async void btnRestoreSrpgAll_Click(object sender, RoutedEventArgs e) { if (this.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; this.pbSrpgProgress.Visibility = Visibility.Visible; this.pbSrpgProgress.IsIndeterminate = true; this.lblSrpgProgressStatus.Visibility = Visibility.Visible; this.lblSrpgProgressStatus.Text = "すべての改造を解除中..."; var progress = new Progress(status => { this.Dispatcher.Invoke(() => { this.lblSrpgProgressStatus.Text = status; this.AppendLog($"[SRPG Studio 完全復元] {status}"); }); }); try { var (success, msg) = await this._srpgModService.RestoreAllModsAsync(tg, progress); foreach (var mod in tg.SrpgModOptions) mod.IsEnabled = false; this.AppendLog($"[SRPG Studio 完全復元] {tg.Title}:\n{msg}"); MessageBox.Show($"すべての改造を解除しました:\n\n{msg}", "復元完了", MessageBoxButton.OK, MessageBoxImage.Information); this._scannerService.SaveCache(this._games); this._scannerService.SaveBookmarks(this._games); } finally { this.pbSrpgProgress.Visibility = Visibility.Collapsed; this.lblSrpgProgressStatus.Visibility = Visibility.Collapsed; } } #endregion #region 共通アクション (フォルダを開く・ログ操作) private void btnOpenFolder_Click(object sender, RoutedEventArgs e) { if (this.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 (this.lstGames.SelectedItem is GameItemBase game && Directory.Exists(game.RootDirectory)) { Process.Start(new ProcessStartInfo { FileName = game.RootDirectory, UseShellExecute = true }); } } private void AppendLog(string message) { string timestamp = DateTime.Now.ToString("HH:mm:ss"); this._logQueue.Enqueue($"[{timestamp}] {message}\n"); } private void FlushLogQueue() { if (this._logQueue.IsEmpty) return; var sb = new StringBuilder(); while (this._logQueue.TryDequeue(out var msg)) { sb.Append(msg); if (sb.Length > 20000) break; // 1回あたりの最大文字数を制限してUIを軽快に保つ } if (sb.Length > 0) { // テキストボックスの行数が多すぎる場合は古いログを切り詰める(メモリ肥大化・クラッシュ防止) if (this.txtLog.Text.Length > 100000) { this.txtLog.Text = this.txtLog.Text[^50000..]; } this.txtLog.AppendText(sb.ToString()); this.scrollLog.ScrollToEnd(); } } private void btnClearLog_Click(object sender, RoutedEventArgs e) { while (this._logQueue.TryDequeue(out _)) { } this.txtLog.Clear(); } #endregion } }