Document OS Utilities

This commit is contained in:
copecone committed 2026-10-15 16:17:13 +09:00
1 parent d2bd655118
commit a389283d33
3 files changed
+322 -12

No files matched your search

+160 -4
View File
@@ -10,12 +10,49 @@ using MelonLoader;
namespace ADOFAIRenderer.Util.OS;
/// <summary>
/// Native "select folder" dialog used to choose the render output directory.
/// <para>
/// - <b>Windows</b>: the shell's <c>IFileOpenDialog</c> (COM, <c>FOS_PICKFOLDERS</c>) on a dedicated STA thread owned by the
/// game window; when it cannot be created or shown, the legacy <c>SHBrowseForFolderW</c> dialog.
/// </para>
/// <para>- <b>macOS</b>: <c>osascript</c> running AppleScript <c>choose folder</c>.</para>
/// <para>
/// - <b>Linux</b>: <c>zenity --file-selection --directory</c>; when zenity does not return an existing directory (not installed,
/// cancelled or failed), <c>kdialog --getexistingdirectory</c>.
/// </para>
/// <para>
/// The dialog runs off the Unity main thread so the game keeps rendering frames while it is open. Only one dialog can be open
/// at a time. Failures are reported to the callback as null (same as cancel); exceptions are logged as warnings, except a
/// zenity start failure, which silently moves on to kdialog.
/// </para>
/// </summary>
[SuppressMessage("ReSharper", "InconsistentNaming")]
[SuppressMessage("ReSharper", "UnusedMember.Local")]
internal static class FolderDialogUtil
{
// 1 while a dialog is open, 0 otherwise. Set with Interlocked.CompareExchange in OpenFolderBrowser and reset by the
// dialog worker before it dispatches the result.
private static int _isDialogOpen;
/// <summary>
/// Opens the folder selection dialog asynchronously and returns immediately.
/// <para>
/// When a dialog is already open, logs a message and returns without opening another one; <paramref name="onSelected"/>
/// is not called in that case. Otherwise the dialog runs on a background thread (Windows: new STA thread
/// "FolderDialog-Win"; macOS/Linux: thread pool task) and <paramref name="onSelected"/> receives the result.
/// </para>
/// <para>
/// Callback thread: when the caller has a <see cref="SynchronizationContext"/> (the Unity main thread has one), the callback
/// is posted to it and runs on the caller's thread; otherwise it runs on the dialog thread. Exceptions thrown by the
/// callback are caught and logged.
/// </para>
/// <para>On platforms other than Windows, macOS and Linux the callback receives null.</para>
/// </summary>
/// <param name="initialDirectory">Folder shown first; ignored when empty or not an existing directory.</param>
/// <param name="onSelected">
/// Receives the absolute path of the selected existing directory, or null when the user cancelled or the dialog failed.
/// </param>
public static void OpenFolderBrowser(string initialDirectory, Action<string?> onSelected)
{
if (Interlocked.CompareExchange(ref _isDialogOpen, 1, 0) != 0)
@@ -24,12 +61,18 @@ internal static class FolderDialogUtil
return;
}
// Captured on the calling thread so the result can be posted back to it.
var syncContext = SynchronizationContext.Current;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// Resolved on the calling thread: GetActiveWindow only returns a window attached to the calling thread's
// message queue.
var ownerHandle = GetGameWindowHandle();
// Both dialogs run on a single-threaded apartment (STA) thread with OLE initialized; SHBrowseForFolder with
// BIF_NEWDIALOGSTYLE fails in a multithreaded apartment.
// Reference: https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/ns-shlobj_core-browseinfow
var thread = new Thread(() =>
{
string? selected = null;
@@ -45,6 +88,8 @@ internal static class FolderDialogUtil
}
finally
{
// OleInitialize returns S_OK or S_FALSE (already initialized) on success; each successful call is
// balanced by one OleUninitialize.
if (oleHr >= 0)
{
try
@@ -98,6 +143,13 @@ internal static class FolderDialogUtil
}
}
/// <summary>
/// Delivers the dialog result: posts <paramref name="onSelected"/> to <paramref name="syncContext"/> when it is not null,
/// otherwise invokes it on the current (dialog) thread. Callback exceptions are caught and logged.
/// </summary>
/// <param name="syncContext">Synchronization context of the thread that opened the dialog, or null.</param>
/// <param name="onSelected">Result callback.</param>
/// <param name="selected">Selected directory path, or null.</param>
private static void DispatchResult(SynchronizationContext? syncContext, Action<string?> onSelected, string? selected)
{
if (syncContext != null)
@@ -129,20 +181,32 @@ internal static class FolderDialogUtil
#region Windows Implementation
// COM class ID of the shell's common file dialog (FileOpenDialog) and the interface IDs of IFileOpenDialog and
// IShellItem (shobjidl_core.h).
private static readonly Guid CLSID_FileOpenDialog = new("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7");
private static readonly Guid IID_IFileOpenDialog = new("d57c7288-d4ad-4768-be02-9d969532d960");
private static readonly Guid IID_IShellItem = new("43826D1E-E718-42EE-BC55-A1E261C37BFE");
// HRESULT_FROM_WIN32(ERROR_CANCELLED) = 0x800704C7: IModalWindow::Show result when the user cancels the dialog.
// Reference: https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-imodalwindow-show
private const int ERROR_CANCELLED_HR = unchecked((int)0x800704C7);
// Active window attached to the calling thread's message queue, or NULL.
[DllImport("user32.dll")]
private static extern IntPtr GetActiveWindow();
// Foreground window of the desktop (any process), or NULL.
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
// Thread ID that created the window; the process ID is returned through lpdwProcessId.
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
/// <summary>
/// Finds the game window to own the dialog, in order: the calling thread's active window, the foreground window when it
/// belongs to this process, then <see cref="Process.MainWindowHandle"/>.
/// </summary>
/// <returns>Window handle, or <see cref="IntPtr.Zero"/> when none is found or a call fails (the dialog is then unowned).</returns>
private static IntPtr GetGameWindowHandle()
{
try
@@ -175,6 +239,13 @@ internal static class FolderDialogUtil
return IntPtr.Zero;
}
/// <summary>
/// Shows the IFileOpenDialog folder picker; when it throws (cannot be created, or Show fails with an error other than
/// cancel), logs a warning and shows the legacy SHBrowseForFolder dialog. Runs on the STA dialog thread.
/// </summary>
/// <param name="initialDirectory">Folder shown first, or empty.</param>
/// <param name="ownerHandle">Owner window, or <see cref="IntPtr.Zero"/>.</param>
/// <returns>Selected existing directory, or null on cancel.</returns>
private static string? OpenWindowsFolderBrowser(string initialDirectory, IntPtr ownerHandle)
{
try
@@ -188,16 +259,31 @@ internal static class FolderDialogUtil
}
}
/// <summary>
/// Shows the shell common file dialog in folder mode.
/// <para>
/// Options: <c>FOS_PICKFOLDERS</c> (choose folders), <c>FOS_FORCEFILESYSTEM</c> (file system items only) and
/// <c>FOS_PATHMUSTEXIST</c>. The initial folder is set with <c>SetFolder</c> and <c>SetDefaultFolder</c> when it exists.
/// When <c>Show</c> fails with an owner window (error other than cancel), it is retried once without an owner.
/// The result item is read as a file system path (<c>SIGDN_FILESYSPATH</c>); the returned string is freed with
/// <see cref="Marshal.FreeCoTaskMem"/> and the COM objects are released.
/// </para>
/// </summary>
/// <param name="initialDirectory">Folder shown first, or empty.</param>
/// <param name="ownerHandle">Owner window, or <see cref="IntPtr.Zero"/>.</param>
/// <returns>Selected existing directory; null on cancel or when the result has no file system path.</returns>
/// <exception cref="COMException">The dialog cannot be created, or Show fails with an error other than cancel.</exception>
private static string? OpenWindowsFolderBrowserModern(string initialDirectory, IntPtr ownerHandle)
{
// 1. Try native CoCreateInstance first (works on Mono and .NET without class registration)
// 1. Create the dialog with ole32 CoCreateInstance (in-process server), marshalled directly to IFileOpenDialog.
var clsid = CLSID_FileOpenDialog;
var iid = IID_IFileOpenDialog;
int createHr = CoCreateInstance(ref clsid, IntPtr.Zero, 1 /* CLSCTX_INPROC_SERVER */, ref iid, out var dialog);
if (createHr != 0)
{
// 2. Fallback to Activator via Type.GetTypeFromCLSID
// 2. On failure, create it through the runtime's COM interop (Type.GetTypeFromCLSID + Activator.CreateInstance).
// createHr keeps the CoCreateInstance error for the exception below.
var comType = Type.GetTypeFromCLSID(CLSID_FileOpenDialog);
if (comType != null)
{
@@ -223,6 +309,7 @@ internal static class FolderDialogUtil
var normalized = Path.GetFullPath(initialDirectory).TrimEnd('\\', '/');
if (Directory.Exists(normalized))
{
// The dialog takes folders as IShellItem; SHCreateItemFromParsingName creates one from the path.
var shellItemGuid = IID_IShellItem;
int itemHr = SHCreateItemFromParsingName(normalized, IntPtr.Zero, ref shellItemGuid, out var initialItem);
if (itemHr == 0)
@@ -293,8 +380,19 @@ internal static class FolderDialogUtil
}
}
/// <summary>
/// Shows the legacy shell folder browser (<c>SHBrowseForFolderW</c>) with the resizable dialog style, an edit box, and
/// file system folders only. The initial folder is selected from the dialog callback (<c>BFFM_INITIALIZED</c> ->
/// <c>BFFM_SETSELECTIONW</c> with the path string). Cancel and failure both return null. Native buffers and the returned
/// item ID list are freed before returning.
/// </summary>
/// <param name="initialDirectory">Folder selected first, or empty.</param>
/// <param name="ownerHandle">Owner window, or <see cref="IntPtr.Zero"/>.</param>
/// <returns>Selected existing directory, or null.</returns>
private static string? OpenWindowsFolderBrowserLegacy(string initialDirectory, IntPtr ownerHandle)
{
// Display name buffer: MAX_PATH (260) UTF-16 characters, the size SHBrowseForFolder assumes.
// Reference: https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/ns-shlobj_core-browseinfow
IntPtr pszDisplayName = Marshal.AllocHGlobal(260 * sizeof(char));
IntPtr initialDirPtr = IntPtr.Zero;
BrowseCallbackProc? callback = null;
@@ -318,6 +416,9 @@ internal static class FolderDialogUtil
var normalized = Path.GetFullPath(initialDirectory).TrimEnd('\\', '/');
if (Directory.Exists(normalized))
{
// lpData = bi.lParam = the UTF-16 path; wParam 1 (TRUE) tells BFFM_SETSELECTION it is a string.
// The delegate is kept alive until the dialog returns (GC.KeepAlive in finally).
// Reference: https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/bb762598(v=vs.85)
initialDirPtr = Marshal.StringToHGlobalUni(normalized);
callback = (hwnd, uMsg, _, lpData) =>
{
@@ -340,12 +441,12 @@ internal static class FolderDialogUtil
pidl = SHBrowseForFolderW(ref bi);
if (pidl == IntPtr.Zero && ownerHandle != IntPtr.Zero)
{
// If it returned null with ownerHandle, check if retry with IntPtr.Zero is appropriate
// But note: cancelling also returns Zero. We do not redundantly re-prompt if cancelled.
// SHBrowseForFolderW returns NULL both on cancel and on failure, so no retry without the owner is made.
}
if (pidl != IntPtr.Zero)
{
// SHGetPathFromIDListW writes up to MAX_PATH (260) characters.
var sb = new StringBuilder(260);
if (SHGetPathFromIDListW(pidl, sb))
{
@@ -376,6 +477,10 @@ internal static class FolderDialogUtil
#region COM & Win32 Interop Definitions
/// <summary>
/// <c>FILEOPENDIALOGOPTIONS</c> flags passed to <c>IFileDialog::SetOptions</c> (subset; values from shobjidl_core.h).
/// Reference: https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/ne-shobjidl_core-_fileopendialogoptions
/// </summary>
[Flags]
private enum FOS : uint
{
@@ -386,11 +491,20 @@ internal static class FolderDialogUtil
FOS_FILEMUSTEXIST = 0x00001000,
}
/// <summary>
/// Display name form requested from <c>IShellItem::GetDisplayName</c>; <c>SIGDN_FILESYSPATH</c> is the item's file system
/// path (the call fails for items without one).
/// Reference: https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/ne-shobjidl_core-sigdn
/// </summary>
private enum SIGDN : uint
{
SIGDN_FILESYSPATH = 0x80058000
}
/// <summary>
/// COM interop declaration of the shell <c>IShellItem</c> interface (vtable order of shobjidl_core.h). Only
/// <c>GetDisplayName</c> is called; it keeps its HRESULT return (<c>PreserveSig</c>).
/// </summary>
[ComImport]
[Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
@@ -404,6 +518,11 @@ internal static class FolderDialogUtil
void Compare(IShellItem psi, uint hint, out int piOrder);
}
/// <summary>
/// COM interop declaration of <c>IFileOpenDialog</c>: the methods of <c>IModalWindow</c> (<c>Show</c>), <c>IFileDialog</c>
/// and <c>IFileOpenDialog</c> in vtable order. <c>Show</c> keeps its HRESULT return (<c>PreserveSig</c>); the other methods
/// throw <see cref="COMException"/> on a failure HRESULT.
/// </summary>
[ComImport]
[Guid("d57c7288-d4ad-4768-be02-9d969532d960")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
@@ -438,12 +557,15 @@ internal static class FolderDialogUtil
void GetSelectedItems(out IntPtr ppsai);
}
// Initializes COM as a single-threaded apartment plus OLE on the calling thread; returns an HRESULT (S_OK / S_FALSE on success).
[DllImport("ole32.dll", ExactSpelling = true)]
private static extern int OleInitialize(IntPtr pvReserved);
// Balances one successful OleInitialize on the same thread.
[DllImport("ole32.dll", ExactSpelling = true)]
private static extern void OleUninitialize();
// Creates a COM object of class rclsid and returns interface riid; declared here with the IFileOpenDialog return type.
[DllImport("ole32.dll", ExactSpelling = true)]
private static extern int CoCreateInstance(
[In] ref Guid rclsid,
@@ -452,6 +574,7 @@ internal static class FolderDialogUtil
[In] ref Guid riid,
[Out, MarshalAs(UnmanagedType.Interface)] out IFileOpenDialog ppv);
// Creates an IShellItem from a parsing name (file system path); returns an HRESULT (0 = S_OK).
[DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = true)]
private static extern int SHCreateItemFromParsingName(
[MarshalAs(UnmanagedType.LPWStr)] string pszPath,
@@ -459,14 +582,22 @@ internal static class FolderDialogUtil
[In] ref Guid riid,
[Out, MarshalAs(UnmanagedType.Interface)] out IShellItem ppv);
// BROWSEINFO.ulFlags: file system directories only, resizable new-style dialog, edit box for typing a name.
// Reference: https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/ns-shlobj_core-browseinfow
private const uint BIF_RETURNONLYFSDIRS = 0x0001;
private const uint BIF_NEWDIALOGSTYLE = 0x0040;
private const uint BIF_EDITBOX = 0x0010;
// Browse dialog messages (shlobj_core.h): BFFM_INITIALIZED is sent to the callback when the dialog has finished
// initializing; BFFM_SETSELECTIONW (WM_USER + 103, Unicode) is sent to the dialog to select a folder. The reference
// describes the messages; the numeric values are the shlobj_core.h definitions.
// Reference:https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/bb762598(v=vs.85)
private const uint BFFM_INITIALIZED = 1;
private const uint BFFM_SETSELECTIONW = 0x0400 + 103;
// BFFCALLBACK: called by the browse dialog for dialog events; returns 0 except for BFFM_VALIDATEFAILED.
private delegate int BrowseCallbackProc(IntPtr hwnd, uint uMsg, IntPtr lParam, IntPtr lpData);
// Unicode BROWSEINFOW structure passed to SHBrowseForFolderW (field order and types of shlobj_core.h).
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct BROWSEINFO
{
@@ -480,13 +611,16 @@ internal static class FolderDialogUtil
public int iImage;
}
// Shows the modal browse dialog; returns the selected item's ID list (freed with CoTaskMemFree), or NULL on cancel or failure.
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr SHBrowseForFolderW(ref BROWSEINFO lpbi);
// Converts an item ID list to a file system path; false when the item is not part of the file system.
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SHGetPathFromIDListW(IntPtr pidl, StringBuilder pszPath);
// Sends a window message and waits for it to be processed (used from the browse dialog callback).
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
@@ -496,10 +630,21 @@ internal static class FolderDialogUtil
#region macOS Implementation
/// <summary>
/// Runs <c>osascript -e</c> with the AppleScript <c>POSIX path of (choose folder with prompt ... [default location ...])</c>
/// and blocks until the process exits. The initial directory is passed as a POSIX file in an AppleScript string literal
/// (backslashes and double quotes escaped). On cancel osascript prints nothing to standard output.
/// </summary>
/// <param name="initialDirectory">Folder shown first; used only when it is an existing directory.</param>
/// <returns>
/// The trimmed standard output when it is an existing directory; null on cancel, when the process cannot be started, or
/// on an exception (logged as a warning).
/// </returns>
private static string? OpenMacFolderBrowser(string initialDirectory)
{
try
{
// POSIX path of (...) converts the chosen folder alias to a slash-separated path.
string script;
if (!string.IsNullOrEmpty(initialDirectory) && Directory.Exists(initialDirectory))
{
@@ -541,6 +686,17 @@ internal static class FolderDialogUtil
#region Linux Implementation
/// <summary>
/// Runs <c>zenity --file-selection --directory --title=... [--filename=initialDirectory]</c> and blocks until it exits.
/// When zenity cannot be started, exits with a non-zero code (cancel or error) or prints a path that is not an existing
/// directory, runs <c>kdialog --getexistingdirectory [initialDirectory] --title ...</c> instead. Both commands print the
/// selected path to standard output.
/// </summary>
/// <param name="initialDirectory">Folder shown first; used only when it is an existing directory.</param>
/// <returns>
/// The selected existing directory; null when both dialogs return nothing, when kdialog cannot be started, or on an
/// exception (logged as a warning).
/// </returns>
private static string? OpenLinuxFolderBrowser(string initialDirectory)
{
try