feat(app): Jobs › Scheduled and the desktop scheduler
Owner review 2, R10 on the desktop: every timer that queued work out of sight is now a visible, editable schedule of this PC. - DesktopScheduleHost implements IScheduleHost: the PC's time zone, the archive at Settings › Archive's folder (refreshed from archive.json, none while it is offline), and three system schedules: archive-scan (every:<ScanIntervalMinutes>m, seeded once from the old setting, no catch-up), index-backup (every day with catch-up, replacing DatabaseBackups.RunDailyAsync) and housekeeping (daily 04:00 with catch-up: job history 90 days and the new cache-trim step). - AppServices starts the Scheduler after the engine, once the archive was reopened; an unplugged archive is looked for every minute and the scheduler woken when it is back. The rescan loop and the daily backup loop are gone; ApplyJobSettings wakes the scheduler. - CacheStore.Trim brings the cache to Settings › Storage › Cache limit, oldest files first, skipping files in use and the proxies, render-node and server-import folders; CacheTrimStep runs it as a clean-up step. - Jobs gets a Queue | Scheduled segmented control. Scheduled lists the schedules (switch, name, action, when, next run, last result) with Run now, Edit, Reset (system) or Delete (user's, confirmed), the selected schedule's last runs with Show in queue, and an in-window editor that checks every field with the scheduler's limits. Jobs a schedule queued carry a "Scheduled" pill; the history line follows the housekeeping's job-history days. - JobNotices: a scheduled background run raises a toast only when it fails (upkeep stays silent). - Settings › Archive › Rescan every is removed; ScanIntervalMinutes stays only as the seed. Strings in en and it; the others are retranslated. - The capture shows jobs-scheduled and jobs-schedule-editor on a stopped scheduler clock with sample schedules. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit e25d812feb3f417cb9251c748c29e8035fd9b03c)
This commit is contained in:
1 parent
75daab7275
commit
bc786c12c4
108 files changed
+3724
-490
No files matched your search
@@ -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)
|
||||
{
|
||||
@@ -636,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,
|
||||
@@ -671,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),
|
||||
|
||||
@@ -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,8 @@ 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"/>).
|
||||
/// </summary>
|
||||
public async Task OpenAsync(string databasePath, CancellationToken ct = default)
|
||||
{
|
||||
@@ -236,26 +251,29 @@ public sealed class AppServices : IAsyncDisposable
|
||||
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);
|
||||
_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 +286,77 @@ 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. An
|
||||
/// archive whose archive.json is not there (an unplugged drive) is looked for every <see cref="ReopenInterval"/> until
|
||||
/// it is back, then 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;
|
||||
await StartSchedulerAsync(ct).ConfigureAwait(false);
|
||||
if (reopen is null) return;
|
||||
using var timer = new PeriodicTimer(ReopenInterval);
|
||||
while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false))
|
||||
{
|
||||
if (reopen is not null
|
||||
&& (!string.Equals(reopen, Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase) || await ReopenAsync(reopen, ct).ConfigureAwait(false)))
|
||||
reopen = null;
|
||||
try
|
||||
{
|
||||
await RescanAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or ArgumentException)
|
||||
{
|
||||
// The next tick tries again (a share that dropped, an archive removed from the index meanwhile).
|
||||
Log.Warning("archive", "The archive could not be rescanned", ex);
|
||||
}
|
||||
if (!string.Equals(reopen, Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase)) return;
|
||||
if (!await ReopenAsync(reopen, ct).ConfigureAwait(false)) continue;
|
||||
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>
|
||||
/// 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 +414,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));
|
||||
|
||||
@@ -97,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) ----
|
||||
|
||||
@@ -116,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
|
||||
@@ -181,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,119 @@
|
||||
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). 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).</summary>
|
||||
public const string IndexBackup = "index-backup";
|
||||
|
||||
/// <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, Deep: settings.DeepAnalysisAfterScan), CatchUp: false),
|
||||
new(IndexBackup, "Index backup", ScheduleActions.Backup, ScheduleRecurrence.Interval(1, RecurrenceUnit.Days),
|
||||
new ScheduleParametersDto(Keep: DatabaseBackups.Keep)),
|
||||
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>
|
||||
/// 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,
|
||||
|
||||
@@ -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,545 @@
|
||||
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;
|
||||
var available = owner.Actions;
|
||||
ActionOptions = [.. ScheduleActions.All.Select(a => available.FirstOrDefault(x => x.Name == a) is { } info
|
||||
? new ScheduleActionOption(a, info.Available, info.Reason)
|
||||
: new ScheduleActionOption(a, true, null))];
|
||||
_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 = [.. Enum.GetValues<RecurrenceUnit>().Select(u => new SettingsOption<RecurrenceUnit>(u, Loc.L("Jobs.Editor.Unit." + u)))];
|
||||
_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 = [.. new[] { JobPriority.Background, JobPriority.Normal, JobPriority.User }.Select(p => new SettingsOption<JobPriority>(p, ScheduleText.Priority(p)))];
|
||||
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);
|
||||
|
||||
public IReadOnlyList<ScheduleActionOption> ActionOptions { get; }
|
||||
|
||||
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; }
|
||||
|
||||
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;
|
||||
public bool ShowsDeep => _action.Name is ScheduleActions.Scan or 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(_action.Name == ScheduleActions.Scan ? "Tooltips.Jobs.Editor.DeepAfterScan" : "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; }
|
||||
|
||||
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);
|
||||
|
||||
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();
|
||||
base.OnLanguageChanged();
|
||||
}
|
||||
|
||||
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,186 @@
|
||||
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 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) _lastJob = null;
|
||||
_schedule = schedule;
|
||||
_isEnabled = schedule.Enabled;
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
|
||||
/// <summary>The job the last run queued changed (or was read): the last result follows its state.</summary>
|
||||
internal void SetLastJob(Job? job)
|
||||
{
|
||||
if (job is not null && job.Id != _schedule.LastJobId) return;
|
||||
_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,187 @@
|
||||
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 week, short names of the UI language.</summary>
|
||||
public static string Days(IEnumerable<DayOfWeek> days) =>
|
||||
days.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,512 @@
|
||||
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>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;
|
||||
_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;
|
||||
var outcome = await Call(() => 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();
|
||||
}
|
||||
|
||||
private async Task LoadLastJobAsync(ScheduleRowViewModel row)
|
||||
{
|
||||
if (row.Schedule.LastJobId is not { } id || _database() is not { } db) return;
|
||||
try
|
||||
{
|
||||
row.SetLastJob(await db.Jobs.GetAsync(id));
|
||||
}
|
||||
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.</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));
|
||||
}
|
||||
}
|
||||
@@ -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,42 @@ 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).</summary>
|
||||
public int TabIndex
|
||||
{
|
||||
get => _tabIndex;
|
||||
set
|
||||
{
|
||||
if (value is < 0 or > 1 || !Set(ref _tabIndex, value)) return;
|
||||
OnPropertyChanged(nameof(IsQueue));
|
||||
OnPropertyChanged(nameof(IsScheduled));
|
||||
}
|
||||
}
|
||||
|
||||
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 +175,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": the job-history step of the housekeeping schedule.</summary>
|
||||
public string HistoryText => Loc.Plural("Jobs.History", (long)Chronos.Data.Housekeeping.CleanupSteps.DefaultHistoryDays);
|
||||
/// <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 +188,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 +214,7 @@ public sealed class JobsViewModel : SectionViewModel
|
||||
_queue.Progress -= OnProgress;
|
||||
}
|
||||
_throttle?.Dispose();
|
||||
Schedules.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
@@ -234,6 +271,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));
|
||||
@@ -344,6 +382,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 ================= -->
|
||||
|
||||
@@ -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"]),
|
||||
@@ -440,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; }
|
||||
@@ -1527,7 +1510,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();
|
||||
|
||||
@@ -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