feat: owner review 2 phase 2: scheduled jobs and log settings (#10)
CI / Build and test (push) Successful in 7m0s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 6s
Release / Build, test and publish (push) Successful in 13m28s
CI / PostgreSQL 16 integration (push) Successful in 5m52s
CI / PostgreSQL 17 integration (push) Successful in 4m50s
CI / Docker image (push) Successful in 1m4s
Release / Server image (push) Successful in 1m35s

- Jobs > Scheduled on the desktop and the admin panel. Every timer that queued work is now a visible system schedule: archive scan, upload clean-up, index backup, job-history and audit clean-ups, desktop housekeeping. New actions: verify, thumbnails, proxies, analysis, maintenance, backup, clean-ups, reports.
- The scheduler: migration 0007, in-house recurrence, compare-and-set claim, catch-up, scan at start.
- Log settings: levels, retention, size parts, total limit, daily or hourly rotation, audit retention, diagnostics share; the server writes Debug/Trace to its files again; logging never fails a job.

Upgrade: CHRONOS_LOG_LEVEL set in an existing container locks both levels; migration 0007 is one-way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #10.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-27 11:19:26 +01:00
1 parent 1f089888e8
commit af9eeaab9b
349 files changed
+28341 -1304

No files matched your search

+127
View File
@@ -0,0 +1,127 @@
using System.IO;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Housekeeping;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
namespace Chronos.App.Jobs;
/// <summary>
/// The desktop's <see cref="IScheduleHost"/> (owner review 2, R10). Times are the PC's; schedules work on the archive at
/// Settings › Archive's folder (<see cref="CurrentArchive"/>), which first takes the settings another process sharing it
/// wrote into its archive.json, as the rescans before it did, and counts as none while it is offline (an unplugged
/// drive). The system schedules stand for the timers the desktop used to run out of sight: the archive scan (its interval
/// carried over from the former Settings › Archive › Rescan every, <see cref="AppSettings.ScanIntervalMinutes"/>, once:
/// a row that exists keeps the user's edits), the daily index backup, and the housekeeping clean-up at 04:00 (job history,
/// cache trim). Scans give what they find a deep analysis as Settings › Analysis › After a scan says at each run
/// (<see cref="DeepAnalysisAfterScan"/>), like the scans started by hand. Thread-safe: the scheduler calls it from its loop.
/// </summary>
public sealed class DesktopScheduleHost(AppSettings settings, Func<ChronosDatabase?> database, Func<ArchiveService?> archives) : IScheduleHost
{
/// <summary>Incremental scan of the archive, every <see cref="AppSettings.ScanIntervalMinutes"/> (10) minutes, no catch-up.</summary>
public const string ArchiveScan = "archive-scan";
/// <summary>
/// Copy of the index into the backups folder, every day, with catch-up (it replaced the daily backup loop). Seeded due
/// at once when the newest copy is a day old, as that loop made one at start.
/// </summary>
public const string IndexBackup = DatabaseBackups.ScheduleKey;
/// <summary>Clean-up of the job history and the cache, daily at 04:00, with catch-up.</summary>
public const string Housekeeping = "housekeeping";
/// <summary>When the housekeeping runs.</summary>
public static readonly TimeOnly HousekeepingTime = new(4, 0);
/// <summary>The PC's zone; tests set another.</summary>
public TimeZoneInfo TimeZone { get; init; } = TimeZoneInfo.Local;
public IReadOnlyList<SystemSchedule> SystemSchedules =>
[
new(ArchiveScan, "Archive scan", ScheduleActions.Scan, ScheduleRecurrence.Interval(ScanMinutes(settings), RecurrenceUnit.Minutes),
new ScheduleParametersDto(Force: false), CatchUp: false),
new(IndexBackup, "Index backup", ScheduleActions.Backup, ScheduleRecurrence.Interval(1, RecurrenceUnit.Days),
new ScheduleParametersDto(Keep: DatabaseBackups.Keep),
LastDone: database() is { } db ? DatabaseBackups.Newest(db, archives()?.BackupDirectory) : null),
new(Housekeeping, "Housekeeping", ScheduleActions.Cleanup, ScheduleRecurrence.DailyAt(HousekeepingTime),
new ScheduleParametersDto(Steps: [Chronos.Data.Housekeeping.CleanupSteps.JobHistory, CacheTrimStep.StepName],
OlderThanDays: Chronos.Data.Housekeeping.CleanupSteps.DefaultHistoryDays)),
];
public IReadOnlyList<string> CleanupSteps => archives()?.CleanupSteps.Select(s => s.Name).ToList() ?? [];
/// <summary>
/// The interval the scan schedule is seeded with (and reset to): the former rescan setting, within what an interval
/// accepts (5 minutes to a day).
/// </summary>
public static int ScanMinutes(AppSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
return int.Clamp(settings.ScanIntervalMinutes, ScheduleRecurrence.MinMinutes, ScheduleRecurrence.MaxMinutes);
}
public async ValueTask<Archive?> GetArchiveAsync(CancellationToken cancellationToken)
{
if (database() is not { } db || archives() is not { } service) return null;
var archive = CurrentArchive.Pick(await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false), settings.LastArchivePath);
if (archive is null || ArchiveService.GetAvailability(archive) == ArchiveAvailability.Offline) return null;
try
{
await service.RefreshSettingsAsync(archive.Id, cancellationToken).ConfigureAwait(false);
return await db.Archives.GetAsync(archive.Id, cancellationToken).ConfigureAwait(false) ?? archive;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or NewerFormatException)
{
// The settings as last read: the run still works on the archive, the next one reads them again.
Log.Warning("schedules", $"The settings of {archive.RootPath} could not be read again", ex);
return archive;
}
}
/// <summary>The desktop runs every action its engine has a handler for.</summary>
public string? Unavailable(string action) => null;
/// <summary>Settings › Analysis › After a scan, read at every run: a scheduled scan follows it as a scan started by hand does.</summary>
public bool DeepAnalysisAfterScan => settings.DeepAnalysisAfterScan;
}
/// <summary>
/// The desktop's clean-up step <c>cache-trim</c> (owner review 2, R10): brings the cache folder down to Settings › Storage ›
/// Cache limit, oldest files first, skipping files in use (<see cref="CacheStore.Trim"/>). The proxies of server sequences
/// (complete sets the sync keeps), the render node's folder (it trims its own downloads to the same limit) and the copies an
/// import to the server stages are never trimmed; Settings › Storage › Clear still empties everything.
/// </summary>
public sealed class CacheTrimStep(Func<string> folder, Func<long> limitBytes) : ICleanupStep
{
public const string StepName = "cache-trim";
/// <summary>Folders of the cache the trim leaves whole.</summary>
public static IReadOnlyList<string> Kept { get; } = ["proxies", "render-node", "server-import"];
public string Name => StepName;
public Task<string> RunAsync(CleanupContext context, CleanupParameters parameters)
{
ArgumentNullException.ThrowIfNull(context);
var limit = limitBytes();
return Task.Run(() =>
{
var result = CacheStore.Trim(folder(), limit, Kept, context.Cancellation);
if (result is null) return Loc.L("Jobs.Log.CacheNotOwned");
return result.Deleted == 0
? Loc.L("Jobs.Log.CacheKept", Gigabytes(result.After), Gigabytes(limit))
: Loc.L("Jobs.Log.CacheTrimmed", Gigabytes(result.After), Gigabytes(limit), Gigabytes(result.Freed));
}, context.Cancellation);
}
/// <summary>"12.4 GB" in the binary gigabytes of Settings › Storage › Cache limit.</summary>
private static string Gigabytes(long bytes) => Loc.L("Common.Size.GB", (bytes / (double)(1L << 30)).ToString("0.#", Loc.Culture));
}
+11 -5
View File
@@ -13,9 +13,10 @@ public enum JobNotice
/// <summary>
/// Which job endings raise a toast (BRIEF §12.1 "toasts for job completion"): the long operations the user asked for
/// end with one toast, whichever screen started them. Background work (thumbnails, proxies, light analysis, the
/// analysis queued after an import) and scans (the archive is rescanned every 10 minutes) end silently; an import
/// analysis queued after an import) and scans (the archive scan schedule runs every 10 minutes) end silently; an import
/// has its own toast when it ends well, and a download shows on its Library card and Server row. Every other failure
/// is said. Cancelled jobs were stopped on purpose.
/// is said. A schedule's background run (owner review 2, R10: the index backup, a weekly verify) is said only when it
/// fails, unless it is upkeep the next run repeats. Cancelled jobs were stopped on purpose.
/// </summary>
public static class JobNotices
{
@@ -26,7 +27,9 @@ public static class JobNotices
public static JobNotice For(JobState? before, Job job)
{
ArgumentNullException.ThrowIfNull(job);
if (before is JobState.Done or JobState.Failed or JobState.Cancelled || job.Priority == JobPriority.Background) return JobNotice.None;
if (before is JobState.Done or JobState.Failed or JobState.Cancelled) return JobNotice.None;
if (job.Priority == JobPriority.Background)
return job.ScheduleId is not null && job.State == JobState.Failed && !IsUpkeep(job.Kind) ? JobNotice.Failed : JobNotice.None;
return job.State switch
{
JobState.Done when Announces(job.Kind) => JobNotice.Done,
@@ -39,9 +42,12 @@ public static class JobNotices
kind is JobKind.Render or JobKind.DeepAnalyse or JobKind.Verify or JobKind.Rebuild or JobKind.Maintenance or JobKind.UploadCommit
or JobKind.Move or JobKind.Adopt;
/// <summary>Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing.</summary>
/// <summary>
/// Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing.
/// Clean-ups too: the housekeeping schedule runs them again (a failed index backup is said).
/// </summary>
private static bool IsUpkeep(JobKind kind) =>
kind is JobKind.Scan or JobKind.Thumbs or JobKind.Proxies or JobKind.LightAnalyse;
kind is JobKind.Scan or JobKind.Thumbs or JobKind.Proxies or JobKind.LightAnalyse or JobKind.Cleanup;
}
/// <summary>Endings said in one toast: one job, or several of a batch.</summary>
+3
View File
@@ -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);
+245
View File
@@ -0,0 +1,245 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:Chronos.Ui.Controls;assembly=Chronos.Ui"
xmlns:v="clr-namespace:Chronos.Ui.Visuals;assembly=Chronos.Ui"
xmlns:l="clr-namespace:Chronos.Ui.Localization;assembly=Chronos.Ui"
xmlns:j="clr-namespace:Chronos.App.Jobs"
xmlns:infra="clr-namespace:Chronos.App.Infrastructure">
<!-- The in-window schedule editor of Jobs › Scheduled (owner review 2, R10), with the dialog kit of the Archive screen. -->
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Chronos;component/Archive/ArchiveDialogs.xaml" />
</ResourceDictionary.MergedDictionaries>
<!-- One editor row: the label column grows with the longest label (DESIGN §2), the controls take the rest. -->
<Style x:Key="Grid.EditorRow" TargetType="Grid">
<Setter Property="Margin" Value="0,0,0,10" />
<Setter Property="MinHeight" Value="32" />
</Style>
<!-- A choice of the action list: one this PC cannot run is disabled, its reason in the tooltip. -->
<Style x:Key="ComboBoxItem.Action" TargetType="ComboBoxItem" BasedOn="{StaticResource {x:Type ComboBoxItem}}">
<Setter Property="IsEnabled" Value="{Binding IsAvailable}" />
<Setter Property="ToolTip" Value="{Binding ToolTip}" />
<Setter Property="ToolTipService.ShowOnDisabled" Value="True" />
<Setter Property="AutomationProperties.Name" Value="{Binding Label}" />
<Setter Property="AutomationProperties.HelpText" Value="{Binding ToolTip}" />
</Style>
<!-- A day of the week: a 44 px toggle, its full name in the tooltip. -->
<Style x:Key="ToggleButton.Day" TargetType="ToggleButton" BasedOn="{StaticResource {x:Type ToggleButton}}">
<Setter Property="MinWidth" Value="44" />
<Setter Property="Padding" Value="8,0" />
<Setter Property="Margin" Value="0,0,6,6" />
</Style>
<DataTemplate DataType="{x:Type j:ScheduleEditorViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="600" MaxHeight="720">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
<ScrollViewer Grid.Row="1" Margin="0,14,0,0" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
<StackPanel Grid.IsSharedSizeScope="True">
<!-- Name: a system schedule keeps its own. -->
<Grid Style="{StaticResource Grid.EditorRow}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Jobs.Editor.Name}" Style="{StaticResource Text.DialogLabel}" />
<TextBox Grid.Column="1" Text="{Binding Name.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" ToolTip="{Binding Name.ToolTip}"
MaxLength="100" AutomationProperties.Name="{l:Loc Jobs.Editor.Name}"
Visibility="{Binding IsSystem, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<TextBlock Grid.Column="1" Text="{Binding SystemName}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" ToolTip="{Binding Name.ToolTip}"
Visibility="{Binding IsSystem, Converter={StaticResource BoolToVisibility}}" />
</Grid>
<Grid Style="{StaticResource Grid.EditorRow}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Jobs.Editor.Action}" Style="{StaticResource Text.DialogLabel}" />
<ComboBox Grid.Column="1" Width="240" HorizontalAlignment="Left" ItemsSource="{Binding ActionOptions}" SelectedItem="{Binding SelectedAction}"
DisplayMemberPath="Label" ItemContainerStyle="{StaticResource ComboBoxItem.Action}" ToolTip="{Binding ActionToolTip}"
ToolTipService.ShowOnDisabled="True" IsEnabled="{Binding CanChangeAction}"
AutomationProperties.Name="{l:Loc Jobs.Editor.Action}" />
</Grid>
<!-- When: the kind, then its own fields. -->
<Grid Style="{StaticResource Grid.EditorRow}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Jobs.Editor.Repeat}" Style="{StaticResource Text.DialogLabel}" />
<v:SegmentedControl Grid.Column="1" HorizontalAlignment="Left" SelectedIndex="{Binding KindIndex}" AutomationProperties.Name="{l:Loc Jobs.Editor.Repeat}">
<v:SegmentedItem Content="{l:Loc Jobs.Editor.Every}" ToolTip="{l:Loc Tooltips.Jobs.Editor.KindEvery}" AutomationProperties.Name="{l:Loc Jobs.Editor.Every}" />
<v:SegmentedItem Content="{l:Loc Jobs.Editor.Daily}" ToolTip="{l:Loc Tooltips.Jobs.Editor.KindDaily}" AutomationProperties.Name="{l:Loc Jobs.Editor.Daily}" />
<v:SegmentedItem Content="{l:Loc Jobs.Editor.Weekly}" ToolTip="{l:Loc Tooltips.Jobs.Editor.KindWeekly}" AutomationProperties.Name="{l:Loc Jobs.Editor.Weekly}" />
<v:SegmentedItem Content="{l:Loc Jobs.Editor.Monthly}" ToolTip="{l:Loc Tooltips.Jobs.Editor.KindMonthly}" AutomationProperties.Name="{l:Loc Jobs.Editor.Monthly}" />
</v:SegmentedControl>
</Grid>
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding IsEvery, Converter={StaticResource BoolToVisibility}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Jobs.Editor.Interval}" Style="{StaticResource Text.DialogLabel}" />
<StackPanel Grid.Column="1" Orientation="Horizontal">
<TextBox Style="{StaticResource TextBox.Number}" Text="{Binding Every.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
ToolTip="{Binding Every.ToolTip}" AutomationProperties.Name="{l:Loc Jobs.Editor.Interval}" />
<ComboBox Width="120" Margin="8,0,0,0" ItemsSource="{Binding Units}" SelectedItem="{Binding SelectedUnit}" DisplayMemberPath="Label"
ToolTip="{l:Loc Tooltips.Jobs.Editor.Unit}" AutomationProperties.Name="{l:Loc Jobs.Editor.Unit}" />
</StackPanel>
</Grid>
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding IsWeekly, Converter={StaticResource BoolToVisibility}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Jobs.Editor.Days}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Top" Margin="0,7,14,0" />
<ItemsControl Grid.Column="1" ItemsSource="{Binding Days}" Focusable="False" AutomationProperties.Name="{l:Loc Jobs.Editor.Days}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ToggleButton Style="{StaticResource ToggleButton.Day}" Content="{Binding Label}" IsChecked="{Binding IsChecked}" ToolTip="{Binding ToolTip}"
AutomationProperties.Name="{Binding ToolTip}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding IsMonthly, Converter={StaticResource BoolToVisibility}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Jobs.Editor.DayOfMonth}" Style="{StaticResource Text.DialogLabel}" />
<TextBox Grid.Column="1" Style="{StaticResource TextBox.Number}" HorizontalAlignment="Left"
Text="{Binding DayOfMonth.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" ToolTip="{Binding DayOfMonth.ToolTip}"
AutomationProperties.Name="{l:Loc Jobs.Editor.DayOfMonth}" />
</Grid>
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding HasTime, Converter={StaticResource BoolToVisibility}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Jobs.Editor.Time}" Style="{StaticResource Text.DialogLabel}" />
<!-- Hours and minutes stay in their order in every language. -->
<TextBox Grid.Column="1" Style="{StaticResource TextBox.Number}" HorizontalAlignment="Left" FlowDirection="LeftToRight"
Text="{Binding Time.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" ToolTip="{Binding Time.ToolTip}"
AutomationProperties.Name="{l:Loc Jobs.Editor.Time}" />
</Grid>
<Grid Style="{StaticResource Grid.EditorRow}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<!-- The recurrence as the table will show it. -->
<TextBlock Grid.Column="1" Text="{Binding WhenText}" Foreground="{DynamicResource Brush.TextMuted}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis"
ToolTip="{l:Loc Tooltips.Jobs.Editor.When}" AutomationProperties.LiveSetting="Polite" infra:LiveRegion.Text="{Binding WhenText}" />
</Grid>
<!-- The action's parameters. -->
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding ShowsOlderThan, Converter={StaticResource BoolToVisibility}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding OlderThanLabel}" Style="{StaticResource Text.DialogLabel}" />
<StackPanel Grid.Column="1" Orientation="Horizontal">
<TextBox Style="{StaticResource TextBox.Number}" Text="{Binding OlderThan.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
ToolTip="{Binding OlderThan.ToolTip}" AutomationProperties.Name="{Binding OlderThanLabel}" />
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Jobs.Editor.DaysUnit}" Margin="8,0,0,0" />
</StackPanel>
</Grid>
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding ShowsPercent, Converter={StaticResource BoolToVisibility}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Jobs.Editor.Percent}" Style="{StaticResource Text.DialogLabel}" />
<StackPanel Grid.Column="1" Orientation="Horizontal">
<TextBox Style="{StaticResource TextBox.Number}" Text="{Binding Percent.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
ToolTip="{Binding Percent.ToolTip}" AutomationProperties.Name="{l:Loc Jobs.Editor.Percent}" />
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Jobs.Editor.PercentUnit}" Margin="8,0,0,0" />
</StackPanel>
</Grid>
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding ShowsKeep, Converter={StaticResource BoolToVisibility}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Jobs.Editor.Keep}" Style="{StaticResource Text.DialogLabel}" />
<TextBox Grid.Column="1" Style="{StaticResource TextBox.Number}" HorizontalAlignment="Left"
Text="{Binding Keep.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" ToolTip="{Binding Keep.ToolTip}"
AutomationProperties.Name="{l:Loc Jobs.Editor.Keep}" />
</Grid>
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding ShowsSteps, Converter={StaticResource BoolToVisibility}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Jobs.Editor.Steps}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Top" Margin="0,4,14,0" />
<ItemsControl Grid.Column="1" ItemsSource="{Binding Steps}" Focusable="False" AutomationProperties.Name="{l:Loc Jobs.Editor.Steps}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Label}" IsChecked="{Binding IsChecked}" ToolTip="{Binding ToolTip}" Margin="0,0,0,6" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
<Grid Style="{StaticResource Grid.EditorRow}" Visibility="{Binding HasSwitches, Converter={StaticResource BoolToVisibility}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<WrapPanel Grid.Column="1" VerticalAlignment="Center">
<CheckBox Content="{Binding ForceLabel}" IsChecked="{Binding Force}" ToolTip="{Binding ForceToolTip}" Margin="0,0,20,6"
Visibility="{Binding ShowsForce, Converter={StaticResource BoolToVisibility}}" />
<CheckBox Content="{l:Loc Jobs.Editor.Deep}" IsChecked="{Binding Deep}" ToolTip="{Binding DeepToolTip}" Margin="0,0,20,6"
Visibility="{Binding ShowsDeep, Converter={StaticResource BoolToVisibility}}" />
<CheckBox Content="{l:Loc Jobs.Editor.DryRun}" IsChecked="{Binding DryRun}" ToolTip="{l:Loc Tooltips.Jobs.Editor.DryRun}" Margin="0,0,20,6"
Visibility="{Binding ShowsDryRun, Converter={StaticResource BoolToVisibility}}" />
</WrapPanel>
</Grid>
<!-- How its jobs run. -->
<Grid Style="{StaticResource Grid.EditorRow}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Jobs.Editor.Priority}" Style="{StaticResource Text.DialogLabel}" />
<ComboBox Grid.Column="1" Width="160" HorizontalAlignment="Left" ItemsSource="{Binding Priorities}" SelectedItem="{Binding SelectedPriority}"
DisplayMemberPath="Label" ToolTip="{l:Loc Tooltips.Jobs.Editor.Priority}" AutomationProperties.Name="{l:Loc Jobs.Editor.Priority}" />
</Grid>
<Grid Style="{StaticResource Grid.EditorRow}" Margin="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" SharedSizeGroup="EditorLabel" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<WrapPanel Grid.Column="1" VerticalAlignment="Center">
<CheckBox Content="{l:Loc Jobs.Editor.CatchUp}" IsChecked="{Binding CatchUp}" ToolTip="{l:Loc Tooltips.Jobs.Editor.CatchUp}" Margin="0,0,20,0" />
<CheckBox Content="{l:Loc Jobs.Editor.Enabled}" IsChecked="{Binding Enabled}" ToolTip="{l:Loc Tooltips.Jobs.Editor.Enabled}" />
</WrapPanel>
</Grid>
</StackPanel>
</ScrollViewer>
<DockPanel Grid.Row="2" Margin="0,18,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Jobs.Editor.Save}" Command="{Binding SaveCommand}"
ToolTip="{Binding SaveToolTip}" ToolTipService.ShowOnDisabled="True" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{l:Loc Tooltips.Jobs.Editor.Cancel}" IsCancel="True"
MinWidth="96" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" HorizontalAlignment="Left" />
</DockPanel>
</Grid>
</Border>
</DataTemplate>
</ResourceDictionary>
@@ -0,0 +1,582 @@
using System.Collections;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Windows.Input;
using Chronos.App.Settings;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Jobs;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Jobs;
/// <summary>A text field of the schedule editor: checked as it is typed, its problem in the tooltip (DESIGN §4 inputs).</summary>
public sealed class ScheduleField : ObservableObject, INotifyDataErrorInfo
{
private readonly Func<string, string?> _validate;
private readonly Func<string> _toolTip;
private string _text;
private string? _error;
public ScheduleField(string text, Func<string, string?> validate, Func<string> toolTip)
{
_text = text;
_validate = validate;
_toolTip = toolTip;
_error = validate(text);
}
/// <summary>The text changed, or its problem did.</summary>
public event Action? Changed;
public event EventHandler<DataErrorsChangedEventArgs>? ErrorsChanged;
public string Text
{
get => _text;
set
{
if (!Set(ref _text, value ?? string.Empty)) return;
Validate();
Changed?.Invoke();
}
}
/// <summary>The problem of the text; null when it is valid.</summary>
public string? Error => _error;
public bool HasErrors => _error is not null;
/// <summary>The problem while invalid, otherwise what the field is for.</summary>
public string ToolTip => _error ?? _toolTip();
public IEnumerable GetErrors(string? propertyName) =>
_error is not null && propertyName is null or "" or nameof(Text) ? new[] { _error } : Array.Empty<string>();
/// <summary>Checks the text again (a rule it depends on changed: the interval's unit).</summary>
public void Validate()
{
var error = _validate(_text);
if (error == _error) return;
_error = error;
OnPropertyChanged(nameof(Error));
OnPropertyChanged(nameof(HasErrors));
OnPropertyChanged(nameof(ToolTip));
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Text)));
Changed?.Invoke();
}
internal void Refresh()
{
_error = _validate(_text);
OnPropertyChanged(string.Empty);
ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(nameof(Text)));
}
}
/// <summary>An action of the editor's list: unavailable ones are shown disabled, their reason in the tooltip.</summary>
public sealed record ScheduleActionOption(string Name, bool IsAvailable, string? Reason)
{
public string Label => ScheduleText.Action(Name);
public string ToolTip => IsAvailable ? ScheduleText.ActionToolTip(Name) : ScheduleText.Unavailable(Reason);
public override string ToString() => Label;
}
/// <summary>A checkable choice of the editor (a day of the week, a clean-up step).</summary>
public sealed class ScheduleChoice<T>(T value, Func<string> label, Func<string> toolTip, bool isChecked, Action changed) : ObservableObject
{
private bool _isChecked = isChecked;
public T Value { get; } = value;
public string Label => label();
public string ToolTip => toolTip();
public bool IsChecked
{
get => _isChecked;
set
{
if (Set(ref _isChecked, value)) changed();
}
}
internal void Refresh() => OnAllPropertiesChanged();
}
/// <summary>
/// The in-window editor of a schedule (owner review 2, R10): its name (a system schedule keeps its own), its action (those
/// this PC cannot run are disabled, their reason in the tooltip), when it runs (every n minutes, hours or days; daily,
/// weekly or monthly at a time of this PC's zone), the action's parameters, the priority of its jobs, catch-up and on/off.
/// Every field is checked as it is typed with the scheduler's own limits; Save stays off while one is invalid and its
/// tooltip names the first problem. One primary action, one way out (Cancel, Esc).
/// </summary>
public sealed class ScheduleEditorViewModel : LocalizedViewModel
{
private readonly SchedulesViewModel _owner;
private readonly ScheduleDto? _schedule;
private ScheduleActionOption _action;
private int _kindIndex;
private SettingsOption<RecurrenceUnit> _unit;
private SettingsOption<JobPriority> _priority;
private bool _catchUp;
private bool _enabled;
private bool _force;
private bool _deep;
private bool _dryRun;
private bool _isBusy;
private string? _errorText;
private string? _errorToolTip;
private IReadOnlyList<ScheduleChoice<string>> _steps = [];
internal ScheduleEditorViewModel(SchedulesViewModel owner, ScheduleDto? schedule)
{
_owner = owner;
_schedule = schedule;
ActionOptions = BuildActionOptions();
_action = schedule is not null
? ActionOptions.FirstOrDefault(o => o.Name == schedule.Action) ?? new ScheduleActionOption(schedule.Action, false, null)
: ActionOptions.FirstOrDefault(o => o.IsAvailable) ?? ActionOptions[0];
Name = new ScheduleField(schedule is null ? string.Empty : schedule.Name, ValidateName, () => Loc.L(IsSystem ? "Tooltips.Jobs.Editor.SystemName" : "Tooltips.Jobs.Editor.Name"));
// When: the stored recurrence, or every day at 03:00 for a new schedule.
var recurrence = ScheduleMapping.FromDto(schedule?.Recurrence) ?? ScheduleRecurrence.DailyAt(new TimeOnly(3, 0));
_kindIndex = (int)recurrence.Kind;
Units = BuildUnits();
_unit = Units.First(u => u.Value == (recurrence.Kind == RecurrenceKind.Every ? recurrence.Unit : RecurrenceUnit.Hours));
Every = new ScheduleField(Number(recurrence.Kind == RecurrenceKind.Every ? recurrence.Every : 6), ValidateEvery, () => Loc.L("Tooltips.Jobs.Editor.Every"));
Time = new ScheduleField(recurrence.Time.ToString("HH:mm", CultureInfo.InvariantCulture), ValidateTime, () => Loc.L("Tooltips.Jobs.Editor.Time"));
var weekly = recurrence.Kind == RecurrenceKind.Weekly ? recurrence.Days : [DayOfWeek.Monday];
var first = Loc.Culture.DateTimeFormat.FirstDayOfWeek;
Days = [.. Enumerable.Range(0, 7).Select(i => (DayOfWeek)(((int)first + i) % 7)).Select(d =>
new ScheduleChoice<DayOfWeek>(d, () => ScheduleText.DayShort(d), () => ScheduleText.DayLong(d), weekly.Contains(d), OnChanged))];
DayOfMonth = new ScheduleField(Number(recurrence.Kind == RecurrenceKind.Monthly ? recurrence.DayOfMonth : 1), ValidateDayOfMonth,
() => Loc.L("Tooltips.Jobs.Editor.DayOfMonth"));
OlderThan = new ScheduleField(string.Empty, v => ValidateNumber(v, 0, ScheduleActions.MaxDays), () => Loc.L(IsVerify ? "Tooltips.Jobs.Editor.Unverified" : "Tooltips.Jobs.Editor.OlderThan"));
Percent = new ScheduleField(string.Empty, v => ValidateNumber(v, 1, 100), () => Loc.L("Tooltips.Jobs.Editor.Percent"));
Keep = new ScheduleField(string.Empty, v => ValidateNumber(v, 1, 100), () => Loc.L("Tooltips.Jobs.Editor.Keep"));
LoadParameters(schedule?.Parameters ?? ScheduleActions.Defaults(_action.Name));
Priorities = BuildPriorities();
var priority = schedule is not null && JobWire.TryParsePriority(schedule.Priority, out var stored) ? stored : JobPriority.Background;
_priority = Priorities.First(p => p.Value == priority);
_catchUp = schedule?.CatchUp ?? true;
_enabled = schedule?.Enabled ?? true;
foreach (var field in new[] { Name, Every, Time, DayOfMonth, OlderThan, Percent, Keep }) field.Changed += OnChanged;
SaveCommand = new AsyncRelayCommand(SaveAsync, () => !_isBusy && Problem() is null);
CloseCommand = new RelayCommand(() => _owner.CloseEditor(this), () => !_isBusy);
}
/// <summary>The schedule edited; null for a new one.</summary>
public Guid? ScheduleId => _schedule?.Id;
public bool IsNew => _schedule is null;
/// <summary>A system schedule keeps its name and action.</summary>
public bool IsSystem => _schedule?.SystemKey is not null;
public string Heading => _schedule is null ? Loc.L("Jobs.Schedule.New") : Loc.L("Jobs.Editor.Heading", ScheduleText.Name(_schedule));
public ScheduleField Name { get; }
/// <summary>The name shown for a system schedule, which is not edited.</summary>
public string SystemName => _schedule is null ? string.Empty : ScheduleText.Name(_schedule);
/// <summary>Every action, with whether this PC runs it as last read; built again when that or the UI language changes.</summary>
public IReadOnlyList<ScheduleActionOption> ActionOptions { get; private set; }
public ScheduleActionOption SelectedAction
{
get => _action;
set
{
if (value is null || !value.IsAvailable || IsSystem || !Set(ref _action, value)) return;
// Another action starts from its own defaults, as the scheduler does.
LoadParameters(ScheduleActions.Defaults(value.Name));
OnPropertyChanged(string.Empty);
OnChanged();
}
}
public string ActionToolTip => IsSystem ? Loc.L("Tooltips.Jobs.Editor.SystemAction") : _action.ToolTip;
/// <summary>The action can be chosen (not for a system schedule).</summary>
public bool CanChangeAction => !IsSystem;
// ---------------- When ----------------
/// <summary>0 every, 1 daily, 2 weekly, 3 monthly (the segmented control's index; <see cref="RecurrenceKind"/> order).</summary>
public int KindIndex
{
get => _kindIndex;
set
{
if (value is < 0 or > 3 || !Set(ref _kindIndex, value)) return;
OnPropertyChanged(nameof(IsEvery));
OnPropertyChanged(nameof(HasTime));
OnPropertyChanged(nameof(IsWeekly));
OnPropertyChanged(nameof(IsMonthly));
OnChanged();
}
}
public RecurrenceKind Kind => (RecurrenceKind)_kindIndex;
public bool IsEvery => Kind == RecurrenceKind.Every;
public bool HasTime => Kind != RecurrenceKind.Every;
public bool IsWeekly => Kind == RecurrenceKind.Weekly;
public bool IsMonthly => Kind == RecurrenceKind.Monthly;
public ScheduleField Every { get; }
public IReadOnlyList<SettingsOption<RecurrenceUnit>> Units { get; private set; }
public SettingsOption<RecurrenceUnit> SelectedUnit
{
get => _unit;
set
{
if (value is null || !Set(ref _unit, value)) return;
Every.Validate();
OnChanged();
}
}
public ScheduleField Time { get; }
/// <summary>The days of a weekly schedule, from the first day of the UI language's week.</summary>
public IReadOnlyList<ScheduleChoice<DayOfWeek>> Days { get; }
public ScheduleField DayOfMonth { get; }
/// <summary>"Daily at 03:00": the recurrence as the table will show it; "—" while a field is invalid.</summary>
public string WhenText => Recurrence() is { } recurrence ? ScheduleText.When(recurrence) : "—";
// ---------------- Parameters ----------------
public bool ShowsForce => _action.Name is ScheduleActions.Scan or ScheduleActions.Thumbnails or ScheduleActions.Proxies;
/// <summary>Analysis only: a scan's deep analysis follows Settings › Analysis › After a scan at every run.</summary>
public bool ShowsDeep => _action.Name == ScheduleActions.Analysis;
public bool ShowsOlderThan => _action.Name is ScheduleActions.Verify or ScheduleActions.Cleanup;
public bool ShowsPercent => _action.Name == ScheduleActions.Verify;
public bool ShowsDryRun => _action.Name == ScheduleActions.Maintenance;
public bool ShowsKeep => _action.Name == ScheduleActions.Backup;
public bool ShowsSteps => _action.Name == ScheduleActions.Cleanup;
/// <summary>The action has on/off parameters (full scan, deep analysis, report only), shown together on one row.</summary>
public bool HasSwitches => ShowsForce || ShowsDeep || ShowsDryRun;
public bool Force
{
get => _force;
set => Set(ref _force, value);
}
public string ForceLabel => Loc.L(_action.Name == ScheduleActions.Scan ? "Jobs.Editor.FullScan" : "Jobs.Editor.RebuildAll");
public string ForceToolTip => Loc.L(_action.Name == ScheduleActions.Scan ? "Tooltips.Jobs.Editor.FullScan" : "Tooltips.Jobs.Editor.RebuildAll");
public bool Deep
{
get => _deep;
set => Set(ref _deep, value);
}
public string DeepToolTip => Loc.L("Tooltips.Jobs.Editor.DeepAnalysis");
public bool DryRun
{
get => _dryRun;
set => Set(ref _dryRun, value);
}
public ScheduleField OlderThan { get; }
public string OlderThanLabel => Loc.L(IsVerify ? "Jobs.Editor.Unverified" : "Jobs.Editor.OlderThan");
public ScheduleField Percent { get; }
public ScheduleField Keep { get; }
/// <summary>The clean-up steps this PC runs, those of the schedule checked.</summary>
public IReadOnlyList<ScheduleChoice<string>> Steps
{
get => _steps;
private set => Set(ref _steps, value);
}
// ---------------- Options ----------------
public IReadOnlyList<SettingsOption<JobPriority>> Priorities { get; private set; }
public SettingsOption<JobPriority> SelectedPriority
{
get => _priority;
set
{
if (value is not null) Set(ref _priority, value);
}
}
public bool CatchUp
{
get => _catchUp;
set => Set(ref _catchUp, value);
}
public bool Enabled
{
get => _enabled;
set => Set(ref _enabled, value);
}
// ---------------- Save ----------------
public ICommand SaveCommand { get; }
/// <summary>Cancel: closes without saving.</summary>
public ICommand CloseCommand { get; }
public string SaveToolTip => Problem() ?? Loc.L(IsNew ? "Tooltips.Jobs.Editor.Create" : "Tooltips.Jobs.Editor.Save");
public bool IsBusy
{
get => _isBusy;
private set
{
if (!Set(ref _isBusy, value)) return;
CommandManager.InvalidateRequerySuggested();
}
}
/// <summary>Why the last save did not happen; null when nothing failed.</summary>
public string? ErrorText
{
get => _errorText;
private set => Set(ref _errorText, value);
}
public string? ErrorToolTip
{
get => _errorToolTip;
private set => Set(ref _errorToolTip, value);
}
/// <summary>
/// The first invalid field's problem, in the order of the dialog (name, when, parameters); null when the schedule can
/// be saved.
/// </summary>
public string? Problem()
{
if (!IsSystem && Name.Error is { } name) return name;
switch (Kind)
{
case RecurrenceKind.Every when Every.Error is { } every:
return every;
case RecurrenceKind.Every:
break;
default:
if (Time.Error is { } time) return time;
if (Kind == RecurrenceKind.Weekly && !Days.Any(d => d.IsChecked)) return Loc.L("Tooltips.Jobs.Editor.NoDays");
if (Kind == RecurrenceKind.Monthly && DayOfMonth.Error is { } day) return day;
break;
}
if (ShowsOlderThan && OlderThan.Error is { } older) return older;
if (ShowsPercent && Percent.Error is { } percent) return percent;
if (ShowsKeep && Keep.Error is { } keep) return keep;
if (ShowsSteps && !Steps.Any(s => s.IsChecked)) return Loc.L("Tooltips.Jobs.Editor.NoSteps");
return null;
}
/// <summary>The recurrence the fields describe; null while one of them is invalid.</summary>
public RecurrenceDto? Recurrence()
{
var time = Time.Error is null && TryTime(Time.Text, out var at) ? at.ToString("HH:mm", CultureInfo.InvariantCulture) : null;
RecurrenceDto? dto = Kind switch
{
RecurrenceKind.Every when TryNumber(Every.Text, out var every) => new RecurrenceDto("every", Every: every, Unit: ScheduleMapping.Unit(_unit.Value)),
RecurrenceKind.Daily when time is not null => new RecurrenceDto("daily", Time: time),
RecurrenceKind.Weekly when time is not null && Days.Any(d => d.IsChecked) =>
new RecurrenceDto("weekly", Time: time, Days: [.. Days.Where(d => d.IsChecked).Select(d => ScheduleRecurrence.DayName(d.Value))]),
RecurrenceKind.Monthly when time is not null && TryNumber(DayOfMonth.Text, out var day) => new RecurrenceDto("monthly", Time: time, DayOfMonth: day),
_ => null,
};
return ScheduleMapping.FromDto(dto) is not null ? dto : null;
}
/// <summary>The action's parameters as the fields hold them (only the action's own).</summary>
public ScheduleParametersDto Parameters() => ScheduleActions.Normalize(_action.Name, new ScheduleParametersDto(
OlderThanDays: ShowsOlderThan && TryNumber(OlderThan.Text, out var days) ? days : null,
Percent: ShowsPercent && TryNumber(Percent.Text, out var percent) ? percent : null,
Deep: ShowsDeep ? _deep : null,
DryRun: ShowsDryRun ? _dryRun : null,
Force: ShowsForce ? _force : null,
Steps: ShowsSteps ? [.. Steps.Where(s => s.IsChecked).Select(s => s.Value)] : null,
Keep: ShowsKeep && TryNumber(Keep.Text, out var keep) ? keep : null));
internal CreateScheduleRequest BuildCreate() =>
new(Name.Text.Trim(), _action.Name, Recurrence()!, Parameters(), _catchUp, JobWire.Priority(_priority.Value), _enabled);
/// <summary>Every field the dialog shows; a system schedule's name and action are left out (they stay).</summary>
internal UpdateScheduleRequest BuildUpdate() =>
new(IsSystem ? null : Name.Text.Trim(), IsSystem ? null : _action.Name, Recurrence(), Parameters(), _catchUp, JobWire.Priority(_priority.Value), _enabled);
/// <summary>Whether this PC runs each action was read again (<see cref="SchedulesViewModel.RefreshActionsAsync"/>).</summary>
internal void RefreshActions() => RebuildActionOptions();
protected override void OnLanguageChanged()
{
foreach (var field in new[] { Name, Every, Time, DayOfMonth, OlderThan, Percent, Keep }) field.Refresh();
foreach (var day in Days) day.Refresh();
foreach (var step in Steps) step.Refresh();
// The dropdowns' choices carry their labels: new ones in the new language, the same values chosen. Each list is
// announced before its choice, so a dropdown finds the choice among its items.
RebuildActionOptions();
Units = BuildUnits();
_unit = Units.First(u => u.Value == _unit.Value);
OnPropertyChanged(nameof(Units));
OnPropertyChanged(nameof(SelectedUnit));
Priorities = BuildPriorities();
_priority = Priorities.First(p => p.Value == _priority.Value);
OnPropertyChanged(nameof(Priorities));
OnPropertyChanged(nameof(SelectedPriority));
base.OnLanguageChanged();
}
/// <summary>The actions again, from the owner's last read; the chosen one stays chosen.</summary>
private void RebuildActionOptions()
{
ActionOptions = BuildActionOptions();
_action = ActionOptions.FirstOrDefault(o => o.Name == _action.Name) ?? _action;
OnPropertyChanged(nameof(ActionOptions));
OnPropertyChanged(nameof(SelectedAction));
OnPropertyChanged(nameof(ActionToolTip));
}
private ScheduleActionOption[] BuildActionOptions()
{
var available = _owner.Actions;
return [.. ScheduleActions.All.Select(a => available.FirstOrDefault(x => x.Name == a) is { } info
? new ScheduleActionOption(a, info.Available, info.Reason)
: new ScheduleActionOption(a, true, null))];
}
private static SettingsOption<RecurrenceUnit>[] BuildUnits() =>
[.. Enum.GetValues<RecurrenceUnit>().Select(u => new SettingsOption<RecurrenceUnit>(u, Loc.L("Jobs.Editor.Unit." + u)))];
private static SettingsOption<JobPriority>[] BuildPriorities() =>
[.. new[] { JobPriority.Background, JobPriority.Normal, JobPriority.User }.Select(p => new SettingsOption<JobPriority>(p, ScheduleText.Priority(p)))];
private bool IsVerify => _action.Name == ScheduleActions.Verify;
/// <summary>Save: the schedule as the fields hold it; the editor closes once it is stored, or says why it was not.</summary>
internal async Task SaveAsync()
{
if (Problem() is not null) return;
IsBusy = true;
ErrorText = null;
ErrorToolTip = null;
try
{
var result = await _owner.SaveAsync(this);
if (result.Problem is { } problem)
{
ErrorText = Loc.L("Jobs.Editor.Refused");
ErrorToolTip = Loc.L("Tooltips.Jobs.Editor.Refused", problem);
return;
}
IsBusy = false;
_owner.CloseEditor(this);
}
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
{
Log.Warning("schedules", "A schedule could not be saved", ex);
ErrorText = Loc.L("Jobs.Editor.SaveFailed");
ErrorToolTip = ex.Message;
}
finally
{
IsBusy = false;
}
}
/// <summary>Fills the parameter fields from <paramref name="parameters"/> (normalised for the current action).</summary>
private void LoadParameters(ScheduleParametersDto parameters)
{
var p = ScheduleActions.Normalize(_action.Name, parameters);
var defaults = ScheduleActions.Defaults(ScheduleActions.Verify);
_force = p.Force ?? false;
_deep = p.Deep ?? false;
_dryRun = p.DryRun ?? false;
OlderThan.Text = Number(p.OlderThanDays ?? defaults.OlderThanDays ?? 30);
// Its tooltip names what the days count (unverified, or older), which follows the action.
OlderThan.Refresh();
Percent.Text = Number(p.Percent ?? defaults.Percent ?? 100);
Keep.Text = Number(p.Keep ?? DatabaseBackups.Keep);
var chosen = p.Steps ?? [];
// The steps this PC runs, then any the schedule names that it does not (kept, shown by their wire name).
var names = _owner.Steps.Concat(chosen.Where(s => !_owner.Steps.Contains(s))).ToList();
Steps = [.. names.Select(s => new ScheduleChoice<string>(s, () => ScheduleText.Step(s), () => ScheduleText.StepToolTip(s), chosen.Contains(s), OnChanged))];
}
private void OnChanged()
{
OnPropertyChanged(nameof(WhenText));
OnPropertyChanged(nameof(SaveToolTip));
CommandManager.InvalidateRequerySuggested();
}
private string? ValidateName(string text)
{
if (string.IsNullOrWhiteSpace(text)) return Loc.L("Tooltips.Jobs.Editor.NameMissing");
return text.Trim().Length > Scheduler.MaxNameLength ? Loc.L("Tooltips.Jobs.Editor.NameLong", Scheduler.MaxNameLength) : null;
}
private string? ValidateEvery(string text)
{
var (min, max) = _unit.Value switch
{
RecurrenceUnit.Minutes => (ScheduleRecurrence.MinMinutes, ScheduleRecurrence.MaxMinutes),
RecurrenceUnit.Days => (1, ScheduleRecurrence.MaxDays),
_ => (1, ScheduleRecurrence.MaxHours),
};
return ValidateNumber(text, min, max);
}
private static string? ValidateDayOfMonth(string text) => ValidateNumber(text, 1, ScheduleRecurrence.MaxDayOfMonth);
private static string? ValidateTime(string text) => TryTime(text, out _) ? null : Loc.L("Tooltips.Jobs.Editor.TimeInvalid");
private static string? ValidateNumber(string text, int min, int max) =>
TryNumber(text, out var value) && value >= min && value <= max ? null : Loc.L("Tooltips.Jobs.Editor.Number", Number(min), Number(max));
private static string Number(int value) => value.ToString(CultureInfo.CurrentCulture);
/// <summary>A whole number as the user's culture writes it (no sign, no thousands).</summary>
private static bool TryNumber(string text, out int value) =>
int.TryParse(text.Trim(), NumberStyles.None, CultureInfo.CurrentCulture, out value) || int.TryParse(text.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out value);
/// <summary>"03:00", "3:00", "3.00": hours and minutes of a 24-hour clock.</summary>
internal static bool TryTime(string text, out TimeOnly time)
{
time = default;
var parts = text.Trim().Split(':', '.');
if (parts is not [var h, var m] || h.Length is < 1 or > 2 || m.Length != 2) return false;
if (!int.TryParse(h, NumberStyles.None, CultureInfo.InvariantCulture, out var hour) || !int.TryParse(m, NumberStyles.None, CultureInfo.InvariantCulture, out var minute)
|| hour > 23 || minute > 59)
return false;
time = new TimeOnly(hour, minute);
return true;
}
}
@@ -0,0 +1,211 @@
using System.Windows.Input;
using Chronos.App.Infrastructure;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Protocol;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Jobs;
/// <summary>
/// One row of Jobs › Scheduled (owner review 2, R10): the on/off switch, name, action, when it runs, the next run and the
/// last result, and its commands (Run now, Edit, then Reset for a system schedule or Delete for one the user created).
/// </summary>
public sealed class ScheduleRowViewModel : ObservableObject
{
private readonly SchedulesViewModel _owner;
private ScheduleDto _schedule;
private Job? _lastJob;
private long _lastJobStamp;
private bool _isEnabled;
internal ScheduleRowViewModel(ScheduleDto schedule, SchedulesViewModel owner)
{
_schedule = schedule;
_owner = owner;
_isEnabled = schedule.Enabled;
RunNowCommand = new AsyncRelayCommand(() => owner.RunNowAsync(this), () => IsAvailable);
EditCommand = new RelayCommand(() => owner.Edit(this));
DeleteCommand = new AsyncRelayCommand(() => owner.DeleteAsync(this), () => !IsSystem);
ResetCommand = new AsyncRelayCommand(() => owner.ResetAsync(this), () => IsSystem);
}
public ScheduleDto Schedule => _schedule;
public Guid Id => _schedule.Id;
/// <summary>A system schedule: one of the host's timers, reset instead of deleted.</summary>
public bool IsSystem => _schedule.SystemKey is not null;
/// <summary>The job the last run queued, when it is known.</summary>
public Job? LastJob => _lastJob;
public string Name => ScheduleText.Name(_schedule);
public string NameToolTip => IsSystem ? Loc.L("Tooltips.Jobs.Schedule.System", Name) : Name;
public string ActionText => ScheduleText.Action(_schedule.Action);
/// <summary>What the action does, or why this PC does not run it.</summary>
public string ActionToolTip => IsAvailable ? ScheduleText.ActionToolTip(_schedule.Action) : ScheduleText.Unavailable(_owner.UnavailableReason(_schedule.Action));
/// <summary>This PC runs the schedule's action.</summary>
public bool IsAvailable => _owner.IsAvailable(_schedule.Action);
public string WhenText => ScheduleText.When(_schedule.Recurrence);
/// <summary>When it runs, whether a missed run is caught up, and the priority of its jobs.</summary>
public string WhenToolTip => string.Join(Loc.Separator, WhenText,
Loc.L(_schedule.CatchUp ? "Tooltips.Jobs.Schedule.CatchUpOn" : "Tooltips.Jobs.Schedule.CatchUpOff"),
Loc.L("Tooltips.Jobs.Schedule.PriorityIs", ScheduleText.Priority(Priority)));
public string NextText => ScheduleText.Next(_schedule.NextRun, _schedule.Enabled);
public string NextToolTip => !_schedule.Enabled ? Loc.L("Tooltips.Jobs.Schedule.NextOff")
: _schedule.NextRun is { } next ? Loc.L("Tooltips.Jobs.Schedule.Next", Formatting.Date(next) + " " + Formatting.TimeOfDay(next))
: Loc.L("Tooltips.Jobs.Schedule.NextPending");
public string LastText => ScheduleText.Outcome(_schedule.LastOutcome, _lastJob);
public string LastToolTip => ScheduleText.OutcomeToolTip(_schedule.LastOutcome, _schedule.LastRun, _lastJob);
public StatusKind LastKind => ScheduleText.OutcomeKind(_schedule.LastOutcome, _lastJob);
/// <summary>Off, a schedule never runs by itself (Run now still runs it). Turning it on or off saves at once.</summary>
public bool IsEnabled
{
get => _isEnabled;
set
{
if (Set(ref _isEnabled, value)) _ = _owner.SetEnabledAsync(this, value);
}
}
public string EnabledToolTip => Loc.L(_isEnabled ? "Tooltips.Jobs.Schedule.EnabledOn" : "Tooltips.Jobs.Schedule.EnabledOff");
/// <summary>"Index backup · Index backup · Daily at 03:00": the row's name for screen readers.</summary>
public string AccessibleName => string.Join(Loc.Separator, Name, ActionText, WhenText);
public ICommand RunNowCommand { get; }
public ICommand EditCommand { get; }
public ICommand DeleteCommand { get; }
public ICommand ResetCommand { get; }
public string RunNowToolTip => IsAvailable ? Loc.L("Tooltips.Jobs.Schedule.RunNow") : ScheduleText.Unavailable(_owner.UnavailableReason(_schedule.Action));
/// <summary>"Run now: Index backup", what each row button is called for screen readers.</summary>
public string RunNowName => Loc.L("Jobs.ActionFor", Loc.L("Jobs.Schedule.RunNow"), Name);
public string EditName => Loc.L("Jobs.ActionFor", Loc.L("Jobs.Schedule.Edit"), Name);
public string DeleteName => Loc.L("Jobs.ActionFor", Loc.L("Jobs.Schedule.Delete"), Name);
public string ResetName => Loc.L("Jobs.ActionFor", Loc.L("Jobs.Schedule.Reset"), Name);
public string EnabledName => Loc.L("Jobs.ActionFor", Loc.L("Jobs.Schedule.Enabled"), Name);
private JobPriority Priority => JobWire.TryParsePriority(_schedule.Priority, out var priority) ? priority : JobPriority.Background;
/// <summary>A newer copy of the schedule (an edit, a run, a correction of its next run).</summary>
internal void Update(ScheduleDto schedule)
{
if (schedule.LastJobId != _schedule.LastJobId)
{
// A read of the previous job no longer applies.
_lastJob = null;
_lastJobStamp++;
}
_schedule = schedule;
_isEnabled = schedule.Enabled;
OnAllPropertiesChanged();
}
/// <summary>The job the last run queued changed (live, from the engine): the last result follows its state.</summary>
internal void SetLastJob(Job? job)
{
if (job is not null && job.Id != _schedule.LastJobId) return;
_lastJobStamp++;
ShowLastJob(job);
}
/// <summary>
/// A read of the last job from the index starts; its result applies only while nothing newer arrived (a live change,
/// another job, a later read): see <see cref="SetLoadedLastJob"/>.
/// </summary>
internal long BeginLastJobRead() => ++_lastJobStamp;
/// <summary>The last job as the read begun at <paramref name="read"/> found it; ignored when that read is stale.</summary>
internal void SetLoadedLastJob(Job? job, long read)
{
if (read != _lastJobStamp || (job is not null && job.Id != _schedule.LastJobId)) return;
ShowLastJob(job);
}
private void ShowLastJob(Job? job)
{
_lastJob = job;
OnPropertyChanged(nameof(LastJob));
OnPropertyChanged(nameof(LastText));
OnPropertyChanged(nameof(LastToolTip));
OnPropertyChanged(nameof(LastKind));
}
/// <summary>The switch goes back to the stored state (the change was refused).</summary>
internal void RevertEnabled()
{
_isEnabled = _schedule.Enabled;
OnPropertyChanged(nameof(IsEnabled));
OnPropertyChanged(nameof(EnabledToolTip));
}
internal void Refresh() => OnAllPropertiesChanged();
}
/// <summary>A job a schedule queued, in the selected schedule's last runs: kind, target, when, state, and Show in queue.</summary>
public sealed class ScheduleRunViewModel : ObservableObject
{
private Job _job;
internal ScheduleRunViewModel(Job job, Func<Guid, Task> show)
{
_job = job;
ShowCommand = new AsyncRelayCommand(() => show(_job.Id));
}
public Job Job => _job;
public Guid Id => _job.Id;
public string Kind => JobText.Kind(_job.Kind);
public string Target => _job.TargetLabel ?? string.Empty;
/// <summary>When the run queued it ("Today 03:00").</summary>
public string WhenText => ScheduleText.Moment(_job.Created);
public string StateText => JobText.State(new JobEntry(_job));
public string StateToolTip => string.Join(Loc.Separator, StateText,
_job.Error is { Length: > 0 } error ? error : Loc.L("Tooltips.Jobs.State." + _job.State));
public StatusKind StateKind => _job.State switch
{
JobState.Running => StatusKind.Running,
JobState.Queued => StatusKind.Queued,
JobState.Paused => StatusKind.Paused,
JobState.Done => StatusKind.Done,
JobState.Failed => StatusKind.Failed,
_ => StatusKind.Offline,
};
/// <summary>"Verify · Archive · 2024: done": the row for screen readers.</summary>
public string AccessibleName => Loc.L("Jobs.Row.State", JobText.Name(_job), StateText);
public string ShowName => Loc.L("Jobs.ActionFor", Loc.L("Jobs.Schedule.ShowJob"), JobText.Name(_job));
public ICommand ShowCommand { get; }
internal void Update(Job job)
{
_job = job;
OnAllPropertiesChanged();
}
internal void Refresh() => OnAllPropertiesChanged();
}
+193
View File
@@ -0,0 +1,193 @@
using Chronos.App.Infrastructure;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Housekeeping;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
using Chronos.Ui.Controls;
namespace Chronos.App.Jobs;
/// <summary>
/// Localized texts of schedules (Jobs › Scheduled, owner review 2, R10): names, actions, clean-up steps, when they run,
/// their next run and what their last run did. Wire names (<c>scan</c>, <c>skipped-pending</c>, <c>job-history</c>) never
/// reach the screen; an unknown one (a newer build's) is shown as it is.
/// </summary>
public static class ScheduleText
{
/// <summary>A system schedule by its key in the user's language; a user's schedule by the name they gave it.</summary>
public static string Name(ScheduleDto schedule)
{
ArgumentNullException.ThrowIfNull(schedule);
return schedule.SystemKey is { } key && SystemKeyName(key) is { } name ? Loc.L(name) : schedule.Name;
}
/// <summary>"Archive scan", "Index backup", …</summary>
public static string Action(string action) => ScheduleActions.IsKnown(action) ? Loc.L("Jobs.Schedule.Action." + Pascal(action)) : action;
/// <summary>What the action does.</summary>
public static string ActionToolTip(string action) =>
ScheduleActions.IsKnown(action) ? Loc.L("Tooltips.Jobs.Schedule.Action." + Pascal(action)) : Loc.L("Tooltips.Jobs.Schedule.Unavailable.Other");
/// <summary>Why this PC does not run an action (<see cref="ScheduleUnavailable"/>, or a code of the host's own).</summary>
public static string Unavailable(string? reason) => reason switch
{
ScheduleUnavailable.NoHandler => Loc.L("Tooltips.Jobs.Schedule.Unavailable.NoHandler"),
ScheduleUnavailable.Postgres => Loc.L("Tooltips.Jobs.Schedule.Unavailable.Postgres"),
ScheduleUnavailable.NoIndexFile => Loc.L("Tooltips.Jobs.Schedule.Unavailable.NoIndexFile"),
ScheduleUnavailable.ProxiesDisabled => Loc.L("Tooltips.Jobs.Schedule.Unavailable.ProxiesDisabled"),
_ => Loc.L("Tooltips.Jobs.Schedule.Unavailable.Other"),
};
/// <summary>"Job history", "Cache trim", …: a clean-up step; an unknown one by its wire name.</summary>
public static string Step(string step) => StepKey(step) is { } key ? Loc.L("Jobs.Schedule.Step." + key) : step;
public static string StepToolTip(string step) => StepKey(step) is { } key ? Loc.L("Tooltips.Jobs.Schedule.Step." + key) : step;
/// <summary>"Every 10 minutes", "Daily at 03:00", "Mon, Thu at 02:30", "Monthly, day 1 at 04:00".</summary>
public static string When(RecurrenceDto? recurrence) =>
ScheduleMapping.FromDto(recurrence) is { } parsed ? When(parsed) : Loc.L("Jobs.Schedule.When.Invalid");
/// <inheritdoc cref="When(RecurrenceDto?)"/>
public static string When(ScheduleRecurrence recurrence)
{
ArgumentNullException.ThrowIfNull(recurrence);
return recurrence.Kind switch
{
RecurrenceKind.Every => Loc.Plural("Jobs.Schedule.When." + recurrence.Unit, recurrence.Every),
RecurrenceKind.Daily => Loc.L("Jobs.Schedule.When.Daily", Time(recurrence.Time)),
RecurrenceKind.Weekly when recurrence.Days.Count == 7 => Loc.L("Jobs.Schedule.When.Daily", Time(recurrence.Time)),
RecurrenceKind.Weekly => Loc.L("Jobs.Schedule.When.Weekly", Days(recurrence.Days), Time(recurrence.Time)),
_ => Loc.L("Jobs.Schedule.When.Monthly", recurrence.DayOfMonth, Time(recurrence.Time)),
};
}
/// <summary>
/// "Mon, Thu": the days in the order of the UI language's week, from its first day as the editor lists them (Sunday
/// first in English, Monday first in Italian), short names of the UI language.
/// </summary>
public static string Days(IEnumerable<DayOfWeek> days)
{
var first = (int)Loc.Culture.DateTimeFormat.FirstDayOfWeek;
return days.OrderBy(d => ((int)d - first + 7) % 7).Select(DayShort).Aggregate((a, b) => Loc.L("Jobs.Schedule.DayList", a, b));
}
/// <summary>"Mon" in the UI language.</summary>
public static string DayShort(DayOfWeek day) => Loc.Culture.DateTimeFormat.GetAbbreviatedDayName(day);
/// <summary>"Monday" in the UI language.</summary>
public static string DayLong(DayOfWeek day) => Loc.Culture.DateTimeFormat.GetDayName(day);
/// <summary>A wall-clock time in the UI language's short format ("03:00", "3:00 AM").</summary>
public static string Time(TimeOnly time) => DateTime.MinValue.Add(time.ToTimeSpan()).ToString("t", Loc.Culture);
/// <summary>
/// The next run as the table shows it: "Today 03:00", "Tomorrow 03:00", a date and time further away, "Off" for a
/// disabled schedule, "—" while it has none yet.
/// </summary>
public static string Next(DateTimeOffset? next, bool enabled)
{
if (!enabled) return Loc.L("Jobs.Schedule.Off");
return next is { } at ? Moment(at) : "—";
}
/// <summary>"Today 03:00", "Tomorrow 03:00", "Yesterday 03:00", or the short date and time.</summary>
public static string Moment(DateTimeOffset at)
{
var local = at.ToLocalTime();
var days = (local.Date - AppClock.Today).Days;
var time = Formatting.TimeOfDay(at);
return days switch
{
0 => Loc.L("Jobs.Schedule.Today", time),
1 => Loc.L("Jobs.Schedule.Tomorrow", time),
-1 => Loc.L("Jobs.Schedule.Yesterday", time),
_ => Formatting.Date(at) + " " + time,
};
}
/// <summary>
/// What the last run did: the state of the job it queued when that is known ("done", "failed", "running"), else the
/// outcome ("skipped: busy", "nothing to do", …); "never run" before the first run.
/// </summary>
public static string Outcome(string? outcome, Job? lastJob)
{
if (outcome is null) return Loc.L("Jobs.Schedule.Outcome.Never");
if (outcome == ScheduleOutcome.Queued && lastJob is not null) return Loc.L("Jobs.State." + lastJob.State);
if (ScheduleOutcome.IsFailed(outcome, out _)) return Loc.L("Jobs.Schedule.Outcome.Failed");
return OutcomeKey(outcome) is { } key ? Loc.L("Jobs.Schedule.Outcome." + key) : outcome;
}
/// <summary>The outcome explained, with when the last run was and the reason of a failure.</summary>
public static string OutcomeToolTip(string? outcome, DateTimeOffset? lastRun, Job? lastJob)
{
if (outcome is null || lastRun is not { } at) return Loc.L("Tooltips.Jobs.Schedule.Outcome.Never");
var when = Loc.L("Jobs.Schedule.LastRun", Moment(at));
string why;
if (ScheduleOutcome.IsFailed(outcome, out var reason)) why = Loc.L("Tooltips.Jobs.Schedule.Outcome.Failed", reason);
else if (outcome == ScheduleOutcome.Queued && lastJob is { Error: { Length: > 0 } error }) why = error;
else if (outcome == ScheduleOutcome.Queued && lastJob is not null) why = Loc.L("Tooltips.Jobs.State." + lastJob.State);
else why = OutcomeKey(outcome) is { } key ? Loc.L("Tooltips.Jobs.Schedule.Outcome." + key) : outcome;
return string.Join(Loc.Separator, when, why);
}
/// <summary>Glyph of the last result, paired with its word.</summary>
public static StatusKind OutcomeKind(string? outcome, Job? lastJob)
{
if (outcome is null) return StatusKind.Offline;
if (ScheduleOutcome.IsFailed(outcome, out _)) return StatusKind.Failed;
if (outcome == ScheduleOutcome.Queued && lastJob is not null)
{
return lastJob.State switch
{
JobState.Running => StatusKind.Running,
JobState.Queued => StatusKind.Queued,
JobState.Paused => StatusKind.Paused,
JobState.Done => StatusKind.Done,
JobState.Failed => StatusKind.Failed,
_ => StatusKind.Offline,
};
}
return outcome switch
{
ScheduleOutcome.Queued => StatusKind.Queued,
ScheduleOutcome.SkippedNothing => StatusKind.Done,
ScheduleOutcome.SkippedPending => StatusKind.Paused,
ScheduleOutcome.Unavailable => StatusKind.Warning,
_ => StatusKind.Offline,
};
}
/// <summary>"Background", "Normal", "High": the priority of the jobs a schedule queues.</summary>
public static string Priority(JobPriority priority) => Loc.L("Jobs.Schedule.Priority." + priority);
private static string? SystemKeyName(string key) => key switch
{
DesktopScheduleHost.ArchiveScan => "Jobs.Schedule.System.ArchiveScan",
DesktopScheduleHost.IndexBackup => "Jobs.Schedule.System.IndexBackup",
DesktopScheduleHost.Housekeeping => "Jobs.Schedule.System.Housekeeping",
_ => null,
};
private static string? StepKey(string step) => step switch
{
CleanupSteps.JobHistory => "JobHistory",
CleanupSteps.Audit => "Audit",
CleanupSteps.TrashReport => "TrashReport",
CacheTrimStep.StepName => "CacheTrim",
_ => null,
};
private static string? OutcomeKey(string outcome) => outcome switch
{
ScheduleOutcome.Queued => "Queued",
ScheduleOutcome.SkippedPending => "SkippedPending",
ScheduleOutcome.SkippedOffline => "SkippedOffline",
ScheduleOutcome.SkippedNothing => "SkippedNothing",
ScheduleOutcome.Unavailable => "Unavailable",
_ => null,
};
/// <summary><c>scan</c> → <c>Scan</c>: the resource name of a wire name.</summary>
private static string Pascal(string name) => string.Concat(name.Split('-').Select(p => p.Length == 0 ? p : char.ToUpperInvariant(p[0]) + p[1..]));
}
+544
View File
@@ -0,0 +1,544 @@
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Input;
using Chronos.App.Infrastructure;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Housekeeping;
using Chronos.Data.Scheduling;
using Chronos.Protocol;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Jobs;
/// <summary>
/// Jobs › Scheduled (owner review 2, R10): every schedule of this PC's <see cref="Scheduler"/> (the system ones that stand
/// for its timers first), each with its switch, next run and last result, kept current by the scheduler's events and by
/// the jobs its runs queued; the selected schedule's last runs, each one shown in the queue on request; the in-window
/// editor of a new or existing schedule. Calls to the scheduler run off the UI thread; their results and its events are
/// applied on it. WPF-free apart from the commands: tests drive it with a scheduler of their own.
/// </summary>
public sealed class SchedulesViewModel : LocalizedViewModel
{
/// <summary>Runs listed for the selected schedule.</summary>
public const int RunsShown = 20;
private readonly Func<Scheduler?> _scheduler;
private readonly Func<ChronosDatabase?> _database;
private readonly Func<ConfirmRequest, bool> _confirm;
private readonly Action<string, string?, bool> _notify;
private readonly Func<Guid, Task> _showJob;
private readonly Dictionary<Guid, ScheduleRowViewModel> _rows = [];
private SynchronizationContext? _context;
private Scheduler? _attached;
private IReadOnlyList<ScheduleActionDto> _actions = [];
private IReadOnlyList<string> _steps = [];
private ScheduleRowViewModel? _selected;
private ScheduleEditorViewModel? _editor;
private bool _isLoaded;
private int _runsRequest;
private Task? _attach;
/// <param name="scheduler">The running scheduler (once <see cref="AttachAsync"/> was told it runs).</param>
/// <param name="database">The index, to read the jobs the runs queued.</param>
/// <param name="confirm">Asks before a delete or a reset.</param>
/// <param name="notify">A toast: title, message, whether something did not happen.</param>
/// <param name="showJob">Shows a job in the queue tab.</param>
public SchedulesViewModel(Func<Scheduler?> scheduler, Func<ChronosDatabase?> database, Func<ConfirmRequest, bool> confirm,
Action<string, string?, bool> notify, Func<Guid, Task> showJob)
{
_scheduler = scheduler;
_database = database;
_confirm = confirm;
_notify = notify;
_showJob = showJob;
NewCommand = new RelayCommand(New, () => IsRunning && _editor is null);
}
/// <summary>A schedule changed in a way the history text depends on (the housekeeping's job-history days).</summary>
public event Action? HistoryChanged;
/// <summary>System schedules first, then the user's, oldest first (the scheduler's order).</summary>
public ObservableCollection<ScheduleRowViewModel> Rows { get; } = [];
/// <summary>The jobs the selected schedule queued, newest first.</summary>
public ObservableCollection<ScheduleRunViewModel> Runs { get; } = [];
public ICommand NewCommand { get; }
public string NewToolTip => IsRunning ? Loc.L("Tooltips.Jobs.Schedule.New") : Loc.L("Tooltips.Jobs.Schedule.NotRunning");
/// <summary>The scheduler of this PC runs (it does not without an index, or while it failed to start).</summary>
public bool IsRunning => _attached is not null;
/// <summary>The schedules were read, or it is known that there are none to read.</summary>
public bool IsLoaded => _isLoaded;
public bool HasRows => Rows.Count > 0;
/// <summary>The empty state: the scheduler does not run here.</summary>
public bool IsUnavailable => _isLoaded && !IsRunning;
public ScheduleRowViewModel? Selected
{
get => _selected;
set
{
if (!Set(ref _selected, value)) return;
OnPropertyChanged(nameof(HasSelection));
OnPropertyChanged(nameof(RunsHeading));
RunsLoading = LoadRunsAsync();
}
}
public bool HasSelection => _selected is not null;
/// <summary>"Last runs · Index backup".</summary>
public string RunsHeading => _selected is { } row ? Loc.L("Jobs.Row.Name", Loc.L("Jobs.Schedule.Runs"), row.Name) : Loc.L("Jobs.Schedule.Runs");
public bool HasRuns => Runs.Count > 0;
public bool IsRunsEmpty => _selected is not null && Runs.Count == 0;
/// <summary>The open editor; null when none.</summary>
public ScheduleEditorViewModel? Editor
{
get => _editor;
private set
{
if (!Set(ref _editor, value)) return;
OnPropertyChanged(nameof(IsEditorOpen));
OnPropertyChanged(nameof(IsContentEnabled));
CommandManager.InvalidateRequerySuggested();
}
}
public bool IsEditorOpen => _editor is not null;
/// <summary>The screen behind an open editor takes neither clicks nor keyboard focus.</summary>
public bool IsContentEnabled => _editor is null;
/// <summary>The actions with whether this PC runs them, as last read.</summary>
public IReadOnlyList<ScheduleActionDto> Actions => _actions;
/// <summary>The clean-up steps this PC's clean-up jobs run.</summary>
public IReadOnlyList<string> Steps => _steps;
/// <summary>
/// Days of job history the housekeeping schedule keeps: its age limit while it is on and removes job history; null
/// while it keeps every job; the product's default before the schedules are read.
/// </summary>
public int? HistoryDays
{
get
{
if (!_isLoaded || !IsRunning) return CleanupSteps.DefaultHistoryDays;
var housekeeping = Rows.FirstOrDefault(r => r.Schedule.SystemKey == DesktopScheduleHost.Housekeeping)?.Schedule;
if (housekeeping is not { Enabled: true, Action: ScheduleActions.Cleanup } || housekeeping.Parameters.Steps?.Contains(CleanupSteps.JobHistory) != true)
return null;
return housekeeping.Parameters.OlderThanDays is > 0 and var days ? days : null;
}
}
internal Scheduler? Scheduler => _attached;
/// <summary>The last read of the selected schedule's runs (capture, tests).</summary>
internal Task RunsLoading { get; private set; } = Task.CompletedTask;
/// <summary>Completes once <see cref="AttachAsync"/> has read the schedules, or knows there are none.</summary>
public Task Attached => _attach ?? Task.CompletedTask;
/// <summary>
/// Waits for the scheduler (<paramref name="ready"/>: true once it runs), then follows its events and reads the
/// schedules. Call on the UI thread, once: events are brought back to it.
/// </summary>
public Task AttachAsync(Task<bool> ready)
{
ArgumentNullException.ThrowIfNull(ready);
return _attach ??= AttachCoreAsync(ready);
}
private async Task AttachCoreAsync(Task<bool> ready)
{
_context = SynchronizationContext.Current;
bool running;
try
{
running = await ready;
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("schedules", "The schedules did not start", ex);
running = false;
}
if (!running || _scheduler() is not { } scheduler)
{
_isLoaded = true;
RaiseState();
return;
}
_attached = scheduler;
scheduler.ScheduleChanged += OnScheduleChanged;
scheduler.ScheduleDeleted += OnScheduleDeleted;
await ReloadAsync();
}
public override void Dispose()
{
if (_attached is not null)
{
_attached.ScheduleChanged -= OnScheduleChanged;
_attached.ScheduleDeleted -= OnScheduleDeleted;
}
_editor?.Dispose();
base.Dispose();
}
/// <summary>Reads every schedule, the actions' availability and the jobs of the last runs again.</summary>
public async Task ReloadAsync()
{
if (_attached is not { } scheduler) return;
SchedulesDto list;
try
{
list = await Task.Run(() => scheduler.ListAsync());
}
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
{
Log.Warning("schedules", "The schedules could not be read", ex);
_isLoaded = true;
RaiseState();
return;
}
_actions = list.Actions;
_steps = list.Steps ?? [];
var wanted = list.Items.Select(s => s.Id).ToHashSet();
foreach (var gone in _rows.Keys.Where(id => !wanted.Contains(id)).ToList()) Remove(gone);
for (var i = 0; i < list.Items.Count; i++)
{
var dto = list.Items[i];
if (!_rows.TryGetValue(dto.Id, out var row))
{
row = new ScheduleRowViewModel(dto, this);
_rows[dto.Id] = row;
}
else
{
// Every text again: the actions' availability may have changed too.
row.Update(dto);
}
var at = Rows.IndexOf(row);
if (at == i) continue;
if (at >= 0) Rows.Move(at, i);
else Rows.Insert(i, row);
}
_isLoaded = true;
RaiseState();
HistoryChanged?.Invoke();
foreach (var row in Rows.ToList()) await LoadLastJobAsync(row);
if (_selected is not null) await LoadRunsAsync();
}
/// <summary>
/// Reads again whether this PC runs each action (Jobs › Scheduled is shown: proxies may have been turned on or off,
/// another archive chosen): the rows' Run now and tooltips, and the actions of the editor, follow it.
/// </summary>
public async Task RefreshActionsAsync()
{
if (_attached is not { } scheduler) return;
SchedulesDto list;
try
{
list = await Task.Run(() => scheduler.ListAsync());
}
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
{
Log.Warning("schedules", "The actions could not be read again", ex);
return;
}
_actions = list.Actions;
_steps = list.Steps ?? [];
foreach (var row in Rows) row.Refresh();
_editor?.RefreshActions();
CommandManager.InvalidateRequerySuggested();
}
/// <summary>A job changed (UI thread, from the Jobs screen's flush): the last result and the last runs follow it.</summary>
public void OnJob(Job job)
{
ArgumentNullException.ThrowIfNull(job);
if (job.ScheduleId is not { } id || !_rows.TryGetValue(id, out var row)) return;
if (row.Schedule.LastJobId == job.Id) row.SetLastJob(job);
if (!ReferenceEquals(_selected, row)) return;
if (Runs.FirstOrDefault(r => r.Id == job.Id) is { } run)
{
run.Update(job);
}
else
{
Runs.Insert(0, new ScheduleRunViewModel(job, _showJob));
while (Runs.Count > RunsShown) Runs.RemoveAt(Runs.Count - 1);
RaiseRuns();
}
}
/// <summary>Whether this PC runs <paramref name="action"/> (unknown until the list is read: yes).</summary>
public bool IsAvailable(string action) => _actions.FirstOrDefault(a => a.Name == action) is not { Available: false };
public string? UnavailableReason(string action) => _actions.FirstOrDefault(a => a.Name == action)?.Reason;
protected override void OnLanguageChanged()
{
foreach (var row in Rows) row.Refresh();
foreach (var run in Runs) run.Refresh();
HistoryChanged?.Invoke();
base.OnLanguageChanged();
}
// ---------------- Row commands ----------------
/// <summary>Runs the schedule now, as its next run would; says so when nothing was queued.</summary>
internal async Task RunNowAsync(ScheduleRowViewModel row)
{
if (_attached is not { } scheduler) return;
var run = await Call(() => scheduler.RunNowAsync(row.Id, null));
if (run is null)
{
await ReloadAsync();
return;
}
Apply(run.Schedule);
if (run.Outcome == ScheduleOutcome.Queued) return;
// This PC no longer runs the action: the row says so from now on.
if (run.Outcome == ScheduleOutcome.Unavailable) await RefreshActionsAsync();
_notify(Loc.L("Jobs.Row.Name", row.Name, ScheduleText.Outcome(run.Outcome, null)), ScheduleText.OutcomeToolTip(run.Outcome, run.Schedule.LastRun, null),
ScheduleOutcome.IsFailed(run.Outcome, out _) || run.Outcome == ScheduleOutcome.Unavailable);
}
/// <summary>Turns a schedule on or off (its switch); a refused change puts the switch back.</summary>
internal async Task SetEnabledAsync(ScheduleRowViewModel row, bool enabled)
{
if (_attached is not { } scheduler) return;
var result = await Call(() => scheduler.UpdateAsync(row.Id, new UpdateScheduleRequest(Enabled: enabled)));
if (result?.Schedule is { } saved)
{
Apply(saved);
return;
}
row.RevertEnabled();
if (result is { NotFound: true }) await ReloadAsync();
}
internal void Edit(ScheduleRowViewModel row)
{
if (_editor is not null) return;
Editor = new ScheduleEditorViewModel(this, row.Schedule);
}
/// <summary>Deletes a schedule the user created, after asking.</summary>
internal async Task DeleteAsync(ScheduleRowViewModel row)
{
if (_attached is not { } scheduler || row.IsSystem) return;
var confirmed = _confirm(new ConfirmRequest
{
Heading = Loc.L("Jobs.Schedule.DeleteHeading", row.Name),
Message = Loc.L("Jobs.Schedule.DeleteMessage"),
SafeText = Loc.L("Jobs.Schedule.Keep"),
SafeToolTip = Loc.L("Tooltips.Jobs.Schedule.Keep"),
ActionText = Loc.L("Jobs.Schedule.Delete"),
ActionToolTip = Loc.L("Tooltips.Jobs.Schedule.Delete"),
IsDestructive = true,
});
if (!confirmed) return;
// Nullable: a failed call is null, not the enum's first value (Deleted), so its row stays.
var outcome = await Call<ScheduleDeleteOutcome?>(async () => await scheduler.DeleteAsync(row.Id));
if (outcome is ScheduleDeleteOutcome.Deleted or ScheduleDeleteOutcome.NotFound) Remove(row.Id);
}
/// <summary>Puts a system schedule back to this PC's defaults, after asking.</summary>
internal async Task ResetAsync(ScheduleRowViewModel row)
{
if (_attached is not { } scheduler || !row.IsSystem) return;
var confirmed = _confirm(new ConfirmRequest
{
Heading = Loc.L("Jobs.Schedule.ResetHeading", row.Name),
Message = Loc.L("Jobs.Schedule.ResetMessage"),
SafeText = Loc.L("Jobs.Schedule.Keep"),
SafeToolTip = Loc.L("Tooltips.Jobs.Schedule.KeepEdits"),
ActionText = Loc.L("Jobs.Schedule.Reset"),
ActionToolTip = Loc.L("Tooltips.Jobs.Schedule.Reset"),
});
if (!confirmed) return;
var result = await Call(() => scheduler.ResetAsync(row.Id));
if (result?.Schedule is { } saved) Apply(saved);
else await ReloadAsync();
}
// ---------------- Editor ----------------
private void New()
{
if (_editor is not null || !IsRunning) return;
Editor = new ScheduleEditorViewModel(this, null);
}
/// <summary>Saves what the editor holds: a new schedule, or the fields of the one it edits.</summary>
internal async Task<ScheduleEditResult> SaveAsync(ScheduleEditorViewModel editor)
{
if (_attached is not { } scheduler) return new ScheduleEditResult(null, null);
var result = editor.ScheduleId is { } id
? await Task.Run(() => scheduler.UpdateAsync(id, editor.BuildUpdate()))
: await Task.Run(() => scheduler.CreateAsync(editor.BuildCreate(), null));
if (result.Schedule is { } saved)
{
Apply(saved);
if (editor.ScheduleId is null && _rows.TryGetValue(saved.Id, out var created)) Selected = created;
}
else if (result.NotFound)
{
await ReloadAsync();
}
return result;
}
/// <summary>Closes <paramref name="editor"/> if it is still the open one.</summary>
internal void CloseEditor(ScheduleEditorViewModel editor)
{
if (!ReferenceEquals(_editor, editor)) return;
editor.Dispose();
Editor = null;
}
// ---------------- Events and rows ----------------
private void OnScheduleChanged(ScheduleDto schedule) => Post(() => Apply(schedule));
private void OnScheduleDeleted(Guid id) => Post(() => Remove(id));
private void Post(Action action)
{
if (_context is null || SynchronizationContext.Current == _context) action();
else _context.Post(_ => action(), null);
}
/// <summary>A schedule as the scheduler returned or announced it: its row changes, or joins the list in the scheduler's order.</summary>
private void Apply(ScheduleDto schedule)
{
if (_rows.TryGetValue(schedule.Id, out var row))
{
var newRun = row.Schedule.LastRun != schedule.LastRun;
var newJob = schedule.LastJobId is { } job && job != row.LastJob?.Id;
row.Update(schedule);
if (newJob) _ = LoadLastJobAsync(row);
if (newRun && ReferenceEquals(_selected, row)) RunsLoading = LoadRunsAsync();
}
else
{
row = new ScheduleRowViewModel(schedule, this);
_rows[schedule.Id] = row;
Rows.Insert(InsertionIndex(schedule), row);
_ = LoadLastJobAsync(row);
RaiseState();
}
if (schedule.SystemKey == DesktopScheduleHost.Housekeeping) HistoryChanged?.Invoke();
}
/// <summary>Where a new row goes: system schedules first, then by creation.</summary>
private int InsertionIndex(ScheduleDto schedule)
{
for (var i = 0; i < Rows.Count; i++)
{
var other = Rows[i].Schedule;
var before = (schedule.SystemKey is not null, other.SystemKey is not null) switch
{
(true, false) => true,
(false, true) => false,
_ => schedule.Created < other.Created,
};
if (before) return i;
}
return Rows.Count;
}
private void Remove(Guid id)
{
if (!_rows.Remove(id, out var row)) return;
Rows.Remove(row);
if (ReferenceEquals(_selected, row)) Selected = null;
RaiseState();
}
/// <summary>Reads the job of the schedule's last run; a change of it announced meanwhile, or a later read, wins.</summary>
private async Task LoadLastJobAsync(ScheduleRowViewModel row)
{
if (row.Schedule.LastJobId is not { } id || _database() is not { } db) return;
var read = row.BeginLastJobRead();
try
{
row.SetLoadedLastJob(await db.Jobs.GetAsync(id), read);
}
catch (DatabaseException ex)
{
Log.Warning("schedules", $"The last job of schedule {row.Id} could not be read", ex);
}
}
/// <summary>The selected schedule's jobs, newest first; a later selection wins over a slower read.</summary>
private async Task LoadRunsAsync()
{
var request = ++_runsRequest;
var row = _selected;
IReadOnlyList<Job> jobs = [];
if (row is not null && _database() is { } db)
{
try
{
jobs = await db.Jobs.ListByScheduleAsync(row.Id, RunsShown);
}
catch (DatabaseException ex)
{
Log.Warning("schedules", $"The runs of schedule {row.Id} could not be read", ex);
}
}
if (request != _runsRequest) return;
Runs.Clear();
foreach (var job in jobs) Runs.Add(new ScheduleRunViewModel(job, _showJob));
RaiseRuns();
}
/// <summary>
/// Runs a scheduler call off the UI thread; a failure becomes a toast and null (for a value type, ask for its nullable
/// type: its default would read as a result).
/// </summary>
private async Task<T?> Call<T>(Func<Task<T>> call)
{
try
{
return await Task.Run(call);
}
catch (Exception ex) when (ex is DatabaseException or IOException or InvalidOperationException)
{
Log.Warning("schedules", "A schedule could not be changed", ex);
_notify(Loc.L("Jobs.Schedule.Failed"), ex.Message, true);
return default;
}
}
private void RaiseState()
{
OnPropertyChanged(nameof(IsRunning));
OnPropertyChanged(nameof(IsLoaded));
OnPropertyChanged(nameof(HasRows));
OnPropertyChanged(nameof(IsUnavailable));
OnPropertyChanged(nameof(NewToolTip));
CommandManager.InvalidateRequerySuggested();
}
private void RaiseRuns()
{
OnPropertyChanged(nameof(HasRuns));
OnPropertyChanged(nameof(IsRunsEmpty));
}
}