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.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.Ui.Mvvm; using Chronos.Ui.Theming; namespace Chronos.App.Sections; /// /// 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 (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 restores the index from a daily backup at the next start; About, the last page, shows this copy /// (, whose update notice Updates shows). /// public sealed class SettingsViewModel : SectionViewModel { private readonly AppSettings _s; private SettingsPage _page = SettingsPage.General; private string _searchText = string.Empty; private IReadOnlyList _visiblePages; private IReadOnlyList _previewNames = []; private string? _archiveFreeText; private string? _cacheUsageText; private string? _adapterText; private bool _isDetecting; private bool _isTesting; private CancellationTokenSource? _selfTest; private Archive? _archive; /// /// The open of the archive at the folder chosen last (), with the archive it found /// there: edits of the Archive rows made meanwhile wait for it (). /// private Task _retarget = Task.FromResult(null); /// Drops a read of the open archive's settings that may have missed an edit being written meanwhile. private readonly ArchiveReadGate _archiveReads = new(); private bool _isDetectingFormats; private IReadOnlyList _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.Polling"]), 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.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.Diagnostics", "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(); _ = UpdateArchiveAsync(a => a with { Templates = a.Templates with { Folder = v } }); }, () => Loc.L("Tooltips.Settings.FolderTemplate")); FileTemplate = new EditableField(_s.FileTemplate, v => NamingPreview.Validate(v, isFolder: false), v => { _s.FileTemplate = v; Save(); _ = UpdateArchiveAsync(a => a with { Templates = a.Templates with { File = v } }); }, () => Loc.L("Tooltips.Settings.FileTemplate")); 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))]; // ---- Storage ---- CacheFolder = new EditableField(CacheStore.Folder(shell.Services.Environment, _s), v => ArchiveLocations.Validate(v), v => { var full = Path.GetFullPath(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")); 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(DataFolder)); OpenLogsCommand = new RelayCommand(() => ShellActions.Reveal(LogsFolder)); 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 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.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); /// Filters the section list. 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 VisiblePages { get => _visiblePages; private set => Set(ref _visiblePages, value); } // ---------------- General ---------------- public IReadOnlyList 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); } } /// Where "Start with Windows" is kept (the Run key); screenshots, tests and portable copies keep it in memory. internal IStartWithWindows Startup { get; set; } /// The latest archive folder change: done once the rows show what the folder holds (tests wait for it). internal Task ArchiveRetarget => _retarget; /// The read of the open archive's settings when Settings was last shown: done once the rows show them (tests wait for it). internal Task ArchiveReload { get; private set; } = Task.CompletedTask; /// A portable copy leaves nothing in the registry (BRIEF §6.2): it offers no Startup row. public bool ShowsStartup => !Shell.Services.Environment.IsPortable; /// Chronos starts minimised when the user signs in to Windows. public bool StartWithWindows { get => Startup.IsEnabled; set { if (Startup.IsEnabled == value) return; Startup.SetEnabled(value); OnPropertyChanged(); } } /// Toasts also appear as Windows notifications while the window is minimised or in the background. public bool OsNotifications { get => _s.OsNotifications; set { if (_s.OsNotifications == value) return; _s.OsNotifications = value; Save(); OnPropertyChanged(); } } /// The usage counts consent belongs to monetization (BRIEF §21): only builds with it enabled offer it. 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; } /// "1.8 TB free". public string? ArchiveFreeText { get => _archiveFreeText; private set => Set(ref _archiveFreeText, value); } /// The first three names the templates produce (live while typing). public IReadOnlyList PreviewNames { get => _previewNames; private set => Set(ref _previewNames, value); } /// /// 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. /// public IReadOnlyList> 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")), ]; /// The open archive's proxy size (archive.json), and the one of new archives. public SettingsOption 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 } }); } } /// 240, 320 (default), 480 or 640; another size of the archive (160 to 1024 are valid) is listed with its number. public IReadOnlyList> ThumbnailSizes => Sizes([240, 320, 480, 640], _s.ThumbnailLongEdge); /// The open archive's thumbnail size (archive.json), and the one of new archives. public SettingsOption 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 } }); } } public IReadOnlyList> ScanIntervals => [.. new[] { 5, 10, 15, 30, 60 }.Select(m => new SettingsOption(m, Formatting.Duration(TimeSpan.FromMinutes(m))))]; /// How often this PC rescans the open archive for changes made elsewhere (BRIEF §7: polling). public SettingsOption SelectedScanInterval { get => ScanIntervals.FirstOrDefault(p => p.Value == _s.ScanIntervalMinutes) ?? ScanIntervals[1]; set { if (value is null || value.Value == _s.ScanIntervalMinutes) return; _s.ScanIntervalMinutes = value.Value; // Saving applies it: the running rescan timer takes the new period. Save(); OnPropertyChanged(); } } // ---------------- 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 ---------------- /// BRIEF §10.2: half native, capped at 2048 by default. public IReadOnlyList> AnalysisWidths => [.. new[] { 1024, 2048, 3072, 4096 }.Select(n => new SettingsOption(n, n.ToString(CultureInfo.InvariantCulture)))]; public SettingsOption 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> Qualities => [.. Enum.GetValues().Select(q => new SettingsOption(q, Loc.L("Settings.Rendering.Quality." + q)))]; public SettingsOption 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(); } } /// Installed memory in GB (rounded). public int InstalledGb { get; } public int MemoryMinimum => 2; public int MemoryMaximum => Math.Max(MemoryMinimum, InstalledGb - 2); /// Auto: a quarter of installed memory. 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; /// Auto: half the logical cores (photos the running job processes at once, owner review 1). 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; } /// /// 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. /// public bool PriorityQueue { get => _s.PriorityQueue; set => SetSetting(_s.PriorityQueue, value, v => _s.PriorityQueue = v); } /// The kinds of job this PC runs with their levels in the priority queue, the ones the user waits for first. public IReadOnlyList 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 Encoders { get; } = []; /// "NVIDIA GeForce RTX 4070 · 3 encoders". public string? AdapterText { get => _adapterText; private set { if (Set(ref _adapterText, value)) OnPropertyChanged(nameof(AdapterToolTip)); } } /// The adapter and its encoders whole (the row may cut them at the minimum width), then what they are. 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 Formats { get; } = []; /// The one-line notices of BRIEF §8.1: each missing codec extension with its Install button. public ObservableCollection 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; } /// "1.4 GB used · 612 GB free". public string? CacheUsageText { get => _cacheUsageText; private set => Set(ref _cacheUsageText, value); } // ---------------- 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 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 => Shell.Services.Environment.DataDirectory; public string LogsFolder => Shell.Services.Environment.LogDirectory; public string PortableText => Loc.L(Shell.Services.Environment.IsPortable ? "Settings.Advanced.PortableOn" : "Settings.Advanced.PortableOff"); public ICommand OpenDataFolderCommand { get; } public ICommand OpenLogsCommand { get; } public ICommand ExportDiagnosticsCommand { get; } public ICommand BackupDatabaseCommand { get; } /// The daily copies of the index, newest first (Restore). public IReadOnlyList 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(); } } /// A restore waits for the next start of Chronos. public bool IsRestoreStaged => DatabaseBackups.HasStagedRestore(Shell.Services.Environment.DatabasePath); /// Also while the index cannot be opened: that is the case a restore exists for (BRIEF §6.2). 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; } /// /// Advanced holds no setting with a default (paths and actions only), Formats only shows this PC and About only this /// copy: they have no Reset section. /// public bool CanResetSection => _page is not (SettingsPage.Advanced or SettingsPage.Formats or SettingsPage.About); public ICommand ExportSettingsCommand { get; } public ICommand ImportSettingsCommand { get; } /// /// 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. /// 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; 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(DataFolder), 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(DataFolder)); 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; _selfTest?.Cancel(); _interfacePriority?.Dispose(); base.Dispose(); } /// Other screens change the archive and the server in use: Settings shows them when it opens. 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(); } /// Stores a switch of Settings and tells the view (the caller's property). private void SetSetting(bool current, bool value, Action 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)); } /// /// 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. /// 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(); } /// /// 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). /// private Task LoadArchiveAsync() => LoadArchiveAsync(_s.LastArchivePath); /// /// for the archive folder , which a folder change may have /// replaced meanwhile: the rows are then left to the folder chosen since, and the archive registered at /// is still returned, so edits made for that folder reach it. /// private async Task 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; } /// Whether is still this PC's archive folder (the one the rows show). private bool IsArchiveFolder(string? root) => string.Equals(root, _s.LastArchivePath, StringComparison.Ordinal); /// /// The archive an Archive row edits, as the folder was when the row was edited (, 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. /// private async Task ArchiveAtFolderAsync(Task 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; } /// /// 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. is the folder change the edit was /// made after, the latest one by default. /// private async Task UpdateArchiveAsync(Func edit, Task? retarget = null) { retarget ??= _retarget; var waited = !retarget.IsCompleted; if (await ArchiveAtFolderAsync(retarget) is not { } archive || Shell.Services.Archives is not { } archives) return; bool reload; _archiveReads.BeginWrite(); try { var updated = 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(); } /// /// Every archive row into the archive found after : Archive › Reset section, after the user /// confirmed it for that archive. /// private Task PushArchiveSettingsAsync(Task 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); /// /// 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. /// private async Task 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); } /// /// 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. /// 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; } /// The preset sizes in order, with among them when it is none of them. private static IReadOnlyList> Sizes(int[] presets, int? current) { var values = current is { } size && !presets.Contains(size) ? presets.Append(size) : presets; return [.. values.Order().Select(n => new SettingsOption(n, n.ToString(CultureInfo.InvariantCulture)))]; } private string? ValidateParallelism(string text) => ValidateInt(text, 1, Math.Max(1, LogicalCores * 2)); /// The kinds the priority queue lists, in the order of the Jobs screen's kinds the user starts most. 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, ]; /// Stores for , keeping only the levels that differ from the defaults. private void SetJobPriority(JobKind kind, JobKindPriority level) { var queue = Shell.Services.PriorityQueue; var levels = Enum.GetValues().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)); 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(); } /// Lists the encoders again (Re-detect). 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(); } } /// Encodes the synthetic test clip with every encoder in turn (Run self-test). 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(); } } /// /// Lists the decode tier of every format on this PC (Settings › Formats); with the codecs are /// detected again first (after installing an extension), and the next jobs decode with them. /// 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(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 { var path = await db.BackupAsync(Shell.Services.Environment.BackupDirectory, DatabaseBackups.Keep); 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(); } /// The copies in the backups folder, newest first; the newest is chosen. private void LoadBackups() { var environment = Shell.Services.Environment; IReadOnlyList 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)); } /// /// 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 (; the staged copy is out of reach of the pruning to three /// copies). Nothing replaces the index while Chronos runs. /// 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(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; } Save(); OnAllPropertiesChanged(); Shell.Server.Refresh(); } /// /// 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. /// 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.ScanIntervalMinutes = defaults.ScanIntervalMinutes; FolderTemplate.Load(_s.FolderTemplate); FileTemplate.Load(_s.FileTemplate); 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)); } /// /// 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). /// 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; var defaults = new AppSettings { LastArchivePath = _s.LastArchivePath, ServerUrl = _s.ServerUrl, ServerUsername = _s.ServerUsername, ProtectedToken = _s.ProtectedToken, TrustedCertificates = _s.TrustedCertificates, RecentServers = _s.RecentServers, Window = _s.Window, RailCollapsed = _s.RailCollapsed, LastEditedSequence = _s.LastEditedSequence, FirstRunCompleted = _s.FirstRunCompleted, JobsClearedAt = _s.JobsClearedAt, }; // 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")); } /// Takes every value of and shows it everywhere (reset, import). 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); LoadImportFields(); LoadAnalysisFields(); Parallelism.Load(EffectiveParallelism.ToString(CultureInfo.CurrentCulture)); CacheFolder.Load(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(); 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; var copy = _s.Clone(); // Secrets and machine-bound values stay on this PC. copy.ProtectedToken = null; copy.Window = null; 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) // and the first-run flag. imported.ProtectedToken = _s.ProtectedToken; imported.ServerUrl = _s.ServerUrl; imported.Window = _s.Window; imported.RailCollapsed = _s.RailCollapsed; imported.LastEditedSequence = _s.LastEditedSequence; imported.FirstRunCompleted = _s.FirstRunCompleted; ApplyAll(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(); ArchiveRoot.Refresh(); FolderTemplate.Refresh(); FileTemplate.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(); } }