merge: Windows platform interop (WIC, devices, shell, DPAPI, DWM)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
42 files changed
+3460
No files matched your search
@@ -0,0 +1,116 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Windows.Wic;
|
||||
|
||||
namespace Titano.Core.Windows.Codecs;
|
||||
|
||||
/// <summary>How one image format decodes through WIC on this machine.</summary>
|
||||
/// <param name="Format">The format.</param>
|
||||
/// <param name="Decoder">The WIC decoder that handles its extensions, if any (it may only reach previews, e.g. the in-box DNG decoder).</param>
|
||||
/// <param name="IsNative">True when WIC delivers a full native decode (<see cref="DecodeTier.Native"/>).</param>
|
||||
/// <param name="MissingExtensions">Store extensions whose installation would make the format native.</param>
|
||||
public sealed record FormatSupport(ImageFileFormat Format, WicDecoderInfo? Decoder, bool IsNative, IReadOnlyList<StoreExtension> MissingExtensions);
|
||||
|
||||
/// <summary>
|
||||
/// Which WIC decoders exist on this machine and what they mean per <see cref="ImageFileFormat"/> (BRIEF §8.1):
|
||||
/// JPEG/PNG/TIFF/BMP/GIF/JPEG XR are built in; DNG and camera RAW count only through the Raw Image Extension
|
||||
/// (the in-box DNG decoder reads just the embedded preview); HEIF needs the HEIF decoder plus an HEVC decoder,
|
||||
/// AVIF an AVIF-capable decoder plus an AV1 decoder; WebP the WebP extension. Immutable snapshot; call
|
||||
/// <see cref="Detect"/> again (with refresh) after the user installs an extension.
|
||||
/// </summary>
|
||||
public sealed class CodecInventory
|
||||
{
|
||||
/// <summary>The Raw Image Extension reuses the CLSID of the older in-box RAW codec, so its package identifies it.</summary>
|
||||
internal const string RawImageExtensionPackageFamily = "Microsoft.RawImageExtension_8wekyb3d8bbwe";
|
||||
|
||||
private readonly Dictionary<ImageFileFormat, FormatSupport> _formats;
|
||||
|
||||
internal CodecInventory(IReadOnlyList<WicDecoderInfo> decoders, bool hasHevcDecoder, bool hasAv1Decoder)
|
||||
{
|
||||
Decoders = decoders;
|
||||
HasHevcDecoder = hasHevcDecoder;
|
||||
HasAv1Decoder = hasAv1Decoder;
|
||||
_formats = ImageFormatInfo.Known.ToDictionary(i => i.Format, Evaluate);
|
||||
Formats = [.. _formats.Values];
|
||||
MissingExtensions = StoreExtension.All.Where(e => Formats.Any(f => f.MissingExtensions.Contains(e))).ToArray();
|
||||
}
|
||||
|
||||
/// <summary>Installed WIC decoders, in WIC's enumeration order.</summary>
|
||||
public IReadOnlyList<WicDecoderInfo> Decoders { get; }
|
||||
|
||||
/// <summary>An HEVC decoder MFT is present (HEVC Video Extensions or a vendor hardware decoder).</summary>
|
||||
public bool HasHevcDecoder { get; }
|
||||
|
||||
/// <summary>An AV1 decoder MFT is present (AV1 Video Extension or a vendor hardware decoder).</summary>
|
||||
public bool HasAv1Decoder { get; }
|
||||
|
||||
/// <summary>One entry per known format, in <see cref="ImageFormatInfo.Known"/> order.</summary>
|
||||
public IReadOnlyList<FormatSupport> Formats { get; }
|
||||
|
||||
/// <summary>Distinct Store extensions that would unlock at least one format, for the "Install" notice.</summary>
|
||||
public IReadOnlyList<StoreExtension> MissingExtensions { get; }
|
||||
|
||||
/// <summary>Enumerates WIC decoders and probes the HEVC/AV1 decoders. Call from any thread.</summary>
|
||||
/// <param name="refresh">Make WIC re-read codec registrations (after an extension was installed).</param>
|
||||
public static CodecInventory Detect(bool refresh = false)
|
||||
{
|
||||
var rawExtensionInstalled = PackageProbe.IsInstalled(RawImageExtensionPackageFamily);
|
||||
var decoders = WicComponents.EnumerateDecoders(refresh)
|
||||
.Select(d => d with { Extension = Classify(d, rawExtensionInstalled) })
|
||||
.ToArray();
|
||||
return new CodecInventory(decoders, VideoDecoderProbe.HasDecoder(VideoDecoderProbe.Hevc), VideoDecoderProbe.HasDecoder(VideoDecoderProbe.Av1));
|
||||
}
|
||||
|
||||
public FormatSupport For(ImageFileFormat format) =>
|
||||
_formats.TryGetValue(format, out var support) ? support : new FormatSupport(format, null, false, []);
|
||||
|
||||
public bool IsNative(ImageFileFormat format) => For(format).IsNative;
|
||||
|
||||
/// <summary>Which Microsoft Store extension installed a decoder, judged by its CLSID (and vendor for AVIF).</summary>
|
||||
internal static StoreExtensionKind? Classify(WicDecoderInfo decoder, bool rawExtensionInstalled)
|
||||
{
|
||||
if (decoder.Clsid == WicGuids.RawDecoder) return rawExtensionInstalled ? StoreExtensionKind.RawImage : null;
|
||||
if (decoder.Clsid == WicGuids.HeifDecoder) return StoreExtensionKind.HeifImage;
|
||||
if (decoder.Clsid == WicGuids.WebpDecoder) return StoreExtensionKind.WebpImage;
|
||||
var microsoft = decoder.Vendor == WicGuids.VendorMicrosoft || decoder.Vendor == WicGuids.VendorMicrosoftBuiltIn;
|
||||
return microsoft && decoder.Handles("avif") ? StoreExtensionKind.Av1Video : null;
|
||||
}
|
||||
|
||||
private FormatSupport Evaluate(ImageFormatInfo info)
|
||||
{
|
||||
var handler = Decoders.FirstOrDefault(d => info.Extensions.Any(d.Handles));
|
||||
switch (info.Format)
|
||||
{
|
||||
case ImageFileFormat.Heif:
|
||||
return new(info.Format, handler, handler is not null && HasHevcDecoder,
|
||||
Missing((handler is null, StoreExtensionKind.HeifImage), (!HasHevcDecoder, StoreExtensionKind.HevcVideo)));
|
||||
|
||||
case ImageFileFormat.Avif:
|
||||
// AVIF is HEIF with AV1 payloads: the HEIF decoder reads it when no dedicated AVIF decoder is registered.
|
||||
var avif = handler ?? Decoders.FirstOrDefault(d => d.Extension == StoreExtensionKind.HeifImage);
|
||||
return new(info.Format, avif, avif is not null && HasAv1Decoder,
|
||||
Missing((avif is null, StoreExtensionKind.HeifImage), (!HasAv1Decoder, StoreExtensionKind.Av1Video)));
|
||||
|
||||
case ImageFileFormat.WebP:
|
||||
return new(info.Format, handler, handler is not null, Missing((handler is null, StoreExtensionKind.WebpImage)));
|
||||
}
|
||||
|
||||
if (info.IsRaw)
|
||||
{
|
||||
var raw = Decoders.FirstOrDefault(d => d.Extension == StoreExtensionKind.RawImage && info.Extensions.Any(d.Handles));
|
||||
var extensionInstalled = Decoders.Any(d => d.Extension == StoreExtensionKind.RawImage);
|
||||
return new(info.Format, raw ?? handler, raw is not null, Missing((!extensionInstalled, StoreExtensionKind.RawImage)));
|
||||
}
|
||||
|
||||
return new(info.Format, handler, handler is not null, []);
|
||||
}
|
||||
|
||||
private static StoreExtension[] Missing(params ReadOnlySpan<(bool IsMissing, StoreExtensionKind Kind)> requirements)
|
||||
{
|
||||
var missing = new List<StoreExtension>(requirements.Length);
|
||||
foreach (var (isMissing, kind) in requirements)
|
||||
{
|
||||
if (isMissing) missing.Add(StoreExtension.Get(kind));
|
||||
}
|
||||
return [.. missing];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Titano.Core.Windows.Codecs;
|
||||
|
||||
/// <summary>Checks whether a packaged (Store) app is registered for the current user.</summary>
|
||||
internal static partial class PackageProbe
|
||||
{
|
||||
private const int ERROR_SUCCESS = 0;
|
||||
private const int ERROR_INSUFFICIENT_BUFFER = 122;
|
||||
|
||||
/// <summary>True when at least one package of <paramref name="packageFamilyName"/> is installed for this user.</summary>
|
||||
public static bool IsInstalled(string packageFamilyName)
|
||||
{
|
||||
uint count = 0, bufferLength = 0;
|
||||
// With empty buffers the call reports how many packages exist (ERROR_INSUFFICIENT_BUFFER when any do).
|
||||
var result = GetPackagesByPackageFamily(packageFamilyName, ref count, 0, ref bufferLength, 0);
|
||||
return (result is ERROR_SUCCESS or ERROR_INSUFFICIENT_BUFFER) && count > 0;
|
||||
}
|
||||
|
||||
[LibraryImport("kernel32.dll", StringMarshalling = StringMarshalling.Utf16)]
|
||||
private static partial int GetPackagesByPackageFamily(string packageFamilyName, ref uint count, nint packageFullNames, ref uint bufferLength, nint buffer);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using Titano.Core.Windows.Shell;
|
||||
|
||||
namespace Titano.Core.Windows.Codecs;
|
||||
|
||||
/// <summary>Free or paid Microsoft Store codec extensions that widen what WIC can decode (BRIEF §8.1).</summary>
|
||||
public enum StoreExtensionKind
|
||||
{
|
||||
RawImage,
|
||||
HeifImage,
|
||||
HevcVideo,
|
||||
Av1Video,
|
||||
WebpImage,
|
||||
}
|
||||
|
||||
/// <summary>A Microsoft Store codec extension: product id and the URIs that open its Store page.</summary>
|
||||
public sealed record StoreExtension(StoreExtensionKind Kind, string ProductName, string ProductId)
|
||||
{
|
||||
/// <summary>Catalogue in the order the UI lists missing extensions.</summary>
|
||||
public static IReadOnlyList<StoreExtension> All { get; } =
|
||||
[
|
||||
new(StoreExtensionKind.RawImage, "Raw Image Extension", "9NCTDW2W1BH8"),
|
||||
new(StoreExtensionKind.HeifImage, "HEIF Image Extensions", "9PMMSR1CGPWG"),
|
||||
new(StoreExtensionKind.HevcVideo, "HEVC Video Extensions", "9NMZLZ57R3T7"),
|
||||
new(StoreExtensionKind.Av1Video, "AV1 Video Extension", "9MVZQVXJBQ9V"),
|
||||
new(StoreExtensionKind.WebpImage, "WebP Image Extensions", "9PG2DK419DRG"),
|
||||
];
|
||||
|
||||
/// <summary>Store app deep link (<c>ms-windows-store://pdp/?ProductId=…</c>).</summary>
|
||||
public Uri StoreUri => new($"ms-windows-store://pdp/?ProductId={ProductId}");
|
||||
|
||||
/// <summary>Web page of the same product, for systems without the Store app.</summary>
|
||||
public Uri WebUri => new($"https://apps.microsoft.com/detail/{ProductId.ToLowerInvariant()}");
|
||||
|
||||
public static StoreExtension Get(StoreExtensionKind kind) => All.First(e => e.Kind == kind);
|
||||
|
||||
/// <summary>Opens the Store page through the shell; false when the shell could not open it.</summary>
|
||||
public bool OpenInStore() => ShellLauncher.OpenUrl(StoreUri.AbsoluteUri);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Titano.Core.Windows.Codecs;
|
||||
|
||||
/// <summary>
|
||||
/// Detects HEVC and AV1 decoders with <c>MFTEnumEx</c>, the check Microsoft documents for the codecs that HEIC and
|
||||
/// AVIF decoding through WIC depend on (HEVC / AV1 Video Extensions or a vendor hardware decoder).
|
||||
/// </summary>
|
||||
internal static unsafe partial class VideoDecoderProbe
|
||||
{
|
||||
/// <summary>MFVideoFormat_HEVC (FOURCC 'HEVC').</summary>
|
||||
public static readonly Guid Hevc = new("43564548-0000-0010-8000-00aa00389b71");
|
||||
|
||||
/// <summary>MFVideoFormat_AV1 (FOURCC 'AV01').</summary>
|
||||
public static readonly Guid Av1 = new("31305641-0000-0010-8000-00aa00389b71");
|
||||
|
||||
private static readonly Guid VideoDecoderCategory = new("d6c02d4b-6833-45b4-971a-05a4b04bab91");
|
||||
private static readonly Guid MediaTypeVideo = new("73646976-0000-0010-8000-00aa00389b71");
|
||||
|
||||
private const uint MF_VERSION = 0x00020070;
|
||||
private const uint MFSTARTUP_LITE = 0x1;
|
||||
private const uint MFT_ENUM_FLAG_SYNCMFT = 0x1, MFT_ENUM_FLAG_ASYNCMFT = 0x2, MFT_ENUM_FLAG_HARDWARE = 0x4, MFT_ENUM_FLAG_SORTANDFILTER = 0x40;
|
||||
|
||||
/// <summary>True when at least one decoder MFT accepts the video <paramref name="subtype"/>.</summary>
|
||||
public static bool HasDecoder(Guid subtype)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (MFStartup(MF_VERSION, MFSTARTUP_LITE) < 0) return false;
|
||||
try
|
||||
{
|
||||
var input = new MftRegisterTypeInfo { MajorType = MediaTypeVideo, Subtype = subtype };
|
||||
const uint flags = MFT_ENUM_FLAG_SYNCMFT | MFT_ENUM_FLAG_ASYNCMFT | MFT_ENUM_FLAG_HARDWARE | MFT_ENUM_FLAG_SORTANDFILTER;
|
||||
if (MFTEnumEx(VideoDecoderCategory, flags, &input, null, out var activates, out var count) < 0) return false;
|
||||
for (var i = 0; i < count; i++) Marshal.Release(((nint*)activates)[i]);
|
||||
Marshal.FreeCoTaskMem(activates);
|
||||
return count > 0;
|
||||
}
|
||||
finally
|
||||
{
|
||||
MFShutdown();
|
||||
}
|
||||
}
|
||||
catch (DllNotFoundException)
|
||||
{
|
||||
// Windows "N" editions ship without Media Foundation unless the Media Feature Pack is installed.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct MftRegisterTypeInfo
|
||||
{
|
||||
public Guid MajorType;
|
||||
public Guid Subtype;
|
||||
}
|
||||
|
||||
[LibraryImport("mfplat.dll")]
|
||||
private static partial int MFStartup(uint version, uint flags);
|
||||
|
||||
[LibraryImport("mfplat.dll")]
|
||||
private static partial int MFShutdown();
|
||||
|
||||
[LibraryImport("mfplat.dll")]
|
||||
private static partial int MFTEnumEx(Guid category, uint flags, MftRegisterTypeInfo* inputType, MftRegisterTypeInfo* outputType, out nint activates, out uint count);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
namespace Titano.Core.Windows.Codecs;
|
||||
|
||||
/// <summary>One installed WIC decoder as registered on this machine.</summary>
|
||||
/// <param name="FriendlyName">Registered display name, e.g. "JPEG Decoder".</param>
|
||||
/// <param name="Clsid">Decoder class id.</param>
|
||||
/// <param name="ContainerFormat">WIC container format GUID.</param>
|
||||
/// <param name="Vendor">Vendor GUID (Microsoft built-in, Microsoft, or a third party).</param>
|
||||
/// <param name="Version">Registered version string.</param>
|
||||
/// <param name="FileExtensions">Lower-case extensions without the dot.</param>
|
||||
/// <param name="Extension">The Microsoft Store extension that installed it, if any.</param>
|
||||
public sealed record WicDecoderInfo(
|
||||
string FriendlyName,
|
||||
Guid Clsid,
|
||||
Guid ContainerFormat,
|
||||
Guid Vendor,
|
||||
string Version,
|
||||
IReadOnlyList<string> FileExtensions,
|
||||
StoreExtensionKind? Extension)
|
||||
{
|
||||
/// <summary>True when the decoder registers <paramref name="extension"/> (with or without the dot).</summary>
|
||||
public bool Handles(string extension)
|
||||
{
|
||||
var bare = extension.TrimStart('.');
|
||||
foreach (var e in FileExtensions)
|
||||
{
|
||||
if (string.Equals(e, bare, StringComparison.OrdinalIgnoreCase)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Parses WIC's comma-separated extension list (".jpg,.jpeg") into bare lower-case names.</summary>
|
||||
internal static IReadOnlyList<string> ParseExtensions(string list) =>
|
||||
list.Split([',', ';', ' '], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
.Select(e => e.TrimStart('.').ToLowerInvariant())
|
||||
.Where(e => e.Length > 0)
|
||||
.Distinct()
|
||||
.ToArray();
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Titano.Core.Windows.Devices;
|
||||
|
||||
/// <summary>Outcome of the Windows format dialog.</summary>
|
||||
public enum FormatDialogResult
|
||||
{
|
||||
/// <summary>The user formatted the volume.</summary>
|
||||
Formatted,
|
||||
|
||||
/// <summary>The user closed the dialog without formatting.</summary>
|
||||
Cancelled,
|
||||
|
||||
/// <summary>Windows reported that the drive cannot be formatted.</summary>
|
||||
NotFormattable,
|
||||
|
||||
/// <summary>The last format attempt failed.</summary>
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>Shows the modal dialog for <paramref name="driveLetter"/>. Call on the UI thread that owns <paramref name="ownerWindow"/>.</summary>
|
||||
/// <exception cref="ArgumentException">No owner window (the dialog requires one).</exception>
|
||||
/// <exception cref="ArgumentOutOfRangeException">Not a drive letter.</exception>
|
||||
/// <exception cref="InvalidOperationException">The drive holds the running Windows installation.</exception>
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using Titano.Core.Diagnostics;
|
||||
|
||||
namespace Titano.Core.Windows.Devices;
|
||||
|
||||
/// <summary>Event data for a volume that appeared or disappeared.</summary>
|
||||
public sealed class VolumeEventArgs(VolumeInfo volume) : EventArgs
|
||||
{
|
||||
public VolumeInfo Volume { get; } = volume;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <see cref="DriveInfo"/> 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.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
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<string, VolumeInfo> _known = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Lock _gate = new();
|
||||
private Thread? _thread;
|
||||
private nint _window;
|
||||
private GCHandle _self;
|
||||
private int _disposed;
|
||||
|
||||
/// <summary>A candidate volume was inserted or became ready.</summary>
|
||||
public event EventHandler<VolumeEventArgs>? VolumeArrived;
|
||||
|
||||
/// <summary>A known volume was removed (or its media was swapped; the new one then arrives).</summary>
|
||||
public event EventHandler<VolumeEventArgs>? VolumeRemoved;
|
||||
|
||||
/// <summary>Candidate volumes currently present (populated by <see cref="Start"/>, without events).</summary>
|
||||
public IReadOnlyList<VolumeInfo> Volumes
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return [.. _known.Values.OrderBy(v => v.RootPath, StringComparer.OrdinalIgnoreCase)];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True for volumes the import UI lists: removable media, or fixed media with a DCIM folder.</summary>
|
||||
public static bool IsCandidate(VolumeInfo volume) =>
|
||||
volume.DriveType == VolumeDriveType.Removable || (volume.DriveType == VolumeDriveType.Fixed && volume.HasDcim);
|
||||
|
||||
/// <summary>Takes the initial snapshot and starts watching; returns once the window exists.</summary>
|
||||
/// <exception cref="Win32Exception">The hidden window could not be created.</exception>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Stops watching and waits for the watcher thread (unless called from one of its event handlers).</summary>
|
||||
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<nint, uint, nint, nint, nint>)&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);
|
||||
}
|
||||
|
||||
/// <summary>Re-reads the drive letters named by a DEV_BROADCAST_VOLUME unit mask (bit 0 = A:).</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Full poll: every local drive letter plus every previously known root.</summary>
|
||||
private void Rescan(bool raiseEvents)
|
||||
{
|
||||
var roots = new HashSet<string>(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<VolumeEventArgs>? 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>DEV_BROADCAST_VOLUME (the header's first three fields, then the unit mask and flags).</summary>
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct DeviceBroadcastVolume
|
||||
{
|
||||
public uint Size;
|
||||
public uint DeviceType;
|
||||
public uint Reserved;
|
||||
public uint UnitMask;
|
||||
public ushort Flags;
|
||||
}
|
||||
|
||||
/// <summary>WNDCLASSEXW (80 bytes on x64).</summary>
|
||||
[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;
|
||||
}
|
||||
|
||||
/// <summary>MSG (48 bytes on x64).</summary>
|
||||
[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);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
namespace Titano.Core.Windows.Devices;
|
||||
|
||||
/// <summary>Outcome of <see cref="VolumeEjector.Eject"/>.</summary>
|
||||
public enum EjectResult
|
||||
{
|
||||
/// <summary>The volume was dismounted and the media ejected; the card can be removed.</summary>
|
||||
Ejected,
|
||||
|
||||
/// <summary>Another process holds files open on the volume; nothing was changed.</summary>
|
||||
InUse,
|
||||
|
||||
/// <summary>The drive is not a removable-media drive (fixed, network, unknown or no such letter).</summary>
|
||||
NotRemovable,
|
||||
|
||||
/// <summary>Windows refused to open, dismount or eject the volume.</summary>
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Safe card removal (BRIEF §12.4): open <c>\\.\X:</c>, 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Clears any media-removal lock; readers that do not implement the request count as unlocked.</summary>
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using System.Globalization;
|
||||
|
||||
namespace Titano.Core.Windows.Devices;
|
||||
|
||||
/// <summary>GetDriveTypeW results.</summary>
|
||||
public enum VolumeDriveType
|
||||
{
|
||||
Unknown = 0,
|
||||
NoRootDirectory = 1,
|
||||
Removable = 2,
|
||||
Fixed = 3,
|
||||
Remote = 4,
|
||||
CdRom = 5,
|
||||
RamDisk = 6,
|
||||
}
|
||||
|
||||
/// <summary>A mounted volume with the facts card import needs (BRIEF §12.4, §13).</summary>
|
||||
/// <param name="RootPath">Root with trailing separator, e.g. <c>E:\</c>.</param>
|
||||
/// <param name="Label">Volume label (may be empty).</param>
|
||||
/// <param name="FileSystem">File system name, e.g. exFAT.</param>
|
||||
/// <param name="SerialNumber">Volume serial number assigned at format time.</param>
|
||||
/// <param name="TotalBytes">Capacity in bytes.</param>
|
||||
/// <param name="FreeBytes">Free bytes available to the current user.</param>
|
||||
/// <param name="DriveType">Drive type reported by Windows.</param>
|
||||
/// <param name="HasDcim">A <c>DCIM</c> folder exists at the root (camera card).</param>
|
||||
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]);
|
||||
|
||||
/// <summary>Card identity <c>{serial:X8}-{label}-{capacity}</c> (BRIEF §13); stable across readers and drive letters.</summary>
|
||||
public string Identity => string.Create(CultureInfo.InvariantCulture, $"{SerialNumber:X8}-{Label}-{TotalBytes}");
|
||||
|
||||
/// <summary>Reads a volume; null when the root does not exist or holds no media (empty card reader).</summary>
|
||||
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 _);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Every ready fixed or removable volume, enumerated through <see cref="DriveInfo"/> (network and optical drives are skipped).</summary>
|
||||
public static IReadOnlyList<VolumeInfo> ListLocal()
|
||||
{
|
||||
var volumes = new List<VolumeInfo>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>"e:", "E:\" or "E:\DCIM" → "E:\".</summary>
|
||||
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() + "\\";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
namespace Titano.Core.Windows.Devices;
|
||||
|
||||
/// <summary>kernel32 volume and device-control entry points used by the Devices helpers.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Per-thread error mode; SEM_FAILCRITICALERRORS stops "insert a disk" dialogs on empty card readers.</summary>
|
||||
[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);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Titano.Core.IO;
|
||||
|
||||
namespace Titano.Core.Windows.Interop;
|
||||
|
||||
/// <summary>IStream over a file through <c>SHCreateStreamOnFileEx</c>.</summary>
|
||||
internal static partial class ShellStream
|
||||
{
|
||||
private const uint STGM_READ = 0x0;
|
||||
private const uint STGM_SHARE_DENY_NONE = 0x40;
|
||||
private const uint FILE_ATTRIBUTE_NORMAL = 0x80;
|
||||
|
||||
/// <summary>
|
||||
/// Opens <paramref name="path"/> read-only while letting other processes read and write it (FileShare.ReadWrite),
|
||||
/// so a camera tether or a copy in progress is never blocked. Returns an owned IStream pointer the caller must
|
||||
/// <see cref="Marshal.Release"/>. Failures surface as the matching .NET exception (FileNotFoundException, …).
|
||||
/// </summary>
|
||||
public static nint OpenRead(string path)
|
||||
{
|
||||
var hr = SHCreateStreamOnFileEx(LongPath.Normalize(path), STGM_READ | STGM_SHARE_DENY_NONE, FILE_ATTRIBUTE_NORMAL, 0, 0, out var stream);
|
||||
Marshal.ThrowExceptionForHR(hr);
|
||||
return stream;
|
||||
}
|
||||
|
||||
[LibraryImport("shlwapi.dll", StringMarshalling = StringMarshalling.Utf16)]
|
||||
private static partial int SHCreateStreamOnFileEx(string file, uint mode, uint attributes, int create, nint template, out nint stream);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Titano.Core.Windows.Interop;
|
||||
|
||||
/// <summary>COM apartment, activation and release helpers shared by the WIC, shell and taskbar interop.</summary>
|
||||
internal static partial class Win32Com
|
||||
{
|
||||
public const int RPC_E_CHANGED_MODE = unchecked((int)0x80010106);
|
||||
public const int REGDB_E_CLASSNOTREG = unchecked((int)0x80040154);
|
||||
|
||||
private const uint COINIT_MULTITHREADED = 0x0;
|
||||
private const uint CLSCTX_INPROC_SERVER = 0x1;
|
||||
|
||||
[ThreadStatic]
|
||||
private static bool t_initialized;
|
||||
|
||||
/// <summary>
|
||||
/// Joins the calling thread to the multithreaded apartment unless it already has one (an STA UI thread keeps
|
||||
/// its apartment, which free-threaded WIC also accepts). Idempotent per thread. COM stays initialised until the
|
||||
/// thread exits, as the runtime does for the threads it initialises itself.
|
||||
/// </summary>
|
||||
public static void EnsureInitialized()
|
||||
{
|
||||
if (t_initialized) return;
|
||||
var hr = CoInitializeEx(0, COINIT_MULTITHREADED);
|
||||
if (hr < 0 && hr != RPC_E_CHANGED_MODE) Marshal.ThrowExceptionForHR(hr);
|
||||
t_initialized = true;
|
||||
}
|
||||
|
||||
/// <summary>Creates an in-process COM object and wraps it; returns the HRESULT (instance is null on failure).</summary>
|
||||
public static int TryCreateInstance(Guid clsid, Guid iid, out object? instance)
|
||||
{
|
||||
EnsureInitialized();
|
||||
var hr = CoCreateInstance(clsid, 0, CLSCTX_INPROC_SERVER, iid, out var pointer);
|
||||
if (hr < 0)
|
||||
{
|
||||
instance = null;
|
||||
return hr;
|
||||
}
|
||||
try
|
||||
{
|
||||
instance = Marshal.GetObjectForIUnknown(pointer);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// The wrapper holds its own reference.
|
||||
Marshal.Release(pointer);
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
/// <summary>Releases the wrapper's reference to the native object now rather than at finalization.</summary>
|
||||
public static void Release(object? comObject)
|
||||
{
|
||||
if (comObject is not null && Marshal.IsComObject(comObject)) Marshal.ReleaseComObject(comObject);
|
||||
}
|
||||
|
||||
[LibraryImport("ole32.dll")]
|
||||
private static partial int CoInitializeEx(nint reserved, uint coInit);
|
||||
|
||||
[LibraryImport("ole32.dll")]
|
||||
private static partial int CoCreateInstance(in Guid clsid, nint outer, uint context, in Guid iid, out nint instance);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Titano.Core.Windows.Interop;
|
||||
|
||||
/// <summary>
|
||||
/// x64 PROPVARIANT (24 bytes: VARTYPE + three reserved WORDs, then a 16-byte union). Only the integer members
|
||||
/// Titano reads are mapped; anything the callee allocates is freed by <see cref="Clear"/>.
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Explicit, Size = 24)]
|
||||
internal partial struct PropVariant
|
||||
{
|
||||
private const ushort VT_I2 = 2, VT_I4 = 3, VT_UI1 = 17, VT_UI2 = 18, VT_UI4 = 19;
|
||||
|
||||
[FieldOffset(0)]
|
||||
public ushort VarType;
|
||||
|
||||
[FieldOffset(8)]
|
||||
private byte _byte;
|
||||
|
||||
[FieldOffset(8)]
|
||||
private short _int16;
|
||||
|
||||
[FieldOffset(8)]
|
||||
private ushort _uint16;
|
||||
|
||||
[FieldOffset(8)]
|
||||
private int _int32;
|
||||
|
||||
[FieldOffset(8)]
|
||||
private uint _uint32;
|
||||
|
||||
/// <summary>Reads an 8/16/32-bit integer value; false for any other type.</summary>
|
||||
public readonly bool TryGetInt32(out int value)
|
||||
{
|
||||
switch (VarType)
|
||||
{
|
||||
case VT_UI1:
|
||||
value = _byte;
|
||||
return true;
|
||||
case VT_I2:
|
||||
value = _int16;
|
||||
return true;
|
||||
case VT_UI2:
|
||||
value = _uint16;
|
||||
return true;
|
||||
case VT_I4:
|
||||
value = _int32;
|
||||
return true;
|
||||
case VT_UI4 when _uint32 <= int.MaxValue:
|
||||
value = (int)_uint32;
|
||||
return true;
|
||||
default:
|
||||
value = 0;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Frees whatever the callee allocated and resets the value to VT_EMPTY.</summary>
|
||||
public static void Clear(ref PropVariant value) => PropVariantClear(ref value);
|
||||
|
||||
[LibraryImport("ole32.dll")]
|
||||
private static partial int PropVariantClear(ref PropVariant value);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Titano.Core.Windows.Interop;
|
||||
|
||||
/// <summary>Window handle validation shared by the DWM and taskbar helpers.</summary>
|
||||
internal static partial class Win32Window
|
||||
{
|
||||
/// <summary>True when <paramref name="window"/> names an existing window; rejects null and stale handles up front.</summary>
|
||||
public static bool Exists(nint window) => window != 0 && IsWindow(window);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool IsWindow(nint window);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Titano.Core.Windows.Power;
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the system (and optionally the display) awake during a long job: SetThreadExecutionState with
|
||||
/// ES_CONTINUOUS | ES_SYSTEM_REQUIRED, cleared again on <see cref="Dispose"/>. The execution state belongs to the
|
||||
/// calling thread, so each blocker owns a small dedicated thread; this keeps the request valid even when an async
|
||||
/// job is disposed on a different pool thread than the one that started it.
|
||||
/// </summary>
|
||||
public sealed partial class SleepBlocker : IDisposable
|
||||
{
|
||||
private const uint ES_SYSTEM_REQUIRED = 0x1;
|
||||
private const uint ES_DISPLAY_REQUIRED = 0x2;
|
||||
private const uint ES_CONTINUOUS = 0x80000000;
|
||||
|
||||
private readonly ManualResetEventSlim _release = new();
|
||||
private readonly Thread _owner;
|
||||
private int _disposed;
|
||||
|
||||
/// <param name="keepDisplayOn">Also keep the display on (e.g. while a preview plays).</param>
|
||||
public SleepBlocker(bool keepDisplayOn = false)
|
||||
{
|
||||
var flags = ES_CONTINUOUS | ES_SYSTEM_REQUIRED | (keepDisplayOn ? ES_DISPLAY_REQUIRED : 0);
|
||||
using var applied = new ManualResetEventSlim();
|
||||
_owner = new Thread(() =>
|
||||
{
|
||||
IsActive = SetThreadExecutionState(flags) != 0;
|
||||
applied.Set();
|
||||
_release.Wait();
|
||||
SetThreadExecutionState(ES_CONTINUOUS);
|
||||
})
|
||||
{
|
||||
IsBackground = true,
|
||||
Name = "Titano sleep blocker",
|
||||
};
|
||||
_owner.Start();
|
||||
applied.Wait();
|
||||
}
|
||||
|
||||
/// <summary>False when Windows rejected the request.</summary>
|
||||
public bool IsActive { get; private set; }
|
||||
|
||||
/// <summary>Restores normal sleep behaviour.</summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
|
||||
_release.Set();
|
||||
_owner.Join();
|
||||
_release.Dispose();
|
||||
}
|
||||
|
||||
[LibraryImport("kernel32.dll")]
|
||||
private static partial uint SetThreadExecutionState(uint flags);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace Titano.Core.Windows.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Windows Data Protection API in the current-user scope (BRIEF §15): secrets such as server tokens are encrypted
|
||||
/// with a key derived from the user's logon credentials, so only the same Windows user can decrypt them.
|
||||
/// Optional entropy binds a secret to a purpose (it must be supplied again to decrypt).
|
||||
/// </summary>
|
||||
public static unsafe partial class Dpapi
|
||||
{
|
||||
private const uint CRYPTPROTECT_UI_FORBIDDEN = 0x1;
|
||||
|
||||
/// <exception cref="CryptographicException">Encryption failed.</exception>
|
||||
public static byte[] Protect(ReadOnlySpan<byte> plaintext, ReadOnlySpan<byte> entropy = default)
|
||||
{
|
||||
// An empty span pins to null, but the API wants a valid pointer even for zero bytes.
|
||||
byte empty = 0;
|
||||
fixed (byte* input = plaintext)
|
||||
fixed (byte* salt = entropy)
|
||||
{
|
||||
var inputBlob = new DataBlob { Size = (uint)plaintext.Length, Data = input == null ? &empty : input };
|
||||
var entropyBlob = new DataBlob { Size = (uint)entropy.Length, Data = salt };
|
||||
DataBlob output = default;
|
||||
if (!CryptProtectData(&inputBlob, null, entropy.IsEmpty ? null : &entropyBlob, 0, 0, CRYPTPROTECT_UI_FORBIDDEN, &output))
|
||||
throw new CryptographicException(Marshal.GetLastPInvokeErrorMessage());
|
||||
return TakeOutput(output, clear: false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <exception cref="CryptographicException">The data was protected by another user, tampered with, or the entropy differs.</exception>
|
||||
public static byte[] Unprotect(ReadOnlySpan<byte> protectedData, ReadOnlySpan<byte> entropy = default)
|
||||
{
|
||||
byte empty = 0;
|
||||
fixed (byte* input = protectedData)
|
||||
fixed (byte* salt = entropy)
|
||||
{
|
||||
var inputBlob = new DataBlob { Size = (uint)protectedData.Length, Data = input == null ? &empty : input };
|
||||
var entropyBlob = new DataBlob { Size = (uint)entropy.Length, Data = salt };
|
||||
DataBlob output = default;
|
||||
if (!CryptUnprotectData(&inputBlob, null, entropy.IsEmpty ? null : &entropyBlob, 0, 0, CRYPTPROTECT_UI_FORBIDDEN, &output))
|
||||
throw new CryptographicException(Marshal.GetLastPInvokeErrorMessage());
|
||||
return TakeOutput(output, clear: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Protects a UTF-8 string and returns Base64, convenient for JSON settings.</summary>
|
||||
public static string ProtectString(string value, ReadOnlySpan<byte> entropy = default)
|
||||
{
|
||||
var bytes = Encoding.UTF8.GetBytes(value);
|
||||
try
|
||||
{
|
||||
return Convert.ToBase64String(Protect(bytes, entropy));
|
||||
}
|
||||
finally
|
||||
{
|
||||
CryptographicOperations.ZeroMemory(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reverses <see cref="ProtectString"/>.</summary>
|
||||
/// <exception cref="FormatException">The text is not Base64.</exception>
|
||||
/// <exception cref="CryptographicException">The data cannot be decrypted by this user with this entropy.</exception>
|
||||
public static string UnprotectString(string protectedBase64, ReadOnlySpan<byte> entropy = default)
|
||||
{
|
||||
var bytes = Unprotect(Convert.FromBase64String(protectedBase64), entropy);
|
||||
try
|
||||
{
|
||||
return Encoding.UTF8.GetString(bytes);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CryptographicOperations.ZeroMemory(bytes);
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] TakeOutput(DataBlob output, bool clear)
|
||||
{
|
||||
try
|
||||
{
|
||||
var native = new Span<byte>(output.Data, (int)output.Size);
|
||||
var result = native.ToArray();
|
||||
if (clear) CryptographicOperations.ZeroMemory(native);
|
||||
return result;
|
||||
}
|
||||
finally
|
||||
{
|
||||
LocalFree((nint)output.Data);
|
||||
}
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct DataBlob
|
||||
{
|
||||
public uint Size;
|
||||
public byte* Data;
|
||||
}
|
||||
|
||||
[LibraryImport("crypt32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool CryptProtectData(DataBlob* dataIn, char* description, DataBlob* entropy, nint reserved, nint prompt, uint flags, DataBlob* dataOut);
|
||||
|
||||
[LibraryImport("crypt32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool CryptUnprotectData(DataBlob* dataIn, char** description, DataBlob* entropy, nint reserved, nint prompt, uint flags, DataBlob* dataOut);
|
||||
|
||||
[LibraryImport("kernel32.dll")]
|
||||
private static partial nint LocalFree(nint memory);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
namespace Titano.Core.Windows.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// Where the desktop programs keep their data (BRIEF §6.2): <c>%LOCALAPPDATA%\Titano</c>, or <c>.\data</c> next to the
|
||||
/// executable in portable mode. SQLite corrupts inside synchronised folders, so a data root under OneDrive is
|
||||
/// reported by <see cref="SyncedFolder"/> and refused by <see cref="CreateDirectories"/>.
|
||||
/// </summary>
|
||||
public sealed class AppPaths
|
||||
{
|
||||
public const string ProductFolderName = "Titano";
|
||||
public const string DatabaseFileName = "titano.db";
|
||||
|
||||
private AppPaths(string dataRoot, bool isPortable, string? syncedFolder)
|
||||
{
|
||||
DataRoot = dataRoot;
|
||||
IsPortable = isPortable;
|
||||
SyncedFolder = syncedFolder;
|
||||
}
|
||||
|
||||
public bool IsPortable { get; }
|
||||
|
||||
public string DataRoot { get; }
|
||||
|
||||
public string DatabasePath => Path.Combine(DataRoot, DatabaseFileName);
|
||||
|
||||
public string LogsDirectory => Path.Combine(DataRoot, "logs");
|
||||
|
||||
public string CacheDirectory => Path.Combine(DataRoot, "cache");
|
||||
|
||||
public string ThumbnailsDirectory => Path.Combine(DataRoot, "thumbnails");
|
||||
|
||||
/// <summary>The OneDrive sync root containing <see cref="DataRoot"/>, or null when the location is safe.</summary>
|
||||
public string? SyncedFolder { get; }
|
||||
|
||||
public bool IsInSyncedFolder => SyncedFolder is not null;
|
||||
|
||||
/// <summary>Paths for this process: the executable's folder decides portable mode.</summary>
|
||||
public static AppPaths Resolve() => Resolve(AppContext.BaseDirectory, KnownFolders.LocalAppData);
|
||||
|
||||
/// <summary>Paths for an executable in <paramref name="applicationDirectory"/>, checked against the user's OneDrive roots.</summary>
|
||||
public static AppPaths Resolve(string applicationDirectory, string localAppData) =>
|
||||
Resolve(applicationDirectory, localAppData, OneDriveFolders.SyncRoots());
|
||||
|
||||
internal static AppPaths Resolve(string applicationDirectory, string localAppData, IReadOnlyList<string> syncRoots)
|
||||
{
|
||||
var portable = PortableMode.IsEnabled(applicationDirectory);
|
||||
var root = Path.GetFullPath(portable
|
||||
? Path.Combine(applicationDirectory, PortableMode.DataFolderName)
|
||||
: Path.Combine(localAppData, ProductFolderName));
|
||||
return new AppPaths(root, portable, OneDriveFolders.Containing(root, syncRoots));
|
||||
}
|
||||
|
||||
/// <summary>Creates the data, logs, cache and thumbnails folders.</summary>
|
||||
/// <exception cref="InvalidOperationException">The data root lies inside a OneDrive-synced folder.</exception>
|
||||
public void CreateDirectories()
|
||||
{
|
||||
if (SyncedFolder is not null)
|
||||
throw new InvalidOperationException($"The data folder '{DataRoot}' is inside the OneDrive folder '{SyncedFolder}'; the database would be corrupted by synchronisation.");
|
||||
Directory.CreateDirectory(DataRoot);
|
||||
Directory.CreateDirectory(LogsDirectory);
|
||||
Directory.CreateDirectory(CacheDirectory);
|
||||
Directory.CreateDirectory(ThumbnailsDirectory);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Titano.Core.Windows.Shell;
|
||||
|
||||
/// <summary>Known folder paths through SHGetKnownFolderPath (honours folder redirection).</summary>
|
||||
public static partial class KnownFolders
|
||||
{
|
||||
/// <summary>FOLDERID_LocalAppData.</summary>
|
||||
public static readonly Guid LocalAppDataId = new("f1b32785-6fba-4fcf-9d55-7b8e7f157091");
|
||||
|
||||
/// <summary>FOLDERID_Pictures.</summary>
|
||||
public static readonly Guid PicturesId = new("33e28130-4e1e-4676-835a-98395c3bc3bb");
|
||||
|
||||
/// <summary>%LOCALAPPDATA% (never synced by OneDrive).</summary>
|
||||
public static string LocalAppData => GetPath(LocalAppDataId);
|
||||
|
||||
/// <summary>The user's Pictures folder (may be redirected into OneDrive).</summary>
|
||||
public static string Pictures => GetPath(PicturesId);
|
||||
|
||||
/// <exception cref="COMException">The folder does not exist or is not available to this user.</exception>
|
||||
public static string GetPath(Guid folderId)
|
||||
{
|
||||
var hr = SHGetKnownFolderPath(folderId, 0, 0, out var buffer);
|
||||
try
|
||||
{
|
||||
Marshal.ThrowExceptionForHR(hr);
|
||||
return Marshal.PtrToStringUni(buffer) ?? string.Empty;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// The buffer must be freed whether or not the call succeeded.
|
||||
Marshal.FreeCoTaskMem(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
[LibraryImport("shell32.dll")]
|
||||
private static partial int SHGetKnownFolderPath(in Guid folderId, uint flags, nint token, out nint path);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace Titano.Core.Windows.Shell;
|
||||
|
||||
/// <summary>Folders synchronised by OneDrive for the current user (personal and work/school accounts).</summary>
|
||||
public static class OneDriveFolders
|
||||
{
|
||||
private const string AccountsKey = @"Software\Microsoft\OneDrive\Accounts";
|
||||
private static readonly string[] EnvironmentVariables = ["OneDrive", "OneDriveConsumer", "OneDriveCommercial"];
|
||||
|
||||
/// <summary>
|
||||
/// Sync roots from the OneDrive environment variables and <c>HKCU\Software\Microsoft\OneDrive\Accounts\*\UserFolder</c>,
|
||||
/// as full paths without a trailing separator, distinct (case-insensitive).
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> SyncRoots()
|
||||
{
|
||||
var roots = new List<string>();
|
||||
foreach (var variable in EnvironmentVariables) Add(roots, Environment.GetEnvironmentVariable(variable));
|
||||
using var accounts = Registry.CurrentUser.OpenSubKey(AccountsKey);
|
||||
if (accounts is not null)
|
||||
{
|
||||
foreach (var name in accounts.GetSubKeyNames())
|
||||
{
|
||||
using var account = accounts.OpenSubKey(name);
|
||||
Add(roots, account?.GetValue("UserFolder") as string);
|
||||
}
|
||||
}
|
||||
return roots;
|
||||
}
|
||||
|
||||
/// <summary>The sync root that contains <paramref name="path"/>, or null. Both are expected to be full paths.</summary>
|
||||
public static string? Containing(string path, IEnumerable<string> syncRoots) => syncRoots.FirstOrDefault(root => IsUnder(path, root));
|
||||
|
||||
/// <summary>True when <paramref name="path"/> equals <paramref name="root"/> or lies below it (whole path segments, case-insensitive).</summary>
|
||||
internal static bool IsUnder(string path, string root)
|
||||
{
|
||||
var trimmedRoot = root.TrimEnd('\\', '/');
|
||||
if (trimmedRoot.Length == 0 || !path.StartsWith(trimmedRoot, StringComparison.OrdinalIgnoreCase)) return false;
|
||||
return path.Length == trimmedRoot.Length || path[trimmedRoot.Length] is '\\' or '/';
|
||||
}
|
||||
|
||||
private static void Add(List<string> roots, string? candidate)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(candidate) || !Path.IsPathFullyQualified(candidate)) return;
|
||||
var full = Path.GetFullPath(candidate).TrimEnd('\\', '/');
|
||||
if (!roots.Contains(full, StringComparer.OrdinalIgnoreCase)) roots.Add(full);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace Titano.Core.Windows.Shell;
|
||||
|
||||
/// <summary>Portable mode (BRIEF §6.2): a <c>portable.txt</c> next to the executable keeps all data under <c>.\data\</c>.</summary>
|
||||
public static class PortableMode
|
||||
{
|
||||
public const string MarkerFileName = "portable.txt";
|
||||
public const string DataFolderName = "data";
|
||||
|
||||
public static bool IsEnabled(string applicationDirectory) => File.Exists(Path.Combine(applicationDirectory, MarkerFileName));
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
using System.Runtime.ExceptionServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Titano.Core.Windows.Shell;
|
||||
|
||||
/// <summary>
|
||||
/// The only shell verbs Titano may invoke (BRIEF §8.6): <c>open</c> for web and Microsoft Store links and
|
||||
/// <c>explore</c>/select for revealing files. Callable from any thread: the work runs on an STA as shell
|
||||
/// extensions require (inline on a UI thread, otherwise on a short-lived STA thread).
|
||||
/// </summary>
|
||||
public static partial class ShellLauncher
|
||||
{
|
||||
private static readonly string[] AllowedSchemes = ["http", "https", "ms-windows-store"];
|
||||
|
||||
private const uint SEE_MASK_NOASYNC = 0x100;
|
||||
private const uint SEE_MASK_FLAG_NO_UI = 0x400;
|
||||
private const int SW_SHOWNORMAL = 1;
|
||||
|
||||
/// <summary>True for absolute http, https and ms-windows-store URLs, the only links handed to the shell.</summary>
|
||||
public static bool IsAllowedUrl(string url) =>
|
||||
Uri.TryCreate(url, UriKind.Absolute, out var uri)
|
||||
&& AllowedSchemes.Contains(uri.Scheme, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>Opens the URL with ShellExecuteEx("open"); false when the shell could not open it.</summary>
|
||||
/// <exception cref="ArgumentException">The URL is not an absolute http, https or ms-windows-store URL.</exception>
|
||||
public static bool OpenUrl(string url)
|
||||
{
|
||||
if (!IsAllowedUrl(url)) throw new ArgumentException("Only http, https and ms-windows-store URLs may be opened.", nameof(url));
|
||||
var canonical = new Uri(url, UriKind.Absolute).AbsoluteUri;
|
||||
return RunOnSta(() => Execute("open", canonical));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shows a file selected in its Explorer folder (SHOpenFolderAndSelectItems) or opens a folder ("explore").
|
||||
/// False when the path does not exist or the shell failed.
|
||||
/// </summary>
|
||||
public static bool RevealInExplorer(string path)
|
||||
{
|
||||
var full = Path.GetFullPath(path);
|
||||
if (Directory.Exists(full)) return RunOnSta(() => Execute("explore", full));
|
||||
return File.Exists(full) && RunOnSta(() => SelectInFolder(full));
|
||||
}
|
||||
|
||||
private static unsafe bool Execute(string verb, string file)
|
||||
{
|
||||
fixed (char* verbPointer = verb)
|
||||
fixed (char* filePointer = file)
|
||||
{
|
||||
var info = new ShellExecuteInfo
|
||||
{
|
||||
Size = (uint)sizeof(ShellExecuteInfo),
|
||||
Mask = SEE_MASK_NOASYNC | SEE_MASK_FLAG_NO_UI,
|
||||
Verb = (nint)verbPointer,
|
||||
File = (nint)filePointer,
|
||||
Show = SW_SHOWNORMAL,
|
||||
};
|
||||
return ShellExecuteExW(ref info);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool SelectInFolder(string file)
|
||||
{
|
||||
if (SHParseDisplayName(file, 0, out var itemList, 0, out _) < 0) return false;
|
||||
try
|
||||
{
|
||||
// With no child items the absolute ID list names the item to select; Explorer opens its parent.
|
||||
return SHOpenFolderAndSelectItems(itemList, 0, 0, 0) >= 0;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.FreeCoTaskMem(itemList);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool RunOnSta(Func<bool> action)
|
||||
{
|
||||
if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA) return action();
|
||||
var result = false;
|
||||
ExceptionDispatchInfo? failure = null;
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
result = action();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
failure = ExceptionDispatchInfo.Capture(ex);
|
||||
}
|
||||
})
|
||||
{
|
||||
IsBackground = true,
|
||||
Name = "Titano shell",
|
||||
};
|
||||
thread.SetApartmentState(ApartmentState.STA);
|
||||
thread.Start();
|
||||
thread.Join();
|
||||
failure?.Throw();
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>SHELLEXECUTEINFOW (112 bytes on x64).</summary>
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct ShellExecuteInfo
|
||||
{
|
||||
public uint Size;
|
||||
public uint Mask;
|
||||
public nint Window;
|
||||
public nint Verb;
|
||||
public nint File;
|
||||
public nint Parameters;
|
||||
public nint Directory;
|
||||
public int Show;
|
||||
public nint InstanceApp;
|
||||
public nint ItemIdList;
|
||||
public nint Class;
|
||||
public nint ClassKey;
|
||||
public uint HotKey;
|
||||
public nint IconOrMonitor;
|
||||
public nint Process;
|
||||
}
|
||||
|
||||
[LibraryImport("shell32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static partial bool ShellExecuteExW(ref ShellExecuteInfo info);
|
||||
|
||||
[LibraryImport("shell32.dll", StringMarshalling = StringMarshalling.Utf16)]
|
||||
private static partial int SHParseDisplayName(string name, nint bindContext, out nint itemIdList, uint attributesIn, out uint attributesOut);
|
||||
|
||||
[LibraryImport("shell32.dll")]
|
||||
private static partial int SHOpenFolderAndSelectItems(nint folder, uint count, nint items, uint flags);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Titano.Core.Windows.Interop;
|
||||
|
||||
namespace Titano.Core.Windows.Shell;
|
||||
|
||||
/// <summary>TBPFLAG: the taskbar button progress style.</summary>
|
||||
public enum TaskbarProgressState
|
||||
{
|
||||
None = 0x0,
|
||||
Indeterminate = 0x1,
|
||||
Normal = 0x2,
|
||||
Error = 0x4,
|
||||
Paused = 0x8,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Taskbar button progress through ITaskbarList3. The taskbar object is apartment-threaded: create, use and dispose
|
||||
/// an instance on the UI thread that owns the window. Every call returns false (never throws) when the taskbar is
|
||||
/// unavailable, the window handle is null or stale, or the shell rejects the call.
|
||||
/// </summary>
|
||||
public sealed class TaskbarProgress : IDisposable
|
||||
{
|
||||
private static readonly Guid TaskbarListClsid = new("56fdf344-fd6d-11d0-958a-006097c9a090");
|
||||
private ITaskbarList3? _taskbar;
|
||||
|
||||
public TaskbarProgress()
|
||||
{
|
||||
if (Win32Com.TryCreateInstance(TaskbarListClsid, typeof(ITaskbarList3).GUID, out var instance) >= 0
|
||||
&& instance is ITaskbarList3 taskbar
|
||||
&& taskbar.HrInit() >= 0)
|
||||
{
|
||||
_taskbar = taskbar;
|
||||
return;
|
||||
}
|
||||
Win32Com.Release(instance);
|
||||
}
|
||||
|
||||
/// <summary>False when no taskbar is available (e.g. a session without Explorer).</summary>
|
||||
public bool IsAvailable => _taskbar is not null;
|
||||
|
||||
public bool SetState(nint window, TaskbarProgressState state) =>
|
||||
_taskbar is { } taskbar && Win32Window.Exists(window) && taskbar.SetProgressState(window, state) >= 0;
|
||||
|
||||
/// <summary>Sets the bar to <paramref name="completed"/>/<paramref name="total"/> (switches to <see cref="TaskbarProgressState.Normal"/> if no progress was shown).</summary>
|
||||
public bool SetValue(nint window, ulong completed, ulong total) =>
|
||||
total > 0 && _taskbar is { } taskbar && Win32Window.Exists(window) && taskbar.SetProgressValue(window, Math.Min(completed, total), total) >= 0;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Win32Com.Release(_taskbar);
|
||||
_taskbar = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>ITaskbarList3 (ITaskbarList → ITaskbarList2 → ITaskbarList3), declared up to SetProgressState.</summary>
|
||||
[ComImport]
|
||||
[Guid("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
internal interface ITaskbarList3
|
||||
{
|
||||
[PreserveSig]
|
||||
int HrInit();
|
||||
|
||||
[PreserveSig]
|
||||
int AddTab(nint window);
|
||||
|
||||
[PreserveSig]
|
||||
int DeleteTab(nint window);
|
||||
|
||||
[PreserveSig]
|
||||
int ActivateTab(nint window);
|
||||
|
||||
[PreserveSig]
|
||||
int SetActiveAlt(nint window);
|
||||
|
||||
[PreserveSig]
|
||||
int MarkFullscreenWindow(nint window, int fullscreen);
|
||||
|
||||
[PreserveSig]
|
||||
int SetProgressValue(nint window, ulong completed, ulong total);
|
||||
|
||||
[PreserveSig]
|
||||
int SetProgressState(nint window, TaskbarProgressState state);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace Titano.Core.Windows.Wic;
|
||||
|
||||
/// <summary>
|
||||
/// Where each stored pixel (x, y) of a <c>width</c>×<c>height</c> image lands once Exif orientation 1–8 is applied,
|
||||
/// as a linear index <c>Origin + x·StepX + y·StepY</c> into the row-major oriented image. Applying the orientation
|
||||
/// while de-interleaving costs nothing extra, unlike a WIC flip-rotator over a scanline decoder.
|
||||
/// </summary>
|
||||
internal readonly record struct OrientationMap(int Width, int Height, int Origin, int StepX, int StepY)
|
||||
{
|
||||
/// <summary>Orientations 5–8 swap width and height.</summary>
|
||||
public static bool SwapsAxes(int orientation) => orientation is >= 5 and <= 8;
|
||||
|
||||
/// <summary>Map for a stored <paramref name="width"/>×<paramref name="height"/> image; unknown values act as 1.</summary>
|
||||
public static OrientationMap Create(int orientation, int width, int height) => orientation switch
|
||||
{
|
||||
2 => new(width, height, width - 1, -1, width), // mirror horizontal
|
||||
3 => new(width, height, (height * width) - 1, -1, -width), // rotate 180°
|
||||
4 => new(width, height, (height - 1) * width, 1, -width), // mirror vertical
|
||||
5 => new(height, width, 0, height, 1), // transpose
|
||||
6 => new(height, width, height - 1, height, -1), // rotate 90° clockwise
|
||||
7 => new(height, width, (width * height) - 1, -height, -1), // transverse
|
||||
8 => new(height, width, (width - 1) * height, -height, 1), // rotate 90° counter-clockwise
|
||||
_ => new(width, height, 0, 1, width),
|
||||
};
|
||||
|
||||
public int IndexOf(int x, int y) => Origin + (x * StepX) + (y * StepY);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Windows.Codecs;
|
||||
using Titano.Core.Windows.Interop;
|
||||
|
||||
namespace Titano.Core.Windows.Wic;
|
||||
|
||||
/// <summary>Enumerates installed WIC decoders through <c>IWICImagingFactory::CreateComponentEnumerator</c>.</summary>
|
||||
internal static class WicComponents
|
||||
{
|
||||
private const uint ComponentDecoder = 0x1;
|
||||
private const uint EnumerateRefresh = 0x1;
|
||||
private const uint EnumerateUnsigned = 0x40000000;
|
||||
|
||||
/// <summary>
|
||||
/// Every enabled decoder, signed or not (third-party camera codecs are often unsigned and WIC still uses them).
|
||||
/// <paramref name="refresh"/> makes WIC re-read the registrations, e.g. after a Store extension was installed.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<WicDecoderInfo> EnumerateDecoders(bool refresh)
|
||||
{
|
||||
Win32Com.EnsureInitialized();
|
||||
var decoders = new List<WicDecoderInfo>();
|
||||
var enumerator = WicFactory.Instance.CreateComponentEnumerator(ComponentDecoder, EnumerateUnsigned | (refresh ? EnumerateRefresh : 0));
|
||||
try
|
||||
{
|
||||
while (enumerator.Next(1, out var unknown, out var fetched) == 0 && fetched == 1)
|
||||
{
|
||||
object? component = null;
|
||||
try
|
||||
{
|
||||
component = Marshal.GetObjectForIUnknown(unknown);
|
||||
if (component is IWICBitmapDecoderInfo info) decoders.Add(Read(info));
|
||||
}
|
||||
catch (COMException ex)
|
||||
{
|
||||
Log.Warning("wic", "Skipped a WIC decoder whose registration could not be read", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.Release(unknown);
|
||||
Win32Com.Release(component);
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Win32Com.Release(enumerator);
|
||||
}
|
||||
return decoders;
|
||||
}
|
||||
|
||||
/// <summary>Reads a component-info string through the "ask for the length, then fill" protocol.</summary>
|
||||
public static unsafe string ReadString(WicStringGetter getter)
|
||||
{
|
||||
if (getter(0, null, out var length) < 0 || length <= 1) return string.Empty;
|
||||
var buffer = new char[length];
|
||||
int hr;
|
||||
fixed (char* p = buffer)
|
||||
{
|
||||
hr = getter(length, p, out length);
|
||||
}
|
||||
if (hr < 0) return string.Empty;
|
||||
var text = buffer.AsSpan(0, (int)Math.Min(length, (uint)buffer.Length));
|
||||
var end = text.IndexOf('\0');
|
||||
return new string(end >= 0 ? text[..end] : text);
|
||||
}
|
||||
|
||||
// Lambdas call through the interface normally rather than binding delegates to COM methods.
|
||||
private static unsafe WicDecoderInfo Read(IWICBitmapDecoderInfo info) => new(
|
||||
FriendlyName: ReadString((uint capacity, char* buffer, out uint length) => info.GetFriendlyName(capacity, buffer, out length)),
|
||||
Clsid: info.GetCLSID(),
|
||||
ContainerFormat: info.GetContainerFormat(),
|
||||
Vendor: info.GetVendorGUID(),
|
||||
Version: ReadString((uint capacity, char* buffer, out uint length) => info.GetVersion(capacity, buffer, out length)),
|
||||
FileExtensions: WicDecoderInfo.ParseExtensions(
|
||||
ReadString((uint capacity, char* buffer, out uint length) => info.GetFileExtensions(capacity, buffer, out length))),
|
||||
Extension: null);
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
using System.Buffers;
|
||||
using System.Runtime.InteropServices;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Windows.Codecs;
|
||||
using Titano.Core.Windows.Interop;
|
||||
|
||||
namespace Titano.Core.Windows.Wic;
|
||||
|
||||
/// <summary>
|
||||
/// Native decoding through the Windows Imaging Component (BRIEF §8.2 tier 1) for every format with an installed
|
||||
/// WIC decoder (see <see cref="CodecInventory"/>). Thread-safe: each call builds its own pull chain
|
||||
/// (decoder → Fant scaler → format converter) on the calling thread, which joins the MTA if it has no apartment.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Pixels are requested as 64bppRGBA and linearised with the exact sRGB EOTF (<see cref="ColorSpace.Linear16"/>):
|
||||
/// WIC integer formats are sRGB-encoded, the 16-bit request keeps 16-bit PNG/TIFF precision, and the result matches
|
||||
/// the managed decoders bit for bit, whereas WIC's own integer→float conversion uses its own gamma approximation.
|
||||
/// Sources whose native format is floating or fixed point (scRGB: JPEG XR, HDR) are requested as 128bppRGBAFloat
|
||||
/// and copied unchanged, keeping highlights above 1. Alpha is discarded. The Exif orientation is applied while
|
||||
/// de-interleaving (<see cref="OrientationMap"/>).
|
||||
/// </remarks>
|
||||
public sealed class WicDecoderProvider : IImageDecoderProvider
|
||||
{
|
||||
private const int WINCODEC_ERR_COMPONENTNOTFOUND = unchecked((int)0x88982F50);
|
||||
private const int WICBitmapInterpolationModeFant = 3;
|
||||
private const int WICBitmapDitherTypeNone = 0;
|
||||
private const int WICBitmapPaletteTypeCustom = 0;
|
||||
private const uint NumericFixedPoint = 4, NumericFloat = 5;
|
||||
private const int BandBytes = 4 << 20;
|
||||
|
||||
/// <summary>The photo-policy query covers every WIC container; the raw paths catch decoders without the policy.</summary>
|
||||
private static readonly string[] OrientationQueries = ["System.Photo.Orientation", "/app1/ifd/{ushort=274}", "/ifd/{ushort=274}"];
|
||||
|
||||
/// <param name="inventory">Codec snapshot deciding <see cref="TierFor"/>; detected now when omitted.</param>
|
||||
public WicDecoderProvider(CodecInventory? inventory = null) => Inventory = inventory ?? CodecInventory.Detect();
|
||||
|
||||
public string Name => "wic";
|
||||
|
||||
public CodecInventory Inventory { get; }
|
||||
|
||||
public DecodeTier? TierFor(ImageFileFormat format) => Inventory.IsNative(format) ? DecodeTier.Native : null;
|
||||
|
||||
/// <summary>
|
||||
/// Decodes the first frame. Returns null when WIC cannot natively decode this format here, when the request
|
||||
/// forces the embedded preview, or when no installed decoder recognises the content. Corrupt files raise the
|
||||
/// WIC <see cref="COMException"/>; unreadable files the matching <see cref="IOException"/>.
|
||||
/// </summary>
|
||||
public DecodedImage? Decode(DecodeRequest request, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (request.ForcePreview || TierFor(ImageFormatInfo.FromPath(request.Path).Format) is null) return null;
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
|
||||
Win32Com.EnsureInitialized();
|
||||
var factory = WicFactory.Instance;
|
||||
var stream = ShellStream.OpenRead(request.Path);
|
||||
IWICBitmapDecoder? decoder = null;
|
||||
IWICBitmapFrameDecode? frame = null;
|
||||
IWICBitmapScaler? scaler = null;
|
||||
IWICFormatConverter? converter = null;
|
||||
try
|
||||
{
|
||||
var hr = factory.CreateDecoderFromStream(stream, 0, WicDecodeOptions.MetadataCacheOnDemand, out decoder);
|
||||
if (hr == WINCODEC_ERR_COMPONENTNOTFOUND) return null;
|
||||
Marshal.ThrowExceptionForHR(hr);
|
||||
frame = decoder!.GetFrame(0);
|
||||
frame.GetSize(out var width, out var height);
|
||||
var orientation = request.ApplyOrientation ? ReadOrientation(frame) : 1;
|
||||
|
||||
var (targetWidth, targetHeight) = TargetSize(width, height, request.MaxLongEdge);
|
||||
IWICBitmapSource source = frame;
|
||||
if (targetWidth != width || targetHeight != height)
|
||||
{
|
||||
scaler = factory.CreateBitmapScaler();
|
||||
scaler.Initialize(frame, targetWidth, targetHeight, WICBitmapInterpolationModeFant);
|
||||
source = scaler;
|
||||
}
|
||||
|
||||
converter = factory.CreateFormatConverter();
|
||||
var sourceFormat = source.GetPixelFormat();
|
||||
var floating = IsFloatingPoint(factory, frame.GetPixelFormat()) && CanConvert(converter, sourceFormat, WicGuids.PixelFormat128bppRGBAFloat);
|
||||
var targetFormat = floating ? WicGuids.PixelFormat128bppRGBAFloat : WicGuids.PixelFormat64bppRGBA;
|
||||
converter.Initialize(source, ref targetFormat, WICBitmapDitherTypeNone, 0, 0.0, WICBitmapPaletteTypeCustom);
|
||||
|
||||
var map = OrientationMap.Create(orientation, (int)targetWidth, (int)targetHeight);
|
||||
var pixels = CopyToPlanes(converter, (int)targetWidth, (int)targetHeight, floating, map, cancellationToken);
|
||||
var swap = OrientationMap.SwapsAxes(orientation);
|
||||
return new DecodedImage(pixels, DecodeTier.Native, Name, (int)(swap ? height : width), (int)(swap ? width : height));
|
||||
}
|
||||
finally
|
||||
{
|
||||
Win32Com.Release(converter);
|
||||
Win32Com.Release(scaler);
|
||||
Win32Com.Release(frame);
|
||||
Win32Com.Release(decoder);
|
||||
Marshal.Release(stream);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Size after fitting the long edge into <paramref name="maxLongEdge"/> (never upscales; 0 = native).</summary>
|
||||
internal static (uint Width, uint Height) TargetSize(uint width, uint height, int maxLongEdge)
|
||||
{
|
||||
var longEdge = Math.Max(width, height);
|
||||
if (maxLongEdge <= 0 || longEdge <= (uint)maxLongEdge) return (width, height);
|
||||
var scale = (double)maxLongEdge / longEdge;
|
||||
return ((uint)Math.Max(1, Math.Round(width * scale)), (uint)Math.Max(1, Math.Round(height * scale)));
|
||||
}
|
||||
|
||||
private static int ReadOrientation(IWICBitmapFrameDecode frame)
|
||||
{
|
||||
if (frame.GetMetadataQueryReader(out var reader) < 0 || reader is null) return 1;
|
||||
try
|
||||
{
|
||||
foreach (var query in OrientationQueries)
|
||||
{
|
||||
var value = default(PropVariant);
|
||||
if (reader.GetMetadataByName(query, ref value) < 0) continue;
|
||||
try
|
||||
{
|
||||
if (value.TryGetInt32(out var orientation) && orientation is >= 1 and <= 8) return orientation;
|
||||
}
|
||||
finally
|
||||
{
|
||||
PropVariant.Clear(ref value);
|
||||
}
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Win32Com.Release(reader);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True for fixed- and floating-point (scRGB) pixel formats; unknown formats count as integer.</summary>
|
||||
private static bool IsFloatingPoint(IWICImagingFactory factory, Guid pixelFormat)
|
||||
{
|
||||
IWICComponentInfo? info = null;
|
||||
try
|
||||
{
|
||||
info = factory.CreateComponentInfo(ref pixelFormat);
|
||||
return info is IWICPixelFormatInfo2 format && format.GetNumericRepresentation() is NumericFixedPoint or NumericFloat;
|
||||
}
|
||||
catch (COMException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Win32Com.Release(info);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool CanConvert(IWICFormatConverter converter, Guid from, Guid to)
|
||||
{
|
||||
converter.CanConvert(ref from, ref to, out var canConvert);
|
||||
return canConvert != 0;
|
||||
}
|
||||
|
||||
/// <summary>Pulls the converted pixels in bands of rows (bounded memory) and writes oriented linear planes.</summary>
|
||||
private static unsafe ImageBuffer CopyToPlanes(IWICBitmapSource source, int width, int height, bool floating, OrientationMap map, CancellationToken cancellationToken)
|
||||
{
|
||||
var stride = checked(width * (floating ? 16 : 8));
|
||||
var bandRows = Math.Clamp(BandBytes / stride, 1, height);
|
||||
var image = new ImageBuffer(map.Width, map.Height, 3, clear: false);
|
||||
var band = ArrayPool<byte>.Shared.Rent(checked(stride * bandRows));
|
||||
try
|
||||
{
|
||||
var r = image.Plane(0);
|
||||
var g = image.Plane(1);
|
||||
var b = image.Plane(2);
|
||||
fixed (byte* bandPointer = band)
|
||||
{
|
||||
for (var top = 0; top < height; top += bandRows)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
var rows = Math.Min(bandRows, height - top);
|
||||
var rect = new WicRect { X = 0, Y = top, Width = width, Height = rows };
|
||||
source.CopyPixels(ref rect, (uint)stride, (uint)(stride * rows), (nint)bandPointer);
|
||||
for (var row = 0; row < rows; row++)
|
||||
{
|
||||
var line = new ReadOnlySpan<byte>(bandPointer + (row * stride), stride);
|
||||
var index = map.IndexOf(0, top + row);
|
||||
if (floating) WriteFloatRow(MemoryMarshal.Cast<byte, float>(line), index, map.StepX, r, g, b);
|
||||
else WriteSrgb16Row(MemoryMarshal.Cast<byte, ushort>(line), index, map.StepX, r, g, b);
|
||||
}
|
||||
}
|
||||
}
|
||||
return image;
|
||||
}
|
||||
catch
|
||||
{
|
||||
image.Dispose();
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<byte>.Shared.Return(band);
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteSrgb16Row(ReadOnlySpan<ushort> rgba, int index, int step, Span<float> r, Span<float> g, Span<float> b)
|
||||
{
|
||||
for (var i = 0; i < rgba.Length; i += 4, index += step)
|
||||
{
|
||||
r[index] = ColorSpace.Linear16(rgba[i]);
|
||||
g[index] = ColorSpace.Linear16(rgba[i + 1]);
|
||||
b[index] = ColorSpace.Linear16(rgba[i + 2]);
|
||||
}
|
||||
}
|
||||
|
||||
private static void WriteFloatRow(ReadOnlySpan<float> rgba, int index, int step, Span<float> r, Span<float> g, Span<float> b)
|
||||
{
|
||||
// scRGB can carry negative (out-of-gamut) components; the pipeline's range starts at 0.
|
||||
for (var i = 0; i < rgba.Length; i += 4, index += step)
|
||||
{
|
||||
r[index] = MathF.Max(rgba[i], 0f);
|
||||
g[index] = MathF.Max(rgba[i + 1], 0f);
|
||||
b[index] = MathF.Max(rgba[i + 2], 0f);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Titano.Core.Windows.Interop;
|
||||
|
||||
namespace Titano.Core.Windows.Wic;
|
||||
|
||||
/// <summary>Process-wide WIC imaging factory (free-threaded; safe to call from any thread).</summary>
|
||||
internal static class WicFactory
|
||||
{
|
||||
private static readonly Lazy<IWICImagingFactory> Shared = new(Create);
|
||||
|
||||
public static IWICImagingFactory Instance => Shared.Value;
|
||||
|
||||
private static IWICImagingFactory Create()
|
||||
{
|
||||
// Create it in the MTA: a factory born on a UI thread's STA could make worker threads marshal every
|
||||
// call into that apartment.
|
||||
if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
|
||||
return Task.Run(Create).GetAwaiter().GetResult();
|
||||
|
||||
var iid = typeof(IWICImagingFactory).GUID;
|
||||
var hr = Win32Com.TryCreateInstance(WicGuids.ImagingFactory2, iid, out var instance);
|
||||
// WICImagingFactory2 is missing only on Windows 7 without the platform update.
|
||||
if (hr == Win32Com.REGDB_E_CLASSNOTREG) hr = Win32Com.TryCreateInstance(WicGuids.ImagingFactory1, iid, out instance);
|
||||
Marshal.ThrowExceptionForHR(hr);
|
||||
return (IWICImagingFactory)instance!;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
namespace Titano.Core.Windows.Wic;
|
||||
|
||||
/// <summary>Class, vendor and pixel-format identifiers from wincodec.h.</summary>
|
||||
internal static class WicGuids
|
||||
{
|
||||
public static readonly Guid ImagingFactory1 = new("cacaf262-9370-4615-a13b-9f5539da4c0a");
|
||||
public static readonly Guid ImagingFactory2 = new("317d06e8-5f24-433d-bdf7-79ce68d8abc2");
|
||||
|
||||
/// <summary>CLSID_WICRAWDecoder: the camera RAW decoder (Raw Image Extension; also the CLSID of the older in-box codec).</summary>
|
||||
public static readonly Guid RawDecoder = new("41945702-8302-44a6-9445-ac98e8afa086");
|
||||
|
||||
/// <summary>CLSID_WICHeifDecoder (HEIF Image Extensions; decodes HEVC- and AV1-coded HEIF).</summary>
|
||||
public static readonly Guid HeifDecoder = new("e9a4a80a-44fe-4de4-8971-7150b10a5199");
|
||||
|
||||
/// <summary>CLSID_WICWebpDecoder (WebP Image Extensions).</summary>
|
||||
public static readonly Guid WebpDecoder = new("7693e886-51c9-4070-8419-9f70738ec8fa");
|
||||
|
||||
public static readonly Guid VendorMicrosoft = new("f0e749ca-edef-4589-a73a-ee0e626a2a2b");
|
||||
public static readonly Guid VendorMicrosoftBuiltIn = new("257a30fd-06b6-462b-aea4-63f70b86e533");
|
||||
|
||||
/// <summary>16-bit unsigned RGBA, sRGB-encoded like every WIC integer format.</summary>
|
||||
public static readonly Guid PixelFormat64bppRGBA = new("6fddc324-4e03-4bfe-b185-3d77768dc916");
|
||||
|
||||
/// <summary>32-bit float RGBA, scRGB (linear light, Rec.709 primaries) like every WIC float format.</summary>
|
||||
public static readonly Guid PixelFormat128bppRGBAFloat = new("6fddc324-4e03-4bfe-b185-3d77768dc919");
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Titano.Core.Windows.Interop;
|
||||
|
||||
namespace Titano.Core.Windows.Wic;
|
||||
|
||||
// Windows Imaging Component interfaces, vtable order as in wincodec.h / objidl.h.
|
||||
// [ComImport] interfaces do not inherit vtable slots from their C# base, so every derived interface
|
||||
// redeclares the base methods (with `new`) in their native order before its own. Interfaces are declared
|
||||
// up to the last slot Titano calls (a vtable prefix is valid); intermediate slots Titano never calls keep
|
||||
// their native shape with pointer-sized placeholders for interfaces it does not model. Methods whose
|
||||
// failure is an expected outcome use [PreserveSig]; the others throw COMException on a failed HRESULT.
|
||||
|
||||
/// <summary>WICDecodeOptions.</summary>
|
||||
internal enum WicDecodeOptions
|
||||
{
|
||||
MetadataCacheOnDemand = 0,
|
||||
MetadataCacheOnLoad = 1,
|
||||
}
|
||||
|
||||
/// <summary>WICRect.</summary>
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct WicRect
|
||||
{
|
||||
public int X;
|
||||
public int Y;
|
||||
public int Width;
|
||||
public int Height;
|
||||
}
|
||||
|
||||
[ComImport]
|
||||
[Guid("ec5ec8a9-c395-4314-9c77-54d7a935ff70")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
internal interface IWICImagingFactory
|
||||
{
|
||||
[PreserveSig]
|
||||
int CreateDecoderFromFilename(nint fileName, nint vendor, uint desiredAccess, WicDecodeOptions options, out nint decoder);
|
||||
|
||||
[PreserveSig]
|
||||
int CreateDecoderFromStream(nint stream, nint vendor, WicDecodeOptions options, out IWICBitmapDecoder? decoder);
|
||||
|
||||
[PreserveSig]
|
||||
int CreateDecoderFromFileHandle(nint file, nint vendor, WicDecodeOptions options, out nint decoder);
|
||||
|
||||
IWICComponentInfo CreateComponentInfo(ref Guid clsid);
|
||||
|
||||
[PreserveSig]
|
||||
int CreateDecoder(ref Guid containerFormat, nint vendor, out nint decoder);
|
||||
|
||||
/// <summary>Returns an owned IWICBitmapEncoder pointer (used by the tests to synthesise JPEG fixtures).</summary>
|
||||
[PreserveSig]
|
||||
int CreateEncoder(ref Guid containerFormat, nint vendor, out nint encoder);
|
||||
|
||||
[PreserveSig]
|
||||
int CreatePalette(out nint palette);
|
||||
|
||||
IWICFormatConverter CreateFormatConverter();
|
||||
|
||||
IWICBitmapScaler CreateBitmapScaler();
|
||||
|
||||
[PreserveSig]
|
||||
int CreateBitmapClipper(out nint clipper);
|
||||
|
||||
[PreserveSig]
|
||||
int CreateBitmapFlipRotator(out nint flipRotator);
|
||||
|
||||
[PreserveSig]
|
||||
int CreateStream(out nint stream);
|
||||
|
||||
[PreserveSig]
|
||||
int CreateColorContext(out nint colorContext);
|
||||
|
||||
[PreserveSig]
|
||||
int CreateColorTransformer(out nint colorTransform);
|
||||
|
||||
[PreserveSig]
|
||||
int CreateBitmap(uint width, uint height, ref Guid pixelFormat, int cacheOption, out nint bitmap);
|
||||
|
||||
[PreserveSig]
|
||||
int CreateBitmapFromSource(nint source, int cacheOption, out nint bitmap);
|
||||
|
||||
[PreserveSig]
|
||||
int CreateBitmapFromSourceRect(nint source, uint x, uint y, uint width, uint height, out nint bitmap);
|
||||
|
||||
[PreserveSig]
|
||||
int CreateBitmapFromMemory(uint width, uint height, ref Guid pixelFormat, uint stride, uint bufferSize, nint buffer, out nint bitmap);
|
||||
|
||||
[PreserveSig]
|
||||
int CreateBitmapFromHBITMAP(nint bitmapHandle, nint paletteHandle, int alphaOption, out nint bitmap);
|
||||
|
||||
[PreserveSig]
|
||||
int CreateBitmapFromHICON(nint iconHandle, out nint bitmap);
|
||||
|
||||
IEnumUnknown CreateComponentEnumerator(uint componentTypes, uint options);
|
||||
}
|
||||
|
||||
[ComImport]
|
||||
[Guid("00000100-0000-0000-c000-000000000046")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
internal interface IEnumUnknown
|
||||
{
|
||||
/// <summary>S_OK when <paramref name="count"/> items were fetched, S_FALSE at the end.</summary>
|
||||
[PreserveSig]
|
||||
int Next(uint count, out nint element, out uint fetched);
|
||||
}
|
||||
|
||||
[ComImport]
|
||||
[Guid("9edde9e7-8dee-47ea-99df-e6faf2ed44bf")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
internal interface IWICBitmapDecoder
|
||||
{
|
||||
[PreserveSig]
|
||||
int QueryCapability(nint stream, out uint capability);
|
||||
|
||||
[PreserveSig]
|
||||
int Initialize(nint stream, WicDecodeOptions options);
|
||||
|
||||
Guid GetContainerFormat();
|
||||
|
||||
[PreserveSig]
|
||||
int GetDecoderInfo(out nint decoderInfo);
|
||||
|
||||
[PreserveSig]
|
||||
int CopyPalette(nint palette);
|
||||
|
||||
[PreserveSig]
|
||||
int GetMetadataQueryReader(out nint reader);
|
||||
|
||||
[PreserveSig]
|
||||
int GetPreview(out nint preview);
|
||||
|
||||
[PreserveSig]
|
||||
int GetColorContexts(uint count, nint colorContexts, out uint actualCount);
|
||||
|
||||
[PreserveSig]
|
||||
int GetThumbnail(out nint thumbnail);
|
||||
|
||||
uint GetFrameCount();
|
||||
|
||||
IWICBitmapFrameDecode GetFrame(uint index);
|
||||
}
|
||||
|
||||
[ComImport]
|
||||
[Guid("00000120-a8f2-4877-ba0a-fd2b6645fb94")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
internal interface IWICBitmapSource
|
||||
{
|
||||
void GetSize(out uint width, out uint height);
|
||||
|
||||
Guid GetPixelFormat();
|
||||
|
||||
void GetResolution(out double dpiX, out double dpiY);
|
||||
|
||||
[PreserveSig]
|
||||
int CopyPalette(nint palette);
|
||||
|
||||
void CopyPixels(ref WicRect rect, uint stride, uint bufferSize, nint buffer);
|
||||
}
|
||||
|
||||
[ComImport]
|
||||
[Guid("3b16811b-6a43-4ec9-a813-3d930c13b940")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
internal interface IWICBitmapFrameDecode : IWICBitmapSource
|
||||
{
|
||||
new void GetSize(out uint width, out uint height);
|
||||
|
||||
new Guid GetPixelFormat();
|
||||
|
||||
new void GetResolution(out double dpiX, out double dpiY);
|
||||
|
||||
[PreserveSig]
|
||||
new int CopyPalette(nint palette);
|
||||
|
||||
new void CopyPixels(ref WicRect rect, uint stride, uint bufferSize, nint buffer);
|
||||
|
||||
/// <summary>Fails (e.g. WINCODEC_ERR_UNSUPPORTEDOPERATION) for formats without metadata.</summary>
|
||||
[PreserveSig]
|
||||
int GetMetadataQueryReader(out IWICMetadataQueryReader? reader);
|
||||
}
|
||||
|
||||
[ComImport]
|
||||
[Guid("00000301-a8f2-4877-ba0a-fd2b6645fb94")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
internal interface IWICFormatConverter : IWICBitmapSource
|
||||
{
|
||||
new void GetSize(out uint width, out uint height);
|
||||
|
||||
new Guid GetPixelFormat();
|
||||
|
||||
new void GetResolution(out double dpiX, out double dpiY);
|
||||
|
||||
[PreserveSig]
|
||||
new int CopyPalette(nint palette);
|
||||
|
||||
new void CopyPixels(ref WicRect rect, uint stride, uint bufferSize, nint buffer);
|
||||
|
||||
void Initialize(IWICBitmapSource source, ref Guid destinationFormat, int dither, nint palette, double alphaThresholdPercent, int paletteTranslate);
|
||||
|
||||
void CanConvert(ref Guid sourceFormat, ref Guid destinationFormat, out int canConvert);
|
||||
}
|
||||
|
||||
[ComImport]
|
||||
[Guid("00000302-a8f2-4877-ba0a-fd2b6645fb94")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
internal interface IWICBitmapScaler : IWICBitmapSource
|
||||
{
|
||||
new void GetSize(out uint width, out uint height);
|
||||
|
||||
new Guid GetPixelFormat();
|
||||
|
||||
new void GetResolution(out double dpiX, out double dpiY);
|
||||
|
||||
[PreserveSig]
|
||||
new int CopyPalette(nint palette);
|
||||
|
||||
new void CopyPixels(ref WicRect rect, uint stride, uint bufferSize, nint buffer);
|
||||
|
||||
void Initialize(IWICBitmapSource source, uint width, uint height, int interpolationMode);
|
||||
}
|
||||
|
||||
[ComImport]
|
||||
[Guid("30989668-e1c9-4597-b395-458eedb808df")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
internal interface IWICMetadataQueryReader
|
||||
{
|
||||
Guid GetContainerFormat();
|
||||
|
||||
[PreserveSig]
|
||||
int GetLocation(uint capacity, nint buffer, out uint length);
|
||||
|
||||
/// <summary>Fails with WINCODEC_ERR_PROPERTYNOTFOUND when the query matches nothing.</summary>
|
||||
[PreserveSig]
|
||||
int GetMetadataByName([MarshalAs(UnmanagedType.LPWStr)] string name, ref PropVariant value);
|
||||
}
|
||||
|
||||
/// <summary>String getters of the component-info family: capacity 0 + null buffer returns the required length.</summary>
|
||||
internal unsafe delegate int WicStringGetter(uint capacity, char* buffer, out uint length);
|
||||
|
||||
[ComImport]
|
||||
[Guid("23bc3f0a-698b-4357-886b-f24d50671334")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
internal unsafe interface IWICComponentInfo
|
||||
{
|
||||
uint GetComponentType();
|
||||
|
||||
Guid GetCLSID();
|
||||
|
||||
uint GetSigningStatus();
|
||||
|
||||
[PreserveSig]
|
||||
int GetAuthor(uint capacity, char* buffer, out uint length);
|
||||
|
||||
Guid GetVendorGUID();
|
||||
|
||||
[PreserveSig]
|
||||
int GetVersion(uint capacity, char* buffer, out uint length);
|
||||
|
||||
[PreserveSig]
|
||||
int GetSpecVersion(uint capacity, char* buffer, out uint length);
|
||||
|
||||
[PreserveSig]
|
||||
int GetFriendlyName(uint capacity, char* buffer, out uint length);
|
||||
}
|
||||
|
||||
/// <summary>IWICPixelFormatInfo2 (IWICComponentInfo → IWICPixelFormatInfo → IWICPixelFormatInfo2).</summary>
|
||||
[ComImport]
|
||||
[Guid("a9db33a2-af5f-43c7-b679-74f5984b5aa4")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
internal unsafe interface IWICPixelFormatInfo2 : IWICComponentInfo
|
||||
{
|
||||
new uint GetComponentType();
|
||||
|
||||
new Guid GetCLSID();
|
||||
|
||||
new uint GetSigningStatus();
|
||||
|
||||
[PreserveSig]
|
||||
new int GetAuthor(uint capacity, char* buffer, out uint length);
|
||||
|
||||
new Guid GetVendorGUID();
|
||||
|
||||
[PreserveSig]
|
||||
new int GetVersion(uint capacity, char* buffer, out uint length);
|
||||
|
||||
[PreserveSig]
|
||||
new int GetSpecVersion(uint capacity, char* buffer, out uint length);
|
||||
|
||||
[PreserveSig]
|
||||
new int GetFriendlyName(uint capacity, char* buffer, out uint length);
|
||||
|
||||
Guid GetFormatGUID();
|
||||
|
||||
[PreserveSig]
|
||||
int GetColorContext(out nint colorContext);
|
||||
|
||||
uint GetBitsPerPixel();
|
||||
|
||||
uint GetChannelCount();
|
||||
|
||||
[PreserveSig]
|
||||
int GetChannelMask(uint channel, uint maskSize, nint mask, out uint actualSize);
|
||||
|
||||
void SupportsTransparency(out int supportsTransparency);
|
||||
|
||||
/// <summary>WICPixelFormatNumericRepresentation: 2 unsigned integer, 4 fixed point, 5 float.</summary>
|
||||
uint GetNumericRepresentation();
|
||||
}
|
||||
|
||||
/// <summary>IWICBitmapDecoderInfo (IWICComponentInfo → IWICBitmapCodecInfo → IWICBitmapDecoderInfo).</summary>
|
||||
[ComImport]
|
||||
[Guid("d8cd007f-d08f-4191-9bfc-236ea7f0e4b5")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
internal unsafe interface IWICBitmapDecoderInfo : IWICComponentInfo
|
||||
{
|
||||
new uint GetComponentType();
|
||||
|
||||
new Guid GetCLSID();
|
||||
|
||||
new uint GetSigningStatus();
|
||||
|
||||
[PreserveSig]
|
||||
new int GetAuthor(uint capacity, char* buffer, out uint length);
|
||||
|
||||
new Guid GetVendorGUID();
|
||||
|
||||
[PreserveSig]
|
||||
new int GetVersion(uint capacity, char* buffer, out uint length);
|
||||
|
||||
[PreserveSig]
|
||||
new int GetSpecVersion(uint capacity, char* buffer, out uint length);
|
||||
|
||||
[PreserveSig]
|
||||
new int GetFriendlyName(uint capacity, char* buffer, out uint length);
|
||||
|
||||
Guid GetContainerFormat();
|
||||
|
||||
[PreserveSig]
|
||||
int GetPixelFormats(uint count, nint pixelFormats, out uint actualCount);
|
||||
|
||||
[PreserveSig]
|
||||
int GetColorManagementVersion(uint capacity, char* buffer, out uint length);
|
||||
|
||||
[PreserveSig]
|
||||
int GetDeviceManufacturer(uint capacity, char* buffer, out uint length);
|
||||
|
||||
[PreserveSig]
|
||||
int GetDeviceModels(uint capacity, char* buffer, out uint length);
|
||||
|
||||
[PreserveSig]
|
||||
int GetMimeTypes(uint capacity, char* buffer, out uint length);
|
||||
|
||||
/// <summary>Comma-separated list such as ".jpg,.jpeg,.jpe,.jfif".</summary>
|
||||
[PreserveSig]
|
||||
int GetFileExtensions(uint capacity, char* buffer, out uint length);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Titano.Core.Windows.Interop;
|
||||
|
||||
namespace Titano.Core.Windows.Window;
|
||||
|
||||
/// <summary>DWMWA_SYSTEMBACKDROP_TYPE values (Windows 11 22H2+).</summary>
|
||||
public enum SystemBackdrop
|
||||
{
|
||||
Auto = 0,
|
||||
None = 1,
|
||||
Mica = 2,
|
||||
Acrylic = 3,
|
||||
MicaAlt = 4,
|
||||
}
|
||||
|
||||
/// <summary>DWMWA_WINDOW_CORNER_PREFERENCE values (Windows 11+).</summary>
|
||||
public enum WindowCornerPreference
|
||||
{
|
||||
Default = 0,
|
||||
DoNotRound = 1,
|
||||
Round = 2,
|
||||
RoundSmall = 3,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Window chrome through DwmSetWindowAttribute (BRIEF §2.1). Every helper returns false, without throwing, when the
|
||||
/// handle is null or stale or this Windows build does not support the attribute, so callers need no version checks.
|
||||
/// </summary>
|
||||
public static partial class DwmWindow
|
||||
{
|
||||
private const uint DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 = 19;
|
||||
private const uint DWMWA_USE_IMMERSIVE_DARK_MODE = 20;
|
||||
private const uint DWMWA_WINDOW_CORNER_PREFERENCE = 33;
|
||||
private const uint DWMWA_BORDER_COLOR = 34;
|
||||
private const uint DWMWA_CAPTION_COLOR = 35;
|
||||
private const uint DWMWA_SYSTEMBACKDROP_TYPE = 38;
|
||||
private const uint DWMWA_COLOR_DEFAULT = 0xFFFFFFFF;
|
||||
|
||||
/// <summary>Dark title bar (attribute 20; 19 on Windows 10 1809–1909).</summary>
|
||||
public static bool SetDarkMode(nint window, bool enabled)
|
||||
{
|
||||
if (!Win32Window.Exists(window)) return false;
|
||||
var value = enabled ? 1 : 0;
|
||||
return Set(window, DWMWA_USE_IMMERSIVE_DARK_MODE, value) || Set(window, DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1, value);
|
||||
}
|
||||
|
||||
public static bool SetBackdrop(nint window, SystemBackdrop backdrop) =>
|
||||
Win32Window.Exists(window) && Set(window, DWMWA_SYSTEMBACKDROP_TYPE, (int)backdrop);
|
||||
|
||||
public static bool SetCornerPreference(nint window, WindowCornerPreference preference) =>
|
||||
Win32Window.Exists(window) && Set(window, DWMWA_WINDOW_CORNER_PREFERENCE, (int)preference);
|
||||
|
||||
/// <summary>Title bar colour; null restores the system default.</summary>
|
||||
public static bool SetCaptionColor(nint window, RgbColor? color) =>
|
||||
Win32Window.Exists(window) && Set(window, DWMWA_CAPTION_COLOR, unchecked((int)(color?.ToColorRef() ?? DWMWA_COLOR_DEFAULT)));
|
||||
|
||||
/// <summary>Window border colour; null restores the system default.</summary>
|
||||
public static bool SetBorderColor(nint window, RgbColor? color) =>
|
||||
Win32Window.Exists(window) && Set(window, DWMWA_BORDER_COLOR, unchecked((int)(color?.ToColorRef() ?? DWMWA_COLOR_DEFAULT)));
|
||||
|
||||
private static unsafe bool Set(nint window, uint attribute, int value) =>
|
||||
DwmSetWindowAttribute(window, attribute, &value, sizeof(int)) >= 0;
|
||||
|
||||
[LibraryImport("dwmapi.dll")]
|
||||
private static unsafe partial int DwmSetWindowAttribute(nint window, uint attribute, void* value, uint size);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
namespace Titano.Core.Windows.Window;
|
||||
|
||||
/// <summary>An opaque 8-bit sRGB colour, as used by DWM window chrome and the system accent.</summary>
|
||||
public readonly record struct RgbColor(byte R, byte G, byte B)
|
||||
{
|
||||
/// <summary>Win32 COLORREF layout 0x00BBGGRR.</summary>
|
||||
internal uint ToColorRef() => R | ((uint)G << 8) | ((uint)B << 16);
|
||||
|
||||
/// <summary>From 0xAABBGGRR (COLORREF with alpha, as stored in the registry's AccentColor).</summary>
|
||||
internal static RgbColor FromAbgr(uint value) => new((byte)value, (byte)(value >> 8), (byte)(value >> 16));
|
||||
|
||||
/// <summary>From 0xAARRGGBB (DwmGetColorizationColor).</summary>
|
||||
internal static RgbColor FromArgb(uint value) => new((byte)(value >> 16), (byte)(value >> 8), (byte)value);
|
||||
|
||||
public override string ToString() => $"#{R:X2}{G:X2}{B:X2}";
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace Titano.Core.Windows.Window;
|
||||
|
||||
/// <summary>The user's light/dark app mode and accent colour, read on demand (see <see cref="SystemThemeWatcher"/> for changes).</summary>
|
||||
public static partial class SystemTheme
|
||||
{
|
||||
internal const string PersonalizeKey = @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize";
|
||||
internal const string DwmKey = @"Software\Microsoft\Windows\DWM";
|
||||
|
||||
/// <summary>HKCU <c>…\Themes\Personalize\AppsUseLightTheme</c>; true when absent (the Windows default).</summary>
|
||||
public static bool AppsUseLightTheme
|
||||
{
|
||||
get
|
||||
{
|
||||
using var key = Registry.CurrentUser.OpenSubKey(PersonalizeKey);
|
||||
return key?.GetValue("AppsUseLightTheme") is not int value || value != 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The accent colour: HKCU <c>…\DWM\AccentColor</c>, else DwmGetColorizationColor; null when neither is available.</summary>
|
||||
public static RgbColor? AccentColor
|
||||
{
|
||||
get
|
||||
{
|
||||
using (var key = Registry.CurrentUser.OpenSubKey(DwmKey))
|
||||
{
|
||||
if (key?.GetValue("AccentColor") is int abgr) return RgbColor.FromAbgr(unchecked((uint)abgr));
|
||||
}
|
||||
return DwmGetColorizationColor(out var argb, out _) >= 0 ? RgbColor.FromArgb(argb) : null;
|
||||
}
|
||||
}
|
||||
|
||||
[LibraryImport("dwmapi.dll")]
|
||||
private static partial int DwmGetColorizationColor(out uint colorization, out int opaqueBlend);
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
using Titano.Core.Diagnostics;
|
||||
|
||||
namespace Titano.Core.Windows.Window;
|
||||
|
||||
/// <summary>
|
||||
/// Raises <see cref="Changed"/> when the app light/dark mode or the accent colour changes, using
|
||||
/// RegNotifyChangeKeyValue on a dedicated background thread (the registration lives as long as that thread).
|
||||
/// Handlers run on that thread; marshal to the UI dispatcher.
|
||||
/// </summary>
|
||||
public sealed partial class SystemThemeWatcher : IDisposable
|
||||
{
|
||||
private const uint REG_NOTIFY_CHANGE_LAST_SET = 0x4;
|
||||
|
||||
private readonly ManualResetEvent _stop = new(false);
|
||||
private readonly Thread _thread;
|
||||
private int _disposed;
|
||||
|
||||
public SystemThemeWatcher()
|
||||
{
|
||||
_thread = new Thread(Run) { IsBackground = true, Name = "Titano theme watcher" };
|
||||
_thread.Start();
|
||||
}
|
||||
|
||||
/// <summary>Raised once per effective change of <see cref="SystemTheme.AppsUseLightTheme"/> or <see cref="SystemTheme.AccentColor"/>.</summary>
|
||||
public event EventHandler? Changed;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) != 0) return;
|
||||
_stop.Set();
|
||||
// From a Changed handler the loop is still running on this thread and will observe the stop signal itself.
|
||||
if (_thread == Thread.CurrentThread) return;
|
||||
_thread.Join();
|
||||
_stop.Dispose();
|
||||
}
|
||||
|
||||
private void Run()
|
||||
{
|
||||
using var personalize = Registry.CurrentUser.OpenSubKey(SystemTheme.PersonalizeKey);
|
||||
using var dwm = Registry.CurrentUser.OpenSubKey(SystemTheme.DwmKey);
|
||||
var keys = new[] { personalize, dwm }.OfType<RegistryKey>().ToArray();
|
||||
var signals = keys.Select(_ => new AutoResetEvent(false)).ToArray();
|
||||
try
|
||||
{
|
||||
for (var i = 0; i < keys.Length; i++) Arm(keys[i], signals[i]);
|
||||
WaitHandle[] handles = [_stop, .. signals];
|
||||
var last = (SystemTheme.AppsUseLightTheme, SystemTheme.AccentColor);
|
||||
while (true)
|
||||
{
|
||||
var index = WaitHandle.WaitAny(handles);
|
||||
if (index == 0) return;
|
||||
// Re-arm before reading so a change landing in between still signals.
|
||||
Arm(keys[index - 1], signals[index - 1]);
|
||||
var now = (SystemTheme.AppsUseLightTheme, SystemTheme.AccentColor);
|
||||
if (now == last) continue;
|
||||
last = now;
|
||||
RaiseChanged();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
foreach (var signal in signals) signal.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static void Arm(RegistryKey key, AutoResetEvent signal)
|
||||
{
|
||||
var result = RegNotifyChangeKeyValue(key.Handle, false, REG_NOTIFY_CHANGE_LAST_SET, signal.SafeWaitHandle, true);
|
||||
if (result != 0) Log.Warning("theme", $"RegNotifyChangeKeyValue failed for {key.Name} (error {result}).");
|
||||
}
|
||||
|
||||
private void RaiseChanged()
|
||||
{
|
||||
try
|
||||
{
|
||||
Changed?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// An exception escaping this thread would terminate the process.
|
||||
Log.Error("theme", "A theme Changed handler failed", ex);
|
||||
}
|
||||
}
|
||||
|
||||
[LibraryImport("advapi32.dll")]
|
||||
private static partial int RegNotifyChangeKeyValue(
|
||||
SafeRegistryHandle key,
|
||||
[MarshalAs(UnmanagedType.Bool)] bool watchSubtree,
|
||||
uint notifyFilter,
|
||||
SafeWaitHandle eventHandle,
|
||||
[MarshalAs(UnmanagedType.Bool)] bool asynchronous);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Windows.Codecs;
|
||||
using Titano.Core.Windows.Wic;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Windows.Tests.Codecs;
|
||||
|
||||
public sealed class CodecInventoryTests
|
||||
{
|
||||
private static readonly WicDecoderInfo Jpeg = Decoder("JPEG Decoder", Guid.NewGuid(), WicGuids.VendorMicrosoftBuiltIn, ".jpeg,.jpe,.jpg,.jfif,.exif");
|
||||
private static readonly WicDecoderInfo InBoxDng = Decoder("DNG Decoder", Guid.NewGuid(), WicGuids.VendorMicrosoftBuiltIn, ".dng");
|
||||
private static readonly WicDecoderInfo Raw = Decoder("Microsoft Raw Image Decoder", WicGuids.RawDecoder, WicGuids.VendorMicrosoft, ".arw,.cr2,.cr3,.dng,.nef,.raf");
|
||||
private static readonly WicDecoderInfo Heif = Decoder("HEIF Decoder", WicGuids.HeifDecoder, WicGuids.VendorMicrosoft, ".heic,.heif,.hif");
|
||||
private static readonly WicDecoderInfo Webp = Decoder("WebP Decoder", WicGuids.WebpDecoder, WicGuids.VendorMicrosoft, ".webp");
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void DetectFindsTheBuiltInDecoders()
|
||||
{
|
||||
var inventory = CodecInventory.Detect();
|
||||
Assert.NotEmpty(inventory.Decoders);
|
||||
foreach (var format in new[] { ImageFileFormat.Jpeg, ImageFileFormat.Png, ImageFileFormat.Tiff })
|
||||
{
|
||||
var support = inventory.For(format);
|
||||
Assert.True(support.IsNative, $"{format} should decode natively through WIC");
|
||||
var decoder = Assert.NotNull(support.Decoder);
|
||||
Assert.False(string.IsNullOrWhiteSpace(decoder.FriendlyName), $"{format} decoder has no name");
|
||||
Assert.NotEqual(Guid.Empty, decoder.ContainerFormat);
|
||||
Assert.Empty(support.MissingExtensions);
|
||||
}
|
||||
Assert.Equal(ImageFormatInfo.Known.Count, inventory.Formats.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RawNeedsTheRawImageExtension()
|
||||
{
|
||||
var inventory = Inventory([Jpeg, InBoxDng, Classified(Raw, rawExtensionInstalled: false)]);
|
||||
var dng = inventory.For(ImageFileFormat.Dng);
|
||||
Assert.False(dng.IsNative);
|
||||
Assert.Equal<string?>("DNG Decoder", dng.Decoder?.FriendlyName);
|
||||
Assert.SequenceEqual([StoreExtension.Get(StoreExtensionKind.RawImage)], dng.MissingExtensions);
|
||||
Assert.False(inventory.IsNative(ImageFileFormat.Cr3));
|
||||
Assert.Contains(StoreExtension.Get(StoreExtensionKind.RawImage), inventory.MissingExtensions);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RawIsNativeThroughTheExtension()
|
||||
{
|
||||
var inventory = Inventory([Jpeg, InBoxDng, Classified(Raw, rawExtensionInstalled: true)]);
|
||||
Assert.True(inventory.IsNative(ImageFileFormat.Dng));
|
||||
Assert.Equal<StoreExtensionKind?>(StoreExtensionKind.RawImage, inventory.For(ImageFileFormat.Dng).Decoder?.Extension);
|
||||
Assert.True(inventory.IsNative(ImageFileFormat.Cr3));
|
||||
// Installed but without this extension registered: nothing to install, still not native.
|
||||
var gpr = inventory.For(ImageFileFormat.Gpr);
|
||||
Assert.False(gpr.IsNative);
|
||||
Assert.Empty(gpr.MissingExtensions);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void HeifNeedsAnHevcDecoder()
|
||||
{
|
||||
var withoutHevc = Inventory([Jpeg, Classified(Heif)]).For(ImageFileFormat.Heif);
|
||||
Assert.False(withoutHevc.IsNative);
|
||||
Assert.SequenceEqual([StoreExtension.Get(StoreExtensionKind.HevcVideo)], withoutHevc.MissingExtensions);
|
||||
|
||||
Assert.True(Inventory([Jpeg, Classified(Heif)], hevc: true).IsNative(ImageFileFormat.Heif));
|
||||
|
||||
var nothing = Inventory([Jpeg]).For(ImageFileFormat.Heif);
|
||||
Assert.SequenceEqual(
|
||||
[StoreExtension.Get(StoreExtensionKind.HeifImage), StoreExtension.Get(StoreExtensionKind.HevcVideo)],
|
||||
nothing.MissingExtensions);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AvifUsesTheHeifDecoderWithAnAv1Decoder()
|
||||
{
|
||||
var withoutAv1 = Inventory([Classified(Heif)], hevc: true).For(ImageFileFormat.Avif);
|
||||
Assert.False(withoutAv1.IsNative);
|
||||
Assert.Equal<string?>("HEIF Decoder", withoutAv1.Decoder?.FriendlyName);
|
||||
Assert.SequenceEqual([StoreExtension.Get(StoreExtensionKind.Av1Video)], withoutAv1.MissingExtensions);
|
||||
|
||||
Assert.True(Inventory([Classified(Heif)], av1: true).IsNative(ImageFileFormat.Avif));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void WebpNeedsTheWebpExtension()
|
||||
{
|
||||
Assert.SequenceEqual([StoreExtension.Get(StoreExtensionKind.WebpImage)], Inventory([Jpeg]).For(ImageFileFormat.WebP).MissingExtensions);
|
||||
Assert.True(Inventory([Jpeg, Classified(Webp)]).IsNative(ImageFileFormat.WebP));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void BuiltInFormatsNeverAskForExtensions()
|
||||
{
|
||||
var inventory = Inventory([Jpeg]);
|
||||
Assert.True(inventory.IsNative(ImageFileFormat.Jpeg));
|
||||
Assert.False(inventory.IsNative(ImageFileFormat.Png));
|
||||
Assert.Empty(inventory.For(ImageFileFormat.Png).MissingExtensions);
|
||||
Assert.False(inventory.IsNative(ImageFileFormat.Unknown));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ClassificationUsesClsidPackageAndVendor()
|
||||
{
|
||||
Assert.Null(CodecInventory.Classify(Raw, rawExtensionInstalled: false));
|
||||
Assert.Equal<StoreExtensionKind?>(StoreExtensionKind.RawImage, CodecInventory.Classify(Raw, rawExtensionInstalled: true));
|
||||
Assert.Equal<StoreExtensionKind?>(StoreExtensionKind.HeifImage, CodecInventory.Classify(Heif, false));
|
||||
Assert.Equal<StoreExtensionKind?>(StoreExtensionKind.WebpImage, CodecInventory.Classify(Webp, false));
|
||||
var avif = Decoder("AVIF Decoder", Guid.NewGuid(), WicGuids.VendorMicrosoft, ".avif");
|
||||
Assert.Equal<StoreExtensionKind?>(StoreExtensionKind.Av1Video, CodecInventory.Classify(avif, false));
|
||||
var thirdParty = Decoder("Other AVIF", Guid.NewGuid(), Guid.NewGuid(), ".avif");
|
||||
Assert.Null(CodecInventory.Classify(thirdParty, false));
|
||||
Assert.Null(CodecInventory.Classify(Jpeg, false));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void StoreLinksUseTheProductIds()
|
||||
{
|
||||
Assert.Equal(5, StoreExtension.All.Count);
|
||||
var raw = StoreExtension.Get(StoreExtensionKind.RawImage);
|
||||
Assert.Equal("ms-windows-store://pdp/?ProductId=9NCTDW2W1BH8", raw.StoreUri.AbsoluteUri);
|
||||
Assert.Equal("https://apps.microsoft.com/detail/9nctdw2w1bh8", raw.WebUri.AbsoluteUri);
|
||||
Assert.Equal("9PMMSR1CGPWG", StoreExtension.Get(StoreExtensionKind.HeifImage).ProductId);
|
||||
Assert.Equal("9NMZLZ57R3T7", StoreExtension.Get(StoreExtensionKind.HevcVideo).ProductId);
|
||||
Assert.Equal("9MVZQVXJBQ9V", StoreExtension.Get(StoreExtensionKind.Av1Video).ProductId);
|
||||
Assert.Equal("9PG2DK419DRG", StoreExtension.Get(StoreExtensionKind.WebpImage).ProductId);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ExtensionListsAreNormalised()
|
||||
{
|
||||
Assert.SequenceEqual(["jpg", "jpeg", "jfif"], WicDecoderInfo.ParseExtensions(".JPG, .jpeg;.jfif,,.jpg"));
|
||||
Assert.True(Jpeg.Handles(".JPG"));
|
||||
Assert.True(Jpeg.Handles("jfif"));
|
||||
Assert.False(Jpeg.Handles("png"));
|
||||
}
|
||||
|
||||
private static CodecInventory Inventory(WicDecoderInfo[] decoders, bool hevc = false, bool av1 = false) => new(decoders, hevc, av1);
|
||||
|
||||
private static WicDecoderInfo Classified(WicDecoderInfo decoder, bool rawExtensionInstalled = false) =>
|
||||
decoder with { Extension = CodecInventory.Classify(decoder, rawExtensionInstalled) };
|
||||
|
||||
private static WicDecoderInfo Decoder(string name, Guid clsid, Guid vendor, string extensions) =>
|
||||
new(name, clsid, Guid.NewGuid(), vendor, "1.0", WicDecoderInfo.ParseExtensions(extensions), null);
|
||||
}
|
||||
@@ -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<InvalidOperationException>(watcher.Start);
|
||||
watcher.Dispose();
|
||||
Assert.Throws<ObjectDisposedException>(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<ArgumentOutOfRangeException>(() => VolumeEjector.Eject('1'));
|
||||
|
||||
[Test]
|
||||
public void FormatDialogNeedsAnOwnerWindow() => Assert.Throws<ArgumentException>(() => 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<InvalidOperationException>(() => FormatDialog.Show(1, letter));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
using Titano.Core.Windows.Power;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Windows.Tests.Power;
|
||||
|
||||
[WindowsOnly]
|
||||
public sealed class SleepBlockerTests
|
||||
{
|
||||
[Test]
|
||||
[Timeout(10_000)]
|
||||
public async Task BlocksUntilDisposedFromAnyThread()
|
||||
{
|
||||
var blocker = new SleepBlocker();
|
||||
Assert.True(blocker.IsActive);
|
||||
// Disposing on another pool thread must still clear the request made by the owner thread.
|
||||
await Task.Run(blocker.Dispose);
|
||||
blocker.Dispose();
|
||||
}
|
||||
|
||||
[Test]
|
||||
[Timeout(10_000)]
|
||||
public void DisplayVariantWorks()
|
||||
{
|
||||
using var blocker = new SleepBlocker(keepDisplayOn: true);
|
||||
Assert.True(blocker.IsActive);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Titano.Core.Windows.Security;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Windows.Tests.Security;
|
||||
|
||||
[WindowsOnly]
|
||||
public sealed class DpapiTests
|
||||
{
|
||||
private static readonly byte[] Secret = Encoding.UTF8.GetBytes("titano-refresh-token-0123456789");
|
||||
|
||||
[Test]
|
||||
public void RoundTripsBytes()
|
||||
{
|
||||
var protectedData = Dpapi.Protect(Secret);
|
||||
Assert.False(protectedData.AsSpan().SequenceEqual(Secret), "ciphertext equals plaintext");
|
||||
Assert.Greater(protectedData.Length, Secret.Length);
|
||||
Assert.BytesEqual(Secret, Dpapi.Unprotect(protectedData));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void EntropyMustMatch()
|
||||
{
|
||||
var entropy = "Titano.Uploader.Token"u8.ToArray();
|
||||
var protectedData = Dpapi.Protect(Secret, entropy);
|
||||
Assert.BytesEqual(Secret, Dpapi.Unprotect(protectedData, entropy));
|
||||
Assert.Throws<CryptographicException>(() => Dpapi.Unprotect(protectedData, "other"u8));
|
||||
Assert.Throws<CryptographicException>(() => Dpapi.Unprotect(protectedData));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TamperedDataIsRejected()
|
||||
{
|
||||
var protectedData = Dpapi.Protect(Secret);
|
||||
protectedData[^1] ^= 0x5A;
|
||||
Assert.Throws<CryptographicException>(() => Dpapi.Unprotect(protectedData));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void RoundTripsStringsAndEmptyValues()
|
||||
{
|
||||
var stored = Dpapi.ProtectString("päss wörd ✓");
|
||||
Assert.Equal("päss wörd ✓", Dpapi.UnprotectString(stored));
|
||||
Assert.Equal(string.Empty, Dpapi.UnprotectString(Dpapi.ProtectString(string.Empty)));
|
||||
Assert.Empty(Dpapi.Unprotect(Dpapi.Protect([])));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
using Titano.Core.Windows.Shell;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Windows.Tests.Shell;
|
||||
|
||||
public sealed class AppPathsTests(TestContext context)
|
||||
{
|
||||
[Test]
|
||||
public void PortableMarkerKeepsDataNextToTheExecutable()
|
||||
{
|
||||
var app = context.CreateTempDirectory("app");
|
||||
var local = context.CreateTempDirectory("local");
|
||||
File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), "");
|
||||
|
||||
var paths = AppPaths.Resolve(app, local, []);
|
||||
Assert.True(paths.IsPortable);
|
||||
Assert.Equal(Path.Combine(app, "data"), paths.DataRoot);
|
||||
Assert.Equal(Path.Combine(app, "data", "titano.db"), paths.DatabasePath);
|
||||
Assert.False(paths.IsInSyncedFolder);
|
||||
|
||||
paths.CreateDirectories();
|
||||
Assert.True(Directory.Exists(paths.LogsDirectory));
|
||||
Assert.True(Directory.Exists(paths.CacheDirectory));
|
||||
Assert.True(Directory.Exists(paths.ThumbnailsDirectory));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void InstalledModeUsesLocalAppData()
|
||||
{
|
||||
var app = context.CreateTempDirectory("app");
|
||||
var local = context.CreateTempDirectory("local");
|
||||
|
||||
var paths = AppPaths.Resolve(app, local, []);
|
||||
Assert.False(paths.IsPortable);
|
||||
Assert.Equal(Path.Combine(local, "Titano"), paths.DataRoot);
|
||||
Assert.Equal(Path.Combine(local, "Titano", "titano.db"), paths.DatabasePath);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DataInsideOneDriveIsReportedAndRefused()
|
||||
{
|
||||
var oneDrive = context.CreateTempDirectory("onedrive");
|
||||
var app = Directory.CreateDirectory(Path.Combine(oneDrive, "Tools", "Titano")).FullName;
|
||||
File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), "");
|
||||
|
||||
var paths = AppPaths.Resolve(app, context.CreateTempDirectory("local"), [oneDrive]);
|
||||
Assert.True(paths.IsInSyncedFolder);
|
||||
Assert.Equal<string?>(oneDrive, paths.SyncedFolder);
|
||||
Assert.Throws<InvalidOperationException>(paths.CreateDirectories);
|
||||
Assert.False(Directory.Exists(paths.DataRoot));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SyncRootMatchingIsSegmentWise()
|
||||
{
|
||||
var root = Path.Combine(context.CreateTempDirectory(), "OneDrive");
|
||||
Assert.True(OneDriveFolders.IsUnder(root, root));
|
||||
Assert.True(OneDriveFolders.IsUnder(Path.Combine(root, "Pictures"), root + Path.DirectorySeparatorChar));
|
||||
Assert.True(OneDriveFolders.IsUnder(Path.Combine(root, "x").ToUpperInvariant(), root));
|
||||
Assert.False(OneDriveFolders.IsUnder(root + "Backup", root));
|
||||
Assert.Null(OneDriveFolders.Containing(root + "Backup", [root]));
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void ResolveChecksTheRealOneDriveRoots()
|
||||
{
|
||||
var app = context.CreateTempDirectory("app");
|
||||
File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), "");
|
||||
var paths = AppPaths.Resolve(app, KnownFolders.LocalAppData);
|
||||
Assert.True(paths.IsPortable);
|
||||
Assert.Equal(OneDriveFolders.Containing(paths.DataRoot, OneDriveFolders.SyncRoots()), paths.SyncedFolder);
|
||||
Assert.True(OneDriveFolders.SyncRoots().All(Path.IsPathFullyQualified));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
using Titano.Core.Windows.Shell;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Windows.Tests.Shell;
|
||||
|
||||
public sealed class ShellTests(TestContext context)
|
||||
{
|
||||
private static readonly nint StaleWindow = 0x0BAD_F00D;
|
||||
|
||||
[Theory]
|
||||
[Case("https://apps.microsoft.com/detail/9nctdw2w1bh8")]
|
||||
[Case("http://nas.local:8443/admin")]
|
||||
[Case("ms-windows-store://pdp/?ProductId=9NCTDW2W1BH8")]
|
||||
public void WebAndStoreUrlsAreAllowed(string url) => Assert.True(ShellLauncher.IsAllowedUrl(url));
|
||||
|
||||
[Theory]
|
||||
[Case("file:///C:/Windows/System32/cmd.exe")]
|
||||
[Case(@"C:\Windows\System32\cmd.exe")]
|
||||
[Case(@"\\server\share\run.bat")]
|
||||
[Case("javascript:alert(1)")]
|
||||
[Case("mailto:someone@example.com")]
|
||||
[Case("relative/page.html")]
|
||||
[Case("")]
|
||||
public void OtherTargetsAreRejected(string url) => Assert.False(ShellLauncher.IsAllowedUrl(url));
|
||||
|
||||
[Test]
|
||||
public void OpenUrlRefusesRejectedTargetsBeforeTouchingTheShell() =>
|
||||
Assert.Throws<ArgumentException>(() => ShellLauncher.OpenUrl("file:///C:/Windows/System32/cmd.exe"));
|
||||
|
||||
[Test]
|
||||
public void RevealOfAMissingPathReturnsFalse() =>
|
||||
Assert.False(ShellLauncher.RevealInExplorer(Path.Combine(context.CreateTempDirectory(), "missing.jpg")));
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void KnownFoldersMatchTheSystem()
|
||||
{
|
||||
Assert.Equal(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData).ToUpperInvariant(),
|
||||
KnownFolders.LocalAppData.ToUpperInvariant());
|
||||
Assert.True(Path.IsPathFullyQualified(KnownFolders.Pictures), KnownFolders.Pictures);
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void TaskbarCallsWithoutAValidWindowReturnFalse()
|
||||
{
|
||||
using var taskbar = new TaskbarProgress();
|
||||
Assert.False(taskbar.SetState(0, TaskbarProgressState.Normal));
|
||||
Assert.False(taskbar.SetValue(0, 1, 2));
|
||||
Assert.False(taskbar.SetState(StaleWindow, TaskbarProgressState.Indeterminate));
|
||||
Assert.False(taskbar.SetValue(StaleWindow, 1, 2));
|
||||
taskbar.Dispose();
|
||||
Assert.False(taskbar.IsAvailable);
|
||||
Assert.False(taskbar.SetValue(StaleWindow, 1, 2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
using Titano.Core.Windows.Wic;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Windows.Tests.Wic;
|
||||
|
||||
public sealed class OrientationMapTests
|
||||
{
|
||||
[Theory]
|
||||
[Case(1)]
|
||||
[Case(2)]
|
||||
[Case(3)]
|
||||
[Case(4)]
|
||||
[Case(5)]
|
||||
[Case(6)]
|
||||
[Case(7)]
|
||||
[Case(8)]
|
||||
public void MatchesTheExifDefinition(int orientation)
|
||||
{
|
||||
const int width = 5, height = 3;
|
||||
var map = OrientationMap.Create(orientation, width, height);
|
||||
var swapped = OrientationMap.SwapsAxes(orientation);
|
||||
Assert.Equal(swapped ? height : width, map.Width);
|
||||
Assert.Equal(swapped ? width : height, map.Height);
|
||||
|
||||
var seen = new HashSet<int>();
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var (dx, dy) = Reference(orientation, x, y, width, height);
|
||||
Assert.Equal((dy * map.Width) + dx, map.IndexOf(x, y), $"orientation {orientation}, pixel ({x},{y})");
|
||||
seen.Add(map.IndexOf(x, y));
|
||||
}
|
||||
}
|
||||
Assert.Equal(width * height, seen.Count);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UnknownValuesActAsIdentity() => Assert.Equal(OrientationMap.Create(1, 4, 2), OrientationMap.Create(0, 4, 2));
|
||||
|
||||
[Theory]
|
||||
[Case(4000u, 3000u, 1920, 1920u, 1440u)]
|
||||
[Case(400u, 100u, 100, 100u, 25u)]
|
||||
[Case(3000u, 4000u, 1000, 750u, 1000u)]
|
||||
[Case(640u, 480u, 0, 640u, 480u)]
|
||||
[Case(640u, 480u, 2000, 640u, 480u)]
|
||||
[Case(2u, 1000u, 10, 1u, 10u)]
|
||||
public void TargetSizeFitsTheLongEdge(uint width, uint height, int maxLongEdge, uint expectedWidth, uint expectedHeight)
|
||||
{
|
||||
var (w, h) = WicDecoderProvider.TargetSize(width, height, maxLongEdge);
|
||||
Assert.Equal(expectedWidth, w);
|
||||
Assert.Equal(expectedHeight, h);
|
||||
}
|
||||
|
||||
/// <summary>Displayed position of stored pixel (x, y), straight from the Exif 2.3 orientation table.</summary>
|
||||
private static (int X, int Y) Reference(int orientation, int x, int y, int w, int h) => orientation switch
|
||||
{
|
||||
2 => (w - 1 - x, y),
|
||||
3 => (w - 1 - x, h - 1 - y),
|
||||
4 => (x, h - 1 - y),
|
||||
5 => (y, x),
|
||||
6 => (h - 1 - y, x),
|
||||
7 => (h - 1 - y, w - 1 - x),
|
||||
8 => (y, w - 1 - x),
|
||||
_ => (x, y),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Windows.Wic;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Windows.Tests.Wic;
|
||||
|
||||
[WindowsOnly]
|
||||
public sealed class WicDecoderProviderTests(TestContext context)
|
||||
{
|
||||
private static readonly Lazy<WicDecoderProvider> SharedProvider = new(() => new WicDecoderProvider());
|
||||
private static readonly double MidGrey = ColorSpace.SrgbToLinear(128 / 255.0);
|
||||
|
||||
private static WicDecoderProvider Provider => SharedProvider.Value;
|
||||
|
||||
[Test]
|
||||
public void BuiltInFormatsAreNative()
|
||||
{
|
||||
Assert.Equal("wic", Provider.Name);
|
||||
foreach (var format in new[] { ImageFileFormat.Jpeg, ImageFileFormat.Png, ImageFileFormat.Tiff, ImageFileFormat.Bmp, ImageFileFormat.Gif })
|
||||
Assert.Equal<DecodeTier?>(DecodeTier.Native, Provider.TierFor(format), format.ToString());
|
||||
Assert.Null(Provider.TierFor(ImageFileFormat.Unknown));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PngMidGreyDecodesToLinearLight()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "grey.png");
|
||||
WicTestImages.WriteRgbPng(path, 64, 48, (_, _) => (128, 128, 128));
|
||||
|
||||
using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path)));
|
||||
Assert.Equal(DecodeTier.Native, image.Tier);
|
||||
Assert.Equal("wic", image.Decoder);
|
||||
Assert.Equal(64, image.Pixels.Width);
|
||||
Assert.Equal(48, image.Pixels.Height);
|
||||
Assert.Equal(3, image.Pixels.Channels);
|
||||
Assert.Equal(64, image.SourceWidth);
|
||||
Assert.Equal(48, image.SourceHeight);
|
||||
AssertUniform(image.Pixels, MidGrey, 1e-3);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void PngChannelsKeepTheirOrder()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "red-blue.png");
|
||||
WicTestImages.WriteRgbPng(path, 32, 16, (x, _) => x < 16 ? ((byte)255, (byte)0, (byte)0) : ((byte)0, (byte)0, (byte)255));
|
||||
|
||||
using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path)));
|
||||
var p = image.Pixels;
|
||||
Assert.Approximately(1.0, p[0, 4, 8], 1e-4);
|
||||
Assert.Approximately(0.0, p[1, 4, 8], 1e-4);
|
||||
Assert.Approximately(0.0, p[2, 4, 8], 1e-4);
|
||||
Assert.Approximately(0.0, p[0, 28, 8], 1e-4);
|
||||
Assert.Approximately(1.0, p[2, 28, 8], 1e-4);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SixteenBitPngKeepsPrecision()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "grey16.png");
|
||||
WicTestImages.WriteGray16Png(path, 8, 8, 0x8000);
|
||||
|
||||
using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path)));
|
||||
AssertUniform(image.Pixels, ColorSpace.Linear16(0x8000), 1e-4);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void JpegMidGreyDecodesToLinearLight()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "grey.jpg");
|
||||
WicTestImages.WriteGrayJpeg(path, 64, 48, (_, _) => 128);
|
||||
|
||||
using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path)));
|
||||
Assert.Equal(64, image.Pixels.Width);
|
||||
Assert.Equal(48, image.Pixels.Height);
|
||||
AssertUniform(image.Pixels, MidGrey, 1e-3);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ScalingToMaxLongEdgeKeepsAspect()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "wide.png");
|
||||
WicTestImages.WriteRgbPng(path, 400, 100, (_, _) => (128, 128, 128));
|
||||
|
||||
using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path, MaxLongEdge: 100)));
|
||||
Assert.Equal(100, image.Pixels.Width);
|
||||
Assert.Equal(25, image.Pixels.Height);
|
||||
Assert.Equal(400, image.SourceWidth);
|
||||
Assert.Equal(100, image.SourceHeight);
|
||||
AssertUniform(image.Pixels, MidGrey, 2e-3);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Orientation6RotatesClockwise()
|
||||
{
|
||||
// Stored 64×32 with a white 16×16 block at the top-left; displayed 32×64 with the block at the top-right.
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "rotated.jpg");
|
||||
WicTestImages.WriteGrayJpeg(path, 64, 32, (x, y) => x < 16 && y < 16 ? (byte)255 : (byte)0, exifOrientation: 6);
|
||||
|
||||
using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path)));
|
||||
Assert.Equal(32, image.Pixels.Width);
|
||||
Assert.Equal(64, image.Pixels.Height);
|
||||
Assert.Equal(32, image.SourceWidth);
|
||||
Assert.Equal(64, image.SourceHeight);
|
||||
Assert.Greater(image.Pixels[1, 24, 8], 0.8);
|
||||
Assert.Less(image.Pixels[1, 8, 8], 0.05);
|
||||
Assert.Less(image.Pixels[1, 24, 40], 0.05);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void OrientationIsIgnoredWhenNotRequested()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "rotated.jpg");
|
||||
WicTestImages.WriteGrayJpeg(path, 64, 32, (x, y) => x < 16 && y < 16 ? (byte)255 : (byte)0, exifOrientation: 6);
|
||||
|
||||
using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path, ApplyOrientation: false)));
|
||||
Assert.Equal(64, image.Pixels.Width);
|
||||
Assert.Equal(32, image.Pixels.Height);
|
||||
Assert.Greater(image.Pixels[1, 8, 8], 0.8);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void DecodesAFileAnotherProcessHasOpenForWriting()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "busy.png");
|
||||
WicTestImages.WriteRgbPng(path, 16, 16, (_, _) => (128, 128, 128));
|
||||
using var writer = new FileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
|
||||
|
||||
using var image = Assert.NotNull(Provider.Decode(new DecodeRequest(path)));
|
||||
Assert.Equal(16, image.Pixels.Width);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void UnrecognisedContentReturnsNull()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "noise.png");
|
||||
File.WriteAllBytes(path, Enumerable.Range(0, 4096).Select(i => (byte)(i * 37)).ToArray());
|
||||
Assert.Null(Provider.Decode(new DecodeRequest(path)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void MissingFileThrowsFileNotFound()
|
||||
{
|
||||
var path = Path.Combine(context.CreateTempDirectory(), "missing.png");
|
||||
Assert.Throws<FileNotFoundException>(() => Provider.Decode(new DecodeRequest(path)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ForcedPreviewIsLeftToOtherProviders() =>
|
||||
Assert.Null(Provider.Decode(new DecodeRequest(Path.Combine(context.CreateTempDirectory(), "any.jpg"), ForcePreview: true)));
|
||||
|
||||
private static void AssertUniform(ImageBuffer image, double expected, double tolerance)
|
||||
{
|
||||
for (var c = 0; c < image.Channels; c++)
|
||||
{
|
||||
var plane = image.Plane(c);
|
||||
for (var i = 0; i < plane.Length; i++)
|
||||
{
|
||||
if (Math.Abs(plane[i] - expected) > tolerance)
|
||||
Assert.Fail($"channel {c} pixel {i}: expected {expected:F5} ± {tolerance}, actual {plane[i]:F5}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Runtime.InteropServices;
|
||||
using Titano.Core.Codecs.Png;
|
||||
using Titano.Core.Windows.Interop;
|
||||
using Titano.Core.Windows.Wic;
|
||||
|
||||
namespace Titano.Core.Windows.Tests.Wic;
|
||||
|
||||
/// <summary>Synthetic fixtures: PNG through the managed encoder, JPEG through WIC's own encoder.</summary>
|
||||
internal static unsafe partial class WicTestImages
|
||||
{
|
||||
private static readonly Guid JpegContainer = new("19e4a5aa-5662-4fc5-a0c0-1758028e1057");
|
||||
private static readonly Guid PixelFormat8bppGray = new("6fddc324-4e03-4bfe-b185-3d77768dc908");
|
||||
|
||||
private const uint STGM_WRITE = 0x1, STGM_SHARE_EXCLUSIVE = 0x10, STGM_CREATE = 0x1000;
|
||||
private const uint FILE_ATTRIBUTE_NORMAL = 0x80;
|
||||
private const int WICBitmapEncoderNoCache = 2;
|
||||
|
||||
public static void WriteRgbPng(string path, int width, int height, Func<int, int, (byte R, byte G, byte B)> pixel)
|
||||
{
|
||||
var data = new byte[width * height * 3];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++)
|
||||
{
|
||||
var (r, g, b) = pixel(x, y);
|
||||
var i = ((y * width) + x) * 3;
|
||||
data[i] = r;
|
||||
data[i + 1] = g;
|
||||
data[i + 2] = b;
|
||||
}
|
||||
}
|
||||
File.WriteAllBytes(path, PngEncoder.Encode(data, width, height, PngColorType.Rgb));
|
||||
}
|
||||
|
||||
public static void WriteGray16Png(string path, int width, int height, ushort value)
|
||||
{
|
||||
var data = new byte[width * height * 2];
|
||||
for (var i = 0; i < data.Length; i += 2) BinaryPrimitives.WriteUInt16BigEndian(data.AsSpan(i), value);
|
||||
File.WriteAllBytes(path, PngEncoder.Encode(data, width, height, PngColorType.Gray, bitDepth: 16));
|
||||
}
|
||||
|
||||
/// <summary>Grayscale baseline JPEG from WIC's encoder; optionally tagged with an Exif orientation.</summary>
|
||||
public static void WriteGrayJpeg(string path, int width, int height, Func<int, int, byte> gray, int? exifOrientation = null)
|
||||
{
|
||||
var pixels = new byte[width * height];
|
||||
for (var y = 0; y < height; y++)
|
||||
{
|
||||
for (var x = 0; x < width; x++) pixels[(y * width) + x] = gray(x, y);
|
||||
}
|
||||
|
||||
var container = JpegContainer;
|
||||
Marshal.ThrowExceptionForHR(WicFactory.Instance.CreateEncoder(ref container, 0, out var encoderPointer));
|
||||
IWICBitmapEncoder encoder;
|
||||
try
|
||||
{
|
||||
encoder = (IWICBitmapEncoder)Marshal.GetObjectForIUnknown(encoderPointer);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Marshal.Release(encoderPointer);
|
||||
}
|
||||
|
||||
Marshal.ThrowExceptionForHR(SHCreateStreamOnFileEx(path, STGM_CREATE | STGM_WRITE | STGM_SHARE_EXCLUSIVE, FILE_ATTRIBUTE_NORMAL, 1, 0, out var stream));
|
||||
IWICBitmapFrameEncode? frame = null;
|
||||
nint options = 0;
|
||||
try
|
||||
{
|
||||
encoder.Initialize(stream, WICBitmapEncoderNoCache);
|
||||
encoder.CreateNewFrame(out frame, out options);
|
||||
frame.Initialize(options);
|
||||
frame.SetSize((uint)width, (uint)height);
|
||||
var format = PixelFormat8bppGray;
|
||||
frame.SetPixelFormat(ref format);
|
||||
if (format != PixelFormat8bppGray) throw new InvalidOperationException("The WIC JPEG encoder did not accept 8bppGray.");
|
||||
fixed (byte* p = pixels) frame.WritePixels((uint)height, (uint)width, (uint)pixels.Length, (nint)p);
|
||||
frame.Commit();
|
||||
encoder.Commit();
|
||||
}
|
||||
finally
|
||||
{
|
||||
Win32Com.Release(frame);
|
||||
if (options != 0) Marshal.Release(options);
|
||||
Win32Com.Release(encoder);
|
||||
Marshal.Release(stream);
|
||||
}
|
||||
|
||||
if (exifOrientation is { } orientation) InsertExifOrientation(path, orientation);
|
||||
}
|
||||
|
||||
/// <summary>Adds an APP1 Exif segment holding only IFD0 Orientation (after APP0 when present, as cameras do).</summary>
|
||||
private static void InsertExifOrientation(string path, int orientation)
|
||||
{
|
||||
var jpeg = File.ReadAllBytes(path);
|
||||
byte[] tiff =
|
||||
[
|
||||
(byte)'I', (byte)'I', 42, 0, 8, 0, 0, 0, // little-endian header, IFD0 at offset 8
|
||||
1, 0, // one entry
|
||||
0x12, 0x01, 3, 0, 1, 0, 0, 0, (byte)orientation, 0, 0, 0, // 0x0112 Orientation, SHORT, count 1
|
||||
0, 0, 0, 0, // no next IFD
|
||||
];
|
||||
var insertAt = 2;
|
||||
if (jpeg[2] == 0xFF && jpeg[3] == 0xE0) insertAt = 4 + BinaryPrimitives.ReadUInt16BigEndian(jpeg.AsSpan(4));
|
||||
var segmentLength = 2 + 6 + tiff.Length;
|
||||
using var output = new MemoryStream();
|
||||
output.Write(jpeg, 0, insertAt);
|
||||
output.Write([0xFF, 0xE1, (byte)(segmentLength >> 8), (byte)segmentLength]);
|
||||
output.Write("Exif\0\0"u8);
|
||||
output.Write(tiff);
|
||||
output.Write(jpeg, insertAt, jpeg.Length - insertAt);
|
||||
File.WriteAllBytes(path, output.ToArray());
|
||||
}
|
||||
|
||||
[LibraryImport("shlwapi.dll", StringMarshalling = StringMarshalling.Utf16)]
|
||||
private static partial int SHCreateStreamOnFileEx(string file, uint mode, uint attributes, int create, nint template, out nint stream);
|
||||
}
|
||||
|
||||
[ComImport]
|
||||
[Guid("00000103-a8f2-4877-ba0a-fd2b6645fb94")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
internal interface IWICBitmapEncoder
|
||||
{
|
||||
void Initialize(nint stream, int cacheOption);
|
||||
|
||||
Guid GetContainerFormat();
|
||||
|
||||
void GetEncoderInfo(out nint encoderInfo);
|
||||
|
||||
void SetColorContexts(uint count, nint colorContexts);
|
||||
|
||||
void SetPalette(nint palette);
|
||||
|
||||
void SetThumbnail(nint thumbnail);
|
||||
|
||||
void SetPreview(nint preview);
|
||||
|
||||
void CreateNewFrame(out IWICBitmapFrameEncode frame, out nint encoderOptions);
|
||||
|
||||
void Commit();
|
||||
}
|
||||
|
||||
[ComImport]
|
||||
[Guid("00000105-a8f2-4877-ba0a-fd2b6645fb94")]
|
||||
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
|
||||
internal interface IWICBitmapFrameEncode
|
||||
{
|
||||
void Initialize(nint encoderOptions);
|
||||
|
||||
void SetSize(uint width, uint height);
|
||||
|
||||
void SetResolution(double dpiX, double dpiY);
|
||||
|
||||
void SetPixelFormat(ref Guid pixelFormat);
|
||||
|
||||
void SetColorContexts(uint count, nint colorContexts);
|
||||
|
||||
void SetPalette(nint palette);
|
||||
|
||||
void SetThumbnail(nint thumbnail);
|
||||
|
||||
void WritePixels(uint lineCount, uint stride, uint bufferSize, nint pixels);
|
||||
|
||||
void WriteSource(nint source, nint rect);
|
||||
|
||||
void Commit();
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using Titano.Core.Windows.Window;
|
||||
using Titano.Testing;
|
||||
|
||||
namespace Titano.Core.Windows.Tests.Window;
|
||||
|
||||
public sealed class WindowTests
|
||||
{
|
||||
private static readonly nint StaleWindow = 0x0BAD_F00D;
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void DwmCallsWithoutAValidWindowReturnFalse()
|
||||
{
|
||||
foreach (var window in new[] { (nint)0, StaleWindow })
|
||||
{
|
||||
Assert.False(DwmWindow.SetDarkMode(window, true));
|
||||
Assert.False(DwmWindow.SetBackdrop(window, SystemBackdrop.Mica));
|
||||
Assert.False(DwmWindow.SetCornerPreference(window, WindowCornerPreference.Round));
|
||||
Assert.False(DwmWindow.SetCaptionColor(window, new RgbColor(0x20, 0x20, 0x20)));
|
||||
Assert.False(DwmWindow.SetBorderColor(window, null));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
public void SystemThemeReadsWithoutThrowing()
|
||||
{
|
||||
Assert.DoesNotThrow(() => _ = SystemTheme.AppsUseLightTheme);
|
||||
Assert.DoesNotThrow(() => _ = SystemTheme.AccentColor);
|
||||
}
|
||||
|
||||
[Test]
|
||||
[WindowsOnly]
|
||||
[Timeout(30_000)]
|
||||
public void ThemeWatcherStartsAndStops()
|
||||
{
|
||||
var watcher = new SystemThemeWatcher();
|
||||
watcher.Changed += (_, _) => { };
|
||||
watcher.Dispose();
|
||||
watcher.Dispose();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ColoursConvertBetweenWin32Layouts()
|
||||
{
|
||||
var accent = RgbColor.FromAbgr(0xFFD77800);
|
||||
Assert.Equal(new RgbColor(0x00, 0x78, 0xD7), accent);
|
||||
Assert.Equal("#0078D7", accent.ToString());
|
||||
Assert.Equal(0x00D77800u, accent.ToColorRef());
|
||||
Assert.Equal(accent, RgbColor.FromArgb(0xFF0078D7));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user