using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Input;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.App.Library;
using Chronos.App.Settings;
using Chronos.App.Shell;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Jobs;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Sections;
/// A filter chip of the Jobs toolbar ("Running · 4").
public sealed class JobFilterChip(JobFilter filter, Action select) : ObservableObject
{
private int _count;
private bool _isSelected;
public JobFilter Filter { get; } = filter;
public string Text => Loc.L("Jobs.Filter." + Filter, Formatting.Count(_count));
public string ToolTip => Loc.L("Tooltips.Jobs.Filter." + Filter);
public ICommand SelectCommand { get; } = new RelayCommand(() => select(filter));
public bool IsSelected
{
get => _isSelected;
set => Set(ref _isSelected, value);
}
public int Count
{
get => _count;
set
{
if (Set(ref _count, value)) OnPropertyChanged(nameof(Text));
}
}
internal void Refresh() => OnAllPropertiesChanged();
}
///
/// 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 (). 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 (), whichever screen started it.
///
public sealed class JobsViewModel : SectionViewModel
{
private static readonly TimeSpan FlushInterval = TimeSpan.FromMilliseconds(100);
private const int PageSize = 200;
private readonly JobListModel _model = new();
private readonly JobUpdateBuffer _buffer = new();
private readonly Dictionary _rows = [];
private readonly HashSet _unseenFailures = [];
private readonly JobEndings _endings = new();
/// Finished renders whose toast was taken ().
private readonly HashSet _renderToasts = [];
private readonly JobActions _actions;
private CoalescingThrottle? _throttle;
private IJobQueue? _queue;
private JobFilter _filter = JobFilter.All;
private string _searchText = string.Empty;
private string? _cursor;
private bool _hasMore;
private bool _loading;
private bool _hasLoaded;
private int _tabIndex;
public JobsViewModel(ShellViewModel shell)
: base(SectionKey.Jobs, "Icon.Jobs")
{
Shell = shell;
_actions = new JobActions(this);
Chips = [.. Enum.GetValues().Select(f => new JobFilterChip(f, SelectFilter) { IsSelected = f == JobFilter.All })];
PauseCurrentCommand = new AsyncRelayCommand(PauseCurrentAsync, () => _model.Current is not null);
PauseAllCommand = new AsyncRelayCommand(PauseAllAsync, () => _model.RunningCount > 0);
ClearDoneCommand = new RelayCommand(ClearDone, () => _model.CountOf(JobFilter.Done, ClearedAt) + _model.CountOf(JobFilter.Failed, ClearedAt) > 0);
RenderingSettingsCommand = new RelayCommand(() =>
{
Shell.Settings.Page = SettingsPage.Rendering;
Shell.Navigate(SectionKey.Settings);
});
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));
};
}
/// A row the screen should bring into view and expand (a job shown from Jobs › Scheduled).
public event Action? RowRevealRequested;
public ShellViewModel Shell { get; }
/// Jobs › Scheduled.
public SchedulesViewModel Schedules { get; }
/// 0 = Queue, 1 = Scheduled (the segmented control's index). Scheduled, shown, reads the actions' availability again.
public int TabIndex
{
get => _tabIndex;
set
{
if (value is < 0 or > 1 || !Set(ref _tabIndex, value)) return;
OnPropertyChanged(nameof(IsQueue));
OnPropertyChanged(nameof(IsScheduled));
if (IsScheduled) _ = Schedules.RefreshActionsAsync();
}
}
public bool IsQueue => _tabIndex == 0;
public bool IsScheduled => _tabIndex == 1;
/// The screen behind the schedule editor takes neither clicks nor keyboard focus.
public bool IsContentEnabled => Schedules.IsContentEnabled;
/// Rows in display order for the current filter and search.
public ObservableCollection Rows { get; } = [];
public IReadOnlyList Chips { get; }
public ICommand PauseCurrentCommand { get; }
public ICommand PauseAllCommand { get; }
public ICommand ClearDoneCommand { get; }
public ICommand RenderingSettingsCommand { get; }
public ICommand LoadMoreCommand { get; }
/// The empty state's one action: jobs start with an import.
public ICommand ImportCommand { get; }
public JobFilter Filter
{
get => _filter;
set
{
if (!Set(ref _filter, value)) return;
foreach (var chip in Chips) chip.IsSelected = chip.Filter == value;
SyncRows();
}
}
public string SearchText
{
get => _searchText;
set
{
if (Set(ref _searchText, value ?? string.Empty)) SyncRows();
}
}
/// "8 photos at once": what the running job of this PC processes together (Settings › Rendering › Parallelism).
public string ParallelismText => Loc.Plural("Jobs.Parallelism", Shell.Services.Parallelism);
/// The engine of this PC runs jobs (it runs none before it starts).
public bool HasEngine => _queue is { IsRunning: true };
/// The priority queue of Settings › Rendering is on: higher jobs pause the running one.
public bool IsPriorityQueueOn => HasEngine && Shell.Services.Settings.PriorityQueue;
/// "History keeps 90 days": the age limit of the housekeeping schedule's job-history step; "Full history kept" without one.
public string HistoryText => Schedules.HistoryDays is { } days ? Loc.Plural("Jobs.History", days) : Loc.L("Jobs.HistoryKept");
public bool IsEmpty => _hasLoaded && Rows.Count == 0;
public bool HasRows => Rows.Count > 0;
internal IJobQueue? Queue => _queue;
internal JobListModel Model => _model;
private DateTimeOffset? ClearedAt => Shell.Services.Settings.JobsClearedAt;
/// Subscribes to the engine and loads the first page of jobs; the Scheduled tab follows the schedules once they run.
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)
{
_hasLoaded = true;
RaiseState();
return;
}
_throttle = new CoalescingThrottle(FlushInterval, SynchronizationContext.Current, Flush);
_queue.JobChanged += OnJobChanged;
_queue.Progress += OnProgress;
_ = LoadMoreAsync();
}
public override void Dispose()
{
if (_queue is not null)
{
_queue.JobChanged -= OnJobChanged;
_queue.Progress -= OnProgress;
}
_throttle?.Dispose();
Schedules.Dispose();
base.Dispose();
}
/// The UI language changed: the rows, the filter chips and the job bar say it again in the new language.
protected override void OnLanguageChanged()
{
foreach (var row in _rows.Values) row.Refresh();
foreach (var chip in Chips) chip.Refresh();
UpdateShell();
base.OnLanguageChanged();
}
/// Reads the job list again from the first page (after jobs were written outside the engine).
public Task ReloadAsync()
{
_cursor = null;
_hasMore = true;
_hasLoaded = false;
return LoadMoreAsync();
}
/// Next page of the history (newest first); the view calls it when the list scrolls near its end.
public async Task LoadMoreAsync()
{
if (_queue is null || _loading || (_hasLoaded && !_hasMore)) return;
_loading = true;
try
{
var stamp = _model.Stamp;
var page = await _queue.ListAsync(_cursor, PageSize);
foreach (var job in page.Items) _model.ApplyLoaded(job, stamp);
_cursor = page.NextCursor;
_hasMore = page.NextCursor is not null;
}
catch (DatabaseException ex)
{
Log.Warning("jobs", "Job list unavailable", ex);
_hasMore = false;
}
finally
{
_loading = false;
_hasLoaded = true;
}
Flush();
}
/// Applies everything buffered since the last flush (UI thread).
internal void Flush()
{
var (jobs, progress) = _buffer.Drain();
foreach (var job in jobs)
{
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));
SyncRows();
UpdateShell();
}
///
/// Failures seen on this screen no longer count on the rail; back on Scheduled (from Settings, say), the actions'
/// availability is read again.
///
protected override void OnActivated()
{
if (IsScheduled) _ = Schedules.RefreshActionsAsync();
if (_unseenFailures.Count == 0) return;
_unseenFailures.Clear();
UpdateShell();
}
///
/// A change the engine reported (these are live, never pages read again): a failure counts on the rail until this
/// screen is opened, and a long operation that ends is announced at the end of the flush ().
///
private void Follow(JobState? before, Job job)
{
if (job.State != JobState.Failed) _unseenFailures.Remove(job.Id);
else if (before != JobState.Failed && !IsSelected) _unseenFailures.Add(job.Id);
var notice = JobNotices.For(before, job);
// A flush can take the end before the editor that follows the render has seen it: the editor says it, with its output.
if (notice == JobNotice.Done && job.Kind == JobKind.Render
&& (Shell.Sequence.Editor?.FollowsRender(job.Id) == true || !ClaimRenderToast(job.Id))) return;
_endings.Add(notice, job);
}
///
/// Takes the toast of a finished render, which is said once (UI thread): true for the first caller only, which then
/// raises it. The editor of the render's sequence takes it when it sees the render end, and says it with the output
/// file even when the sequence cannot be read again or the editor closed meanwhile; a render the editor did not
/// follow is said here.
///
internal bool ClaimRenderToast(Guid jobId) => _renderToasts.Add(jobId);
///
/// The toast of a job that ended, with one action (BRIEF §12.1, §0.2 rule 6). Several endings at once (a batch
/// finished, or failed together) say how many and lead to this screen. Clicking the Windows notification of a
/// toast opens what it names; a retry waits until the user has seen why the job failed. Conversions that replaced photos
/// offer Undo instead (), which never runs from the Windows notification.
///
private Toast ToastFor(JobEnding ending)
{
var job = ending.Jobs[0];
var failed = ending.Notice == JobNotice.Failed;
if (!failed && ending.Jobs.All(ConvertUndo.Replaces)) return ConvertUndo.Toast(Shell, ending.Jobs);
if (ending.Jobs.Count > 1)
{
return new Toast
{
Title = Loc.Plural(failed ? "Shell.Job.FailedPlural" : "Shell.Job.DonePlural", ending.Jobs.Count),
Message = ending.Jobs.All(j => j.Kind == job.Kind) ? JobText.Kind(job.Kind) : null,
ActionText = Loc.L("Shell.Nav.Jobs"),
ActionToolTip = Loc.L("Tooltips.Nav.Jobs"),
ActionCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Jobs)),
IsError = failed,
RunsFromNotification = true,
};
}
if (!failed)
{
return new Toast
{
Title = Loc.L("Shell.Job.Done"),
Message = JobText.Name(job),
ActionText = Loc.L("Jobs.Action.Open"),
ActionToolTip = Loc.L("Tooltips.Jobs.Open"),
ActionCommand = new AsyncRelayCommand(() => OpenTargetAsync(job)),
RunsFromNotification = true,
};
}
return job.Kind == JobKind.Import
// The Import screen resumes an import with its plan and card; it holds the retry.
? new Toast
{
Title = Loc.L("Shell.Job.Failed"),
Message = JobText.Name(job),
ActionText = Loc.L("Shell.Nav.Import"),
ActionToolTip = Loc.L("Tooltips.Nav.Import"),
ActionCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Import)),
IsError = true,
RunsFromNotification = true,
}
: new Toast
{
Title = Loc.L("Shell.Job.Failed"),
Message = JobText.Name(job),
ActionText = Loc.L("Jobs.Action.Retry"),
ActionToolTip = Loc.L("Tooltips.Jobs.Retry"),
ActionCommand = new AsyncRelayCommand(() => _queue?.ResumeAsync(job.Id) ?? Task.CompletedTask),
IsError = true,
};
}
/// A job changed state (any thread; tests feed it too): buffered until the next flush.
internal void OnJobChanged(Job job)
{
_buffer.Post(job);
_throttle?.Signal();
}
private void OnProgress(JobProgressInfo progress)
{
_buffer.Post(progress);
_throttle?.Signal();
}
private void SelectFilter(JobFilter filter) => Filter = filter;
///
/// 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.
///
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);
}
/// Brings to the model's order with moves (rows keep their expanded log).
private void SyncRows()
{
_model.PriorityQueue = Shell.Services.PriorityQueue;
var ordered = _model.Ordered(_filter, _searchText, ClearedAt);
var wanted = new HashSet(ordered.Select(e => e.Id));
for (var i = Rows.Count - 1; i >= 0; i--)
{
if (!wanted.Contains(Rows[i].Id)) Rows.RemoveAt(i);
}
for (var i = 0; i < ordered.Count; i++)
{
var entry = ordered[i];
var position = entry.State == JobState.Queued ? _model.QueuePosition(entry.Id) : 0;
if (!_rows.TryGetValue(entry.Id, out var row))
{
row = new JobRowViewModel(entry, position, _actions);
_rows[entry.Id] = row;
}
else
{
row.Update(entry, position);
}
if (i < Rows.Count && ReferenceEquals(Rows[i], row)) continue;
var existing = Rows.IndexOf(row);
if (existing >= 0) Rows.Move(existing, i);
else Rows.Insert(i, row);
}
foreach (var chip in Chips) chip.Count = _model.CountOf(chip.Filter, ClearedAt);
RaiseState();
}
private void UpdateShell()
{
if (_model.Current is { } current)
Shell.SetJob(JobText.Bar(current), current.Fraction ?? 0, indeterminate: current.Fraction is null, name: JobText.Name(current.Job));
else
Shell.SetJob(null, 0);
// The status strip and the Running chip count the same jobs: running or paused (Jobs.html). The rail badge adds the
// failures not seen here yet, which also turn the taskbar button red while no job runs.
var active = _model.CountOf(JobFilter.Running);
Shell.SetJobCount(active, _model.QueuedCount);
Shell.SetUnseenFailures(_unseenFailures.Count);
Badge = active + _unseenFailures.Count;
OnPropertyChanged(nameof(ParallelismText));
OnPropertyChanged(nameof(HasEngine));
OnPropertyChanged(nameof(IsPriorityQueueOn));
CommandManager.InvalidateRequerySuggested();
}
private void RaiseState()
{
OnPropertyChanged(nameof(IsEmpty));
OnPropertyChanged(nameof(HasRows));
}
private async Task PauseCurrentAsync()
{
if (_model.Current is { } current && _queue is not null) await _queue.PauseAsync(current.Id);
}
private async Task PauseAllAsync()
{
if (_queue is null) return;
foreach (var entry in _model.Ordered(JobFilter.Running).Where(e => e.State == JobState.Running).ToList()) await _queue.PauseAsync(entry.Id);
}
private void ClearDone()
{
Shell.Services.Settings.JobsClearedAt = DateTimeOffset.UtcNow;
Shell.Services.SaveSettings();
SyncRows();
}
///
/// Opens what a job worked on inside Chronos: its sequence in the editor; several sequences (a deep analysis of a
/// Library selection) in the Library, every one of them selected; else the Archive screen. A job over more sequences
/// than a Library page holds (a maintenance run over a whole archive) opens the Library as it is: looking each one
/// up, then reading page after page to select them all, would hold the screen.
///
internal async Task OpenTargetAsync(Job job)
{
var db = Shell.Services.Database;
if (db is null || job.TargetIds.Count == 0) return;
var targets = job.TargetIds.Distinct().ToList();
if (targets.Count > LibraryPager.DefaultPageSize)
{
Shell.Navigate(SectionKey.Library);
return;
}
// Each one is looked up: an id no longer in the index would have the Library read every page in search of it.
var sequences = new List(targets.Count);
foreach (var id in targets)
{
if (await db.Sequences.GetAsync(id) is { } sequence) sequences.Add(sequence.Id);
}
switch (sequences.Count)
{
case 0:
Shell.Navigate(SectionKey.Archive);
break;
case 1:
Shell.OpenSequence(sequences[0]);
break;
default:
Shell.Navigate(SectionKey.Library);
await Shell.Library.ShowSelectedAsync(sequences);
break;
}
}
/// Shows the folder of what a job worked on in Explorer.
internal async Task RevealTargetAsync(Job job)
{
var db = Shell.Services.Database;
if (db is null || job.TargetIds.Count == 0) return;
var id = job.TargetIds[0];
if (await db.Sequences.GetAsync(id) is { } sequence && await db.Archives.GetAsync(sequence.ArchiveId) is { } owner)
ShellActions.Reveal(Path.Combine(owner.RootPath, sequence.Folder.Replace('/', Path.DirectorySeparatorChar)));
else if (await db.Archives.GetAsync(id) is { } archive)
ShellActions.Reveal(archive.RootPath);
}
}
/// Row actions per job state (Jobs.html) and their commands.
internal sealed class JobActions(JobsViewModel owner)
{
public string WorkerId => owner.Queue?.WorkerId ?? Environment.MachineName;
public IReadOnlyList For(JobEntry entry)
{
var job = entry.Job;
var row = JobText.Name(job);
return entry.State switch
{
JobState.Running =>
[
OnQueue("Jobs.Action.Pause", "Tooltips.Jobs.Pause", row, q => q.PauseAsync(job.Id)),
OnQueue("Jobs.Action.Cancel", "Tooltips.Jobs.Cancel", row, q => q.CancelAsync(job.Id)),
],
JobState.Paused =>
[
OnQueue("Jobs.Action.Resume", "Tooltips.Jobs.Resume", row, q => q.ResumeAsync(job.Id)),
OnQueue("Jobs.Action.Cancel", "Tooltips.Jobs.Cancel", row, q => q.CancelAsync(job.Id)),
],
JobState.Queued when job.Priority < JobPriority.User =>
[
OnQueue("Jobs.Action.MoveUp", "Tooltips.Jobs.MoveUp", row, q => q.RaisePriorityAsync(job.Id)),
OnQueue("Jobs.Action.Remove", "Tooltips.Jobs.Remove", row, q => q.CancelAsync(job.Id)),
],
JobState.Queued =>
[
OnQueue("Jobs.Action.Pause", "Tooltips.Jobs.PauseQueued", row, q => q.PauseAsync(job.Id)),
OnQueue("Jobs.Action.Remove", "Tooltips.Jobs.Remove", row, q => q.CancelAsync(job.Id)),
],
JobState.Failed =>
[
OnQueue("Jobs.Action.Retry", "Tooltips.Jobs.Retry", row, q => q.ResumeAsync(job.Id)),
Action("Jobs.Action.Show", "Tooltips.Jobs.Show", row, () => owner.OpenTargetAsync(job)),
],
JobState.Cancelled =>
[
OnQueue("Jobs.Action.Retry", "Tooltips.Jobs.Retry", row, q => q.ResumeAsync(job.Id)),
],
_ =>
[
Action("Jobs.Action.Open", "Tooltips.Jobs.Open", row, () => owner.OpenTargetAsync(job)),
Action("Jobs.Action.Folder", "Tooltips.Jobs.Folder", row, () => owner.RevealTargetAsync(job)),
],
};
}
/// Reads the stored log tail of a row (persisted with each checkpoint).
public async Task LoadLogAsync(JobRowViewModel row)
{
if (owner.Queue is not { } queue) return;
try
{
if (await queue.GetAsync(row.Id) is { } job) row.SetLog(job.LogTail);
}
catch (DatabaseException ex)
{
Log.Warning("jobs", "Job log unavailable", ex);
}
}
/// A row button named with its row for screen readers ("Pause: Render · Harbour sunset").
private static JobAction Action(string textKey, string toolTipKey, string row, Func run)
{
var text = Loc.L(textKey);
return new JobAction(text, Loc.L(toolTipKey), Loc.L("Jobs.ActionFor", text, row), new AsyncRelayCommand(run));
}
private JobAction OnQueue(string textKey, string toolTipKey, string row, Func run) =>
Action(textKey, toolTipKey, row, async () =>
{
if (owner.Queue is { } queue) await run(queue);
});
}