Compare commits

..
28 Commits
Author SHA1 Message Date
armonica f50976a6c0 最適化: ラベル表示状態のキャッシュ永続化および実在検証の超高速化
- UnifiedGameCacheEntryにIsModded等のラベル状態を保持し、起動直後の0秒時点から全ラベルを即時表示
- フォルダ更新日時(LastWriteTime)比較により、不変ゲームの重いディスクI/O検証を完全スキップ
- 実在検証完了後に一覧およびステータスラベルの最新描画リフレッシュを追加
2026-10-20 15:11:37 +09:00
armonica b0fdea2411 最適化: NTFS MFT走査およびディスク読み取りの並列化と限界高速化
- 複数ドライブ(C:, Z:等)のMFTスキャンを完全並列実行するように改善
- MFTのI/Oバッファを2MBに拡張しシステムコールを削減
- ターゲット外ファイルの無駄な文字列化・オブジェクト生成を完全スキップする2パス抽出アルゴリズムを導入
- 既存ゲーム実在検証処理(VerifyAndEnrichGamesAsync)をParallel.ForEachで並列化
- 新規フォルダ走査の並列度引き上げと複数ドライブ同時走査に対応
2026-10-20 15:02:14 +09:00
armonica dd00c96e20 機能改善: 高速スキャン連携とインメモリプレフィルタによるゲーム検出処理の統合
Everything -> NTFS MFT -> 通常走査の順でフォールバックするパイプラインを構築し、インメモリプレフィルタにより無関係なフォルダのディスクI/Oを排除してゲーム検出を劇的に高速化しました。UIログにも適用エンジンを表示します。
2026-10-20 11:30:13 +09:00
armonica 4c94cf814f 機能追加: NTFS MFT (USN Journal) 直接読み取りによる高速ファイル走査サービスを追加
低レベルボリュームハンドルから FSCTL_ENUM_USN_DATA を呼び出し、ドライブ全体の MFT/USN レコードを直接メモリへ読み出して対象フォルダ配下のインデックスを秒速生成する NtfsMftScanService を実装しました。
2026-10-20 11:30:07 +09:00
armonica 2c02e10dd1 機能追加: Everything IPC を利用した超高速フォルダ走査サービスを追加
Everything が起動しているかを判定し、WM_COPYDATA 通信によって指定フォルダ配下の全ファイル・サブディレクトリを一括取得する EverythingSearchService を実装しました。
2026-10-20 11:29:58 +09:00
armonica b65122537d 機能追加: メモリ上でのディレクトリ・ファイル高速判定用スナップショットクラスを追加
Everything や NTFS MFT から取得したファイルツリーをインメモリで保持し、ディスクI/Oを行わずにファイル存在確認や一覧取得を可能にする FastDirectorySnapshot クラスを実装しました。
2026-10-20 11:29:53 +09:00
armonica ee9eeb3118 設定: アプリ起動時に常に管理者権限を要求するマニフェストを追加
app.manifest を新規作成して requestedExecutionLevel に requireAdministrator を指定し、GameLauncher.csproj にマニフェストを組み込みました。
2026-10-20 11:29:47 +09:00
armonica dc03f5284a feat(scanner): 起動時フリーズ解消(完全非同期化)とステータスバー最下部プログレスバー連携 2026-10-20 10:56:42 +09:00
armonica 6447fc2635 feat(perf): サムネイルキャッシュの即時ロードおよびデコード負荷極小化の実装 2026-10-20 10:55:34 +09:00
armonica ec4d718311 feat(ui): 右側詳細パネルのシンプル化とスクリプト改造不可時の項目非表示化 2026-10-20 10:54:53 +09:00
armonica c03cc97af1 feat(ui): ゲーム一覧の仮想スクロール最適化(Recycling・Pixel単位スクロール)の実装 2026-10-20 10:54:04 +09:00
armonica ae86b53147 スタイル: コーディング規約に準拠したコードフォーマットの適用(this.の明示、空白スタイルの統一)
- 自インスタンスメンバーアクセスへの this. 付与(28ファイル)
- .editorconfig に準拠したインデント・波括弧・空白スタイルの適用
- UTF-8 (BOMあり)、CRLF改行コード、行末空白除去の整合性検証
2026-10-20 10:14:26 +09:00
armonica 2fa40c950f feat(ui): GameItemBase への仮想プロパティ追加とメイン画面バッジ表示バインディングの堅牢化 2026-10-14 17:02:23 +09:00
armonica 7ead7386f6 feat(evb): Enigma Virtual Box (EVB) のVFSシグネチャ検証による誤検出防止とスキャナ同期の強化 2026-10-14 17:01:33 +09:00
armonica ee7b37323c docs(codecs): セーブデータコーデック基盤へのXMLドキュメントコメント付与および実装スタイルの整理 2026-10-14 17:01:02 +09:00
armonica 922f669191 style: .editorconfig の追加および全ファイルのエンコーディング(UTF-8 BOM)・CRLF・行末空白の統一 2026-10-14 17:00:27 +09:00
armonica 751e382adc feat(ui): ログ出力のバッチフラッシュ化・全体プログレス表示およびUI連携の改善
- ログ出力を ConcurrentQueue によるキューイングとタイマーによるバッチフラッシュ方式へ移行し、大量ログ出力時のUIフリーズを防止
- ログテキストボックスの文字数制限(10万文字超過時のトリム)を導入しメモリ肥大化を抑制
- ステータスバーに全体処理用プログレスバー(pbGlobalProgress)を追加
- EVB要解凍バッジおよびその他エンジンバッジのXAMLバインディング連携を整理
- セーブエディタ・ウディタ・SRPG Studio等の各種操作後に SaveBookmarks を呼び出すよう保存処理を補完
2026-10-14 09:59:11 +09:00
armonica cfdba6806a feat(scanner): アイコンサムネイルキャッシュ・深層exe探索・ブックマーク永続化に対応
- 抽出したアイコンを PNG 形式で Thumbnails フォルダにキャッシュし再スキャンを高速化
- サブディレクトリ内のゲーム実行ファイル(.exe)を最大深さまで再帰探索するロジックを追加
- キャッシュ再構築時でもお気に入りを保持する bookmarks.json 独立永続化機能を追加
- EngineLogicVersion によるエンジン判定ロジック更新時のキャッシュ自動無効化・再スキャンを導入
- EVB・スタンドアロン・その他エンジンの消失復旧および判定ロジックを強化
2026-10-14 09:58:33 +09:00
armonica 45bff52198 feat(engine): その他エンジン種別の追加およびラベル・サムネイル基盤の拡張
- エンジン区分に Other(その他)を追加し、該当バッジおよびフィルターに対応
- GameItemBase に EngineLabelText, EngineLabelBackground, OtherBadgeVisibility を追加
- TkoolGameItem および UnityGameItem で各エンジンのラベル表示ロジックを実装
- AppPathHelper にサムネイル保存用ディレクトリ取得メソッドを追加
- Converters に文字列非空時可視化コンバーター(StringNotEmptyToVisibilityConverter)を追加
- TkoolGameItem の EVB「要解凍」バッジ表示テキスト連携を実装
2026-10-14 09:58:14 +09:00
armonica 4398f80aa4 feat(tkool): リソース修復サービスおよび文字化け・URLエンコード救済プラグインを追加
- ツクールMV/MZの日本語ファイル名・URLエンコード・丸数字表記揺れを並列修復する TkoolResourceRepairService を追加
- ゲーム起動時に読み込み不整合を動的に解決する必須救済プラグイン ResourceLoaderFix.js を追加
- TkoolModService にて ResourceLoaderFix を最優先で適用するよう対応
2026-10-14 09:57:54 +09:00
armonica 908dc443eb fix(evb): PEセクションによるEVB判定の厳格化と誤検知の防止
- 誤検知の要因となっていたバイナリ文字列探索(ContainsEvbContentMarker)を廃止
- PEセクションテーブル(.enigma1, .enigma2)の検出のみで確実に判定するよう見直し
2026-10-14 09:57:33 +09:00
armonica 8f67ab1864 docs: UI文字列の日本語統一および変更時チェックリストを更新
- UI文字列追加・変更時の日本語表記遵守規則を明記
- 変更時チェックリストに日本語出力確認項目を追加
2026-10-14 09:57:11 +09:00
armonica 6f98860892 refactor(plugins): プラグイン管理UIのグループ化表示および特定ゲーム専用プラグインの分離に対応
- ModPluginDefinition に IsGameSpecific, TargetGameKey, GroupName, DefaultEnabled を追加
- プリンセスシナジー専用プラグイン(AlwaysMaxHp/AlwaysMaxMp)を一般ゲーム一覧から除外し対象ゲーム限定で表示
- TkoolGameItem のプラグイン一覧を CommonPluginOptions と SpecificPluginOptions に分離
- プラグイン設定Expander内に「共通プラグイン」と「固有ゲーム専用プラグイン」のグループ分けUIを実装
- 右側詳細パネルのレイアウトを改善し、起動ボタンを上部固定したまま下部設定のみを開閉可能に変更
- 不要な旧プラグイン GameLauncher_Mod.js の削除および読み込み除外処理を徹底
2026-10-09 10:48:20 +09:00
armonica c0989362a9 feat(bookmark): ゲームのお気に入り(ブックマーク)登録機能および優先ソート・フィルターを追加
- GameItemBase に IsBookmarked プロパティおよび関連バインディング項目を追加
- 一覧カード内星アイコン、詳細ヘッダーボタン、右クリックコンテキストメニューからブックマーク切替可能に
- ソート順に「★ ブックマーク優先」を追加し、サブフィルターに「★ ブックマークのみ」絞り込みを追加
- キャッシュ保存(UnifiedGameCacheEntry)にブックマーク状態を永続化し次回起動時も保持
- ステータスバーにブックマーク登録件数の集計表示を追加
2026-10-09 10:41:57 +09:00
armonica 59519208f3 feat(nwjs): NW.js汎用ゲームの自動検出・専用タブおよびバッジ表示機能を追加
- package.jsonを起点とする汎用NW.jsゲームの検出ロジック(NwjsDetector)を新規実装
- メインナビゲーションタブに「NW.js」タブを追加し、エンジン別フィルタリングに対応
- 一覧カードおよび詳細パネルヘッダーにNW.jsバッジを追加
- キャッシュ復元およびステータスバー集計にNW.jsエンジン分類を反映
2026-10-09 10:36:57 +09:00
armonica 90584379b7 feat(ui): EVB解凍済みバッジの表示および実効exeによる起動処理に対応
- TkoolGameItem に EVB解凍済みバッジ用の可視性プロパティ(EvbExtractedVisibility)を追加
- ResolveLaunchExecutable にて解凍先ディレクトリからの実効exe解決フォールバックを強化
- MainWindow.xaml に緑色の「解凍済み」バッジを追加し、UI上で状態を一目で確認可能に改善
- MainWindow.xaml.cs の LaunchGameAsync で TkoolGameItem の実効起動exeパスを解決して起動するように修正
2026-10-08 14:12:48 +09:00
armonica 5433371a77 feat(scanner): 解凍済みEVBゲームの起動パス・Mod対象解決と状態永続化に対応
- 解凍済みEVBゲームに対して、解凍先ディレクトリ内の実効exeを起動対象として解決
- 退避バックアップファイル(.glbak)の検索・解決処理を追加
- 解凍先フォルダ(_evb_extracted)配下の plugins.js をMod適用対象として検出し、MV/MZエンジン種別を判定
- EVBメタデータ(IsEvbPacked, IsEvbExtracted, EvbExtractedDirPathなど)をスキャンキャッシュに永続化
2026-10-08 14:12:17 +09:00
armonica 3550e20891 feat(evb): 解凍完了マーカーに基づくEVBゲーム検出の維持機能を追加
- 元exeが .glbak に退避された解凍後でもEVBゲームとして継続認識できるよう IsExtracted 判定を追加
- 解凍完了マーカー(_evb_extracted)の存在を検証し、後続の起動・アイコン解決の破損を防止
2026-10-08 14:12:07 +09:00
77 changed files with 6172 additions and 2263 deletions

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
root = true
[*]
charset = utf-8-bom
end_of_line = crlf
indent_style = space
indent_size = 4
trim_trailing_whitespace = true
insert_final_newline = true
[*.cs]
# this. の明示
dotnet_style_qualification_for_field = true:suggestion
dotnet_style_qualification_for_property = true:suggestion
dotnet_style_qualification_for_method = true:suggestion
dotnet_style_qualification_for_event = true:suggestion
# 改行・波括弧スタイル
csharp_new_line_before_open_brace = all
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
# 空白スタイル
csharp_space_after_cast = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_between_method_call_parameter_list_parentheses = false
csharp_space_between_method_declaration_parameter_list_parentheses = false
+1 -1
View File
@@ -1,4 +1,4 @@
## Visual Studio 2026 / .NET .gitignore
## Visual Studio 2026 / .NET .gitignore
[Bb]in/
[Oo]bj/
[Ll]og/
+6 -1
View File
@@ -1,4 +1,4 @@
# AGENTS.md — GameLauncher エージェント規則
# AGENTS.md — GameLauncher エージェント規則
このファイルは **GameLauncher プロジェクトの AI エージェント向け規則** である。
本プロジェクトでのすべての変更(コード追加・修正・削除・発行)は、必ず以下の規則に従って実施すること。
@@ -50,6 +50,10 @@
- コードコメントは既存コードに合わせて日本語/英語を適切に使い分ける。
- 新規ファイルには冒頭に説明コメントを付ける。
- ファイル名・シンボル参照はバッククォートで囲む。
- UI 文字列を追加・変更する場合は、既存の日本語表記に合わせる。
> 注: ユーザーから見える出力の言語(日本語)については、グローバルのユーザー記憶
> (`/memories/preferences.md`)で規定する。重複を避けるため本ファイルでは規定しない。
---
@@ -60,3 +64,4 @@
3. ゲーム個別処理は `Engines/<Engine>/Games/<GameName>/` に分離し、他ゲームへ影響しないか。
4. 外部ツールは `Engines/<Engine>/Tools/` にあり、`AppPathHelper` 経由で参照しているか。
5. ビルドが成功し、`publish.ps1` で発行できるか。
6. ユーザーから見える出力が日本語になっているか(判定基準は `/memories/preferences.md`)。
+1 -1
View File
@@ -1,4 +1,4 @@
<Window x:Class="GameLauncher.AddKeyDialog"
<Window x:Class="GameLauncher.AddKeyDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
+12 -12
View File
@@ -1,4 +1,4 @@
using System.Windows;
using System.Windows;
using System.Windows.Controls;
using GameLauncher.Models;
using GameLauncher.Engines.Unity;
@@ -16,37 +16,37 @@ namespace GameLauncher
public AddKeyDialog()
{
InitializeComponent();
txtKeyName.Focus();
this.InitializeComponent();
this.txtKeyName.Focus();
}
private void btnOk_Click(object sender, RoutedEventArgs e)
{
var keyName = txtKeyName.Text.Trim();
var keyName = this.txtKeyName.Text.Trim();
if (string.IsNullOrWhiteSpace(keyName))
{
MessageBox.Show("キー名を入力してください。", "入力エラー", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
KeyName = keyName;
var selectedTag = (cmbKeyType.SelectedItem as ComboBoxItem)?.Tag?.ToString();
KeyType = selectedTag switch
this.KeyName = keyName;
var selectedTag = (this.cmbKeyType.SelectedItem as ComboBoxItem)?.Tag?.ToString();
this.KeyType = selectedTag switch
{
"Float" => PlayerPrefsType.Float,
"String" => PlayerPrefsType.String,
_ => PlayerPrefsType.Int
};
KeyValue = txtKeyValue.Text;
this.KeyValue = this.txtKeyValue.Text;
DialogResult = true;
Close();
this.DialogResult = true;
this.Close();
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
Close();
this.DialogResult = false;
this.Close();
}
}
}
+2 -2
View File
@@ -1,9 +1,9 @@
<Application x:Class="GameLauncher.App"
<Application x:Class="GameLauncher.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:GameLauncher"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
+3 -3
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.IO;
using System.Windows;
using GameLauncher.Helpers;
@@ -25,7 +25,7 @@ namespace GameLauncher
{
var ex = args.Exception;
LogError("DispatcherUnhandledException", ex);
MessageBox.Show($"アプリケーションエラーが発生しました:\n\n{ex.Message}\n\n詳細:\n{ex}",
MessageBox.Show($"アプリケーションエラーが発生しました:\n\n{ex.Message}\n\n詳細:\n{ex}",
"GameLauncher エラー", MessageBoxButton.OK, MessageBoxImage.Error);
args.Handled = true;
};
@@ -35,7 +35,7 @@ namespace GameLauncher
if (args.ExceptionObject is Exception ex)
{
LogError("AppDomain.UnhandledException", ex);
MessageBox.Show($"致命的なエラーが発生しました:\n\n{ex.Message}\n\n詳細:\n{ex}",
MessageBox.Show($"致命的なエラーが発生しました:\n\n{ex.Message}\n\n詳細:\n{ex}",
"GameLauncher 致命的エラー", MessageBoxButton.OK, MessageBoxImage.Error);
}
};
+1 -1
View File
@@ -1,4 +1,4 @@
//ティラノビルダーによる自動ビルド 
//ティラノビルダーによる自動ビルド
;debugMenu.visible=false
;configSave=file
;global.config_version=5.00
+12 -12
View File
@@ -1,7 +1,7 @@
<Window x:Class="GameLauncher.ConfigDialog"
<Window x:Class="GameLauncher.ConfigDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="アプリケーション設定"
Title="アプリケーション設定"
Height="420" Width="640"
WindowStartupLocation="CenterOwner"
Background="#181824"
@@ -77,7 +77,7 @@
<Border Background="#20202E" BorderBrush="{StaticResource BorderColor}" BorderThickness="1" CornerRadius="8" Padding="14" Margin="0,0,0,14">
<StackPanel>
<TextBlock Text="📦 RGSS Extractor のパス (ツクールVX / VX Ace用)" FontSize="13" FontWeight="Bold" Foreground="#A29BFE"/>
<TextBlock Text="ツクールVXおよびVX Aceの暗号化アーカイブ (*.rgss3a / *.rgss2a) の解凍・抽出に使用する外部ツールのパスを設定します。"
<TextBlock Text="ツクールVXおよびVX Aceの暗号化アーカイブ (*.rgss3a / *.rgss2a) の解凍・抽出に使用する外部ツールのパスを設定します。"
FontSize="11" Foreground="{StaticResource TextSecondary}" TextWrapping="Wrap" Margin="0,3,0,10"/>
<Grid>
@@ -86,7 +86,7 @@
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="txtRgssExtractorPath" Grid.Column="0" Background="#14141C" Foreground="#FFFFFF"
<TextBox x:Name="txtRgssExtractorPath" Grid.Column="0" Background="#14141C" Foreground="#FFFFFF"
BorderBrush="{StaticResource BorderColor}" BorderThickness="1" Padding="8,6" FontSize="12"/>
<Button Grid.Column="2" Style="{StaticResource ModernButton}" Content="📁 参照..." Click="btnBrowseExtractor_Click"/>
</Grid>
@@ -97,7 +97,7 @@
<Border Background="#20202E" BorderBrush="{StaticResource BorderColor}" BorderThickness="1" CornerRadius="8" Padding="14" Margin="0,0,0,14">
<StackPanel>
<TextBlock Text="🐺 Wolf RPG アーカイブ解凍ツールのパス (Data.wolf 解凍用)" FontSize="13" FontWeight="Bold" Foreground="#3B3B98"/>
<TextBlock Text="WOLF RPGエディターの暗号化アーカイブ (*.wolf) の解凍・抽出に使用するツールのパスを設定します(未指定時は内蔵ツール Tools\UberWolfCli.exe が自動使用されます)。"
<TextBlock Text="WOLF RPGエディターの暗号化アーカイブ (*.wolf) の解凍・抽出に使用するツールのパスを設定します(未指定時は内蔵ツール Tools\UberWolfCli.exe が自動使用されます)。"
FontSize="11" Foreground="{StaticResource TextSecondary}" TextWrapping="Wrap" Margin="0,3,0,10"/>
<Grid>
@@ -106,7 +106,7 @@
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="txtWolfExtractorPath" Grid.Column="0" Background="#14141C" Foreground="#FFFFFF"
<TextBox x:Name="txtWolfExtractorPath" Grid.Column="0" Background="#14141C" Foreground="#FFFFFF"
BorderBrush="{StaticResource BorderColor}" BorderThickness="1" Padding="8,6" FontSize="12"/>
<Button Grid.Column="2" Style="{StaticResource ModernButton}" Content="📁 参照..." Click="btnBrowseWolfExtractor_Click"/>
</Grid>
@@ -117,7 +117,7 @@
<Border Background="#20202E" BorderBrush="{StaticResource BorderColor}" BorderThickness="1" CornerRadius="8" Padding="14" Margin="0,0,0,14">
<StackPanel>
<TextBlock Text="🖥 ウィンドウ拡大用 外部ツールのパス (ツクールVX / VX Ace用)" FontSize="13" FontWeight="Bold" Foreground="#FDCB6E"/>
<TextBlock Text="ゲームウィンドウを拡大する外部ツール(Sizer等)の実行ファイルパスを設定します。未指定の場合、ランチャー内蔵のWin32 API方式で拡大します。"
<TextBlock Text="ゲームウィンドウを拡大する外部ツール(Sizer等)の実行ファイルパスを設定します。未指定の場合、ランチャー内蔵のWin32 API方式で拡大します。"
FontSize="11" Foreground="{StaticResource TextSecondary}" TextWrapping="Wrap" Margin="0,3,0,10"/>
<Grid>
@@ -126,7 +126,7 @@
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="txtWindowResizeToolPath" Grid.Column="0" Background="#14141C" Foreground="#FFFFFF"
<TextBox x:Name="txtWindowResizeToolPath" Grid.Column="0" Background="#14141C" Foreground="#FFFFFF"
BorderBrush="{StaticResource BorderColor}" BorderThickness="1" Padding="8,6" FontSize="12"/>
<Button Grid.Column="2" Style="{StaticResource ModernButton}" Content="📁 参照..." Click="btnBrowseWindowResizeTool_Click"/>
</Grid>
@@ -137,7 +137,7 @@
<Border Background="#20202E" BorderBrush="{StaticResource BorderColor}" BorderThickness="1" CornerRadius="8" Padding="14" Margin="0,0,0,14">
<StackPanel>
<TextBlock Text="📦 バックアップ統一保存先" FontSize="13" FontWeight="Bold" Foreground="#00B894"/>
<TextBlock Text="ツクールMV/MZ・ティラノ・ツクールVX/VX Ace・Unityのすべてのバックアップは、exe直下のBackupsフォルダ(Z:\自作ソフト\GameLauncher\Backups)に集約されます。"
<TextBlock Text="ツクールMV/MZ・ティラノ・ツクールVX/VX Ace・Unityのすべてのバックアップは、exe直下のBackupsフォルダ(Z:\自作ソフト\GameLauncher\Backups)に集約されます。"
FontSize="11" Foreground="{StaticResource TextSecondary}" TextWrapping="Wrap" Margin="0,3,0,10"/>
<Grid>
@@ -146,7 +146,7 @@
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="txtBackupsPath" Grid.Column="0" Background="#14141C" Foreground="#81ECEC"
<TextBox x:Name="txtBackupsPath" Grid.Column="0" Background="#14141C" Foreground="#81ECEC"
BorderBrush="{StaticResource BorderColor}" BorderThickness="1" Padding="8,6" FontSize="12" IsReadOnly="True"/>
<Button Grid.Column="2" Style="{StaticResource ModernButton}" Content="📂 フォルダを開く" Click="btnOpenBackupsDir_Click"/>
</Grid>
@@ -156,9 +156,9 @@
<!-- 3. デフォルト起動時改造適用 -->
<Border Background="#20202E" BorderBrush="{StaticResource BorderColor}" BorderThickness="1" CornerRadius="8" Padding="14">
<StackPanel>
<CheckBox x:Name="chkDefaultApplyMod" Content="一度も変更していないゲームにおける「起動時に改造を適用する」の初期値をONにする"
<CheckBox x:Name="chkDefaultApplyMod" Content="一度も変更していないゲームにおける「起動時に改造を適用する」の初期値をONにする"
FontSize="12" FontWeight="SemiBold" Foreground="#FFFFFF"/>
<TextBlock Text="新規検出されたゲームにおいて、初期状態でスクリプト改造を有効にするかどうかを設定します。"
<TextBlock Text="新規検出されたゲームにおいて、初期状態でスクリプト改造を有効にするかどうかを設定します。"
FontSize="11" Foreground="{StaticResource TextSecondary}" Margin="24,4,0,0"/>
</StackPanel>
</Border>
+23 -23
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
@@ -19,14 +19,14 @@ namespace GameLauncher
public ConfigDialog(LauncherConfig config)
{
InitializeComponent();
_config = config;
this.InitializeComponent();
this._config = config;
txtRgssExtractorPath.Text = _config.RgssExtractorPath ?? @"C:\Soft\RGSS-Extractor-v1.0\RGSS Extractor.exe";
txtWolfExtractorPath.Text = _config.WolfExtractorPath ?? string.Empty;
txtWindowResizeToolPath.Text = _config.WindowResizeToolPath ?? string.Empty;
txtBackupsPath.Text = AppPathHelper.GetBackupsDirectory();
chkDefaultApplyMod.IsChecked = _config.DefaultApplyMod;
this.txtRgssExtractorPath.Text = this._config.RgssExtractorPath ?? @"C:\Soft\RGSS-Extractor-v1.0\RGSS Extractor.exe";
this.txtWolfExtractorPath.Text = this._config.WolfExtractorPath ?? string.Empty;
this.txtWindowResizeToolPath.Text = this._config.WindowResizeToolPath ?? string.Empty;
this.txtBackupsPath.Text = AppPathHelper.GetBackupsDirectory();
this.chkDefaultApplyMod.IsChecked = this._config.DefaultApplyMod;
}
private void btnBrowseExtractor_Click(object sender, RoutedEventArgs e)
@@ -38,7 +38,7 @@ namespace GameLauncher
FileName = "RGSS Extractor.exe"
};
var currentDir = Path.GetDirectoryName(txtRgssExtractorPath.Text);
var currentDir = Path.GetDirectoryName(this.txtRgssExtractorPath.Text);
if (!string.IsNullOrEmpty(currentDir) && Directory.Exists(currentDir))
{
ofd.InitialDirectory = currentDir;
@@ -46,7 +46,7 @@ namespace GameLauncher
if (ofd.ShowDialog() == true)
{
txtRgssExtractorPath.Text = ofd.FileName;
this.txtRgssExtractorPath.Text = ofd.FileName;
}
}
@@ -59,7 +59,7 @@ namespace GameLauncher
FileName = "UberWolfCli.exe"
};
var currentDir = Path.GetDirectoryName(txtWolfExtractorPath.Text);
var currentDir = Path.GetDirectoryName(this.txtWolfExtractorPath.Text);
if (!string.IsNullOrEmpty(currentDir) && Directory.Exists(currentDir))
{
ofd.InitialDirectory = currentDir;
@@ -67,7 +67,7 @@ namespace GameLauncher
if (ofd.ShowDialog() == true)
{
txtWolfExtractorPath.Text = ofd.FileName;
this.txtWolfExtractorPath.Text = ofd.FileName;
}
}
@@ -80,7 +80,7 @@ namespace GameLauncher
FileName = "Sizer.exe"
};
var currentDir = Path.GetDirectoryName(txtWindowResizeToolPath.Text);
var currentDir = Path.GetDirectoryName(this.txtWindowResizeToolPath.Text);
if (!string.IsNullOrEmpty(currentDir) && Directory.Exists(currentDir))
{
ofd.InitialDirectory = currentDir;
@@ -88,7 +88,7 @@ namespace GameLauncher
if (ofd.ShowDialog() == true)
{
txtWindowResizeToolPath.Text = ofd.FileName;
this.txtWindowResizeToolPath.Text = ofd.FileName;
}
}
@@ -111,19 +111,19 @@ namespace GameLauncher
private void btnSave_Click(object sender, RoutedEventArgs e)
{
_config.RgssExtractorPath = txtRgssExtractorPath.Text.Trim();
_config.WolfExtractorPath = txtWolfExtractorPath.Text.Trim();
_config.WindowResizeToolPath = txtWindowResizeToolPath.Text.Trim();
_config.DefaultApplyMod = chkDefaultApplyMod.IsChecked == true;
IsSaved = true;
DialogResult = true;
Close();
this._config.RgssExtractorPath = this.txtRgssExtractorPath.Text.Trim();
this._config.WolfExtractorPath = this.txtWolfExtractorPath.Text.Trim();
this._config.WindowResizeToolPath = this.txtWindowResizeToolPath.Text.Trim();
this._config.DefaultApplyMod = this.chkDefaultApplyMod.IsChecked == true;
this.IsSaved = true;
this.DialogResult = true;
this.Close();
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
DialogResult = false;
Close();
this.DialogResult = false;
this.Close();
}
}
}
+2 -3
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.IO;
namespace GameLauncher.Engines.Common
@@ -136,8 +136,7 @@ namespace GameLauncher.Engines.Common
return EngineTkool;
}
var packageJson = Path.Combine(gameDirectory, "package.json");
if (File.Exists(packageJson) && Directory.Exists(Path.Combine(gameDirectory, "nwjs")))
if (Engines.Nwjs.NwjsDetector.IsNwjsGame(gameDirectory))
{
return EngineNwjs;
}
+1 -1
View File
@@ -1,4 +1,4 @@
using GameLauncher.Models;
using GameLauncher.Models;
namespace GameLauncher.Engines.Common
{
+153 -73
View File
@@ -1,43 +1,40 @@
using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace GameLauncher.Engines.Evb
{
/// <summary>
/// Detects Enigma Virtual Box (EVB) packed executables using reliable PE signatures
/// only. Heuristic checks such as file name or extension are intentionally avoided so
/// that ordinary (unpacked) games are never misclassified.
/// Detects Enigma Virtual Box (EVB) packed executables that are actually compressed
/// with EVB and unpackable by <c>evbunpack</c>.
///
/// Detection strategy:
/// 1. Parse the PE header and inspect the section table for the packer's sections
/// (".enigma1" / ".enigma2"). A present section is a decisive match.
/// 2. When sections are inconclusive, scan bounded windows of the file for the
/// "Enigma Virtual Box" marker string embedded by the packer.
/// 1. Parse the PE header and inspect the section table for the packer's
/// <c>.enigma1</c> section (required by <c>evbunpack</c> to restore the PE).
/// 2. Verify the presence of the EVB virtual filesystem pack header signature
/// (<c>"EVB\0"</c> / <c>0x45, 0x56, 0x42, 0x00</c>) inside the Enigma section
/// data or PE overlay (required by <c>evbunpack</c> to extract the VFS, and
/// distinguishes Enigma Virtual Box from commercial Enigma Protector DRM which
/// cannot be unpacked).
///
/// This class is engine-local and has no side effects.
/// </summary>
public static class EvbDetectionHelper
{
/// <summary>Marker string embedded by the Enigma Virtual Box packer.</summary>
private const string EnigmaMarker = "Enigma Virtual Box";
/// <summary>Primary section name required by evbunpack.</summary>
private const string EnigmaPrimarySection = ".enigma1";
/// <summary>Section names produced by the packer.</summary>
private static readonly string[] EnigmaSections = { ".enigma1", ".enigma2" };
/// <summary>Secondary section name produced by the packer.</summary>
private const string EnigmaSecondarySection = ".enigma2";
/// <summary>Additional loader identifiers checked during the content scan.</summary>
private static readonly string[] EvbContentMarkers =
{
EnigmaMarker,
"evb.dll",
"EnigmaVB",
};
/// <summary>EVB virtual filesystem header magic ("EVB\0").</summary>
private static readonly byte[] EvbMagic = [0x45, 0x56, 0x42, 0x00];
/// <summary>Returns true when the given executable is packed with EVB.</summary>
/// <summary>Returns true when the given executable is packed with EVB and can be unpacked.</summary>
/// <remarks>
/// Step 1 reads the PE section table for the packer's section names.
/// Step 2 falls back to a bounded content scan for the packer marker.
/// Any IO/format error yields false (treated as "not confidently EVB").
/// Reads the PE section table for <c>.enigma1</c> and verifies the <c>EVB\0</c>
/// virtual filesystem header. Any IO/format error yields false.
/// </remarks>
public static bool IsEvbPacked(string exePath)
{
@@ -48,24 +45,11 @@ namespace GameLauncher.Engines.Evb
try
{
// Step 1: decisive PE section check.
if (HasEnigmaSection(exePath))
{
return true;
}
}
catch
{
// Fall through to the content scan on any parse failure.
}
try
{
// Step 2: content marker scan over bounded windows.
return ContainsEvbContentMarker(exePath);
return HasExtractableEnigmaPackage(exePath);
}
catch
{
// Unparseable executable -> never claim EVB.
return false;
}
}
@@ -83,8 +67,11 @@ namespace GameLauncher.Engines.Evb
try
{
return Directory.GetFiles(gameDirectory, "*.exe", SearchOption.TopDirectoryOnly)
.FirstOrDefault(IsEvbPacked);
var exes = Directory.GetFiles(gameDirectory, "*.exe", SearchOption.TopDirectoryOnly)
.Where(f => !IsExcludedUtilityExe(Path.GetFileName(f)))
.OrderBy(f => string.Equals(Path.GetFileName(f), "Game.exe", StringComparison.OrdinalIgnoreCase) ? 0 : 1);
return exes.FirstOrDefault(IsEvbPacked);
}
catch
{
@@ -92,10 +79,49 @@ namespace GameLauncher.Engines.Evb
}
}
private static bool IsExcludedUtilityExe(string fileName)
{
if (string.IsNullOrEmpty(fileName)) return true;
return fileName.StartsWith("unins", StringComparison.OrdinalIgnoreCase) ||
fileName.StartsWith("UnityCrashHandler", StringComparison.OrdinalIgnoreCase) ||
fileName.Equals("notification_helper.exe", StringComparison.OrdinalIgnoreCase) ||
fileName.Equals("crashpad_handler.exe", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Parses the PE section table and checks for the EVB packer's section names.
/// Returns true when the game directory already holds a completed EVB extraction.
///
/// Once a game is unpacked, the original packed exe is renamed to "*.glbak" and the
/// unpacked files (including the real exe) live inside the game-local "_evb_extracted"
/// folder. At that point <see cref="FindEvbPackedExecutable"/> can no longer find a
/// top-level "*.exe", so this extra signal is required to keep recognizing the folder
/// as an EVB game (otherwise launch and icon resolution break after unpacking).
///
/// Only a completed extraction (completion marker present) is accepted, so a normal
/// unpacked game without any EVB artifacts is never misclassified.
/// </summary>
private static bool HasEnigmaSection(string exePath)
public static bool IsExtracted(string gameDirectory)
{
if (string.IsNullOrWhiteSpace(gameDirectory) || !Directory.Exists(gameDirectory))
{
return false;
}
try
{
return EvbUnpackService.IsExtractionComplete(gameDirectory, out _);
}
catch
{
return false;
}
}
/// <summary>
/// Parses the PE section table, verifies the <c>.enigma1</c> section, and checks
/// for the <c>EVB\0</c> virtual filesystem header required by <c>evbunpack</c>.
/// </summary>
private static bool HasExtractableEnigmaPackage(string exePath)
{
using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using var reader = new BinaryReader(fs);
@@ -124,22 +150,30 @@ namespace GameLauncher.Engines.Evb
return false;
}
// COFF header: skip machine + number of sections is at offset 2 from here.
fs.Seek(peOffset + 4, SeekOrigin.Begin);
// COFF header: number of sections is at offset 6 from PE signature (peOffset + 6).
fs.Seek(peOffset + 6, SeekOrigin.Begin);
ushort sectionCount = reader.ReadUInt16();
if (sectionCount == 0 || sectionCount > 96)
{
return false;
}
// Optional header size (end of the optional header) is at offset 20 in the COFF header.
// Optional header size is at offset 20 in the COFF header.
fs.Seek(peOffset + 20, SeekOrigin.Begin);
ushort optionalHeaderSize = reader.ReadUInt16();
// Section table starts right after the optional header.
long sectionTable = peOffset + 24 + optionalHeaderSize;
// Each section header is 40 bytes; the section name is the first 8 bytes.
bool hasEnigma1 = false;
var enigmaRanges = new List<(long Offset, long Size)>();
long maxSectionEnd = 0;
// Each section header is 40 bytes.
for (int i = 0; i < sectionCount; i++)
{
long offset = sectionTable + (long)i * 40;
if (offset + 8 > fs.Length)
if (offset + 40 > fs.Length)
{
break;
}
@@ -148,54 +182,100 @@ namespace GameLauncher.Engines.Evb
var nameBytes = reader.ReadBytes(8);
var name = System.Text.Encoding.ASCII.GetString(nameBytes).TrimEnd('\0').Trim();
foreach (var section in EnigmaSections)
fs.Seek(offset + 16, SeekOrigin.Begin);
uint rawSize = reader.ReadUInt32();
uint rawPtr = reader.ReadUInt32();
if (rawPtr > 0 && rawSize > 0)
{
if (string.Equals(name, section, StringComparison.OrdinalIgnoreCase))
long end = (long)rawPtr + rawSize;
if (end > maxSectionEnd && end <= fs.Length)
{
return true;
maxSectionEnd = end;
}
}
if (string.Equals(name, EnigmaPrimarySection, StringComparison.OrdinalIgnoreCase))
{
hasEnigma1 = true;
if (rawPtr > 0 && rawSize > 0 && rawPtr < fs.Length)
{
enigmaRanges.Insert(0, (rawPtr, Math.Min((long)rawSize, fs.Length - rawPtr)));
}
}
else if (string.Equals(name, EnigmaSecondarySection, StringComparison.OrdinalIgnoreCase))
{
if (rawPtr > 0 && rawSize > 0 && rawPtr < fs.Length)
{
enigmaRanges.Add((rawPtr, Math.Min((long)rawSize, fs.Length - rawPtr)));
}
}
}
// evbunpack requires the .enigma1 section to unpack and rebuild the executable.
if (!hasEnigma1)
{
return false;
}
// Also include PE overlay if any bytes exist after the last section.
if (maxSectionEnd > 0 && maxSectionEnd + 64 <= fs.Length)
{
enigmaRanges.Add((maxSectionEnd, fs.Length - maxSectionEnd));
}
// Verify that the EVB virtual filesystem signature ("EVB\0") exists in the
// Enigma sections or overlay so that Enigma Protector DRM executables (which
// have .enigma1/.enigma2 but no unpackable EVB VFS) are not misclassified.
foreach (var (rangeOffset, rangeSize) in enigmaRanges)
{
if (ContainsEvbMagicInRange(fs, rangeOffset, rangeSize))
{
return true;
}
}
return false;
}
/// <summary>
/// Scans bounded windows of the executable for EVB loader markers.
/// EVB metadata typically sits near the end of the PE (overlay).
/// Searches for the "EVB\0" pack header signature within the given file range
/// (scanning up to the first 16 MB of the range in 64 KB chunks).
/// </summary>
private static bool ContainsEvbContentMarker(string exePath)
private static bool ContainsEvbMagicInRange(FileStream fs, long startOffset, long length)
{
const int windowSize = 2 * 1024 * 1024;
using var fs = new FileStream(exePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
long size = fs.Length;
if (size < 1024)
const int chunkSize = 64 * 1024;
long maxScan = Math.Min(length, 16L * 1024 * 1024);
if (maxScan < EvbMagic.Length)
{
return false;
}
double[] fractions = { 0.5, 0.8, 0.9, 0.97 };
foreach (var frac in fractions)
var buffer = new byte[chunkSize + EvbMagic.Length];
long scanned = 0;
while (scanned < maxScan)
{
long start = (long)(size * frac);
int readLen = (int)Math.Min(windowSize, size - start);
if (readLen <= 0)
long readPos = startOffset + scanned;
int toRead = (int)Math.Min(buffer.Length, (startOffset + maxScan) - readPos);
if (toRead < EvbMagic.Length)
{
continue;
break;
}
var buf = new byte[readLen];
fs.Seek(start, SeekOrigin.Begin);
int read = fs.Read(buf, 0, buf.Length);
var text = System.Text.Encoding.ASCII.GetString(buf, 0, read);
foreach (var marker in EvbContentMarkers)
fs.Seek(readPos, SeekOrigin.Begin);
int read = fs.Read(buffer, 0, toRead);
if (read < EvbMagic.Length)
{
if (text.IndexOf(marker, StringComparison.OrdinalIgnoreCase) >= 0)
{
return true;
}
break;
}
if (buffer.AsSpan(0, read).IndexOf(EvbMagic) >= 0)
{
return true;
}
scanned += chunkSize;
}
return false;
+14 -14
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.IO;
using GameLauncher.Engines.Common;
@@ -18,9 +18,16 @@ namespace GameLauncher.Engines.Evb
public static class EvbDetector
{
/// <summary>
/// Returns true when the game directory holds an EVB packed executable.
/// A packed project file (<c>*.evb</c>) in the folder is also accepted as a
/// decisive signal, in addition to the PE-signature check.
/// Returns true when the game directory holds an EVB packed executable
/// that can actually be unpacked (or a completed extraction of one).
///
/// Accepts only the following decisive signals:
/// 1. A top-level executable carrying both a decisive EVB PE section (.enigma1)
/// and the EVB virtual filesystem signature ("EVB\0"), so it is unpackable.
/// 2. An already-unpacked game (game-local "_evb_extracted" with a completion
/// marker). This is required because unpacking renames the original packed exe
/// to "*.glbak", after which the signature check alone would no longer detect
/// the game and its launch / icon resolution would break.
/// </summary>
public static bool IsEvbGame(string gameDirectory)
{
@@ -29,17 +36,10 @@ namespace GameLauncher.Engines.Evb
return false;
}
try
// A completed extraction keeps the game recognized even without the packed exe.
if (EvbDetectionHelper.IsExtracted(gameDirectory))
{
// A packed project file in the folder is the strongest single signal.
if (Directory.GetFiles(gameDirectory, "*.evb", SearchOption.TopDirectoryOnly).Length > 0)
{
return true;
}
}
catch
{
// Fall through to the executable signature check.
return true;
}
return EvbDetectionHelper.FindEvbPackedExecutable(gameDirectory) != null;
+2 -2
View File
@@ -1,4 +1,4 @@
using System;
using System;
using GameLauncher.Engines.Common;
using GameLauncher.Models;
@@ -34,7 +34,7 @@ namespace GameLauncher.Engines.Evb
/// <inheritdoc />
public string ResolveToolPath(string toolFileName)
=> AppPathHelperBridge.Resolve(EngineName, toolFileName);
=> AppPathHelperBridge.Resolve(this.EngineName, toolFileName);
}
/// <summary>
+3 -3
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
@@ -79,7 +79,7 @@ namespace GameLauncher.Engines.Evb
try
{
// Preferred names commonly used by NW.js / RPG Maker / Tyrano bundles.
string[] preferred = { "Game.exe", "game.exe", "nw.exe", "Game_boxed.exe" };
string[] preferred = ["Game.exe", "game.exe", "nw.exe", "Game_boxed.exe"];
foreach (var name in preferred)
{
var direct = Path.Combine(outputDirectory, name);
@@ -302,7 +302,7 @@ namespace GameLauncher.Engines.Evb
{
foreach (var backup in Directory.GetFiles(gameRootDir, "*" + ExeBackupSuffix))
{
var original = backup.Substring(0, backup.Length - ExeBackupSuffix.Length);
var original = backup[..^ExeBackupSuffix.Length];
if (!File.Exists(original))
{
File.Move(backup, original);
+1 -1
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
+1 -1
View File
@@ -1,4 +1,4 @@
Apache License
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
+1 -1
View File
@@ -1,4 +1,4 @@
# evbunpack (bundled tool)
# evbunpack (bundled tool)
`evbunpack.exe` is a bundled, third-party unpacker used by the **Evb** engine module to
unpack applications protected with **Enigma Virtual Box**.
+18 -20
View File
@@ -170,7 +170,7 @@ namespace GameLauncher.Engines.Nwjs
long packageJsonOffset = -1;
long packageJsonSize = -1;
TraverseFiles(filesRoot, "", dataOffset, fs.Length, result, includeFileList,
this.TraverseFiles(filesRoot, "", dataOffset, fs.Length, result, includeFileList,
ref systemJsonRelative, ref systemJsonOffset, ref systemJsonSize,
ref packageJsonRelative, ref packageJsonOffset, ref packageJsonSize);
@@ -274,7 +274,7 @@ namespace GameLauncher.Engines.Nwjs
if (val.TryGetProperty("files", out var subFiles))
{
TraverseFiles(subFiles, path, dataOffset, fileLength, result, includeFileList,
this.TraverseFiles(subFiles, path, dataOffset, fileLength, result, includeFileList,
ref systemJsonRelative, ref systemJsonOffset, ref systemJsonSize,
ref packageJsonRelative, ref packageJsonOffset, ref packageJsonSize);
}
@@ -349,7 +349,7 @@ namespace GameLauncher.Engines.Nwjs
systemJsonOffset = offset;
systemJsonSize = size;
}
else if (name.Equals("package.json", StringComparison.OrdinalIgnoreCase) &&
else if (name.Equals("package.json", StringComparison.OrdinalIgnoreCase) &&
!path.Contains("node_modules", StringComparison.OrdinalIgnoreCase))
{
// ルートの package.json または project/package.json を最優先
@@ -395,7 +395,7 @@ namespace GameLauncher.Engines.Nwjs
// UNC パス (例: \\server\share\...) の場合
if (normalized.StartsWith(@"\\", StringComparison.Ordinal))
{
return @"\\?\UNC\" + normalized.Substring(2);
return @"\\?\UNC\" + normalized[2..];
}
// 相対パスの場合は安全に絶対パスを取得してからプレフィックスを付与
@@ -408,7 +408,7 @@ namespace GameLauncher.Engines.Nwjs
}
if (full.StartsWith(@"\\", StringComparison.Ordinal))
{
return @"\\?\UNC\" + full.Substring(2);
return @"\\?\UNC\" + full[2..];
}
return @"\\?\" + full;
}
@@ -447,7 +447,7 @@ namespace GameLauncher.Engines.Nwjs
}
// ヘッダ詳細解析
var inspect = InspectAsar(targetAsar, includeFileList: true);
var inspect = this.InspectAsar(targetAsar, includeFileList: true);
if (!inspect.IsValid || inspect.FileEntries.Count == 0)
{
return (false, "asar ファイルのヘッダ解析に失敗したか、ファイルが含まれていません。");
@@ -503,20 +503,18 @@ namespace GameLauncher.Engines.Nwjs
fs.Seek(dataOffset + entry.Offset, SeekOrigin.Begin);
long remaining = entry.Size;
using (var outFs = new FileStream(destFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
using var outFs = new FileStream(destFilePath, FileMode.Create, FileAccess.Write, FileShare.None);
while (remaining > 0)
{
while (remaining > 0)
{
int toRead = (int)Math.Min(remaining, buffer.Length);
int read = fs.Read(buffer, 0, toRead);
if (read == 0) break;
int toRead = (int)Math.Min(remaining, buffer.Length);
int read = fs.Read(buffer, 0, toRead);
if (read == 0) break;
outFs.Write(buffer, 0, read);
remaining -= read;
extractedBytes += read;
outFs.Write(buffer, 0, read);
remaining -= read;
extractedBytes += read;
progress?.Report((extractedBytes, totalBytes, i + 1, totalFiles, Path.GetFileName(entry.RelativePath)));
}
progress?.Report((extractedBytes, totalBytes, i + 1, totalFiles, Path.GetFileName(entry.RelativePath)));
}
}
catch (Exception fileEx)
@@ -568,12 +566,12 @@ namespace GameLauncher.Engines.Nwjs
{
return await Task.Run(() =>
{
var backupAsar = asarPath.EndsWith(AsarBackupSuffix, StringComparison.OrdinalIgnoreCase)
? asarPath
var backupAsar = asarPath.EndsWith(AsarBackupSuffix, StringComparison.OrdinalIgnoreCase)
? asarPath
: asarPath + AsarBackupSuffix;
var originalAsar = asarPath.EndsWith(AsarBackupSuffix, StringComparison.OrdinalIgnoreCase)
? asarPath.Substring(0, asarPath.Length - AsarBackupSuffix.Length)
? asarPath[..^AsarBackupSuffix.Length]
: asarPath;
string extExtractedDir = ToExtendedPath(extractedDir);
+332
View File
@@ -0,0 +1,332 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Windows.Media;
using GameLauncher.Engines.Common;
using GameLauncher.Engines.Tkool;
using GameLauncher.Engines.Unity;
using GameLauncher.Models;
namespace GameLauncher.Engines.Nwjs
{
/// <summary>
/// 汎用 NW.js (Node-Webkit) アプリケーション/ゲームの検出およびアイテム生成を行うヘルパークラス
/// </summary>
public static class NwjsDetector
{
private static readonly HashSet<string> ExcludedExeNames = new(StringComparer.OrdinalIgnoreCase)
{
"notification_helper.exe",
"crashpad_handler.exe",
"elevate.exe"
};
/// <summary>
/// 指定されたディレクトリが汎用 NW.js ゲームであるかを判定します。
/// ツクール(MV/MZ/RGSS)、ティラノスクリプト、ウディタ、SRPG Studio など既存エンジン形式は除外します。
/// </summary>
/// <param name="dirPath">対象ディレクトリパス</param>
/// <returns>NW.js ゲームであれば true</returns>
public static bool IsNwjsGame(string dirPath)
{
try
{
if (string.IsNullOrWhiteSpace(dirPath) || !Directory.Exists(dirPath))
{
return false;
}
var packageJsonPath = Path.Combine(dirPath, "package.json");
if (!File.Exists(packageJsonPath))
{
return false;
}
// 既存の他エンジン判定(ツクール・ティラノ・ウディタ・SRPG)を最優先で除外
if (Directory.Exists(Path.Combine(dirPath, "www")) ||
File.Exists(Path.Combine(dirPath, "data", "System.json")) ||
File.Exists(Path.Combine(dirPath, "Game.ini")) ||
Directory.Exists(Path.Combine(dirPath, "tyrano")) ||
Directory.GetFiles(dirPath, "*.tjs", SearchOption.TopDirectoryOnly).Length > 0 ||
Directory.GetFiles(dirPath, "*.wolf", SearchOption.TopDirectoryOnly).Length > 0 ||
File.Exists(Path.Combine(dirPath, "data.dts")))
{
return false;
}
// NW.js の痕跡を確認
if (File.Exists(Path.Combine(dirPath, "nw.dll")) ||
File.Exists(Path.Combine(dirPath, "nw.exe")) ||
File.Exists(Path.Combine(dirPath, "resources.pak")) ||
File.Exists(Path.Combine(dirPath, "node.dll")) ||
Directory.Exists(Path.Combine(dirPath, "nwjs")))
{
return true;
}
// package.json に main や window 記述があるか確認
if (TryReadPackageJson(dirPath, out _, out _, out var main, out _))
{
if (!string.IsNullOrWhiteSpace(main) && File.Exists(Path.Combine(dirPath, main)))
{
return true;
}
}
}
catch
{
return false;
}
return false;
}
/// <summary>
/// 指定ディレクトリ内の NW.js ゲームを検出し、TkoolGameItem を生成します。
/// </summary>
/// <param name="dirPath">ゲームフォルダの絶対パス</param>
/// <param name="folderName">フォルダ名</param>
/// <param name="folderModified">フォルダ更新日時</param>
/// <param name="iconLoader">アイコン読み込み関数</param>
/// <returns>検出されたゲームアイテム。該当しない場合は null</returns>
public static TkoolGameItem? DetectNwjsGame(
string dirPath,
string folderName,
DateTime? folderModified,
Func<string?, string?, ImageSource?> iconLoader)
{
try
{
if (!IsNwjsGame(dirPath))
{
return null;
}
TryReadPackageJson(dirPath, out var windowTitle, out var packageName, out var mainFile, out var iconRelPath);
// タイトルの決定: window.title > index.html の <title> > package.json の name > フォルダ名
string title = string.Empty;
if (!string.IsNullOrWhiteSpace(windowTitle))
{
title = windowTitle.Trim();
}
if (string.IsNullOrWhiteSpace(title))
{
var htmlPath = !string.IsNullOrWhiteSpace(mainFile)
? Path.Combine(dirPath, mainFile)
: Path.Combine(dirPath, "index.html");
title = ExtractHtmlTitle(htmlPath);
}
if (string.IsNullOrWhiteSpace(title) && !string.IsNullOrWhiteSpace(packageName))
{
title = packageName.Trim();
}
if (string.IsNullOrWhiteSpace(title))
{
title = folderName;
}
// 実行ファイルの探索
var exePath = FindNwjsExecutable(dirPath, title, packageName);
// アイコンの取得
ImageSource? icon = null;
if (iconLoader != null)
{
icon = iconLoader(exePath, dirPath);
}
return new TkoolGameItem
{
Title = title,
FolderName = folderName,
RootDirectory = dirPath,
ExecutablePath = exePath ?? string.Empty,
PluginsJsPath = string.Empty,
PluginsDirPath = string.Empty,
EngineType = TkoolEngineType.Nwjs,
IsModded = false,
ApplyMod = false,
IconImage = icon,
FolderLastModified = folderModified
};
}
catch
{
return null;
}
}
/// <summary>
/// NW.js ゲーム用の実行可能ファイル(.exe)を探索します。
/// notification_helper.exe などの Chromium 内部ユーティリティを除外し、ゲーム本体の exe を特定します。
/// </summary>
/// <param name="dirPath">ディレクトリパス</param>
/// <param name="title">ゲームタイトル</param>
/// <param name="packageName">package.json の name</param>
/// <returns>実行ファイルのパス。見つからない場合は null</returns>
public static string? FindNwjsExecutable(string dirPath, string? title, string? packageName)
{
try
{
var exes = Directory.GetFiles(dirPath, "*.exe", SearchOption.TopDirectoryOnly)
.Where(f =>
{
var fileName = Path.GetFileName(f);
if (fileName.StartsWith("unins", StringComparison.OrdinalIgnoreCase))
{
return false;
}
if (ExcludedExeNames.Contains(fileName))
{
return false;
}
return true;
})
.ToList();
if (exes.Count == 0)
{
return null;
}
if (exes.Count == 1)
{
return exes[0];
}
// 優先度1: タイトル名またはパッケージ名が含まれる実行ファイル
if (!string.IsNullOrWhiteSpace(title))
{
var match = exes.FirstOrDefault(f => Path.GetFileNameWithoutExtension(f).Contains(title, StringComparison.OrdinalIgnoreCase));
if (match != null)
{
return match;
}
}
if (!string.IsNullOrWhiteSpace(packageName))
{
var match = exes.FirstOrDefault(f => Path.GetFileNameWithoutExtension(f).Contains(packageName, StringComparison.OrdinalIgnoreCase));
if (match != null)
{
return match;
}
}
// 優先度2: Game.exe または nw.exe
var gameExe = exes.FirstOrDefault(f => string.Equals(Path.GetFileName(f), "Game.exe", StringComparison.OrdinalIgnoreCase));
if (gameExe != null)
{
return gameExe;
}
var nwExe = exes.FirstOrDefault(f => string.Equals(Path.GetFileName(f), "nw.exe", StringComparison.OrdinalIgnoreCase));
if (nwExe != null)
{
return nwExe;
}
// 優先度3: 候補の先頭
return exes[0];
}
catch
{
return null;
}
}
/// <summary>
/// package.json を読み込み、主要な設定値を抽出します。
/// </summary>
private static bool TryReadPackageJson(
string dirPath,
out string? windowTitle,
out string? name,
out string? main,
out string? iconRelPath)
{
windowTitle = null;
name = null;
main = null;
iconRelPath = null;
try
{
var packageJsonPath = Path.Combine(dirPath, "package.json");
if (!File.Exists(packageJsonPath))
{
return false;
}
var json = File.ReadAllText(packageJsonPath);
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
if (root.TryGetProperty("name", out var nameProp) && nameProp.ValueKind == JsonValueKind.String)
{
name = nameProp.GetString();
}
if (root.TryGetProperty("main", out var mainProp) && mainProp.ValueKind == JsonValueKind.String)
{
main = mainProp.GetString();
}
if (root.TryGetProperty("window", out var winProp) && winProp.ValueKind == JsonValueKind.Object)
{
if (winProp.TryGetProperty("title", out var titleProp) && titleProp.ValueKind == JsonValueKind.String)
{
windowTitle = titleProp.GetString();
}
if (winProp.TryGetProperty("icon", out var iconProp) && iconProp.ValueKind == JsonValueKind.String)
{
iconRelPath = iconProp.GetString();
}
}
return true;
}
catch
{
return false;
}
}
/// <summary>
/// HTML ファイルから title タグのテキストを抽出します。
/// </summary>
private static string ExtractHtmlTitle(string htmlPath)
{
try
{
if (!File.Exists(htmlPath))
{
return string.Empty;
}
var html = File.ReadAllText(htmlPath);
var match = Regex.Match(html, @"<title[^>]*>(.*?)</title>", RegexOptions.IgnoreCase | RegexOptions.Singleline);
if (match.Success)
{
var title = match.Groups[1].Value.Trim();
return System.Net.WebUtility.HtmlDecode(title);
}
}
catch
{
}
return string.Empty;
}
}
}
@@ -1,4 +1,4 @@
using System;
using System;
using System.IO;
using GameLauncher.Engines.Tkool;
@@ -52,7 +52,7 @@ namespace GameLauncher.Engines.Rgss.Games.IiniTitleRepair
var trim = line.Trim();
if (trim.StartsWith("Title=", StringComparison.OrdinalIgnoreCase))
{
var val = trim.Substring(6).Trim();
var val = trim[6..].Trim();
if (!string.IsNullOrWhiteSpace(val) && !val.Contains('\uFFFD'))
{
tg.Title = val;
@@ -73,23 +73,23 @@ namespace GameLauncher.Engines.Rgss.Games.IiniTitleRepair
{
try
{
if (!File.Exists(filePath)) return Array.Empty<string>();
if (!File.Exists(filePath)) return [];
byte[] bytes = File.ReadAllBytes(filePath);
if (bytes.Length == 0) return Array.Empty<string>();
if (bytes.Length == 0) return [];
// 1. UTF-8 BOM (EF BB BF)
if (bytes.Length >= 3 && bytes[0] == 0xEF && bytes[1] == 0xBB && bytes[2] == 0xBF)
{
var text = System.Text.Encoding.UTF8.GetString(bytes, 3, bytes.Length - 3);
return text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
return text.Split(["\r\n", "\r", "\n"], StringSplitOptions.None);
}
// 2. UTF-16 LE BOM (FF FE)
if (bytes.Length >= 2 && bytes[0] == 0xFF && bytes[1] == 0xFE)
{
var text = System.Text.Encoding.Unicode.GetString(bytes, 2, bytes.Length - 2);
return text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
return text.Split(["\r\n", "\r", "\n"], StringSplitOptions.None);
}
// 3. Shift_JIS (CP932)
@@ -104,11 +104,11 @@ namespace GameLauncher.Engines.Rgss.Games.IiniTitleRepair
}
var decoded = encoding.GetString(bytes);
return decoded.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
return decoded.Split(["\r\n", "\r", "\n"], StringSplitOptions.None);
}
catch
{
return Array.Empty<string>();
return [];
}
}
}
+9 -14
View File
@@ -415,11 +415,11 @@ namespace GameLauncher.Engines.Rgss
{
if (game.ApplyMod)
{
return await ApplyModAsync(game, pluginSettings, rgssExtractorPath);
return await this.ApplyModAsync(game, pluginSettings, rgssExtractorPath);
}
else
{
return RestoreOriginal(game);
return this.RestoreOriginal(game);
}
}
@@ -439,7 +439,7 @@ namespace GameLauncher.Engines.Rgss
// 1. スクリプトファイルが存在しない場合(RGSS暗号化アーカイブ内の場合)、自動抽出
if (string.IsNullOrEmpty(scriptsPath) || !File.Exists(scriptsPath))
{
var (extractSuccess, extractMsg) = await ExtractScriptsAsync(game, rgssExtractorPath);
var (extractSuccess, extractMsg) = await this.ExtractScriptsAsync(game, rgssExtractorPath);
if (!extractSuccess)
{
return (false, $"スクリプトの抽出に失敗したため改造を適用できませんでした: {extractMsg}");
@@ -519,8 +519,8 @@ namespace GameLauncher.Engines.Rgss
{
var scriptsPath = game.PluginsJsPath;
var gameBackupDir = AppPathHelper.GetGameBackupDirectory(game.FolderName, game.RootDirectory);
var scriptFileName = !string.IsNullOrEmpty(scriptsPath)
? Path.GetFileName(scriptsPath)
var scriptFileName = !string.IsNullOrEmpty(scriptsPath)
? Path.GetFileName(scriptsPath)
: (game.EngineType == TkoolEngineType.VXAce ? "Scripts.rvdata2" : "Scripts.rvdata");
var backupPath = Path.Combine(gameBackupDir, scriptFileName + BackupSuffix);
@@ -819,14 +819,13 @@ namespace GameLauncher.Engines.Rgss
if (parserType != null)
{
var parser = Activator.CreateInstance(parserType);
var parseFileMethod = parserType.GetMethod("parse_file", new[] { typeof(string) });
var parseFileMethod = parserType.GetMethod("parse_file", [typeof(string)]);
var getFileDataMethod = parserType.GetMethod("get_filedata");
var closeFileMethod = parserType.GetMethod("close_file");
if (parseFileMethod != null && getFileDataMethod != null && parser != null)
{
var entries = parseFileMethod.Invoke(parser, new object[] { archivePath }) as System.Collections.IEnumerable;
if (entries != null)
if (parseFileMethod.Invoke(parser, [archivePath]) is System.Collections.IEnumerable entries)
{
foreach (var entry in entries)
{
@@ -839,8 +838,7 @@ namespace GameLauncher.Engines.Rgss
(entryName.EndsWith(targetFileName, StringComparison.OrdinalIgnoreCase) ||
Path.GetFileName(entryName).Equals(targetFileName, StringComparison.OrdinalIgnoreCase)))
{
var fileBytes = getFileDataMethod.Invoke(parser, new object[] { entry }) as byte[];
if (fileBytes != null && fileBytes.Length > 0)
if (getFileDataMethod.Invoke(parser, [entry]) is byte[] fileBytes && fileBytes.Length > 0)
{
closeFileMethod?.Invoke(parser, null);
@@ -873,10 +871,7 @@ namespace GameLauncher.Engines.Rgss
};
using var proc = Process.Start(psi);
if (proc != null)
{
proc.WaitForExit(30000); // 最大30秒待機
}
proc?.WaitForExit(30000); // 最大30秒待機
// RGSS Extractor はツール自身のフォルダ配下に Data\Scripts.rvdata2 等を出力
var possibleOutput = Path.Combine(toolDir, "Data", targetFileName);
+12 -12
View File
@@ -513,7 +513,7 @@ namespace GameLauncher.Engines.Rgss
int endIdx = content.IndexOf(ModEndTag, StringComparison.Ordinal);
if (endIdx > startIdx)
{
content = content.Substring(0, startIdx).TrimEnd() + "\n\n" + modCode + "\n";
content = content[..startIdx].TrimEnd() + "\n\n" + modCode + "\n";
File.WriteAllText(scriptPath, content, Encoding.UTF8);
return;
}
@@ -562,7 +562,7 @@ namespace GameLauncher.Engines.Rgss
if (!SrpgArchiveService.IsExtracted(gameDir))
{
progress?.Report("アーカイブ(data.dts)を初回展開中...");
var unpackRes = await _archiveService.UnpackDataDtsAsync(gameDir, progress);
var unpackRes = await this._archiveService.UnpackDataDtsAsync(gameDir, progress);
if (!unpackRes.Success)
{
return unpackRes;
@@ -571,7 +571,7 @@ namespace GameLauncher.Engines.Rgss
var extractedDir = SrpgArchiveService.GetExtractedDirectory(gameDir);
progress?.Report("Modスクリプトを生成中...");
var modBody = GenerateModScript(item);
var modBody = this.GenerateModScript(item);
var jsContent = $"{ModStartTag}\n{modBody}\n{ModEndTag}";
// 2. 既存のスクリプトへ注入
@@ -604,7 +604,7 @@ namespace GameLauncher.Engines.Rgss
// 3. data.dts を再パック
progress?.Report("Modを適用した data.dts を再構築中...");
var repackRes = await _archiveService.RepackDataDtsAsync(gameDir, progress);
var repackRes = await this._archiveService.RepackDataDtsAsync(gameDir, progress);
if (repackRes.Success)
{
item.IsModded = true;
@@ -658,8 +658,8 @@ namespace GameLauncher.Engines.Rgss
// 2. バックアップが存在すればバックアップ復元を試行
progress?.Report("オリジナルバックアップから data.dts を復元中...");
var revertRes = await _archiveService.RevertBackupAsync(gameDir);
if (revertRes.Success)
var (Success, Message) = await this._archiveService.RevertBackupAsync(gameDir);
if (Success)
{
item.IsModded = false;
return (true, "改造プラグインを解除し、元のアーカイブへ復元しました。");
@@ -667,7 +667,7 @@ namespace GameLauncher.Engines.Rgss
// バックアップが無い場合は Mod解除状態で再パック
progress?.Report("Mod解除状態でアーカイブを再構築中...");
var repackRes = await _archiveService.RepackDataDtsAsync(gameDir, progress);
var repackRes = await this._archiveService.RepackDataDtsAsync(gameDir, progress);
if (repackRes.Success)
{
item.IsModded = false;
@@ -689,7 +689,7 @@ namespace GameLauncher.Engines.Rgss
// 1. プロキシDLL解除
if (IsProxyDllEnabled(gameDir))
{
DisableProxyDll(gameDir);
this.DisableProxyDll(gameDir);
logs.Add("・プロキシDLL (version.dll) を解除しました");
}
@@ -726,10 +726,10 @@ namespace GameLauncher.Engines.Rgss
// 3. バックアップからの data.dts 復元
progress?.Report("バックアップから元の data.dts を復元中...");
var revertRes = await _archiveService.RevertBackupAsync(gameDir);
if (revertRes.Success)
var (Success, Message) = await this._archiveService.RevertBackupAsync(gameDir);
if (Success)
{
logs.Add($"・{revertRes.Message}");
logs.Add($"・{Message}");
}
else
{
@@ -737,7 +737,7 @@ namespace GameLauncher.Engines.Rgss
}
// 4. 解凍フォルダの退避
var restoreExtractedRes = _archiveService.RestoreExtractedState(gameDir);
var restoreExtractedRes = this._archiveService.RestoreExtractedState(gameDir);
if (restoreExtractedRes.Success && !restoreExtractedRes.Message.Contains("存在しません"))
{
logs.Add($"・{restoreExtractedRes.Message}");
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -159,9 +159,9 @@ namespace GameLauncher.Engines.Tkool
var entry = $"{BeginMarker}{{\"name\":\"{ModPluginId}\",\"status\":true,\"description\":\"GameLauncher mod\",\"parameters\":{{}}}}{EndMarker}";
var prefix = content.Substring(0, arrayStart + 1);
var prefix = content[..(arrayStart + 1)];
var inner = content.Substring(arrayStart + 1, arrayEnd - arrayStart - 1);
var suffix = content.Substring(arrayEnd);
var suffix = content[arrayEnd..];
var trimmedInner = inner.Trim();
var newInner = string.IsNullOrEmpty(trimmedInner)
@@ -198,7 +198,7 @@ namespace GameLauncher.Engines.Tkool
while (scan >= 0 && char.IsWhiteSpace(content[scan])) scan--;
if (scan >= 0 && content[scan] == ',') cutStart = scan;
content = content.Substring(0, cutStart) + content.Substring(end);
content = content[..cutStart] + content[end..];
}
while (content != prev);
+39 -17
View File
@@ -31,17 +31,21 @@ namespace GameLauncher.Engines.Tkool
"BattleTurnRecover",
"MaxGainGold",
"MaxGainExp",
"InstantMessage"
"InstantMessage",
"GameLauncher_Mod",
"GameLauncherMod",
"GameLauncher_StandaloneMod",
"GameLauncherStandaloneMod"
];
private List<ModPluginDefinition> _availablePlugins = [];
/// <summary>現在認識されている利用可能なプラグイン一覧</summary>
public IReadOnlyList<ModPluginDefinition> AvailablePlugins => _availablePlugins;
public IReadOnlyList<ModPluginDefinition> AvailablePlugins => this._availablePlugins;
public TkoolModService()
{
LoadAvailablePlugins();
this.LoadAvailablePlugins();
}
/// <summary>
@@ -86,13 +90,22 @@ namespace GameLauncher.Engines.Tkool
{
try
{
list.Add(ModPluginDefinition.FromFile(file));
var def = ModPluginDefinition.FromFile(file);
if (string.Equals(def.Id, "GameLauncher_Mod", StringComparison.OrdinalIgnoreCase) ||
string.Equals(def.Id, "GameLauncher_StandaloneMod", StringComparison.OrdinalIgnoreCase) ||
string.Equals(def.Id, "GameLauncherMod", StringComparison.OrdinalIgnoreCase) ||
string.Equals(def.Id, "GameLauncherStandaloneMod", StringComparison.OrdinalIgnoreCase))
{
continue;
}
list.Add(def);
}
catch { }
}
}
_availablePlugins = list;
this._availablePlugins = list;
return list;
}
@@ -146,11 +159,11 @@ namespace GameLauncher.Engines.Tkool
{
if (game.ApplyMod)
{
return ApplyMod(game, defaultSettings);
return this.ApplyMod(game, defaultSettings);
}
else
{
return RestoreOriginal(game);
return this.RestoreOriginal(game);
}
}
catch (Exception ex)
@@ -203,18 +216,27 @@ namespace GameLauncher.Engines.Tkool
string baseContent = File.ReadAllText(backupPath, Encoding.UTF8);
// 最新の動的プラグイン一覧を取得
if (_availablePlugins.Count == 0)
if (this._availablePlugins.Count == 0)
{
LoadAvailablePlugins();
this.LoadAvailablePlugins();
}
// 有効化対象のプラグインを取得
var pluginsToEnable = _availablePlugins
.Where(p => game.IsPluginEnabled(p.Id, defaultSettings, fallbackVal: true))
// ※ResourceLoaderFix はリソース読み込み不具合の必須救済プラグインのため、常に有効化・先頭配置
var fixPlugin = this._availablePlugins.FirstOrDefault(p => string.Equals(p.Id, "ResourceLoaderFix", StringComparison.OrdinalIgnoreCase));
var pluginsToEnable = this._availablePlugins
.Where(p => string.Equals(p.Id, "ResourceLoaderFix", StringComparison.OrdinalIgnoreCase) || game.IsPluginEnabled(p.Id, defaultSettings, fallbackVal: true))
.ToList();
// ResourceLoaderFix を最優先(先頭)に配置して、他プラグイン実行前のリソース要求も確実に救済
if (fixPlugin != null && pluginsToEnable.Contains(fixPlugin))
{
pluginsToEnable.Remove(fixPlugin);
pluginsToEnable.Insert(0, fixPlugin);
}
// 3. ゲーム側の plugins ディレクトリから不要な旧プラグインや無効プラグインを安全に掃除
var allManaged = GetAllManagedPluginNames(_availablePlugins);
var allManaged = GetAllManagedPluginNames(this._availablePlugins);
var enabledIds = new HashSet<string>(pluginsToEnable.Select(p => p.Id), StringComparer.OrdinalIgnoreCase);
foreach (var pluginId in allManaged)
@@ -233,7 +255,7 @@ namespace GameLauncher.Engines.Tkool
// 4. 有効対象のプラグインファイルをゲーム側へ配置
foreach (var plugin in pluginsToEnable)
{
CopyPluginToGame(plugin, pluginsDir);
this.CopyPluginToGame(plugin, pluginsDir);
}
// 5. plugins.js をパース・再構築して有効プラグインを追加
@@ -285,7 +307,7 @@ namespace GameLauncher.Engines.Tkool
// 2. ゲーム側の plugins フォルダから新旧すべてのプラグインファイルを安全に削除(ゴミを残さない)
if (!string.IsNullOrEmpty(pluginsDir) && Directory.Exists(pluginsDir))
{
var allManaged = GetAllManagedPluginNames(_availablePlugins);
var allManaged = GetAllManagedPluginNames(this._availablePlugins);
foreach (var pluginName in allManaged)
{
var targetFile = Path.Combine(pluginsDir, $"{pluginName}.js");
@@ -332,9 +354,9 @@ namespace GameLauncher.Engines.Tkool
return content;
}
string prefix = content.Substring(0, arrayStart + 1);
string prefix = content[..(arrayStart + 1)];
string inner = content.Substring(arrayStart + 1, arrayEnd - arrayStart - 1);
string suffix = content.Substring(arrayEnd);
string suffix = content[arrayEnd..];
// 新旧すべてのプラグイン名を除去対象とする
var managedSet = GetAllManagedPluginNames();
@@ -388,7 +410,7 @@ namespace GameLauncher.Engines.Tkool
if (depth == 0)
{
string objText = inner.Substring(objStart, i - objStart).Trim();
string objText = inner[objStart..i].Trim();
// このオブジェクトが新旧管理対象プラグインかどうか判定
var match = Regex.Match(objText, @"""name""\s*:\s*""([^""]+)""");
if (match.Success && managedSet.Contains(match.Groups[1].Value))
+618
View File
@@ -0,0 +1,618 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using GameLauncher.Helpers;
namespace GameLauncher.Engines.Tkool
{
/// <summary>
/// ツクールMV/MZ等のゲームリソース(画像・音声・スクリプト等)における
/// URLエンコード名、文字化け、機種依存文字(丸数字等)の不整合を、
/// 「実際のゲームコード・データで使われているファイル名」と照合して並列かつ超高速に自動修復するサービス。
///
/// 設計方針:
/// - コード主導のピンポイント照合:
/// 1. data/*.json や plugins.js 等のゲームコード・定義データから要求リソース名を並列抽出。
/// 2. コード側が要求しているのにディスク上に存在しないファイル名(例: エロステ_ページ②.png)を特定。
/// 3. ディスク上の類似ファイル(エロステ_ページ2.png や URLデコード名)から要求通りのファイルを作成。
/// - マルチスレッド並列処理:
/// ・Parallel.ForEach による CPU コア全開の超高速走査・チェック・リンク生成。
/// - 独立ログファイル出力:
/// ・Logs フォルダ内に詳細ログファイル(ResourceRepair_*.log)を出力し、
/// ランチャー画面上のテキストボックス肥大化によるUIフリーズを完全防止。
/// </summary>
public class TkoolResourceRepairService
{
[DllImport("Kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CreateHardLink(string lpFileName, string lpExistingFileName, IntPtr lpSecurityAttributes);
/// <summary>修復完了キャッシュマーカーファイル名</summary>
public const string RepairMarkerFileName = ".gl_resource_repaired";
private static bool _encodingProviderRegistered;
// 丸数字マッピング (①: U+2460 〜 ⑳: U+2473)
private static readonly string[] CircleNumbers =
[
"①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨", "⑩",
"⑪", "⑫", "⑬", "⑭", "⑮", "⑯", "⑰", "⑱", "⑲", "⑳"
];
// 全角数字マッピング (0: U+FF10 〜 9: U+FF19)
private static readonly string[] FullWidthNumbers =
[
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"
];
public TkoolResourceRepairService()
{
EnsureEncodingProvider();
}
private static void EnsureEncodingProvider()
{
if (!_encodingProviderRegistered)
{
try
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
_encodingProviderRegistered = true;
}
catch { }
}
}
/// <summary>
/// 修復処理のリアルタイム進捗情報
/// </summary>
public record RepairProgress(int Current, int Total, int RepairedCount, string CurrentStatus);
/// <summary>
/// 修復処理の結果情報
/// </summary>
public record RepairResult(bool Success, int RepairedCount, int CleanedCount, long ElapsedMilliseconds, string Message, string LogFilePath);
/// <summary>
/// ログファイルの保存先ディレクトリを取得します。
/// </summary>
public static string GetLogsDirectory()
{
var exeDir = AppPathHelper.GetExeDirectory();
var logsDir = Path.Combine(exeDir, "Logs");
if (!Directory.Exists(logsDir))
{
Directory.CreateDirectory(logsDir);
}
return logsDir;
}
/// <summary>
/// 指定したツクールゲームのリソースファイルを非同期・並列で修復します(UIをブロックしません)。
/// </summary>
public Task<RepairResult> RepairGameResourcesAsync(
TkoolGameItem game,
bool forceRescan = false,
IProgress<RepairProgress>? progress = null,
Action<string>? uiLogCallback = null)
{
return Task.Run(() => this.RepairGameResources(game, forceRescan, progress, uiLogCallback));
}
/// <summary>
/// 指定したツクールゲームのリソースファイルを並列走査・コード照合修復します。
/// </summary>
public RepairResult RepairGameResources(
TkoolGameItem game,
bool forceRescan = false,
IProgress<RepairProgress>? progress = null,
Action<string>? uiLogCallback = null)
{
if (game == null)
{
return new RepairResult(false, 0, 0, 0, "対象ゲームが指定されていません。", string.Empty);
}
var sw = Stopwatch.StartNew();
// ログファイルの初期化
var logsDir = GetLogsDirectory();
var safeGameName = Regex.Replace(game.FolderName ?? game.Title ?? "Game", @"[\\/:*?""<>|]", "_");
var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
var logFilePath = Path.Combine(logsDir, $"ResourceRepair_{safeGameName}_{timestamp}.log");
var logLines = new ConcurrentBag<string>();
void FileLog(string message)
{
logLines.Add($"[{DateTime.Now:HH:mm:ss.fff}] {message}");
}
FileLog($"=== ゲームリソース高速並列修復開始 ===");
FileLog($"ゲーム名: {game.Title}");
FileLog($"ルートフォルダ: {game.RootDirectory}");
FileLog($"並列CPUコア数: {Environment.ProcessorCount}");
uiLogCallback?.Invoke($"[リソース修復] {game.Title}: ゲームコードとの並列照合を開始します...");
progress?.Report(new RepairProgress(0, 100, 0, "ゲームコード・データを収集中..."));
var targetDirs = this.CollectResourceDirectories(game);
if (targetDirs.Count == 0)
{
sw.Stop();
var msg = "修復対象のリソースディレクトリが見つかりませんでした。";
FileLog(msg);
this.WriteLogFile(logFilePath, logLines);
uiLogCallback?.Invoke($"[リソース修復] {msg}");
return new RepairResult(true, 0, 0, sw.ElapsedMilliseconds, msg, logFilePath);
}
// -------------------------------------------------------------
// ステップ 1: ゲームデータ (data/*.json, js/*.js) から要求リソース名を並列抽出
// -------------------------------------------------------------
FileLog("ステップ 1: data フォルダ内の JSON およびスクリプトから、コード上で実際に使用されているリソース名を並列抽出中...");
var requestedNames = this.ExtractRequestedResourceNamesFromCode(game, FileLog);
FileLog($"ステップ 1 完了: コード上で使われているリソース識別子を {requestedNames.Count} 件抽出しました。");
progress?.Report(new RepairProgress(20, 100, 0, $"コードリソース抽出完了 ({requestedNames.Count}件)"));
// -------------------------------------------------------------
// ステップ 2: 素材フォルダ (img, audio 等) の実ファイルを並列収集
// -------------------------------------------------------------
FileLog("ステップ 2: 素材フォルダ (img, audio 等) の全ファイルを並列収集・分類中...");
var resourceFiles = new ConcurrentBag<string>();
var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount };
Parallel.ForEach(targetDirs, parallelOptions, dir =>
{
if (!Directory.Exists(dir)) return;
try
{
foreach (var f in Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories))
{
var name = Path.GetFileName(f);
if (!string.Equals(name, RepairMarkerFileName, StringComparison.OrdinalIgnoreCase))
{
resourceFiles.Add(f);
}
}
}
catch (Exception ex)
{
FileLog($"[警告] 一覧取得例外: {dir} ({ex.Message})");
}
});
var allFilesList = resourceFiles.ToList();
FileLog($"ステップ 2 完了: 素材ファイルを合計 {allFilesList.Count} 件検出しました。");
progress?.Report(new RepairProgress(40, 100, 0, $"素材ファイル収集完了 ({allFilesList.Count}件)"));
int repairedCount = 0;
int cleanedCount = 0;
// -------------------------------------------------------------
// ステップ 3: 過去の破損ファイル (%と丸数字の混在) の並列クリーンアップ
// -------------------------------------------------------------
Parallel.ForEach(allFilesList, parallelOptions, filePath =>
{
var fileName = Path.GetFileName(filePath);
if (fileName.Contains('%') && this.ContainsCircleNumber(fileName))
{
try
{
if (File.Exists(filePath))
{
File.Delete(filePath);
System.Threading.Interlocked.Increment(ref cleanedCount);
FileLog($"[不正ファイル削除] {fileName}");
}
}
catch { }
}
});
// -------------------------------------------------------------
// ステップ 4: パーセントエンコードされたファイル名の安全完全デコード (並列)
// -------------------------------------------------------------
FileLog("ステップ 4: URLエンコードされたファイル名の完全デコードと日本語リンク作成中 (並列)...");
var newlyDecodedFiles = new ConcurrentBag<string>();
Parallel.ForEach(allFilesList, parallelOptions, filePath =>
{
var fileName = Path.GetFileName(filePath);
if (fileName.Contains('%'))
{
try
{
var unescaped = this.FullyUnescapeString(fileName);
if (!string.Equals(unescaped, fileName, StringComparison.Ordinal) && !unescaped.Contains('%'))
{
var dirPath = Path.GetDirectoryName(filePath);
if (!string.IsNullOrEmpty(dirPath))
{
var unescapedPath = Path.Combine(dirPath, unescaped);
if (!File.Exists(unescapedPath))
{
if (this.CreateLinkOrCopy(filePath, unescapedPath))
{
System.Threading.Interlocked.Increment(ref repairedCount);
newlyDecodedFiles.Add(unescapedPath);
FileLog($"[URLデコード作成] {fileName} -> {unescaped}");
}
}
}
}
}
catch { }
}
});
// ステップ4で新しく作成されたファイルも素材リストに合流
if (!newlyDecodedFiles.IsEmpty)
{
allFilesList.AddRange(newlyDecodedFiles);
}
progress?.Report(new RepairProgress(70, 100, repairedCount, "コード上のファイル名と実素材の照合中..."));
// -------------------------------------------------------------
// ステップ 5: コード上で要求されているファイル名と実素材の照合・表記揺れ解決 (並列)
// -------------------------------------------------------------
FileLog("ステップ 5: コード上で要求されているファイル名(丸数字など)と実素材の表記揺れ照合中 (並列)...");
// ディレクトリごとに実ファイル名辞書を作成(高速ルックアップ用)
var dirFilesMap = allFilesList
.GroupBy(f => Path.GetDirectoryName(f) ?? string.Empty)
.ToDictionary(g => g.Key, g => g.Select(p => Path.GetFileName(p)).ToHashSet(StringComparer.OrdinalIgnoreCase));
// ディレクトリごとに実ファイルの正規化キー辞書を作成(重複キーによるArgumentException例外を安全に回避)
var dirNormalizedMap = allFilesList
.GroupBy(f => Path.GetDirectoryName(f) ?? string.Empty)
.ToDictionary(g => g.Key, g =>
{
var dict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var p in g)
{
var key = this.NormalizeFuzzyKey(Path.GetFileNameWithoutExtension(p));
if (!dict.ContainsKey(key))
{
dict[key] = p;
}
}
return dict;
});
// コードで要求されている各リソース名について照合
Parallel.ForEach(requestedNames, parallelOptions, reqName =>
{
var reqExt = Path.GetExtension(reqName);
var reqNameNoExt = string.IsNullOrEmpty(reqExt) ? reqName : Path.GetFileNameWithoutExtension(reqName);
var normalizedReq = this.NormalizeFuzzyKey(reqNameNoExt);
foreach (var (dirPath, fileSet) in dirFilesMap)
{
// 拡張子がある場合とない場合(.png を補完)を検討
var extensionsToCheck = string.IsNullOrEmpty(reqExt)
? new[] { ".png", ".ogg", ".m4a" }
: [reqExt];
foreach (var ext in extensionsToCheck)
{
var expectedFileName = reqNameNoExt + ext;
// すでにその名前が存在していれば修復不要
if (fileSet.Contains(expectedFileName)) continue;
// ディレクトリ内に正規化キーが一致する実ファイルがあるか探す
if (dirNormalizedMap.TryGetValue(dirPath, out var normDict) &&
normDict.TryGetValue(normalizedReq, out var existingFilePath))
{
var existingExt = Path.GetExtension(existingFilePath);
if (string.Equals(existingExt, ext, StringComparison.OrdinalIgnoreCase))
{
var targetPath = Path.Combine(dirPath, expectedFileName);
if (!File.Exists(targetPath))
{
if (this.CreateLinkOrCopy(existingFilePath, targetPath))
{
System.Threading.Interlocked.Increment(ref repairedCount);
FileLog($"[コード要求リソース修復] コード要求名: {expectedFileName} <- 実ファイル: {Path.GetFileName(existingFilePath)}");
lock (fileSet) { fileSet.Add(expectedFileName); }
}
}
}
}
}
}
});
sw.Stop();
// ログファイルへの一括書き込み
FileLog($"=== 修復完了: 作成 {repairedCount} 件、クリーンアップ {cleanedCount} 件 (所要時間: {sw.ElapsedMilliseconds}ms) ===");
this.WriteLogFile(logFilePath, logLines);
var summaryMsg = $"リソース修復完了: コード要求照合により {repairedCount} 件作成、{cleanedCount} 件クリーンアップ (所要時間: {sw.ElapsedMilliseconds}ms)";
uiLogCallback?.Invoke($"[リソース修復] {summaryMsg}");
uiLogCallback?.Invoke($"[リソース修復] 詳細ログを出力しました: {logFilePath}");
progress?.Report(new RepairProgress(100, 100, repairedCount, "完了"));
return new RepairResult(true, repairedCount, cleanedCount, sw.ElapsedMilliseconds, summaryMsg, logFilePath);
}
/// <summary>
/// ゲームの data/*.json および js/*.js からコード上で要求されているリソース名を並列抽出します。
/// </summary>
private HashSet<string> ExtractRequestedResourceNamesFromCode(TkoolGameItem game, Action<string> log)
{
var requested = new ConcurrentBag<string>();
var dataDirs = new List<string>();
// data フォルダおよび js フォルダの探索
var roots = new List<string>();
if (game.IsEvbExtracted && !string.IsNullOrEmpty(game.EvbExtractedDirPath) && Directory.Exists(game.EvbExtractedDirPath))
{
roots.Add(game.EvbExtractedDirPath);
}
if (!string.IsNullOrEmpty(game.RootDirectory) && Directory.Exists(game.RootDirectory))
{
roots.Add(game.RootDirectory);
}
foreach (var r in roots)
{
var candidates = new[] { r, Path.Combine(r, "www") };
foreach (var c in candidates)
{
var dataPath = Path.Combine(c, "data");
if (Directory.Exists(dataPath) && !dataDirs.Contains(dataPath)) dataDirs.Add(dataPath);
var jsPath = Path.Combine(c, "js");
if (Directory.Exists(jsPath) && !dataDirs.Contains(jsPath)) dataDirs.Add(jsPath);
}
}
var textFiles = new List<string>();
foreach (var d in dataDirs)
{
try
{
textFiles.AddRange(Directory.GetFiles(d, "*.json", SearchOption.AllDirectories));
textFiles.AddRange(Directory.GetFiles(d, "*.js", SearchOption.AllDirectories));
}
catch { }
}
log($"コード検査対象ファイル数: {textFiles.Count} 件 (並列抽出)");
var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount };
Parallel.ForEach(textFiles, parallelOptions, file =>
{
try
{
var text = File.ReadAllText(file, Encoding.UTF8);
// JSON/JS文字列 "..." または '...' を抽出
var matches = Regex.Matches(text, @"""([^""\r\n]{1,80})""|'([^'\r\n]{1,80})'");
foreach (Match m in matches)
{
var val = (m.Groups[1].Success ? m.Groups[1].Value : m.Groups[2].Value).Trim();
// 素材名として意味のある文字列(日本語、丸数字、記号、拡張子付き等)を収集
if (this.IsPotentialResourceName(val))
{
requested.Add(val);
}
}
}
catch { }
});
return new HashSet<string>(requested, StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// 文字列が画像・音声等のリソース名候補として適切か判定します。
/// </summary>
private bool IsPotentialResourceName(string text)
{
if (string.IsNullOrWhiteSpace(text) || text.Length > 80) return false;
// システム予約語やJSON構文は除外
if (text == "true" || text == "false" || text == "null" || text == "undefined") return false;
if (text.StartsWith("{") || text.StartsWith("[")) return false;
// 拡張子を持つ、または日本語/丸数字を含む、または _ や - を含む識別子
if (text.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
text.EndsWith(".ogg", StringComparison.OrdinalIgnoreCase) ||
text.EndsWith(".m4a", StringComparison.OrdinalIgnoreCase))
{
return true;
}
// 日本語・全角文字または丸数字を含む文字列(例: "エロステ_ページ②")
if (this.ContainsNonAscii(text) || this.ContainsCircleNumber(text))
{
// 空白のみや極端な記号列は除外
return !text.Contains("<") && !text.Contains(">");
}
return false;
}
/// <summary>
/// 丸数字(①〜⑳)⇔ 通常数字(1〜20)および 全角数字 を正規化したファジーマッチ用キーを生成します。
/// </summary>
private string NormalizeFuzzyKey(string text)
{
if (string.IsNullOrEmpty(text)) return string.Empty;
var res = text.Normalize(NormalizationForm.FormC).ToLowerInvariant();
// 丸数字 -> 通常数字
for (int i = 0; i < CircleNumbers.Length; i++)
{
res = res.Replace(CircleNumbers[i], (i + 1).ToString());
}
// 全角数字 -> 半角数字
for (int i = 0; i < FullWidthNumbers.Length; i++)
{
res = res.Replace(FullWidthNumbers[i], i.ToString());
}
// 波ダッシュ・チルダ
res = res.Replace('\u301C', '\uFF5E');
// 全角カッコ -> 半角カッコ
res = res.Replace('(', '(').Replace(')', ')');
return res;
}
/// <summary>
/// 蓄積されたログ行をログファイルへ一括書き込みします。
/// </summary>
private void WriteLogFile(string path, IEnumerable<string> lines)
{
try
{
File.WriteAllLines(path, lines, new UTF8Encoding(true));
}
catch { }
}
/// <summary>
/// パーセントエンコードされた文字列を100%完全にデコードします。
/// </summary>
private string FullyUnescapeString(string input)
{
if (string.IsNullOrEmpty(input) || !input.Contains('%')) return input;
try
{
var unescaped = Uri.UnescapeDataString(input);
if (!unescaped.Contains('%')) return unescaped;
}
catch { }
try
{
return Regex.Replace(input, @"((?:%[0-9A-Fa-f]{2})+)", match =>
{
try
{
var hexPart = match.Value;
var bytes = new List<byte>();
for (int i = 0; i < hexPart.Length; i += 3)
{
if (hexPart[i] == '%' && i + 2 < hexPart.Length)
{
bytes.Add(Convert.ToByte(hexPart.Substring(i + 1, 2), 16));
}
}
return Encoding.UTF8.GetString([.. bytes]);
}
catch
{
return match.Value;
}
});
}
catch
{
return input;
}
}
/// <summary>
/// 丸数字が含まれているか判定します。
/// </summary>
private bool ContainsCircleNumber(string text)
{
if (string.IsNullOrEmpty(text)) return false;
foreach (var circle in CircleNumbers)
{
if (text.Contains(circle)) return true;
}
return false;
}
/// <summary>
/// 非ASCII文字(全角文字・日本語等)が含まれているか判定します。
/// </summary>
private bool ContainsNonAscii(string text)
{
if (string.IsNullOrEmpty(text)) return false;
foreach (char c in text)
{
if (c > 127) return true;
}
return false;
}
/// <summary>
/// ハードリンクを最優先で作成し、失敗した場合はファイルコピーを行います。
/// </summary>
private bool CreateLinkOrCopy(string sourceFile, string targetFile)
{
try
{
if (File.Exists(targetFile)) return true;
if (CreateHardLink(targetFile, sourceFile, IntPtr.Zero))
{
return true;
}
File.Copy(sourceFile, targetFile, overwrite: false);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 修復対象となるリソースフォルダ一覧(img, audio, js, data等)を収集します。
/// </summary>
private List<string> CollectResourceDirectories(TkoolGameItem game)
{
var result = new List<string>();
var roots = new List<string>();
if (game.IsEvbExtracted && !string.IsNullOrEmpty(game.EvbExtractedDirPath) && Directory.Exists(game.EvbExtractedDirPath))
{
roots.Add(game.EvbExtractedDirPath);
}
if (!string.IsNullOrEmpty(game.RootDirectory) && Directory.Exists(game.RootDirectory))
{
roots.Add(game.RootDirectory);
}
foreach (var root in roots)
{
var candidates = new[] { root, Path.Combine(root, "www"), Path.Combine(root, "package.nw") };
foreach (var baseDir in candidates)
{
if (!Directory.Exists(baseDir)) continue;
var subDirs = new[] { "img", "audio", "js", "data" };
foreach (var sub in subDirs)
{
var target = Path.Combine(baseDir, sub);
if (Directory.Exists(target) && !result.Contains(target))
{
result.Add(target);
}
}
}
}
return result;
}
}
}
+1 -1
View File
@@ -313,7 +313,7 @@ namespace GameLauncher.Engines.Tyrano
var btn = document.createElement('div');
btn.innerHTML = '⚙ チート';
btn.style.cssText = 'position:fixed;top:10px;right:10px;z-index:999999;background:rgba(20,20,30,0.85);color:#00B894;padding:6px 12px;border-radius:6px;font-size:12px;cursor:pointer;border:1px solid #00B894;font-family:sans-serif;user-select:none;font-weight:bold;box-shadow:0 2px 6px rgba(0,0,0,0.5);';
var modal = document.createElement('div');
modal.style.cssText = 'display:none;position:fixed;top:45px;right:10px;width:340px;max-height:480px;background:rgba(24,24,32,0.96);border:1px solid #555;border-radius:8px;z-index:999999;padding:12px;overflow-y:auto;color:#E0E0E6;font-size:12px;font-family:sans-serif;box-shadow:0 4px 12px rgba(0,0,0,0.7);';
+7 -2
View File
@@ -10,7 +10,9 @@
Unity,
Wolf,
SrpgStudio,
Evb
Evb,
Nwjs,
Other
}
/// <summary>
@@ -25,6 +27,8 @@
VXAce,
Wolf,
SrpgStudio,
Nwjs,
Other,
Unknown
}
@@ -49,7 +53,8 @@
FolderLastModifiedAsc = 3, // フォルダ更新日時 (古い順)
TitleAsc = 4, // タイトル (昇順)
TitleDesc = 5, // タイトル (降順)
FolderNameAsc = 6 // フォルダ名 (昇順)
FolderNameAsc = 6, // フォルダ名 (昇順)
BookmarkedFirst = 7 // ★ ブックマーク優先
}
/// <summary>
+38 -32
View File
@@ -21,22 +21,22 @@ namespace GameLauncher.Engines.Unity
/// <summary>[Game]_Data ディレクトリ絶対パス</summary>
public string DataDirectoryPath
{
get => _dataDirectoryPath;
set { if (_dataDirectoryPath != value) { _dataDirectoryPath = value; OnPropertyChanged(); } }
get => this._dataDirectoryPath;
set { if (this._dataDirectoryPath != value) { this._dataDirectoryPath = value; this.OnPropertyChanged(); } }
}
/// <summary>app.info 由来の会社名/開発者名</summary>
public string CompanyName
{
get => _companyName;
get => this._companyName;
set
{
if (_companyName != value)
if (this._companyName != value)
{
_companyName = value;
OnPropertyChanged();
OnPropertyChanged(nameof(RegistryPath));
OnPropertyChanged(nameof(LocalLowPath));
this._companyName = value;
this.OnPropertyChanged();
this.OnPropertyChanged(nameof(this.RegistryPath));
this.OnPropertyChanged(nameof(this.LocalLowPath));
}
}
}
@@ -44,35 +44,35 @@ namespace GameLauncher.Engines.Unity
/// <summary>app.info 由来の製品名</summary>
public string ProductName
{
get => _productName;
get => this._productName;
set
{
if (_productName != value)
if (this._productName != value)
{
_productName = value;
OnPropertyChanged();
OnPropertyChanged(nameof(RegistryPath));
OnPropertyChanged(nameof(LocalLowPath));
this._productName = value;
this.OnPropertyChanged();
this.OnPropertyChanged(nameof(this.RegistryPath));
this.OnPropertyChanged(nameof(this.LocalLowPath));
}
}
}
public override bool IsIL2CPP => BackendType == UnityBackendType.IL2CPP;
public override bool IsMono => BackendType == UnityBackendType.Mono;
public override bool IsIL2CPP => this.BackendType == UnityBackendType.IL2CPP;
public override bool IsMono => this.BackendType == UnityBackendType.Mono;
/// <summary>バックエンド形式 (IL2CPP / Mono)</summary>
public UnityBackendType BackendType
{
get => _backendType;
get => this._backendType;
set
{
if (_backendType != value)
if (this._backendType != value)
{
_backendType = value;
OnPropertyChanged();
OnPropertyChanged(nameof(BackendBadgeText));
OnPropertyChanged(nameof(IsIL2CPP));
OnPropertyChanged(nameof(IsMono));
this._backendType = value;
this.OnPropertyChanged();
this.OnPropertyChanged(nameof(this.BackendBadgeText));
this.OnPropertyChanged(nameof(this.IsIL2CPP));
this.OnPropertyChanged(nameof(this.IsMono));
}
}
}
@@ -80,15 +80,15 @@ namespace GameLauncher.Engines.Unity
/// <summary>Unityバージョン文字列</summary>
public override string UnityVersion
{
get => _unityVersion;
set { if (_unityVersion != value) { _unityVersion = value; OnPropertyChanged(); } }
get => this._unityVersion;
set { if (this._unityVersion != value) { this._unityVersion = value; this.OnPropertyChanged(); } }
}
/// <summary>セーブデータ(レジストリまたはファイル)が検出されたかどうか</summary>
public override bool HasSaveData
{
get => _hasSaveData;
set { if (_hasSaveData != value) { _hasSaveData = value; OnPropertyChanged(); } }
get => this._hasSaveData;
set { if (this._hasSaveData != value) { this._hasSaveData = value; this.OnPropertyChanged(); } }
}
/// <summary>
@@ -99,9 +99,9 @@ namespace GameLauncher.Engines.Unity
{
get
{
if (string.IsNullOrEmpty(CompanyName) || string.IsNullOrEmpty(ProductName))
if (string.IsNullOrEmpty(this.CompanyName) || string.IsNullOrEmpty(this.ProductName))
return string.Empty;
return $@"Software\{CompanyName}\{ProductName}";
return $@"Software\{this.CompanyName}\{this.ProductName}";
}
}
@@ -113,22 +113,28 @@ namespace GameLauncher.Engines.Unity
{
get
{
if (string.IsNullOrEmpty(CompanyName) || string.IsNullOrEmpty(ProductName))
if (string.IsNullOrEmpty(this.CompanyName) || string.IsNullOrEmpty(this.ProductName))
return string.Empty;
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var appData = Path.GetDirectoryName(localAppData);
if (string.IsNullOrEmpty(appData)) return string.Empty;
return Path.Combine(appData, "LocalLow", CompanyName, ProductName);
return Path.Combine(appData, "LocalLow", this.CompanyName, this.ProductName);
}
}
public override string BackendBadgeText => BackendType switch
public override string BackendBadgeText => this.BackendType switch
{
UnityBackendType.IL2CPP => "IL2CPP",
UnityBackendType.Mono => "Mono",
_ => "Unity"
};
/// <summary>
/// エンジン種別ラベル。Unityは専用バッジ(IL2CPP/Mono等)で表現するため空文字を返し、
/// エンジン種別ラベル自体は表示しません。
/// </summary>
public override string EngineLabelText => string.Empty;
}
}
+37 -37
View File
@@ -28,35 +28,35 @@ namespace GameLauncher.Engines.Unity
/// <summary>レジストリの生キー名(例: ClearedLevel_h1378399435)</summary>
public string RawKey
{
get => _rawKey;
set { if (_rawKey != value) { _rawKey = value; OnPropertyChanged(); } }
get => this._rawKey;
set { if (this._rawKey != value) { this._rawKey = value; this.OnPropertyChanged(); } }
}
/// <summary>Unityのハッシュを除去した整形式キー名(例: ClearedLevel)</summary>
public string CleanKey
{
get => _cleanKey;
set { if (_cleanKey != value) { _cleanKey = value; OnPropertyChanged(); } }
get => this._cleanKey;
set { if (this._cleanKey != value) { this._cleanKey = value; this.OnPropertyChanged(); } }
}
/// <summary>値のデータ型</summary>
public PlayerPrefsType Type
{
get => _type;
set { if (_type != value) { _type = value; OnPropertyChanged(); OnPropertyChanged(nameof(TypeDisplay)); } }
get => this._type;
set { if (this._type != value) { this._type = value; this.OnPropertyChanged(); this.OnPropertyChanged(nameof(this.TypeDisplay)); } }
}
/// <summary>実際の値(int, float, string, byte[])</summary>
public object? Value
{
get => _value;
get => this._value;
set
{
if (!Equals(_value, value))
if (!Equals(this._value, value))
{
_value = value;
OnPropertyChanged();
UpdateEditValue();
this._value = value;
this.OnPropertyChanged();
this.UpdateEditValue();
}
}
}
@@ -64,15 +64,15 @@ namespace GameLauncher.Engines.Unity
/// <summary>UI表示・編集用の文字列値</summary>
public string EditValue
{
get => _editValue;
get => this._editValue;
set
{
if (_editValue != value)
if (this._editValue != value)
{
_editValue = value;
_isModified = true;
OnPropertyChanged();
OnPropertyChanged(nameof(IsModified));
this._editValue = value;
this._isModified = true;
this.OnPropertyChanged();
this.OnPropertyChanged(nameof(this.IsModified));
}
}
}
@@ -80,11 +80,11 @@ namespace GameLauncher.Engines.Unity
/// <summary>値が変更されたかどうか</summary>
public bool IsModified
{
get => _isModified;
set { if (_isModified != value) { _isModified = value; OnPropertyChanged(); } }
get => this._isModified;
set { if (this._isModified != value) { this._isModified = value; this.OnPropertyChanged(); } }
}
public string TypeDisplay => Type switch
public string TypeDisplay => this.Type switch
{
PlayerPrefsType.Int => "Int (数値)",
PlayerPrefsType.Float => "Float (小数)",
@@ -95,19 +95,19 @@ namespace GameLauncher.Engines.Unity
private void UpdateEditValue()
{
if (_value == null)
if (this._value == null)
{
_editValue = string.Empty;
this._editValue = string.Empty;
}
else if (_value is byte[] bytes)
else if (this._value is byte[] bytes)
{
try
{
var text = System.Text.Encoding.UTF8.GetString(bytes).TrimEnd('\0');
if (text.All(c => !char.IsControl(c) || c == '\r' || c == '\n' || c == '\t'))
{
_editValue = text;
_type = PlayerPrefsType.String;
this._editValue = text;
this._type = PlayerPrefsType.String;
return;
}
}
@@ -118,21 +118,21 @@ namespace GameLauncher.Engines.Unity
float f = BitConverter.ToSingle(bytes, 0);
if (!float.IsNaN(f) && !float.IsInfinity(f))
{
_editValue = f.ToString("G");
_type = PlayerPrefsType.Float;
this._editValue = f.ToString("G");
this._type = PlayerPrefsType.Float;
return;
}
}
_editValue = BitConverter.ToString(bytes).Replace("-", " ");
this._editValue = BitConverter.ToString(bytes).Replace("-", " ");
}
else
{
_editValue = _value.ToString() ?? string.Empty;
this._editValue = this._value.ToString() ?? string.Empty;
}
_isModified = false;
OnPropertyChanged(nameof(EditValue));
OnPropertyChanged(nameof(IsModified));
this._isModified = false;
this.OnPropertyChanged(nameof(this.EditValue));
this.OnPropertyChanged(nameof(this.IsModified));
}
}
@@ -152,13 +152,13 @@ namespace GameLauncher.Engines.Unity
{
get
{
if (FileSize < 1024) return $"{FileSize} B";
if (FileSize < 1024 * 1024) return $"{FileSize / 1024.0:F1} KB";
return $"{FileSize / (1024.0 * 1024.0):F2} MB";
if (this.FileSize < 1024) return $"{this.FileSize} B";
if (this.FileSize < 1024 * 1024) return $"{this.FileSize / 1024.0:F1} KB";
return $"{this.FileSize / (1024.0 * 1024.0):F2} MB";
}
}
public string LastModifiedDisplay => LastModified.ToString("yyyy/MM/dd HH:mm:ss");
public string LastModifiedDisplay => this.LastModified.ToString("yyyy/MM/dd HH:mm:ss");
}
/// <summary>
@@ -172,6 +172,6 @@ namespace GameLauncher.Engines.Unity
public string BackupType { get; set; } = string.Empty; // "Registry (.reg)" または "ファイル"
public string Note { get; set; } = string.Empty;
public string TimestampDisplay => Timestamp.ToString("yyyy/MM/dd HH:mm:ss");
public string TimestampDisplay => this.Timestamp.ToString("yyyy/MM/dd HH:mm:ss");
}
}
+9 -9
View File
@@ -81,7 +81,7 @@ namespace GameLauncher.Engines.Unity
catch { }
// キー名昇順でソート
return list.OrderBy(e => e.CleanKey, StringComparer.OrdinalIgnoreCase).ToList();
return [.. list.OrderBy(e => e.CleanKey, StringComparer.OrdinalIgnoreCase)];
}
/// <summary>
@@ -319,7 +319,7 @@ namespace GameLauncher.Engines.Unity
proc?.WaitForExit(3000);
// JSONバックアップも併せて出力
var entries = GetPlayerPrefs(registryPath);
var entries = this.GetPlayerPrefs(registryPath);
var jsonBackupFile = Path.Combine(backupDir, $"PlayerPrefs_{timestamp}.json");
var serializableList = entries.Select(e => new
{
@@ -416,7 +416,7 @@ namespace GameLauncher.Engines.Unity
FileSize = fi.Length,
LastModified = fi.LastWriteTime,
LocationType = "LocalLow",
IsTextOrJson = CheckIsTextOrJson(f)
IsTextOrJson = this.CheckIsTextOrJson(f)
});
}
}
@@ -429,7 +429,7 @@ namespace GameLauncher.Engines.Unity
try
{
// ルート直下
CollectCandidateFiles(game.RootDirectory, "ゲームフォルダ", list);
this.CollectCandidateFiles(game.RootDirectory, "ゲームフォルダ", list);
// Save / SaveData / saves / savedata サブフォルダ
var subNames = new[] { "Save", "SaveData", "saves", "savedata", "Save_Data" };
@@ -438,21 +438,21 @@ namespace GameLauncher.Engines.Unity
var subPath = Path.Combine(game.RootDirectory, sub);
if (Directory.Exists(subPath))
{
CollectCandidateFiles(subPath, "ゲームフォルダ/" + sub, list, isStrict: false);
this.CollectCandidateFiles(subPath, "ゲームフォルダ/" + sub, list, isStrict: false);
}
}
// Dataフォルダ直下のセーブファイル候補
if (!string.IsNullOrEmpty(game.DataDirectoryPath) && Directory.Exists(game.DataDirectoryPath))
{
CollectCandidateFiles(game.DataDirectoryPath, "Dataフォルダ", list);
this.CollectCandidateFiles(game.DataDirectoryPath, "Dataフォルダ", list);
}
}
catch { }
}
// 更新日時降順でソート
return list.OrderByDescending(f => f.LastModified).ToList();
return [.. list.OrderByDescending(f => f.LastModified)];
}
private void CollectCandidateFiles(string dir, string locationLabel, List<SaveFileEntry> list, bool isStrict = true)
@@ -494,7 +494,7 @@ namespace GameLauncher.Engines.Unity
FileSize = fi.Length,
LastModified = fi.LastWriteTime,
LocationType = locationLabel,
IsTextOrJson = CheckIsTextOrJson(f)
IsTextOrJson = this.CheckIsTextOrJson(f)
});
}
}
@@ -649,7 +649,7 @@ namespace GameLauncher.Engines.Unity
}
catch { }
return list.OrderByDescending(b => b.Timestamp).ToList();
return [.. list.OrderByDescending(b => b.Timestamp)];
}
/// <summary>
+1 -1
View File
@@ -85,7 +85,7 @@ namespace GameLauncher.Engines.Wolf
return (false, "ゲームのルートディレクトリが見つかりません。");
}
var extractorPath = ResolveExtractorPath(customExtractorPath);
var extractorPath = this.ResolveExtractorPath(customExtractorPath);
if (string.IsNullOrEmpty(extractorPath) || !File.Exists(extractorPath))
{
return (false, "Wolf RPG アーカイブ解凍ツール(UberWolfCli.exe / WolfDec.exe)が見つかりません。設定ダイアログからツールのパスを指定してください。");
+3 -3
View File
@@ -51,7 +51,7 @@ namespace GameLauncher.Engines.Wolf
try
{
// 1. プロキシDLL本体の探索 (Tools\speedhack-i686\version.dll)
var sourceDllPath = ResolveProxyDllPath();
var sourceDllPath = this.ResolveProxyDllPath();
if (string.IsNullOrEmpty(sourceDllPath) || !File.Exists(sourceDllPath))
{
return (false, "プロキシDLL(Engines\\Wolf\\Tools\\speedhack-i686\\version.dll)が見つかりません。");
@@ -73,7 +73,7 @@ namespace GameLauncher.Engines.Wolf
File.Copy(sourceDllPath, targetDllPath, overwrite: true);
// 4. speedhack_config.json の生成・書き込み
var configContent = GenerateSpeedhackConfig(baseSpeed, toggleSpeed, holdSpeed);
var configContent = this.GenerateSpeedhackConfig(baseSpeed, toggleSpeed, holdSpeed);
File.WriteAllText(targetConfigPath, configContent, new UTF8Encoding(false));
game.WolfProxyDll = true;
@@ -138,7 +138,7 @@ namespace GameLauncher.Engines.Wolf
var sb = new StringBuilder();
// 1. プロキシDLLの解除
var (dllSuccess, dllMsg) = RemoveProxyDll(game);
var (dllSuccess, dllMsg) = this.RemoveProxyDll(game);
sb.AppendLine(dllMsg);
// 2. Game.exe バックアップからの復元(存在する場合)
+6 -6
View File
@@ -108,7 +108,7 @@ namespace GameLauncher.Engines.Wolf
catch { }
}
return result.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
return [.. result.Distinct(StringComparer.OrdinalIgnoreCase)];
}
/// <summary>
@@ -186,7 +186,7 @@ namespace GameLauncher.Engines.Wolf
throw new FileNotFoundException($"セーブデータファイルが見つかりません: {filePath}");
byte[] rawBytes = File.ReadAllBytes(filePath);
byte[] decrypted = Decrypt(rawBytes);
byte[] decrypted = this.Decrypt(rawBytes);
var result = new WolfSaveData
{
@@ -217,10 +217,10 @@ namespace GameLauncher.Engines.Wolf
}
// セーブデータ内の全文字列スキャン
ScanStrings(result, decrypted, enc);
this.ScanStrings(result, decrypted, enc);
// セーブデータ内の通常変数スキャン
ScanVariables(result, decrypted);
this.ScanVariables(result, decrypted);
return result;
}
@@ -293,7 +293,7 @@ namespace GameLauncher.Engines.Wolf
throw new InvalidOperationException("保存対象のデータが空です。");
// 1. バックアップ作成 (Backups フォルダへ)
string? backupPath = BackupSaveFile(model.FilePath, folderName, rootDirectory);
string? backupPath = this.BackupSaveFile(model.FilePath, folderName, rootDirectory);
// 2. 変数・項目の変更を RawDecryptedBytes に書き戻し
foreach (var item in model.Variables)
@@ -306,7 +306,7 @@ namespace GameLauncher.Engines.Wolf
}
// 3. 暗号化 & チェックサム再計算
byte[] encrypted = Encrypt(model.RawDecryptedBytes);
byte[] encrypted = this.Encrypt(model.RawDecryptedBytes);
// 4. アトミック書き込み
string tempFile = model.FilePath + ".tmp_" + Guid.NewGuid().ToString("N");
+2 -2
View File
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
@@ -14,6 +14,7 @@
<PublishSingleFile>true</PublishSingleFile>
<IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
<DebugType>embedded</DebugType>
<ApplicationManifest>app.manifest</ApplicationManifest>
</PropertyGroup>
<ItemGroup>
@@ -24,7 +25,6 @@
<None Remove="Engines\Nwjs\Tools\speedhack-i686\hid.dll" />
<None Remove="Engines\Nwjs\Tools\speedhack-i686\version.dll" />
<None Remove="plugins\AlwaysMaxHpMp.js" />
<None Remove="plugins\GameLauncher_StandaloneMod.js" />
</ItemGroup>
<ItemGroup>
+1 -1
View File
@@ -1,3 +1,3 @@
<Solution>
<Solution>
<Project Path="GameLauncher.csproj" />
</Solution>
+19 -1
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.IO;
namespace GameLauncher.Helpers
@@ -157,6 +157,24 @@ namespace GameLauncher.Helpers
return path;
}
/// <summary>
/// サムネイル画像キャッシュの格納ルートディレクトリを取得します。
/// GameLauncher.exe のあるフォルダ直下の「Thumbnails」フォルダを使用・作成します。
/// </summary>
public static string GetThumbnailsDirectory()
{
var thumbDir = Path.Combine(GetExeDirectory(), "Thumbnails");
if (!Directory.Exists(thumbDir))
{
try
{
Directory.CreateDirectory(thumbDir);
}
catch { }
}
return thumbDir;
}
/// <summary>
/// Unityセーブデータバックアップ全体の格納ルートディレクトリを取得します。
/// GameLauncher.exe のあるフォルダ直下の「Backups」フォルダを使用・作成します。
+41 -1
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
@@ -108,4 +108,44 @@ namespace GameLauncher.Helpers
throw new NotImplementedException();
}
}
/// <summary>
/// 文字列が null または空文字(空白のみ含む)の場合に Collapsed、文字が存在する場合に Visible を返すコンバーター
/// </summary>
public class StringNotEmptyToVisibilityConverter : IValueConverter
{
public static readonly StringNotEmptyToVisibilityConverter Instance = new();
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
if (value is string s && !string.IsNullOrWhiteSpace(s))
{
return Visibility.Visible;
}
return Visibility.Collapsed;
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
/// <summary>
/// bool値が true の場合に Visible、false または null の場合に Collapsed を返すコンバーター
/// </summary>
public class BooleanToVisibilityConverter : IValueConverter
{
public static readonly BooleanToVisibilityConverter Instance = new();
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
return value is true ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
return value is Visibility v && v == Visibility.Visible;
}
}
}
+424 -462
View File
File diff suppressed because it is too large. Load diff
+858 -557
View File
File diff suppressed because it is too large. Load diff
+193 -39
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
@@ -22,6 +22,7 @@ namespace GameLauncher.Models
private ImageSource? _iconImage;
private DateTime? _lastLaunched;
private DateTime? _folderLastModified;
private bool _isBookmarked;
public event PropertyChangedEventHandler? PropertyChanged;
@@ -33,51 +34,51 @@ namespace GameLauncher.Models
/// <summary>ゲームの表示タイトル</summary>
public string Title
{
get => _title;
set { if (_title != value) { _title = value; OnPropertyChanged(); } }
get => this._title;
set { if (this._title != value) { this._title = value; this.OnPropertyChanged(); } }
}
/// <summary>フォルダ名</summary>
public string FolderName
{
get => _folderName;
set { if (_folderName != value) { _folderName = value; OnPropertyChanged(); } }
get => this._folderName;
set { if (this._folderName != value) { this._folderName = value; this.OnPropertyChanged(); } }
}
/// <summary>ゲームのルートディレクトリ絶対パス</summary>
public string RootDirectory
{
get => _rootDirectory;
set { if (_rootDirectory != value) { _rootDirectory = value; OnPropertyChanged(); } }
get => this._rootDirectory;
set { if (this._rootDirectory != value) { this._rootDirectory = value; this.OnPropertyChanged(); } }
}
/// <summary>ゲームの実行ファイル(.exe等)絶対パス</summary>
public string ExecutablePath
{
get => _executablePath;
set { if (_executablePath != value) { _executablePath = value; OnPropertyChanged(); } }
get => this._executablePath;
set { if (this._executablePath != value) { this._executablePath = value; this.OnPropertyChanged(); } }
}
/// <summary>アプリアイコン画像</summary>
public ImageSource? IconImage
{
get => _iconImage;
set { if (_iconImage != value) { _iconImage = value; OnPropertyChanged(); } }
get => this._iconImage;
set { if (this._iconImage != value) { this._iconImage = value; this.OnPropertyChanged(); } }
}
/// <summary>ランチャーからの最終起動日時</summary>
public DateTime? LastLaunched
{
get => _lastLaunched;
get => this._lastLaunched;
set
{
if (_lastLaunched != value)
if (this._lastLaunched != value)
{
_lastLaunched = value;
OnPropertyChanged();
OnPropertyChanged(nameof(LastLaunchedDisplay));
OnPropertyChanged(nameof(LastLaunchedCardDisplay));
OnPropertyChanged(nameof(LastLaunchedDetailDisplay));
this._lastLaunched = value;
this.OnPropertyChanged();
this.OnPropertyChanged(nameof(this.LastLaunchedDisplay));
this.OnPropertyChanged(nameof(this.LastLaunchedCardDisplay));
this.OnPropertyChanged(nameof(this.LastLaunchedDetailDisplay));
}
}
}
@@ -85,51 +86,111 @@ namespace GameLauncher.Models
/// <summary>フォルダ更新日時</summary>
public DateTime? FolderLastModified
{
get => _folderLastModified;
get => this._folderLastModified;
set
{
if (_folderLastModified != value)
if (this._folderLastModified != value)
{
_folderLastModified = value;
OnPropertyChanged();
OnPropertyChanged(nameof(FolderLastModifiedDisplay));
OnPropertyChanged(nameof(FolderLastModifiedCardDisplay));
OnPropertyChanged(nameof(FolderLastModifiedDetailDisplay));
this._folderLastModified = value;
this.OnPropertyChanged();
this.OnPropertyChanged(nameof(this.FolderLastModifiedDisplay));
this.OnPropertyChanged(nameof(this.FolderLastModifiedCardDisplay));
this.OnPropertyChanged(nameof(this.FolderLastModifiedDetailDisplay));
}
}
}
/// <summary>ユーザーによるブックマーク登録状態</summary>
public bool IsBookmarked
{
get => this._isBookmarked;
set
{
if (this._isBookmarked != value)
{
this._isBookmarked = value;
this.OnPropertyChanged();
this.OnPropertyChanged(nameof(this.BookmarkIcon));
this.OnPropertyChanged(nameof(this.BookmarkTooltip));
this.OnPropertyChanged(nameof(this.BookmarkButtonText));
this.OnPropertyChanged(nameof(this.BookmarkBrush));
}
}
}
public string BookmarkIcon => this._isBookmarked ? "★" : "☆";
public string BookmarkTooltip => this._isBookmarked ? "ブックマーク解除" : "ブックマークに追加";
public string BookmarkButtonText => this._isBookmarked ? "★ ブックマーク中" : "☆ ブックマーク";
public Brush BookmarkBrush => this._isBookmarked
? new SolidColorBrush(Color.FromRgb(0xFD, 0xCB, 0x6E))
: new SolidColorBrush(Color.FromArgb(0x88, 0xAA, 0xAA, 0xBB));
/// <summary>ゲームエンジンの種別</summary>
public abstract GameEngineKind EngineKind { get; }
public bool IsTkoolOrTyrano => EngineKind is GameEngineKind.Tkool or GameEngineKind.Tyrano;
public bool IsUnity => EngineKind == GameEngineKind.Unity;
public bool IsTkoolOrTyrano => this.EngineKind is GameEngineKind.Tkool or GameEngineKind.Tyrano;
public bool IsUnity => this.EngineKind == GameEngineKind.Unity;
/// <summary>Enigma Virtual Box でパックされたゲームか</summary>
public virtual bool IsEvb => false;
public string LastLaunchedDisplay => LastLaunched.HasValue
? LastLaunched.Value.ToString("yyyy/MM/dd HH:mm")
/// <summary>Enigma Virtual Box でパックされた exe を持つゲームかどうか</summary>
public virtual bool IsEvbPacked
{
get => false;
set { }
}
/// <summary>EVB 解凍済みかどうか</summary>
public virtual bool IsEvbExtracted
{
get => false;
set { }
}
/// <summary>EVB バッジの可視性(該当しなければ Collapsed)</summary>
public virtual Visibility EvbBadgeVisibility => Visibility.Collapsed;
/// <summary>EVB バッジのテキスト(該当しなければ空文字)</summary>
public virtual string EvbBadgeText => string.Empty;
/// <summary>EVB 要解凍バッジの可視性(該当しなければ Collapsed)</summary>
public virtual Visibility EvbNeedsUnpackVisibility => Visibility.Collapsed;
/// <summary>EVB 要解凍バッジのテキスト(該当しなければ空文字)</summary>
public virtual string EvbNeedsUnpackBadgeText => string.Empty;
/// <summary>EVB 解凍済みバッジの可視性(該当しなければ Collapsed)</summary>
public virtual Visibility EvbExtractedVisibility => Visibility.Collapsed;
/// <summary>EVB 解凍済みバッジのテキスト(該当しなければ空文字)</summary>
public virtual string EvbExtractedBadgeText => string.Empty;
/// <summary>EVB 詳細状態テキスト</summary>
public virtual string EvbDetailStatusText => string.Empty;
public string LastLaunchedDisplay => this.LastLaunched.HasValue
? this.LastLaunched.Value.ToString("yyyy/MM/dd HH:mm")
: "未起動";
public string LastLaunchedCardDisplay => LastLaunched.HasValue
? $"▶ {LastLaunched.Value:yy/MM/dd HH:mm}"
public string LastLaunchedCardDisplay => this.LastLaunched.HasValue
? $"▶ {this.LastLaunched.Value:yy/MM/dd HH:mm}"
: "▶ 未起動";
public string LastLaunchedDetailDisplay => LastLaunched.HasValue
? LastLaunched.Value.ToString("yyyy/MM/dd HH:mm:ss")
public string LastLaunchedDetailDisplay => this.LastLaunched.HasValue
? this.LastLaunched.Value.ToString("yyyy/MM/dd HH:mm:ss")
: "まだ起動されていません";
public string FolderLastModifiedDisplay => FolderLastModified.HasValue
? FolderLastModified.Value.ToString("yyyy/MM/dd HH:mm")
public string FolderLastModifiedDisplay => this.FolderLastModified.HasValue
? this.FolderLastModified.Value.ToString("yyyy/MM/dd HH:mm")
: "-";
public string FolderLastModifiedCardDisplay => FolderLastModified.HasValue
? $"📁 {FolderLastModified.Value:yy/MM/dd HH:mm}"
public string FolderLastModifiedCardDisplay => this.FolderLastModified.HasValue
? $"📁 {this.FolderLastModified.Value:yy/MM/dd HH:mm}"
: "📁 -";
public string FolderLastModifiedDetailDisplay => FolderLastModified.HasValue
? FolderLastModified.Value.ToString("yyyy/MM/dd HH:mm:ss")
public string FolderLastModifiedDetailDisplay => this.FolderLastModified.HasValue
? this.FolderLastModified.Value.ToString("yyyy/MM/dd HH:mm:ss")
: "不明";
// ================= バッジ・UIバインディング共通仮想プロパティ =================
@@ -157,6 +218,24 @@ namespace GameLauncher.Models
/// <summary>SRPG Studioか</summary>
public virtual bool IsSrpgStudio => false;
/// <summary>NW.js汎用ゲームか</summary>
public virtual bool IsNwjs => false;
/// <summary>その他のゲームエンジンか</summary>
public virtual bool IsOther => false;
/// <summary>
/// エンジン種別ラベルの表示文字列。空文字の場合はラベル自体を表示しません。
/// (Unity等は該当しないため空、ツクール系は MV/MZ 等を返す)
/// </summary>
public virtual string EngineLabelText => string.Empty;
/// <summary>エンジン種別ラベルの背景色</summary>
public virtual Brush EngineLabelBackground => Brushes.Transparent;
/// <summary>その他バッジの可視性(該当しなければ Collapsed)</summary>
public virtual Visibility OtherBadgeVisibility => Visibility.Collapsed;
/// <summary>プリンセスシナジー(専用改造対象のMZゲーム)か</summary>
public virtual bool IsPrincessSynergy => false;
@@ -188,6 +267,18 @@ namespace GameLauncher.Models
set { }
}
/// <summary>ウディタアーカイブバッジのテキスト(該当しなければ空文字)</summary>
public virtual string WolfArchiveBadgeText => string.Empty;
/// <summary>ウディタアーカイブバッジの背景色</summary>
public virtual Brush WolfArchiveBadgeBackground => Brushes.Transparent;
/// <summary>ウディタアーカイブバッジの可視性(該当しなければ Collapsed)</summary>
public virtual Visibility WolfArchiveBadgeVisibility => Visibility.Collapsed;
/// <summary>ウディタアーカイブ詳細状態テキスト</summary>
public virtual string WolfArchiveDetailStatusText => string.Empty;
/// <summary>SRPG Studioアーカイブ(data.dts)を持つか</summary>
public virtual bool HasSrpgArchive
{
@@ -226,6 +317,18 @@ namespace GameLauncher.Models
/// <summary>SRPG Studio詳細状態テキスト</summary>
public virtual string SrpgDetailStatusText => string.Empty;
/// <summary>NW.jsバッジのテキスト</summary>
public virtual string NwjsBadgeText => string.Empty;
/// <summary>NW.jsバッジの背景色</summary>
public virtual Brush NwjsBadgeBackground => Brushes.Transparent;
/// <summary>NW.jsバッジの可視性</summary>
public virtual Visibility NwjsBadgeVisibility => Visibility.Collapsed;
/// <summary>NW.js詳細状態テキスト</summary>
public virtual string NwjsDetailStatusText => string.Empty;
/// <summary>Unity IL2CPPか</summary>
public virtual bool IsIL2CPP => false;
@@ -301,5 +404,56 @@ namespace GameLauncher.Models
get => _emptyPluginOptions;
set { }
}
/// <summary>共通プラグイン設定コレクション</summary>
public virtual ObservableCollection<ModPluginOptionItem> CommonPluginOptions
{
get => _emptyPluginOptions;
set { }
}
/// <summary>固有ゲーム専用プラグイン設定コレクション</summary>
public virtual ObservableCollection<ModPluginOptionItem> SpecificPluginOptions
{
get => _emptyPluginOptions;
set { }
}
/// <summary>固有ゲーム専用プラグインが存在するかどうか</summary>
public virtual bool HasSpecificPlugins => false;
/// <summary>プリンセスシナジー専用: HP常時MAX</summary>
public virtual bool PrincessAlwaysMaxHp
{
get => false;
set { }
}
/// <summary>プリンセスシナジー専用: MP常時MAX</summary>
public virtual bool PrincessAlwaysMaxMp
{
get => false;
set { }
}
/// <summary>ウディタ プロキシDLL適用フラグ</summary>
public virtual bool WolfProxyDll
{
get => false;
set { }
}
/// <summary>SRPG Studio プロキシDLL適用フラグ</summary>
public virtual bool SrpgProxyDll
{
get => false;
set { }
}
/// <summary>
/// スクリプト改造(プラグイン注入など)が適用可能な状態かどうか。
/// 該当ゲームが改造非対応(ウディタ・SRPG・NW.js・その他・未解凍状態など)の場合は false を返し、
/// 右側パネルのスクリプト改造項目を非表示にします。
/// </summary>
public virtual bool CanApplyScriptMod => false;
}
}
+13 -2
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections;
using System.Collections.Generic;
using GameLauncher.Engines.Tkool;
@@ -40,6 +40,7 @@ namespace GameLauncher.Models
public bool TkoolFilterAsarOnly { get; set; }
public bool TkoolFilterRgssOnly { get; set; }
public bool TkoolFilterAllRgss { get; set; }
public bool FilterBookmarkedOnly { get; set; }
public string UnityBackendFilter { get; set; } = "All";
public bool UnityFilterSaveOnly { get; set; }
}
@@ -56,8 +57,9 @@ namespace GameLauncher.Models
if (x is not GameItemBase a || y is not GameItemBase b)
return 0;
return SortOrder switch
return this.SortOrder switch
{
GameSortOrder.BookmarkedFirst => CompareBookmarkedFirst(a, b),
GameSortOrder.LastLaunchedDesc => CompareNullableDateTimeDesc(a.LastLaunched, b.LastLaunched, a.Title, b.Title),
GameSortOrder.LastLaunchedAsc => CompareNullableDateTimeAsc(a.LastLaunched, b.LastLaunched, a.Title, b.Title),
GameSortOrder.FolderLastModifiedDesc => CompareNullableDateTimeDesc(a.FolderLastModified, b.FolderLastModified, a.Title, b.Title),
@@ -69,6 +71,15 @@ namespace GameLauncher.Models
};
}
private static int CompareBookmarkedFirst(GameItemBase a, GameItemBase b)
{
if (a.IsBookmarked != b.IsBookmarked)
{
return a.IsBookmarked ? -1 : 1;
}
return CompareNullableDateTimeDesc(a.LastLaunched, b.LastLaunched, a.Title, b.Title);
}
private static int CompareNullableDateTimeDesc(DateTime? d1, DateTime? d2, string title1, string title2)
{
if (d1.HasValue && d2.HasValue)
+39 -9
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.CompilerServices;
@@ -17,6 +17,18 @@ namespace GameLauncher.Models
public string FileName { get; set; } = string.Empty; // ファイル名 (例: "BattleSpeedUp.js")
public string FilePath { get; set; } = string.Empty; // フルパス
/// <summary>特定ゲーム専用プラグインかどうか</summary>
public bool IsGameSpecific { get; set; }
/// <summary>対象ゲーム識別子 (例: "PrincessSynergy")</summary>
public string TargetGameKey { get; set; } = string.Empty;
/// <summary>表示用グループ名</summary>
public string GroupName { get; set; } = "共通機能";
/// <summary>初期チェックの既定値 (未設定時の初期値)</summary>
public bool DefaultEnabled { get; set; } = true;
/// <summary>
/// .js ファイルから定義情報を解析・生成します。
/// </summary>
@@ -38,6 +50,16 @@ namespace GameLauncher.Models
catch { }
string displayName = GetFriendlyName(id, desc);
bool isSpecific = id is "AlwaysMaxHp" or "AlwaysMaxMp";
string targetKey = isSpecific ? "PrincessSynergy" : string.Empty;
string groupName = isSpecific ? "固有ゲーム専用プラグイン" : "共通プラグイン";
bool defEnabled = id switch
{
"ShopMaxBuy" => false,
"AlwaysMaxHp" => false,
"AlwaysMaxMp" => false,
_ => true
};
return new ModPluginDefinition
{
@@ -45,7 +67,11 @@ namespace GameLauncher.Models
Name = displayName,
Description = desc,
FileName = fileName,
FilePath = filePath
FilePath = filePath,
IsGameSpecific = isSpecific,
TargetGameKey = targetKey,
GroupName = groupName,
DefaultEnabled = defEnabled
};
}
@@ -65,6 +91,8 @@ namespace GameLauncher.Models
"GoldGainMax" => "所持金増減時MAX (9999999G)",
"ExpGainMax" => "経験値獲得時MAX (一気にLv99)",
"MessageInstant" => "メッセージ瞬間表示 (ウェイトスキップ)",
"AlwaysMaxHp" => "HP常時MAX (プリンセスシナジー専用)",
"AlwaysMaxMp" => "MP常時MAX (プリンセスシナジー専用)",
_ => !string.IsNullOrEmpty(desc) ? $"{id} ({desc})" : id
};
}
@@ -78,19 +106,21 @@ namespace GameLauncher.Models
private bool _isEnabled = true;
public ModPluginDefinition Definition { get; set; } = null!;
public string Id => Definition.Id;
public string Name => Definition.Name;
public string Description => Definition.Description;
public string Id => this.Definition.Id;
public string Name => this.Definition.Name;
public string Description => this.Definition.Description;
public string GroupName => this.Definition.GroupName;
public bool IsGameSpecific => this.Definition.IsGameSpecific;
public bool IsEnabled
{
get => _isEnabled;
get => this._isEnabled;
set
{
if (_isEnabled != value)
if (this._isEnabled != value)
{
_isEnabled = value;
OnPropertyChanged();
this._isEnabled = value;
this.OnPropertyChanged();
}
}
}
+17 -17
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
@@ -26,36 +26,36 @@ namespace GameLauncher.Models
/// <summary>項目名(キー名、変数名)</summary>
public string Key
{
get => _key;
set { if (_key != value) { _key = value; OnPropertyChanged(); } }
get => this._key;
set { if (this._key != value) { this._key = value; this.OnPropertyChanged(); } }
}
/// <summary>分類・カテゴリ(セクション、オブジェクト名など)</summary>
public string Category
{
get => _category;
set { if (_category != value) { _category = value; OnPropertyChanged(); } }
get => this._category;
set { if (this._category != value) { this._category = value; this.OnPropertyChanged(); } }
}
/// <summary>データ型(Int, Float, Bool, String など)</summary>
public string Type
{
get => _type;
set { if (_type != value) { _type = value; OnPropertyChanged(); } }
get => this._type;
set { if (this._type != value) { this._type = value; this.OnPropertyChanged(); } }
}
/// <summary>GUI編集用の値文字列</summary>
public string EditValue
{
get => _editValue;
get => this._editValue;
set
{
if (_editValue != value)
if (this._editValue != value)
{
_editValue = value;
_isModified = true;
OnPropertyChanged();
OnPropertyChanged(nameof(IsModified));
this._editValue = value;
this._isModified = true;
this.OnPropertyChanged();
this.OnPropertyChanged(nameof(this.IsModified));
}
}
}
@@ -63,15 +63,15 @@ namespace GameLauncher.Models
/// <summary>値がユーザーによって変更されたかどうか</summary>
public bool IsModified
{
get => _isModified;
set { if (_isModified != value) { _isModified = value; OnPropertyChanged(); } }
get => this._isModified;
set { if (this._isModified != value) { this._isModified = value; this.OnPropertyChanged(); } }
}
/// <summary>備考・説明・オフセット位置など</summary>
public string Description
{
get => _description;
set { if (_description != value) { _description = value; OnPropertyChanged(); } }
get => this._description;
set { if (this._description != value) { this._description = value; this.OnPropertyChanged(); } }
}
/// <summary>内部保持用の生データや元データ(再エンコード用)</summary>
+1 -1
View File
@@ -1,4 +1,4 @@
# GameLauncher (ツクールMV・MZ・ティラノ & Unity 統合ゲームランチャー)
# GameLauncher (ツクールMV・MZ・ティラノ & Unity 統合ゲームランチャー)
RPGツクール(MV・MZ)、ティラノスクリプト、およびUnity製ゲームを1つの洗練された画面で一元管理・高速起動できる統合ランチャーです。
従来の **TkoolLauncher** と **UnityLauncher** の全機能(スクリプト改造、ASAR解凍・復元、PlayerPrefsレジストリ編集、セーブファイル編集、バックアップ)が欠けることなく完全に統合されています。
+3 -3
View File
@@ -1,4 +1,4 @@
<Window x:Class="GameLauncher.SaveEditorWindow"
<Window x:Class="GameLauncher.SaveEditorWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
@@ -293,7 +293,7 @@
<TextBlock x:Name="lblSelectedKeyName" Text="(なし)" FontWeight="SemiBold" Foreground="{StaticResource TextPrimary}" FontSize="12"/>
</StackPanel>
<TextBox x:Name="txtEditValueBar" Grid.Column="1" Background="#262636" BorderBrush="{StaticResource BorderBrushColor}"
<TextBox x:Name="txtEditValueBar" Grid.Column="1" Background="#262636" BorderBrush="{StaticResource BorderBrushColor}"
BorderThickness="1" Padding="8,4" Foreground="{StaticResource TextPrimary}" FontSize="12"
VerticalAlignment="Center" KeyDown="txtEditValueBar_KeyDown"/>
@@ -483,7 +483,7 @@
</StackPanel>
</Button>
<TextBlock Text="※コピーしたプロンプトを Antigravity IDE のチャットに貼り付けると、AIがセーブ構造を解析してGUI編集プラグインを即座に追加してくれます。"
<TextBlock Text="※コピーしたプロンプトを Antigravity IDE のチャットに貼り付けると、AIがセーブ構造を解析してGUI編集プラグインを即座に追加してくれます。"
Foreground="#A29BFE" FontSize="11" TextWrapping="Wrap" HorizontalAlignment="Center" TextAlignment="Center" Margin="0,0,0,16"/>
<Button Style="{StaticResource ModernButton}" Content="強制的にテキストとして開く" Click="btnForceShowBinary_Click" HorizontalAlignment="Center"/>
+162 -162
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
@@ -33,7 +33,7 @@ namespace GameLauncher
// PlayerPrefs データ
private readonly ObservableCollection<PlayerPrefsEntry> _allPrefs = [];
private ListCollectionView _prefsView = null!;
private readonly ListCollectionView _prefsView = null!;
// ファイル一覧データ
private readonly ObservableCollection<SaveFileEntry> _saveFiles = [];
@@ -41,7 +41,7 @@ namespace GameLauncher
// GUIセーブプロパティデータ
private readonly ObservableCollection<SaveDataPropertyEntry> _guiProperties = [];
private ListCollectionView _guiPropsView = null!;
private readonly ListCollectionView _guiPropsView = null!;
private ISaveDataCodec? _currentCodec;
// バックアップ一覧データ
@@ -49,36 +49,36 @@ namespace GameLauncher
public SaveEditorWindow(UnityGameItem game)
{
InitializeComponent();
Game = game;
this.InitializeComponent();
this.Game = game;
lblGameTitle.Text = game.Title;
lblGameInfo.Text = $"{game.CompanyName} / {game.ProductName} ({game.BackendBadgeText})";
this.lblGameTitle.Text = game.Title;
this.lblGameInfo.Text = $"{game.CompanyName} / {game.ProductName} ({game.BackendBadgeText})";
// PlayerPrefs ビュー
_prefsView = (ListCollectionView)CollectionViewSource.GetDefaultView(_allPrefs);
_prefsView.Filter = FilterPrefs;
dgPlayerPrefs.ItemsSource = _prefsView;
this._prefsView = (ListCollectionView)CollectionViewSource.GetDefaultView(this._allPrefs);
this._prefsView.Filter = this.FilterPrefs;
this.dgPlayerPrefs.ItemsSource = this._prefsView;
// ファイル一覧
lstSaveFiles.ItemsSource = _saveFiles;
this.lstSaveFiles.ItemsSource = this._saveFiles;
// GUI プロパティビュー
_guiPropsView = (ListCollectionView)CollectionViewSource.GetDefaultView(_guiProperties);
_guiPropsView.Filter = FilterGuiProperties;
dgGuiProperties.ItemsSource = _guiPropsView;
this._guiPropsView = (ListCollectionView)CollectionViewSource.GetDefaultView(this._guiProperties);
this._guiPropsView.Filter = this.FilterGuiProperties;
this.dgGuiProperties.ItemsSource = this._guiPropsView;
// バックアップ一覧
dgBackups.ItemsSource = _backups;
this.dgBackups.ItemsSource = this._backups;
Loaded += SaveEditorWindow_Loaded;
Loaded += this.SaveEditorWindow_Loaded;
}
private void SaveEditorWindow_Loaded(object sender, RoutedEventArgs e)
{
ReloadPlayerPrefs();
ReloadSaveFiles();
ReloadBackups();
this.ReloadPlayerPrefs();
this.ReloadSaveFiles();
this.ReloadBackups();
}
// ====================================================================
@@ -87,26 +87,26 @@ namespace GameLauncher
public void ReloadPlayerPrefs()
{
_allPrefs.Clear();
if (string.IsNullOrEmpty(Game.RegistryPath))
this._allPrefs.Clear();
if (string.IsNullOrEmpty(this.Game.RegistryPath))
{
lblStatus.Text = "レジストリ情報が設定されていません (app.info が見つかりませんでした)";
this.lblStatus.Text = "レジストリ情報が設定されていません (app.info が見つかりませんでした)";
return;
}
var entries = _saveService.GetPlayerPrefs(Game.RegistryPath);
var entries = this._saveService.GetPlayerPrefs(this.Game.RegistryPath);
foreach (var entry in entries)
{
_allPrefs.Add(entry);
this._allPrefs.Add(entry);
}
lblStatus.Text = $"PlayerPrefs: {entries.Count} 件のキーを読み込みました (HKCU\\{Game.RegistryPath})";
this.lblStatus.Text = $"PlayerPrefs: {entries.Count} 件のキーを読み込みました (HKCU\\{this.Game.RegistryPath})";
}
private bool FilterPrefs(object obj)
{
if (obj is not PlayerPrefsEntry entry) return false;
var query = txtSearchPrefs.Text.Trim();
var query = this.txtSearchPrefs.Text.Trim();
if (string.IsNullOrEmpty(query)) return true;
return entry.CleanKey.Contains(query, StringComparison.OrdinalIgnoreCase) ||
@@ -116,26 +116,26 @@ namespace GameLauncher
private void txtSearchPrefs_TextChanged(object sender, TextChangedEventArgs e)
{
_prefsView.Refresh();
this._prefsView.Refresh();
}
private void dgPlayerPrefs_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (dgPlayerPrefs.SelectedItem is PlayerPrefsEntry entry)
if (this.dgPlayerPrefs.SelectedItem is PlayerPrefsEntry entry)
{
lblSelectedKeyName.Text = entry.CleanKey;
txtEditValueBar.Text = entry.EditValue;
txtEditValueBar.IsEnabled = true;
btnSaveCurrentPref.IsEnabled = true;
btnDeleteCurrentPref.IsEnabled = true;
this.lblSelectedKeyName.Text = entry.CleanKey;
this.txtEditValueBar.Text = entry.EditValue;
this.txtEditValueBar.IsEnabled = true;
this.btnSaveCurrentPref.IsEnabled = true;
this.btnDeleteCurrentPref.IsEnabled = true;
}
else
{
lblSelectedKeyName.Text = "(なし)";
txtEditValueBar.Text = string.Empty;
txtEditValueBar.IsEnabled = false;
btnSaveCurrentPref.IsEnabled = false;
btnDeleteCurrentPref.IsEnabled = false;
this.lblSelectedKeyName.Text = "(なし)";
this.txtEditValueBar.Text = string.Empty;
this.txtEditValueBar.IsEnabled = false;
this.btnSaveCurrentPref.IsEnabled = false;
this.btnDeleteCurrentPref.IsEnabled = false;
}
}
@@ -143,25 +143,25 @@ namespace GameLauncher
{
if (e.Key == Key.Enter)
{
SaveCurrentSelectedPref();
this.SaveCurrentSelectedPref();
}
}
private void btnSaveCurrentPref_Click(object sender, RoutedEventArgs e)
{
SaveCurrentSelectedPref();
this.SaveCurrentSelectedPref();
}
private void SaveCurrentSelectedPref()
{
if (dgPlayerPrefs.SelectedItem is not PlayerPrefsEntry entry) return;
if (this.dgPlayerPrefs.SelectedItem is not PlayerPrefsEntry entry) return;
entry.EditValue = txtEditValueBar.Text;
bool success = _saveService.SavePlayerPref(Game.RegistryPath, entry);
entry.EditValue = this.txtEditValueBar.Text;
bool success = this._saveService.SavePlayerPref(this.Game.RegistryPath, entry);
if (success)
{
lblStatus.Text = $"キー '{entry.CleanKey}' の値を正常に更新しました。";
dgPlayerPrefs.Items.Refresh();
this.lblStatus.Text = $"キー '{entry.CleanKey}' の値を正常に更新しました。";
this.dgPlayerPrefs.Items.Refresh();
}
else
{
@@ -172,16 +172,16 @@ namespace GameLauncher
private void btnDeleteCurrentPref_Click(object sender, RoutedEventArgs e)
{
if (dgPlayerPrefs.SelectedItem is not PlayerPrefsEntry entry) return;
if (this.dgPlayerPrefs.SelectedItem is not PlayerPrefsEntry entry) return;
var res = MessageBox.Show($"キー '{entry.CleanKey}' ({entry.RawKey}) をレジストリから削除しますか?",
"キー削除の確認", MessageBoxButton.YesNo, MessageBoxImage.Warning);
if (res != MessageBoxResult.Yes) return;
if (_saveService.DeletePlayerPref(Game.RegistryPath, entry.RawKey))
if (this._saveService.DeletePlayerPref(this.Game.RegistryPath, entry.RawKey))
{
_allPrefs.Remove(entry);
lblStatus.Text = $"キー '{entry.CleanKey}' を削除しました。";
this._allPrefs.Remove(entry);
this.lblStatus.Text = $"キー '{entry.CleanKey}' を削除しました。";
}
else
{
@@ -194,10 +194,10 @@ namespace GameLauncher
var dlg = new AddKeyDialog { Owner = this };
if (dlg.ShowDialog() == true)
{
if (_saveService.AddPlayerPref(Game.RegistryPath, dlg.KeyName, dlg.KeyType, dlg.KeyValue, out string rawKey))
if (this._saveService.AddPlayerPref(this.Game.RegistryPath, dlg.KeyName, dlg.KeyType, dlg.KeyValue, out string rawKey))
{
ReloadPlayerPrefs();
lblStatus.Text = $"新規キー '{dlg.KeyName}' ({rawKey}) を追加しました。";
this.ReloadPlayerPrefs();
this.lblStatus.Text = $"新規キー '{dlg.KeyName}' ({rawKey}) を追加しました。";
}
else
{
@@ -208,12 +208,12 @@ namespace GameLauncher
private void btnBackupPrefs_Click(object sender, RoutedEventArgs e)
{
var backupDir = AppPathHelper.GetGameBackupDirectory(Game.FolderName, Game.RootDirectory);
var result = _saveService.BackupRegistry(Game.RegistryPath, backupDir);
var backupDir = AppPathHelper.GetGameBackupDirectory(this.Game.FolderName, this.Game.RootDirectory);
var result = this._saveService.BackupRegistry(this.Game.RegistryPath, backupDir);
if (result != null)
{
ReloadBackups();
lblStatus.Text = $"レジストリをバックアップしました: {Path.GetFileName(result)}";
this.ReloadBackups();
this.lblStatus.Text = $"レジストリをバックアップしました: {Path.GetFileName(result)}";
MessageBox.Show($"レジストリをバックアップしました:\n\n{result}", "バックアップ完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
@@ -224,7 +224,7 @@ namespace GameLauncher
private void btnRestorePrefs_Click(object sender, RoutedEventArgs e)
{
var backupDir = AppPathHelper.GetGameBackupDirectory(Game.FolderName, Game.RootDirectory);
var backupDir = AppPathHelper.GetGameBackupDirectory(this.Game.FolderName, this.Game.RootDirectory);
var dlg = new OpenFileDialog
{
Title = "復元する .reg ファイルを選択",
@@ -238,10 +238,10 @@ namespace GameLauncher
"復元の確認", MessageBoxButton.YesNo, MessageBoxImage.Warning);
if (res != MessageBoxResult.Yes) return;
if (_saveService.RestoreRegistry(dlg.FileName))
if (this._saveService.RestoreRegistry(dlg.FileName))
{
ReloadPlayerPrefs();
lblStatus.Text = "レジストリを正常に復元しました。";
this.ReloadPlayerPrefs();
this.lblStatus.Text = "レジストリを正常に復元しました。";
MessageBox.Show("レジストリを正常に復元しました。", "復元完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
@@ -253,17 +253,17 @@ namespace GameLauncher
private void btnReloadPrefs_Click(object sender, RoutedEventArgs e)
{
ReloadPlayerPrefs();
this.ReloadPlayerPrefs();
}
private void ctxSavePref_Click(object sender, RoutedEventArgs e)
{
SaveCurrentSelectedPref();
this.SaveCurrentSelectedPref();
}
private void ctxCopyKey_Click(object sender, RoutedEventArgs e)
{
if (dgPlayerPrefs.SelectedItem is PlayerPrefsEntry entry)
if (this.dgPlayerPrefs.SelectedItem is PlayerPrefsEntry entry)
{
Clipboard.SetText(entry.CleanKey);
}
@@ -271,7 +271,7 @@ namespace GameLauncher
private void ctxCopyValue_Click(object sender, RoutedEventArgs e)
{
if (dgPlayerPrefs.SelectedItem is PlayerPrefsEntry entry)
if (this.dgPlayerPrefs.SelectedItem is PlayerPrefsEntry entry)
{
Clipboard.SetText(entry.EditValue);
}
@@ -279,7 +279,7 @@ namespace GameLauncher
private void ctxDeletePref_Click(object sender, RoutedEventArgs e)
{
btnDeleteCurrentPref_Click(sender, e);
this.btnDeleteCurrentPref_Click(sender, e);
}
// ====================================================================
@@ -288,98 +288,98 @@ namespace GameLauncher
public void ReloadSaveFiles()
{
_saveFiles.Clear();
var files = _saveService.GetSaveFiles(Game);
this._saveFiles.Clear();
var files = this._saveService.GetSaveFiles(this.Game);
foreach (var f in files)
{
_saveFiles.Add(f);
this._saveFiles.Add(f);
}
if (_saveFiles.Count > 0)
if (this._saveFiles.Count > 0)
{
lstSaveFiles.SelectedIndex = 0;
this.lstSaveFiles.SelectedIndex = 0;
}
else
{
lblCurrentFileName.Text = "セーブファイルは見つかりませんでした";
lblCurrentFilePath.Text = string.Empty;
txtFileContent.Text = string.Empty;
HideAllEditorPanels();
this.lblCurrentFileName.Text = "セーブファイルは見つかりませんでした";
this.lblCurrentFilePath.Text = string.Empty;
this.txtFileContent.Text = string.Empty;
this.HideAllEditorPanels();
}
}
private void HideAllEditorPanels()
{
pnlGuiEditor.Visibility = Visibility.Collapsed;
pnlTextEditor.Visibility = Visibility.Collapsed;
pnlUnsupportedBinary.Visibility = Visibility.Collapsed;
btnFormatJson.Visibility = Visibility.Collapsed;
btnSaveFileContent.Visibility = Visibility.Collapsed;
btnSaveGuiProperties.Visibility = Visibility.Collapsed;
badgeCodec.Visibility = Visibility.Collapsed;
this.pnlGuiEditor.Visibility = Visibility.Collapsed;
this.pnlTextEditor.Visibility = Visibility.Collapsed;
this.pnlUnsupportedBinary.Visibility = Visibility.Collapsed;
this.btnFormatJson.Visibility = Visibility.Collapsed;
this.btnSaveFileContent.Visibility = Visibility.Collapsed;
this.btnSaveGuiProperties.Visibility = Visibility.Collapsed;
this.badgeCodec.Visibility = Visibility.Collapsed;
}
private void lstSaveFiles_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lstSaveFiles.SelectedItem is not SaveFileEntry entry) return;
_currentSelectedFile = entry;
if (this.lstSaveFiles.SelectedItem is not SaveFileEntry entry) return;
this._currentSelectedFile = entry;
lblCurrentFileName.Text = entry.FileName;
lblCurrentFilePath.Text = entry.FilePath;
HideAllEditorPanels();
this.lblCurrentFileName.Text = entry.FileName;
this.lblCurrentFilePath.Text = entry.FilePath;
this.HideAllEditorPanels();
// 1. コーデック(対応形式)が存在するか判定
var codec = SaveDataCodecManager.Instance.FindCodec(Game, entry);
var codec = SaveDataCodecManager.Instance.FindCodec(this.Game, entry);
if (codec != null)
{
// GUI エディタモードをアクティブ化
_currentCodec = codec;
badgeCodec.Visibility = Visibility.Visible;
lblCodecName.Text = codec.CodecName;
this._currentCodec = codec;
this.badgeCodec.Visibility = Visibility.Visible;
this.lblCodecName.Text = codec.CodecName;
LoadGuiPropertiesFromCodec(codec, entry.FilePath);
pnlGuiEditor.Visibility = Visibility.Visible;
btnSaveGuiProperties.Visibility = Visibility.Visible;
lblStatus.Text = $"{codec.CodecName} で読み込みました: {entry.FileName}";
this.LoadGuiPropertiesFromCodec(codec, entry.FilePath);
this.pnlGuiEditor.Visibility = Visibility.Visible;
this.btnSaveGuiProperties.Visibility = Visibility.Visible;
this.lblStatus.Text = $"{codec.CodecName} で読み込みました: {entry.FileName}";
return;
}
// 2. プレーンテキスト/JSON形式の場合
if (entry.IsTextOrJson)
{
pnlTextEditor.Visibility = Visibility.Visible;
txtFileContent.Text = _saveService.ReadSaveFileText(entry.FilePath);
btnFormatJson.Visibility = Visibility.Visible;
btnSaveFileContent.Visibility = Visibility.Visible;
lblStatus.Text = $"テキストとして開きました: {entry.FileName}";
this.pnlTextEditor.Visibility = Visibility.Visible;
this.txtFileContent.Text = this._saveService.ReadSaveFileText(entry.FilePath);
this.btnFormatJson.Visibility = Visibility.Visible;
this.btnSaveFileContent.Visibility = Visibility.Visible;
this.lblStatus.Text = $"テキストとして開きました: {entry.FileName}";
return;
}
// 3. 未対応のバイナリセーブデータ形式の場合
pnlUnsupportedBinary.Visibility = Visibility.Visible;
DisplayUnsupportedBinaryInfo(entry);
lblStatus.Text = $"未対応のバイナリセーブデータ: {entry.FileName}";
this.pnlUnsupportedBinary.Visibility = Visibility.Visible;
this.DisplayUnsupportedBinaryInfo(entry);
this.lblStatus.Text = $"未対応のバイナリセーブデータ: {entry.FileName}";
}
private void LoadGuiPropertiesFromCodec(ISaveDataCodec codec, string filePath)
{
_guiProperties.Clear();
this._guiProperties.Clear();
var props = codec.LoadProperties(filePath);
foreach (var p in props)
{
_guiProperties.Add(p);
this._guiProperties.Add(p);
}
lblGuiPropCount.Text = $"{props.Count} 項目";
this.lblGuiPropCount.Text = $"{props.Count} 項目";
if (props.Count > 0)
{
dgGuiProperties.SelectedIndex = 0;
this.dgGuiProperties.SelectedIndex = 0;
}
}
private bool FilterGuiProperties(object obj)
{
if (obj is not SaveDataPropertyEntry prop) return false;
var query = txtSearchGuiProps.Text.Trim();
var query = this.txtSearchGuiProps.Text.Trim();
if (string.IsNullOrEmpty(query)) return true;
return prop.Key.Contains(query, StringComparison.OrdinalIgnoreCase) ||
@@ -389,26 +389,26 @@ namespace GameLauncher
private void txtSearchGuiProps_TextChanged(object sender, TextChangedEventArgs e)
{
_guiPropsView.Refresh();
int visibleCount = _guiPropsView.Cast<object>().Count();
lblGuiPropCount.Text = $"{visibleCount} / {_guiProperties.Count} 項目";
this._guiPropsView.Refresh();
int visibleCount = this._guiPropsView.Cast<object>().Count();
this.lblGuiPropCount.Text = $"{visibleCount} / {this._guiProperties.Count} 項目";
}
private void dgGuiProperties_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (dgGuiProperties.SelectedItem is SaveDataPropertyEntry prop)
if (this.dgGuiProperties.SelectedItem is SaveDataPropertyEntry prop)
{
lblSelectedPropKey.Text = prop.Key;
txtEditPropValueBar.Text = prop.EditValue;
txtEditPropValueBar.IsEnabled = true;
btnApplyPropValue.IsEnabled = true;
this.lblSelectedPropKey.Text = prop.Key;
this.txtEditPropValueBar.Text = prop.EditValue;
this.txtEditPropValueBar.IsEnabled = true;
this.btnApplyPropValue.IsEnabled = true;
}
else
{
lblSelectedPropKey.Text = "(未選択)";
txtEditPropValueBar.Text = string.Empty;
txtEditPropValueBar.IsEnabled = false;
btnApplyPropValue.IsEnabled = false;
this.lblSelectedPropKey.Text = "(未選択)";
this.txtEditPropValueBar.Text = string.Empty;
this.txtEditPropValueBar.IsEnabled = false;
this.btnApplyPropValue.IsEnabled = false;
}
}
@@ -416,28 +416,28 @@ namespace GameLauncher
{
if (e.Key == Key.Enter)
{
btnApplyPropValue_Click(sender, e);
this.btnApplyPropValue_Click(sender, e);
}
}
private void btnApplyPropValue_Click(object sender, RoutedEventArgs e)
{
if (dgGuiProperties.SelectedItem is SaveDataPropertyEntry prop)
if (this.dgGuiProperties.SelectedItem is SaveDataPropertyEntry prop)
{
prop.EditValue = txtEditPropValueBar.Text;
dgGuiProperties.Items.Refresh();
lblStatus.Text = $"項目 '{prop.Key}' の値を変更しました。(「変更を保存」ボタンでファイルへ書き戻せます)";
prop.EditValue = this.txtEditPropValueBar.Text;
this.dgGuiProperties.Items.Refresh();
this.lblStatus.Text = $"項目 '{prop.Key}' の値を変更しました。(「変更を保存」ボタンでファイルへ書き戻せます)";
}
}
private void btnSaveGuiProperties_Click(object sender, RoutedEventArgs e)
{
if (_currentSelectedFile == null || _currentCodec == null) return;
if (this._currentSelectedFile == null || this._currentCodec == null) return;
bool success = _currentCodec.SaveProperties(_currentSelectedFile.FilePath, _guiProperties.ToList());
bool success = this._currentCodec.SaveProperties(this._currentSelectedFile.FilePath, [.. this._guiProperties]);
if (success)
{
lblStatus.Text = $"セーブファイルを正常に更新しました (自動バックアップ .bak 作成済み): {_currentSelectedFile.FileName}";
this.lblStatus.Text = $"セーブファイルを正常に更新しました (自動バックアップ .bak 作成済み): {this._currentSelectedFile.FileName}";
MessageBox.Show("セーブファイルを正常に更新・保存しました。\n(元のファイルは同階層に .bak として自動バックアップされています)",
"保存完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
@@ -460,41 +460,41 @@ namespace GameLauncher
{
hexList.Add(bytes[i].ToString("X2"));
}
lblHexPreview.Text = string.Join(" ", hexList) + (bytes.Length > 32 ? " ..." : "");
this.lblHexPreview.Text = string.Join(" ", hexList) + (bytes.Length > 32 ? " ..." : "");
}
}
catch
{
lblHexPreview.Text = "(読み込み失敗)";
this.lblHexPreview.Text = "(読み込み失敗)";
}
}
private void btnCopyIdePrompt_Click(object sender, RoutedEventArgs e)
{
if (_currentSelectedFile == null) return;
if (this._currentSelectedFile == null) return;
string prompt = SaveDataCodecManager.Instance.GenerateAntigravityPrompt(Game, _currentSelectedFile);
string prompt = SaveDataCodecManager.Instance.GenerateAntigravityPrompt(this.Game, this._currentSelectedFile);
Clipboard.SetText(prompt);
lblStatus.Text = "📋 Antigravity IDE 用の解析依頼プロンプトをクリップボードにコピーしました!";
this.lblStatus.Text = "📋 Antigravity IDE 用の解析依頼プロンプトをクリップボードにコピーしました!";
MessageBox.Show("Antigravity IDE 解析用プロンプトをコピーしました!\n\nAntigravity IDE のチャット欄に貼り付けて送信すると、AIがこのゲームのセーブデータ構造を解析し、GUI編集プラグインを自動で追加してくれます。",
"プロンプトをコピーしました", MessageBoxButton.OK, MessageBoxImage.Information);
}
private void btnForceShowBinary_Click(object sender, RoutedEventArgs e)
{
if (_currentSelectedFile == null) return;
pnlUnsupportedBinary.Visibility = Visibility.Collapsed;
pnlTextEditor.Visibility = Visibility.Visible;
btnSaveFileContent.Visibility = Visibility.Visible;
txtFileContent.Text = _saveService.ReadSaveFileText(_currentSelectedFile.FilePath);
if (this._currentSelectedFile == null) return;
this.pnlUnsupportedBinary.Visibility = Visibility.Collapsed;
this.pnlTextEditor.Visibility = Visibility.Visible;
this.btnSaveFileContent.Visibility = Visibility.Visible;
this.txtFileContent.Text = this._saveService.ReadSaveFileText(this._currentSelectedFile.FilePath);
}
private void btnFormatJson_Click(object sender, RoutedEventArgs e)
{
try
{
var raw = txtFileContent.Text;
var raw = this.txtFileContent.Text;
if (string.IsNullOrWhiteSpace(raw)) return;
using var doc = JsonDocument.Parse(raw);
@@ -503,8 +503,8 @@ namespace GameLauncher
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
});
txtFileContent.Text = formatted;
lblStatus.Text = "JSONを整形しました。";
this.txtFileContent.Text = formatted;
this.lblStatus.Text = "JSONを整形しました。";
}
catch (Exception ex)
{
@@ -514,12 +514,12 @@ namespace GameLauncher
private void btnSaveFileContent_Click(object sender, RoutedEventArgs e)
{
if (_currentSelectedFile == null) return;
if (this._currentSelectedFile == null) return;
bool success = _saveService.WriteSaveFileText(_currentSelectedFile.FilePath, txtFileContent.Text);
bool success = this._saveService.WriteSaveFileText(this._currentSelectedFile.FilePath, this.txtFileContent.Text);
if (success)
{
lblStatus.Text = $"ファイルを保存しました (自動バックアップ .bak 作成済み): {_currentSelectedFile.FileName}";
this.lblStatus.Text = $"ファイルを保存しました (自動バックアップ .bak 作成済み): {this._currentSelectedFile.FileName}";
MessageBox.Show("ファイルを保存しました。\n(元のファイルは同階層に .bak としてバックアップされています)",
"保存完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
@@ -532,14 +532,14 @@ namespace GameLauncher
private void btnBackupSingleFile_Click(object sender, RoutedEventArgs e)
{
if (_currentSelectedFile == null) return;
if (this._currentSelectedFile == null) return;
var backupDir = AppPathHelper.GetGameBackupDirectory(Game.FolderName, Game.RootDirectory);
var result = _saveService.BackupSaveFile(_currentSelectedFile.FilePath, backupDir);
var backupDir = AppPathHelper.GetGameBackupDirectory(this.Game.FolderName, this.Game.RootDirectory);
var result = this._saveService.BackupSaveFile(this._currentSelectedFile.FilePath, backupDir);
if (result != null)
{
ReloadBackups();
lblStatus.Text = $"ファイルをバックアップしました: {Path.GetFileName(result)}";
this.ReloadBackups();
this.lblStatus.Text = $"ファイルをバックアップしました: {Path.GetFileName(result)}";
MessageBox.Show($"ファイルをバックアップしました:\n\n{result}", "バックアップ完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
@@ -550,7 +550,7 @@ namespace GameLauncher
private void btnReloadSaveFiles_Click(object sender, RoutedEventArgs e)
{
ReloadSaveFiles();
this.ReloadSaveFiles();
}
// ====================================================================
@@ -559,22 +559,22 @@ namespace GameLauncher
public void ReloadBackups()
{
_backups.Clear();
var list = _saveService.GetBackupList(Game);
this._backups.Clear();
var list = this._saveService.GetBackupList(this.Game);
foreach (var b in list)
{
_backups.Add(b);
this._backups.Add(b);
}
}
private void btnReloadBackups_Click(object sender, RoutedEventArgs e)
{
ReloadBackups();
this.ReloadBackups();
}
private void btnOpenBackupDir_Click(object sender, RoutedEventArgs e)
{
var backupDir = AppPathHelper.GetGameBackupDirectory(Game.FolderName, Game.RootDirectory);
var backupDir = AppPathHelper.GetGameBackupDirectory(this.Game.FolderName, this.Game.RootDirectory);
UnitySaveManagerService.OpenFolderInExplorer(backupDir);
}
@@ -588,9 +588,9 @@ namespace GameLauncher
"復元の確認", MessageBoxButton.YesNo, MessageBoxImage.Warning);
if (res == MessageBoxResult.Yes)
{
if (_saveService.RestoreRegistry(backup.BackupPath))
if (this._saveService.RestoreRegistry(backup.BackupPath))
{
ReloadPlayerPrefs();
this.ReloadPlayerPrefs();
MessageBox.Show("レジストリを正常に復元しました。", "復元完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
@@ -613,29 +613,29 @@ namespace GameLauncher
private void btnOpenLocalLow_Click(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrEmpty(Game.LocalLowPath))
if (!string.IsNullOrEmpty(this.Game.LocalLowPath))
{
if (!Directory.Exists(Game.LocalLowPath))
if (!Directory.Exists(this.Game.LocalLowPath))
{
var parent = Path.GetDirectoryName(Game.LocalLowPath);
var parent = Path.GetDirectoryName(this.Game.LocalLowPath);
if (parent != null && Directory.Exists(parent))
{
UnitySaveManagerService.OpenFolderInExplorer(parent);
return;
}
}
UnitySaveManagerService.OpenFolderInExplorer(Game.LocalLowPath);
UnitySaveManagerService.OpenFolderInExplorer(this.Game.LocalLowPath);
}
}
private void btnOpenGameFolder_Click(object sender, RoutedEventArgs e)
{
UnitySaveManagerService.OpenFolderInExplorer(Game.RootDirectory);
UnitySaveManagerService.OpenFolderInExplorer(this.Game.RootDirectory);
}
private void btnOpenRegedit_Click(object sender, RoutedEventArgs e)
{
_saveService.OpenRegistryEditor(Game.RegistryPath);
this._saveService.OpenRegistryEditor(this.Game.RegistryPath);
}
}
}
+106 -34
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
@@ -7,8 +7,8 @@ using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using GameLauncher.Models;
using GameLauncher.Engines.Unity;
using GameLauncher.Models;
namespace GameLauncher.Services.Codecs
{
@@ -17,10 +17,19 @@ namespace GameLauncher.Services.Codecs
/// </summary>
public class EasySave3Codec : ISaveDataCodec
{
/// <summary>
/// コーデックの表示名を取得します。
/// </summary>
public string CodecName => "Easy Save 3 (ES3) コーデック";
/// <summary>
/// パスワード入力が必要かどうかを取得します。
/// </summary>
public bool RequiresPassword => false;
/// <summary>
/// パスワード入力ダイアログに表示する案内メッセージを取得します。
/// </summary>
public string? PasswordPromptMessage => "暗号化パスワードが設定されている場合は入力してください(未設定・既定の場合は空欄):";
// キャッシュ用の最新平文JSONノード
@@ -28,6 +37,12 @@ namespace GameLauncher.Services.Codecs
private bool _wasEncrypted;
private string? _usedPassword;
/// <summary>
/// 指定されたセーブファイルが本コーデックで処理可能かを判定します。
/// </summary>
/// <param name="game">対象のUnityゲーム情報</param>
/// <param name="file">対象のセーブファイル情報</param>
/// <returns>処理可能な場合は true、それ以外は false</returns>
public bool CanHandle(UnityGameItem game, SaveFileEntry file)
{
var ext = Path.GetExtension(file.FilePath).ToLowerInvariant();
@@ -43,6 +58,12 @@ namespace GameLauncher.Services.Codecs
return false;
}
/// <summary>
/// セーブファイルからプロパティ一覧を読み込みます。
/// </summary>
/// <param name="filePath">セーブファイルの絶対パス</param>
/// <param name="optionalPassword">任意の暗号化パスワード</param>
/// <returns>展開されたセーブデータプロパティのリスト</returns>
public List<SaveDataPropertyEntry> LoadProperties(string filePath, string? optionalPassword = null)
{
var list = new List<SaveDataPropertyEntry>();
@@ -52,8 +73,8 @@ namespace GameLauncher.Services.Codecs
if (fileBytes.Length == 0) return list;
string? jsonText = null;
_wasEncrypted = false;
_usedPassword = null;
this._wasEncrypted = false;
this._usedPassword = null;
// 1. まず平文 JSON または Gzip 解凍を試みる
try
@@ -91,12 +112,12 @@ namespace GameLauncher.Services.Codecs
foreach (var pwd in candidatePasswords)
{
var decrypted = TryDecryptAes(fileBytes, pwd);
var decrypted = this.TryDecryptAes(fileBytes, pwd);
if (!string.IsNullOrEmpty(decrypted))
{
jsonText = decrypted;
_wasEncrypted = true;
_usedPassword = pwd;
this._wasEncrypted = true;
this._usedPassword = pwd;
break;
}
}
@@ -105,30 +126,36 @@ namespace GameLauncher.Services.Codecs
if (string.IsNullOrEmpty(jsonText))
{
// JSON展開ができなかった場合、バイナリキー・バリュー形式として先頭・重要オフセットを抽出
return ExtractBinaryPropertiesFallback(fileBytes);
return this.ExtractBinaryPropertiesFallback(fileBytes);
}
// JSON からプロパティを再帰的に展開
try
{
_cachedRootNode = JsonNode.Parse(jsonText);
if (_cachedRootNode is JsonObject rootObj)
this._cachedRootNode = JsonNode.Parse(jsonText);
if (this._cachedRootNode is JsonObject rootObj)
{
FlattenJsonObject(rootObj, "", list);
this.FlattenJsonObject(rootObj, "", list);
}
else if (_cachedRootNode is JsonArray rootArr)
else if (this._cachedRootNode is JsonArray rootArr)
{
FlattenJsonArray(rootArr, "Array", list);
this.FlattenJsonArray(rootArr, "Array", list);
}
}
catch
{
return ExtractBinaryPropertiesFallback(fileBytes);
return this.ExtractBinaryPropertiesFallback(fileBytes);
}
return list;
}
/// <summary>
/// JSONオブジェクトを再帰的に走査し、プロパティ一覧に追加します。
/// </summary>
/// <param name="obj">対象のJSONオブジェクト</param>
/// <param name="prefix">現在のキー階層プレフィックス</param>
/// <param name="list">追加先のプロパティリスト</param>
private void FlattenJsonObject(JsonObject obj, string prefix, List<SaveDataPropertyEntry> list)
{
foreach (var kvp in obj)
@@ -181,14 +208,14 @@ namespace GameLauncher.Services.Codecs
}
else
{
FlattenJsonObject(childObj, key, list);
this.FlattenJsonObject(childObj, key, list);
}
}
else if (node is JsonArray childArr)
{
if (childArr.Count <= 20)
{
FlattenJsonArray(childArr, key, list);
this.FlattenJsonArray(childArr, key, list);
}
else
{
@@ -206,6 +233,12 @@ namespace GameLauncher.Services.Codecs
}
}
/// <summary>
/// JSON配列を再帰的に走査し、プロパティ一覧に追加します。
/// </summary>
/// <param name="arr">対象のJSON配列</param>
/// <param name="prefix">現在のキー階層プレフィックス</param>
/// <param name="list">追加先のプロパティリスト</param>
private void FlattenJsonArray(JsonArray arr, string prefix, List<SaveDataPropertyEntry> list)
{
for (int i = 0; i < arr.Count; i++)
@@ -225,22 +258,29 @@ namespace GameLauncher.Services.Codecs
}
else if (node is JsonObject childObj)
{
FlattenJsonObject(childObj, key, list);
this.FlattenJsonObject(childObj, key, list);
}
}
}
/// <summary>
/// JSON展開に失敗した場合のフォールバックとしてバイナリ値を抽出します。
/// </summary>
/// <param name="bytes">ファイル全体のバイナリデータ</param>
/// <returns>バイナリ情報プロパティのリスト</returns>
private List<SaveDataPropertyEntry> ExtractBinaryPropertiesFallback(byte[] bytes)
{
var list = new List<SaveDataPropertyEntry>();
list.Add(new SaveDataPropertyEntry
var list = new List<SaveDataPropertyEntry>
{
Key = "FileSize",
Category = "ファイル情報",
Type = "Int",
EditValue = bytes.Length.ToString(),
Description = "ファイルサイズ (bytes)"
});
new SaveDataPropertyEntry
{
Key = "FileSize",
Category = "ファイル情報",
Type = "Int",
EditValue = bytes.Length.ToString(),
Description = "ファイルサイズ (bytes)"
}
};
// 先頭 128 バイトから 4 バイト整数と ASCII 文字列を検出してプロパティ化
int limit = Math.Min(bytes.Length - 4, 128);
@@ -261,18 +301,25 @@ namespace GameLauncher.Services.Codecs
return list;
}
/// <summary>
/// 編集後のプロパティ一覧をセーブファイルへ書き戻して保存します。
/// </summary>
/// <param name="filePath">保存先セーブファイルの絶対パス</param>
/// <param name="properties">編集されたプロパティ一覧</param>
/// <param name="optionalPassword">任意の暗号化パスワード</param>
/// <returns>保存に成功した場合は true、それ以外は false</returns>
public bool SaveProperties(string filePath, List<SaveDataPropertyEntry> properties, string? optionalPassword = null)
{
try
{
if (_cachedRootNode != null)
if (this._cachedRootNode != null)
{
// JSON の値を更新
foreach (var prop in properties)
{
if (prop.RawData is string keyPath)
{
UpdateJsonNodeByPath(_cachedRootNode, keyPath, prop.EditValue, prop.Type);
this.UpdateJsonNodeByPath(this._cachedRootNode, keyPath, prop.EditValue, prop.Type);
}
}
@@ -281,15 +328,15 @@ namespace GameLauncher.Services.Codecs
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
string updatedJson = _cachedRootNode.ToJsonString(options);
string updatedJson = this._cachedRootNode.ToJsonString(options);
byte[] outputBytes = Encoding.UTF8.GetBytes(updatedJson);
// もともと暗号化されていた場合は再暗号化
if (_wasEncrypted)
if (this._wasEncrypted)
{
string pwd = !string.IsNullOrEmpty(optionalPassword) ? optionalPassword : (_usedPassword ?? "Moodkie");
outputBytes = EncryptAes(outputBytes, pwd);
string pwd = !string.IsNullOrEmpty(optionalPassword) ? optionalPassword : (this._usedPassword ?? "Moodkie");
outputBytes = this.EncryptAes(outputBytes, pwd);
}
// バックアップ作成
@@ -331,12 +378,19 @@ namespace GameLauncher.Services.Codecs
}
}
/// <summary>
/// キーパスに基づいてJSONノードの値を更新します。
/// </summary>
/// <param name="root">ルートのJSONノード</param>
/// <param name="path">ドット区切りのキーパス</param>
/// <param name="newValue">更新後の値文字列</param>
/// <param name="type">値の型名</param>
private void UpdateJsonNodeByPath(JsonNode root, string path, string newValue, string type)
{
try
{
// ドットと角括弧でパスを分割
var parts = path.Split(new[] { '.', '[', ']' }, StringSplitOptions.RemoveEmptyEntries);
var parts = path.Split(['.', '[', ']'], StringSplitOptions.RemoveEmptyEntries);
JsonNode? current = root;
for (int i = 0; i < parts.Length - 1; i++)
@@ -358,16 +412,22 @@ namespace GameLauncher.Services.Codecs
string lastKey = parts[^1];
if (current is JsonObject finalObj)
{
finalObj[lastKey] = ParseJsonValue(newValue, type);
finalObj[lastKey] = this.ParseJsonValue(newValue, type);
}
else if (current is JsonArray finalArr && int.TryParse(lastKey, out int finalIdx) && finalIdx < finalArr.Count)
{
finalArr[finalIdx] = ParseJsonValue(newValue, type);
finalArr[finalIdx] = this.ParseJsonValue(newValue, type);
}
}
catch { }
}
/// <summary>
/// 文字列値と型名から対応するJSONノードを生成します。
/// </summary>
/// <param name="value">値文字列</param>
/// <param name="type">型名</param>
/// <returns>生成されたJSONノード</returns>
private JsonNode? ParseJsonValue(string value, string type)
{
if (type == "Int" && int.TryParse(value, out int i)) return JsonValue.Create(i);
@@ -389,6 +449,12 @@ namespace GameLauncher.Services.Codecs
return JsonValue.Create(value);
}
/// <summary>
/// AESアルゴリズムによるセーブデータの復号を試みます。
/// </summary>
/// <param name="data">暗号化バイナリデータ</param>
/// <param name="password">復号パスワード</param>
/// <returns>復号された平文文字列。失敗時は null</returns>
private string? TryDecryptAes(byte[] data, string password)
{
try
@@ -424,6 +490,12 @@ namespace GameLauncher.Services.Codecs
return null;
}
/// <summary>
/// 平文バイト配列をAESアルゴリズムで暗号化します。
/// </summary>
/// <param name="plainBytes">平文バイナリデータ</param>
/// <param name="password">暗号化パスワード</param>
/// <returns>暗号化されたバイナリデータ</returns>
private byte[] EncryptAes(byte[] plainBytes, string password)
{
byte[] rawUtf8 = Encoding.UTF8.GetBytes(password);
+30 -8
View File
@@ -1,6 +1,6 @@
using System.Collections.Generic;
using GameLauncher.Models;
using System.Collections.Generic;
using GameLauncher.Engines.Unity;
using GameLauncher.Models;
namespace GameLauncher.Services.Codecs
{
@@ -9,22 +9,44 @@ namespace GameLauncher.Services.Codecs
/// </summary>
public interface ISaveDataCodec
{
/// <summary>コーデックの識別名称(例: "Easy Save 3 (ES3)", "YU-RIS セーブデータ")</summary>
/// <summary>
/// コーデックの識別名称(例: "Easy Save 3 (ES3)", "YU-RIS セーブデータ")を取得します。
/// </summary>
string CodecName { get; }
/// <summary>このコーデックで指定ファイルを処理可能か判定</summary>
/// <summary>
/// このコーデックで指定ファイルを処理可能か判定します。
/// </summary>
/// <param name="game">対象のUnityゲーム情報</param>
/// <param name="file">対象のセーブファイル情報</param>
/// <returns>処理可能な場合は true、それ以外は false</returns>
bool CanHandle(UnityGameItem game, SaveFileEntry file);
/// <summary>セーブファイルからGUI編集用プロパティ一覧をロード・解析</summary>
/// <summary>
/// セーブファイルからGUI編集用プロパティ一覧をロード・解析します。
/// </summary>
/// <param name="filePath">セーブファイルの絶対パス</param>
/// <param name="optionalPassword">任意の暗号化パスワード</param>
/// <returns>展開されたセーブデータプロパティのリスト</returns>
List<SaveDataPropertyEntry> LoadProperties(string filePath, string? optionalPassword = null);
/// <summary>GUI編集されたプロパティ一覧をファイルへ再エンコード・保存</summary>
/// <summary>
/// GUI編集されたプロパティ一覧をファイルへ再エンコード・保存します。
/// </summary>
/// <param name="filePath">保存先セーブファイルの絶対パス</param>
/// <param name="properties">編集されたプロパティ一覧</param>
/// <param name="optionalPassword">任意の暗号化パスワード</param>
/// <returns>保存に成功した場合は true、それ以外は false</returns>
bool SaveProperties(string filePath, List<SaveDataPropertyEntry> properties, string? optionalPassword = null);
/// <summary>復号にパスワードやキーが必要かどうか</summary>
/// <summary>
/// 復号にパスワードやキーが必要かどうかを取得します。
/// </summary>
bool RequiresPassword { get; }
/// <summary>パスワード入力時の案内メッセージ</summary>
/// <summary>
/// パスワード入力時の案内メッセージを取得します。
/// </summary>
string? PasswordPromptMessage { get; }
}
}
+30 -2
View File
@@ -1,9 +1,9 @@
using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using GameLauncher.Models;
using GameLauncher.Engines.Unity;
using GameLauncher.Models;
namespace GameLauncher.Services.Codecs
{
@@ -12,12 +12,27 @@ namespace GameLauncher.Services.Codecs
/// </summary>
public class YurisSaveCodec : ISaveDataCodec
{
/// <summary>
/// コーデックの表示名を取得します。
/// </summary>
public string CodecName => "YU-RIS セーブデータ (YSSD) コーデック";
/// <summary>
/// パスワード入力が必要かどうかを取得します。
/// </summary>
public bool RequiresPassword => false;
/// <summary>
/// パスワード入力ダイアログに表示する案内メッセージを取得します。
/// </summary>
public string? PasswordPromptMessage => null;
/// <summary>
/// 指定されたセーブファイルが本コーデックで処理可能かを判定します。
/// </summary>
/// <param name="game">対象のUnityゲーム情報</param>
/// <param name="file">対象のセーブファイル情報</param>
/// <returns>処理可能な場合は true、それ以外は false</returns>
public bool CanHandle(UnityGameItem game, SaveFileEntry file)
{
if (!File.Exists(file.FilePath)) return false;
@@ -39,6 +54,12 @@ namespace GameLauncher.Services.Codecs
}
}
/// <summary>
/// セーブファイルからプロパティ一覧を読み込みます。
/// </summary>
/// <param name="filePath">セーブファイルの絶対パス</param>
/// <param name="optionalPassword">任意の暗号化パスワード</param>
/// <returns>展開されたセーブデータプロパティのリスト</returns>
public List<SaveDataPropertyEntry> LoadProperties(string filePath, string? optionalPassword = null)
{
var list = new List<SaveDataPropertyEntry>();
@@ -101,6 +122,13 @@ namespace GameLauncher.Services.Codecs
return list;
}
/// <summary>
/// 編集後のプロパティ一覧をセーブファイルへ書き戻して保存します。
/// </summary>
/// <param name="filePath">保存先セーブファイルの絶対パス</param>
/// <param name="properties">編集されたプロパティ一覧</param>
/// <param name="optionalPassword">任意の暗号化パスワード</param>
/// <returns>保存に成功した場合は true、それ以外は false</returns>
public bool SaveProperties(string filePath, List<SaveDataPropertyEntry> properties, string? optionalPassword = null)
{
try
+312
View File
@@ -0,0 +1,312 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Interop;
namespace GameLauncher.Services
{
/// <summary>
/// 高速検索ソフト「Everything」のIPC (WM_COPYDATA) APIを利用して、
/// 指定フォルダ配下の全ファイルおよびサブディレクトリを0.1秒未満で一括取得するサービス
/// </summary>
public class EverythingSearchService
{
#region □定数(Private)
private const int WM_COPYDATA = 0x004A;
private const int EVERYTHING_IPC_COPYDATA_QUERYW = 2;
private const uint EVERYTHING_IPC_ALLRESULTS = 0xFFFFFFFF;
private const uint EVERYTHING_IPC_FOLDER = 0x00000002;
private const uint EVERYTHING_IPC_DRIVE = 0x00000004;
private const uint PM_REMOVE = 0x0001;
#endregion
#region □構造体(Private)
[StructLayout(LayoutKind.Sequential)]
private struct COPYDATASTRUCT
{
public IntPtr dwData;
public int cbData;
public IntPtr lpData;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct EVERYTHING_IPC_QUERYW_HEADER
{
public uint max_results;
public uint offset;
public uint reply_copydata_message;
public uint search_flags;
public IntPtr reply_hwnd;
}
[StructLayout(LayoutKind.Sequential)]
private struct MSG
{
public IntPtr hwnd;
public uint message;
public IntPtr wParam;
public IntPtr lParam;
public uint time;
public int pt_x;
public int pt_y;
}
#endregion
#region □メソッド(Public)
/// <summary>
/// Everything が現在システム上で実行中であるか判定します。
/// </summary>
public static bool IsEverythingRunning()
{
try
{
var procs = Process.GetProcessesByName("Everything");
if (procs != null && procs.Length > 0)
{
return true;
}
}
catch { }
try
{
var hwnd = FindWindowW("EVERYTHING_TASKBAR_NOTIFICATION", null);
if (hwnd != IntPtr.Zero)
{
return true;
}
}
catch { }
return false;
}
/// <summary>
/// 指定されたパス群(例: C:\..., Z:\...)に対して、Everything IPCを用いて高速スナップショットを生成します。
/// </summary>
/// <param name="targetDirectories">走査対象のディレクトリルート一覧</param>
/// <param name="timeoutMs">タイムアウト(ミリ秒)</param>
/// <returns>生成されたスナップショット。Everything未稼働または失敗時は null</returns>
public static FastDirectorySnapshot? TryScanTargetsFast(IEnumerable<string> targetDirectories, int timeoutMs = 3000)
{
var everythingHwnd = FindWindowW("EVERYTHING_TASKBAR_NOTIFICATION", null);
if (everythingHwnd == IntPtr.Zero)
{
return null;
}
var snapshot = new FastDirectorySnapshot();
bool anySuccess = false;
foreach (var targetDir in targetDirectories)
{
if (string.IsNullOrWhiteSpace(targetDir)) continue;
string cleanDir = Path.GetFullPath(targetDir).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
try
{
bool ok = QueryDirectory(everythingHwnd, cleanDir, snapshot, timeoutMs);
if (ok)
{
anySuccess = true;
}
}
catch
{
// 個別パスのクエリ失敗時はスキップ
}
}
return anySuccess ? snapshot : null;
}
#endregion
#region □メソッド(Private)
/// <summary>
/// Everything IPC を用いて1つのディレクトリ配下のファイル・フォルダ一覧を取得し、スナップショットに格納します。
/// </summary>
private static bool QueryDirectory(IntPtr everythingHwnd, string targetDirectory, FastDirectorySnapshot snapshot, int timeoutMs)
{
bool success = false;
var resetEvent = new ManualResetEvent(false);
// STAスレッド上でメッセージ受信用 HwndSource を作成
var thread = new Thread(() =>
{
HwndSource? source = null;
try
{
var parameters = new HwndSourceParameters("GameLauncher_Everything_Receiver")
{
Width = 0,
Height = 0,
PositionX = -100,
PositionY = -100,
WindowStyle = 0x800000 // WS_BORDER (非表示)
};
source = new HwndSource(parameters);
source.AddHook((IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) =>
{
if (msg == WM_COPYDATA)
{
var cds = Marshal.PtrToStructure<COPYDATASTRUCT>(lParam);
if (cds.lpData != IntPtr.Zero && cds.cbData > 12)
{
ParseEverythingIpcList(cds.lpData, targetDirectory, snapshot);
success = true;
handled = true;
resetEvent.Set();
}
}
return IntPtr.Zero;
});
// Everything への検索文字列構築(指定パス配下の全エントリ)
string searchQuery = $"path:\"{targetDirectory}\"";
byte[] queryBytes = BuildQueryPayload(source.Handle, searchQuery);
GCHandle pinnedQuery = GCHandle.Alloc(queryBytes, GCHandleType.Pinned);
try
{
var cdsSend = new COPYDATASTRUCT
{
dwData = (IntPtr)EVERYTHING_IPC_COPYDATA_QUERYW,
cbData = queryBytes.Length,
lpData = pinnedQuery.AddrOfPinnedObject()
};
SendMessage(everythingHwnd, WM_COPYDATA, source.Handle, ref cdsSend);
// メッセージループを回して結果を待つ
var sw = Stopwatch.StartNew();
while (sw.ElapsedMilliseconds < timeoutMs && !success)
{
while (PeekMessage(out var msg, IntPtr.Zero, 0, 0, PM_REMOVE))
{
TranslateMessage(ref msg);
DispatchMessage(ref msg);
}
Thread.Sleep(5);
}
}
finally
{
if (pinnedQuery.IsAllocated) pinnedQuery.Free();
}
}
catch
{
// クエリ処理中の例外
}
finally
{
source?.Dispose();
resetEvent.Set();
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.IsBackground = true;
thread.Start();
resetEvent.WaitOne(timeoutMs);
return success;
}
/// <summary>
/// Everything IPC 送信用クエリバイナリペイロードを構築します。
/// </summary>
private static byte[] BuildQueryPayload(IntPtr replyHwnd, string searchQuery)
{
var header = new EVERYTHING_IPC_QUERYW_HEADER
{
max_results = EVERYTHING_IPC_ALLRESULTS,
offset = 0,
reply_copydata_message = 0,
search_flags = 0,
reply_hwnd = replyHwnd
};
int headerSize = Marshal.SizeOf(typeof(EVERYTHING_IPC_QUERYW_HEADER));
byte[] queryStrBytes = Encoding.Unicode.GetBytes(searchQuery + "\0");
byte[] payload = new byte[headerSize + queryStrBytes.Length];
IntPtr headerPtr = Marshal.AllocHGlobal(headerSize);
try
{
Marshal.StructureToPtr(header, headerPtr, false);
Marshal.Copy(headerPtr, payload, 0, headerSize);
}
finally
{
Marshal.FreeHGlobal(headerPtr);
}
Buffer.BlockCopy(queryStrBytes, 0, payload, headerSize, queryStrBytes.Length);
return payload;
}
/// <summary>
/// Everything から返信された EVERYTHING_IPC_LISTW バイナリをパースし、スナップショットに登録します。
/// </summary>
private static void ParseEverythingIpcList(IntPtr pList, string targetDirectory, FastDirectorySnapshot snapshot)
{
int totitems = Marshal.ReadInt32(pList, 0);
int numitems = Marshal.ReadInt32(pList, 4);
int offset = Marshal.ReadInt32(pList, 8);
if (numitems <= 0) return;
int itemHeaderBase = 12; // sizeof(DWORD) * 3
int itemSize = 12; // sizeof(DWORD) * 3 (flags, filename_offset, path_offset)
for (int i = 0; i < numitems; i++)
{
int itemOffset = itemHeaderBase + (i * itemSize);
uint flags = (uint)Marshal.ReadInt32(pList, itemOffset);
int filenameOffset = Marshal.ReadInt32(pList, itemOffset + 4);
int pathOffset = Marshal.ReadInt32(pList, itemOffset + 8);
string filename = Marshal.PtrToStringUni(IntPtr.Add(pList, filenameOffset)) ?? string.Empty;
string dirPath = Marshal.PtrToStringUni(IntPtr.Add(pList, pathOffset)) ?? string.Empty;
bool isFolder = (flags & EVERYTHING_IPC_FOLDER) != 0 || (flags & EVERYTHING_IPC_DRIVE) != 0;
if (isFolder)
{
string fullSubDir = Path.Combine(dirPath, filename);
snapshot.AddDirectory(dirPath, fullSubDir);
}
else
{
snapshot.AddFile(dirPath, filename);
}
}
}
#endregion
#region □P/Invoke(Private)
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr FindWindowW(string lpClassName, string? lpWindowName);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, ref COPYDATASTRUCT lParam);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool PeekMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg);
[DllImport("user32.dll")]
private static extern bool TranslateMessage([In] ref MSG lpMsg);
[DllImport("user32.dll")]
private static extern IntPtr DispatchMessage([In] ref MSG lpmsg);
#endregion
}
}
+211
View File
@@ -0,0 +1,211 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace GameLauncher.Services
{
/// <summary>
/// メモリ上に展開されたディレクトリおよびファイル構成の高速インメモリスナップショット
/// </summary>
public class FastDirectorySnapshot
{
#region □プロパティ(Public)
/// <summary>
/// ディレクトリパス -> 直下のファイル名(ファイル名のみ)のハッシュセット
/// </summary>
public Dictionary<string, HashSet<string>> FilesByDir { get; } = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// ディレクトリパス -> 直下のサブディレクトリのフルパスリスト
/// </summary>
public Dictionary<string, List<string>> SubDirsByDir { get; } = new(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// 登録されている総ディレクトリ数
/// </summary>
public int TotalDirectoryCount => this.SubDirsByDir.Count;
/// <summary>
/// 登録されている総ファイル数
/// </summary>
public int TotalFileCount => this.FilesByDir.Values.Sum(set => set.Count);
#endregion
#region □メソッド(Public)
/// <summary>
/// ファイルをスナップショットに登録します。
/// </summary>
public void AddFile(string dirPath, string fileName)
{
var normalizedDir = NormalizePath(dirPath);
if (!this.FilesByDir.TryGetValue(normalizedDir, out var files))
{
files = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
this.FilesByDir[normalizedDir] = files;
}
files.Add(fileName);
if (!this.SubDirsByDir.ContainsKey(normalizedDir))
{
this.SubDirsByDir[normalizedDir] = new List<string>();
}
}
/// <summary>
/// サブディレクトリを親ディレクトリのスナップショットに登録します。
/// </summary>
public void AddDirectory(string parentDirPath, string childDirPath)
{
var normalizedParent = NormalizePath(parentDirPath);
var normalizedChild = NormalizePath(childDirPath);
if (!this.SubDirsByDir.TryGetValue(normalizedParent, out var children))
{
children = new List<string>();
this.SubDirsByDir[normalizedParent] = children;
}
if (!children.Contains(normalizedChild, StringComparer.OrdinalIgnoreCase))
{
children.Add(normalizedChild);
}
if (!this.SubDirsByDir.ContainsKey(normalizedChild))
{
this.SubDirsByDir[normalizedChild] = new List<string>();
}
}
/// <summary>
/// 指定されたディレクトリが存在するかどうかをインメモリで判定します。
/// </summary>
public bool DirectoryExists(string dirPath)
{
var normalized = NormalizePath(dirPath);
return this.SubDirsByDir.ContainsKey(normalized) || this.FilesByDir.ContainsKey(normalized);
}
/// <summary>
/// 指定されたファイルが存在するかどうかをインメモリで判定します。
/// </summary>
public bool FileExists(string filePath)
{
var dir = NormalizePath(Path.GetDirectoryName(filePath) ?? string.Empty);
var name = Path.GetFileName(filePath);
if (this.FilesByDir.TryGetValue(dir, out var files))
{
return files.Contains(name);
}
return false;
}
/// <summary>
/// 指定されたディレクトリ直下のサブディレクトリ一覧を取得します。
/// </summary>
public string[] GetDirectories(string dirPath)
{
var normalized = NormalizePath(dirPath);
if (this.SubDirsByDir.TryGetValue(normalized, out var subDirs))
{
return subDirs.ToArray();
}
return Array.Empty<string>();
}
/// <summary>
/// 指定されたディレクトリ直下のファイルフルパス一覧を取得します。
/// </summary>
public string[] GetFiles(string dirPath, string searchPattern = "*")
{
var normalized = NormalizePath(dirPath);
if (!this.FilesByDir.TryGetValue(normalized, out var files))
{
return Array.Empty<string>();
}
if (string.IsNullOrEmpty(searchPattern) || searchPattern == "*")
{
return files.Select(f => Path.Combine(normalized, f)).ToArray();
}
if (searchPattern.StartsWith("*.") && searchPattern.IndexOf('*', 1) < 0 && searchPattern.IndexOf('?', 1) < 0)
{
string ext = searchPattern.Substring(1);
return files
.Where(f => f.EndsWith(ext, StringComparison.OrdinalIgnoreCase))
.Select(f => Path.Combine(normalized, f))
.ToArray();
}
var regex = WildcardToRegex(searchPattern);
return files
.Where(f => regex.IsMatch(f))
.Select(f => Path.Combine(normalized, f))
.ToArray();
}
/// <summary>
/// 別のスナップショットの内容を現在のスナップショットにマージします。
/// </summary>
/// <param name="other">マージ元のスナップショット</param>
public void MergeFrom(FastDirectorySnapshot other)
{
if (other == null) return;
foreach (var kvp in other.FilesByDir)
{
if (!this.FilesByDir.TryGetValue(kvp.Key, out var files))
{
files = new HashSet<string>(kvp.Value, StringComparer.OrdinalIgnoreCase);
this.FilesByDir[kvp.Key] = files;
}
else
{
files.UnionWith(kvp.Value);
}
}
foreach (var kvp in other.SubDirsByDir)
{
if (!this.SubDirsByDir.TryGetValue(kvp.Key, out var subDirs))
{
subDirs = new List<string>(kvp.Value);
this.SubDirsByDir[kvp.Key] = subDirs;
}
else
{
foreach (var dir in kvp.Value)
{
if (!subDirs.Contains(dir, StringComparer.OrdinalIgnoreCase))
{
subDirs.Add(dir);
}
}
}
}
}
#endregion
#region □メソッド(Private)
/// <summary>
/// パス末尾の区切り文字を除去し、正規化します。
/// </summary>
private static string NormalizePath(string path)
{
if (string.IsNullOrEmpty(path)) return string.Empty;
return path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
/// <summary>
/// ワイルドカードパターンを正規表現に変換します。
/// </summary>
private static Regex WildcardToRegex(string pattern)
{
string escaped = Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".");
return new Regex("^" + escaped + "$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
}
#endregion
}
}
File diff suppressed because it is too large. Load diff
+399
View File
@@ -0,0 +1,399 @@
using System;
using System.Buffers.Binary;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
namespace GameLauncher.Services
{
/// <summary>
/// NTFS の MFT (USN Journal: FSCTL_ENUM_USN_DATA) を直接読み取り、
/// ドライブ内のファイルおよびディレクトリツリーを爆速で一括抽出するサービス
/// </summary>
public class NtfsMftScanService
{
#region □定数(Private)
private const uint GENERIC_READ = 0x80000000;
private const uint FILE_SHARE_READ = 0x00000001;
private const uint FILE_SHARE_WRITE = 0x00000002;
private const uint OPEN_EXISTING = 3;
private const uint FSCTL_QUERY_USN_JOURNAL = 0x000900f4;
private const uint FSCTL_ENUM_USN_DATA = 0x000900b3;
private const uint FILE_ATTRIBUTE_DIRECTORY = 0x00000010;
/// <summary>
/// MFT読み込みバッファサイズ(2MB)。1回のDeviceIoControl呼び出しで最大効率を引き出します。
/// </summary>
private const int BufferSize = 2048 * 1024;
#endregion
#region □構造体(Private)
[StructLayout(LayoutKind.Sequential)]
private struct USN_JOURNAL_DATA
{
public ulong UsnJournalID;
public long FirstUsn;
public long NextUsn;
public long LowestValidUsn;
public long MaxUsn;
public ulong MaximumSize;
public ulong AllocationDelta;
}
[StructLayout(LayoutKind.Sequential)]
private struct MFT_ENUM_DATA_V0
{
public ulong StartFileReferenceNumber;
public long LowUsn;
public long HighUsn;
}
/// <summary>
/// MFTディレクトリ情報ノード
/// </summary>
private struct DirNode
{
public ulong Id;
public ulong ParentId;
public string Name;
}
#endregion
#region □メソッド(Public)
/// <summary>
/// 指定されたパス群(例: C:\..., Z:\...)に対して、NTFS MFT 直接読み取りを用いて高速スナップショットを生成します。
/// 複数ドライブが存在する場合は、各ドライブを並列処理してディスクアクセス速度を極限まで高めます。
/// </summary>
/// <param name="targetDirectories">走査対象のディレクトリルート一覧</param>
/// <returns>生成されたスナップショット。失敗または非NTFS時は null</returns>
public static FastDirectorySnapshot? TryScanTargetsFast(IEnumerable<string> targetDirectories)
{
var targetsByDrive = new Dictionary<char, List<string>>();
foreach (var dir in targetDirectories)
{
if (string.IsNullOrWhiteSpace(dir)) continue;
var full = Path.GetFullPath(dir).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
if (full.Length >= 2 && full[1] == ':')
{
char driveLetter = char.ToUpperInvariant(full[0]);
if (!targetsByDrive.TryGetValue(driveLetter, out var list))
{
list = new List<string>();
targetsByDrive[driveLetter] = list;
}
list.Add(full);
}
}
if (targetsByDrive.Count == 0) return null;
var snapshots = new ConcurrentBag<FastDirectorySnapshot>();
// ドライブごとに並列処理を実行(物理/論理ドライブ間のI/OおよびCPUを限界まで同時並行化)
Parallel.ForEach(targetsByDrive, kvp =>
{
char driveLetter = kvp.Key;
var targetPaths = kvp.Value;
var driveSnapshot = new FastDirectorySnapshot();
try
{
bool ok = ScanVolumeMft(driveLetter, targetPaths, driveSnapshot);
if (ok && (driveSnapshot.TotalDirectoryCount > 0 || driveSnapshot.TotalFileCount > 0))
{
snapshots.Add(driveSnapshot);
}
}
catch
{
// ドライブスキャン失敗時はスキップ
}
});
if (snapshots.IsEmpty) return null;
var merged = new FastDirectorySnapshot();
foreach (var snap in snapshots)
{
merged.MergeFrom(snap);
}
return merged;
}
#endregion
#region □メソッド(Private)
/// <summary>
/// 1つのドライブボリュームのMFTを読み込み、指定されたターゲットパス配下のファイルをスナップショットに登録します。
/// </summary>
private static bool ScanVolumeMft(char driveLetter, List<string> targetPaths, FastDirectorySnapshot snapshot)
{
string volumePath = @"\\.\" + driveLetter + ":";
using var hVolume = CreateFile(
volumePath,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
IntPtr.Zero,
OPEN_EXISTING,
0,
IntPtr.Zero);
if (hVolume.IsInvalid)
{
return false;
}
// 1. USNジャーナル情報の取得
var journalData = new USN_JOURNAL_DATA();
int journalDataSize = Marshal.SizeOf(typeof(USN_JOURNAL_DATA));
if (!DeviceIoControl(hVolume, FSCTL_QUERY_USN_JOURNAL, IntPtr.Zero, 0, out journalData, journalDataSize, out _, IntPtr.Zero))
{
return false;
}
// 2. MFT列挙用パラメータの準備
var enumData = new MFT_ENUM_DATA_V0
{
StartFileReferenceNumber = 0,
LowUsn = 0,
HighUsn = journalData.NextUsn
};
int enumDataSize = Marshal.SizeOf(typeof(MFT_ENUM_DATA_V0));
IntPtr enumDataPtr = Marshal.AllocHGlobal(enumDataSize);
Marshal.StructureToPtr(enumData, enumDataPtr, false);
byte[] buffer = new byte[BufferSize];
GCHandle bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
IntPtr bufferPtr = bufferHandle.AddrOfPinnedObject();
// 読み込んだ全MFTデータチャンクを保持(I/Oを最優先で一括連続完了させる)
var chunks = new List<(byte[] Buffer, int Length)>();
try
{
while (DeviceIoControl(hVolume, FSCTL_ENUM_USN_DATA, enumDataPtr, enumDataSize, bufferPtr, BufferSize, out uint bytesReturned, IntPtr.Zero))
{
if (bytesReturned <= 8) break;
// 次の開始参照番号を取得
ulong nextId = (ulong)Marshal.ReadInt64(bufferPtr);
Marshal.WriteInt64(enumDataPtr, (long)nextId);
byte[] chunkCopy = new byte[bytesReturned];
Buffer.BlockCopy(buffer, 0, chunkCopy, 0, (int)bytesReturned);
chunks.Add((chunkCopy, (int)bytesReturned));
}
}
finally
{
if (bufferHandle.IsAllocated) bufferHandle.Free();
if (enumDataPtr != IntPtr.Zero) Marshal.FreeHGlobal(enumDataPtr);
}
if (chunks.Count == 0) return false;
// 3. 【第1パス】ディレクトリのみを収集(ディレクトリは全体の数%に過ぎないため極めて高速)
var dirNodes = new Dictionary<ulong, DirNode>(65536);
var childrenByParent = new Dictionary<ulong, List<ulong>>(65536);
foreach (var chunk in chunks)
{
ReadOnlySpan<byte> span = chunk.Buffer.AsSpan(0, chunk.Length);
int offset = 8;
while (offset < chunk.Length)
{
if (offset + 60 > chunk.Length) break;
ReadOnlySpan<byte> record = span.Slice(offset);
int recordLength = BinaryPrimitives.ReadInt32LittleEndian(record);
if (recordLength <= 0 || offset + recordLength > chunk.Length) break;
uint fileAttributes = BinaryPrimitives.ReadUInt32LittleEndian(record.Slice(52));
if ((fileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
{
ulong fileRef = BinaryPrimitives.ReadUInt64LittleEndian(record.Slice(8)) & 0x0000FFFFFFFFFFFFUL;
ulong parentRef = BinaryPrimitives.ReadUInt64LittleEndian(record.Slice(16)) & 0x0000FFFFFFFFFFFFUL;
ushort fileNameLength = BinaryPrimitives.ReadUInt16LittleEndian(record.Slice(56));
ushort fileNameOffset = BinaryPrimitives.ReadUInt16LittleEndian(record.Slice(58));
if (fileNameLength > 0 && fileNameOffset + fileNameLength <= recordLength)
{
string dirName = Encoding.Unicode.GetString(record.Slice(fileNameOffset, fileNameLength));
dirNodes[fileRef] = new DirNode { Id = fileRef, ParentId = parentRef, Name = dirName };
if (!childrenByParent.TryGetValue(parentRef, out var childList))
{
childList = new List<ulong>();
childrenByParent[parentRef] = childList;
}
childList.Add(fileRef);
}
}
offset += recordLength;
}
}
// 4. ターゲットパスのNodeId特定と、配下の子孫ディレクトリパスの確定
var targetDirIds = new HashSet<ulong>();
var dirIdToFullPath = new Dictionary<ulong, string>();
foreach (var targetPath in targetPaths)
{
ulong? targetNodeId = FindDirNodeIdByPath(driveLetter, targetPath, dirNodes, childrenByParent);
if (targetNodeId.HasValue)
{
CollectDescendantDirectories(targetNodeId.Value, targetPath, dirNodes, childrenByParent, targetDirIds, dirIdToFullPath, snapshot);
}
}
// 該当するターゲットディレクトリが存在しなければ終了
if (targetDirIds.Count == 0) return true;
// 5. 【第2パス】ターゲット配下のファイルのみを高速抽出
// (ターゲット外の数百万個の無関係なファイルは名前取得やオブジェクト生成を完全にスキップ!)
foreach (var chunk in chunks)
{
ReadOnlySpan<byte> span = chunk.Buffer.AsSpan(0, chunk.Length);
int offset = 8;
while (offset < chunk.Length)
{
if (offset + 60 > chunk.Length) break;
ReadOnlySpan<byte> record = span.Slice(offset);
int recordLength = BinaryPrimitives.ReadInt32LittleEndian(record);
if (recordLength <= 0 || offset + recordLength > chunk.Length) break;
uint fileAttributes = BinaryPrimitives.ReadUInt32LittleEndian(record.Slice(52));
// ディレクトリは第1パスですでに登録済みのためスキップ
if ((fileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
{
ulong parentRef = BinaryPrimitives.ReadUInt64LittleEndian(record.Slice(16)) & 0x0000FFFFFFFFFFFFUL;
// ターゲット配下のディレクトリに属するファイルのみを抽出
if (targetDirIds.Contains(parentRef) && dirIdToFullPath.TryGetValue(parentRef, out string? parentDirPath))
{
ushort fileNameLength = BinaryPrimitives.ReadUInt16LittleEndian(record.Slice(56));
ushort fileNameOffset = BinaryPrimitives.ReadUInt16LittleEndian(record.Slice(58));
if (fileNameLength > 0 && fileNameOffset + fileNameLength <= recordLength)
{
string fileName = Encoding.Unicode.GetString(record.Slice(fileNameOffset, fileNameLength));
snapshot.AddFile(parentDirPath, fileName);
}
}
}
offset += recordLength;
}
}
return true;
}
/// <summary>
/// パス文字列から対応するディレクトリのノードIDを特定します。
/// </summary>
private static ulong? FindDirNodeIdByPath(
char driveLetter,
string path,
Dictionary<ulong, DirNode> dirNodes,
Dictionary<ulong, List<ulong>> childrenByParent)
{
string rootStr = driveLetter + @":\";
if (path.Equals(rootStr.TrimEnd('\\'), StringComparison.OrdinalIgnoreCase) || path.Equals(rootStr, StringComparison.OrdinalIgnoreCase))
{
return 5UL; // ルートディレクトリID
}
var parts = path.Substring(3).Split(new[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries);
ulong currentParent = 5UL;
foreach (var part in parts)
{
bool found = false;
if (childrenByParent.TryGetValue(currentParent, out var childIds))
{
foreach (var childId in childIds)
{
if (dirNodes.TryGetValue(childId, out var node) && string.Equals(node.Name, part, StringComparison.OrdinalIgnoreCase))
{
currentParent = node.Id;
found = true;
break;
}
}
}
if (!found) return null;
}
return currentParent;
}
/// <summary>
/// ターゲットディレクトリ配下の子孫ディレクトリIDおよびフルパスを再帰的に収集し、スナップショットに登録します。
/// </summary>
private static void CollectDescendantDirectories(
ulong parentNodeId,
string currentPath,
Dictionary<ulong, DirNode> dirNodes,
Dictionary<ulong, List<ulong>> childrenByParent,
HashSet<ulong> targetDirIds,
Dictionary<ulong, string> dirIdToFullPath,
FastDirectorySnapshot snapshot)
{
targetDirIds.Add(parentNodeId);
dirIdToFullPath[parentNodeId] = currentPath;
if (!childrenByParent.TryGetValue(parentNodeId, out var childIds)) return;
foreach (var childId in childIds)
{
if (!dirNodes.TryGetValue(childId, out var childNode)) continue;
string childPath = Path.Combine(currentPath, childNode.Name);
snapshot.AddDirectory(currentPath, childPath);
CollectDescendantDirectories(childId, childPath, dirNodes, childrenByParent, targetDirIds, dirIdToFullPath, snapshot);
}
}
#endregion
#region □P/Invoke(Private)
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern SafeFileHandle CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool DeviceIoControl(
SafeFileHandle hDevice,
uint dwIoControlCode,
IntPtr lpInBuffer,
int nInBufferSize,
out USN_JOURNAL_DATA lpOutBuffer,
int nOutBufferSize,
out uint lpBytesReturned,
IntPtr lpOverlapped);
[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool DeviceIoControl(
SafeFileHandle hDevice,
uint dwIoControlCode,
IntPtr lpInBuffer,
int nInBufferSize,
IntPtr lpOutBuffer,
int nOutBufferSize,
out uint lpBytesReturned,
IntPtr lpOverlapped);
#endregion
}
}
+20 -7
View File
@@ -1,12 +1,11 @@
using System;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using GameLauncher.Engines.Unity;
using GameLauncher.Models;
using GameLauncher.Services.Codecs;
using GameLauncher.Engines.Unity;
using GameLauncher.Engines.Wolf;
namespace GameLauncher.Services
{
@@ -15,23 +14,32 @@ namespace GameLauncher.Services
/// </summary>
public class SaveDataCodecManager
{
/// <summary>
/// シングルトンインスタンスを取得します。
/// </summary>
public static readonly SaveDataCodecManager Instance = new();
private readonly List<ISaveDataCodec> _codecs = [];
/// <summary>
/// <see cref="SaveDataCodecManager"/> クラスの新しいインスタンスを初期化します。
/// </summary>
public SaveDataCodecManager()
{
// コーデックの登録
_codecs.Add(new EasySave3Codec());
_codecs.Add(new YurisSaveCodec());
this._codecs.Add(new EasySave3Codec());
this._codecs.Add(new YurisSaveCodec());
}
/// <summary>
/// 指定されたゲームおよびセーブファイルに対応するコーデックを検索します。
/// </summary>
/// <param name="game">対象のUnityゲーム情報</param>
/// <param name="file">対象のセーブファイル情報</param>
/// <returns>対応するコーデック。見つからない場合は null</returns>
public ISaveDataCodec? FindCodec(UnityGameItem game, SaveFileEntry file)
{
foreach (var codec in _codecs)
foreach (var codec in this._codecs)
{
if (codec.CanHandle(game, file))
{
@@ -44,6 +52,9 @@ namespace GameLauncher.Services
/// <summary>
/// 未対応セーブデータについて、Antigravity IDE に依頼できる安全なプロンプトを自動生成します。
/// </summary>
/// <param name="game">対象のUnityゲーム情報</param>
/// <param name="file">対象のセーブファイル情報</param>
/// <returns>生成された依頼プロンプト文字列</returns>
public string GenerateAntigravityPrompt(UnityGameItem game, SaveFileEntry file)
{
// ポリシー配慮: 会社名・タイトル名からセンシティブ表現を除去/安全な別名に変換
@@ -98,8 +109,10 @@ namespace GameLauncher.Services
}
/// <summary>
/// AIプロンプト向けに文字列を安全・中立的な表現にサニタイズ
/// AIプロンプト向けに文字列を安全・中立的な表現にサニタイズします。
/// </summary>
/// <param name="input">元の文字列</param>
/// <returns>サニタイズされた安全な文字列</returns>
private static string SanitizeForPrompt(string input)
{
if (string.IsNullOrWhiteSpace(input)) return "Game";
+3 -3
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
@@ -67,12 +67,12 @@ namespace GameLauncher.Services
catch (Exception ex)
{
// 外部ツール起動失敗時は内蔵方式にフォールバック
var (ok, msg) = await ApplyBuiltInResizeAsync(process);
var (ok, msg) = await this.ApplyBuiltInResizeAsync(process);
return (ok, $"外部ツール起動に失敗したため内蔵方式を使用: {ex.Message} / {msg}");
}
}
return await ApplyBuiltInResizeAsync(process);
return await this.ApplyBuiltInResizeAsync(process);
}
/// <summary>
+2 -2
View File
@@ -1,4 +1,4 @@
<Window x:Class="GameLauncher.WolfSaveEditorDialog"
<Window x:Class="GameLauncher.WolfSaveEditorDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
@@ -155,7 +155,7 @@
<!-- 数値ピンポイント検索(所持金・ステータス特定) -->
<StackPanel Grid.Column="0" Orientation="Horizontal" VerticalAlignment="Center" Margin="0,0,16,0">
<TextBlock Text="🎯 数値検索 (所持金等):" VerticalAlignment="Center" Foreground="{StaticResource TextSecondary}" FontSize="12" Margin="0,0,6,0"/>
<TextBox x:Name="txtTargetValue" Width="110" Height="26" VerticalContentAlignment="Center" Padding="4,0"
<TextBox x:Name="txtTargetValue" Width="110" Height="26" VerticalContentAlignment="Center" Padding="4,0"
Background="#14141C" Foreground="#FFFFFF" BorderBrush="{StaticResource BorderBrushColor}" Text=""/>
<Button Content="検索" Style="{StaticResource ModernButton}" Click="btnSearchValue_Click" Margin="6,0,4,0"/>
<Button Content="MAX(9999999)化" Style="{StaticResource ModernButton}" Click="btnSetMaxTarget_Click" Margin="0,0,4,0" ToolTip="検索された数値を 9,999,999 に書き換えます"/>
+64 -64
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
@@ -27,15 +27,15 @@ namespace GameLauncher
public WolfSaveEditorDialog(TkoolGameItem game, WolfSaveService saveService)
{
InitializeComponent();
_game = game;
_saveService = saveService;
this.InitializeComponent();
this._game = game;
this._saveService = saveService;
lblGameTitle.Text = _game.Title;
lblGamePath.Text = _game.RootDirectory;
txtInfoBackupDir.Text = AppPathHelper.GetGameBackupDirectory(_game.FolderName, _game.RootDirectory);
this.lblGameTitle.Text = this._game.Title;
this.lblGamePath.Text = this._game.RootDirectory;
this.txtInfoBackupDir.Text = AppPathHelper.GetGameBackupDirectory(this._game.FolderName, this._game.RootDirectory);
LoadSaveFileList();
this.LoadSaveFileList();
}
/// <summary>
@@ -45,36 +45,36 @@ namespace GameLauncher
{
try
{
var files = _saveService.GetSaveFiles(_game.RootDirectory);
cboSaveFiles.Items.Clear();
var files = this._saveService.GetSaveFiles(this._game.RootDirectory);
this.cboSaveFiles.Items.Clear();
foreach (var f in files)
{
cboSaveFiles.Items.Add(Path.GetFileName(f));
this.cboSaveFiles.Items.Add(Path.GetFileName(f));
}
if (cboSaveFiles.Items.Count > 0)
if (this.cboSaveFiles.Items.Count > 0)
{
cboSaveFiles.SelectedIndex = 0;
this.cboSaveFiles.SelectedIndex = 0;
}
else
{
lblStatus.Text = "セーブデータ(*.sav)が見つかりませんでした。";
this.lblStatus.Text = "セーブデータ(*.sav)が見つかりませんでした。";
}
}
catch (Exception ex)
{
lblStatus.Text = $"セーブファイル列挙エラー: {ex.Message}";
this.lblStatus.Text = $"セーブファイル列挙エラー: {ex.Message}";
}
}
private void cboSaveFiles_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (cboSaveFiles.SelectedItem == null) return;
var fileName = cboSaveFiles.SelectedItem.ToString();
if (this.cboSaveFiles.SelectedItem == null) return;
var fileName = this.cboSaveFiles.SelectedItem.ToString();
if (string.IsNullOrEmpty(fileName)) return;
LoadSaveFile(fileName);
this.LoadSaveFile(fileName);
}
/// <summary>
@@ -84,46 +84,46 @@ namespace GameLauncher
{
try
{
var files = _saveService.GetSaveFiles(_game.RootDirectory);
var files = this._saveService.GetSaveFiles(this._game.RootDirectory);
var fullPath = files.FirstOrDefault(f => string.Equals(Path.GetFileName(f), fileName, StringComparison.OrdinalIgnoreCase));
if (string.IsNullOrEmpty(fullPath) || !File.Exists(fullPath))
{
lblStatus.Text = $"ファイルが存在しません: {fileName}";
this.lblStatus.Text = $"ファイルが存在しません: {fileName}";
return;
}
_currentSaveData = _saveService.LoadSave(fullPath);
_allVariables = [.. _currentSaveData.Variables];
_allStrings = [.. _currentSaveData.Strings];
this._currentSaveData = this._saveService.LoadSave(fullPath);
this._allVariables = [.. this._currentSaveData.Variables];
this._allStrings = [.. this._currentSaveData.Strings];
// メタ情報表示
txtInfoTitle.Text = string.IsNullOrEmpty(_currentSaveData.GameTitle) ? "(不明)" : _currentSaveData.GameTitle;
txtInfoVersion.Text = $"0x{_currentSaveData.FileVersion:X4}";
txtInfoEncoding.Text = _currentSaveData.IsUtf8 ? "UTF-8" : "Shift-JIS (CP932)";
txtInfoSize.Text = $"{_currentSaveData.RawDecryptedBytes.Length:N0} バイト";
this.txtInfoTitle.Text = string.IsNullOrEmpty(this._currentSaveData.GameTitle) ? "(不明)" : this._currentSaveData.GameTitle;
this.txtInfoVersion.Text = $"0x{this._currentSaveData.FileVersion:X4}";
this.txtInfoEncoding.Text = this._currentSaveData.IsUtf8 ? "UTF-8" : "Shift-JIS (CP932)";
this.txtInfoSize.Text = $"{this._currentSaveData.RawDecryptedBytes.Length:N0} バイト";
ApplyFilter();
this.ApplyFilter();
lblStatus.Text = $"'{fileName}' を正常に読み込みました。";
lblSaveCount.Text = $"変数項目: {_allVariables.Count}件, 文字列項目: {_allStrings.Count}件";
this.lblStatus.Text = $"'{fileName}' を正常に読み込みました。";
this.lblSaveCount.Text = $"変数項目: {this._allVariables.Count}件, 文字列項目: {this._allStrings.Count}件";
}
catch (Exception ex)
{
MessageBox.Show($"セーブデータの読み込みに失敗しました:\n{ex.Message}", "読み込みエラー", MessageBoxButton.OK, MessageBoxImage.Error);
lblStatus.Text = $"読み込みエラー: {ex.Message}";
this.lblStatus.Text = $"読み込みエラー: {ex.Message}";
}
}
private void btnReload_Click(object sender, RoutedEventArgs e)
{
if (cboSaveFiles.SelectedItem != null)
if (this.cboSaveFiles.SelectedItem != null)
{
LoadSaveFile(cboSaveFiles.SelectedItem.ToString()!);
this.LoadSaveFile(this.cboSaveFiles.SelectedItem.ToString()!);
}
else
{
LoadSaveFileList();
this.LoadSaveFileList();
}
}
@@ -132,23 +132,23 @@ namespace GameLauncher
/// </summary>
private void ApplyFilter()
{
var filter = txtFilter.Text?.Trim() ?? string.Empty;
var filter = this.txtFilter.Text?.Trim() ?? string.Empty;
if (string.IsNullOrEmpty(filter))
{
dgVariables.ItemsSource = _allVariables;
dgStrings.ItemsSource = _allStrings;
this.dgVariables.ItemsSource = this._allVariables;
this.dgStrings.ItemsSource = this._allStrings;
}
else
{
dgVariables.ItemsSource = _allVariables
this.dgVariables.ItemsSource = this._allVariables
.Where(v => v.DisplayName.Contains(filter, StringComparison.OrdinalIgnoreCase) ||
v.Category.Contains(filter, StringComparison.OrdinalIgnoreCase) ||
v.Value.ToString().Contains(filter, StringComparison.OrdinalIgnoreCase) ||
v.Offset.ToString("X").Contains(filter, StringComparison.OrdinalIgnoreCase))
.ToList();
dgStrings.ItemsSource = _allStrings
this.dgStrings.ItemsSource = this._allStrings
.Where(s => s.Value.Contains(filter, StringComparison.OrdinalIgnoreCase) ||
s.Offset.ToString("X").Contains(filter, StringComparison.OrdinalIgnoreCase))
.ToList();
@@ -157,7 +157,7 @@ namespace GameLauncher
private void txtFilter_TextChanged(object sender, TextChangedEventArgs e)
{
ApplyFilter();
this.ApplyFilter();
}
/// <summary>
@@ -165,21 +165,21 @@ namespace GameLauncher
/// </summary>
private void btnSearchValue_Click(object sender, RoutedEventArgs e)
{
if (!int.TryParse(txtTargetValue.Text.Trim(), out int target))
if (!int.TryParse(this.txtTargetValue.Text.Trim(), out int target))
{
MessageBox.Show("検索する数値を半角数字で入力してください。(例: 現在の所持金やステータス)", "入力エラー", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
var matches = _allVariables.Where(v => v.Value == target).ToList();
var matches = this._allVariables.Where(v => v.Value == target).ToList();
if (matches.Count == 0)
{
MessageBox.Show($"値が {target:N0} と一致する変数が見つかりませんでした。", "検索結果", MessageBoxButton.OK, MessageBoxImage.Information);
return;
}
dgVariables.ItemsSource = matches;
lblStatus.Text = $"値 {target:N0} に一致する候補が {matches.Count} 件見つかりました。";
this.dgVariables.ItemsSource = matches;
this.lblStatus.Text = $"値 {target:N0} に一致する候補が {matches.Count} 件見つかりました。";
}
/// <summary>
@@ -187,7 +187,7 @@ namespace GameLauncher
/// </summary>
private void btnSetMaxTarget_Click(object sender, RoutedEventArgs e)
{
if (dgVariables.ItemsSource is not IEnumerable<WolfVariableItem> currentList) return;
if (this.dgVariables.ItemsSource is not IEnumerable<WolfVariableItem> currentList) return;
var list = currentList.ToList();
if (list.Count == 0) return;
@@ -201,8 +201,8 @@ namespace GameLauncher
{
item.Value = 9999999;
}
dgVariables.Items.Refresh();
lblStatus.Text = $"{list.Count} 件の値を 9,999,999 に変更しました。保存ボタンを押すと反映されます。";
this.dgVariables.Items.Refresh();
this.lblStatus.Text = $"{list.Count} 件の値を 9,999,999 に変更しました。保存ボタンを押すと反映されます。";
}
}
@@ -214,14 +214,14 @@ namespace GameLauncher
if (sender is Button btn && btn.Tag is WolfVariableItem item)
{
item.Value = 9999999;
dgVariables.Items.Refresh();
lblStatus.Text = $"{item.DisplayName} の値を 9,999,999 に設定しました。";
this.dgVariables.Items.Refresh();
this.lblStatus.Text = $"{item.DisplayName} の値を 9,999,999 に設定しました。";
}
}
private void dgVariables_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
lblStatus.Text = "値を編集しました。「上書き保存」を押すとバックアップを作成して保存されます。";
this.lblStatus.Text = "値を編集しました。「上書き保存」を押すとバックアップを作成して保存されます。";
}
/// <summary>
@@ -229,7 +229,7 @@ namespace GameLauncher
/// </summary>
private void btnSave_Click(object sender, RoutedEventArgs e)
{
if (_currentSaveData == null)
if (this._currentSaveData == null)
{
MessageBox.Show("保存対象のセーブデータがありません。", "エラー", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
@@ -238,19 +238,19 @@ namespace GameLauncher
try
{
// 変数リストの最新値をモデルへ反映
_currentSaveData.Variables = _allVariables;
this._currentSaveData.Variables = this._allVariables;
// 保存実行 (自動バックアップ)
string backupPath = _saveService.SaveToFile(_currentSaveData, _game.FolderName, _game.RootDirectory);
string backupPath = this._saveService.SaveToFile(this._currentSaveData, this._game.FolderName, this._game.RootDirectory);
var msg = $"セーブデータ '{_currentSaveData.FileName}' を安全に上書き保存しました!\n\n【バックアップ保存先】\n{backupPath}";
var msg = $"セーブデータ '{this._currentSaveData.FileName}' を安全に上書き保存しました!\n\n【バックアップ保存先】\n{backupPath}";
MessageBox.Show(msg, "保存完了", MessageBoxButton.OK, MessageBoxImage.Information);
lblStatus.Text = $"保存完了 (バックアップ: {Path.GetFileName(backupPath)})";
this.lblStatus.Text = $"保存完了 (バックアップ: {Path.GetFileName(backupPath)})";
}
catch (Exception ex)
{
MessageBox.Show($"保存中にエラーが発生しました:\n{ex.Message}", "保存エラー", MessageBoxButton.OK, MessageBoxImage.Error);
lblStatus.Text = $"保存エラー: {ex.Message}";
this.lblStatus.Text = $"保存エラー: {ex.Message}";
}
}
@@ -259,20 +259,20 @@ namespace GameLauncher
/// </summary>
private void btnExportJson_Click(object sender, RoutedEventArgs e)
{
if (_currentSaveData == null) return;
if (this._currentSaveData == null) return;
var sfd = new SaveFileDialog
{
Title = "セーブデータを JSON としてエクスポート",
Filter = "JSON ファイル (*.json)|*.json",
FileName = $"{Path.GetFileNameWithoutExtension(_currentSaveData.FileName)}_export.json"
FileName = $"{Path.GetFileNameWithoutExtension(this._currentSaveData.FileName)}_export.json"
};
if (sfd.ShowDialog() == true)
{
try
{
_saveService.ExportToJson(_currentSaveData, sfd.FileName);
this._saveService.ExportToJson(this._currentSaveData, sfd.FileName);
MessageBox.Show($"JSON ファイルをエクスポートしました:\n{sfd.FileName}", "エクスポート完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ex)
@@ -287,7 +287,7 @@ namespace GameLauncher
/// </summary>
private void btnImportJson_Click(object sender, RoutedEventArgs e)
{
if (_currentSaveData == null) return;
if (this._currentSaveData == null) return;
var ofd = new OpenFileDialog
{
@@ -299,9 +299,9 @@ namespace GameLauncher
{
try
{
_saveService.ImportFromJson(_currentSaveData, ofd.FileName);
_allVariables = [.. _currentSaveData.Variables];
ApplyFilter();
this._saveService.ImportFromJson(this._currentSaveData, ofd.FileName);
this._allVariables = [.. this._currentSaveData.Variables];
this.ApplyFilter();
MessageBox.Show("JSON データを正常に取り込みました。「上書き保存」を押すとファイルへ反映されます。", "インポート完了", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ex)
@@ -318,7 +318,7 @@ namespace GameLauncher
{
try
{
var dir = AppPathHelper.GetGameBackupDirectory(_game.FolderName, _game.RootDirectory);
var dir = AppPathHelper.GetGameBackupDirectory(this._game.FolderName, this._game.RootDirectory);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="GameLauncher.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<!-- 常に管理者権限で実行する -->
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10 / Windows 11 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</application>
</compatibility>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2, PerMonitor</dpiAwareness>
</windowsSettings>
</application>
</assembly>
+1 -1
View File
@@ -1,4 +1,4 @@
/*:
/*:
* @target MZ
* @plugindesc プリンセスシナジー専用: 主人公のHPを常時最大に固定する
* @author GameLauncher
+1 -1
View File
@@ -1,4 +1,4 @@
/*:
/*:
* @target MZ
* @plugindesc プリンセスシナジー専用: 主人公のMPを常時最大に固定する
* @author GameLauncher
+13 -14
View File
@@ -1,4 +1,4 @@
/*:
/*:
* @target MZ
* @plugindesc 戦闘高速化・ウェイト削除・アニメーション早送り
* @author Antigravity
@@ -48,7 +48,7 @@
Window_BattleLog.prototype.isFastForward = function() {
return true;
};
// 念のため、updateWaitCount をオーバーライドしてウェイトを即座に消費させる
const _Window_BattleLog_updateWaitCount = Window_BattleLog.prototype.updateWaitCount;
Window_BattleLog.prototype.updateWaitCount = function() {
@@ -62,10 +62,10 @@
// -------------------------------------------------------------------------
// Sprite_Animation のオーバーライド (アニメーションの高速化)
// -------------------------------------------------------------------------
// MZでは、アニメーションはEffekseerかSprite_Animationによって処理されます。
// Effekseerの場合、速度を上げてみます。
// Sprite_AnimationMVのロジックが存在する場合、オーバーライド(レガシー)
if (Sprite_Animation.prototype.update) {
const _Sprite_Animation_update = Sprite_Animation.prototype.update;
@@ -77,11 +77,11 @@
if (this.isPlaying()) _Sprite_Animation_update.call(this);
};
}
// -------------------------------------------------------------------------
// Scene_Battle のオーバーライド
// -------------------------------------------------------------------------
// バトルシーンでの早送りを強制
Scene_Battle.prototype.isFastForward = function() {
return true;
@@ -90,12 +90,12 @@
// -------------------------------------------------------------------------
// Scene_Base のオーバーライド (トランジションの高速化)
// -------------------------------------------------------------------------
// 標準フェードの高速化
Scene_Base.prototype.fadeSpeed = function() {
return 1;
};
// 低速フェードの高速化
Scene_Base.prototype.slowFadeSpeed = function() {
return 5;
@@ -104,7 +104,7 @@
// -------------------------------------------------------------------------
// SceneManager のオーバーライド (Effekseerの高速化)
// -------------------------------------------------------------------------
// Effekseerアニメーション(MZのバトルで使用)の高速化
if (SceneManager.updateEffekseer) {
SceneManager.updateEffekseer = function() {
@@ -122,7 +122,7 @@
}
};
}
// -------------------------------------------------------------------------
// Game_CharacterBase のオーバーライド (移動の高速化)
// -------------------------------------------------------------------------
@@ -136,11 +136,11 @@
// // プレイヤーにのみ高速化を適用したい場合でも、ここで適用するとデフォルトですべてのキャラクターに影響します。
// // プレイヤーのみに適用するには、Game_Player.prototype.initMembersなどをオーバーライドしてください。
// };
//
//
// // プレイヤーの速度を上げるためにrealMoveSpeedをオーバーライド
// Game_Player.prototype.realMoveSpeed = function() {
// // 標準移動速度 + 3(超高速)
// return this._moveSpeed + 2;
// return this._moveSpeed + 2;
// };
// -------------------------------------------------------------------------
@@ -165,7 +165,7 @@
// -------------------------------------------------------------------------
// Scene_Battle のオーバーライド (自動戦闘 & 自動開始)
// -------------------------------------------------------------------------
// バトル開始メッセージをスキップ
BattleManager.displayStartMessages = function() {
// 何もしない
@@ -207,4 +207,3 @@
};
})();
+1 -2
View File
@@ -1,4 +1,4 @@
/*:
/*:
* @target MZ MV
* @plugindesc 戦闘ターン開始時およびコマンド選択時に味方全員のHPを全回復します。
* @author GameLauncher
@@ -28,4 +28,3 @@
_BattleManager_startInput.call(this);
};
})();
+1 -2
View File
@@ -1,4 +1,4 @@
/*:
/*:
* @target MZ MV
* @plugindesc 戦闘ターン開始時およびコマンド選択時に味方全員のMPを全回復します。
* @author GameLauncher
@@ -28,4 +28,3 @@
_BattleManager_startInput.call(this);
};
})();
+1 -2
View File
@@ -1,4 +1,4 @@
/*:
/*:
* @target MZ MV
* @plugindesc 戦闘ターン開始時およびコマンド選択時に味方全員のTPを全回復します。
* @author GameLauncher
@@ -28,4 +28,3 @@
_BattleManager_startInput.call(this);
};
})();
+1 -1
View File
@@ -1,4 +1,4 @@
/*:
/*:
* @target MZ MV
* @plugindesc マップ移動時のダッシュ速度を通常より大幅に高速化します。
* @author GameLauncher
+1 -1
View File
@@ -1,4 +1,4 @@
/*:
/*:
* @target MZ MV
* @plugindesc 経験値を獲得した際、即座に最大レベル(99)まで成長させます。
* @author GameLauncher
-99
View File
@@ -1,99 +0,0 @@
/*:
* @plugindesc GameLauncher mod (HP once at self turn start / MP always MAX / speed).
* @author GameLauncher
*
* @param EnableHpRecover
* @text HP自動回復(自ターン開始時のみ)
* @type boolean
* @default true
*
* @param EnableMpRecover
* @text MP常時MAX
* @type boolean
* @default true
*
* @param SpeedMultiplier
* @text 速度倍率
* @type number
* @decimals 2
* @default 3.0
*/
(function () {
'use strict';
var pluginName = 'GameLauncher_Mod';
var params = PluginManager.parameters(pluginName) || {};
function toBool(v, def) {
if (v === undefined || v === null || v === '') return def;
return String(v).toLowerCase() === 'true';
}
var ENABLE_HP = toBool(params['EnableHpRecover'], true);
var ENABLE_MP = toBool(params['EnableMpRecover'], true);
var SPEED = parseFloat(params['SpeedMultiplier']);
if (isNaN(SPEED) || SPEED <= 0) SPEED = 3.0;
// 自パーティのアクターかどうか(他ゲーム・敵などへ影響しないよう厳密判定)
function isPlayerActor(battler) {
return battler && typeof battler.isActor === 'function' && battler.isActor();
}
// =========================================================================
// HP: 自ターン開始時に1度だけ MAX まで回復する。
// 毎フレーム回復はしない(次ターンまでプレイヤーは自由にHPを減らせる)。
// =========================================================================
if (ENABLE_HP && typeof BattleManager !== 'undefined' && BattleManager.startTurn) {
var _GameLauncher_startTurn = BattleManager.startTurn;
BattleManager.startTurn = function () {
_GameLauncher_startTurn.call(this);
var battler = this.actor && this.actor();
if (isPlayerActor(battler)) {
// この瞬間に一度だけ全回復(以降はダメージで減らせる)
battler.setHp(battler.mhp);
}
};
}
// =========================================================================
// MP: 常時 MAX を維持する(自アクターのみ、値が mmp 未満なら即座に戻す)。
// =========================================================================
if (ENABLE_MP && typeof Game_Battler !== 'undefined' && Game_Battler.prototype) {
var _GameLauncher_setMp = Game_Battler.prototype.setMp;
Game_Battler.prototype.setMp = function (value) {
_GameLauncher_setMp.call(this, value);
if (isPlayerActor(this)) {
this._mp = this.mmp;
}
};
var _GameLauncher_refresh = Game_Battler.prototype.refresh;
Game_Battler.prototype.refresh = function () {
_GameLauncher_refresh.call(this);
if (isPlayerActor(this)) {
this._mp = this.mmp;
}
};
}
// =========================================================================
// 速度倍率: シーン更新のデルタタイムを実質的に乗算する(speedhack)。
// =========================================================================
if (SPEED !== 1.0 && typeof SceneManager !== 'undefined' && SceneManager.updateMain) {
var _GameLauncher_updateMain = SceneManager.updateMain;
SceneManager.updateMain = function () {
var scene = this._scene;
if (scene && scene.isActive && scene.isActive()) {
var delta = this._deltaTime || (1000 / 60);
if (scene.update) {
scene.update(delta * SPEED);
}
if (scene.isActive && scene.isActive()) {
_GameLauncher_updateMain.call(this);
}
return;
}
_GameLauncher_updateMain.call(this);
};
}
})();
+1 -1
View File
@@ -1,4 +1,4 @@
/*:
/*:
* @target MZ MV
* @plugindesc お金(ゴールド)を入手した際、所持金を即座に最大値(9999999)にします。
* @author GameLauncher
+1 -1
View File
@@ -1,4 +1,4 @@
/*:
/*:
* @target MZ MV
* @plugindesc アイテム・武器・防具を入手した際、自動的に所持数を最大値(99個)にします。
* @author GameLauncher
+1 -1
View File
@@ -1,4 +1,4 @@
/*:
/*:
* @target MZ MV
* @plugindesc 通常アイテム使用時の消費を無効化します(減らずに何度でも使用可能)。
* @author GameLauncher
+1 -1
View File
@@ -1,4 +1,4 @@
/*:
/*:
* @target MZ MV
* @plugindesc メッセージを常に瞬間表示し、文章中のウェイトを無効化します。
* @author GameLauncher
+263
View File
@@ -0,0 +1,263 @@
/*:
* @target MZ MV
* @plugindesc 日本語・URLエンコード・文字化け・機種依存文字(丸数字等)の素材読み込み失敗を自動修復・救済します。
* @author GameLauncher
*
* @help
* 日本語ファイル名がURLエンコード(%E3%...)されたり、ファイル名と要求パスが
* 一致せず「Loading Error Failed to load」で停止してしまう現象を自動的に修復・救済します。
* 丸数字(①②...)と通常数字(1, 2...)の表記揺れやNW.jsのファイルシステム探索に対応しています。
*/
(() => {
'use strict';
const hasNode = typeof require === 'function' && typeof process === 'object';
const fs = hasNode ? require('fs') : null;
const path = hasNode ? require('path') : null;
// 1x1 透明 PNG (Data URL) - 万が一ファイルが見つからない場合のフォールバック用
const BLANK_PNG = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
// 丸数字・ローマ数字・全角数字のマッピングテーブル
const CIRCLE_NUMBERS = ['①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨', '⑩', '⑪', '⑫', '⑬', '⑭', '⑮', '⑯', '⑰', '⑱', '⑲', '⑳'];
/**
* 文字列内の丸数字や全角数字、波ダッシュ等を正規化して比較用キーを生成します。
* @param {string} str - 対象文字列
* @returns {string} 正規化文字列
*/
function normalizeFuzzy(str) {
if (!str) return '';
let res = str.normalize('NFC').toLowerCase();
// 丸数字 -> 通常数字
for (let i = 0; i < CIRCLE_NUMBERS.length; i++) {
res = res.replaceAll(CIRCLE_NUMBERS[i], String(i + 1));
}
// 全角数字 -> 半角数字
res = res.replace(/[0-9]/g, s => String.fromCharCode(s.charCodeAt(0) - 0xFEE0));
// 波ダッシュ・チルダ
res = res.replaceAll('\u301C', '\uFF5E');
// 全角カッコ -> 半角カッコ
res = res.replaceAll('(', '(').replaceAll(')', ')');
return res;
}
/**
* URLからファイルシステム上の実ファイルを探索します。
* @param {string} url - 読み込み対象のURL/相対パス
* @returns {string|null} 実ファイルの絶対パスまたは相対パス(見つからない場合はnull)
*/
function findActualFile(url) {
if (!fs || !path || !url) return null;
// クエリパラメータやハッシュを除去
const cleanUrl = url.split('?')[0].split('#')[0];
let decodedUrl = cleanUrl;
try {
decodedUrl = decodeURIComponent(cleanUrl);
} catch (e) { }
// 中途半端に % が残っている場合の再デコード
if (decodedUrl.includes('%')) {
try {
decodedUrl = decodedUrl.replace(/(%[0-9A-Fa-f]{2})+/g, match => {
try { return decodeURIComponent(match); } catch (e) { return match; }
});
} catch (e) { }
}
let encodedUrl = cleanUrl;
try {
const parts = cleanUrl.split('/');
encodedUrl = parts.map(p => encodeURIComponent(decodeURIComponent(p))).join('/');
} catch (e) { }
// 1. そのままのパスで存在するか
if (fs.existsSync(cleanUrl)) return cleanUrl;
// 2. URLデコードしたパスで存在するか
if (fs.existsSync(decodedUrl)) return decodedUrl;
// 3. URLエンコードしたパスで存在するか
if (fs.existsSync(encodedUrl)) return encodedUrl;
// 4. ディレクトリ内の実ファイルを走査して柔軟に検索(丸数字・表記揺れ対応)
try {
const dir = path.dirname(decodedUrl);
const targetBase = path.basename(decodedUrl);
const targetExt = path.extname(decodedUrl);
const targetNameWithoutExt = path.basename(decodedUrl, targetExt);
if (fs.existsSync(dir)) {
const files = fs.readdirSync(dir);
const fuzzyTarget = normalizeFuzzy(targetBase);
const fuzzyTargetWithoutExt = normalizeFuzzy(targetNameWithoutExt);
for (const file of files) {
const fileExt = path.extname(file);
const fileNameWithoutExt = path.basename(file, fileExt);
// A. 通常比較
if (file.toLowerCase() === targetBase.toLowerCase()) {
return path.join(dir, file);
}
// B. 表記揺れ(丸数字①⇔1、全角数字等)のファジーマッチ
const fuzzyFile = normalizeFuzzy(file);
const fuzzyFileWithoutExt = normalizeFuzzy(fileNameWithoutExt);
if (fuzzyFile === fuzzyTarget) {
return path.join(dir, file);
}
if (fuzzyFileWithoutExt === fuzzyTargetWithoutExt && fileExt.toLowerCase() === targetExt.toLowerCase()) {
return path.join(dir, file);
}
// C. URLエンコード/デコードされたファイル名との比較
try {
const decodedFile = decodeURIComponent(file);
if (normalizeFuzzy(decodedFile) === fuzzyTarget) {
return path.join(dir, file);
}
} catch (e) { }
}
}
} catch (e) { }
return null;
}
/**
* 実ファイルをBase64 DataURLとして読み込みます。
* @param {string} filePath - 実ファイルのパス
* @param {string} mimeType - MIMEタイプ
* @returns {string|null} DataURL
*/
function readFileAsDataUrl(filePath, mimeType = 'image/png') {
if (!fs || !filePath) return null;
try {
const buf = fs.readFileSync(filePath);
return `data:${mimeType};base64,${buf.toString('base64')}`;
} catch (e) {
return null;
}
}
// =========================================================================
// 1. Bitmap ロードの救済 (ツクールMV / MZ)
// =========================================================================
if (typeof Bitmap !== 'undefined') {
const _Bitmap_load = Bitmap.load;
Bitmap.load = function(url) {
if (fs && url) {
const actual = findActualFile(url);
if (actual && actual !== url) {
try {
const actualUrl = actual.replace(/\\/g, '/');
return _Bitmap_load.call(this, actualUrl);
} catch (e) { }
}
}
return _Bitmap_load.call(this, url);
};
const _Bitmap_prototype_onError = Bitmap.prototype._onError;
Bitmap.prototype._onError = function() {
if (!this._recoveryAttempted && this._url) {
this._recoveryAttempted = true;
const actualFile = findActualFile(this._url);
if (actualFile) {
const dataUrl = readFileAsDataUrl(actualFile, 'image/png');
if (dataUrl && this._image) {
console.log(`[GameLauncher] 画像の実ファイルを特定して自動救済: ${this._url} -> ${actualFile}`);
this._isLoading = true;
this._hasError = false;
this._image.src = dataUrl;
return;
}
}
// URLデコード版を直接 image.src に設定してリトライ
try {
const decoded = decodeURIComponent(this._url);
if (decoded !== this._url && this._image) {
this._isLoading = true;
this._hasError = false;
this._url = decoded;
this._image.src = decoded;
return;
}
} catch (e) { }
// 最終手段: ゲーム停止・クラッシュを回避するため透明PNGで代替
if (this._image) {
console.warn(`[GameLauncher] 未存在画像の透過代替を適用(エラー停止回避): ${this._url}`);
this._isLoading = false;
this._hasError = false;
this._image.src = BLANK_PNG;
if (typeof this._onLoad === 'function') {
try { this._onLoad(); } catch (e) { }
}
return;
}
}
_Bitmap_prototype_onError.call(this);
};
}
// =========================================================================
// 2. WebAudio / AudioManager ロードの救済 (ツクールMV / MZ)
// =========================================================================
if (typeof WebAudio !== 'undefined') {
const _WebAudio_prototype_load = WebAudio.prototype._load;
WebAudio.prototype._load = function(url) {
let targetUrl = url;
if (fs && url) {
const actual = findActualFile(url);
if (actual) {
targetUrl = actual.replace(/\\/g, '/');
}
}
return _WebAudio_prototype_load.call(this, targetUrl);
};
}
// =========================================================================
// 3. Graphics.printLoadingError のエラー停止緩和
// =========================================================================
if (typeof Graphics !== 'undefined' && Graphics.printLoadingError) {
const _Graphics_printLoadingError = Graphics.printLoadingError;
Graphics.printLoadingError = function(url) {
console.warn(`[GameLauncher] Loading Error が検出されました: ${url}`);
_Graphics_printLoadingError.call(this, url);
};
}
// =========================================================================
// 4. PluginManager スクリプト読み込みの救済
// =========================================================================
if (typeof PluginManager !== 'undefined' && PluginManager.loadScript) {
const _PluginManager_loadScript = PluginManager.loadScript;
PluginManager.loadScript = function(name) {
if (fs && name) {
const target = 'js/plugins/' + name;
const actual = findActualFile(target);
if (actual) {
const baseName = path.basename(actual);
return _PluginManager_loadScript.call(this, baseName);
}
}
return _PluginManager_loadScript.call(this, name);
};
}
console.log('[GameLauncher] ResourceLoaderFix プラグインが正常にロードされました。');
})();
+1 -1
View File
@@ -1,4 +1,4 @@
/*:
/*:
* @target MZ MV
* @plugindesc ショップでのアイテム購入時、個数入力の初期値を最大購入可能数にします。
* @author GameLauncher
+1 -1
View File
@@ -53,4 +53,4 @@ if ($LASTEXITCODE -eq 0) {
Write-Host "発行成功: $publishDir\GameLauncher.exe" -ForegroundColor Green
} else {
Write-Host "発行失敗 (終了コード: $LASTEXITCODE)" -ForegroundColor Red
}
}