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;
/// Library presentation (BRIEF §12.2).
public enum LibraryLayout
{
Grid,
List,
/// Year bands with photos per month above the card grid.
Timeline,
/// The Videos section's two lanes, Published and Workspace (the Library has no board).
Board,
}
/// Rendering quality profile (Settings › Rendering).
public enum QualityProfile
{
Best,
Balanced,
Fast,
}
/// Which encoders a render may use (Settings › Rendering).
public enum HardwarePreference
{
PreferHardware,
SoftwareOnly,
HardwareForPreviews,
}
///
/// Which project Edit opens for a sequence that has several in the workspace (Settings › Workspace › Open project, phase 5c).
///
public enum WorkspaceOpenPolicy
{
/// The project opened last for the sequence (), else the one saved last.
LastUsed,
/// The sequence's Main project.
Main,
/// Ask each time, listing the sequence's projects.
Ask,
}
/// A server certificate the user trusted on first use (BRIEF §12.7).
public sealed class TrustedCertificate
{
public string Fingerprint { get; set; } = string.Empty;
public string? Server { get; set; }
public DateTimeOffset TrustedAt { get; set; }
}
///
/// 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
/// (: projects, links and jobs made then still name them), the archive its
/// downloaded originals go to, and when it was last seen. Its folders (servers\<id> in the workspace and the
/// cache) are named by the id, never by the name.
///
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 Aliases { get; set; } = [];
/// The archive of this PC that holds the server's downloaded originals (owner review 5, Q1); null until the first download.
public Guid? OriginalsArchiveId { get; set; }
public DateTimeOffset LastSeen { get; set; }
}
///
/// 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.
///
public sealed class ShareSettings
{
public const int DefaultHttpsPort = 8443;
public const int DefaultHttpPort = 8080;
public bool Enabled { get; set; }
/// The name clients see; empty: this PC's name.
public string? Name { get; set; }
public int HttpsPort { get; set; } = DefaultHttpsPort;
public int HttpPort { get; set; } = DefaultHttpPort;
/// The ports clients reach when a router forwards others to this PC; null: the ones above.
public int? PublicHttpsPort { get; set; }
public int? PublicHttpPort { get; set; }
/// Announce the library to Chronos programs on the local network.
public bool Discovery { get; set; } = true;
/// What restarts a running share when it changes (the name, the ports, the discovery); the rest applies live.
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;
}
}
///
/// Per-user preferences (language, theme, window layout, archive defaults, server session). Kept in
/// settings.json next to the database and written atomically, because language and theme apply before the
/// database opens.
///
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;
/// 2⁻⁴ of white: the deep analysis' night threshold (a mean log2 luminance of −4).
public const double DefaultNightBrightnessPercent = 6.25;
// ---- General ----
public string? Language { get; set; }
public AppTheme Theme { get; set; } = AppTheme.Dark;
public bool RailCollapsed { get; set; }
///
/// 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 ().
///
public Dictionary EditorGroups { get; set; } = new(StringComparer.Ordinal);
/// The sequence opened in Edit last; the picker selects it first (owner review 1, R7).
public Guid? LastEditedSequence { get; set; }
/// Toasts also appear as Windows notifications while the window is minimised or in the background (BRIEF §12.1).
public bool OsNotifications { get; set; } = true;
public WindowPlacement? Window { get; set; }
/// The first-run choice (local archive, adopted folder or server) was made.
public bool FirstRunCompleted { get; set; }
// ---- Updates ----
public bool CheckForUpdates { get; set; } = true;
// ---- Archive ----
/// Root of the local archive; null until the first-run choice or Settings › Archive sets it.
public string? LastArchivePath { get; set; }
/// Naming templates of new archives; Settings › Archive also writes them into the open archive's archive.json.
public string FolderTemplate { get; set; } = TemplateDefaults.Folder;
public string FileTemplate { get; set; } = TemplateDefaults.File;
///
/// 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.
///
public string? VideosFolder { get; set; } = Videos.VideosFolders.Default();
/// Proxy long edge of new archives (also written into the open archive); 0 = full size, -1 = no proxies.
public int ProxyLongEdge { get; set; } = 1920;
/// Thumbnail long edge of new archives (also written into the open archive), BRIEF §8.5.
public int ThumbnailLongEdge { get; set; } = 320;
///
/// Obsolete (owner review 2, R10): the former Settings › Archive › Rescan every. Nothing edits it any more; it only seeds
/// the interval of the archive-scan schedule () 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.
///
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 ----
/// Upper bound of the deep-analysis long edge (BRIEF §10.2: half native, capped at 2048 by default).
public int AnalysisLongEdge { get; set; } = 2048;
/// Frames whose mean brightness is at or below this share of white (in percent) count as night frames.
public double NightBrightnessPercent { get; set; } = DefaultNightBrightnessPercent;
/// Stars per megapixel from which a night frame shows a star field.
public double StarFieldDensity { get; set; } = 30;
/// The default of a new card's "Deep analysis" after import (BRIEF §13: on, in the background).
public bool DeepAnalysisAfterImport { get; set; } = true;
/// Sequences a scan of this PC indexes (adopted folders, new sidecars) also get a background deep analysis.
public bool DeepAnalysisAfterScan { get; set; }
// ---- Library ----
public LibraryLayout LibraryLayout { get; set; } = LibraryLayout.Grid;
public SequenceSort LibrarySort { get; set; } = SequenceSort.Newest;
///
/// The Videos section as cards (), as a list () or as the
/// Board ().
///
public LibraryLayout VideosLayout { get; set; } = LibraryLayout.Grid;
// ---- Rendering ----
public QualityProfile Quality { get; set; } = QualityProfile.Balanced;
/// Frame memory budget in GB; null = Auto (a quarter of installed memory).
public int? MemoryBudgetGb { get; set; }
/// 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).
public int? Parallelism { get; set; }
public bool BackgroundPriority { get; set; } = true;
public HardwarePreference HardwareEncoding { get; set; } = HardwarePreference.PreferHardware;
// ---- Storage ----
/// Cache (spill frames, thumbnails); null = cache under the data folder.
public string? CacheFolder { get; set; }
/// Decoded thumbnails kept in memory.
public int ThumbnailMemoryItems { get; set; } = DefaultThumbnailMemoryItems;
/// Upper bound of the disk cache in GB.
public int CacheLimitGb { get; set; } = DefaultCacheLimitGb;
// ---- Workspace (owner review 2, R8) ----
/// The workspace, where projects are edited outside the library; null = workspace under the data folder.
public string? WorkspaceFolder { get; set; }
/// A version saved in the workspace is sent to its home at once (and the home's new versions taken).
public bool WorkspaceAutoSync { get; set; } = true;
/// Versions taken from a home that a workspace project keeps besides its base and the versions not sent yet.
public int WorkspaceKeptVersions { get; set; } = DefaultWorkspaceKeptVersions;
/// The workspace project opened last for each sequence (sequence id → project id); Edit opens it again.
public Dictionary WorkspaceRecent { get; set; } = [];
///
/// 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.
///
public int WorkspaceSizeLimitGb { get; set; } = DefaultWorkspaceSizeLimitGb;
///
/// What "Open in workspace" copies unless chosen otherwise: or
/// (the proxies plus the originals, to render on this PC).
///
public string WorkspaceDefaultMedia { get; set; } = BundleMedia.Proxies;
/// A render of a project with changes not saved as a version saves one first (and sends it when Sync automatically is on).
public bool WorkspaceVersionOnRender { get; set; } = true;
///
/// 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.
///
public int WorkspaceCleanAfterDays { get; set; } = DefaultWorkspaceCleanAfterDays;
/// Which project Edit opens for a sequence with several in the workspace.
public WorkspaceOpenPolicy WorkspaceOpenProject { get; set; } = WorkspaceOpenPolicy.LastUsed;
///
/// 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.
///
[System.Text.Json.Serialization.JsonIgnore]
public string EffectiveDefaultMedia =>
string.Equals(WorkspaceDefaultMedia, BundleMedia.Originals, StringComparison.OrdinalIgnoreCase) ? BundleMedia.Originals : BundleMedia.Proxies;
/// as everything applies it: a value this Chronos does not know reads as the last used. Settings › Workspace shows the same.
[System.Text.Json.Serialization.JsonIgnore]
public WorkspaceOpenPolicy EffectiveOpenPolicy => Enum.IsDefined(WorkspaceOpenProject) ? WorkspaceOpenProject : WorkspaceOpenPolicy.LastUsed;
///
/// 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 .
///
public Dictionary WorkspaceOpened { get; set; } = [];
// ---- Server ----
public string? ServerUrl { get; set; }
public string? ServerUsername { get; set; }
/// The session token, encrypted for this Windows user with DPAPI (Base64).
public string? ProtectedToken { get; set; }
public List TrustedCertificates { get; set; } = [];
public List RecentServers { get; set; } = [];
///
/// 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.
///
public List KnownServers { get; set; } = [];
/// The alias table of , as the sync and the workspace compare server keys through it.
public ServerIdentity KnownIdentity() => new([.. KnownServers.Where(k => k.Id != Guid.Empty).Select(k => new KnownServerKey(k.Id, [.. k.Aliases]))]);
/// The known server of ; null when this PC has none.
public KnownServer? FindKnownServer(Guid id) => KnownServers.FirstOrDefault(k => k.Id == id);
/// Settings › Server › Sharing: this PC's library shared to the LAN while Chronos runs (owner review 5, #67).
public ShareSettings Share { get; set; } = new();
/// Let the server send render jobs to this PC (BRIEF §14.7).
public bool RenderNodeOptIn { get; set; }
/// Keep the proxy caches of the server sequences this PC opened with proxies up to date (BRIEF §12.7).
public bool KeepProxiesOffline { get; set; }
/// Send and take project settings changed on one side without asking (Server.html).
public bool SyncSettingsAutomatically { get; set; } = true;
/// Pause transfers with a server (uploads, sync downloads, workspace copies and renders sent) while Windows reports the connection as metered (Server.html).
public bool PauseUploadsOnMetered { get; set; }
// ---- Jobs ----
///
/// 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.
///
public bool PriorityQueue { get; set; }
/// Levels of the priority queue that differ from the defaults, by job kind (render → high).
public Dictionary JobPriorities { get; set; } = [];
/// "Clear done": finished jobs older than this are hidden from the Jobs list (they stay in the history).
public DateTimeOffset? JobsClearedAt { get; set; }
// ---- Advanced › Logs (owner review 2, R11; applied by AppLogging) ----
/// Least severe level written to the log files.
public LogLevel LogLevel { get; set; } = LogLevel.Info;
/// Log files last written longer ago are deleted.
public int LogRetentionDays { get; set; } = LogFileOptions.DefaultRetentionDays;
/// A log file this large (MB of 2²⁰ bytes) continues in a numbered one; 0 = no limit.
public int LogMaxFileMb { get; set; } = LogFileOptions.DefaultMaxFileMb;
/// While the log files together are larger (MB), the oldest are deleted, never the current one; 0 = no limit.
public int LogMaxTotalMb { get; set; } = LogFileOptions.DefaultMaxTotalMb;
/// One log file per UTC day or per hour.
public LogRotation LogRotation { get; set; } = LogRotation.Daily;
/// MB kept from the end of each log file in the diagnostics bundle.
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; }
}
/// Settings › Archive as the settings of a new archive (its name: the folder's).
public ArchiveSettings ArchiveDefaults() => new(string.Empty, new LayoutTemplates { Folder = FolderTemplate, File = FileTemplate },
new ProxyPolicy { LongEdge = ProxyLongEdge }, new ThumbnailPolicy { LongEdge = ThumbnailLongEdge });
/// Settings › Import and Analysis as the profile of a card or folder without its own (BRIEF §12.4), with the archive's templates.
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,
};
/// Settings › Analysis over : the width cap and the night and star-field thresholds.
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();
}
/// Reads settings JSON (Settings › Import); null when the text is not a settings object.
/// The text is not valid JSON.
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());
/// A deep copy (JSON round trip), used for import and reset.
public AppSettings Clone() => Parse(ToJson()) ?? new AppSettings();
///
/// 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).
///
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,
};
///
/// 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).
///
public AppSettings ForExport()
{
var copy = Clone();
copy.ProtectedToken = null;
copy.Window = null;
copy.WorkspaceFolder = null;
copy.WorkspaceRecent = [];
copy.WorkspaceOpened = [];
copy.KnownServers = [];
return copy;
}
///
/// Settings › Import: 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 .
///
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;