Files
Chronos/src/Chronos.App/Infrastructure/AppSettings.cs
T
Alby96 20d64af4a4
CI / Build and test (push) Successful in 11m36s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 12s
Release / Build, test and publish (push) Successful in 14m56s
CI / PostgreSQL 16 integration (push) Successful in 10m11s
CI / PostgreSQL 17 integration (push) Successful in 10m15s
CI / Docker image (push) Successful in 45s
Release / Server image (push) Successful in 4m55s
feat: single setup, mass-pass progress, per-server homes, Desktop shares its library (owner review 5, v1.1.0) (#68)
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
2026-11-15 18:11:43 +01:00

508 lines
24 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.Data.Sync;
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>The Videos section's two lanes, Published and Workspace (the Library has no board).</summary>
Board,
}
/// <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>
/// A server this PC signed in to that announced its stable id (owner review 5, #66): its name and last address, the TLS
/// fingerprint it presented, the address keys it was reached under before (or besides) its id
/// (<see cref="Chronos.Data.Sync.SyncService.ServerKey"/>: projects, links and jobs made then still name them), the archive its
/// downloaded originals go to, and when it was last seen. Its folders (<c>servers\&lt;id&gt;</c> in the workspace and the
/// cache) are named by the id, never by the name.
/// </summary>
public sealed class KnownServer
{
public Guid Id { get; set; }
public string? Name { get; set; }
public string? LastAddress { get; set; }
public string? Fingerprint { get; set; }
public List<string> Aliases { get; set; } = [];
/// <summary>The archive of this PC that holds the server's downloaded originals (owner review 5, Q1); null until the first download.</summary>
public Guid? OriginalsArchiveId { get; set; }
public DateTimeOffset LastSeen { get; set; }
}
/// <summary>
/// Settings › Server › Sharing (owner review 5, #67): this PC's library served to the LAN by the server Chronos hosts
/// while it runs. Absent in a 1.0 settings file: off, on Docker's ports.
/// </summary>
public sealed class ShareSettings
{
public const int DefaultHttpsPort = 8443;
public const int DefaultHttpPort = 8080;
public bool Enabled { get; set; }
/// <summary>The name clients see; empty: this PC's name.</summary>
public string? Name { get; set; }
public int HttpsPort { get; set; } = DefaultHttpsPort;
public int HttpPort { get; set; } = DefaultHttpPort;
/// <summary>The ports clients reach when a router forwards others to this PC; null: the ones above.</summary>
public int? PublicHttpsPort { get; set; }
public int? PublicHttpPort { get; set; }
/// <summary>Announce the library to Chronos programs on the local network.</summary>
public bool Discovery { get; set; } = true;
/// <summary>What restarts a running share when it changes (the name, the ports, the discovery); the rest applies live.</summary>
public bool SameEndpoint(ShareSettings other)
{
ArgumentNullException.ThrowIfNull(other);
return string.Equals(Name?.Trim() ?? string.Empty, other.Name?.Trim() ?? string.Empty, StringComparison.Ordinal) && HttpsPort == other.HttpsPort &&
HttpPort == other.HttpPort && PublicHttpsPort == other.PublicHttpsPort && PublicHttpPort == other.PublicHttpPort && Discovery == other.Discovery;
}
}
/// <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 editor's collapsible groups this user opened or closed, by group key ("export.encoding" → false; owner review 1,
/// R3): kept like the rail's state, never in a project (<see cref="Chronos.App.Editor.EditorSettings.Groups"/>).
/// </summary>
public Dictionary<string, bool> EditorGroups { get; set; } = new(StringComparer.Ordinal);
/// <summary>The sequence opened in Edit last; the picker selects it first (owner review 1, R7).</summary>
public Guid? LastEditedSequence { 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>
/// Where Videos › Copy to folder puts copies of renders (owner review 1, R9): Videos\Chronos by default, null or empty
/// when unset (Copy then says why it cannot run). Never inside the archive or the workspace.
/// </summary>
public string? VideosFolder { get; set; } = Videos.VideosFolders.Default();
/// <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;
/// <summary>
/// The Videos section as cards (<see cref="LibraryLayout.Grid"/>), as a list (<see cref="LibraryLayout.List"/>) or as the
/// Board (<see cref="LibraryLayout.Board"/>).
/// </summary>
public LibraryLayout VideosLayout { get; set; } = LibraryLayout.Grid;
// ---- 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>
/// The servers known by their stable id and the address keys each was reached under (owner review 5, #66): a server's
/// projects, links and jobs stay its own whatever address it is reached by. This PC's state: Reset and Import keep it,
/// Export leaves it out.
/// </summary>
public List<KnownServer> KnownServers { get; set; } = [];
/// <summary>The alias table of <see cref="KnownServers"/>, as the sync and the workspace compare server keys through it.</summary>
public ServerIdentity KnownIdentity() => new([.. KnownServers.Where(k => k.Id != Guid.Empty).Select(k => new KnownServerKey(k.Id, [.. k.Aliases]))]);
/// <summary>The known server of <paramref name="id"/>; null when this PC has none.</summary>
public KnownServer? FindKnownServer(Guid id) => KnownServers.FirstOrDefault(k => k.Id == id);
/// <summary>Settings › Server › Sharing: this PC's library shared to the LAN while Chronos runs (owner review 5, #67).</summary>
public ShareSettings Share { get; set; } = new();
/// <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,
KnownServers = KnownServers,
Window = Window,
RailCollapsed = RailCollapsed,
EditorGroups = EditorGroups,
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 = [];
copy.KnownServers = [];
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, the archive folder (another PC's drive letter can
/// name one of this PC's own folders), 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.LastArchivePath = LastArchivePath;
imported.ProtectedToken = ProtectedToken;
imported.ServerUrl = ServerUrl;
imported.Window = Window;
imported.RailCollapsed = RailCollapsed;
imported.EditorGroups = EditorGroups;
imported.LastEditedSequence = LastEditedSequence;
imported.FirstRunCompleted = FirstRunCompleted;
imported.WorkspaceFolder = WorkspaceFolder;
imported.WorkspaceRecent = WorkspaceRecent;
imported.WorkspaceOpened = WorkspaceOpened;
imported.KnownServers = KnownServers;
return imported;
}
}
[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true)]
[JsonSerializable(typeof(AppSettings))]
internal sealed partial class AppSettingsJson : JsonSerializerContext;