feat: owner review 2 phase 2: scheduled jobs and log settings (#10)
CI / Build and test (push) Successful in 7m0s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 13m28s
CI / PostgreSQL 16 integration (push) Successful in 5m52s
CI / PostgreSQL 17 integration (push) Successful in 4m50s
CI / Docker image (push) Successful in 1m4s
Release / Server image (push) Successful in 1m35s
CI / Build and test (push) Successful in 7m0s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 13m28s
CI / PostgreSQL 16 integration (push) Successful in 5m52s
CI / PostgreSQL 17 integration (push) Successful in 4m50s
CI / Docker image (push) Successful in 1m4s
Release / Server image (push) Successful in 1m35s
- Jobs > Scheduled on the desktop and the admin panel. Every timer that queued work is now a visible system schedule: archive scan, upload clean-up, index backup, job-history and audit clean-ups, desktop housekeeping. New actions: verify, thumbnails, proxies, analysis, maintenance, backup, clean-ups, reports. - The scheduler: migration 0007, in-house recurrence, compare-and-set claim, catch-up, scan at start. - Log settings: levels, retention, size parts, total limit, daily or hourly rotation, audit retention, diagnostics share; the server writes Debug/Trace to its files again; logging never fails a job. Upgrade: CHRONOS_LOG_LEVEL set in an existing container locks both levels; migration 0007 is one-way. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #10.
This commit is contained in:
1 parent
1f089888e8
commit
af9eeaab9b
349 files changed
+28341
-1304
No files matched your search
@@ -41,7 +41,9 @@ public partial class App : Application
|
||||
var capture = captureIndex >= 0;
|
||||
// Capture never reads or writes the user's data folder.
|
||||
Environment = capture ? AppEnvironment.ForCapture() : AppEnvironment.Detect();
|
||||
_log = new FileLogSink(Environment.LogDirectory, "chronos");
|
||||
// Settings › Advanced › Logs from the first line, which prunes the folder: also a launch that only hands over. The
|
||||
// settings are read again once this launch owns the data folder, since a Chronos that was closing saves them on exit.
|
||||
_log = AppLogging.Open(Environment.LogDirectory, capture ? new AppSettings() : AppSettings.Load(Environment.SettingsPath));
|
||||
// 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", $"Chronos {AppServices.VersionText} starting; data at {Environment.DataDirectory}");
|
||||
@@ -77,6 +79,7 @@ public partial class App : Application
|
||||
}
|
||||
|
||||
Settings = capture ? new AppSettings { Language = "en" } : AppSettings.Load(Environment.SettingsPath);
|
||||
ApplyLogSettings();
|
||||
UiLanguage.Apply(Settings.Language);
|
||||
ThemeManager.Initialize(this, capture ? AppTheme.Dark : Settings.Theme);
|
||||
AppResources.Merge(this);
|
||||
@@ -182,7 +185,7 @@ public partial class App : Application
|
||||
|
||||
public void SaveSettings()
|
||||
{
|
||||
// A launch that handed over to the running Chronos exits before loading any settings.
|
||||
// A launch that handed over to the running Chronos reads the settings only for its log and never sets Settings.
|
||||
if (Settings is null) return;
|
||||
try
|
||||
{
|
||||
@@ -192,6 +195,14 @@ public partial class App : Application
|
||||
{
|
||||
Log.Warning("app", "Settings not saved", ex);
|
||||
}
|
||||
// Every settings change passes here, Settings › Advanced › Logs, its Reset and an imported file included.
|
||||
ApplyLogSettings();
|
||||
}
|
||||
|
||||
/// <summary>Settings › Advanced › Logs to the log files, from the next line on (owner review 2, R11).</summary>
|
||||
private void ApplyLogSettings()
|
||||
{
|
||||
if (_log is not null) AppLogging.Apply(_log, Settings);
|
||||
}
|
||||
|
||||
protected override void OnExit(ExitEventArgs e)
|
||||
|
||||
@@ -24,6 +24,7 @@ using Chronos.Core.Video;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
@@ -33,8 +34,8 @@ namespace Chronos.App.DesignTime;
|
||||
/// <summary>
|
||||
/// Synthetic content for <c>--capture</c> screenshots and the screen smoke tests ONLY: a temporary SQLite index
|
||||
/// with an archive of generated JPEGs (one sequence stores its thumbnail as an embedded preview inside a fake RAW
|
||||
/// file), jobs in every state, a fake signed-in server with sequences to compare (one in conflict) and a fake
|
||||
/// encoder inventory. Everything lives in the
|
||||
/// file), jobs in every state, schedules (the system ones with runs, a weekly integrity check, a monthly report turned
|
||||
/// off), a fake signed-in server with sequences to compare (one in conflict) and a fake encoder inventory. Everything lives in the
|
||||
/// capture environment's temporary folder; nothing touches the network or the user's data.
|
||||
/// </summary>
|
||||
public sealed class SampleData
|
||||
@@ -55,6 +56,8 @@ public sealed class SampleData
|
||||
private ChronosDatabase? _db;
|
||||
private Guid _sunrise;
|
||||
private Guid _lakeComo;
|
||||
private Guid _weeklyVerify = Guid.CreateVersion7();
|
||||
private Guid? _scanSchedule;
|
||||
private Permissions _permissions = RolePermissions.Default(UserRole.Editor);
|
||||
|
||||
private SampleData(AppServices services) => _services = services;
|
||||
@@ -77,6 +80,8 @@ public sealed class SampleData
|
||||
services.Devices = new SampleDeviceMonitor();
|
||||
services.Sync.RemoteFactory = (_, _, _) => sample._remote;
|
||||
services.Sync.EditorFactory = (_, _, _) => sample._remote;
|
||||
// The schedules keep the sample's moment: nothing becomes due while the screenshots are taken.
|
||||
services.SchedulerTime = new FixedTime(Now);
|
||||
return sample;
|
||||
}
|
||||
|
||||
@@ -109,7 +114,10 @@ public sealed class SampleData
|
||||
await db.Sequences.SetTagsAsync(sequences[0].Sequence.Id, ["sunset", "harbour"]);
|
||||
await db.Sequences.SetTagsAsync(sequences[9].Sequence.Id, ["holy grail"]);
|
||||
|
||||
foreach (var job in Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id)) await db.Jobs.EnqueueAsync(job);
|
||||
_scanSchedule = (await db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan))?.Id;
|
||||
var jobs = Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id).ToList();
|
||||
foreach (var job in jobs) await db.Jobs.EnqueueAsync(job);
|
||||
await FillSchedulesAsync(db, jobs);
|
||||
await FillServerAsync(db, sequences.Select(s => s.Sequence).ToList());
|
||||
await SampleCards.InsertAsync(db, (SampleDeviceMonitor)_services.Devices, _services.Environment.DataDirectory);
|
||||
await FillViewsAsync(db);
|
||||
@@ -126,6 +134,53 @@ public sealed class SampleData
|
||||
settings.FirstRunCompleted = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Jobs › Scheduled (owner review 2, R10): the archive scan ran 4 minutes ago (its scan is in the history), the index
|
||||
/// backup yesterday, the housekeeping never yet; a weekly integrity check the user made, whose run waits in the queue, and
|
||||
/// a monthly orphans report turned off.
|
||||
/// </summary>
|
||||
private async Task FillSchedulesAsync(ChronosDatabase db, IReadOnlyList<Job> jobs)
|
||||
{
|
||||
var verify = jobs.First(j => j.ScheduleId == _weeklyVerify);
|
||||
var weekly = ScheduleRecurrence.WeeklyAt([DayOfWeek.Sunday], new TimeOnly(2, 0));
|
||||
var created = Now.AddDays(-40);
|
||||
await db.Schedules.InsertAsync(new Schedule
|
||||
{
|
||||
Id = _weeklyVerify,
|
||||
Name = "Weekly integrity check",
|
||||
Action = ScheduleActions.Verify,
|
||||
ParametersJson = ScheduleMapping.ParametersJson(ScheduleActions.Verify, new ScheduleParametersDto(OlderThanDays: 30, Percent: 25)),
|
||||
Recurrence = weekly.Format(),
|
||||
NextRun = weekly.Next(Now, TimeZoneInfo.Local),
|
||||
LastRun = verify.Created,
|
||||
LastJobId = verify.Id,
|
||||
LastOutcome = ScheduleOutcome.Queued,
|
||||
Created = created,
|
||||
Updated = created,
|
||||
});
|
||||
var monthly = ScheduleRecurrence.MonthlyAt(1, new TimeOnly(5, 0));
|
||||
await db.Schedules.InsertAsync(new Schedule
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Name = "Monthly orphans report",
|
||||
Action = ScheduleActions.Orphans,
|
||||
Recurrence = monthly.Format(),
|
||||
Enabled = false,
|
||||
Created = created.AddMinutes(5),
|
||||
Updated = created.AddMinutes(5),
|
||||
});
|
||||
if (_scanSchedule is { } scan && jobs.FirstOrDefault(j => j.ScheduleId == scan) is { } scanned)
|
||||
await db.Schedules.RecordOutcomeAsync(scan, scanned.Id, ScheduleOutcome.Queued, scanned.Created);
|
||||
if (await db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.IndexBackup) is { } backup)
|
||||
await db.Schedules.RecordOutcomeAsync(backup.Id, null, ScheduleOutcome.SkippedNothing, Now.AddDays(-1).AddHours(-2));
|
||||
}
|
||||
|
||||
/// <summary>A clock stopped at one moment (the schedules of the capture).</summary>
|
||||
private sealed class FixedTime(DateTimeOffset now) : TimeProvider
|
||||
{
|
||||
public override DateTimeOffset GetUtcNow() => now;
|
||||
}
|
||||
|
||||
/// <summary>Two saved views of the Library ("Not analysed, largest" and one camera), BRIEF §12.2.</summary>
|
||||
private static async Task FillViewsAsync(ChronosDatabase db)
|
||||
{
|
||||
@@ -185,7 +240,7 @@ public sealed class SampleData
|
||||
{
|
||||
var db = _db ?? throw new InvalidOperationException("FillAsync first.");
|
||||
var service = _services.Sync.Service ?? throw new InvalidOperationException("The index is not open.");
|
||||
// The history is kept whatever the date: the sample's finished jobs are dated from Now, not from today.
|
||||
// The engine purges no history (the housekeeping schedule does): the sample's finished jobs, dated from Now, stay.
|
||||
await using var engine = new JobEngine(db, service.CreateJobHandlers(_services.Sync),
|
||||
new JobEngineOptions
|
||||
{
|
||||
@@ -193,7 +248,6 @@ public sealed class SampleData
|
||||
WorkerId = "sample-proxies",
|
||||
Kinds = [JobKind.Download],
|
||||
PollInterval = TimeSpan.FromMilliseconds(50),
|
||||
HistoryRetention = TimeSpan.FromDays(36_500),
|
||||
});
|
||||
await engine.StartAsync();
|
||||
var job = await service.EnqueueDownloadAsync(engine, ServerAddress, _sunrise, "Sunrise over Superga", SyncDownloadMode.Proxies, null);
|
||||
@@ -637,10 +691,11 @@ public sealed class SampleData
|
||||
var here = _services.WorkerId;
|
||||
Job Make(JobKind kind, Sequence? target, string label, JobState state, long done, long total, double? rate = null, TimeSpan? eta = null,
|
||||
TimeSpan? startedAgo = null, TimeSpan? runFor = null, string? node = null, string? error = null, string? log = null,
|
||||
JobPriority priority = JobPriority.Normal, TimeSpan? createdAgo = null) => new()
|
||||
JobPriority priority = JobPriority.Normal, TimeSpan? createdAgo = null, Guid? schedule = null) => new()
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = kind,
|
||||
ScheduleId = schedule,
|
||||
TargetIds = target is null ? [archiveId] : [target.Id],
|
||||
TargetLabel = label,
|
||||
State = state,
|
||||
@@ -672,9 +727,14 @@ public sealed class SampleData
|
||||
yield return Make(JobKind.Proxies, s[1], s[1].DisplayTitle, JobState.Paused, 915, 1_005, startedAgo: TimeSpan.FromMinutes(14),
|
||||
priority: JobPriority.Background);
|
||||
yield return Make(JobKind.Render, s[3], "Aurora, Tromsø → 1080p share H.264", JobState.Queued, 0, 0, createdAgo: TimeSpan.FromMinutes(12));
|
||||
yield return Make(JobKind.Verify, null, "Archive · 2024", JobState.Queued, 0, 0, priority: JobPriority.Background, createdAgo: TimeSpan.FromMinutes(30));
|
||||
// The weekly integrity check the user scheduled waits behind the user's jobs.
|
||||
yield return Make(JobKind.Verify, null, "Archive · 2024", JobState.Queued, 0, 0, priority: JobPriority.Background, createdAgo: TimeSpan.FromMinutes(30),
|
||||
schedule: _weeklyVerify);
|
||||
yield return Make(JobKind.Verify, s[7], s[7].DisplayTitle, JobState.Failed, 640, 640, 900, startedAgo: TimeSpan.FromMinutes(25), runFor: TimeSpan.FromSeconds(43),
|
||||
error: "2 files whose hash no longer matches the sidecar", log: "09:58:01 verify 640 files\n09:58:43 2 hash mismatches: 2025-08-02_0213.ARW, 2025-08-02_0214.ARW");
|
||||
// The archive scan schedule's latest run.
|
||||
yield return Make(JobKind.Scan, null, "ChronosArchive", JobState.Done, 412, 412, 640, startedAgo: TimeSpan.FromMinutes(4), runFor: TimeSpan.FromSeconds(1),
|
||||
priority: JobPriority.Background, schedule: _scanSchedule);
|
||||
yield return Make(JobKind.Render, s[5], "Milan skyline dusk → 4K HEVC", JobState.Done, 2_400, 2_400, 14.8, startedAgo: TimeSpan.FromMinutes(70),
|
||||
runFor: new TimeSpan(0, 2, 41), node: "studio-pc");
|
||||
yield return Make(JobKind.Import, s[0], "EOS R5 · card A → Archive · 4,812 photos", JobState.Done, 4_812, 4_812, 7.1, startedAgo: TimeSpan.FromMinutes(110),
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
using Chronos.Core.Diagnostics;
|
||||
|
||||
namespace Chronos.App.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// Settings › Advanced › Logs applied to this PC's log files (owner review 2, R11): the level, retention, size limits and
|
||||
/// rotation of the <see cref="FileLogSink"/> App starts with, and the engine's <see cref="Log.MinimumLevel"/> (the files
|
||||
/// are the only output outside screenshots). Values outside the ranges Settings offers are brought within them, and a
|
||||
/// total below one file is raised to that file (<see cref="LogFileOptions.TotalBelowFile"/>), which the server refuses.
|
||||
/// </summary>
|
||||
public static class AppLogging
|
||||
{
|
||||
public const int DefaultDiagnosticsLogMb = (int)(DiagnosticsArchive.DefaultLogTailBytes / LogFileOptions.BytesPerMb);
|
||||
|
||||
public const int MaxRetentionDays = 3650;
|
||||
public const int MaxFileMb = 10 * 1024;
|
||||
public const int MaxTotalMb = 1024 * 1024;
|
||||
public const int MaxDiagnosticsLogMb = 1024;
|
||||
|
||||
public static LogFileOptions Options(AppSettings settings)
|
||||
{
|
||||
var file = int.Clamp(settings.LogMaxFileMb, 0, MaxFileMb);
|
||||
var total = int.Clamp(settings.LogMaxTotalMb, 0, MaxTotalMb);
|
||||
return new()
|
||||
{
|
||||
Level = Enum.IsDefined(settings.LogLevel) ? settings.LogLevel : LogLevel.Info,
|
||||
RetentionDays = int.Clamp(settings.LogRetentionDays, 1, MaxRetentionDays),
|
||||
MaxFileMb = file,
|
||||
MaxTotalMb = LogFileOptions.TotalBelowFile(file, total) ? file : total,
|
||||
Rotation = Enum.IsDefined(settings.LogRotation) ? settings.LogRotation : LogRotation.Daily,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Bytes the diagnostics bundle keeps from the end of each log file.</summary>
|
||||
public static long DiagnosticsTailBytes(AppSettings settings) => int.Clamp(settings.DiagnosticsLogMb, 1, MaxDiagnosticsLogMb) * LogFileOptions.BytesPerMb;
|
||||
|
||||
/// <summary>
|
||||
/// The log files App starts with, in <paramref name="directory"/>, with <paramref name="settings"/> from the first line:
|
||||
/// that line opens a file and prunes, so the defaults would delete what the user keeps longer.
|
||||
/// </summary>
|
||||
public static FileLogSink Open(string directory, AppSettings settings)
|
||||
{
|
||||
var options = Options(settings);
|
||||
Log.MinimumLevel = options.Level;
|
||||
return new FileLogSink(directory, "chronos", options);
|
||||
}
|
||||
|
||||
/// <summary>The settings to <paramref name="sink"/> and the engine, from the next line on.</summary>
|
||||
public static void Apply(FileLogSink sink, AppSettings settings)
|
||||
{
|
||||
var options = Options(settings);
|
||||
sink.Configure(options);
|
||||
Log.MinimumLevel = options.Level;
|
||||
}
|
||||
}
|
||||
@@ -22,19 +22,22 @@ using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol.Client;
|
||||
|
||||
namespace Chronos.App.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// Composition root of local mode (BRIEF §4.4): the SQLite index under the data folder (migrated on open, a restore
|
||||
/// staged in Settings › Advanced carried out first, then copied once a day into the backups folder), the archive engine
|
||||
/// (WIC first, then managed decoders), the analysis and render engine (the same decoders; Media Foundation, then
|
||||
/// 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
|
||||
/// 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
|
||||
/// staged in Settings › Advanced carried out first), the archive engine (WIC first, then managed decoders), the analysis
|
||||
/// and render engine (the same decoders; Media Foundation, then managed encoders), the one <see cref="JobEngine"/> of
|
||||
/// this PC with the handlers of <see cref="CreateJobHandlers"/>, the <see cref="Data.Scheduling.Scheduler"/> that queues the
|
||||
/// recurring work (owner review 2, R10: the archive scan, the daily index backup and the housekeeping are its system
|
||||
/// schedules, <see cref="DesktopScheduleHost"/>), 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 archive at Settings › Archive's folder is reopened at start before the
|
||||
/// scheduler starts, and while it is unplugged every <see cref="ReopenInterval"/> until it is back; the schedules follow
|
||||
/// the folder, also 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
|
||||
@@ -52,9 +55,8 @@ public sealed class AppServices : IAsyncDisposable
|
||||
private static readonly Lazy<HttpClient> DownloadHttp = new(() => new HttpClient { Timeout = Timeout.InfiniteTimeSpan });
|
||||
private readonly CancellationTokenSource _stopping = new();
|
||||
private readonly Dictionary<Guid, Guid> _scans = [];
|
||||
private Task _polling = Task.CompletedTask;
|
||||
private Task _backups = Task.CompletedTask;
|
||||
private PeriodicTimer? _pollTimer;
|
||||
private readonly TaskCompletionSource<bool> _schedulerReady = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
private Task _schedules = Task.CompletedTask;
|
||||
private WicDecoderProvider? _wic;
|
||||
private readonly RenderNodeHost _renderNode;
|
||||
private ServerSession _server = null!;
|
||||
@@ -68,6 +70,7 @@ public sealed class AppServices : IAsyncDisposable
|
||||
_renderNode = new RenderNodeHost(StartRenderNode);
|
||||
ArchiveSetup = new EngineArchiveSetup(this);
|
||||
Sync = new SyncHost(this);
|
||||
ScheduleHost = new DesktopScheduleHost(settings, () => Database, () => Archives);
|
||||
Server = new ServerSession(settings, saveSettings, new ChronosServerApiFactory(), new DpapiTokenProtector());
|
||||
Encoders = new MediaFoundationInventory();
|
||||
Formats = new WicFormatInventory(() => _wic);
|
||||
@@ -113,8 +116,20 @@ public sealed class AppServices : IAsyncDisposable
|
||||
/// <summary>Decode tier per format on this PC and the missing codec extensions (Settings › Formats).</summary>
|
||||
public IFormatInventory Formats { get; set; }
|
||||
|
||||
/// <summary>Time between the rescans of the open archive (Settings › Archive).</summary>
|
||||
public TimeSpan ScanInterval => TimeSpan.FromMinutes(int.Clamp(Settings.ScanIntervalMinutes, 1, 24 * 60));
|
||||
/// <summary>How often an archive that was unplugged at start is looked for again, until it is back.</summary>
|
||||
public static TimeSpan ReopenInterval { get; } = TimeSpan.FromMinutes(1);
|
||||
|
||||
/// <summary>What the scheduler works with on this PC: its zone, the current archive, the system schedules.</summary>
|
||||
public DesktopScheduleHost ScheduleHost { get; }
|
||||
|
||||
/// <summary>The schedules of this PC (Jobs › Scheduled); null until they run (<see cref="SchedulerReady"/>).</summary>
|
||||
public Scheduler? Scheduler { get; private set; }
|
||||
|
||||
/// <summary>True once <see cref="Scheduler"/> runs; false when it never will (no index, no engine, it failed, the app stops).</summary>
|
||||
public Task<bool> SchedulerReady => _schedulerReady.Task;
|
||||
|
||||
/// <summary>The clock of the schedules; the capture stops it at its sample moment.</summary>
|
||||
public TimeProvider SchedulerTime { get; set; } = TimeProvider.System;
|
||||
|
||||
/// <summary>How the restore staged in Settings › Advanced went when the index opened; null when none was staged.</summary>
|
||||
public StagedRestoreResult? StagedRestore { get; private set; }
|
||||
@@ -186,13 +201,13 @@ public sealed class AppServices : IAsyncDisposable
|
||||
public void SavePreferences() => SaveSettingsAction();
|
||||
|
||||
/// <summary>
|
||||
/// The archive's rescan interval, now, and a review of the priority queue (Settings › Rendering): turned on, it may make
|
||||
/// the running job yield at once. The parallelism applies from the next sequence or job.
|
||||
/// A review of the priority queue (Settings › Rendering): turned on, it may make the running job yield at once; and a
|
||||
/// pass of the schedules, whose runs read the settings. The parallelism applies from the next sequence or job.
|
||||
/// </summary>
|
||||
public void ApplyJobSettings()
|
||||
{
|
||||
Engine?.Wake();
|
||||
if (_pollTimer is { } timer && timer.Period != ScanInterval) timer.Period = ScanInterval;
|
||||
Scheduler?.Wake();
|
||||
}
|
||||
|
||||
/// <summary>Photos the running job of this PC processes at once (Settings › Rendering › Parallelism, Auto: half the logical cores).</summary>
|
||||
@@ -216,8 +231,9 @@ public sealed class AppServices : IAsyncDisposable
|
||||
|
||||
/// <summary>
|
||||
/// Opens (or creates) the index at <paramref name="databasePath"/>, migrates it (after a restore staged in Settings ›
|
||||
/// Advanced replaced it, which needs no open index: it also recovers one that no longer opens), starts the job engine
|
||||
/// and the daily backups.
|
||||
/// Advanced replaced it, which needs no open index: it also recovers one that no longer opens), starts the job engine,
|
||||
/// then in the background reopens the archive and starts the schedules (<see cref="SchedulerReady"/>, false at once
|
||||
/// when the index or the engine does not open).
|
||||
/// </summary>
|
||||
public async Task OpenAsync(string databasePath, CancellationToken ct = default)
|
||||
{
|
||||
@@ -231,31 +247,44 @@ public sealed class AppServices : IAsyncDisposable
|
||||
{
|
||||
OpenError = ex;
|
||||
Log.Error("app", "The index could not be opened", ex);
|
||||
// No index, no schedules: Jobs › Scheduled says so instead of waiting for them.
|
||||
_schedulerReady.TrySetResult(false);
|
||||
return;
|
||||
}
|
||||
await StartJobsAsync(Database, startEngine: true, ct);
|
||||
Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems);
|
||||
Devices.Start();
|
||||
var database = Database;
|
||||
_backups = Task.Run(() => DatabaseBackups.RunDailyAsync(database, Environment.BackupDirectory, null, _stopping.Token));
|
||||
_polling = PollAsync(_stopping.Token);
|
||||
try
|
||||
{
|
||||
await StartJobsAsync(Database, startEngine: true, ct);
|
||||
Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems);
|
||||
Devices.Start();
|
||||
}
|
||||
catch
|
||||
{
|
||||
_schedulerReady.TrySetResult(false);
|
||||
throw;
|
||||
}
|
||||
_schedules = RunSchedulesAsync(_stopping.Token);
|
||||
}
|
||||
|
||||
/// <summary>Uses an already open index (capture, tests) instead of opening one; sample data keeps the engine stopped.</summary>
|
||||
/// <summary>
|
||||
/// Uses an already open index (capture, tests) instead of opening one, and starts the schedules (no archive to reopen);
|
||||
/// sample data keeps the engine stopped.
|
||||
/// </summary>
|
||||
public async Task AttachAsync(ChronosDatabase database, bool startEngine = true, CancellationToken ct = default)
|
||||
{
|
||||
Database = database;
|
||||
await StartJobsAsync(database, startEngine, ct);
|
||||
Thumbnails = new ThumbnailService(database, Settings.ThumbnailMemoryItems);
|
||||
await StartSchedulerAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>Stops polling, the render node and the engine, then closes the index. The app's exit waits for this on the UI
|
||||
/// thread, so nothing here continues on it.</summary>
|
||||
/// <summary>Stops the schedules, the render node and the engine, then closes the index. The app's exit waits for this on
|
||||
/// the UI thread, so nothing here continues on it.</summary>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _stopping.CancelAsync().ConfigureAwait(false);
|
||||
await _polling.ConfigureAwait(false);
|
||||
await _backups.ConfigureAwait(false);
|
||||
await _schedules.ConfigureAwait(false);
|
||||
_schedulerReady.TrySetResult(false);
|
||||
if (Scheduler is not null) await Scheduler.DisposeAsync().ConfigureAwait(false);
|
||||
_stopping.Dispose();
|
||||
_server.PropertyChanged -= OnServerChanged;
|
||||
await _renderNode.DisposeAsync().ConfigureAwait(false);
|
||||
@@ -268,66 +297,101 @@ public sealed class AppServices : IAsyncDisposable
|
||||
if (Database is not null) await Database.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <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.
|
||||
/// At start, off the UI thread: reopens the archive at Settings › Archive's folder (a moved one relinked, interrupted
|
||||
/// renames finished), then starts the schedules, whose first pass settles the runs missed while Chronos was closed, and
|
||||
/// runs the archive scan once, as the rescans did at start (<see cref="ScanNowAsync"/>). An archive whose archive.json is
|
||||
/// not there (an unplugged drive) is looked for every <see cref="ReopenInterval"/> until it is back, then scanned and the
|
||||
/// schedules look at once for a due run; unless the folder changed meanwhile: whatever changed it opened the new
|
||||
/// archive. The app's exit waits for this on the UI thread.
|
||||
/// </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)
|
||||
private async Task RunSchedulesAsync(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
|
||||
{
|
||||
do
|
||||
if (reopen is not null && await ReopenAsync(reopen, ct).ConfigureAwait(false)) reopen = null;
|
||||
var started = SchedulerTime.GetUtcNow();
|
||||
await StartSchedulerAsync(ct).ConfigureAwait(false);
|
||||
if (reopen is null)
|
||||
{
|
||||
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);
|
||||
}
|
||||
await ScanNowAsync(started, ct).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
using var timer = new PeriodicTimer(ReopenInterval);
|
||||
while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
if (!string.Equals(reopen, Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase)) return;
|
||||
if (!await ReopenAsync(reopen, ct).ConfigureAwait(false)) continue;
|
||||
await ScanNowAsync(null, ct).ConfigureAwait(false);
|
||||
Scheduler?.Wake();
|
||||
return;
|
||||
}
|
||||
while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false));
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
// The exit waits for this task: nothing it throws may stop the app from closing.
|
||||
Log.Error("schedules", "The archive could not be reopened or the schedules started", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_pollTimer = null;
|
||||
_schedulerReady.TrySetResult(false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs the archive scan schedule once now when it is enabled (owner review 2, R10: the archive was opened or is back),
|
||||
/// unless it ran since <paramref name="since"/> (the first pass fired it) or its scan is still pending.
|
||||
/// </summary>
|
||||
private async Task ScanNowAsync(DateTimeOffset? since, CancellationToken ct)
|
||||
{
|
||||
if (Scheduler is not { } scheduler) return;
|
||||
try
|
||||
{
|
||||
await scheduler.RunSystemNowAsync(DesktopScheduleHost.ArchiveScan, since, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
|
||||
{
|
||||
Log.Warning("schedules", "The archive scan could not be run now; its schedule runs the next one", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts <see cref="Scheduler"/> on this PC's engine: it seeds the system schedules and runs its first pass before
|
||||
/// <see cref="SchedulerReady"/> turns true. Without an engine, or when the schedules cannot be read, there is none.
|
||||
/// </summary>
|
||||
private async Task StartSchedulerAsync(CancellationToken ct)
|
||||
{
|
||||
if (Database is not { } db || Engine is not { } engine || Scheduler is not null)
|
||||
{
|
||||
_schedulerReady.TrySetResult(Scheduler is not null);
|
||||
return;
|
||||
}
|
||||
var scheduler = new Scheduler(db, engine, new SchedulerOptions { Time = SchedulerTime });
|
||||
try
|
||||
{
|
||||
await Task.Run(() => scheduler.StartAsync(ScheduleHost, ct), ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException or ArgumentException)
|
||||
{
|
||||
Log.Error("schedules", "The schedules could not be started; nothing recurring runs until the next start", ex);
|
||||
await scheduler.DisposeAsync().ConfigureAwait(false);
|
||||
_schedulerReady.TrySetResult(false);
|
||||
return;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
await scheduler.DisposeAsync().ConfigureAwait(false);
|
||||
throw;
|
||||
}
|
||||
Scheduler = scheduler;
|
||||
Log.Info("schedules", "Schedules started");
|
||||
_schedulerReady.TrySetResult(true);
|
||||
}
|
||||
|
||||
/// <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.
|
||||
@@ -385,6 +449,9 @@ public sealed class AppServices : IAsyncDisposable
|
||||
Decoder = DecoderFactory.CreateClient(_wic),
|
||||
Parallelism = () => Parallelism,
|
||||
MemoryBudget = () => ProcessingTuning.MemoryBudget(Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes),
|
||||
// The housekeeping schedule trims the cache to Settings › Storage › Cache limit (owner review 2, R10).
|
||||
CleanupSteps = [new CacheTrimStep(() => CacheStore.Folder(Environment, Settings), () => Settings.CacheLimitGb * (1L << 30))],
|
||||
BackupDirectory = Environment.BackupDirectory,
|
||||
};
|
||||
Archives = new ArchiveService(database, archive);
|
||||
Processing = new ProcessingService(database, ProcessingOptions(archive));
|
||||
|
||||
@@ -3,6 +3,7 @@ using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using Chronos.Core.Analysis.Deep;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Import;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Naming;
|
||||
@@ -96,7 +97,11 @@ public sealed class AppSettings
|
||||
/// <summary>Thumbnail long edge of new archives (also written into the open archive), BRIEF §8.5.</summary>
|
||||
public int ThumbnailLongEdge { get; set; } = 320;
|
||||
|
||||
/// <summary>Minutes between the rescans of the open archive (BRIEF §7: polling by mtime and size, no file-system watchers).</summary>
|
||||
/// <summary>
|
||||
/// Obsolete (owner review 2, R10): the former Settings › Archive › Rescan every. Nothing edits it any more; it only seeds
|
||||
/// the interval of the <c>archive-scan</c> schedule (<see cref="Jobs.DesktopScheduleHost"/>) the first time it is created,
|
||||
/// and is what Reset puts that schedule back to. The schedule's own interval is edited in Jobs › Scheduled.
|
||||
/// </summary>
|
||||
public int ScanIntervalMinutes { get; set; } = DefaultScanIntervalMinutes;
|
||||
|
||||
// ---- Import (defaults of new cards and folders; a card's own profile wins) ----
|
||||
@@ -185,6 +190,25 @@ public sealed class AppSettings
|
||||
/// <summary>"Clear done": finished jobs older than this are hidden from the Jobs list (they stay in the history).</summary>
|
||||
public DateTimeOffset? JobsClearedAt { get; set; }
|
||||
|
||||
// ---- Advanced › Logs (owner review 2, R11; applied by AppLogging) ----
|
||||
/// <summary>Least severe level written to the log files.</summary>
|
||||
public LogLevel LogLevel { get; set; } = LogLevel.Info;
|
||||
|
||||
/// <summary>Log files last written longer ago are deleted.</summary>
|
||||
public int LogRetentionDays { get; set; } = LogFileOptions.DefaultRetentionDays;
|
||||
|
||||
/// <summary>A log file this large (MB of 2²⁰ bytes) continues in a numbered one; 0 = no limit.</summary>
|
||||
public int LogMaxFileMb { get; set; } = LogFileOptions.DefaultMaxFileMb;
|
||||
|
||||
/// <summary>While the log files together are larger (MB), the oldest are deleted, never the current one; 0 = no limit.</summary>
|
||||
public int LogMaxTotalMb { get; set; } = LogFileOptions.DefaultMaxTotalMb;
|
||||
|
||||
/// <summary>One log file per UTC day or per hour.</summary>
|
||||
public LogRotation LogRotation { get; set; } = LogRotation.Daily;
|
||||
|
||||
/// <summary>MB kept from the end of each log file in the diagnostics bundle.</summary>
|
||||
public int DiagnosticsLogMb { get; set; } = AppLogging.DefaultDiagnosticsLogMb;
|
||||
|
||||
public sealed class WindowPlacement
|
||||
{
|
||||
public double Left { get; set; }
|
||||
|
||||
@@ -14,7 +14,8 @@ namespace Chronos.App.Infrastructure;
|
||||
|
||||
/// <summary>
|
||||
/// The diagnostics bundle of Settings › Advanced (BRIEF §12.8, §12.9, §22 Phase 8): an environment report, the codec
|
||||
/// and encoder inventory, the settings, the latest failed jobs and the log files, zipped into a folder the user chose.
|
||||
/// and encoder inventory, the settings, the latest failed jobs and the end of each log file (Settings › Advanced ›
|
||||
/// Diagnostics logs), zipped into a folder the user chose.
|
||||
/// Everything passes through <see cref="SecretScrubber"/> (the saved server token, passwords and keys never leave the
|
||||
/// PC) and no photo or archive file is ever included.
|
||||
/// </summary>
|
||||
@@ -31,6 +32,7 @@ public static class DiagnosticsBundle
|
||||
public static Task<string> CreateAsync(AppServices services, string folder, IEnumerable<string>? extraLines = null, CancellationToken ct = default)
|
||||
{
|
||||
var settings = services.Settings.ToJson();
|
||||
var tailBytes = AppLogging.DiagnosticsTailBytes(services.Settings);
|
||||
var report = Report(services.Environment, extraLines) + DatabaseLine(services.Database);
|
||||
return Task.Run(async () =>
|
||||
{
|
||||
@@ -47,7 +49,7 @@ public static class DiagnosticsBundle
|
||||
bundle.AddText("codecs.txt", codecs);
|
||||
bundle.AddJson("settings.json", settings);
|
||||
bundle.AddJobs("jobs-failed.json", failures);
|
||||
bundle.AddLogs(services.Environment.LogDirectory, cancellationToken: ct);
|
||||
bundle.AddLogs(services.Environment.LogDirectory, tailBytes: tailBytes, cancellationToken: ct);
|
||||
}
|
||||
File.Move(temp, path);
|
||||
return path;
|
||||
@@ -114,8 +116,15 @@ public static class DiagnosticsBundle
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>What <see cref="CacheStore.Trim"/> did: the cache's size before, the bytes and files it deleted.</summary>
|
||||
public sealed record CacheTrimResult(long Before, long Freed, int Deleted)
|
||||
{
|
||||
/// <summary>The cache's size afterwards.</summary>
|
||||
public long After => Before - Freed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The disk cache (spilled frames, thumbnails): its folder, its size and clearing it. Only a folder Chronos created
|
||||
/// The disk cache (spilled frames, thumbnails): its folder, its size, trimming and clearing it. Only a folder Chronos created
|
||||
/// (it carries a marker file) is ever emptied, so pointing the cache at a folder with user files cannot delete them.
|
||||
/// </summary>
|
||||
public static class CacheStore
|
||||
@@ -179,6 +188,69 @@ public static class CacheStore
|
||||
return freed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Brings an owned cache folder down to <paramref name="limitBytes"/> (owner review 2, R10: the housekeeping
|
||||
/// schedule's cache step): the least recently written files go first, files in use stay (a render spilling, an import
|
||||
/// staging), and so does everything under the <paramref name="keep"/> folders (relative to the cache: sets that must
|
||||
/// stay whole), which still counts towards the size. Null when the folder is not a Chronos cache folder: nothing is
|
||||
/// deleted there.
|
||||
/// </summary>
|
||||
public static CacheTrimResult? Trim(string folder, long limitBytes, IReadOnlyCollection<string>? keep = null, CancellationToken ct = default)
|
||||
{
|
||||
if (!Directory.Exists(folder)) return new CacheTrimResult(0, 0, 0);
|
||||
if (!IsOwned(folder)) return null;
|
||||
var root = new DirectoryInfo(folder);
|
||||
var kept = (keep ?? []).Select(k => Path.TrimEndingDirectorySeparator(Path.GetFullPath(Path.Combine(root.FullName, k))) + Path.DirectorySeparatorChar).ToList();
|
||||
var marker = Path.Combine(root.FullName, MarkerFile);
|
||||
var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint };
|
||||
var candidates = new List<FileInfo>();
|
||||
long size = 0;
|
||||
foreach (var file in root.EnumerateFiles("*", options))
|
||||
{
|
||||
size += file.Length;
|
||||
if (file.FullName.Equals(marker, StringComparison.OrdinalIgnoreCase)
|
||||
|| kept.Any(k => file.FullName.StartsWith(k, StringComparison.OrdinalIgnoreCase))) continue;
|
||||
candidates.Add(file);
|
||||
}
|
||||
var before = size;
|
||||
long freed = 0;
|
||||
var deleted = 0;
|
||||
foreach (var file in candidates.OrderBy(f => f.LastWriteTimeUtc))
|
||||
{
|
||||
if (size <= limitBytes) break;
|
||||
ct.ThrowIfCancellationRequested();
|
||||
// Read before the delete: a deleted file has no length.
|
||||
var length = file.Length;
|
||||
if (!TryDeleteUnused(file)) continue;
|
||||
size -= length;
|
||||
freed += length;
|
||||
deleted++;
|
||||
}
|
||||
return new CacheTrimResult(before, freed, deleted);
|
||||
}
|
||||
|
||||
/// <summary>Deletes a file nobody has open; false for one in use or protected.</summary>
|
||||
private static bool TryDeleteUnused(FileInfo file)
|
||||
{
|
||||
try
|
||||
{
|
||||
// A file open anywhere else (written, read or mapped) cannot be opened exclusively: it stays.
|
||||
using (new FileStream(file.FullName, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
|
||||
{
|
||||
}
|
||||
file.Delete();
|
||||
return true;
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static long TryDelete(FileInfo file)
|
||||
{
|
||||
try
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
using System.IO;
|
||||
using Chronos.App.Archiving;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol;
|
||||
|
||||
namespace Chronos.App.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// The desktop's <see cref="IScheduleHost"/> (owner review 2, R10). Times are the PC's; schedules work on the archive at
|
||||
/// Settings › Archive's folder (<see cref="CurrentArchive"/>), which first takes the settings another process sharing it
|
||||
/// wrote into its archive.json, as the rescans before it did, and counts as none while it is offline (an unplugged
|
||||
/// drive). The system schedules stand for the timers the desktop used to run out of sight: the archive scan (its interval
|
||||
/// carried over from the former Settings › Archive › Rescan every, <see cref="AppSettings.ScanIntervalMinutes"/>, once:
|
||||
/// a row that exists keeps the user's edits), the daily index backup, and the housekeeping clean-up at 04:00 (job history,
|
||||
/// cache trim). Scans give what they find a deep analysis as Settings › Analysis › After a scan says at each run
|
||||
/// (<see cref="DeepAnalysisAfterScan"/>), like the scans started by hand. Thread-safe: the scheduler calls it from its loop.
|
||||
/// </summary>
|
||||
public sealed class DesktopScheduleHost(AppSettings settings, Func<ChronosDatabase?> database, Func<ArchiveService?> archives) : IScheduleHost
|
||||
{
|
||||
/// <summary>Incremental scan of the archive, every <see cref="AppSettings.ScanIntervalMinutes"/> (10) minutes, no catch-up.</summary>
|
||||
public const string ArchiveScan = "archive-scan";
|
||||
|
||||
/// <summary>
|
||||
/// Copy of the index into the backups folder, every day, with catch-up (it replaced the daily backup loop). Seeded due
|
||||
/// at once when the newest copy is a day old, as that loop made one at start.
|
||||
/// </summary>
|
||||
public const string IndexBackup = DatabaseBackups.ScheduleKey;
|
||||
|
||||
/// <summary>Clean-up of the job history and the cache, daily at 04:00, with catch-up.</summary>
|
||||
public const string Housekeeping = "housekeeping";
|
||||
|
||||
/// <summary>When the housekeeping runs.</summary>
|
||||
public static readonly TimeOnly HousekeepingTime = new(4, 0);
|
||||
|
||||
/// <summary>The PC's zone; tests set another.</summary>
|
||||
public TimeZoneInfo TimeZone { get; init; } = TimeZoneInfo.Local;
|
||||
|
||||
public IReadOnlyList<SystemSchedule> SystemSchedules =>
|
||||
[
|
||||
new(ArchiveScan, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(ScanMinutes(settings), RecurrenceUnit.Minutes),
|
||||
new ScheduleParametersDto(Force: false), CatchUp: false),
|
||||
new(IndexBackup, "Index backup", ScheduleActions.Backup, ScheduleRecurrence.Interval(1, RecurrenceUnit.Days),
|
||||
new ScheduleParametersDto(Keep: DatabaseBackups.Keep),
|
||||
LastDone: database() is { } db ? DatabaseBackups.Newest(db, archives()?.BackupDirectory) : null),
|
||||
new(Housekeeping, "Housekeeping", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(HousekeepingTime),
|
||||
new ScheduleParametersDto(Steps: [Chronos.Data.Housekeeping.CleanupSteps.JobHistory, CacheTrimStep.StepName],
|
||||
OlderThanDays: Chronos.Data.Housekeeping.CleanupSteps.DefaultHistoryDays)),
|
||||
];
|
||||
|
||||
public IReadOnlyList<string> CleanupSteps => archives()?.CleanupSteps.Select(s => s.Name).ToList() ?? [];
|
||||
|
||||
/// <summary>
|
||||
/// The interval the scan schedule is seeded with (and reset to): the former rescan setting, within what an interval
|
||||
/// accepts (5 minutes to a day).
|
||||
/// </summary>
|
||||
public static int ScanMinutes(AppSettings settings)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(settings);
|
||||
return int.Clamp(settings.ScanIntervalMinutes, ScheduleRecurrence.MinMinutes, ScheduleRecurrence.MaxMinutes);
|
||||
}
|
||||
|
||||
public async ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (database() is not { } db || archives() is not { } service) return null;
|
||||
var archive = CurrentArchive.Pick(await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false), settings.LastArchivePath);
|
||||
if (archive is null || ArchiveService.GetAvailability(archive) == ArchiveAvailability.Offline) return null;
|
||||
try
|
||||
{
|
||||
await service.RefreshSettingsAsync(archive.Id, cancellationToken).ConfigureAwait(false);
|
||||
return await db.Archives.GetAsync(archive.Id, cancellationToken).ConfigureAwait(false) ?? archive;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or NewerFormatException)
|
||||
{
|
||||
// The settings as last read: the run still works on the archive, the next one reads them again.
|
||||
Log.Warning("schedules", $"The settings of {archive.RootPath} could not be read again", ex);
|
||||
return archive;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The desktop runs every action its engine has a handler for.</summary>
|
||||
public string? Unavailable(string action) => null;
|
||||
|
||||
/// <summary>Settings › Analysis › After a scan, read at every run: a scheduled scan follows it as a scan started by hand does.</summary>
|
||||
public bool DeepAnalysisAfterScan => settings.DeepAnalysisAfterScan;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The desktop's clean-up step <c>cache-trim</c> (owner review 2, R10): brings the cache folder down to Settings › Storage ›
|
||||
/// Cache limit, oldest files first, skipping files in use (<see cref="CacheStore.Trim"/>). The proxies of server sequences
|
||||
/// (complete sets the sync keeps), the render node's folder (it trims its own downloads to the same limit) and the copies an
|
||||
/// import to the server stages are never trimmed; Settings › Storage › Clear still empties everything.
|
||||
/// </summary>
|
||||
public sealed class CacheTrimStep(Func<string> folder, Func<long> limitBytes) : ICleanupStep
|
||||
{
|
||||
public const string StepName = "cache-trim";
|
||||
|
||||
/// <summary>Folders of the cache the trim leaves whole.</summary>
|
||||
public static IReadOnlyList<string> Kept { get; } = ["proxies", "render-node", "server-import"];
|
||||
|
||||
public string Name => StepName;
|
||||
|
||||
public Task<string> RunAsync(CleanupContext context, CleanupParameters parameters)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(context);
|
||||
var limit = limitBytes();
|
||||
return Task.Run(() =>
|
||||
{
|
||||
var result = CacheStore.Trim(folder(), limit, Kept, context.Cancellation);
|
||||
if (result is null) return Loc.L("Jobs.Log.CacheNotOwned");
|
||||
return result.Deleted == 0
|
||||
? Loc.L("Jobs.Log.CacheKept", Gigabytes(result.After), Gigabytes(limit))
|
||||
: Loc.L("Jobs.Log.CacheTrimmed", Gigabytes(result.After), Gigabytes(limit), Gigabytes(result.Freed));
|
||||
}, context.Cancellation);
|
||||
}
|
||||
|
||||
/// <summary>"12.4 GB" in the binary gigabytes of Settings › Storage › Cache limit.</summary>
|
||||
private static string Gigabytes(long bytes) => Loc.L("Common.Size.GB", (bytes / (double)(1L << 30)).ToString("0.#", Loc.Culture));
|
||||
}
|
||||
@@ -13,9 +13,10 @@ public enum JobNotice
|
||||
/// <summary>
|
||||
/// Which job endings raise a toast (BRIEF §12.1 "toasts for job completion"): the long operations the user asked for
|
||||
/// end with one toast, whichever screen started them. Background work (thumbnails, proxies, light analysis, the
|
||||
/// analysis queued after an import) and scans (the archive is rescanned every 10 minutes) end silently; an import
|
||||
/// analysis queued after an import) and scans (the archive scan schedule runs every 10 minutes) end silently; an import
|
||||
/// has its own toast when it ends well, and a download shows on its Library card and Server row. Every other failure
|
||||
/// is said. Cancelled jobs were stopped on purpose.
|
||||
/// is said. A schedule's background run (owner review 2, R10: the index backup, a weekly verify) is said only when it
|
||||
/// fails, unless it is upkeep the next run repeats. Cancelled jobs were stopped on purpose.
|
||||
/// </summary>
|
||||
public static class JobNotices
|
||||
{
|
||||
@@ -26,7 +27,9 @@ public static class JobNotices
|
||||
public static JobNotice For(JobState? before, Job job)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
if (before is JobState.Done or JobState.Failed or JobState.Cancelled || job.Priority == JobPriority.Background) return JobNotice.None;
|
||||
if (before is JobState.Done or JobState.Failed or JobState.Cancelled) return JobNotice.None;
|
||||
if (job.Priority == JobPriority.Background)
|
||||
return job.ScheduleId is not null && job.State == JobState.Failed && !IsUpkeep(job.Kind) ? JobNotice.Failed : JobNotice.None;
|
||||
return job.State switch
|
||||
{
|
||||
JobState.Done when Announces(job.Kind) => JobNotice.Done,
|
||||
@@ -39,9 +42,12 @@ public static class JobNotices
|
||||
kind is JobKind.Render or JobKind.DeepAnalyse or JobKind.Verify or JobKind.Rebuild or JobKind.Maintenance or JobKind.UploadCommit
|
||||
or JobKind.Move or JobKind.Adopt;
|
||||
|
||||
/// <summary>Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing.</summary>
|
||||
/// <summary>
|
||||
/// Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing.
|
||||
/// Clean-ups too: the housekeeping schedule runs them again (a failed index backup is said).
|
||||
/// </summary>
|
||||
private static bool IsUpkeep(JobKind kind) =>
|
||||
kind is JobKind.Scan or JobKind.Thumbs or JobKind.Proxies or JobKind.LightAnalyse;
|
||||
kind is JobKind.Scan or JobKind.Thumbs or JobKind.Proxies or JobKind.LightAnalyse or JobKind.Cleanup;
|
||||
}
|
||||
|
||||
/// <summary>Endings said in one toast: one job, or several of a batch.</summary>
|
||||
|
||||
@@ -36,6 +36,9 @@ public sealed class JobRowViewModel : ObservableObject
|
||||
|
||||
public string Target => _entry.Job.TargetLabel ?? string.Empty;
|
||||
|
||||
/// <summary>A schedule queued the job (owner review 2, R10): the row shows a "Scheduled" pill.</summary>
|
||||
public bool IsScheduled => _entry.Job.ScheduleId is not null;
|
||||
|
||||
/// <summary>"Render · Harbour sunset → 4K HEVC": the row's name for screen readers.</summary>
|
||||
public string AccessibleName => JobText.Name(_entry.Job);
|
||||
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
|
||||
xmlns:v="clr-namespace:Chronos.Ui.Visuals;assembly=Chronos.Ui"
|
||||
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
|
||||
xmlns:j="clr-namespace:Chronos.App.Jobs"
|
||||
xmlns:infra="clr-namespace:Chronos.App.Infrastructure">
|
||||
<!-- The in-window schedule editor of Jobs › Scheduled (owner review 2, R10), with the dialog kit of the Archive screen. -->
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="pack://application:,,,/Chronos;component/Archive/ArchiveDialogs.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
|
||||
<!-- One editor row: the label column grows with the longest label (DESIGN §2), the controls take the rest. -->
|
||||
<Style x:Key="Grid.EditorRow" TargetType="Grid">
|
||||
<Setter Property="Margin" Value="0,0,0,10" />
|
||||
<Setter Property="MinHeight" Value="32" />
|
||||
</Style>
|
||||
|
||||
<!-- A choice of the action list: one this PC cannot run is disabled, its reason in the tooltip. -->
|
||||
<Style x:Key="ComboBoxItem.Action" TargetType="ComboBoxItem" BasedOn="{StaticResource {x:Type ComboBoxItem}}">
|
||||
<Setter Property="IsEnabled" Value="{Binding IsAvailable}" />
|
||||
<Setter Property="ToolTip" Value="{Binding ToolTip}" />
|
||||
<Setter Property="ToolTipService.ShowOnDisabled" Value="True" />
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding Label}" />
|
||||
<Setter Property="AutomationProperties.HelpText" Value="{Binding ToolTip}" />
|
||||
</Style>
|
||||
|
||||
<!-- A day of the week: a 44 px toggle, its full name in the tooltip. -->
|
||||
<Style x:Key="ToggleButton.Day" TargetType="ToggleButton" BasedOn="{StaticResource {x:Type ToggleButton}}">
|
||||
<Setter Property="MinWidth" Value="44" />
|
||||
<Setter Property="Padding" Value="8,0" />
|
||||
<Setter Property="Margin" Value="0,0,6,6" />
|
||||
</Style>
|
||||
|
||||
<DataTemplate DataType="{x:Type j:ScheduleEditorViewModel}">
|
||||
<Border Style="{StaticResource Border.Dialog}" Width="600" MaxHeight="720">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
|
||||
<ScrollViewer Grid.Row="1" Margin="0,14,0,0" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
|
||||
<StackPanel Grid.IsSharedSizeScope="True">
|
||||
<!-- Name: a system schedule keeps its own. -->
|
||||
<Grid Style="{StaticResource Grid.EditorRow}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Name}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<TextBox Grid.Column="1" Text="{Binding Name.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" ToolTip="{Binding Name.ToolTip}"
|
||||
MaxLength="100" AutomationProperties.Name="{l:Loc Jobs.Editor.Name}"
|
||||
Visibility="{Binding IsSystem, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding SystemName}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" ToolTip="{Binding Name.ToolTip}"
|
||||
Visibility="{Binding IsSystem, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Action}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<ComboBox Grid.Column="1" Width="240" HorizontalAlignment="Left" ItemsSource="{Binding ActionOptions}" SelectedItem="{Binding SelectedAction}"
|
||||
DisplayMemberPath="Label" ItemContainerStyle="{StaticResource ComboBoxItem.Action}" ToolTip="{Binding ActionToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" IsEnabled="{Binding CanChangeAction}"
|
||||
AutomationProperties.Name="{l:Loc Jobs.Editor.Action}" />
|
||||
</Grid>
|
||||
|
||||
<!-- When: the kind, then its own fields. -->
|
||||
<Grid Style="{StaticResource Grid.EditorRow}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Repeat}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<v:SegmentedControl Grid.Column="1" HorizontalAlignment="Left" SelectedIndex="{Binding KindIndex}" AutomationProperties.Name="{l:Loc Jobs.Editor.Repeat}">
|
||||
<v:SegmentedItem Content="{l:Loc Jobs.Editor.Every}" ToolTip="{l:Loc Tooltips.Jobs.Editor.KindEvery}" AutomationProperties.Name="{l:Loc Jobs.Editor.Every}" />
|
||||
<v:SegmentedItem Content="{l:Loc Jobs.Editor.Daily}" ToolTip="{l:Loc Tooltips.Jobs.Editor.KindDaily}" AutomationProperties.Name="{l:Loc Jobs.Editor.Daily}" />
|
||||
<v:SegmentedItem Content="{l:Loc Jobs.Editor.Weekly}" ToolTip="{l:Loc Tooltips.Jobs.Editor.KindWeekly}" AutomationProperties.Name="{l:Loc Jobs.Editor.Weekly}" />
|
||||
<v:SegmentedItem Content="{l:Loc Jobs.Editor.Monthly}" ToolTip="{l:Loc Tooltips.Jobs.Editor.KindMonthly}" AutomationProperties.Name="{l:Loc Jobs.Editor.Monthly}" />
|
||||
</v:SegmentedControl>
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding IsEvery, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Interval}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal">
|
||||
<TextBox Style="{StaticResource TextBox.Number}" Text="{Binding Every.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
ToolTip="{Binding Every.ToolTip}" AutomationProperties.Name="{l:Loc Jobs.Editor.Interval}" />
|
||||
<ComboBox Width="120" Margin="8,0,0,0" ItemsSource="{Binding Units}" SelectedItem="{Binding SelectedUnit}" DisplayMemberPath="Label"
|
||||
ToolTip="{l:Loc Tooltips.Jobs.Editor.Unit}" AutomationProperties.Name="{l:Loc Jobs.Editor.Unit}" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding IsWeekly, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Days}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Top" Margin="0,7,14,0" />
|
||||
<ItemsControl Grid.Column="1" ItemsSource="{Binding Days}" Focusable="False" AutomationProperties.Name="{l:Loc Jobs.Editor.Days}">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<WrapPanel />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<ToggleButton Style="{StaticResource ToggleButton.Day}" Content="{Binding Label}" IsChecked="{Binding IsChecked}" ToolTip="{Binding ToolTip}"
|
||||
AutomationProperties.Name="{Binding ToolTip}" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding IsMonthly, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.DayOfMonth}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<TextBox Grid.Column="1" Style="{StaticResource TextBox.Number}" HorizontalAlignment="Left"
|
||||
Text="{Binding DayOfMonth.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" ToolTip="{Binding DayOfMonth.ToolTip}"
|
||||
AutomationProperties.Name="{l:Loc Jobs.Editor.DayOfMonth}" />
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding HasTime, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Time}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<!-- Hours and minutes stay in their order in every language. -->
|
||||
<TextBox Grid.Column="1" Style="{StaticResource TextBox.Number}" HorizontalAlignment="Left" FlowDirection="LeftToRight"
|
||||
Text="{Binding Time.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" ToolTip="{Binding Time.ToolTip}"
|
||||
AutomationProperties.Name="{l:Loc Jobs.Editor.Time}" />
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<!-- The recurrence as the table will show it. -->
|
||||
<TextBlock Grid.Column="1" Text="{Binding WhenText}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis"
|
||||
ToolTip="{l:Loc Tooltips.Jobs.Editor.When}" AutomationProperties.LiveSetting="Polite" infra:LiveRegion.Text="{Binding WhenText}" />
|
||||
</Grid>
|
||||
|
||||
<!-- The action's parameters. -->
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding ShowsOlderThan, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{Binding OlderThanLabel}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal">
|
||||
<TextBox Style="{StaticResource TextBox.Number}" Text="{Binding OlderThan.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
ToolTip="{Binding OlderThan.ToolTip}" AutomationProperties.Name="{Binding OlderThanLabel}" />
|
||||
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Jobs.Editor.DaysUnit}" Margin="8,0,0,0" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding ShowsPercent, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Percent}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal">
|
||||
<TextBox Style="{StaticResource TextBox.Number}" Text="{Binding Percent.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
ToolTip="{Binding Percent.ToolTip}" AutomationProperties.Name="{l:Loc Jobs.Editor.Percent}" />
|
||||
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Jobs.Editor.PercentUnit}" Margin="8,0,0,0" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding ShowsKeep, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Keep}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<TextBox Grid.Column="1" Style="{StaticResource TextBox.Number}" HorizontalAlignment="Left"
|
||||
Text="{Binding Keep.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" ToolTip="{Binding Keep.ToolTip}"
|
||||
AutomationProperties.Name="{l:Loc Jobs.Editor.Keep}" />
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding ShowsSteps, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Steps}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Top" Margin="0,4,14,0" />
|
||||
<ItemsControl Grid.Column="1" ItemsSource="{Binding Steps}" Focusable="False" AutomationProperties.Name="{l:Loc Jobs.Editor.Steps}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<CheckBox Content="{Binding Label}" IsChecked="{Binding IsChecked}" ToolTip="{Binding ToolTip}" Margin="0,0,0,6" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding HasSwitches, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<WrapPanel Grid.Column="1" VerticalAlignment="Center">
|
||||
<CheckBox Content="{Binding ForceLabel}" IsChecked="{Binding Force}" ToolTip="{Binding ForceToolTip}" Margin="0,0,20,6"
|
||||
Visibility="{Binding ShowsForce, Converter={StaticResource BoolToVisibility}}" />
|
||||
<CheckBox Content="{l:Loc Jobs.Editor.Deep}" IsChecked="{Binding Deep}" ToolTip="{Binding DeepToolTip}" Margin="0,0,20,6"
|
||||
Visibility="{Binding ShowsDeep, Converter={StaticResource BoolToVisibility}}" />
|
||||
<CheckBox Content="{l:Loc Jobs.Editor.DryRun}" IsChecked="{Binding DryRun}" ToolTip="{l:Loc Tooltips.Jobs.Editor.DryRun}" Margin="0,0,20,6"
|
||||
Visibility="{Binding ShowsDryRun, Converter={StaticResource BoolToVisibility}}" />
|
||||
</WrapPanel>
|
||||
</Grid>
|
||||
|
||||
<!-- How its jobs run. -->
|
||||
<Grid Style="{StaticResource Grid.EditorRow}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Jobs.Editor.Priority}" Style="{StaticResource Text.DialogLabel}" />
|
||||
<ComboBox Grid.Column="1" Width="160" HorizontalAlignment="Left" ItemsSource="{Binding Priorities}" SelectedItem="{Binding SelectedPriority}"
|
||||
DisplayMemberPath="Label" ToolTip="{l:Loc Tooltips.Jobs.Editor.Priority}" AutomationProperties.Name="{l:Loc Jobs.Editor.Priority}" />
|
||||
</Grid>
|
||||
<Grid Style="{StaticResource Grid.EditorRow}" Margin="0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<WrapPanel Grid.Column="1" VerticalAlignment="Center">
|
||||
<CheckBox Content="{l:Loc Jobs.Editor.CatchUp}" IsChecked="{Binding CatchUp}" ToolTip="{l:Loc Tooltips.Jobs.Editor.CatchUp}" Margin="0,0,20,0" />
|
||||
<CheckBox Content="{l:Loc Jobs.Editor.Enabled}" IsChecked="{Binding Enabled}" ToolTip="{l:Loc Tooltips.Jobs.Editor.Enabled}" />
|
||||
</WrapPanel>
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
<DockPanel Grid.Row="2" Margin="0,18,0,0">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Jobs.Editor.Save}" Command="{Binding SaveCommand}"
|
||||
ToolTip="{Binding SaveToolTip}" ToolTipService.ShowOnDisabled="True" MinWidth="96" Margin="8,0,0,0" />
|
||||
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{l:Loc Tooltips.Jobs.Editor.Cancel}" IsCancel="True"
|
||||
MinWidth="96" />
|
||||
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" HorizontalAlignment="Left" />
|
||||
</DockPanel>
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ResourceDictionary>
|
||||
@@ -0,0 +1,582 @@
|
||||
using System.Collections;
|
||||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Jobs;
|
||||
|
||||
/// <summary>A text field of the schedule editor: checked as it is typed, its problem in the tooltip (DESIGN §4 inputs).</summary>
|
||||
public sealed class ScheduleField : ObservableObject, INotifyDataErrorInfo
|
||||
{
|
||||
private readonly Func<string, string?> _validate;
|
||||
private readonly Func<string> _toolTip;
|
||||
private string _text;
|
||||
private string? _error;
|
||||
|
||||
public ScheduleField(string text, Func<string, string?> validate, Func<string> toolTip)
|
||||
{
|
||||
_text = text;
|
||||
_validate = validate;
|
||||
_toolTip = toolTip;
|
||||
_error = validate(text);
|
||||
}
|
||||
|
||||
/// <summary>The text changed, or its problem did.</summary>
|
||||
public event Action? Changed;
|
||||
|
||||
public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged;
|
||||
|
||||
public string Text
|
||||
{
|
||||
get => _text;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _text, value ?? string.Empty)) return;
|
||||
Validate();
|
||||
Changed?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The problem of the text; null when it is valid.</summary>
|
||||
public string? Error => _error;
|
||||
|
||||
public bool HasErrors => _error is not null;
|
||||
|
||||
/// <summary>The problem while invalid, otherwise what the field is for.</summary>
|
||||
public string ToolTip => _error ?? _toolTip();
|
||||
|
||||
public IEnumerable GetErrors(string? propertyName) =>
|
||||
_error is not null && propertyName is null or "" or nameof(Text) ? new[] { _error } : Array.Empty<string>();
|
||||
|
||||
/// <summary>Checks the text again (a rule it depends on changed: the interval's unit).</summary>
|
||||
public void Validate()
|
||||
{
|
||||
var error = _validate(_text);
|
||||
if (error == _error) return;
|
||||
_error = error;
|
||||
OnPropertyChanged(nameof(Error));
|
||||
OnPropertyChanged(nameof(HasErrors));
|
||||
OnPropertyChanged(nameof(ToolTip));
|
||||
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Text)));
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
internal void Refresh()
|
||||
{
|
||||
_error = _validate(_text);
|
||||
OnPropertyChanged(string.Empty);
|
||||
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Text)));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An action of the editor's list: unavailable ones are shown disabled, their reason in the tooltip.</summary>
|
||||
public sealed record ScheduleActionOption(string Name, bool IsAvailable, string? Reason)
|
||||
{
|
||||
public string Label => ScheduleText.Action(Name);
|
||||
|
||||
public string ToolTip => IsAvailable ? ScheduleText.ActionToolTip(Name) : ScheduleText.Unavailable(Reason);
|
||||
|
||||
public override string ToString() => Label;
|
||||
}
|
||||
|
||||
/// <summary>A checkable choice of the editor (a day of the week, a clean-up step).</summary>
|
||||
public sealed class ScheduleChoice<T>(T value, Func<string> label, Func<string> toolTip, bool isChecked, Action changed) : ObservableObject
|
||||
{
|
||||
private bool _isChecked = isChecked;
|
||||
|
||||
public T Value { get; } = value;
|
||||
|
||||
public string Label => label();
|
||||
|
||||
public string ToolTip => toolTip();
|
||||
|
||||
public bool IsChecked
|
||||
{
|
||||
get => _isChecked;
|
||||
set
|
||||
{
|
||||
if (Set(ref _isChecked, value)) changed();
|
||||
}
|
||||
}
|
||||
|
||||
internal void Refresh() => OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The in-window editor of a schedule (owner review 2, R10): its name (a system schedule keeps its own), its action (those
|
||||
/// this PC cannot run are disabled, their reason in the tooltip), when it runs (every n minutes, hours or days; daily,
|
||||
/// weekly or monthly at a time of this PC's zone), the action's parameters, the priority of its jobs, catch-up and on/off.
|
||||
/// Every field is checked as it is typed with the scheduler's own limits; Save stays off while one is invalid and its
|
||||
/// tooltip names the first problem. One primary action, one way out (Cancel, Esc).
|
||||
/// </summary>
|
||||
public sealed class ScheduleEditorViewModel : LocalizedViewModel
|
||||
{
|
||||
private readonly SchedulesViewModel _owner;
|
||||
private readonly ScheduleDto? _schedule;
|
||||
private ScheduleActionOption _action;
|
||||
private int _kindIndex;
|
||||
private SettingsOption<RecurrenceUnit> _unit;
|
||||
private SettingsOption<JobPriority> _priority;
|
||||
private bool _catchUp;
|
||||
private bool _enabled;
|
||||
private bool _force;
|
||||
private bool _deep;
|
||||
private bool _dryRun;
|
||||
private bool _isBusy;
|
||||
private string? _errorText;
|
||||
private string? _errorToolTip;
|
||||
private IReadOnlyList<ScheduleChoice<string>> _steps = [];
|
||||
|
||||
internal ScheduleEditorViewModel(SchedulesViewModel owner, ScheduleDto? schedule)
|
||||
{
|
||||
_owner = owner;
|
||||
_schedule = schedule;
|
||||
ActionOptions = BuildActionOptions();
|
||||
_action = schedule is not null
|
||||
? ActionOptions.FirstOrDefault(o => o.Name == schedule.Action) ?? new ScheduleActionOption(schedule.Action, false, null)
|
||||
: ActionOptions.FirstOrDefault(o => o.IsAvailable) ?? ActionOptions[0];
|
||||
|
||||
Name = new ScheduleField(schedule is null ? string.Empty : schedule.Name, ValidateName, () => Loc.L(IsSystem ? "Tooltips.Jobs.Editor.SystemName" : "Tooltips.Jobs.Editor.Name"));
|
||||
|
||||
// When: the stored recurrence, or every day at 03:00 for a new schedule.
|
||||
var recurrence = ScheduleMapping.FromDto(schedule?.Recurrence) ?? ScheduleRecurrence.DailyAt(new TimeOnly(3, 0));
|
||||
_kindIndex = (int)recurrence.Kind;
|
||||
Units = BuildUnits();
|
||||
_unit = Units.First(u => u.Value == (recurrence.Kind == RecurrenceKind.Every ? recurrence.Unit : RecurrenceUnit.Hours));
|
||||
Every = new ScheduleField(Number(recurrence.Kind == RecurrenceKind.Every ? recurrence.Every : 6), ValidateEvery, () => Loc.L("Tooltips.Jobs.Editor.Every"));
|
||||
Time = new ScheduleField(recurrence.Time.ToString("HH:mm", CultureInfo.InvariantCulture), ValidateTime, () => Loc.L("Tooltips.Jobs.Editor.Time"));
|
||||
var weekly = recurrence.Kind == RecurrenceKind.Weekly ? recurrence.Days : [DayOfWeek.Monday];
|
||||
var first = Loc.Culture.DateTimeFormat.FirstDayOfWeek;
|
||||
Days = [.. Enumerable.Range(0, 7).Select(i => (DayOfWeek)(((int)first + i) % 7)).Select(d =>
|
||||
new ScheduleChoice<DayOfWeek>(d, () => ScheduleText.DayShort(d), () => ScheduleText.DayLong(d), weekly.Contains(d), OnChanged))];
|
||||
DayOfMonth = new ScheduleField(Number(recurrence.Kind == RecurrenceKind.Monthly ? recurrence.DayOfMonth : 1), ValidateDayOfMonth,
|
||||
() => Loc.L("Tooltips.Jobs.Editor.DayOfMonth"));
|
||||
|
||||
OlderThan = new ScheduleField(string.Empty, v => ValidateNumber(v, 0, ScheduleActions.MaxDays), () => Loc.L(IsVerify ? "Tooltips.Jobs.Editor.Unverified" : "Tooltips.Jobs.Editor.OlderThan"));
|
||||
Percent = new ScheduleField(string.Empty, v => ValidateNumber(v, 1, 100), () => Loc.L("Tooltips.Jobs.Editor.Percent"));
|
||||
Keep = new ScheduleField(string.Empty, v => ValidateNumber(v, 1, 100), () => Loc.L("Tooltips.Jobs.Editor.Keep"));
|
||||
LoadParameters(schedule?.Parameters ?? ScheduleActions.Defaults(_action.Name));
|
||||
|
||||
Priorities = BuildPriorities();
|
||||
var priority = schedule is not null && JobWire.TryParsePriority(schedule.Priority, out var stored) ? stored : JobPriority.Background;
|
||||
_priority = Priorities.First(p => p.Value == priority);
|
||||
_catchUp = schedule?.CatchUp ?? true;
|
||||
_enabled = schedule?.Enabled ?? true;
|
||||
|
||||
foreach (var field in new[] { Name, Every, Time, DayOfMonth, OlderThan, Percent, Keep }) field.Changed += OnChanged;
|
||||
SaveCommand = new AsyncRelayCommand(SaveAsync, () => !_isBusy && Problem() is null);
|
||||
CloseCommand = new RelayCommand(() => _owner.CloseEditor(this), () => !_isBusy);
|
||||
}
|
||||
|
||||
/// <summary>The schedule edited; null for a new one.</summary>
|
||||
public Guid? ScheduleId => _schedule?.Id;
|
||||
|
||||
public bool IsNew => _schedule is null;
|
||||
|
||||
/// <summary>A system schedule keeps its name and action.</summary>
|
||||
public bool IsSystem => _schedule?.SystemKey is not null;
|
||||
|
||||
public string Heading => _schedule is null ? Loc.L("Jobs.Schedule.New") : Loc.L("Jobs.Editor.Heading", ScheduleText.Name(_schedule));
|
||||
|
||||
public ScheduleField Name { get; }
|
||||
|
||||
/// <summary>The name shown for a system schedule, which is not edited.</summary>
|
||||
public string SystemName => _schedule is null ? string.Empty : ScheduleText.Name(_schedule);
|
||||
|
||||
/// <summary>Every action, with whether this PC runs it as last read; built again when that or the UI language changes.</summary>
|
||||
public IReadOnlyList<ScheduleActionOption> ActionOptions { get; private set; }
|
||||
|
||||
public ScheduleActionOption SelectedAction
|
||||
{
|
||||
get => _action;
|
||||
set
|
||||
{
|
||||
if (value is null || !value.IsAvailable || IsSystem || !Set(ref _action, value)) return;
|
||||
// Another action starts from its own defaults, as the scheduler does.
|
||||
LoadParameters(ScheduleActions.Defaults(value.Name));
|
||||
OnPropertyChanged(string.Empty);
|
||||
OnChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public string ActionToolTip => IsSystem ? Loc.L("Tooltips.Jobs.Editor.SystemAction") : _action.ToolTip;
|
||||
|
||||
/// <summary>The action can be chosen (not for a system schedule).</summary>
|
||||
public bool CanChangeAction => !IsSystem;
|
||||
|
||||
// ---------------- When ----------------
|
||||
|
||||
/// <summary>0 every, 1 daily, 2 weekly, 3 monthly (the segmented control's index; <see cref="RecurrenceKind"/> order).</summary>
|
||||
public int KindIndex
|
||||
{
|
||||
get => _kindIndex;
|
||||
set
|
||||
{
|
||||
if (value is < 0 or > 3 || !Set(ref _kindIndex, value)) return;
|
||||
OnPropertyChanged(nameof(IsEvery));
|
||||
OnPropertyChanged(nameof(HasTime));
|
||||
OnPropertyChanged(nameof(IsWeekly));
|
||||
OnPropertyChanged(nameof(IsMonthly));
|
||||
OnChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public RecurrenceKind Kind => (RecurrenceKind)_kindIndex;
|
||||
|
||||
public bool IsEvery => Kind == RecurrenceKind.Every;
|
||||
public bool HasTime => Kind != RecurrenceKind.Every;
|
||||
public bool IsWeekly => Kind == RecurrenceKind.Weekly;
|
||||
public bool IsMonthly => Kind == RecurrenceKind.Monthly;
|
||||
|
||||
public ScheduleField Every { get; }
|
||||
|
||||
public IReadOnlyList<SettingsOption<RecurrenceUnit>> Units { get; private set; }
|
||||
|
||||
public SettingsOption<RecurrenceUnit> SelectedUnit
|
||||
{
|
||||
get => _unit;
|
||||
set
|
||||
{
|
||||
if (value is null || !Set(ref _unit, value)) return;
|
||||
Every.Validate();
|
||||
OnChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public ScheduleField Time { get; }
|
||||
|
||||
/// <summary>The days of a weekly schedule, from the first day of the UI language's week.</summary>
|
||||
public IReadOnlyList<ScheduleChoice<DayOfWeek>> Days { get; }
|
||||
|
||||
public ScheduleField DayOfMonth { get; }
|
||||
|
||||
/// <summary>"Daily at 03:00": the recurrence as the table will show it; "—" while a field is invalid.</summary>
|
||||
public string WhenText => Recurrence() is { } recurrence ? ScheduleText.When(recurrence) : "—";
|
||||
|
||||
// ---------------- Parameters ----------------
|
||||
|
||||
public bool ShowsForce => _action.Name is ScheduleActions.Scan or ScheduleActions.Thumbnails or ScheduleActions.Proxies;
|
||||
/// <summary>Analysis only: a scan's deep analysis follows Settings › Analysis › After a scan at every run.</summary>
|
||||
public bool ShowsDeep => _action.Name == ScheduleActions.Analysis;
|
||||
public bool ShowsOlderThan => _action.Name is ScheduleActions.Verify or ScheduleActions.Cleanup;
|
||||
public bool ShowsPercent => _action.Name == ScheduleActions.Verify;
|
||||
public bool ShowsDryRun => _action.Name == ScheduleActions.Maintenance;
|
||||
public bool ShowsKeep => _action.Name == ScheduleActions.Backup;
|
||||
public bool ShowsSteps => _action.Name == ScheduleActions.Cleanup;
|
||||
|
||||
/// <summary>The action has on/off parameters (full scan, deep analysis, report only), shown together on one row.</summary>
|
||||
public bool HasSwitches => ShowsForce || ShowsDeep || ShowsDryRun;
|
||||
|
||||
public bool Force
|
||||
{
|
||||
get => _force;
|
||||
set => Set(ref _force, value);
|
||||
}
|
||||
|
||||
public string ForceLabel => Loc.L(_action.Name == ScheduleActions.Scan ? "Jobs.Editor.FullScan" : "Jobs.Editor.RebuildAll");
|
||||
|
||||
public string ForceToolTip => Loc.L(_action.Name == ScheduleActions.Scan ? "Tooltips.Jobs.Editor.FullScan" : "Tooltips.Jobs.Editor.RebuildAll");
|
||||
|
||||
public bool Deep
|
||||
{
|
||||
get => _deep;
|
||||
set => Set(ref _deep, value);
|
||||
}
|
||||
|
||||
public string DeepToolTip => Loc.L("Tooltips.Jobs.Editor.DeepAnalysis");
|
||||
|
||||
public bool DryRun
|
||||
{
|
||||
get => _dryRun;
|
||||
set => Set(ref _dryRun, value);
|
||||
}
|
||||
|
||||
public ScheduleField OlderThan { get; }
|
||||
|
||||
public string OlderThanLabel => Loc.L(IsVerify ? "Jobs.Editor.Unverified" : "Jobs.Editor.OlderThan");
|
||||
|
||||
public ScheduleField Percent { get; }
|
||||
|
||||
public ScheduleField Keep { get; }
|
||||
|
||||
/// <summary>The clean-up steps this PC runs, those of the schedule checked.</summary>
|
||||
public IReadOnlyList<ScheduleChoice<string>> Steps
|
||||
{
|
||||
get => _steps;
|
||||
private set => Set(ref _steps, value);
|
||||
}
|
||||
|
||||
// ---------------- Options ----------------
|
||||
|
||||
public IReadOnlyList<SettingsOption<JobPriority>> Priorities { get; private set; }
|
||||
|
||||
public SettingsOption<JobPriority> SelectedPriority
|
||||
{
|
||||
get => _priority;
|
||||
set
|
||||
{
|
||||
if (value is not null) Set(ref _priority, value);
|
||||
}
|
||||
}
|
||||
|
||||
public bool CatchUp
|
||||
{
|
||||
get => _catchUp;
|
||||
set => Set(ref _catchUp, value);
|
||||
}
|
||||
|
||||
public bool Enabled
|
||||
{
|
||||
get => _enabled;
|
||||
set => Set(ref _enabled, value);
|
||||
}
|
||||
|
||||
// ---------------- Save ----------------
|
||||
|
||||
public ICommand SaveCommand { get; }
|
||||
|
||||
/// <summary>Cancel: closes without saving.</summary>
|
||||
public ICommand CloseCommand { get; }
|
||||
|
||||
public string SaveToolTip => Problem() ?? Loc.L(IsNew ? "Tooltips.Jobs.Editor.Create" : "Tooltips.Jobs.Editor.Save");
|
||||
|
||||
public bool IsBusy
|
||||
{
|
||||
get => _isBusy;
|
||||
private set
|
||||
{
|
||||
if (!Set(ref _isBusy, value)) return;
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Why the last save did not happen; null when nothing failed.</summary>
|
||||
public string? ErrorText
|
||||
{
|
||||
get => _errorText;
|
||||
private set => Set(ref _errorText, value);
|
||||
}
|
||||
|
||||
public string? ErrorToolTip
|
||||
{
|
||||
get => _errorToolTip;
|
||||
private set => Set(ref _errorToolTip, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first invalid field's problem, in the order of the dialog (name, when, parameters); null when the schedule can
|
||||
/// be saved.
|
||||
/// </summary>
|
||||
public string? Problem()
|
||||
{
|
||||
if (!IsSystem && Name.Error is { } name) return name;
|
||||
switch (Kind)
|
||||
{
|
||||
case RecurrenceKind.Every when Every.Error is { } every:
|
||||
return every;
|
||||
case RecurrenceKind.Every:
|
||||
break;
|
||||
default:
|
||||
if (Time.Error is { } time) return time;
|
||||
if (Kind == RecurrenceKind.Weekly && !Days.Any(d => d.IsChecked)) return Loc.L("Tooltips.Jobs.Editor.NoDays");
|
||||
if (Kind == RecurrenceKind.Monthly && DayOfMonth.Error is { } day) return day;
|
||||
break;
|
||||
}
|
||||
if (ShowsOlderThan && OlderThan.Error is { } older) return older;
|
||||
if (ShowsPercent && Percent.Error is { } percent) return percent;
|
||||
if (ShowsKeep && Keep.Error is { } keep) return keep;
|
||||
if (ShowsSteps && !Steps.Any(s => s.IsChecked)) return Loc.L("Tooltips.Jobs.Editor.NoSteps");
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>The recurrence the fields describe; null while one of them is invalid.</summary>
|
||||
public RecurrenceDto? Recurrence()
|
||||
{
|
||||
var time = Time.Error is null && TryTime(Time.Text, out var at) ? at.ToString("HH:mm", CultureInfo.InvariantCulture) : null;
|
||||
RecurrenceDto? dto = Kind switch
|
||||
{
|
||||
RecurrenceKind.Every when TryNumber(Every.Text, out var every) => new RecurrenceDto("every", Every: every, Unit: ScheduleMapping.Unit(_unit.Value)),
|
||||
RecurrenceKind.Daily when time is not null => new RecurrenceDto("daily", Time: time),
|
||||
RecurrenceKind.Weekly when time is not null && Days.Any(d => d.IsChecked) =>
|
||||
new RecurrenceDto("weekly", Time: time, Days: [.. Days.Where(d => d.IsChecked).Select(d => ScheduleRecurrence.DayName(d.Value))]),
|
||||
RecurrenceKind.Monthly when time is not null && TryNumber(DayOfMonth.Text, out var day) => new RecurrenceDto("monthly", Time: time, DayOfMonth: day),
|
||||
_ => null,
|
||||
};
|
||||
return ScheduleMapping.FromDto(dto) is not null ? dto : null;
|
||||
}
|
||||
|
||||
/// <summary>The action's parameters as the fields hold them (only the action's own).</summary>
|
||||
public ScheduleParametersDto Parameters() => ScheduleActions.Normalize(_action.Name, new ScheduleParametersDto(
|
||||
OlderThanDays: ShowsOlderThan && TryNumber(OlderThan.Text, out var days) ? days : null,
|
||||
Percent: ShowsPercent && TryNumber(Percent.Text, out var percent) ? percent : null,
|
||||
Deep: ShowsDeep ? _deep : null,
|
||||
DryRun: ShowsDryRun ? _dryRun : null,
|
||||
Force: ShowsForce ? _force : null,
|
||||
Steps: ShowsSteps ? [.. Steps.Where(s => s.IsChecked).Select(s => s.Value)] : null,
|
||||
Keep: ShowsKeep && TryNumber(Keep.Text, out var keep) ? keep : null));
|
||||
|
||||
internal CreateScheduleRequest BuildCreate() =>
|
||||
new(Name.Text.Trim(), _action.Name, Recurrence()!, Parameters(), _catchUp, JobWire.Priority(_priority.Value), _enabled);
|
||||
|
||||
/// <summary>Every field the dialog shows; a system schedule's name and action are left out (they stay).</summary>
|
||||
internal UpdateScheduleRequest BuildUpdate() =>
|
||||
new(IsSystem ? null : Name.Text.Trim(), IsSystem ? null : _action.Name, Recurrence(), Parameters(), _catchUp, JobWire.Priority(_priority.Value), _enabled);
|
||||
|
||||
/// <summary>Whether this PC runs each action was read again (<see cref="SchedulesViewModel.RefreshActionsAsync"/>).</summary>
|
||||
internal void RefreshActions() => RebuildActionOptions();
|
||||
|
||||
protected override void OnLanguageChanged()
|
||||
{
|
||||
foreach (var field in new[] { Name, Every, Time, DayOfMonth, OlderThan, Percent, Keep }) field.Refresh();
|
||||
foreach (var day in Days) day.Refresh();
|
||||
foreach (var step in Steps) step.Refresh();
|
||||
// The dropdowns' choices carry their labels: new ones in the new language, the same values chosen. Each list is
|
||||
// announced before its choice, so a dropdown finds the choice among its items.
|
||||
RebuildActionOptions();
|
||||
Units = BuildUnits();
|
||||
_unit = Units.First(u => u.Value == _unit.Value);
|
||||
OnPropertyChanged(nameof(Units));
|
||||
OnPropertyChanged(nameof(SelectedUnit));
|
||||
Priorities = BuildPriorities();
|
||||
_priority = Priorities.First(p => p.Value == _priority.Value);
|
||||
OnPropertyChanged(nameof(Priorities));
|
||||
OnPropertyChanged(nameof(SelectedPriority));
|
||||
base.OnLanguageChanged();
|
||||
}
|
||||
|
||||
/// <summary>The actions again, from the owner's last read; the chosen one stays chosen.</summary>
|
||||
private void RebuildActionOptions()
|
||||
{
|
||||
ActionOptions = BuildActionOptions();
|
||||
_action = ActionOptions.FirstOrDefault(o => o.Name == _action.Name) ?? _action;
|
||||
OnPropertyChanged(nameof(ActionOptions));
|
||||
OnPropertyChanged(nameof(SelectedAction));
|
||||
OnPropertyChanged(nameof(ActionToolTip));
|
||||
}
|
||||
|
||||
private ScheduleActionOption[] BuildActionOptions()
|
||||
{
|
||||
var available = _owner.Actions;
|
||||
return [.. ScheduleActions.All.Select(a => available.FirstOrDefault(x => x.Name == a) is { } info
|
||||
? new ScheduleActionOption(a, info.Available, info.Reason)
|
||||
: new ScheduleActionOption(a, true, null))];
|
||||
}
|
||||
|
||||
private static SettingsOption<RecurrenceUnit>[] BuildUnits() =>
|
||||
[.. Enum.GetValues<RecurrenceUnit>().Select(u => new SettingsOption<RecurrenceUnit>(u, Loc.L("Jobs.Editor.Unit." + u)))];
|
||||
|
||||
private static SettingsOption<JobPriority>[] BuildPriorities() =>
|
||||
[.. new[] { JobPriority.Background, JobPriority.Normal, JobPriority.User }.Select(p => new SettingsOption<JobPriority>(p, ScheduleText.Priority(p)))];
|
||||
|
||||
private bool IsVerify => _action.Name == ScheduleActions.Verify;
|
||||
|
||||
/// <summary>Save: the schedule as the fields hold it; the editor closes once it is stored, or says why it was not.</summary>
|
||||
internal async Task SaveAsync()
|
||||
{
|
||||
if (Problem() is not null) return;
|
||||
IsBusy = true;
|
||||
ErrorText = null;
|
||||
ErrorToolTip = null;
|
||||
try
|
||||
{
|
||||
var result = await _owner.SaveAsync(this);
|
||||
if (result.Problem is { } problem)
|
||||
{
|
||||
ErrorText = Loc.L("Jobs.Editor.Refused");
|
||||
ErrorToolTip = Loc.L("Tooltips.Jobs.Editor.Refused", problem);
|
||||
return;
|
||||
}
|
||||
IsBusy = false;
|
||||
_owner.CloseEditor(this);
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
|
||||
{
|
||||
Log.Warning("schedules", "A schedule could not be saved", ex);
|
||||
ErrorText = Loc.L("Jobs.Editor.SaveFailed");
|
||||
ErrorToolTip = ex.Message;
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsBusy = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Fills the parameter fields from <paramref name="parameters"/> (normalised for the current action).</summary>
|
||||
private void LoadParameters(ScheduleParametersDto parameters)
|
||||
{
|
||||
var p = ScheduleActions.Normalize(_action.Name, parameters);
|
||||
var defaults = ScheduleActions.Defaults(ScheduleActions.Verify);
|
||||
_force = p.Force ?? false;
|
||||
_deep = p.Deep ?? false;
|
||||
_dryRun = p.DryRun ?? false;
|
||||
OlderThan.Text = Number(p.OlderThanDays ?? defaults.OlderThanDays ?? 30);
|
||||
// Its tooltip names what the days count (unverified, or older), which follows the action.
|
||||
OlderThan.Refresh();
|
||||
Percent.Text = Number(p.Percent ?? defaults.Percent ?? 100);
|
||||
Keep.Text = Number(p.Keep ?? DatabaseBackups.Keep);
|
||||
var chosen = p.Steps ?? [];
|
||||
// The steps this PC runs, then any the schedule names that it does not (kept, shown by their wire name).
|
||||
var names = _owner.Steps.Concat(chosen.Where(s => !_owner.Steps.Contains(s))).ToList();
|
||||
Steps = [.. names.Select(s => new ScheduleChoice<string>(s, () => ScheduleText.Step(s), () => ScheduleText.StepToolTip(s), chosen.Contains(s), OnChanged))];
|
||||
}
|
||||
|
||||
private void OnChanged()
|
||||
{
|
||||
OnPropertyChanged(nameof(WhenText));
|
||||
OnPropertyChanged(nameof(SaveToolTip));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
|
||||
private string? ValidateName(string text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text)) return Loc.L("Tooltips.Jobs.Editor.NameMissing");
|
||||
return text.Trim().Length > Scheduler.MaxNameLength ? Loc.L("Tooltips.Jobs.Editor.NameLong", Scheduler.MaxNameLength) : null;
|
||||
}
|
||||
|
||||
private string? ValidateEvery(string text)
|
||||
{
|
||||
var (min, max) = _unit.Value switch
|
||||
{
|
||||
RecurrenceUnit.Minutes => (ScheduleRecurrence.MinMinutes, ScheduleRecurrence.MaxMinutes),
|
||||
RecurrenceUnit.Days => (1, ScheduleRecurrence.MaxDays),
|
||||
_ => (1, ScheduleRecurrence.MaxHours),
|
||||
};
|
||||
return ValidateNumber(text, min, max);
|
||||
}
|
||||
|
||||
private static string? ValidateDayOfMonth(string text) => ValidateNumber(text, 1, ScheduleRecurrence.MaxDayOfMonth);
|
||||
|
||||
private static string? ValidateTime(string text) => TryTime(text, out _) ? null : Loc.L("Tooltips.Jobs.Editor.TimeInvalid");
|
||||
|
||||
private static string? ValidateNumber(string text, int min, int max) =>
|
||||
TryNumber(text, out var value) && value >= min && value <= max ? null : Loc.L("Tooltips.Jobs.Editor.Number", Number(min), Number(max));
|
||||
|
||||
private static string Number(int value) => value.ToString(CultureInfo.CurrentCulture);
|
||||
|
||||
/// <summary>A whole number as the user's culture writes it (no sign, no thousands).</summary>
|
||||
private static bool TryNumber(string text, out int value) =>
|
||||
int.TryParse(text.Trim(), NumberStyles.None, CultureInfo.CurrentCulture, out value) || int.TryParse(text.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out value);
|
||||
|
||||
/// <summary>"03:00", "3:00", "3.00": hours and minutes of a 24-hour clock.</summary>
|
||||
internal static bool TryTime(string text, out TimeOnly time)
|
||||
{
|
||||
time = default;
|
||||
var parts = text.Trim().Split(':', '.');
|
||||
if (parts is not [var h, var m] || h.Length is < 1 or > 2 || m.Length != 2) return false;
|
||||
if (!int.TryParse(h, NumberStyles.None, CultureInfo.InvariantCulture, out var hour) || !int.TryParse(m, NumberStyles.None, CultureInfo.InvariantCulture, out var minute)
|
||||
|| hour > 23 || minute > 59)
|
||||
return false;
|
||||
time = new TimeOnly(hour, minute);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// One row of Jobs › Scheduled (owner review 2, R10): the on/off switch, name, action, when it runs, the next run and the
|
||||
/// last result, and its commands (Run now, Edit, then Reset for a system schedule or Delete for one the user created).
|
||||
/// </summary>
|
||||
public sealed class ScheduleRowViewModel : ObservableObject
|
||||
{
|
||||
private readonly SchedulesViewModel _owner;
|
||||
private ScheduleDto _schedule;
|
||||
private Job? _lastJob;
|
||||
private long _lastJobStamp;
|
||||
private bool _isEnabled;
|
||||
|
||||
internal ScheduleRowViewModel(ScheduleDto schedule, SchedulesViewModel owner)
|
||||
{
|
||||
_schedule = schedule;
|
||||
_owner = owner;
|
||||
_isEnabled = schedule.Enabled;
|
||||
RunNowCommand = new AsyncRelayCommand(() => owner.RunNowAsync(this), () => IsAvailable);
|
||||
EditCommand = new RelayCommand(() => owner.Edit(this));
|
||||
DeleteCommand = new AsyncRelayCommand(() => owner.DeleteAsync(this), () => !IsSystem);
|
||||
ResetCommand = new AsyncRelayCommand(() => owner.ResetAsync(this), () => IsSystem);
|
||||
}
|
||||
|
||||
public ScheduleDto Schedule => _schedule;
|
||||
public Guid Id => _schedule.Id;
|
||||
|
||||
/// <summary>A system schedule: one of the host's timers, reset instead of deleted.</summary>
|
||||
public bool IsSystem => _schedule.SystemKey is not null;
|
||||
|
||||
/// <summary>The job the last run queued, when it is known.</summary>
|
||||
public Job? LastJob => _lastJob;
|
||||
|
||||
public string Name => ScheduleText.Name(_schedule);
|
||||
|
||||
public string NameToolTip => IsSystem ? Loc.L("Tooltips.Jobs.Schedule.System", Name) : Name;
|
||||
|
||||
public string ActionText => ScheduleText.Action(_schedule.Action);
|
||||
|
||||
/// <summary>What the action does, or why this PC does not run it.</summary>
|
||||
public string ActionToolTip => IsAvailable ? ScheduleText.ActionToolTip(_schedule.Action) : ScheduleText.Unavailable(_owner.UnavailableReason(_schedule.Action));
|
||||
|
||||
/// <summary>This PC runs the schedule's action.</summary>
|
||||
public bool IsAvailable => _owner.IsAvailable(_schedule.Action);
|
||||
|
||||
public string WhenText => ScheduleText.When(_schedule.Recurrence);
|
||||
|
||||
/// <summary>When it runs, whether a missed run is caught up, and the priority of its jobs.</summary>
|
||||
public string WhenToolTip => string.Join(Loc.Separator, WhenText,
|
||||
Loc.L(_schedule.CatchUp ? "Tooltips.Jobs.Schedule.CatchUpOn" : "Tooltips.Jobs.Schedule.CatchUpOff"),
|
||||
Loc.L("Tooltips.Jobs.Schedule.PriorityIs", ScheduleText.Priority(Priority)));
|
||||
|
||||
public string NextText => ScheduleText.Next(_schedule.NextRun, _schedule.Enabled);
|
||||
|
||||
public string NextToolTip => !_schedule.Enabled ? Loc.L("Tooltips.Jobs.Schedule.NextOff")
|
||||
: _schedule.NextRun is { } next ? Loc.L("Tooltips.Jobs.Schedule.Next", Formatting.Date(next) + " " + Formatting.TimeOfDay(next))
|
||||
: Loc.L("Tooltips.Jobs.Schedule.NextPending");
|
||||
|
||||
public string LastText => ScheduleText.Outcome(_schedule.LastOutcome, _lastJob);
|
||||
|
||||
public string LastToolTip => ScheduleText.OutcomeToolTip(_schedule.LastOutcome, _schedule.LastRun, _lastJob);
|
||||
|
||||
public StatusKind LastKind => ScheduleText.OutcomeKind(_schedule.LastOutcome, _lastJob);
|
||||
|
||||
/// <summary>Off, a schedule never runs by itself (Run now still runs it). Turning it on or off saves at once.</summary>
|
||||
public bool IsEnabled
|
||||
{
|
||||
get => _isEnabled;
|
||||
set
|
||||
{
|
||||
if (Set(ref _isEnabled, value)) _ = _owner.SetEnabledAsync(this, value);
|
||||
}
|
||||
}
|
||||
|
||||
public string EnabledToolTip => Loc.L(_isEnabled ? "Tooltips.Jobs.Schedule.EnabledOn" : "Tooltips.Jobs.Schedule.EnabledOff");
|
||||
|
||||
/// <summary>"Index backup · Index backup · Daily at 03:00": the row's name for screen readers.</summary>
|
||||
public string AccessibleName => string.Join(Loc.Separator, Name, ActionText, WhenText);
|
||||
|
||||
public ICommand RunNowCommand { get; }
|
||||
public ICommand EditCommand { get; }
|
||||
public ICommand DeleteCommand { get; }
|
||||
public ICommand ResetCommand { get; }
|
||||
|
||||
public string RunNowToolTip => IsAvailable ? Loc.L("Tooltips.Jobs.Schedule.RunNow") : ScheduleText.Unavailable(_owner.UnavailableReason(_schedule.Action));
|
||||
|
||||
/// <summary>"Run now: Index backup", what each row button is called for screen readers.</summary>
|
||||
public string RunNowName => Loc.L("Jobs.ActionFor", Loc.L("Jobs.Schedule.RunNow"), Name);
|
||||
public string EditName => Loc.L("Jobs.ActionFor", Loc.L("Jobs.Schedule.Edit"), Name);
|
||||
public string DeleteName => Loc.L("Jobs.ActionFor", Loc.L("Jobs.Schedule.Delete"), Name);
|
||||
public string ResetName => Loc.L("Jobs.ActionFor", Loc.L("Jobs.Schedule.Reset"), Name);
|
||||
public string EnabledName => Loc.L("Jobs.ActionFor", Loc.L("Jobs.Schedule.Enabled"), Name);
|
||||
|
||||
private JobPriority Priority => JobWire.TryParsePriority(_schedule.Priority, out var priority) ? priority : JobPriority.Background;
|
||||
|
||||
/// <summary>A newer copy of the schedule (an edit, a run, a correction of its next run).</summary>
|
||||
internal void Update(ScheduleDto schedule)
|
||||
{
|
||||
if (schedule.LastJobId != _schedule.LastJobId)
|
||||
{
|
||||
// A read of the previous job no longer applies.
|
||||
_lastJob = null;
|
||||
_lastJobStamp++;
|
||||
}
|
||||
_schedule = schedule;
|
||||
_isEnabled = schedule.Enabled;
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
/// <summary>The job the last run queued changed (live, from the engine): the last result follows its state.</summary>
|
||||
internal void SetLastJob(Job? job)
|
||||
{
|
||||
if (job is not null && job.Id != _schedule.LastJobId) return;
|
||||
_lastJobStamp++;
|
||||
ShowLastJob(job);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A read of the last job from the index starts; its result applies only while nothing newer arrived (a live change,
|
||||
/// another job, a later read): see <see cref="SetLoadedLastJob"/>.
|
||||
/// </summary>
|
||||
internal long BeginLastJobRead() => ++_lastJobStamp;
|
||||
|
||||
/// <summary>The last job as the read begun at <paramref name="read"/> found it; ignored when that read is stale.</summary>
|
||||
internal void SetLoadedLastJob(Job? job, long read)
|
||||
{
|
||||
if (read != _lastJobStamp || (job is not null && job.Id != _schedule.LastJobId)) return;
|
||||
ShowLastJob(job);
|
||||
}
|
||||
|
||||
private void ShowLastJob(Job? job)
|
||||
{
|
||||
_lastJob = job;
|
||||
OnPropertyChanged(nameof(LastJob));
|
||||
OnPropertyChanged(nameof(LastText));
|
||||
OnPropertyChanged(nameof(LastToolTip));
|
||||
OnPropertyChanged(nameof(LastKind));
|
||||
}
|
||||
|
||||
/// <summary>The switch goes back to the stored state (the change was refused).</summary>
|
||||
internal void RevertEnabled()
|
||||
{
|
||||
_isEnabled = _schedule.Enabled;
|
||||
OnPropertyChanged(nameof(IsEnabled));
|
||||
OnPropertyChanged(nameof(EnabledToolTip));
|
||||
}
|
||||
|
||||
internal void Refresh() => OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
/// <summary>A job a schedule queued, in the selected schedule's last runs: kind, target, when, state, and Show in queue.</summary>
|
||||
public sealed class ScheduleRunViewModel : ObservableObject
|
||||
{
|
||||
private Job _job;
|
||||
|
||||
internal ScheduleRunViewModel(Job job, Func<Guid, Task> show)
|
||||
{
|
||||
_job = job;
|
||||
ShowCommand = new AsyncRelayCommand(() => show(_job.Id));
|
||||
}
|
||||
|
||||
public Job Job => _job;
|
||||
public Guid Id => _job.Id;
|
||||
|
||||
public string Kind => JobText.Kind(_job.Kind);
|
||||
|
||||
public string Target => _job.TargetLabel ?? string.Empty;
|
||||
|
||||
/// <summary>When the run queued it ("Today 03:00").</summary>
|
||||
public string WhenText => ScheduleText.Moment(_job.Created);
|
||||
|
||||
public string StateText => JobText.State(new JobEntry(_job));
|
||||
|
||||
public string StateToolTip => string.Join(Loc.Separator, StateText,
|
||||
_job.Error is { Length: > 0 } error ? error : Loc.L("Tooltips.Jobs.State." + _job.State));
|
||||
|
||||
public StatusKind StateKind => _job.State switch
|
||||
{
|
||||
JobState.Running => StatusKind.Running,
|
||||
JobState.Queued => StatusKind.Queued,
|
||||
JobState.Paused => StatusKind.Paused,
|
||||
JobState.Done => StatusKind.Done,
|
||||
JobState.Failed => StatusKind.Failed,
|
||||
_ => StatusKind.Offline,
|
||||
};
|
||||
|
||||
/// <summary>"Verify · Archive · 2024: done": the row for screen readers.</summary>
|
||||
public string AccessibleName => Loc.L("Jobs.Row.State", JobText.Name(_job), StateText);
|
||||
|
||||
public string ShowName => Loc.L("Jobs.ActionFor", Loc.L("Jobs.Schedule.ShowJob"), JobText.Name(_job));
|
||||
|
||||
public ICommand ShowCommand { get; }
|
||||
|
||||
internal void Update(Job job)
|
||||
{
|
||||
_job = job;
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
internal void Refresh() => OnAllPropertiesChanged();
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Ui.Controls;
|
||||
|
||||
namespace Chronos.App.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Localized texts of schedules (Jobs › Scheduled, owner review 2, R10): names, actions, clean-up steps, when they run,
|
||||
/// their next run and what their last run did. Wire names (<c>scan</c>, <c>skipped-pending</c>, <c>job-history</c>) never
|
||||
/// reach the screen; an unknown one (a newer build's) is shown as it is.
|
||||
/// </summary>
|
||||
public static class ScheduleText
|
||||
{
|
||||
/// <summary>A system schedule by its key in the user's language; a user's schedule by the name they gave it.</summary>
|
||||
public static string Name(ScheduleDto schedule)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(schedule);
|
||||
return schedule.SystemKey is { } key && SystemKeyName(key) is { } name ? Loc.L(name) : schedule.Name;
|
||||
}
|
||||
|
||||
/// <summary>"Archive scan", "Index backup", …</summary>
|
||||
public static string Action(string action) => ScheduleActions.IsKnown(action) ? Loc.L("Jobs.Schedule.Action." + Pascal(action)) : action;
|
||||
|
||||
/// <summary>What the action does.</summary>
|
||||
public static string ActionToolTip(string action) =>
|
||||
ScheduleActions.IsKnown(action) ? Loc.L("Tooltips.Jobs.Schedule.Action." + Pascal(action)) : Loc.L("Tooltips.Jobs.Schedule.Unavailable.Other");
|
||||
|
||||
/// <summary>Why this PC does not run an action (<see cref="ScheduleUnavailable"/>, or a code of the host's own).</summary>
|
||||
public static string Unavailable(string? reason) => reason switch
|
||||
{
|
||||
ScheduleUnavailable.NoHandler => Loc.L("Tooltips.Jobs.Schedule.Unavailable.NoHandler"),
|
||||
ScheduleUnavailable.Postgres => Loc.L("Tooltips.Jobs.Schedule.Unavailable.Postgres"),
|
||||
ScheduleUnavailable.NoIndexFile => Loc.L("Tooltips.Jobs.Schedule.Unavailable.NoIndexFile"),
|
||||
ScheduleUnavailable.ProxiesDisabled => Loc.L("Tooltips.Jobs.Schedule.Unavailable.ProxiesDisabled"),
|
||||
_ => Loc.L("Tooltips.Jobs.Schedule.Unavailable.Other"),
|
||||
};
|
||||
|
||||
/// <summary>"Job history", "Cache trim", …: a clean-up step; an unknown one by its wire name.</summary>
|
||||
public static string Step(string step) => StepKey(step) is { } key ? Loc.L("Jobs.Schedule.Step." + key) : step;
|
||||
|
||||
public static string StepToolTip(string step) => StepKey(step) is { } key ? Loc.L("Tooltips.Jobs.Schedule.Step." + key) : step;
|
||||
|
||||
/// <summary>"Every 10 minutes", "Daily at 03:00", "Mon, Thu at 02:30", "Monthly, day 1 at 04:00".</summary>
|
||||
public static string When(RecurrenceDto? recurrence) =>
|
||||
ScheduleMapping.FromDto(recurrence) is { } parsed ? When(parsed) : Loc.L("Jobs.Schedule.When.Invalid");
|
||||
|
||||
/// <inheritdoc cref="When(RecurrenceDto?)"/>
|
||||
public static string When(ScheduleRecurrence recurrence)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(recurrence);
|
||||
return recurrence.Kind switch
|
||||
{
|
||||
RecurrenceKind.Every => Loc.Plural("Jobs.Schedule.When." + recurrence.Unit, recurrence.Every),
|
||||
RecurrenceKind.Daily => Loc.L("Jobs.Schedule.When.Daily", Time(recurrence.Time)),
|
||||
RecurrenceKind.Weekly when recurrence.Days.Count == 7 => Loc.L("Jobs.Schedule.When.Daily", Time(recurrence.Time)),
|
||||
RecurrenceKind.Weekly => Loc.L("Jobs.Schedule.When.Weekly", Days(recurrence.Days), Time(recurrence.Time)),
|
||||
_ => Loc.L("Jobs.Schedule.When.Monthly", recurrence.DayOfMonth, Time(recurrence.Time)),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Mon, Thu": the days in the order of the UI language's week, from its first day as the editor lists them (Sunday
|
||||
/// first in English, Monday first in Italian), short names of the UI language.
|
||||
/// </summary>
|
||||
public static string Days(IEnumerable<DayOfWeek> days)
|
||||
{
|
||||
var first = (int)Loc.Culture.DateTimeFormat.FirstDayOfWeek;
|
||||
return days.OrderBy(d => ((int)d - first + 7) % 7).Select(DayShort).Aggregate((a, b) => Loc.L("Jobs.Schedule.DayList", a, b));
|
||||
}
|
||||
|
||||
/// <summary>"Mon" in the UI language.</summary>
|
||||
public static string DayShort(DayOfWeek day) => Loc.Culture.DateTimeFormat.GetAbbreviatedDayName(day);
|
||||
|
||||
/// <summary>"Monday" in the UI language.</summary>
|
||||
public static string DayLong(DayOfWeek day) => Loc.Culture.DateTimeFormat.GetDayName(day);
|
||||
|
||||
/// <summary>A wall-clock time in the UI language's short format ("03:00", "3:00 AM").</summary>
|
||||
public static string Time(TimeOnly time) => DateTime.MinValue.Add(time.ToTimeSpan()).ToString("t", Loc.Culture);
|
||||
|
||||
/// <summary>
|
||||
/// The next run as the table shows it: "Today 03:00", "Tomorrow 03:00", a date and time further away, "Off" for a
|
||||
/// disabled schedule, "—" while it has none yet.
|
||||
/// </summary>
|
||||
public static string Next(DateTimeOffset? next, bool enabled)
|
||||
{
|
||||
if (!enabled) return Loc.L("Jobs.Schedule.Off");
|
||||
return next is { } at ? Moment(at) : "—";
|
||||
}
|
||||
|
||||
/// <summary>"Today 03:00", "Tomorrow 03:00", "Yesterday 03:00", or the short date and time.</summary>
|
||||
public static string Moment(DateTimeOffset at)
|
||||
{
|
||||
var local = at.ToLocalTime();
|
||||
var days = (local.Date - AppClock.Today).Days;
|
||||
var time = Formatting.TimeOfDay(at);
|
||||
return days switch
|
||||
{
|
||||
0 => Loc.L("Jobs.Schedule.Today", time),
|
||||
1 => Loc.L("Jobs.Schedule.Tomorrow", time),
|
||||
-1 => Loc.L("Jobs.Schedule.Yesterday", time),
|
||||
_ => Formatting.Date(at) + " " + time,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the last run did: the state of the job it queued when that is known ("done", "failed", "running"), else the
|
||||
/// outcome ("skipped: busy", "nothing to do", …); "never run" before the first run.
|
||||
/// </summary>
|
||||
public static string Outcome(string? outcome, Job? lastJob)
|
||||
{
|
||||
if (outcome is null) return Loc.L("Jobs.Schedule.Outcome.Never");
|
||||
if (outcome == ScheduleOutcome.Queued && lastJob is not null) return Loc.L("Jobs.State." + lastJob.State);
|
||||
if (ScheduleOutcome.IsFailed(outcome, out _)) return Loc.L("Jobs.Schedule.Outcome.Failed");
|
||||
return OutcomeKey(outcome) is { } key ? Loc.L("Jobs.Schedule.Outcome." + key) : outcome;
|
||||
}
|
||||
|
||||
/// <summary>The outcome explained, with when the last run was and the reason of a failure.</summary>
|
||||
public static string OutcomeToolTip(string? outcome, DateTimeOffset? lastRun, Job? lastJob)
|
||||
{
|
||||
if (outcome is null || lastRun is not { } at) return Loc.L("Tooltips.Jobs.Schedule.Outcome.Never");
|
||||
var when = Loc.L("Jobs.Schedule.LastRun", Moment(at));
|
||||
string why;
|
||||
if (ScheduleOutcome.IsFailed(outcome, out var reason)) why = Loc.L("Tooltips.Jobs.Schedule.Outcome.Failed", reason);
|
||||
else if (outcome == ScheduleOutcome.Queued && lastJob is { Error: { Length: > 0 } error }) why = error;
|
||||
else if (outcome == ScheduleOutcome.Queued && lastJob is not null) why = Loc.L("Tooltips.Jobs.State." + lastJob.State);
|
||||
else why = OutcomeKey(outcome) is { } key ? Loc.L("Tooltips.Jobs.Schedule.Outcome." + key) : outcome;
|
||||
return string.Join(Loc.Separator, when, why);
|
||||
}
|
||||
|
||||
/// <summary>Glyph of the last result, paired with its word.</summary>
|
||||
public static StatusKind OutcomeKind(string? outcome, Job? lastJob)
|
||||
{
|
||||
if (outcome is null) return StatusKind.Offline;
|
||||
if (ScheduleOutcome.IsFailed(outcome, out _)) return StatusKind.Failed;
|
||||
if (outcome == ScheduleOutcome.Queued && lastJob is not null)
|
||||
{
|
||||
return lastJob.State switch
|
||||
{
|
||||
JobState.Running => StatusKind.Running,
|
||||
JobState.Queued => StatusKind.Queued,
|
||||
JobState.Paused => StatusKind.Paused,
|
||||
JobState.Done => StatusKind.Done,
|
||||
JobState.Failed => StatusKind.Failed,
|
||||
_ => StatusKind.Offline,
|
||||
};
|
||||
}
|
||||
return outcome switch
|
||||
{
|
||||
ScheduleOutcome.Queued => StatusKind.Queued,
|
||||
ScheduleOutcome.SkippedNothing => StatusKind.Done,
|
||||
ScheduleOutcome.SkippedPending => StatusKind.Paused,
|
||||
ScheduleOutcome.Unavailable => StatusKind.Warning,
|
||||
_ => StatusKind.Offline,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>"Background", "Normal", "High": the priority of the jobs a schedule queues.</summary>
|
||||
public static string Priority(JobPriority priority) => Loc.L("Jobs.Schedule.Priority." + priority);
|
||||
|
||||
private static string? SystemKeyName(string key) => key switch
|
||||
{
|
||||
DesktopScheduleHost.ArchiveScan => "Jobs.Schedule.System.ArchiveScan",
|
||||
DesktopScheduleHost.IndexBackup => "Jobs.Schedule.System.IndexBackup",
|
||||
DesktopScheduleHost.Housekeeping => "Jobs.Schedule.System.Housekeeping",
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private static string? StepKey(string step) => step switch
|
||||
{
|
||||
CleanupSteps.JobHistory => "JobHistory",
|
||||
CleanupSteps.Audit => "Audit",
|
||||
CleanupSteps.TrashReport => "TrashReport",
|
||||
CacheTrimStep.StepName => "CacheTrim",
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private static string? OutcomeKey(string outcome) => outcome switch
|
||||
{
|
||||
ScheduleOutcome.Queued => "Queued",
|
||||
ScheduleOutcome.SkippedPending => "SkippedPending",
|
||||
ScheduleOutcome.SkippedOffline => "SkippedOffline",
|
||||
ScheduleOutcome.SkippedNothing => "SkippedNothing",
|
||||
ScheduleOutcome.Unavailable => "Unavailable",
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary><c>scan</c> → <c>Scan</c>: the resource name of a wire name.</summary>
|
||||
private static string Pascal(string name) => string.Concat(name.Split('-').Select(p => p.Length == 0 ? p : char.ToUpperInvariant(p[0]) + p[1..]));
|
||||
}
|
||||
@@ -0,0 +1,544 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Housekeeping;
|
||||
using Chronos.Data.Scheduling;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Jobs › Scheduled (owner review 2, R10): every schedule of this PC's <see cref="Scheduler"/> (the system ones that stand
|
||||
/// for its timers first), each with its switch, next run and last result, kept current by the scheduler's events and by
|
||||
/// the jobs its runs queued; the selected schedule's last runs, each one shown in the queue on request; the in-window
|
||||
/// editor of a new or existing schedule. Calls to the scheduler run off the UI thread; their results and its events are
|
||||
/// applied on it. WPF-free apart from the commands: tests drive it with a scheduler of their own.
|
||||
/// </summary>
|
||||
public sealed class SchedulesViewModel : LocalizedViewModel
|
||||
{
|
||||
/// <summary>Runs listed for the selected schedule.</summary>
|
||||
public const int RunsShown = 20;
|
||||
|
||||
private readonly Func<Scheduler?> _scheduler;
|
||||
private readonly Func<ChronosDatabase?> _database;
|
||||
private readonly Func<ConfirmRequest, bool> _confirm;
|
||||
private readonly Action<string, string?, bool> _notify;
|
||||
private readonly Func<Guid, Task> _showJob;
|
||||
private readonly Dictionary<Guid, ScheduleRowViewModel> _rows = [];
|
||||
private SynchronizationContext? _context;
|
||||
private Scheduler? _attached;
|
||||
private IReadOnlyList<ScheduleActionDto> _actions = [];
|
||||
private IReadOnlyList<string> _steps = [];
|
||||
private ScheduleRowViewModel? _selected;
|
||||
private ScheduleEditorViewModel? _editor;
|
||||
private bool _isLoaded;
|
||||
private int _runsRequest;
|
||||
private Task? _attach;
|
||||
|
||||
/// <param name="scheduler">The running scheduler (once <see cref="AttachAsync"/> was told it runs).</param>
|
||||
/// <param name="database">The index, to read the jobs the runs queued.</param>
|
||||
/// <param name="confirm">Asks before a delete or a reset.</param>
|
||||
/// <param name="notify">A toast: title, message, whether something did not happen.</param>
|
||||
/// <param name="showJob">Shows a job in the queue tab.</param>
|
||||
public SchedulesViewModel(Func<Scheduler?> scheduler, Func<ChronosDatabase?> database, Func<ConfirmRequest, bool> confirm,
|
||||
Action<string, string?, bool> notify, Func<Guid, Task> showJob)
|
||||
{
|
||||
_scheduler = scheduler;
|
||||
_database = database;
|
||||
_confirm = confirm;
|
||||
_notify = notify;
|
||||
_showJob = showJob;
|
||||
NewCommand = new RelayCommand(New, () => IsRunning && _editor is null);
|
||||
}
|
||||
|
||||
/// <summary>A schedule changed in a way the history text depends on (the housekeeping's job-history days).</summary>
|
||||
public event Action? HistoryChanged;
|
||||
|
||||
/// <summary>System schedules first, then the user's, oldest first (the scheduler's order).</summary>
|
||||
public ObservableCollection<ScheduleRowViewModel> Rows { get; } = [];
|
||||
|
||||
/// <summary>The jobs the selected schedule queued, newest first.</summary>
|
||||
public ObservableCollection<ScheduleRunViewModel> Runs { get; } = [];
|
||||
|
||||
public ICommand NewCommand { get; }
|
||||
|
||||
public string NewToolTip => IsRunning ? Loc.L("Tooltips.Jobs.Schedule.New") : Loc.L("Tooltips.Jobs.Schedule.NotRunning");
|
||||
|
||||
/// <summary>The scheduler of this PC runs (it does not without an index, or while it failed to start).</summary>
|
||||
public bool IsRunning => _attached is not null;
|
||||
|
||||
/// <summary>The schedules were read, or it is known that there are none to read.</summary>
|
||||
public bool IsLoaded => _isLoaded;
|
||||
|
||||
public bool HasRows => Rows.Count > 0;
|
||||
|
||||
/// <summary>The empty state: the scheduler does not run here.</summary>
|
||||
public bool IsUnavailable => _isLoaded && !IsRunning;
|
||||
|
||||
public ScheduleRowViewModel? Selected
|
||||
{
|
||||
get => _selected;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _selected, value)) return;
|
||||
OnPropertyChanged(nameof(HasSelection));
|
||||
OnPropertyChanged(nameof(RunsHeading));
|
||||
RunsLoading = LoadRunsAsync();
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasSelection => _selected is not null;
|
||||
|
||||
/// <summary>"Last runs · Index backup".</summary>
|
||||
public string RunsHeading => _selected is { } row ? Loc.L("Jobs.Row.Name", Loc.L("Jobs.Schedule.Runs"), row.Name) : Loc.L("Jobs.Schedule.Runs");
|
||||
|
||||
public bool HasRuns => Runs.Count > 0;
|
||||
|
||||
public bool IsRunsEmpty => _selected is not null && Runs.Count == 0;
|
||||
|
||||
/// <summary>The open editor; null when none.</summary>
|
||||
public ScheduleEditorViewModel? Editor
|
||||
{
|
||||
get => _editor;
|
||||
private set
|
||||
{
|
||||
if (!Set(ref _editor, value)) return;
|
||||
OnPropertyChanged(nameof(IsEditorOpen));
|
||||
OnPropertyChanged(nameof(IsContentEnabled));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsEditorOpen => _editor is not null;
|
||||
|
||||
/// <summary>The screen behind an open editor takes neither clicks nor keyboard focus.</summary>
|
||||
public bool IsContentEnabled => _editor is null;
|
||||
|
||||
/// <summary>The actions with whether this PC runs them, as last read.</summary>
|
||||
public IReadOnlyList<ScheduleActionDto> Actions => _actions;
|
||||
|
||||
/// <summary>The clean-up steps this PC's clean-up jobs run.</summary>
|
||||
public IReadOnlyList<string> Steps => _steps;
|
||||
|
||||
/// <summary>
|
||||
/// Days of job history the housekeeping schedule keeps: its age limit while it is on and removes job history; null
|
||||
/// while it keeps every job; the product's default before the schedules are read.
|
||||
/// </summary>
|
||||
public int? HistoryDays
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!_isLoaded || !IsRunning) return CleanupSteps.DefaultHistoryDays;
|
||||
var housekeeping = Rows.FirstOrDefault(r => r.Schedule.SystemKey == DesktopScheduleHost.Housekeeping)?.Schedule;
|
||||
if (housekeeping is not { Enabled: true, Action: ScheduleActions.Cleanup } || housekeeping.Parameters.Steps?.Contains(CleanupSteps.JobHistory) != true)
|
||||
return null;
|
||||
return housekeeping.Parameters.OlderThanDays is > 0 and var days ? days : null;
|
||||
}
|
||||
}
|
||||
|
||||
internal Scheduler? Scheduler => _attached;
|
||||
|
||||
/// <summary>The last read of the selected schedule's runs (capture, tests).</summary>
|
||||
internal Task RunsLoading { get; private set; } = Task.CompletedTask;
|
||||
|
||||
/// <summary>Completes once <see cref="AttachAsync"/> has read the schedules, or knows there are none.</summary>
|
||||
public Task Attached => _attach ?? Task.CompletedTask;
|
||||
|
||||
/// <summary>
|
||||
/// Waits for the scheduler (<paramref name="ready"/>: true once it runs), then follows its events and reads the
|
||||
/// schedules. Call on the UI thread, once: events are brought back to it.
|
||||
/// </summary>
|
||||
public Task AttachAsync(Task<bool> ready)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ready);
|
||||
return _attach ??= AttachCoreAsync(ready);
|
||||
}
|
||||
|
||||
private async Task AttachCoreAsync(Task<bool> ready)
|
||||
{
|
||||
_context = SynchronizationContext.Current;
|
||||
bool running;
|
||||
try
|
||||
{
|
||||
running = await ready;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("schedules", "The schedules did not start", ex);
|
||||
running = false;
|
||||
}
|
||||
if (!running || _scheduler() is not { } scheduler)
|
||||
{
|
||||
_isLoaded = true;
|
||||
RaiseState();
|
||||
return;
|
||||
}
|
||||
_attached = scheduler;
|
||||
scheduler.ScheduleChanged += OnScheduleChanged;
|
||||
scheduler.ScheduleDeleted += OnScheduleDeleted;
|
||||
await ReloadAsync();
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
if (_attached is not null)
|
||||
{
|
||||
_attached.ScheduleChanged -= OnScheduleChanged;
|
||||
_attached.ScheduleDeleted -= OnScheduleDeleted;
|
||||
}
|
||||
_editor?.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>Reads every schedule, the actions' availability and the jobs of the last runs again.</summary>
|
||||
public async Task ReloadAsync()
|
||||
{
|
||||
if (_attached is not { } scheduler) return;
|
||||
SchedulesDto list;
|
||||
try
|
||||
{
|
||||
list = await Task.Run(() => scheduler.ListAsync());
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
|
||||
{
|
||||
Log.Warning("schedules", "The schedules could not be read", ex);
|
||||
_isLoaded = true;
|
||||
RaiseState();
|
||||
return;
|
||||
}
|
||||
_actions = list.Actions;
|
||||
_steps = list.Steps ?? [];
|
||||
var wanted = list.Items.Select(s => s.Id).ToHashSet();
|
||||
foreach (var gone in _rows.Keys.Where(id => !wanted.Contains(id)).ToList()) Remove(gone);
|
||||
for (var i = 0; i < list.Items.Count; i++)
|
||||
{
|
||||
var dto = list.Items[i];
|
||||
if (!_rows.TryGetValue(dto.Id, out var row))
|
||||
{
|
||||
row = new ScheduleRowViewModel(dto, this);
|
||||
_rows[dto.Id] = row;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Every text again: the actions' availability may have changed too.
|
||||
row.Update(dto);
|
||||
}
|
||||
var at = Rows.IndexOf(row);
|
||||
if (at == i) continue;
|
||||
if (at >= 0) Rows.Move(at, i);
|
||||
else Rows.Insert(i, row);
|
||||
}
|
||||
_isLoaded = true;
|
||||
RaiseState();
|
||||
HistoryChanged?.Invoke();
|
||||
foreach (var row in Rows.ToList()) await LoadLastJobAsync(row);
|
||||
if (_selected is not null) await LoadRunsAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads again whether this PC runs each action (Jobs › Scheduled is shown: proxies may have been turned on or off,
|
||||
/// another archive chosen): the rows' Run now and tooltips, and the actions of the editor, follow it.
|
||||
/// </summary>
|
||||
public async Task RefreshActionsAsync()
|
||||
{
|
||||
if (_attached is not { } scheduler) return;
|
||||
SchedulesDto list;
|
||||
try
|
||||
{
|
||||
list = await Task.Run(() => scheduler.ListAsync());
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
|
||||
{
|
||||
Log.Warning("schedules", "The actions could not be read again", ex);
|
||||
return;
|
||||
}
|
||||
_actions = list.Actions;
|
||||
_steps = list.Steps ?? [];
|
||||
foreach (var row in Rows) row.Refresh();
|
||||
_editor?.RefreshActions();
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
|
||||
/// <summary>A job changed (UI thread, from the Jobs screen's flush): the last result and the last runs follow it.</summary>
|
||||
public void OnJob(Job job)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
if (job.ScheduleId is not { } id || !_rows.TryGetValue(id, out var row)) return;
|
||||
if (row.Schedule.LastJobId == job.Id) row.SetLastJob(job);
|
||||
if (!ReferenceEquals(_selected, row)) return;
|
||||
if (Runs.FirstOrDefault(r => r.Id == job.Id) is { } run)
|
||||
{
|
||||
run.Update(job);
|
||||
}
|
||||
else
|
||||
{
|
||||
Runs.Insert(0, new ScheduleRunViewModel(job, _showJob));
|
||||
while (Runs.Count > RunsShown) Runs.RemoveAt(Runs.Count - 1);
|
||||
RaiseRuns();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Whether this PC runs <paramref name="action"/> (unknown until the list is read: yes).</summary>
|
||||
public bool IsAvailable(string action) => _actions.FirstOrDefault(a => a.Name == action) is not { Available: false };
|
||||
|
||||
public string? UnavailableReason(string action) => _actions.FirstOrDefault(a => a.Name == action)?.Reason;
|
||||
|
||||
protected override void OnLanguageChanged()
|
||||
{
|
||||
foreach (var row in Rows) row.Refresh();
|
||||
foreach (var run in Runs) run.Refresh();
|
||||
HistoryChanged?.Invoke();
|
||||
base.OnLanguageChanged();
|
||||
}
|
||||
|
||||
// ---------------- Row commands ----------------
|
||||
|
||||
/// <summary>Runs the schedule now, as its next run would; says so when nothing was queued.</summary>
|
||||
internal async Task RunNowAsync(ScheduleRowViewModel row)
|
||||
{
|
||||
if (_attached is not { } scheduler) return;
|
||||
var run = await Call(() => scheduler.RunNowAsync(row.Id, null));
|
||||
if (run is null)
|
||||
{
|
||||
await ReloadAsync();
|
||||
return;
|
||||
}
|
||||
Apply(run.Schedule);
|
||||
if (run.Outcome == ScheduleOutcome.Queued) return;
|
||||
// This PC no longer runs the action: the row says so from now on.
|
||||
if (run.Outcome == ScheduleOutcome.Unavailable) await RefreshActionsAsync();
|
||||
_notify(Loc.L("Jobs.Row.Name", row.Name, ScheduleText.Outcome(run.Outcome, null)), ScheduleText.OutcomeToolTip(run.Outcome, run.Schedule.LastRun, null),
|
||||
ScheduleOutcome.IsFailed(run.Outcome, out _) || run.Outcome == ScheduleOutcome.Unavailable);
|
||||
}
|
||||
|
||||
/// <summary>Turns a schedule on or off (its switch); a refused change puts the switch back.</summary>
|
||||
internal async Task SetEnabledAsync(ScheduleRowViewModel row, bool enabled)
|
||||
{
|
||||
if (_attached is not { } scheduler) return;
|
||||
var result = await Call(() => scheduler.UpdateAsync(row.Id, new UpdateScheduleRequest(Enabled: enabled)));
|
||||
if (result?.Schedule is { } saved)
|
||||
{
|
||||
Apply(saved);
|
||||
return;
|
||||
}
|
||||
row.RevertEnabled();
|
||||
if (result is { NotFound: true }) await ReloadAsync();
|
||||
}
|
||||
|
||||
internal void Edit(ScheduleRowViewModel row)
|
||||
{
|
||||
if (_editor is not null) return;
|
||||
Editor = new ScheduleEditorViewModel(this, row.Schedule);
|
||||
}
|
||||
|
||||
/// <summary>Deletes a schedule the user created, after asking.</summary>
|
||||
internal async Task DeleteAsync(ScheduleRowViewModel row)
|
||||
{
|
||||
if (_attached is not { } scheduler || row.IsSystem) return;
|
||||
var confirmed = _confirm(new ConfirmRequest
|
||||
{
|
||||
Heading = Loc.L("Jobs.Schedule.DeleteHeading", row.Name),
|
||||
Message = Loc.L("Jobs.Schedule.DeleteMessage"),
|
||||
SafeText = Loc.L("Jobs.Schedule.Keep"),
|
||||
SafeToolTip = Loc.L("Tooltips.Jobs.Schedule.Keep"),
|
||||
ActionText = Loc.L("Jobs.Schedule.Delete"),
|
||||
ActionToolTip = Loc.L("Tooltips.Jobs.Schedule.Delete"),
|
||||
IsDestructive = true,
|
||||
});
|
||||
if (!confirmed) return;
|
||||
// Nullable: a failed call is null, not the enum's first value (Deleted), so its row stays.
|
||||
var outcome = await Call<ScheduleDeleteOutcome?>(async () => await scheduler.DeleteAsync(row.Id));
|
||||
if (outcome is ScheduleDeleteOutcome.Deleted or ScheduleDeleteOutcome.NotFound) Remove(row.Id);
|
||||
}
|
||||
|
||||
/// <summary>Puts a system schedule back to this PC's defaults, after asking.</summary>
|
||||
internal async Task ResetAsync(ScheduleRowViewModel row)
|
||||
{
|
||||
if (_attached is not { } scheduler || !row.IsSystem) return;
|
||||
var confirmed = _confirm(new ConfirmRequest
|
||||
{
|
||||
Heading = Loc.L("Jobs.Schedule.ResetHeading", row.Name),
|
||||
Message = Loc.L("Jobs.Schedule.ResetMessage"),
|
||||
SafeText = Loc.L("Jobs.Schedule.Keep"),
|
||||
SafeToolTip = Loc.L("Tooltips.Jobs.Schedule.KeepEdits"),
|
||||
ActionText = Loc.L("Jobs.Schedule.Reset"),
|
||||
ActionToolTip = Loc.L("Tooltips.Jobs.Schedule.Reset"),
|
||||
});
|
||||
if (!confirmed) return;
|
||||
var result = await Call(() => scheduler.ResetAsync(row.Id));
|
||||
if (result?.Schedule is { } saved) Apply(saved);
|
||||
else await ReloadAsync();
|
||||
}
|
||||
|
||||
// ---------------- Editor ----------------
|
||||
|
||||
private void New()
|
||||
{
|
||||
if (_editor is not null || !IsRunning) return;
|
||||
Editor = new ScheduleEditorViewModel(this, null);
|
||||
}
|
||||
|
||||
/// <summary>Saves what the editor holds: a new schedule, or the fields of the one it edits.</summary>
|
||||
internal async Task<ScheduleEditResult> SaveAsync(ScheduleEditorViewModel editor)
|
||||
{
|
||||
if (_attached is not { } scheduler) return new ScheduleEditResult(null, null);
|
||||
var result = editor.ScheduleId is { } id
|
||||
? await Task.Run(() => scheduler.UpdateAsync(id, editor.BuildUpdate()))
|
||||
: await Task.Run(() => scheduler.CreateAsync(editor.BuildCreate(), null));
|
||||
if (result.Schedule is { } saved)
|
||||
{
|
||||
Apply(saved);
|
||||
if (editor.ScheduleId is null && _rows.TryGetValue(saved.Id, out var created)) Selected = created;
|
||||
}
|
||||
else if (result.NotFound)
|
||||
{
|
||||
await ReloadAsync();
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>Closes <paramref name="editor"/> if it is still the open one.</summary>
|
||||
internal void CloseEditor(ScheduleEditorViewModel editor)
|
||||
{
|
||||
if (!ReferenceEquals(_editor, editor)) return;
|
||||
editor.Dispose();
|
||||
Editor = null;
|
||||
}
|
||||
|
||||
// ---------------- Events and rows ----------------
|
||||
|
||||
private void OnScheduleChanged(ScheduleDto schedule) => Post(() => Apply(schedule));
|
||||
|
||||
private void OnScheduleDeleted(Guid id) => Post(() => Remove(id));
|
||||
|
||||
private void Post(Action action)
|
||||
{
|
||||
if (_context is null || SynchronizationContext.Current == _context) action();
|
||||
else _context.Post(_ => action(), null);
|
||||
}
|
||||
|
||||
/// <summary>A schedule as the scheduler returned or announced it: its row changes, or joins the list in the scheduler's order.</summary>
|
||||
private void Apply(ScheduleDto schedule)
|
||||
{
|
||||
if (_rows.TryGetValue(schedule.Id, out var row))
|
||||
{
|
||||
var newRun = row.Schedule.LastRun != schedule.LastRun;
|
||||
var newJob = schedule.LastJobId is { } job && job != row.LastJob?.Id;
|
||||
row.Update(schedule);
|
||||
if (newJob) _ = LoadLastJobAsync(row);
|
||||
if (newRun && ReferenceEquals(_selected, row)) RunsLoading = LoadRunsAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
row = new ScheduleRowViewModel(schedule, this);
|
||||
_rows[schedule.Id] = row;
|
||||
Rows.Insert(InsertionIndex(schedule), row);
|
||||
_ = LoadLastJobAsync(row);
|
||||
RaiseState();
|
||||
}
|
||||
if (schedule.SystemKey == DesktopScheduleHost.Housekeeping) HistoryChanged?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>Where a new row goes: system schedules first, then by creation.</summary>
|
||||
private int InsertionIndex(ScheduleDto schedule)
|
||||
{
|
||||
for (var i = 0; i < Rows.Count; i++)
|
||||
{
|
||||
var other = Rows[i].Schedule;
|
||||
var before = (schedule.SystemKey is not null, other.SystemKey is not null) switch
|
||||
{
|
||||
(true, false) => true,
|
||||
(false, true) => false,
|
||||
_ => schedule.Created < other.Created,
|
||||
};
|
||||
if (before) return i;
|
||||
}
|
||||
return Rows.Count;
|
||||
}
|
||||
|
||||
private void Remove(Guid id)
|
||||
{
|
||||
if (!_rows.Remove(id, out var row)) return;
|
||||
Rows.Remove(row);
|
||||
if (ReferenceEquals(_selected, row)) Selected = null;
|
||||
RaiseState();
|
||||
}
|
||||
|
||||
/// <summary>Reads the job of the schedule's last run; a change of it announced meanwhile, or a later read, wins.</summary>
|
||||
private async Task LoadLastJobAsync(ScheduleRowViewModel row)
|
||||
{
|
||||
if (row.Schedule.LastJobId is not { } id || _database() is not { } db) return;
|
||||
var read = row.BeginLastJobRead();
|
||||
try
|
||||
{
|
||||
row.SetLoadedLastJob(await db.Jobs.GetAsync(id), read);
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("schedules", $"The last job of schedule {row.Id} could not be read", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The selected schedule's jobs, newest first; a later selection wins over a slower read.</summary>
|
||||
private async Task LoadRunsAsync()
|
||||
{
|
||||
var request = ++_runsRequest;
|
||||
var row = _selected;
|
||||
IReadOnlyList<Job> jobs = [];
|
||||
if (row is not null && _database() is { } db)
|
||||
{
|
||||
try
|
||||
{
|
||||
jobs = await db.Jobs.ListByScheduleAsync(row.Id, RunsShown);
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("schedules", $"The runs of schedule {row.Id} could not be read", ex);
|
||||
}
|
||||
}
|
||||
if (request != _runsRequest) return;
|
||||
Runs.Clear();
|
||||
foreach (var job in jobs) Runs.Add(new ScheduleRunViewModel(job, _showJob));
|
||||
RaiseRuns();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs a scheduler call off the UI thread; a failure becomes a toast and null (for a value type, ask for its nullable
|
||||
/// type: its default would read as a result).
|
||||
/// </summary>
|
||||
private async Task<T?> Call<T>(Func<Task<T>> call)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await Task.Run(call);
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
|
||||
{
|
||||
Log.Warning("schedules", "A schedule could not be changed", ex);
|
||||
_notify(Loc.L("Jobs.Schedule.Failed"), ex.Message, true);
|
||||
return default;
|
||||
}
|
||||
}
|
||||
|
||||
private void RaiseState()
|
||||
{
|
||||
OnPropertyChanged(nameof(IsRunning));
|
||||
OnPropertyChanged(nameof(IsLoaded));
|
||||
OnPropertyChanged(nameof(HasRows));
|
||||
OnPropertyChanged(nameof(IsUnavailable));
|
||||
OnPropertyChanged(nameof(NewToolTip));
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
|
||||
private void RaiseRuns()
|
||||
{
|
||||
OnPropertyChanged(nameof(HasRuns));
|
||||
OnPropertyChanged(nameof(IsRunsEmpty));
|
||||
}
|
||||
}
|
||||
@@ -189,7 +189,7 @@ public sealed class ArchiveViewModel : SectionViewModel
|
||||
|
||||
public ICommand BackupCommand { get; }
|
||||
|
||||
/// <summary>"Maintenance ▾ › Restore database…" (BRIEF §12.5): Settings › Advanced, where a daily copy is compared and restored (§6.2).</summary>
|
||||
/// <summary>"Maintenance ▾ › Restore database…" (BRIEF §12.5): Settings › Advanced, where a backup copy is compared and restored (§6.2).</summary>
|
||||
public ICommand RestoreCommand { get; }
|
||||
|
||||
public ICommand MaintenanceCommand { get; }
|
||||
@@ -844,7 +844,7 @@ public sealed class ArchiveViewModel : SectionViewModel
|
||||
if (Services.Database is not { } db) return;
|
||||
try
|
||||
{
|
||||
var path = await db.BackupAsync(Services.Environment.BackupDirectory);
|
||||
var path = await db.BackupAsync(Services.Environment.BackupDirectory, await DatabaseBackups.KeptAsync(db));
|
||||
Shell.Notify(Loc.L("Settings.Advanced.BackupDone"), Formatting.LeftToRight(Path.GetFileName(path)), Loc.L("Library.Export.Show"),
|
||||
Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
|
||||
}
|
||||
|
||||
@@ -2,229 +2,268 @@
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
|
||||
xmlns:v="clr-namespace:Chronos.Ui.Visuals;assembly=Chronos.Ui"
|
||||
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
|
||||
xmlns:s="clr-namespace:Chronos.App.Sections"
|
||||
xmlns:infra="clr-namespace:Chronos.App.Infrastructure"
|
||||
xmlns:j="clr-namespace:Chronos.App.Jobs">
|
||||
<UserControl.Resources>
|
||||
<Style x:Key="Text.Muted" TargetType="TextBlock" BasedOn="{StaticResource Text.Cell}">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsDimmed}" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<!-- Numbers stay right-aligned in both reading directions (DESIGN §4 tables). -->
|
||||
<Style x:Key="Text.MutedNumber" TargetType="TextBlock" BasedOn="{StaticResource Text.Muted}">
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
<Setter Property="FlowDirection" Value="LeftToRight" />
|
||||
</Style>
|
||||
<!-- Speeds and times left carry the language's unit ("2 د"): they read in its direction, at the end of the cell like their header. -->
|
||||
<Style x:Key="Text.MutedEnd" TargetType="TextBlock" BasedOn="{StaticResource Text.Muted}">
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
</Style>
|
||||
<Style x:Key="Text.HeaderEnd" TargetType="TextBlock" BasedOn="{StaticResource Text.Header}">
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
</Style>
|
||||
<Style x:Key="ProgressBar.Job" TargetType="ProgressBar" BasedOn="{StaticResource {x:Type ProgressBar}}">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsDone}" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Success}" />
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding IsFailed}" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Error}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<ItemsPanelTemplate x:Key="Panel.Row">
|
||||
<StackPanel Orientation="Horizontal" />
|
||||
</ItemsPanelTemplate>
|
||||
<ItemsPanelTemplate x:Key="Panel.Wrap">
|
||||
<WrapPanel />
|
||||
</ItemsPanelTemplate>
|
||||
<!-- Filter chip (Jobs.html, aria-pressed): one of a group, so screen readers hear which filter is on. -->
|
||||
<Style x:Key="RadioButton.Chip" TargetType="RadioButton" BasedOn="{StaticResource Button.Base}">
|
||||
<Setter Property="Height" Value="30" />
|
||||
<Setter Property="Padding" Value="12,0" />
|
||||
<Setter Property="Typography.NumeralAlignment" Value="Tabular" />
|
||||
<Setter Property="ui:ControlState.CornerRadius" Value="15" />
|
||||
<Style.Triggers>
|
||||
<Trigger Property="IsChecked" Value="True">
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter Property="ui:ControlState.HoverBorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<!-- A row reads as its job and state; Tab goes to its buttons. -->
|
||||
<Style x:Key="ListBoxItem.Job" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.PlainRow}">
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding AccessibleName}" />
|
||||
<Setter Property="AutomationProperties.ItemStatus" Value="{Binding StateText}" />
|
||||
</Style>
|
||||
<ResourceDictionary>
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<!-- The schedule editor (Jobs › Scheduled) opens over the whole screen. -->
|
||||
<ResourceDictionary Source="pack://application:,,,/Chronos;component/Jobs/ScheduleDialogs.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
<Style x:Key="Text.Muted" TargetType="TextBlock" BasedOn="{StaticResource Text.Cell}">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsDimmed}" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<!-- Numbers stay right-aligned in both reading directions (DESIGN §4 tables). -->
|
||||
<Style x:Key="Text.MutedNumber" TargetType="TextBlock" BasedOn="{StaticResource Text.Muted}">
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
<Setter Property="FlowDirection" Value="LeftToRight" />
|
||||
</Style>
|
||||
<!-- Speeds and times left carry the language's unit ("2 د"): they read in its direction, at the end of the cell like their header. -->
|
||||
<Style x:Key="Text.MutedEnd" TargetType="TextBlock" BasedOn="{StaticResource Text.Muted}">
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
</Style>
|
||||
<Style x:Key="Text.HeaderEnd" TargetType="TextBlock" BasedOn="{StaticResource Text.Header}">
|
||||
<Setter Property="TextAlignment" Value="Right" />
|
||||
</Style>
|
||||
<Style x:Key="ProgressBar.Job" TargetType="ProgressBar" BasedOn="{StaticResource {x:Type ProgressBar}}">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsDone}" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Success}" />
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding IsFailed}" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Error}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<ItemsPanelTemplate x:Key="Panel.Row">
|
||||
<StackPanel Orientation="Horizontal" />
|
||||
</ItemsPanelTemplate>
|
||||
<ItemsPanelTemplate x:Key="Panel.Wrap">
|
||||
<WrapPanel />
|
||||
</ItemsPanelTemplate>
|
||||
<!-- Filter chip (Jobs.html, aria-pressed): one of a group, so screen readers hear which filter is on. -->
|
||||
<Style x:Key="RadioButton.Chip" TargetType="RadioButton" BasedOn="{StaticResource Button.Base}">
|
||||
<Setter Property="Height" Value="30" />
|
||||
<Setter Property="Padding" Value="12,0" />
|
||||
<Setter Property="Typography.NumeralAlignment" Value="Tabular" />
|
||||
<Setter Property="ui:ControlState.CornerRadius" Value="15" />
|
||||
<Style.Triggers>
|
||||
<Trigger Property="IsChecked" Value="True">
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter Property="ui:ControlState.HoverBorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
<!-- A row reads as its job and state; Tab goes to its buttons. -->
|
||||
<Style x:Key="ListBoxItem.Job" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.PlainRow}">
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding AccessibleName}" />
|
||||
<Setter Property="AutomationProperties.ItemStatus" Value="{Binding StateText}" />
|
||||
</Style>
|
||||
</ResourceDictionary>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid IsEnabled="{Binding IsContentEnabled}">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Toolbar in visual (and Tab) order: state chips · search, then workers, Pause all, Clear done. The search moves under
|
||||
the chips before anything is cut (+40 % text at 1200 px). -->
|
||||
<Grid Margin="20,12">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<WrapPanel VerticalAlignment="Center">
|
||||
<ItemsControl ItemsSource="{Binding Chips}" ItemsPanel="{StaticResource Panel.Wrap}" Focusable="False" VerticalAlignment="Center">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type s:JobFilterChip}">
|
||||
<RadioButton Style="{StaticResource RadioButton.Chip}" GroupName="JobFilters" Content="{Binding Text}" IsChecked="{Binding IsSelected, Mode=OneWay}"
|
||||
Command="{Binding SelectCommand}" ToolTip="{Binding ToolTip}" Margin="0,1,8,1" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<StackPanel Orientation="Horizontal" Margin="0,1,0,1">
|
||||
<Border Width="1" Height="22" Background="{DynamicResource Brush.Stroke}" Margin="6,0,14,0" VerticalAlignment="Center" />
|
||||
<TextBox Width="240" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.Search}"
|
||||
ui:Field.Placeholder="{l:Loc Jobs.Search}" ToolTip="{l:Loc Tooltips.Jobs.Search}" AutomationProperties.Name="{l:Loc Jobs.Search}" />
|
||||
</StackPanel>
|
||||
</WrapPanel>
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center" Margin="12,0,0,0" Visibility="{Binding HasEngine, Converter={StaticResource BoolToVisibility}}">
|
||||
<Border Style="{StaticResource Pill.Auto}" Margin="0,0,10,0" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Jobs.PriorityQueue}"
|
||||
Visibility="{Binding IsPriorityQueueOn, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{l:Loc Jobs.PriorityQueue}" FontSize="{StaticResource Size.Chip}" Foreground="{DynamicResource Brush.Accent}" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<TextBlock Text="{Binding ParallelismText}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center"
|
||||
Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Jobs.Parallelism}" />
|
||||
</StackPanel>
|
||||
<Button Grid.Column="2" Content="{l:Loc Jobs.PauseAll}" Command="{Binding PauseAllCommand}" ToolTip="{l:Loc Tooltips.Jobs.PauseAll}" Margin="12,0,0,0" VerticalAlignment="Center" />
|
||||
<Button Grid.Column="3" Content="{l:Loc Jobs.ClearDone}" Command="{Binding ClearDoneCommand}" ToolTip="{l:Loc Tooltips.Jobs.ClearDone}" Margin="8,0,0,0" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
<!-- Toolbar: Queue | Scheduled (owner review 2, R10), then the tab's own tools. -->
|
||||
<DockPanel Margin="20,12">
|
||||
<v:SegmentedControl DockPanel.Dock="Left" VerticalAlignment="Center" SelectedIndex="{Binding TabIndex}" AutomationProperties.Name="{l:Loc Jobs.Tab.Name}">
|
||||
<v:SegmentedItem Content="{l:Loc Jobs.Tab.Queue}" ToolTip="{l:Loc Tooltips.Jobs.Tab.Queue}" AutomationProperties.Name="{l:Loc Jobs.Tab.Queue}" />
|
||||
<v:SegmentedItem Content="{l:Loc Jobs.Tab.Scheduled}" ToolTip="{l:Loc Tooltips.Jobs.Tab.Scheduled}" AutomationProperties.Name="{l:Loc Jobs.Tab.Scheduled}" />
|
||||
</v:SegmentedControl>
|
||||
<Border DockPanel.Dock="Left" Width="1" Height="22" Background="{DynamicResource Brush.Stroke}" Margin="14,0" VerticalAlignment="Center" />
|
||||
<Button DockPanel.Dock="Right" Content="{l:Loc Jobs.Schedule.New}" Command="{Binding Schedules.NewCommand}" ToolTip="{Binding Schedules.NewToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" VerticalAlignment="Center" Visibility="{Binding IsScheduled, Converter={StaticResource BoolToVisibility}}" />
|
||||
<!-- Queue toolbar in visual (and Tab) order: state chips · search, then workers, Pause all, Clear done. The search moves under
|
||||
the chips before anything is cut (+40 % text at 1200 px). -->
|
||||
<Grid Visibility="{Binding IsQueue, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<WrapPanel VerticalAlignment="Center">
|
||||
<ItemsControl ItemsSource="{Binding Chips}" ItemsPanel="{StaticResource Panel.Wrap}" Focusable="False" VerticalAlignment="Center">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type s:JobFilterChip}">
|
||||
<RadioButton Style="{StaticResource RadioButton.Chip}" GroupName="JobFilters" Content="{Binding Text}" IsChecked="{Binding IsSelected, Mode=OneWay}"
|
||||
Command="{Binding SelectCommand}" ToolTip="{Binding ToolTip}" Margin="0,1,8,1" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<StackPanel Orientation="Horizontal" Margin="0,1,0,1">
|
||||
<Border Width="1" Height="22" Background="{DynamicResource Brush.Stroke}" Margin="6,0,14,0" VerticalAlignment="Center" />
|
||||
<TextBox Width="240" Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" ui:Field.Glyph="{StaticResource Icon.Search}"
|
||||
ui:Field.Placeholder="{l:Loc Jobs.Search}" ToolTip="{l:Loc Tooltips.Jobs.Search}" AutomationProperties.Name="{l:Loc Jobs.Search}" />
|
||||
</StackPanel>
|
||||
</WrapPanel>
|
||||
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center" Margin="12,0,0,0" Visibility="{Binding HasEngine, Converter={StaticResource BoolToVisibility}}">
|
||||
<Border Style="{StaticResource Pill.Auto}" Margin="0,0,10,0" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Jobs.PriorityQueue}"
|
||||
Visibility="{Binding IsPriorityQueueOn, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{l:Loc Jobs.PriorityQueue}" FontSize="{StaticResource Size.Chip}" Foreground="{DynamicResource Brush.Accent}" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<TextBlock Text="{Binding ParallelismText}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center"
|
||||
Typography.NumeralAlignment="Tabular" ToolTip="{l:Loc Tooltips.Jobs.Parallelism}" />
|
||||
</StackPanel>
|
||||
<Button Grid.Column="2" Content="{l:Loc Jobs.PauseAll}" Command="{Binding PauseAllCommand}" ToolTip="{l:Loc Tooltips.Jobs.PauseAll}" Margin="12,0,0,0" VerticalAlignment="Center" />
|
||||
<Button Grid.Column="3" Content="{l:Loc Jobs.ClearDone}" Command="{Binding ClearDoneCommand}" ToolTip="{l:Loc Tooltips.Jobs.ClearDone}" Margin="8,0,0,0" VerticalAlignment="Center" />
|
||||
</Grid>
|
||||
</DockPanel>
|
||||
|
||||
<Border Grid.Row="1" Style="{StaticResource Border.Panel}" Margin="20,0,20,12" Visibility="{Binding HasRows, Converter={StaticResource BoolToVisibility}}">
|
||||
<!-- Header and rows share their columns (Jobs.html grid-template-columns): the same 14 px padding, the actions column sized
|
||||
by its widest row in every row, and the list's scroll-bar gutter always kept (10 px), mirrored on the header's right. -->
|
||||
<Grid Grid.IsSharedSizeScope="True">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<!-- ===================== Queue ===================== -->
|
||||
<Grid Grid.Row="1" Visibility="{Binding IsQueue, Converter={StaticResource BoolToVisibility}}">
|
||||
<Border Style="{StaticResource Border.Panel}" Margin="20,0,20,12" Visibility="{Binding HasRows, Converter={StaticResource BoolToVisibility}}">
|
||||
<!-- Header and rows share their columns (Jobs.html grid-template-columns): the same 14 px padding, the actions column sized
|
||||
by its widest row in every row, and the list's scroll-bar gutter always kept (10 px), mirrored on the header's right. -->
|
||||
<Grid Grid.IsSharedSizeScope="True">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Header -->
|
||||
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,8,24,8">
|
||||
<Grid>
|
||||
<!-- Kind, Where and State share the width with Target and Progress (Target, whose name is in its tooltip, gives way first), so the actions keep
|
||||
their room at 1200 px beside the 200 px rail in every language; a cut kind, place, state or header shows whole in its tooltip. On wide
|
||||
windows Kind, Where and State stop growing and Target takes the rest (Jobs.html). -->
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="28" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="90" MaxWidth="140" />
|
||||
<ColumnDefinition Width="1.6*" MinWidth="84" />
|
||||
<ColumnDefinition Width="*" MinWidth="104" MaxWidth="240" />
|
||||
<ColumnDefinition Width="90" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition Width="0.6*" MinWidth="80" MaxWidth="140" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="116" MaxWidth="170" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="150" SharedSizeGroup="JobActions" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Kind}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Kind}" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Target}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Target}" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Progress}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Progress}" />
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.HeaderEnd}" Text="{l:Loc Jobs.Column.Speed}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Speed}" />
|
||||
<TextBlock Grid.Column="5" Style="{StaticResource Text.HeaderEnd}" Text="{l:Loc Jobs.Column.Left}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Left}" />
|
||||
<TextBlock Grid.Column="6" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Where}" Margin="16,0,0,0" ToolTip="{l:Loc Jobs.Column.Where}" />
|
||||
<TextBlock Grid.Column="7" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.State}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.State}" />
|
||||
<!-- Header -->
|
||||
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,8,24,8">
|
||||
<Grid>
|
||||
<!-- Kind, Where and State share the width with Target and Progress (Target, whose name is in its tooltip, gives way first), so the actions keep
|
||||
their room at 1200 px beside the 200 px rail in every language; a cut kind, place, state or header shows whole in its tooltip. On wide
|
||||
windows Kind, Where and State stop growing and Target takes the rest (Jobs.html). -->
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="28" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="90" MaxWidth="140" />
|
||||
<ColumnDefinition Width="1.6*" MinWidth="84" />
|
||||
<ColumnDefinition Width="*" MinWidth="104" MaxWidth="240" />
|
||||
<ColumnDefinition Width="90" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition Width="0.6*" MinWidth="80" MaxWidth="140" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="116" MaxWidth="170" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="150" SharedSizeGroup="JobActions" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Kind}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Kind}" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Target}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Target}" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Progress}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Progress}" />
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.HeaderEnd}" Text="{l:Loc Jobs.Column.Speed}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Speed}" />
|
||||
<TextBlock Grid.Column="5" Style="{StaticResource Text.HeaderEnd}" Text="{l:Loc Jobs.Column.Left}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.Left}" />
|
||||
<TextBlock Grid.Column="6" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.Where}" Margin="16,0,0,0" ToolTip="{l:Loc Jobs.Column.Where}" />
|
||||
<TextBlock Grid.Column="7" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Column.State}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Column.State}" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Rows: queue order, then the history; expandable log tail. Tab walks every row button (the rows take no focus). -->
|
||||
<ListBox x:Name="JobList" Grid.Row="1" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.Job}"
|
||||
VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.ScrollUnit="Pixel"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.ScrollChanged="OnScrollChanged"
|
||||
KeyboardNavigation.TabNavigation="Continue" AutomationProperties.Name="{l:Loc Shell.Nav.Jobs}">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type j:JobRowViewModel}">
|
||||
<StackPanel>
|
||||
<Border x:Name="Row" Height="38" Background="Transparent" Padding="14,0">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="28" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="90" MaxWidth="140" />
|
||||
<ColumnDefinition Width="1.6*" MinWidth="84" />
|
||||
<ColumnDefinition Width="*" MinWidth="104" MaxWidth="240" />
|
||||
<ColumnDefinition Width="90" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition Width="0.6*" MinWidth="80" MaxWidth="140" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="116" MaxWidth="170" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="150" SharedSizeGroup="JobActions" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Button x:Name="Toggle" Style="{StaticResource Button.IconSubtle}" Width="22" Height="22" MinWidth="22" HorizontalAlignment="Left"
|
||||
ui:ButtonIcon.Glyph="{StaticResource Icon.ChevronRight}" Command="{Binding ToggleLogCommand}"
|
||||
ToolTip="{Binding ToggleToolTip}" AutomationProperties.Name="{Binding ToggleName}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Muted}" Text="{Binding Kind}" Margin="10,0,0,0" ToolTip="{Binding Kind}" />
|
||||
<!-- A job a schedule queued carries the "Scheduled" pill after its target, which gives way first. -->
|
||||
<DockPanel Grid.Column="2" Margin="10,0,0,0">
|
||||
<Border DockPanel.Dock="Right" Style="{StaticResource Pill.Auto}" Height="20" Padding="7,0" Margin="8,0,0,0" VerticalAlignment="Center"
|
||||
ToolTip="{l:Loc Tooltips.Jobs.Scheduled}" Visibility="{Binding IsScheduled, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{l:Loc Jobs.Scheduled}" FontSize="{StaticResource Size.Chip}" Foreground="{DynamicResource Brush.Accent}" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Target}" ToolTip="{Binding Target}" />
|
||||
</DockPanel>
|
||||
<Grid Grid.Column="3" Margin="10,0,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="44" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ProgressBar Style="{StaticResource ProgressBar.Job}" Maximum="1" Value="{Binding Progress, Mode=OneWay}" VerticalAlignment="Center"
|
||||
AutomationProperties.Name="{Binding AccessibleName}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.MutedNumber}" Text="{Binding PercentText}" />
|
||||
</Grid>
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.MutedEnd}" Text="{Binding SpeedText}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="5" Style="{StaticResource Text.MutedEnd}" Text="{Binding LeftText}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="6" Style="{StaticResource Text.Muted}" Text="{Binding WhereText}" Margin="16,0,0,0" ToolTip="{Binding WhereText}" />
|
||||
<!-- A new state is announced with its job; progress ticks are not. -->
|
||||
<ui:StatusGlyph Grid.Column="7" Kind="{Binding StateKind}" Text="{Binding StateText}" ToolTip="{Binding StateToolTip}"
|
||||
FontSize="13" VerticalAlignment="Center" Margin="10,0,0,0"
|
||||
AutomationProperties.LiveSetting="Polite" infra:LiveRegion.Text="{Binding StateAnnouncement}" />
|
||||
<ItemsControl Grid.Column="8" ItemsSource="{Binding Actions}" ItemsPanel="{StaticResource Panel.Row}" Focusable="False"
|
||||
VerticalAlignment="Center" Margin="10,0,0,0">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type j:JobAction}">
|
||||
<Button Style="{StaticResource Button.Row}" Content="{Binding Text}" Command="{Binding Command}" ToolTip="{Binding ToolTip}"
|
||||
AutomationProperties.Name="{Binding AccessibleName}" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</Grid>
|
||||
</Border>
|
||||
<!-- The log keeps its left-to-right lines (times, paths, numbers) in every language. -->
|
||||
<Border x:Name="Log" Background="{DynamicResource Brush.Bg}" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0"
|
||||
Padding="52,10,14,12" Visibility="Collapsed">
|
||||
<TextBlock Style="{StaticResource Text.Log}" Text="{Binding LogText}" FlowDirection="LeftToRight" />
|
||||
</Border>
|
||||
</StackPanel>
|
||||
<DataTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding IsExpanded}" Value="True">
|
||||
<Setter TargetName="Log" Property="Visibility" Value="Visible" />
|
||||
<Setter TargetName="Row" Property="Background" Value="{DynamicResource Brush.Card}" />
|
||||
<Setter TargetName="Toggle" Property="ui:ButtonIcon.Glyph" Value="{StaticResource Icon.ChevronDown}" />
|
||||
</DataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
|
||||
<!-- Footer -->
|
||||
<Border Grid.Row="2" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0" Padding="14,8">
|
||||
<DockPanel LastChildFill="False" TextElement.FontSize="12">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Jobs.RenderingSettings}" Command="{Binding RenderingSettingsCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Jobs.RenderingSettings}" />
|
||||
<TextBlock Text="{Binding HistoryText}" Foreground="{DynamicResource Brush.TextMuted}" ToolTip="{l:Loc Tooltips.Jobs.History}" />
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Rows: queue order, then the history; expandable log tail. Tab walks every row button (the rows take no focus). -->
|
||||
<ListBox x:Name="JobList" Grid.Row="1" ItemsSource="{Binding Rows}" ItemContainerStyle="{StaticResource ListBoxItem.Job}"
|
||||
VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.ScrollUnit="Pixel"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.ScrollChanged="OnScrollChanged"
|
||||
KeyboardNavigation.TabNavigation="Continue" AutomationProperties.Name="{l:Loc Shell.Nav.Jobs}">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type j:JobRowViewModel}">
|
||||
<StackPanel>
|
||||
<Border x:Name="Row" Height="38" Background="Transparent" Padding="14,0">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="28" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="90" MaxWidth="140" />
|
||||
<ColumnDefinition Width="1.6*" MinWidth="84" />
|
||||
<ColumnDefinition Width="*" MinWidth="104" MaxWidth="240" />
|
||||
<ColumnDefinition Width="90" />
|
||||
<ColumnDefinition Width="80" />
|
||||
<ColumnDefinition Width="0.6*" MinWidth="80" MaxWidth="140" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="116" MaxWidth="170" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="150" SharedSizeGroup="JobActions" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Button x:Name="Toggle" Style="{StaticResource Button.IconSubtle}" Width="22" Height="22" MinWidth="22" HorizontalAlignment="Left"
|
||||
ui:ButtonIcon.Glyph="{StaticResource Icon.ChevronRight}" Command="{Binding ToggleLogCommand}"
|
||||
ToolTip="{Binding ToggleToolTip}" AutomationProperties.Name="{Binding ToggleName}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Muted}" Text="{Binding Kind}" Margin="10,0,0,0" ToolTip="{Binding Kind}" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding Target}" Margin="10,0,0,0" ToolTip="{Binding Target}" />
|
||||
<Grid Grid.Column="3" Margin="10,0,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="44" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ProgressBar Style="{StaticResource ProgressBar.Job}" Maximum="1" Value="{Binding Progress, Mode=OneWay}" VerticalAlignment="Center"
|
||||
AutomationProperties.Name="{Binding AccessibleName}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.MutedNumber}" Text="{Binding PercentText}" />
|
||||
</Grid>
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.MutedEnd}" Text="{Binding SpeedText}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="5" Style="{StaticResource Text.MutedEnd}" Text="{Binding LeftText}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="6" Style="{StaticResource Text.Muted}" Text="{Binding WhereText}" Margin="16,0,0,0" ToolTip="{Binding WhereText}" />
|
||||
<!-- A new state is announced with its job; progress ticks are not. -->
|
||||
<ui:StatusGlyph Grid.Column="7" Kind="{Binding StateKind}" Text="{Binding StateText}" ToolTip="{Binding StateToolTip}"
|
||||
FontSize="13" VerticalAlignment="Center" Margin="10,0,0,0"
|
||||
AutomationProperties.LiveSetting="Polite" infra:LiveRegion.Text="{Binding StateAnnouncement}" />
|
||||
<ItemsControl Grid.Column="8" ItemsSource="{Binding Actions}" ItemsPanel="{StaticResource Panel.Row}" Focusable="False"
|
||||
VerticalAlignment="Center" Margin="10,0,0,0">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type j:JobAction}">
|
||||
<Button Style="{StaticResource Button.Row}" Content="{Binding Text}" Command="{Binding Command}" ToolTip="{Binding ToolTip}"
|
||||
AutomationProperties.Name="{Binding AccessibleName}" />
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</Grid>
|
||||
</Border>
|
||||
<!-- The log keeps its left-to-right lines (times, paths, numbers) in every language. -->
|
||||
<Border x:Name="Log" Background="{DynamicResource Brush.Bg}" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0"
|
||||
Padding="52,10,14,12" Visibility="Collapsed">
|
||||
<TextBlock Style="{StaticResource Text.Log}" Text="{Binding LogText}" FlowDirection="LeftToRight" />
|
||||
</Border>
|
||||
</StackPanel>
|
||||
<DataTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding IsExpanded}" Value="True">
|
||||
<Setter TargetName="Log" Property="Visibility" Value="Visible" />
|
||||
<Setter TargetName="Row" Property="Background" Value="{DynamicResource Brush.Card}" />
|
||||
<Setter TargetName="Toggle" Property="ui:ButtonIcon.Glyph" Value="{StaticResource Icon.ChevronDown}" />
|
||||
</DataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
|
||||
<!-- Footer -->
|
||||
<Border Grid.Row="2" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0" Padding="14,8">
|
||||
<DockPanel LastChildFill="False" TextElement.FontSize="12">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Jobs.RenderingSettings}" Command="{Binding RenderingSettingsCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Jobs.RenderingSettings}" />
|
||||
<TextBlock Text="{Binding HistoryText}" Foreground="{DynamicResource Brush.TextMuted}" ToolTip="{l:Loc Tooltips.Jobs.History}" />
|
||||
</DockPanel>
|
||||
</Border>
|
||||
<ui:EmptyState Message="{l:Loc Jobs.Empty}" Visibility="{Binding IsEmpty, Converter={StaticResource BoolToVisibility}}">
|
||||
<Button Content="{l:Loc Shell.Nav.Import}" Command="{Binding ImportCommand}" ToolTip="{l:Loc Tooltips.Jobs.Import}" />
|
||||
</ui:EmptyState>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<ui:EmptyState Grid.Row="1" Message="{l:Loc Jobs.Empty}" Visibility="{Binding IsEmpty, Converter={StaticResource BoolToVisibility}}">
|
||||
<Button Content="{l:Loc Shell.Nav.Import}" Command="{Binding ImportCommand}" ToolTip="{l:Loc Tooltips.Jobs.Import}" />
|
||||
</ui:EmptyState>
|
||||
<!-- ===================== Scheduled ===================== -->
|
||||
<ContentControl Grid.Row="1" Content="{Binding Schedules}" Focusable="False" Visibility="{Binding IsScheduled, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
|
||||
<!-- The schedule editor over a scrim; the keyboard stays inside it. -->
|
||||
<Grid DataContext="{Binding Schedules}" Visibility="{Binding IsEditorOpen, Converter={StaticResource BoolToVisibility}}" KeyboardNavigation.TabNavigation="Cycle"
|
||||
KeyboardNavigation.ControlTabNavigation="Cycle" KeyboardNavigation.DirectionalNavigation="Contained">
|
||||
<Border Background="{DynamicResource Brush.Scrim}" />
|
||||
<ContentPresenter x:Name="DialogHost" Content="{Binding Editor}" Margin="20" />
|
||||
</Grid>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -1,10 +1,23 @@
|
||||
using System.ComponentModel;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Threading;
|
||||
using Chronos.App.Jobs;
|
||||
|
||||
namespace Chronos.App.Sections;
|
||||
|
||||
public partial class JobsView : UserControl
|
||||
{
|
||||
public JobsView() => InitializeComponent();
|
||||
private JobsViewModel? _model;
|
||||
private IInputElement? _beforeDialog;
|
||||
|
||||
public JobsView()
|
||||
{
|
||||
InitializeComponent();
|
||||
DataContextChanged += OnDataContextChanged;
|
||||
}
|
||||
|
||||
/// <summary>Loads older history when the list scrolls near its end.</summary>
|
||||
private void OnScrollChanged(object sender, ScrollChangedEventArgs e)
|
||||
@@ -12,4 +25,51 @@ public partial class JobsView : UserControl
|
||||
if (DataContext is not JobsViewModel vm || e.ExtentHeight <= 0) return;
|
||||
if (e.VerticalOffset + e.ViewportHeight >= e.ExtentHeight - Math.Max(e.ViewportHeight, 200)) _ = vm.LoadMoreAsync();
|
||||
}
|
||||
|
||||
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (_model is not null)
|
||||
{
|
||||
_model.RowRevealRequested -= OnRevealRequested;
|
||||
_model.Schedules.PropertyChanged -= OnSchedulesChanged;
|
||||
}
|
||||
_model = e.NewValue as JobsViewModel;
|
||||
if (_model is not null)
|
||||
{
|
||||
_model.RowRevealRequested += OnRevealRequested;
|
||||
_model.Schedules.PropertyChanged += OnSchedulesChanged;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A job shown from Jobs › Scheduled: its row comes into view (the list is visible again by then) and takes the keyboard.</summary>
|
||||
private void OnRevealRequested(JobRowViewModel row) =>
|
||||
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () =>
|
||||
{
|
||||
JobList.ScrollIntoView(row);
|
||||
JobList.UpdateLayout();
|
||||
if (JobList.ItemContainerGenerator.ContainerFromItem(row) is ListBoxItem item) item.MoveFocus(new TraversalRequest(FocusNavigationDirection.First));
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// The schedule editor takes the keyboard when it opens (its first field); when it closes, the keyboard goes back to the
|
||||
/// control that opened it while that can still take it.
|
||||
/// </summary>
|
||||
private void OnSchedulesChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName != nameof(SchedulesViewModel.Editor) || _model is not { } model) return;
|
||||
if (model.Schedules.Editor is not null)
|
||||
{
|
||||
if (!IsVisible) return;
|
||||
_beforeDialog ??= Keyboard.FocusedElement is Visual focused && IsAncestorOf(focused) ? Keyboard.FocusedElement : null;
|
||||
Dispatcher.BeginInvoke(DispatcherPriority.Input, () => DialogHost.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)));
|
||||
return;
|
||||
}
|
||||
var back = _beforeDialog;
|
||||
_beforeDialog = null;
|
||||
if (!IsVisible) return;
|
||||
Dispatcher.BeginInvoke(DispatcherPriority.Input, () =>
|
||||
{
|
||||
if (back is UIElement { IsVisible: true, IsEnabled: true, Focusable: true } element) element.Focus();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -49,10 +49,11 @@ public sealed class JobFilterChip(JobFilter filter, Action<JobFilter> select) :
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Jobs (BRIEF §12.6, Jobs.html): queue and history with live progress from the engine (batched to about 10
|
||||
/// updates a second), filters, queue order, an expandable log tail per job, and the row actions. Also feeds the
|
||||
/// shell's job bar, the status strip and the rail badge (running jobs, and failures not seen on this screen yet), and
|
||||
/// raises the toast of a long operation that ends (<see cref="JobNotices"/>), whichever screen started it.
|
||||
/// Jobs (BRIEF §12.6, Jobs.html), two tabs: Queue, the queue and history with live progress from the engine (batched to
|
||||
/// about 10 updates a second), filters, queue order, an expandable log tail per job, and the row actions; Scheduled
|
||||
/// (owner review 2, R10), the schedules of this PC (<see cref="SchedulesViewModel"/>). Also feeds the shell's job bar, the
|
||||
/// status strip and the rail badge (running jobs, and failures not seen on this screen yet), and raises the toast of a
|
||||
/// long operation that ends (<see cref="JobNotices"/>), whichever screen started it.
|
||||
/// </summary>
|
||||
public sealed class JobsViewModel : SectionViewModel
|
||||
{
|
||||
@@ -77,6 +78,7 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
private bool _hasMore;
|
||||
private bool _loading;
|
||||
private bool _hasLoaded;
|
||||
private int _tabIndex;
|
||||
|
||||
public JobsViewModel(ShellViewModel shell)
|
||||
: base(SectionKey.Jobs, "Icon.Jobs")
|
||||
@@ -94,10 +96,43 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
});
|
||||
LoadMoreCommand = new RelayCommand(() => _ = LoadMoreAsync());
|
||||
ImportCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Import));
|
||||
Schedules = new SchedulesViewModel(() => Shell.Services.Scheduler, () => Shell.Services.Database, request => Shell.Services.Dialogs.Confirm(request),
|
||||
(title, message, isError) => Shell.Notify(title, message, isError: isError), ShowJobAsync);
|
||||
Schedules.HistoryChanged += () => OnPropertyChanged(nameof(HistoryText));
|
||||
Schedules.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName is nameof(SchedulesViewModel.IsContentEnabled) or "" or null) OnPropertyChanged(nameof(IsContentEnabled));
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>A row the screen should bring into view and expand (a job shown from Jobs › Scheduled).</summary>
|
||||
public event Action<JobRowViewModel>? RowRevealRequested;
|
||||
|
||||
public ShellViewModel Shell { get; }
|
||||
|
||||
/// <summary>Jobs › Scheduled.</summary>
|
||||
public SchedulesViewModel Schedules { get; }
|
||||
|
||||
/// <summary>0 = Queue, 1 = Scheduled (the segmented control's index). Scheduled, shown, reads the actions' availability again.</summary>
|
||||
public int TabIndex
|
||||
{
|
||||
get => _tabIndex;
|
||||
set
|
||||
{
|
||||
if (value is < 0 or > 1 || !Set(ref _tabIndex, value)) return;
|
||||
OnPropertyChanged(nameof(IsQueue));
|
||||
OnPropertyChanged(nameof(IsScheduled));
|
||||
if (IsScheduled) _ = Schedules.RefreshActionsAsync();
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsQueue => _tabIndex == 0;
|
||||
|
||||
public bool IsScheduled => _tabIndex == 1;
|
||||
|
||||
/// <summary>The screen behind the schedule editor takes neither clicks nor keyboard focus.</summary>
|
||||
public bool IsContentEnabled => Schedules.IsContentEnabled;
|
||||
|
||||
/// <summary>Rows in display order for the current filter and search.</summary>
|
||||
public ObservableCollection<JobRowViewModel> Rows { get; } = [];
|
||||
|
||||
@@ -141,8 +176,8 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
/// <summary>The priority queue of Settings › Rendering is on: higher jobs pause the running one.</summary>
|
||||
public bool IsPriorityQueueOn => HasEngine && Shell.Services.Settings.PriorityQueue;
|
||||
|
||||
/// <summary>"History keeps 90 days".</summary>
|
||||
public string HistoryText => Loc.Plural("Jobs.History", (long)new JobEngineOptions().HistoryRetention.TotalDays);
|
||||
/// <summary>"History keeps 90 days": the age limit of the housekeeping schedule's job-history step; "Full history kept" without one.</summary>
|
||||
public string HistoryText => Schedules.HistoryDays is { } days ? Loc.Plural("Jobs.History", days) : Loc.L("Jobs.HistoryKept");
|
||||
|
||||
public bool IsEmpty => _hasLoaded && Rows.Count == 0;
|
||||
|
||||
@@ -154,9 +189,11 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
|
||||
private DateTimeOffset? ClearedAt => Shell.Services.Settings.JobsClearedAt;
|
||||
|
||||
/// <summary>Subscribes to the engine and loads the first page of jobs.</summary>
|
||||
/// <summary>Subscribes to the engine and loads the first page of jobs; the Scheduled tab follows the schedules once they run.</summary>
|
||||
public void Attach()
|
||||
{
|
||||
// Without an index the Scheduled tab says the schedules do not run.
|
||||
_ = Schedules.AttachAsync(Shell.Services.SchedulerReady);
|
||||
_queue = Shell.Services.Jobs;
|
||||
if (_queue is null)
|
||||
{
|
||||
@@ -178,6 +215,7 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
_queue.Progress -= OnProgress;
|
||||
}
|
||||
_throttle?.Dispose();
|
||||
Schedules.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
@@ -234,6 +272,7 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
var before = _model[job.Id]?.State;
|
||||
_model.Apply(job);
|
||||
Follow(before, job);
|
||||
Schedules.OnJob(job);
|
||||
}
|
||||
foreach (var p in progress) _model.Apply(p);
|
||||
foreach (var ending in _endings.Take(_model.IsBusy)) Shell.ShowToast(ToastFor(ending));
|
||||
@@ -241,9 +280,13 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
UpdateShell();
|
||||
}
|
||||
|
||||
/// <summary>Failures seen on this screen no longer count on the rail.</summary>
|
||||
/// <summary>
|
||||
/// Failures seen on this screen no longer count on the rail; back on Scheduled (from Settings, say), the actions'
|
||||
/// availability is read again.
|
||||
/// </summary>
|
||||
protected override void OnActivated()
|
||||
{
|
||||
if (IsScheduled) _ = Schedules.RefreshActionsAsync();
|
||||
if (_unseenFailures.Count == 0) return;
|
||||
_unseenFailures.Clear();
|
||||
UpdateShell();
|
||||
@@ -344,6 +387,38 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
|
||||
private void SelectFilter(JobFilter filter) => Filter = filter;
|
||||
|
||||
/// <summary>
|
||||
/// Shows a job in the Queue tab (from a schedule's last runs): every filter off, its row read when the list has not
|
||||
/// loaded it yet, expanded with its log, and brought into view.
|
||||
/// </summary>
|
||||
internal async Task ShowJobAsync(Guid jobId)
|
||||
{
|
||||
TabIndex = 0;
|
||||
Filter = JobFilter.All;
|
||||
SearchText = string.Empty;
|
||||
if (_model[jobId] is null && _queue is not null)
|
||||
{
|
||||
var stamp = _model.Stamp;
|
||||
try
|
||||
{
|
||||
if (await _queue.GetAsync(jobId) is { } job) _model.ApplyLoaded(job, stamp);
|
||||
}
|
||||
catch (DatabaseException ex)
|
||||
{
|
||||
Log.Warning("jobs", $"Job {jobId} could not be read", ex);
|
||||
}
|
||||
SyncRows();
|
||||
}
|
||||
if (!_rows.TryGetValue(jobId, out var row) || !Rows.Contains(row))
|
||||
{
|
||||
// Hidden by Clear done: the history keeps it, the list no longer shows it.
|
||||
Shell.Notify(Loc.L("Jobs.Schedule.JobHidden"), Loc.L("Tooltips.Jobs.Schedule.JobHidden"));
|
||||
return;
|
||||
}
|
||||
row.IsExpanded = true;
|
||||
RowRevealRequested?.Invoke(row);
|
||||
}
|
||||
|
||||
/// <summary>Brings <see cref="Rows"/> to the model's order with moves (rows keep their expanded log).</summary>
|
||||
private void SyncRows()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
<UserControl x:Class="Chronos.App.Sections.SchedulesView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
|
||||
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
|
||||
xmlns:infra="clr-namespace:Chronos.App.Infrastructure"
|
||||
xmlns:j="clr-namespace:Chronos.App.Jobs">
|
||||
<!-- Jobs › Scheduled (owner review 2, R10): the schedules of this PC, and the last runs of the selected one. -->
|
||||
<UserControl.Resources>
|
||||
<Style x:Key="Text.Muted" TargetType="TextBlock" BasedOn="{StaticResource Text.Cell}">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
|
||||
</Style>
|
||||
<!-- A schedule row: selecting it shows its last runs; it reads as its name, action and recurrence, its last result as its status. -->
|
||||
<Style x:Key="ListBoxItem.Schedule" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
|
||||
<Setter Property="Padding" Value="0" />
|
||||
<Setter Property="FocusVisualStyle" Value="{StaticResource Focus.Inset}" />
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding AccessibleName}" />
|
||||
<Setter Property="AutomationProperties.ItemStatus" Value="{Binding LastText}" />
|
||||
</Style>
|
||||
<Style x:Key="ListBoxItem.Run" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.PlainRow}">
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding AccessibleName}" />
|
||||
</Style>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Grid Margin="20,0,20,12">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="*" MinHeight="150" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<Border Style="{StaticResource Border.Panel}" Visibility="{Binding HasRows, Converter={StaticResource BoolToVisibility}}">
|
||||
<!-- Header and rows share their columns: the same 14 px padding, the actions column sized by its widest row, the scroll-bar gutter kept. -->
|
||||
<Grid Grid.IsSharedSizeScope="True">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,8,24,8">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="56" />
|
||||
<ColumnDefinition Width="1.2*" MinWidth="120" />
|
||||
<ColumnDefinition Width="0.9*" MinWidth="100" MaxWidth="190" />
|
||||
<ColumnDefinition Width="1.1*" MinWidth="120" MaxWidth="240" />
|
||||
<ColumnDefinition Width="0.8*" MinWidth="110" MaxWidth="170" />
|
||||
<ColumnDefinition Width="0.8*" MinWidth="110" MaxWidth="180" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="200" SharedSizeGroup="ScheduleActions" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Schedule.Column.On}" ToolTip="{l:Loc Jobs.Schedule.Column.On}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Schedule.Column.Name}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Schedule.Column.Name}" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Schedule.Column.Action}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Schedule.Column.Action}" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Schedule.Column.When}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Schedule.Column.When}" />
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Schedule.Column.Next}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Schedule.Column.Next}" />
|
||||
<TextBlock Grid.Column="5" Style="{StaticResource Text.Header}" Text="{l:Loc Jobs.Schedule.Column.Last}" Margin="10,0,0,0" ToolTip="{l:Loc Jobs.Schedule.Column.Last}" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- Rows: the arrow keys move the selection; Tab walks the switch and the buttons of each row. -->
|
||||
<ListBox x:Name="ScheduleList" Grid.Row="1" ItemsSource="{Binding Rows}" SelectedItem="{Binding Selected}" ItemContainerStyle="{StaticResource ListBoxItem.Schedule}"
|
||||
ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Visible" KeyboardNavigation.TabNavigation="Continue"
|
||||
AutomationProperties.Name="{l:Loc Jobs.Tab.Scheduled}">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type j:ScheduleRowViewModel}">
|
||||
<Grid Height="38" Margin="14,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="56" />
|
||||
<ColumnDefinition Width="1.2*" MinWidth="120" />
|
||||
<ColumnDefinition Width="0.9*" MinWidth="100" MaxWidth="190" />
|
||||
<ColumnDefinition Width="1.1*" MinWidth="120" MaxWidth="240" />
|
||||
<ColumnDefinition Width="0.8*" MinWidth="110" MaxWidth="170" />
|
||||
<ColumnDefinition Width="0.8*" MinWidth="110" MaxWidth="180" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="200" SharedSizeGroup="ScheduleActions" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<CheckBox Style="{StaticResource CheckBox.Switch}" IsChecked="{Binding IsEnabled}" ToolTip="{Binding EnabledToolTip}" VerticalAlignment="Center"
|
||||
HorizontalAlignment="Left" AutomationProperties.Name="{Binding EnabledName}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Name}" ToolTip="{Binding NameToolTip}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Muted}" Text="{Binding ActionText}" ToolTip="{Binding ActionToolTip}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.Cell}" Text="{Binding WhenText}" ToolTip="{Binding WhenToolTip}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.Muted}" Text="{Binding NextText}" ToolTip="{Binding NextToolTip}" Margin="10,0,0,0" />
|
||||
<!-- A new result is announced with its schedule. -->
|
||||
<ui:StatusGlyph Grid.Column="5" Kind="{Binding LastKind}" Text="{Binding LastText}" ToolTip="{Binding LastToolTip}" FontSize="13" VerticalAlignment="Center"
|
||||
Margin="10,0,0,0" AutomationProperties.LiveSetting="Polite" infra:LiveRegion.Text="{Binding LastText}" />
|
||||
<StackPanel Grid.Column="6" Orientation="Horizontal" VerticalAlignment="Center" Margin="10,0,0,0">
|
||||
<Button Style="{StaticResource Button.Row}" Content="{l:Loc Jobs.Schedule.RunNow}" Command="{Binding RunNowCommand}" ToolTip="{Binding RunNowToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{Binding RunNowName}" />
|
||||
<Button Style="{StaticResource Button.Row}" Content="{l:Loc Jobs.Schedule.Edit}" Command="{Binding EditCommand}" ToolTip="{l:Loc Tooltips.Jobs.Schedule.Edit}"
|
||||
AutomationProperties.Name="{Binding EditName}" />
|
||||
<Button Style="{StaticResource Button.Row}" Content="{l:Loc Jobs.Schedule.Reset}" Command="{Binding ResetCommand}" ToolTip="{l:Loc Tooltips.Jobs.Schedule.Reset}"
|
||||
AutomationProperties.Name="{Binding ResetName}" Visibility="{Binding IsSystem, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button Style="{StaticResource Button.Row}" Content="{l:Loc Jobs.Schedule.Delete}" Command="{Binding DeleteCommand}" ToolTip="{l:Loc Tooltips.Jobs.Schedule.Delete}"
|
||||
AutomationProperties.Name="{Binding DeleteName}"
|
||||
Visibility="{Binding IsSystem, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<!-- The selected schedule's last runs: Show in queue opens the job's row in the Queue tab. -->
|
||||
<Border Grid.Row="1" Style="{StaticResource Border.Panel}" Margin="0,12,0,0" MaxHeight="260" Visibility="{Binding HasSelection, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,8">
|
||||
<TextBlock Text="{Binding RunsHeading}" Style="{StaticResource Text.PanelTitle}" FontSize="13" TextTrimming="CharacterEllipsis" ToolTip="{l:Loc Tooltips.Jobs.Schedule.Runs}" />
|
||||
</Border>
|
||||
<ListBox Grid.Row="1" ItemsSource="{Binding Runs}" ItemContainerStyle="{StaticResource ListBoxItem.Run}" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
|
||||
KeyboardNavigation.TabNavigation="Continue" AutomationProperties.Name="{Binding RunsHeading}"
|
||||
Visibility="{Binding HasRuns, Converter={StaticResource BoolToVisibility}}">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type j:ScheduleRunViewModel}">
|
||||
<Grid Height="34" Margin="14,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="0.6*" MinWidth="110" MaxWidth="170" />
|
||||
<ColumnDefinition Width="0.7*" MinWidth="90" MaxWidth="150" />
|
||||
<ColumnDefinition Width="1.4*" MinWidth="120" />
|
||||
<ColumnDefinition Width="0.8*" MinWidth="110" MaxWidth="190" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Muted}" Text="{Binding WhenText}" ToolTip="{l:Loc Tooltips.Jobs.Schedule.RunWhen}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.Muted}" Text="{Binding Kind}" ToolTip="{Binding Kind}" Margin="10,0,0,0" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding Target}" ToolTip="{Binding Target}" Margin="10,0,0,0" />
|
||||
<ui:StatusGlyph Grid.Column="3" Kind="{Binding StateKind}" Text="{Binding StateText}" ToolTip="{Binding StateToolTip}" FontSize="13" VerticalAlignment="Center"
|
||||
Margin="10,0,0,0" />
|
||||
<Button Grid.Column="4" Style="{StaticResource Button.Row}" Content="{l:Loc Jobs.Schedule.ShowJob}" Command="{Binding ShowCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Jobs.Schedule.ShowJob}" AutomationProperties.Name="{Binding ShowName}" VerticalAlignment="Center" Margin="10,0,0,0" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
<TextBlock Grid.Row="1" Text="{l:Loc Jobs.Schedule.NoRuns}" Foreground="{DynamicResource Brush.TextMuted}" Margin="14,10"
|
||||
Visibility="{Binding IsRunsEmpty, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
</Border>
|
||||
|
||||
<ui:EmptyState Grid.RowSpan="2" Message="{l:Loc Jobs.Schedule.NotRunning}" Visibility="{Binding IsUnavailable, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,9 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace Chronos.App.Sections;
|
||||
|
||||
/// <summary>Jobs › Scheduled: the view of <see cref="Jobs.SchedulesViewModel"/>.</summary>
|
||||
public partial class SchedulesView : UserControl
|
||||
{
|
||||
public SchedulesView() => InitializeComponent();
|
||||
}
|
||||
@@ -192,10 +192,6 @@
|
||||
<ComboBox Width="140" HorizontalAlignment="Left" ItemsSource="{Binding ThumbnailSizes}" SelectedItem="{Binding SelectedThumbnailSize}" DisplayMemberPath="Label"
|
||||
ToolTip="{l:Loc Tooltips.Settings.ThumbnailSize}" AutomationProperties.Name="{l:Loc Settings.Archive.Thumbnails}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Archive.Polling}">
|
||||
<ComboBox Width="140" HorizontalAlignment="Left" ItemsSource="{Binding ScanIntervals}" SelectedItem="{Binding SelectedScanInterval}" DisplayMemberPath="Label"
|
||||
ToolTip="{l:Loc Tooltips.Settings.Polling}" AutomationProperties.Name="{l:Loc Settings.Archive.Polling}" />
|
||||
</HeaderedContentControl>
|
||||
</StackPanel>
|
||||
|
||||
<!-- ================= Import: defaults of new cards and folders ================= -->
|
||||
@@ -617,6 +613,31 @@
|
||||
<Button Grid.Column="1" Content="{l:Loc Common.Open}" Command="{Binding OpenLogsCommand}" ToolTip="{l:Loc Tooltips.Common.OpenLogs}" Margin="10,0,0,0" />
|
||||
</Grid>
|
||||
</HeaderedContentControl>
|
||||
<!-- Owner review 2, R11: what the log files keep; a choice applies to them at once. -->
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.LogLevel}">
|
||||
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding Logs.Levels}" SelectedItem="{Binding Logs.SelectedLevel}" DisplayMemberPath="Label"
|
||||
ToolTip="{l:Loc Tooltips.Settings.LogLevel}" AutomationProperties.Name="{l:Loc Settings.Advanced.LogLevel}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.KeepLogs}">
|
||||
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding Logs.RetentionChoices}" SelectedItem="{Binding Logs.SelectedRetention}"
|
||||
DisplayMemberPath="Label" ToolTip="{l:Loc Tooltips.Settings.KeepLogs}" AutomationProperties.Name="{l:Loc Settings.Advanced.KeepLogs}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.FileSize}">
|
||||
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding Logs.FileSizeChoices}" SelectedItem="{Binding Logs.SelectedFileSize}"
|
||||
DisplayMemberPath="Label" ToolTip="{l:Loc Tooltips.Settings.LogFileSize}" AutomationProperties.Name="{l:Loc Settings.Advanced.FileSize}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.LogsTotal}">
|
||||
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding Logs.TotalSizeChoices}" SelectedItem="{Binding Logs.SelectedTotalSize}"
|
||||
DisplayMemberPath="Label" ToolTip="{l:Loc Tooltips.Settings.LogsTotal}" AutomationProperties.Name="{l:Loc Settings.Advanced.LogsTotal}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.Rotation}">
|
||||
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding Logs.Rotations}" SelectedItem="{Binding Logs.SelectedRotation}" DisplayMemberPath="Label"
|
||||
ToolTip="{l:Loc Tooltips.Settings.Rotation}" AutomationProperties.Name="{l:Loc Settings.Advanced.Rotation}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.DiagnosticsLogs}">
|
||||
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding Logs.DiagnosticsChoices}" SelectedItem="{Binding Logs.SelectedDiagnostics}"
|
||||
DisplayMemberPath="Label" ToolTip="{l:Loc Tooltips.Settings.DiagnosticsLogs}" AutomationProperties.Name="{l:Loc Settings.Advanced.DiagnosticsLogs}" />
|
||||
</HeaderedContentControl>
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.Diagnostics}">
|
||||
<Button HorizontalAlignment="Left" Content="{l:Loc Settings.Advanced.ExportBundle}" Command="{Binding ExportDiagnosticsCommand}" ToolTip="{l:Loc Tooltips.Settings.Diagnostics}"
|
||||
ui:ButtonIcon.Glyph="{StaticResource Icon.Export}" />
|
||||
@@ -625,7 +646,7 @@
|
||||
<Button HorizontalAlignment="Left" Content="{l:Loc Settings.Advanced.BackupNow}" Command="{Binding BackupDatabaseCommand}" ToolTip="{l:Loc Tooltips.Settings.Backup}"
|
||||
ui:ButtonIcon.Glyph="{StaticResource Icon.Database}" />
|
||||
</HeaderedContentControl>
|
||||
<!-- Restore: a daily copy, its dry run and confirmation; it replaces the index at the next start. -->
|
||||
<!-- Restore: a backup copy of the index, its dry run and confirmation; it replaces the index at the next start. -->
|
||||
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.Restore}">
|
||||
<WrapPanel>
|
||||
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Settings.Advanced.NoBackups}" Margin="0,0,12,0"
|
||||
|
||||
@@ -30,8 +30,8 @@ namespace Chronos.App.Sections;
|
||||
/// 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
|
||||
/// (<see cref="ShellViewModel.About"/>, whose update notice Updates shows).
|
||||
/// install; Advanced sets the log files (<see cref="Logs"/>) and restores the index from a backup at the next start;
|
||||
/// About, the last page, shows this copy (<see cref="ShellViewModel.About"/>, whose update notice Updates shows).
|
||||
/// </summary>
|
||||
public sealed class SettingsViewModel : SectionViewModel
|
||||
{
|
||||
@@ -73,7 +73,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
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"]),
|
||||
"Settings.Archive.Thumbnails"]),
|
||||
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"]),
|
||||
@@ -83,8 +83,9 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
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"]),
|
||||
new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.LogLevel", "Settings.Advanced.KeepLogs",
|
||||
"Settings.Advanced.FileSize", "Settings.Advanced.LogsTotal", "Settings.Advanced.Rotation", "Settings.Advanced.Diagnostics",
|
||||
"Settings.Advanced.DiagnosticsLogs", "Settings.Advanced.Backup", "Settings.Advanced.Restore", "Settings.Advanced.Reset"]),
|
||||
// The translation row shows outside English only, and the language changes while Settings is open.
|
||||
new(SettingsPage.About, () => ["Shell.AppName", "About.Build", "About.Runtime", "About.System", "About.Licence", "About.ThirdParty",
|
||||
.. Shell.About.IsTranslated ? (string[])["About.Translation"] : []]),
|
||||
@@ -156,6 +157,10 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
}, () => Loc.L("Tooltips.Settings.Parallelism"));
|
||||
JobPriorities = [.. PriorityKinds.Select(k => new JobPriorityRow(k, kind => Shell.Services.PriorityQueue.LevelOf(kind), SetJobPriority))];
|
||||
|
||||
// ---- Advanced ----
|
||||
// Saving applies them to the log files (App.SaveSettings).
|
||||
Logs = new LogSettingsRows(_s, Save);
|
||||
|
||||
// ---- Storage ----
|
||||
CacheFolder = new EditableField(CacheStore.Folder(shell.Services.Environment, _s), v => ArchiveLocations.Validate(v), v =>
|
||||
{
|
||||
@@ -435,23 +440,6 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<SettingsOption<int>> ScanIntervals =>
|
||||
[.. new[] { 5, 10, 15, 30, 60 }.Select(m => new SettingsOption<int>(m, Formatting.Duration(TimeSpan.FromMinutes(m))))];
|
||||
|
||||
/// <summary>How often this PC rescans the open archive for changes made elsewhere (BRIEF §7: polling).</summary>
|
||||
public SettingsOption<int> 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; }
|
||||
@@ -765,12 +753,16 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
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");
|
||||
|
||||
/// <summary>Level, retention, size limits and rotation of the log files, and the diagnostics bundle's share of each.</summary>
|
||||
public LogSettingsRows Logs { get; }
|
||||
|
||||
public ICommand OpenDataFolderCommand { get; }
|
||||
public ICommand OpenLogsCommand { get; }
|
||||
public ICommand ExportDiagnosticsCommand { get; }
|
||||
public ICommand BackupDatabaseCommand { get; }
|
||||
|
||||
/// <summary>The daily copies of the index, newest first (Restore).</summary>
|
||||
/// <summary>The copies of the index in the backups folder (the Index backup schedule's, Back up now's), newest first (Restore).</summary>
|
||||
public IReadOnlyList<BackupOption> Backups
|
||||
{
|
||||
get => _backups;
|
||||
@@ -807,10 +799,10 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
public ICommand ResetSectionCommand { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// Formats only shows this PC and About only this copy: they have no Reset section. Advanced's resets its log rows
|
||||
/// (owner review 2, R11); its paths and actions have no default.
|
||||
/// </summary>
|
||||
public bool CanResetSection => _page is not (SettingsPage.Advanced or SettingsPage.Formats or SettingsPage.About);
|
||||
public bool CanResetSection => _page is not (SettingsPage.Formats or SettingsPage.About);
|
||||
public ICommand ExportSettingsCommand { get; }
|
||||
public ICommand ImportSettingsCommand { get; }
|
||||
|
||||
@@ -1138,6 +1130,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
[
|
||||
JobKind.Render, JobKind.Import, JobKind.Download, JobKind.UploadCommit, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse,
|
||||
JobKind.DeepAnalyse, JobKind.Thumbs, JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move,
|
||||
JobKind.Backup, JobKind.Cleanup,
|
||||
];
|
||||
|
||||
/// <summary>Stores <paramref name="level"/> for <paramref name="kind"/>, keeping only the levels that differ from the defaults.</summary>
|
||||
@@ -1310,7 +1303,8 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
if (Shell.Services.Database is not { } db) return;
|
||||
try
|
||||
{
|
||||
var path = await db.BackupAsync(Shell.Services.Environment.BackupDirectory, DatabaseBackups.Keep);
|
||||
// As many copies stay as the backup schedules keep (Jobs › Scheduled › Index backup › Copies kept).
|
||||
var path = await db.BackupAsync(Shell.Services.Environment.BackupDirectory, await DatabaseBackups.KeptAsync(db));
|
||||
Shell.Notify(Loc.L("Settings.Advanced.BackupDone"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
|
||||
}
|
||||
catch (Exception ex) when (ex is DatabaseException or IOException or NotSupportedException)
|
||||
@@ -1344,7 +1338,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
/// Restore (BRIEF §6.2, §12.8): a dry run reads what the chosen copy holds against the index now (shown as unreadable
|
||||
/// when the index did not open, the case a restore exists for); after the user's destructive confirmation the copy is
|
||||
/// staged beside the index for the next start, where the index as it is then is kept first and replaced before it is
|
||||
/// opened (<see cref="DatabaseBackups.RestoreStagedAsync"/>; the staged copy is out of reach of the pruning to three
|
||||
/// opened (<see cref="DatabaseBackups.RestoreStagedAsync"/>; the staged copy is out of reach of the pruning of the
|
||||
/// copies). Nothing replaces the index while Chronos runs.
|
||||
/// </summary>
|
||||
private async Task RestoreDatabaseAsync()
|
||||
@@ -1494,6 +1488,9 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
case SettingsPage.Updates:
|
||||
_s.CheckForUpdates = defaults.CheckForUpdates;
|
||||
break;
|
||||
case SettingsPage.Advanced:
|
||||
Logs.Reset();
|
||||
break;
|
||||
}
|
||||
Save();
|
||||
OnAllPropertiesChanged();
|
||||
@@ -1514,7 +1511,6 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
_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();
|
||||
@@ -1599,6 +1595,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
DefaultServer.Load(ServerAddress.Display(_s.ServerUrl));
|
||||
_interfacePriority?.Update();
|
||||
foreach (var row in JobPriorities) row.Refresh();
|
||||
Logs.Refresh();
|
||||
UpdatePreview();
|
||||
LoadCertificates();
|
||||
OnAllPropertiesChanged();
|
||||
@@ -1673,6 +1670,7 @@ public sealed class SettingsViewModel : SectionViewModel
|
||||
foreach (var row in JobPriorities) row.Refresh();
|
||||
foreach (var row in Formats) row.Refresh();
|
||||
foreach (var row in MissingExtensions) row.Refresh();
|
||||
Logs.Refresh();
|
||||
ArchiveRoot.Refresh();
|
||||
FolderTemplate.Refresh();
|
||||
FileTemplate.Refresh();
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// The log rows of Settings › Advanced (owner review 2, R11): level, retention, file size, total size and rotation of this
|
||||
/// PC's log files, and how much of each the diagnostics bundle keeps. Each choice is stored and saved at once, and saving
|
||||
/// applies it to the files (<see cref="AppLogging"/>). The rows show the values the files get: one set elsewhere (an
|
||||
/// imported or hand-edited settings file) is brought within range as <see cref="AppLogging.Options"/> does, then listed
|
||||
/// with the presets. File sizes above the total and totals below the file size are not offered
|
||||
/// (<see cref="LogFileOptions.TotalBelowFile"/>).
|
||||
/// </summary>
|
||||
public sealed class LogSettingsRows(AppSettings settings, Action save) : ObservableObject
|
||||
{
|
||||
public static readonly int[] RetentionPresets = [1, 3, 7, 14, 30, 90, 365];
|
||||
public static readonly int[] FileSizePresets = [10, 20, 50, 100, 200, 500];
|
||||
public static readonly int[] TotalSizePresets = [256, 512, 1024, 2048, 5120, 10240];
|
||||
public static readonly int[] DiagnosticsPresets = [1, 2, 4, 8, 16, 32];
|
||||
|
||||
public IReadOnlyList<SettingsOption<LogLevel>> Levels =>
|
||||
[.. Enum.GetValues<LogLevel>().Select(l => new SettingsOption<LogLevel>(l, Loc.L("Settings.Advanced.Level." + l)))];
|
||||
|
||||
public SettingsOption<LogLevel> SelectedLevel
|
||||
{
|
||||
get => Levels.FirstOrDefault(l => l.Value == settings.LogLevel) ?? Levels.First(l => l.Value == LogLevel.Info);
|
||||
set => Store(value, settings.LogLevel, v => settings.LogLevel = v);
|
||||
}
|
||||
|
||||
public IReadOnlyList<SettingsOption<int>> RetentionChoices =>
|
||||
[.. With(RetentionPresets, Applied.RetentionDays).Select(n => new SettingsOption<int>(n, Loc.Plural("Settings.Advanced.Days", n)))];
|
||||
|
||||
public SettingsOption<int> SelectedRetention
|
||||
{
|
||||
get => Selected(RetentionChoices, Applied.RetentionDays);
|
||||
set => Store(value, settings.LogRetentionDays, v => settings.LogRetentionDays = v);
|
||||
}
|
||||
|
||||
public IReadOnlyList<SettingsOption<int>> FileSizeChoices
|
||||
{
|
||||
get
|
||||
{
|
||||
var applied = Applied;
|
||||
return Sizes(FileSizePresets, applied.MaxFileMb, n => !LogFileOptions.TotalBelowFile(n, applied.MaxTotalMb));
|
||||
}
|
||||
}
|
||||
|
||||
public SettingsOption<int> SelectedFileSize
|
||||
{
|
||||
get => Selected(FileSizeChoices, Applied.MaxFileMb);
|
||||
set
|
||||
{
|
||||
// The totals offered depend on the file size.
|
||||
if (Store(value, settings.LogMaxFileMb, v => settings.LogMaxFileMb = v)) Changed(nameof(TotalSizeChoices), nameof(SelectedTotalSize));
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<SettingsOption<int>> TotalSizeChoices
|
||||
{
|
||||
get
|
||||
{
|
||||
var applied = Applied;
|
||||
return Sizes(TotalSizePresets, applied.MaxTotalMb, n => !LogFileOptions.TotalBelowFile(applied.MaxFileMb, n));
|
||||
}
|
||||
}
|
||||
|
||||
public SettingsOption<int> SelectedTotalSize
|
||||
{
|
||||
get => Selected(TotalSizeChoices, Applied.MaxTotalMb);
|
||||
set
|
||||
{
|
||||
if (Store(value, settings.LogMaxTotalMb, v => settings.LogMaxTotalMb = v)) Changed(nameof(FileSizeChoices), nameof(SelectedFileSize));
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<SettingsOption<LogRotation>> Rotations =>
|
||||
[.. Enum.GetValues<LogRotation>().Select(r => new SettingsOption<LogRotation>(r, Loc.L("Settings.Advanced.Rotation." + r)))];
|
||||
|
||||
public SettingsOption<LogRotation> SelectedRotation
|
||||
{
|
||||
get => Rotations.FirstOrDefault(r => r.Value == settings.LogRotation) ?? Rotations[0];
|
||||
set => Store(value, settings.LogRotation, v => settings.LogRotation = v);
|
||||
}
|
||||
|
||||
public IReadOnlyList<SettingsOption<int>> DiagnosticsChoices =>
|
||||
[.. With(DiagnosticsPresets, AppliedDiagnosticsMb).Select(n => new SettingsOption<int>(n, Megabytes(n)))];
|
||||
|
||||
public SettingsOption<int> SelectedDiagnostics
|
||||
{
|
||||
get => Selected(DiagnosticsChoices, AppliedDiagnosticsMb);
|
||||
set => Store(value, settings.DiagnosticsLogMb, v => settings.DiagnosticsLogMb = v);
|
||||
}
|
||||
|
||||
/// <summary>The defaults of every row (Reset section on Advanced); the caller saves.</summary>
|
||||
public void Reset()
|
||||
{
|
||||
var defaults = new AppSettings();
|
||||
settings.LogLevel = defaults.LogLevel;
|
||||
settings.LogRetentionDays = defaults.LogRetentionDays;
|
||||
settings.LogMaxFileMb = defaults.LogMaxFileMb;
|
||||
settings.LogMaxTotalMb = defaults.LogMaxTotalMb;
|
||||
settings.LogRotation = defaults.LogRotation;
|
||||
settings.DiagnosticsLogMb = defaults.DiagnosticsLogMb;
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>Labels in the current language, values as the settings have them now.</summary>
|
||||
internal void Refresh() => OnAllPropertiesChanged();
|
||||
|
||||
/// <summary>The values the log files get from the settings now.</summary>
|
||||
private LogFileOptions Applied => AppLogging.Options(settings);
|
||||
|
||||
private int AppliedDiagnosticsMb => (int)(AppLogging.DiagnosticsTailBytes(settings) / LogFileOptions.BytesPerMb);
|
||||
|
||||
/// <summary>
|
||||
/// Stores a choice that differs from the stored value (<paramref name="current"/>, which may lie out of range: choosing
|
||||
/// the value shown then saves it as applied) and saves; false when there was nothing to store.
|
||||
/// </summary>
|
||||
private bool Store<T>(SettingsOption<T>? choice, T current, Action<T> set, [System.Runtime.CompilerServices.CallerMemberName] string? property = null)
|
||||
{
|
||||
if (choice is null || EqualityComparer<T>.Default.Equals(choice.Value, current)) return false;
|
||||
set(choice.Value);
|
||||
save();
|
||||
OnPropertyChanged(property);
|
||||
return true;
|
||||
}
|
||||
|
||||
private void Changed(string choices, string selected)
|
||||
{
|
||||
OnPropertyChanged(choices);
|
||||
OnPropertyChanged(selected);
|
||||
}
|
||||
|
||||
private static SettingsOption<int> Selected(IReadOnlyList<SettingsOption<int>> choices, int value) => choices.FirstOrDefault(c => c.Value == value) ?? choices[0];
|
||||
|
||||
/// <summary>
|
||||
/// The presets <paramref name="offered"/> in order, then "No limit" (0); <paramref name="current"/> joins them when it
|
||||
/// is another size.
|
||||
/// </summary>
|
||||
private static IReadOnlyList<SettingsOption<int>> Sizes(int[] presets, int current, Func<int, bool> offered) =>
|
||||
[
|
||||
.. With(presets.Where(offered).ToArray(), current).Where(n => n > 0).Select(n => new SettingsOption<int>(n, Megabytes(n))),
|
||||
new(0, Loc.L("Settings.Advanced.NoLimit")),
|
||||
];
|
||||
|
||||
private static IEnumerable<int> With(int[] presets, int current) => (presets.Contains(current) ? presets : presets.Append(current)).Order();
|
||||
|
||||
private static string Megabytes(int n) => Loc.L("Common.Size.MB", Formatting.Count(n));
|
||||
}
|
||||
@@ -70,6 +70,9 @@ public static class ScreenCapture
|
||||
await sample.FillAsync();
|
||||
await shell.Library.RefreshAsync();
|
||||
await shell.Jobs.ReloadAsync();
|
||||
// The sample wrote its schedules into the index, past the scheduler's events.
|
||||
await shell.Jobs.Schedules.Attached;
|
||||
await shell.Jobs.Schedules.ReloadAsync();
|
||||
await shell.Services.Server.RestoreAsync();
|
||||
await shell.Services.Sync.RefreshAsync();
|
||||
await shell.Server.Sync.ReloadAsync();
|
||||
@@ -103,6 +106,7 @@ public static class ScreenCapture
|
||||
shell.Navigate(SectionKey.Jobs);
|
||||
if (shell.Jobs.Rows.Count > 0) shell.Jobs.Rows[0].IsExpanded = true;
|
||||
written += await SaveAsync(window, directory, "jobs", theme);
|
||||
written += await CaptureSchedulesAsync(window, shell, directory, theme);
|
||||
|
||||
shell.Navigate(SectionKey.Server);
|
||||
written += await SaveAsync(window, directory, "server", theme);
|
||||
@@ -195,6 +199,29 @@ public static class ScreenCapture
|
||||
return written;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <c>jobs-scheduled</c> (owner review 2, R10: the Scheduled tab with the weekly integrity check selected and its last
|
||||
/// run) and <c>jobs-schedule-editor</c> (that schedule in the editor), then the Queue tab again.
|
||||
/// </summary>
|
||||
private static async Task<int> CaptureSchedulesAsync(MainWindow window, ShellViewModel shell, string directory, AppTheme theme)
|
||||
{
|
||||
var schedules = shell.Jobs.Schedules;
|
||||
shell.Jobs.TabIndex = 1;
|
||||
var written = 0;
|
||||
if ((schedules.Rows.FirstOrDefault(r => !r.IsSystem && r.IsEnabled) ?? schedules.Rows.FirstOrDefault()) is { } row)
|
||||
{
|
||||
schedules.Selected = row;
|
||||
await schedules.RunsLoading;
|
||||
written += await SaveAsync(window, directory, "jobs-scheduled", theme);
|
||||
row.EditCommand.Execute(null);
|
||||
written += await SaveAsync(window, directory, "jobs-schedule-editor", theme);
|
||||
schedules.Editor?.CloseCommand.Execute(null);
|
||||
schedules.Selected = null;
|
||||
}
|
||||
shell.Jobs.TabIndex = 0;
|
||||
return written;
|
||||
}
|
||||
|
||||
private static void SelectSyncFilter(ShellViewModel shell, SyncFilter filter) =>
|
||||
shell.Server.Sync.Chips.First(c => c.Filter == filter).SelectCommand.Execute(null);
|
||||
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:s="clr-namespace:Chronos.App.Sections">
|
||||
xmlns:s="clr-namespace:Chronos.App.Sections"
|
||||
xmlns:j="clr-namespace:Chronos.App.Jobs">
|
||||
<!-- Section view model → view. -->
|
||||
<DataTemplate DataType="{x:Type s:LibraryViewModel}"><s:LibraryView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:ImportViewModel}"><s:ImportView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:SequenceViewModel}"><s:SequenceView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:ArchiveViewModel}"><s:ArchiveView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:JobsViewModel}"><s:JobsView /></DataTemplate>
|
||||
<!-- Jobs › Scheduled, the second tab of Jobs (owner review 2, R10). -->
|
||||
<DataTemplate DataType="{x:Type j:SchedulesViewModel}"><s:SchedulesView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:ServerViewModel}"><s:ServerView /></DataTemplate>
|
||||
<DataTemplate DataType="{x:Type s:SettingsViewModel}"><s:SettingsView /></DataTemplate>
|
||||
</ResourceDictionary>
|
||||
Reference in new issue
Block a user