diff --git a/src/Titano.Core.Windows/Devices/FormatDialog.cs b/src/Titano.Core.Windows/Devices/FormatDialog.cs new file mode 100644 index 00000000..7d91dec1 --- /dev/null +++ b/src/Titano.Core.Windows/Devices/FormatDialog.cs @@ -0,0 +1,57 @@ +using System.Runtime.InteropServices; + +namespace Titano.Core.Windows.Devices; + +/// Outcome of the Windows format dialog. +public enum FormatDialogResult +{ + /// The user formatted the volume. + Formatted, + + /// The user closed the dialog without formatting. + Cancelled, + + /// Windows reported that the drive cannot be formatted. + NotFormattable, + + /// The last format attempt failed. + Failed, +} + +/// +/// The Windows "Format" dialog (SHFormatDrive), the only way Titano formats a card (BRIEF §8.6): the user confirms +/// and starts the format in the OS dialog, quick format preselected. +/// +public static partial class FormatDialog +{ + private const uint SHFMT_ID_DEFAULT = 0xFFFF; + private const uint SHFMT_OPT_QUICK = 0x0; // no SHFMT_OPT_FULL: "Quick Format" stays checked + private const uint SHFMT_ERROR = 0xFFFFFFFF; + private const uint SHFMT_CANCEL = 0xFFFFFFFE; + private const uint SHFMT_NOFORMAT = 0xFFFFFFFD; + + /// Shows the modal dialog for . Call on the UI thread that owns . + /// No owner window (the dialog requires one). + /// Not a drive letter. + /// The drive holds the running Windows installation. + public static FormatDialogResult Show(nint ownerWindow, char driveLetter) + { + if (ownerWindow == 0) throw new ArgumentException("The format dialog needs an owner window.", nameof(ownerWindow)); + var letter = char.ToUpperInvariant(driveLetter); + if (letter is < 'A' or > 'Z') throw new ArgumentOutOfRangeException(nameof(driveLetter), driveLetter, "Expected a drive letter A–Z."); + var systemRoot = Path.GetPathRoot(Environment.SystemDirectory); + if (!string.IsNullOrEmpty(systemRoot) && char.ToUpperInvariant(systemRoot[0]) == letter) + throw new InvalidOperationException("The Windows system drive cannot be formatted."); + + return SHFormatDrive(ownerWindow, (uint)(letter - 'A'), SHFMT_ID_DEFAULT, SHFMT_OPT_QUICK) switch + { + SHFMT_CANCEL => FormatDialogResult.Cancelled, + SHFMT_NOFORMAT => FormatDialogResult.NotFormattable, + SHFMT_ERROR => FormatDialogResult.Failed, + _ => FormatDialogResult.Formatted, + }; + } + + [LibraryImport("shell32.dll")] + private static partial uint SHFormatDrive(nint ownerWindow, uint drive, uint formatId, uint options); +} diff --git a/src/Titano.Core.Windows/Devices/RemovableVolumeWatcher.cs b/src/Titano.Core.Windows/Devices/RemovableVolumeWatcher.cs new file mode 100644 index 00000000..d87091d0 --- /dev/null +++ b/src/Titano.Core.Windows/Devices/RemovableVolumeWatcher.cs @@ -0,0 +1,346 @@ +using System.ComponentModel; +using System.Runtime.InteropServices; +using Titano.Core.Diagnostics; + +namespace Titano.Core.Windows.Devices; + +/// Event data for a volume that appeared or disappeared. +public sealed class VolumeEventArgs(VolumeInfo volume) : EventArgs +{ + public VolumeInfo Volume { get; } = volume; +} + +/// +/// Detects cards and other import candidates (BRIEF §13): removable volumes, plus fixed volumes that hold a DCIM +/// folder. A hidden window on a dedicated message-loop thread receives WM_DEVICECHANGE +/// (DBT_DEVICEARRIVAL / DBT_DEVICEREMOVECOMPLETE with DEV_BROADCAST_VOLUME unit masks) and a 3-second +/// poll on the same thread catches anything the broadcast missed. Both paths diff against +/// the last snapshot, so each change is reported exactly once. Events are raised on the watcher thread. +/// +/// +/// The window is top-level but never shown, not message-only (HWND_MESSAGE): Windows broadcasts volume arrival +/// and removal only to top-level windows, and message-only windows receive no broadcasts. +/// +public sealed unsafe partial class RemovableVolumeWatcher : IDisposable +{ + private const string WindowClassName = "Titano.RemovableVolumeWatcher"; + private const uint PollIntervalMilliseconds = 3000; + private const nuint PollTimerId = 1; + + private const uint WM_DESTROY = 0x0002; + private const uint WM_CLOSE = 0x0010; + private const uint WM_TIMER = 0x0113; + private const uint WM_DEVICECHANGE = 0x0219; + private const nint DBT_DEVICEARRIVAL = 0x8000; + private const nint DBT_DEVICEREMOVECOMPLETE = 0x8004; + private const uint DBT_DEVTYP_VOLUME = 0x2; + private const uint WS_EX_TOOLWINDOW = 0x80; + private const int GWLP_USERDATA = -21; + private const int ERROR_CLASS_ALREADY_EXISTS = 1410; + + private static readonly Lock ClassGate = new(); + private static bool s_classRegistered; + + private readonly Dictionary _known = new(StringComparer.OrdinalIgnoreCase); + private readonly Lock _gate = new(); + private Thread? _thread; + private nint _window; + private GCHandle _self; + private int _disposed; + + /// A candidate volume was inserted or became ready. + public event EventHandler? VolumeArrived; + + /// A known volume was removed (or its media was swapped; the new one then arrives). + public event EventHandler? VolumeRemoved; + + /// Candidate volumes currently present (populated by , without events). + public IReadOnlyList Volumes + { + get + { + lock (_gate) return [.. _known.Values.OrderBy(v => v.RootPath, StringComparer.OrdinalIgnoreCase)]; + } + } + + /// True for volumes the import UI lists: removable media, or fixed media with a DCIM folder. + public static bool IsCandidate(VolumeInfo volume) => + volume.DriveType == VolumeDriveType.Removable || (volume.DriveType == VolumeDriveType.Fixed && volume.HasDcim); + + /// Takes the initial snapshot and starts watching; returns once the window exists. + /// The hidden window could not be created. + public void Start() + { + ObjectDisposedException.ThrowIf(_disposed != 0, this); + if (_thread is not null) throw new InvalidOperationException("The watcher is already running."); + + using var ready = new ManualResetEventSlim(); + Win32Exception? failure = null; + var thread = new Thread(() => + { + try + { + _window = CreateHiddenWindow(); + Rescan(raiseEvents: false); + } + catch (Win32Exception ex) + { + failure = ex; + } + finally + { + ready.Set(); + } + if (failure is null) RunMessageLoop(); + }) + { + IsBackground = true, + Name = "Titano volume watcher", + }; + thread.Start(); + ready.Wait(); + if (failure is not null) + { + thread.Join(); + throw failure; + } + _thread = thread; + } + + /// Stops watching and waits for the watcher thread (unless called from one of its event handlers). + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; + if (_window != 0) PostMessageW(_window, WM_CLOSE, 0, 0); + if (_thread is { } thread && thread != Thread.CurrentThread) thread.Join(); + } + + private nint CreateHiddenWindow() + { + var instance = GetModuleHandleW(null); + RegisterWindowClass(instance); + var window = CreateWindowExW(WS_EX_TOOLWINDOW, WindowClassName, WindowClassName, 0, 0, 0, 0, 0, 0, 0, instance, 0); + if (window == 0) throw new Win32Exception(Marshal.GetLastPInvokeError()); + _self = GCHandle.Alloc(this); + SetWindowLongPtrW(window, GWLP_USERDATA, GCHandle.ToIntPtr(_self)); + if (SetTimer(window, PollTimerId, PollIntervalMilliseconds, 0) == 0) + Log.Warning("devices", $"SetTimer failed (error {Marshal.GetLastPInvokeError()}); relying on WM_DEVICECHANGE only."); + return window; + } + + private static void RegisterWindowClass(nint instance) + { + lock (ClassGate) + { + if (s_classRegistered) return; + fixed (char* className = WindowClassName) + { + var windowClass = new WindowClass + { + Size = (uint)sizeof(WindowClass), + WindowProcedure = (nint)(delegate* unmanaged)&WindowProcedure, + Instance = instance, + ClassName = className, + }; + if (RegisterClassExW(&windowClass) == 0 && Marshal.GetLastPInvokeError() != ERROR_CLASS_ALREADY_EXISTS) + throw new Win32Exception(Marshal.GetLastPInvokeError()); + } + s_classRegistered = true; + } + } + + private void RunMessageLoop() + { + try + { + while (GetMessageW(out var message, 0, 0, 0) > 0) + { + TranslateMessage(&message); + DispatchMessageW(&message); + } + } + finally + { + // Normally a no-op (WM_QUIT follows WM_DESTROY); after a GetMessage failure it guarantees that no + // callback can reach the handle once it is freed. + DestroyWindow(_window); + _self.Free(); + } + } + + [UnmanagedCallersOnly] + private static nint WindowProcedure(nint window, uint message, nint wParam, nint lParam) + { + try + { + var handle = GetWindowLongPtrW(window, GWLP_USERDATA); + if (handle != 0 && GCHandle.FromIntPtr(handle).Target is RemovableVolumeWatcher watcher) + { + switch (message) + { + case WM_DEVICECHANGE when (wParam == DBT_DEVICEARRIVAL || wParam == DBT_DEVICEREMOVECOMPLETE) && lParam != 0: + var header = (DeviceBroadcastVolume*)lParam; + if (header->DeviceType == DBT_DEVTYP_VOLUME) watcher.Refresh(header->UnitMask); + return 1; + case WM_TIMER when (nuint)wParam == PollTimerId: + watcher.Rescan(raiseEvents: true); + return 0; + case WM_CLOSE: + KillTimer(window, PollTimerId); + DestroyWindow(window); + return 0; + case WM_DESTROY: + PostQuitMessage(0); + return 0; + } + } + } + catch (Exception ex) + { + // Nothing may unwind through a native callback. + Log.Error("devices", "Volume watcher message handling failed", ex); + } + return DefWindowProcW(window, message, wParam, lParam); + } + + /// Re-reads the drive letters named by a DEV_BROADCAST_VOLUME unit mask (bit 0 = A:). + private void Refresh(uint unitMask) + { + for (var bit = 0; bit < 26; bit++) + { + if ((unitMask & (1u << bit)) == 0) continue; + var root = $"{(char)('A' + bit)}:\\"; + Update(root, Read(root), raiseEvents: true); + } + } + + /// Full poll: every local drive letter plus every previously known root. + private void Rescan(bool raiseEvents) + { + var roots = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var drive in DriveInfo.GetDrives()) + { + if (drive.DriveType is DriveType.Fixed or DriveType.Removable) roots.Add(drive.Name); + } + lock (_gate) roots.UnionWith(_known.Keys); + foreach (var root in roots) Update(root, Read(root), raiseEvents); + } + + private static VolumeInfo? Read(string root) => VolumeInfo.TryRead(root) is { } volume && IsCandidate(volume) ? volume : null; + + private void Update(string root, VolumeInfo? current, bool raiseEvents) + { + VolumeInfo? previous; + lock (_gate) + { + _known.TryGetValue(root, out previous); + if (current is null) _known.Remove(root); + else _known[root] = current; + } + if (!raiseEvents) return; + var sameVolume = previous is not null && current is not null && previous.Identity == current.Identity; + if (previous is not null && !sameVolume) Raise(VolumeRemoved, previous); + if (current is not null && !sameVolume) Raise(VolumeArrived, current); + } + + private void Raise(EventHandler? handler, VolumeInfo volume) + { + try + { + handler?.Invoke(this, new VolumeEventArgs(volume)); + } + catch (Exception ex) + { + Log.Error("devices", $"A volume event handler failed for {volume.RootPath}", ex); + } + } + + /// DEV_BROADCAST_VOLUME (the header's first three fields, then the unit mask and flags). + [StructLayout(LayoutKind.Sequential)] + private struct DeviceBroadcastVolume + { + public uint Size; + public uint DeviceType; + public uint Reserved; + public uint UnitMask; + public ushort Flags; + } + + /// WNDCLASSEXW (80 bytes on x64). + [StructLayout(LayoutKind.Sequential)] + private struct WindowClass + { + public uint Size; + public uint Style; + public nint WindowProcedure; + public int ClassExtraBytes; + public int WindowExtraBytes; + public nint Instance; + public nint Icon; + public nint Cursor; + public nint Background; + public char* MenuName; + public char* ClassName; + public nint SmallIcon; + } + + /// MSG (48 bytes on x64). + [StructLayout(LayoutKind.Sequential)] + private struct Message + { + public nint Window; + public uint Id; + public nint WParam; + public nint LParam; + public uint Time; + public int X; + public int Y; + public uint Private; + } + + [LibraryImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf16)] + private static partial nint GetModuleHandleW(string? moduleName); + + [LibraryImport("user32.dll", SetLastError = true)] + private static partial ushort RegisterClassExW(WindowClass* windowClass); + + [LibraryImport("user32.dll", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + private static partial nint CreateWindowExW(uint exStyle, string className, string windowName, uint style, int x, int y, int width, int height, nint parent, nint menu, nint instance, nint parameter); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool DestroyWindow(nint window); + + [LibraryImport("user32.dll")] + private static partial nint DefWindowProcW(nint window, uint message, nint wParam, nint lParam); + + [LibraryImport("user32.dll")] + private static partial int GetMessageW(out Message message, nint window, uint filterMin, uint filterMax); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool TranslateMessage(Message* message); + + [LibraryImport("user32.dll")] + private static partial nint DispatchMessageW(Message* message); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool PostMessageW(nint window, uint message, nint wParam, nint lParam); + + [LibraryImport("user32.dll")] + private static partial void PostQuitMessage(int exitCode); + + [LibraryImport("user32.dll", SetLastError = true)] + private static partial nuint SetTimer(nint window, nuint id, uint elapse, nint timerProcedure); + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool KillTimer(nint window, nuint id); + + [LibraryImport("user32.dll")] + private static partial nint SetWindowLongPtrW(nint window, int index, nint value); + + [LibraryImport("user32.dll")] + private static partial nint GetWindowLongPtrW(nint window, int index); +} diff --git a/src/Titano.Core.Windows/Devices/VolumeEjector.cs b/src/Titano.Core.Windows/Devices/VolumeEjector.cs new file mode 100644 index 00000000..0dfb1d1b --- /dev/null +++ b/src/Titano.Core.Windows/Devices/VolumeEjector.cs @@ -0,0 +1,76 @@ +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +namespace Titano.Core.Windows.Devices; + +/// Outcome of . +public enum EjectResult +{ + /// The volume was dismounted and the media ejected; the card can be removed. + Ejected, + + /// Another process holds files open on the volume; nothing was changed. + InUse, + + /// The drive is not a removable-media drive (fixed, network, unknown or no such letter). + NotRemovable, + + /// Windows refused to open, dismount or eject the volume. + Failed, +} + +/// +/// Safe card removal (BRIEF §12.4): open \\.\X:, FSCTL_LOCK_VOLUME (retried while other handles close), +/// FSCTL_DISMOUNT_VOLUME, IOCTL_STORAGE_MEDIA_REMOVAL (allow), IOCTL_STORAGE_EJECT_MEDIA. Blocks for up to about +/// two seconds while retrying the lock; call it off the UI thread. +/// +public static unsafe class VolumeEjector +{ + private const uint DRIVE_REMOVABLE = 2; + private const uint DRIVE_CDROM = 5; + private const int LockAttempts = 5; + private static readonly TimeSpan LockRetryDelay = TimeSpan.FromMilliseconds(500); + + public static EjectResult Eject(char driveLetter) + { + var letter = char.ToUpperInvariant(driveLetter); + if (letter is < 'A' or > 'Z') throw new ArgumentOutOfRangeException(nameof(driveLetter), driveLetter, "Expected a drive letter A–Z."); + if (VolumeNative.GetDriveType($"{letter}:\\") is not (DRIVE_REMOVABLE or DRIVE_CDROM)) return EjectResult.NotRemovable; + + using var volume = VolumeNative.CreateFile( + $@"\\.\{letter}:", + VolumeNative.GENERIC_READ | VolumeNative.GENERIC_WRITE, + VolumeNative.FILE_SHARE_READ | VolumeNative.FILE_SHARE_WRITE, + 0, + VolumeNative.OPEN_EXISTING, + 0, + 0); + if (volume.IsInvalid) return EjectResult.Failed; + if (!Lock(volume)) return EjectResult.InUse; + if (!Control(volume, VolumeNative.FSCTL_DISMOUNT_VOLUME)) return EjectResult.Failed; + if (!AllowRemoval(volume)) return EjectResult.Failed; + // Closing the handle afterwards releases the lock. + return Control(volume, VolumeNative.IOCTL_STORAGE_EJECT_MEDIA) ? EjectResult.Ejected : EjectResult.Failed; + } + + private static bool Lock(SafeFileHandle volume) + { + for (var attempt = 1; attempt <= LockAttempts; attempt++) + { + if (Control(volume, VolumeNative.FSCTL_LOCK_VOLUME)) return true; + if (attempt < LockAttempts) Thread.Sleep(LockRetryDelay); + } + return false; + } + + /// Clears any media-removal lock; readers that do not implement the request count as unlocked. + private static bool AllowRemoval(SafeFileHandle volume) + { + byte preventMediaRemoval = 0; + if (VolumeNative.DeviceIoControl(volume, VolumeNative.IOCTL_STORAGE_MEDIA_REMOVAL, &preventMediaRemoval, sizeof(byte), null, 0, out _, 0)) return true; + return Marshal.GetLastPInvokeError() is VolumeNative.ERROR_INVALID_FUNCTION or VolumeNative.ERROR_NOT_SUPPORTED; + } + + private static bool Control(SafeFileHandle volume, uint code) => + VolumeNative.DeviceIoControl(volume, code, null, 0, null, 0, out _, 0); +} diff --git a/src/Titano.Core.Windows/Devices/VolumeInfo.cs b/src/Titano.Core.Windows/Devices/VolumeInfo.cs new file mode 100644 index 00000000..38b016dc --- /dev/null +++ b/src/Titano.Core.Windows/Devices/VolumeInfo.cs @@ -0,0 +1,92 @@ +using System.Globalization; + +namespace Titano.Core.Windows.Devices; + +/// GetDriveTypeW results. +public enum VolumeDriveType +{ + Unknown = 0, + NoRootDirectory = 1, + Removable = 2, + Fixed = 3, + Remote = 4, + CdRom = 5, + RamDisk = 6, +} + +/// A mounted volume with the facts card import needs (BRIEF §12.4, §13). +/// Root with trailing separator, e.g. E:\. +/// Volume label (may be empty). +/// File system name, e.g. exFAT. +/// Volume serial number assigned at format time. +/// Capacity in bytes. +/// Free bytes available to the current user. +/// Drive type reported by Windows. +/// A DCIM folder exists at the root (camera card). +public sealed record VolumeInfo( + string RootPath, + string Label, + string FileSystem, + uint SerialNumber, + long TotalBytes, + long FreeBytes, + VolumeDriveType DriveType, + bool HasDcim) +{ + private const int MaxPath = 261; + + public char DriveLetter => char.ToUpperInvariant(RootPath[0]); + + /// Card identity {serial:X8}-{label}-{capacity} (BRIEF §13); stable across readers and drive letters. + public string Identity => string.Create(CultureInfo.InvariantCulture, $"{SerialNumber:X8}-{Label}-{TotalBytes}"); + + /// Reads a volume; null when the root does not exist or holds no media (empty card reader). + public static unsafe VolumeInfo? TryRead(string rootPath) + { + var root = NormalizeRoot(rootPath); + var driveType = (VolumeDriveType)VolumeNative.GetDriveType(root); + if (driveType is VolumeDriveType.Unknown or VolumeDriveType.NoRootDirectory) return null; + + VolumeNative.SetThreadErrorMode(VolumeNative.SEM_FAILCRITICALERRORS, out var previousMode); + try + { + var label = stackalloc char[MaxPath]; + var fileSystem = stackalloc char[MaxPath]; + if (!VolumeNative.GetVolumeInformation(root, label, MaxPath, out var serial, out _, out _, fileSystem, MaxPath)) return null; + if (!VolumeNative.GetDiskFreeSpaceEx(root, out var free, out var total, out _)) return null; + return new VolumeInfo( + root, + new string(label), + new string(fileSystem), + serial, + (long)total, + (long)free, + driveType, + Directory.Exists(Path.Combine(root, "DCIM"))); + } + finally + { + VolumeNative.SetThreadErrorMode(previousMode, out _); + } + } + + /// Every ready fixed or removable volume, enumerated through (network and optical drives are skipped). + public static IReadOnlyList ListLocal() + { + var volumes = new List(); + foreach (var drive in DriveInfo.GetDrives()) + { + if (drive.DriveType is not (System.IO.DriveType.Fixed or System.IO.DriveType.Removable)) continue; + if (TryRead(drive.Name) is { } volume) volumes.Add(volume); + } + return volumes; + } + + /// "e:", "E:\" or "E:\DCIM" → "E:\". + internal static string NormalizeRoot(string path) + { + var root = Path.GetPathRoot(path); + if (string.IsNullOrEmpty(root)) throw new ArgumentException("The path has no root.", nameof(path)); + return root.EndsWith('\\') ? root.ToUpperInvariant() : root.ToUpperInvariant() + "\\"; + } +} diff --git a/src/Titano.Core.Windows/Devices/VolumeNative.cs b/src/Titano.Core.Windows/Devices/VolumeNative.cs new file mode 100644 index 00000000..58a261d2 --- /dev/null +++ b/src/Titano.Core.Windows/Devices/VolumeNative.cs @@ -0,0 +1,54 @@ +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +namespace Titano.Core.Windows.Devices; + +/// kernel32 volume and device-control entry points used by the Devices helpers. +internal static unsafe partial class VolumeNative +{ + public const uint GENERIC_READ = 0x80000000; + public const uint GENERIC_WRITE = 0x40000000; + public const uint FILE_SHARE_READ = 0x1; + public const uint FILE_SHARE_WRITE = 0x2; + public const uint OPEN_EXISTING = 3; + public const uint SEM_FAILCRITICALERRORS = 0x1; + + public const uint FSCTL_LOCK_VOLUME = 0x00090018; + public const uint FSCTL_DISMOUNT_VOLUME = 0x00090020; + public const uint IOCTL_STORAGE_MEDIA_REMOVAL = 0x002D4804; + public const uint IOCTL_STORAGE_EJECT_MEDIA = 0x002D4808; + + public const int ERROR_INVALID_FUNCTION = 1; + public const int ERROR_NOT_SUPPORTED = 50; + + [LibraryImport("kernel32.dll", EntryPoint = "GetDriveTypeW", StringMarshalling = StringMarshalling.Utf16)] + public static partial uint GetDriveType(string rootPath); + + [LibraryImport("kernel32.dll", EntryPoint = "GetVolumeInformationW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool GetVolumeInformation( + string rootPath, + char* volumeName, + uint volumeNameSize, + out uint serialNumber, + out uint maximumComponentLength, + out uint fileSystemFlags, + char* fileSystemName, + uint fileSystemNameSize); + + [LibraryImport("kernel32.dll", EntryPoint = "GetDiskFreeSpaceExW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool GetDiskFreeSpaceEx(string directory, out ulong freeBytesAvailable, out ulong totalBytes, out ulong totalFreeBytes); + + /// Per-thread error mode; SEM_FAILCRITICALERRORS stops "insert a disk" dialogs on empty card readers. + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool SetThreadErrorMode(uint newMode, out uint oldMode); + + [LibraryImport("kernel32.dll", EntryPoint = "CreateFileW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + public static partial SafeFileHandle CreateFile(string fileName, uint desiredAccess, uint shareMode, nint securityAttributes, uint creationDisposition, uint flagsAndAttributes, nint templateFile); + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool DeviceIoControl(SafeFileHandle device, uint controlCode, void* inBuffer, uint inBufferSize, void* outBuffer, uint outBufferSize, out uint bytesReturned, nint overlapped); +} diff --git a/tests/Titano.Core.Windows.Tests/Devices/VolumeTests.cs b/tests/Titano.Core.Windows.Tests/Devices/VolumeTests.cs new file mode 100644 index 00000000..039dd40c --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Devices/VolumeTests.cs @@ -0,0 +1,98 @@ +using System.Text.RegularExpressions; +using Titano.Core.Windows.Devices; +using Titano.Testing; + +namespace Titano.Core.Windows.Tests.Devices; + +public sealed class VolumeTests +{ + [Test] + [WindowsOnly] + public void ListingIncludesTheSystemDriveWithItsSerial() + { + var systemRoot = Path.GetPathRoot(Environment.SystemDirectory)!; + var volumes = VolumeInfo.ListLocal(); + var system = volumes.FirstOrDefault(v => string.Equals(v.RootPath, systemRoot, StringComparison.OrdinalIgnoreCase)); + if (system is null) Assert.Fail($"{systemRoot} missing from [{string.Join(", ", volumes.Select(v => v.RootPath))}]"); + Assert.NotEqual(0u, system!.SerialNumber); + Assert.Greater(system.TotalBytes, 0); + Assert.InRange(system.FreeBytes, 0, system.TotalBytes); + Assert.Equal(VolumeDriveType.Fixed, system.DriveType); + Assert.False(string.IsNullOrEmpty(system.FileSystem)); + Assert.True(Regex.IsMatch(system.Identity, "^[0-9A-F]{8}-.*-[0-9]+$"), system.Identity); + } + + [Test] + [WindowsOnly] + public void MissingDriveLetterReadsAsNull() + { + var used = DriveInfo.GetDrives().Select(d => char.ToUpperInvariant(d.Name[0])).ToHashSet(); + var free = Enumerable.Range('D', 23).Select(c => (char)c).Where(c => !used.Contains(c)).ToArray(); + if (free.Length == 0) TestContext.Skip("Every drive letter is in use."); + Assert.Null(VolumeInfo.TryRead($"{free[^1]}:\\")); + } + + [Test] + [WindowsOnly] + public void RootsAreNormalised() + { + Assert.Equal(@"E:\", VolumeInfo.NormalizeRoot("e:")); + Assert.Equal(@"E:\", VolumeInfo.NormalizeRoot(@"E:\")); + Assert.Equal(@"E:\", VolumeInfo.NormalizeRoot(@"e:\DCIM\100CANON")); + } + + [Test] + public void IdentityFollowsTheBriefFormat() + { + var card = new VolumeInfo(@"E:\", "EOS_DIGITAL", "exFAT", 0x3F2A9C11, 127_865_454_592, 1_000, VolumeDriveType.Removable, true); + Assert.Equal("3F2A9C11-EOS_DIGITAL-127865454592", card.Identity); + Assert.Equal('E', card.DriveLetter); + Assert.Equal("0000000A--1024", (card with { SerialNumber = 10, Label = "", TotalBytes = 1024 }).Identity); + } + + [Test] + public void CandidatesAreRemovableOrCameraVolumes() + { + var card = new VolumeInfo(@"E:\", "", "exFAT", 1, 1, 1, VolumeDriveType.Removable, false); + Assert.True(RemovableVolumeWatcher.IsCandidate(card)); + Assert.False(RemovableVolumeWatcher.IsCandidate(card with { DriveType = VolumeDriveType.Fixed })); + Assert.True(RemovableVolumeWatcher.IsCandidate(card with { DriveType = VolumeDriveType.Fixed, HasDcim = true })); + Assert.False(RemovableVolumeWatcher.IsCandidate(card with { DriveType = VolumeDriveType.Remote, HasDcim = true })); + } + + [Test] + [WindowsOnly] + [Timeout(30_000)] + public void WatcherStartsAndStops() + { + using var watcher = new RemovableVolumeWatcher(); + watcher.Start(); + Assert.True(watcher.Volumes.All(RemovableVolumeWatcher.IsCandidate)); + Assert.Throws(watcher.Start); + watcher.Dispose(); + Assert.Throws(watcher.Start); + } + + [Test] + [WindowsOnly] + public void EjectRefusesTheSystemDrive() + { + var letter = Path.GetPathRoot(Environment.SystemDirectory)![0]; + Assert.Equal(EjectResult.NotRemovable, VolumeEjector.Eject(letter)); + } + + [Test] + public void EjectRejectsNonLetters() => Assert.Throws(() => VolumeEjector.Eject('1')); + + [Test] + public void FormatDialogNeedsAnOwnerWindow() => Assert.Throws(() => FormatDialog.Show(0, 'E')); + + [Test] + [WindowsOnly] + public void FormatDialogRefusesTheSystemDrive() + { + var letter = Path.GetPathRoot(Environment.SystemDirectory)![0]; + // The guard runs before the dialog, so any non-null owner handle exercises it without showing UI. + Assert.Throws(() => FormatDialog.Show(1, letter)); + } +}