refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s

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 and the system SQLite. 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; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

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>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-23 12:45:18 +02:00
1 parent c99842cc86
commit f2b58522b9
1801 files changed
+11804 -10676

No files matched your search

@@ -0,0 +1,17 @@
namespace Chronos.App.Infrastructure;
/// <summary>
/// Today's date for screens that lay themselves out around it (the Library timeline's years, the months of the
/// Archive heatmap). <c>--capture</c> freezes it at the sample's moment, so the screenshots draw the same pixels on
/// any day and the pixel diff against their baselines stays meaningful.
/// </summary>
public static class AppClock
{
private static DateTimeOffset? _frozen;
/// <summary>The local date: the frozen moment's while frozen, the computer's otherwise.</summary>
public static DateTime Today => (_frozen?.ToLocalTime().DateTime ?? DateTime.Now).Date;
/// <summary>Stops the clock at <paramref name="moment"/> for the rest of the process (screenshots only).</summary>
public static void Freeze(DateTimeOffset moment) => _frozen = moment;
}
@@ -0,0 +1,80 @@
using System.IO;
using Chronos.Core.Windows.Shell;
namespace Chronos.App.Infrastructure;
/// <summary>
/// Where the client keeps its data (BRIEF §6.2, <see cref="AppPaths"/>): <c>%LOCALAPPDATA%\Chronos</c>, or <c>.\data</c>
/// next to the executable when <c>portable.txt</c> exists. Never inside a folder OneDrive synchronises (SQLite corrupts
/// there): a portable copy in one keeps its data in <c>%LOCALAPPDATA%\Chronos</c>, and Settings tells the user so
/// (<see cref="PortableSyncRoot"/>, <see cref="EarlierPortableData"/>). When that folder itself lies in one, nowhere
/// is safe: Chronos starts all the same and Settings warns (<see cref="SyncedFolder"/>).
/// </summary>
public sealed class AppEnvironment
{
private AppEnvironment(string dataDirectory, bool portable, bool isCapture, string? syncedFolder = null, string? portableSyncRoot = null,
string? earlierPortableData = null)
{
DataDirectory = dataDirectory;
IsPortable = portable;
IsCapture = isCapture;
SyncedFolder = syncedFolder;
PortableSyncRoot = portableSyncRoot;
EarlierPortableData = earlierPortableData;
Directory.CreateDirectory(DataDirectory);
Directory.CreateDirectory(LogDirectory);
Directory.CreateDirectory(CacheDirectory);
}
public string DataDirectory { get; }
public bool IsPortable { get; }
/// <summary>A throw-away environment for <c>--capture</c>: nothing of the user's data is read or written.</summary>
public bool IsCapture { get; }
/// <summary>The OneDrive folder <see cref="DataDirectory"/> itself lies in, where the index may be damaged; null when it is safe.</summary>
public string? SyncedFolder { get; }
/// <summary>The OneDrive folder this portable copy runs from; its data is in <c>%LOCALAPPDATA%\Chronos</c> instead of <c>.\data</c>. Null otherwise.</summary>
public string? PortableSyncRoot { get; }
/// <summary>The <c>.\data</c> folder this portable copy used before it ran from OneDrive, left as it was; null when there is none.</summary>
public string? EarlierPortableData { get; }
public string LogDirectory => Path.Combine(DataDirectory, "logs");
public string CacheDirectory => Path.Combine(DataDirectory, "cache");
public string BackupDirectory => Path.Combine(DataDirectory, "backups");
public string DatabasePath => Path.Combine(DataDirectory, AppPaths.DatabaseFileName);
public string SettingsPath => Path.Combine(DataDirectory, AppPaths.SettingsFileName);
/// <summary>The environment of this process: its executable's folder and the user's OneDrive folders decide.</summary>
public static AppEnvironment Detect() => From(AppPaths.Resolve());
/// <summary>The environment at <paramref name="paths"/> (its folders are created).</summary>
public static AppEnvironment From(AppPaths paths)
{
ArgumentNullException.ThrowIfNull(paths);
return new(paths.DataRoot, paths.IsPortable, isCapture: false, paths.SyncedFolder, paths.PortableSyncRoot, paths.EarlierPortableData);
}
/// <summary>A fresh temporary data folder for screenshots and smoke tests; delete it with <see cref="DeleteCaptureData"/>.</summary>
public static AppEnvironment ForCapture() =>
new(Path.Combine(Path.GetTempPath(), "chronos-capture-" + Guid.CreateVersion7().ToString("N")), portable: false, isCapture: true);
/// <summary>Removes the temporary data folder of a capture environment (never a real one).</summary>
public void DeleteCaptureData()
{
if (!IsCapture) return;
try
{
Directory.Delete(DataDirectory, recursive: true);
}
catch (IOException)
{
// Files still open (log, database) are left to the OS temp cleanup.
}
catch (UnauthorizedAccessException)
{
}
}
}
@@ -0,0 +1,473 @@
using System.ComponentModel;
using System.IO;
using System.Net.Http;
using System.Reflection;
using Chronos.App.About;
using Chronos.App.Archiving;
using Chronos.App.Import;
using Chronos.App.Jobs;
using Chronos.App.Library;
using Chronos.App.Server;
using Chronos.App.Settings;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Model;
using Chronos.Core.Video.Managed;
using Chronos.Core.Windows.MediaFoundation;
using Chronos.Core.Windows.Wic;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Protocol.Client;
namespace Chronos.App.Infrastructure;
/// <summary>
/// Composition root of local mode (BRIEF §4.4): the SQLite index under the data folder (migrated on open, a restore
/// staged in Settings › Advanced carried out first, then copied once a day into the backups folder), the archive engine
/// (WIC first, then managed decoders), the analysis and render engine (the same decoders; Media Foundation, then
/// managed encoders), the one <see cref="JobEngine"/> of this PC with the handlers of <see cref="CreateJobHandlers"/>,
/// thumbnails, the server session, the render node, the encoder and format inventories, the update check and the sync
/// with the signed-in server (<see cref="SyncHost"/>). Started after the window shows, stopped when the app exits. The
/// archive at Settings › Archive's folder is reopened at start and rescanned every <see cref="ScanInterval"/>, as is one
/// chosen later (BRIEF §7: polling, no file-system watchers). Jobs follow Settings › Rendering and Analysis from the
/// next one on (memory budget, quality profile, analysis parameters through <see cref="ProcessingTuning"/>; parallelism
/// as the engine's workers). The render node runs while the user offers this PC (<see cref="AppSettings.RenderNodeOptIn"/>)
/// and a server session is open (never in capture mode). Renders and the render node use hardware encoders as
/// Settings › Rendering allows (<see cref="AllowsHardware(HardwarePreference, string)"/>). Disposal never needs the UI
/// thread, which waits for it.
/// </summary>
public sealed class AppServices : IAsyncDisposable
{
/// <summary>The quick preview preset: the one render "Hardware for previews only" leaves on the GPU.</summary>
private const string PreviewPresetId = "720p-preview";
private static readonly Lazy<HttpClient> Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) });
/// <summary>Update packages are large: their download fails when it stalls (<see cref="UpdateDownload.IdleTimeout"/>), never after a fixed total time.</summary>
private static readonly Lazy<HttpClient> DownloadHttp = new(() => new HttpClient { Timeout = Timeout.InfiniteTimeSpan });
private readonly CancellationTokenSource _stopping = new();
private readonly Dictionary<Guid, Guid> _scans = [];
private Task _polling = Task.CompletedTask;
private Task _backups = Task.CompletedTask;
private PeriodicTimer? _pollTimer;
private WicDecoderProvider? _wic;
private readonly RenderNodeHost _renderNode;
private ServerSession _server = null!;
public AppServices(AppEnvironment environment, AppSettings settings, Action saveSettings, IAppDialogs dialogs)
{
Environment = environment;
Settings = settings;
SaveSettingsAction = saveSettings;
Dialogs = dialogs;
_renderNode = new RenderNodeHost(StartRenderNode);
ArchiveSetup = new EngineArchiveSetup(this);
Sync = new SyncHost(this);
Server = new ServerSession(settings, saveSettings, new ChronosServerApiFactory(), new DpapiTokenProtector());
Encoders = new MediaFoundationInventory();
Formats = new WicFormatInventory(() => _wic);
CheckForUpdateAsync = ct => UpdateCheck.FetchAsync(Http.Value, ProductLinks.StableReleasesApi, VersionText, ct);
DownloadUpdateAsync = (release, progress, ct) =>
UpdateDownload.DownloadAsync(DownloadHttp.Value, release, environment.IsPortable, UpdateDownload.Root(Path.GetTempPath()), VersionText, progress,
UpdateDownload.IdleTimeout, ct);
}
public AppEnvironment Environment { get; }
public AppSettings Settings { get; }
public IAppDialogs Dialogs { get; }
private Action SaveSettingsAction { get; }
/// <summary>First-run and Library archive actions.</summary>
public IArchiveSetup ArchiveSetup { get; set; }
/// <summary>The archive engine; null until the index is open.</summary>
public ArchiveService? Archives { get; private set; }
/// <summary>Analysis and render engine; null until the index is open.</summary>
public ProcessingService? Processing { get; private set; }
public ServerSession Server
{
get => _server;
set
{
if (_server is not null) _server.PropertyChanged -= OnServerChanged;
_server = value;
_server.PropertyChanged += OnServerChanged;
UpdateRenderNode();
Sync.Update();
}
}
/// <summary>Sync with the signed-in server: engine, job connection, background comparison.</summary>
public SyncHost Sync { get; }
public IEncoderInventory Encoders { get; set; }
/// <summary>Decode tier per format on this PC and the missing codec extensions (Settings › Formats).</summary>
public IFormatInventory Formats { get; set; }
/// <summary>Time between the rescans of the open archive (Settings › Archive).</summary>
public TimeSpan ScanInterval => TimeSpan.FromMinutes(int.Clamp(Settings.ScanIntervalMinutes, 1, 24 * 60));
/// <summary>How the restore staged in Settings › Advanced went when the index opened; null when none was staged.</summary>
public StagedRestoreResult? StagedRestore { get; private set; }
/// <summary>Card detection, eject and format (BRIEF §13); started with the index, replaced by a fake in capture.</summary>
public IDeviceMonitor Devices { get; set; } = new WindowsDeviceMonitor();
/// <summary>Latest public release (Gitea releases API of the releases repository, BRIEF §18).</summary>
public Func<CancellationToken, Task<ReleaseInfo?>> CheckForUpdateAsync { get; set; }
/// <summary>Downloads and verifies the package of a release for this copy (setup, or portable zip; BRIEF §18 P1) and returns its path.</summary>
public Func<ReleaseInfo, IProgress<double>?, CancellationToken, Task<string>> DownloadUpdateAsync { get; set; }
/// <summary>The index; null until <see cref="OpenAsync"/> succeeded.</summary>
public ChronosDatabase? Database { get; private set; }
public JobEngine? Engine { get; private set; }
public IJobQueue? Jobs { get; private set; }
public ThumbnailService? Thumbnails { get; private set; }
/// <summary>Why the index could not be opened; null when it is open.</summary>
public Exception? OpenError { get; private set; }
/// <summary>Node id of this PC's workers.</summary>
public string WorkerId { get; init; } = System.Environment.MachineName;
/// <summary>"0.1.0" (informational version).</summary>
public static string VersionText { get; } =
typeof(AppServices).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
/// <summary>The job handlers of this PC's engine — the single registration list; a kind without a handler stays
/// queued (it is never claimed here).</summary>
public static IReadOnlyList<IJobHandler> CreateJobHandlers(AppServices services) =>
[
.. services.Archives?.CreateJobHandlers() ?? [], .. services.Processing?.CreateJobHandlers() ?? [],
.. services.Sync.Service?.CreateJobHandlers(services.Sync) ?? [],
];
/// <summary>
/// Queues a scan of <paramref name="archive"/> unless one is already waiting or running; the sequences it indexes get
/// a background deep analysis when Settings › Analysis asks for it.
/// </summary>
public async Task QueueScanAsync(Archive archive, bool full, CancellationToken ct = default)
{
if (Engine is null || Database is null) return;
Guid previous;
lock (_scans)
{
_scans.TryGetValue(archive.Id, out previous);
}
if (previous != Guid.Empty && await Database.Jobs.GetAsync(previous, ct) is { State: JobState.Queued or JobState.Running }) return;
var job = await Engine.EnqueueAsync(ArchiveJobs.Scan(archive, full, Settings.DeepAnalysisAfterScan), cancellationToken: ct);
lock (_scans)
{
_scans[archive.Id] = job.Id;
}
}
public void SaveSettings()
{
SaveSettingsAction();
UpdateRenderNode();
ApplyJobSettings();
}
/// <summary>Writes the settings file and nothing else: for choices that change only what is shown (the rail, the sequence edited last).</summary>
public void SavePreferences() => SaveSettingsAction();
/// <summary>
/// The archive's rescan interval, now, and a review of the priority queue (Settings › Rendering): turned on, it may make
/// the running job yield at once. The parallelism applies from the next sequence or job.
/// </summary>
public void ApplyJobSettings()
{
Engine?.Wake();
if (_pollTimer is { } timer && timer.Period != ScanInterval) timer.Period = ScanInterval;
}
/// <summary>Photos the running job of this PC processes at once (Settings › Rendering › Parallelism, Auto: half the logical cores).</summary>
public int Parallelism => ProcessingTuning.Parallelism(Settings, System.Environment.ProcessorCount);
/// <summary>The priority queue of Settings › Rendering, as the job engine reads it.</summary>
public JobPriorityQueue PriorityQueue => JobPriorityQueue.From(Settings.PriorityQueue, Settings.JobPriorities);
/// <summary>Starts, restarts or stops the render node to match the opt-in, the server session and the trusted certificates (BRIEF §14.7).</summary>
public void UpdateRenderNode() =>
_renderNode.Update(RenderNodeSession.For(Settings.RenderNodeOptIn && Processing is not null && !Environment.IsCapture, _server.IsConnected,
_server.Flow.Address, _server.Flow.Token, _server.Fingerprints, AllowsHardware(Settings.HardwareEncoding, ExportResolver.CustomId)));
/// <summary>Settings › Rendering: whether a render of <paramref name="presetId"/> may use hardware encoders.</summary>
public static bool AllowsHardware(HardwarePreference preference, string presetId) => preference switch
{
HardwarePreference.PreferHardware => true,
HardwarePreference.HardwareForPreviews => presetId.Equals(PreviewPresetId, StringComparison.OrdinalIgnoreCase),
_ => false,
};
/// <summary>
/// Opens (or creates) the index at <paramref name="databasePath"/>, migrates it (after a restore staged in Settings ›
/// Advanced replaced it, which needs no open index: it also recovers one that no longer opens), starts the job engine
/// and the daily backups.
/// </summary>
public async Task OpenAsync(string databasePath, CancellationToken ct = default)
{
await RestoreStagedAsync(databasePath, ct);
try
{
Database = await Task.Run(() => ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(databasePath), ct), ct);
Log.Info("app", $"Index open (schema {Database.SchemaVersion}) at {databasePath}");
}
catch (Exception ex) when (ex is DatabaseException or System.IO.IOException or UnauthorizedAccessException or DllNotFoundException)
{
OpenError = ex;
Log.Error("app", "The index could not be opened", ex);
return;
}
await StartJobsAsync(Database, startEngine: true, ct);
Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems);
Devices.Start();
var database = Database;
_backups = Task.Run(() => DatabaseBackups.RunDailyAsync(database, Environment.BackupDirectory, null, _stopping.Token));
_polling = PollAsync(_stopping.Token);
}
/// <summary>Uses an already open index (capture, tests) instead of opening one; sample data keeps the engine stopped.</summary>
public async Task AttachAsync(ChronosDatabase database, bool startEngine = true, CancellationToken ct = default)
{
Database = database;
await StartJobsAsync(database, startEngine, ct);
Thumbnails = new ThumbnailService(database, Settings.ThumbnailMemoryItems);
}
/// <summary>Stops polling, the render node and the engine, then closes the index. The app's exit waits for this on the UI
/// thread, so nothing here continues on it.</summary>
public async ValueTask DisposeAsync()
{
await _stopping.CancelAsync().ConfigureAwait(false);
await _polling.ConfigureAwait(false);
await _backups.ConfigureAwait(false);
_stopping.Dispose();
_server.PropertyChanged -= OnServerChanged;
await _renderNode.DisposeAsync().ConfigureAwait(false);
await Sync.DisposeAsync().ConfigureAwait(false);
(Jobs as IDisposable)?.Dispose();
if (Engine is not null) await Engine.DisposeAsync().ConfigureAwait(false);
Thumbnails?.Dispose();
Devices.Dispose();
Server.Dispose();
if (Database is not null) await Database.DisposeAsync().ConfigureAwait(false);
}
/// <summary>The period of the rescans while they run (Settings › Archive › Rescan every); null before the index opens.</summary>
internal TimeSpan? PollingPeriod => _pollTimer?.Period;
/// <summary>
/// One rescan of the polling, off the UI thread: the archive the Import and Archive screens work on
/// (<see cref="CurrentArchive"/>, the one at Settings › Archive's folder) first takes the settings another process
/// sharing it wrote into its archive.json (also on a read-only share), then gets an incremental scan while it is
/// online. Returns that archive; null when the index holds none.
/// </summary>
internal Task<Archive?> RescanAsync(CancellationToken ct = default) => Task.Run(async () =>
{
if (Database is not { } db || Archives is not { } archives) return null;
var archive = CurrentArchive.Pick(await db.Archives.ListAsync(ct).ConfigureAwait(false), Settings.LastArchivePath);
if (archive is null) return null;
var availability = ArchiveService.GetAvailability(archive);
if (availability != ArchiveAvailability.Offline) await archives.RefreshSettingsAsync(archive.Id, ct).ConfigureAwait(false);
if (availability == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct).ConfigureAwait(false);
return archive;
}, ct);
/// <summary>
/// Rescans the archive now and every <see cref="ScanInterval"/> (<see cref="RescanAsync"/>) until the app exits, which
/// waits for it on the UI thread. Each rescan follows the archive folder: one chosen on the first run, in Settings or
/// by a relink is rescanned from the next tick on, the one before no longer. The archive at the folder of the start is
/// first reopened (a moved one relinked, interrupted renames finished), at each tick until its archive.json is there
/// (an unplugged drive), unless the folder changed meanwhile: whatever changed it opened the new archive.
/// </summary>
private async Task PollAsync(CancellationToken ct)
{
var reopen = Settings.LastArchivePath is { Length: > 0 } start ? start : null;
// Settings › Archive changes the period of this timer (ApplyJobSettings).
using var timer = _pollTimer = new PeriodicTimer(ScanInterval);
try
{
do
{
if (reopen is not null
&& (!string.Equals(reopen, Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase) || await ReopenAsync(reopen, ct).ConfigureAwait(false)))
reopen = null;
try
{
await RescanAsync(ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or ArgumentException)
{
// The next tick tries again (a share that dropped, an archive removed from the index meanwhile).
Log.Warning("archive", "The archive could not be rescanned", ex);
}
}
while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false));
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
}
finally
{
_pollTimer = null;
}
}
/// <summary>
/// Registers the archive at <paramref name="root"/> again as at open; false while its archive.json is not there. A
/// damaged or newer one is not tried again: the archive the index holds at the folder is still rescanned.
/// </summary>
private async Task<bool> ReopenAsync(string root, CancellationToken ct)
{
if (Archives is not { } archives) return true;
try
{
return await Task.Run(async () =>
{
if (!File.Exists(new ArchivePaths(root).ManifestPath)) return false;
await archives.OpenAsync(root, ct).ConfigureAwait(false);
return true;
}, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or NewerFormatException)
{
Log.Warning("archive", $"The archive at {root} could not be opened", ex);
return true;
}
}
/// <summary>
/// A restore staged in Settings › Advanced replaces the index file before the index is opened, so it also recovers an
/// index that no longer opens (<see cref="StagedRestore"/>).
/// </summary>
private async Task RestoreStagedAsync(string databasePath, CancellationToken ct)
{
try
{
if (await Task.Run(() => DatabaseBackups.RestoreStagedAsync(databasePath, Environment.BackupDirectory, ct), ct))
{
StagedRestore = StagedRestoreResult.Restored;
Log.Info("app", $"Index at {databasePath} restored from the staged copy");
}
}
catch (InvalidDataException ex)
{
StagedRestore = StagedRestoreResult.Unreadable;
Log.Error("app", "The staged index copy failed its checks; it was set aside and the index kept", ex);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException or DllNotFoundException)
{
StagedRestore = StagedRestoreResult.Deferred;
Log.Error("app", "The staged index restore could not run; the index was kept and the restore stays staged", ex);
}
}
private async Task StartJobsAsync(ChronosDatabase database, bool startEngine, CancellationToken ct)
{
_wic = new WicDecoderProvider();
var archive = new ArchiveServiceOptions
{
Decoder = DecoderFactory.CreateClient(_wic),
Parallelism = () => Parallelism,
MemoryBudget = () => ProcessingTuning.MemoryBudget(Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes),
};
Archives = new ArchiveService(database, archive);
Processing = new ProcessingService(database, ProcessingOptions(archive));
Sync.Open(database, Archives, archive);
var handlers = CreateJobHandlers(this);
var kinds = handlers.Select(h => h.Kind).Distinct().ToArray();
// One job at a time (owner review 1): the parallelism works inside it, the priority queue decides which runs.
Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds, PriorityQueue = () => PriorityQueue });
// Sync follows the engine's jobs before it runs any: a render resumed at start that finishes at once is still sent (Export "Sync").
Sync.Update();
// With no handler the engine must not run: an empty kind list would let workers claim (and fail) every job.
var started = startEngine && handlers.Count > 0;
if (started) await Engine.StartAsync(ct);
Jobs = new EngineJobQueue(database, Engine, started);
Log.Info("jobs", started ? $"Job engine started for {string.Join(", ", kinds)}" : "No job handlers registered; jobs stay queued");
UpdateRenderNode();
}
/// <summary>Media Foundation (hardware first, software H.264; hardware as Settings › Rendering allows) then managed
/// encoders; at the start of each job the options take the current Settings › Rendering and Analysis (memory budget,
/// Auto a quarter of the installed memory; cache folder; quality profile; parallelism; analysis width and thresholds).</summary>
private ProcessingOptions ProcessingOptions(ArchiveServiceOptions archive) => new()
{
Archive = archive,
Encoders = [new MediaFoundationEncoderProvider(), new ManagedEncoderProvider()],
AllowsHardware = presetId => AllowsHardware(Settings.HardwareEncoding, presetId),
Host = EncoderHost.Client,
ProducedBy = System.Environment.MachineName,
Tune = basis => ProcessingTuning.Apply(basis, Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes, System.Environment.ProcessorCount,
CacheStore.Folder(Environment, Settings)),
};
private void OnServerChanged(object? sender, PropertyChangedEventArgs e)
{
UpdateRenderNode();
Sync.Update();
}
/// <summary>
/// The render node of <paramref name="session"/>: this PC's encoders (Media Foundation, then managed), downloads and
/// outputs in the cache folder within its size limit.
/// </summary>
private IRenderNode StartRenderNode(RenderNodeSession session)
{
var processing = Processing ?? throw new InvalidOperationException("The index is not open.");
var cache = CacheStore.Folder(Environment, Settings);
CacheStore.Prepare(cache);
var client = new ChronosClient(session.Address, new CertificatePinning(session.TrustedFingerprints), $"Chronos ({System.Environment.MachineName})")
{
Token = session.Token,
};
var node = new RenderNodeClient(client, processing.Options, new RenderNodeOptions
{
ClientName = System.Environment.MachineName,
CacheDirectory = Path.Combine(cache, "render-node"),
CacheLimitBytes = Settings.CacheLimitGb * (1L << 30),
});
node.Start();
return new RunningNode(node, client);
}
/// <summary>A started node and the client it owns.</summary>
private sealed class RunningNode(RenderNodeClient node, ChronosClient client) : IRenderNode
{
public Task Completion => node.Completion;
public async ValueTask DisposeAsync()
{
await node.DisposeAsync().ConfigureAwait(false);
client.Dispose();
}
}
}
/// <summary>How a restore staged in Settings › Advanced went at start.</summary>
public enum StagedRestoreResult
{
/// <summary>The index is the chosen backup now; the one it replaced was backed up first.</summary>
Restored,
/// <summary>The staged copy failed its checks: it was set aside and the index kept.</summary>
Unreadable,
/// <summary>The index could not be backed up or replaced: it was kept and the restore runs at the next start.</summary>
Deferred,
}
@@ -0,0 +1,254 @@
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using Chronos.Core.Analysis.Deep;
using Chronos.Core.Archiving;
using Chronos.Core.Import;
using Chronos.Core.IO;
using Chronos.Core.Naming;
using Chronos.Data.Archiving;
using Chronos.Data.Repositories;
using Chronos.Ui.Theming;
namespace Chronos.App.Infrastructure;
/// <summary>Library presentation (BRIEF §12.2).</summary>
public enum LibraryLayout
{
Grid,
List,
/// <summary>Year bands with photos per month above the card grid.</summary>
Timeline,
}
/// <summary>Rendering quality profile (Settings › Rendering).</summary>
public enum QualityProfile
{
Best,
Balanced,
Fast,
}
/// <summary>Which encoders a render may use (Settings › Rendering).</summary>
public enum HardwarePreference
{
PreferHardware,
SoftwareOnly,
HardwareForPreviews,
}
/// <summary>A server certificate the user trusted on first use (BRIEF §12.7).</summary>
public sealed class TrustedCertificate
{
public string Fingerprint { get; set; } = string.Empty;
public string? Server { get; set; }
public DateTimeOffset TrustedAt { get; set; }
}
/// <summary>
/// Per-user preferences (language, theme, window layout, archive defaults, server session). Kept in
/// <c>settings.json</c> next to the database and written atomically, because language and theme apply before the
/// database opens.
/// </summary>
public sealed class AppSettings
{
public const int DefaultThumbnailMemoryItems = 2_000;
public const int DefaultCacheLimitGb = 20;
public const int DefaultScanIntervalMinutes = 10;
/// <summary>2⁻⁴ of white: the deep analysis' night threshold (a mean log2 luminance of −4).</summary>
public const double DefaultNightBrightnessPercent = 6.25;
// ---- General ----
public string? Language { get; set; }
public AppTheme Theme { get; set; } = AppTheme.Dark;
public bool RailCollapsed { get; set; }
/// <summary>The sequence opened in Edit last; the picker selects it first (owner review 1, R7).</summary>
public Guid? LastEditedSequence { get; set; }
/// <summary>The first-run consent of BRIEF §21; offered only by builds with <see cref="ProductFeatures.AdsEnabled"/>.</summary>
public bool AnonymousUsageCounts { get; set; }
/// <summary>Toasts also appear as Windows notifications while the window is minimised or in the background (BRIEF §12.1).</summary>
public bool OsNotifications { get; set; } = true;
public WindowPlacement? Window { get; set; }
/// <summary>The first-run choice (local archive, adopted folder or server) was made.</summary>
public bool FirstRunCompleted { get; set; }
// ---- Updates ----
public bool CheckForUpdates { get; set; } = true;
// ---- Archive ----
/// <summary>Root of the local archive; null until the first-run choice or Settings › Archive sets it.</summary>
public string? LastArchivePath { get; set; }
/// <summary>Naming templates of new archives; Settings › Archive also writes them into the open archive's archive.json.</summary>
public string FolderTemplate { get; set; } = TemplateDefaults.Folder;
public string FileTemplate { get; set; } = TemplateDefaults.File;
/// <summary>Proxy long edge of new archives (also written into the open archive); 0 = full size, -1 = no proxies.</summary>
public int ProxyLongEdge { get; set; } = 1920;
/// <summary>Thumbnail long edge of new archives (also written into the open archive), BRIEF §8.5.</summary>
public int ThumbnailLongEdge { get; set; } = 320;
/// <summary>Minutes between the rescans of the open archive (BRIEF §7: polling by mtime and size, no file-system watchers).</summary>
public int ScanIntervalMinutes { get; set; } = DefaultScanIntervalMinutes;
// ---- Import (defaults of new cards and folders; a card's own profile wins) ----
public int ImportSessionGapMinutes { get; set; } = 45;
public int ImportMinimumFrames { get; set; } = 8;
public bool ImportSubfolders { get; set; } = true;
public bool ImportVerify { get; set; } = true;
public DuplicatePolicy ImportDuplicates { get; set; } = DuplicatePolicy.Skip;
public AfterImport ImportAfter { get; set; } = AfterImport.Keep;
public bool ImportEject { get; set; } = true;
// ---- Analysis ----
/// <summary>Upper bound of the deep-analysis long edge (BRIEF §10.2: half native, capped at 2048 by default).</summary>
public int AnalysisLongEdge { get; set; } = 2048;
/// <summary>Frames whose mean brightness is at or below this share of white (in percent) count as night frames.</summary>
public double NightBrightnessPercent { get; set; } = DefaultNightBrightnessPercent;
/// <summary>Stars per megapixel from which a night frame shows a star field.</summary>
public double StarFieldDensity { get; set; } = 30;
/// <summary>The default of a new card's "Deep analysis" after import (BRIEF §13: on, in the background).</summary>
public bool DeepAnalysisAfterImport { get; set; } = true;
/// <summary>Sequences a scan of this PC indexes (adopted folders, new sidecars) also get a background deep analysis.</summary>
public bool DeepAnalysisAfterScan { get; set; }
// ---- Library ----
public LibraryLayout LibraryLayout { get; set; } = LibraryLayout.Grid;
public SequenceSort LibrarySort { get; set; } = SequenceSort.Newest;
// ---- Rendering ----
public QualityProfile Quality { get; set; } = QualityProfile.Balanced;
/// <summary>Frame memory budget in GB; null = Auto (a quarter of installed memory).</summary>
public int? MemoryBudgetGb { get; set; }
/// <summary>Photos the running job processes at once (owner review 1: jobs run one at a time); null = Auto (half the logical cores, at least one).</summary>
public int? Parallelism { get; set; }
public bool BackgroundPriority { get; set; } = true;
public HardwarePreference HardwareEncoding { get; set; } = HardwarePreference.PreferHardware;
// ---- Storage ----
/// <summary>Cache (spill frames, thumbnails); null = <c>cache</c> under the data folder.</summary>
public string? CacheFolder { get; set; }
/// <summary>Decoded thumbnails kept in memory.</summary>
public int ThumbnailMemoryItems { get; set; } = DefaultThumbnailMemoryItems;
/// <summary>Upper bound of the disk cache in GB.</summary>
public int CacheLimitGb { get; set; } = DefaultCacheLimitGb;
// ---- Server ----
public string? ServerUrl { get; set; }
public string? ServerUsername { get; set; }
/// <summary>The session token, encrypted for this Windows user with DPAPI (Base64).</summary>
public string? ProtectedToken { get; set; }
public List<TrustedCertificate> TrustedCertificates { get; set; } = [];
public List<string> RecentServers { get; set; } = [];
/// <summary>Let the server send render jobs to this PC (BRIEF §14.7).</summary>
public bool RenderNodeOptIn { get; set; }
/// <summary>Keep the proxy caches of the server sequences this PC opened with proxies up to date (BRIEF §12.7).</summary>
public bool KeepProxiesOffline { get; set; }
/// <summary>Send and take project settings changed on one side without asking (Server.html).</summary>
public bool SyncSettingsAutomatically { get; set; } = true;
/// <summary>Pause upload jobs while Windows reports the connection as metered (Server.html).</summary>
public bool PauseUploadsOnMetered { get; set; }
// ---- Jobs ----
/// <summary>
/// The priority queue (owner review 1): a job of a higher level makes the running one of a lower level yield, and that
/// one resumes by itself afterwards. Off: jobs wait their turn.
/// </summary>
public bool PriorityQueue { get; set; }
/// <summary>Levels of the priority queue that differ from the defaults, by job kind (<c>render</c> → <c>high</c>).</summary>
public Dictionary<string, string> JobPriorities { get; set; } = [];
/// <summary>"Clear done": finished jobs older than this are hidden from the Jobs list (they stay in the history).</summary>
public DateTimeOffset? JobsClearedAt { get; set; }
public sealed class WindowPlacement
{
public double Left { get; set; }
public double Top { get; set; }
public double Width { get; set; }
public double Height { get; set; }
public bool Maximized { get; set; }
}
/// <summary>Settings › Archive as the settings of a new archive (its name: the folder's).</summary>
public ArchiveSettings ArchiveDefaults() => new(string.Empty, new LayoutTemplates { Folder = FolderTemplate, File = FileTemplate },
new ProxyPolicy { LongEdge = ProxyLongEdge }, new ThumbnailPolicy { LongEdge = ThumbnailLongEdge });
/// <summary>Settings › Import and Analysis as the profile of a card or folder without its own (BRIEF §12.4), with the archive's templates.</summary>
public CardProfile ImportProfile(string folderTemplate, string fileTemplate) => new()
{
FolderTemplate = folderTemplate,
FileTemplate = fileTemplate,
SessionGapMinutes = ImportSessionGapMinutes,
MinimumSessionFrames = ImportMinimumFrames,
IncludeSubfolders = ImportSubfolders,
VerifyCopies = ImportVerify,
Duplicates = ImportDuplicates,
AfterImport = ImportAfter,
Eject = ImportEject,
DeepAnalysis = DeepAnalysisAfterImport,
};
/// <summary>Settings › Analysis over <paramref name="basis"/>: the width cap and the night and star-field thresholds.</summary>
public DeepAnalysisOptions DeepAnalysis(DeepAnalysisOptions basis) => basis with
{
MaxAnalysisLongEdge = int.Max(basis.MinAnalysisLongEdge, AnalysisLongEdge),
DarkLogLuminance = System.Math.Log2(double.Clamp(NightBrightnessPercent, 0.01, 100) / 100),
StarFieldDensity = double.Max(0, StarFieldDensity),
};
public static AppSettings Load(string path)
{
try
{
if (File.Exists(path)) return Parse(File.ReadAllText(path)) ?? new AppSettings();
}
catch (JsonException)
{
// A corrupt settings file must never block startup; defaults apply.
}
catch (IOException)
{
}
return new AppSettings();
}
/// <summary>Reads settings JSON (Settings › Import); null when the text is not a settings object.</summary>
/// <exception cref="JsonException">The text is not valid JSON.</exception>
public static AppSettings? Parse(string json) => JsonSerializer.Deserialize(json, AppSettingsJson.Default.AppSettings);
public string ToJson() => JsonSerializer.Serialize(this, AppSettingsJson.Default.AppSettings);
public void Save(string path) => AtomicFile.WriteAllText(path, ToJson());
/// <summary>A deep copy (JSON round trip), used for import and reset.</summary>
public AppSettings Clone() => Parse(ToJson()) ?? new AppSettings();
}
[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true)]
[JsonSerializable(typeof(AppSettings))]
internal sealed partial class AppSettingsJson : JsonSerializerContext;
@@ -0,0 +1,139 @@
using System.IO;
using Chronos.App.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Data.Archiving;
namespace Chronos.App.Infrastructure;
/// <summary>
/// First-run and Library archive choices (BRIEF §12.1): create a local archive or adopt an existing folder tree.
/// </summary>
public interface IArchiveSetup
{
/// <summary>Creates (or opens) the local archive rooted at <paramref name="root"/>.</summary>
Task CreateAsync(string root, CancellationToken cancellationToken = default);
/// <summary>Indexes the photos under <paramref name="folder"/> in place, or opens a previous Chronos archive there.</summary>
Task AdoptAsync(string folder, CancellationToken cancellationToken = default);
}
/// <summary>
/// Creates or adopts the archive through the archive engine (originals stay where they are), remembers it as the
/// archive to open at start and queues a full scan that indexes its sequences. A folder that becomes a new archive gets
/// the naming templates, proxy size and thumbnail size of Settings › Archive; an existing archive keeps its own.
/// </summary>
public sealed class EngineArchiveSetup(AppServices services) : IArchiveSetup
{
public Task CreateAsync(string root, CancellationToken cancellationToken = default) => OpenAsync(root, cancellationToken);
public Task AdoptAsync(string folder, CancellationToken cancellationToken = default) => OpenAsync(folder, cancellationToken);
private async Task OpenAsync(string path, CancellationToken cancellationToken)
{
var archives = services.Archives ?? throw new InvalidOperationException("The index is not open.", services.OpenError);
var root = Path.GetFullPath(path);
var defaults = services.Settings.ArchiveDefaults();
var archive = await Task.Run(async () =>
{
Directory.CreateDirectory(root);
return await archives.AdoptAsync(root, defaults, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
services.Settings.LastArchivePath = root;
services.SaveSettings();
await services.QueueScanAsync(archive, full: true, cancellationToken);
Log.Info("archive", $"Archive {archive.Name} ready at {root}");
}
}
/// <summary>
/// Runs an archive action from the UI; a failure becomes a toast instead of an unhandled exception. The toast says why
/// in one localized sentence (<see cref="Cause"/>); the exception's own text stays in the log.
/// </summary>
public static class ArchiveActions
{
public static async Task<bool> TryAsync(Shell.ShellViewModel shell, Func<IArchiveSetup, Task> action)
{
try
{
await action(shell.Services.ArchiveSetup);
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or InvalidDataException
or ArgumentException or Data.DatabaseException)
{
Log.Error("archive", "Archive action failed", ex);
shell.Notify(Core.Localization.Loc.L("Errors.Archive.Open"), Cause(ex), isError: true);
return false;
}
}
/// <summary>
/// Why creating, opening or changing an archive failed: the archive's own sentences for files (an unreadable
/// archive.json included), access and the index (<see cref="ArchiveFailures"/>), otherwise <see cref="Shell.ErrorText"/>
/// (a catalog sentence, or "Something went wrong").
/// </summary>
public static string Cause(Exception ex) =>
ex is IOException or InvalidDataException or UnauthorizedAccessException or Data.DatabaseException ? ArchiveFailures.Cause(ex) : Shell.ErrorText.For(ex);
}
/// <summary>Archive roots offered by default and their free space.</summary>
public static class ArchiveLocations
{
public const string DefaultFolderName = "ChronosArchive";
/// <summary>"&lt;fixed drive with the most free space&gt;\ChronosArchive".</summary>
public static string SuggestRoot()
{
try
{
var best = DriveInfo.GetDrives()
.Where(d => d.DriveType == DriveType.Fixed && d.IsReady)
.OrderByDescending(d => d.AvailableFreeSpace)
.FirstOrDefault();
if (best is not null) return Path.Combine(best.RootDirectory.FullName, DefaultFolderName);
}
catch (IOException)
{
}
catch (UnauthorizedAccessException)
{
}
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), DefaultFolderName);
}
/// <summary>Free bytes on the volume of <paramref name="path"/>; null when unknown.</summary>
public static long? FreeSpace(string? path)
{
if (string.IsNullOrWhiteSpace(path)) return null;
try
{
var root = Path.GetPathRoot(Path.GetFullPath(path));
if (string.IsNullOrEmpty(root)) return null;
var drive = new DriveInfo(root);
return drive.IsReady ? drive.AvailableFreeSpace : null;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
return null;
}
}
/// <summary>The problem of an archive root as a localized sentence; null when it can be used.</summary>
public static string? Validate(string? path)
{
if (string.IsNullOrWhiteSpace(path)) return Core.Localization.Loc.L("Errors.Path.Empty");
try
{
if (!Path.IsPathFullyQualified(path)) return Core.Localization.Loc.L("Errors.Path.NotAbsolute");
var full = Path.GetFullPath(path);
if (File.Exists(full)) return Core.Localization.Loc.L("Errors.Path.IsFile");
var root = Path.GetPathRoot(full);
if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) return Core.Localization.Loc.L("Errors.Path.NoDrive");
return null;
}
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
{
return Core.Localization.Loc.L("Errors.Path.Invalid");
}
}
}
@@ -0,0 +1,199 @@
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Chronos.App.Settings;
using Chronos.Core.Diagnostics;
using Chronos.Core.Export;
using Chronos.Core.Model;
using Chronos.Core.Windows.Codecs;
using Chronos.Data;
using Chronos.Data.Sqlite;
namespace Chronos.App.Infrastructure;
/// <summary>
/// The diagnostics bundle of About and Settings › Advanced (BRIEF §12.9, §22 Phase 8): an environment report, the codec
/// and encoder inventory, the settings, the latest failed jobs and the log files, zipped into a folder the user chose.
/// Everything passes through <see cref="SecretScrubber"/> (the saved server token, passwords and keys never leave the
/// PC) and no photo or archive file is ever included.
/// </summary>
public static class DiagnosticsBundle
{
/// <summary>Failed jobs included, newest first.</summary>
public const int FailedJobs = 50;
/// <summary>
/// Writes "Chronos diagnostics yyyy-MM-dd HHmm.zip" (" (2)", " (3)"… when that name is taken) into
/// <paramref name="folder"/> and returns its path; a bundle that fails half-way leaves no file behind. Call on the UI
/// thread: the settings are captured there; detection and writing run in the background.
/// </summary>
public static Task<string> CreateAsync(AppServices services, string folder, IEnumerable<string>? extraLines = null, CancellationToken ct = default)
{
var settings = services.Settings.ToJson();
var report = Report(services.Environment, extraLines) + DatabaseLine(services.Database);
return Task.Run(async () =>
{
var failures = services.Database is { } db ? (await db.Jobs.ListAsync(JobState.Failed, FailedJobs, null, ct).ConfigureAwait(false)).Items : [];
var codecs = Codecs(services.Encoders);
var path = ExportNaming.Unique(folder, $"Chronos diagnostics {DateTime.Now.ToString("yyyy-MM-dd HHmm", CultureInfo.InvariantCulture)}", ".zip");
var temp = path + ".tmp";
try
{
await using (var file = new FileStream(temp, FileMode.Create, FileAccess.Write, FileShare.None))
using (var bundle = new DiagnosticsArchive(file))
{
bundle.AddText("environment.txt", report);
bundle.AddText("codecs.txt", codecs);
bundle.AddJson("settings.json", settings);
bundle.AddJobs("jobs-failed.json", failures);
bundle.AddLogs(services.Environment.LogDirectory, cancellationToken: ct);
}
File.Move(temp, path);
return path;
}
finally
{
// Gone after a successful move; after a failure a half-written zip helps nobody.
if (File.Exists(temp)) File.Delete(temp);
}
}, ct);
}
/// <summary>Plain-text environment report.</summary>
public static string Report(AppEnvironment environment, IEnumerable<string>? extraLines = null)
{
var sb = new StringBuilder();
sb.AppendLine(CultureInfo.InvariantCulture, $"Chronos {AppServices.VersionText}");
sb.Append(DiagnosticsArchive.SystemReport());
sb.AppendLine(CultureInfo.InvariantCulture, $"Data {environment.DataDirectory} (portable: {environment.IsPortable})");
if (extraLines is not null)
{
foreach (var line in extraLines) sb.AppendLine(line);
}
return sb.ToString();
}
private static string DatabaseLine(ChronosDatabase? database)
{
if (database is null) return "Index not open\n";
var line = string.Create(CultureInfo.InvariantCulture, $"Index schema {database.SchemaVersion}\n");
// The SQLite build's options (BRIEF §6.2) explain behaviour differences between Windows versions.
return database.Database is SqliteDatabase
? line + $"SQLite {SqliteDatabase.LibraryVersion}; compile options: {string.Join(' ', SqliteDatabase.CompileOptions)}\n"
: line;
}
/// <summary>Graphics adapter, video encoders, WIC decoders per format and missing Store extensions.</summary>
private static string Codecs(IEncoderInventory encoders)
{
var sb = new StringBuilder();
sb.AppendLine(CultureInfo.InvariantCulture, $"Graphics adapter: {encoders.Adapter() ?? "none"}");
sb.AppendLine("Encoders:");
foreach (var e in encoders.Detect())
{
var size = e.MaxWidth > 0 ? string.Create(CultureInfo.InvariantCulture, $" max {e.MaxWidth}x{e.MaxHeight}") : string.Empty;
sb.AppendLine(CultureInfo.InvariantCulture, $" {e.Codec} · {e.DisplayName} ({(e.Hardware ? "hardware" : "software")}{(e.TenBit ? ", 10-bit" : string.Empty)}{size})");
}
try
{
var inventory = CodecInventory.Detect();
sb.AppendLine(CultureInfo.InvariantCulture, $"HEVC decoder: {inventory.HasHevcDecoder}; AV1 decoder: {inventory.HasAv1Decoder}");
sb.AppendLine("Image formats (WIC):");
foreach (var f in inventory.Formats)
{
var missing = f.MissingExtensions.Count == 0 ? string.Empty : "; missing " + string.Join(", ", f.MissingExtensions.Select(x => x.ProductName));
sb.AppendLine(CultureInfo.InvariantCulture, $" {f.Format}: {(f.IsNative ? "native" : f.Decoder is null ? "no decoder" : "preview only")}{(f.Decoder is { } d ? $" ({d.FriendlyName} {d.Version})" : string.Empty)}{missing}");
}
}
catch (Exception ex) when (ex is COMException or DllNotFoundException or EntryPointNotFoundException or InvalidOperationException)
{
sb.AppendLine("WIC decoders could not be listed: " + ex.Message);
}
return sb.ToString();
}
}
/// <summary>
/// The disk cache (spilled frames, thumbnails): its folder, its size and clearing it. Only a folder Chronos created
/// (it carries a marker file) is ever emptied, so pointing the cache at a folder with user files cannot delete them.
/// </summary>
public static class CacheStore
{
public const string MarkerFile = ".chronos-cache";
/// <summary>The cache folder in effect.</summary>
public static string Folder(AppEnvironment environment, AppSettings settings) =>
string.IsNullOrWhiteSpace(settings.CacheFolder) ? environment.CacheDirectory : settings.CacheFolder!;
/// <summary>Creates the folder (if needed) and marks it as Chronos's.</summary>
public static void Prepare(string folder)
{
Directory.CreateDirectory(folder);
var marker = Path.Combine(folder, MarkerFile);
if (!File.Exists(marker)) File.WriteAllText(marker, "Chronos cache folder. Its contents can be deleted at any time.");
}
/// <summary>True when <paramref name="folder"/> is a Chronos cache folder (safe to empty).</summary>
public static bool IsOwned(string folder) => File.Exists(Path.Combine(folder, MarkerFile));
/// <summary>Total bytes of the files in the cache (0 when missing).</summary>
public static long Size(string folder)
{
if (!Directory.Exists(folder)) return 0;
long total = 0;
var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint };
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", options)) total += file.Length;
return total;
}
/// <summary>Deletes everything inside an owned cache folder except the marker; returns the bytes freed.</summary>
/// <exception cref="InvalidOperationException">The folder is not a Chronos cache folder.</exception>
public static long Clear(string folder)
{
if (!Directory.Exists(folder)) return 0;
if (!IsOwned(folder)) throw new InvalidOperationException("Not a Chronos cache folder: " + folder);
long freed = 0;
var root = new DirectoryInfo(folder);
foreach (var file in root.EnumerateFiles())
{
if (file.Name == MarkerFile) continue;
freed += TryDelete(file);
}
foreach (var directory in root.EnumerateDirectories())
{
if ((directory.Attributes & FileAttributes.ReparsePoint) != 0) continue;
var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint };
foreach (var file in directory.EnumerateFiles("*", options)) freed += TryDelete(file);
try
{
directory.Delete(recursive: true);
}
catch (IOException)
{
}
catch (UnauthorizedAccessException)
{
}
}
return freed;
}
private static long TryDelete(FileInfo file)
{
try
{
var length = file.Length;
file.Delete();
return length;
}
catch (IOException)
{
return 0; // in use (a render spilling right now)
}
catch (UnauthorizedAccessException)
{
return 0;
}
}
}
@@ -0,0 +1,66 @@
using Chronos.Core.Localization;
namespace Chronos.App.Infrastructure;
/// <summary>Culture-aware number, size and duration formatting for the UI.</summary>
public static class Formatting
{
/// <summary>Localized "{0} KB" formats from bytes to petabytes (BRIEF §16: sizes follow the language, "96,2 Go").</summary>
private static readonly string[] ByteUnits = ["Common.Size.B", "Common.Size.KB", "Common.Size.MB", "Common.Size.GB", "Common.Size.TB", "Common.Size.PB"];
/// <summary>1,536 → "1.5 KB" (decimal units, as Explorer shows for drives).</summary>
public static string Bytes(long bytes)
{
double value = bytes;
var unit = 0;
while (value >= 1000 && unit < ByteUnits.Length - 1)
{
value /= 1000;
unit++;
}
var format = unit == 0 || value >= 100 ? "0" : "0.#";
return Loc.L(ByteUnits[unit], value.ToString(format, Loc.Culture));
}
public static string Count(long n) => n.ToString("N0", Loc.Culture);
/// <summary>Compact duration: "2 h 00 m", "5 min", "40 s".</summary>
public static string Duration(TimeSpan t)
{
if (t < TimeSpan.Zero) t = TimeSpan.Zero;
if (t.TotalHours >= 24) return Loc.L("Common.Duration.Days", (int)t.TotalDays, t.Hours);
if (t.TotalHours >= 1) return Loc.L("Common.Duration.Hours", (int)t.TotalHours, t.Minutes.ToString("00", Loc.Culture));
if (t.TotalMinutes >= 1) return Loc.L("Common.Duration.Minutes", (int)Math.Round(t.TotalMinutes));
return Loc.L("Common.Duration.Seconds", (int)Math.Round(t.TotalSeconds));
}
/// <summary>Clock-style elapsed time for finished jobs: "2:41", "1:02:41".</summary>
public static string Elapsed(TimeSpan t)
{
if (t < TimeSpan.Zero) t = TimeSpan.Zero;
return t.TotalHours >= 1
? ((int)t.TotalHours).ToString(Loc.Culture) + ":" + t.Minutes.ToString("00", Loc.Culture) + ":" + t.Seconds.ToString("00", Loc.Culture)
: ((int)t.TotalMinutes).ToString(Loc.Culture) + ":" + t.Seconds.ToString("00", Loc.Culture);
}
/// <summary>0.62 → "62 %".</summary>
public static string Percent(double fraction) => Loc.L("Common.Percent", Math.Round(Math.Clamp(fraction, 0, 1) * 100).ToString("0", Loc.Culture));
/// <summary>Items per second with one decimal below 100: "11.3", "118".</summary>
public static string Rate(double perSecond) => perSecond.ToString(perSecond < 100 ? "0.#" : "N0", Loc.Culture);
/// <summary>Local time of day in the culture's short format ("09:12").</summary>
public static string TimeOfDay(DateTimeOffset at) => at.ToLocalTime().ToString("t", Loc.Culture);
/// <summary>Calendar date in the culture's short format.</summary>
public static string Date(DateTimeOffset at) => at.ToLocalTime().ToString("d", Loc.Culture);
/// <summary>Camera wall-clock date in the culture's short format.</summary>
public static string Date(DateTime wallClock) => wallClock.ToString("d", Loc.Culture);
/// <summary>
/// A path, address or fingerprint kept left to right inside right-to-left text (a Unicode left-to-right embedding),
/// so its separators and digits stay in place; it reads unchanged in left-to-right languages.
/// </summary>
public static string LeftToRight(string text) => "\u202A" + text + "\u202C";
}
@@ -0,0 +1,48 @@
namespace Chronos.App.Infrastructure;
/// <summary>Texts of a confirmation dialog (DESIGN §4: two buttons, safe action left and default).</summary>
public sealed record ConfirmRequest
{
public required string Heading { get; init; }
public required string Message { get; init; }
/// <summary>Detail block (certificate fingerprint, list of what changes); null hides it.</summary>
public string? Detail { get; init; }
/// <summary>The detail is set in the monospaced font (fingerprints, values to compare); false sets it in the UI font (names, sentences).</summary>
public bool IsDetailMonospaced { get; init; } = true;
public string? DetailToolTip { get; init; }
public required string SafeText { get; init; }
public required string SafeToolTip { get; init; }
public required string ActionText { get; init; }
public required string ActionToolTip { get; init; }
/// <summary>Warning-outlined action (never a primary) for data-destroying choices.</summary>
public bool IsDestructive { get; init; }
/// <summary>Text the user must type before the action enables (formatting a card: its name); null asks no typing.</summary>
public string? TypedConfirmation { get; init; }
/// <summary>Label of the typing field ("Type the card name to confirm").</summary>
public string? TypedPrompt { get; init; }
}
/// <summary>Modal questions and OS pickers the view models ask for (BRIEF §12.1: modals only for confirmations and login).</summary>
public interface IAppDialogs
{
/// <summary>A folder chosen in the shell's folder picker; null when cancelled.</summary>
string? PickFolder(string title, string? initialFolder = null);
/// <summary>A JSON file chosen in the shell's Open dialog; null when cancelled.</summary>
string? PickJsonFile(string title);
/// <summary>True when the user chose the action.</summary>
bool Confirm(ConfirmRequest request);
/// <summary>
/// The login form. <paramref name="signIn"/> receives user and password and returns null on success or the
/// error sentence to show; the form stays open until it succeeds or the user cancels. True when signed in.
/// </summary>
bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn);
}
@@ -0,0 +1,46 @@
using System.Globalization;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Threading;
using Chronos.Core.Localization;
namespace Chronos.App.Infrastructure;
/// <summary>
/// A status line screen readers announce when it changes (a live region): <c>LiveRegion.Text</c> becomes the element's
/// accessible name and every later change raises <see cref="AutomationEvents.LiveRegionChanged"/>. The element's
/// <see cref="AutomationProperties.LiveSettingProperty"/> (Polite, or Assertive for errors) must be set as well.
/// </summary>
public static class LiveRegion
{
public static readonly DependencyProperty TextProperty = DependencyProperty.RegisterAttached(
"Text", typeof(string), typeof(LiveRegion), new PropertyMetadata(null, OnTextChanged));
/// <summary>
/// The data and language the last text came from: a recycled list row showing another item, or every status
/// relabelled by a language switch, is not news.
/// </summary>
private static readonly DependencyProperty SourceProperty = DependencyProperty.RegisterAttached(
"Source", typeof(Origin), typeof(LiveRegion), new PropertyMetadata(null));
public static string? GetText(DependencyObject element) => (string?)element.GetValue(TextProperty);
public static void SetText(DependencyObject element, string? value) => element.SetValue(TextProperty, value);
private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is not FrameworkElement element) return;
AutomationProperties.SetName(element, (string?)e.NewValue ?? string.Empty);
var origin = new Origin(element.DataContext, Loc.Culture);
var sameSource = element.GetValue(SourceProperty) is Origin last && ReferenceEquals(last.Data, origin.Data) && last.Culture.Equals(origin.Culture);
element.SetValue(SourceProperty, origin);
// The first value arrives with the screen: only what changes while it is shown is announced, once layout has shown
// it (a status that appears with its text is still collapsed when the text arrives).
if (!sameSource || !element.IsLoaded || e.NewValue is null || !AutomationPeer.ListenerExists(AutomationEvents.LiveRegionChanged)) return;
element.Dispatcher.InvokeAsync(() => UIElementAutomationPeer.CreatePeerForElement(element)?.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged),
DispatcherPriority.Background);
}
private sealed record Origin(object? Data, CultureInfo Culture);
}
@@ -0,0 +1,17 @@
using System.Reflection;
namespace Chronos.App.Infrastructure;
/// <summary>Features a build switches on through MSBuild properties (Directory.Build.props), read from the assembly metadata.</summary>
public static class ProductFeatures
{
/// <summary>
/// Monetization (BRIEF §21: ads, the anonymous usage counts consent, the licence) ships disabled until a build sets
/// <c>ChronosAdsEnabled=true</c>; until then nothing of it shows.
/// </summary>
public static bool AdsEnabled { get; } = Flag("ChronosAdsEnabled");
private static bool Flag(string key) =>
typeof(ProductFeatures).Assembly.GetCustomAttributes<AssemblyMetadataAttribute>().FirstOrDefault(a => a.Key == key)?.Value is { } value
&& bool.TryParse(value, out var on) && on;
}
@@ -0,0 +1,51 @@
using System.Reflection;
namespace Chronos.App.Infrastructure;
/// <summary>
/// Public links (BRIEF §19.4, amended 2026-10-23, R2): the Gitea repository that publishes the releases. Release
/// builds pass the repository they publish to as the ChronosReleasesUrl property.
/// </summary>
public static class ProductLinks
{
/// <summary>The repository of local builds, as Directory.Build.props sets it.</summary>
public const string DefaultRepository = "https://gitea.encke-hake.ts.net/BalboSoft/Chronos";
/// <summary>"https://host/owner/name" of the releases repository.</summary>
public static string Repository { get; } = Normalise(
typeof(ProductLinks).Assembly.GetCustomAttributes<AssemblyMetadataAttribute>()
.FirstOrDefault(a => a.Key == "ChronosReleasesUrl")?.Value) ?? DefaultRepository;
public static string Releases => $"{Repository}/releases";
/// <summary>The published stable releases, from which the update check takes the newest (BRIEF §18).</summary>
public static string StableReleasesApi => StableReleasesApiOf(Repository);
/// <summary>The licence (EULA) at the root of the releases repository (BRIEF §12.9).</summary>
public static string Licence => $"{Repository}/src/branch/main/EULA.md";
/// <summary>Where translations are reviewed by the community (BRIEF §16).</summary>
public static string Issues => $"{Repository}/issues";
/// <summary>
/// The Gitea API address of a repository's published stable releases: "https://host[/prefix]/owner/name" →
/// "https://host[/prefix]/api/v1/repos/owner/name/releases?draft=false&amp;pre-release=false&amp;limit=50" (Gitea may
/// be served under a path prefix).
/// </summary>
public static string StableReleasesApiOf(string repository)
{
var uri = new Uri(repository, UriKind.Absolute);
var segments = uri.AbsolutePath.Trim('/').Split('/', StringSplitOptions.RemoveEmptyEntries);
if (segments.Length < 2) throw new ArgumentException($"Not a repository address: {repository}", nameof(repository));
var prefix = string.Concat(segments[..^2].Select(s => "/" + s));
return $"{uri.GetLeftPart(UriPartial.Authority)}{prefix}/api/v1/repos/{segments[^2]}/{segments[^1]}/releases?draft=false&pre-release=false&limit=50";
}
/// <summary>The address without surrounding spaces, trailing slashes or ".git"; null when empty.</summary>
internal static string? Normalise(string? repository)
{
var text = repository?.Trim().TrimEnd('/');
if (text is not null && text.EndsWith(".git", StringComparison.OrdinalIgnoreCase)) text = text[..^4];
return string.IsNullOrEmpty(text) ? null : text;
}
}
@@ -0,0 +1,124 @@
using Chronos.Core.Diagnostics;
namespace Chronos.App.Infrastructure;
/// <summary>
/// What a render node runs with: the server session (address and token), the certificates it may trust and whether it
/// offers hardware encoders. A change of any of them means another node.
/// </summary>
public sealed record RenderNodeSession(Uri Address, string Token, IReadOnlyCollection<string> TrustedFingerprints, bool Hardware)
{
/// <summary>
/// The session a node should run for, or null when it should be off: the user offers this PC
/// (<paramref name="offered"/>), a server session is open and signed in.
/// </summary>
public static RenderNodeSession? For(bool offered, bool connected, Uri? address, string? token, IReadOnlyCollection<string> trustedFingerprints,
bool hardware) =>
offered && connected && address is not null && token is not null ? new RenderNodeSession(address, token, trustedFingerprints, hardware) : null;
public bool Equals(RenderNodeSession? other) =>
other is not null && Address == other.Address && Token == other.Token && Hardware == other.Hardware
&& TrustedFingerprints.Order(StringComparer.Ordinal).SequenceEqual(other.TrustedFingerprints.Order(StringComparer.Ordinal), StringComparer.Ordinal);
public override int GetHashCode() => HashCode.Combine(Address, Token, Hardware, TrustedFingerprints.Count);
}
/// <summary>A started render node.</summary>
public interface IRenderNode : IAsyncDisposable
{
/// <summary>Completes when the node has stopped, by itself (refused by the server) or when disposed.</summary>
Task Completion { get; }
}
/// <summary>
/// Keeps this PC's render node (BRIEF §14.7) in line with "Offer this PC as render node" and the server session:
/// <see cref="Update"/> starts the node for the wanted session, restarts it for another session or when it stopped by
/// itself, and stops it when none is wanted. Switches run one after the other, off the caller's thread, and never fail:
/// a node that cannot start is logged and stays off until the next update.
/// </summary>
public sealed class RenderNodeHost(Func<RenderNodeSession, IRenderNode> start) : IAsyncDisposable
{
private readonly Lock _gate = new();
private Task _switching = Task.CompletedTask;
private (RenderNodeSession Session, IRenderNode Node)? _running;
private bool _disposed;
/// <summary>The session the node runs for; null when it is off.</summary>
public RenderNodeSession? Session
{
get
{
lock (_gate) return _running?.Session;
}
}
/// <summary>Completes when every switch requested so far has run.</summary>
public Task Switching
{
get
{
lock (_gate) return _switching;
}
}
/// <summary>Runs the node for <paramref name="wanted"/>, or stops it when null.</summary>
public void Update(RenderNodeSession? wanted)
{
lock (_gate)
{
if (_disposed) return;
var previous = _switching;
_switching = Task.Run(async () =>
{
await previous.ConfigureAwait(false);
await SwitchAsync(wanted).ConfigureAwait(false);
});
}
}
/// <summary>Stops the node after the pending switches; later updates are ignored.</summary>
public async ValueTask DisposeAsync()
{
Task pending;
lock (_gate)
{
_disposed = true;
pending = _switching;
}
await pending.ConfigureAwait(false);
await SwitchAsync(null).ConfigureAwait(false);
}
private async Task SwitchAsync(RenderNodeSession? wanted)
{
(RenderNodeSession Session, IRenderNode Node)? running;
lock (_gate) running = _running;
// A node the server refused has stopped by itself: the same session starts it again (the right may be granted now).
if (running?.Session == wanted && running?.Node.Completion.IsCompleted != true) return;
if (running is { } old)
{
lock (_gate) _running = null;
try
{
await old.Node.DisposeAsync().ConfigureAwait(false);
Log.Info("render-node", "Render node stopped");
}
catch (Exception ex)
{
// A node that fails to stop is gone anyway; the next one must still be able to start.
Log.Warning("render-node", "The render node did not stop cleanly", ex);
}
}
if (wanted is null) return;
try
{
var node = start(wanted);
lock (_gate) _running = (wanted, node);
Log.Info("render-node", $"Offering this PC as render node to {wanted.Address}");
}
catch (Exception ex)
{
Log.Warning("render-node", "The render node could not start", ex);
}
}
}
@@ -0,0 +1,31 @@
using System.IO;
using Chronos.Core.Diagnostics;
using Chronos.Core.Windows.Shell;
namespace Chronos.App.Infrastructure;
/// <summary>The only shell launches the product performs (BRIEF §8.6): open a web or Store link, reveal a folder or file.</summary>
public static class ShellActions
{
public static void OpenUrl(string url)
{
if (!ShellLauncher.IsAllowedUrl(url)) return;
try
{
if (!ShellLauncher.OpenUrl(url)) Log.Warning("shell", $"The shell could not open {url}");
}
catch (Exception ex) when (ex is ArgumentException or System.ComponentModel.Win32Exception)
{
Log.Warning("shell", $"The shell could not open {url}", ex);
}
}
/// <summary>Opens a folder in Explorer, or shows a file selected in its folder.</summary>
public static void Reveal(string path)
{
if (string.IsNullOrWhiteSpace(path) || !(Directory.Exists(path) || File.Exists(path))) return;
if (!ShellLauncher.RevealInExplorer(path)) Log.Warning("shell", $"Explorer could not show {path}");
}
public static void OpenFolder(string path) => Reveal(path);
}
@@ -0,0 +1,252 @@
using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Diagnostics;
namespace Chronos.App.Infrastructure;
/// <summary>
/// One Chronos per data folder in a Windows session (two would share one index and job engine): a named mutex marks
/// the running instance, and a later launch (a double-clicked <c>.chronos</c> file, the Start menu) hands its file
/// arguments over a named pipe (current user only), lets the running window come to the front and exits. The running
/// instance listens from the moment it holds the mutex, keeping what arrives until its window can take it, and stops
/// listening as soon as it starts closing; a launch that gets no answer waits for it to exit and starts in its place.
/// Same protocol as the Uploader's, kept per program so neither depends on the other.
/// </summary>
public sealed partial class SingleInstance : IDisposable
{
private const string Header = "CHRONOS/1";
private const int MaxMessageBytes = 1 << 20;
private const int AnyProcess = -1;
private readonly Mutex _mutex;
private readonly string _pipeName;
private readonly CancellationTokenSource _stop = new();
private readonly Lock _gate = new();
private readonly Queue<IReadOnlyList<string>> _waiting = new();
private Action<IReadOnlyList<string>>? _received;
private Task? _listening;
private bool _disposed;
private SingleInstance(Mutex mutex, string pipeName)
{
_mutex = mutex;
_pipeName = pipeName;
}
/// <summary>
/// The instance guard for <paramref name="dataDirectory"/>, or null when another Chronos already uses it in this
/// session (also one running with administrator rights, whose mutex this launch may not even open).
/// </summary>
public static SingleInstance? TryAcquire(string dataDirectory)
{
Mutex mutex;
bool createdNew;
try
{
mutex = new Mutex(initiallyOwned: true, MutexName(dataDirectory), out createdNew);
}
catch (UnauthorizedAccessException ex)
{
Log.Info("instance", $"Chronos runs with administrator rights on this data folder: {ex.Message}");
return null;
}
if (createdNew) return new SingleInstance(mutex, PipeName(dataDirectory));
mutex.Dispose();
return null;
}
/// <summary>
/// Waits up to <paramref name="timeout"/> for the Chronos running on <paramref name="dataDirectory"/> to exit (while
/// it closes it no longer answers hand-overs), then becomes the running instance; null when it still runs, or runs
/// with administrator rights.
/// </summary>
public static SingleInstance? WaitForTurn(string dataDirectory, TimeSpan timeout)
{
Mutex mutex;
try
{
mutex = new Mutex(initiallyOwned: false, MutexName(dataDirectory));
}
catch (UnauthorizedAccessException ex)
{
Log.Info("instance", $"Chronos runs with administrator rights on this data folder: {ex.Message}");
return null;
}
try
{
if (mutex.WaitOne(timeout)) return new SingleInstance(mutex, PipeName(dataDirectory));
}
catch (AbandonedMutexException)
{
// The other Chronos ended without releasing it (it crashed): this thread owns it now.
Log.Warning("instance", "The previous Chronos ended without closing");
return new SingleInstance(mutex, PipeName(dataDirectory));
}
mutex.Dispose();
return null;
}
/// <summary>
/// Sends <paramref name="args"/> (absolute paths; empty = just show the window) to the Chronos running on
/// <paramref name="dataDirectory"/>; false when it could not be reached.
/// </summary>
public static bool HandOver(string dataDirectory, IReadOnlyList<string> args)
{
// This launch came from the user, so it may give the running window the right to come to the front.
AllowSetForegroundWindow(AnyProcess);
try
{
using var pipe = new NamedPipeClientStream(".", PipeName(dataDirectory), PipeDirection.Out, PipeOptions.CurrentUserOnly);
pipe.Connect(3000);
pipe.Write(Encode(args));
pipe.Flush();
return true;
}
catch (Exception ex) when (ex is IOException or TimeoutException or UnauthorizedAccessException)
{
Log.Warning("instance", "Could not reach the running Chronos", ex);
return false;
}
}
/// <summary>Starts receiving messages from later launches; they wait until <see cref="Receive"/> names who takes them.</summary>
public void Listen()
{
lock (_gate)
{
if (_listening is not null || _disposed) return;
_listening = ListenAsync(_pipeName, OnMessage, _stop.Token);
}
}
/// <summary>
/// Hands the messages received so far, then each later one, to <paramref name="received"/>, in order; it runs on a
/// pool thread.
/// </summary>
public void Receive(Action<IReadOnlyList<string>> received)
{
lock (_gate)
{
_received = received;
while (_waiting.TryDequeue(out var args)) received(args);
}
}
/// <summary>
/// Stops answering later launches while keeping the mutex: from now on they wait for this instance to exit instead
/// of handing over arguments it could no longer open.
/// </summary>
public void StopListening()
{
Task? listening;
lock (_gate)
{
if (_disposed) return;
_stop.Cancel();
listening = _listening;
}
// The pipe closes as the loop ends (cancellation ends it quietly).
try
{
listening?.Wait(TimeSpan.FromSeconds(2));
}
catch (AggregateException ex)
{
Log.Warning("instance", "Hand-over listener ended with an error", ex);
}
}
public void Dispose()
{
StopListening();
lock (_gate)
{
if (_disposed) return;
_disposed = true;
}
_mutex.ReleaseMutex();
_mutex.Dispose();
_stop.Dispose();
}
/// <summary>UTF-8: a header line, then one argument per line (paths cannot contain line breaks).</summary>
public static byte[] Encode(IReadOnlyList<string> args) =>
Encoding.UTF8.GetBytes(Header + "\n" + string.Join("\n", args.Where(a => !a.Contains('\n', StringComparison.Ordinal))));
/// <summary>Arguments of a message, or null when it is not one of ours.</summary>
public static IReadOnlyList<string>? Decode(ReadOnlySpan<byte> message)
{
if (message.Length > MaxMessageBytes) return null;
var lines = Encoding.UTF8.GetString(message).Split('\n');
if (lines[0] != Header) return null;
return [.. lines.Skip(1).Where(l => l.Length > 0)];
}
private void OnMessage(IReadOnlyList<string> args)
{
lock (_gate)
{
if (_received is null) _waiting.Enqueue(args);
else _received(args);
}
}
/// <summary>The data folder's identity (case-insensitive, as Windows paths are): a portable copy has its own instance.</summary>
private static string Key(string dataDirectory) =>
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(Path.GetFullPath(dataDirectory).TrimEnd('\\', '/').ToUpperInvariant())))[..16];
private static string MutexName(string dataDirectory) => @"Local\Chronos.App." + Key(dataDirectory);
private static string PipeName(string dataDirectory)
{
using var process = Process.GetCurrentProcess();
return $"Chronos.App.{process.SessionId}.{Environment.UserName}.{Key(dataDirectory)}";
}
private static async Task ListenAsync(string pipeName, Action<IReadOnlyList<string>> received, CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
await using var pipe = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte,
PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
await pipe.WaitForConnectionAsync(ct).ConfigureAwait(false);
using var buffer = new MemoryStream();
await pipe.CopyToAsync(buffer, ct).ConfigureAwait(false);
if (Decode(buffer.GetBuffer().AsSpan(0, (int)buffer.Length)) is { } args) received(args);
}
catch (OperationCanceledException)
{
return;
}
catch (UnauthorizedAccessException ex)
{
// The pipe name belongs to a Chronos running with administrator rights: later launches wait instead.
Log.Warning("instance", "Hand-over pipe not available", ex);
return;
}
catch (IOException ex)
{
// A pipe of the same name still held by a Chronos that is exiting, or a broken connection: try again shortly.
Log.Warning("instance", "Hand-over pipe failed; listening again", ex);
try
{
await Task.Delay(TimeSpan.FromSeconds(1), ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
}
}
}
[LibraryImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool AllowSetForegroundWindow(int processId);
}
@@ -0,0 +1,136 @@
using System.IO;
using System.Security;
using Microsoft.Win32;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
namespace Chronos.App.Infrastructure;
/// <summary>Settings › General › Startup: Chronos starts when the user signs in to Windows.</summary>
public interface IStartWithWindows
{
bool IsEnabled { get; }
void SetEnabled(bool enabled);
/// <summary>Points this copy's entry at the current executable (after an update renamed it).</summary>
void Refresh();
}
/// <summary>
/// <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</c> value that starts Chronos minimised at sign-in, so inserted
/// cards are noticed (BRIEF §12.4) without a window in the way. The registry stays the source of truth because Task
/// Manager can turn it off: an entry it turned off (<see cref="StartupApproval"/>) shows as off, and ticking the box
/// turns it on again. There is one value for every copy of Chronos: a copy shows it as on only when it starts that
/// copy, and never takes it over or removes it unless the user ticks or unticks the box there. The uninstaller removes
/// it with the Uploader's when it starts a program of the folder it removes.
/// </summary>
/// <param name="executable">This copy's program; the running one by default.</param>
/// <param name="root">The registry hive holding the entries; <c>HKEY_CURRENT_USER</c> by default (tests pass a scratch key).</param>
public sealed class RunKeyStartWithWindows(string? executable = null, RegistryKey? root = null) : IStartWithWindows
{
/// <summary>Starts the main window minimised on the taskbar.</summary>
public const string MinimizedOption = "--minimized";
private readonly string? _executable = executable ?? Environment.ProcessPath;
private readonly RegistryKey _root = root ?? Registry.CurrentUser;
/// <summary>The entry starts this copy and Task Manager has not turned it off.</summary>
public bool IsEnabled => StartupCommand.Starts(Read(), _executable) && !StartupApproval.IsTurnedOff(ReadApproval());
public void SetEnabled(bool enabled)
{
if (_executable is not { } executable) return;
Update(key =>
{
if (enabled)
{
key.SetValue(StartupCommand.ClientValue, StartupCommand.Format(executable, MinimizedOption), RegistryValueKind.String);
// Task Manager's "Disable" outlives a new command: ticking the box undoes it.
DeleteApproval();
}
else if (StartupCommand.Starts(key.GetValue(StartupCommand.ClientValue) as string, executable))
{
key.DeleteValue(StartupCommand.ClientValue, throwOnMissingValue: false);
DeleteApproval();
}
});
}
/// <summary>The command follows a renamed program; an entry Task Manager turned off stays off.</summary>
public void Refresh()
{
if (_executable is { } executable && Follows(Read(), executable, File.Exists))
Update(key => key.SetValue(StartupCommand.ClientValue, StartupCommand.Format(executable, MinimizedOption), RegistryValueKind.String));
}
/// <summary>
/// The entry should now start <paramref name="current"/>: the program it names is gone from the folder
/// <paramref name="current"/> runs from (an update renamed it). An entry of another copy, still on disk or
/// elsewhere (a second install, a portable copy, a development build), is left alone.
/// </summary>
internal static bool Follows(string? command, string? current, Func<string, bool> exists)
{
if (current is null || StartupCommand.Executable(command) is not { } stored || StartupCommand.Starts(command, current)) return false;
return !exists(stored) && StartupCommand.FolderOf(current) is { } folder
&& string.Equals(StartupCommand.Folder(command), folder, StringComparison.OrdinalIgnoreCase);
}
private string? Read()
{
try
{
using var key = _root.OpenSubKey(StartupCommand.RunKey);
return key?.GetValue(StartupCommand.ClientValue) as string;
}
catch (Exception ex) when (ex is SecurityException or IOException)
{
return null;
}
}
/// <summary>Task Manager's switch for the entry; null when it never touched it.</summary>
private byte[]? ReadApproval()
{
try
{
using var key = _root.OpenSubKey(StartupApproval.RunKey);
return key?.GetValue(StartupCommand.ClientValue) as byte[];
}
catch (Exception ex) when (ex is SecurityException or IOException)
{
return null;
}
}
private void DeleteApproval()
{
using var key = _root.OpenSubKey(StartupApproval.RunKey, writable: true);
key?.DeleteValue(StartupCommand.ClientValue, throwOnMissingValue: false);
}
private void Update(Action<RegistryKey> change)
{
try
{
using var key = _root.CreateSubKey(StartupCommand.RunKey, writable: true);
change(key);
}
catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException or IOException)
{
Log.Warning("startup", "Run key not updated", ex);
}
}
}
/// <summary>Screenshots, tests and portable copies (which leave nothing in the registry) never touch the user's sign-in programs.</summary>
public sealed class MemoryStartWithWindows : IStartWithWindows
{
public bool IsEnabled { get; private set; }
public void SetEnabled(bool enabled) => IsEnabled = enabled;
public void Refresh()
{
}
}
@@ -0,0 +1,38 @@
using System.Globalization;
using System.Windows;
using Chronos.Core.Localization;
using Chronos.Ui.Controls;
namespace Chronos.App.Infrastructure;
/// <summary>
/// Switches the UI language at run time without restart (BRIEF §16). A <see cref="ChronosWindow"/> takes the
/// language's direction when it is created and follows each switch, so right-to-left languages mirror windows opened
/// before and after this call alike; plain windows (the full-screen preview) take it when they load.
/// </summary>
public static class UiLanguage
{
static UiLanguage()
{
EventManager.RegisterClassHandler(typeof(Window), FrameworkElement.LoadedEvent, new RoutedEventHandler((sender, _) => ((Window)sender).FlowDirection = Bidi.UiDirection));
}
/// <summary>Applies <paramref name="code"/> (or the OS language when null) and returns the culture in use.</summary>
public static CultureInfo Apply(string? code)
{
CultureInfo requested;
try
{
requested = code is null ? CultureInfo.CurrentUICulture : CultureInfo.GetCultureInfo(code);
}
catch (CultureNotFoundException)
{
requested = CultureInfo.CurrentUICulture;
}
var culture = Languages.BestMatch(requested);
CultureInfo.DefaultThreadCurrentUICulture = culture;
CultureInfo.CurrentUICulture = culture;
Loc.SetCulture(culture);
return culture;
}
}
@@ -0,0 +1,74 @@
using System.ComponentModel;
using System.Windows;
using System.Windows.Interop;
using Chronos.App.Import;
using Chronos.Core.Diagnostics;
using Chronos.Core.Windows.Devices;
namespace Chronos.App.Infrastructure;
/// <summary>
/// Card detection on this PC (BRIEF §13): <see cref="RemovableVolumeWatcher"/> (WM_DEVICECHANGE plus a 3-second poll),
/// safe removal through <see cref="VolumeEjector"/> and formatting only through the Windows format dialog
/// (<see cref="FormatDialog"/>, BRIEF §8.6).
/// </summary>
public sealed class WindowsDeviceMonitor : IDeviceMonitor
{
private RemovableVolumeWatcher? _watcher;
public event Action<CardDevice>? Arrived;
public event Action<CardDevice>? Removed;
public IReadOnlyList<CardDevice> Devices => _watcher is { } watcher ? [.. watcher.Volumes.Select(Map)] : [];
public void Start()
{
if (_watcher is not null) return;
var watcher = new RemovableVolumeWatcher();
watcher.VolumeArrived += (_, e) => Arrived?.Invoke(Map(e.Volume));
watcher.VolumeRemoved += (_, e) => Removed?.Invoke(Map(e.Volume));
try
{
watcher.Start();
_watcher = watcher;
}
catch (Win32Exception ex)
{
// Without the watcher cards are still listed by "Folder…"; nothing else depends on it.
Log.Warning("devices", "Card detection is unavailable", ex);
watcher.Dispose();
}
}
public EjectOutcome Eject(CardDevice device) => VolumeEjector.Eject(device.Root[0]) switch
{
EjectResult.Ejected => EjectOutcome.Ejected,
EjectResult.InUse => EjectOutcome.InUse,
_ => EjectOutcome.Failed,
};
public FormatOutcome Format(CardDevice device)
{
var owner = Application.Current?.MainWindow is { } window ? new WindowInteropHelper(window).Handle : 0;
try
{
return FormatDialog.Show(owner, device.Root[0]) switch
{
FormatDialogResult.Formatted => FormatOutcome.Formatted,
FormatDialogResult.Cancelled => FormatOutcome.Cancelled,
_ => FormatOutcome.Failed,
};
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
{
Log.Warning("devices", $"The format dialog cannot open for {device.Root}", ex);
return FormatOutcome.Failed;
}
}
public void Dispose() => _watcher?.Dispose();
private static CardDevice Map(VolumeInfo v) =>
new(v.RootPath, v.Label, v.SerialNumber, v.TotalBytes, v.FreeBytes, v.DriveType == VolumeDriveType.Removable, v.HasDcim);
}