feat(scanner): アイコンサムネイルキャッシュ・深層exe探索・ブックマーク永続化に対応

- 抽出したアイコンを PNG 形式で Thumbnails フォルダにキャッシュし再スキャンを高速化
- サブディレクトリ内のゲーム実行ファイル(.exe)を最大深さまで再帰探索するロジックを追加
- キャッシュ再構築時でもお気に入りを保持する bookmarks.json 独立永続化機能を追加
- EngineLogicVersion によるエンジン判定ロジック更新時のキャッシュ自動無効化・再スキャンを導入
- EVB・スタンドアロン・その他エンジンの消失復旧および判定ロジックを強化
This commit is contained in:
armonica committed 2026-10-14 09:58:33 +09:00
1 parent 45bff52198
commit cfdba6806a
1 file changed
+565 -79
+565 -79
View File
@@ -42,6 +42,12 @@ namespace GameLauncher.Services
public DateTime? FolderLastModified { get; set; } public DateTime? FolderLastModified { get; set; }
public bool IsBookmarked { get; set; } public bool IsBookmarked { get; set; }
/// <summary>
/// エンジン判定ロジックのバージョン。値が現在のロジックと異なるキャッシュは無効化し、
/// 再スキャンしてラベルを正しく付け直します。
/// </summary>
public int EngineLogicVersion { get; set; }
// ツクール / ティラノ専用 // ツクール / ティラノ専用
public string PluginsJsPath { get; set; } = string.Empty; public string PluginsJsPath { get; set; } = string.Empty;
public string PluginsDirPath { get; set; } = string.Empty; public string PluginsDirPath { get; set; } = string.Empty;
@@ -100,8 +106,20 @@ namespace GameLauncher.Services
]; ];
private readonly string _cacheFilePath; private readonly string _cacheFilePath;
/// <summary>
/// ブックマーク専用の永続ファイルパス。キャッシュとは独立して管理し、
/// キャッシュ破棄・再スキャンが発生してもブックマークは保持されます。
/// </summary>
private readonly string _bookmarksFilePath;
private readonly AsarArchiveService _asarService = new(); private readonly AsarArchiveService _asarService = new();
/// <summary>
/// エンジン判定ロジックのバージョン。判定条件を変更したらこの値をインクリメントすると、
/// 既存キャッシュは自動的に無効化され、次回起動時に再スキャンされます。
/// </summary>
private const int CurrentEngineLogicVersion = 2;
static GameScannerService() static GameScannerService()
{ {
try try
@@ -115,6 +133,7 @@ namespace GameLauncher.Services
{ {
var baseDir = AppPathHelper.GetExeDirectory(); var baseDir = AppPathHelper.GetExeDirectory();
_cacheFilePath = Path.Combine(baseDir, "games_cache.json"); _cacheFilePath = Path.Combine(baseDir, "games_cache.json");
_bookmarksFilePath = Path.Combine(baseDir, "bookmarks.json");
} }
/// <summary> /// <summary>
@@ -133,6 +152,14 @@ namespace GameLauncher.Services
string json = File.ReadAllText(_cacheFilePath); string json = File.ReadAllText(_cacheFilePath);
var entries = JsonSerializer.Deserialize<List<UnifiedGameCacheEntry>>(json); var entries = JsonSerializer.Deserialize<List<UnifiedGameCacheEntry>>(json);
if (entries != null) if (entries != null)
{
// エンジン判定ロジックが更新されている場合はキャッシュを破棄して再スキャンさせる。
if (entries.Count > 0 && entries[0].EngineLogicVersion != CurrentEngineLogicVersion)
{
entries = null;
}
}
if (entries != null)
{ {
foreach (var entry in entries) foreach (var entry in entries)
{ {
@@ -409,6 +436,27 @@ namespace GameLauncher.Services
} }
catch { } catch { }
// ブックマーク専用ファイルからブックマーク状態を復元します。
// キャッシュが破棄・再スキャンされても、ブックマークは bookmarks.json から維持されます。
try
{
var bookmarkKeys = LoadBookmarks();
if (bookmarkKeys.Count > 0)
{
foreach (var item in list)
{
if (bookmarkKeys.Contains(NormalizeBookmarkKey(item.RootDirectory)))
{
item.IsBookmarked = true;
}
}
}
// フォルダが消えたブックマークを除去し、既存キャッシュからの移行も兼ねて保存し直します。
SaveBookmarks(list);
}
catch { }
return list; return list;
} }
@@ -428,6 +476,7 @@ namespace GameLauncher.Services
entries.Add(new UnifiedGameCacheEntry entries.Add(new UnifiedGameCacheEntry
{ {
EngineKind = (int)GameEngineKind.Unity, EngineKind = (int)GameEngineKind.Unity,
EngineLogicVersion = CurrentEngineLogicVersion,
Title = ug.Title, Title = ug.Title,
FolderName = ug.FolderName, FolderName = ug.FolderName,
RootDirectory = ug.RootDirectory, RootDirectory = ug.RootDirectory,
@@ -448,6 +497,7 @@ namespace GameLauncher.Services
entries.Add(new UnifiedGameCacheEntry entries.Add(new UnifiedGameCacheEntry
{ {
EngineKind = (int)tg.EngineKind, EngineKind = (int)tg.EngineKind,
EngineLogicVersion = CurrentEngineLogicVersion,
Title = tg.Title, Title = tg.Title,
FolderName = tg.FolderName, FolderName = tg.FolderName,
RootDirectory = tg.RootDirectory, RootDirectory = tg.RootDirectory,
@@ -504,6 +554,88 @@ namespace GameLauncher.Services
catch { } catch { }
} }
/// <summary>
/// ブックマーク対象ゲームの識別キーを正規化します。
/// タイトル変動に耐えるため、RootDirectory をフルパス化し末尾セパレータを除去した文字列をキーとします。
/// </summary>
private static string NormalizeBookmarkKey(string rootDirectory)
{
if (string.IsNullOrWhiteSpace(rootDirectory))
{
return string.Empty;
}
try
{
string fullPath = Path.GetFullPath(rootDirectory);
return fullPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
catch
{
return rootDirectory.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
}
/// <summary>
/// ブックマーク専用ファイル(bookmarks.json)からブックマーク済みフォルダのキー集合を読み込みます。
/// ファイルが無い・壊れている場合は空集合を返します。
/// </summary>
public HashSet<string> LoadBookmarks()
{
var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
try
{
if (!File.Exists(_bookmarksFilePath))
{
return set;
}
string json = File.ReadAllText(_bookmarksFilePath);
var keys = JsonSerializer.Deserialize<List<string>>(json);
if (keys != null)
{
foreach (var key in keys)
{
if (!string.IsNullOrWhiteSpace(key))
{
set.Add(NormalizeBookmarkKey(key));
}
}
}
}
catch { }
return set;
}
/// <summary>
/// ブックマーク済みゲームのキー一覧をブックマーク専用ファイル(bookmarks.json)へ保存します。
/// キャッシュとは独立しているため、キャッシュ破棄・再スキャン時もブックマークは保持されます。
/// </summary>
public void SaveBookmarks(IEnumerable<GameItemBase> games)
{
try
{
var keys = games
.Where(g => g.IsBookmarked)
.Select(g => NormalizeBookmarkKey(g.RootDirectory))
.Where(k => !string.IsNullOrEmpty(k))
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
var options = new JsonSerializerOptions
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
string json = JsonSerializer.Serialize(keys, options);
File.WriteAllText(_bookmarksFilePath, json);
}
catch { }
}
/// <summary> /// <summary>
/// キャッシュから読み込んだゲームのアイコン取得や改造状態の確認、実在検証をバックグラウンドで行います。 /// キャッシュから読み込んだゲームのアイコン取得や改造状態の確認、実在検証をバックグラウンドで行います。
/// </summary> /// </summary>
@@ -534,9 +666,18 @@ namespace GameLauncher.Services
{ {
if (!File.Exists(ug.ExecutablePath)) if (!File.Exists(ug.ExecutablePath))
{ {
onGameRemoved(ug); var recovered = FindGameExecutable(ug.RootDirectory);
cacheNeedsSave = true; if (!string.IsNullOrEmpty(recovered))
continue; {
ug.ExecutablePath = recovered;
cacheNeedsSave = true;
}
else
{
onGameRemoved(ug);
cacheNeedsSave = true;
continue;
}
} }
// フォルダ更新日時 // フォルダ更新日時
@@ -603,9 +744,18 @@ namespace GameLauncher.Services
{ {
if (!File.Exists(tg.ExecutablePath)) if (!File.Exists(tg.ExecutablePath))
{ {
onGameRemoved(tg); var recovered = FindGameExecutable(tg.RootDirectory);
cacheNeedsSave = true; if (!string.IsNullOrEmpty(recovered))
continue; {
tg.ExecutablePath = recovered;
cacheNeedsSave = true;
}
else
{
onGameRemoved(tg);
cacheNeedsSave = true;
continue;
}
} }
// アーカイブ・解凍状態・プロキシDLLの最新同期 // アーカイブ・解凍状態・プロキシDLLの最新同期
@@ -628,9 +778,18 @@ namespace GameLauncher.Services
{ {
if (!File.Exists(tg.ExecutablePath)) if (!File.Exists(tg.ExecutablePath))
{ {
onGameRemoved(tg); var recovered = FindGameExecutable(tg.RootDirectory);
cacheNeedsSave = true; if (!string.IsNullOrEmpty(recovered))
continue; {
tg.ExecutablePath = recovered;
cacheNeedsSave = true;
}
else
{
onGameRemoved(tg);
cacheNeedsSave = true;
continue;
}
} }
// アーカイブ・解凍状態・プロキシDLL・Modスクリプトの最新同期 // アーカイブ・解凍状態・プロキシDLL・Modスクリプトの最新同期
@@ -706,13 +865,22 @@ namespace GameLauncher.Services
continue; continue;
} }
} }
else if (tg.IsEvbPacked || tg.IsStandaloneExePackage) else if (tg.IsEvbPacked || tg.IsStandaloneExePackage || tg.IsOther)
{ {
if (!File.Exists(tg.ExecutablePath)) if (!File.Exists(tg.ExecutablePath))
{ {
onGameRemoved(tg); var recovered = FindGameExecutable(tg.RootDirectory);
cacheNeedsSave = true; if (!string.IsNullOrEmpty(recovered))
continue; {
tg.ExecutablePath = recovered;
cacheNeedsSave = true;
}
else
{
onGameRemoved(tg);
cacheNeedsSave = true;
continue;
}
} }
} }
else else
@@ -793,56 +961,88 @@ namespace GameLauncher.Services
{ {
await Task.Run(() => await Task.Run(() =>
{ {
var po = new ParallelOptions
{
CancellationToken = ct,
MaxDegreeOfParallelism = Math.Clamp(Environment.ProcessorCount * 2, 4, 16)
};
foreach (var targetPath in targetPaths) foreach (var targetPath in targetPaths)
{ {
if (ct.IsCancellationRequested) break; if (ct.IsCancellationRequested) break;
if (!Directory.Exists(targetPath)) continue; if (!Directory.Exists(targetPath)) continue;
IEnumerable<string> subDirs; List<string> subDirs;
try try
{ {
subDirs = Directory.EnumerateDirectories(targetPath); subDirs = Directory.EnumerateDirectories(targetPath).ToList();
} }
catch catch
{ {
continue; continue;
} }
foreach (var dir in subDirs) try
{ {
if (ct.IsCancellationRequested) break; Parallel.ForEach(subDirs, po, (dir, loopState) =>
// 既に検出済みのパスならスキップ
if (existingPaths.Contains(dir))
continue;
// ディレクトリ直下のゲームを検出
var game = DetectGameInDirectory(dir);
if (game != null)
{ {
existingPaths.Add(dir); if (ct.IsCancellationRequested)
progress.Report(game);
continue;
}
// 1階層下も探索(アーカイブ解凍等でサブフォルダが入っているケース)
try
{
var childDirs = Directory.EnumerateDirectories(dir);
foreach (var childDir in childDirs)
{ {
if (ct.IsCancellationRequested) break; loopState.Stop();
if (existingPaths.Contains(childDir)) continue; return;
}
var childGame = DetectGameInDirectory(childDir); bool isExisting;
if (childGame != null) lock (existingPaths)
{
isExisting = existingPaths.Contains(dir);
}
if (isExisting) return;
// ディレクトリ直下のゲームを検出
var game = DetectGameInDirectory(dir);
if (game != null)
{
lock (existingPaths)
{ {
existingPaths.Add(childDir); existingPaths.Add(dir);
progress.Report(childGame); }
progress.Report(game);
return;
}
// 1階層下も探索(アーカイブ解凍等でサブフォルダが入っているケース)
try
{
var childDirs = Directory.EnumerateDirectories(dir);
foreach (var childDir in childDirs)
{
if (ct.IsCancellationRequested) break;
bool isChildExisting;
lock (existingPaths)
{
isChildExisting = existingPaths.Contains(childDir);
}
if (isChildExisting) continue;
var childGame = DetectGameInDirectory(childDir);
if (childGame != null)
{
lock (existingPaths)
{
existingPaths.Add(childDir);
}
progress.Report(childGame);
}
} }
} }
} catch { }
catch { } });
}
catch (OperationCanceledException)
{
break;
} }
} }
}, ct); }, ct);
@@ -858,18 +1058,29 @@ namespace GameLauncher.Services
if (!Directory.Exists(dirPath)) if (!Directory.Exists(dirPath))
return null; return null;
// 1. まずツクール/ティラノ判定 // 1. まずUnity判定(最優先)
// Unityゲームのフォルダ内に data\system や index.html が存在すると、
// 後段のティラノ判定が誤反応してUnityがティラノ扱いになるため、
// 信頼性の高いUnity証拠(UnityPlayer.dll / *_Data\globalgamemanagers 等)を
// 最優先で評価し、他エンジン判定より先に確定させる。
var unityGame = DetectUnityGameInDirectory(dirPath);
if (unityGame != null)
{
return unityGame;
}
// 2. 次にツクール/ティラノ判定
var tkoolGame = DetectTkoolGameInDirectory(dirPath); var tkoolGame = DetectTkoolGameInDirectory(dirPath);
if (tkoolGame != null) if (tkoolGame != null)
{ {
return tkoolGame; return tkoolGame;
} }
// 2. 次にUnity判定 // 3. どの特定エンジンにも該当しない場合は「その他」ゲーム判定
var unityGame = DetectUnityGameInDirectory(dirPath); var otherGame = DetectOtherGameInDirectory(dirPath);
if (unityGame != null) if (otherGame != null)
{ {
return unityGame; return otherGame;
} }
} }
catch { } catch { }
@@ -877,6 +1088,53 @@ namespace GameLauncher.Services
return null; return null;
} }
/// <summary>
/// 指定エンジン(ツクール・ティラノ・ウディタ・SRPG・Unity・NW.js等)に該当しないフォルダから、
/// 実行可能ファイル(.exe)を持つゲームを「その他」ゲームとして検出します。
/// </summary>
public TkoolGameItem? DetectOtherGameInDirectory(string dirPath)
{
try
{
if (!Directory.Exists(dirPath)) return null;
// Unity証拠があるディレクトリは「その他」ではなくUnityとして扱うべきなので除外する。
// (DetectGameInDirectory の順序変更に加えた二重の安全策)
if (HasStrongUnityEvidence(dirPath))
return null;
var folderName = Path.GetFileName(dirPath.TrimEnd('\\', '/'));
DateTime? folderModified = null;
try { folderModified = Directory.GetLastWriteTime(dirPath); } catch { }
// 直下またはサブフォルダ配下から有効な .exe を探索
var exePath = FindGameExecutable(dirPath, maxDepth: 3);
if (string.IsNullOrEmpty(exePath))
{
return null;
}
var icon = LoadIcon(exePath, dirPath);
return new TkoolGameItem
{
Title = folderName,
FolderName = folderName,
RootDirectory = dirPath,
ExecutablePath = exePath,
EngineType = TkoolEngineType.Other,
IconImage = icon,
FolderLastModified = folderModified,
ApplyMod = false,
HasCustomApplyMod = true
};
}
catch
{
return null;
}
}
#region ツクール / ティラノ 検出ロジック #region ツクール / ティラノ 検出ロジック
/// <summary> /// <summary>
@@ -1565,6 +1823,7 @@ namespace GameLauncher.Services
} }
} }
exePath ??= FindGameExecutable(dirPath);
if (exePath == null) if (exePath == null)
{ {
return null; return null;
@@ -1757,6 +2016,7 @@ namespace GameLauncher.Services
} }
} }
exePath ??= FindGameExecutable(dirPath);
if (exePath == null) if (exePath == null)
{ {
return null; return null;
@@ -2082,6 +2342,7 @@ namespace GameLauncher.Services
// 実行ファイルの探索 (Game.exe、または searchDir 内の exe) // 実行ファイルの探索 (Game.exe、または searchDir 内の exe)
var exePath = FindRgssExecutable(searchDir, dirPath); var exePath = FindRgssExecutable(searchDir, dirPath);
exePath ??= FindGameExecutable(dirPath);
if (exePath == null) if (exePath == null)
{ {
return null; return null;
@@ -2225,14 +2486,27 @@ namespace GameLauncher.Services
{ {
try try
{ {
if (Directory.Exists(Path.Combine(dir, "tyrano")) || Directory.Exists(Path.Combine(dir, "data", "system"))) // Unityゲームのフォルダは data\system や index.html を持つ場合があり、
// ティラノスクリプトと誤判定しやすい。Unity証拠が明確な場合はティラノ対象外とする。
if (HasStrongUnityEvidence(dir))
return false;
bool hasTyranoDir = Directory.Exists(Path.Combine(dir, "tyrano"));
bool hasDataSystem = Directory.Exists(Path.Combine(dir, "data", "system"));
// tyrano フォルダはティラノ固有の強い証拠。単独で確定してよい。
if (hasTyranoDir)
return true; return true;
var indexPath = Path.Combine(dir, "index.html"); var indexPath = Path.Combine(dir, "index.html");
if (File.Exists(indexPath)) if (File.Exists(indexPath))
{ {
var html = File.ReadAllText(indexPath); var html = File.ReadAllText(indexPath);
if (html.Contains("tyrano", StringComparison.OrdinalIgnoreCase)) bool htmlHasTyrano = html.Contains("tyrano", StringComparison.OrdinalIgnoreCase);
// data\system 単独では他エンジン(Unity等)と誤爆し得るため、
// index.html 内に "tyrano" 文字列があることを確定条件とする。
if (hasDataSystem && htmlHasTyrano)
return true; return true;
} }
@@ -2241,7 +2515,8 @@ namespace GameLauncher.Services
if (File.Exists(fossilIndexPath)) if (File.Exists(fossilIndexPath))
{ {
var html = File.ReadAllText(fossilIndexPath); var html = File.ReadAllText(fossilIndexPath);
if (html.Contains("tyrano", StringComparison.OrdinalIgnoreCase)) if (html.Contains("tyrano", StringComparison.OrdinalIgnoreCase) ||
html.Contains("FOSSIL", StringComparison.OrdinalIgnoreCase))
return true; return true;
} }
} }
@@ -2250,6 +2525,45 @@ namespace GameLauncher.Services
return false; return false;
} }
/// <summary>
/// ディレクトリがUnity製ゲームであることを示す強い証拠が存在するかを判定します。
/// ティラノ等の他エンジン判定がUnityを誤って取り込まないための事前除外に用います。
/// </summary>
private static bool HasStrongUnityEvidence(string dir)
{
try
{
if (!Directory.Exists(dir))
return false;
// UnityPlayer.dll の存在はUnityビルドの決定的な証拠。
if (File.Exists(Path.Combine(dir, "UnityPlayer.dll")))
return true;
// UnityCrashHandler もUnity固有。
if (Directory.GetFiles(dir, "UnityCrashHandler*.exe", SearchOption.TopDirectoryOnly).Length > 0)
return true;
// *_Data フォルダ内の globalgamemanagers はUnityビルドの中核ファイル。
foreach (var sub in Directory.GetDirectories(dir))
{
if (!Path.GetFileName(sub).EndsWith("_Data", StringComparison.OrdinalIgnoreCase))
continue;
if (File.Exists(Path.Combine(sub, "globalgamemanagers")) ||
File.Exists(Path.Combine(sub, "globalgamemanagers.assets")) ||
Directory.Exists(Path.Combine(sub, "il2cpp_data")) ||
Directory.Exists(Path.Combine(sub, "Managed")))
{
return true;
}
}
}
catch { }
return false;
}
private TkoolEngineType DetectEngineType(string jsDir) private TkoolEngineType DetectEngineType(string jsDir)
{ {
try try
@@ -2331,6 +2645,9 @@ namespace GameLauncher.Services
.ToList(); .ToList();
if (pExes.Count > 0) return pExes[0]; if (pExes.Count > 0) return pExes[0];
} }
// 直下・親で見つからない場合はサブフォルダ内を探索
return FindGameExecutable(rootDir);
} }
catch { } catch { }
@@ -2457,6 +2774,9 @@ namespace GameLauncher.Services
{ {
return exeFiles[0]; return exeFiles[0];
} }
// 直下に見つからない場合はサブフォルダ内を探索
return FindGameExecutable(gameRoot);
} }
catch { } catch { }
@@ -2607,44 +2927,204 @@ namespace GameLauncher.Services
#endregion #endregion
#region 共通アイコン取得 #region 共通アイコン&サムネイルキャッシュ取得
/// <summary>
/// 実行ファイルまたはフォルダからアプリアイコン・サムネイルを取得します。
/// exeと同階層のThumbnailsフォルダにPNG画像としてキャッシュし、2回目以降は超高速に表示します。
/// </summary>
public static ImageSource? LoadIcon(string? exePath, string? fallbackDir = null) public static ImageSource? LoadIcon(string? exePath, string? fallbackDir = null)
{ {
if (string.IsNullOrEmpty(exePath) || !File.Exists(exePath)) var keyPath = !string.IsNullOrEmpty(exePath) ? exePath : fallbackDir;
if (string.IsNullOrEmpty(keyPath))
{ {
if (!string.IsNullOrEmpty(fallbackDir) && Directory.Exists(fallbackDir))
{
var png = Path.Combine(fallbackDir, "icon.png");
if (File.Exists(png))
{
try
{
var bmp = new BitmapImage();
bmp.BeginInit();
bmp.UriSource = new Uri(png);
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.EndInit();
bmp.Freeze();
return bmp;
}
catch { }
}
}
return null; return null;
} }
// 1. サムネイルキャッシュフォルダから即座にロードを試行
string? thumbPath = null;
try try
{ {
using var sysIcon = Icon.ExtractAssociatedIcon(exePath); var thumbDir = AppPathHelper.GetThumbnailsDirectory();
if (sysIcon != null) using var md5 = System.Security.Cryptography.MD5.Create();
var hashBytes = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(keyPath.ToLowerInvariant()));
var hashStr = Convert.ToHexString(hashBytes);
thumbPath = Path.Combine(thumbDir, $"{hashStr}.png");
if (File.Exists(thumbPath))
{ {
var bitmapSource = Imaging.CreateBitmapSourceFromHIcon( var bmp = new BitmapImage();
sysIcon.Handle, bmp.BeginInit();
Int32Rect.Empty, bmp.UriSource = new Uri(thumbPath);
BitmapSizeOptions.FromEmptyOptions()); bmp.CacheOption = BitmapCacheOption.OnLoad;
bitmapSource.Freeze(); bmp.EndInit();
return bitmapSource; bmp.Freeze();
return bmp;
}
}
catch { }
// 2. キャッシュに存在しない場合はアイコンまたは画像を抽出
BitmapSource? bitmapSource = null;
if (!string.IsNullOrEmpty(exePath) && File.Exists(exePath))
{
try
{
using var sysIcon = Icon.ExtractAssociatedIcon(exePath);
if (sysIcon != null)
{
bitmapSource = Imaging.CreateBitmapSourceFromHIcon(
sysIcon.Handle,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
bitmapSource.Freeze();
}
}
catch { }
}
if (bitmapSource == null && !string.IsNullOrEmpty(fallbackDir) && Directory.Exists(fallbackDir))
{
var png = Path.Combine(fallbackDir, "icon.png");
if (File.Exists(png))
{
try
{
var bmp = new BitmapImage();
bmp.BeginInit();
bmp.UriSource = new Uri(png);
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.EndInit();
bmp.Freeze();
bitmapSource = bmp;
}
catch { }
}
}
// 3. 取得できたアイコンをサムネイルキャッシュフォルダへ保存
if (bitmapSource != null && !string.IsNullOrEmpty(thumbPath))
{
try
{
SaveBitmapSourceToPng(bitmapSource, thumbPath);
}
catch { }
}
return bitmapSource;
}
private static void SaveBitmapSourceToPng(BitmapSource source, string filePath)
{
try
{
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(source));
using var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
encoder.Save(stream);
}
catch { }
}
/// <summary>
/// ディレクトリ直下またはサブディレクトリ内からゲーム起動用の実行ファイル(.exe)を探索します。
/// 直下にexeが存在しない場合でも、サブフォルダ配下(最大深さまで)を探索して有効なexeを特定します。
/// </summary>
public static string? FindGameExecutable(string rootDir, int maxDepth = 3)
{
try
{
if (!Directory.Exists(rootDir)) return null;
// 1. 直下の優先候補
var preferredNames = new[] { "Game.exe", "nw.exe", "start.exe", "Launch.exe", "Launcher.exe", "Main.exe", "App.exe" };
foreach (var pref in preferredNames)
{
var p = Path.Combine(rootDir, pref);
if (File.Exists(p)) return p;
}
// フォルダ名と同名のexe
var folderName = Path.GetFileName(rootDir.TrimEnd('\\', '/'));
if (!string.IsNullOrEmpty(folderName))
{
var namedExe = Path.Combine(rootDir, folderName + ".exe");
if (File.Exists(namedExe)) return namedExe;
}
// 直下の全exe(除外パターン以外)
var topExes = Directory.GetFiles(rootDir, "*.exe", SearchOption.TopDirectoryOnly)
.Where(f => !IsExcludedExe(f))
.ToList();
if (topExes.Count > 0)
{
return topExes[0];
}
// 2. 直下にない場合、サブディレクトリ(最大深さまで)を再帰探索
return FindExecutableRecursive(rootDir, 1, maxDepth);
}
catch
{
return null;
}
}
private static string? FindExecutableRecursive(string dir, int currentDepth, int maxDepth)
{
if (currentDepth > maxDepth) return null;
try
{
var subDirs = Directory.GetDirectories(dir);
var preferredNames = new[] { "Game.exe", "nw.exe", "start.exe", "Launch.exe", "Launcher.exe", "Main.exe", "App.exe" };
// まず1階層下の各サブフォルダ内を走査
foreach (var sub in subDirs)
{
var subFolderName = Path.GetFileName(sub);
if (subFolderName.StartsWith(".") ||
subFolderName.Equals("Backups", StringComparison.OrdinalIgnoreCase) ||
subFolderName.Equals("Thumbnails", StringComparison.OrdinalIgnoreCase) ||
subFolderName.Equals("Profiles", StringComparison.OrdinalIgnoreCase))
{
continue;
}
foreach (var pref in preferredNames)
{
var cand = Path.Combine(sub, pref);
if (File.Exists(cand)) return cand;
}
var subNamedExe = Path.Combine(sub, subFolderName + ".exe");
if (File.Exists(subNamedExe)) return subNamedExe;
var subExes = Directory.GetFiles(sub, "*.exe", SearchOption.TopDirectoryOnly)
.Where(f => !IsExcludedExe(f))
.ToList();
if (subExes.Count > 0)
{
return subExes[0];
}
}
// さらに深い階層を探索
foreach (var sub in subDirs)
{
var subFolderName = Path.GetFileName(sub);
if (subFolderName.StartsWith(".") ||
subFolderName.Equals("Backups", StringComparison.OrdinalIgnoreCase) ||
subFolderName.Equals("Thumbnails", StringComparison.OrdinalIgnoreCase) ||
subFolderName.Equals("Profiles", StringComparison.OrdinalIgnoreCase))
{
continue;
}
var deeper = FindExecutableRecursive(sub, currentDepth + 1, maxDepth);
if (deeper != null) return deeper;
} }
} }
catch { } catch { }
@@ -2652,6 +3132,12 @@ namespace GameLauncher.Services
return null; return null;
} }
private static bool IsExcludedExe(string filePath)
{
var fileName = Path.GetFileName(filePath);
return Regex.IsMatch(fileName, @"^(unins|setup|install|crash|handler|UnityCrash|設定|Config|updater|patch)", RegexOptions.IgnoreCase);
}
#endregion #endregion
} }
} }