619 lines
27 KiB
C#
619 lines
27 KiB
C#
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" }
|
||
: new[] { 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.ToArray());
|
||
}
|
||
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;
|
||
}
|
||
}
|
||
}
|