Files
Chronos/src/Chronos.App/Infrastructure/AppSettings.cs
T
Alby96andClaude Opus 5.5 db389a54f2
CI / Build and test (push) Successful in 9m26s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 8s
Release / Build, test and publish (push) Successful in 14m31s
CI / PostgreSQL 16 integration (push) Successful in 9m53s
CI / PostgreSQL 17 integration (push) Successful in 9m22s
CI / Docker image (push) Successful in 44s
Release / Server image (push) Successful in 1m36s
feat: owner review 2 phase 5c: originals, local render, clean-up and the workspace settings (#18)
Originals in the workspace, local render and send home with provenance, the workspace clean-up, size limit and trash, moving the workspace folder, and the complete Settings › Workspace page (owner review 2, R8, phase 5c). One adversarial review round (35 findings, 32 fixed), a copy-cancel race fixed, 184 strings in all 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-11-04 20:03:52 +01:00

411 lines
19 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using Chronos.Core.Analysis.Deep;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Import;
using Chronos.Core.IO;
using Chronos.Core.Naming;
using Chronos.Core.Project;
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>
/// Which project Edit opens for a sequence that has several in the workspace (Settings › Workspace › Open project, phase 5c).
/// </summary>
public enum WorkspaceOpenPolicy
{
/// <summary>The project opened last for the sequence (<see cref="AppSettings.WorkspaceRecent"/>), else the one saved last.</summary>
LastUsed,
/// <summary>The sequence's Main project.</summary>
Main,
/// <summary>Ask each time, listing the sequence's projects.</summary>
Ask,
}
/// <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;
public const int DefaultWorkspaceKeptVersions = 20;
public const int DefaultWorkspaceSizeLimitGb = 100;
public const int DefaultWorkspaceCleanAfterDays = 30;
/// <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>
/// Obsolete (owner review 2, R10): the former Settings › Archive › Rescan every. Nothing edits it any more; it only seeds
/// the interval of the <c>archive-scan</c> schedule (<see cref="Jobs.DesktopScheduleHost"/>) the first time it is created,
/// and is what Reset puts that schedule back to. The schedule's own interval is edited in Jobs › Scheduled.
/// </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;
// ---- Workspace (owner review 2, R8) ----
/// <summary>The workspace, where projects are edited outside the library; null = <c>workspace</c> under the data folder.</summary>
public string? WorkspaceFolder { get; set; }
/// <summary>A version saved in the workspace is sent to its home at once (and the home's new versions taken).</summary>
public bool WorkspaceAutoSync { get; set; } = true;
/// <summary>Versions taken from a home that a workspace project keeps besides its base and the versions not sent yet.</summary>
public int WorkspaceKeptVersions { get; set; } = DefaultWorkspaceKeptVersions;
/// <summary>The workspace project opened last for each sequence (sequence id → project id); Edit opens it again.</summary>
public Dictionary<Guid, Guid> WorkspaceRecent { get; set; } = [];
/// <summary>
/// Phase 5c: past this size (GB of 2³⁰ bytes) the workspace's clean-up removes the media of the projects used longest ago
/// that are in step with their home (never one open, with jobs, or with renders not sent); 0 = no limit.
/// </summary>
public int WorkspaceSizeLimitGb { get; set; } = DefaultWorkspaceSizeLimitGb;
/// <summary>
/// What "Open in workspace" copies unless chosen otherwise: <see cref="BundleMedia.Proxies"/> or
/// <see cref="BundleMedia.Originals"/> (the proxies plus the originals, to render on this PC).
/// </summary>
public string WorkspaceDefaultMedia { get; set; } = BundleMedia.Proxies;
/// <summary>A render of a project with changes not saved as a version saves one first (and sends it when Sync automatically is on).</summary>
public bool WorkspaceVersionOnRender { get; set; } = true;
/// <summary>
/// The workspace's clean-up removes the media of a project not opened for this many days, once it is in step with its
/// home; 0 = never.
/// </summary>
public int WorkspaceCleanAfterDays { get; set; } = DefaultWorkspaceCleanAfterDays;
/// <summary>Which project Edit opens for a sequence with several in the workspace.</summary>
public WorkspaceOpenPolicy WorkspaceOpenProject { get; set; } = WorkspaceOpenPolicy.LastUsed;
/// <summary>
/// <see cref="WorkspaceDefaultMedia"/> as everything applies it: the originals for any case of "originals", else the
/// proxies (a value set elsewhere reads as the proxies). Settings › Workspace shows the same.
/// </summary>
[System.Text.Json.Serialization.JsonIgnore]
public string EffectiveDefaultMedia =>
string.Equals(WorkspaceDefaultMedia, BundleMedia.Originals, StringComparison.OrdinalIgnoreCase) ? BundleMedia.Originals : BundleMedia.Proxies;
/// <summary><see cref="WorkspaceOpenProject"/> as everything applies it: a value this Chronos does not know reads as the last used. Settings › Workspace shows the same.</summary>
[System.Text.Json.Serialization.JsonIgnore]
public WorkspaceOpenPolicy EffectiveOpenPolicy => Enum.IsDefined(WorkspaceOpenProject) ? WorkspaceOpenProject : WorkspaceOpenPolicy.LastUsed;
/// <summary>
/// When each workspace project was last opened in Edit (project id → time), which the clean-up goes by (else the time
/// its working state was saved). This PC's, like <see cref="WorkspaceRecent"/>.
/// </summary>
public Dictionary<Guid, DateTimeOffset> WorkspaceOpened { get; set; } = [];
// ---- 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 transfers with a server (uploads, sync downloads, workspace copies and renders sent) 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; }
// ---- Advanced › Logs (owner review 2, R11; applied by AppLogging) ----
/// <summary>Least severe level written to the log files.</summary>
public LogLevel LogLevel { get; set; } = LogLevel.Info;
/// <summary>Log files last written longer ago are deleted.</summary>
public int LogRetentionDays { get; set; } = LogFileOptions.DefaultRetentionDays;
/// <summary>A log file this large (MB of 2²⁰ bytes) continues in a numbered one; 0 = no limit.</summary>
public int LogMaxFileMb { get; set; } = LogFileOptions.DefaultMaxFileMb;
/// <summary>While the log files together are larger (MB), the oldest are deleted, never the current one; 0 = no limit.</summary>
public int LogMaxTotalMb { get; set; } = LogFileOptions.DefaultMaxTotalMb;
/// <summary>One log file per UTC day or per hour.</summary>
public LogRotation LogRotation { get; set; } = LogRotation.Daily;
/// <summary>MB kept from the end of each log file in the diagnostics bundle.</summary>
public int DiagnosticsLogMb { get; set; } = AppLogging.DefaultDiagnosticsLogMb;
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();
/// <summary>
/// Settings › Advanced › Reset: every default, but the values that are this PC's or this user's state rather than
/// preferences: the archive and the session, the window and its rail, the sequence edited last, the first-run flag, the
/// jobs cleared, and the workspace (its folder, moved only by its own operation, the projects opened last and when).
/// </summary>
public AppSettings ResetKeepingState() => new()
{
LastArchivePath = LastArchivePath,
ServerUrl = ServerUrl,
ServerUsername = ServerUsername,
ProtectedToken = ProtectedToken,
TrustedCertificates = TrustedCertificates,
RecentServers = RecentServers,
Window = Window,
RailCollapsed = RailCollapsed,
LastEditedSequence = LastEditedSequence,
FirstRunCompleted = FirstRunCompleted,
JobsClearedAt = JobsClearedAt,
WorkspaceFolder = WorkspaceFolder,
WorkspaceRecent = WorkspaceRecent,
WorkspaceOpened = WorkspaceOpened,
};
/// <summary>
/// Settings › Export: a copy without secrets and machine-bound values (the session, the window, the workspace's folder and
/// what it remembers of its projects: another PC's ids mean nothing there).
/// </summary>
public AppSettings ForExport()
{
var copy = Clone();
copy.ProtectedToken = null;
copy.Window = null;
copy.WorkspaceFolder = null;
copy.WorkspaceRecent = [];
copy.WorkspaceOpened = [];
return copy;
}
/// <summary>
/// Settings › Import: <paramref name="imported"/> with this PC's own values taken from these settings: the session, the
/// window and its rail, the sequence edited last, the first-run flag, and the workspace (its folder, the projects opened
/// last and when). Changes and returns <paramref name="imported"/>.
/// </summary>
public AppSettings KeepLocalIn(AppSettings imported)
{
ArgumentNullException.ThrowIfNull(imported);
imported.ProtectedToken = ProtectedToken;
imported.ServerUrl = ServerUrl;
imported.Window = Window;
imported.RailCollapsed = RailCollapsed;
imported.LastEditedSequence = LastEditedSequence;
imported.FirstRunCompleted = FirstRunCompleted;
imported.WorkspaceFolder = WorkspaceFolder;
imported.WorkspaceRecent = WorkspaceRecent;
imported.WorkspaceOpened = WorkspaceOpened;
return imported;
}
}
[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true)]
[JsonSerializable(typeof(AppSettings))]
internal sealed partial class AppSettingsJson : JsonSerializerContext;