refactor!: rename Titano to Chronos and move CI and releases to Gitea
CI / Build and test (pull_request) Failing after 2m3s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / Docker image (pull_request) Skipped
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 4s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout. The release cross-compiles the Windows programs, checks their
  icon, version and DPI manifest, packs installers and zips, publishes the
  Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only
  tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow) and
  pe-check.

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-10-23 11:34:48 +02:00
1 parent c99842cc86
commit 5f27a86406
1799 files changed
+11728 -10668

No files matched your search

@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<RootNamespace>Chronos.Core.Windows.Tests</RootNamespace>
</PropertyGroup>
<ItemGroup>
<!-- WPF's MediaPlayer for the playback check (BRIEF §20.2); not UseWPF, which would also change the implicit usings. -->
<FrameworkReference Include="Microsoft.WindowsDesktop.App.WPF" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Chronos.Testing\Chronos.Testing.csproj" />
<ProjectReference Include="..\..\src\Chronos.Core.Windows\Chronos.Core.Windows.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,145 @@
using Chronos.Core.Imaging;
using Chronos.Core.Windows.Codecs;
using Chronos.Core.Windows.Wic;
using Chronos.Testing;
namespace Chronos.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 Chronos.Core.Windows.Devices;
using Chronos.Testing;
namespace Chronos.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,18 @@
using Chronos.Core.Windows.Dxgi;
using Chronos.Testing;
namespace Chronos.Core.Windows.Tests.MediaFoundation;
public sealed class GpuAdaptersTests(TestContext context)
{
[Test]
[WindowsOnly]
public void EnumeratesAtLeastTheBasicRenderDriver()
{
var adapters = GpuAdapters.Enumerate();
foreach (var a in adapters)
context.Log($"{a.Description} vendor=0x{a.VendorId:X4} device=0x{a.DeviceId:X4} vram={a.DedicatedVideoMemory >> 20} MiB software={a.IsSoftware}");
Assert.NotEmpty(adapters);
Assert.True(adapters.All(a => a.Description.Length > 0 && !a.Description.Contains('\0')));
}
}
@@ -0,0 +1,244 @@
using Chronos.Core.Imaging;
using Chronos.Core.Video;
using Chronos.Core.Windows.MediaFoundation;
using Chronos.Testing;
namespace Chronos.Core.Windows.Tests.MediaFoundation;
[Serial] // encoders share GPU sessions and the MF runtime
public sealed class MediaFoundationEncoderTests(TestContext context)
{
private const long Frame30 = 3000; // 1/30 s at 90 kHz
[Test]
public void VendorIdsMapToNames()
{
Assert.Equal("NVIDIA", MediaFoundationEncoderProvider.VendorName("VEN_10DE"));
Assert.Equal("Intel", MediaFoundationEncoderProvider.VendorName("ven_8086"));
Assert.Equal("AMD", MediaFoundationEncoderProvider.VendorName("VEN_1002"));
Assert.Equal("VEN_ABCD", MediaFoundationEncoderProvider.VendorName("VEN_ABCD"));
Assert.Null(MediaFoundationEncoderProvider.VendorName(null));
}
[Test]
[WindowsOnly]
public void EnumeratesEncodersAndHidesSoftwareHevcAndAv1()
{
RequireMediaFoundation();
var encoders = MediaFoundationEncoders.Enumerate();
foreach (var e in encoders) context.Log($"{e.Codec} \"{e.Name}\" hardware={e.IsHardware} async={e.IsAsync} vendor={e.VendorId} 10-bit={e.SupportsTenBit}");
Assert.True(encoders.All(e => !string.IsNullOrWhiteSpace(e.Name)));
var capabilities = new MediaFoundationEncoderProvider().Capabilities;
Assert.True(capabilities.All(c => c.Hardware || c.Codec == VideoCodec.H264), "HEVC/AV1 are hardware-only");
Assert.True(capabilities.All(c => !c.SupportsTenBit || c.Codec != VideoCodec.H264));
Assert.Equal(encoders.Count(e => e.IsHardware || e.Codec == VideoCodec.H264), capabilities.Count);
}
[Test]
[WindowsOnly]
[Timeout(60_000)]
public void SoftwareH264EncodeProducesAValidMp4()
{
RequireEncoder(VideoCodec.H264, hardware: false, tenBit: false);
var dir = context.CreateTempDirectory();
var settings = Settings(Path.Combine(dir, "software.mp4"), VideoCodec.H264, 8) with { PreferHardware = false };
var provider = new MediaFoundationEncoderProvider();
Assert.True(provider.CanEncode(settings));
using (var session = provider.Open(settings))
{
Assert.False(session.IsHardware);
context.Log("encoder: " + session.EncoderName);
WriteFrames(session, 60, 8);
session.Complete();
}
var report = Mp4Inspector.Inspect(settings.OutputPath);
context.Log(report.ToString());
Assert.True(report.IsValid, string.Join("; ", report.Errors));
Assert.Equal(VideoCodec.H264, report.Codec);
Assert.Equal(1280, report.Width);
Assert.Equal(720, report.Height);
Assert.Equal(60, report.FrameCount);
Assert.Approximately(2.0, report.Duration.TotalSeconds, 0.034);
Assert.True(report.FastStart);
Assert.Count(1, Directory.GetFiles(dir)); // no temporary file left behind
}
/// <summary>
/// BRIEF §20.2: what the encoder writes plays in Windows. MediaPlayer (Windows Media Player's pipeline) opens it at
/// the encoded size and length. Where Windows Media Player is missing or unusable (Windows Server, "N" editions) the
/// test is skipped with that reason, and <see cref="SourceReaderDecodesTheSoftwareH264Output"/> is the check.
/// </summary>
[Test]
[WindowsOnly]
[Timeout(120_000)]
public void MediaPlayerOpensTheSoftwareH264Output()
{
RequireEncoder(VideoCodec.H264, hardware: false, tenBit: false);
RequireMediaPlayer();
var opened = OpenWithMediaPlayer(Encoded("playback.mp4", VideoCodec.H264, 8, hardware: false));
context.Log($"MediaPlayer: {opened}");
Assert.Equal(1280, opened.Width);
Assert.Equal(720, opened.Height);
Assert.Approximately(2.0, opened.Duration.TotalSeconds, 0.05);
}
/// <summary>
/// BRIEF §20.2: a Media Foundation source reader decodes the encoder's first frame to the picture that was encoded.
/// It needs no Windows Media Player, so it runs on every Windows with Media Foundation, Server editions included.
/// </summary>
[Test]
[WindowsOnly]
[Timeout(60_000)]
public void SourceReaderDecodesTheSoftwareH264Output()
{
RequireEncoder(VideoCodec.H264, hardware: false, tenBit: false);
var frame = Mp4Playback.DecodeFirstFrame(Encoded("decode.mp4", VideoCodec.H264, 8, hardware: false));
context.Log($"source reader: {frame.Width}×{frame.Height}, {frame.Duration}, luma square {frame.LumaAt(100, 360)}, corner {frame.LumaAt(4, 4)}");
Assert.Equal(1280, frame.Width);
Assert.Equal(720, frame.Height);
Assert.Approximately(2.0, frame.Duration.TotalSeconds, 0.05);
// Frame 0 as WriteFrames drew it: the white square centred at (100, 360) on a dark blue corner.
Assert.Greater(frame.LumaAt(100, 360), 200);
Assert.Less(frame.LumaAt(4, 4), 60);
}
/// <summary>The hardware HEVC Main10 output opens in MediaPlayer at its size and length, where Windows can decode HEVC.</summary>
[Test]
[WindowsOnly]
[Timeout(120_000)]
public void MediaPlayerOpensTheHardwareHevcMain10Output()
{
RequireEncoder(VideoCodec.Hevc, hardware: true, tenBit: true);
RequireMediaPlayer();
if (!Mp4Playback.HasDecoder(VideoCodec.Hevc)) TestContext.Skip("No HEVC decoder on this machine (HEVC Video Extensions)");
var opened = OpenWithMediaPlayer(Encoded("main10.mp4", VideoCodec.Hevc, 10, hardware: true));
context.Log($"MediaPlayer: {opened}");
Assert.Equal(1280, opened.Width);
Assert.Equal(720, opened.Height);
Assert.Approximately(2.0, opened.Duration.TotalSeconds, 0.05);
}
[Test]
[WindowsOnly]
[Timeout(60_000)]
public void HardwareHevcMain10EncodeWhenAvailable()
{
RequireEncoder(VideoCodec.Hevc, hardware: true, tenBit: true);
var dir = context.CreateTempDirectory();
var settings = Settings(Path.Combine(dir, "main10.mp4"), VideoCodec.Hevc, 10);
using (var session = new MediaFoundationEncoderProvider().Open(settings))
{
Assert.True(session.IsHardware);
context.Log("encoder: " + session.EncoderName);
WriteFrames(session, 60, 10);
session.Complete();
}
var report = Mp4Inspector.Inspect(settings.OutputPath);
context.Log(report.ToString());
Assert.True(report.IsValid, string.Join("; ", report.Errors));
Assert.Equal(VideoCodec.Hevc, report.Codec);
Assert.Equal(10, report.BitDepth);
Assert.Equal(60, report.FrameCount);
}
[Test]
[WindowsOnly]
[Timeout(60_000)]
public void DisposeWithoutCompleteLeavesNoFile()
{
RequireEncoder(VideoCodec.H264, hardware: false, tenBit: false);
var dir = context.CreateTempDirectory();
var settings = Settings(Path.Combine(dir, "cancelled.mp4"), VideoCodec.H264, 8) with { PreferHardware = false };
using (var session = new MediaFoundationEncoderProvider().Open(settings))
{
WriteFrames(session, 5, 8);
}
Assert.Empty(Directory.GetFiles(dir));
}
private static EncodeSettings Settings(string path, VideoCodec codec, int bitDepth) => new()
{
OutputPath = path,
Codec = codec,
Width = 1280,
Height = 720,
FrameRate = new Rational(30, 1),
BitDepth = bitDepth,
Profile = codec == VideoCodec.Hevc ? (bitDepth == 10 ? CodecProfile.HevcMain10 : CodecProfile.HevcMain) : CodecProfile.H264High,
BitRate = 4_000_000,
GopLength = 30,
};
/// <summary>A moving colour ramp with a bright square, distinct per frame.</summary>
private static void WriteFrames(IVideoEncoderSession session, int count, int bitDepth)
{
using var frame = new ImageBuffer(1280, 720);
for (var f = 0; f < count; f++)
{
for (var y = 0; y < 720; y++)
{
var r = frame.Row(0, y);
var g = frame.Row(1, y);
var b = frame.Row(2, y);
for (var x = 0; x < 1280; x++)
{
var square = Math.Abs(x - 100 - f * 15) < 60 && Math.Abs(y - 360) < 60;
r[x] = square ? 1f : (float)ColorSpace.SrgbToLinear((x + f * 7) % 1280 / 1280.0);
g[x] = square ? 1f : (float)ColorSpace.SrgbToLinear(y / 720.0);
b[x] = (float)ColorSpace.SrgbToLinear(bitDepth == 10 ? 0.5 + 0.4 * Math.Sin((x + y) * 0.01) : 0.3);
}
}
session.WriteFrame(frame, Frame30);
}
}
/// <summary>Two seconds of <see cref="WriteFrames"/> (60 frames at 30 fps, 1280×720) in a new temporary file.</summary>
private string Encoded(string name, VideoCodec codec, int bitDepth, bool hardware)
{
var settings = Settings(Path.Combine(context.CreateTempDirectory(), name), codec, bitDepth) with { PreferHardware = hardware };
using (var session = new MediaFoundationEncoderProvider().Open(settings))
{
Assert.Equal(hardware, session.IsHardware);
context.Log("encoder: " + session.EncoderName);
WriteFrames(session, 60, bitDepth);
session.Complete();
}
return settings.OutputPath;
}
/// <summary>
/// <see cref="Mp4Playback.OpenWithMediaPlayer"/>, skipped when WPF finds Windows Media Player present but unusable
/// (its <see cref="NotSupportedException"/>, "version 10 or later is required").
/// </summary>
private static Mp4Playback.Opened OpenWithMediaPlayer(string path)
{
try
{
return Mp4Playback.OpenWithMediaPlayer(path, TimeSpan.FromSeconds(60));
}
catch (NotSupportedException ex)
{
TestContext.Skip("Windows Media Player cannot be used: " + ex.Message);
throw;
}
}
private static void RequireMediaPlayer()
{
if (!Mp4Playback.HasMediaPlayer) TestContext.Skip("Windows Media Player is not installed (Windows Server, \"N\" editions); the source reader test checks playback");
}
private static void RequireMediaFoundation()
{
if (!MediaFoundationRuntime.IsAvailable) TestContext.Skip("Media Foundation is not installed (Windows N or Server without Media Foundation)");
}
private static void RequireEncoder(VideoCodec codec, bool hardware, bool tenBit)
{
RequireMediaFoundation();
if (!MediaFoundationEncoders.Enumerate().Any(e => e.Codec == codec && e.IsHardware == hardware && (!tenBit || e.SupportsTenBit)))
TestContext.Skip($"No {(hardware ? "hardware" : "software")} {codec}{(tenBit ? " 10-bit" : string.Empty)} encoder on this machine");
}
}
@@ -0,0 +1,289 @@
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.Marshalling;
using System.Windows.Media;
using System.Windows.Threading;
using Chronos.Core.Video;
using Chronos.Core.Windows.Interop;
using Chronos.Core.Windows.MediaFoundation;
namespace Chronos.Core.Windows.Tests.MediaFoundation;
/// <summary>
/// How Windows plays a written MP4 back (BRIEF §20.2): WPF's <see cref="MediaPlayer"/>, which runs on Windows Media
/// Player's pipeline, and a Media Foundation source reader that decodes the first frame, which also works where Windows
/// Media Player is not installed (Windows Server, "N" editions).
/// </summary>
internal static partial class Mp4Playback
{
/// <summary>What a player reports once the file is open.</summary>
public sealed record Opened(int Width, int Height, TimeSpan Duration);
/// <summary>The first decoded frame: its size, the file's duration and the luma plane (8 bits, top-down, no padding).</summary>
public sealed record FirstFrame(int Width, int Height, TimeSpan Duration, byte[] Luma)
{
public byte LumaAt(int x, int y) => Luma[y * Width + x];
}
/// <summary>True when <see cref="MediaPlayer"/> can work: it needs Windows Media Player (wmp.dll).</summary>
public static bool HasMediaPlayer
{
get
{
if (!NativeLibrary.TryLoad("wmp.dll", out var handle)) return false;
NativeLibrary.Free(handle);
return true;
}
}
/// <summary>
/// True when Media Foundation has a decoder for <paramref name="codec"/>: always for H.264, only with the HEVC Video
/// Extensions for HEVC, which MediaPlayer needs as much as the source reader does.
/// </summary>
public static unsafe bool HasDecoder(VideoCodec codec)
{
using var runtime = MediaFoundationRuntime.Acquire();
var input = new MftRegisterTypeInfo { MajorType = MfGuids.MediaTypeVideo, Subtype = MediaFoundationEncoders.Subtype(codec) };
const uint flags = MfNative.EnumHardware | MfNative.EnumAsync | MfNative.EnumSync | MfNative.EnumSortAndFilter;
if (MfNative.MFTEnumEx(VideoDecoderCategory, flags, &input, null, out var array, out var count) < 0) return false;
try
{
for (var i = 0; i < count; i++) Marshal.Release(Marshal.ReadIntPtr(array, i * IntPtr.Size));
}
finally
{
Marshal.FreeCoTaskMem(array);
}
return count > 0;
}
/// <summary>
/// Opens <paramref name="path"/> with <see cref="MediaPlayer"/> on its own dispatcher thread and returns what it
/// reports at <see cref="MediaPlayer.MediaOpened"/>. Throws, on the calling thread, when it raises
/// <see cref="MediaPlayer.MediaFailed"/>, when neither event comes within <paramref name="timeout"/>, and with WPF's
/// own exception when the player cannot be made or opened at all (a <see cref="NotSupportedException"/> where Windows
/// Media Player 10 or later is not usable): nothing escapes the dispatcher thread, where it would end the test program.
/// </summary>
public static Opened OpenWithMediaPlayer(string path, TimeSpan timeout)
{
Opened? opened = null;
Exception? failure = null;
var thread = new Thread(() =>
{
var dispatcher = Dispatcher.CurrentDispatcher;
MediaPlayer? player = null;
DispatcherTimer? deadline = null;
var finished = false;
// The first outcome counts; the player is closed and the dispatcher stopped once.
void Finish(Opened? result, Exception? error)
{
if (finished) return;
finished = true;
(opened, failure) = (result, error);
deadline?.Stop();
try
{
player?.Close();
}
catch (Exception ex)
{
failure ??= ex;
}
dispatcher.InvokeShutdown();
}
try
{
player = new MediaPlayer();
player.MediaOpened += (_, _) =>
{
// A handler that threw would leave Dispatcher.Run with the player still open.
try
{
Finish(new Opened(player.NaturalVideoWidth, player.NaturalVideoHeight,
player.NaturalDuration.HasTimeSpan ? player.NaturalDuration.TimeSpan : TimeSpan.Zero), null);
}
catch (Exception ex)
{
Finish(null, ex);
}
};
player.MediaFailed += (_, e) =>
Finish(null, new InvalidDataException($"MediaPlayer could not open '{path}': {e.ErrorException?.Message}", e.ErrorException));
// This constructor starts the timer.
deadline = new DispatcherTimer(timeout, DispatcherPriority.Normal, (_, _) =>
Finish(null, new TimeoutException($"MediaPlayer neither opened nor failed on '{path}' within {timeout.TotalSeconds:0} s")), dispatcher);
player.Open(new Uri(path, UriKind.Absolute));
Dispatcher.Run();
}
catch (Exception ex)
{
if (finished) failure ??= ex;
else Finish(null, ex);
}
})
{
IsBackground = true,
Name = "MediaPlayer check",
};
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
// Rethrown with the dispatcher thread's stack trace and its own type: a NotSupportedException stays one.
if (failure is not null) ExceptionDispatchInfo.Throw(failure);
return opened ?? throw new InvalidOperationException("MediaPlayer stopped without a result");
}
/// <summary>Decodes the first video frame of <paramref name="path"/> to NV12 with a Media Foundation source reader.</summary>
public static unsafe FirstFrame DecodeFirstFrame(string path)
{
using var runtime = MediaFoundationRuntime.Acquire();
ComObjects.Check(MFCreateSourceReaderFromURL(path, 0, out var readerPointer), "MFCreateSourceReaderFromURL");
var reader = ComObjects.Attach<IMFSourceReader>(readerPointer);
try
{
var duration = TimeSpan.Zero;
var variant = stackalloc byte[PropVariantSize];
new Span<byte>(variant, PropVariantSize).Clear();
if (reader.GetPresentationAttribute(MediaSource, PresentationDuration, (nint)variant) >= 0)
{
if (*(ushort*)variant == VtUi8) duration = TimeSpan.FromTicks((long)*(ulong*)(variant + 8));
PropVariantClear((nint)variant);
}
// The reader inserts the H.264/HEVC decoder itself once NV12 is asked for.
ComObjects.Check(MfNative.MFCreateMediaType(out var typePointer), "MFCreateMediaType");
var type = ComObjects.Attach<IMFMediaType>(typePointer);
try
{
ComObjects.Check(type.SetGUID(MfGuids.MajorType, MfGuids.MediaTypeVideo), "MF_MT_MAJOR_TYPE");
ComObjects.Check(type.SetGUID(MfGuids.Subtype, MfGuids.FormatNv12), "MF_MT_SUBTYPE");
var native = ComObjects.GetPointer(type);
try
{
ComObjects.Check(reader.SetCurrentMediaType(FirstVideoStream, 0, native), "SetCurrentMediaType(NV12)");
}
finally
{
Marshal.Release(native);
}
}
finally
{
ComObjects.Release(type);
}
var sample = ReadFirstSample(reader);
try
{
ComObjects.Check(reader.GetCurrentMediaType(FirstVideoStream, out var currentPointer), "GetCurrentMediaType");
var current = ComObjects.Attach<IMFMediaType>(currentPointer);
ulong size;
try
{
ComObjects.Check(current.GetUINT64(MfGuids.FrameSize, out size), "MF_MT_FRAME_SIZE");
}
finally
{
ComObjects.Release(current);
}
var (width, height) = ((int)(size >> 32), (int)(size & 0xFFFF_FFFF));
return new FirstFrame(width, height, duration, CopyLuma(sample, width, height));
}
finally
{
ComObjects.Release(sample);
}
}
finally
{
ComObjects.Release(reader);
}
}
/// <summary>Reads until the first video sample; stream ticks and format changes come without one.</summary>
private static IMFSample ReadFirstSample(IMFSourceReader reader)
{
for (var attempt = 0; attempt < 100; attempt++)
{
ComObjects.Check(reader.ReadSample(FirstVideoStream, 0, out _, out var flags, out _, out var samplePointer), "ReadSample");
if (samplePointer != 0) return ComObjects.Attach<IMFSample>(samplePointer);
if ((flags & (ReaderError | ReaderEndOfStream)) != 0) throw new InvalidDataException($"The source reader returned no frame (flags 0x{flags:X})");
}
throw new InvalidDataException("The source reader returned no frame in 100 reads");
}
/// <summary>Copies the Y plane out of the sample's buffer, honouring the decoder's row pitch.</summary>
private static unsafe byte[] CopyLuma(IMFSample sample, int width, int height)
{
ComObjects.Check(sample.ConvertToContiguousBuffer(out var bufferPointer), "ConvertToContiguousBuffer");
var buffer = ComObjects.Attach<IMFMediaBuffer>(bufferPointer);
try
{
var luma = new byte[width * height];
if (buffer is IMF2DBuffer twoD && twoD.Lock2D(out var scanline0, out var pitch) >= 0)
{
try
{
for (var y = 0; y < height; y++) new ReadOnlySpan<byte>((byte*)scanline0 + (long)y * pitch, width).CopyTo(luma.AsSpan(y * width));
}
finally
{
twoD.Unlock2D();
}
return luma;
}
ComObjects.Check(buffer.Lock(out var data, out _, out var length), "IMFMediaBuffer.Lock");
try
{
// A contiguous NV12 frame: the Y rows, then half as many interleaved chroma rows, all of one pitch.
var stride = (int)(length / (uint)(height + height / 2));
if (stride < width) throw new InvalidDataException($"An NV12 buffer of {length} bytes is too small for {width}×{height}");
for (var y = 0; y < height; y++) new ReadOnlySpan<byte>((byte*)data + (long)y * stride, width).CopyTo(luma.AsSpan(y * width));
return luma;
}
finally
{
buffer.Unlock();
}
}
finally
{
ComObjects.Release(buffer);
}
}
private const uint FirstVideoStream = 0xFFFF_FFFC; // MF_SOURCE_READER_FIRST_VIDEO_STREAM
private const uint MediaSource = 0xFFFF_FFFF; // MF_SOURCE_READER_MEDIASOURCE
private const uint ReaderError = 0x1, ReaderEndOfStream = 0x2; // MF_SOURCE_READERF_ERROR, _ENDOFSTREAM
private const ushort VtUi8 = 21;
private const int PropVariantSize = 24; // PROPVARIANT on 64-bit Windows
/// <summary>MFT_CATEGORY_VIDEO_DECODER.</summary>
private static readonly Guid VideoDecoderCategory = new("d6c02d4b-6833-45b4-971a-05a4b04bab91");
/// <summary>MF_PD_DURATION: the presentation's length in 100 ns units.</summary>
private static readonly Guid PresentationDuration = new("6c990d33-bb8e-477a-8598-0d5d96fcd88a");
[LibraryImport("mfreadwrite.dll", StringMarshalling = StringMarshalling.Utf16)]
private static partial int MFCreateSourceReaderFromURL(string url, nint attributes, out nint reader);
[LibraryImport("ole32.dll")]
private static partial int PropVariantClear(nint variant);
}
/// <summary>IMFSourceReader (mfreadwrite.h) in vtable order.</summary>
[GeneratedComInterface]
[Guid("70ae66f2-c809-4e4f-8915-bdcb406b7993")]
internal partial interface IMFSourceReader
{
[PreserveSig] int GetStreamSelection(uint streamIndex, out int selected);
[PreserveSig] int SetStreamSelection(uint streamIndex, int selected);
[PreserveSig] int GetNativeMediaType(uint streamIndex, uint mediaTypeIndex, out nint mediaType);
[PreserveSig] int GetCurrentMediaType(uint streamIndex, out nint mediaType);
[PreserveSig] int SetCurrentMediaType(uint streamIndex, nint reserved, nint mediaType);
[PreserveSig] int SetCurrentPosition(in Guid timeFormat, nint position);
[PreserveSig] int ReadSample(uint streamIndex, uint controlFlags, out uint actualStreamIndex, out uint streamFlags, out long timestamp, out nint sample);
[PreserveSig] int Flush(uint streamIndex);
[PreserveSig] int GetServiceForStream(uint streamIndex, in Guid service, in Guid iid, out nint instance);
[PreserveSig] int GetPresentationAttribute(uint streamIndex, in Guid attribute, nint value);
}
@@ -0,0 +1,27 @@
using Chronos.Core.Windows.Power;
using Chronos.Testing;
namespace Chronos.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,8 @@
using Chronos.Testing;
namespace Chronos.Core.Windows.Tests;
internal static class TestMain
{
public static Task<int> Main(string[] args) => TestRunner.RunAsync(args, typeof(TestMain).Assembly);
}
@@ -0,0 +1,48 @@
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Windows.Security;
using Chronos.Testing;
namespace Chronos.Core.Windows.Tests.Security;
[WindowsOnly]
public sealed class DpapiTests
{
private static readonly byte[] Secret = Encoding.UTF8.GetBytes("chronos-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 = "Chronos.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,93 @@
using Chronos.Core.Windows.Shell;
using Chronos.Testing;
namespace Chronos.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", "chronos.db"), paths.DatabasePath);
Assert.False(paths.IsInSyncedFolder);
Assert.Null(paths.PortableSyncRoot);
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, "Chronos"), paths.DataRoot);
Assert.Equal(Path.Combine(local, "Chronos", "chronos.db"), paths.DatabasePath);
}
[Test]
public void APortableCopyInOneDriveKeepsItsDataInLocalAppData()
{
var oneDrive = context.CreateTempDirectory("onedrive");
var app = Directory.CreateDirectory(Path.Combine(oneDrive, "Tools", "Chronos")).FullName;
File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), "");
var local = context.CreateTempDirectory("local");
var paths = AppPaths.Resolve(app, local, [oneDrive]);
Assert.True(paths.IsPortable);
Assert.Equal(Path.Combine(local, "Chronos"), paths.DataRoot);
Assert.Equal<string?>(oneDrive, paths.PortableSyncRoot);
Assert.False(paths.IsInSyncedFolder);
paths.CreateDirectories();
Assert.True(Directory.Exists(paths.LogsDirectory));
Assert.False(Directory.Exists(Path.Combine(app, "data")), "nothing is written into the synchronised folder");
}
[Test]
public void DataInsideOneDriveIsReportedAndRefused()
{
// Local application data inside a sync root: nowhere is safe, so nothing is created.
var oneDrive = context.CreateTempDirectory("onedrive");
var local = Directory.CreateDirectory(Path.Combine(oneDrive, "AppData", "Local")).FullName;
var paths = AppPaths.Resolve(context.CreateTempDirectory("app"), 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.Equal<string?>(root, OneDriveFolders.Containing(Path.Combine(root, "Pictures"), [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);
var roots = OneDriveFolders.SyncRoots();
Assert.True(paths.IsPortable);
Assert.Equal(OneDriveFolders.Containing(Path.Combine(app, PortableMode.DataFolderName), roots), paths.PortableSyncRoot);
Assert.Equal(OneDriveFolders.Containing(paths.DataRoot, roots), paths.SyncedFolder);
Assert.True(roots.All(Path.IsPathFullyQualified));
}
}
@@ -0,0 +1,86 @@
using Microsoft.Win32;
using Chronos.Core.Windows.Shell;
using Chronos.Testing;
namespace Chronos.Core.Windows.Tests.Shell;
/// <summary>
/// The OneDrive folders of the user as Windows reports them, from its environment and registry (a scratch key in tests).
/// Serial: a test sets a process environment variable.
/// </summary>
[Serial]
public sealed class OneDriveFoldersTests(TestContext context)
{
private const string Variable = "OneDriveCommercial";
[Test]
[WindowsOnly]
public void APortableCopyInTheUsersOneDriveKeepsItsDataInLocalAppData()
{
var oneDrive = context.CreateTempDirectory("onedrive");
var previous = Environment.GetEnvironmentVariable(Variable);
Environment.SetEnvironmentVariable(Variable, oneDrive);
try
{
Assert.Contains(OneDriveFolders.SyncRoots(), root => string.Equals(root, Path.TrimEndingDirectorySeparator(oneDrive), StringComparison.OrdinalIgnoreCase));
// A Desktop that OneDrive's folder backup moved into the sync root, with a portable copy unpacked on it.
var app = Directory.CreateDirectory(Path.Combine(oneDrive, "Desktop", "Chronos")).FullName;
File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), "");
var local = context.CreateTempDirectory("local");
var paths = AppPaths.Resolve(app, local);
Assert.True(paths.IsPortable);
Assert.Equal(Path.Combine(local, AppPaths.ProductFolderName), paths.DataRoot);
Assert.NotNull(paths.PortableSyncRoot);
Assert.False(paths.IsInSyncedFolder);
}
finally
{
Environment.SetEnvironmentVariable(Variable, previous);
}
}
[Test]
[WindowsOnly]
public void ALibrarySyncedBesideTheAccountsFolderIsASyncRootToo()
{
// A scratch hive of its own: the user's OneDrive settings are never read or touched.
var hive = @"Software\Chronos.OneDriveTests." + Guid.NewGuid().ToString("N");
try
{
var profile = context.CreateTempDirectory("profile");
var account = Path.Combine(profile, "OneDrive - Contoso");
// The Sync button of a SharePoint or Teams library puts it in %USERPROFILE%\<tenant>, not in the account's folder.
var library = Path.Combine(profile, "Contoso", "Team Site - Documents");
using var user = Registry.CurrentUser.CreateSubKey(hive, writable: true);
using (var business = user.CreateSubKey(@"Software\Microsoft\OneDrive\Accounts\Business1")) business.SetValue("UserFolder", account);
using (var engine = user.CreateSubKey(@"Software\SyncEngines\Providers\OneDrive\Business1")) engine.SetValue("MountPoint", account);
using (var site = user.CreateSubKey(@"Software\SyncEngines\Providers\OneDrive\8c2f0b1e7d6a4f3e9b5c2d1a0e9f8b7c+1")) site.SetValue("MountPoint", library + @"\");
// Entries without a full path name nothing.
using (var relative = user.CreateSubKey(@"Software\SyncEngines\Providers\OneDrive\Relative")) relative.SetValue("MountPoint", @"Contoso\Elsewhere");
using (user.CreateSubKey(@"Software\SyncEngines\Providers\OneDrive\Empty")) { }
var roots = OneDriveFolders.SyncRoots(user);
Assert.Equal(1, roots.Count(r => string.Equals(r, account, StringComparison.OrdinalIgnoreCase)), "the account's folder once");
Assert.Contains(roots, r => string.Equals(r, library, StringComparison.OrdinalIgnoreCase));
Assert.False(roots.Any(r => r.EndsWith("Elsewhere", StringComparison.OrdinalIgnoreCase)), "a relative mount point is ignored");
// A portable copy unpacked in that library keeps its data in %LOCALAPPDATA%\Chronos.
var app = Directory.CreateDirectory(Path.Combine(library, "Tools", "Chronos")).FullName;
File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), "");
var local = context.CreateTempDirectory("local");
var paths = AppPaths.Resolve(app, local, roots);
Assert.True(paths.IsPortable);
Assert.Equal(Path.Combine(local, AppPaths.ProductFolderName), paths.DataRoot);
Assert.True(string.Equals(library, paths.PortableSyncRoot, StringComparison.OrdinalIgnoreCase), $"sync root {paths.PortableSyncRoot}");
}
finally
{
Registry.CurrentUser.DeleteSubKeyTree(hive, throwOnMissingSubKey: false);
}
}
}
@@ -0,0 +1,57 @@
using Chronos.Core.Windows.Shell;
using Chronos.Testing;
namespace Chronos.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 Chronos.Core.Windows.Wic;
using Chronos.Testing;
namespace Chronos.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 Chronos.Core.Imaging;
using Chronos.Core.Windows.Wic;
using Chronos.Testing;
namespace Chronos.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 Chronos.Core.Codecs.Png;
using Chronos.Core.Windows.Interop;
using Chronos.Core.Windows.Wic;
namespace Chronos.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 Chronos.Core.Windows.Window;
using Chronos.Testing;
namespace Chronos.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));
}
}