Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dd00c96e20 | ||
|
|
4c94cf814f | ||
|
|
2c02e10dd1 | ||
|
|
b65122537d | ||
|
|
ee9eeb3118 |
No files matched your search
@@ -14,6 +14,7 @@
|
|||||||
<PublishSingleFile>true</PublishSingleFile>
|
<PublishSingleFile>true</PublishSingleFile>
|
||||||
<IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
|
<IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
|
||||||
<DebugType>embedded</DebugType>
|
<DebugType>embedded</DebugType>
|
||||||
|
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
|
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
|
|||||||
@@ -447,6 +447,13 @@ namespace GameLauncher
|
|||||||
this.lblStatusEngine.Text = status;
|
this.lblStatusEngine.Text = status;
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
onLogMessage: log =>
|
||||||
|
{
|
||||||
|
this.Dispatcher.Invoke(() =>
|
||||||
|
{
|
||||||
|
this.AppendLog(log);
|
||||||
|
});
|
||||||
|
},
|
||||||
ct: ct);
|
ct: ct);
|
||||||
|
|
||||||
// キャッシュの最終同期(削除されたゲームのブックマークもここで除去する)
|
// キャッシュの最終同期(削除されたゲームのブックマークもここで除去する)
|
||||||
|
|||||||
@@ -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,170 @@
|
|||||||
|
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();
|
||||||
|
}
|
||||||
|
#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
|
||||||
|
}
|
||||||
|
}
|
||||||
+145
-14
@@ -944,12 +944,15 @@ namespace GameLauncher.Services
|
|||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 指定されたフォルダ一覧からツクール・ティラノ・Unityゲームを非同期で走査・検出します。
|
/// 指定されたフォルダ一覧からツクール・ティラノ・Unityゲームを非同期で走査・検出します。
|
||||||
|
/// Everything IPC または NTFS MFT (USN Journal) 直接読み取りを利用して爆速インデックスを生成し、
|
||||||
|
/// インメモリプレフィルタによりディスクI/Oを極限まで抑えて高速検出します。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public async Task ScanDirectoriesAsync(
|
public async Task ScanDirectoriesAsync(
|
||||||
IEnumerable<string> targetPaths,
|
IEnumerable<string> targetPaths,
|
||||||
IProgress<GameItemBase> progress,
|
IProgress<GameItemBase> progress,
|
||||||
HashSet<string> existingPaths,
|
HashSet<string> existingPaths,
|
||||||
Action<string>? onStatusUpdated = null,
|
Action<string>? onStatusUpdated = null,
|
||||||
|
Action<string>? onLogMessage = null,
|
||||||
CancellationToken ct = default)
|
CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
await Task.Run(() =>
|
await Task.Run(() =>
|
||||||
@@ -960,6 +963,63 @@ namespace GameLauncher.Services
|
|||||||
MaxDegreeOfParallelism = Math.Clamp(Environment.ProcessorCount * 2, 4, 16)
|
MaxDegreeOfParallelism = Math.Clamp(Environment.ProcessorCount * 2, 4, 16)
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 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("標準の並列ディレクトリ走査を実行します。");
|
||||||
|
}
|
||||||
|
|
||||||
foreach (var targetPath in targetPaths)
|
foreach (var targetPath in targetPaths)
|
||||||
{
|
{
|
||||||
if (ct.IsCancellationRequested) break;
|
if (ct.IsCancellationRequested) break;
|
||||||
@@ -969,7 +1029,14 @@ namespace GameLauncher.Services
|
|||||||
List<string> subDirs;
|
List<string> subDirs;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
subDirs = [.. Directory.EnumerateDirectories(targetPath)];
|
if (snapshot != null && snapshot.DirectoryExists(targetPath))
|
||||||
|
{
|
||||||
|
subDirs = [.. snapshot.GetDirectories(targetPath)];
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
subDirs = [.. Directory.EnumerateDirectories(targetPath)];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch
|
catch
|
||||||
{
|
{
|
||||||
@@ -993,22 +1060,34 @@ namespace GameLauncher.Services
|
|||||||
}
|
}
|
||||||
if (isExisting) return;
|
if (isExisting) return;
|
||||||
|
|
||||||
// ディレクトリ直下のゲームを検出
|
// スナップショットが存在する場合はインメモリプレフィルタでゲーム候補か判定
|
||||||
var game = this.DetectGameInDirectory(dir);
|
if (snapshot == null || HasPotentialGameContent(dir, snapshot))
|
||||||
if (game != null)
|
|
||||||
{
|
{
|
||||||
lock (existingPaths)
|
var game = this.DetectGameInDirectory(dir);
|
||||||
|
if (game != null)
|
||||||
{
|
{
|
||||||
existingPaths.Add(dir);
|
lock (existingPaths)
|
||||||
|
{
|
||||||
|
existingPaths.Add(dir);
|
||||||
|
}
|
||||||
|
progress.Report(game);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
progress.Report(game);
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1階層下も探索(アーカイブ解凍等でサブフォルダが入っているケース)
|
// 1階層下も探索(アーカイブ解凍等でサブフォルダが入っているケース)
|
||||||
try
|
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)
|
foreach (var childDir in childDirs)
|
||||||
{
|
{
|
||||||
if (ct.IsCancellationRequested) break;
|
if (ct.IsCancellationRequested) break;
|
||||||
@@ -1020,14 +1099,17 @@ namespace GameLauncher.Services
|
|||||||
}
|
}
|
||||||
if (isChildExisting) continue;
|
if (isChildExisting) continue;
|
||||||
|
|
||||||
var childGame = this.DetectGameInDirectory(childDir);
|
if (snapshot == null || HasPotentialGameContent(childDir, snapshot))
|
||||||
if (childGame != null)
|
|
||||||
{
|
{
|
||||||
lock (existingPaths)
|
var childGame = this.DetectGameInDirectory(childDir);
|
||||||
|
if (childGame != null)
|
||||||
{
|
{
|
||||||
existingPaths.Add(childDir);
|
lock (existingPaths)
|
||||||
|
{
|
||||||
|
existingPaths.Add(childDir);
|
||||||
|
}
|
||||||
|
progress.Report(childGame);
|
||||||
}
|
}
|
||||||
progress.Report(childGame);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1042,6 +1124,55 @@ namespace GameLauncher.Services
|
|||||||
}, ct);
|
}, 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>
|
/// <summary>
|
||||||
/// 1つのディレクトリ内にツクール・ティラノまたはUnityゲームが存在するか判定し、対応するアイテムを生成します。
|
/// 1つのディレクトリ内にツクール・ティラノまたはUnityゲームが存在するか判定し、対応するアイテムを生成します。
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -0,0 +1,334 @@
|
|||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Text;
|
||||||
|
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;
|
||||||
|
#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;
|
||||||
|
}
|
||||||
|
|
||||||
|
private class MftNode
|
||||||
|
{
|
||||||
|
public ulong Id;
|
||||||
|
public ulong ParentId;
|
||||||
|
public string Name = string.Empty;
|
||||||
|
public bool IsDirectory;
|
||||||
|
}
|
||||||
|
#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 snapshot = new FastDirectorySnapshot();
|
||||||
|
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;
|
||||||
|
|
||||||
|
bool anySuccess = false;
|
||||||
|
|
||||||
|
foreach (var kvp in targetsByDrive)
|
||||||
|
{
|
||||||
|
char driveLetter = kvp.Key;
|
||||||
|
var targetPaths = kvp.Value;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
bool ok = ScanVolumeMft(driveLetter, targetPaths, snapshot);
|
||||||
|
if (ok)
|
||||||
|
{
|
||||||
|
anySuccess = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
// ドライブスキャン失敗時はスキップ
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return anySuccess ? snapshot : null;
|
||||||
|
}
|
||||||
|
#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);
|
||||||
|
|
||||||
|
const int bufferSize = 1024 * 512; // 512KBバッファ
|
||||||
|
byte[] buffer = new byte[bufferSize];
|
||||||
|
GCHandle bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
|
||||||
|
IntPtr bufferPtr = bufferHandle.AddrOfPinnedObject();
|
||||||
|
|
||||||
|
// ID -> MftNode のマッピングを保持
|
||||||
|
var nodes = new Dictionary<ulong, MftNode>(500000);
|
||||||
|
|
||||||
|
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);
|
||||||
|
|
||||||
|
int offset = 8;
|
||||||
|
while (offset < bytesReturned)
|
||||||
|
{
|
||||||
|
IntPtr recordPtr = IntPtr.Add(bufferPtr, offset);
|
||||||
|
int recordLength = Marshal.ReadInt32(recordPtr);
|
||||||
|
if (recordLength <= 0) break;
|
||||||
|
|
||||||
|
ulong fileRef = (ulong)Marshal.ReadInt64(recordPtr, 8) & 0x0000FFFFFFFFFFFFUL;
|
||||||
|
ulong parentRef = (ulong)Marshal.ReadInt64(recordPtr, 16) & 0x0000FFFFFFFFFFFFUL;
|
||||||
|
uint fileAttributes = (uint)Marshal.ReadInt32(recordPtr, 52);
|
||||||
|
int fileNameLength = Marshal.ReadInt16(recordPtr, 56);
|
||||||
|
int fileNameOffset = Marshal.ReadInt16(recordPtr, 58);
|
||||||
|
|
||||||
|
if (fileNameLength > 0)
|
||||||
|
{
|
||||||
|
string fileName = Marshal.PtrToStringUni(IntPtr.Add(recordPtr, fileNameOffset), fileNameLength / 2);
|
||||||
|
bool isDir = (fileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
|
||||||
|
|
||||||
|
var node = new MftNode
|
||||||
|
{
|
||||||
|
Id = fileRef,
|
||||||
|
ParentId = parentRef,
|
||||||
|
Name = fileName,
|
||||||
|
IsDirectory = isDir
|
||||||
|
};
|
||||||
|
nodes[fileRef] = node;
|
||||||
|
}
|
||||||
|
|
||||||
|
offset += recordLength;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (bufferHandle.IsAllocated) bufferHandle.Free();
|
||||||
|
if (enumDataPtr != IntPtr.Zero) Marshal.FreeHGlobal(enumDataPtr);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nodes.Count == 0) return false;
|
||||||
|
|
||||||
|
// 3. 親IDから子IDのツリーを構築
|
||||||
|
var childrenByParent = new Dictionary<ulong, List<ulong>>(nodes.Count);
|
||||||
|
foreach (var node in nodes.Values)
|
||||||
|
{
|
||||||
|
if (!childrenByParent.TryGetValue(node.ParentId, out var list))
|
||||||
|
{
|
||||||
|
list = new List<ulong>();
|
||||||
|
childrenByParent[node.ParentId] = list;
|
||||||
|
}
|
||||||
|
list.Add(node.Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 各ターゲットパスのノードIDを特定し、その配下のエントリをスナップショットに格納
|
||||||
|
foreach (var targetPath in targetPaths)
|
||||||
|
{
|
||||||
|
var targetNodeId = FindNodeIdByPath(driveLetter, targetPath, nodes, childrenByParent);
|
||||||
|
if (targetNodeId.HasValue)
|
||||||
|
{
|
||||||
|
PopulateSnapshotFromNode(targetNodeId.Value, targetPath, nodes, childrenByParent, snapshot);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// パス文字列から対応するノードIDを検索します。
|
||||||
|
/// </summary>
|
||||||
|
private static ulong? FindNodeIdByPath(char driveLetter, string path, Dictionary<ulong, MftNode> nodes, Dictionary<ulong, List<ulong>> childrenByParent)
|
||||||
|
{
|
||||||
|
string rootStr = driveLetter + @":\";
|
||||||
|
if (path.Equals(rootStr.TrimEnd('\\'), StringComparison.OrdinalIgnoreCase) || path.Equals(rootStr, StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
// ドライブ直下のルートディレクトリ(通常IDは 5 / 0x0005)
|
||||||
|
return 5UL;
|
||||||
|
}
|
||||||
|
|
||||||
|
var parts = path.Substring(3).Split(new[] { '\\', '/' }, StringSplitOptions.RemoveEmptyEntries);
|
||||||
|
ulong currentParent = 5UL; // ルートID
|
||||||
|
|
||||||
|
foreach (var part in parts)
|
||||||
|
{
|
||||||
|
bool found = false;
|
||||||
|
if (childrenByParent.TryGetValue(currentParent, out var childIds))
|
||||||
|
{
|
||||||
|
foreach (var childId in childIds)
|
||||||
|
{
|
||||||
|
if (nodes.TryGetValue(childId, out var node) && node.IsDirectory && 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 PopulateSnapshotFromNode(
|
||||||
|
ulong parentNodeId,
|
||||||
|
string currentPath,
|
||||||
|
Dictionary<ulong, MftNode> nodes,
|
||||||
|
Dictionary<ulong, List<ulong>> childrenByParent,
|
||||||
|
FastDirectorySnapshot snapshot)
|
||||||
|
{
|
||||||
|
if (!childrenByParent.TryGetValue(parentNodeId, out var childIds)) return;
|
||||||
|
|
||||||
|
foreach (var childId in childIds)
|
||||||
|
{
|
||||||
|
if (!nodes.TryGetValue(childId, out var childNode)) continue;
|
||||||
|
|
||||||
|
if (childNode.IsDirectory)
|
||||||
|
{
|
||||||
|
string childPath = Path.Combine(currentPath, childNode.Name);
|
||||||
|
snapshot.AddDirectory(currentPath, childPath);
|
||||||
|
PopulateSnapshotFromNode(childId, childPath, nodes, childrenByParent, snapshot);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
snapshot.AddFile(currentPath, childNode.Name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#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