Files
Chronos/src/Chronos.App/Sections/SettingsViewModel.cs
T
Alby96andClaude Opus 5.5 8c87a9f47f feat(P7): desktop Videos section with player, copy, delete and videos folder
Adds the Videos rail section (Ctrl+4; Archive, Jobs and Server move to
Ctrl+5..7) that lists every render of this PC's archive, the signed-in
server and the workspace (not sent yet) in one list merged by render id,
with search, kind, codec, year, source and order filters, cards or a list,
and a player pane that plays in-process and falls back to "Cannot play
here". Copy to folder queues a hash-verified VideoCopy job into the new
Settings > Archive > Videos folder (never inside the archive or the
workspace, the reason given when unset); Delete... runs the dry run first,
shows its bytes and what stays, and deletes with the plan's fingerprint.
An older server, or one out of reach, leaves this PC's videos with the
reason. The trash dialog restores videos entries through the videos
library, and a finished VideoCopy job raises its toast.

Refs #21

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:28:37 +01:00

1825 lines
82 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.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Text.Json;
using System.Windows.Input;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Server;
using Chronos.App.Settings;
using Chronos.App.Shell;
using Chronos.App.Videos;
using Chronos.App.Workspace;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Import;
using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Naming;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Repositories;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
using Chronos.Ui.Theming;
namespace Chronos.App.Sections;
/// <summary>
/// Settings (BRIEF §12.8, Settings.html): a searchable section list on the left, the controls of one section on
/// the right, tooltips only. Text fields commit on Enter and revert on Esc; invalid input shows the Error border
/// with the reason in the tooltip. Everything persists through <see cref="AppSettings"/> (atomic writes). The
/// Archive rows show and change the open archive's own settings (archive.json, through the archive engine) and are the
/// defaults of new archives; Import and Analysis feed the defaults of new cards and the analysis jobs; Rendering feeds
/// the jobs from the next one on; Formats lists the decode tier per format on this PC with the codec extensions to
/// install; Advanced sets the log files (<see cref="Logs"/>) and restores the index from a backup at the next start;
/// About, the last page, shows this copy (<see cref="ShellViewModel.About"/>, whose update notice Updates shows).
/// </summary>
public sealed class SettingsViewModel : SectionViewModel
{
private readonly AppSettings _s;
private SettingsPage _page = SettingsPage.General;
private string _searchText = string.Empty;
private IReadOnlyList<SettingsPageItem> _visiblePages;
private IReadOnlyList<string> _previewNames = [];
private string? _archiveFreeText;
private string? _cacheUsageText;
private string? _adapterText;
private bool _isDetecting;
private bool _isTesting;
private CancellationTokenSource? _selfTest;
private Archive? _archive;
/// <summary>
/// The open of the archive at the folder chosen last (<see cref="RetargetArchiveAsync"/>), with the archive it found
/// there: edits of the Archive rows made meanwhile wait for it (<see cref="ArchiveAtFolderAsync"/>).
/// </summary>
private Task<Archive?> _retarget = Task.FromResult<Archive?>(null);
/// <summary>Drops a read of the open archive's settings that may have missed an edit being written meanwhile.</summary>
private readonly ArchiveReadGate _archiveReads = new();
/// <summary>The archive whose templates changed and which of them, offered by a toast (as long as a toast stays up).</summary>
private readonly ReorganizeOffer _reorganize = new(new Toast { Title = string.Empty }.Lifetime);
private bool _isDetectingFormats;
private IReadOnlyList<BackupOption> _backups = [];
private BackupOption? _selectedBackup;
private bool _isRestoring;
private InterfacePriority? _interfacePriority;
public SettingsViewModel(ShellViewModel shell)
: base(SectionKey.Settings, "Icon.Settings")
{
Shell = shell;
_s = shell.Services.Settings;
Startup = shell.Services.Environment is { IsCapture: false, IsPortable: false } ? new RunKeyStartWithWindows() : new MemoryStartWithWindows();
AllPages =
[
new(SettingsPage.General, ["Settings.General.Language", "Settings.General.Theme", .. ShowsStartup ? (string[])["Settings.General.Startup"] : [],
"Settings.General.Notifications", .. ProductFeatures.AdsEnabled ? (string[])["Settings.General.Usage"] : []]),
new(SettingsPage.Archive, ["Settings.Archive.Root", "Settings.Archive.Folders", "Settings.Archive.Files", "Settings.Archive.Proxies",
"Settings.Archive.Thumbnails", "Settings.Archive.VideosFolder"]),
new(SettingsPage.Import, ["Import.Scan.Sessions", "Import.Label.Scan", "Import.Scan.Subfolders", "Import.Scan.Verify", "Import.Label.Duplicates",
"Import.Label.After", "Import.After.Eject"]),
new(SettingsPage.Analysis, ["Settings.Analysis.Width", "Settings.Analysis.Night", "Settings.Analysis.Stars", "Settings.Analysis.Deep"]),
new(SettingsPage.Rendering, ["Settings.Rendering.Quality", "Settings.Rendering.Memory", "Settings.Rendering.Parallelism", "Settings.Rendering.PriorityQueue",
"Settings.Rendering.Hardware", "Settings.Rendering.Encoders"]),
new(SettingsPage.Formats, ["Settings.Formats.Title", "Settings.Formats.Column.Tier", "Settings.Formats.Install"]),
new(SettingsPage.Storage, ["Settings.Storage.Folder", "Settings.Storage.Thumbnails", "Settings.Storage.Limit"]),
new(SettingsPage.Workspace, ["Settings.Workspace.Folder", "Settings.Workspace.Move", "Settings.Workspace.SizeLimit", "Settings.Workspace.DefaultMedia",
"Settings.Workspace.Sync", "Settings.Workspace.AfterSave", "Settings.Workspace.VersionOnRender", "Settings.Workspace.SaveBeforeRender",
"Settings.Workspace.Kept", "Settings.Workspace.CleanAfter", "Settings.Workspace.OpenProject", "Settings.Workspace.Trash"]),
new(SettingsPage.Server, ["Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates"]),
new(SettingsPage.Updates, ["Settings.General.CheckOnStart", "Settings.Updates.Latest", "About.Update.Check", "About.Releases"]),
new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.LogLevel", "Settings.Advanced.KeepLogs",
"Settings.Advanced.FileSize", "Settings.Advanced.LogsTotal", "Settings.Advanced.Rotation", "Settings.Advanced.Diagnostics",
"Settings.Advanced.DiagnosticsLogs", "Settings.Advanced.Backup", "Settings.Advanced.Restore", "Settings.Advanced.Reset"]),
// The translation row shows outside English only, and the language changes while Settings is open.
new(SettingsPage.About, () => ["Shell.AppName", "About.Build", "About.Runtime", "About.System", "About.Licence", "About.ThirdParty",
.. Shell.About.IsTranslated ? (string[])["About.Translation"] : []]),
];
_visiblePages = AllPages;
// ---- Archive ----
ArchiveRoot = new EditableField(_s.LastArchivePath ?? string.Empty, v => v.Length == 0 ? null : ArchiveLocations.Validate(v), v =>
{
_s.LastArchivePath = v.Length == 0 ? null : Path.GetFullPath(v);
Save();
UpdateArchiveFree();
_retarget = RetargetArchiveAsync();
}, () => Loc.L("Tooltips.Settings.ArchiveRoot"));
FolderTemplate = new EditableField(_s.FolderTemplate, v => NamingPreview.Validate(v, isFolder: true), v =>
{
_s.FolderTemplate = v;
Save();
_ = OfferReorganizeAsync(UpdateArchiveAsync(a => a with { Templates = a.Templates with { Folder = v } }), ReorganizeParts.Folders);
}, () => Loc.L("Tooltips.Settings.FolderTemplate"));
FileTemplate = new EditableField(_s.FileTemplate, v => NamingPreview.Validate(v, isFolder: false), v =>
{
_s.FileTemplate = v;
Save();
_ = OfferReorganizeAsync(UpdateArchiveAsync(a => a with { Templates = a.Templates with { File = v } }), ReorganizeParts.Files);
}, () => Loc.L("Tooltips.Settings.FileTemplate"));
// Where Videos › Copy to folder puts copies (owner review 1, R9): empty leaves it unset; never inside the archive or the workspace.
VideosFolder = new EditableField(_s.VideosFolder ?? string.Empty, ValidateVideosFolder, v =>
{
_s.VideosFolder = v.Trim().Length == 0 ? null : Path.GetFullPath(v.Trim());
Save();
}, () => Loc.L("Tooltips.Settings.VideosFolder"));
FolderTemplate.PropertyChanged += (_, e) =>
{
if (e.PropertyName == nameof(EditableField.Text)) UpdatePreview();
};
FileTemplate.PropertyChanged += (_, e) =>
{
if (e.PropertyName == nameof(EditableField.Text)) UpdatePreview();
};
// ---- Import ----
SessionGap = new EditableField(_s.ImportSessionGapMinutes.ToString(CultureInfo.CurrentCulture), v => ValidateInt(v, 1, 24 * 60), v =>
{
_s.ImportSessionGapMinutes = int.Parse(v, NumberStyles.Integer, CultureInfo.CurrentCulture);
Save();
}, () => Loc.L("Tooltips.Import.Gap"));
MinimumFrames = new EditableField(_s.ImportMinimumFrames.ToString(CultureInfo.CurrentCulture), v => ValidateInt(v, 1, 1000), v =>
{
_s.ImportMinimumFrames = int.Parse(v, NumberStyles.Integer, CultureInfo.CurrentCulture);
Save();
}, () => Loc.L("Tooltips.Import.MinimumFrames"));
// ---- Analysis ----
NightBrightness = new EditableField(_s.NightBrightnessPercent.ToString("0.##", CultureInfo.CurrentCulture), v => ValidateNumber(v, 0.5, 50), v =>
{
_s.NightBrightnessPercent = double.Parse(v, NumberStyles.Float, CultureInfo.CurrentCulture);
Save();
}, () => Loc.L("Tooltips.Settings.Night"));
StarDensity = new EditableField(_s.StarFieldDensity.ToString("0.##", CultureInfo.CurrentCulture), v => ValidateNumber(v, 1, 1000), v =>
{
_s.StarFieldDensity = double.Parse(v, NumberStyles.Float, CultureInfo.CurrentCulture);
Save();
}, () => Loc.L("Tooltips.Settings.Stars"));
// ---- Rendering ----
InstalledGb = Math.Max(2, (int)Math.Round(GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / 1e9));
Parallelism = new EditableField(EffectiveParallelism.ToString(CultureInfo.CurrentCulture), ValidateParallelism, v =>
{
var n = int.Parse(v, NumberStyles.Integer, CultureInfo.CurrentCulture);
_s.Parallelism = n == ParallelismAuto ? null : n;
// Saving applies it: the job engine takes the new number of workers at once.
Save();
OnPropertyChanged(nameof(IsParallelismAuto));
}, () => Loc.L("Tooltips.Settings.Parallelism"));
JobPriorities = [.. PriorityKinds.Select(k => new JobPriorityRow(k, kind => Shell.Services.PriorityQueue.LevelOf(kind), SetJobPriority))];
// ---- Advanced ----
// Saving applies them to the log files (App.SaveSettings).
Logs = new LogSettingsRows(_s, Save);
// ---- Workspace ----
WorkspaceRows = new WorkspaceSettingsRows(_s, Save, () => AppEnvironment.Shown(Shell.Services.Workspace.Root), OpenWorkspaceFolder, ChangeWorkspaceFolderAsync,
WorkspaceSettingsServices.For(Shell.Services.Workspace, Shell.Services.Dialogs, (title, message, isError) => Shell.Notify(title, message, isError: isError),
MoveWorkspaceFolderAsync, () => WorkspaceFolderChange.ResumeUnfinishedAsync(Shell)));
// ---- Storage ----
// A capture shows its folders under a sample data folder; what is typed is taken back to the folder it stands for.
CacheFolder = new EditableField(AppEnvironment.Shown(CacheStore.Folder(shell.Services.Environment, _s)), v => ArchiveLocations.Validate(AppEnvironment.Actual(v)), v =>
{
var full = Path.GetFullPath(AppEnvironment.Actual(v));
_s.CacheFolder = full.Equals(Shell.Services.Environment.CacheDirectory, StringComparison.OrdinalIgnoreCase) ? null : full;
Save();
_ = UpdateCacheUsageAsync();
}, () => Loc.L("Tooltips.Settings.CacheFolder"));
ThumbnailMemory = new EditableField(_s.ThumbnailMemoryItems.ToString(CultureInfo.CurrentCulture), v => ValidateInt(v, 100, 100_000), v =>
{
_s.ThumbnailMemoryItems = int.Parse(v, NumberStyles.Integer, CultureInfo.CurrentCulture);
Save();
if (Shell.Services.Thumbnails is { } thumbs) thumbs.Capacity = _s.ThumbnailMemoryItems;
}, () => Loc.L("Tooltips.Settings.ThumbnailMemory"));
CacheLimit = new EditableField(_s.CacheLimitGb.ToString(CultureInfo.CurrentCulture), v => ValidateInt(v, 1, 100_000), v =>
{
_s.CacheLimitGb = int.Parse(v, NumberStyles.Integer, CultureInfo.CurrentCulture);
Save();
}, () => Loc.L("Tooltips.Settings.CacheLimit"));
// ---- Server ----
DefaultServer = new EditableField(ServerAddress.Display(_s.ServerUrl), v => v.Trim().Length == 0 || ServerAddress.TryParse(v, out _) ? null : Loc.L("Errors.Server.Address"), v =>
{
var display = v.Trim().Length == 0 ? null : ServerAddress.TryParse(v, out var uri) ? ServerAddress.Display(uri) : null;
if (!string.Equals(display, ServerAddress.Display(_s.ServerUrl), StringComparison.OrdinalIgnoreCase))
{
// A saved token belongs to the old server: never send it elsewhere.
_s.ProtectedToken = null;
}
_s.ServerUrl = display;
Save();
}, () => Loc.L("Tooltips.Settings.DefaultServer"));
SelectPageCommand = new RelayCommand(p =>
{
if (p is SettingsPageItem item) Page = item.Page;
else if (p is SettingsPage page) Page = page;
});
BrowseArchiveCommand = new RelayCommand(() => Browse(ArchiveRoot, "Settings.Archive.PickTitle"));
BrowseCacheCommand = new RelayCommand(() => Browse(CacheFolder, "Settings.Storage.PickTitle"));
BrowseVideosCommand = new RelayCommand(() => Browse(VideosFolder, "Settings.Archive.VideosPickTitle"));
OpenVideosFolderCommand = new RelayCommand(OpenVideosFolder, () => !string.IsNullOrWhiteSpace(_s.VideosFolder));
ResetMemoryCommand = new RelayCommand(() => MemoryBudget = MemoryAuto, () => !IsMemoryAuto);
ResetParallelismCommand = new RelayCommand(() =>
{
_s.Parallelism = null;
Save();
Parallelism.Load(ParallelismAuto.ToString(CultureInfo.CurrentCulture));
OnPropertyChanged(nameof(IsParallelismAuto));
}, () => !IsParallelismAuto);
RedetectCommand = new AsyncRelayCommand(DetectEncodersAsync, () => !_isDetecting && !_isTesting);
SelfTestCommand = new AsyncRelayCommand(SelfTestAsync, () => !_isDetecting && !_isTesting && Encoders.Any(e => e.Row.CanSelfTest));
ClearCacheCommand = new AsyncRelayCommand(ClearCacheAsync);
OpenDataFolderCommand = new RelayCommand(() => ShellActions.Reveal(Shell.Services.Environment.DataDirectory));
OpenLogsCommand = new RelayCommand(() => ShellActions.Reveal(Shell.Services.Environment.LogDirectory));
ExportDiagnosticsCommand = new AsyncRelayCommand(ExportDiagnosticsAsync);
BackupDatabaseCommand = new AsyncRelayCommand(BackupDatabaseAsync, () => Shell.Services.Database is not null);
RedetectFormatsCommand = new AsyncRelayCommand(() => DetectFormatsAsync(refresh: true), () => !_isDetectingFormats);
RestoreDatabaseCommand = new AsyncRelayCommand(RestoreDatabaseAsync, () => CanRestore);
CancelRestoreCommand = new RelayCommand(CancelRestore, () => IsRestoreStaged);
ResetAllCommand = new RelayCommand(ResetAll);
ResetSectionCommand = new RelayCommand(ResetSection, () => CanResetSection);
ExportSettingsCommand = new AsyncRelayCommand(ExportSettingsAsync);
ImportSettingsCommand = new AsyncRelayCommand(ImportSettingsAsync);
Loc.CultureChanged += OnCultureChanged;
UpdatePreview();
UpdateArchiveFree();
}
public ShellViewModel Shell { get; }
public IReadOnlyList<SettingsPageItem> AllPages { get; }
// ---------------- Navigation ----------------
public ICommand SelectPageCommand { get; }
public SettingsPage Page
{
get => _page;
set
{
if (!Set(ref _page, value)) return;
OnPropertyChanged(nameof(SelectedPageItem));
OnPropertyChanged(nameof(PageTitle));
OnPropertyChanged(nameof(CanResetSection));
if (value == SettingsPage.Rendering && Encoders.Count == 0 && !_isDetecting) _ = DetectEncodersAsync();
if (value == SettingsPage.Formats && Formats.Count == 0 && !_isDetectingFormats) _ = DetectFormatsAsync(refresh: false);
if (value == SettingsPage.Storage) _ = UpdateCacheUsageAsync();
if (value == SettingsPage.Workspace) _ = WorkspaceRows.MeasureAsync();
if (value == SettingsPage.Advanced) LoadBackups();
}
}
public SettingsPageItem? SelectedPageItem
{
get => AllPages.First(p => p.Page == _page);
set
{
if (value is not null) Page = value.Page;
}
}
public string PageTitle => Loc.L("Settings.Page." + _page);
/// <summary>Filters the section list.</summary>
public string SearchText
{
get => _searchText;
set
{
if (!Set(ref _searchText, value ?? string.Empty)) return;
var text = _searchText.Trim();
VisiblePages = text.Length == 0 ? AllPages : [.. AllPages.Where(p => p.Matches(text))];
if (VisiblePages.Count > 0 && VisiblePages.All(p => p.Page != _page)) Page = VisiblePages[0].Page;
}
}
public IReadOnlyList<SettingsPageItem> VisiblePages
{
get => _visiblePages;
private set => Set(ref _visiblePages, value);
}
// ---------------- General ----------------
public IReadOnlyList<LanguageOption> Languages => LanguageCatalog.Available;
public LanguageOption SelectedLanguage
{
get => LanguageCatalog.Match(Loc.Culture);
set
{
if (value is null || value == SelectedLanguage) return;
_s.Language = value.Code;
UiLanguage.Apply(value.Code);
Save();
}
}
public bool IsDarkTheme
{
get => _s.Theme == AppTheme.Dark;
set
{
if (value) ApplyTheme(AppTheme.Dark);
}
}
public bool IsLightTheme
{
get => _s.Theme == AppTheme.Light;
set
{
if (value) ApplyTheme(AppTheme.Light);
}
}
public bool IsSystemTheme
{
get => _s.Theme == AppTheme.System;
set
{
if (value) ApplyTheme(AppTheme.System);
}
}
/// <summary>Where "Start with Windows" is kept (the Run key); screenshots, tests and portable copies keep it in memory.</summary>
internal IStartWithWindows Startup { get; set; }
/// <summary>The latest archive folder change: done once the rows show what the folder holds (tests wait for it).</summary>
internal Task ArchiveRetarget => _retarget;
/// <summary>The read of the open archive's settings when Settings was last shown: done once the rows show them (tests wait for it).</summary>
internal Task ArchiveReload { get; private set; } = Task.CompletedTask;
/// <summary>A portable copy leaves nothing in the registry (BRIEF §6.2): it offers no Startup row.</summary>
public bool ShowsStartup => !Shell.Services.Environment.IsPortable;
/// <summary>Chronos starts minimised when the user signs in to Windows.</summary>
public bool StartWithWindows
{
get => Startup.IsEnabled;
set
{
if (Startup.IsEnabled == value) return;
Startup.SetEnabled(value);
OnPropertyChanged();
}
}
/// <summary>Toasts also appear as Windows notifications while the window is minimised or in the background.</summary>
public bool OsNotifications
{
get => _s.OsNotifications;
set
{
if (_s.OsNotifications == value) return;
_s.OsNotifications = value;
Save();
OnPropertyChanged();
}
}
/// <summary>The usage counts consent belongs to monetization (BRIEF §21): only builds with it enabled offer it.</summary>
public bool ShowsUsageCounts => ProductFeatures.AdsEnabled;
public bool UsageCounts
{
get => _s.AnonymousUsageCounts;
set
{
if (_s.AnonymousUsageCounts == value) return;
_s.AnonymousUsageCounts = value;
Save();
OnPropertyChanged();
}
}
// ---------------- Archive ----------------
public EditableField ArchiveRoot { get; }
public EditableField FolderTemplate { get; }
public EditableField FileTemplate { get; }
public ICommand BrowseArchiveCommand { get; }
/// <summary>Archive › Videos folder: where Videos › Copy to folder puts copies of renders.</summary>
public EditableField VideosFolder { get; }
public ICommand BrowseVideosCommand { get; }
public ICommand OpenVideosFolderCommand { get; }
/// <summary>"1.8 TB free".</summary>
public string? ArchiveFreeText
{
get => _archiveFreeText;
private set => Set(ref _archiveFreeText, value);
}
/// <summary>The first three names the templates produce (live while typing).</summary>
public IReadOnlyList<string> PreviewNames
{
get => _previewNames;
private set => Set(ref _previewNames, value);
}
/// <summary>
/// BRIEF §8.5: 1280, 1920 (default), 2560 or full size; no proxies is what a server admin may also choose. A size the
/// archive got elsewhere (the admin panel also offers 3840) is listed with its number, never shown as another size.
/// </summary>
public IReadOnlyList<SettingsOption<int>> ProxySizes =>
[
.. Sizes([1280, 1920, 2560], _s.ProxyLongEdge is ProxyPolicy.FullSize or ProxyPolicy.Disabled ? null : _s.ProxyLongEdge),
new(ProxyPolicy.FullSize, Loc.L("Settings.Archive.FullSize")),
new(ProxyPolicy.Disabled, Loc.L("Settings.Archive.NoProxies")),
];
/// <summary>The open archive's proxy size (archive.json), and the one of new archives.</summary>
public SettingsOption<int> SelectedProxySize
{
get => ProxySizes.First(p => p.Value == _s.ProxyLongEdge);
set
{
if (value is null || value.Value == _s.ProxyLongEdge) return;
_s.ProxyLongEdge = value.Value;
Save();
OnPropertyChanged();
_ = UpdateArchiveAsync(a => a with { Proxies = a.Proxies with { LongEdge = value.Value } });
}
}
/// <summary>240, 320 (default), 480 or 640; another size of the archive (160 to 1024 are valid) is listed with its number.</summary>
public IReadOnlyList<SettingsOption<int>> ThumbnailSizes => Sizes([240, 320, 480, 640], _s.ThumbnailLongEdge);
/// <summary>The open archive's thumbnail size (archive.json), and the one of new archives.</summary>
public SettingsOption<int> SelectedThumbnailSize
{
get => ThumbnailSizes.First(p => p.Value == _s.ThumbnailLongEdge);
set
{
if (value is null || value.Value == _s.ThumbnailLongEdge) return;
_s.ThumbnailLongEdge = value.Value;
Save();
OnPropertyChanged();
_ = UpdateArchiveAsync(a => a with { Thumbnails = a.Thumbnails with { LongEdge = value.Value } });
}
}
// ---------------- Import ----------------
public EditableField SessionGap { get; }
public EditableField MinimumFrames { get; }
public bool ImportSubfolders
{
get => _s.ImportSubfolders;
set => SetSetting(_s.ImportSubfolders, value, v => _s.ImportSubfolders = v);
}
public bool ImportVerify
{
get => _s.ImportVerify;
set => SetSetting(_s.ImportVerify, value, v => _s.ImportVerify = v);
}
public bool IsSkipDuplicates
{
get => _s.ImportDuplicates == DuplicatePolicy.Skip;
set
{
if (value) SetDuplicates(DuplicatePolicy.Skip);
}
}
public bool IsImportDuplicates
{
get => _s.ImportDuplicates == DuplicatePolicy.ImportAgain;
set
{
if (value) SetDuplicates(DuplicatePolicy.ImportAgain);
}
}
public bool IsKeepCard
{
get => _s.ImportAfter == AfterImport.Keep;
set
{
if (value) SetAfterImport(AfterImport.Keep);
}
}
public bool IsDeleteImported
{
get => _s.ImportAfter == AfterImport.DeleteImported;
set
{
if (value) SetAfterImport(AfterImport.DeleteImported);
}
}
public bool IsFormatCard
{
get => _s.ImportAfter == AfterImport.FormatCard;
set
{
if (value) SetAfterImport(AfterImport.FormatCard);
}
}
public bool ImportEject
{
get => _s.ImportEject;
set => SetSetting(_s.ImportEject, value, v => _s.ImportEject = v);
}
// ---------------- Analysis ----------------
/// <summary>BRIEF §10.2: half native, capped at 2048 by default.</summary>
public IReadOnlyList<SettingsOption<int>> AnalysisWidths =>
[.. new[] { 1024, 2048, 3072, 4096 }.Select(n => new SettingsOption<int>(n, n.ToString(CultureInfo.InvariantCulture)))];
public SettingsOption<int> SelectedAnalysisWidth
{
get => AnalysisWidths.FirstOrDefault(p => p.Value == _s.AnalysisLongEdge) ?? AnalysisWidths[1];
set
{
if (value is null || value.Value == _s.AnalysisLongEdge) return;
_s.AnalysisLongEdge = value.Value;
Save();
OnPropertyChanged();
}
}
public EditableField NightBrightness { get; }
public EditableField StarDensity { get; }
public bool DeepAnalysisAfterImport
{
get => _s.DeepAnalysisAfterImport;
set => SetSetting(_s.DeepAnalysisAfterImport, value, v => _s.DeepAnalysisAfterImport = v);
}
public bool DeepAnalysisAfterScan
{
get => _s.DeepAnalysisAfterScan;
set => SetSetting(_s.DeepAnalysisAfterScan, value, v => _s.DeepAnalysisAfterScan = v);
}
// ---------------- Rendering ----------------
public IReadOnlyList<SettingsOption<QualityProfile>> Qualities =>
[.. Enum.GetValues<QualityProfile>().Select(q => new SettingsOption<QualityProfile>(q, Loc.L("Settings.Rendering.Quality." + q)))];
public SettingsOption<QualityProfile> SelectedQuality
{
get => Qualities.First(q => q.Value == _s.Quality);
set
{
if (value is null || value.Value == _s.Quality) return;
_s.Quality = value.Value;
Save();
OnPropertyChanged();
}
}
/// <summary>Installed memory in GB (rounded).</summary>
public int InstalledGb { get; }
public int MemoryMinimum => 2;
public int MemoryMaximum => Math.Max(MemoryMinimum, InstalledGb - 2);
/// <summary>Auto: a quarter of installed memory.</summary>
public int MemoryAuto => Math.Clamp(InstalledGb / 4, MemoryMinimum, MemoryMaximum);
public double MemoryBudget
{
get => _s.MemoryBudgetGb ?? MemoryAuto;
set
{
var gb = (int)Math.Round(Math.Clamp(value, MemoryMinimum, MemoryMaximum));
int? stored = gb == MemoryAuto ? null : gb;
if (stored == _s.MemoryBudgetGb) return;
_s.MemoryBudgetGb = stored;
Save();
OnPropertyChanged();
OnPropertyChanged(nameof(MemoryText));
OnPropertyChanged(nameof(IsMemoryAuto));
}
}
public bool IsMemoryAuto => _s.MemoryBudgetGb is null;
public string MemoryText => Loc.L("Settings.Rendering.Gb", (int)MemoryBudget);
public string InstalledText => Loc.L("Settings.Rendering.Installed", InstalledGb);
public string MemoryAutoText => Loc.L("Settings.Rendering.AutoValue", MemoryAuto);
public ICommand ResetMemoryCommand { get; }
public EditableField Parallelism { get; }
public int LogicalCores => Environment.ProcessorCount;
/// <summary>Auto: half the logical cores (photos the running job processes at once, owner review 1).</summary>
public int ParallelismAuto => ProcessingTuning.ParallelismAuto(LogicalCores);
private int EffectiveParallelism => _s.Parallelism ?? ParallelismAuto;
public bool IsParallelismAuto => _s.Parallelism is null;
public string CoresText => Loc.Plural("Settings.Rendering.Cores", LogicalCores);
public string ParallelismAutoText => Loc.L("Settings.Rendering.AutoValue", ParallelismAuto);
public ICommand ResetParallelismCommand { get; }
/// <summary>
/// The priority queue (owner review 1): on, a job of a higher level pauses the running one without asking, and that one
/// resumes by itself afterwards; off, jobs wait their turn.
/// </summary>
public bool PriorityQueue
{
get => _s.PriorityQueue;
set => SetSetting(_s.PriorityQueue, value, v => _s.PriorityQueue = v);
}
/// <summary>The kinds of job this PC runs with their levels in the priority queue, the ones the user waits for first.</summary>
public IReadOnlyList<JobPriorityRow> JobPriorities { get; }
public bool BackgroundPriority
{
get => _s.BackgroundPriority;
set
{
if (_s.BackgroundPriority == value) return;
_s.BackgroundPriority = value;
Save();
OnPropertyChanged();
_interfacePriority?.Update();
}
}
public bool IsPreferHardware
{
get => _s.HardwareEncoding == HardwarePreference.PreferHardware;
set => SetHardware(value, HardwarePreference.PreferHardware);
}
public bool IsSoftwareOnly
{
get => _s.HardwareEncoding == HardwarePreference.SoftwareOnly;
set => SetHardware(value, HardwarePreference.SoftwareOnly);
}
public bool IsHardwareForPreviews
{
get => _s.HardwareEncoding == HardwarePreference.HardwareForPreviews;
set => SetHardware(value, HardwarePreference.HardwareForPreviews);
}
public ObservableCollection<EncoderRowViewModel> Encoders { get; } = [];
/// <summary>"NVIDIA GeForce RTX 4070 · 3 encoders".</summary>
public string? AdapterText
{
get => _adapterText;
private set
{
if (Set(ref _adapterText, value)) OnPropertyChanged(nameof(AdapterToolTip));
}
}
/// <summary>The adapter and its encoders whole (the row may cut them at the minimum width), then what they are.</summary>
public string AdapterToolTip => AdapterText is { Length: > 0 } adapter
? string.Join(Loc.Separator, adapter, Loc.L("Tooltips.Settings.Adapter"))
: Loc.L("Tooltips.Settings.Adapter");
public bool IsDetecting
{
get => _isDetecting;
private set => Set(ref _isDetecting, value);
}
public ICommand RedetectCommand { get; }
public ICommand SelfTestCommand { get; }
// ---------------- Formats ----------------
public ObservableCollection<FormatRowViewModel> Formats { get; } = [];
/// <summary>The one-line notices of BRIEF §8.1: each missing codec extension with its Install button.</summary>
public ObservableCollection<MissingExtensionViewModel> MissingExtensions { get; } = [];
public bool HasMissingExtensions => MissingExtensions.Count > 0;
public bool IsDetectingFormats
{
get => _isDetectingFormats;
private set => Set(ref _isDetectingFormats, value);
}
public ICommand RedetectFormatsCommand { get; }
// ---------------- Storage ----------------
public EditableField CacheFolder { get; }
public EditableField ThumbnailMemory { get; }
public EditableField CacheLimit { get; }
public ICommand BrowseCacheCommand { get; }
public ICommand ClearCacheCommand { get; }
/// <summary>"1.4 GB used · 612 GB free".</summary>
public string? CacheUsageText
{
get => _cacheUsageText;
private set => Set(ref _cacheUsageText, value);
}
// ---------------- Workspace ----------------
/// <summary>
/// Settings › Workspace (owner review 2, R8; phase 5c): the folder (Change, Move…, what it takes), Size limit, Default
/// media, Sync automatically, Version on render, Kept versions, Clean after, Open project and Trash.
/// </summary>
public WorkspaceSettingsRows WorkspaceRows { get; }
/// <summary>Shows the workspace folder in Explorer (made, with its manifest, when the workspace was never used).</summary>
private void OpenWorkspaceFolder()
{
try
{
ShellActions.Reveal(Shell.Services.Workspace.Store.Root);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{
Shell.ReportError(ex);
}
}
/// <summary>Another workspace folder, after its plan (nothing is moved): Edit lists its projects from then on.</summary>
private async Task ChangeWorkspaceFolderAsync()
{
await WorkspaceFolderChange.ChooseAsync(Shell);
WorkspaceRows.Refresh();
await WorkspaceRows.MeasureAsync();
}
/// <summary>The workspace folder moved with its projects, after its plan: the move job takes them, and Edit waits for it.</summary>
private async Task MoveWorkspaceFolderAsync()
{
await WorkspaceFolderChange.MoveAsync(Shell);
WorkspaceRows.Refresh();
}
/// <summary>A move of the workspace folder ended (any thread): the page shows the folder in use, what it takes, and Move… and Change… again.</summary>
private void OnWorkspaceMoveEnded() => System.Windows.Application.Current?.Dispatcher.BeginInvoke(() =>
{
WorkspaceRows.Refresh();
CommandManager.InvalidateRequerySuggested();
if (_page == SettingsPage.Workspace) _ = WorkspaceRows.MeasureAsync();
});
// ---------------- Server ----------------
public EditableField DefaultServer { get; }
public bool RenderNodeOptIn
{
get => _s.RenderNodeOptIn;
set
{
if (_s.RenderNodeOptIn == value) return;
_s.RenderNodeOptIn = value;
Save();
OnPropertyChanged();
Shell.Server.Refresh();
}
}
public ObservableCollection<TrustedCertificateRow> Certificates { get; } = [];
public bool HasCertificates => Certificates.Count > 0;
// ---------------- Updates ----------------
public bool CheckForUpdates
{
get => _s.CheckForUpdates;
set
{
if (_s.CheckForUpdates == value) return;
_s.CheckForUpdates = value;
Save();
OnPropertyChanged();
}
}
// ---------------- Advanced ----------------
public string DataFolder => AppEnvironment.Shown(Shell.Services.Environment.DataDirectory);
public string LogsFolder => AppEnvironment.Shown(Shell.Services.Environment.LogDirectory);
public string PortableText => Loc.L(Shell.Services.Environment.IsPortable ? "Settings.Advanced.PortableOn" : "Settings.Advanced.PortableOff");
/// <summary>Level, retention, size limits and rotation of the log files, and the diagnostics bundle's share of each.</summary>
public LogSettingsRows Logs { get; }
public ICommand OpenDataFolderCommand { get; }
public ICommand OpenLogsCommand { get; }
public ICommand ExportDiagnosticsCommand { get; }
public ICommand BackupDatabaseCommand { get; }
/// <summary>The copies of the index in the backups folder (the Index backup schedule's, Back up now's), newest first (Restore).</summary>
public IReadOnlyList<BackupOption> Backups
{
get => _backups;
private set
{
if (!Set(ref _backups, value)) return;
OnPropertyChanged(nameof(HasBackups));
}
}
public bool HasBackups => _backups.Count > 0;
public BackupOption? SelectedBackup
{
get => _selectedBackup;
set
{
if (Set(ref _selectedBackup, value)) CommandManager.InvalidateRequerySuggested();
}
}
/// <summary>A restore waits for the next start of Chronos.</summary>
public bool IsRestoreStaged => DatabaseBackups.HasStagedRestore(Shell.Services.Environment.DatabasePath);
/// <summary>Also while the index cannot be opened: that is the case a restore exists for (BRIEF §6.2).</summary>
private bool CanRestore => !_isRestoring && _selectedBackup is not null && !IsRestoreStaged;
public ICommand RestoreDatabaseCommand { get; }
public ICommand CancelRestoreCommand { get; }
public ICommand ResetAllCommand { get; }
// ---------------- Footer ----------------
public ICommand ResetSectionCommand { get; }
/// <summary>
/// Formats only shows this PC and About only this copy: they have no Reset section. Advanced's resets its log rows
/// (owner review 2, R11); its paths and actions have no default.
/// </summary>
public bool CanResetSection => _page is not (SettingsPage.Formats or SettingsPage.About);
public ICommand ExportSettingsCommand { get; }
public ICommand ImportSettingsCommand { get; }
/// <summary>
/// Loads what needs the services (certificates, cache usage, the open archive's settings), follows the server session,
/// applies "Background priority" while Chronos is in front and says how a restore staged before this start went, and
/// where the data of a portable copy in a OneDrive folder went.
/// </summary>
public void Attach()
{
try
{
CacheStore.Prepare(Shell.Services.Environment.CacheDirectory);
}
catch (IOException ex)
{
Log.Warning("settings", "Cache folder not prepared", ex);
}
LoadCertificates();
Shell.Services.Server.PropertyChanged += OnServerChanged;
Shell.Services.Workspace.MoveEnded += OnWorkspaceMoveEnded;
if (System.Windows.Application.Current is { } app) _interfacePriority = new InterfacePriority(app, () => _s.BackgroundPriority);
_ = LoadArchiveAsync();
switch (Shell.Services.StagedRestore)
{
case StagedRestoreResult.Restored:
Shell.Notify(Loc.L("Settings.Advanced.Restored"));
break;
case StagedRestoreResult.Unreadable:
Shell.Notify(Loc.L("Settings.Advanced.RestoreFailed"), Loc.L("Errors.Backup.Unreadable"), isError: true);
break;
case StagedRestoreResult.Deferred:
Shell.Notify(Loc.L("Settings.Advanced.RestoreFailed"), Loc.L("Errors.Backup.Deferred"), isError: true);
break;
}
// BRIEF §6.2: a portable copy in a folder OneDrive synchronises keeps its data in this user's folder instead, and
// leaves the data it kept beside it before where it is. Only a user folder that is itself synchronised is unsafe.
var environment = Shell.Services.Environment;
if (environment.SyncedFolder is not null)
Shell.Notify(Loc.L("Settings.Advanced.DataInOneDrive"), Formatting.LeftToRight(DataFolder), Loc.L("Common.Open"),
Loc.L("Tooltips.Settings.DataInOneDrive"), () => ShellActions.Reveal(Shell.Services.Environment.DataDirectory), isError: true);
else if (environment.PortableSyncRoot is not null)
Shell.Notify(Loc.L("Settings.Advanced.DataOutsideOneDrive"), Formatting.LeftToRight(DataFolder), Loc.L("Common.Open"),
Loc.L("Tooltips.Settings.OpenDataFolder"), () => ShellActions.Reveal(Shell.Services.Environment.DataDirectory));
if (environment.EarlierPortableData is { } earlier)
Shell.Notify(Loc.L("Settings.Advanced.EarlierData"), Formatting.LeftToRight(earlier), Loc.L("Common.Open"),
Loc.L("Tooltips.Settings.EarlierData"), () => ShellActions.Reveal(earlier));
Startup.Refresh();
}
public override void Dispose()
{
Loc.CultureChanged -= OnCultureChanged;
Shell.Services.Server.PropertyChanged -= OnServerChanged;
Shell.Services.Workspace.MoveEnded -= OnWorkspaceMoveEnded;
_selfTest?.Cancel();
_interfacePriority?.Dispose();
base.Dispose();
}
/// <summary>Other screens change the archive and the server in use: Settings shows them when it opens.</summary>
protected override void OnActivated() => ReloadShared();
// ---------------- Implementation ----------------
private void Save() => Shell.Services.SaveSettings();
private void ApplyTheme(AppTheme theme)
{
_s.Theme = theme;
ThemeManager.Apply(theme);
Save();
OnPropertyChanged(nameof(IsDarkTheme));
OnPropertyChanged(nameof(IsLightTheme));
OnPropertyChanged(nameof(IsSystemTheme));
}
private void SetHardware(bool value, HardwarePreference preference)
{
if (!value || _s.HardwareEncoding == preference) return;
_s.HardwareEncoding = preference;
Save();
OnPropertyChanged(nameof(IsPreferHardware));
OnPropertyChanged(nameof(IsSoftwareOnly));
OnPropertyChanged(nameof(IsHardwareForPreviews));
Shell.Server.Refresh();
}
/// <summary>Stores a switch of Settings and tells the view (the caller's property).</summary>
private void SetSetting(bool current, bool value, Action<bool> store, [System.Runtime.CompilerServices.CallerMemberName] string? property = null)
{
if (current == value) return;
store(value);
Save();
OnPropertyChanged(property);
}
private void SetDuplicates(DuplicatePolicy policy)
{
if (_s.ImportDuplicates == policy) return;
_s.ImportDuplicates = policy;
Save();
OnPropertyChanged(nameof(IsSkipDuplicates));
OnPropertyChanged(nameof(IsImportDuplicates));
}
private void SetAfterImport(AfterImport after)
{
if (_s.ImportAfter == after) return;
_s.ImportAfter = after;
Save();
OnPropertyChanged(nameof(IsKeepCard));
OnPropertyChanged(nameof(IsDeleteImported));
OnPropertyChanged(nameof(IsFormatCard));
}
/// <summary>
/// Takes the archive and server values other screens set (opening an archive, connecting), unless the field holds an
/// edit not committed yet, and the sign-in entry as Task Manager may have left it.
/// </summary>
private void ReloadShared()
{
if (!ArchiveRoot.IsDirty) ArchiveRoot.Load(_s.LastArchivePath ?? string.Empty);
if (!DefaultServer.IsDirty) DefaultServer.Load(ServerAddress.Display(_s.ServerUrl));
OnPropertyChanged(nameof(StartWithWindows));
UpdateArchiveFree();
ArchiveReload = LoadArchiveAsync();
if (_page == SettingsPage.Advanced) LoadBackups();
// What the workspace takes and holds in its trash may have changed elsewhere (a local copy removed in Edit).
if (_page == SettingsPage.Workspace) _ = WorkspaceRows.MeasureAsync();
}
/// <summary>
/// Shows the open archive's own templates, proxy size and thumbnail size unless a field holds an edit; they also become
/// the defaults of new archives. They come from its archive.json, which also brings the index up to a change another
/// process sharing the archive made, so imports follow it too. While the file cannot be read (offline), the templates
/// and proxy size are the index's and the thumbnail size stays this PC's: only the file knows the archive's. The open
/// archive is the one at the archive folder of this PC, never another one of the index: with no folder, or none
/// registered there, the rows edit only this PC's defaults. Returns that archive (null for none).
/// </summary>
private Task<Archive?> LoadArchiveAsync() => LoadArchiveAsync(_s.LastArchivePath);
/// <summary>
/// <see cref="LoadArchiveAsync()"/> for the archive folder <paramref name="root"/>, which a folder change may have
/// replaced meanwhile: the rows are then left to the folder chosen since, and the archive registered at
/// <paramref name="root"/> is still returned, so edits made for that folder reach it.
/// </summary>
private async Task<Archive?> LoadArchiveAsync(string? root)
{
if (Shell.Services.Database is not { } db || Shell.Services.Archives is not { } archives) return null;
Archive? archive = null;
try
{
ArchiveSettings settings;
while (true)
{
var read = _archiveReads.BeginRead();
var registered = await db.Archives.ListAsync();
archive = root is { Length: > 0 } ? CurrentArchive.At(registered, root) : null;
if (!IsArchiveFolder(root)) return archive;
_archive = archive;
if (archive is null) return null;
settings = await Task.Run(() => archives.RefreshSettingsAsync(archive.Id))
?? new ArchiveSettings(archive.Name, new LayoutTemplates { Folder = archive.FolderTemplate, File = archive.FileTemplate },
new ProxyPolicy { LongEdge = archive.ProxyLongEdge }, new ThumbnailPolicy { LongEdge = _s.ThumbnailLongEdge });
if (!IsArchiveFolder(root)) return archive;
// A read that overlapped an edit being written may have missed it: it is not shown, and the rows are read
// again once no edit is being written (ArchiveReadGate), so this is done only when they show the archive.
if (_archiveReads.IsCurrent(read)) break;
await _archiveReads.WrittenAsync();
}
if (!FolderTemplate.IsDirty) FolderTemplate.Load(settings.Templates.Folder);
if (!FileTemplate.IsDirty) FileTemplate.Load(settings.Templates.File);
var changed = _s.FolderTemplate != settings.Templates.Folder || _s.FileTemplate != settings.Templates.File
|| _s.ProxyLongEdge != settings.Proxies.LongEdge || _s.ThumbnailLongEdge != settings.Thumbnails.LongEdge;
_s.FolderTemplate = settings.Templates.Folder;
_s.FileTemplate = settings.Templates.File;
_s.ProxyLongEdge = settings.Proxies.LongEdge;
_s.ThumbnailLongEdge = settings.Thumbnails.LongEdge;
if (changed) Save();
// The lists first: a size the archive got elsewhere joins them before it is selected.
OnPropertyChanged(nameof(ProxySizes));
OnPropertyChanged(nameof(ThumbnailSizes));
OnPropertyChanged(nameof(SelectedProxySize));
OnPropertyChanged(nameof(SelectedThumbnailSize));
UpdatePreview();
}
catch (Exception ex) when (ex is DatabaseException or ArgumentException)
{
Log.Warning("settings", "The open archive's settings could not be read", ex);
}
return archive;
}
/// <summary>Whether <paramref name="root"/> is still this PC's archive folder (the one the rows show).</summary>
private bool IsArchiveFolder(string? root) => string.Equals(root, _s.LastArchivePath, StringComparison.Ordinal);
/// <summary>
/// The archive an Archive row edits, as the folder was when the row was edited (<paramref name="retarget"/>, the
/// latest folder change then): the open one, or, while the archive at that folder is still opening or once another
/// folder has been chosen, the one found there (null for none), so the edit is neither lost nor sent to a folder
/// chosen later.
/// </summary>
private async Task<Archive?> ArchiveAtFolderAsync(Task<Archive?> retarget)
{
if (retarget.IsCompleted && retarget == _retarget) return _archive;
// Its failures were told already; only the archive it found matters here.
await ((Task)retarget).ConfigureAwait(ConfigureAwaitOptions.ContinueOnCapturedContext | ConfigureAwaitOptions.SuppressThrowing);
return retarget.IsCompletedSuccessfully ? retarget.Result : null;
}
/// <summary>
/// Writes one Archive row into the open archive's archive.json and index through the archive engine (BRIEF §7). When
/// that fails (offline, read-only, busy) the user hears why and the rows show the archive's values again. An edit made
/// while the archive at a folder just chosen is opening waits for it, then goes to that archive (or stays this PC's
/// default when there is none), instead of being lost. <paramref name="retarget"/> is the folder change the edit was
/// made after, the latest one by default. Returns the archive as the edit left it; null when no archive took it.
/// </summary>
private async Task<Archive?> UpdateArchiveAsync(Func<ArchiveSettings, ArchiveSettings> edit, Task<Archive?>? retarget = null)
{
retarget ??= _retarget;
var waited = !retarget.IsCompleted;
if (await ArchiveAtFolderAsync(retarget) is not { } archive || Shell.Services.Archives is not { } archives) return null;
bool reload;
Archive? saved = null;
_archiveReads.BeginWrite();
try
{
var updated = saved = await Task.Run(() => archives.UpdateSettingsAsync(archive.Id, edit));
// The archive folder may have changed meanwhile: the rows then belong to another archive.
if (_archive?.Id == updated.Id) _archive = updated;
// The open showed the archive's values over the edit: unless another folder was chosen since, the rows (and
// this PC's defaults) take what it holds now.
reload = waited && _retarget == retarget;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or InvalidDataException or NewerFormatException
or DatabaseException)
{
Log.Warning("settings", "The archive settings were not saved", ex);
Shell.Notify(Loc.L("Settings.Archive.NotSaved"), ArchiveActions.Cause(ex), isError: true);
reload = true;
}
finally
{
// A read of the archive's settings this write overlapped was not shown: it reads again once no edit is written.
_archiveReads.EndWrite();
}
// Only once the write ended: a read begun while it is written waits for that end.
if (reload) await LoadArchiveAsync();
return saved;
}
/// <summary>
/// A template names only what is filed from now on: once the archive took a new one (<paramref name="update"/>), a toast
/// offers Reorganize, which applies the templates changed since to every sequence already in the archive, after a dry
/// run (owner review 2, R7). A template changed while the toast is still up joins it instead of raising another.
/// </summary>
private async Task OfferReorganizeAsync(Task<Archive?> update, ReorganizeParts part)
{
if (await update is not { } archive || Shell.Services.Database is not { } db) return;
try
{
// An empty archive has nothing to reorganize.
if (await db.Sequences.CountAsync(new SequenceQuery { ArchiveId = archive.Id }) == 0) return;
}
catch (DatabaseException ex)
{
Log.Warning("settings", "The sequences of the archive were not counted", ex);
return;
}
var raised = DateTime.UtcNow;
if (!_reorganize.Add(archive, part, raised)) return;
var toast = new Toast
{
Title = Loc.L("Settings.Archive.TemplatesSaved"),
Message = Loc.L("Settings.Archive.ExistingKept"),
ActionText = Loc.L("Settings.Archive.Reorganize"),
ActionToolTip = Loc.L("Tooltips.Settings.Reorganize"),
ActionCommand = new RelayCommand(() =>
{
// Every template of this archive changed since; what this toast offered when another toast of it took them.
var (target, parts) = _reorganize.Take(archive.Id) ?? (archive, part);
Shell.Navigate(SectionKey.Archive);
_ = Shell.Archive.OpenReorganizeAllAsync(target, parts);
}),
};
// Gone from the screen early (dismissed, pushed out), the next change of this archive raises a toast of its own.
toast.Closed += (_, _) => _reorganize.Closed(archive.Id, raised);
Shell.ShowToast(toast);
}
/// <summary>
/// Every archive row into the archive found after <paramref name="retarget"/>: Archive › Reset section, after the user
/// confirmed it for that archive.
/// </summary>
private Task PushArchiveSettingsAsync(Task<Archive?> retarget) => UpdateArchiveAsync(a => a with
{
Templates = a.Templates with { Folder = _s.FolderTemplate, File = _s.FileTemplate },
Proxies = a.Proxies with { LongEdge = _s.ProxyLongEdge },
Thumbnails = a.Thumbnails with { LongEdge = _s.ThumbnailLongEdge },
}, retarget);
/// <summary>
/// The archive folder changed: an archive already there is registered as at start (relinked when it moved) and given
/// its rescan, and the rows show its settings; any other folder leaves them with this PC's defaults for new archives.
/// Later edits never reach the archive shown before. Returns the archive registered at that folder (null for none),
/// even when another folder has been chosen since: edits made for this one go there.
/// </summary>
private async Task<Archive?> RetargetArchiveAsync()
{
_archive = null;
var root = _s.LastArchivePath;
if (root is not null && Shell.Services.Archives is { } archives)
{
try
{
var opened = await Task.Run(async () => File.Exists(new ArchivePaths(root).ManifestPath) ? await archives.OpenAsync(root) : null);
if (opened is not null) await Shell.Services.QueueScanAsync(opened, full: false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or NewerFormatException
or DatabaseException)
{
Log.Warning("settings", $"The archive at {root} could not be opened", ex);
Shell.Notify(Loc.L("Errors.Archive.Open"), ArchiveActions.Cause(ex), isError: true);
}
}
return await LoadArchiveAsync(root);
}
/// <summary>
/// Archive › Reset section with an archive open writes the defaults into that archive's archive.json, which the server
/// and the other PCs share: the user confirms it for that archive by name first.
/// </summary>
private bool ConfirmArchiveReset(Archive archive) => Shell.Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.L("Settings.Archive.ResetTitle", archive.Name),
Message = Loc.L("Settings.Archive.ResetMessage"),
SafeText = Loc.L("Settings.Storage.Keep"),
SafeToolTip = Loc.L("Tooltips.Settings.KeepArchiveSettings"),
ActionText = Loc.L("Settings.Archive.ResetAction"),
ActionToolTip = Loc.L("Tooltips.Settings.ResetArchiveConfirm"),
IsDestructive = true,
});
private void OnServerChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
LoadCertificates();
if (!DefaultServer.IsDirty) DefaultServer.Load(ServerAddress.Display(_s.ServerUrl));
}
private void UpdatePreview() => PreviewNames = NamingPreview.FirstNames(FolderTemplate.Text, FileTemplate.Text);
private void UpdateArchiveFree()
{
var path = _s.LastArchivePath;
ArchiveFreeText = ArchiveLocations.FreeSpace(path) is { } free ? Loc.L("Settings.Archive.Free", Formatting.Bytes(free)) : null;
}
/// <summary>The preset sizes in order, with <paramref name="current"/> among them when it is none of them.</summary>
private static IReadOnlyList<SettingsOption<int>> Sizes(int[] presets, int? current)
{
var values = current is { } size && !presets.Contains(size) ? presets.Append(size) : presets;
return [.. values.Order().Select(n => new SettingsOption<int>(n, n.ToString(CultureInfo.InvariantCulture)))];
}
private string? ValidateParallelism(string text) => ValidateInt(text, 1, Math.Max(1, LogicalCores * 2));
/// <summary>The kinds the priority queue lists, in the order of the Jobs screen's kinds the user starts most.</summary>
private static readonly JobKind[] PriorityKinds =
[
JobKind.Render, JobKind.Import, JobKind.Download, JobKind.UploadCommit, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse,
JobKind.DeepAnalyse, JobKind.Thumbs, JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move,
JobKind.Backup, JobKind.Cleanup, JobKind.EmptyTrash, JobKind.Convert, JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend,
JobKind.WorkspaceMove, JobKind.VideoCopy,
];
/// <summary>Stores <paramref name="level"/> for <paramref name="kind"/>, keeping only the levels that differ from the defaults.</summary>
private void SetJobPriority(JobKind kind, JobKindPriority level)
{
var queue = Shell.Services.PriorityQueue;
var levels = Enum.GetValues<JobKind>().ToDictionary(k => k, queue.LevelOf);
levels[kind] = level;
_s.JobPriorities = JobPriorityQueue.Changed(levels);
Save();
}
private static string? ValidateInt(string text, int min, int max) =>
int.TryParse(text.Trim(), NumberStyles.Integer, CultureInfo.CurrentCulture, out var n) && n >= min && n <= max
? null
: Loc.L("Errors.Number.Range", min.ToString("N0", Loc.Culture), max.ToString("N0", Loc.Culture));
private static string? ValidateNumber(string text, double min, double max) =>
double.TryParse(text.Trim(), NumberStyles.Float, CultureInfo.CurrentCulture, out var n) && double.IsFinite(n) && n >= min && n <= max
? null
: Loc.L("Errors.Number.DecimalRange", min.ToString("0.##", Loc.Culture), max.ToString("0.##", Loc.Culture));
/// <summary>Empty leaves the videos folder unset; a path must be absolute and outside the archive and the workspace.</summary>
private string? ValidateVideosFolder(string text) =>
text.Trim().Length == 0 ? null
: VideosFolders.Problem(text.Trim(), _s.LastArchivePath, Shell.Services.Workspace.Root) is { } problem ? VideoText.FolderReason(problem) : null;
/// <summary>Opens the videos folder in Explorer, creating it first (it is Chronos's own folder for copies).</summary>
private void OpenVideosFolder()
{
if (string.IsNullOrWhiteSpace(_s.VideosFolder)) return;
try
{
Directory.CreateDirectory(_s.VideosFolder);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
Log.Warning("settings", $"The videos folder could not be created: {ex.Message}");
Shell.ReportError(ex);
return;
}
ShellActions.Reveal(_s.VideosFolder);
}
private void Browse(EditableField field, string titleKey)
{
var folder = Shell.Services.Dialogs.PickFolder(Loc.L(titleKey), field.Value.Length > 0 ? field.Value : null);
if (folder is null) return;
field.Text = folder;
field.Commit();
}
/// <summary>Lists the encoders again (Re-detect).</summary>
public async Task DetectEncodersAsync()
{
IsDetecting = true;
try
{
var inventory = Shell.Services.Encoders;
var (adapter, rows) = await Task.Run(() => (inventory.Adapter(), inventory.Detect()));
Encoders.Clear();
foreach (var row in rows) Encoders.Add(new EncoderRowViewModel(row));
var hardware = rows.Count(r => r.Hardware);
AdapterText = string.Join(Loc.Separator, new[] { adapter, Loc.Plural("Settings.Rendering.EncoderCount", rows.Count(r => r.Source == EncoderSource.MediaFoundation)) }
.Where(s => !string.IsNullOrEmpty(s)));
Log.Info("settings", $"{rows.Count} encoder(s), {hardware} hardware");
}
catch (Exception ex) when (ex is System.Runtime.InteropServices.COMException or PlatformNotSupportedException or DllNotFoundException)
{
Log.Warning("settings", "Encoders could not be detected", ex);
}
finally
{
IsDetecting = false;
CommandManager.InvalidateRequerySuggested();
}
}
/// <summary>Encodes the synthetic test clip with every encoder in turn (Run self-test).</summary>
public async Task SelfTestAsync()
{
_isTesting = true;
_selfTest = new CancellationTokenSource();
try
{
foreach (var row in Encoders.Where(r => r.Row.CanSelfTest).ToList())
{
row.IsTesting = true;
try
{
row.Result = await Shell.Services.Encoders.SelfTestAsync(row.Row, _selfTest.Token);
}
finally
{
row.IsTesting = false;
}
}
}
finally
{
_isTesting = false;
_selfTest.Dispose();
_selfTest = null;
CommandManager.InvalidateRequerySuggested();
}
}
/// <summary>
/// Lists the decode tier of every format on this PC (Settings › Formats); with <paramref name="refresh"/> the codecs are
/// detected again first (after installing an extension), and the next jobs decode with them.
/// </summary>
public async Task DetectFormatsAsync(bool refresh)
{
IsDetectingFormats = true;
try
{
var inventory = Shell.Services.Formats;
var report = await Task.Run(() => inventory.Detect(refresh));
Formats.Clear();
foreach (var row in report.Formats) Formats.Add(new FormatRowViewModel(row));
MissingExtensions.Clear();
foreach (var extension in report.Missing)
MissingExtensions.Add(new MissingExtensionViewModel(extension, new RelayCommand(() => inventory.OpenStore(extension))));
OnPropertyChanged(nameof(HasMissingExtensions));
Log.Info("settings", $"{report.Formats.Count(f => f.Tier == Core.Imaging.DecodeTier.Native)} format(s) decode fully; missing extensions: {string.Join(", ", report.Missing.Select(m => m.ProductName))}");
}
catch (Exception ex) when (ex is System.Runtime.InteropServices.COMException or PlatformNotSupportedException or DllNotFoundException or EntryPointNotFoundException)
{
Log.Warning("settings", "Image codecs could not be detected", ex);
}
finally
{
IsDetectingFormats = false;
CommandManager.InvalidateRequerySuggested();
}
}
private async Task UpdateCacheUsageAsync()
{
var folder = CacheStore.Folder(Shell.Services.Environment, _s);
var (used, free) = await Task.Run(() => (CacheStore.Size(folder), ArchiveLocations.FreeSpace(folder)));
CacheUsageText = free is { } f
? Loc.L("Settings.Storage.Usage", Formatting.Bytes(used), Formatting.Bytes(f))
: Loc.L("Settings.Storage.Used", Formatting.Bytes(used));
}
private async Task ClearCacheAsync()
{
var folder = CacheStore.Folder(Shell.Services.Environment, _s);
var confirmed = Shell.Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.L("Settings.Storage.ClearTitle"),
Message = Loc.L("Settings.Storage.ClearMessage"),
Detail = Formatting.LeftToRight(AppEnvironment.Shown(folder)),
DetailToolTip = Loc.L("Tooltips.Settings.CacheFolder"),
SafeText = Loc.L("Settings.Storage.Keep"),
SafeToolTip = Loc.L("Tooltips.Settings.KeepCache"),
ActionText = Loc.L("Settings.Storage.Clear"),
ActionToolTip = Loc.L("Tooltips.Settings.ClearCache"),
IsDestructive = true,
});
if (!confirmed) return;
Shell.Services.Thumbnails?.Clear();
if (!CacheStore.IsOwned(folder))
{
Shell.Notify(Loc.L("Settings.Storage.NotOwned"), isError: true);
return;
}
var freed = await Task.Run(() => CacheStore.Clear(folder));
Shell.Notify(Loc.L("Settings.Storage.Cleared", Formatting.Bytes(freed)));
await UpdateCacheUsageAsync();
}
private async Task ExportDiagnosticsAsync()
{
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Settings.Advanced.DiagnosticsTitle"));
if (folder is null) return;
var selfTests = Encoders.Where(e => e.HasResult).Select(e => $"Self-test {e.Codec} {e.Row.DisplayName}: {e.ResultText}").ToList();
try
{
var path = await DiagnosticsBundle.CreateAsync(Shell.Services, folder, selfTests);
Shell.Notify(Loc.L("Settings.Advanced.DiagnosticsDone"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{
Shell.ReportError(ex);
}
}
private async Task BackupDatabaseAsync()
{
if (Shell.Services.Database is not { } db) return;
try
{
// As many copies stay as the backup schedules keep (Jobs › Scheduled › Index backup › Copies kept).
var path = await db.BackupAsync(Shell.Services.Environment.BackupDirectory, await DatabaseBackups.KeptAsync(db));
Shell.Notify(Loc.L("Settings.Advanced.BackupDone"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
}
catch (Exception ex) when (ex is DatabaseException or IOException or NotSupportedException)
{
Shell.ReportError(ex);
}
LoadBackups();
}
/// <summary>The copies in the backups folder, newest first; the newest is chosen.</summary>
private void LoadBackups()
{
var environment = Shell.Services.Environment;
IReadOnlyList<DatabaseBackup> found;
try
{
found = DatabaseBackups.List(environment.BackupDirectory, environment.DatabasePath);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("settings", "The backups folder could not be listed", ex);
found = [];
}
var selected = _selectedBackup?.Backup.Path;
Backups = [.. found.Select(b => new BackupOption(b))];
SelectedBackup = Backups.FirstOrDefault(b => b.Backup.Path == selected) ?? Backups.FirstOrDefault();
OnPropertyChanged(nameof(IsRestoreStaged));
}
/// <summary>
/// Restore (BRIEF §6.2, §12.8): a dry run reads what the chosen copy holds against the index now (shown as unreadable
/// when the index did not open, the case a restore exists for); after the user's destructive confirmation the copy is
/// staged beside the index for the next start, where the index as it is then is kept first and replaced before it is
/// opened (<see cref="DatabaseBackups.RestoreStagedAsync"/>; the staged copy is out of reach of the pruning of the
/// copies). Nothing replaces the index while Chronos runs.
/// </summary>
private async Task RestoreDatabaseAsync()
{
if (_selectedBackup is not { } option) return;
var backup = option.Backup;
var environment = Shell.Services.Environment;
_isRestoring = true;
CommandManager.InvalidateRequerySuggested();
try
{
DatabaseSummary restored;
try
{
restored = await Task.Run(() => DatabaseBackups.SummarizeBackupAsync(backup.Path, environment.DataDirectory));
}
catch (Exception ex) when (ex is InvalidDataException or IOException or UnauthorizedAccessException or DatabaseException)
{
Log.Warning("settings", $"The backup {backup.Path} cannot be restored", ex);
Shell.Notify(Loc.L("Errors.Backup.Unreadable"), isError: true);
return;
}
DatabaseSummary? current = null;
if (Shell.Services.Database is { } db)
{
try
{
current = await DatabaseBackups.SummarizeAsync(db);
}
catch (DatabaseException ex)
{
// A damaged index may open and still fail to count: it is shown as unreadable, and the restore remains possible.
Log.Warning("settings", "The current index could not be summarized", ex);
}
}
var currentLine = current is { } now
? Loc.L("Settings.Advanced.RestoreCurrent", Formatting.Count(now.Sequences), Formatting.Count(now.Photos))
: Loc.L("Settings.Advanced.RestoreUnreadable");
var confirmed = Shell.Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.L("Settings.Advanced.RestoreTitle", option.Label),
Message = Loc.L("Settings.Advanced.RestoreMessage"),
Detail = string.Join(Environment.NewLine,
Loc.L("Settings.Advanced.RestoreBackup", Formatting.Count(restored.Sequences), Formatting.Count(restored.Photos)), currentLine),
IsDetailMonospaced = false,
DetailToolTip = Formatting.LeftToRight(backup.Path),
SafeText = Loc.L("Settings.Storage.Keep"),
SafeToolTip = Loc.L("Tooltips.Settings.KeepIndex"),
ActionText = Loc.L("Settings.Advanced.RestoreAction"),
ActionToolTip = Loc.L("Tooltips.Settings.RestoreConfirm"),
IsDestructive = true,
});
if (!confirmed) return;
try
{
await Task.Run(() => DatabaseBackups.StageRestoreAsync(backup.Path, environment.DatabasePath));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Error("settings", "The restore was not staged", ex);
Shell.ReportError(ex);
return;
}
Log.Info("settings", $"Restore of {backup.Path} staged ({restored.Sequences} sequences, {restored.Photos} photos)");
Shell.Notify(Loc.L("Settings.Advanced.RestoreStaged"), Loc.L("Settings.Advanced.RestartToRestore"));
}
finally
{
_isRestoring = false;
LoadBackups();
CommandManager.InvalidateRequerySuggested();
}
}
private void CancelRestore()
{
try
{
DatabaseBackups.CancelStagedRestore(Shell.Services.Environment.DatabasePath);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Shell.ReportError(ex);
}
OnPropertyChanged(nameof(IsRestoreStaged));
CommandManager.InvalidateRequerySuggested();
}
private void ResetSection()
{
var defaults = new AppSettings();
switch (_page)
{
case SettingsPage.General:
_s.AnonymousUsageCounts = defaults.AnonymousUsageCounts;
_s.OsNotifications = defaults.OsNotifications;
Startup.SetEnabled(false);
ApplyTheme(defaults.Theme);
_s.Language = null;
UiLanguage.Apply(null);
break;
case SettingsPage.Archive:
_ = ResetArchiveAsync(defaults);
return;
case SettingsPage.Import:
_s.ImportSessionGapMinutes = defaults.ImportSessionGapMinutes;
_s.ImportMinimumFrames = defaults.ImportMinimumFrames;
_s.ImportSubfolders = defaults.ImportSubfolders;
_s.ImportVerify = defaults.ImportVerify;
_s.ImportDuplicates = defaults.ImportDuplicates;
_s.ImportAfter = defaults.ImportAfter;
_s.ImportEject = defaults.ImportEject;
LoadImportFields();
break;
case SettingsPage.Analysis:
_s.AnalysisLongEdge = defaults.AnalysisLongEdge;
_s.NightBrightnessPercent = defaults.NightBrightnessPercent;
_s.StarFieldDensity = defaults.StarFieldDensity;
_s.DeepAnalysisAfterImport = defaults.DeepAnalysisAfterImport;
_s.DeepAnalysisAfterScan = defaults.DeepAnalysisAfterScan;
LoadAnalysisFields();
break;
case SettingsPage.Rendering:
_s.Quality = defaults.Quality;
_s.MemoryBudgetGb = null;
_s.Parallelism = null;
_s.BackgroundPriority = defaults.BackgroundPriority;
_s.HardwareEncoding = defaults.HardwareEncoding;
_s.PriorityQueue = defaults.PriorityQueue;
_s.JobPriorities = [];
foreach (var row in JobPriorities) row.Refresh();
Parallelism.Load(ParallelismAuto.ToString(CultureInfo.CurrentCulture));
_interfacePriority?.Update();
break;
case SettingsPage.Storage:
_s.CacheFolder = null;
_s.ThumbnailMemoryItems = defaults.ThumbnailMemoryItems;
_s.CacheLimitGb = defaults.CacheLimitGb;
CacheFolder.Load(AppEnvironment.Shown(CacheStore.Folder(Shell.Services.Environment, _s)));
ThumbnailMemory.Load(_s.ThumbnailMemoryItems.ToString(CultureInfo.CurrentCulture));
CacheLimit.Load(_s.CacheLimitGb.ToString(CultureInfo.CurrentCulture));
if (Shell.Services.Thumbnails is { } thumbs) thumbs.Capacity = _s.ThumbnailMemoryItems;
break;
case SettingsPage.Server:
_s.RenderNodeOptIn = defaults.RenderNodeOptIn;
break;
case SettingsPage.Updates:
_s.CheckForUpdates = defaults.CheckForUpdates;
break;
case SettingsPage.Workspace:
WorkspaceRows.Reset();
break;
case SettingsPage.Advanced:
Logs.Reset();
break;
}
Save();
OnAllPropertiesChanged();
Shell.Server.Refresh();
}
/// <summary>
/// Archive › Reset section. The rows are the open archive's own: resetting them changes it for everyone sharing it, so
/// only when confirmed. The archive at a folder just chosen is opened first, so the question names it and the reset
/// reaches it instead of being undone when it opens.
/// </summary>
private async Task ResetArchiveAsync(AppSettings defaults)
{
var retarget = _retarget;
var open = await ArchiveAtFolderAsync(retarget);
if (open is not null && !ConfirmArchiveReset(open)) return;
_s.FolderTemplate = defaults.FolderTemplate;
_s.FileTemplate = defaults.FileTemplate;
_s.ProxyLongEdge = defaults.ProxyLongEdge;
_s.ThumbnailLongEdge = defaults.ThumbnailLongEdge;
_s.VideosFolder = defaults.VideosFolder;
FolderTemplate.Load(_s.FolderTemplate);
FileTemplate.Load(_s.FileTemplate);
VideosFolder.Load(_s.VideosFolder ?? string.Empty);
UpdatePreview();
Save();
OnAllPropertiesChanged();
if (open is not null) await PushArchiveSettingsAsync(retarget);
// Another folder was chosen while this one's archive opened: the rows show what that folder's archive holds again.
if (retarget != _retarget) await LoadArchiveAsync();
}
private void LoadImportFields()
{
SessionGap.Load(_s.ImportSessionGapMinutes.ToString(CultureInfo.CurrentCulture));
MinimumFrames.Load(_s.ImportMinimumFrames.ToString(CultureInfo.CurrentCulture));
}
private void LoadAnalysisFields()
{
NightBrightness.Load(_s.NightBrightnessPercent.ToString("0.##", CultureInfo.CurrentCulture));
StarDensity.Load(_s.StarFieldDensity.ToString("0.##", CultureInfo.CurrentCulture));
}
/// <summary>
/// Advanced › Reset: every preference of this PC back to its default after a destructive confirmation. What identifies
/// this PC's data and session stays: the archive folder, the server, its session and trusted certificates, the window
/// and the first-run choice. The open archive's own settings (archive.json, shared with the server and other PCs) are
/// not touched: the Archive rows show them again (with no archive open, they show the reset defaults of new archives).
/// </summary>
private void ResetAll()
{
var confirmed = Shell.Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.L("Settings.Advanced.ResetTitle"),
Message = Loc.L("Settings.Advanced.ResetMessage"),
SafeText = Loc.L("Settings.Storage.Keep"),
SafeToolTip = Loc.L("Tooltips.Settings.KeepSettings"),
ActionText = Loc.L("Settings.Advanced.ResetAction"),
ActionToolTip = Loc.L("Tooltips.Settings.ResetConfirm"),
IsDestructive = true,
});
if (!confirmed) return;
// The workspace holds this PC's work: its folder stays where it is (moving it is its own operation).
var defaults = _s.ResetKeepingState();
// Start with Windows lives in the registry, not in the settings file: its default is off.
Startup.SetEnabled(false);
ApplyAll(defaults);
_ = LoadArchiveAsync();
Log.Info("settings", "Every setting reset to its default");
Shell.Notify(Loc.L("Settings.Advanced.ResetDone"));
}
/// <summary>Takes every value of <paramref name="source"/> and shows it everywhere (reset, import).</summary>
private void ApplyAll(AppSettings source)
{
foreach (var property in typeof(AppSettings).GetProperties().Where(p => p.CanRead && p.CanWrite))
property.SetValue(_s, property.GetValue(source));
Save();
ThemeManager.Apply(_s.Theme);
UiLanguage.Apply(_s.Language);
ArchiveRoot.Load(_s.LastArchivePath ?? string.Empty);
FolderTemplate.Load(_s.FolderTemplate);
FileTemplate.Load(_s.FileTemplate);
VideosFolder.Load(_s.VideosFolder ?? string.Empty);
LoadImportFields();
LoadAnalysisFields();
Parallelism.Load(EffectiveParallelism.ToString(CultureInfo.CurrentCulture));
CacheFolder.Load(AppEnvironment.Shown(CacheStore.Folder(Shell.Services.Environment, _s)));
ThumbnailMemory.Load(_s.ThumbnailMemoryItems.ToString(CultureInfo.CurrentCulture));
CacheLimit.Load(_s.CacheLimitGb.ToString(CultureInfo.CurrentCulture));
if (Shell.Services.Thumbnails is { } thumbs) thumbs.Capacity = _s.ThumbnailMemoryItems;
DefaultServer.Load(ServerAddress.Display(_s.ServerUrl));
_interfacePriority?.Update();
foreach (var row in JobPriorities) row.Refresh();
Logs.Refresh();
WorkspaceRows.Refresh();
UpdatePreview();
LoadCertificates();
OnAllPropertiesChanged();
Shell.Server.Refresh();
}
private async Task ExportSettingsAsync()
{
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Settings.Export.Title"));
if (folder is null) return;
// Secrets and machine-bound values stay on this PC.
var copy = _s.ForExport();
var path = Path.Combine(folder, $"Chronos settings {DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}.json");
await Task.Run(() => AtomicFile.WriteAllText(path, copy.ToJson()));
Shell.Notify(Loc.L("Settings.Export.Done"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
}
private async Task ImportSettingsAsync()
{
var file = Shell.Services.Dialogs.PickJsonFile(Loc.L("Settings.Import.Title"));
if (file is null) return;
AppSettings? imported;
try
{
imported = AppSettings.Parse(await File.ReadAllTextAsync(file));
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
{
Log.Warning("settings", $"Settings file {file} not imported", ex);
imported = null;
}
if (imported is null)
{
Shell.Notify(Loc.L("Errors.Settings.Import"), isError: true);
return;
}
// Everything but the session, the window and its rail, the sequence edited last (another PC's ids mean nothing here),
// the first-run flag and the workspace, which is this PC's (its folder, the projects opened last and when).
ApplyAll(_s.KeepLocalIn(imported));
// Settings of a PC never rewrite the shared archive.json: the imported templates and sizes are the defaults of new
// archives, and the rows show the own settings of the archive at the (possibly imported) archive folder.
_retarget = RetargetArchiveAsync();
Shell.Notify(Loc.L("Settings.Import.Done"));
}
private void LoadCertificates()
{
Certificates.Clear();
foreach (var certificate in _s.TrustedCertificates.OrderByDescending(c => c.TrustedAt))
{
// The same question as on the Server screen; the session on that certificate is closed first.
Certificates.Add(new TrustedCertificateRow(certificate, new RelayCommand(() =>
{
if (Shell.Services.Server.ConfirmForget(certificate.Fingerprint, Shell.Services.Dialogs)) LoadCertificates();
})));
}
OnPropertyChanged(nameof(HasCertificates));
}
private void OnCultureChanged(object? sender, EventArgs e)
{
foreach (var page in AllPages) page.Refresh();
foreach (var row in Encoders) row.Refresh();
foreach (var row in JobPriorities) row.Refresh();
foreach (var row in Formats) row.Refresh();
foreach (var row in MissingExtensions) row.Refresh();
Logs.Refresh();
WorkspaceRows.Refresh();
ArchiveRoot.Refresh();
FolderTemplate.Refresh();
FileTemplate.Refresh();
VideosFolder.Refresh();
SessionGap.Refresh();
MinimumFrames.Refresh();
// Decimals are written in the language's own way ("6.25", "6,25").
if (!NightBrightness.IsDirty && !StarDensity.IsDirty) LoadAnalysisFields();
NightBrightness.Refresh();
StarDensity.Refresh();
Parallelism.Refresh();
CacheFolder.Refresh();
ThumbnailMemory.Refresh();
CacheLimit.Refresh();
DefaultServer.Refresh();
UpdateArchiveFree();
UpdatePreview();
LoadCertificates();
if (_backups.Count > 0) LoadBackups();
}
}