Files
GameLauncher/Engines/Nwjs/NwjsDetector.cs
T

402 lines
15 KiB
C#

// Engines/Nwjs/NwjsDetector.cs — 汎用 NW.js ゲーム検出およびメタデータ解決ヘルパー
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Windows.Media;
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
{
#region □変数(Private)
private static readonly HashSet<string> ExcludedExeNames = new(StringComparer.OrdinalIgnoreCase)
{
"notification_helper.exe",
"crashpad_handler.exe",
"elevate.exe"
};
#endregion
#region □メソッド(Public)
/// <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 (NwjsDetector.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 (!NwjsDetector.IsNwjsGame(dirPath))
{
return null;
}
NwjsDetector.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 = NwjsDetector.ExtractHtmlTitle(htmlPath);
}
if (string.IsNullOrWhiteSpace(title) && !string.IsNullOrWhiteSpace(packageName))
{
title = packageName.Trim();
}
if (string.IsNullOrWhiteSpace(title))
{
title = folderName;
}
// 実行ファイルの探索
var exePath = NwjsDetector.FindNwjsExecutable(dirPath, title, packageName);
// アイコンの取得
ImageSource? icon = null;
if (iconLoader != null)
{
icon = iconLoader(exePath, dirPath);
}
string entryHtmlPath = NwjsDetector.ResolveEntryHtmlPath(dirPath, mainFile);
string entryDirPath = !string.IsNullOrEmpty(entryHtmlPath)
? (Path.GetDirectoryName(entryHtmlPath) ?? dirPath)
: dirPath;
bool isModded = !string.IsNullOrEmpty(entryHtmlPath) && NwjsModService.CheckIsModded(entryHtmlPath);
var saveFiles = NwjsSaveService.FindSaveFiles(dirPath, folderName);
string saveDirPath = saveFiles.Count > 0
? (Path.GetDirectoryName(saveFiles[0].FilePath) ?? dirPath)
: string.Empty;
return new TkoolGameItem
{
Title = title,
FolderName = folderName,
RootDirectory = dirPath,
ExecutablePath = exePath ?? string.Empty,
PluginsJsPath = entryHtmlPath,
PluginsDirPath = entryDirPath,
EngineType = TkoolEngineType.Nwjs,
IsModded = isModded,
ApplyMod = isModded,
HasSaveData = saveFiles.Count > 0,
// セーブデータ有無
IconImage = icon,
FolderLastModified = folderModified
};
}
catch
{
return null;
}
}
/// <summary>
/// NW.js ゲームのエントリ HTML ファイル(index.html 等)の絶対パスを解決します。
/// </summary>
/// <param name="dirPath">ゲームルートディレクトリ</param>
/// <param name="mainFromPackage">package.json の main フィールド(省略可)</param>
/// <returns>存在する HTML ファイルのフルパス。見つからない場合は空文字列</returns>
public static string ResolveEntryHtmlPath(string dirPath, string? mainFromPackage = null)
{
if (string.IsNullOrWhiteSpace(dirPath) || !Directory.Exists(dirPath))
{
return string.Empty;
}
if (string.IsNullOrWhiteSpace(mainFromPackage))
{
NwjsDetector.TryReadPackageJson(dirPath, out _, out _, out mainFromPackage, out _);
}
if (!string.IsNullOrWhiteSpace(mainFromPackage))
{
string candidate = Path.Combine(dirPath, mainFromPackage.TrimStart('/', '\\'));
string ext = Path.GetExtension(candidate);
if ((ext.Equals(".html", StringComparison.OrdinalIgnoreCase) || ext.Equals(".htm", StringComparison.OrdinalIgnoreCase)) &&
File.Exists(candidate))
{
return candidate;
}
}
string rootIndex = Path.Combine(dirPath, "index.html");
if (File.Exists(rootIndex))
{
return rootIndex;
}
string wwwIndex = Path.Combine(dirPath, "www", "index.html");
if (File.Exists(wwwIndex))
{
return wwwIndex;
}
return string.Empty;
}
/// <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 (NwjsDetector.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;
}
}
#endregion
#region □メソッド(Private)
/// <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;
}
#endregion
}
}