Compare commits
7
Commits
dc03f5284a
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f50976a6c0 | ||
|
|
b0fdea2411 | ||
|
|
dd00c96e20 | ||
|
|
4c94cf814f | ||
|
|
2c02e10dd1 | ||
|
|
b65122537d | ||
|
|
ee9eeb3118 |
No files matched your search
@@ -14,6 +14,7 @@
|
||||
<PublishSingleFile>true</PublishSingleFile>
|
||||
<IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
|
||||
<DebugType>embedded</DebugType>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
+13
-1
@@ -399,6 +399,12 @@ namespace GameLauncher
|
||||
});
|
||||
},
|
||||
ct: ct);
|
||||
|
||||
this.Dispatcher.Invoke(() =>
|
||||
{
|
||||
this.UpdateStatusLabels();
|
||||
this._gamesView.Refresh();
|
||||
});
|
||||
}
|
||||
|
||||
// 2-2. 差分スキャン(新規フォルダの走査)
|
||||
@@ -447,6 +453,13 @@ namespace GameLauncher
|
||||
this.lblStatusEngine.Text = status;
|
||||
});
|
||||
},
|
||||
onLogMessage: log =>
|
||||
{
|
||||
this.Dispatcher.Invoke(() =>
|
||||
{
|
||||
this.AppendLog(log);
|
||||
});
|
||||
},
|
||||
ct: ct);
|
||||
|
||||
// キャッシュの最終同期(削除されたゲームのブックマークもここで除去する)
|
||||
@@ -2202,4 +2215,3 @@ namespace GameLauncher
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
+237
-52
@@ -54,6 +54,7 @@ namespace GameLauncher.Services
|
||||
public int TkoolEngineType { get; set; }
|
||||
public bool HasCustomApplyMod { get; set; }
|
||||
public bool ApplyMod { get; set; } = true;
|
||||
public bool IsModded { get; set; }
|
||||
public Dictionary<string, bool>? PluginSettings { get; set; }
|
||||
public bool IsAsar { get; set; }
|
||||
public bool IsAsarExtracted { get; set; }
|
||||
@@ -198,7 +199,7 @@ namespace GameLauncher.Services
|
||||
LastLaunched = entry.LastLaunched,
|
||||
FolderLastModified = entry.FolderLastModified,
|
||||
IsBookmarked = entry.IsBookmarked,
|
||||
IsModded = false,
|
||||
IsModded = entry.IsModded,
|
||||
IsAsar = entry.IsAsar,
|
||||
IsAsarExtracted = entry.IsAsarExtracted,
|
||||
AsarPath = entry.AsarPath,
|
||||
@@ -471,6 +472,7 @@ namespace GameLauncher.Services
|
||||
TkoolEngineType = (int)tg.EngineType,
|
||||
HasCustomApplyMod = tg.HasCustomApplyMod,
|
||||
ApplyMod = tg.ApplyMod,
|
||||
IsModded = tg.IsModded,
|
||||
PluginSettings = tg.PluginSettings.Count > 0 ? tg.PluginSettings : null,
|
||||
IsAsar = tg.IsAsar,
|
||||
IsAsarExtracted = tg.IsAsarExtracted,
|
||||
@@ -610,27 +612,71 @@ namespace GameLauncher.Services
|
||||
await Task.Run(() =>
|
||||
{
|
||||
var copyList = games.ToList();
|
||||
bool cacheNeedsSave = false;
|
||||
int cacheNeedsSave = 0;
|
||||
|
||||
int total = copyList.Count;
|
||||
int processed = 0;
|
||||
|
||||
foreach (var game in copyList)
|
||||
var po = new ParallelOptions
|
||||
{
|
||||
processed++;
|
||||
if (onProgress != null && (processed % 5 == 0 || processed == total))
|
||||
{
|
||||
onProgress(processed, total, $"実在検証中... ({processed}/{total})");
|
||||
}
|
||||
if (ct.IsCancellationRequested) break;
|
||||
CancellationToken = ct,
|
||||
MaxDegreeOfParallelism = Math.Clamp(Environment.ProcessorCount * 2, 4, 16)
|
||||
};
|
||||
|
||||
// 実在検証
|
||||
try
|
||||
{
|
||||
Parallel.ForEach(copyList, po, (game, loopState) =>
|
||||
{
|
||||
if (ct.IsCancellationRequested)
|
||||
{
|
||||
loopState.Stop();
|
||||
return;
|
||||
}
|
||||
|
||||
int current = Interlocked.Increment(ref processed);
|
||||
if (onProgress != null && (current % 10 == 0 || current == total))
|
||||
{
|
||||
onProgress(current, total, $"実在検証中... ({current}/{total})");
|
||||
}
|
||||
|
||||
// 実在検証および更新日時の取得
|
||||
DateTime currentLastWrite;
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(game.RootDirectory))
|
||||
{
|
||||
onGameRemoved(game);
|
||||
cacheNeedsSave = true;
|
||||
continue;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
return;
|
||||
}
|
||||
currentLastWrite = Directory.GetLastWriteTime(game.RootDirectory);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// キャッシュのフォルダ更新日時と完全一致している場合、内部構成(exe/plugins/アーカイブ/EVB等)は不変のため
|
||||
// 重いディスクI/O(EVBバイナリ解析、plugins.js読み取り、wolf走査等)を完全にスキップして超高速化
|
||||
bool isUnchanged = game.FolderLastModified.HasValue && game.FolderLastModified.Value == currentLastWrite;
|
||||
if (isUnchanged)
|
||||
{
|
||||
// 未ロードのアイコンのみ必要に応じてロード
|
||||
if (game.IconImage == null)
|
||||
{
|
||||
var icon = LoadIcon(game.ExecutablePath, game.RootDirectory);
|
||||
if (icon != null)
|
||||
{
|
||||
game.IconImage = icon;
|
||||
onGameUpdated(game);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// 更新があった、または初回検証の場合は更新日時を最新化
|
||||
game.FolderLastModified = currentLastWrite;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
|
||||
if (game is UnityGameItem ug)
|
||||
{
|
||||
@@ -640,13 +686,13 @@ namespace GameLauncher.Services
|
||||
if (!string.IsNullOrEmpty(recovered))
|
||||
{
|
||||
ug.ExecutablePath = recovered;
|
||||
cacheNeedsSave = true;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
onGameRemoved(ug);
|
||||
cacheNeedsSave = true;
|
||||
continue;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -656,7 +702,7 @@ namespace GameLauncher.Services
|
||||
try
|
||||
{
|
||||
ug.FolderLastModified = Directory.GetLastWriteTime(ug.RootDirectory);
|
||||
cacheNeedsSave = true;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
@@ -666,7 +712,7 @@ namespace GameLauncher.Services
|
||||
if (ug.HasSaveData != hasSave)
|
||||
{
|
||||
ug.HasSaveData = hasSave;
|
||||
cacheNeedsSave = true;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
}
|
||||
|
||||
// アイコン読み込み
|
||||
@@ -692,7 +738,7 @@ namespace GameLauncher.Services
|
||||
tg.RgssArchivePath = null;
|
||||
tg.PluginsJsPath = string.Empty;
|
||||
tg.PluginsDirPath = string.Empty;
|
||||
cacheNeedsSave = true;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
onGameUpdated(tg);
|
||||
}
|
||||
|
||||
@@ -704,7 +750,7 @@ namespace GameLauncher.Services
|
||||
FixRgssTitleFromIni(tg);
|
||||
if (tg.Title != oldTitle)
|
||||
{
|
||||
cacheNeedsSave = true;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
onGameUpdated(tg);
|
||||
}
|
||||
}
|
||||
@@ -727,7 +773,7 @@ namespace GameLauncher.Services
|
||||
{
|
||||
tg.EvbExtractedDirPath = currentEvbOutDir;
|
||||
}
|
||||
cacheNeedsSave = true;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
onGameUpdated(tg);
|
||||
}
|
||||
|
||||
@@ -740,13 +786,13 @@ namespace GameLauncher.Services
|
||||
if (!string.IsNullOrEmpty(recovered))
|
||||
{
|
||||
tg.ExecutablePath = recovered;
|
||||
cacheNeedsSave = true;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
onGameRemoved(tg);
|
||||
cacheNeedsSave = true;
|
||||
continue;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -763,7 +809,7 @@ namespace GameLauncher.Services
|
||||
tg.IsWolfExtracted = isWolfExtracted;
|
||||
tg.WolfProxyDll = isProxyDll;
|
||||
tg.IsModded = isProxyDll;
|
||||
cacheNeedsSave = true;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
}
|
||||
}
|
||||
else if (tg.IsSrpgStudio)
|
||||
@@ -774,13 +820,13 @@ namespace GameLauncher.Services
|
||||
if (!string.IsNullOrEmpty(recovered))
|
||||
{
|
||||
tg.ExecutablePath = recovered;
|
||||
cacheNeedsSave = true;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
onGameRemoved(tg);
|
||||
cacheNeedsSave = true;
|
||||
continue;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -797,7 +843,7 @@ namespace GameLauncher.Services
|
||||
tg.IsSrpgExtracted = isSrpgExtracted;
|
||||
tg.SrpgProxyDll = isProxyDll;
|
||||
tg.IsModded = isProxyDll || isModScript;
|
||||
cacheNeedsSave = true;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
}
|
||||
}
|
||||
else if (tg.IsAsar)
|
||||
@@ -808,8 +854,8 @@ namespace GameLauncher.Services
|
||||
if (!asarExists)
|
||||
{
|
||||
onGameRemoved(tg);
|
||||
cacheNeedsSave = true;
|
||||
continue;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
return;
|
||||
}
|
||||
|
||||
// 解凍状態の整合性確認
|
||||
@@ -819,13 +865,13 @@ namespace GameLauncher.Services
|
||||
if (tg.IsAsarExtracted && (!dirExtracted || !jsExists))
|
||||
{
|
||||
tg.IsAsarExtracted = false;
|
||||
cacheNeedsSave = true;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
onGameUpdated(tg);
|
||||
}
|
||||
else if (!tg.IsAsarExtracted && dirExtracted && jsExists)
|
||||
{
|
||||
tg.IsAsarExtracted = true;
|
||||
cacheNeedsSave = true;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
onGameUpdated(tg);
|
||||
}
|
||||
}
|
||||
@@ -837,14 +883,14 @@ namespace GameLauncher.Services
|
||||
if (!archiveExists && !scriptExists)
|
||||
{
|
||||
onGameRemoved(tg);
|
||||
cacheNeedsSave = true;
|
||||
continue;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
return;
|
||||
}
|
||||
|
||||
if (tg.IsRgssExtracted != scriptExists)
|
||||
{
|
||||
tg.IsRgssExtracted = scriptExists;
|
||||
cacheNeedsSave = true;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
onGameUpdated(tg);
|
||||
}
|
||||
}
|
||||
@@ -853,8 +899,8 @@ namespace GameLauncher.Services
|
||||
if (!File.Exists(tg.ExecutablePath) && !File.Exists(Path.Combine(tg.RootDirectory, "package.json")))
|
||||
{
|
||||
onGameRemoved(tg);
|
||||
cacheNeedsSave = true;
|
||||
continue;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
else if (tg.IsEvbPacked || tg.IsStandaloneExePackage || tg.IsOther)
|
||||
@@ -865,13 +911,13 @@ namespace GameLauncher.Services
|
||||
if (!string.IsNullOrEmpty(recovered))
|
||||
{
|
||||
tg.ExecutablePath = recovered;
|
||||
cacheNeedsSave = true;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
onGameRemoved(tg);
|
||||
cacheNeedsSave = true;
|
||||
continue;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -880,8 +926,8 @@ namespace GameLauncher.Services
|
||||
if (!File.Exists(tg.PluginsJsPath))
|
||||
{
|
||||
onGameRemoved(tg);
|
||||
cacheNeedsSave = true;
|
||||
continue;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -891,7 +937,7 @@ namespace GameLauncher.Services
|
||||
try
|
||||
{
|
||||
tg.FolderLastModified = Directory.GetLastWriteTime(tg.RootDirectory);
|
||||
cacheNeedsSave = true;
|
||||
Interlocked.Exchange(ref cacheNeedsSave, 1);
|
||||
onGameUpdated(tg);
|
||||
}
|
||||
catch { }
|
||||
@@ -933,9 +979,13 @@ namespace GameLauncher.Services
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
|
||||
if (cacheNeedsSave)
|
||||
if (cacheNeedsSave != 0)
|
||||
{
|
||||
this.SaveCache(copyList.Where(g => Directory.Exists(g.RootDirectory)));
|
||||
}
|
||||
@@ -944,12 +994,15 @@ namespace GameLauncher.Services
|
||||
|
||||
/// <summary>
|
||||
/// 指定されたフォルダ一覧からツクール・ティラノ・Unityゲームを非同期で走査・検出します。
|
||||
/// Everything IPC または NTFS MFT (USN Journal) 直接読み取りを利用して爆速インデックスを生成し、
|
||||
/// インメモリプレフィルタによりディスクI/Oを極限まで抑えて高速検出します。
|
||||
/// </summary>
|
||||
public async Task ScanDirectoriesAsync(
|
||||
IEnumerable<string> targetPaths,
|
||||
IProgress<GameItemBase> progress,
|
||||
HashSet<string> existingPaths,
|
||||
Action<string>? onStatusUpdated = null,
|
||||
Action<string>? onLogMessage = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
await Task.Run(() =>
|
||||
@@ -957,28 +1010,97 @@ namespace GameLauncher.Services
|
||||
var po = new ParallelOptions
|
||||
{
|
||||
CancellationToken = ct,
|
||||
MaxDegreeOfParallelism = Math.Clamp(Environment.ProcessorCount * 2, 4, 16)
|
||||
MaxDegreeOfParallelism = Math.Clamp(Environment.ProcessorCount * 4, 8, 32)
|
||||
};
|
||||
|
||||
// 1. Everything / NTFS MFT による超高速スナップショット取得
|
||||
FastDirectorySnapshot? snapshot = null;
|
||||
string engineName = string.Empty;
|
||||
|
||||
if (EverythingSearchService.IsEverythingRunning())
|
||||
{
|
||||
onStatusUpdated?.Invoke("Everything IPCによる高速スキャンを実行中...");
|
||||
try
|
||||
{
|
||||
snapshot = EverythingSearchService.TryScanTargetsFast(targetPaths);
|
||||
if (snapshot != null && (snapshot.TotalDirectoryCount > 0 || snapshot.TotalFileCount > 0))
|
||||
{
|
||||
engineName = "Everything (IPC高速走査)";
|
||||
}
|
||||
else
|
||||
{
|
||||
snapshot = null;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
snapshot = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (snapshot == null)
|
||||
{
|
||||
onStatusUpdated?.Invoke("NTFS MFT (USN Journal) による高速スキャンを実行中...");
|
||||
try
|
||||
{
|
||||
snapshot = NtfsMftScanService.TryScanTargetsFast(targetPaths);
|
||||
if (snapshot != null && (snapshot.TotalDirectoryCount > 0 || snapshot.TotalFileCount > 0))
|
||||
{
|
||||
engineName = "NTFS MFT直接読み取り (USN Journal高速走査)";
|
||||
}
|
||||
else
|
||||
{
|
||||
snapshot = null;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
snapshot = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (snapshot != null)
|
||||
{
|
||||
onStatusUpdated?.Invoke($"高速インデックス取得完了 ({engineName}): {snapshot.TotalDirectoryCount} フォルダ / {snapshot.TotalFileCount} ファイル");
|
||||
onLogMessage?.Invoke($"高速ファイルシステムインデックス [{engineName}] を取得しました({snapshot.TotalDirectoryCount} ディレクトリ, {snapshot.TotalFileCount} ファイル)。");
|
||||
}
|
||||
else
|
||||
{
|
||||
onStatusUpdated?.Invoke("通常ディレクトリ走査を実行中...");
|
||||
onLogMessage?.Invoke("標準の並列ディレクトリ走査を実行します。");
|
||||
}
|
||||
|
||||
// 全ターゲットディレクトリの直下サブディレクトリを一括集約(複数ドライブのI/Oを完全並列化)
|
||||
var allSubDirs = new List<string>();
|
||||
foreach (var targetPath in targetPaths)
|
||||
{
|
||||
if (ct.IsCancellationRequested) break;
|
||||
if (!Directory.Exists(targetPath)) continue;
|
||||
onStatusUpdated?.Invoke($"新規フォルダ走査中: {Path.GetFileName(targetPath.TrimEnd('\\', '/'))}...");
|
||||
|
||||
List<string> subDirs;
|
||||
try
|
||||
{
|
||||
subDirs = [.. Directory.EnumerateDirectories(targetPath)];
|
||||
if (snapshot != null && snapshot.DirectoryExists(targetPath))
|
||||
{
|
||||
allSubDirs.AddRange(snapshot.GetDirectories(targetPath));
|
||||
}
|
||||
else
|
||||
{
|
||||
allSubDirs.AddRange(Directory.EnumerateDirectories(targetPath));
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (allSubDirs.Count > 0)
|
||||
{
|
||||
onStatusUpdated?.Invoke($"新規フォルダ走査中 ({allSubDirs.Count} フォルダ)... (並列度 {po.MaxDegreeOfParallelism})");
|
||||
|
||||
try
|
||||
{
|
||||
Parallel.ForEach(subDirs, po, (dir, loopState) =>
|
||||
Parallel.ForEach(allSubDirs, po, (dir, loopState) =>
|
||||
{
|
||||
if (ct.IsCancellationRequested)
|
||||
{
|
||||
@@ -993,7 +1115,9 @@ namespace GameLauncher.Services
|
||||
}
|
||||
if (isExisting) return;
|
||||
|
||||
// ディレクトリ直下のゲームを検出
|
||||
// スナップショットが存在する場合はインメモリプレフィルタでゲーム候補か判定
|
||||
if (snapshot == null || HasPotentialGameContent(dir, snapshot))
|
||||
{
|
||||
var game = this.DetectGameInDirectory(dir);
|
||||
if (game != null)
|
||||
{
|
||||
@@ -1004,11 +1128,21 @@ namespace GameLauncher.Services
|
||||
progress.Report(game);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 1階層下も探索(アーカイブ解凍等でサブフォルダが入っているケース)
|
||||
try
|
||||
{
|
||||
var childDirs = Directory.EnumerateDirectories(dir);
|
||||
IEnumerable<string> childDirs;
|
||||
if (snapshot != null && snapshot.DirectoryExists(dir))
|
||||
{
|
||||
childDirs = snapshot.GetDirectories(dir);
|
||||
}
|
||||
else
|
||||
{
|
||||
childDirs = Directory.EnumerateDirectories(dir);
|
||||
}
|
||||
|
||||
foreach (var childDir in childDirs)
|
||||
{
|
||||
if (ct.IsCancellationRequested) break;
|
||||
@@ -1020,6 +1154,8 @@ namespace GameLauncher.Services
|
||||
}
|
||||
if (isChildExisting) continue;
|
||||
|
||||
if (snapshot == null || HasPotentialGameContent(childDir, snapshot))
|
||||
{
|
||||
var childGame = this.DetectGameInDirectory(childDir);
|
||||
if (childGame != null)
|
||||
{
|
||||
@@ -1031,17 +1167,66 @@ namespace GameLauncher.Services
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
});
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}, ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// スナップショットのメモリ情報を用いて、対象フォルダがゲームファイルを含む可能性があるか高速判定します。
|
||||
/// </summary>
|
||||
private static bool HasPotentialGameContent(string dirPath, FastDirectorySnapshot snapshot)
|
||||
{
|
||||
var normalized = dirPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
|
||||
|
||||
// 1. 直下のファイル群をメモリ上でチェック
|
||||
if (snapshot.FilesByDir.TryGetValue(normalized, out var files))
|
||||
{
|
||||
foreach (var f in files)
|
||||
{
|
||||
if (f.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) ||
|
||||
f.EndsWith(".wolf", StringComparison.OrdinalIgnoreCase) ||
|
||||
f.EndsWith(".rgss3a", StringComparison.OrdinalIgnoreCase) ||
|
||||
f.EndsWith(".rgss2a", StringComparison.OrdinalIgnoreCase) ||
|
||||
f.EndsWith(".rgssad", StringComparison.OrdinalIgnoreCase) ||
|
||||
f.EndsWith(".html", StringComparison.OrdinalIgnoreCase) ||
|
||||
f.EndsWith(".htm", StringComparison.OrdinalIgnoreCase) ||
|
||||
f.Equals("package.json", StringComparison.OrdinalIgnoreCase) ||
|
||||
f.Equals("Game.ini", StringComparison.OrdinalIgnoreCase) ||
|
||||
f.Equals("UnityPlayer.dll", StringComparison.OrdinalIgnoreCase) ||
|
||||
f.Equals("data.xp3", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 直下のサブディレクトリ名をメモリ上でチェック
|
||||
if (snapshot.SubDirsByDir.TryGetValue(normalized, out var subDirs))
|
||||
{
|
||||
foreach (var sub in subDirs)
|
||||
{
|
||||
var name = Path.GetFileName(sub);
|
||||
if (name.Equals("data", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.Equals("tyrano", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.Equals("www", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.EndsWith("_Data", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.Equals("BasicData", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.Equals("System", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
/// <summary>
|
||||
/// 1つのディレクトリ内にツクール・ティラノまたはUnityゲームが存在するか判定し、対応するアイテムを生成します。
|
||||
/// </summary>
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
Reference in new issue
Block a user