merge: desktop settings fixes (V-4, V-6, V-7, V-30, V-31, V-32, V-34, ENG-08)

Merge branch fix2/desktop-settings into the verification branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 16:54:07 +00:00
commit 78190476be
34 files changed
+1132 -171

No files matched your search

+4
View File
@@ -45,6 +45,10 @@ public partial class App : Application
// Capture runs in CI: mirror the log to stderr so failures are visible in the job output.
Log.SetSink(capture ? new TeeLogSink(_log, new StderrLogSink()) : _log);
Log.Info("app", $"Titano {AppServices.VersionText} starting; data at {Environment.DataDirectory}");
// Settings tells the user once the window is up.
if (Environment.PortableSyncRoot is { } portableIn) Log.Warning("app", $"This portable copy runs in the OneDrive folder {portableIn}: its data is kept outside it");
if (Environment.EarlierPortableData is { } earlier) Log.Warning("app", $"The data this portable copy kept in {earlier} before is left there and no longer used");
if (Environment.SyncedFolder is { } synced) Log.Warning("app", $"The data folder lies in the OneDrive folder {synced}: synchronisation may damage the index");
var projectFile = capture ? null : ProjectFileArgument(e.Args);
if (!capture)
+29 -11
View File
@@ -1,18 +1,26 @@
using System.IO;
using Titano.Core.Windows.Shell;
namespace Titano.App.Infrastructure;
/// <summary>
/// Where the client keeps its data (BRIEF §6.2): <c>%LOCALAPPDATA%\Titano</c>, or <c>.\data</c> next to the
/// executable when <c>portable.txt</c> exists. Never inside Documents/OneDrive (SQLite corrupts in synced folders).
/// Where the client keeps its data (BRIEF §6.2, <see cref="AppPaths"/>): <c>%LOCALAPPDATA%\Titano</c>, or <c>.\data</c>
/// next to the executable when <c>portable.txt</c> exists. Never inside a folder OneDrive synchronises (SQLite corrupts
/// there): a portable copy in one keeps its data in <c>%LOCALAPPDATA%\Titano</c>, and Settings tells the user so
/// (<see cref="PortableSyncRoot"/>, <see cref="EarlierPortableData"/>). When that folder itself lies in one, nowhere
/// is safe: Titano starts all the same and Settings warns (<see cref="SyncedFolder"/>).
/// </summary>
public sealed class AppEnvironment
{
private AppEnvironment(string dataDirectory, bool portable, bool isCapture)
private AppEnvironment(string dataDirectory, bool portable, bool isCapture, string? syncedFolder = null, string? portableSyncRoot = null,
string? earlierPortableData = null)
{
DataDirectory = dataDirectory;
IsPortable = portable;
IsCapture = isCapture;
SyncedFolder = syncedFolder;
PortableSyncRoot = portableSyncRoot;
EarlierPortableData = earlierPortableData;
Directory.CreateDirectory(DataDirectory);
Directory.CreateDirectory(LogDirectory);
Directory.CreateDirectory(CacheDirectory);
@@ -24,19 +32,29 @@ public sealed class AppEnvironment
/// <summary>A throw-away environment for <c>--capture</c>: nothing of the user's data is read or written.</summary>
public bool IsCapture { get; }
/// <summary>The OneDrive folder <see cref="DataDirectory"/> itself lies in, where the index may be damaged; null when it is safe.</summary>
public string? SyncedFolder { get; }
/// <summary>The OneDrive folder this portable copy runs from; its data is in <c>%LOCALAPPDATA%\Titano</c> instead of <c>.\data</c>. Null otherwise.</summary>
public string? PortableSyncRoot { get; }
/// <summary>The <c>.\data</c> folder this portable copy used before it ran from OneDrive, left as it was; null when there is none.</summary>
public string? EarlierPortableData { get; }
public string LogDirectory => Path.Combine(DataDirectory, "logs");
public string CacheDirectory => Path.Combine(DataDirectory, "cache");
public string BackupDirectory => Path.Combine(DataDirectory, "backups");
public string DatabasePath => Path.Combine(DataDirectory, "titano.db");
public string SettingsPath => Path.Combine(DataDirectory, "settings.json");
public string DatabasePath => Path.Combine(DataDirectory, AppPaths.DatabaseFileName);
public string SettingsPath => Path.Combine(DataDirectory, AppPaths.SettingsFileName);
public static AppEnvironment Detect()
/// <summary>The environment of this process: its executable's folder and the user's OneDrive folders decide.</summary>
public static AppEnvironment Detect() => From(AppPaths.Resolve());
/// <summary>The environment at <paramref name="paths"/> (its folders are created).</summary>
public static AppEnvironment From(AppPaths paths)
{
var exeDir = AppContext.BaseDirectory;
if (File.Exists(Path.Combine(exeDir, "portable.txt")))
return new AppEnvironment(Path.Combine(exeDir, "data"), portable: true, isCapture: false);
var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
return new AppEnvironment(Path.Combine(local, "Titano"), portable: false, isCapture: false);
ArgumentNullException.ThrowIfNull(paths);
return new(paths.DataRoot, paths.IsPortable, isCapture: false, paths.SyncedFolder, paths.PortableSyncRoot, paths.EarlierPortableData);
}
/// <summary>A fresh temporary data folder for screenshots and smoke tests; delete it with <see cref="DeleteCaptureData"/>.</summary>
+75 -20
View File
@@ -3,6 +3,7 @@ using System.IO;
using System.Net.Http;
using System.Reflection;
using Titano.App.About;
using Titano.App.Archiving;
using Titano.App.Import;
using Titano.App.Jobs;
using Titano.App.Library;
@@ -32,13 +33,13 @@ namespace Titano.App.Infrastructure;
/// managed encoders), the one <see cref="JobEngine"/> of this PC with the handlers of <see cref="CreateJobHandlers"/>,
/// thumbnails, the server session, the render node, the encoder and format inventories, the update check and the sync
/// with the signed-in server (<see cref="SyncHost"/>). Started after the window shows, stopped when the app exits. The
/// last archive is reopened at start and rescanned every <see cref="ScanInterval"/> (Settings › Archive; BRIEF §7:
/// polling, no file-system watchers). Jobs follow Settings › Rendering and Analysis from the next one on (memory
/// budget, quality profile, analysis parameters through <see cref="ProcessingTuning"/>; parallelism as the engine's
/// workers). The render node runs while the user offers this PC (<see cref="AppSettings.RenderNodeOptIn"/>) and a
/// server session is open (never in capture mode). Renders and the render node use hardware encoders as Settings ›
/// Rendering allows (<see cref="AllowsHardware(HardwarePreference, string)"/>). Disposal never needs the UI thread,
/// which waits for it.
/// archive at Settings › Archive's folder is reopened at start and rescanned every <see cref="ScanInterval"/>, as is one
/// chosen later (BRIEF §7: polling, no file-system watchers). Jobs follow Settings › Rendering and Analysis from the
/// next one on (memory budget, quality profile, analysis parameters through <see cref="ProcessingTuning"/>; parallelism
/// as the engine's workers). The render node runs while the user offers this PC (<see cref="AppSettings.RenderNodeOptIn"/>)
/// and a server session is open (never in capture mode). Renders and the render node use hardware encoders as
/// Settings › Rendering allows (<see cref="AllowsHardware(HardwarePreference, string)"/>). Disposal never needs the UI
/// thread, which waits for it.
/// </summary>
public sealed class AppServices : IAsyncDisposable
{
@@ -228,7 +229,7 @@ public sealed class AppServices : IAsyncDisposable
Devices.Start();
var database = Database;
_backups = Task.Run(() => DatabaseBackups.RunDailyAsync(database, Environment.BackupDirectory, null, _stopping.Token));
if (Settings.LastArchivePath is { Length: > 0 } root) _polling = PollAsync(root, _stopping.Token);
_polling = PollAsync(_stopping.Token);
}
/// <summary>Uses an already open index (capture, tests) instead of opening one; sample data keeps the engine stopped.</summary>
@@ -258,35 +259,89 @@ public sealed class AppServices : IAsyncDisposable
if (Database is not null) await Database.DisposeAsync().ConfigureAwait(false);
}
/// <summary>Reopens the last archive (relinking a moved one, finishing interrupted renames) and rescans it periodically,
/// off the UI thread (disposal waits for it there).</summary>
private async Task PollAsync(string root, CancellationToken ct)
/// <summary>The period of the rescans while they run (Settings › Archive › Rescan every); null before the index opens.</summary>
internal TimeSpan? PollingPeriod => _pollTimer?.Period;
/// <summary>
/// One rescan of the polling, off the UI thread: the archive the Import and Archive screens work on
/// (<see cref="CurrentArchive"/>, the one at Settings › Archive's folder) first takes the settings another process
/// sharing it wrote into its archive.json (also on a read-only share), then gets an incremental scan while it is
/// online. Returns that archive; null when the index holds none.
/// </summary>
internal Task<Archive?> RescanAsync(CancellationToken ct = default) => Task.Run(async () =>
{
if (Database is not { } db || Archives is not { } archives) return null;
var archive = CurrentArchive.Pick(await db.Archives.ListAsync(ct).ConfigureAwait(false), Settings.LastArchivePath);
if (archive is null) return null;
var availability = ArchiveService.GetAvailability(archive);
if (availability != ArchiveAvailability.Offline) await archives.RefreshSettingsAsync(archive.Id, ct).ConfigureAwait(false);
if (availability == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct).ConfigureAwait(false);
return archive;
}, ct);
/// <summary>
/// Rescans the archive now and every <see cref="ScanInterval"/> (<see cref="RescanAsync"/>) until the app exits, which
/// waits for it on the UI thread. Each rescan follows the archive folder: one chosen on the first run, in Settings or
/// by a relink is rescanned from the next tick on, the one before no longer. The archive at the folder of the start is
/// first reopened (a moved one relinked, interrupted renames finished), at each tick until its archive.json is there
/// (an unplugged drive), unless the folder changed meanwhile: whatever changed it opened the new archive.
/// </summary>
private async Task PollAsync(CancellationToken ct)
{
var reopen = Settings.LastArchivePath is { Length: > 0 } start ? start : null;
// Settings › Archive changes the period of this timer (ApplyJobSettings).
using var timer = _pollTimer = new PeriodicTimer(ScanInterval);
try
{
if (Archives is null) return;
var archive = await Task.Run(() => Archives.OpenAsync(root, ct), ct).ConfigureAwait(false);
// Settings › Archive changes the period of this timer (ApplyJobSettings).
using var timer = _pollTimer = new PeriodicTimer(ScanInterval);
do
{
if (ArchiveService.GetAvailability(archive) == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct).ConfigureAwait(false);
if (reopen is not null
&& (!string.Equals(reopen, Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase) || await ReopenAsync(reopen, ct).ConfigureAwait(false)))
reopen = null;
try
{
await RescanAsync(ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or ArgumentException)
{
// The next tick tries again (a share that dropped, an archive removed from the index meanwhile).
Log.Warning("archive", "The archive could not be rescanned", ex);
}
}
while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false));
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException)
{
Log.Warning("archive", $"The archive at {root} could not be opened", ex);
}
finally
{
_pollTimer = null;
}
}
/// <summary>
/// Registers the archive at <paramref name="root"/> again as at open; false while its archive.json is not there. A
/// damaged or newer one is not tried again: the archive the index holds at the folder is still rescanned.
/// </summary>
private async Task<bool> ReopenAsync(string root, CancellationToken ct)
{
if (Archives is not { } archives) return true;
try
{
return await Task.Run(async () =>
{
if (!File.Exists(new ArchivePaths(root).ManifestPath)) return false;
await archives.OpenAsync(root, ct).ConfigureAwait(false);
return true;
}, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or NewerFormatException)
{
Log.Warning("archive", $"The archive at {root} could not be opened", ex);
return true;
}
}
/// <summary>
/// A restore staged in Settings › Advanced replaces the index file before the index is opened, so it also recovers an
/// index that no longer opens (<see cref="StagedRestore"/>).
@@ -20,37 +20,48 @@ public interface IStartWithWindows
/// <summary>
/// <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</c> value that starts Titano minimised at sign-in, so inserted
/// cards are noticed (BRIEF §12.4) without a window in the way. The registry stays the source of truth because Task
/// Manager can turn it off. There is one value for every copy of Titano: a copy shows it as on only when it starts
/// that copy, and never takes it over or removes it unless the user ticks or unticks the box there. The uninstaller
/// removes it with the Uploader's when it starts a program of the folder it removes.
/// Manager can turn it off: an entry it turned off (<see cref="StartupApproval"/>) shows as off, and ticking the box
/// turns it on again. There is one value for every copy of Titano: a copy shows it as on only when it starts that
/// copy, and never takes it over or removes it unless the user ticks or unticks the box there. The uninstaller removes
/// it with the Uploader's when it starts a program of the folder it removes.
/// </summary>
public sealed class RunKeyStartWithWindows(string? executable = null) : IStartWithWindows
/// <param name="executable">This copy's program; the running one by default.</param>
/// <param name="root">The registry hive holding the entries; <c>HKEY_CURRENT_USER</c> by default (tests pass a scratch key).</param>
public sealed class RunKeyStartWithWindows(string? executable = null, RegistryKey? root = null) : IStartWithWindows
{
/// <summary>Starts the main window minimised on the taskbar.</summary>
public const string MinimizedOption = "--minimized";
private readonly string? _executable = executable ?? Environment.ProcessPath;
private readonly RegistryKey _root = root ?? Registry.CurrentUser;
public bool IsEnabled => StartupCommand.Starts(Read(), _executable);
/// <summary>The entry starts this copy and Task Manager has not turned it off.</summary>
public bool IsEnabled => StartupCommand.Starts(Read(), _executable) && !StartupApproval.IsTurnedOff(ReadApproval());
public void SetEnabled(bool enabled)
{
if (_executable is null) return;
try
if (_executable is not { } executable) return;
Update(key =>
{
using var key = Registry.CurrentUser.CreateSubKey(StartupCommand.RunKey, writable: true);
if (enabled) key.SetValue(StartupCommand.ClientValue, StartupCommand.Format(_executable, MinimizedOption), RegistryValueKind.String);
else if (StartupCommand.Starts(key.GetValue(StartupCommand.ClientValue) as string, _executable)) key.DeleteValue(StartupCommand.ClientValue, throwOnMissingValue: false);
}
catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException or IOException)
{
Log.Warning("startup", "Run key not updated", ex);
}
if (enabled)
{
key.SetValue(StartupCommand.ClientValue, StartupCommand.Format(executable, MinimizedOption), RegistryValueKind.String);
// Task Manager's "Disable" outlives a new command: ticking the box undoes it.
DeleteApproval();
}
else if (StartupCommand.Starts(key.GetValue(StartupCommand.ClientValue) as string, executable))
{
key.DeleteValue(StartupCommand.ClientValue, throwOnMissingValue: false);
DeleteApproval();
}
});
}
/// <summary>The command follows a renamed program; an entry Task Manager turned off stays off.</summary>
public void Refresh()
{
if (Follows(Read(), _executable, File.Exists)) SetEnabled(true);
if (_executable is { } executable && Follows(Read(), executable, File.Exists))
Update(key => key.SetValue(StartupCommand.ClientValue, StartupCommand.Format(executable, MinimizedOption), RegistryValueKind.String));
}
/// <summary>
@@ -65,11 +76,11 @@ public sealed class RunKeyStartWithWindows(string? executable = null) : IStartWi
&& string.Equals(StartupCommand.Folder(command), folder, StringComparison.OrdinalIgnoreCase);
}
private static string? Read()
private string? Read()
{
try
{
using var key = Registry.CurrentUser.OpenSubKey(StartupCommand.RunKey);
using var key = _root.OpenSubKey(StartupCommand.RunKey);
return key?.GetValue(StartupCommand.ClientValue) as string;
}
catch (Exception ex) when (ex is SecurityException or IOException)
@@ -77,6 +88,39 @@ public sealed class RunKeyStartWithWindows(string? executable = null) : IStartWi
return null;
}
}
/// <summary>Task Manager's switch for the entry; null when it never touched it.</summary>
private byte[]? ReadApproval()
{
try
{
using var key = _root.OpenSubKey(StartupApproval.RunKey);
return key?.GetValue(StartupCommand.ClientValue) as byte[];
}
catch (Exception ex) when (ex is SecurityException or IOException)
{
return null;
}
}
private void DeleteApproval()
{
using var key = _root.OpenSubKey(StartupApproval.RunKey, writable: true);
key?.DeleteValue(StartupCommand.ClientValue, throwOnMissingValue: false);
}
private void Update(Action<RegistryKey> change)
{
try
{
using var key = _root.CreateSubKey(StartupCommand.RunKey, writable: true);
change(key);
}
catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException or IOException)
{
Log.Warning("startup", "Run key not updated", ex);
}
}
}
/// <summary>Screenshots, tests and portable copies (which leave nothing in the registry) never touch the user's sign-in programs.</summary>
+120 -37
View File
@@ -45,6 +45,12 @@ public sealed class SettingsViewModel : SectionViewModel
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);
private bool _isDetectingFormats;
private IReadOnlyList<BackupOption> _backups = [];
private BackupOption? _selectedBackup;
@@ -82,7 +88,7 @@ public sealed class SettingsViewModel : SectionViewModel
_s.LastArchivePath = v.Length == 0 ? null : Path.GetFullPath(v);
Save();
UpdateArchiveFree();
_ = RetargetArchiveAsync();
_retarget = RetargetArchiveAsync();
}, () => Loc.L("Tooltips.Settings.ArchiveRoot"));
FolderTemplate = new EditableField(_s.FolderTemplate, v => NamingPreview.Validate(v, isFolder: true), v =>
{
@@ -307,6 +313,9 @@ public sealed class SettingsViewModel : SectionViewModel
/// <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>A portable copy leaves nothing in the registry (BRIEF §6.2): it offers no Startup row.</summary>
public bool ShowsStartup => !Shell.Services.Environment.IsPortable;
@@ -770,7 +779,8 @@ public sealed class SettingsViewModel : SectionViewModel
/// <summary>
/// Loads what needs the services (certificates, cache usage, the open archive's settings), follows the server session,
/// applies "Background priority" while Titano is in front and says how a restore staged before this start went.
/// applies "Background priority" while Titano 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()
{
@@ -798,6 +808,18 @@ public sealed class SettingsViewModel : SectionViewModel
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();
}
@@ -868,33 +890,48 @@ public sealed class SettingsViewModel : SectionViewModel
/// <summary>
/// Takes the archive and server values other screens set (opening an archive, connecting), unless the field holds an
/// edit not committed yet.
/// 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();
_ = LoadArchiveAsync();
if (_page == SettingsPage.Advanced) LoadBackups();
}
/// <summary>
/// Shows the open archive's own templates, proxy size and thumbnail size (its archive.json; the index's while it is
/// offline) unless a field holds an edit; they also become the defaults of new archives. The open archive is the one
/// at the archive folder of this PC, never another one of the index: with none registered there, the rows edit only
/// this PC's defaults.
/// 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 async Task LoadArchiveAsync()
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;
if (Shell.Services.Database is not { } db || Shell.Services.Archives is not { } archives) return null;
Archive? archive = null;
try
{
var registered = await db.Archives.ListAsync();
var archive = _s.LastArchivePath is { Length: > 0 } root ? CurrentArchive.At(registered, root) : CurrentArchive.Pick(registered, null);
archive = root is { Length: > 0 } ? CurrentArchive.At(registered, root) : null;
if (!IsArchiveFolder(root)) return archive;
_archive = archive;
if (archive is null) return;
var settings = await Task.Run(() => archives.GetSettingsAsync(archive.Id));
if (archive is null) return null;
var 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;
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
@@ -915,20 +952,46 @@ public sealed class SettingsViewModel : SectionViewModel
{
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.
/// 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.
/// </summary>
private async Task UpdateArchiveAsync(Func<ArchiveSettings, ArchiveSettings> edit)
private async Task UpdateArchiveAsync(Func<ArchiveSettings, ArchiveSettings> edit, Task<Archive?>? retarget = null)
{
if (_archive is not { } archive || Shell.Services.Archives is not { } archives) return;
retarget ??= _retarget;
var waited = !retarget.IsCompleted;
if (await ArchiveAtFolderAsync(retarget) is not { } archive || Shell.Services.Archives is not { } archives) return;
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.
if (waited && _retarget == retarget) await LoadArchiveAsync();
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or InvalidDataException or NewerFormatException
or DatabaseException)
@@ -939,36 +1002,42 @@ public sealed class SettingsViewModel : SectionViewModel
}
}
/// <summary>Every archive row into the open archive: Archive › Reset section, after the user confirmed it for that archive.</summary>
private Task PushArchiveSettingsAsync() => UpdateArchiveAsync(a => a with
/// <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.
/// 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 RetargetArchiveAsync()
private async Task<Archive?> RetargetArchiveAsync()
{
_archive = null;
if (_s.LastArchivePath is { } root && Shell.Services.Archives is { } archives)
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 DatabaseException)
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);
}
}
await LoadArchiveAsync();
return await LoadArchiveAsync(root);
}
/// <summary>
@@ -1306,19 +1375,8 @@ public sealed class SettingsViewModel : SectionViewModel
UiLanguage.Apply(null);
break;
case SettingsPage.Archive:
// The rows are the open archive's own: resetting them changes it for everyone sharing it, so only when confirmed.
var open = _archive;
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();
if (open is not null) _ = PushArchiveSettingsAsync();
break;
_ = ResetArchiveAsync(defaults);
return;
case SettingsPage.Import:
_s.ImportSessionGapMinutes = defaults.ImportSessionGapMinutes;
_s.ImportMinimumFrames = defaults.ImportMinimumFrames;
@@ -1367,6 +1425,31 @@ public sealed class SettingsViewModel : SectionViewModel
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.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));
@@ -1484,7 +1567,7 @@ public sealed class SettingsViewModel : SectionViewModel
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.
_ = RetargetArchiveAsync();
_retarget = RetargetArchiveAsync();
Shell.Notify(Loc.L("Settings.Import.Done"));
}
+34 -14
View File
@@ -1,22 +1,30 @@
using Titano.Core.IO;
namespace Titano.Core.Windows.Shell;
/// <summary>
/// Where the desktop programs keep their data (BRIEF §6.2): <c>%LOCALAPPDATA%\Titano</c>, or <c>.\data</c> next to the
/// executable in portable mode. SQLite corrupts inside synchronised folders, so a data root under OneDrive is
/// reported by <see cref="SyncedFolder"/> and refused by <see cref="CreateDirectories"/>.
/// Where the desktop programs keep their data (BRIEF §6.2, <see cref="DataLocation"/>): <c>%LOCALAPPDATA%\Titano</c>, or
/// <c>.\data</c> next to the executable in portable mode. SQLite corrupts inside synchronised folders, so a portable
/// copy in a OneDrive folder keeps its data in <c>%LOCALAPPDATA%\Titano</c> instead (<see cref="PortableSyncRoot"/>
/// names that folder to tell the user, <see cref="EarlierPortableData"/> the data it kept there before), and a data
/// root still under OneDrive is reported by <see cref="SyncedFolder"/> and refused by <see cref="CreateDirectories"/>.
/// </summary>
public sealed class AppPaths
{
public const string ProductFolderName = "Titano";
public const string ProductFolderName = DataLocation.ProductFolderName;
public const string DatabaseFileName = "titano.db";
public const string SettingsFileName = "settings.json";
private AppPaths(string dataRoot, bool isPortable, string? syncedFolder)
private AppPaths(DataLocation location, string? earlierPortableData)
{
DataRoot = dataRoot;
IsPortable = isPortable;
SyncedFolder = syncedFolder;
DataRoot = location.Root;
IsPortable = location.IsPortable;
SyncedFolder = location.SyncedFolder;
PortableSyncRoot = location.PortableSyncRoot;
EarlierPortableData = earlierPortableData;
}
/// <summary>A portable copy, also when its data had to go to <c>%LOCALAPPDATA%\Titano</c>.</summary>
public bool IsPortable { get; }
public string DataRoot { get; }
@@ -34,6 +42,15 @@ public sealed class AppPaths
public bool IsInSyncedFolder => SyncedFolder is not null;
/// <summary>The OneDrive sync root a portable copy runs from, whose data is in <c>%LOCALAPPDATA%\Titano</c> instead; null otherwise.</summary>
public string? PortableSyncRoot { get; }
/// <summary>
/// The <c>.\data</c> folder of a portable copy now in a OneDrive folder when it still holds the index or the settings
/// of an earlier start: nothing moves or deletes it, and the user is told where it is. Null otherwise.
/// </summary>
public string? EarlierPortableData { get; }
/// <summary>Paths for this process: the executable's folder decides portable mode.</summary>
public static AppPaths Resolve() => Resolve(AppContext.BaseDirectory, KnownFolders.LocalAppData);
@@ -41,13 +58,16 @@ public sealed class AppPaths
public static AppPaths Resolve(string applicationDirectory, string localAppData) =>
Resolve(applicationDirectory, localAppData, OneDriveFolders.SyncRoots());
internal static AppPaths Resolve(string applicationDirectory, string localAppData, IReadOnlyList<string> syncRoots)
/// <summary>Paths for an executable in <paramref name="applicationDirectory"/>, checked against <paramref name="syncRoots"/>.</summary>
public static AppPaths Resolve(string applicationDirectory, string localAppData, IReadOnlyCollection<string> syncRoots)
{
var portable = PortableMode.IsEnabled(applicationDirectory);
var root = Path.GetFullPath(portable
? Path.Combine(applicationDirectory, PortableMode.DataFolderName)
: Path.Combine(localAppData, ProductFolderName));
return new AppPaths(root, portable, OneDriveFolders.Containing(root, syncRoots));
var location = DataLocation.Choose(applicationDirectory, PortableMode.IsEnabled(applicationDirectory), localAppData, syncRoots);
var beside = Path.GetFullPath(Path.Combine(applicationDirectory, PortableMode.DataFolderName));
var earlier = location.PortableSyncRoot is not null
&& (File.Exists(Path.Combine(beside, DatabaseFileName)) || File.Exists(Path.Combine(beside, SettingsFileName)))
? beside
: null;
return new AppPaths(location, earlier);
}
/// <summary>Creates the data, logs, cache and thumbnails folders.</summary>
@@ -1,4 +1,6 @@
using System.Security;
using Microsoft.Win32;
using Titano.Core.IO;
namespace Titano.Core.Windows.Shell;
@@ -10,34 +12,34 @@ public static class OneDriveFolders
/// <summary>
/// Sync roots from the OneDrive environment variables and <c>HKCU\Software\Microsoft\OneDrive\Accounts\*\UserFolder</c>,
/// as full paths without a trailing separator, distinct (case-insensitive).
/// as full paths without a trailing separator, distinct (case-insensitive). An account key that cannot be read is
/// skipped: the programs start all the same.
/// </summary>
public static IReadOnlyList<string> SyncRoots()
{
var roots = new List<string>();
foreach (var variable in EnvironmentVariables) Add(roots, Environment.GetEnvironmentVariable(variable));
using var accounts = Registry.CurrentUser.OpenSubKey(AccountsKey);
if (accounts is not null)
try
{
foreach (var name in accounts.GetSubKeyNames())
using var accounts = Registry.CurrentUser.OpenSubKey(AccountsKey);
if (accounts is not null)
{
using var account = accounts.OpenSubKey(name);
Add(roots, account?.GetValue("UserFolder") as string);
foreach (var name in accounts.GetSubKeyNames())
{
using var account = accounts.OpenSubKey(name);
Add(roots, account?.GetValue("UserFolder") as string);
}
}
}
catch (Exception ex) when (ex is SecurityException or IOException or UnauthorizedAccessException)
{
// The environment variables name the usual roots.
}
return roots;
}
/// <summary>The sync root that contains <paramref name="path"/>, or null. Both are expected to be full paths.</summary>
public static string? Containing(string path, IEnumerable<string> syncRoots) => syncRoots.FirstOrDefault(root => IsUnder(path, root));
/// <summary>True when <paramref name="path"/> equals <paramref name="root"/> or lies below it (whole path segments, case-insensitive).</summary>
internal static bool IsUnder(string path, string root)
{
var trimmedRoot = root.TrimEnd('\\', '/');
if (trimmedRoot.Length == 0 || !path.StartsWith(trimmedRoot, StringComparison.OrdinalIgnoreCase)) return false;
return path.Length == trimmedRoot.Length || path[trimmedRoot.Length] is '\\' or '/';
}
public static string? Containing(string path, IEnumerable<string> syncRoots) => DataLocation.SyncRootOf(path, syncRoots);
private static void Add(List<string> roots, string? candidate)
{
@@ -1,10 +1,12 @@
using Titano.Core.IO;
namespace Titano.Core.Windows.Shell;
/// <summary>Portable mode (BRIEF §6.2): a <c>portable.txt</c> next to the executable keeps all data under <c>.\data\</c>.</summary>
public static class PortableMode
{
public const string MarkerFileName = "portable.txt";
public const string DataFolderName = "data";
public const string DataFolderName = DataLocation.PortableFolderName;
public static bool IsEnabled(string applicationDirectory) => File.Exists(Path.Combine(applicationDirectory, MarkerFileName));
}
+52
View File
@@ -0,0 +1,52 @@
namespace Titano.Core.IO;
/// <summary>
/// Where the desktop client keeps its data (BRIEF §6.2): the per-user folder (<c>%LOCALAPPDATA%\Titano</c>), or
/// <c>.\data</c> next to the executable of a portable copy (a <c>portable.txt</c> beside it). SQLite corrupts inside
/// synchronised folders, so a portable copy in a folder OneDrive synchronises (a OneDrive folder, or a Desktop or
/// Documents folder moved into one) keeps its data in the per-user folder instead, and <see cref="PortableSyncRoot"/>
/// says so, to tell the user. Paths are full paths; a folder lies in a sync root when its whole leading segments are
/// that root's, ignoring case as Windows does.
/// </summary>
/// <param name="Root">The data folder.</param>
/// <param name="IsPortable">The copy is portable, also when its data had to go to the per-user folder.</param>
/// <param name="SyncedFolder">The sync root that contains <paramref name="Root"/> itself; null when the data is safe there.</param>
/// <param name="PortableSyncRoot">The sync root a portable copy runs from, whose data went to the per-user folder instead; null otherwise.</param>
public sealed record DataLocation(string Root, bool IsPortable, string? SyncedFolder, string? PortableSyncRoot)
{
/// <summary>The data folder's name under the user's local application data.</summary>
public const string ProductFolderName = "Titano";
/// <summary>The data folder's name next to a portable copy's executable.</summary>
public const string PortableFolderName = "data";
/// <summary>
/// The data folder of a copy in <paramref name="applicationDirectory"/> (<paramref name="portable"/> when it has a
/// <c>portable.txt</c>), given the user's local application data and the OneDrive sync roots.
/// </summary>
public static DataLocation Choose(string applicationDirectory, bool portable, string localAppData, IReadOnlyCollection<string> syncRoots)
{
ArgumentNullException.ThrowIfNull(applicationDirectory);
ArgumentNullException.ThrowIfNull(localAppData);
ArgumentNullException.ThrowIfNull(syncRoots);
var perUser = Path.GetFullPath(Path.Combine(localAppData, ProductFolderName));
if (!portable) return new DataLocation(perUser, false, SyncRootOf(perUser, syncRoots), null);
var beside = Path.GetFullPath(Path.Combine(applicationDirectory, PortableFolderName));
return SyncRootOf(beside, syncRoots) is { } synced
? new DataLocation(perUser, true, SyncRootOf(perUser, syncRoots), synced)
: new DataLocation(beside, true, null, null);
}
/// <summary>The sync root that contains <paramref name="path"/>, or null.</summary>
public static string? SyncRootOf(string path, IEnumerable<string> syncRoots) => syncRoots.FirstOrDefault(root => IsUnder(path, root));
/// <summary>True when <paramref name="path"/> equals <paramref name="root"/> or lies below it (whole path segments, case-insensitive).</summary>
public static bool IsUnder(string path, string root)
{
ArgumentNullException.ThrowIfNull(path);
ArgumentNullException.ThrowIfNull(root);
var trimmedRoot = root.TrimEnd('\\', '/');
if (trimmedRoot.Length == 0 || !path.StartsWith(trimmedRoot, StringComparison.OrdinalIgnoreCase)) return false;
return path.Length == trimmedRoot.Length || path[trimmedRoot.Length] is '\\' or '/';
}
}
+16
View File
@@ -0,0 +1,16 @@
namespace Titano.Core.IO;
/// <summary>
/// Whether Windows runs a sign-in entry (<see cref="StartupCommand"/>). Task Manager's Startup tab and Settings › Apps ›
/// Startup turn an entry off without touching its Run value: they write a binary value of the same name under
/// <see cref="RunKey"/> whose first byte is odd while the entry is off (0x03) and even once it is on again (0x02). An
/// entry without that value is on. Rewriting the Run value leaves it as it is, so turning an entry back on means
/// removing it.
/// </summary>
public static class StartupApproval
{
public const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run";
/// <summary>The entry is turned off according to its StartupApproved <paramref name="state"/> (null when it has none).</summary>
public static bool IsTurnedOff(byte[]? state) => state is { Length: > 0 } && (state[0] & 1) != 0;
}
+54 -9
View File
@@ -147,17 +147,31 @@ public sealed class ArchiveService : IJobHandlerProvider
public async Task<ArchiveSettings> GetSettingsAsync(Guid archiveId, CancellationToken cancellationToken = default)
{
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
var paths = new ArchivePaths(archive.RootPath);
try
return TryReadManifest(archive) is { } manifest
? ArchiveSettings.Of(manifest)
: new ArchiveSettings(archive.Name, new LayoutTemplates { Folder = archive.FolderTemplate, File = archive.FileTemplate },
new ProxyPolicy { LongEdge = archive.ProxyLongEdge }, new ThumbnailPolicy());
}
/// <summary>
/// The settings in the archive's <c>archive.json</c>, with its index row brought up to them when another process
/// sharing the archive changed the file (a server's admin panel, another PC's Settings): imports and uploads take their
/// templates and proxy size from that row. Null while the file cannot be read (offline, damaged, newer, of another
/// archive): the row stays as it is, and only <see cref="GetSettingsAsync"/>'s stand-ins are known.
/// </summary>
public async Task<ArchiveSettings?> RefreshSettingsAsync(Guid archiveId, CancellationToken cancellationToken = default)
{
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
if (TryReadManifest(archive) is not { } manifest) return null;
var settings = ArchiveSettings.Of(manifest);
if (!settings.IsRegisteredIn(archive))
{
if (File.Exists(paths.ManifestPath)) return ArchiveSettings.Of(ManifestStore.ReadArchive(paths.ManifestPath));
// Read without the settings lease, as at open: an edit made meanwhile writes its own row, and the next refresh
// settles a file that changes again.
await RegisterAsync(new ArchivePaths(archive.RootPath), manifest, cancellationToken).ConfigureAwait(false);
Log.Info("archive", $"Settings of {archive.RootPath} changed elsewhere: {manifest.LayoutTemplates.Folder} · {manifest.LayoutTemplates.File}, proxies {manifest.ProxyPolicy.LongEdge}");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{
Log.Warning("archive", $"The settings of {paths.Root} cannot be read; the index's are used", ex);
}
return new ArchiveSettings(archive.Name, new LayoutTemplates { Folder = archive.FolderTemplate, File = archive.FileTemplate },
new ProxyPolicy { LongEdge = archive.ProxyLongEdge }, new ThumbnailPolicy());
return settings;
}
/// <summary>
@@ -325,6 +339,29 @@ public sealed class ArchiveService : IJobHandlerProvider
return archive;
}
/// <summary>
/// The archive's <c>archive.json</c>; null (logged) while it cannot be read, when a newer Titano wrote it (this one
/// would drop what it does not know) or when it belongs to another archive.
/// </summary>
private static ArchiveManifest? TryReadManifest(Archive archive)
{
var paths = new ArchivePaths(archive.RootPath);
try
{
if (!File.Exists(paths.ManifestPath)) return null;
var manifest = ManifestStore.ReadArchive(paths.ManifestPath);
if (manifest.SchemaVersion > ArchiveManifest.CurrentSchemaVersion)
Log.Warning("archive", $"{paths.ManifestPath} has schema version {manifest.SchemaVersion}, newer than this Titano's; the index's settings are used");
else if (manifest.Id == archive.Id) return manifest;
else Log.Warning("archive", $"{paths.ManifestPath} belongs to archive {manifest.Id}, not {archive.Id}; the index's settings are used");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{
Log.Warning("archive", $"The settings of {paths.Root} cannot be read; the index's are used", ex);
}
return null;
}
private async Task<Archive> LoadArchiveAsync(Guid archiveId, CancellationToken cancellationToken) =>
await _db.Archives.GetAsync(archiveId, cancellationToken).ConfigureAwait(false) ?? throw new ArgumentException($"Unknown archive {archiveId}.", nameof(archiveId));
@@ -349,6 +386,14 @@ public sealed record ArchiveSettings(string Name, LayoutTemplates Templates, Pro
public static ArchiveSettings Of(ArchiveManifest manifest) => new(manifest.Name, manifest.LayoutTemplates, manifest.ProxyPolicy, manifest.ThumbnailPolicy);
/// <summary>Whether the index row <paramref name="archive"/> holds these settings (all it keeps: not the thumbnail policy).</summary>
public bool IsRegisteredIn(Archive archive)
{
ArgumentNullException.ThrowIfNull(archive);
return Name == archive.Name && Templates.Folder == archive.FolderTemplate && Templates.File == archive.FileTemplate
&& Proxies.LongEdge == archive.ProxyLongEdge;
}
/// <summary>The first invalid field by its API name (<c>name</c>, <c>folderTemplate</c>, <c>fileTemplate</c>,
/// <c>proxyLongEdge</c>, <c>thumbnailLongEdge</c>); null when every field is valid.</summary>
public string? Problem()
+3 -1
View File
@@ -19,7 +19,9 @@ public static class ArchiveEndpoints
public static void Map(RouteGroupBuilder api)
{
var archive = api.MapGroup("/archive").Requires(Permissions.ManageArchive);
archive.MapGet("/settings", (ServerArchive a) => Results.Json(Settings(a.Current), ProtocolJson.Default.ArchiveSettingsDto));
// The form saves every field: it starts from what archive.json holds now, also a desktop's change since the last poll.
archive.MapGet("/settings", async (HttpContext c, ServerArchive a, TitanoDatabase db, [FromServices] ArchiveService? archives) =>
Results.Json(Settings(archives is null ? a.Current : await a.RefreshAsync(archives, db, c.RequestAborted)), ProtocolJson.Default.ArchiveSettingsDto));
archive.MapPut("/settings", UpdateAsync);
archive.MapGet("/stats", async (HttpContext c, TitanoDatabase db, ServerArchive a) =>
Results.Json(await StatsAsync(db, a, c.RequestAborted), ProtocolJson.Default.ArchiveStatsDto));
+5 -2
View File
@@ -10,9 +10,11 @@ namespace Titano.Server.Storage;
/// Polls the archive (BRIEF §7: by modification time and size, no file-system watchers): an incremental scan at start
/// and every <see cref="Interval"/> while the archive is online, so photos already in an adopted folder and sequences
/// another writer adds (a desktop sharing the archive, files copied in by hand) are indexed without an administrator's
/// rescan. A scan or rebuild of the archive that is waiting, running or paused is not queued again.
/// rescan. Settings such a writer changed in archive.json reach the index first, so uploads and the admin panel follow
/// them. A scan or rebuild of the archive that is waiting, running or paused is not queued again.
/// </summary>
public sealed class ArchivePolling(TitanoDatabase db, ServerArchive archive, JobEngineHost jobs, TimeProvider time, ILogger<ArchivePolling> logger)
public sealed class ArchivePolling(TitanoDatabase db, ServerArchive archive, ArchiveService archives, JobEngineHost jobs, TimeProvider time,
ILogger<ArchivePolling> logger)
: BackgroundService
{
/// <summary>The desktop's rhythm (it polls its archive the same way).</summary>
@@ -26,6 +28,7 @@ public sealed class ArchivePolling(TitanoDatabase db, ServerArchive archive, Job
if (!jobs.CanRun(JobKind.Scan)) return null;
var current = archive.Current;
if (ArchiveService.GetAvailability(current) != ArchiveAvailability.Online) return null;
current = await archive.RefreshAsync(archives, db, cancellationToken);
foreach (var kind in new[] { JobKind.Scan, JobKind.Rebuild })
{
foreach (var state in Pending)
@@ -19,6 +19,29 @@ public sealed class ServerArchive(Archive archive)
set => _current = value;
}
/// <summary>
/// Serves <paramref name="value"/> unless <see cref="Current"/> is no longer <paramref name="expected"/>, the archive
/// it was read from: an edit an administrator saved meanwhile is never undone. False when it was not replaced.
/// </summary>
public bool TryReplace(Archive expected, Archive value) => ReferenceEquals(Interlocked.CompareExchange(ref _current, value, expected), expected);
/// <summary>
/// <see cref="Current"/> once it and the index row hold the settings another writer sharing the archive (a desktop)
/// put into its archive.json (<see cref="ArchiveService.RefreshSettingsAsync"/>): uploads, the polling and the admin
/// panel, whose form saves every field, never work from older ones. Unchanged while the file cannot be read.
/// </summary>
public async Task<Archive> RefreshAsync(ArchiveService archives, TitanoDatabase db, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(archives);
ArgumentNullException.ThrowIfNull(db);
var current = Current;
// Only a change the refresh registered is served, and never over an edit an administrator saved since the read above.
if (await archives.RefreshSettingsAsync(current.Id, cancellationToken).ConfigureAwait(false) is { } settings && !settings.IsRegisteredIn(current)
&& await db.Archives.GetAsync(current.Id, cancellationToken).ConfigureAwait(false) is { } row)
TryReplace(current, row);
return Current;
}
public Guid Id => _current.Id;
public string Root => _current.RootPath;
+6 -3
View File
@@ -41,13 +41,16 @@ public sealed class SampleData
],
};
/// <summary>A view model over in-memory sample services; settings changes are discarded.</summary>
public MainViewModel CreateViewModel()
/// <summary>
/// A view model over in-memory sample services; settings changes are discarded. <paramref name="startup"/> stands for
/// the sign-in entry (an in-memory one, on, by default).
/// </summary>
public MainViewModel CreateViewModel(IStartupRegistration? startup = null)
{
var memory = new ProcessedFileMemory();
_session.BandwidthLimit = Settings.BandwidthLimit;
_vm = new MainViewModel(new UploaderServices(
Settings, () => { }, _session, _queue, new SampleEngine(_queue), new SampleStartup(), new UploaderDialogs(),
Settings, () => { }, _session, _queue, new SampleEngine(_queue), startup ?? new SampleStartup(), new UploaderDialogs(),
new WatchFolderService(memory, _queue.ContainsPath), memory, string.Empty));
foreach (var w in _vm.WatchFolders) w.IsAvailable = true;
// A disconnected drive: its chip shows the hollow ring and wraps to a second line.
@@ -1,3 +1,4 @@
using System.IO;
using System.Security;
using Microsoft.Win32;
using Titano.Core.Diagnostics;
@@ -15,49 +16,65 @@ public interface IStartupRegistration
/// <summary>
/// <c>HKCU\Software\Microsoft\Windows\CurrentVersion\Run</c> value that starts the uploader in the tray at sign-in.
/// The registry stays the source of truth because Task Manager can turn it off. Uninstalling removes the value when
/// it starts the Uploader the uninstaller removes (<see cref="StartupCommand"/> names it for both).
/// The registry stays the source of truth because Task Manager can turn it off: an entry it turned off
/// (<see cref="StartupApproval"/>) shows as off, and ticking the box turns it on again. Uninstalling removes the value
/// when it starts the Uploader the uninstaller removes (<see cref="StartupCommand"/> names it for both).
/// </summary>
public sealed class RunKeyStartupRegistration : IStartupRegistration
/// <param name="executable">The Uploader's program; the running one by default.</param>
/// <param name="root">The registry hive holding the entries; <c>HKEY_CURRENT_USER</c> by default (tests pass a scratch key).</param>
public sealed class RunKeyStartupRegistration(string? executable = null, RegistryKey? root = null) : IStartupRegistration
{
private const string RunKey = StartupCommand.RunKey;
private const string ValueName = StartupCommand.UploaderValue;
public bool IsEnabled
private readonly string? _executable = executable ?? Environment.ProcessPath;
private readonly RegistryKey _root = root ?? Registry.CurrentUser;
/// <summary>The entry exists and Task Manager has not turned it off.</summary>
public bool IsEnabled => HasEntry && !StartupApproval.IsTurnedOff(Read(StartupApproval.RunKey) as byte[]);
private bool HasEntry => Read(RunKey) is string { Length: > 0 };
private string Command => StartupCommand.Format(_executable ?? string.Empty, CommandLine.TrayOption);
public void SetEnabled(bool enabled) => Update(key =>
{
get
{
try
{
using var key = Registry.CurrentUser.OpenSubKey(RunKey);
return key?.GetValue(ValueName) is string { Length: > 0 };
}
catch (SecurityException)
{
return false;
}
}
if (enabled) key.SetValue(ValueName, Command, RegistryValueKind.String);
else key.DeleteValue(ValueName, throwOnMissingValue: false);
// Task Manager's "Disable" outlives a new command: ticking the box undoes it, and unticking leaves nothing behind.
using var approval = _root.OpenSubKey(StartupApproval.RunKey, writable: true);
approval?.DeleteValue(ValueName, throwOnMissingValue: false);
});
/// <summary>Points an existing entry at the current executable (after an update moved it); one Task Manager turned off stays off.</summary>
public void Refresh()
{
if (HasEntry) Update(key => key.SetValue(ValueName, Command, RegistryValueKind.String));
}
private static string Command => $"\"{Environment.ProcessPath}\" {CommandLine.TrayOption}";
public void SetEnabled(bool enabled)
private object? Read(string subKey)
{
try
{
using var key = Registry.CurrentUser.CreateSubKey(RunKey, writable: true);
if (enabled) key.SetValue(ValueName, Command, RegistryValueKind.String);
else key.DeleteValue(ValueName, throwOnMissingValue: false);
using var key = _root.OpenSubKey(subKey);
return key?.GetValue(ValueName);
}
catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException)
catch (Exception ex) when (ex is SecurityException or IOException)
{
return null;
}
}
private void Update(Action<RegistryKey> change)
{
try
{
using var key = _root.CreateSubKey(RunKey, writable: true);
change(key);
}
catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException or IOException)
{
Log.Warning("startup", "Run key not updated", ex);
}
}
/// <summary>Points an existing entry at the current executable (after an update moved it).</summary>
public void Refresh()
{
if (IsEnabled) SetEnabled(true);
}
}
@@ -4,7 +4,8 @@ namespace Titano.Uploader.Infrastructure;
/// <summary>
/// Where the uploader keeps its files: <c>%LOCALAPPDATA%\Titano</c> (shared with the client), or <c>.\data</c> next
/// to the executable when <c>portable.txt</c> exists — the same rule as the desktop client.
/// to the executable when <c>portable.txt</c> exists — the desktop client's rule, except that the client never keeps
/// its SQLite index in a folder OneDrive synchronises; the Uploader's JSON files, written atomically, stay there.
/// </summary>
public sealed class UploaderEnvironment
{
+7 -1
View File
@@ -156,7 +156,13 @@ public sealed class MainViewModel : LocalizedViewModel
public bool IsSettingsOpen
{
get => _isSettingsOpen;
set => Set(ref _isSettingsOpen, value);
set
{
if (!Set(ref _isSettingsOpen, value) || !value) return;
// The Uploader runs for the whole session: Task Manager may have turned its sign-in entry off meanwhile.
_startWithWindows = _s.Startup.IsEnabled;
OnPropertyChanged(nameof(StartWithWindows));
}
}
// ---------------- Target ----------------