using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Input;
using Titano.App.Infrastructure;
using Titano.App.Jobs;
using Titano.App.Settings;
using Titano.App.Shell;
using Titano.Core.Diagnostics;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data;
using Titano.Data.Jobs;
using Titano.Ui.Mvvm;
namespace Titano.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): queue and history with live progress from the engine (batched to about 10
/// updates a second), filters, queue order, an expandable log tail per job, and the row actions. Also feeds the
/// shell's job bar, the status strip and the rail badge.
///
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 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;
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));
}
public ShellViewModel Shell { get; }
/// 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();
}
}
/// "Workers 1 / 4": jobs this PC's workers run out of its workers.
public string WorkersText => Loc.L("Jobs.Workers", _queue is { } queue ? _model.RunningOn(queue.WorkerId) : 0, _queue?.Workers ?? 0);
/// The engine of this PC runs workers (it has none before it starts).
public bool HasWorkers => _queue is { Workers: > 0 };
/// "History keeps 90 days".
public string HistoryText => Loc.Plural("Jobs.History", (long)new JobEngineOptions().HistoryRetention.TotalDays);
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.
public void Attach()
{
_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();
base.Dispose();
}
/// 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) _model.Apply(job);
foreach (var p in progress) _model.Apply(p);
SyncRows();
UpdateShell();
}
private 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;
/// Brings to the model's order with moves (rows keep their expanded log).
private void SyncRows()
{
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);
else
Shell.SetJob(null, 0);
// The rail badge, the status strip and the Running chip count the same jobs: running or paused (Jobs.html).
var active = _model.CountOf(JobFilter.Running);
Shell.SetJobCount(active, _model.QueuedCount);
Badge = active;
OnPropertyChanged(nameof(WorkersText));
OnPropertyChanged(nameof(HasWorkers));
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 Titano: its sequence in the editor, or the Archive screen.
internal async Task OpenTargetAsync(Job job)
{
var db = Shell.Services.Database;
if (db is null || job.TargetIds.Count == 0) return;
if (await db.Sequences.GetAsync(job.TargetIds[0]) is { } sequence) Shell.OpenSequence(sequence.Id);
else Shell.Navigate(SectionKey.Archive);
}
/// 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);
});
}