refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s
The owner renamed the product and moved the repository to the self-hosted Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control, and asked for Actions and a first automatic release with the server package and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md). - Chronos everywhere: a byte-exact rename of contents and paths, then a per-language review of the forms the old name's ending had dictated. - Gitea instead of GitHub: the update check, licence, issue and support links read ChronosReleasesUrl; the update check takes the highest stable version, offers a pre-release build its final release and reports a repository it cannot see as a failed check. EULA, security policy and Gitea issue forms live at the repository root. - Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release, nightly image and performance gates in the .NET SDK container with git checkout and the system SQLite. The release cross-compiles the Windows programs, checks their icon, version and DPI manifest, packs installers and zips, publishes the Gitea release and pushes the server image (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows runner (WINDOWS_RUNNER). - New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the docker-exec script, which Gitea's service containers do not allow; the throw-away server runs without durability) and pe-check. - Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR, 3 on the shared runner; the weekly performance gates keep theirs). BREAKING CHANGE: programs, settings, data folders, file types, environment variables and the Docker image use the new name; nothing is migrated from Titano, which never had a release. 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 #6.
This commit is contained in:
1 parent
c99842cc86
commit
f2b58522b9
1801 files changed
+11804
-10676
No files matched your search
@@ -0,0 +1,155 @@
|
||||
using Chronos.Core.Analysis;
|
||||
using Chronos.Core.Analysis.Deep;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Ui.Controls;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>A finding of the analyses on the Analysis step: what it says, the frame it starts at and the step that deals with it.</summary>
|
||||
public sealed class AnalysisFinding
|
||||
{
|
||||
private readonly EditorViewModel _editor;
|
||||
|
||||
internal AnalysisFinding(EditorViewModel editor, FindingItem item, string? stepKey)
|
||||
{
|
||||
_editor = editor;
|
||||
Kind = item.Kind;
|
||||
Text = item.Text;
|
||||
Frame = item.Frame;
|
||||
StepKey = stepKey;
|
||||
}
|
||||
|
||||
public StatusKind Kind { get; }
|
||||
|
||||
public string Text { get; }
|
||||
|
||||
/// <summary>The first frame it concerns; null for a finding about the whole sequence.</summary>
|
||||
public int? Frame { get; }
|
||||
|
||||
/// <summary>The <see cref="EditPath"/> step that deals with it; null when no step does.</summary>
|
||||
public string? StepKey { get; }
|
||||
|
||||
/// <summary>The step that deals with it (looked up when shown: the steps exist once the editor does).</summary>
|
||||
public EditorTab? Step => StepKey is null ? null : _editor.Tabs.FirstOrDefault(t => t.Key == StepKey);
|
||||
|
||||
/// <summary>"Open Exposure, the step that deals with this · Alt+3".</summary>
|
||||
public string? GoToToolTip => Step is { } step ? Loc.L("Tooltips.Editor.Analysis.GoTo", step.Header, step.Number) : null;
|
||||
|
||||
/// <summary>The sentence (what UI Automation reads for a row the list has not realised).</summary>
|
||||
public override string ToString() => Text;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The first step of the Edit path (owner review 1, R7): every finding of the analyses with the step that deals with it,
|
||||
/// what the deep analysis measured (light, flicker, exposure steps received, shake, flagged frames) and where each later
|
||||
/// step stands. Analyse runs from here as from the header.
|
||||
/// </summary>
|
||||
public sealed class AnalysisTab : EditorTab
|
||||
{
|
||||
private IReadOnlyList<AnalysisFinding> _findings = [];
|
||||
private AnalysisFinding? _selected;
|
||||
|
||||
public AnalysisTab(EditorViewModel editor)
|
||||
: base(editor, EditPath.Analysis, null)
|
||||
{
|
||||
Rows =
|
||||
[
|
||||
new InfoRow("Editor.Analysis.Light", "Tooltips.Editor.Analysis.Light", () => Measured(d => LightText(d.Sky.Light))),
|
||||
// The finding's and the deflicker reason's measure (the deviation from the smooth course), rounded as they are.
|
||||
new InfoRow("Editor.Analysis.Flicker", "Tooltips.Editor.Analysis.Flicker",
|
||||
() => Measured(d => Loc.L("Editor.Value.Ev", double.Round(d.Flicker.AmplitudeEv, 3, MidpointRounding.AwayFromZero).ToString("0.###", Loc.Culture)))),
|
||||
new InfoRow("Editor.Analysis.Steps", "Tooltips.Editor.Analysis.Steps",
|
||||
() => Measured(d => Loc.L("Editor.Analysis.StepsValue", d.Exposure.ReceivedSteps, d.Exposure.MetadataSteps))),
|
||||
new InfoRow("Editor.Analysis.Shake", "Tooltips.Editor.Analysis.Shake", ShakeValue),
|
||||
new InfoRow("Editor.Analysis.Flagged", "Tooltips.Editor.Analysis.Flagged",
|
||||
() => Measured(d => Loc.Plural("Editor.Value.Frames", d.Issues.Excludable().Length))),
|
||||
];
|
||||
Load();
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>The findings, the most severe first.</summary>
|
||||
public IReadOnlyList<AnalysisFinding> Findings
|
||||
{
|
||||
get => _findings;
|
||||
private set
|
||||
{
|
||||
if (Set(ref _findings, value)) OnPropertyChanged(nameof(HasFindings));
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasFindings => _findings.Count > 0;
|
||||
|
||||
/// <summary>The finding chosen in the list: the preview seeks its first frame.</summary>
|
||||
public AnalysisFinding? SelectedFinding
|
||||
{
|
||||
get => _selected;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _selected, value) || value?.Frame is not { } frame) return;
|
||||
Editor.CurrentIndex = frame;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Instead of an empty list: the analysis running, not run yet, or nothing found.</summary>
|
||||
public string EmptyText => StateText.Length > 0 && Status == StepStatus.Running ? StateText
|
||||
: Editor.Session.Content.Deep is null ? Loc.L("Editor.Chart.NotAnalysed")
|
||||
: Loc.L("Editor.Frames.NoWarnings");
|
||||
|
||||
/// <summary>The glyph beside the step's state in its panel.</summary>
|
||||
public StatusKind StateKind => Status switch
|
||||
{
|
||||
StepStatus.Done => StatusKind.Analysed,
|
||||
StepStatus.Running => StatusKind.Analysing,
|
||||
StepStatus.Attention => StatusKind.Warning,
|
||||
_ => StatusKind.NotAnalysed,
|
||||
};
|
||||
|
||||
/// <summary>The path's other steps, each with where it stands.</summary>
|
||||
public IEnumerable<EditorTab> PathSteps => Editor.Tabs.Where(t => !ReferenceEquals(t, this));
|
||||
|
||||
public override bool PrefersTallMeasure => true;
|
||||
|
||||
public override void OnContentChanged()
|
||||
{
|
||||
Load();
|
||||
base.OnContentChanged();
|
||||
}
|
||||
|
||||
/// <summary>The step's state changed: the panel's glyph and the empty list's sentence follow.</summary>
|
||||
internal void OnStepChanged()
|
||||
{
|
||||
OnPropertyChanged(nameof(StateKind));
|
||||
OnPropertyChanged(nameof(EmptyText));
|
||||
}
|
||||
|
||||
private void Load()
|
||||
{
|
||||
Findings = [.. Editor.Session.Advice.Findings.OrderByDescending(f => f.Severity)
|
||||
.Select(f => new AnalysisFinding(Editor, FramesTab.ToItem(f), EditPath.StepOf(f.Key)))];
|
||||
_selected = null;
|
||||
OnPropertyChanged(nameof(SelectedFinding));
|
||||
OnPropertyChanged(nameof(EmptyText));
|
||||
}
|
||||
|
||||
/// <summary>The camera's wobble, or n/a when too few frame pairs could be measured (the Motion step asks for it then).</summary>
|
||||
private (string? Value, string? NotApplicableReason) ShakeValue()
|
||||
{
|
||||
if (Editor.Session.Content.Deep is { Shake: { MeasuredFraction: < ShakeSummary.MinMeasuredFraction } shake })
|
||||
return (null, Loc.L("Advisor.Missing.Shake", (100 * shake.MeasuredFraction).ToString("0", Loc.Culture)));
|
||||
return Measured(d => Loc.L("Editor.Value.Pixels", d.Shake.RmsPx.ToString("0.#", Loc.Culture)));
|
||||
}
|
||||
|
||||
/// <summary>A value of the deep analysis, or n/a saying it needs the analysis.</summary>
|
||||
private (string? Value, string? NotApplicableReason) Measured(Func<DeepAnalysisReport, string> value) =>
|
||||
Editor.Session.Content.Deep is { } deep ? (value(deep), null) : (null, Loc.L("Tooltips.Editor.NotApplicable.NeedsAnalysis"));
|
||||
|
||||
private static string LightText(DayNight light) => Loc.L(light switch
|
||||
{
|
||||
DayNight.Day => "Editor.Analysis.Light.Day",
|
||||
DayNight.Night => "Editor.Analysis.Light.Night",
|
||||
DayNight.DayToNight => "Editor.Analysis.Light.DayToNight",
|
||||
DayNight.NightToDay => "Editor.Analysis.Light.NightToDay",
|
||||
_ => "Editor.Analysis.Light.Unknown",
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Advice;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Mathematics;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Ui.Mvvm;
|
||||
using Chronos.Ui.Visuals;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// Camera (BRIEF §12.3): the free crop of the frame (margins), the output aspect and its placement inside the crop, and
|
||||
/// virtual-camera keyframes edited as a zoom curve over the sequence (X = frame, Y = zoom) with the selected keyframe's
|
||||
/// framing below.
|
||||
/// </summary>
|
||||
public sealed class CameraTab : EditorTab
|
||||
{
|
||||
/// <summary>Zoom at the top of the curve editor.</summary>
|
||||
public const double MaxZoom = 4;
|
||||
|
||||
private int _selectedKey = -1;
|
||||
|
||||
public CameraTab(EditorViewModel editor)
|
||||
: base(editor, "Camera", AdvisorSection.Camera)
|
||||
{
|
||||
var s = editor.Session;
|
||||
Rows =
|
||||
[
|
||||
CropRow(s, CropSide.Left, "Editor.Camera.CropLeft"),
|
||||
CropRow(s, CropSide.Right, "Editor.Camera.CropRight"),
|
||||
CropRow(s, CropSide.Top, "Editor.Camera.CropTop"),
|
||||
CropRow(s, CropSide.Bottom, "Editor.Camera.CropBottom"),
|
||||
new AutoChoiceRow<string>(s, EditorSettings.Aspect, "Editor.Camera.Aspect", "Tooltips.Editor.Camera.Aspect",
|
||||
[
|
||||
new Choice("source", "Editor.Aspect.Source"), new Choice("16:9", "Editor.Aspect.Ratio", "16:9"), new Choice("21:9", "Editor.Aspect.Ratio", "21:9"),
|
||||
new Choice("4:3", "Editor.Aspect.Ratio", "4:3"), new Choice("3:2", "Editor.Aspect.Ratio", "3:2"), new Choice("1:1", "Editor.Aspect.Ratio", "1:1"),
|
||||
new Choice("9:16", "Editor.Aspect.Ratio", "9:16"), new Choice("4:5", "Editor.Aspect.Ratio", "4:5"),
|
||||
]),
|
||||
new NumberRow(s, "Editor.Camera.OffsetX", "Tooltips.Editor.Camera.OffsetX", -1, 1, 0.05, p => p.Camera.OffsetX,
|
||||
(p, v) => p with { Camera = p.Camera with { OffsetX = v } }, EditorText.Placement),
|
||||
new NumberRow(s, "Editor.Camera.OffsetY", "Tooltips.Editor.Camera.OffsetY", -1, 1, 0.05, p => p.Camera.OffsetY,
|
||||
(p, v) => p with { Camera = p.Camera with { OffsetY = v } }, EditorText.Placement),
|
||||
];
|
||||
AddKeyCommand = new RelayCommand(AddKey, () => !Editor.IsLocked && Keys.All(k => k.Frame != Editor.CurrentIndex));
|
||||
RemoveKeyCommand = new RelayCommand(RemoveKey, () => !Editor.IsLocked && SelectedKey >= 0);
|
||||
CommitCurveCommand = new RelayCommand(CommitCurve);
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>Keyframes as curve points: X = frame / (count − 1), Y = (zoom − 1) / (<see cref="MaxZoom"/> − 1). Edited in place by the curve editor.</summary>
|
||||
public ObservableCollection<Point> KeyPoints { get; } = [];
|
||||
|
||||
public int SelectedKey
|
||||
{
|
||||
get => _selectedKey;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _selectedKey, value)) return;
|
||||
OnSelectedKeyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasSelectedKey => SelectedKey >= 0 && SelectedKey < Keys.Count;
|
||||
|
||||
/// <summary>Framing of the selected keyframe: centre (0–1) and zoom.</summary>
|
||||
public double SelectedCenterX
|
||||
{
|
||||
get => HasSelectedKey ? Keys[SelectedKey].CenterX : 0.5;
|
||||
set => EditSelected(k => k with { CenterX = double.Clamp(value, 0, 1) });
|
||||
}
|
||||
|
||||
public double SelectedCenterY
|
||||
{
|
||||
get => HasSelectedKey ? Keys[SelectedKey].CenterY : 0.5;
|
||||
set => EditSelected(k => k with { CenterY = double.Clamp(value, 0, 1) });
|
||||
}
|
||||
|
||||
public double SelectedZoom
|
||||
{
|
||||
get => HasSelectedKey ? Keys[SelectedKey].Zoom : 1;
|
||||
set => EditSelected(k => k with { Zoom = double.Clamp(value, 1, MaxZoom) });
|
||||
}
|
||||
|
||||
public string SelectedZoomText => Loc.L("Editor.Value.Zoom", SelectedZoom.ToString("0.00", Loc.Culture));
|
||||
|
||||
/// <summary>"Keyframe 2 of 3 · frame 0413".</summary>
|
||||
public string KeyText => HasSelectedKey
|
||||
? Loc.L("Editor.Camera.KeyOf", SelectedKey + 1, Keys.Count, (Keys[SelectedKey].Frame + 1).ToString("D4", Loc.Culture))
|
||||
: Loc.Plural("Editor.Camera.Keys", Keys.Count);
|
||||
|
||||
public double Playhead => Editor.FrameCount > 1 ? (double)Editor.CurrentIndex / (Editor.FrameCount - 1) : double.NaN;
|
||||
|
||||
public Func<double, string> XFormatter => x => EditorText.Position((int)double.Round(x * (Editor.FrameCount - 1)), Editor.FrameCount);
|
||||
|
||||
public Func<double, string> YFormatter { get; } = y => Loc.L("Editor.Value.Zoom", (1 + y * (MaxZoom - 1)).ToString("0.00", Loc.Culture));
|
||||
|
||||
public ICommand AddKeyCommand { get; }
|
||||
|
||||
public ICommand RemoveKeyCommand { get; }
|
||||
|
||||
/// <summary>What Add keyframe does, or why it cannot run now.</summary>
|
||||
public string AddKeyToolTip => Editor.LockedToolTip
|
||||
?? Loc.L(Keys.Any(k => k.Frame == Editor.CurrentIndex) ? "Tooltips.Editor.Camera.KeyExists" : "Tooltips.Editor.Camera.AddKey");
|
||||
|
||||
/// <summary>How to edit the keyframe curve, or why it waits.</summary>
|
||||
public string CurveToolTip => Editor.LockedToolTip ?? Loc.L("Tooltips.Editor.Camera.Curve");
|
||||
|
||||
public string RemoveKeyToolTip => Editor.LockedToolTip ?? Loc.L(HasSelectedKey ? "Tooltips.Editor.Camera.RemoveKey" : "Tooltips.Editor.Camera.NoKey");
|
||||
|
||||
/// <summary>Run by the curve editor after each finished edit.</summary>
|
||||
public ICommand CommitCurveCommand { get; }
|
||||
|
||||
/// <summary>Keyframes in frame order (the order of <see cref="KeyPoints"/>).</summary>
|
||||
private List<CameraKey> Keys => [.. Editor.Session.Project.Camera.Keyframes.OrderBy(k => k.Frame)];
|
||||
|
||||
public override void Refresh()
|
||||
{
|
||||
base.Refresh();
|
||||
var points = Keys.Select(ToPoint).ToList();
|
||||
if (!points.SequenceEqual(KeyPoints))
|
||||
{
|
||||
KeyPoints.Clear();
|
||||
foreach (var p in points) KeyPoints.Add(p);
|
||||
}
|
||||
if (SelectedKey >= Keys.Count) SelectedKey = Keys.Count - 1;
|
||||
OnSelectedKeyChanged();
|
||||
}
|
||||
|
||||
/// <summary>The curve editor finished an edit (add, move, delete): the points become the keyframes, keeping each one's framing.</summary>
|
||||
public void CommitCurve()
|
||||
{
|
||||
var old = Keys;
|
||||
var keys = new List<CameraKey>();
|
||||
foreach (var point in KeyPoints.OrderBy(p => p.X))
|
||||
{
|
||||
var frame = (int)double.Round(point.X * double.Max(1, Editor.FrameCount - 1));
|
||||
var zoom = 1 + double.Clamp(point.Y, 0, 1) * (MaxZoom - 1);
|
||||
var nearest = old.MinBy(k => int.Abs(k.Frame - frame));
|
||||
keys.Add(nearest is null ? new CameraKey(frame, 0.5, 0.5, zoom, 0) : nearest with { Frame = frame, Zoom = zoom });
|
||||
}
|
||||
Editor.Session.Edit(p => p with { Camera = p.Camera with { Keyframes = [.. keys.DistinctBy(k => k.Frame)] } });
|
||||
}
|
||||
|
||||
public override void OnCurrentFrameChanged()
|
||||
{
|
||||
OnPropertyChanged(nameof(Playhead));
|
||||
OnPropertyChanged(nameof(AddKeyToolTip));
|
||||
}
|
||||
|
||||
public override void OnBusyChanged()
|
||||
{
|
||||
base.OnBusyChanged();
|
||||
OnPropertyChanged(nameof(AddKeyToolTip));
|
||||
OnPropertyChanged(nameof(RemoveKeyToolTip));
|
||||
OnPropertyChanged(nameof(CurveToolTip));
|
||||
}
|
||||
|
||||
/// <summary>A margin of the free crop (<see cref="CropMargins"/>); all zero = the whole frame.</summary>
|
||||
private static NumberRow CropRow(EditorSession session, CropSide side, string headerKey) => new(session, headerKey, "Tooltips.Editor.Camera.Crop", 0,
|
||||
CropMargins.MaxMargin, 0.01, p => CropMargins.Of(p.Camera.Crop)[(int)side],
|
||||
(p, v) => p with { Camera = p.Camera with { Crop = CropMargins.With(p.Camera.Crop, side, v) } }, v => Formatting.Percent(v));
|
||||
|
||||
private Point ToPoint(CameraKey key) => new(Editor.FrameCount > 1 ? (double)key.Frame / (Editor.FrameCount - 1) : 0, (key.Zoom - 1) / (MaxZoom - 1));
|
||||
|
||||
private void AddKey()
|
||||
{
|
||||
var frame = Editor.CurrentIndex;
|
||||
var key = new CameraKey(frame, 0.5, 0.5, 1, 0);
|
||||
Editor.Session.Edit(p => p with { Camera = p.Camera with { Keyframes = [.. p.Camera.Keyframes.Append(key).OrderBy(k => k.Frame)] } });
|
||||
SelectedKey = Keys.FindIndex(k => k.Frame == frame);
|
||||
}
|
||||
|
||||
private void RemoveKey()
|
||||
{
|
||||
if (!HasSelectedKey) return;
|
||||
var frame = Keys[SelectedKey].Frame;
|
||||
Editor.Session.Edit(p => p with { Camera = p.Camera with { Keyframes = [.. p.Camera.Keyframes.Where(k => k.Frame != frame)] } });
|
||||
}
|
||||
|
||||
private void EditSelected(Func<CameraKey, CameraKey> change)
|
||||
{
|
||||
if (!HasSelectedKey) return;
|
||||
var index = SelectedKey;
|
||||
Editor.Session.Edit(p =>
|
||||
{
|
||||
var keys = p.Camera.Keyframes.OrderBy(k => k.Frame).ToList();
|
||||
keys[index] = change(keys[index]);
|
||||
return p with { Camera = p.Camera with { Keyframes = keys } };
|
||||
}, "Camera.Key");
|
||||
}
|
||||
|
||||
private void OnSelectedKeyChanged()
|
||||
{
|
||||
OnPropertyChanged(nameof(HasSelectedKey));
|
||||
OnPropertyChanged(nameof(RemoveKeyToolTip));
|
||||
OnPropertyChanged(nameof(SelectedCenterX));
|
||||
OnPropertyChanged(nameof(SelectedCenterY));
|
||||
OnPropertyChanged(nameof(SelectedZoom));
|
||||
OnPropertyChanged(nameof(SelectedZoomText));
|
||||
OnPropertyChanged(nameof(KeyText));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Time (BRIEF §12.3): timing mode, playback rate, fit-to duration, the plan chart (video frames each photo gets, cuts
|
||||
/// marked, the plan in numbers) and the time-remap curve (output time → source position, Fritsch–Carlson as the render
|
||||
/// evaluates it).
|
||||
/// </summary>
|
||||
public sealed class TimeTab : EditorTab
|
||||
{
|
||||
private Func<double, double>? _evaluator;
|
||||
private string? _planText;
|
||||
private IReadOnlyList<ChartSeries> _planSeries = [];
|
||||
private IReadOnlyList<TimelineMarker> _planMarkers = [];
|
||||
|
||||
public TimeTab(EditorViewModel editor)
|
||||
: base(editor, "Time", AdvisorSection.Timing)
|
||||
{
|
||||
var s = editor.Session;
|
||||
Rows =
|
||||
[
|
||||
new AutoChoiceRow<TimingMode>(s, EditorSettings.TimingMode, "Editor.Time.Mode", "Tooltips.Editor.Time.Mode",
|
||||
[
|
||||
new Choice(TimingMode.Constant, "Editor.Timing.Constant"), new Choice(TimingMode.Adaptive, "Editor.Timing.Adaptive"),
|
||||
new Choice(TimingMode.Interpolated, "Editor.Timing.Interpolated"), new Choice(TimingMode.Remapped, "Editor.Timing.Remapped"),
|
||||
]),
|
||||
new AutoChoiceRow<string>(s, EditorSettings.FrameRate, "Editor.Time.Rate", "Tooltips.Editor.Time.Rate",
|
||||
[.. ExportPresets.FrameRates.Select(r => new Choice(FrameRateText.Format(r), "Editor.Value.Fps", EditorText.FrameRate(r)))]),
|
||||
new NumberRow(s, "Editor.Time.Fit", "Tooltips.Editor.Time.Fit", 0, 600, 5, p => p.Timing.FitToSeconds ?? 0,
|
||||
(p, v) => p with { Timing = p.Timing with { FitToSeconds = v > 0 ? v : null } },
|
||||
v => v > 0 ? Formatting.Duration(TimeSpan.FromSeconds(v)) : Loc.L("Editor.Value.Off")),
|
||||
];
|
||||
CommitCurveCommand = new RelayCommand(CommitCurve);
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>Remap control points (output fraction → source fraction), edited in place by the curve editor.</summary>
|
||||
public ObservableCollection<Point> RemapPoints { get; } = [];
|
||||
|
||||
/// <summary>The monotone spline through <see cref="RemapPoints"/>.</summary>
|
||||
public Func<double, double>? Evaluator { get => _evaluator; private set => Set(ref _evaluator, value); }
|
||||
|
||||
/// <summary>Run by the curve editor after each finished edit.</summary>
|
||||
public ICommand CommitCurveCommand { get; }
|
||||
|
||||
/// <summary>How to edit the remap curve, or why it waits.</summary>
|
||||
public string CurveToolTip => Editor.LockedToolTip ?? Loc.L("Tooltips.Editor.Time.Curve");
|
||||
|
||||
/// <summary>"3,600 frames → 2 min 30 s · 24 fps".</summary>
|
||||
public string? PlanText { get => _planText; private set => Set(ref _planText, value); }
|
||||
|
||||
/// <summary>Video frames each photo is shown for (0 = skipped by a speed-up, gap = excluded), over the sequence.</summary>
|
||||
public IReadOnlyList<ChartSeries> PlanSeries { get => _planSeries; private set => Set(ref _planSeries, value); }
|
||||
|
||||
/// <summary>Cuts of the plan (deliberate pauses, gaps, long exclusion runs).</summary>
|
||||
public IReadOnlyList<TimelineMarker> PlanMarkers { get => _planMarkers; private set => Set(ref _planMarkers, value); }
|
||||
|
||||
public IReadOnlyList<ChartLegendItem> PlanLegend { get; } = [new(Loc.L("Editor.Chart.Shown"), "Brush.Accent")];
|
||||
|
||||
public Func<double, string> PlanFormatter { get; } = v => v.ToString("0.#", Loc.Culture);
|
||||
|
||||
public double Playhead => Editor.FrameCount > 1 ? (double)Editor.CurrentIndex / (Editor.FrameCount - 1) : double.NaN;
|
||||
|
||||
public Func<double, string> XFormatter { get; } = x => Loc.L("Editor.Time.Output", (x * 100).ToString("0", Loc.Culture));
|
||||
|
||||
public Func<double, string> YFormatter { get; } = y => Loc.L("Editor.Time.Source", (y * 100).ToString("0", Loc.Culture));
|
||||
|
||||
public override void Refresh()
|
||||
{
|
||||
base.Refresh();
|
||||
var curve = Editor.Session.Project.Timing.RemapCurve;
|
||||
var points = curve.Select(p => new Point(p.X, p.Y)).ToList();
|
||||
if (!points.SequenceEqual(RemapPoints))
|
||||
{
|
||||
RemapPoints.Clear();
|
||||
foreach (var p in points) RemapPoints.Add(p);
|
||||
}
|
||||
Evaluator = Spline(points);
|
||||
}
|
||||
|
||||
public override void OnPlanChanged()
|
||||
{
|
||||
if (Editor.Plan is not { } plan)
|
||||
{
|
||||
PlanText = null;
|
||||
PlanSeries = [];
|
||||
PlanMarkers = [];
|
||||
return;
|
||||
}
|
||||
var render = plan.Setup.Plan;
|
||||
PlanText = Loc.Plural("Editor.Time.Plan", render.Frames.Count, Formatting.Duration(TimeSpan.FromSeconds(render.DurationSeconds)),
|
||||
EditorText.FrameRate(render.FrameRate));
|
||||
var shown = new double[Editor.FrameCount];
|
||||
Array.Fill(shown, double.NaN);
|
||||
foreach (var index in render.IncludedFrames) shown[index] = 0;
|
||||
foreach (var frame in render.Frames)
|
||||
{
|
||||
var index = int.Clamp((int)double.Round(frame.SourcePosition), 0, shown.Length - 1);
|
||||
shown[index] = (double.IsNaN(shown[index]) ? 0 : shown[index]) + frame.Slots;
|
||||
}
|
||||
PlanSeries = [new ChartSeries(Loc.L("Editor.Chart.Shown"), shown, "Brush.Accent")];
|
||||
PlanMarkers = [.. render.IncludedFrames.Where(render.IsCutBefore).Select(i => new TimelineMarker(i, MarkerKind.Warning, Loc.L("Editor.Marker.Cut")))];
|
||||
}
|
||||
|
||||
/// <summary>The curve editor finished an edit: the points become the remap curve, and the timing mode follows it.</summary>
|
||||
public void CommitCurve()
|
||||
{
|
||||
var curve = RemapPoints.OrderBy(p => p.X).Select(p => new CurvePoint(double.Clamp(p.X, 0, 1), double.Clamp(p.Y, 0, 1))).ToList();
|
||||
Editor.Session.Edit(p => p with
|
||||
{
|
||||
Timing = p.Timing with
|
||||
{
|
||||
RemapCurve = curve,
|
||||
Mode = EditorSettings.TimingMode.Effective(p, null) == TimingMode.Remapped ? p.Timing.Mode : p.Timing.Mode.WithManual(TimingMode.Remapped),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
public override void OnCurrentFrameChanged() => OnPropertyChanged(nameof(Playhead));
|
||||
|
||||
public override void OnBusyChanged()
|
||||
{
|
||||
base.OnBusyChanged();
|
||||
OnPropertyChanged(nameof(CurveToolTip));
|
||||
}
|
||||
|
||||
private static Func<double, double>? Spline(IReadOnlyList<Point> points)
|
||||
{
|
||||
if (points.Count < 2) return null;
|
||||
var ordered = points.OrderBy(p => p.X).DistinctBy(p => p.X).ToList();
|
||||
if (ordered.Count < 2) return null;
|
||||
var spline = new MonotoneSpline([.. ordered.Select(p => p.X)], [.. ordered.Select(p => p.Y)]);
|
||||
return x => double.Clamp(spline.Evaluate(x), 0, 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System.Globalization;
|
||||
using System.Windows.Data;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>Columns of the Export tab's preset grid: as many as fit at <see cref="MinCardWidth"/> (four at 1440 px, three at 1200 px).</summary>
|
||||
public sealed class CardColumns : IValueConverter
|
||||
{
|
||||
public const double MinCardWidth = 200;
|
||||
|
||||
public static CardColumns Instance { get; } = new();
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
|
||||
value is double width && double.IsFinite(width) ? int.Max(1, (int)(width / MinCardWidth)) : 4;
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotSupportedException();
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>Margins of the free crop, in the order of <see cref="CropMargins.Of"/> (opposites differ in the lowest bit).</summary>
|
||||
public enum CropSide
|
||||
{
|
||||
Left,
|
||||
Right,
|
||||
Top,
|
||||
Bottom,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Camera tab's crop margins over <c>CameraSettings.Crop</c> (a normalised x, y, width, height rectangle, null for the
|
||||
/// whole frame): each margin at most <see cref="MaxMargin"/>, opposite margins leaving at least <see cref="MinSize"/>.
|
||||
/// </summary>
|
||||
public static class CropMargins
|
||||
{
|
||||
public const double MaxMargin = 0.45;
|
||||
|
||||
public const double MinSize = 0.1;
|
||||
|
||||
/// <summary>Left, right, top and bottom margins of <paramref name="crop"/> (zeros for none or an invalid one, which the render ignores too).</summary>
|
||||
public static double[] Of(double[]? crop) => crop is [var x, var y, var w, var h] && double.IsFinite(x + y + w + h)
|
||||
? [double.Clamp(x, 0, 1), double.Clamp(1 - x - w, 0, 1), double.Clamp(y, 0, 1), double.Clamp(1 - y - h, 0, 1)]
|
||||
: [0, 0, 0, 0];
|
||||
|
||||
/// <summary><paramref name="crop"/> with one margin changed; null when no margin is left (the whole frame).</summary>
|
||||
public static double[]? With(double[]? crop, CropSide side, double value)
|
||||
{
|
||||
var margins = Of(crop);
|
||||
var opposite = (int)side ^ 1;
|
||||
margins[(int)side] = double.Clamp(value, 0, double.Min(MaxMargin, 1 - MinSize - margins[opposite]));
|
||||
if (margins.All(m => m == 0)) return null;
|
||||
var (left, right, top, bottom) = (margins[0], margins[1], margins[2], margins[3]);
|
||||
return [left, top, 1 - left - right, 1 - top - bottom];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using Chronos.Ui.Visuals;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>Runs a command after every finished edit of a <see cref="CurveEditor"/> (add, move, delete, nudge).</summary>
|
||||
public static class CurveCommit
|
||||
{
|
||||
public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
|
||||
"Command", typeof(ICommand), typeof(CurveCommit), new PropertyMetadata(null, OnCommandChanged));
|
||||
|
||||
public static ICommand? GetCommand(DependencyObject d) => (ICommand?)d.GetValue(CommandProperty);
|
||||
|
||||
public static void SetCommand(DependencyObject d, ICommand? value) => d.SetValue(CommandProperty, value);
|
||||
|
||||
private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (d is not CurveEditor editor) return;
|
||||
editor.EditCompleted -= OnEditCompleted;
|
||||
if (e.NewValue is not null) editor.EditCompleted += OnEditCompleted;
|
||||
}
|
||||
|
||||
private static void OnEditCompleted(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (GetCommand((DependencyObject)sender) is { } command && command.CanExecute(null)) command.Execute(null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using Chronos.App.Jobs;
|
||||
using Chronos.Core.Advice;
|
||||
using Chronos.Core.Analysis;
|
||||
using Chronos.Core.Analysis.Deep;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// Where a step of the Edit path stands (owner review 1, R7). Each status has its own badge glyph, so colour never
|
||||
/// carries it alone. A status guides: it never keeps the user out of a step.
|
||||
/// </summary>
|
||||
public enum StepStatus
|
||||
{
|
||||
/// <summary>Not done yet: the step's number in a ring.</summary>
|
||||
Todo,
|
||||
|
||||
/// <summary>Nothing is missing: ✓.</summary>
|
||||
Done,
|
||||
|
||||
/// <summary>Something waits for the user: ▲.</summary>
|
||||
Attention,
|
||||
|
||||
/// <summary>The step's job runs, waits or is paused: ◐.</summary>
|
||||
Running,
|
||||
|
||||
/// <summary>The step needs the deep analysis first: ○.</summary>
|
||||
Waiting,
|
||||
}
|
||||
|
||||
/// <summary>A step's status, its text (three words at most) and, when there is more to say, a sentence for its tooltip.</summary>
|
||||
public sealed record StepState(StepStatus Status, string Text, string? Detail = null);
|
||||
|
||||
/// <summary>The step a sequence showed and the steps visited, which the Edit section keeps for the rest of the run.</summary>
|
||||
/// <param name="Analysis">The deep analysis the steps were seen with (<see cref="EditPath.AnalysisStamp"/>): another one since resets the visited marks.</param>
|
||||
public sealed record StepMemory(string Step, IReadOnlyCollection<string> Visited, string? Analysis = null);
|
||||
|
||||
/// <summary>What the statuses of the steps are worked out from.</summary>
|
||||
/// <param name="Analysis">The sequence's deep analysis that runs, else the paused one, else the queued one.</param>
|
||||
/// <param name="Render">The same for its renders.</param>
|
||||
/// <param name="RenderBlocked">Why the export cannot be rendered now, once its plan is known; null otherwise.</param>
|
||||
/// <param name="RenderMatches">A render was made from the current settings, or the newest says nothing about its settings.</param>
|
||||
public sealed record PathFacts(
|
||||
SequenceContent Content,
|
||||
AdvisorResult Advice,
|
||||
ProjectSettings Project,
|
||||
Job? Analysis,
|
||||
Job? Render,
|
||||
string? RenderBlocked,
|
||||
bool RenderMatches);
|
||||
|
||||
/// <summary>
|
||||
/// The Edit section's guided path (owner review 1, R7): each editor tab is one step, from the deep analysis to the
|
||||
/// export. This class says where each step stands, which step deals with each finding of the analyses, where the
|
||||
/// editor opens and whether the settings of a render are the current ones.
|
||||
/// </summary>
|
||||
public static class EditPath
|
||||
{
|
||||
public const string Analysis = "Analysis";
|
||||
public const string Frames = "Frames";
|
||||
public const string Exposure = "Exposure";
|
||||
public const string Motion = "Motion";
|
||||
public const string Camera = "Camera";
|
||||
public const string Time = "Time";
|
||||
public const string Stack = "Stack";
|
||||
public const string Export = "Export";
|
||||
|
||||
/// <summary>The step that deals with each finding of the light and the deep analysis.</summary>
|
||||
public static IReadOnlyDictionary<string, string> FindingSteps { get; } = new Dictionary<string, string>(StringComparer.Ordinal)
|
||||
{
|
||||
[FindingKeys.NoTimestamps] = Time,
|
||||
[FindingKeys.Gaps] = Time,
|
||||
[FindingKeys.Sessions] = Time,
|
||||
[FindingKeys.IrregularInterval] = Time,
|
||||
[FindingKeys.DuplicateTimestamps] = Time,
|
||||
[FindingKeys.NonMonotonicTimestamps] = Time,
|
||||
[FindingKeys.ClockJumps] = Time,
|
||||
[FindingKeys.TimeZoneEstimated] = Time,
|
||||
[FindingKeys.ExposureSteps] = Exposure,
|
||||
[FindingKeys.ExposureStep] = Exposure,
|
||||
[FindingKeys.MissingExposure] = Exposure,
|
||||
[FindingKeys.DayNightTransition] = Exposure,
|
||||
[DeepFindingKeys.Flicker] = Exposure,
|
||||
[DeepFindingKeys.WhiteBalanceJitter] = Exposure,
|
||||
[DeepFindingKeys.StepsNotReceived] = Exposure,
|
||||
[FindingKeys.CameraChanged] = Frames,
|
||||
[FindingKeys.LensChanged] = Frames,
|
||||
[DeepFindingKeys.UnreadableFrames] = Frames,
|
||||
[DeepFindingKeys.BlackFrames] = Frames,
|
||||
[DeepFindingKeys.WhiteFrames] = Frames,
|
||||
[DeepFindingKeys.DuplicateFrames] = Frames,
|
||||
[DeepFindingKeys.SceneChanges] = Frames,
|
||||
// Single frames of another size or orientation: Frames excludes them (no Camera setting acts on single frames).
|
||||
[FindingKeys.MixedResolution] = Frames,
|
||||
[FindingKeys.MixedOrientation] = Frames,
|
||||
[DeepFindingKeys.Shake] = Motion,
|
||||
[DeepFindingKeys.Panning] = Motion,
|
||||
[DeepFindingKeys.StarField] = Stack,
|
||||
[DeepFindingKeys.Clouds] = Stack,
|
||||
[FindingKeys.PreviewOnly] = Export,
|
||||
};
|
||||
|
||||
/// <summary>The step that deals with <paramref name="findingKey"/>; null for a finding no step names.</summary>
|
||||
public static string? StepOf(string findingKey) => FindingSteps.GetValueOrDefault(findingKey);
|
||||
|
||||
/// <summary>
|
||||
/// The step the editor opens on: the one last shown for this sequence in this run; else Analysis while the sequence
|
||||
/// has no current deep analysis or one waits, runs or is paused (<paramref name="analysis"/>, so the user sees it
|
||||
/// first); else Frames.
|
||||
/// </summary>
|
||||
public static string Start(string? remembered, SequenceContent content, Job? analysis = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
return remembered ?? (content.Deep is null || analysis is not null ? Analysis : Frames);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tells one deep analysis of the sequence from another (or from none), so that the step memory of a sequence closed
|
||||
/// while an analysis ran knows the steps changed meanwhile; null without a deep analysis.
|
||||
/// </summary>
|
||||
public static string? AnalysisStamp(SequenceContent content)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
return content.Deep is not { } d
|
||||
? null
|
||||
: string.Create(CultureInfo.InvariantCulture,
|
||||
$"{d.FrameCount}|{d.Findings.Count}|{d.Flicker.AmplitudeEv:R}|{d.Shake.RmsPx:R}|{d.Exposure.ReceivedSteps}|{d.Issues.Excludable().Length}|{d.HeroIndex}");
|
||||
}
|
||||
|
||||
/// <summary>Where <paramref name="step"/> stands.</summary>
|
||||
public static StepState Of(string step, PathFacts facts)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(facts);
|
||||
return step switch
|
||||
{
|
||||
Analysis => AnalysisState(facts),
|
||||
Frames => FramesState(facts),
|
||||
Exposure => SettingsState(facts, AdvisorSection.Exposure),
|
||||
Motion => SettingsState(facts, AdvisorSection.Motion),
|
||||
Camera => SettingsState(facts, AdvisorSection.Camera),
|
||||
Time => SettingsState(facts, AdvisorSection.Timing),
|
||||
Stack => StackState(facts.Project),
|
||||
Export => ExportState(facts),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(step), step, null),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings of <paramref name="project"/> that make its video, for comparing them with a render's: without the
|
||||
/// hero (the Library's picture), the frames still to place, the batch, the output folder, the output's name and the
|
||||
/// server copy, none of which changes the video.
|
||||
/// </summary>
|
||||
public static string Signature(ProjectSettings project)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
return (project with
|
||||
{
|
||||
HeroFrame = null,
|
||||
PendingFrames = null,
|
||||
Export = project.Export with { Batch = [], Folder = null, NameTemplate = string.Empty, SyncToServer = false },
|
||||
}).ToJson();
|
||||
}
|
||||
|
||||
private static StepState AnalysisState(PathFacts facts)
|
||||
{
|
||||
if (facts.Analysis is { } job) return new StepState(StepStatus.Running, JobLine(job));
|
||||
var content = facts.Content;
|
||||
if (content.Deep is null)
|
||||
{
|
||||
if ((content.Sequence.Status & SequenceStatus.AnalyzedDeep) == 0) return new StepState(StepStatus.Todo, Loc.L("Editor.Chart.NotAnalysed"));
|
||||
// Analysed, but the saved analysis describes frames the sequence no longer has, or cannot be read now (the
|
||||
// archive offline, the file moved or damaged, a server that sends none).
|
||||
return content.DeepOfOtherFrames
|
||||
? new StepState(StepStatus.Attention, Loc.L("Editor.Step.FramesChanged"), Loc.L("Tooltips.Editor.Step.FramesChanged"))
|
||||
: new StepState(StepStatus.Attention, Loc.L("Editor.Step.AnalysisUnavailable"), Loc.L("Tooltips.Editor.Step.AnalysisUnavailable"));
|
||||
}
|
||||
var warnings = facts.Advice.Findings.Count(f => f.Severity >= FindingSeverity.Warning);
|
||||
var text = warnings == 0
|
||||
? Loc.L("Editor.Step.Analysed")
|
||||
: string.Join(Loc.Separator, Loc.L("Editor.Step.Analysed"), Loc.Plural("Editor.Summary.Warnings", warnings));
|
||||
return new StepState(StepStatus.Done, text);
|
||||
}
|
||||
|
||||
private static StepState FramesState(PathFacts facts)
|
||||
{
|
||||
if (facts.Content.Deep is not { } deep) return Waiting();
|
||||
// Flagged frames the video still shows: neither excluded nor skipped by the render anyway.
|
||||
var flagged = deep.Issues.Excludable().Except(facts.Project.ExcludedFrames).Except(facts.Content.NotRenderable()).Count();
|
||||
return flagged > 0
|
||||
? new StepState(StepStatus.Attention, Loc.Plural("Editor.Step.Flagged", flagged), Loc.Plural("Tooltips.Editor.Step.Flagged", flagged))
|
||||
: new StepState(StepStatus.Done, Loc.L("Editor.Step.Excluded", facts.Project.ExcludedFrames.Count));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A settings step: waiting while an Auto setting of its section needs the deep analysis, needing attention while one
|
||||
/// lacks other data (no timestamps, no exposure data, an unknown source size), which taking the value over by hand
|
||||
/// settles; otherwise Auto, or Edited when a setting or a value of the section was set by hand.
|
||||
/// </summary>
|
||||
private static StepState SettingsState(PathFacts facts, AdvisorSection section)
|
||||
{
|
||||
var deep = facts.Content.Deep;
|
||||
var missing = facts.Advice.In(section).Where(r => r.IsMissingData && Counts(r, facts.Project, deep)).ToList();
|
||||
if (missing.Any(r => r.ReasonKey == AdvisorKeys.MissingDeep)) return Waiting();
|
||||
if (missing.FirstOrDefault() is { } reason) return new StepState(StepStatus.Attention, Loc.L("Editor.Step.MissingData"), Advisor.Explain(reason));
|
||||
var auto = EditorSettings.IsSectionAuto(facts.Project, section) && !HasHandValues(facts.Project, section);
|
||||
return new StepState(StepStatus.Done, Loc.L(auto ? "Common.Auto" : "Editor.Step.Edited"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Advice without a value asks something of the user only for an Auto setting that applies now: a setting shown n/a
|
||||
/// (its switch is off) cannot be taken over by hand, and once a deep analysis exists, a value it could not measure
|
||||
/// (no usable region mask) stays at the engine's fallback rather than waiting for an analysis that has run.
|
||||
/// </summary>
|
||||
private static bool Counts(Recommendation recommendation, ProjectSettings project, DeepAnalysisReport? deep)
|
||||
{
|
||||
if (recommendation.ReasonKey == AdvisorKeys.MissingDeep && deep is not null) return false;
|
||||
return EditorSettings.All.FirstOrDefault(s => s.Id == recommendation.Parameter) is not { } setting
|
||||
|| (setting.IsAuto(project) && EditorSettings.Applies(setting, project, deep));
|
||||
}
|
||||
|
||||
/// <summary>Values of the section set by hand that are not Auto settings: crop, offsets and camera moves; fit to a duration; the exposure offset.</summary>
|
||||
private static bool HasHandValues(ProjectSettings project, AdvisorSection section) => section switch
|
||||
{
|
||||
AdvisorSection.Camera => CropMargins.Of(project.Camera.Crop).Any(m => m > 0) || project.Camera.OffsetX != 0 || project.Camera.OffsetY != 0
|
||||
|| project.Camera.Keyframes.Count > 0,
|
||||
AdvisorSection.Timing => project.Timing.FitToSeconds is > 0,
|
||||
AdvisorSection.Exposure => project.Exposure.ExposureOffsetEv != 0,
|
||||
_ => false,
|
||||
};
|
||||
|
||||
private static StepState StackState(ProjectSettings project) => project.Stack.Mode switch
|
||||
{
|
||||
StackSetting.None => new StepState(StepStatus.Todo, Loc.L("Editor.Step.Optional")),
|
||||
StackSetting.Median => new StepState(StepStatus.Done, Loc.L("Editor.Stack.Median")),
|
||||
StackSetting.Mean => new StepState(StepStatus.Done, Loc.L("Editor.Stack.Mean")),
|
||||
_ => new StepState(StepStatus.Done, Loc.L("Editor.Stack.StarTrails")),
|
||||
};
|
||||
|
||||
private static StepState ExportState(PathFacts facts)
|
||||
{
|
||||
if (facts.Render is { } job) return new StepState(StepStatus.Running, JobLine(job));
|
||||
if (facts.RenderBlocked is { } reason) return new StepState(StepStatus.Attention, Loc.L("Editor.Step.Blocked"), reason);
|
||||
if (facts.Content.Renders.Count == 0) return new StepState(StepStatus.Todo, Loc.L("Editor.Step.NotRendered"));
|
||||
return facts.RenderMatches
|
||||
? new StepState(StepStatus.Done, Loc.L("Editor.Step.Rendered"))
|
||||
: new StepState(StepStatus.Attention, Loc.L("Editor.Step.Outdated"), Loc.L("Tooltips.Editor.Step.Outdated"));
|
||||
}
|
||||
|
||||
private static StepState Waiting() => new(StepStatus.Waiting, Loc.L("Editor.Step.Waiting"), Loc.L("Tooltips.Editor.NotApplicable.NeedsAnalysis"));
|
||||
|
||||
/// <summary>"Deep analysis · running".</summary>
|
||||
private static string JobLine(Job job) => string.Join(Loc.Separator, JobText.Kind(job.Kind), Loc.L("Jobs.State." + job.State));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings the sequence's renders were made from, read once when the sequence loads, so each change of the project
|
||||
/// only works out its own <see cref="EditPath.Signature"/>.
|
||||
/// </summary>
|
||||
public sealed class RenderedSettings
|
||||
{
|
||||
private readonly HashSet<string> _signatures = new(StringComparer.Ordinal);
|
||||
|
||||
/// <param name="renders">Newest first, as <see cref="SequenceContent.Renders"/>.</param>
|
||||
public RenderedSettings(IReadOnlyList<Render> renders)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(renders);
|
||||
foreach (var render in renders)
|
||||
{
|
||||
if (render.SettingsJson is not { Length: > 0 } json) continue;
|
||||
try
|
||||
{
|
||||
_signatures.Add(EditPath.Signature(ProjectSettings.FromJson(json)));
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or InvalidDataException)
|
||||
{
|
||||
// Settings no longer readable (or written by a newer Chronos) say nothing either way, like none.
|
||||
}
|
||||
}
|
||||
// A render that keeps no settings (a server's, or one fetched from it) cannot be compared: it counts as current.
|
||||
NewestUnknown = renders.Count > 0 && (renders[0].SettingsJson is not { Length: > 0 } || _signatures.Count == 0);
|
||||
}
|
||||
|
||||
/// <summary>The newest render says nothing comparable about its settings.</summary>
|
||||
public bool NewestUnknown { get; }
|
||||
|
||||
/// <summary>A render was made from settings that make the same video as <paramref name="project"/>'s, or the newest cannot tell.</summary>
|
||||
public bool Matches(ProjectSettings project) => NewestUnknown || _signatures.Contains(EditPath.Signature(project));
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using System.IO;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// A sequence the editor could not read or store, for a reason the editor words itself in one localized sentence (the
|
||||
/// sequence is gone, its project cannot be read, the account may not change it, the settings kept changing elsewhere,
|
||||
/// the frames changed on the server). A toast shows <see cref="Exception.Message"/> as it is (BRIEF §0.2 rule 6); any
|
||||
/// other failure is mapped to a catalog sentence by its cause.
|
||||
/// </summary>
|
||||
public class EditorException(string message, Exception? innerException = null) : IOException(message, innerException);
|
||||
@@ -0,0 +1,85 @@
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Ui.Visuals;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>Linear-light frames as frozen sRGB bitmaps the UI thread can show (created on any thread).</summary>
|
||||
public static class EditorImages
|
||||
{
|
||||
public static BitmapSource ToBitmap(ImageBuffer image)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(image);
|
||||
var channels = int.Min(3, image.Channels);
|
||||
var pixels = PixelConvert.ToInterleaved8(image, channels);
|
||||
var format = channels == 1 ? PixelFormats.Gray8 : PixelFormats.Rgb24;
|
||||
var bitmap = BitmapSource.Create(image.Width, image.Height, 96, 96, format, null, pixels, image.Width * channels);
|
||||
bitmap.Freeze();
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
/// <summary>A waveform as an opacity mask (white, alpha = density) so the view paints it in a theme brush.</summary>
|
||||
public static BitmapSource ToMask(LumaWaveform waveform)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(waveform);
|
||||
var pixels = new byte[waveform.Density.Length * 4];
|
||||
for (var i = 0; i < waveform.Density.Length; i++)
|
||||
{
|
||||
var alpha = waveform.Density[i];
|
||||
pixels[4 * i] = pixels[4 * i + 1] = pixels[4 * i + 2] = pixels[4 * i + 3] = alpha;
|
||||
}
|
||||
var bitmap = BitmapSource.Create(waveform.Columns, waveform.Rows, 96, 96, PixelFormats.Pbgra32, null, pixels, waveform.Columns * 4);
|
||||
bitmap.Freeze();
|
||||
return bitmap;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Filmstrip thumbnails decoded through the editor's <see cref="ISequenceSource"/> (embedded previews when large
|
||||
/// enough), at most a few at a time so scrolling the strip never floods the decoders.
|
||||
/// </summary>
|
||||
public sealed class EditorThumbnails(ISequenceSource source, int count) : IThumbnailSource
|
||||
{
|
||||
private readonly SemaphoreSlim _decoders = new(int.Clamp(Environment.ProcessorCount / 2, 2, 6));
|
||||
private int _pending;
|
||||
|
||||
public int Count { get; } = count;
|
||||
|
||||
/// <summary>Thumbnails requested and not yet returned (capture and tests wait for them).</summary>
|
||||
public int Pending => Volatile.Read(ref _pending);
|
||||
|
||||
public async ValueTask<ImageSource?> GetAsync(int index, int pixelWidth, CancellationToken cancellationToken)
|
||||
{
|
||||
Interlocked.Increment(ref _pending);
|
||||
try
|
||||
{
|
||||
return await DecodeAsync(index, pixelWidth, cancellationToken);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Interlocked.Decrement(ref _pending);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<ImageSource?> DecodeAsync(int index, int pixelWidth, CancellationToken cancellationToken)
|
||||
{
|
||||
await _decoders.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
// Long edge for frames up to 16:9 tall or wide; the cache rounds requests, so nearby widths share a decode.
|
||||
using var frame = await source.DecodeAsync(index, int.Clamp(pixelWidth, 32, 512), DecodePurpose.Thumbnail, cancellationToken);
|
||||
return frame is null ? null : EditorImages.ToBitmap(frame);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
Log.Debug("editor", $"No thumbnail for frame {index}: {ex.Message}");
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_decoders.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
<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:e="clr-namespace:Chronos.App.Editor">
|
||||
<!--
|
||||
The measuring tool of each step, below the filmstrip (BRIEF §12.3): the Analysis step's findings, luminance, flicker
|
||||
and waveform, camera path and sky charts, the frame table, the keyframe and time-remap curve editors with the plan
|
||||
chart, and the Export step's preset cards. Clicking a chart seeks the preview.
|
||||
-->
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="pack://application:,,,/Chronos;component/Editor/EditorStyles.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
|
||||
<!-- One choice of a vertical segment group (the Exposure chart switch): text, accent when chosen. -->
|
||||
<Style x:Key="RadioButton.ChartSegment" TargetType="RadioButton" BasedOn="{StaticResource RadioButton.Segment}">
|
||||
<Setter Property="Width" Value="Auto" />
|
||||
<Setter Property="MinWidth" Value="64" />
|
||||
<Setter Property="Height" Value="26" />
|
||||
<Setter Property="Padding" Value="10,0" />
|
||||
<Setter Property="FontSize" Value="{StaticResource Size.Secondary}" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Left" />
|
||||
<Setter Property="Margin" Value="0,0,0,-1" />
|
||||
</Style>
|
||||
|
||||
<DataTemplate x:Key="Template.Chart">
|
||||
<Border Style="{StaticResource Border.Panel}" Padding="10" Margin="0,10,0,0">
|
||||
<v:SeriesChart Series="{Binding Series}" Legend="{Binding Legend}" Summary="{Binding Summary}" YLabelFormatter="{Binding YFormatter}"
|
||||
CurrentIndex="{Binding Editor.CurrentIndex, Mode=TwoWay}" ToolTip="{l:Loc Tooltips.Editor.Chart.Seek}" AutomationProperties.Name="{Binding Header}" />
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- Exposure: luminance (measured vs target), flicker (frame-to-frame change before and after) or the waveform of the frame on screen. -->
|
||||
<DataTemplate DataType="{x:Type e:ExposureTab}">
|
||||
<Border Style="{StaticResource Border.Panel}" Padding="10" Margin="0,10,0,0">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<StackPanel Margin="0,0,10,0" VerticalAlignment="Top" AutomationProperties.Name="{l:Loc Editor.Chart.Switch}">
|
||||
<RadioButton Style="{StaticResource RadioButton.ChartSegment}" ui:ControlState.CornerRadius="6,6,0,0" Content="{l:Loc Editor.Chart.Luminance}"
|
||||
IsChecked="{Binding IsLuminance}" ToolTip="{l:Loc Tooltips.Editor.Chart.Luminance}" />
|
||||
<RadioButton Style="{StaticResource RadioButton.ChartSegment}" ui:ControlState.CornerRadius="0" Content="{l:Loc Editor.Chart.Flicker}"
|
||||
IsChecked="{Binding IsFlicker}" ToolTip="{l:Loc Tooltips.Editor.Chart.Flicker}" />
|
||||
<RadioButton Style="{StaticResource RadioButton.ChartSegment}" ui:ControlState.CornerRadius="0,0,6,6" Content="{l:Loc Editor.Chart.Waveform}"
|
||||
IsChecked="{Binding IsWaveform}" ToolTip="{l:Loc Tooltips.Editor.Chart.Waveform}" />
|
||||
</StackPanel>
|
||||
<v:SeriesChart Grid.Column="1" Series="{Binding Series}" Legend="{Binding Legend}" Markers="{Binding Markers}" Summary="{Binding Summary}"
|
||||
YLabelFormatter="{Binding YFormatter}" CurrentIndex="{Binding Editor.CurrentIndex, Mode=TwoWay}" ToolTip="{l:Loc Tooltips.Editor.Chart.Seek}"
|
||||
AutomationProperties.Name="{Binding Header}"
|
||||
Visibility="{Binding IsWaveform, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
<!-- Waveform monitor: luma level (bottom 0 %, top 100 %) across the picture; density drawn in the accent colour. -->
|
||||
<Grid Grid.Column="1" Visibility="{Binding IsWaveform, Converter={StaticResource BoolToVisibility}}" ToolTip="{l:Loc Tooltips.Editor.Chart.WaveformView}"
|
||||
AutomationProperties.Name="{l:Loc Editor.Chart.Waveform}">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.ColumnSpan="2" Text="{Binding WaveformTitle}" Style="{StaticResource Text.Header}" Margin="0,0,0,6" Typography.NumeralAlignment="Tabular" />
|
||||
<Grid Grid.Row="1" Margin="0,0,6,0">
|
||||
<TextBlock Text="{l:Loc Editor.Chart.Level100}" Style="{StaticResource Text.Header}" VerticalAlignment="Top" HorizontalAlignment="Right" />
|
||||
<TextBlock Text="{l:Loc Editor.Chart.Level50}" Style="{StaticResource Text.Header}" VerticalAlignment="Center" HorizontalAlignment="Right" />
|
||||
<TextBlock Text="{l:Loc Editor.Chart.Level0}" Style="{StaticResource Text.Header}" VerticalAlignment="Bottom" HorizontalAlignment="Right" />
|
||||
</Grid>
|
||||
<Border Grid.Row="1" Grid.Column="1" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1">
|
||||
<Grid>
|
||||
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,0" VerticalAlignment="Center" />
|
||||
<Rectangle Fill="{DynamicResource Brush.Accent}">
|
||||
<Rectangle.OpacityMask>
|
||||
<ImageBrush ImageSource="{Binding Editor.WaveformImage}" Stretch="Fill" />
|
||||
</Rectangle.OpacityMask>
|
||||
</Rectangle>
|
||||
</Grid>
|
||||
</Border>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
|
||||
<!--
|
||||
Analysis (owner review 1, R7): every finding of the analyses, the most severe first, with the step that deals with
|
||||
it; choosing one seeks its first frame (a finding about the whole sequence has none, and no tooltip saying so). Each
|
||||
row reads as its sentence to screen readers.
|
||||
-->
|
||||
<DataTemplate DataType="{x:Type e:AnalysisTab}">
|
||||
<Grid Margin="0,10,0,0">
|
||||
<Border Style="{StaticResource Border.Panel}">
|
||||
<DockPanel>
|
||||
<TextBlock DockPanel.Dock="Top" Text="{l:Loc Editor.Analysis.Findings}" Style="{StaticResource Text.Section}" Margin="14,10,14,6" />
|
||||
<ListBox ItemsSource="{Binding Findings}" SelectedItem="{Binding SelectedFinding}" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
|
||||
AutomationProperties.Name="{l:Loc Editor.Analysis.Findings}" KeyboardNavigation.TabNavigation="Continue" BorderThickness="0" Background="Transparent">
|
||||
<ListBox.ItemContainerStyle>
|
||||
<Style TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding Text}" />
|
||||
<Setter Property="ToolTip" Value="{l:Loc Tooltips.Editor.Frames.Finding}" />
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding Frame}" Value="{x:Null}">
|
||||
<Setter Property="ToolTip" Value="{x:Null}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</ListBox.ItemContainerStyle>
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type e:AnalysisFinding}">
|
||||
<Grid MinHeight="36">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ui:StatusGlyph Kind="{Binding Kind}" VerticalAlignment="Center" Margin="0,0,8,0" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding Text}" TextWrapping="Wrap" VerticalAlignment="Center" Margin="0,6" />
|
||||
<Button Grid.Column="2" Style="{StaticResource Button.Row}" Margin="8,0,0,0" VerticalAlignment="Center"
|
||||
Command="{Binding DataContext.Editor.GoToStepCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding Step}"
|
||||
ToolTip="{Binding GoToToolTip}" AutomationProperties.Name="{Binding Step.Header}"
|
||||
Visibility="{Binding Step, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<TextBlock Text="{Binding Step.Header}" VerticalAlignment="Center" />
|
||||
<ui:Icon Glyph="{StaticResource Icon.ChevronRight}" Size="12" Margin="4,0,0,0" VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</Button>
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
<!-- No finding: the analysis runs, has not run yet, or found nothing. -->
|
||||
<ui:EmptyState Message="{Binding EmptyText}" Visibility="{Binding HasFindings, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
|
||||
<DataTemplate DataType="{x:Type e:MotionTab}">
|
||||
<ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource Template.Chart}" />
|
||||
</DataTemplate>
|
||||
|
||||
<DataTemplate DataType="{x:Type e:StackTab}">
|
||||
<ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource Template.Chart}" />
|
||||
</DataTemplate>
|
||||
|
||||
<!-- Frames: virtualised table with sortable headers; row actions show on hover or selection (DESIGN §4 tables). -->
|
||||
<DataTemplate DataType="{x:Type e:FramesTab}">
|
||||
<Border Style="{StaticResource Border.Panel}" Margin="0,10,0,0">
|
||||
<!-- Header and rows share the actions column, so the columns line up when the row actions are wider than 118 px (longer languages). -->
|
||||
<Grid Grid.IsSharedSizeScope="True">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,4,24,4">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="0.7*" MinWidth="40" />
|
||||
<ColumnDefinition Width="1.2*" MinWidth="76" />
|
||||
<ColumnDefinition Width="0.9*" MinWidth="52" />
|
||||
<ColumnDefinition Width="0.6*" MinWidth="36" />
|
||||
<ColumnDefinition Width="0.6*" MinWidth="36" />
|
||||
<ColumnDefinition Width="1.1*" MinWidth="64" />
|
||||
<ColumnDefinition Width="0.9*" MinWidth="44" />
|
||||
<ColumnDefinition Width="1.4*" MinWidth="60" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="118" SharedSizeGroup="FrameActions" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Button Style="{StaticResource Button.SortHeader}" DataContext="{Binding Columns[0]}" Command="{Binding SortCommand}"
|
||||
Content="{Binding Header}" ToolTip="{Binding ToolTip}" />
|
||||
<Button Grid.Column="1" Style="{StaticResource Button.SortHeader}" DataContext="{Binding Columns[1]}" Command="{Binding SortCommand}"
|
||||
Content="{Binding Header}" ToolTip="{Binding ToolTip}" HorizontalContentAlignment="Right" />
|
||||
<Button Grid.Column="2" Style="{StaticResource Button.SortHeader}" DataContext="{Binding Columns[2]}" Command="{Binding SortCommand}"
|
||||
Content="{Binding Header}" ToolTip="{Binding ToolTip}" HorizontalContentAlignment="Right" />
|
||||
<Button Grid.Column="3" Style="{StaticResource Button.SortHeader}" DataContext="{Binding Columns[3]}" Command="{Binding SortCommand}"
|
||||
Content="{Binding Header}" ToolTip="{Binding ToolTip}" HorizontalContentAlignment="Right" />
|
||||
<Button Grid.Column="4" Style="{StaticResource Button.SortHeader}" DataContext="{Binding Columns[4]}" Command="{Binding SortCommand}"
|
||||
Content="{Binding Header}" ToolTip="{Binding ToolTip}" HorizontalContentAlignment="Right" />
|
||||
<Button Grid.Column="5" Style="{StaticResource Button.SortHeader}" DataContext="{Binding Columns[5]}" Command="{Binding SortCommand}"
|
||||
Content="{Binding Header}" ToolTip="{Binding ToolTip}" HorizontalContentAlignment="Right" />
|
||||
<Button Grid.Column="6" Style="{StaticResource Button.SortHeader}" DataContext="{Binding Columns[6]}" Command="{Binding SortCommand}"
|
||||
Content="{Binding Header}" ToolTip="{Binding ToolTip}" Margin="10,0,0,0" />
|
||||
<Button Grid.Column="7" Style="{StaticResource Button.SortHeader}" DataContext="{Binding Columns[7]}" Command="{Binding SortCommand}"
|
||||
Content="{Binding Header}" ToolTip="{Binding ToolTip}" Margin="10,0,0,0" />
|
||||
</Grid>
|
||||
</Border>
|
||||
<ListBox Grid.Row="1" ItemsSource="{Binding Frames}" SelectedItem="{Binding Selected}" ItemContainerStyle="{StaticResource ListBoxItem.Row}"
|
||||
VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Frames.Table}" AutomationProperties.Name="{Binding Header}" BorderThickness="0" Background="Transparent">
|
||||
<ListBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type e:FrameRow}">
|
||||
<Grid Height="36">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="0.7*" MinWidth="40" />
|
||||
<ColumnDefinition Width="1.2*" MinWidth="76" />
|
||||
<ColumnDefinition Width="0.9*" MinWidth="52" />
|
||||
<ColumnDefinition Width="0.6*" MinWidth="36" />
|
||||
<ColumnDefinition Width="0.6*" MinWidth="36" />
|
||||
<ColumnDefinition Width="1.1*" MinWidth="64" />
|
||||
<ColumnDefinition Width="0.9*" MinWidth="44" />
|
||||
<ColumnDefinition Width="1.4*" MinWidth="60" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="118" SharedSizeGroup="FrameActions" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Number}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.CellNumber}" Text="{Binding Time}" />
|
||||
<TextBlock Grid.Column="2" Style="{StaticResource Text.CellNumber}" Text="{Binding Exposure}" />
|
||||
<TextBlock Grid.Column="3" Style="{StaticResource Text.CellNumber}" Text="{Binding Iso}" />
|
||||
<TextBlock Grid.Column="4" Style="{StaticResource Text.CellNumber}" Text="{Binding Aperture}" />
|
||||
<TextBlock Grid.Column="5" Style="{StaticResource Text.CellNumber}" Text="{Binding Size}" />
|
||||
<TextBlock Grid.Column="6" Style="{StaticResource Text.Cell}" Text="{Binding Tier}" Margin="10,0,0,0" ToolTip="{Binding Tier}" />
|
||||
<TextBlock x:Name="Flags" Grid.Column="7" Style="{StaticResource Text.Cell}" Text="{Binding Flags}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextMuted}"
|
||||
ToolTip="{Binding FlagsToolTip}" />
|
||||
<StackPanel x:Name="Actions" Grid.Column="8" Orientation="Horizontal" HorizontalAlignment="Right" Visibility="Hidden">
|
||||
<Button Style="{StaticResource Button.Row}" Content="{Binding ExcludeText}" ToolTip="{Binding ExcludeToolTip}" ToolTipService.ShowOnDisabled="True"
|
||||
Command="{Binding DataContext.ToggleExcludeCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}" />
|
||||
<Button Style="{StaticResource Button.Row}" Width="26" MinWidth="26" Padding="0" Margin="0" ui:ButtonIcon.Glyph="{StaticResource Icon.Hero}"
|
||||
ToolTip="{Binding DataContext.HeroToolTip, RelativeSource={RelativeSource AncestorType=ListBox}}" ToolTipService.ShowOnDisabled="True"
|
||||
AutomationProperties.Name="{l:Loc Editor.Frames.SetHero}"
|
||||
Command="{Binding DataContext.SetHeroCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
<DataTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource AncestorType=ListBoxItem}}" Value="True">
|
||||
<Setter TargetName="Actions" Property="Visibility" Value="Visible" />
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}}" Value="True">
|
||||
<Setter TargetName="Actions" Property="Visibility" Value="Visible" />
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding IsExcluded}" Value="True">
|
||||
<Setter TargetName="Flags" Property="Foreground" Value="{DynamicResource Brush.Warning}" />
|
||||
</DataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
</ListBox.ItemTemplate>
|
||||
</ListBox>
|
||||
</Grid>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- Camera: zoom keyframes over the sequence (◆ on the filmstrip). -->
|
||||
<DataTemplate DataType="{x:Type e:CameraTab}">
|
||||
<Border Style="{StaticResource Border.Panel}" Padding="10" Margin="0,10,0,0">
|
||||
<v:CurveEditor Points="{Binding KeyPoints}" Mode="Keyframes" SelectedIndex="{Binding SelectedKey, Mode=TwoWay}" PlayheadPosition="{Binding Playhead}"
|
||||
XLabelFormatter="{Binding XFormatter}" YLabelFormatter="{Binding YFormatter}" e:CurveCommit.Command="{Binding CommitCurveCommand}"
|
||||
IsEnabled="{Binding Editor.IsEditable}" ToolTip="{Binding CurveToolTip}" ToolTipService.ShowOnDisabled="True"
|
||||
AutomationProperties.Name="{l:Loc Editor.Camera.Curve}" />
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- Time: the plan chart (video frames per photo, cuts) beside the remap curve (output time → source position). -->
|
||||
<DataTemplate DataType="{x:Type e:TimeTab}">
|
||||
<Grid Margin="0,10,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="10" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Border Style="{StaticResource Border.Panel}" Padding="10">
|
||||
<v:SeriesChart Series="{Binding PlanSeries}" Legend="{Binding PlanLegend}" Markers="{Binding PlanMarkers}" Summary="{Binding PlanText}"
|
||||
YLabelFormatter="{Binding PlanFormatter}" CurrentIndex="{Binding Editor.CurrentIndex, Mode=TwoWay}" ToolTip="{l:Loc Tooltips.Editor.Chart.Plan}"
|
||||
AutomationProperties.Name="{l:Loc Editor.Time.PlanChart}" />
|
||||
</Border>
|
||||
<Border Grid.Column="2" Style="{StaticResource Border.Panel}" Padding="10">
|
||||
<DockPanel>
|
||||
<TextBlock DockPanel.Dock="Top" Text="{l:Loc Editor.Time.Curve}" Style="{StaticResource Text.Header}" Margin="0,0,0,6" />
|
||||
<v:CurveEditor Points="{Binding RemapPoints}" Mode="TimeRemap" Evaluator="{Binding Evaluator}" ShowDiagonal="True" PlayheadPosition="{Binding Playhead}"
|
||||
XLabelFormatter="{Binding XFormatter}" YLabelFormatter="{Binding YFormatter}" e:CurveCommit.Command="{Binding CommitCurveCommand}"
|
||||
IsEnabled="{Binding Editor.IsEditable}" ToolTip="{Binding CurveToolTip}" ToolTipService.ShowOnDisabled="True"
|
||||
AutomationProperties.Name="{l:Loc Editor.Time.Curve}" />
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- Export: preset cards at least 200 px wide (four per row in Export.html at 1440 px, three at 1200 px). -->
|
||||
<DataTemplate DataType="{x:Type e:ExportTab}">
|
||||
<ScrollViewer Margin="0,10,0,0" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
|
||||
<ItemsControl ItemsSource="{Binding Cards}" Focusable="False" IsEnabled="{Binding Editor.IsEditable}" Margin="-5,0,-5,0">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
<UniformGrid Columns="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType=ItemsControl}, Converter={x:Static e:CardColumns.Instance}}" />
|
||||
</ItemsPanelTemplate>
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type e:PresetCard}">
|
||||
<!-- Disabled while a job runs or the project cannot change: the card's tooltip says why. -->
|
||||
<Button Style="{StaticResource Button.PresetCard}" Command="{Binding SelectCommand}" CommandParameter="{Binding}" ToolTip="{Binding ToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{Binding Name}">
|
||||
<DockPanel>
|
||||
<!-- The chip moves under the name when both do not fit on one line. -->
|
||||
<WrapPanel DockPanel.Dock="Top">
|
||||
<TextBlock Text="{Binding Name}" FontWeight="SemiBold" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" Margin="0,0,8,0" />
|
||||
<Border Style="{StaticResource Border.Recommended}" Margin="0" Visibility="{Binding IsRecommended, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{l:Loc Editor.Export.Recommended}" FontSize="{StaticResource Size.Chip}" Foreground="{DynamicResource Brush.Accent}" />
|
||||
</Border>
|
||||
</WrapPanel>
|
||||
<DockPanel DockPanel.Dock="Bottom">
|
||||
<CheckBox DockPanel.Dock="Right" IsChecked="{Binding IsInBatch}" Visibility="{Binding CanBatch, Converter={StaticResource BoolToVisibility}}"
|
||||
ToolTip="{Binding BatchToolTip}" ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{l:Loc Editor.Export.InBatch}" Margin="6,0,0,0" />
|
||||
<TextBlock Text="{Binding Estimate}" FontSize="{StaticResource Size.Secondary}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"
|
||||
Typography.NumeralAlignment="Tabular" />
|
||||
</DockPanel>
|
||||
<StackPanel Margin="0,4,0,0">
|
||||
<TextBlock Text="{Binding Format}" FontSize="{StaticResource Size.Secondary}" Foreground="{DynamicResource Brush.TextMuted}" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{Binding Encoding}" FontSize="{StaticResource Size.Secondary}" Foreground="{DynamicResource Brush.TextMuted}" TextTrimming="CharacterEllipsis"
|
||||
Margin="0,4,0,0" />
|
||||
</StackPanel>
|
||||
</DockPanel>
|
||||
</Button>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</ScrollViewer>
|
||||
</DataTemplate>
|
||||
</ResourceDictionary>
|
||||
@@ -0,0 +1,503 @@
|
||||
<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:shell="clr-namespace:Chronos.App.Shell"
|
||||
xmlns:e="clr-namespace:Chronos.App.Editor">
|
||||
<!--
|
||||
The column of each step (BRIEF §12.3, Editor.html aside, Export.html Output panel): the setting rows by type, the
|
||||
common section frame (title, rows, Optimise section, Reset) and the panels with their own content.
|
||||
-->
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="pack://application:,,,/Chronos;component/Editor/EditorStyles.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
|
||||
<!-- ===================== Setting rows ===================== -->
|
||||
<DataTemplate DataType="{x:Type e:AutoNumberRow}">
|
||||
<ui:AutoSlider Header="{Binding Header}" Value="{Binding Value}" IsAuto="{Binding IsAuto}" AutoValue="{Binding AutoValue}" AutoReason="{Binding AutoReason}"
|
||||
IsApplicable="{Binding IsApplicable, Mode=OneWay}" NotApplicableReason="{Binding NotApplicableReason}" Minimum="{Binding Minimum}"
|
||||
Maximum="{Binding Maximum}" SmallChange="{Binding Step}" TickFrequency="{Binding Step}" IsSnapToTickEnabled="True" ValueFormat="{Binding Format}"
|
||||
SliderToolTip="{Binding ToolTip}" ToolTip="{Binding ToolTip}" AutomationProperties.Name="{Binding Header}" />
|
||||
</DataTemplate>
|
||||
|
||||
<DataTemplate DataType="{x:Type e:AutoSwitchRow}">
|
||||
<Grid Margin="0,0,0,12" MinHeight="26">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{Binding Header}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" ToolTip="{Binding ToolTip}" />
|
||||
<Border x:Name="Pill" Grid.Column="1" Style="{StaticResource Pill.Auto}" Margin="8,0" VerticalAlignment="Center" ToolTip="{Binding AutoReason}">
|
||||
<TextBlock Text="{Binding AutoText}" FontSize="{StaticResource Size.Chip}" Foreground="{DynamicResource Brush.Accent}" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<Button x:Name="Reset" Grid.Column="1" Style="{StaticResource Button.IconSubtle}" Width="26" Height="26" Margin="8,0" Visibility="Collapsed"
|
||||
ui:ButtonIcon.Glyph="{StaticResource Icon.Reset}" Command="{Binding ResetCommand}" ToolTip="{l:Loc Tooltips.Common.ResetToAuto}"
|
||||
AutomationProperties.Name="{l:Loc Editor.ResetToAuto}" />
|
||||
<CheckBox Grid.Column="2" Style="{StaticResource CheckBox.Switch}" IsChecked="{Binding IsOn}" VerticalAlignment="Center" ToolTip="{Binding ToolTip}"
|
||||
AutomationProperties.Name="{Binding Header}" />
|
||||
</Grid>
|
||||
<DataTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding IsAuto}" Value="False">
|
||||
<Setter TargetName="Pill" Property="Visibility" Value="Collapsed" />
|
||||
<Setter TargetName="Reset" Property="Visibility" Value="Visible" />
|
||||
</DataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
|
||||
<DataTemplate DataType="{x:Type e:AutoChoiceRow}">
|
||||
<StackPanel Margin="0,0,0,12">
|
||||
<Grid MinHeight="26">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{Binding Header}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" ToolTip="{Binding ToolTip}" />
|
||||
<Border x:Name="Pill" Grid.Column="1" Style="{StaticResource Pill.Auto}" Margin="8,0,0,0" VerticalAlignment="Center" ToolTip="{Binding AutoReason}">
|
||||
<TextBlock Text="{Binding AutoText}" FontSize="{StaticResource Size.Chip}" Foreground="{DynamicResource Brush.Accent}" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<Button x:Name="Reset" Grid.Column="1" Style="{StaticResource Button.IconSubtle}" Width="26" Height="26" Margin="8,0,0,0" Visibility="Collapsed"
|
||||
ui:ButtonIcon.Glyph="{StaticResource Icon.Reset}" Command="{Binding ResetCommand}" ToolTip="{l:Loc Tooltips.Common.ResetToAuto}"
|
||||
AutomationProperties.Name="{l:Loc Editor.ResetToAuto}" />
|
||||
<TextBlock x:Name="NotApplicable" Grid.Column="1" Style="{StaticResource Text.NotApplicable}" Text="{l:Loc Common.NotApplicable}"
|
||||
ToolTip="{Binding NotApplicableReason}" Visibility="Collapsed" />
|
||||
</Grid>
|
||||
<ComboBox x:Name="Choices" Margin="0,6,0,0" ItemsSource="{Binding Options}" SelectedItem="{Binding Selected}" DisplayMemberPath="Label"
|
||||
ToolTip="{Binding ToolTip}" AutomationProperties.Name="{Binding Header}" />
|
||||
</StackPanel>
|
||||
<DataTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding IsAuto}" Value="False">
|
||||
<Setter TargetName="Pill" Property="Visibility" Value="Collapsed" />
|
||||
<Setter TargetName="Reset" Property="Visibility" Value="Visible" />
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding IsApplicable}" Value="False">
|
||||
<Setter TargetName="Pill" Property="Visibility" Value="Collapsed" />
|
||||
<Setter TargetName="Reset" Property="Visibility" Value="Collapsed" />
|
||||
<Setter TargetName="NotApplicable" Property="Visibility" Value="Visible" />
|
||||
<Setter TargetName="Choices" Property="IsEnabled" Value="False" />
|
||||
</DataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
|
||||
<DataTemplate DataType="{x:Type e:NumberRow}">
|
||||
<StackPanel Margin="0,0,0,12">
|
||||
<Grid MinHeight="24">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{Binding Header}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" ToolTip="{Binding ToolTip}" />
|
||||
<TextBlock x:Name="Value" Grid.Column="1" Style="{StaticResource Text.RowValue}" Text="{Binding DisplayValue}" Margin="8,0,0,0" />
|
||||
<TextBlock x:Name="NotApplicable" Grid.Column="1" Style="{StaticResource Text.NotApplicable}" Text="{l:Loc Common.NotApplicable}"
|
||||
ToolTip="{Binding NotApplicableReason}" Visibility="Collapsed" Margin="8,0,0,0" />
|
||||
</Grid>
|
||||
<Slider x:Name="Slider" Margin="0,6,0,0" Minimum="{Binding Minimum}" Maximum="{Binding Maximum}" SmallChange="{Binding Step}" LargeChange="{Binding Step}"
|
||||
TickFrequency="{Binding Step}" IsSnapToTickEnabled="True" Value="{Binding Value}" ToolTip="{Binding ToolTip}" AutomationProperties.Name="{Binding Header}" />
|
||||
</StackPanel>
|
||||
<DataTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding IsApplicable}" Value="False">
|
||||
<Setter TargetName="Value" Property="Visibility" Value="Collapsed" />
|
||||
<Setter TargetName="NotApplicable" Property="Visibility" Value="Visible" />
|
||||
<Setter TargetName="Slider" Property="IsEnabled" Value="False" />
|
||||
</DataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
|
||||
<DataTemplate DataType="{x:Type e:ChoiceRow}">
|
||||
<Grid Margin="0,0,0,12" MinHeight="32">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="*" MinWidth="120" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{Binding Header}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" ToolTip="{Binding ToolTip}" />
|
||||
<ComboBox Grid.Column="1" ItemsSource="{Binding Options}" SelectedItem="{Binding Selected}" DisplayMemberPath="Label" ToolTip="{Binding ToolTip}"
|
||||
AutomationProperties.Name="{Binding Header}" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
|
||||
<DataTemplate DataType="{x:Type e:InfoRow}">
|
||||
<Grid Margin="0,0,0,12" MinHeight="24">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{Binding Header}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" ToolTip="{Binding ToolTip}" />
|
||||
<TextBlock x:Name="Value" Grid.Column="1" Style="{StaticResource Text.RowValue}" Text="{Binding Value}" Margin="8,0,0,0" ToolTip="{Binding ToolTip}" />
|
||||
<TextBlock x:Name="NotApplicable" Grid.Column="1" Style="{StaticResource Text.NotApplicable}" Text="{l:Loc Common.NotApplicable}"
|
||||
ToolTip="{Binding NotApplicableReason}" Visibility="Collapsed" Margin="8,0,0,0" />
|
||||
</Grid>
|
||||
<DataTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding IsApplicable}" Value="False">
|
||||
<Setter TargetName="Value" Property="Visibility" Value="Collapsed" />
|
||||
<Setter TargetName="NotApplicable" Property="Visibility" Value="Visible" />
|
||||
</DataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- ===================== Section frame: title, rows, extra content, Optimise section · Reset ===================== -->
|
||||
<ControlTemplate x:Key="Template.SectionPanel" TargetType="ContentControl">
|
||||
<Border Style="{StaticResource Border.EditorPanel}">
|
||||
<DockPanel>
|
||||
<TextBlock DockPanel.Dock="Top" Text="{Binding Header}" Style="{StaticResource Text.Section}" Margin="0,0,0,14" />
|
||||
<Grid DockPanel.Dock="Bottom" Margin="0,12,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Button Content="{l:Loc Editor.OptimiseSection}" Command="{Binding OptimiseCommand}" ToolTip="{Binding OptimiseToolTip}" ToolTipService.ShowOnDisabled="True" />
|
||||
<Button Grid.Column="1" Style="{StaticResource Button.SectionReset}" Content="{l:Loc Editor.Reset}" Margin="8,0,0,0" Command="{Binding ResetCommand}"
|
||||
ToolTip="{Binding ResetToolTip}" Visibility="{Binding CanReset, Converter={StaticResource BoolToVisibility}}" />
|
||||
</Grid>
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
|
||||
<StackPanel IsEnabled="{Binding Editor.IsEditable}" ToolTip="{Binding Editor.LockedToolTip}" ToolTipService.ShowOnDisabled="True">
|
||||
<ItemsControl ItemsSource="{Binding Rows}" Focusable="False" />
|
||||
<ContentPresenter />
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</ControlTemplate>
|
||||
|
||||
<!--
|
||||
Analysis (owner review 1, R7): where the analysis stands, what it measured, the path's other steps with where each
|
||||
stands (a click opens one), and Analyse. Render stays the screen's one primary button.
|
||||
-->
|
||||
<DataTemplate DataType="{x:Type e:AnalysisTab}">
|
||||
<Border Style="{StaticResource Border.EditorPanel}">
|
||||
<DockPanel>
|
||||
<TextBlock DockPanel.Dock="Top" Text="{Binding Header}" Style="{StaticResource Text.Section}" Margin="0,0,0,10" />
|
||||
<ui:StatusGlyph DockPanel.Dock="Top" Kind="{Binding StateKind}" Text="{Binding StateText}" ToolTip="{Binding StepToolTip}" Margin="0,0,0,14" />
|
||||
<Button DockPanel.Dock="Bottom" Margin="0,12,0,0" HorizontalAlignment="Left" Content="{l:Loc Editor.Analyse}" Command="{Binding Editor.AnalyseCommand}"
|
||||
ToolTip="{Binding Editor.AnalyseToolTip}" ToolTipService.ShowOnDisabled="True" />
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
|
||||
<StackPanel>
|
||||
<ItemsControl ItemsSource="{Binding Rows}" Focusable="False" />
|
||||
<TextBlock Text="{l:Loc Editor.Path}" Style="{StaticResource Text.Section}" Margin="0,8,0,8" />
|
||||
<ItemsControl ItemsSource="{Binding PathSteps}" Focusable="False">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type e:EditorTab}">
|
||||
<Button Style="{StaticResource Button.Finding}" Command="{Binding Editor.GoToStepCommand}" CommandParameter="{Binding}" ToolTip="{Binding StepToolTip}"
|
||||
AutomationProperties.Name="{Binding Header}" AutomationProperties.ItemStatus="{Binding StateText}">
|
||||
<DockPanel>
|
||||
<Control DockPanel.Dock="Left" Template="{StaticResource Template.StepBadge}" Focusable="False" IsTabStop="False" VerticalAlignment="Center" />
|
||||
<TextBlock DockPanel.Dock="Left" Text="{Binding Header}" VerticalAlignment="Center" Margin="8,0" />
|
||||
<TextBlock Text="{Binding StateText}" Style="{StaticResource Text.Secondary}" VerticalAlignment="Center" TextAlignment="Right"
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
</DockPanel>
|
||||
</Button>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
|
||||
<DataTemplate DataType="{x:Type e:ExposureTab}">
|
||||
<ContentControl Template="{StaticResource Template.SectionPanel}" Focusable="False" />
|
||||
</DataTemplate>
|
||||
|
||||
<DataTemplate DataType="{x:Type e:MotionTab}">
|
||||
<ContentControl Template="{StaticResource Template.SectionPanel}" Focusable="False" />
|
||||
</DataTemplate>
|
||||
|
||||
<DataTemplate DataType="{x:Type e:TimeTab}">
|
||||
<ContentControl Template="{StaticResource Template.SectionPanel}" Focusable="False" />
|
||||
</DataTemplate>
|
||||
|
||||
<DataTemplate DataType="{x:Type e:StackTab}">
|
||||
<ContentControl Template="{StaticResource Template.SectionPanel}" Focusable="False" />
|
||||
</DataTemplate>
|
||||
|
||||
<!-- Camera: rows, then the selected keyframe's framing. -->
|
||||
<DataTemplate DataType="{x:Type e:CameraTab}">
|
||||
<ContentControl Template="{StaticResource Template.SectionPanel}" Focusable="False">
|
||||
<StackPanel Margin="0,4,0,0">
|
||||
<Grid MinHeight="26" Margin="0,0,0,8">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{Binding KeyText}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" Style="{StaticResource Text.Secondary}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Camera.Keys}" />
|
||||
<Button Grid.Column="1" Style="{StaticResource Button.Icon}" Width="28" Height="28" MinWidth="28" Margin="8,0,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.Plus}"
|
||||
Command="{Binding AddKeyCommand}" ToolTip="{Binding AddKeyToolTip}" ToolTipService.ShowOnDisabled="True"
|
||||
AutomationProperties.Name="{l:Loc Editor.Camera.AddKey}" />
|
||||
<Button Grid.Column="2" Style="{StaticResource Button.Icon}" Width="28" Height="28" MinWidth="28" Margin="6,0,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.Minus}"
|
||||
Command="{Binding RemoveKeyCommand}" ToolTip="{Binding RemoveKeyToolTip}" ToolTipService.ShowOnDisabled="True"
|
||||
AutomationProperties.Name="{l:Loc Editor.Camera.RemoveKey}" />
|
||||
</Grid>
|
||||
<StackPanel Visibility="{Binding HasSelectedKey, Converter={StaticResource BoolToVisibility}}">
|
||||
<Grid MinHeight="24">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Editor.Camera.Zoom}" VerticalAlignment="Center" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.RowValue}" Text="{Binding SelectedZoomText}" />
|
||||
</Grid>
|
||||
<Slider Margin="0,6,0,12" Minimum="1" Maximum="4" SmallChange="0.05" LargeChange="0.25" Value="{Binding SelectedZoom}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Camera.Zoom}" AutomationProperties.Name="{l:Loc Editor.Camera.Zoom}" />
|
||||
<TextBlock Text="{l:Loc Editor.Camera.CenterX}" />
|
||||
<Slider Margin="0,6,0,12" Minimum="0" Maximum="1" SmallChange="0.01" LargeChange="0.1" Value="{Binding SelectedCenterX}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Camera.CenterX}" AutomationProperties.Name="{l:Loc Editor.Camera.CenterX}" />
|
||||
<TextBlock Text="{l:Loc Editor.Camera.CenterY}" />
|
||||
<Slider Margin="0,6,0,0" Minimum="0" Maximum="1" SmallChange="0.01" LargeChange="0.1" Value="{Binding SelectedCenterY}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Camera.CenterY}" AutomationProperties.Name="{l:Loc Editor.Camera.CenterY}" />
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
</ContentControl>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- Frames: hero, exclusions of the current frame, warnings of the analyses. -->
|
||||
<DataTemplate DataType="{x:Type e:FramesTab}">
|
||||
<ContentControl Template="{StaticResource Template.SectionPanel}" Focusable="False">
|
||||
<StackPanel>
|
||||
<Grid MinHeight="32" Margin="0,0,0,10">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{l:Loc Editor.Frames.HeroLabel}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.RowValue}" Text="{Binding HeroText}" Margin="8,0" />
|
||||
<Button Grid.Column="2" Style="{StaticResource Button.Icon}" ui:ButtonIcon.Glyph="{StaticResource Icon.Hero}" Command="{Binding SetHeroCommand}"
|
||||
ToolTip="{Binding HeroToolTip}" ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{l:Loc Editor.Frames.SetHero}" />
|
||||
</Grid>
|
||||
<Grid MinHeight="32" Margin="0,0,0,14">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<StackPanel VerticalAlignment="Center">
|
||||
<TextBlock Text="{l:Loc Editor.Frames.ExcludedLabel}" TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Text="{Binding ExcludedText}" Style="{StaticResource Text.Secondary}" TextTrimming="CharacterEllipsis" />
|
||||
</StackPanel>
|
||||
<Button Grid.Column="1" Content="{Binding CurrentExcludeText}" Command="{Binding ToggleExcludeCommand}" ToolTip="{Binding CurrentExcludeToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" Margin="8,0,0,0" />
|
||||
</Grid>
|
||||
<!-- The findings about single frames (the Analysis step lists every finding). -->
|
||||
<TextBlock Text="{l:Loc Editor.Frames.FrameWarnings}" Style="{StaticResource Text.Section}" Margin="0,0,0,8" />
|
||||
<TextBlock Text="{l:Loc Editor.Frames.NoFrameWarnings}" Style="{StaticResource Text.Secondary}"
|
||||
Visibility="{Binding HasFindings, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
<ItemsControl ItemsSource="{Binding Findings}" Focusable="False">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type e:FindingItem}">
|
||||
<Button Style="{StaticResource Button.Finding}" Command="{Binding DataContext.SeekCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
|
||||
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Editor.Frames.Finding}">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ui:StatusGlyph Kind="{Binding Kind}" VerticalAlignment="Top" Margin="0,1,6,0" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding Text}" TextWrapping="Wrap" FontSize="{StaticResource Size.Secondary}" />
|
||||
</Grid>
|
||||
</Button>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</ContentControl>
|
||||
</DataTemplate>
|
||||
|
||||
<!-- Export: the Output panel (Export.html aside). -->
|
||||
<DataTemplate DataType="{x:Type e:ExportTab}">
|
||||
<Border Style="{StaticResource Border.EditorPanel}">
|
||||
<DockPanel>
|
||||
<TextBlock DockPanel.Dock="Top" Text="{Binding Title}" Style="{StaticResource Text.Section}" Margin="0,0,0,12" TextTrimming="CharacterEllipsis" />
|
||||
<StackPanel DockPanel.Dock="Bottom" Margin="0,12,0,0">
|
||||
<Grid Margin="0,0,0,8">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Button Content="{l:Loc Editor.Export.AddToQueue}" Command="{Binding AddToQueueCommand}" ToolTip="{Binding AddToQueueToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" />
|
||||
<Button Grid.Column="1" Content="{l:Loc Editor.Export.Batch}" Margin="8,0,0,0" Command="{Binding BatchCommand}" ToolTip="{Binding BatchToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" />
|
||||
</Grid>
|
||||
<Button Style="{StaticResource Button.Primary}" Height="36" Content="{l:Loc Editor.Export.RenderNow}" Command="{Binding RenderNowCommand}"
|
||||
ToolTip="{Binding Editor.RenderToolTip}" ToolTipService.ShowOnDisabled="True" />
|
||||
<DockPanel Margin="0,8,0,0">
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Editor.Export.HistoryLink}" Command="{Binding HistoryCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Export.History}" Margin="6,0,0,0" Visibility="{Binding CanOpenHistory, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Editor.Export.Reveal}" Command="{Binding RevealLastCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Render.Reveal}" Margin="6,0,0,0" Visibility="{Binding CanReveal, Converter={StaticResource BoolToVisibility}}" />
|
||||
<TextBlock Text="{Binding HistoryText}" Style="{StaticResource Text.Faint}" FontSize="{StaticResource Size.Chip}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"
|
||||
ToolTip="{Binding HistoryText}" />
|
||||
</DockPanel>
|
||||
<!-- A .chronos project file that opens this sequence with these settings (BRIEF §18). -->
|
||||
<Button Style="{StaticResource Button.Link}" HorizontalAlignment="Left" Margin="0,8,0,0" Content="{l:Loc Editor.ProjectFile.Save}"
|
||||
Command="{Binding SaveProjectCommand}" ToolTip="{Binding SaveProjectToolTip}" ToolTipService.ShowOnDisabled="True" />
|
||||
<!-- This PC's settings kept by "Save both" (sync conflicts): the newest, or another from the menu, becomes the project as one undo step. -->
|
||||
<v:SplitButton Margin="0,8,0,0" HorizontalAlignment="Left" Content="{Binding RestoreText}" Command="{Binding RestoreCommand}"
|
||||
ItemsSource="{Binding SavedCopies}" DisplayMemberPath="Label" SelectedItem="{Binding SelectedCopy}" ToolTip="{Binding RestoreToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True"
|
||||
DropDownToolTip="{l:Loc Tooltips.Editor.Export.RestoreChoice}" AutomationProperties.Name="{l:Loc Editor.Export.RestoreName}"
|
||||
Visibility="{Binding HasSavedCopies, Converter={StaticResource BoolToVisibility}}" />
|
||||
</StackPanel>
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
|
||||
<StackPanel IsEnabled="{Binding Editor.IsEditable}" ToolTip="{Binding Editor.LockedToolTip}" ToolTipService.ShowOnDisabled="True">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="{StaticResource Editor.Grid.Label}" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<TextBlock Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.Container}" ToolTip="{l:Loc Editor.Export.Container}" />
|
||||
<ComboBox Grid.Column="1" Margin="0,0,0,8" ItemsSource="{Binding Containers}" SelectedItem="{Binding SelectedContainer}" DisplayMemberPath="Label"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Export.Container}" AutomationProperties.Name="{l:Loc Editor.Export.Container}" />
|
||||
|
||||
<TextBlock Grid.Row="1" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.Codec}" ToolTip="{l:Loc Editor.Export.Codec}" />
|
||||
<ComboBox Grid.Row="1" Grid.Column="1" Margin="0,0,0,8" ItemsSource="{Binding CodecChoices}" SelectedItem="{Binding SelectedCodec}" DisplayMemberPath="Label"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Export.Codec}" AutomationProperties.Name="{l:Loc Editor.Export.Codec}" />
|
||||
|
||||
<TextBlock Grid.Row="2" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.Resolution}" ToolTip="{l:Loc Editor.Export.Resolution}" />
|
||||
<Grid Grid.Row="2" Grid.Column="1" Margin="0,0,0,8">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" MinWidth="56" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" MinWidth="56" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBox Style="{StaticResource TextBox.Number}" Width="NaN" Text="{Binding Width.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding Width}" ToolTip="{Binding Width.ToolTip}" AutomationProperties.Name="{l:Loc Editor.Export.Width}" />
|
||||
<TextBlock Grid.Column="1" Text="×" Foreground="{DynamicResource Brush.TextFaint}" VerticalAlignment="Center" Margin="6,0" />
|
||||
<TextBox Grid.Column="2" Style="{StaticResource TextBox.Number}" Width="NaN" Text="{Binding Height.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding Height}" ToolTip="{Binding Height.ToolTip}" AutomationProperties.Name="{l:Loc Editor.Export.Height}" />
|
||||
<TextBlock Grid.Column="3" Text="{Binding AspectText}" Style="{StaticResource Text.Hint}" FontSize="{StaticResource Size.Secondary}" Margin="6,0,0,0" />
|
||||
</Grid>
|
||||
|
||||
<TextBlock Grid.Row="3" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.FrameRate}" ToolTip="{l:Loc Editor.Export.FrameRate}" />
|
||||
<Grid Grid.Row="3" Grid.Column="1" Margin="0,0,0,8">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ComboBox ItemsSource="{Binding FrameRates}" SelectedItem="{Binding SelectedFrameRate}" DisplayMemberPath="Label"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Export.FrameRate}" AutomationProperties.Name="{l:Loc Editor.Export.FrameRate}" />
|
||||
<Border Grid.Column="1" Style="{StaticResource Pill.Auto}" Margin="8,0,0,0" ToolTip="{Binding FrameRateAutoToolTip}"
|
||||
Visibility="{Binding IsFrameRateAuto, Converter={StaticResource BoolToVisibility}}">
|
||||
<TextBlock Text="{l:Loc Common.Auto}" FontSize="{StaticResource Size.Chip}" Foreground="{DynamicResource Brush.Accent}" VerticalAlignment="Center" />
|
||||
</Border>
|
||||
<Button Grid.Column="1" Style="{StaticResource Button.IconSubtle}" Width="26" Height="26" Margin="8,0,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.Reset}"
|
||||
Command="{Binding ResetFrameRateCommand}" ToolTip="{l:Loc Tooltips.Editor.Export.FrameRateReset}" AutomationProperties.Name="{l:Loc Editor.ResetToAuto}"
|
||||
Visibility="{Binding IsFrameRateAuto, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
</Grid>
|
||||
|
||||
<TextBlock Grid.Row="4" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.Quality}" ToolTip="{l:Loc Editor.Export.Quality}" />
|
||||
<Grid Grid.Row="4" Grid.Column="1" Margin="0,0,0,8" MinHeight="32">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="64" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Slider Minimum="1" Maximum="{Binding QualityMaximum}" SmallChange="1" LargeChange="5" IsSnapToTickEnabled="True" TickFrequency="1" Value="{Binding Quality}"
|
||||
IsEnabled="{Binding IsQualityApplicable}" ToolTip="{Binding QualityToolTip}" AutomationProperties.Name="{l:Loc Editor.Export.Quality}"
|
||||
VerticalAlignment="Center" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.RowValue}" Text="{Binding QualityText}" Margin="8,0,0,0"
|
||||
Visibility="{Binding IsQualityApplicable, Converter={StaticResource BoolToVisibility}}" />
|
||||
<TextBlock Grid.Column="1" Style="{StaticResource Text.NotApplicable}" Text="{l:Loc Common.NotApplicable}" ToolTip="{Binding QualityNotApplicable}" Margin="8,0,0,0"
|
||||
Visibility="{Binding IsQualityApplicable, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
|
||||
</Grid>
|
||||
|
||||
<TextBlock Grid.Row="5" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.Encoder}" ToolTip="{l:Loc Editor.Export.Encoder}" />
|
||||
<Grid Grid.Row="5" Grid.Column="1" Margin="0,0,0,8">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ComboBox ItemsSource="{Binding Encoders}" SelectedItem="{Binding SelectedEncoder}" DisplayMemberPath="Label" IsEnabled="{Binding CanChooseEncoder}"
|
||||
ToolTip="{Binding EncoderToolTip}" ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{l:Loc Editor.Export.Encoder}" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding EncoderKind}" FontSize="{StaticResource Size.Secondary}" VerticalAlignment="Center" Margin="8,0,0,0">
|
||||
<TextBlock.Style>
|
||||
<Style TargetType="TextBlock">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsHardware}" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Success}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</TextBlock.Style>
|
||||
</TextBlock>
|
||||
</Grid>
|
||||
|
||||
<TextBlock Grid.Row="6" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.Colour}" ToolTip="{l:Loc Editor.Export.Colour}" />
|
||||
<ComboBox Grid.Row="6" Grid.Column="1" Margin="0,0,0,8" ItemsSource="{Binding Depths}" SelectedItem="{Binding SelectedDepth}" DisplayMemberPath="Label"
|
||||
IsEnabled="{Binding CanChooseDepth}" ToolTip="{l:Loc Tooltips.Editor.Export.Colour}" ToolTipService.ShowOnDisabled="True"
|
||||
AutomationProperties.Name="{l:Loc Editor.Export.Colour}" />
|
||||
|
||||
<TextBlock Grid.Row="7" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.FileName}" ToolTip="{l:Loc Editor.Export.FileName}" />
|
||||
<TextBox Grid.Row="7" Grid.Column="1" Margin="0,0,0,8" Text="{Binding NameTemplate.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
|
||||
shell:EditBehavior.Field="{Binding NameTemplate}" ToolTip="{Binding NameTemplate.ToolTip}" AutomationProperties.Name="{l:Loc Editor.Export.FileName}" />
|
||||
|
||||
<TextBlock Grid.Row="8" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.SaveTo}" ToolTip="{l:Loc Editor.Export.SaveTo}" />
|
||||
<!-- The folder ends in an ellipsis (its full path is in the tooltip). -->
|
||||
<ComboBox Grid.Row="8" Grid.Column="1" ItemsSource="{Binding SaveChoices}" SelectedItem="{Binding SelectedSave}" IsEnabled="{Binding CanChooseFolder}"
|
||||
ToolTip="{Binding SaveToolTip}" ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{l:Loc Editor.Export.SaveTo}">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type e:SaveChoice}">
|
||||
<TextBlock Text="{Binding Label}" TextTrimming="CharacterEllipsis" />
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<!-- Export.html "Sync" (12 px): also send the render to the server the sequence is linked to. Under the folder rather than beside
|
||||
it, as in the mockup, so that neither is cut in the 194 px field column in longer languages. -->
|
||||
<CheckBox Grid.Row="9" Grid.Column="1" Margin="0,6,0,0" HorizontalAlignment="Left" FontSize="{StaticResource Size.Secondary}"
|
||||
Content="{l:Loc Editor.Export.Sync}" IsChecked="{Binding SyncToServer}" IsEnabled="{Binding CanSync}" ToolTip="{Binding SyncToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" />
|
||||
</Grid>
|
||||
|
||||
<Border Style="{StaticResource Border.Card}" Margin="0,12,0,0" Padding="12,10">
|
||||
<StackPanel>
|
||||
<DockPanel>
|
||||
<TextBlock DockPanel.Dock="Right" Text="{Binding EstimatedSize}" Style="{StaticResource Text.Number}" FontSize="{StaticResource Size.Secondary}" />
|
||||
<TextBlock Text="{l:Loc Editor.Export.Size}" Style="{StaticResource Text.Secondary}" />
|
||||
</DockPanel>
|
||||
<DockPanel Margin="0,4,0,0">
|
||||
<TextBlock DockPanel.Dock="Right" Text="{Binding EstimatedTime}" FontSize="{StaticResource Size.Secondary}" TextTrimming="CharacterEllipsis" MaxWidth="180" />
|
||||
<TextBlock Text="{l:Loc Editor.Export.Time}" Style="{StaticResource Text.Secondary}" />
|
||||
</DockPanel>
|
||||
<DockPanel Margin="0,4,0,0">
|
||||
<TextBlock DockPanel.Dock="Right" Text="{Binding ResultName}" FontSize="{StaticResource Size.Secondary}" TextTrimming="CharacterEllipsis" MaxWidth="180"
|
||||
ToolTip="{Binding ResultName}" />
|
||||
<TextBlock Text="{l:Loc Editor.Export.Result}" Style="{StaticResource Text.Secondary}" />
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<ItemsControl ItemsSource="{Binding Notices}" Margin="0,8,0,0" Focusable="False">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<Grid Margin="0,4,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ui:Icon Glyph="{StaticResource Icon.Warning}" Foreground="{DynamicResource Brush.Warning}" VerticalAlignment="Top" Margin="0,1,6,0" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding}" TextWrapping="Wrap" FontSize="{StaticResource Size.Secondary}" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</DataTemplate>
|
||||
</ResourceDictionary>
|
||||
@@ -0,0 +1,422 @@
|
||||
using Chronos.Core.Advice;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// One sequence open in the editor (BRIEF §12.3): its content, the advisor's view of it (§10.3), the project with undo
|
||||
/// and redo, and the actions of every section — edit, Optimise (§10.4), Reset, exclusions and hero, analysis and render
|
||||
/// jobs. Every change is saved shortly after it is made (<see cref="ProjectSaver"/>); a change stored meanwhile by
|
||||
/// someone else (an analysis job, another client) is merged in. On a server sequence, settings both sides changed to
|
||||
/// different values wait for the user's choice (<see cref="Conflict"/>). Frames inserted under the editor (a sync
|
||||
/// download, an import of earlier photos, a scan) are read again before the next save or render, and the project's frame
|
||||
/// positions, its undo steps included, move with their frames as the stored ones did. Call from one thread (the UI thread).
|
||||
/// </summary>
|
||||
public sealed class EditorSession : IAsyncDisposable
|
||||
{
|
||||
public static readonly TimeSpan DefaultSaveDelay = TimeSpan.FromMilliseconds(400);
|
||||
|
||||
/// <summary>Times a save reads the frames again when frames keep changing under it.</summary>
|
||||
private const int FollowAttempts = 3;
|
||||
|
||||
/// <summary>Sections "Optimise all" walks through, in panel order.</summary>
|
||||
public static IReadOnlyList<AdvisorSection> OptimisedSections { get; } =
|
||||
[AdvisorSection.Frames, AdvisorSection.Timing, AdvisorSection.Exposure, AdvisorSection.Motion, AdvisorSection.Camera, AdvisorSection.Export];
|
||||
|
||||
private readonly IReadOnlyList<EncoderCapability> _codecs;
|
||||
private readonly ProjectSaver _saver;
|
||||
private ProjectSettings _basis;
|
||||
|
||||
/// <summary>
|
||||
/// The sequence being read again (<see cref="BeginReadAsync"/>) until its content is taken: saves and other reads wait
|
||||
/// for it.
|
||||
/// </summary>
|
||||
private Task _reading = Task.CompletedTask;
|
||||
|
||||
public EditorSession(ISequenceSource source, SequenceContent content, IReadOnlyList<EncoderCapability> codecs, TimeSpan? saveDelay = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(source);
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
Source = source;
|
||||
_codecs = codecs ?? [];
|
||||
_basis = content.Project;
|
||||
History = new ProjectHistory(content.Project);
|
||||
History.Changed += OnProjectChanged;
|
||||
_saver = new ProjectSaver(SaveAsync, saveDelay ?? DefaultSaveDelay);
|
||||
_saver.Failed += OnSaveFailed;
|
||||
(Content, Context, Advice, Presets) = Analyse(content, _codecs);
|
||||
}
|
||||
|
||||
/// <summary>The project changed (edit, undo, redo, Optimise, a merge).</summary>
|
||||
public event Action? ProjectChanged;
|
||||
|
||||
/// <summary>The sequence was read again (after an analysis): frames, reports, advice and presets.</summary>
|
||||
public event Action? ContentChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Saving the project failed (raised once per run of failures; the save is retried until it succeeds). A conflict
|
||||
/// raises <see cref="ConflictFound"/> instead.
|
||||
/// </summary>
|
||||
public event Action<Exception>? SaveFailed;
|
||||
|
||||
/// <summary>A save met settings changed on the server too (<see cref="Conflict"/> was null): the user picks a side.</summary>
|
||||
public event Action<ProjectConflictException>? ConflictFound;
|
||||
|
||||
public ISequenceSource Source { get; }
|
||||
|
||||
/// <summary>A server sequence edited with proxies: saved, analysed and rendered on the server.</summary>
|
||||
public bool IsRemote => Source.IsRemote;
|
||||
|
||||
/// <summary>The project is shown, not changed (<see cref="ISequenceSource.IsReadOnly"/>): edits, undo and redo do nothing.</summary>
|
||||
public bool IsReadOnly => Source.IsReadOnly;
|
||||
|
||||
public SequenceContent Content { get; private set; }
|
||||
|
||||
public SequenceContext Context { get; private set; }
|
||||
|
||||
/// <summary>The advisor's recommendations and findings for the current analyses.</summary>
|
||||
public AdvisorResult Advice { get; private set; }
|
||||
|
||||
/// <summary>Sequence presets that fit the content, best first (BRIEF §10.3).</summary>
|
||||
public IReadOnlyList<SequencePreset> Presets { get; private set; }
|
||||
|
||||
public ProjectHistory History { get; }
|
||||
|
||||
public ProjectSettings Project => History.Current;
|
||||
|
||||
/// <summary>A change is waiting for its save, being saved, or waiting for a retry after a failed save.</summary>
|
||||
public bool HasPendingSave => _saver.HasPendingChanges;
|
||||
|
||||
/// <summary>Why the pending change could not be stored; null when the last save succeeded.</summary>
|
||||
public Exception? LastSaveError => _saver.LastError;
|
||||
|
||||
/// <summary>
|
||||
/// Settings this editor and someone on the server changed to different values, as the last save found them; null
|
||||
/// when there are none. Saves wait (they are retried and meet it again) until <see cref="ResolveConflict"/>.
|
||||
/// </summary>
|
||||
public ProjectConflictException? Conflict { get; private set; }
|
||||
|
||||
/// <summary>Applies <paramref name="change"/> as an undoable step; false when it changes nothing.</summary>
|
||||
/// <param name="mergeKey">Consecutive edits with the same key are one undo step (a slider drag).</param>
|
||||
public bool Edit(Func<ProjectSettings, ProjectSettings> change, string? mergeKey = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(change);
|
||||
return !IsReadOnly && History.Apply(change(Project), mergeKey);
|
||||
}
|
||||
|
||||
/// <summary>The drag or key press behind a run of merged edits ended (<see cref="ProjectHistory.EndRun"/>).</summary>
|
||||
public void EndEditRun() => History.EndRun();
|
||||
|
||||
public bool Undo() => !IsReadOnly && History.Undo();
|
||||
|
||||
public bool Redo() => !IsReadOnly && History.Redo();
|
||||
|
||||
/// <summary>"Optimise section": the advisor's heavier decisions for <paramref name="section"/>, one undo step; returns what changed.</summary>
|
||||
public IReadOnlyList<SettingChange> Optimise(AdvisorSection section) => Optimise([section]);
|
||||
|
||||
/// <summary>"Optimise all": every section, one undo step.</summary>
|
||||
public IReadOnlyList<SettingChange> OptimiseAll() => Optimise(OptimisedSections);
|
||||
|
||||
/// <summary>"Reset": the section's Auto settings back to Auto.</summary>
|
||||
public bool ResetSection(AdvisorSection section) => Edit(p => EditorSettings.ResetSection(p, section));
|
||||
|
||||
/// <summary>Adds frames to, or removes them from, the project's exclusions.</summary>
|
||||
public bool SetExcluded(IEnumerable<int> frames, bool excluded)
|
||||
{
|
||||
var chosen = frames.Where(i => (uint)i < (uint)Content.Count).ToHashSet();
|
||||
return Edit(p => p with
|
||||
{
|
||||
ExcludedFrames = excluded ? [.. p.ExcludedFrames.Union(chosen).Order()] : [.. p.ExcludedFrames.Where(i => !chosen.Contains(i))],
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Makes <paramref name="frame"/> the hero frame (sequence thumbnail).</summary>
|
||||
public bool SetHero(int frame) => (uint)frame < (uint)Content.Count && Edit(p => p with { HeroFrame = frame });
|
||||
|
||||
/// <summary>
|
||||
/// Applies a sequence preset (BRIEF §10.3) as one undoable step: its timing, exposure, motion, aspect and export
|
||||
/// preset; the user's frames (exclusions, hero), crop, keyframes, remap curve, exposure offset and output naming stay.
|
||||
/// </summary>
|
||||
public bool ApplyPreset(SequencePreset preset)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(preset);
|
||||
var s = preset.Settings;
|
||||
return Edit(p => p with
|
||||
{
|
||||
Timing = s.Timing with { RemapCurve = p.Timing.RemapCurve, FitToSeconds = p.Timing.FitToSeconds },
|
||||
Exposure = s.Exposure with { ExposureOffsetEv = p.Exposure.ExposureOffsetEv, HighlightKnee = p.Exposure.HighlightKnee },
|
||||
Motion = s.Motion,
|
||||
Camera = p.Camera with { Aspect = s.Camera.Aspect },
|
||||
Export = p.Export with { Preset = s.Export.Preset, Overrides = new ExportOverrides() },
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A render of <paramref name="export"/> with the project as it is now (the job embeds it, so a render queued before
|
||||
/// the save lands still renders what the user sees).
|
||||
/// </summary>
|
||||
public ArchiveJobRequest RenderRequest(ExportSettings export, bool useProxies = false) =>
|
||||
ProcessingJobs.Render(Content.Sequence, export, Content.SourceWidth, Content.SourceHeight, Project with { Export = export }, useProxies);
|
||||
|
||||
/// <summary>
|
||||
/// The jobs that render <paramref name="export"/> and its batch: one job on this PC (the sequence is prepared once),
|
||||
/// one per preset on a server, where a render node uploads one file per job (BRIEF §14.7).
|
||||
/// </summary>
|
||||
public IReadOnlyList<ArchiveJobRequest> RenderRequests(ExportSettings export) => IsRemote
|
||||
? ProcessingJobs.RenderEach(Content.Sequence, export, Content.SourceWidth, Content.SourceHeight, Project with { Export = export })
|
||||
: [RenderRequest(export)];
|
||||
|
||||
/// <summary>
|
||||
/// Makes a "Save both" copy of this PC's settings the project, as one undoable step; null when it stores the same values.
|
||||
/// </summary>
|
||||
/// <returns>The restore, which its toast can take back while it is the last change.</returns>
|
||||
/// <exception cref="System.IO.InvalidDataException">The copy cannot be read.</exception>
|
||||
public async Task<ProjectRestore?> RestoreAsync(SavedCopy copy)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(copy);
|
||||
var restored = await Task.Run(() => SavedCopies.Read(copy));
|
||||
var before = Project;
|
||||
return Edit(_ => restored) ? new ProjectRestore(this, before, Project) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settles <see cref="Conflict"/> against the server's settings as the last save read them. Both choices first take
|
||||
/// in what only the server changed (like any merge, without an undo step). <paramref name="keepMine"/> then saves
|
||||
/// the editor's values of the settings both changed; otherwise the server's values become the project as one
|
||||
/// undoable step, so Ctrl+Z brings the editor's back (and saves them).
|
||||
/// </summary>
|
||||
/// <returns>False when there is no conflict to settle (a later save already went through).</returns>
|
||||
public bool ResolveConflict(bool keepMine)
|
||||
{
|
||||
if (Conflict is not { Server: var theirs }) return false;
|
||||
Conflict = null;
|
||||
var basis = _basis;
|
||||
_basis = theirs;
|
||||
History.Replace(ProjectMerge.Merge(basis, Project, theirs));
|
||||
if (!keepMine) History.Apply(ProjectMerge.Merge(basis, theirs, Project));
|
||||
// The change waiting for its retry goes now, on top of the server's settings.
|
||||
_ = _saver.FlushAsync();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The export of the project with preset <paramref name="presetId"/> chosen (own values, no batch).</summary>
|
||||
public ExportSettings ExportFor(string presetId) =>
|
||||
Project.Export with { Preset = Project.Export.Preset.WithManual(presetId), Overrides = new ExportOverrides(), Batch = [] };
|
||||
|
||||
public ArchiveJobRequest AnalysisRequest() => ProcessingJobs.DeepAnalysis([Content.Sequence.Id], Content.Sequence.DisplayTitle);
|
||||
|
||||
public Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken = default) => Source.SubmitAsync(request, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Makes the project's frame positions name the sequence's frames as they are now, before the project is taken along
|
||||
/// (a render embeds it): frames inserted since the last read (a sync download, an import of earlier photos, a scan)
|
||||
/// are read again and the positions follow them (<see cref="ReloadAsync"/>). A server sequence whose frames changed
|
||||
/// becomes outdated instead (<see cref="ISequenceSource.IsOutdated"/>: read-only, its renders refused).
|
||||
/// </summary>
|
||||
public async Task EnsureFramesAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
while (!_reading.IsCompleted) await _reading;
|
||||
var current = await Source.FramesCurrentAsync(cancellationToken);
|
||||
// A read that began meanwhile (a save that met the new frames) may have taken them already: it ends first.
|
||||
while (!_reading.IsCompleted) await _reading;
|
||||
if (!current && !IsRemote) await ReloadAsync(cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the sequence again (an analysis finished): new reports and advice, the frames with the project's positions
|
||||
/// following them (<see cref="Follow"/>), the stored project merged into the open one. Saves wait until it is taken,
|
||||
/// and a read waits for the one under way, so each follows the frames the one before it took.
|
||||
/// </summary>
|
||||
public async Task ReloadAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _saver.FlushAsync();
|
||||
var taken = await BeginReadAsync();
|
||||
try
|
||||
{
|
||||
var content = await Source.LoadAsync(cancellationToken);
|
||||
Follow(content);
|
||||
// A server's settings that conflict with the editor's waiting change are not merged over it: that change's
|
||||
// retry meets them and asks (Conflict).
|
||||
if (Conflict is null && (!IsRemote || ProjectMerge.Conflicts(_basis, Project, content.Project).Count == 0))
|
||||
{
|
||||
var merged = ProjectMerge.Merge(_basis, Project, content.Project);
|
||||
_basis = content.Project;
|
||||
History.Replace(merged);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
taken.SetResult();
|
||||
}
|
||||
ContentChanged?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>Stores pending changes now; false when the save failed (the change stays pending and is retried).</summary>
|
||||
public Task<bool> FlushAsync() => _saver.FlushAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Stops retrying a change that could not be stored while the user decides about it (<see cref="ProjectSaver.HoldAsync"/>);
|
||||
/// end it with <see cref="KeepPending"/> or <see cref="DiscardPending"/>.
|
||||
/// </summary>
|
||||
/// <returns>True when a change is still not stored; false when a retry stored it meanwhile (nothing to decide).</returns>
|
||||
public Task<bool> HoldPendingAsync() => _saver.HoldAsync();
|
||||
|
||||
/// <summary>The user kept the change: it is retried in the background as before.</summary>
|
||||
public void KeepPending() => _saver.Release();
|
||||
|
||||
/// <summary>The user discarded the change: it is dropped and never written, and nothing more is saved (the editor closes).</summary>
|
||||
public void DiscardPending() => _saver.Stop();
|
||||
|
||||
/// <summary>
|
||||
/// Stores what is pending one last time, stops retrying and releases the source; callers that must not lose an edit
|
||||
/// flush and ask first (<c>SequenceViewModel.ConfirmCloseAsync</c>).
|
||||
/// </summary>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
History.Changed -= OnProjectChanged;
|
||||
if (!await _saver.FlushAsync()) Log.Warning("editor", $"The last change of {Content.Sequence.DisplayTitle} was not saved", _saver.LastError);
|
||||
_saver.Stop();
|
||||
await Source.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes <paramref name="content"/> as the sequence. Frames inserted or removed since the last read (a sync download,
|
||||
/// an import of earlier photos, a scan) moved the stored project's frame positions with their frames: the editor's
|
||||
/// project, its undo and redo steps and its basis move the same way (<see cref="ProjectSettings.FollowFrames"/>), so
|
||||
/// they keep naming the frames the user chose. Call while the read is under way (<see cref="BeginReadAsync"/>).
|
||||
/// </summary>
|
||||
private void Follow(SequenceContent content)
|
||||
{
|
||||
var before = Content.Frames.Select(f => f.Id).ToList();
|
||||
(Content, Context, Advice, Presets) = Analyse(content, _codecs);
|
||||
if (before.SequenceEqual(content.Frames.Select(f => f.Id))) return;
|
||||
var after = content.Frames;
|
||||
Log.Info("editor", $"The frames of {content.Sequence.DisplayTitle} changed while it was open; its frame positions follow them");
|
||||
_basis = Move(_basis);
|
||||
History.Remap(Move);
|
||||
|
||||
ProjectSettings Move(ProjectSettings project) =>
|
||||
NamesFrames(project) && ProjectSettings.FollowFrames(project.ToJson(), before, after) is { } moved ? ProjectSettings.FromJson(moved) : project;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Waits for the read under way (two jobs that end together read the sequence one after the other), then marks a new
|
||||
/// one under way until the returned source is completed.
|
||||
/// </summary>
|
||||
private async Task<TaskCompletionSource> BeginReadAsync()
|
||||
{
|
||||
while (!_reading.IsCompleted) await _reading;
|
||||
var taken = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_reading = taken.Task;
|
||||
return taken;
|
||||
}
|
||||
|
||||
/// <summary>Exclusions, a hero, keyframes or frames waiting for their photos: positions that follow frames.</summary>
|
||||
private static bool NamesFrames(ProjectSettings project) =>
|
||||
project.ExcludedFrames.Count > 0 || project.HeroFrame is not null || project.Camera.Keyframes.Count > 0 || project.PendingFrames is { Count: > 0 };
|
||||
|
||||
private static (SequenceContent, SequenceContext, AdvisorResult, IReadOnlyList<SequencePreset>) Analyse(SequenceContent content,
|
||||
IReadOnlyList<EncoderCapability> codecs)
|
||||
{
|
||||
var context = SequenceContext.FromFrames(content.Frames, codecs);
|
||||
return (content, context, Advisor.Recommend(content.Light, content.Deep, context), SequencePresets.Generate(content.Light, content.Deep, context));
|
||||
}
|
||||
|
||||
private IReadOnlyList<SettingChange> Optimise(IReadOnlyList<AdvisorSection> sections)
|
||||
{
|
||||
if (IsReadOnly) return [];
|
||||
var settings = Project;
|
||||
var changes = new List<SettingChange>();
|
||||
foreach (var section in sections)
|
||||
{
|
||||
var result = Advisor.Optimise(section, settings, Advice);
|
||||
settings = result.Settings;
|
||||
changes.AddRange(result.Changes);
|
||||
}
|
||||
History.Apply(settings);
|
||||
return changes;
|
||||
}
|
||||
|
||||
private void OnSaveFailed(Exception ex, int failures)
|
||||
{
|
||||
// A conflict is retried without the network until the user settles it: noted once, when it is found.
|
||||
if (ex is ProjectConflictException) return;
|
||||
Log.Warning("editor", $"Saving the project of {Content.Sequence.DisplayTitle} failed (attempt {failures})", ex);
|
||||
if (failures == 1) SaveFailed?.Invoke(ex);
|
||||
}
|
||||
|
||||
private void OnProjectChanged()
|
||||
{
|
||||
_saver.Schedule(Project);
|
||||
ProjectChanged?.Invoke();
|
||||
}
|
||||
|
||||
private async Task SaveAsync(ProjectSettings project)
|
||||
{
|
||||
if (!_reading.IsCompleted)
|
||||
{
|
||||
// A read under way decides the frames the project's positions name. Once it is taken, the project as it is
|
||||
// then contains this change (projects are whole snapshots), with its positions on those frames.
|
||||
while (!_reading.IsCompleted) await _reading;
|
||||
project = Project;
|
||||
}
|
||||
ProjectSettings stored;
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
stored = await Source.SaveProjectAsync(project, _basis, CancellationToken.None);
|
||||
break;
|
||||
}
|
||||
catch (FramesChangedException) when (attempt < FollowAttempts)
|
||||
{
|
||||
// Frames were inserted under the editor and the stored positions moved with them: the frames are read
|
||||
// again (after a read under way, whose move this edit's snapshot missed), the project's positions follow
|
||||
// them, and the project as it is then, which contains this edit, is saved in the new order.
|
||||
var taken = await BeginReadAsync();
|
||||
try
|
||||
{
|
||||
Follow(await Source.LoadAsync(CancellationToken.None));
|
||||
}
|
||||
finally
|
||||
{
|
||||
taken.SetResult();
|
||||
}
|
||||
project = Project;
|
||||
ContentChanged?.Invoke();
|
||||
}
|
||||
catch (ProjectConflictException ex)
|
||||
{
|
||||
var found = Conflict is null;
|
||||
Conflict = ex;
|
||||
if (found)
|
||||
{
|
||||
Log.Info("editor", $"Settings of {Content.Sequence.DisplayTitle} changed on the server too: {string.Join(", ", ex.Differences.Select(d => d.Path))}");
|
||||
ConflictFound?.Invoke(ex);
|
||||
}
|
||||
throw;
|
||||
}
|
||||
}
|
||||
Conflict = null;
|
||||
_basis = stored;
|
||||
// Someone else's change was merged in: show it without an undo step (edits made since the save are kept).
|
||||
if (!ProjectMerge.SameValues(stored, project)) History.Replace(ProjectMerge.Merge(project, Project, stored));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A "Save both" copy made the project (<see cref="EditorSession.RestoreAsync"/>). Its Undo brings back the project from
|
||||
/// before as a new step, and only while the restore is still the last change: after another edit, an undo or a merged
|
||||
/// save it would take that change back instead.
|
||||
/// </summary>
|
||||
public sealed class ProjectRestore(EditorSession session, ProjectSettings before, ProjectSettings restored)
|
||||
{
|
||||
public bool CanUndo => ReferenceEquals(session.Project, restored);
|
||||
|
||||
public bool Undo() => CanUndo && session.Edit(_ => before);
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
using Chronos.Core.Advice;
|
||||
using Chronos.Core.Analysis;
|
||||
using Chronos.Core.Analysis.Deep;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Motion;
|
||||
using Chronos.Core.Project;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>An advisor-decided setting of the editor, whatever its value type.</summary>
|
||||
public interface IAutoSetting
|
||||
{
|
||||
/// <summary><see cref="AdvisorParameters"/> id.</summary>
|
||||
string Id { get; }
|
||||
|
||||
AdvisorSection Section { get; }
|
||||
|
||||
bool IsAuto(ProjectSettings project);
|
||||
|
||||
/// <summary>Drops the manual value so the advice applies.</summary>
|
||||
ProjectSettings Reset(ProjectSettings project);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One <see cref="Auto{T}"/> member of the project (BRIEF §10.4) and the value the engine uses when the advisor has
|
||||
/// none (<see cref="Fallback"/>, from the deep analysis when it measured one).
|
||||
/// </summary>
|
||||
public sealed class AutoSetting<T>(
|
||||
string id,
|
||||
AdvisorSection section,
|
||||
Func<ProjectSettings, Auto<T>> get,
|
||||
Func<ProjectSettings, Auto<T>, ProjectSettings> set,
|
||||
Func<ProjectSettings, DeepAnalysisReport?, T> fallback) : IAutoSetting
|
||||
where T : notnull
|
||||
{
|
||||
public string Id { get; } = id;
|
||||
|
||||
public AdvisorSection Section { get; } = section;
|
||||
|
||||
public Auto<T> Get(ProjectSettings project) => get(project);
|
||||
|
||||
public bool IsAuto(ProjectSettings project) => get(project).IsAuto;
|
||||
|
||||
/// <summary>The advisor's value, else what the engine uses without advice.</summary>
|
||||
public T AutoValue(ProjectSettings project, DeepAnalysisReport? deep) => get(project) is { HasAdvice: true, AutoValue: { } advised } ? advised : fallback(project, deep);
|
||||
|
||||
/// <summary>The value in force.</summary>
|
||||
public T Effective(ProjectSettings project, DeepAnalysisReport? deep) => get(project).Resolve(fallback(project, deep));
|
||||
|
||||
/// <summary>Touching the control: the value becomes manual.</summary>
|
||||
public ProjectSettings WithManual(ProjectSettings project, T value) => set(project, get(project).WithManual(value));
|
||||
|
||||
public ProjectSettings Reset(ProjectSettings project) => set(project, get(project).Reset());
|
||||
}
|
||||
|
||||
/// <summary>The Auto settings of the editor's sections, in panel order.</summary>
|
||||
public static class EditorSettings
|
||||
{
|
||||
public static readonly AutoSetting<TimingMode> TimingMode = new(AdvisorParameters.TimingMode, AdvisorSection.Timing,
|
||||
p => p.Timing.Mode, (p, a) => p with { Timing = p.Timing with { Mode = a } }, (_, _) => Core.Project.TimingMode.Constant);
|
||||
|
||||
/// <summary>Playback rate; without a value it equals the export frame rate (DECISIONS: export fps vs playback rate).</summary>
|
||||
public static readonly AutoSetting<string> FrameRate = new(AdvisorParameters.FrameRate, AdvisorSection.Timing,
|
||||
p => p.Timing.FrameRate, (p, a) => p with { Timing = p.Timing with { FrameRate = a } },
|
||||
(p, _) => FrameRateText.Format(ExportResolver.Resolve(p.Export).FrameRate));
|
||||
|
||||
public static readonly AutoSetting<bool> Deflicker = new(AdvisorParameters.Deflicker, AdvisorSection.Exposure,
|
||||
p => p.Exposure.Deflicker, (p, a) => p with { Exposure = p.Exposure with { Deflicker = a } }, (_, _) => false);
|
||||
|
||||
public static readonly AutoSetting<int> DeflickerWindow = new(AdvisorParameters.DeflickerWindow, AdvisorSection.Exposure,
|
||||
p => p.Exposure.DeflickerWindow, (p, a) => p with { Exposure = p.Exposure with { DeflickerWindow = a } },
|
||||
(_, deep) => deep?.Flicker.RecommendedWindow ?? DeflickerOptions.Default.Window);
|
||||
|
||||
public static readonly AutoSetting<double> DeflickerStrength = new(AdvisorParameters.DeflickerStrength, AdvisorSection.Exposure,
|
||||
p => p.Exposure.DeflickerStrength, (p, a) => p with { Exposure = p.Exposure with { DeflickerStrength = a } }, (_, _) => DeflickerOptions.Default.Strength);
|
||||
|
||||
public static readonly AutoSetting<RegionMode> Regions = new(AdvisorParameters.Regions, AdvisorSection.Exposure,
|
||||
p => p.Exposure.Regions, (p, a) => p with { Exposure = p.Exposure with { Regions = a } }, (_, _) => RegionMode.Off);
|
||||
|
||||
public static readonly AutoSetting<bool> HolyGrail = new(AdvisorParameters.HolyGrail, AdvisorSection.Exposure,
|
||||
p => p.Exposure.HolyGrail, (p, a) => p with { Exposure = p.Exposure with { HolyGrail = a } }, (_, _) => false);
|
||||
|
||||
public static readonly AutoSetting<int> TransitionLength = new(AdvisorParameters.TransitionLength, AdvisorSection.Exposure,
|
||||
p => p.Exposure.TransitionLength, (p, a) => p with { Exposure = p.Exposure with { TransitionLength = a } },
|
||||
(_, deep) => deep?.Exposure.TransitionLength ?? new HolyGrailOptions().SingleStepTransitionFrames);
|
||||
|
||||
public static readonly AutoSetting<bool> WhiteBalance = new(AdvisorParameters.WhiteBalanceSmoothing, AdvisorSection.Exposure,
|
||||
p => p.Exposure.WhiteBalanceSmoothing, (p, a) => p with { Exposure = p.Exposure with { WhiteBalanceSmoothing = a } }, (_, _) => false);
|
||||
|
||||
public static readonly AutoSetting<bool> MotionBlur = new(AdvisorParameters.MotionBlur, AdvisorSection.Motion,
|
||||
p => p.Motion.MotionBlur, (p, a) => p with { Motion = p.Motion with { MotionBlur = a } }, (_, _) => false);
|
||||
|
||||
public static readonly AutoSetting<double> ShutterAngle = new(AdvisorParameters.TargetShutterAngle, AdvisorSection.Motion,
|
||||
p => p.Motion.TargetShutterAngle, (p, a) => p with { Motion = p.Motion with { TargetShutterAngle = a } }, (_, _) => 180.0);
|
||||
|
||||
public static readonly AutoSetting<FlowQualitySetting> FlowQuality = new(AdvisorParameters.FlowQuality, AdvisorSection.Motion,
|
||||
p => p.Motion.FlowQuality, (p, a) => p with { Motion = p.Motion with { FlowQuality = a } }, (_, _) => FlowQualitySetting.Balanced);
|
||||
|
||||
public static readonly AutoSetting<bool> Stabilize = new(AdvisorParameters.Stabilize, AdvisorSection.Motion,
|
||||
p => p.Motion.Stabilize, (p, a) => p with { Motion = p.Motion with { Stabilize = a } }, (_, _) => false);
|
||||
|
||||
public static readonly AutoSetting<double> StabilizeSmoothing = new(AdvisorParameters.StabilizeSmoothing, AdvisorSection.Motion,
|
||||
p => p.Motion.StabilizeSmoothing, (p, a) => p with { Motion = p.Motion with { StabilizeSmoothing = a } }, (_, _) => new StabilizerOptions().SmoothingSigma);
|
||||
|
||||
public static readonly AutoSetting<string> Aspect = new(AdvisorParameters.Aspect, AdvisorSection.Camera,
|
||||
p => p.Camera.Aspect, (p, a) => p with { Camera = p.Camera with { Aspect = a } }, (_, _) => "source");
|
||||
|
||||
public static readonly AutoSetting<string> ExportPreset = new(AdvisorParameters.ExportPreset, AdvisorSection.Export,
|
||||
p => p.Export.Preset, (p, a) => p with { Export = p.Export with { Preset = a } }, (_, _) => ExportResolver.DefaultPresetId);
|
||||
|
||||
public static IReadOnlyList<IAutoSetting> All { get; } =
|
||||
[
|
||||
TimingMode, FrameRate, Deflicker, DeflickerWindow, DeflickerStrength, Regions, HolyGrail, TransitionLength, WhiteBalance,
|
||||
MotionBlur, ShutterAngle, FlowQuality, Stabilize, StabilizeSmoothing, Aspect, ExportPreset,
|
||||
];
|
||||
|
||||
/// <summary>"Reset": every Auto setting of <paramref name="section"/> back to Auto; stacking (no advice) back to off.</summary>
|
||||
public static ProjectSettings ResetSection(ProjectSettings project, AdvisorSection section)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
foreach (var setting in All)
|
||||
{
|
||||
if (setting.Section == section) project = setting.Reset(project);
|
||||
}
|
||||
return section == AdvisorSection.Stack ? project with { Stack = new StackSettings() } : project;
|
||||
}
|
||||
|
||||
/// <summary>True when every Auto setting of <paramref name="section"/> is in Auto.</summary>
|
||||
public static bool IsSectionAuto(ProjectSettings project, AdvisorSection section) =>
|
||||
All.Where(s => s.Section == section).All(s => s.IsAuto(project));
|
||||
|
||||
/// <summary>
|
||||
/// Whether <paramref name="setting"/> applies under the switches in force: the deflicker window, strength and regions
|
||||
/// with deflicker on, the transition length with holy grail on, the shutter angle with motion blur on, the flow quality
|
||||
/// with motion blur or interpolated timing, the stabiliser's smoothing with stabilisation on. A setting that does not
|
||||
/// apply shows n/a in its row (which cannot be taken over by hand then), and the Edit path asks nothing about it.
|
||||
/// </summary>
|
||||
public static bool Applies(IAutoSetting setting, ProjectSettings project, DeepAnalysisReport? deep)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(setting);
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
return setting.Id switch
|
||||
{
|
||||
AdvisorParameters.DeflickerWindow or AdvisorParameters.DeflickerStrength or AdvisorParameters.Regions => Deflicker.Effective(project, deep),
|
||||
AdvisorParameters.TransitionLength => HolyGrail.Effective(project, deep),
|
||||
AdvisorParameters.TargetShutterAngle => MotionBlur.Effective(project, deep),
|
||||
AdvisorParameters.FlowQuality => MotionBlur.Effective(project, deep) || TimingMode.Effective(project, deep) == Core.Project.TimingMode.Interpolated,
|
||||
AdvisorParameters.StabilizeSmoothing => Stabilize.Effective(project, deep),
|
||||
_ => true,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
<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:e="clr-namespace:Chronos.App.Editor">
|
||||
<!--
|
||||
Styles of the sequence editor (Editor.html, Export.html) on the kit of Chronos.Ui and the client styles. Brushes are
|
||||
DynamicResource; sizes and the kit's styles StaticResource.
|
||||
-->
|
||||
|
||||
<!-- Preview height against the measuring area: the editor favours the picture; the Analysis findings and the Export preset cards take more room. -->
|
||||
<GridLength x:Key="Editor.Grid.Preview">17*</GridLength>
|
||||
<GridLength x:Key="Editor.Grid.Measure">10*</GridLength>
|
||||
<GridLength x:Key="Editor.Grid.ExportPreview">9*</GridLength>
|
||||
<GridLength x:Key="Editor.Grid.ExportMeasure">12*</GridLength>
|
||||
<GridLength x:Key="Editor.Grid.Panel">320</GridLength>
|
||||
<!-- Label column of the Output panel (Export.html 96 px); labels end in an ellipsis and say it all in their tooltip. -->
|
||||
<GridLength x:Key="Editor.Grid.Label">96</GridLength>
|
||||
|
||||
<!-- Tools over the preview (Editor.html): 30 px, icon and label, chrome fill, accent when on. -->
|
||||
<Style x:Key="ToggleButton.PreviewTool" TargetType="ToggleButton" BasedOn="{StaticResource {x:Type ToggleButton}}">
|
||||
<Setter Property="MinWidth" Value="30" />
|
||||
<Setter Property="Height" Value="30" />
|
||||
<Setter Property="Padding" Value="10,0" />
|
||||
<!-- 6 px apart, also between two lines of tools (the line they sit on takes the bottom 6 px back). -->
|
||||
<Setter Property="Margin" Value="0,0,6,6" />
|
||||
<Setter Property="Background" Value="{DynamicResource Brush.Chrome}" />
|
||||
<Setter Property="ui:ControlState.HoverBackground" Value="{DynamicResource Brush.Card}" />
|
||||
<Setter Property="ToolTipService.ShowOnDisabled" Value="True" />
|
||||
</Style>
|
||||
|
||||
<!-- Icon-only tools (full screen, play, crop view): square, named for assistive technology. -->
|
||||
<Style x:Key="ToggleButton.PreviewToolIcon" TargetType="ToggleButton" BasedOn="{StaticResource ToggleButton.PreviewTool}">
|
||||
<Setter Property="Width" Value="30" />
|
||||
<Setter Property="Padding" Value="0" />
|
||||
</Style>
|
||||
|
||||
<Style x:Key="Button.PreviewTool" TargetType="Button" BasedOn="{StaticResource Button.Base}">
|
||||
<Setter Property="MinWidth" Value="30" />
|
||||
<Setter Property="Height" Value="30" />
|
||||
<Setter Property="Padding" Value="10,0" />
|
||||
<Setter Property="Margin" Value="0,0,6,6" />
|
||||
<Setter Property="Background" Value="{DynamicResource Brush.Chrome}" />
|
||||
<Setter Property="ui:ControlState.HoverBackground" Value="{DynamicResource Brush.Card}" />
|
||||
</Style>
|
||||
|
||||
<Style x:Key="Button.PreviewToolIcon" TargetType="Button" BasedOn="{StaticResource Button.PreviewTool}">
|
||||
<Setter Property="Width" Value="30" />
|
||||
<Setter Property="Padding" Value="0" />
|
||||
</Style>
|
||||
|
||||
<!-- Play / pause: the glyph follows the player. -->
|
||||
<Style x:Key="Button.PlayTool" TargetType="Button" BasedOn="{StaticResource Button.PreviewToolIcon}">
|
||||
<Setter Property="ui:ButtonIcon.Glyph" Value="{StaticResource Icon.Play}" />
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsPlaying}" Value="True">
|
||||
<Setter Property="ui:ButtonIcon.Glyph" Value="{StaticResource Icon.Pause}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
|
||||
<!-- Settings column (320 px panel, Editor.html aside). -->
|
||||
<Style x:Key="Border.EditorPanel" TargetType="Border" BasedOn="{StaticResource Border.Panel}">
|
||||
<Setter Property="Padding" Value="14" />
|
||||
</Style>
|
||||
|
||||
<!-- Value next to a row label: tabular, right-aligned. -->
|
||||
<Style x:Key="Text.RowValue" TargetType="TextBlock" BasedOn="{StaticResource Text.Number}">
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
<Setter Property="HorizontalAlignment" Value="Right" />
|
||||
<Setter Property="TextTrimming" Value="CharacterEllipsis" />
|
||||
</Style>
|
||||
|
||||
<!-- "n/a" with the reason in the tooltip (DESIGN §4 sliders). -->
|
||||
<Style x:Key="Text.NotApplicable" TargetType="TextBlock">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextFaint}" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
<Setter Property="HorizontalAlignment" Value="Right" />
|
||||
</Style>
|
||||
|
||||
<!-- Section Reset (Editor.html): stroke border, transparent fill, muted text. -->
|
||||
<Style x:Key="Button.SectionReset" TargetType="Button" BasedOn="{StaticResource Button.Base}">
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
|
||||
<Setter Property="ui:ControlState.HoverBackground" Value="{DynamicResource Brush.Card}" />
|
||||
<Setter Property="ToolTipService.ShowOnDisabled" Value="True" />
|
||||
</Style>
|
||||
|
||||
<!-- Sortable column header of the frame table (DESIGN §4: 11 px faint, sortable); the chevron marks the sorted column. -->
|
||||
<Style x:Key="Button.SortHeader" TargetType="Button">
|
||||
<Setter Property="FocusVisualStyle" Value="{StaticResource Focus.Ring}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextFaint}" />
|
||||
<Setter Property="FontSize" Value="11" />
|
||||
<Setter Property="Height" Value="28" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Left" />
|
||||
<Setter Property="Cursor" Value="Hand" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border Background="Transparent">
|
||||
<!-- The name ends in an ellipsis in a narrow column (the tooltip names the column). -->
|
||||
<Grid HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="Center">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="{Binding Content, RelativeSource={RelativeSource TemplatedParent}}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center" />
|
||||
<ui:Icon x:Name="Arrow" Grid.Column="1" Glyph="{StaticResource Icon.ChevronUp}" Size="12" Margin="2,0,0,0" VerticalAlignment="Center" Visibility="Collapsed" />
|
||||
</Grid>
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding IsSorted}" Value="True">
|
||||
<Setter TargetName="Arrow" Property="Visibility" Value="Visible" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Text}" />
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding IsDescending}" Value="True">
|
||||
<Setter TargetName="Arrow" Property="Glyph" Value="{StaticResource Icon.ChevronDown}" />
|
||||
</DataTrigger>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Text}" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- Preset card (Export.html): card fill, stroke, radius 8; accent border and glow when selected. -->
|
||||
<Style x:Key="Button.PresetCard" TargetType="Button">
|
||||
<Setter Property="FocusVisualStyle" Value="{StaticResource Focus.Ring}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Text}" />
|
||||
<Setter Property="Background" Value="{DynamicResource Brush.Card}" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Brush.Stroke}" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
|
||||
<Setter Property="VerticalContentAlignment" Value="Stretch" />
|
||||
<Setter Property="Height" Value="118" />
|
||||
<Setter Property="Margin" Value="5,0,5,10" />
|
||||
<Setter Property="Cursor" Value="Hand" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Grid>
|
||||
<Border x:Name="Glow" Margin="-3" CornerRadius="11" BorderThickness="3" BorderBrush="{DynamicResource Brush.AccentSelected}" Visibility="Collapsed" />
|
||||
<Border x:Name="Bd" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="1"
|
||||
CornerRadius="{StaticResource Radius.Card}" Padding="12,10" SnapsToDevicePixels="True">
|
||||
<ContentPresenter />
|
||||
</Border>
|
||||
</Grid>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource Brush.StrokeStrong}" />
|
||||
</Trigger>
|
||||
<DataTrigger Binding="{Binding IsSelected}" Value="True">
|
||||
<Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter TargetName="Glow" Property="Visibility" Value="Visible" />
|
||||
</DataTrigger>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter Property="Opacity" Value="0.4" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- "Recommended" chip on a card: accent border and text (DESIGN §4 chips). -->
|
||||
<Style x:Key="Border.Recommended" TargetType="Border">
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource Brush.Accent}" />
|
||||
<Setter Property="BorderThickness" Value="1" />
|
||||
<Setter Property="CornerRadius" Value="10" />
|
||||
<Setter Property="Padding" Value="6,0" />
|
||||
<Setter Property="Margin" Value="8,0,0,0" />
|
||||
<Setter Property="VerticalAlignment" Value="Center" />
|
||||
</Style>
|
||||
|
||||
<!--
|
||||
The editor's title, which chooses another sequence (owner review 1, R7): subtle like Button.Subtle, but its content is measured
|
||||
at the width the header leaves, so the title ends in an ellipsis and the chevron stays.
|
||||
-->
|
||||
<Style x:Key="Button.Title" TargetType="Button" BasedOn="{StaticResource Button.Subtle}">
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border x:Name="Bd" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"
|
||||
BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="{TemplateBinding ui:ControlState.CornerRadius}" SnapsToDevicePixels="True">
|
||||
<ContentPresenter Margin="{TemplateBinding Padding}" VerticalAlignment="Center" RecognizesAccessKey="False" />
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{Binding (ui:ControlState.HoverBackground), RelativeSource={RelativeSource TemplatedParent}}" />
|
||||
<Setter TargetName="Bd" Property="BorderBrush" Value="{Binding (ui:ControlState.HoverBorderBrush), RelativeSource={RelativeSource TemplatedParent}}" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsPressed" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{Binding (ui:ControlState.PressedBackground), RelativeSource={RelativeSource TemplatedParent}}" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsEnabled" Value="False">
|
||||
<Setter Property="Opacity" Value="0.4" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!-- ===================== The Edit path (owner review 1, R7): the step bar under the header ===================== -->
|
||||
|
||||
<!--
|
||||
A step's badge: its number in a ring until there is something to say, then the status glyph of DESIGN §4 (✓ done,
|
||||
▲ attention, ◐ running, ○ waiting), so colour never carries the state alone. The glyphs are not directional.
|
||||
-->
|
||||
<ControlTemplate x:Key="Template.StepBadge" TargetType="Control">
|
||||
<Grid Width="22" Height="22">
|
||||
<Ellipse x:Name="Ring" Stroke="{DynamicResource Brush.Stroke}" StrokeThickness="1.5" />
|
||||
<TextBlock x:Name="Number" Text="{Binding Number}" FontSize="11" Foreground="{DynamicResource Brush.TextMuted}" HorizontalAlignment="Center"
|
||||
VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
|
||||
<ui:Icon x:Name="Glyph" Size="16" HorizontalAlignment="Center" VerticalAlignment="Center" Visibility="Collapsed" />
|
||||
</Grid>
|
||||
<ControlTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding Status}" Value="{x:Static e:StepStatus.Done}">
|
||||
<Setter TargetName="Ring" Property="Visibility" Value="Collapsed" />
|
||||
<Setter TargetName="Number" Property="Visibility" Value="Collapsed" />
|
||||
<Setter TargetName="Glyph" Property="Visibility" Value="Visible" />
|
||||
<Setter TargetName="Glyph" Property="Glyph" Value="{StaticResource Icon.Check}" />
|
||||
<Setter TargetName="Glyph" Property="Foreground" Value="{DynamicResource Brush.Success}" />
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding Status}" Value="{x:Static e:StepStatus.Attention}">
|
||||
<Setter TargetName="Ring" Property="Visibility" Value="Collapsed" />
|
||||
<Setter TargetName="Number" Property="Visibility" Value="Collapsed" />
|
||||
<Setter TargetName="Glyph" Property="Visibility" Value="Visible" />
|
||||
<Setter TargetName="Glyph" Property="Glyph" Value="{StaticResource Icon.Triangle}" />
|
||||
<Setter TargetName="Glyph" Property="Foreground" Value="{DynamicResource Brush.Warning}" />
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding Status}" Value="{x:Static e:StepStatus.Running}">
|
||||
<Setter TargetName="Ring" Property="Visibility" Value="Collapsed" />
|
||||
<Setter TargetName="Number" Property="Visibility" Value="Collapsed" />
|
||||
<Setter TargetName="Glyph" Property="Visibility" Value="Visible" />
|
||||
<Setter TargetName="Glyph" Property="Glyph" Value="{StaticResource Icon.HalfDot}" />
|
||||
<Setter TargetName="Glyph" Property="Foreground" Value="{DynamicResource Brush.Warning}" />
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding Status}" Value="{x:Static e:StepStatus.Waiting}">
|
||||
<Setter TargetName="Ring" Property="Visibility" Value="Collapsed" />
|
||||
<Setter TargetName="Number" Property="Visibility" Value="Collapsed" />
|
||||
<Setter TargetName="Glyph" Property="Visibility" Value="Visible" />
|
||||
<Setter TargetName="Glyph" Property="Glyph" Value="{StaticResource Icon.Ring}" />
|
||||
<Setter TargetName="Glyph" Property="Foreground" Value="{DynamicResource Brush.TextFaint}" />
|
||||
</DataTrigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
|
||||
<!-- The step bar: every step in one row of equal cells (120.75 px each at the 1200 px minimum), no scrolling. -->
|
||||
<Style x:Key="ListBox.Steps" TargetType="ListBox" BasedOn="{StaticResource ListBox.Base}">
|
||||
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Disabled" />
|
||||
<Setter Property="ItemsPanel">
|
||||
<Setter.Value>
|
||||
<ItemsPanelTemplate>
|
||||
<UniformGrid Rows="1" />
|
||||
</ItemsPanelTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ListBox">
|
||||
<ItemsPresenter />
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!--
|
||||
One step: badge, name and a connector line to the next. The current step is underlined in the accent colour with its
|
||||
name in semibold; visited steps have their name in the text colour, the others muted. Tight padding leaves a name about
|
||||
82 px at the 1200 px minimum (every English and Italian name fits, even selected); a longer one ends in an ellipsis and
|
||||
the step's tooltip starts with it.
|
||||
-->
|
||||
<Style x:Key="ListBoxItem.Step" TargetType="ListBoxItem">
|
||||
<Setter Property="FocusVisualStyle" Value="{StaticResource Focus.Inset}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.TextMuted}" />
|
||||
<Setter Property="Height" Value="36" />
|
||||
<Setter Property="Padding" Value="4,0" />
|
||||
<Setter Property="Cursor" Value="Hand" />
|
||||
<Setter Property="ToolTip" Value="{Binding StepToolTip}" />
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding Header}" />
|
||||
<Setter Property="AutomationProperties.ItemStatus" Value="{Binding StateText}" />
|
||||
<Setter Property="AutomationProperties.AcceleratorKey" Value="{Binding Shortcut}" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="ListBoxItem">
|
||||
<Grid Background="Transparent">
|
||||
<Border x:Name="Bd" CornerRadius="{StaticResource Radius.Control}" Padding="{TemplateBinding Padding}" Background="Transparent">
|
||||
<DockPanel>
|
||||
<Control DockPanel.Dock="Left" Template="{StaticResource Template.StepBadge}" Focusable="False" IsTabStop="False" VerticalAlignment="Center" />
|
||||
<TextBlock x:Name="Label" DockPanel.Dock="Left" Text="{Binding Header}" FontSize="{StaticResource Size.Body}" Margin="6,0,2,0" VerticalAlignment="Center"
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
<Border x:Name="Connector" Height="1" Background="{DynamicResource Brush.Stroke}" VerticalAlignment="Center" />
|
||||
</DockPanel>
|
||||
</Border>
|
||||
<Border x:Name="Underline" Height="2" Margin="4,0" VerticalAlignment="Bottom" Background="{DynamicResource Brush.Accent}" Visibility="Collapsed" />
|
||||
</Grid>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource Brush.Card}" />
|
||||
</Trigger>
|
||||
<DataTrigger Binding="{Binding IsVisited}" Value="True">
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Text}" />
|
||||
</DataTrigger>
|
||||
<Trigger Property="IsSelected" Value="True">
|
||||
<Setter TargetName="Underline" Property="Visibility" Value="Visible" />
|
||||
<Setter TargetName="Label" Property="FontWeight" Value="SemiBold" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Text}" />
|
||||
</Trigger>
|
||||
<DataTrigger Binding="{Binding IsLast}" Value="True">
|
||||
<Setter TargetName="Connector" Property="Visibility" Value="Hidden" />
|
||||
</DataTrigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
|
||||
<!--
|
||||
A finding of the warnings list: glyph and one sentence, click seeks its first frame. Its own template (no
|
||||
horizontal StackPanel as in the kit's buttons) so the sentence is measured at the panel width and wraps.
|
||||
-->
|
||||
<Style x:Key="Button.Finding" TargetType="Button">
|
||||
<Setter Property="FocusVisualStyle" Value="{StaticResource Focus.Ring}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource Brush.Text}" />
|
||||
<Setter Property="Background" Value="Transparent" />
|
||||
<Setter Property="MinHeight" Value="28" />
|
||||
<Setter Property="Padding" Value="6,4" />
|
||||
<Setter Property="HorizontalAlignment" Value="Stretch" />
|
||||
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
|
||||
<Setter Property="Cursor" Value="Hand" />
|
||||
<Setter Property="Template">
|
||||
<Setter.Value>
|
||||
<ControlTemplate TargetType="Button">
|
||||
<Border x:Name="Bd" Background="{TemplateBinding Background}" CornerRadius="{StaticResource Radius.Control}" Padding="{TemplateBinding Padding}">
|
||||
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" />
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="IsMouseOver" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource Brush.Card}" />
|
||||
</Trigger>
|
||||
<Trigger Property="IsPressed" Value="True">
|
||||
<Setter TargetName="Bd" Property="Background" Value="{DynamicResource Brush.CardPressed}" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
</Setter.Value>
|
||||
</Setter>
|
||||
</Style>
|
||||
</ResourceDictionary>
|
||||
@@ -0,0 +1,155 @@
|
||||
using System.Windows.Input;
|
||||
using Chronos.Core.Advice;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// One step of the Edit path (BRIEF §12.3, owner review 1 R7): its measuring tool below the filmstrip and its column
|
||||
/// on the right, with "Optimise section" and "Reset" for a section the advisor decides. <see cref="Refresh"/> runs after
|
||||
/// every project change; the editor sets where the step stands (<see cref="SetStep"/>).
|
||||
/// </summary>
|
||||
public abstract class EditorTab : LocalizedViewModel
|
||||
{
|
||||
private StepState _state = new(StepStatus.Todo, string.Empty);
|
||||
private bool _isVisited;
|
||||
|
||||
protected EditorTab(EditorViewModel editor, string key, AdvisorSection? section)
|
||||
{
|
||||
Editor = editor;
|
||||
Key = key;
|
||||
Section = section;
|
||||
OptimiseCommand = new RelayCommand(() =>
|
||||
{
|
||||
if (Section is { } s) Editor.Optimise(s);
|
||||
}, () => CanOptimise && !Editor.IsLocked);
|
||||
ResetCommand = new RelayCommand(() =>
|
||||
{
|
||||
if (Section is { } s) Editor.Session.ResetSection(s);
|
||||
}, () => CanReset && !Editor.IsLocked);
|
||||
}
|
||||
|
||||
public EditorViewModel Editor { get; }
|
||||
|
||||
/// <summary>"Frames", "Exposure"… (resource key suffix and <see cref="EditPath"/> step).</summary>
|
||||
public string Key { get; }
|
||||
|
||||
/// <summary>The advisor section of the step; null for a step the advisor does not decide (Analysis).</summary>
|
||||
public AdvisorSection? Section { get; }
|
||||
|
||||
public string Header => Loc.L("Editor.Tab." + Key);
|
||||
|
||||
public string ToolTip => Loc.L("Tooltips.Editor.Tab." + Key);
|
||||
|
||||
/// <summary>Settings rows of the right column (empty for tabs with their own panel).</summary>
|
||||
public IReadOnlyList<SettingRow> Rows { get; protected init; } = [];
|
||||
|
||||
/// <summary>The advisor has heavier decisions for this section (stacking and the analysis have none).</summary>
|
||||
public virtual bool CanOptimise => Section is not null;
|
||||
|
||||
public virtual bool CanReset => Section is not null;
|
||||
|
||||
/// <summary>What Optimise section does, or why it cannot run now.</summary>
|
||||
public string OptimiseToolTip => !CanOptimise ? Loc.L("Tooltips.Editor.OptimiseNone") : Editor.LockedToolTip ?? Loc.L("Tooltips.Editor.OptimiseSection");
|
||||
|
||||
public string ResetToolTip => Editor.LockedToolTip ?? Loc.L("Tooltips.Editor.ResetSection");
|
||||
|
||||
public ICommand OptimiseCommand { get; }
|
||||
|
||||
public ICommand ResetCommand { get; }
|
||||
|
||||
// ---- The step ----
|
||||
|
||||
/// <summary>Position on the path, from 1.</summary>
|
||||
public int Number { get; internal set; }
|
||||
|
||||
/// <summary>The path's last step (its connector line is not drawn).</summary>
|
||||
public bool IsLast { get; internal set; }
|
||||
|
||||
/// <summary>Alt+1…Alt+9; empty from the tenth step on.</summary>
|
||||
public string Shortcut => Number is >= 1 and <= 9 ? Loc.L("Editor.Step.Shortcut", Number) : string.Empty;
|
||||
|
||||
/// <summary>The user opened the step since the sequence opened (or since the analysis it waited for ended).</summary>
|
||||
public bool IsVisited
|
||||
{
|
||||
get => _isVisited;
|
||||
internal set => Set(ref _isVisited, value);
|
||||
}
|
||||
|
||||
public StepStatus Status => _state.Status;
|
||||
|
||||
/// <summary>"Auto", "3 flagged frames", "Not rendered" (three words at most).</summary>
|
||||
public string StateText => _state.Text;
|
||||
|
||||
/// <summary>A sentence on the state, when there is more to say than <see cref="StateText"/>.</summary>
|
||||
public string? StateDetail => _state.Detail;
|
||||
|
||||
/// <summary>"Exposure · what the step is for · its state · Alt+3": the name first, so a name cut in the step bar can be read whole.</summary>
|
||||
public string StepToolTip => Shortcut.Length > 0
|
||||
? Loc.L("Tooltips.Editor.Step", Header, ToolTip, StateDetail ?? StateText, Number)
|
||||
: string.Join(Loc.Separator, Header, ToolTip, StateDetail ?? StateText);
|
||||
|
||||
/// <summary>The measuring area takes more of the height than the preview (the findings, the preset cards).</summary>
|
||||
public virtual bool PrefersTallMeasure => false;
|
||||
|
||||
/// <summary>Where the step stands now; raises only what changed.</summary>
|
||||
public void SetStep(StepState state)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(state);
|
||||
if (state == _state) return;
|
||||
var old = _state;
|
||||
_state = state;
|
||||
if (old.Status != state.Status) OnPropertyChanged(nameof(Status));
|
||||
if (old.Text != state.Text) OnPropertyChanged(nameof(StateText));
|
||||
if (old.Detail != state.Detail) OnPropertyChanged(nameof(StateDetail));
|
||||
OnPropertyChanged(nameof(StepToolTip));
|
||||
}
|
||||
|
||||
/// <summary>Re-reads the project (any change).</summary>
|
||||
public virtual void Refresh()
|
||||
{
|
||||
foreach (var row in Rows) row.Refresh();
|
||||
}
|
||||
|
||||
/// <summary>The sequence was read again: new analyses (charts, findings).</summary>
|
||||
public virtual void OnContentChanged() => Refresh();
|
||||
|
||||
/// <summary>The preview's corrections were prepared for the current settings (target curves).</summary>
|
||||
public virtual void OnCorrectionsChanged()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>The export plan of the project changed (durations, sizes).</summary>
|
||||
public virtual void OnPlanChanged()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>The frame on screen changed (playheads, the frame table, keyframe commands).</summary>
|
||||
public virtual void OnCurrentFrameChanged()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>A job of this sequence started or ended: commands and their tooltips follow.</summary>
|
||||
public virtual void OnBusyChanged()
|
||||
{
|
||||
OnPropertyChanged(nameof(OptimiseToolTip));
|
||||
OnPropertyChanged(nameof(ResetToolTip));
|
||||
}
|
||||
|
||||
/// <summary>Raises the enabled state of the tab's asynchronous commands (the others follow the command manager).</summary>
|
||||
public virtual void RefreshCommands()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Whether this sequence can send its renders to the server changed (<see cref="EditorViewModel.SyncGate"/>).</summary>
|
||||
public virtual void OnSyncGateChanged()
|
||||
{
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
foreach (var row in Rows) row.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
using System.Collections;
|
||||
using System.Globalization;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Jobs;
|
||||
using Chronos.Core.Advice;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>The editor's composed texts (header summary, shot data, preset card lines), in the current UI language.</summary>
|
||||
public static class EditorText
|
||||
{
|
||||
private static string Separator => Loc.Separator;
|
||||
|
||||
/// <summary>"3,600 frames · Canon EOS R5 · 2 s interval · 2 h 00 m · 3 warnings".</summary>
|
||||
public static string Summary(SequenceContent content, int warnings)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
var s = content.Sequence;
|
||||
var parts = new List<string> { Loc.Plural("Editor.Summary.Frames", content.Count) };
|
||||
if (s.CameraModel is { Length: > 0 } camera) parts.Add(camera);
|
||||
if (content.Light.MedianIntervalSeconds is > 0 and var interval) parts.Add(Loc.L("Editor.Summary.Interval", Number(interval)));
|
||||
if (content.Light.CaptureSpan > TimeSpan.Zero) parts.Add(Formatting.Duration(content.Light.CaptureSpan));
|
||||
if (warnings > 0) parts.Add(Loc.Plural("Editor.Summary.Warnings", warnings));
|
||||
return string.Join(Separator, parts);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Render · 46 %", "Render · queued", "Deep analysis · paused": a job the server runs for a server sequence (the job
|
||||
/// bar shows this PC's jobs only).
|
||||
/// </summary>
|
||||
public static string ServerJob(Job job)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
return job switch
|
||||
{
|
||||
{ State: JobState.Running, ProgressTotal: > 0 } => JobText.Kind(job.Kind) + Separator + Formatting.Percent((double)job.ProgressDone / job.ProgressTotal),
|
||||
{ State: JobState.Running } => JobText.Kind(job.Kind),
|
||||
_ => JobText.Kind(job.Kind) + Separator + Loc.L("Jobs.State." + job.State),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>"Render running on Studio NAS · 1,240 / 3,600 · 11.3 fps · 3 min left"; "Render waiting on Studio NAS".</summary>
|
||||
public static string ServerJobDetail(Job job, string server)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
var key = job.State switch
|
||||
{
|
||||
JobState.Queued => "Tooltips.Editor.ServerJob.Queued",
|
||||
JobState.Paused => "Tooltips.Editor.ServerJob.Paused",
|
||||
_ => "Tooltips.Editor.ServerJob",
|
||||
};
|
||||
var parts = new List<string> { Loc.L(key, JobText.Kind(job.Kind), server) };
|
||||
if (JobText.Counter(job.ProgressDone, job.ProgressTotal) is { Length: > 0 } counter) parts.Add(counter);
|
||||
if (JobText.Speed(job.Kind, job.ItemsPerSecond) is { Length: > 0 } speed) parts.Add(speed);
|
||||
if (job.Eta is { } eta) parts.Add(Loc.L("Editor.ServerJob.Left", Formatting.Duration(eta)));
|
||||
return string.Join(Separator, parts);
|
||||
}
|
||||
|
||||
/// <summary>"3,600 frames · 24 fps · 2 min 30 s · 3840×2160 · source 8192×5464": what the export makes of the sequence (Export.html header).</summary>
|
||||
public static string OutputSummary(SequenceContent content, ExportPlan plan)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
ArgumentNullException.ThrowIfNull(plan);
|
||||
var render = plan.Setup.Plan;
|
||||
var settings = plan.Setup.Encoder.Settings;
|
||||
var parts = new List<string>
|
||||
{
|
||||
Loc.Plural("Editor.Summary.Frames", content.Count),
|
||||
Loc.L("Editor.Value.Fps", FrameRate(render.FrameRate)),
|
||||
Formatting.Duration(TimeSpan.FromSeconds(render.DurationSeconds)),
|
||||
};
|
||||
if (settings.Width > 0 && settings.Height > 0) parts.Add(Size(settings.Width, settings.Height));
|
||||
if (content.SourceWidth > 0 && content.SourceHeight > 0) parts.Add(Loc.L("Editor.Summary.Source", Size(content.SourceWidth, content.SourceHeight)));
|
||||
return string.Join(Separator, parts);
|
||||
}
|
||||
|
||||
/// <summary>"0413 / 3,600 · 18:02:11 · 1/8 s · f/8 · ISO 400 · 24 mm".</summary>
|
||||
public static string Shot(Frame frame, int index, int count)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(frame);
|
||||
var parts = new List<string> { Position(index, count) };
|
||||
if (frame.CapturedAt is { } at) parts.Add(at.ToString("T", Loc.Culture));
|
||||
if (frame.ExposureTime is > 0 and var t) parts.Add(Shutter(t));
|
||||
if (frame.FNumber is > 0 and var f) parts.Add(Loc.L("Editor.Shot.Aperture", Number(f)));
|
||||
if (frame.Iso is > 0 and var iso) parts.Add(Loc.L("Editor.Shot.Iso", iso));
|
||||
if (frame.FocalLength is > 0 and var mm) parts.Add(Loc.L("Editor.Shot.Focal", Number(mm)));
|
||||
// Shown over the photo, a left-to-right island.
|
||||
return string.Join(Loc.IslandSeparator, parts);
|
||||
}
|
||||
|
||||
/// <summary>"0413 / 3,600".</summary>
|
||||
public static string Position(int index, int count) =>
|
||||
(index + 1).ToString("D4", Loc.Culture) + " / " + count.ToString("N0", Loc.Culture);
|
||||
|
||||
/// <summary>"1/250 s", "1/8 s", "2 s".</summary>
|
||||
public static string Shutter(double seconds) => seconds >= 0.3
|
||||
? Loc.L("Editor.Shot.Shutter", Number(seconds))
|
||||
: Loc.L("Editor.Shot.Shutter", "1/" + double.Round(1 / seconds).ToString("0", Loc.Culture));
|
||||
|
||||
/// <summary>"MP4 · HEVC Main10 · 3840×2160 · 24 fps".</summary>
|
||||
public static string Format(ResolvedExport export, int width, int height)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(export);
|
||||
var parts = new List<string> { Loc.L("Export.Container." + VideoCodecInfo.DefaultContainer(export.Codec)), CodecName(export.Codec, export.Profile, export.BitDepth) };
|
||||
if (width > 0 && height > 0) parts.Add(Size(width, height));
|
||||
parts.Add(Loc.L("Editor.Export.Fps", FrameRate(export.FrameRate)));
|
||||
return string.Join(Separator, parts);
|
||||
}
|
||||
|
||||
/// <summary>"120 Mb/s · 0.07 bpp · NVENC" for video, "Quality 95 · Chronos" for frames.</summary>
|
||||
public static string Encoding(ResolvedExport export, long bitRate, string? encoder)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(export);
|
||||
var parts = new List<string>();
|
||||
if (!VideoCodecInfo.IsManaged(export.Codec))
|
||||
{
|
||||
parts.Add(BitRate(bitRate));
|
||||
var bpp = export.BitsPerPixel > 0 ? export.BitsPerPixel : ExportPreset.DefaultBitsPerPixel(export.Codec);
|
||||
if (export.BitRate == 0 && bpp > 0) parts.Add(Loc.L("Editor.Export.Bpp", bpp.ToString("0.00", Loc.Culture)));
|
||||
}
|
||||
else if (export.Codec is VideoCodec.Mjpeg or VideoCodec.JpegSequence or VideoCodec.Gif)
|
||||
{
|
||||
parts.Add(Loc.L("Editor.Export.QualityValue", export.Quality));
|
||||
}
|
||||
if (encoder is { Length: > 0 }) parts.Add(encoder);
|
||||
return string.Join(Separator, parts);
|
||||
}
|
||||
|
||||
/// <summary>"2.2 GB · about 5 min".</summary>
|
||||
public static string Estimate(ExportEstimate estimate)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(estimate);
|
||||
return Formatting.Bytes(estimate.Bytes) + Separator + Loc.L("Editor.Export.About", Formatting.Duration(estimate.Time));
|
||||
}
|
||||
|
||||
/// <summary>"120 Mb/s".</summary>
|
||||
public static string BitRate(long bitsPerSecond) => Loc.L("Editor.Export.Mbps", (bitsPerSecond / 1e6).ToString(bitsPerSecond >= 10_000_000 ? "0" : "0.#", Loc.Culture));
|
||||
|
||||
/// <summary>"3840×2160".</summary>
|
||||
public static string Size(int width, int height) => width.ToString(Loc.Culture) + "×" + height.ToString(Loc.Culture);
|
||||
|
||||
/// <summary>"23.976", "24".</summary>
|
||||
public static string FrameRate(Rational rate) => rate.Denominator == 1 ? rate.Numerator.ToString(Loc.Culture) : rate.Value.ToString("0.###", Loc.Culture);
|
||||
|
||||
/// <summary>Technical codec name ("H.264 High", "HEVC Main10", "PNG"…).</summary>
|
||||
public static string CodecName(VideoCodec codec, CodecProfile profile, int bitDepth) => codec switch
|
||||
{
|
||||
VideoCodec.Hevc when profile == CodecProfile.HevcMain10 || bitDepth > 8 => Loc.L("Export.Codec.HevcMain10"),
|
||||
VideoCodec.Hevc => Loc.L("Export.Codec.Hevc"),
|
||||
VideoCodec.H264 => Loc.L("Export.Codec.H264"),
|
||||
_ => Loc.L("Export.Codec." + codec),
|
||||
};
|
||||
|
||||
/// <summary>"+1.0", "−0.7" (EV with a sign).</summary>
|
||||
public static string Ev(double ev) => ev.ToString("+0.0;−0.0;0.0", Loc.Culture);
|
||||
|
||||
/// <summary>"01:17.2" (minutes, seconds and tenths of a video position).</summary>
|
||||
public static string Clock(double seconds)
|
||||
{
|
||||
var t = TimeSpan.FromSeconds(double.Max(0, seconds));
|
||||
return ((int)t.TotalMinutes).ToString("00", Loc.Culture) + ":" + t.Seconds.ToString("00", Loc.Culture) + Loc.Culture.NumberFormat.NumberDecimalSeparator
|
||||
+ (t.Milliseconds / 100).ToString(Loc.Culture);
|
||||
}
|
||||
|
||||
/// <summary>"Centred", "+0.25" (crop placement −1…1).</summary>
|
||||
public static string Placement(double value) => value == 0 ? Loc.L("Editor.Value.Centred") : value.ToString("+0.00;−0.00", Loc.Culture);
|
||||
|
||||
/// <summary>The label of an advisor parameter as its control shows it.</summary>
|
||||
public static string ParameterLabel(string parameter) => parameter switch
|
||||
{
|
||||
AdvisorParameters.Hero => Loc.L("Editor.Frames.HeroLabel"),
|
||||
AdvisorParameters.Excluded => Loc.L("Editor.Frames.ExcludedLabel"),
|
||||
AdvisorParameters.TimingMode => Loc.L("Editor.Time.Mode"),
|
||||
AdvisorParameters.FrameRate => Loc.L("Editor.Time.Rate"),
|
||||
AdvisorParameters.FitToSeconds => Loc.L("Editor.Time.Fit"),
|
||||
AdvisorParameters.Deflicker => Loc.L("Editor.Exposure.Deflicker"),
|
||||
AdvisorParameters.DeflickerWindow => Loc.L("Editor.Exposure.Window"),
|
||||
AdvisorParameters.DeflickerStrength => Loc.L("Editor.Exposure.Strength"),
|
||||
AdvisorParameters.Regions => Loc.L("Editor.Exposure.Regions"),
|
||||
AdvisorParameters.HolyGrail => Loc.L("Editor.Exposure.HolyGrail"),
|
||||
AdvisorParameters.TransitionLength => Loc.L("Editor.Exposure.Transitions"),
|
||||
AdvisorParameters.WhiteBalanceSmoothing => Loc.L("Editor.Exposure.WhiteBalance"),
|
||||
AdvisorParameters.MotionBlur => Loc.L("Editor.Motion.Blur"),
|
||||
AdvisorParameters.TargetShutterAngle => Loc.L("Editor.Motion.Shutter"),
|
||||
AdvisorParameters.FlowQuality => Loc.L("Editor.Motion.Flow"),
|
||||
AdvisorParameters.Stabilize => Loc.L("Editor.Motion.Stabilize"),
|
||||
AdvisorParameters.StabilizeSmoothing => Loc.L("Editor.Motion.Smoothing"),
|
||||
AdvisorParameters.Aspect => Loc.L("Editor.Camera.Aspect"),
|
||||
AdvisorParameters.OffsetY => Loc.L("Editor.Camera.OffsetY"),
|
||||
AdvisorParameters.ExportPreset => Loc.L("Editor.Export.Preset"),
|
||||
AdvisorParameters.Resolution => Loc.L("Editor.Export.Resolution"),
|
||||
_ => parameter,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// "Deflicker window: 21 frames → 41 frames", one line of the Optimise toast. Bidi never mirrors an arrow, so a
|
||||
/// right-to-left language reads it from its own resource, the arrow pointing from the old value to the new one.
|
||||
/// </summary>
|
||||
public static string Change(SettingChange change) =>
|
||||
Loc.L(Loc.IsRightToLeft ? "Editor.Optimise.ChangeRtl" : "Editor.Optimise.Change", ParameterLabel(change.Parameter), Value(change.Parameter, change.Before),
|
||||
Value(change.Parameter, change.After));
|
||||
|
||||
/// <summary>A value of an advisor parameter as its control shows it (the "what changed" toast of Optimise).</summary>
|
||||
public static string Value(string parameter, object? value) => (parameter, value) switch
|
||||
{
|
||||
(_, null) => Loc.L("Editor.Value.None"),
|
||||
(AdvisorParameters.Hero, int frame) => Loc.L("Editor.Frames.HeroValue", (frame + 1).ToString("D4", Loc.Culture)),
|
||||
(AdvisorParameters.Aspect, "source") => Loc.L("Editor.Aspect.Source"),
|
||||
(AdvisorParameters.FrameRate, string rate) when FrameRateText.TryParse(rate, out var parsed) => Loc.L("Editor.Value.Fps", FrameRate(parsed)),
|
||||
(AdvisorParameters.FitToSeconds, double seconds) => Formatting.Duration(TimeSpan.FromSeconds(seconds)),
|
||||
(AdvisorParameters.DeflickerWindow or AdvisorParameters.TransitionLength, int frames) => Loc.Plural("Editor.Value.Frames", frames),
|
||||
(AdvisorParameters.DeflickerStrength, double strength) => strength.ToString("0.00", Loc.Culture),
|
||||
(AdvisorParameters.TargetShutterAngle, double degrees) => Loc.L("Editor.Value.Degrees", degrees.ToString("0", Loc.Culture)),
|
||||
(AdvisorParameters.StabilizeSmoothing, double sigma) => Loc.Plural("Editor.Value.Frames", (long)double.Round(sigma)),
|
||||
(AdvisorParameters.OffsetY, double offset) => Placement(offset),
|
||||
(AdvisorParameters.Resolution, string size) => size.Replace('x', '×'),
|
||||
(_, bool on) => Loc.L(on ? "Editor.Value.On" : "Editor.Value.Off"),
|
||||
(_, TimingMode mode) => Loc.L("Editor.Timing." + mode),
|
||||
(_, RegionMode mode) => mode == RegionMode.Off ? Loc.L("Editor.Value.Off") : Loc.L("Editor.Regions." + mode),
|
||||
(_, FlowQualitySetting quality) => Loc.L("Editor.Flow." + quality),
|
||||
(_, string id) when ExportPresets.Find(id) is { } preset => Loc.L(preset.NameKey),
|
||||
(_, string text) => text,
|
||||
(_, double number) => number.ToString("0.##", Loc.Culture),
|
||||
(_, IEnumerable list) => Loc.Plural("Editor.Value.Frames", list.Cast<object>().LongCount()),
|
||||
(_, IFormattable formattable) => formattable.ToString(null, Loc.Culture),
|
||||
_ => Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty,
|
||||
};
|
||||
|
||||
private static string Number(double value) => value.ToString(value >= 10 ? "0" : "0.#", Loc.Culture);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,113 @@
|
||||
using Chronos.Core.Advice;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Render;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Data.Processing;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>A choice of the Export tab: a built-in export preset, or a sequence preset (full settings plus an export preset).</summary>
|
||||
/// <param name="ExportPresetId">The export preset the card renders.</param>
|
||||
/// <param name="Sequence">The sequence preset it applies, null for a plain export preset.</param>
|
||||
/// <param name="IsRecommended">The advisor's export choice for this sequence.</param>
|
||||
/// <param name="Reason">Why it fits (advisor reason), localised; null for plain presets.</param>
|
||||
public sealed record ExportChoice(string Id, string Name, string ExportPresetId, SequencePreset? Sequence, bool IsRecommended, string? Reason);
|
||||
|
||||
/// <summary>What one export will produce: resolved values, encoder, plan, size and time estimate, file name.</summary>
|
||||
/// <param name="FileName">Output name with extension (a folder name for image sequences).</param>
|
||||
/// <param name="NameError">The first problem of the name template, localised; null when it is valid.</param>
|
||||
public sealed record ExportPlan(ResolvedExport Export, RenderSetup Setup, ExportEstimate Estimate, string FileName, string? NameError)
|
||||
{
|
||||
public string PresetName => ProcessingJobs.PresetName(Export);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The Export tab's numbers (BRIEF §11.4–11.5): the preset list (sequence presets first, then the built-in presets, the
|
||||
/// advisor's pick marked), and for any export the encoder this machine would use with its notices, the plan, the size
|
||||
/// and time estimates (<see cref="ExportEstimator"/>) and the output name (<see cref="ExportNaming"/>). Nothing decodes:
|
||||
/// the plan needs only the frame metadata and the source size.
|
||||
/// </summary>
|
||||
public sealed class ExportPlanner(SequenceContent content, IReadOnlyList<IVideoEncoderProvider> encoders, EncoderHost host, ThroughputModel? model = null)
|
||||
{
|
||||
/// <summary>Encoder providers of the machine that renders, in priority order.</summary>
|
||||
public IReadOnlyList<IVideoEncoderProvider> Encoders { get; } = encoders;
|
||||
|
||||
/// <summary>Sequence presets that fit the content, then every built-in export preset.</summary>
|
||||
public static IReadOnlyList<ExportChoice> Choices(IReadOnlyList<SequencePreset> presets, AdvisorResult advice)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(presets);
|
||||
ArgumentNullException.ThrowIfNull(advice);
|
||||
var recommended = advice.Find(AdvisorParameters.ExportPreset)?.Value as string;
|
||||
var choices = new List<ExportChoice>();
|
||||
foreach (var preset in presets)
|
||||
{
|
||||
choices.Add(new ExportChoice("sequence:" + preset.Id, preset.DisplayName(), preset.ExportPresetId, preset, false,
|
||||
preset.ReasonKey is { } key ? Advisor.Explain(key, preset.ReasonArgs) : null));
|
||||
}
|
||||
var reason = advice.Find(AdvisorParameters.ExportPreset) is { IsMissingData: false } r ? Advisor.Explain(r) : null;
|
||||
foreach (var preset in ExportPresets.BuiltIn)
|
||||
{
|
||||
var isRecommended = string.Equals(preset.Id, recommended, StringComparison.OrdinalIgnoreCase);
|
||||
choices.Add(new ExportChoice(preset.Id, Loc.L(preset.NameKey), preset.Id, null, isRecommended, isRecommended ? reason : null));
|
||||
}
|
||||
return choices;
|
||||
}
|
||||
|
||||
/// <summary>The project's own export.</summary>
|
||||
public ExportPlan? Plan(ProjectSettings project) => Plan(project, project.Export);
|
||||
|
||||
/// <summary>What <paramref name="export"/> would produce with <paramref name="project"/>; null when the source size is unknown.</summary>
|
||||
public ExportPlan? Plan(ProjectSettings project, ExportSettings export)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
ArgumentNullException.ThrowIfNull(export);
|
||||
if (content.SourceWidth <= 0 || content.SourceHeight <= 0 || content.Count == 0) return null;
|
||||
var resolved = ExportResolver.Resolve(export);
|
||||
var input = new RenderInput
|
||||
{
|
||||
Source = new SizeOnly(content),
|
||||
Frames = SourceFrameInfo.From(content.Frames, content.Light.AdjustedTimes.Length == content.Count ? content.Light.AdjustedTimes : null),
|
||||
Project = project with { Export = export, ExcludedFrames = [.. project.ExcludedFrames.Union(content.NotRenderable()).Order()] },
|
||||
};
|
||||
var setup = RenderSetup.Create(input, new RenderTarget(resolved, ExportNaming.FallbackName), Encoders, host);
|
||||
var (name, error) = FileName(export.NameTemplate, resolved, setup);
|
||||
return new ExportPlan(resolved, setup, setup.Estimate(model), name, error);
|
||||
}
|
||||
|
||||
/// <summary>The first problem of a name template, localised; null when it is valid.</summary>
|
||||
public static string? NameError(IReadOnlyList<Core.Naming.TemplateError> errors) =>
|
||||
errors.Count == 0 ? null : Loc.L("Errors.Template." + errors[0].Code, errors[0].Token ?? string.Empty, errors[0].Position + 1);
|
||||
|
||||
private (string Name, string? Error) FileName(string template, ResolvedExport export, RenderSetup setup)
|
||||
{
|
||||
var settings = setup.Encoder.Settings;
|
||||
var expanded = ExportNaming.Expand(template, new ExportNameContext
|
||||
{
|
||||
Date = content.Sequence.FirstCapture ?? DateTime.Now,
|
||||
Title = content.Sequence.DisplayTitle,
|
||||
PresetName = ProcessingJobs.PresetName(export),
|
||||
Width = settings.Width,
|
||||
Height = settings.Height,
|
||||
FrameRate = settings.FrameRate,
|
||||
Codec = settings.Codec,
|
||||
});
|
||||
var extension = VideoCodecInfo.DefaultContainer(settings.Codec) == ContainerFormat.ImageSequence ? string.Empty : VideoCodecInfo.FileExtension(settings.Codec);
|
||||
return (expanded.Name + extension, NameError(expanded.Errors));
|
||||
}
|
||||
|
||||
/// <summary>The render setup reads sizes and counts only.</summary>
|
||||
private sealed class SizeOnly(SequenceContent content) : IRenderFrameSource
|
||||
{
|
||||
public int FrameCount => content.Count;
|
||||
|
||||
public int Width => content.SourceWidth;
|
||||
|
||||
public int Height => content.SourceHeight;
|
||||
|
||||
public ValueTask<ImageBuffer> GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) =>
|
||||
throw new NotSupportedException("Export planning never decodes.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
using System.IO;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Data.Sync;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>Whether the Export "Sync" option can be used, or why not (its tooltip says which).</summary>
|
||||
public enum ExportSyncGate
|
||||
{
|
||||
Available,
|
||||
|
||||
/// <summary>A server sequence: its renders are made on the server and stay there.</summary>
|
||||
Remote,
|
||||
|
||||
/// <summary>No server session is open.</summary>
|
||||
SignedOut,
|
||||
|
||||
/// <summary>The server does not have this sequence.</summary>
|
||||
NotLinked,
|
||||
|
||||
/// <summary>The account may not send files to the server.</summary>
|
||||
NoUpload,
|
||||
}
|
||||
|
||||
/// <summary>What became of the Export "Sync" of a finished render.</summary>
|
||||
/// <param name="Gate">Why the render was not sent, or <see cref="ExportSyncGate.Available"/>.</param>
|
||||
/// <param name="Send">The queued send job; null when it was not queued.</param>
|
||||
public sealed record ExportSyncResult(ExportSyncGate Gate, Job? Send);
|
||||
|
||||
/// <summary>
|
||||
/// Export "Sync" (Export.html "register the export on the server when connected", BRIEF §14.5): a render made on this
|
||||
/// PC whose export asked for it is sent to the server the sequence is linked to once it is done
|
||||
/// (<see cref="SyncService.EnqueueSendExportsAsync"/>). The choice travels inside the render job (its export), so it
|
||||
/// holds after the editor closes; a render that ends while the session is down is queued for the last session's server
|
||||
/// and its send waits for the session (and fails visibly on the Jobs screen when it does not come back).
|
||||
/// </summary>
|
||||
public sealed class ExportSync(ChronosDatabase db, SyncService sync, JobEngine engine)
|
||||
{
|
||||
/// <summary>The option's state for a sequence.</summary>
|
||||
/// <param name="server">Key of the signed-in server; null while signed out.</param>
|
||||
/// <param name="linked">The server has the sequence (a sync link joins them).</param>
|
||||
public static ExportSyncGate Gate(bool isRemote, string? server, bool linked, bool canUpload) =>
|
||||
isRemote ? ExportSyncGate.Remote
|
||||
: server is null ? ExportSyncGate.SignedOut
|
||||
: !linked ? ExportSyncGate.NotLinked
|
||||
: !canUpload ? ExportSyncGate.NoUpload
|
||||
: ExportSyncGate.Available;
|
||||
|
||||
/// <summary>Queues sending a finished render's output.</summary>
|
||||
/// <param name="server">Key of the server: the signed-in one, else the one of the saved session; null without either.</param>
|
||||
/// <param name="canUpload">The account may send files (assumed while the session is down: the server refuses the send otherwise).</param>
|
||||
/// <returns>The send job or why there is none; null when the job is not a finished render of this PC that asked for it.</returns>
|
||||
public async Task<ExportSyncResult?> SendAsync(Job job, string? server, bool canUpload, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
if (job is not { Kind: JobKind.Render, State: JobState.Done, TargetIds: [var target] } || !Wanted(job)) return null;
|
||||
if (await db.Sequences.GetAsync(target, cancellationToken) is not { } local) return null;
|
||||
var linked = server is not null && await sync.LinkOfAsync(server, local.Id, cancellationToken) is not null;
|
||||
var gate = Gate(false, server, linked, canUpload);
|
||||
return gate == ExportSyncGate.Available
|
||||
? new ExportSyncResult(gate, await sync.EnqueueSendExportsAsync(engine, server!, local, cancellationToken))
|
||||
: new ExportSyncResult(gate, null);
|
||||
}
|
||||
|
||||
private static bool Wanted(Job job)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ProcessingJobs.ReadRender(job.ParametersJson).Export.SyncToServer;
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,670 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Settings;
|
||||
using Chronos.Core.Advice;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Video;
|
||||
using Chronos.Data.Processing;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>A preset card of the Export tab (Export.html): what it renders and what it will cost on this machine.</summary>
|
||||
public sealed class PresetCard(ExportTab owner, ExportChoice choice) : ObservableObject
|
||||
{
|
||||
private string? _format;
|
||||
private string? _encoding;
|
||||
private string? _estimate;
|
||||
private bool _isSelected;
|
||||
|
||||
public ExportChoice Choice { get; } = choice;
|
||||
|
||||
public string Name => Choice.Name;
|
||||
|
||||
public bool IsRecommended => Choice.IsRecommended;
|
||||
|
||||
/// <summary>Sequence presets apply full settings; export presets only choose the output.</summary>
|
||||
public bool IsSequencePreset => Choice.Sequence is not null;
|
||||
|
||||
/// <summary>What choosing the card does, or why it cannot be chosen now (a job runs, the project cannot change).</summary>
|
||||
public string ToolTip => owner.Editor.LockedToolTip ?? (Choice.Reason is { } reason
|
||||
? Loc.L(IsSequencePreset ? "Tooltips.Editor.Export.ApplyPreset" : "Tooltips.Editor.Export.Recommended", reason)
|
||||
: Loc.L("Tooltips.Editor.Export.Preset", Name));
|
||||
|
||||
public string BatchToolTip => owner.Editor.LockedToolTip ?? Loc.L("Tooltips.Editor.Export.InBatch");
|
||||
|
||||
/// <summary>"MP4 · HEVC Main10 · 3840×2160 · 24 fps".</summary>
|
||||
public string? Format { get => _format; private set => Set(ref _format, value); }
|
||||
|
||||
/// <summary>"120 Mb/s · 0.07 bpp · NVENC".</summary>
|
||||
public string? Encoding { get => _encoding; private set => Set(ref _encoding, value); }
|
||||
|
||||
/// <summary>"2.2 GB · about 5 min".</summary>
|
||||
public string? Estimate { get => _estimate; private set => Set(ref _estimate, value); }
|
||||
|
||||
public bool IsSelected { get => _isSelected; set => Set(ref _isSelected, value); }
|
||||
|
||||
/// <summary>Ticked for "Batch…" (export presets only).</summary>
|
||||
public bool IsInBatch
|
||||
{
|
||||
get => owner.IsInBatch(Choice.ExportPresetId);
|
||||
set => owner.SetInBatch(Choice.ExportPresetId, value);
|
||||
}
|
||||
|
||||
public bool CanBatch => !IsSequencePreset;
|
||||
|
||||
public ICommand SelectCommand => owner.SelectCommand;
|
||||
|
||||
/// <remarks>A server sequence renders on the server: this PC's encoders neither name nor rule out the encoding.</remarks>
|
||||
public void Update(ExportPlan? plan)
|
||||
{
|
||||
if (plan is null)
|
||||
{
|
||||
Format = Encoding = Estimate = null;
|
||||
return;
|
||||
}
|
||||
var settings = plan.Setup.Encoder.Settings;
|
||||
var remote = owner.Editor.IsRemote;
|
||||
Format = EditorText.Format(plan.Export, settings.Width, settings.Height);
|
||||
Encoding = EditorText.Encoding(plan.Export, settings.BitRate, remote ? null : plan.Setup.Encoder.Capability?.Name);
|
||||
Estimate = remote || plan.Setup.Encoder.IsReady ? EditorText.Estimate(plan.Estimate) : Loc.L("Editor.Export.Unavailable");
|
||||
}
|
||||
|
||||
public void RefreshBatch() => OnPropertyChanged(nameof(IsInBatch));
|
||||
|
||||
/// <summary>A job of the sequence started or ended, or the project became read-only: the tooltips say why the card waits.</summary>
|
||||
public void RefreshLocked()
|
||||
{
|
||||
OnPropertyChanged(nameof(ToolTip));
|
||||
OnPropertyChanged(nameof(BatchToolTip));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A codec choice of the Output panel with the profile and depth it implies.</summary>
|
||||
public sealed record CodecChoice(VideoCodec Codec, CodecProfile Profile, int BitDepth)
|
||||
{
|
||||
public ContainerFormat Container => VideoCodecInfo.DefaultContainer(Codec);
|
||||
|
||||
public string Label => EditorText.CodecName(Codec, Profile, BitDepth);
|
||||
}
|
||||
|
||||
/// <summary>Where renders go: the sequence's exports folder or a folder the user picked.</summary>
|
||||
public sealed record SaveChoice(string? Folder, bool Browse = false)
|
||||
{
|
||||
public string Label => Browse ? Loc.L("Editor.Export.Browse") : Folder is null ? Loc.L("Editor.Export.SequenceFolder") : Path.GetFileName(Folder.TrimEnd('\\', '/'));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Export (Export.html, BRIEF §11.4–11.5): preset cards with size and time estimates, the Output panel (container,
|
||||
/// codec, size, frame rate, quality, encoder, colour depth, name template, folder) with the estimate and the encoder's
|
||||
/// notices, and the render actions (now, queue, batch). Editing a value makes the preset "Custom" (§11.4).
|
||||
/// </summary>
|
||||
public sealed class ExportTab : EditorTab
|
||||
{
|
||||
public static IReadOnlyList<CodecChoice> Codecs { get; } =
|
||||
[
|
||||
new(VideoCodec.H264, CodecProfile.H264High, 8), new(VideoCodec.Hevc, CodecProfile.HevcMain, 8), new(VideoCodec.Hevc, CodecProfile.HevcMain10, 10),
|
||||
new(VideoCodec.Av1, CodecProfile.Av1Main, 10), new(VideoCodec.Mjpeg, CodecProfile.Auto, 8), new(VideoCodec.Gif, CodecProfile.Auto, 8),
|
||||
new(VideoCodec.Apng, CodecProfile.Auto, 8), new(VideoCodec.PngSequence, CodecProfile.Auto, 8), new(VideoCodec.JpegSequence, CodecProfile.Auto, 8),
|
||||
new(VideoCodec.Tiff16Sequence, CodecProfile.Auto, 16), new(VideoCodec.LinearDngSequence, CodecProfile.Auto, 16),
|
||||
];
|
||||
|
||||
private readonly LatestRunner _estimates = new(TimeSpan.FromMilliseconds(250));
|
||||
private readonly AsyncRelayCommand _renderNow;
|
||||
private readonly AsyncRelayCommand _addToQueue;
|
||||
private readonly AsyncRelayCommand _batch;
|
||||
private readonly AsyncRelayCommand _restore;
|
||||
private SavedCopy? _selectedCopy;
|
||||
private IReadOnlyList<PresetCard> _cards = [];
|
||||
private IReadOnlyList<CodecChoice> _codecChoices = [];
|
||||
private IReadOnlyList<Choice> _encoders = [];
|
||||
private IReadOnlyList<SaveChoice> _saveChoices = [];
|
||||
private IReadOnlyList<Choice> _depths = [];
|
||||
private IReadOnlyList<string> _notices = [];
|
||||
private bool _refreshing;
|
||||
|
||||
public ExportTab(EditorViewModel editor)
|
||||
: base(editor, "Export", AdvisorSection.Export)
|
||||
{
|
||||
SelectCommand = new RelayCommand(p => Select(p as PresetCard), _ => !Editor.IsLocked);
|
||||
_renderNow = new AsyncRelayCommand(() => Editor.RenderAsync(JobPriority.User, batch: false), () => Editor.CanRender);
|
||||
_addToQueue = new AsyncRelayCommand(() => Editor.RenderAsync(JobPriority.Normal, batch: false), () => Editor.CanRender);
|
||||
_batch = new AsyncRelayCommand(() => Editor.RenderAsync(JobPriority.User, batch: true), () => Editor.CanRender && Batch.Count > 0);
|
||||
HistoryCommand = new RelayCommand(OpenHistory);
|
||||
RevealLastCommand = new RelayCommand(() => ShellActions.Reveal(Editor.Session.Content.Renders[0].OutputPath), () => CanReveal);
|
||||
_restore = new AsyncRelayCommand(RestoreAsync, () => !Editor.IsLocked && SelectedCopy is not null);
|
||||
SaveProjectCommand = new AsyncRelayCommand(() => new ProjectFiles(Editor.Shell).SaveAsync(Editor.Session), () => !Editor.IsRemote);
|
||||
ResetFrameRateCommand = new RelayCommand(() => EditOverrides(o => o with { FrameRate = null }));
|
||||
Width = new EditableField(string.Empty, ValidateSize, v => EditOverrides(o => o with { Width = ParseSize(v) }), () => Loc.L("Tooltips.Editor.Export.Width"));
|
||||
Height = new EditableField(string.Empty, ValidateSize, v => EditOverrides(o => o with { Height = ParseSize(v) }), () => Loc.L("Tooltips.Editor.Export.Height"));
|
||||
NameTemplate = new EditableField(string.Empty, ValidateTemplate, v => EditExport(e => e with { NameTemplate = v }), () => Loc.L("Tooltips.Editor.Export.Name"));
|
||||
_selectedCopy = SavedCopies.FirstOrDefault();
|
||||
LoadCards();
|
||||
Refresh();
|
||||
}
|
||||
|
||||
public IReadOnlyList<PresetCard> Cards { get => _cards; private set => Set(ref _cards, value); }
|
||||
|
||||
public ICommand SelectCommand { get; }
|
||||
|
||||
public ICommand RenderNowCommand => _renderNow;
|
||||
|
||||
public ICommand AddToQueueCommand => _addToQueue;
|
||||
|
||||
public ICommand BatchCommand => _batch;
|
||||
|
||||
/// <summary>Jobs, filtered on this sequence (its renders and analyses).</summary>
|
||||
public ICommand HistoryCommand { get; }
|
||||
|
||||
/// <summary>"Reveal in Explorer" for the newest render (BRIEF §11.5 follow-up).</summary>
|
||||
public ICommand RevealLastCommand { get; }
|
||||
|
||||
public string AddToQueueToolTip => Editor.RenderBlockedReason ?? Loc.L("Tooltips.Editor.Export.AddToQueue");
|
||||
|
||||
public string BatchToolTip => Editor.RenderBlockedReason ?? (Batch.Count == 0 ? Loc.L("Tooltips.Editor.Export.BatchEmpty")
|
||||
: Editor.IsRemote ? Loc.L("Tooltips.Editor.Export.BatchServer", Editor.ServerName)
|
||||
: Loc.L("Tooltips.Editor.Export.Batch"));
|
||||
|
||||
public bool HasHistory => Editor.Session.Content.Renders.Count > 0;
|
||||
|
||||
/// <summary>The "history" link opens this PC's Jobs screen, which does not list a server's jobs.</summary>
|
||||
public bool CanOpenHistory => !Editor.IsRemote;
|
||||
|
||||
/// <summary>The newest render is a file on this PC (a server's renders stay on the server).</summary>
|
||||
public bool CanReveal => Editor.Session.Content.Renders is [{ OutputPath.Length: > 0 }, ..];
|
||||
|
||||
/// <summary>
|
||||
/// Saves a <c>.chronos</c> project file of this sequence and its settings (BRIEF §18); a server sequence has no
|
||||
/// archive on this PC for the file to name.
|
||||
/// </summary>
|
||||
public ICommand SaveProjectCommand { get; }
|
||||
|
||||
public string SaveProjectToolTip => Editor.IsRemote ? Loc.L("Tooltips.Editor.ProjectFile.Remote") : Loc.L("Tooltips.Editor.ProjectFile.Save");
|
||||
|
||||
// ---- Export "Sync" (Export.html, next to Save to) ----
|
||||
|
||||
/// <summary>Send each render made on this PC to the server the sequence is linked to; remembered in the project.</summary>
|
||||
public bool SyncToServer
|
||||
{
|
||||
get => Export.SyncToServer;
|
||||
set
|
||||
{
|
||||
if (!_refreshing && value != Export.SyncToServer) EditExport(e => e with { SyncToServer = value });
|
||||
}
|
||||
}
|
||||
|
||||
public bool CanSync => Editor.SyncGate == ExportSyncGate.Available;
|
||||
|
||||
/// <summary>What Sync does, or why it cannot be used for this sequence now.</summary>
|
||||
public string SyncToolTip => Loc.L(Editor.SyncGate switch
|
||||
{
|
||||
ExportSyncGate.Remote => "Tooltips.Editor.Export.SyncRemote",
|
||||
ExportSyncGate.SignedOut => "Tooltips.Editor.Export.SyncSignedOut",
|
||||
ExportSyncGate.NotLinked => "Tooltips.Editor.Export.SyncNotLinked",
|
||||
ExportSyncGate.NoUpload => "Tooltips.Editor.Export.SyncNoUpload",
|
||||
_ => "Tooltips.Editor.Export.Sync",
|
||||
});
|
||||
|
||||
/// <summary>A server sequence renders into its exports folder on the server.</summary>
|
||||
public bool CanChooseFolder => !Editor.IsRemote;
|
||||
|
||||
// ---- "Save both" copies of this PC's settings ----
|
||||
|
||||
public IReadOnlyList<SavedCopy> SavedCopies => Editor.Session.Content.SavedCopies;
|
||||
|
||||
public bool HasSavedCopies => SavedCopies.Count > 0;
|
||||
|
||||
/// <summary>The copy Restore makes the project: the newest unless another is chosen in the menu.</summary>
|
||||
public SavedCopy? SelectedCopy
|
||||
{
|
||||
get => _selectedCopy;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _selectedCopy, value)) return;
|
||||
OnPropertyChanged(nameof(RestoreText));
|
||||
OnPropertyChanged(nameof(RestoreToolTip));
|
||||
_restore.RaiseCanExecuteChanged();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"Restore settings · 03/10/2026 14:22".</summary>
|
||||
public string RestoreText => Loc.L("Editor.Export.Restore", SelectedCopy?.Label ?? string.Empty);
|
||||
|
||||
public string RestoreToolTip => Editor.LockedToolTip ?? Loc.L("Tooltips.Editor.Export.Restore", SelectedCopy?.Label ?? string.Empty);
|
||||
|
||||
public ICommand RestoreCommand => _restore;
|
||||
|
||||
public ICommand ResetFrameRateCommand { get; }
|
||||
|
||||
/// <summary>"Output · 4K archive".</summary>
|
||||
public string Title => Loc.L("Editor.Export.Output", Editor.Plan?.PresetName ?? ProcessingJobs.PresetName(ExportResolver.Resolve(Export)));
|
||||
|
||||
public IReadOnlyList<Choice> Containers { get; } =
|
||||
[
|
||||
new(ContainerFormat.Mp4, "Export.Container.Mp4"), new(ContainerFormat.Avi, "Export.Container.Avi"), new(ContainerFormat.Gif, "Export.Container.Gif"),
|
||||
new(ContainerFormat.Apng, "Export.Container.Apng"), new(ContainerFormat.ImageSequence, "Export.Container.ImageSequence"),
|
||||
];
|
||||
|
||||
public Choice? SelectedContainer
|
||||
{
|
||||
get => Containers.FirstOrDefault(c => Equals(c.Value, Resolved.Container));
|
||||
set
|
||||
{
|
||||
if (_refreshing || value?.Value is not ContainerFormat container || container == Resolved.Container) return;
|
||||
SelectCodec(Codecs.First(c => c.Container == container));
|
||||
}
|
||||
}
|
||||
|
||||
public IReadOnlyList<CodecChoice> CodecChoices { get => _codecChoices; private set => Set(ref _codecChoices, value); }
|
||||
|
||||
public CodecChoice? SelectedCodec
|
||||
{
|
||||
get => CodecChoices.FirstOrDefault(c => c.Codec == Resolved.Codec && (c.Codec != VideoCodec.Hevc || (c.BitDepth > 8) == (Resolved.BitDepth > 8)));
|
||||
set
|
||||
{
|
||||
if (!_refreshing && value is not null) SelectCodec(value);
|
||||
}
|
||||
}
|
||||
|
||||
public EditableField Width { get; }
|
||||
|
||||
public EditableField Height { get; }
|
||||
|
||||
/// <summary>"16:9".</summary>
|
||||
public string AspectText => Editor.Plan is { } plan ? Aspect(plan.Setup.Encoder.Settings.Width, plan.Setup.Encoder.Settings.Height) : string.Empty;
|
||||
|
||||
public IReadOnlyList<Choice> FrameRates { get; } = [.. ExportPresets.FrameRates.Select(r => new Choice(FrameRateText.Format(r), "Editor.Value.Number", EditorText.FrameRate(r)))];
|
||||
|
||||
public Choice? SelectedFrameRate
|
||||
{
|
||||
get => FrameRates.FirstOrDefault(c => FrameRateText.TryParse((string)c.Value, out var r) && FrameRateText.AreEqual(r, Resolved.FrameRate));
|
||||
set
|
||||
{
|
||||
if (!_refreshing && value?.Value is string rate) EditOverrides(o => o with { FrameRate = rate });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The preset's own frame rate is in force (no override).</summary>
|
||||
public bool IsFrameRateAuto => Export.Overrides.FrameRate is null;
|
||||
|
||||
public string FrameRateAutoToolTip => Loc.L("Tooltips.Editor.Export.FrameRateAuto", EditorText.FrameRate(ExportResolver.Resolve(Export with { Overrides = new ExportOverrides() }).FrameRate));
|
||||
|
||||
/// <summary>Bit rate in Mb/s (video) or quality 1–100 (JPEG, MJPEG, GIF).</summary>
|
||||
public double Quality
|
||||
{
|
||||
get => IsBitRate ? (Editor.Plan?.Setup.Encoder.Settings.BitRate ?? Resolved.BitRate) / 1e6 : Resolved.Quality;
|
||||
set
|
||||
{
|
||||
if (_refreshing) return;
|
||||
if (IsBitRate) EditOverrides(o => o with { BitRate = (long)(double.Round(value) * 1e6) }, "Export.Quality");
|
||||
else EditOverrides(o => o with { Quality = (int)double.Round(value) }, "Export.Quality");
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsBitRate => !VideoCodecInfo.IsManaged(Resolved.Codec);
|
||||
|
||||
public double QualityMaximum => IsBitRate ? 400 : 100;
|
||||
|
||||
public bool IsQualityApplicable => IsBitRate || Resolved.Codec is VideoCodec.Mjpeg or VideoCodec.JpegSequence or VideoCodec.Gif;
|
||||
|
||||
public string? QualityNotApplicable => IsQualityApplicable ? null : Loc.L("Tooltips.Editor.NotApplicable.Lossless");
|
||||
|
||||
public string QualityText => IsBitRate ? EditorText.BitRate((long)(Quality * 1e6)) : Quality.ToString("0", Loc.Culture);
|
||||
|
||||
public string QualityToolTip => Loc.L(IsBitRate ? "Tooltips.Editor.Export.BitRate" : "Tooltips.Editor.Export.Quality");
|
||||
|
||||
public IReadOnlyList<Choice> Encoders { get => _encoders; private set => Set(ref _encoders, value); }
|
||||
|
||||
/// <summary>The encoder is this PC's choice only for its own renders; the server or its render node picks its own.</summary>
|
||||
public bool CanChooseEncoder => !Editor.IsRemote;
|
||||
|
||||
public string EncoderToolTip => Editor.IsRemote ? Loc.L("Tooltips.Editor.Export.EncoderServer", Editor.ServerName) : Loc.L("Tooltips.Editor.Export.Encoder");
|
||||
|
||||
public Choice? SelectedEncoder
|
||||
{
|
||||
get => Encoders.FirstOrDefault(e => Equals(e.Value, Export.Overrides.Encoder ?? string.Empty));
|
||||
set
|
||||
{
|
||||
if (!_refreshing && value?.Value is string name) EditOverrides(o => o with { Encoder = name.Length == 0 ? null : name });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"hardware", "software" for this PC's encoder (the word, not a colour, carries the state).</summary>
|
||||
public string? EncoderKind => !Editor.IsRemote && Editor.Plan?.Setup.Encoder.Capability is { } c
|
||||
? Loc.L(c.Hardware ? "Editor.Export.Hardware" : "Editor.Export.Software")
|
||||
: null;
|
||||
|
||||
public bool IsHardware => !Editor.IsRemote && Editor.Plan?.Setup.Encoder.Capability?.Hardware == true;
|
||||
|
||||
public IReadOnlyList<Choice> Depths { get => _depths; private set => Set(ref _depths, value); }
|
||||
|
||||
public Choice? SelectedDepth
|
||||
{
|
||||
get => Depths.FirstOrDefault(d => (int)d.Value == Resolved.BitDepth) ?? Depths[0];
|
||||
set
|
||||
{
|
||||
if (_refreshing || value?.Value is not int depth || depth == Resolved.BitDepth) return;
|
||||
EditOverrides(o => o with
|
||||
{
|
||||
BitDepth = depth,
|
||||
Profile = Resolved.Codec == VideoCodec.Hevc ? (depth > 8 ? CodecProfile.HevcMain10 : CodecProfile.HevcMain).ToString() : o.Profile,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public bool CanChooseDepth => Depths.Count > 1;
|
||||
|
||||
public EditableField NameTemplate { get; }
|
||||
|
||||
public IReadOnlyList<SaveChoice> SaveChoices { get => _saveChoices; private set => Set(ref _saveChoices, value); }
|
||||
|
||||
/// <summary>The project's folder; a server sequence always renders into its exports folder on the server.</summary>
|
||||
public SaveChoice? SelectedSave
|
||||
{
|
||||
get => SaveChoices.FirstOrDefault(c => !c.Browse && c.Folder == (CanChooseFolder ? Export.Folder : null));
|
||||
set
|
||||
{
|
||||
if (_refreshing || value is null) return;
|
||||
if (!value.Browse)
|
||||
{
|
||||
EditExport(e => e with { Folder = value.Folder });
|
||||
return;
|
||||
}
|
||||
var folder = Editor.Shell.Services.Dialogs.PickFolder(Loc.L("Editor.Export.Browse"), Export.Folder ?? Editor.Session.Content.ExportsFolder);
|
||||
if (folder is not null) EditExport(e => e with { Folder = folder });
|
||||
else OnPropertyChanged(nameof(SelectedSave));
|
||||
}
|
||||
}
|
||||
|
||||
public string SaveToolTip => Editor.IsRemote
|
||||
? Loc.L("Tooltips.Editor.Export.FolderServer")
|
||||
: Loc.L("Tooltips.Editor.Export.Folder", Export.Folder ?? Editor.Session.Content.ExportsFolder ?? string.Empty);
|
||||
|
||||
public string? EstimatedSize => Estimated is { } plan ? Formatting.Bytes(plan.Estimate.Bytes) : null;
|
||||
|
||||
/// <summary>"about 5 min · NVENC"; without this PC's encoder for a server sequence.</summary>
|
||||
public string? EstimatedTime => Estimated is { } plan
|
||||
? Loc.L("Editor.Export.About", Formatting.Duration(plan.Estimate.Time)) + (!Editor.IsRemote && plan.Setup.Encoder.Capability is { } c ? Loc.Separator + c.Name : string.Empty)
|
||||
: null;
|
||||
|
||||
public string? ResultName => Editor.Plan?.FileName;
|
||||
|
||||
/// <summary>What the encoder changed or cannot do (localised notices and render remarks).</summary>
|
||||
public IReadOnlyList<string> Notices { get => _notices; private set => Set(ref _notices, value); }
|
||||
|
||||
/// <summary>"Previous renders of this sequence: 2 · last 2026-09-21".</summary>
|
||||
public string HistoryText => Editor.Session.Content.Renders is { Count: > 0 } renders
|
||||
? Loc.Plural("Editor.Export.History", renders.Count, Formatting.Date(renders[0].Created))
|
||||
: Loc.L("Editor.Export.NoHistory");
|
||||
|
||||
public IReadOnlyList<string> Batch => Export.Batch;
|
||||
|
||||
/// <summary>Completes when the card estimates in flight are done.</summary>
|
||||
public Task EstimatesIdle => _estimates.Idle;
|
||||
|
||||
private ExportSettings Export => Editor.Session.Project.Export;
|
||||
|
||||
private ResolvedExport Resolved => Editor.Plan?.Export ?? ExportResolver.Resolve(Export);
|
||||
|
||||
/// <summary>The plan when its estimates mean something: this PC can encode it, or the server renders it.</summary>
|
||||
private ExportPlan? Estimated => Editor.Plan is { } plan && (Editor.IsRemote || plan.Setup.Encoder.IsReady) ? plan : null;
|
||||
|
||||
public bool IsInBatch(string presetId) => Export.Batch.Contains(presetId, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public void SetInBatch(string presetId, bool value)
|
||||
{
|
||||
if (value == IsInBatch(presetId)) return;
|
||||
EditExport(e => e with { Batch = value ? [.. e.Batch, presetId] : [.. e.Batch.Where(b => !b.Equals(presetId, StringComparison.OrdinalIgnoreCase))] });
|
||||
}
|
||||
|
||||
/// <summary>The preset cards take more of the height than the preview (Export.html).</summary>
|
||||
public override bool PrefersTallMeasure => true;
|
||||
|
||||
public override void Refresh()
|
||||
{
|
||||
base.Refresh();
|
||||
_refreshing = true;
|
||||
try
|
||||
{
|
||||
UpdateLists();
|
||||
SaveChoices = !CanChooseFolder ? [new SaveChoice(null)]
|
||||
: Export.Folder is { } folder ? [new SaveChoice(null), new SaveChoice(folder), new SaveChoice(null, Browse: true)]
|
||||
: [new SaveChoice(null), new SaveChoice(null, Browse: true)];
|
||||
if (!NameTemplate.IsDirty) NameTemplate.Load(Export.NameTemplate);
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_refreshing = false;
|
||||
}
|
||||
SelectCards();
|
||||
foreach (var card in Cards) card.RefreshBatch();
|
||||
_ = EstimateCardsAsync();
|
||||
}
|
||||
|
||||
public override void OnPlanChanged()
|
||||
{
|
||||
_refreshing = true;
|
||||
try
|
||||
{
|
||||
var settings = Editor.Plan?.Setup.Encoder.Settings;
|
||||
if (!Width.IsDirty) Width.Load(settings?.Width.ToString(CultureInfo.InvariantCulture) ?? string.Empty);
|
||||
if (!Height.IsDirty) Height.Load(settings?.Height.ToString(CultureInfo.InvariantCulture) ?? string.Empty);
|
||||
UpdateLists();
|
||||
Notices = Editor.Plan is { } plan ? PlanNotices(plan) : [];
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_refreshing = false;
|
||||
}
|
||||
// The plan follows the preset a read-only session chose to render.
|
||||
SelectCards();
|
||||
}
|
||||
|
||||
public override void OnBusyChanged()
|
||||
{
|
||||
base.OnBusyChanged();
|
||||
foreach (var card in Cards) card.RefreshLocked();
|
||||
}
|
||||
|
||||
public override void OnContentChanged()
|
||||
{
|
||||
LoadCards();
|
||||
if (SelectedCopy is null || !SavedCopies.Contains(SelectedCopy)) SelectedCopy = SavedCopies.FirstOrDefault();
|
||||
base.OnContentChanged();
|
||||
}
|
||||
|
||||
public override void RefreshCommands()
|
||||
{
|
||||
_renderNow.RaiseCanExecuteChanged();
|
||||
_addToQueue.RaiseCanExecuteChanged();
|
||||
_batch.RaiseCanExecuteChanged();
|
||||
_restore.RaiseCanExecuteChanged();
|
||||
OnPropertyChanged(nameof(AddToQueueToolTip));
|
||||
OnPropertyChanged(nameof(BatchToolTip));
|
||||
OnPropertyChanged(nameof(RestoreToolTip));
|
||||
}
|
||||
|
||||
public override void OnSyncGateChanged()
|
||||
{
|
||||
OnPropertyChanged(nameof(CanSync));
|
||||
OnPropertyChanged(nameof(SyncToolTip));
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
_estimates.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>The choices that depend on the resolved codec (new lists only when they change, so selections stay bound).</summary>
|
||||
private void UpdateLists()
|
||||
{
|
||||
var resolved = Resolved;
|
||||
if (CodecChoices.FirstOrDefault()?.Container != resolved.Container) CodecChoices = [.. Codecs.Where(c => c.Container == resolved.Container)];
|
||||
var encoders = EncoderChoices(resolved.Codec);
|
||||
if (!encoders.Select(e => e.Value).SequenceEqual(Encoders.Select(e => e.Value))) Encoders = encoders;
|
||||
int[] depths = resolved.Codec switch
|
||||
{
|
||||
VideoCodec.Hevc or VideoCodec.Av1 => [8, 10],
|
||||
VideoCodec.PngSequence or VideoCodec.Tiff16Sequence => [8, 16],
|
||||
_ => [resolved.BitDepth],
|
||||
};
|
||||
if (!depths.SequenceEqual(Depths.Select(d => (int)d.Value))) Depths = [.. depths.Select(d => new Choice(d, "Editor.Export.Depth", d))];
|
||||
}
|
||||
|
||||
private void LoadCards() => Cards = [.. ExportPlanner.Choices(Editor.Session.Presets, Editor.Session.Advice).Select(c => new PresetCard(this, c))];
|
||||
|
||||
/// <summary>The card of the export preset the plan renders.</summary>
|
||||
private void SelectCards()
|
||||
{
|
||||
foreach (var card in Cards)
|
||||
card.IsSelected = card.Choice.Sequence is null && string.Equals(card.Choice.ExportPresetId, Resolved.PresetId, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the plan changed or cannot do, localised; for a server sequence without this PC's encoder notices (the server
|
||||
/// or its render node picks the encoder).
|
||||
/// </summary>
|
||||
private IReadOnlyList<string> PlanNotices(ExportPlan plan)
|
||||
{
|
||||
var encoder = Editor.IsRemote ? plan.Setup.Encoder.Notices.Select(n => n.Key).ToHashSet(StringComparer.Ordinal) : [];
|
||||
return [.. plan.Setup.Warnings.Where(w => !encoder.Contains(w.Key)).Select(w => Loc.L(w.Key, [.. w.Args]))
|
||||
.Concat(plan.Export.Warnings.Select(k => Loc.L(k))).Distinct()];
|
||||
}
|
||||
|
||||
/// <summary>Estimates every card off the UI thread for the project as it is now (latest request wins).</summary>
|
||||
private async Task EstimateCardsAsync()
|
||||
{
|
||||
var project = Editor.Session.Project;
|
||||
var cards = Cards;
|
||||
var plans = new ExportPlan?[cards.Count];
|
||||
var done = false;
|
||||
try
|
||||
{
|
||||
await _estimates.Schedule(token =>
|
||||
{
|
||||
for (var i = 0; i < cards.Count; i++)
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
var export = project.Export with { Preset = project.Export.Preset.WithManual(cards[i].Choice.ExportPresetId), Overrides = new ExportOverrides(), Batch = [] };
|
||||
plans[i] = Editor.Planner.Plan(project, export);
|
||||
}
|
||||
done = true;
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("editor", "Preset estimates failed", ex);
|
||||
return;
|
||||
}
|
||||
// A superseded request stops part way (or never starts); undo can bring back the same project instance.
|
||||
if (!done || !ReferenceEquals(cards, Cards) || !ReferenceEquals(project, Editor.Session.Project)) return;
|
||||
for (var i = 0; i < cards.Count; i++) cards[i].Update(plans[i]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes the chosen copy the project as one undo step. The toast's Undo brings back the project as it was before, as
|
||||
/// a new step, while the restore is still the last change of this editor (a later edit would otherwise be undone).
|
||||
/// </summary>
|
||||
private async Task RestoreAsync()
|
||||
{
|
||||
if (SelectedCopy is not { } copy) return;
|
||||
ProjectRestore? restore;
|
||||
try
|
||||
{
|
||||
restore = await Editor.Session.RestoreAsync(copy);
|
||||
}
|
||||
catch (InvalidDataException ex)
|
||||
{
|
||||
Editor.Shell.ReportError(ex);
|
||||
return;
|
||||
}
|
||||
if (restore is null)
|
||||
{
|
||||
Editor.Shell.Notify(Loc.L("Editor.Copy.Same"), copy.Label);
|
||||
return;
|
||||
}
|
||||
var editor = Editor;
|
||||
editor.Shell.ShowToast(new Toast
|
||||
{
|
||||
Title = Loc.L("Editor.Copy.Restored"),
|
||||
Message = copy.Label,
|
||||
ActionText = Loc.L("Editor.Copy.Undo"),
|
||||
ActionToolTip = Loc.L("Tooltips.Editor.Copy.Undo"),
|
||||
// Only in the editor that made it: another sequence opened meanwhile has its own project.
|
||||
ActionCommand = new RelayCommand(() => restore.Undo(), () => ReferenceEquals(editor.Shell.Sequence.Editor, editor) && restore.CanUndo),
|
||||
});
|
||||
}
|
||||
|
||||
private void OpenHistory()
|
||||
{
|
||||
Editor.Shell.Jobs.Filter = Jobs.JobFilter.All;
|
||||
Editor.Shell.Jobs.SearchText = Editor.Title;
|
||||
Editor.Shell.Navigate(Shell.SectionKey.Jobs);
|
||||
}
|
||||
|
||||
private void Select(PresetCard? card)
|
||||
{
|
||||
if (card is null) return;
|
||||
if (card.Choice.Sequence is { } preset) Editor.Session.ApplyPreset(preset);
|
||||
else EditExport(e => e with { Preset = e.Preset.WithManual(card.Choice.ExportPresetId), Overrides = new ExportOverrides() });
|
||||
}
|
||||
|
||||
private void SelectCodec(CodecChoice choice) => EditOverrides(o => o with
|
||||
{
|
||||
Codec = ProcessingJobs.CodecName(choice.Codec),
|
||||
Profile = choice.Profile == CodecProfile.Auto ? null : choice.Profile.ToString(),
|
||||
BitDepth = choice.BitDepth,
|
||||
BitRate = null,
|
||||
Encoder = null,
|
||||
});
|
||||
|
||||
private IReadOnlyList<Choice> EncoderChoices(VideoCodec codec)
|
||||
{
|
||||
var names = Editor.Planner.Encoders.SelectMany(p => p.Capabilities).Where(c => c.Codec == codec).Select(c => c.Name).Distinct();
|
||||
return [new Choice(string.Empty, "Editor.Export.EncoderAuto"), .. names.Select(n => new Choice(n, "Editor.Value.Text", n))];
|
||||
}
|
||||
|
||||
private void EditExport(Func<ExportSettings, ExportSettings> change, string? mergeKey = null) =>
|
||||
Editor.Session.Edit(p => p with { Export = change(p.Export) }, mergeKey);
|
||||
|
||||
private void EditOverrides(Func<ExportOverrides, ExportOverrides> change, string? mergeKey = null) =>
|
||||
EditExport(e => e with { Overrides = change(e.Overrides) }, mergeKey);
|
||||
|
||||
private static string? ValidateSize(string text) =>
|
||||
text.Length == 0 || (int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var v) && v is >= 16 and <= 16384)
|
||||
? null
|
||||
: Loc.L("Tooltips.Editor.Export.SizeInvalid");
|
||||
|
||||
private static int? ParseSize(string text) => int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var v) ? v : null;
|
||||
|
||||
private static string? ValidateTemplate(string text) => ExportPlanner.NameError(ExportNaming.Expand(text, new ExportNameContext
|
||||
{
|
||||
Date = DateTime.Today,
|
||||
PresetName = "x",
|
||||
Codec = VideoCodec.H264,
|
||||
}).Errors);
|
||||
|
||||
private static string Aspect(int width, int height)
|
||||
{
|
||||
if (width <= 0 || height <= 0) return string.Empty;
|
||||
var gcd = (int)Gcd(width, height);
|
||||
var (w, h) = (width / gcd, height / gcd);
|
||||
return w > 64 || h > 64 ? (width / (double)height).ToString("0.00", Loc.Culture) + ":1" : $"{w}:{h}";
|
||||
}
|
||||
|
||||
private static long Gcd(long a, long b)
|
||||
{
|
||||
while (b != 0) (a, b) = (b, a % b);
|
||||
return a;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
using Chronos.Core.Advice;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Render;
|
||||
using Chronos.Ui.Visuals;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>The measuring tools of the Exposure tab (BRIEF §12.3 "luminance/waveform charts").</summary>
|
||||
public enum ExposureChart
|
||||
{
|
||||
/// <summary>Measured luminance against the target curve, sky region and exposure steps.</summary>
|
||||
Luminance,
|
||||
|
||||
/// <summary>Frame-to-frame luminance change before and after the correction.</summary>
|
||||
Flicker,
|
||||
|
||||
/// <summary>Luma waveform of the corrected frame on screen.</summary>
|
||||
Waveform,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Exposure (BRIEF §12.3): deflicker, regions, holy-grail transitions and white balance. The luminance chart shows the
|
||||
/// measured luminance (Sun) against the target curve the corrections produce (Accent), the sky region (dashed) and the
|
||||
/// exposure steps as received; the flicker chart the frame-to-frame change before and after correction; the waveform
|
||||
/// the luma distribution of the corrected frame on screen.
|
||||
/// </summary>
|
||||
public sealed class ExposureTab : EditorTab
|
||||
{
|
||||
private IReadOnlyList<ChartSeries> _series = [];
|
||||
private IReadOnlyList<ChartLegendItem> _legend = [];
|
||||
private IReadOnlyList<TimelineMarker> _markers = [];
|
||||
private string? _summary;
|
||||
private ExposureChart _chartMode;
|
||||
|
||||
public ExposureTab(EditorViewModel editor)
|
||||
: base(editor, "Exposure", AdvisorSection.Exposure)
|
||||
{
|
||||
var s = editor.Session;
|
||||
// The same rule as the Edit path's (EditorSettings.Applies): a row shown n/a is never asked for.
|
||||
string? NoDeflicker(ProjectSettings p) =>
|
||||
EditorSettings.Applies(EditorSettings.DeflickerWindow, p, s.Content.Deep) ? null : Loc.L("Tooltips.Editor.NotApplicable.DeflickerOff");
|
||||
string? NoHolyGrail(ProjectSettings p) =>
|
||||
EditorSettings.Applies(EditorSettings.TransitionLength, p, s.Content.Deep) ? null : Loc.L("Tooltips.Editor.NotApplicable.HolyGrailOff");
|
||||
Rows =
|
||||
[
|
||||
new AutoSwitchRow(s, EditorSettings.Deflicker, "Editor.Exposure.Deflicker", "Tooltips.Editor.Exposure.Deflicker"),
|
||||
new AutoNumberRow<int>(s, EditorSettings.DeflickerWindow, "Editor.Exposure.Window", "Tooltips.Editor.Exposure.Window", 5, 151, 2, "0", NoDeflicker),
|
||||
new AutoNumberRow<double>(s, EditorSettings.DeflickerStrength, "Editor.Exposure.Strength", "Tooltips.Editor.Exposure.Strength", 0, 1, 0.05, "0.00", NoDeflicker),
|
||||
new AutoChoiceRow<RegionMode>(s, EditorSettings.Regions, "Editor.Exposure.Regions", "Tooltips.Editor.Exposure.Regions",
|
||||
[
|
||||
new Choice(RegionMode.Off, "Editor.Value.Off"), new Choice(RegionMode.Auto, "Editor.Regions.Auto"),
|
||||
new Choice(RegionMode.Horizon, "Editor.Regions.Horizon"), new Choice(RegionMode.Luminance, "Editor.Regions.Luminance"),
|
||||
], NoDeflicker),
|
||||
new AutoSwitchRow(s, EditorSettings.HolyGrail, "Editor.Exposure.HolyGrail", "Tooltips.Editor.Exposure.HolyGrail"),
|
||||
new AutoNumberRow<int>(s, EditorSettings.TransitionLength, "Editor.Exposure.Transitions", "Tooltips.Editor.Exposure.Transitions", 0, 120, 1, "0", NoHolyGrail),
|
||||
new AutoSwitchRow(s, EditorSettings.WhiteBalance, "Editor.Exposure.WhiteBalance", "Tooltips.Editor.Exposure.WhiteBalance"),
|
||||
new InfoRow("Editor.Exposure.Temperature", "Tooltips.Editor.Exposure.Temperature", Temperature),
|
||||
new NumberRow(s, "Editor.Exposure.Offset", "Tooltips.Editor.Exposure.Offset", -3, 3, 0.1, p => p.Exposure.ExposureOffsetEv,
|
||||
(p, v) => p with { Exposure = p.Exposure with { ExposureOffsetEv = v } }, v => Loc.L("Editor.Value.Ev", EditorText.Ev(v))),
|
||||
];
|
||||
Refresh();
|
||||
BuildChart();
|
||||
}
|
||||
|
||||
/// <summary>Luminance, flicker or waveform (the switch beside the chart).</summary>
|
||||
public ExposureChart ChartMode
|
||||
{
|
||||
get => _chartMode;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _chartMode, value)) return;
|
||||
OnPropertyChanged(nameof(IsLuminance));
|
||||
OnPropertyChanged(nameof(IsFlicker));
|
||||
OnPropertyChanged(nameof(IsWaveform));
|
||||
BuildChart();
|
||||
Editor.OnWaveformNeeded();
|
||||
}
|
||||
}
|
||||
|
||||
// The switch's radio buttons: checking one chooses its chart; the group's unchecking of the others is ignored.
|
||||
public bool IsLuminance { get => _chartMode == ExposureChart.Luminance; set => Choose(value, ExposureChart.Luminance); }
|
||||
|
||||
public bool IsFlicker { get => _chartMode == ExposureChart.Flicker; set => Choose(value, ExposureChart.Flicker); }
|
||||
|
||||
public bool IsWaveform { get => _chartMode == ExposureChart.Waveform; set => Choose(value, ExposureChart.Waveform); }
|
||||
|
||||
/// <summary>"luma of frame 0413".</summary>
|
||||
public string WaveformTitle => Loc.L("Editor.Chart.WaveformOf", (Editor.CurrentIndex + 1).ToString("D4", Loc.Culture));
|
||||
|
||||
public IReadOnlyList<ChartSeries> Series { get => _series; private set => Set(ref _series, value); }
|
||||
|
||||
public IReadOnlyList<ChartLegendItem> Legend { get => _legend; private set => Set(ref _legend, value); }
|
||||
|
||||
public IReadOnlyList<TimelineMarker> Markers { get => _markers; private set => Set(ref _markers, value); }
|
||||
|
||||
/// <summary>"flicker −67 % · max step 0.21 EV".</summary>
|
||||
public string? Summary { get => _summary; private set => Set(ref _summary, value); }
|
||||
|
||||
public Func<double, string> YFormatter => _chartMode == ExposureChart.Flicker ? v => Loc.L("Editor.Value.Ev", EditorText.Ev(v)) : v => v.ToString("0.0", Loc.Culture);
|
||||
|
||||
public override void OnContentChanged()
|
||||
{
|
||||
base.OnContentChanged();
|
||||
BuildChart();
|
||||
}
|
||||
|
||||
public override void OnCorrectionsChanged() => BuildChart();
|
||||
|
||||
public override void OnCurrentFrameChanged() => OnPropertyChanged(nameof(WaveformTitle));
|
||||
|
||||
private void Choose(bool chosen, ExposureChart chart)
|
||||
{
|
||||
if (chosen) ChartMode = chart;
|
||||
}
|
||||
|
||||
private (string?, string?) Temperature()
|
||||
{
|
||||
if (Editor.Session.Content.Deep is not { } deep) return (null, Loc.L("Tooltips.Editor.NotApplicable.NeedsAnalysis"));
|
||||
if (deep.WhiteBalance is { KelvinLow: { } low, KelvinHigh: { } high })
|
||||
return (Loc.L("Editor.Value.Kelvin", RoundToTens(low).ToString("N0", Loc.Culture), RoundToTens(high).ToString("N0", Loc.Culture)), null);
|
||||
return (null, Loc.L("Tooltips.Editor.NotApplicable.Kelvin"));
|
||||
}
|
||||
|
||||
/// <summary>Kelvin shown to the nearest ten (Math.Round takes no negative digit count).</summary>
|
||||
internal static double RoundToTens(double kelvin) => double.Round(kelvin / 10) * 10;
|
||||
|
||||
private void BuildChart()
|
||||
{
|
||||
var content = Editor.Session.Content;
|
||||
var n = content.Count;
|
||||
var corrections = Editor.Corrections is { } c && c.FrameCount == n ? c : null;
|
||||
double[] measured = corrections?.MeasuredLogLuminance is { } m && m.Any(double.IsFinite)
|
||||
? m
|
||||
: content.Deep is { } deep ? [.. deep.Frames.LogLuminance.Select(v => v ?? double.NaN)] : [.. content.Frames.Select(f => f.MeanLogLuminance ?? double.NaN)];
|
||||
var markers = EditorViewModel.StepMarkers(content);
|
||||
var series = new List<ChartSeries>();
|
||||
var legend = new List<ChartLegendItem>();
|
||||
if (_chartMode == ExposureChart.Flicker)
|
||||
{
|
||||
series.Add(new ChartSeries(Loc.L("Editor.Chart.FlickerBefore"), Steps(measured), "Brush.Sun"));
|
||||
legend.Add(new ChartLegendItem(Loc.L("Editor.Chart.FlickerBefore"), "Brush.Sun"));
|
||||
if (corrections is not null && measured.Any(double.IsFinite))
|
||||
{
|
||||
series.Add(new ChartSeries(Loc.L("Editor.Chart.FlickerAfter"), Steps(corrections.TargetLogLuminance()), "Brush.Accent") { Thickness = 2 });
|
||||
legend.Add(new ChartLegendItem(Loc.L("Editor.Chart.FlickerAfter"), "Brush.Accent"));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
series.Add(new ChartSeries(Loc.L("Editor.Chart.Measured"), measured, "Brush.Sun"));
|
||||
legend.Add(new ChartLegendItem(Loc.L("Editor.Chart.Measured"), "Brush.Sun"));
|
||||
if (corrections is not null && measured.Any(double.IsFinite))
|
||||
{
|
||||
series.Add(new ChartSeries(Loc.L("Editor.Chart.Target"), corrections.TargetLogLuminance(), "Brush.Accent") { Thickness = 2 });
|
||||
legend.Add(new ChartLegendItem(Loc.L("Editor.Chart.Target"), "Brush.Accent"));
|
||||
}
|
||||
if (content.Deep is { Regions: not null } withSky && withSky.Frames.SkyLogLuminance.Any(v => v is not null))
|
||||
{
|
||||
series.Add(new ChartSeries(Loc.L("Editor.Chart.Sky"), withSky.Frames.SkyLogLuminance.Select(v => v ?? double.NaN).ToArray(), "Brush.Region")
|
||||
{ Dash = LineDash.Dashed });
|
||||
legend.Add(new ChartLegendItem(Loc.L("Editor.Chart.Sky"), "Brush.Region", LegendSwatch.DashedLine));
|
||||
}
|
||||
}
|
||||
if (markers.Count > 0) legend.Add(new ChartLegendItem(Loc.L("Editor.Chart.Steps"), "Brush.Sun", LegendSwatch.Triangle));
|
||||
Series = series;
|
||||
Legend = legend;
|
||||
Markers = markers;
|
||||
Summary = SummaryOf(corrections);
|
||||
OnPropertyChanged(nameof(YFormatter));
|
||||
}
|
||||
|
||||
/// <summary>Change from the previous usable frame, in EV (NaN where either is unusable).</summary>
|
||||
private static double[] Steps(double[] logLuminance)
|
||||
{
|
||||
var steps = new double[logLuminance.Length];
|
||||
var previous = double.NaN;
|
||||
for (var i = 0; i < steps.Length; i++)
|
||||
{
|
||||
steps[i] = logLuminance[i] - previous;
|
||||
if (double.IsFinite(logLuminance[i])) previous = logLuminance[i];
|
||||
}
|
||||
return steps;
|
||||
}
|
||||
|
||||
private static string? SummaryOf(RenderCorrections? corrections)
|
||||
{
|
||||
if (corrections is null) return null;
|
||||
var parts = new List<string>();
|
||||
if (corrections.Report.Deflicker is { FlickerBefore: > 0 } d)
|
||||
parts.Add(Loc.L("Editor.Exposure.FlickerChange", double.Round((d.FlickerAfter / d.FlickerBefore - 1) * 100).ToString("+0;−0;0", Loc.Culture)));
|
||||
if (corrections.Report.MaxTargetStepEv is { } step) parts.Add(Loc.L("Editor.Exposure.MaxStep", step.ToString("0.00", Loc.Culture)));
|
||||
return parts.Count == 0 ? null : string.Join(Loc.Separator, parts);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
using System.Windows.Input;
|
||||
using Chronos.Core.Advice;
|
||||
using Chronos.Core.Analysis;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Ui.Controls;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>Columns of the Frames table, each sortable (DESIGN §4 tables).</summary>
|
||||
public enum FrameSort
|
||||
{
|
||||
Number,
|
||||
Time,
|
||||
Exposure,
|
||||
Iso,
|
||||
Aperture,
|
||||
Size,
|
||||
Tier,
|
||||
Flags,
|
||||
}
|
||||
|
||||
/// <summary>A sortable column header of the Frames table: its name, its sort state and the command that sorts on it.</summary>
|
||||
public sealed class FrameColumn(FramesTab owner, FrameSort sort) : ObservableObject
|
||||
{
|
||||
public FrameSort Sort { get; } = sort;
|
||||
|
||||
/// <summary>"Time", "Decode" (narrow columns cut it at the minimum window: <see cref="ToolTip"/> has it whole).</summary>
|
||||
public string Header => Loc.L("Editor.Frames.Column." + Sort);
|
||||
|
||||
/// <summary>"Time · Sort by this column…".</summary>
|
||||
public string ToolTip => string.Join(Loc.Separator, Header, Loc.L("Tooltips.Editor.Frames.Sort"));
|
||||
|
||||
public bool IsSorted => owner.SortBy == Sort;
|
||||
|
||||
public bool IsDescending => IsSorted && owner.SortDescending;
|
||||
|
||||
public ICommand SortCommand { get; } = new RelayCommand(() => owner.SortOn(sort));
|
||||
|
||||
public void Refresh()
|
||||
{
|
||||
OnPropertyChanged(nameof(Header));
|
||||
OnPropertyChanged(nameof(ToolTip));
|
||||
OnPropertyChanged(nameof(IsSorted));
|
||||
OnPropertyChanged(nameof(IsDescending));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One frame of the Frames table; texts are formatted when shown (the table is virtualised).</summary>
|
||||
public sealed class FrameRow(FramesTab owner, Frame frame, int index) : ObservableObject
|
||||
{
|
||||
/// <summary>Archive flags named in the table (the others are internal or shown elsewhere).</summary>
|
||||
public const FrameFlags Shown = FrameFlags.Missing | FrameFlags.Corrupt | FrameFlags.Duplicate | FrameFlags.Undecodable | FrameFlags.Black | FrameFlags.White;
|
||||
|
||||
private static readonly FrameFlags[] ShownFlags =
|
||||
[FrameFlags.Missing, FrameFlags.Corrupt, FrameFlags.Duplicate, FrameFlags.Undecodable, FrameFlags.Black, FrameFlags.White];
|
||||
|
||||
public int Index { get; } = index;
|
||||
|
||||
public Frame Frame => frame;
|
||||
|
||||
public string Number => (Index + 1).ToString("D4", Loc.Culture);
|
||||
|
||||
public string Time => frame.CapturedAt?.ToString("T", Loc.Culture) ?? string.Empty;
|
||||
|
||||
public string Exposure => frame.ExposureTime is > 0 and var t ? EditorText.Shutter(t) : string.Empty;
|
||||
|
||||
public string Iso => frame.Iso?.ToString(Loc.Culture) ?? string.Empty;
|
||||
|
||||
public string Aperture => frame.FNumber is > 0 and var f ? Loc.L("Editor.Shot.Aperture", f.ToString("0.#", Loc.Culture)) : string.Empty;
|
||||
|
||||
public string Size => frame.Width > 0 ? EditorText.Size(frame.Width, frame.Height) : string.Empty;
|
||||
|
||||
/// <summary>Decode tier: the format, and "preview" when only the embedded preview decodes.</summary>
|
||||
public string Tier => (frame.Flags & FrameFlags.PreviewOnly) != 0 ? Loc.L("Editor.Frames.PreviewOnly", frame.Format) : frame.Format.ToString();
|
||||
|
||||
/// <summary>"Excluded · black", the project's exclusion first, then the archive's flags.</summary>
|
||||
public string Flags
|
||||
{
|
||||
get
|
||||
{
|
||||
var parts = new List<string>();
|
||||
if (IsExcluded) parts.Add(Loc.L("Editor.Frames.Excluded"));
|
||||
if (IsHero) parts.Add(Loc.L("Editor.Frames.Hero"));
|
||||
foreach (var flag in ShownFlags)
|
||||
{
|
||||
if ((frame.Flags & flag) != 0) parts.Add(Loc.L("Editor.Frames.Flag." + flag));
|
||||
}
|
||||
return string.Join(Loc.Separator, parts);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary><see cref="Flags"/> whole, where the column cuts it; none on a frame without flags.</summary>
|
||||
public string? FlagsToolTip => Flags is { Length: > 0 } flags ? flags : null;
|
||||
|
||||
public bool IsExcluded => owner.IsExcluded(Index);
|
||||
|
||||
public bool IsHero => owner.HeroIndex == Index;
|
||||
|
||||
public string ExcludeText => Loc.L(IsExcluded ? "Editor.Frames.Include" : "Editor.Frames.Exclude");
|
||||
|
||||
public string ExcludeToolTip => owner.Editor.LockedToolTip ?? Loc.L(IsExcluded ? "Tooltips.Editor.Frames.Include" : "Tooltips.Editor.Frames.Exclude");
|
||||
|
||||
/// <summary>A job of the sequence started or ended: the action tooltips say why they wait.</summary>
|
||||
public void RefreshBusy() => OnPropertyChanged(nameof(ExcludeToolTip));
|
||||
|
||||
/// <summary>The project's exclusions or hero changed.</summary>
|
||||
public void Refresh()
|
||||
{
|
||||
OnPropertyChanged(nameof(IsExcluded));
|
||||
OnPropertyChanged(nameof(IsHero));
|
||||
OnPropertyChanged(nameof(Flags));
|
||||
OnPropertyChanged(nameof(FlagsToolTip));
|
||||
OnPropertyChanged(nameof(ExcludeText));
|
||||
OnPropertyChanged(nameof(ExcludeToolTip));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// <summary>A finding of the analyses with the frame to jump to.</summary>
|
||||
public sealed record FindingItem(StatusKind Kind, string Text, int? Frame);
|
||||
|
||||
/// <summary>
|
||||
/// Frames (BRIEF §12.3): the virtualised frame table (index, time, exposure, ISO, aperture, size, tier, flags) with
|
||||
/// exclude/include and hero, and the warnings of the analyses about frames; Optimise adds the advised exclusions and hero.
|
||||
/// </summary>
|
||||
public sealed class FramesTab : EditorTab
|
||||
{
|
||||
private HashSet<int> _excluded = [];
|
||||
private int? _hero;
|
||||
private FrameRow[] _rows = [];
|
||||
private IReadOnlyList<FrameRow> _frames = [];
|
||||
private IReadOnlyList<FindingItem> _findings = [];
|
||||
private FrameRow? _selected;
|
||||
|
||||
public FramesTab(EditorViewModel editor)
|
||||
: base(editor, "Frames", AdvisorSection.Frames)
|
||||
{
|
||||
ToggleExcludeCommand = new RelayCommand(p => ToggleExcluded(p is FrameRow row ? row.Index : Editor.CurrentIndex), _ => !Editor.IsLocked);
|
||||
SetHeroCommand = new RelayCommand(p => Editor.Session.SetHero(p is FrameRow row ? row.Index : Editor.CurrentIndex), _ => !Editor.IsLocked);
|
||||
SeekCommand = new RelayCommand(p =>
|
||||
{
|
||||
if (p is FindingItem { Frame: { } frame }) Editor.CurrentIndex = frame;
|
||||
});
|
||||
Columns = [.. Enum.GetValues<FrameSort>().Select(c => new FrameColumn(this, c))];
|
||||
Load();
|
||||
}
|
||||
|
||||
/// <summary>Rows in the table's order (<see cref="SortBy"/>).</summary>
|
||||
public IReadOnlyList<FrameRow> Frames { get => _frames; private set => Set(ref _frames, value); }
|
||||
|
||||
/// <summary>Column headers in <see cref="FrameSort"/> order.</summary>
|
||||
public IReadOnlyList<FrameColumn> Columns { get; }
|
||||
|
||||
public FrameSort SortBy { get; private set; } = FrameSort.Number;
|
||||
|
||||
public bool SortDescending { get; private set; }
|
||||
|
||||
public IReadOnlyList<FindingItem> Findings
|
||||
{
|
||||
get => _findings;
|
||||
private set
|
||||
{
|
||||
if (Set(ref _findings, value)) OnPropertyChanged(nameof(HasFindings));
|
||||
}
|
||||
}
|
||||
|
||||
public bool HasFindings => _findings.Count > 0;
|
||||
|
||||
/// <summary>The row of the current frame (selecting a row seeks the preview).</summary>
|
||||
public FrameRow? Selected
|
||||
{
|
||||
get => _selected;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _selected, value) || value is null) return;
|
||||
Editor.CurrentIndex = value.Index;
|
||||
}
|
||||
}
|
||||
|
||||
public int? HeroIndex => _hero;
|
||||
|
||||
/// <summary>"Frame 0413", or "Not set".</summary>
|
||||
public string HeroText => _hero is { } h ? Loc.L("Editor.Frames.HeroValue", (h + 1).ToString("D4", Loc.Culture)) : Loc.L("Editor.Frames.HeroNone");
|
||||
|
||||
/// <summary>"12 frames", "None".</summary>
|
||||
public string ExcludedText => _excluded.Count > 0 ? Loc.Plural("Editor.Value.Frames", _excluded.Count) : Loc.L("Editor.Frames.ExcludedNone");
|
||||
|
||||
public bool IsCurrentExcluded => IsExcluded(Editor.CurrentIndex);
|
||||
|
||||
public string CurrentExcludeText => Loc.L(IsCurrentExcluded ? "Editor.Frames.IncludeFrame" : "Editor.Frames.ExcludeFrame");
|
||||
|
||||
public string CurrentExcludeToolTip => Editor.LockedToolTip ?? Loc.L(IsCurrentExcluded ? "Tooltips.Editor.Frames.Include" : "Tooltips.Editor.Frames.Exclude");
|
||||
|
||||
/// <summary>What Set hero does, or why it waits.</summary>
|
||||
public string HeroToolTip => Editor.LockedToolTip ?? Loc.L("Tooltips.Editor.Frames.Hero");
|
||||
|
||||
public override bool CanReset => false;
|
||||
|
||||
public ICommand ToggleExcludeCommand { get; }
|
||||
|
||||
public ICommand SetHeroCommand { get; }
|
||||
|
||||
public ICommand SeekCommand { get; }
|
||||
|
||||
public bool IsExcluded(int index) => _excluded.Contains(index);
|
||||
|
||||
/// <summary>Sorts the table on <paramref name="column"/>; the same column again reverses the order.</summary>
|
||||
public void SortOn(FrameSort column)
|
||||
{
|
||||
SortDescending = column == SortBy && !SortDescending;
|
||||
SortBy = column;
|
||||
Frames = Sorted();
|
||||
foreach (var header in Columns) header.Refresh();
|
||||
}
|
||||
|
||||
public override void Refresh()
|
||||
{
|
||||
base.Refresh();
|
||||
var project = Editor.Session.Project;
|
||||
var excluded = project.ExcludedFrames.ToHashSet();
|
||||
if (excluded.SetEquals(_excluded) && project.HeroFrame == _hero) return;
|
||||
var changed = new HashSet<int>(excluded);
|
||||
changed.SymmetricExceptWith(_excluded);
|
||||
if (_hero is { } oldHero) changed.Add(oldHero);
|
||||
if (project.HeroFrame is { } newHero) changed.Add(newHero);
|
||||
_excluded = excluded;
|
||||
_hero = project.HeroFrame;
|
||||
foreach (var index in changed)
|
||||
{
|
||||
if ((uint)index < (uint)_rows.Length) _rows[index].Refresh();
|
||||
}
|
||||
OnPropertyChanged(nameof(HeroText));
|
||||
OnPropertyChanged(nameof(ExcludedText));
|
||||
OnCurrentFrameChanged();
|
||||
}
|
||||
|
||||
public override void OnContentChanged()
|
||||
{
|
||||
Load();
|
||||
// A language switch arrives here too: the headers follow.
|
||||
foreach (var column in Columns) column.Refresh();
|
||||
base.OnContentChanged();
|
||||
}
|
||||
|
||||
public override void OnBusyChanged()
|
||||
{
|
||||
base.OnBusyChanged();
|
||||
OnPropertyChanged(nameof(HeroToolTip));
|
||||
OnPropertyChanged(nameof(CurrentExcludeToolTip));
|
||||
foreach (var row in _rows) row.RefreshBusy();
|
||||
}
|
||||
|
||||
public override void OnCurrentFrameChanged()
|
||||
{
|
||||
var index = Editor.CurrentIndex;
|
||||
if ((uint)index < (uint)_rows.Length && !ReferenceEquals(_selected, _rows[index]))
|
||||
{
|
||||
_selected = _rows[index];
|
||||
OnPropertyChanged(nameof(Selected));
|
||||
}
|
||||
OnPropertyChanged(nameof(IsCurrentExcluded));
|
||||
OnPropertyChanged(nameof(CurrentExcludeText));
|
||||
OnPropertyChanged(nameof(CurrentExcludeToolTip));
|
||||
}
|
||||
|
||||
private void Load()
|
||||
{
|
||||
var content = Editor.Session.Content;
|
||||
_excluded = Editor.Session.Project.ExcludedFrames.ToHashSet();
|
||||
_hero = Editor.Session.Project.HeroFrame;
|
||||
_rows = [.. content.Frames.Select((f, i) => new FrameRow(this, f, i))];
|
||||
Frames = Sorted();
|
||||
// The findings this step deals with, and those no step deals with; the Analysis step lists them all.
|
||||
Findings = [.. Editor.Session.Advice.Findings.Where(f => EditPath.StepOf(f.Key) is null or EditPath.Frames).OrderByDescending(f => f.Severity).Select(ToItem)];
|
||||
_selected = null;
|
||||
OnCurrentFrameChanged();
|
||||
}
|
||||
|
||||
private IReadOnlyList<FrameRow> Sorted()
|
||||
{
|
||||
IEnumerable<FrameRow> rows = SortBy switch
|
||||
{
|
||||
FrameSort.Time => _rows.OrderBy(r => r.Frame.CapturedAt),
|
||||
FrameSort.Exposure => _rows.OrderBy(r => r.Frame.ExposureTime),
|
||||
FrameSort.Iso => _rows.OrderBy(r => r.Frame.Iso),
|
||||
FrameSort.Aperture => _rows.OrderBy(r => r.Frame.FNumber),
|
||||
FrameSort.Size => _rows.OrderBy(r => (long)r.Frame.Width * r.Frame.Height),
|
||||
FrameSort.Tier => _rows.OrderBy(r => r.Tier, StringComparer.CurrentCulture),
|
||||
// Flagged frames together: excluded first, then by how many archive flags they carry.
|
||||
FrameSort.Flags => _rows.OrderBy(r => (r.IsExcluded ? 0 : 1) * 64 - BitCount(r.Frame.Flags & FrameRow.Shown)),
|
||||
_ => _rows,
|
||||
};
|
||||
if (SortBy != FrameSort.Number && rows is IOrderedEnumerable<FrameRow> ordered) rows = ordered.ThenBy(r => r.Index);
|
||||
return SortDescending ? [.. rows.Reverse()] : [.. rows];
|
||||
}
|
||||
|
||||
private static int BitCount(FrameFlags flags) => System.Numerics.BitOperations.PopCount((uint)flags);
|
||||
|
||||
internal static FindingItem ToItem(Finding finding) => new(
|
||||
finding.Severity switch
|
||||
{
|
||||
FindingSeverity.Error => StatusKind.Error,
|
||||
FindingSeverity.Warning => StatusKind.Warning,
|
||||
_ => StatusKind.NotAnalysed,
|
||||
},
|
||||
Loc.Text(finding.Key, finding.Arguments),
|
||||
finding.Frames.Count > 0 ? finding.Frames[0] : null);
|
||||
|
||||
private void ToggleExcluded(int index) => Editor.Session.SetExcluded([index], !IsExcluded(index));
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<Window x:Class="Chronos.App.Editor.FullScreenPreview"
|
||||
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"
|
||||
Title="{Binding Title}" WindowStyle="None" ResizeMode="NoResize" WindowState="Maximized" ShowInTaskbar="False"
|
||||
Background="{DynamicResource Brush.Preview}" KeyDown="OnKeyDown">
|
||||
<Window.Resources>
|
||||
<ResourceDictionary>
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="pack://application:,,,/Chronos;component/Editor/EditorStyles.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
</ResourceDictionary>
|
||||
</Window.Resources>
|
||||
<!-- Full screen at native resolution (BRIEF §12.3) with collapsible shot data; Esc closes, arrows step, space plays. -->
|
||||
<v:PreviewViewport x:Name="Viewport" Source="{Binding PreviewImage}" OriginalSource="{Binding OriginalImage}" IsCompareEnabled="{Binding IsCompare}"
|
||||
WipeLabel="{Binding WipeLabel}" ZoomMode="Actual" InfoText="{Binding InfoText}" AutomationProperties.Name="{l:Loc Editor.Preview}">
|
||||
<v:PreviewViewport.ToolsContent>
|
||||
<!-- The tools' 6 px bottom margin is for a second line in the editor; one line takes it back. -->
|
||||
<StackPanel Orientation="Horizontal" Margin="0,0,0,-6">
|
||||
<ToggleButton Style="{StaticResource ToggleButton.PreviewTool}" IsChecked="{Binding IsCompare}" ui:ButtonIcon.Glyph="{StaticResource Icon.Compare}"
|
||||
Content="{l:Loc Editor.Preview.Compare}" ToolTip="{l:Loc Tooltips.Editor.Preview.Compare}" />
|
||||
<ToggleButton Style="{StaticResource ToggleButton.PreviewTool}" IsChecked="True" ui:ButtonIcon.Glyph="{StaticResource Icon.Info}" Checked="OnShotData"
|
||||
Unchecked="OnShotData" Content="{l:Loc Editor.Preview.ShotData}" ToolTip="{l:Loc Tooltips.Editor.Preview.ShotData}" />
|
||||
<Button Style="{StaticResource Button.PreviewToolIcon}" ui:ButtonIcon.Glyph="{StaticResource Icon.Close}" Click="OnClose"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Preview.ExitFullScreen}" AutomationProperties.Name="{l:Loc Editor.Preview.ExitFullScreen}" />
|
||||
</StackPanel>
|
||||
</v:PreviewViewport.ToolsContent>
|
||||
</v:PreviewViewport>
|
||||
</Window>
|
||||
@@ -0,0 +1,55 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Controls.Primitives;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Input;
|
||||
using Chronos.Ui.Visuals;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>The preview full screen at native resolution (BRIEF §12.3): the editor keeps rendering into it at screen size.</summary>
|
||||
public partial class FullScreenPreview : Window
|
||||
{
|
||||
private readonly EditorViewModel _editor;
|
||||
|
||||
public FullScreenPreview(EditorViewModel editor)
|
||||
{
|
||||
_editor = editor;
|
||||
DataContext = editor;
|
||||
InitializeComponent();
|
||||
Loaded += (_, _) =>
|
||||
{
|
||||
var scale = PresentationSource.FromVisual(this)?.CompositionTarget?.TransformToDevice.M11 ?? 1;
|
||||
_editor.PreviewEdge = (int)(double.Max(ActualWidth, ActualHeight) * scale);
|
||||
};
|
||||
}
|
||||
|
||||
private void OnShotData(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (((ToggleButton)sender).IsChecked == true)
|
||||
Viewport.SetBinding(PreviewViewport.InfoTextProperty, new Binding(nameof(EditorViewModel.InfoText)));
|
||||
else
|
||||
BindingOperations.ClearBinding(Viewport, PreviewViewport.InfoTextProperty);
|
||||
}
|
||||
|
||||
private void OnClose(object sender, RoutedEventArgs e) => Close();
|
||||
|
||||
private void OnKeyDown(object sender, KeyEventArgs e)
|
||||
{
|
||||
if (e.Key == Key.Escape)
|
||||
{
|
||||
Close();
|
||||
e.Handled = true;
|
||||
return;
|
||||
}
|
||||
ICommand? command = e.Key switch
|
||||
{
|
||||
Key.Space => _editor.PlayCommand,
|
||||
Key.Left => _editor.StepBackCommand,
|
||||
Key.Right => _editor.StepForwardCommand,
|
||||
_ => null,
|
||||
};
|
||||
if (command is null) return;
|
||||
command.Execute(null);
|
||||
e.Handled = true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// The server calls the editor of a server sequence makes (BRIEF §14.3): the sequence and its settings with their
|
||||
/// version, the analysis report, jobs and events. Failures are <see cref="ChronosApiException"/>s (404 gone, 409 settings
|
||||
/// changed meanwhile) or network exceptions. The editor disposes its connection when it closes.
|
||||
/// </summary>
|
||||
public interface IRemoteSequenceApi : IDisposable
|
||||
{
|
||||
Task<SequenceDto> GetSequenceAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The settings JSON and its version, the frames and the renders.</summary>
|
||||
Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>A 409 <see cref="ChronosApiException"/> means the settings version moved on the server.</summary>
|
||||
Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The full deep-analysis report (<c>analysis.json</c>); null when the sequence was never deep-analysed.</summary>
|
||||
Task<string?> GetAnalysisReportAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
Task<JobDto> CreateJobAsync(CreateJobRequest request, CancellationToken cancellationToken);
|
||||
|
||||
Task<JobDto> GetJobAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Every analysis and render job waiting, running or paused on the server (all pages).</summary>
|
||||
Task<IReadOnlyList<JobDto>> ListActiveJobsAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Cancels a waiting or running job; returns it as the server now has it.</summary>
|
||||
Task<JobDto> CancelJobAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Queues a failed or cancelled job again from its checkpoint; returns it as the server now has it.</summary>
|
||||
Task<JobDto> RetryJobAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Moves a waiting job up or down the queue (<paramref name="priority"/>: background, normal or user).</summary>
|
||||
Task<JobDto> SetJobPriorityAsync(Guid id, string priority, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Server events until cancelled or the socket closes.</summary>
|
||||
IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
using Chronos.Core.Analysis;
|
||||
using Chronos.Core.Analysis.Deep;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// Where the sequence open in the editor lives: the local archive (<see cref="LocalSequenceSource"/>) or a server the
|
||||
/// client is connected to (<see cref="RemoteSequenceSource"/>: proxies from the cache, project and jobs through the
|
||||
/// API). The editor reads frames, saves the project, queues jobs and follows them only through this interface.
|
||||
/// </summary>
|
||||
public interface ISequenceSource : IAsyncDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// The sequence lives on a server (BRIEF §14.5 "edit with proxies, render where the originals are"): its project is
|
||||
/// saved there and its renders and analyses run there, one job per preset.
|
||||
/// </summary>
|
||||
bool IsRemote { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The project is shown, not changed: a server sequence for an account without the Edit right, or one whose frames
|
||||
/// changed on the server (<see cref="IsOutdated"/>). The editor disables every change and the source refuses to
|
||||
/// store one. It can turn true while the sequence is open (<see cref="ReadOnlyChanged"/>).
|
||||
/// </summary>
|
||||
bool IsReadOnly { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The frames this PC shows are no longer the sequence's (frames added or removed on the server since its proxies
|
||||
/// were fetched): frame positions in the project would point at other frames, so nothing is saved or rendered until
|
||||
/// the sequence is opened again with fresh proxies.
|
||||
/// </summary>
|
||||
bool IsOutdated { get; }
|
||||
|
||||
/// <summary><see cref="IsReadOnly"/> changed (any thread).</summary>
|
||||
event Action? ReadOnlyChanged;
|
||||
|
||||
/// <summary>A job that may concern the sequence changed (any thread): this PC's engine, or the server's events.</summary>
|
||||
event Action<Job>? JobChanged;
|
||||
|
||||
/// <summary>Everything the editor shows of the sequence; read off the UI thread.</summary>
|
||||
/// <exception cref="EditorException">The sequence is gone, or its project cannot be read (corrupt, or written by a newer Chronos).</exception>
|
||||
Task<SequenceContent> LoadAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Whether the frames <see cref="LoadAsync"/> read last are still the sequence's, in the same order: frames inserted
|
||||
/// or removed since (a sync download, an import of earlier photos, a scan) moved the stored project's positions. A
|
||||
/// server sequence whose frames changed becomes <see cref="IsOutdated"/>.
|
||||
/// </summary>
|
||||
/// <exception cref="EditorException">The sequence is gone.</exception>
|
||||
Task<bool> FramesCurrentAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Frame <paramref name="index"/> in linear light, oriented, long edge at most <paramref name="maxLongEdge"/>; null
|
||||
/// when the frame cannot be read. The caller owns the buffer.
|
||||
/// </summary>
|
||||
ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Stores <paramref name="project"/>, edited from <paramref name="basis"/> (the version last loaded or saved). A
|
||||
/// change made meanwhile by someone else is kept where this edit left the value alone (<see cref="ProjectMerge"/>).
|
||||
/// Returns the stored project.
|
||||
/// </summary>
|
||||
/// <exception cref="EditorException">The editor's own reason the project was not stored, worded for the user.</exception>
|
||||
Task<ProjectSettings> SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Queues an analysis or render job for the sequence; returns the job id.</summary>
|
||||
Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Recent jobs that may concern the sequence (queued, running, finished), for the busy state and the cost of Analyse.</summary>
|
||||
Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Cancels a job of the sequence that waits or runs; its new state arrives through <see cref="JobChanged"/>.</summary>
|
||||
Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Queues a failed or cancelled job of the sequence again from its checkpoint.</summary>
|
||||
Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>A sequence as the editor opens it.</summary>
|
||||
/// <param name="Frames">Frame rows in index order.</param>
|
||||
/// <param name="Light">Light analysis of the frame metadata (BRIEF §10.1).</param>
|
||||
/// <param name="Deep">The saved deep analysis when it describes the current frames, else null (<see cref="DeepOfOtherFrames"/> says why).</param>
|
||||
/// <param name="SourceWidth">Dominant oriented full-resolution width (0 when unknown).</param>
|
||||
/// <param name="ExportsFolder">Default output folder of renders; null when the sequence is not on this PC.</param>
|
||||
/// <param name="Renders">Finished renders, newest first (an empty output path when the file is not on this PC).</param>
|
||||
/// <param name="SavedCopies">This PC's projects kept by "Save both" when a sync conflict was settled, newest first.</param>
|
||||
public sealed record SequenceContent(
|
||||
Sequence Sequence,
|
||||
IReadOnlyList<Frame> Frames,
|
||||
ProjectSettings Project,
|
||||
LightAnalysisReport Light,
|
||||
DeepAnalysisReport? Deep,
|
||||
int SourceWidth,
|
||||
int SourceHeight,
|
||||
string? ExportsFolder,
|
||||
IReadOnlyList<Render> Renders,
|
||||
IReadOnlyList<SavedCopy> SavedCopies)
|
||||
{
|
||||
/// <summary>Flags of frames that never reach a render (as the render job skips them).</summary>
|
||||
public const FrameFlags NotRendered = FrameFlags.Missing | FrameFlags.Corrupt | FrameFlags.Excluded | FrameFlags.Undecodable;
|
||||
|
||||
public int Count => Frames.Count;
|
||||
|
||||
/// <summary>
|
||||
/// A saved deep analysis exists and reads, but describes another number of frames (frames were added or removed since);
|
||||
/// false when there is none or it cannot be read now (archive offline, file moved or damaged, a server that sends none).
|
||||
/// </summary>
|
||||
public bool DeepOfOtherFrames { get; init; }
|
||||
|
||||
/// <summary>Frames the render skips besides the project's exclusions.</summary>
|
||||
public IEnumerable<int> NotRenderable()
|
||||
{
|
||||
for (var i = 0; i < Frames.Count; i++)
|
||||
{
|
||||
if ((Frames[i].Flags & NotRendered) != 0) yield return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// Runs only the latest of a stream of requests (preview frames, estimates): scheduling cancels the request pending or
|
||||
/// running before it, waits the debounce delay, then runs the work on the thread pool. A superseded run ends quietly;
|
||||
/// other failures surface from the task <see cref="Schedule"/> returns.
|
||||
/// </summary>
|
||||
public sealed class LatestRunner(TimeSpan delay) : IDisposable
|
||||
{
|
||||
private CancellationTokenSource? _current;
|
||||
|
||||
/// <summary>Completes when the latest scheduled run has finished or been superseded.</summary>
|
||||
public Task Idle { get; private set; } = Task.CompletedTask;
|
||||
|
||||
public TimeSpan Delay { get; } = delay;
|
||||
|
||||
/// <param name="immediate">Skip the debounce delay (playback, the first frame).</param>
|
||||
public Task Schedule(Func<CancellationToken, Task> work, bool immediate = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(work);
|
||||
var cts = new CancellationTokenSource();
|
||||
Interlocked.Exchange(ref _current, cts)?.Cancel();
|
||||
var run = RunAsync(work, immediate ? TimeSpan.Zero : Delay, cts);
|
||||
Idle = run;
|
||||
return run;
|
||||
}
|
||||
|
||||
/// <summary>Cancels the pending or running request.</summary>
|
||||
public void Cancel() => Interlocked.Exchange(ref _current, null)?.Cancel();
|
||||
|
||||
public void Dispose() => Cancel();
|
||||
|
||||
private async Task RunAsync(Func<CancellationToken, Task> work, TimeSpan wait, CancellationTokenSource cts)
|
||||
{
|
||||
var token = cts.Token;
|
||||
try
|
||||
{
|
||||
if (wait > TimeSpan.Zero) await Task.Delay(wait, token).ConfigureAwait(false);
|
||||
// An async delegate: a work item that throws on cancellation before returning its task (synchronous work) is
|
||||
// caught here, in user code, instead of in the thread pool, where a debugger with Just My Code stops (R4).
|
||||
await Task.Run(async () => await work(token).ConfigureAwait(false), token).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (token.IsCancellationRequested)
|
||||
{
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Only the run that is still current releases the source; a superseded one was cancelled by its successor.
|
||||
if (Interlocked.CompareExchange(ref _current, null, cts) == cts) cts.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Advice;
|
||||
using Chronos.Core.Analysis;
|
||||
using Chronos.Core.Analysis.Deep;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.IO;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Repositories;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// A sequence of an archive on this PC: rows from the index, originals decoded by the client's decoder chain, the
|
||||
/// project in <c>.chronos/project.json</c> mirrored in the index's settings column (with its hero frame, which the
|
||||
/// Library shows), jobs on this PC's engine. Project writes follow the archive engine's protocol: under the sequence's
|
||||
/// lease file (so the server and the job engine wait for it), file first (atomically), then the index with its settings
|
||||
/// version as an optimistic check. Project settings name frames by position, and frames inserted while the sequence is
|
||||
/// open (a sync download, an import of earlier photos, a scan) move the stored positions with their frames: a save made
|
||||
/// against the frames read earlier is refused (<see cref="FramesChangedException"/>) until the editor has read them again
|
||||
/// and moved its own positions the same way (<see cref="EditorSession"/>).
|
||||
/// </summary>
|
||||
public sealed class LocalSequenceSource : ISequenceSource
|
||||
{
|
||||
private const int PageSize = 1000;
|
||||
private const int SaveAttempts = 3;
|
||||
private const int JobsListed = 200;
|
||||
|
||||
/// <summary>Times the frames are listed again when an insertion lands while they are read.</summary>
|
||||
private const int ReadAttempts = 3;
|
||||
|
||||
private readonly ChronosDatabase _db;
|
||||
private readonly Guid _sequenceId;
|
||||
private readonly ImageDecoder _decoder;
|
||||
private readonly JobEngine? _engine;
|
||||
private readonly ArchiveServiceOptions _lease;
|
||||
private string?[] _files = [];
|
||||
|
||||
/// <summary>The JPEG of each GPR frame that an import keeps in another sequence (<see cref="GprCompanions"/>), by position.</summary>
|
||||
private string?[] _companions = [];
|
||||
private Guid[] _frameIds = [];
|
||||
|
||||
/// <summary>The frames version of the frames last read (<see cref="LoadAsync"/>), whose order the project's positions follow.</summary>
|
||||
private int _framesVersion = -1;
|
||||
|
||||
private ArchivePaths? _paths;
|
||||
private SequencePaths? _folder;
|
||||
|
||||
public LocalSequenceSource(ChronosDatabase db, Guid sequenceId, ImageDecoder decoder, JobEngine? engine, ArchiveServiceOptions? lease = null)
|
||||
{
|
||||
_db = db;
|
||||
_sequenceId = sequenceId;
|
||||
_decoder = decoder;
|
||||
_engine = engine;
|
||||
_lease = lease ?? new ArchiveServiceOptions();
|
||||
if (engine is not null) engine.JobChanged += OnJobChanged;
|
||||
}
|
||||
|
||||
public bool IsRemote => false;
|
||||
|
||||
public bool IsReadOnly => false;
|
||||
|
||||
public bool IsOutdated => false;
|
||||
|
||||
/// <summary>A sequence of this PC is never read-only.</summary>
|
||||
public event Action? ReadOnlyChanged
|
||||
{
|
||||
add { }
|
||||
remove { }
|
||||
}
|
||||
|
||||
public event Action<Job>? JobChanged;
|
||||
|
||||
/// <summary>A save changed the frame the Library shows for the sequence: the stored row (any thread).</summary>
|
||||
public event Action<Sequence>? HeroChanged;
|
||||
|
||||
public async Task<SequenceContent> LoadAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var (sequence, frames) = await ReadFramesAsync(cancellationToken);
|
||||
var archive = await _db.Archives.GetAsync(sequence.ArchiveId, cancellationToken) ?? throw Missing();
|
||||
var renders = await _db.Renders.ListBySequenceAsync(_sequenceId, cancellationToken);
|
||||
var companions = await GprCompanions.FindAsync(_db, archive, frames, cancellationToken);
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
var folder = paths.Sequence(sequence.Folder);
|
||||
var files = new string?[frames.Count];
|
||||
for (var i = 0; i < files.Length; i++)
|
||||
{
|
||||
if ((frames[i].Flags & FrameFlags.Missing) == 0) files[i] = paths.FromRelative(frames[i].RelativePath);
|
||||
}
|
||||
_companions = [.. frames.Select(f => companions.GetValueOrDefault(f.Id))];
|
||||
(_paths, _folder, _files, _frameIds, _framesVersion) = (paths, folder, files, [.. frames.Select(f => f.Id)], sequence.FramesVersion);
|
||||
var context = SequenceContext.FromFrames(frames);
|
||||
var (report, otherFrames) = ReadReport(folder, frames.Count);
|
||||
return new SequenceContent(sequence, frames, ReadProject(sequence, folder), LightAnalyzer.Analyze(frames), report,
|
||||
context.SourceWidth, context.SourceHeight, folder.Exports, [.. renders.OrderByDescending(r => r.Created)], SavedCopies.List(folder.MetaDirectory))
|
||||
{
|
||||
DeepOfOtherFrames = otherFrames,
|
||||
};
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <remarks>An insertion bumps the row's frames version in the transaction that renumbers the frames.</remarks>
|
||||
public async Task<bool> FramesCurrentAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var framesVersion = _framesVersion;
|
||||
var row = await _db.Sequences.GetAsync(_sequenceId, cancellationToken) ?? throw Missing();
|
||||
return row.FramesVersion == framesVersion;
|
||||
}
|
||||
|
||||
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
|
||||
{
|
||||
if ((uint)index >= (uint)_files.Length || _files[index] is not { } file) return null;
|
||||
var companions = _companions;
|
||||
var companion = (uint)index < (uint)companions.Length ? companions[index] : null;
|
||||
var pixels = await Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
// Thumbnails take an embedded preview when it is large enough (no RAW development for a filmstrip cell); the
|
||||
// preview and its corrections take an adequate embedded preview of a RAW too, developing only without one (R4).
|
||||
var request = new DecodeRequest(file, maxLongEdge, purpose, ForcePreview: purpose == DecodePurpose.Thumbnail, Companion: companion,
|
||||
PreferPreview: true);
|
||||
return _decoder.Decode(request, cancellationToken)?.Pixels;
|
||||
}
|
||||
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// Superseded by a newer edit: end here, so the cancellation never crosses into the thread pool (a debugger
|
||||
// with Just My Code stops there, R4); it is reported below.
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("editor", $"Frame {file} could not be read", ex);
|
||||
return null;
|
||||
}
|
||||
}, cancellationToken);
|
||||
// A cancelled decode is a cancellation for the caller, never an unreadable frame.
|
||||
if (cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
pixels?.Dispose();
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
}
|
||||
return pixels;
|
||||
}
|
||||
|
||||
public Task<ProjectSettings> SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
var (paths, folder, frameIds, framesVersion) = (_paths, _folder, _frameIds, _framesVersion);
|
||||
if (paths is null || folder is null) throw new InvalidOperationException("LoadAsync first.");
|
||||
return Task.Run(async () =>
|
||||
{
|
||||
ArchiveVolume.EnsureWritable(paths);
|
||||
using var held = await LeaseFile.AcquireAsync(paths.LocksDirectory, $"seq-{_sequenceId:N}", _lease.Owner, _lease.LeaseWait, _lease.LeaseDuration,
|
||||
cancellationToken);
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
var row = await _db.Sequences.GetAsync(_sequenceId, cancellationToken) ?? throw Missing();
|
||||
// Frames were inserted or removed since the editor read them, so its positions name the old order. Insertions
|
||||
// hold this lease, so the frames do not change again before this save ends.
|
||||
if (row.FramesVersion != framesVersion) throw new FramesChangedException(Loc.L("Editor.Error.FramesArriving"));
|
||||
var stored = ReadProject(row, folder);
|
||||
var merged = ProjectMerge.SameValues(stored, basis) ? project : ProjectMerge.Merge(basis, project, stored);
|
||||
var json = merged.ToJson();
|
||||
if (json == stored.ToJson()) return merged;
|
||||
AtomicFile.WriteAllText(folder.ProjectPath, json);
|
||||
var edit = new SequenceEdit { SettingsJson = json, HeroFrameId = merged.HeroFrame == stored.HeroFrame ? null : HeroFrameId(merged, frameIds) };
|
||||
var result = await _db.Sequences.EditAsync(_sequenceId, edit, row.SettingsVersion, framesVersion, cancellationToken);
|
||||
switch (result.Outcome)
|
||||
{
|
||||
case SequenceEditOutcome.Updated:
|
||||
if (result.Sequence is { } updated && updated.HeroFrameId != row.HeroFrameId) HeroChanged?.Invoke(updated);
|
||||
return merged;
|
||||
case SequenceEditOutcome.NotFound:
|
||||
throw Missing();
|
||||
// The settings moved in the index meanwhile (server API): merge again on top of them, or find the frames that
|
||||
// moved; the file follows the next write.
|
||||
case SequenceEditOutcome.Conflict when attempt == SaveAttempts:
|
||||
throw new EditorException(Loc.L("Editor.Error.SaveConflict"));
|
||||
}
|
||||
}
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_engine is null) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
|
||||
var job = await _engine.EnqueueAsync(request, cancellationToken: cancellationToken);
|
||||
return job.Id;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken) =>
|
||||
(await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items;
|
||||
|
||||
public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) =>
|
||||
(_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).CancelAsync(jobId, cancellationToken);
|
||||
|
||||
public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) =>
|
||||
(_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).ResumeAsync(jobId, cancellationToken);
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
if (_engine is not null) _engine.JobChanged -= OnJobChanged;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sequence row with its frames as one state: the frames are listed between two reads of the row that find the
|
||||
/// same frames version (an insertion renumbers the frames and moves the row's positions in one transaction, and
|
||||
/// bumps the version), so the project's positions name these frames.
|
||||
/// </summary>
|
||||
/// <exception cref="EditorException">The sequence is gone, or an insertion landed during every attempt.</exception>
|
||||
private async Task<(Sequence Row, List<Frame> Frames)> ReadFramesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
for (var attempt = 0; attempt < ReadAttempts; attempt++)
|
||||
{
|
||||
var before = await _db.Sequences.GetAsync(_sequenceId, cancellationToken) ?? throw Missing();
|
||||
var frames = new List<Frame>();
|
||||
while (true)
|
||||
{
|
||||
var page = await _db.Frames.ListBySequenceAsync(_sequenceId, frames.Count > 0 ? frames[^1].Index : -1, PageSize, cancellationToken);
|
||||
frames.AddRange(page);
|
||||
if (page.Count < PageSize) break;
|
||||
}
|
||||
var after = await _db.Sequences.GetAsync(_sequenceId, cancellationToken) ?? throw Missing();
|
||||
if (after.FramesVersion == before.FramesVersion) return (after, frames);
|
||||
}
|
||||
throw new EditorException(Loc.L("Editor.Error.FramesArriving"));
|
||||
}
|
||||
|
||||
/// <summary>The settings in force: the index copy, else <c>project.json</c>, else defaults.</summary>
|
||||
/// <exception cref="EditorException">The settings are not a project or come from a newer Chronos.</exception>
|
||||
internal static ProjectSettings ReadProject(Sequence sequence, SequencePaths folder)
|
||||
{
|
||||
var json = sequence.SettingsJson ?? (File.Exists(folder.ProjectPath) ? File.ReadAllText(folder.ProjectPath) : null);
|
||||
if (string.IsNullOrWhiteSpace(json)) return new ProjectSettings();
|
||||
try
|
||||
{
|
||||
return ProjectSettings.FromJson(json);
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or InvalidDataException)
|
||||
{
|
||||
throw new EditorException(Loc.L("Editor.Error.Project"), ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The frame of the project's hero, or <see cref="Guid.Empty"/> (the first frame shows) without one.</summary>
|
||||
private static Guid HeroFrameId(ProjectSettings project, Guid[] frameIds) =>
|
||||
project.HeroFrame is { } hero && (uint)hero < (uint)frameIds.Length ? frameIds[hero] : Guid.Empty;
|
||||
|
||||
/// <summary>The saved deep report when it describes the current frames; whether one of another number of frames was read instead.</summary>
|
||||
private static (DeepAnalysisReport? Report, bool OtherFrames) ReadReport(SequencePaths folder, int frameCount)
|
||||
{
|
||||
if (!File.Exists(folder.AnalysisPath)) return (null, false);
|
||||
try
|
||||
{
|
||||
var report = DeepAnalysisReport.Load(folder.AnalysisPath);
|
||||
return report.FrameCount == frameCount ? (report, false) : (null, true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or JsonException)
|
||||
{
|
||||
Log.Warning("editor", $"{folder.AnalysisPath} cannot be read", ex);
|
||||
return (null, false);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnJobChanged(Job job) => JobChanged?.Invoke(job);
|
||||
|
||||
private static EditorException Missing() => new(Loc.L("Editor.Error.Missing"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The frames of a sequence of this PC changed since the editor read them (frames inserted or removed): nothing was
|
||||
/// saved. The editor reads them again, moves its positions as the index moved the stored ones, and saves again.
|
||||
/// </summary>
|
||||
public sealed class FramesChangedException(string message) : EditorException(message);
|
||||
@@ -0,0 +1,41 @@
|
||||
using Chronos.Core.Imaging;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// A video waveform monitor of one picture (BRIEF §12.3 Exposure "waveform"): for each column band, how many pixels
|
||||
/// sit at each encoded luma level (0 % at the bottom row, 100 % at the top). <see cref="Density"/> is 0–255 per cell,
|
||||
/// row-major from the top, on a log scale so faint traces stay visible; values at or above 100 % pile into the top row.
|
||||
/// </summary>
|
||||
public sealed record LumaWaveform(int Columns, int Rows, byte[] Density)
|
||||
{
|
||||
public const int Levels = 100;
|
||||
public const int MaxColumns = 320;
|
||||
|
||||
public static LumaWaveform Measure(ImageBuffer picture)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(picture);
|
||||
var columns = int.Min(picture.Width, MaxColumns);
|
||||
var counts = new int[Levels * columns];
|
||||
var (w, h) = (picture.Width, picture.Height);
|
||||
var gray = picture.Channels < 3;
|
||||
var r = picture.Plane(0);
|
||||
var g = gray ? r : picture.Plane(1);
|
||||
var b = gray ? r : picture.Plane(2);
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
var i = y * w + x;
|
||||
var luma = ColorSpace.EncodeFast(ColorSpace.LumaR * r[i] + ColorSpace.LumaG * g[i] + ColorSpace.LumaB * b[i]);
|
||||
var level = int.Clamp((int)(luma * (Levels - 1) + 0.5f), 0, Levels - 1);
|
||||
counts[(Levels - 1 - level) * columns + (int)((long)x * columns / w)]++;
|
||||
}
|
||||
}
|
||||
// A column band holding every pixel at one level is full density; one pixel is still visible.
|
||||
var full = double.Log(1 + (double)w * h / columns);
|
||||
var density = new byte[counts.Length];
|
||||
for (var k = 0; k < counts.Length; k++) density[k] = counts[k] == 0 ? (byte)0 : (byte)double.Clamp(48 + 207 * double.Log(1 + counts[k]) / full, 0, 255);
|
||||
return new LumaWaveform(columns, Levels, density);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
using Chronos.Core.Advice;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Ui.Visuals;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>Motion (BRIEF §12.3): motion blur, flow quality and stabilisation, with the measured camera path (shake) chart.</summary>
|
||||
public sealed class MotionTab : EditorTab
|
||||
{
|
||||
private IReadOnlyList<ChartSeries> _series = [];
|
||||
private IReadOnlyList<ChartLegendItem> _legend = [];
|
||||
private string? _summary;
|
||||
|
||||
public MotionTab(EditorViewModel editor)
|
||||
: base(editor, "Motion", AdvisorSection.Motion)
|
||||
{
|
||||
var s = editor.Session;
|
||||
// The same rule as the Edit path's (EditorSettings.Applies): a row shown n/a is never asked for.
|
||||
string? NoBlur(ProjectSettings p) => EditorSettings.Applies(EditorSettings.ShutterAngle, p, s.Content.Deep) ? null : Loc.L("Tooltips.Editor.NotApplicable.BlurOff");
|
||||
string? NoFlow(ProjectSettings p) => EditorSettings.Applies(EditorSettings.FlowQuality, p, s.Content.Deep) ? null : Loc.L("Tooltips.Editor.NotApplicable.NoFlow");
|
||||
string? NoStabilize(ProjectSettings p) =>
|
||||
EditorSettings.Applies(EditorSettings.StabilizeSmoothing, p, s.Content.Deep) ? null : Loc.L("Tooltips.Editor.NotApplicable.StabilizeOff");
|
||||
Rows =
|
||||
[
|
||||
new AutoSwitchRow(s, EditorSettings.MotionBlur, "Editor.Motion.Blur", "Tooltips.Editor.Motion.Blur"),
|
||||
new AutoNumberRow<double>(s, EditorSettings.ShutterAngle, "Editor.Motion.Shutter", "Tooltips.Editor.Motion.Shutter", 0, 360, 15, "0", NoBlur),
|
||||
new AutoChoiceRow<FlowQualitySetting>(s, EditorSettings.FlowQuality, "Editor.Motion.Flow", "Tooltips.Editor.Motion.Flow",
|
||||
[
|
||||
new Choice(FlowQualitySetting.Draft, "Editor.Flow.Draft"), new Choice(FlowQualitySetting.Balanced, "Editor.Flow.Balanced"),
|
||||
new Choice(FlowQualitySetting.Best, "Editor.Flow.Best"),
|
||||
], NoFlow),
|
||||
new AutoSwitchRow(s, EditorSettings.Stabilize, "Editor.Motion.Stabilize", "Tooltips.Editor.Motion.Stabilize"),
|
||||
new AutoNumberRow<double>(s, EditorSettings.StabilizeSmoothing, "Editor.Motion.Smoothing", "Tooltips.Editor.Motion.Smoothing", 2, 60, 1, "0", NoStabilize),
|
||||
];
|
||||
Refresh();
|
||||
BuildChart();
|
||||
}
|
||||
|
||||
public IReadOnlyList<ChartSeries> Series { get => _series; private set => Set(ref _series, value); }
|
||||
|
||||
public IReadOnlyList<ChartLegendItem> Legend { get => _legend; private set => Set(ref _legend, value); }
|
||||
|
||||
/// <summary>"shake 0.42 px · crop 1.8 %".</summary>
|
||||
public string? Summary { get => _summary; private set => Set(ref _summary, value); }
|
||||
|
||||
public Func<double, string> YFormatter { get; } = v => Loc.L("Editor.Value.Pixels", v.ToString("0.#", Loc.Culture));
|
||||
|
||||
public override void OnContentChanged()
|
||||
{
|
||||
base.OnContentChanged();
|
||||
BuildChart();
|
||||
}
|
||||
|
||||
/// <summary>The camera path: per-frame content shifts accumulated from the first frame (gaps hold the last position).</summary>
|
||||
private void BuildChart()
|
||||
{
|
||||
if (Editor.Session.Content.Deep is not { } deep)
|
||||
{
|
||||
Series = [];
|
||||
Legend = [];
|
||||
Summary = Loc.L("Editor.Chart.NotAnalysed");
|
||||
return;
|
||||
}
|
||||
var x = Accumulate(deep.Frames.ShiftX);
|
||||
var y = Accumulate(deep.Frames.ShiftY);
|
||||
Series =
|
||||
[
|
||||
new ChartSeries(Loc.L("Editor.Chart.PathX"), x, "Brush.Accent"),
|
||||
new ChartSeries(Loc.L("Editor.Chart.PathY"), y, "Brush.TextMuted") { Dash = LineDash.Dashed },
|
||||
];
|
||||
Legend = [new ChartLegendItem(Loc.L("Editor.Chart.PathX"), "Brush.Accent"), new ChartLegendItem(Loc.L("Editor.Chart.PathY"), "Brush.TextMuted", LegendSwatch.DashedLine)];
|
||||
var shake = deep.Shake;
|
||||
var parts = new List<string>
|
||||
{
|
||||
Loc.L("Editor.Motion.ShakeValue", shake.RmsPx.ToString("0.00", Loc.Culture)),
|
||||
Loc.L("Editor.Motion.CropValue", (shake.CropCost * 100).ToString("0.0", Loc.Culture)),
|
||||
};
|
||||
if (shake.PanDetected) parts.Add(Loc.L("Editor.Motion.PanValue", shake.PanPxPerFrame.ToString("0.0", Loc.Culture)));
|
||||
Summary = string.Join(Loc.Separator, parts);
|
||||
}
|
||||
|
||||
private static double[] Accumulate(double?[] shifts)
|
||||
{
|
||||
var path = new double[shifts.Length];
|
||||
double position = 0;
|
||||
for (var i = 0; i < shifts.Length; i++)
|
||||
{
|
||||
position += shifts[i] ?? 0;
|
||||
path[i] = position;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stack (BRIEF §12.3): median, mean or star-trail stacking; the chart shows the star field and cloud measurements.</summary>
|
||||
public sealed class StackTab : EditorTab
|
||||
{
|
||||
private IReadOnlyList<ChartSeries> _series = [];
|
||||
private IReadOnlyList<ChartLegendItem> _legend = [];
|
||||
private string? _summary;
|
||||
|
||||
public StackTab(EditorViewModel editor)
|
||||
: base(editor, "Stack", AdvisorSection.Stack)
|
||||
{
|
||||
var s = editor.Session;
|
||||
Rows =
|
||||
[
|
||||
new ChoiceRow(s, "Editor.Stack.Mode", "Tooltips.Editor.Stack.Mode",
|
||||
[
|
||||
new Choice(StackSetting.None, "Editor.Value.Off"), new Choice(StackSetting.Median, "Editor.Stack.Median"),
|
||||
new Choice(StackSetting.Mean, "Editor.Stack.Mean"), new Choice(StackSetting.StarTrails, "Editor.Stack.StarTrails"),
|
||||
],
|
||||
p => p.Stack.Mode, (p, v) => p with { Stack = p.Stack with { Mode = (StackSetting)v } }),
|
||||
new NumberRow(s, "Editor.Stack.Length", "Tooltips.Editor.Stack.Length", 3, 199, 2, p => p.Stack.Length,
|
||||
(p, v) => p with { Stack = p.Stack with { Length = (int)v } }, v => Loc.Plural("Editor.Value.Frames", (long)v),
|
||||
p => p.Stack.Mode == StackSetting.None ? Loc.L("Tooltips.Editor.NotApplicable.StackOff") : null),
|
||||
];
|
||||
Refresh();
|
||||
BuildChart();
|
||||
}
|
||||
|
||||
/// <summary>The advisor never stacks on its own (a temporal median erases moving stars).</summary>
|
||||
public override bool CanOptimise => false;
|
||||
|
||||
public IReadOnlyList<ChartSeries> Series { get => _series; private set => Set(ref _series, value); }
|
||||
|
||||
public IReadOnlyList<ChartLegendItem> Legend { get => _legend; private set => Set(ref _legend, value); }
|
||||
|
||||
public string? Summary { get => _summary; private set => Set(ref _summary, value); }
|
||||
|
||||
public Func<double, string> YFormatter { get; } = v => v.ToString("0.#", Loc.Culture);
|
||||
|
||||
public override void OnContentChanged()
|
||||
{
|
||||
base.OnContentChanged();
|
||||
BuildChart();
|
||||
}
|
||||
|
||||
private void BuildChart()
|
||||
{
|
||||
if (Editor.Session.Content.Deep is not { } deep)
|
||||
{
|
||||
Series = [];
|
||||
Legend = [];
|
||||
Summary = Loc.L("Editor.Chart.NotAnalysed");
|
||||
return;
|
||||
}
|
||||
Series =
|
||||
[
|
||||
new ChartSeries(Loc.L("Editor.Chart.Stars"), deep.Frames.StarDensity.Select(v => v ?? double.NaN).ToArray(), "Brush.Accent"),
|
||||
new ChartSeries(Loc.L("Editor.Chart.Clouds"), deep.Frames.CloudCoverage.Select(v => v is { } c ? c * 100 : double.NaN).ToArray(), "Brush.TextMuted")
|
||||
{ Dash = LineDash.Dashed },
|
||||
];
|
||||
Legend = [new ChartLegendItem(Loc.L("Editor.Chart.Stars"), "Brush.Accent"), new ChartLegendItem(Loc.L("Editor.Chart.Clouds"), "Brush.TextMuted", LegendSwatch.DashedLine)];
|
||||
Summary = Loc.L(deep.Sky.StarField ? "Editor.Stack.StarField" : "Editor.Stack.NoStarField");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,462 @@
|
||||
using System.Globalization;
|
||||
using Chronos.Core.Analysis;
|
||||
using Chronos.Core.Export;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Imaging.Geometry;
|
||||
using Chronos.Core.Motion;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Render;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>What the preview shows of the frame: the output picture, or the whole source frame with the crop marked.</summary>
|
||||
public enum PreviewFraming
|
||||
{
|
||||
/// <summary>Through the render geometry (stabilisation, virtual camera, crop): what the video shows.</summary>
|
||||
Output,
|
||||
|
||||
/// <summary>The whole frame, exposure-corrected; <see cref="PreviewFrame.Crop"/> marks what the output keeps.</summary>
|
||||
Source,
|
||||
}
|
||||
|
||||
/// <param name="LongEdge">Long edge of the preview picture in pixels (the source's own for 1:1).</param>
|
||||
/// <param name="Vectors">Also measure the motion field to the next frame.</param>
|
||||
/// <param name="Waveform">Also measure the luma waveform of the corrected picture.</param>
|
||||
public sealed record PreviewRequest(int Index, ProjectSettings Project, int LongEdge, PreviewFraming Framing, bool Vectors = false, bool Waveform = false);
|
||||
|
||||
/// <summary>A motion sample in preview pixels: origin and displacement to the next frame.</summary>
|
||||
public readonly record struct VectorSample(float X, float Y, float Dx, float Dy);
|
||||
|
||||
/// <summary>One rendered preview: the corrected and the original picture over the same area, and the overlays.</summary>
|
||||
public sealed class PreviewFrame(int index, ImageBuffer corrected, ImageBuffer original) : IDisposable
|
||||
{
|
||||
public int Index { get; } = index;
|
||||
|
||||
public ImageBuffer Corrected { get; } = corrected;
|
||||
|
||||
public ImageBuffer Original { get; } = original;
|
||||
|
||||
/// <summary>The output's part of the picture, normalised (the whole picture in <see cref="PreviewFraming.Output"/>).</summary>
|
||||
public RectD Crop { get; init; } = new(0, 0, 1, 1);
|
||||
|
||||
/// <summary>Sky/land boundary in picture pixels; empty when the analysis found no horizon.</summary>
|
||||
public IReadOnlyList<(double X, double Y)> Horizon { get; init; } = [];
|
||||
|
||||
public IReadOnlyList<VectorSample> Vectors { get; init; } = [];
|
||||
|
||||
/// <summary>Luma waveform of the corrected picture, when requested.</summary>
|
||||
public LumaWaveform? Waveform { get; init; }
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Corrected.Dispose();
|
||||
Original.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The corrected-frame preview through the render pipeline at preview size (BRIEF §12.3). The render pipeline has no
|
||||
/// single-frame entry point, so the per-frame steps of <c>RenderRun</c> are followed here: corrections from
|
||||
/// <see cref="RenderPreparation"/> exactly as a render prepares them, then each frame through the render's exposure
|
||||
/// stage, its single geometry warp and the highlight knee. Stacking and motion blur need neighbouring frames and are
|
||||
/// left to the render.
|
||||
/// <para>
|
||||
/// Preparing is split so a slider never decodes the sequence again: a measuring preparation (luminance, colour means,
|
||||
/// stabilisation; keyed on the settings that change what is measured) runs once, and every other change re-solves
|
||||
/// from its series (<see cref="PrecomputedAnalysis"/>) and its white-balance gains. Analysis-size decodes are kept in
|
||||
/// half precision within a memory budget, so region curves and segmentation re-measure from memory.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class PreviewRenderer(SequenceContent content, ISequenceSource source)
|
||||
{
|
||||
/// <summary>Long edge of the frames the preparation measures (the render uses 512; the preview trades precision for speed).</summary>
|
||||
public const int AnalysisLongEdge = 128;
|
||||
|
||||
private const int VectorLongEdge = 320;
|
||||
|
||||
/// <summary>Motion arrows across the picture's long edge.</summary>
|
||||
private const int VectorColumns = 40;
|
||||
|
||||
private static readonly RenderOptions Options = new() { AnalysisLongEdge = AnalysisLongEdge };
|
||||
|
||||
private readonly CompactFrames _frames = new(content, source);
|
||||
private readonly Lock _gate = new();
|
||||
private (string Key, RenderCorrections Corrections)? _latest;
|
||||
private (string Key, RenderCorrections Corrections)? _measured;
|
||||
|
||||
/// <summary>Frames the preparations decoded so far (tests: a re-solve decodes nothing).</summary>
|
||||
public int Decodes => _frames.Decodes;
|
||||
|
||||
/// <summary>Corrections for <paramref name="project"/> when already prepared, else null.</summary>
|
||||
public RenderCorrections? Cached(ProjectSettings project)
|
||||
{
|
||||
var key = Key(project);
|
||||
lock (_gate) return _latest is { } latest && latest.Key == key ? latest.Corrections : null;
|
||||
}
|
||||
|
||||
/// <summary>The most recently prepared corrections, whatever settings they were made for.</summary>
|
||||
public RenderCorrections? Latest
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return _latest?.Corrections;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Prepares the corrections for <paramref name="project"/> (or returns them when prepared already). Requests come
|
||||
/// one after the other (the editor cancels the previous one); only the caches are shared between calls.
|
||||
/// </summary>
|
||||
public async Task<RenderCorrections> PrepareAsync(ProjectSettings project, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
if (Cached(project) is { } cached) return cached;
|
||||
var key = Key(project);
|
||||
var measured = await MeasureAsync(project, cancellationToken).ConfigureAwait(false);
|
||||
// Nothing is measured again: white balance comes from the measuring preparation, and a stabilisation it could
|
||||
// not solve (its warning is kept) is not tried again.
|
||||
var solveProject = project with
|
||||
{
|
||||
Exposure = project.Exposure with { WhiteBalanceSmoothing = project.Exposure.WhiteBalanceSmoothing.WithManual(false) },
|
||||
Motion = measured.Stabilization is null ? project.Motion with { Stabilize = project.Motion.Stabilize.WithManual(false) } : project.Motion,
|
||||
};
|
||||
var solved = await RenderPreparation.PrepareAsync(Input(solveProject, Reuse(measured, project)), Options, null, cancellationToken).ConfigureAwait(false);
|
||||
var corrections = solved with
|
||||
{
|
||||
// Gains depend only on the measured colour means, which the measuring preparation keyed on.
|
||||
WhiteBalance = measured.WhiteBalance,
|
||||
Report = solved.Report with
|
||||
{
|
||||
MeasuredFrames = measured.Report.MeasuredFrames + solved.Report.MeasuredFrames,
|
||||
Warnings = [.. measured.Report.Warnings.Concat(solved.Report.Warnings).DistinctBy(w => w.ToString())],
|
||||
},
|
||||
};
|
||||
lock (_gate) _latest = (key, corrections);
|
||||
return corrections;
|
||||
}
|
||||
|
||||
/// <summary>Renders one preview with <paramref name="corrections"/> (identity when null); null when the frame cannot be read.</summary>
|
||||
public async Task<PreviewFrame?> RenderAsync(PreviewRequest request, RenderCorrections? corrections, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
var setup = Geometry(request, corrections);
|
||||
if (setup is null) return null;
|
||||
var (geometry, edge) = setup.Value;
|
||||
var frame = await PictureAsync(request.Index, request, corrections, geometry, edge, cancellationToken).ConfigureAwait(false);
|
||||
if (frame is null) return null;
|
||||
var (corrected, original, plan) = frame.Value;
|
||||
try
|
||||
{
|
||||
var vectors = request.Vectors && request.Index + 1 < content.Count
|
||||
? await VectorsAsync(request, corrections, corrected.Width, corrected.Height, cancellationToken).ConfigureAwait(false)
|
||||
: [];
|
||||
return new PreviewFrame(request.Index, corrected, original)
|
||||
{
|
||||
Crop = request.Framing == PreviewFraming.Source ? CropOf(plan, corrected.Width, corrected.Height) : new RectD(0, 0, 1, 1),
|
||||
Horizon = request.Framing == PreviewFraming.Source ? HorizonOf(corrected.Width, corrected.Height) : [],
|
||||
Vectors = vectors,
|
||||
Waveform = request.Waveform ? LumaWaveform.Measure(corrected) : null,
|
||||
};
|
||||
}
|
||||
catch
|
||||
{
|
||||
corrected.Dispose();
|
||||
original.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Cache key of the corrections: every setting <see cref="RenderPreparation"/> reads.</summary>
|
||||
internal static string Key(ProjectSettings project) => new ProjectSettings
|
||||
{
|
||||
Exposure = project.Exposure,
|
||||
Motion = new MotionSettings { Stabilize = project.Motion.Stabilize, StabilizeSmoothing = project.Motion.StabilizeSmoothing },
|
||||
ExcludedFrames = project.ExcludedFrames,
|
||||
}.ToJson();
|
||||
|
||||
/// <summary>Cache key of the measuring preparation: the settings that change what is measured, resolved as the preparation resolves them.</summary>
|
||||
private string MeasureKey(ProjectSettings project)
|
||||
{
|
||||
var (luminance, whiteBalance, stabilize, smoothing) = Measured(project);
|
||||
return string.Join('|', luminance, whiteBalance, stabilize, smoothing.ToString("R", CultureInfo.InvariantCulture), string.Join(',', project.ExcludedFrames));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the measuring preparation measures for <paramref name="project"/>: luminance when the deep analysis has it
|
||||
/// (free) or a module needs it, colour means for white-balance smoothing, the stabilisation path.
|
||||
/// </summary>
|
||||
private (bool Luminance, bool WhiteBalance, bool Stabilize, double Smoothing) Measured(ProjectSettings project) => (
|
||||
HasDeepAnalysis || project.Exposure.Deflicker.Resolve(false) || project.Exposure.HolyGrail.Resolve(false),
|
||||
project.Exposure.WhiteBalanceSmoothing.Resolve(false),
|
||||
project.Motion.Stabilize.Resolve(false),
|
||||
project.Motion.StabilizeSmoothing.Resolve(new StabilizerOptions().SmoothingSigma));
|
||||
|
||||
/// <summary>The deep analysis describes the current frames (its luminance is reused).</summary>
|
||||
private bool HasDeepAnalysis => content.Deep is { } deep && deep.FrameCount == content.Count;
|
||||
|
||||
private PrecomputedAnalysis? DeepLuminance => HasDeepAnalysis
|
||||
? new PrecomputedAnalysis { LogLuminance = [.. content.Deep!.Frames.LogLuminance.Select(v => v ?? double.NaN)] }
|
||||
: null;
|
||||
|
||||
/// <summary>
|
||||
/// Luminance (deflicker forced on while it is wanted, so it is measured or taken from the deep analysis), colour
|
||||
/// means and the stabilisation path for the project's exclusions, prepared once per <see cref="MeasureKey"/>.
|
||||
/// </summary>
|
||||
private async Task<RenderCorrections> MeasureAsync(ProjectSettings project, CancellationToken cancellationToken)
|
||||
{
|
||||
var key = MeasureKey(project);
|
||||
lock (_gate)
|
||||
{
|
||||
if (_measured is { } measured && measured.Key == key) return measured.Corrections;
|
||||
}
|
||||
var (luminance, whiteBalance, stabilize, smoothing) = Measured(project);
|
||||
var basis = new ProjectSettings();
|
||||
var measuring = basis with
|
||||
{
|
||||
Exposure = basis.Exposure with
|
||||
{
|
||||
Deflicker = basis.Exposure.Deflicker.WithManual(luminance),
|
||||
WhiteBalanceSmoothing = basis.Exposure.WhiteBalanceSmoothing.WithManual(whiteBalance),
|
||||
},
|
||||
Motion = basis.Motion with { Stabilize = basis.Motion.Stabilize.WithManual(stabilize), StabilizeSmoothing = basis.Motion.StabilizeSmoothing.WithManual(smoothing) },
|
||||
ExcludedFrames = project.ExcludedFrames,
|
||||
};
|
||||
var corrections = await RenderPreparation.PrepareAsync(Input(measuring, DeepLuminance), Options, null, cancellationToken).ConfigureAwait(false);
|
||||
lock (_gate) _measured = (key, corrections);
|
||||
return corrections;
|
||||
}
|
||||
|
||||
/// <summary>The measured series a re-solve reuses.</summary>
|
||||
private PrecomputedAnalysis Reuse(RenderCorrections measured, ProjectSettings project) => new()
|
||||
{
|
||||
LogLuminance = Measured(project).Luminance ? measured.MeasuredLogLuminance : null,
|
||||
Stabilization = measured.Stabilization is { } corrections
|
||||
// The zoom is 1 / max(crop scale, 0.75), so its inverse is the crop scale the render zooms by.
|
||||
? new StabilizationResult([], [], [], corrections, measured.Report.ShakeRms ?? 0, 1 / measured.StabilizationZoom, false)
|
||||
: null,
|
||||
StabilizationWidth = measured.StabilizationWidth,
|
||||
StabilizationHeight = measured.StabilizationHeight,
|
||||
StabilizationSmoothing = Measured(project).Smoothing,
|
||||
};
|
||||
|
||||
private RenderInput Input(ProjectSettings project, PrecomputedAnalysis? analysis) => new()
|
||||
{
|
||||
Source = _frames,
|
||||
Frames = SourceFrameInfo.From(content.Frames, content.Light.AdjustedTimes.Length == content.Count ? content.Light.AdjustedTimes : null),
|
||||
Project = project with { ExcludedFrames = [.. project.ExcludedFrames.Union(content.NotRenderable()).Order()] },
|
||||
Analysis = analysis,
|
||||
};
|
||||
|
||||
private (RenderGeometry Geometry, int DecodeEdge)? Geometry(PreviewRequest request, RenderCorrections? corrections)
|
||||
{
|
||||
if ((uint)request.Index >= (uint)content.Count || content.SourceWidth <= 0 || content.SourceHeight <= 0) return null;
|
||||
var export = ExportResolver.Resolve(request.Project.Export);
|
||||
var full = RenderGeometry.Create(request.Project.Camera, export, content.SourceWidth, content.SourceHeight, corrections?.StabilizationZoom ?? 1,
|
||||
request.LongEdge);
|
||||
var (width, height) = Resampler.FitWithin(full.OutputWidth, full.OutputHeight, request.LongEdge);
|
||||
var geometry = full.WithOutputSize(int.Max(1, width), int.Max(1, height));
|
||||
var edge = request.Framing == PreviewFraming.Source ? request.LongEdge : geometry.WorkingLongEdge;
|
||||
return (geometry, int.Max(16, edge));
|
||||
}
|
||||
|
||||
/// <summary>Decodes, corrects and frames one source frame: (corrected, original, output→picture plan).</summary>
|
||||
private async Task<(ImageBuffer, ImageBuffer, GeometryPlan?)?> PictureAsync(int index, PreviewRequest request, RenderCorrections? corrections,
|
||||
RenderGeometry geometry, int edge, CancellationToken cancellationToken)
|
||||
{
|
||||
var decoded = await source.DecodeAsync(index, edge, DecodePurpose.Proxy, cancellationToken).ConfigureAwait(false);
|
||||
if (decoded is null) return null;
|
||||
var raw = Rgb(decoded);
|
||||
ImageBuffer? corrected = null;
|
||||
try
|
||||
{
|
||||
corrected = raw.Clone();
|
||||
if (corrections is not null && corrections.FrameCount == content.Count) ApplyExposure(corrected, index, corrections);
|
||||
var settings = geometry.For(raw.Width, raw.Height, index, corrections?.StabilizationAt(index, raw.Width, raw.Height) ?? Affine2D.Identity);
|
||||
var plan = GeometryStage.Plan(raw.Width, raw.Height, settings);
|
||||
if (request.Framing == PreviewFraming.Output)
|
||||
{
|
||||
var framed = GeometryStage.Apply(corrected, settings, cancellationToken);
|
||||
corrected.Dispose();
|
||||
corrected = framed;
|
||||
framed = GeometryStage.Apply(raw, settings, cancellationToken);
|
||||
raw.Dispose();
|
||||
raw = framed;
|
||||
}
|
||||
if (request.Project.Exposure.HighlightKnee is > 0 and < 1 and var knee) ExposureProcessor.Apply(corrected, 0, null, knee);
|
||||
return (corrected, raw, request.Framing == PreviewFraming.Output ? null : plan);
|
||||
}
|
||||
catch
|
||||
{
|
||||
corrected?.Dispose();
|
||||
raw.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The render's exposure stage: region curves through the resampled sky mask, else the global correction, with white-balance gains.</summary>
|
||||
private static void ApplyExposure(ImageBuffer frame, int index, RenderCorrections corrections)
|
||||
{
|
||||
var gains = corrections.WhiteBalance?[index];
|
||||
if (corrections is { Regions: { } mask, SkyEv: { } sky, LandEv: { } land })
|
||||
{
|
||||
ExposureProcessor.ApplyRegion(frame, mask.Resample(frame.Width, frame.Height).Sky, sky[index], land[index], gains);
|
||||
return;
|
||||
}
|
||||
var ev = corrections.ExposureEv[index];
|
||||
if (ev != 0 || (gains is { } g && g != ChannelGains.Identity)) ExposureProcessor.Apply(frame, ev, gains);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Optical flow from this frame to the next, both rendered small the same way (whatever the preview's size, even
|
||||
/// 1:1), sampled on a grid and scaled to the <paramref name="width"/>×<paramref name="height"/> picture.
|
||||
/// </summary>
|
||||
private async Task<IReadOnlyList<VectorSample>> VectorsAsync(PreviewRequest request, RenderCorrections? corrections, int width, int height,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var small = request with { LongEdge = int.Min(request.LongEdge, VectorLongEdge), Vectors = false, Waveform = false };
|
||||
if (Geometry(small, corrections) is not var (geometry, edge)) return [];
|
||||
var current = await PictureAsync(request.Index, small, corrections, geometry, edge, cancellationToken).ConfigureAwait(false);
|
||||
if (current is not var (a, aOriginal, _)) return [];
|
||||
aOriginal.Dispose();
|
||||
using (a)
|
||||
{
|
||||
var next = await PictureAsync(request.Index + 1, small, corrections, geometry, edge, cancellationToken).ConfigureAwait(false);
|
||||
if (next is not var (b, bOriginal, _)) return [];
|
||||
bOriginal.Dispose();
|
||||
using (b)
|
||||
{
|
||||
using var conformed = b.Width == a.Width && b.Height == a.Height ? null : Resampler.Resize(b, a.Width, a.Height);
|
||||
using var engine = new OpticalFlowEngine(FlowQuality.Draft);
|
||||
using var field = engine.Compute(a, conformed ?? b, cancellationToken);
|
||||
var (sx, sy) = ((double)width / a.Width, (double)height / a.Height);
|
||||
var spacing = double.Max(8, int.Max(width, height) / (double)VectorColumns);
|
||||
var samples = new List<VectorSample>();
|
||||
for (var y = spacing / 2; y < height; y += spacing)
|
||||
{
|
||||
for (var x = spacing / 2; x < width; x += spacing)
|
||||
{
|
||||
var (u, v) = field.Sample(x / sx, y / sy);
|
||||
samples.Add(new VectorSample((float)x, (float)y, (float)(u * sx), (float)(v * sy)));
|
||||
}
|
||||
}
|
||||
return samples;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The output's footprint on the source picture (bounding box of the warped output corners), normalised.</summary>
|
||||
private static RectD CropOf(GeometryPlan? plan, int width, int height)
|
||||
{
|
||||
if (plan is not { } p) return new RectD(0, 0, 1, 1);
|
||||
double left = double.MaxValue, top = double.MaxValue, right = double.MinValue, bottom = double.MinValue;
|
||||
foreach (var (u, v) in new[] { (-0.5, -0.5), (p.OutputWidth - 0.5, -0.5), (-0.5, p.OutputHeight - 0.5), (p.OutputWidth - 0.5, p.OutputHeight - 0.5) })
|
||||
{
|
||||
var (x, y) = p.OutputToSource.Apply(u, v);
|
||||
(left, top, right, bottom) = (double.Min(left, x + 0.5), double.Min(top, y + 0.5), double.Max(right, x + 0.5), double.Max(bottom, y + 0.5));
|
||||
}
|
||||
left = double.Clamp(left / width, 0, 1);
|
||||
top = double.Clamp(top / height, 0, 1);
|
||||
return new RectD(left, top, double.Clamp(right / width, 0, 1) - left, double.Clamp(bottom / height, 0, 1) - top);
|
||||
}
|
||||
|
||||
/// <summary>The analysed horizon (normalised rows at evenly spaced columns) in pixels of the whole-frame picture.</summary>
|
||||
private IReadOnlyList<(double X, double Y)> HorizonOf(int width, int height)
|
||||
{
|
||||
if (content.Deep?.Regions is not { Horizon: { Length: > 1 } rows }) return [];
|
||||
var points = new (double X, double Y)[rows.Length];
|
||||
for (var k = 0; k < rows.Length; k++) points[k] = ((double)k / (rows.Length - 1) * width, rows[k] * height);
|
||||
return points;
|
||||
}
|
||||
|
||||
/// <summary>Gray sources become RGB and alpha is dropped, as in the render.</summary>
|
||||
private static ImageBuffer Rgb(ImageBuffer frame)
|
||||
{
|
||||
if (frame.Channels == 3) return frame;
|
||||
using (frame)
|
||||
{
|
||||
if (frame.Channels == 1) return PixelConvert.GrayToRgb(frame);
|
||||
var rgb = new ImageBuffer(frame.Width, frame.Height, 3, clear: false);
|
||||
frame.Data[..(3 * frame.PlaneLength)].CopyTo(rgb.Data);
|
||||
return rgb;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sequence as the preparations read it. Analysis-size decodes are kept in half precision (a quarter of a
|
||||
/// 128-px frame in floats, about 65 KB) within a budget of 1/16 of the memory available to the process (64–512 MB,
|
||||
/// several thousand frames), least recently decoded dropped first, so changing a setting re-measures from memory.
|
||||
/// </summary>
|
||||
private sealed class CompactFrames(SequenceContent content, ISequenceSource source) : IRenderFrameSource
|
||||
{
|
||||
private static readonly long Budget = long.Clamp(GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / 16, 64L << 20, 512L << 20);
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Dictionary<(int Index, int Edge), Stored> _cache = [];
|
||||
private readonly LinkedList<(int Index, int Edge)> _order = new();
|
||||
private long _bytes;
|
||||
private int _decodes;
|
||||
|
||||
public int FrameCount => content.Count;
|
||||
|
||||
public int Width => content.SourceWidth;
|
||||
|
||||
public int Height => content.SourceHeight;
|
||||
|
||||
public int Decodes => Volatile.Read(ref _decodes);
|
||||
|
||||
public async ValueTask<ImageBuffer> GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
|
||||
{
|
||||
Stored? hit;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_cache.TryGetValue((index, maxLongEdge), out hit))
|
||||
{
|
||||
_order.Remove(hit.Node);
|
||||
_order.AddLast(hit.Node);
|
||||
}
|
||||
}
|
||||
if (hit is not null) return hit.Expand();
|
||||
var frame = await source.DecodeAsync(index, maxLongEdge, purpose, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new RenderException("Export.Render.FrameUnreadable", $"Frame {index + 1} could not be decoded.",
|
||||
[(index + 1).ToString(CultureInfo.InvariantCulture), content.Frames[index].FileName]);
|
||||
Interlocked.Increment(ref _decodes);
|
||||
var stored = Stored.From(frame, new LinkedListNode<(int, int)>((index, maxLongEdge)));
|
||||
lock (_gate)
|
||||
{
|
||||
if (stored.Bytes <= Budget && _cache.TryAdd((index, maxLongEdge), stored))
|
||||
{
|
||||
_order.AddLast(stored.Node);
|
||||
_bytes += stored.Bytes;
|
||||
while (_bytes > Budget && _order.First is { } oldest)
|
||||
{
|
||||
_order.RemoveFirst();
|
||||
if (_cache.Remove(oldest.Value, out var dropped)) _bytes -= dropped.Bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
return frame;
|
||||
}
|
||||
|
||||
private sealed class Stored(int width, int height, int channels, Half[] samples, LinkedListNode<(int, int)> node)
|
||||
{
|
||||
public LinkedListNode<(int, int)> Node { get; } = node;
|
||||
|
||||
public long Bytes => (long)samples.Length * sizeof(short);
|
||||
|
||||
public static Stored From(ImageBuffer frame, LinkedListNode<(int, int)> node)
|
||||
{
|
||||
var data = frame.Data;
|
||||
var samples = new Half[data.Length];
|
||||
for (var i = 0; i < data.Length; i++) samples[i] = (Half)data[i];
|
||||
return new Stored(frame.Width, frame.Height, frame.Channels, samples, node);
|
||||
}
|
||||
|
||||
public ImageBuffer Expand()
|
||||
{
|
||||
var frame = new ImageBuffer(width, height, channels, clear: false);
|
||||
var data = frame.Data;
|
||||
for (var i = 0; i < data.Length; i++) data[i] = (float)samples[i];
|
||||
return frame;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
using System.IO;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.App.Shell;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Processing;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// <c>.chronos</c> project files (BRIEF §18): the editor saves one for the open sequence of this PC's archive, and
|
||||
/// opening one (a double-click, which Windows passes to Chronos.exe) opens its sequence in the editor and gives it the
|
||||
/// file's settings as one undoable step.
|
||||
/// </summary>
|
||||
public sealed class ProjectFiles(ShellViewModel shell)
|
||||
{
|
||||
/// <summary>Asks for a folder and saves the session's sequence and current settings there; never replaces a file.</summary>
|
||||
public async Task SaveAsync(EditorSession session)
|
||||
{
|
||||
if (session.IsRemote) return;
|
||||
if (shell.Services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
|
||||
if (shell.Services.Dialogs.PickFolder(Loc.L("Editor.ProjectFile.Title")) is not { } folder) return;
|
||||
var bundle = await ProjectBundles.CreateAsync(db, session.Content.Sequence.Id, session.Project, session.Content.Count);
|
||||
var path = await Task.Run(() =>
|
||||
{
|
||||
var free = ProjectBundle.FreePathIn(folder, bundle.Sequence.Title ?? session.Content.Sequence.DisplayTitle);
|
||||
bundle.Save(free);
|
||||
return free;
|
||||
});
|
||||
Log.Info("project", $"Project file '{path}' saved for sequence {bundle.Sequence.Id}");
|
||||
shell.Notify(Loc.L("Editor.ProjectFile.Saved"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"),
|
||||
() => ShellActions.Reveal(path));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens the project file at <paramref name="path"/>: its sequence in the editor (found by id, else by archive and
|
||||
/// folder), then the file's settings as one undo step. Says in one sentence why when the file cannot be read, its
|
||||
/// sequence is not in the library, or the sequence cannot take the settings now.
|
||||
/// </summary>
|
||||
public async Task OpenAsync(string path)
|
||||
{
|
||||
ProjectBundle bundle;
|
||||
try
|
||||
{
|
||||
bundle = await Task.Run(() => ProjectBundle.Load(path));
|
||||
}
|
||||
catch (Exception ex) when (ex is InvalidDataException or IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("project", $"Project file '{path}' not opened", ex);
|
||||
shell.Notify(Loc.L("Editor.ProjectFile.Unreadable"), Path.GetFileName(path), Loc.L("Common.OpenLogs"), Loc.L("Tooltips.Common.OpenLogs"),
|
||||
() => ShellActions.Reveal(shell.Services.Environment.LogDirectory), isError: true);
|
||||
return;
|
||||
}
|
||||
if (shell.Services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
|
||||
if (await ProjectBundles.ResolveAsync(db, bundle) is not { } sequence)
|
||||
{
|
||||
Log.Info("project", $"Project file '{path}': sequence {bundle.Sequence.Id} ('{bundle.Sequence.Folder}' in archive {bundle.Archive.Id}) not in the index");
|
||||
shell.Notify(Loc.L("Editor.ProjectFile.NotFound"), bundle.Sequence.Title ?? Path.GetFileName(path), Loc.L("Shell.Nav.Archive"),
|
||||
Loc.L("Tooltips.Nav.Archive"), () => shell.Navigate(SectionKey.Archive), isError: true);
|
||||
return;
|
||||
}
|
||||
// Not opened: the editor said why, or kept the open sequence's edit the user chose not to discard.
|
||||
if (await shell.Sequence.ShowAsync(sequence.Id) is not { } editor) return;
|
||||
Apply(editor, bundle);
|
||||
}
|
||||
|
||||
/// <summary>Gives the open sequence the file's settings, unless the editor cannot change them now (a job runs, read-only).</summary>
|
||||
private void Apply(EditorViewModel editor, ProjectBundle bundle)
|
||||
{
|
||||
var session = editor.Session;
|
||||
var settings = bundle.ProjectFor(session.Project, session.Content.Count);
|
||||
if (settings.ToJson() == session.Project.ToJson()) return;
|
||||
if (editor.IsLocked)
|
||||
{
|
||||
shell.Notify(Loc.L("Editor.ProjectFile.Locked"), editor.LockedToolTip, Loc.L("Editor.ProjectFile.Retry"), Loc.L("Tooltips.Editor.ProjectFile.Retry"),
|
||||
() =>
|
||||
{
|
||||
// Still the same editor: the file's settings, laid over the project as it is then.
|
||||
if (ReferenceEquals(shell.Sequence.Editor, editor)) Apply(editor, bundle);
|
||||
}, isError: true);
|
||||
return;
|
||||
}
|
||||
var before = session.Project;
|
||||
if (!session.Edit(_ => settings)) return;
|
||||
session.EndEditRun();
|
||||
var restore = new ProjectRestore(session, before, session.Project);
|
||||
Log.Info("project", $"Project file settings applied to sequence {session.Content.Sequence.Id}");
|
||||
shell.Notify(Loc.L("Editor.ProjectFile.Applied"), session.Content.Sequence.DisplayTitle, Loc.L("Editor.ProjectFile.Undo"),
|
||||
Loc.L("Tooltips.Editor.ProjectFile.Undo"), () => restore.Undo());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
using Chronos.Core.Project;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// Undo and redo of the editor's project (Ctrl+Z / Ctrl+Y). Projects are immutable, so each step is a snapshot.
|
||||
/// Consecutive edits with the same <c>mergeKey</c> (one slider drag, typing in one field) form a single step until
|
||||
/// <see cref="EndRun"/> (the drag or key press ended); any other edit, undo or redo also ends the run. The oldest steps
|
||||
/// are dropped beyond <see cref="Capacity"/>.
|
||||
/// </summary>
|
||||
public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200)
|
||||
{
|
||||
private readonly LinkedList<ProjectSettings> _undo = new();
|
||||
private readonly LinkedList<ProjectSettings> _redo = new();
|
||||
private string? _runKey;
|
||||
|
||||
/// <summary>The project, after any edit, undo, redo or <see cref="Replace"/>.</summary>
|
||||
public event Action? Changed;
|
||||
|
||||
public ProjectSettings Current { get; private set; } = initial ?? throw new ArgumentNullException(nameof(initial));
|
||||
|
||||
public int Capacity { get; } = capacity > 0 ? capacity : throw new ArgumentOutOfRangeException(nameof(capacity));
|
||||
|
||||
public bool CanUndo => _undo.Count > 0;
|
||||
|
||||
public bool CanRedo => _redo.Count > 0;
|
||||
|
||||
/// <summary>Makes <paramref name="next"/> current as an undoable step; false (and nothing recorded) when it stores the same values.</summary>
|
||||
public bool Apply(ProjectSettings next, string? mergeKey = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(next);
|
||||
if (ProjectMerge.SameValues(next, Current)) return false;
|
||||
if (mergeKey is null || mergeKey != _runKey || _undo.Count == 0)
|
||||
{
|
||||
_undo.AddLast(Current);
|
||||
if (_undo.Count > Capacity) _undo.RemoveFirst();
|
||||
}
|
||||
_runKey = mergeKey;
|
||||
_redo.Clear();
|
||||
Current = next;
|
||||
Changed?.Invoke();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The gesture behind a run of merged edits ended: the next edit is a new step even with the same key.</summary>
|
||||
public void EndRun() => _runKey = null;
|
||||
|
||||
public bool Undo()
|
||||
{
|
||||
if (_undo.Last is not { } previous) return false;
|
||||
_undo.RemoveLast();
|
||||
_redo.AddLast(Current);
|
||||
return Move(previous.Value);
|
||||
}
|
||||
|
||||
public bool Redo()
|
||||
{
|
||||
if (_redo.Last is not { } next) return false;
|
||||
_redo.RemoveLast();
|
||||
_undo.AddLast(Current);
|
||||
return Move(next.Value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adopts a project changed outside the editor (analysis advice, another client's edit merged on save) without an
|
||||
/// undo step. Every undo and redo snapshot takes the same outside change, so undo reverts only the user's own steps
|
||||
/// and never brings back a value that predates the adopted change.
|
||||
/// </summary>
|
||||
public void Replace(ProjectSettings current)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(current);
|
||||
if (ProjectMerge.SameValues(current, Current)) return;
|
||||
var rebase = new ProjectMerge.Rebase(Current, current);
|
||||
Rebase(_undo, rebase);
|
||||
Rebase(_redo, rebase);
|
||||
_runKey = null;
|
||||
Current = current;
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rewrites the project and every undo and redo snapshot with <paramref name="remap"/>, without an undo step: a change
|
||||
/// of what the values mean rather than of the values (frame positions following frames inserted under the editor), so
|
||||
/// undo and redo keep naming the same frames.
|
||||
/// </summary>
|
||||
public void Remap(Func<ProjectSettings, ProjectSettings> remap)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(remap);
|
||||
foreach (var steps in new[] { _undo, _redo })
|
||||
{
|
||||
for (var node = steps.First; node is not null; node = node.Next) node.Value = remap(node.Value);
|
||||
}
|
||||
var current = remap(Current);
|
||||
if (ProjectMerge.SameValues(current, Current)) return;
|
||||
_runKey = null;
|
||||
Current = current;
|
||||
Changed?.Invoke();
|
||||
}
|
||||
|
||||
private static void Rebase(LinkedList<ProjectSettings> steps, ProjectMerge.Rebase rebase)
|
||||
{
|
||||
for (var node = steps.First; node is not null; node = node.Next) node.Value = rebase.Apply(node.Value);
|
||||
}
|
||||
|
||||
private bool Move(ProjectSettings target)
|
||||
{
|
||||
_runKey = null;
|
||||
Current = target;
|
||||
Changed?.Invoke();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Sync;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// Three-way merge of projects: the editor's edit (<c>ours</c>) and a change stored meanwhile by someone else
|
||||
/// (<c>theirs</c>: an analysis filling Auto values, another client through the server), both made from <c>basis</c>.
|
||||
/// Values are compared member by member down the JSON tree; a member only one side changed takes that side's value, a
|
||||
/// member both changed takes the editor's (the user is looking at it). <see cref="Conflicts"/> lists those members for
|
||||
/// a source that asks the user instead (a server sequence, BRIEF §14.5).
|
||||
/// </summary>
|
||||
public static class ProjectMerge
|
||||
{
|
||||
public static ProjectSettings Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
ArgumentNullException.ThrowIfNull(ours);
|
||||
ArgumentNullException.ThrowIfNull(theirs);
|
||||
return new Rebase(basis, theirs).Apply(ours);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The members both sides changed to different values, in document order: the path below the project
|
||||
/// ("exposure.deflickerWindow.manual"), the editor's value and theirs as JSON (null when absent).
|
||||
/// </summary>
|
||||
public static IReadOnlyList<SettingsDifference> Conflicts(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
ArgumentNullException.ThrowIfNull(ours);
|
||||
ArgumentNullException.ThrowIfNull(theirs);
|
||||
var conflicts = new List<SettingsDifference>();
|
||||
Collect(JsonNode.Parse(basis.ToJson()), JsonNode.Parse(ours.ToJson()), JsonNode.Parse(theirs.ToJson()), string.Empty, conflicts);
|
||||
return conflicts;
|
||||
}
|
||||
|
||||
/// <summary>True when both projects store the same values.</summary>
|
||||
public static bool SameValues(ProjectSettings a, ProjectSettings b) => a.ToJson() == b.ToJson();
|
||||
|
||||
private static JsonNode? Merge(JsonNode? basis, JsonNode? ours, JsonNode? theirs)
|
||||
{
|
||||
if (JsonNode.DeepEquals(ours, basis)) return theirs?.DeepClone();
|
||||
if (JsonNode.DeepEquals(theirs, basis) || JsonNode.DeepEquals(theirs, ours)) return ours?.DeepClone();
|
||||
if (ours is not JsonObject mine || theirs is not JsonObject other) return ours?.DeepClone();
|
||||
var common = basis as JsonObject;
|
||||
var merged = new JsonObject();
|
||||
foreach (var name in mine.Select(p => p.Key).Union(other.Select(p => p.Key)))
|
||||
{
|
||||
var value = Merge(common?[name], mine[name], other[name]);
|
||||
if (value is not null || mine.ContainsKey(name)) merged[name] = value;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
/// <summary>The members <see cref="Merge(JsonNode?, JsonNode?, JsonNode?)"/> settles for the editor although both sides changed them.</summary>
|
||||
private static void Collect(JsonNode? basis, JsonNode? ours, JsonNode? theirs, string path, List<SettingsDifference> conflicts)
|
||||
{
|
||||
if (JsonNode.DeepEquals(ours, basis) || JsonNode.DeepEquals(theirs, basis) || JsonNode.DeepEquals(theirs, ours)) return;
|
||||
if (ours is JsonObject mine && theirs is JsonObject other)
|
||||
{
|
||||
var common = basis as JsonObject;
|
||||
foreach (var name in mine.Select(p => p.Key).Union(other.Select(p => p.Key)))
|
||||
Collect(common?[name], mine[name], other[name], path.Length == 0 ? name : path + "." + name, conflicts);
|
||||
return;
|
||||
}
|
||||
conflicts.Add(new SettingsDifference(path.Length == 0 ? "settings" : path, ours?.ToJsonString(), theirs?.ToJsonString()));
|
||||
}
|
||||
|
||||
/// <summary>One outside change (<paramref name="basis"/> → <paramref name="theirs"/>) applied to any number of projects made from the basis.</summary>
|
||||
public sealed class Rebase(ProjectSettings basis, ProjectSettings theirs)
|
||||
{
|
||||
private readonly JsonNode? _basis = JsonNode.Parse(basis.ToJson());
|
||||
private readonly JsonNode? _theirs = JsonNode.Parse(theirs.ToJson());
|
||||
|
||||
public ProjectSettings Apply(ProjectSettings ours)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(ours);
|
||||
return ProjectSettings.FromJson(Merge(_basis, JsonNode.Parse(ours.ToJson()), _theirs)?.ToJsonString() ?? "{}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
using Chronos.Core.Project;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// Writes the editor's project shortly after the last change: one write at a time, always the newest project, never
|
||||
/// cancelled half way (a write is a file plus an index row). A failed write keeps the project pending and is retried
|
||||
/// with a growing delay (2 s doubling up to <see cref="MaxRetryDelay"/>) until it is stored, so nothing is dropped
|
||||
/// while the archive is offline or busy. <see cref="FlushAsync"/> skips the wait and reports whether everything is
|
||||
/// stored after one more attempt; <see cref="HoldAsync"/> keeps a failed change as it is while the user decides about
|
||||
/// it. Runs on the context that scheduled the first write (the UI thread).
|
||||
/// </summary>
|
||||
public sealed class ProjectSaver(Func<ProjectSettings, Task> save, TimeSpan delay)
|
||||
{
|
||||
public static readonly TimeSpan MaxRetryDelay = TimeSpan.FromMinutes(1);
|
||||
|
||||
private readonly Lock _gate = new();
|
||||
private readonly List<TaskCompletionSource<bool>> _flushes = [];
|
||||
private ProjectSettings? _pending;
|
||||
private bool _running;
|
||||
private bool _flushRequested;
|
||||
private bool _stopped;
|
||||
private int _failures;
|
||||
private CancellationTokenSource? _wait;
|
||||
|
||||
/// <summary>No write starts until <see cref="Release"/> (or <see cref="Stop"/>): the user is being asked about the pending change.</summary>
|
||||
private bool _held;
|
||||
|
||||
/// <summary>Completes when the hold ends; the loop waits on it instead of writing.</summary>
|
||||
private TaskCompletionSource? _released;
|
||||
|
||||
/// <summary>Completes when the write under way ends (stored or failed, the outcome recorded); null between writes.</summary>
|
||||
private TaskCompletionSource? _writeEnded;
|
||||
|
||||
/// <summary>A write failed: the exception and how many writes in a row failed (1 for the first of a streak).</summary>
|
||||
public event Action<Exception, int>? Failed;
|
||||
|
||||
/// <summary>A change waits for its write, is being written, or failed and waits for its retry.</summary>
|
||||
public bool HasPendingChanges
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (_gate) return _running;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Why the pending change could not be stored; null when the last write succeeded.</summary>
|
||||
public Exception? LastError { get; private set; }
|
||||
|
||||
public void Schedule(ProjectSettings project)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
TaskCompletionSource start;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_stopped) return;
|
||||
_pending = project;
|
||||
if (_running) return;
|
||||
_running = true;
|
||||
start = new TaskCompletionSource();
|
||||
_ = LoopAsync(start.Task);
|
||||
}
|
||||
// The loop starts outside the lock: with nothing to wait for it would otherwise save while holding it.
|
||||
start.SetResult();
|
||||
}
|
||||
|
||||
/// <summary>Stores what is pending now, without the delay.</summary>
|
||||
/// <returns>True when everything is stored; false when the attempt failed (the change stays pending and is retried).</returns>
|
||||
public Task<bool> FlushAsync()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_running) return Task.FromResult(true);
|
||||
var done = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_flushes.Add(done);
|
||||
_flushRequested = true;
|
||||
_wait?.Cancel();
|
||||
return done.Task;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the loop from starting another write until <see cref="Release"/> or <see cref="Stop"/>, once the write under
|
||||
/// way (if any) has ended: a retry that succeeds while the user is asked whether to discard the change would store
|
||||
/// what they are about to drop.
|
||||
/// </summary>
|
||||
/// <returns>True when a change is still not stored (it waits for the user's word); false when everything is stored.</returns>
|
||||
public async Task<bool> HoldAsync()
|
||||
{
|
||||
Task? ended;
|
||||
lock (_gate)
|
||||
{
|
||||
_held = true;
|
||||
ended = _writeEnded?.Task;
|
||||
}
|
||||
if (ended is not null) await ended;
|
||||
lock (_gate) return _pending is not null;
|
||||
}
|
||||
|
||||
/// <summary>Ends <see cref="HoldAsync"/>: the pending change is retried as before (the user kept it).</summary>
|
||||
public void Release()
|
||||
{
|
||||
lock (_gate) ReleaseHold();
|
||||
}
|
||||
|
||||
/// <summary>Drops what is pending and stops retrying (the editor closed and the user chose to discard the change).</summary>
|
||||
public void Stop()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_stopped = true;
|
||||
_pending = null;
|
||||
_wait?.Cancel();
|
||||
ReleaseHold();
|
||||
}
|
||||
}
|
||||
|
||||
private void ReleaseHold()
|
||||
{
|
||||
_held = false;
|
||||
_released?.TrySetResult();
|
||||
_released = null;
|
||||
}
|
||||
|
||||
private async Task LoopAsync(Task started)
|
||||
{
|
||||
await started;
|
||||
var wait = delay;
|
||||
while (true)
|
||||
{
|
||||
CancellationTokenSource? timer = null;
|
||||
lock (_gate)
|
||||
{
|
||||
if (!_flushRequested && wait > TimeSpan.Zero) timer = _wait = new CancellationTokenSource();
|
||||
}
|
||||
if (timer is not null)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Task.Delay(wait, timer.Token);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
}
|
||||
lock (_gate) _wait = null;
|
||||
timer.Dispose();
|
||||
}
|
||||
Task? hold;
|
||||
lock (_gate) hold = _held ? (_released ??= new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)).Task : null;
|
||||
if (hold is not null)
|
||||
{
|
||||
await hold;
|
||||
continue;
|
||||
}
|
||||
ProjectSettings next;
|
||||
lock (_gate)
|
||||
{
|
||||
_flushRequested = false;
|
||||
if (_pending is null)
|
||||
{
|
||||
_running = false;
|
||||
Complete(true);
|
||||
return;
|
||||
}
|
||||
next = _pending;
|
||||
_pending = null;
|
||||
// Taken under the lock with the change, so a hold asked for from now on waits for this write.
|
||||
_writeEnded = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
int failures;
|
||||
try
|
||||
{
|
||||
// Started outside the lock (a write may run synchronously up to its first wait).
|
||||
await SaveAsync(next);
|
||||
LastError = null;
|
||||
lock (_gate)
|
||||
{
|
||||
_failures = 0;
|
||||
EndWrite();
|
||||
}
|
||||
// A change made during the write is written right after it.
|
||||
wait = TimeSpan.Zero;
|
||||
continue;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LastError = ex;
|
||||
lock (_gate)
|
||||
{
|
||||
// A newer change contains this one (projects are whole snapshots); otherwise this one waits for the retry.
|
||||
if (!_stopped) _pending ??= next;
|
||||
failures = ++_failures;
|
||||
EndWrite();
|
||||
}
|
||||
wait = TimeSpan.FromSeconds(double.Min(MaxRetryDelay.TotalSeconds, double.Pow(2, failures)));
|
||||
Failed?.Invoke(ex, failures);
|
||||
// Flushes learn the outcome after the failure was reported.
|
||||
lock (_gate) Complete(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void EndWrite()
|
||||
{
|
||||
_writeEnded?.TrySetResult();
|
||||
_writeEnded = null;
|
||||
}
|
||||
|
||||
/// <summary>The write as a task, also when <c>save</c> throws before returning one.</summary>
|
||||
private Task SaveAsync(ProjectSettings project)
|
||||
{
|
||||
try
|
||||
{
|
||||
return save(project);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return Task.FromException(ex);
|
||||
}
|
||||
}
|
||||
|
||||
private void Complete(bool stored)
|
||||
{
|
||||
foreach (var flush in _flushes) flush.TrySetResult(stored);
|
||||
_flushes.Clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Advice;
|
||||
using Chronos.Core.Analysis;
|
||||
using Chronos.Core.Analysis.Deep;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Imaging;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Core.Render;
|
||||
using Chronos.Data.Archiving.Jobs;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Sync;
|
||||
using Chronos.Protocol;
|
||||
using Chronos.Protocol.Client;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// A server sequence opened with proxies (BRIEF §4.4, §14.5 "edit with proxies, render where the originals are"):
|
||||
/// frames and thumbnails from this PC's proxy cache (<see cref="RemoteSequence.OpenFrames"/>), the project from the
|
||||
/// server's settings with their version, the deep analysis from the server's report. Saves send the settings with the
|
||||
/// version they were made from; a 409 (someone changed them meanwhile) reads the server's settings and merges again
|
||||
/// (<see cref="ProjectMerge"/>) when the two changes touch different settings. A setting both changed to different
|
||||
/// values is a conflict the user settles (BRIEF §14.5 "explicit conflict prompt"): <see cref="ProjectConflictException"/>,
|
||||
/// and nothing is sent until the editor's next save names the server's settings as its basis. Nothing is written to a
|
||||
/// local archive. Analyses and renders are server jobs; their state and progress come from the server's events.
|
||||
/// Project settings name frames by position, so the cached frames must be the server's: a load that finds other frames
|
||||
/// throws <see cref="ProxiesOutdatedException"/>, and frames that change on the server while the sequence is open make
|
||||
/// it <see cref="IsOutdated"/> (read-only, nothing saved or rendered). Saves name the frames version the editor's frames
|
||||
/// are at, so the server refuses one made against frames it no longer has even before its event arrives.
|
||||
/// </summary>
|
||||
public sealed class RemoteSequenceSource : ISequenceSource
|
||||
{
|
||||
private const int SaveAttempts = 3;
|
||||
private static readonly TimeSpan MinBackoff = TimeSpan.FromSeconds(2);
|
||||
private static readonly TimeSpan MaxBackoff = TimeSpan.FromMinutes(1);
|
||||
|
||||
private readonly RemoteSequence _remote;
|
||||
private readonly IRemoteSequenceApi _api;
|
||||
private readonly IRenderFrameSource _frames;
|
||||
private readonly IFrameSource _pixels;
|
||||
private readonly ConcurrentDictionary<Guid, Job> _jobs = new();
|
||||
private readonly ConcurrentDictionary<Guid, byte> _foreign = new();
|
||||
private readonly CancellationTokenSource _stopping = new();
|
||||
private readonly Task _listening;
|
||||
private readonly bool _noEditRight;
|
||||
private Stored? _stored;
|
||||
private int _framesVersion = -1;
|
||||
private int _outdated;
|
||||
private int _disposed;
|
||||
|
||||
/// <param name="readOnly">The account may look at the sequence but not change it (no Edit right on the server).</param>
|
||||
public RemoteSequenceSource(RemoteSequence remote, IRemoteSequenceApi api, ImageDecoder decoder, bool readOnly = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(remote);
|
||||
ArgumentNullException.ThrowIfNull(api);
|
||||
ArgumentNullException.ThrowIfNull(decoder);
|
||||
_remote = remote;
|
||||
_api = api;
|
||||
_noEditRight = readOnly;
|
||||
_frames = remote.OpenFrames(decoder);
|
||||
_pixels = (IFrameSource)_frames;
|
||||
var stopping = _stopping.Token;
|
||||
_listening = Task.Run(() => ListenAsync(stopping), CancellationToken.None);
|
||||
}
|
||||
|
||||
public bool IsRemote => true;
|
||||
|
||||
public bool IsReadOnly => _noEditRight || IsOutdated;
|
||||
|
||||
public bool IsOutdated => Volatile.Read(ref _outdated) == 1;
|
||||
|
||||
public event Action? ReadOnlyChanged;
|
||||
|
||||
public event Action<Job>? JobChanged;
|
||||
|
||||
/// <summary>The server sequence's id.</summary>
|
||||
public Guid Id => _remote.Sequence.Id;
|
||||
|
||||
public async Task<SequenceContent> LoadAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var dto = await Call(() => _api.GetSequenceAsync(Id, cancellationToken));
|
||||
var manifest = await Call(() => _api.GetManifestAsync(Id, cancellationToken));
|
||||
if (!SameFrames(manifest)) throw Outdated();
|
||||
Volatile.Write(ref _framesVersion, manifest.FramesVersion);
|
||||
var report = await Call(() => _api.GetAnalysisReportAsync(Id, cancellationToken));
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
var project = Parse(manifest.SettingsJson);
|
||||
Volatile.Write(ref _stored, new Stored(project, manifest.SettingsVersion));
|
||||
var frames = _remote.Frames;
|
||||
var sequence = _remote.Sequence with
|
||||
{
|
||||
Title = dto.Title,
|
||||
Tags = dto.Tags,
|
||||
Rating = dto.Rating,
|
||||
Notes = dto.Notes,
|
||||
Status = (SequenceStatus)dto.Status,
|
||||
RenderedCount = dto.RenderedCount,
|
||||
HeroFrameId = dto.HeroFrameId,
|
||||
WarningCount = dto.WarningCount,
|
||||
PreviewOnlyCount = dto.PreviewOnlyCount,
|
||||
SettingsJson = manifest.SettingsJson,
|
||||
SettingsVersion = manifest.SettingsVersion,
|
||||
UpdatedAt = dto.UpdatedAt,
|
||||
};
|
||||
var context = SequenceContext.FromFrames(frames);
|
||||
var renders = manifest.Renders.OrderByDescending(r => r.Created).Select(r => new Render
|
||||
{
|
||||
Id = r.Id,
|
||||
SequenceId = Id,
|
||||
PresetName = r.PresetName,
|
||||
OutputPath = string.Empty,
|
||||
Codec = r.Codec,
|
||||
Width = r.Width,
|
||||
Height = r.Height,
|
||||
Fps = r.Fps,
|
||||
DurationSeconds = r.DurationSeconds,
|
||||
Bytes = r.Bytes,
|
||||
Created = r.Created,
|
||||
ProducedBy = r.ProducedBy,
|
||||
}).ToList();
|
||||
var (deep, otherFrames) = Report(report, frames.Count);
|
||||
return new SequenceContent(sequence, frames, project, LightAnalyzer.Analyze(frames), deep, context.SourceWidth, context.SourceHeight, null, renders, [])
|
||||
{
|
||||
DeepOfOtherFrames = otherFrames,
|
||||
};
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <remarks>Read from the server's manifest: a sequence whose frames are not this PC's becomes outdated.</remarks>
|
||||
public async Task<bool> FramesCurrentAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (IsOutdated) return false;
|
||||
return Compare(await Call(() => _api.GetManifestAsync(Id, cancellationToken)));
|
||||
}
|
||||
|
||||
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
|
||||
{
|
||||
if ((uint)index >= (uint)_remote.Frames.Count) return null;
|
||||
// The loader decodes synchronously: an async delegate keeps a superseded decode's cancellation in user code (R4).
|
||||
return await Task.Run(async () => await _pixels.LoadAsync(index, maxLongEdge, cancellationToken).ConfigureAwait(false), cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<ProjectSettings> SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
var (stored, version) = Volatile.Read(ref _stored) ?? throw new InvalidOperationException("LoadAsync first.");
|
||||
var changedThere = !ProjectMerge.SameValues(stored, basis);
|
||||
var merged = changedThere ? ProjectMerge.Merge(basis, project, stored) : project;
|
||||
if (ProjectMerge.SameValues(merged, stored)) return merged;
|
||||
if (IsOutdated) throw new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged"));
|
||||
if (_noEditRight) throw new EditorException(Loc.L("Editor.Error.RemoteReadOnly"));
|
||||
if (changedThere && ProjectMerge.Conflicts(basis, project, stored) is { Count: > 0 } conflicts)
|
||||
throw new ProjectConflictException(Loc.L("Editor.Error.SaveConflict"), stored, conflicts);
|
||||
var hero = merged.HeroFrame == stored.HeroFrame ? (Guid?)null : HeroFrameId(merged);
|
||||
// The positions name the frames this editor holds: the server refuses them (409 frames_conflict) once its
|
||||
// frames changed, also before its event says so. A server that predates the check ignores it.
|
||||
var request = new UpdateSequenceRequest(null, null, null, null, merged.ToJson(), version, hero, Volatile.Read(ref _framesVersion));
|
||||
try
|
||||
{
|
||||
var updated = await Call(() => _api.UpdateSequenceAsync(Id, request, cancellationToken));
|
||||
Volatile.Write(ref _stored, new Stored(merged, updated.SettingsVersion));
|
||||
return merged;
|
||||
}
|
||||
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.Conflict)
|
||||
{
|
||||
// Changed on the server since this editor read it, its settings or its frames: other frames make the
|
||||
// editor outdated (its proxies are not the server's), otherwise the edit merges again on top of the
|
||||
// server's settings, at the frames version they are at.
|
||||
var manifest = await Call(() => _api.GetManifestAsync(Id, cancellationToken));
|
||||
if (!SameFrames(manifest)) throw Outdated();
|
||||
if (attempt == SaveAttempts) throw new EditorException(Loc.L("Editor.Error.SaveConflict"), ex);
|
||||
Volatile.Write(ref _framesVersion, manifest.FramesVersion);
|
||||
Volatile.Write(ref _stored, new Stored(Parse(manifest.SettingsJson), manifest.SettingsVersion));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <remarks>
|
||||
/// The server queues every job at the user's priority; another priority ("Add to queue") is set right after. A
|
||||
/// render embeds the project, whose frame positions mean nothing once the frames changed: refused while outdated.
|
||||
/// </remarks>
|
||||
public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (request.Kind == JobKind.Render && IsOutdated) throw new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged"));
|
||||
var dto = await Call(() => _api.CreateJobAsync(new CreateJobRequest(JobWire.Kind(request.Kind), request.Targets, request.ParametersJson), cancellationToken));
|
||||
if (request.Priority != JobPriority.User) dto = await PrioritiseAsync(dto, request.Priority, cancellationToken);
|
||||
// The server's events may have reported the job already; its first state never replaces a later one.
|
||||
if (JobWire.FromDto(dto) is { } job && _jobs.TryAdd(job.Id, job)) JobChanged?.Invoke(job);
|
||||
return dto.Id;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var active = await Call(() => _api.ListActiveJobsAsync(cancellationToken));
|
||||
var mine = active.Select(JobWire.FromDto).OfType<Job>().Where(Concerns).ToList();
|
||||
foreach (var job in mine) _jobs[job.Id] = job;
|
||||
return mine;
|
||||
}
|
||||
|
||||
public async Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (JobWire.FromDto(await _api.CancelJobAsync(jobId, cancellationToken)) is { } job) Publish(job);
|
||||
}
|
||||
|
||||
public async Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (JobWire.FromDto(await _api.RetryJobAsync(jobId, cancellationToken)) is { } job) Publish(job);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
|
||||
try
|
||||
{
|
||||
await _stopping.CancelAsync();
|
||||
await _listening;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_stopping.Dispose();
|
||||
if (_frames is IAsyncDisposable frames) await frames.DisposeAsync();
|
||||
_api.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Follows the server's events until the editor closes, reconnecting with a growing delay (job states lost meanwhile
|
||||
/// are read back from the jobs, and the frames are compared again). Nothing that fails on the way ends it.
|
||||
/// </summary>
|
||||
private async Task ListenAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var failures = 0;
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
await foreach (var e in _api.EventsAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
failures = 0;
|
||||
await OnEventAsync(e, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested) return;
|
||||
Log.Info("editor", $"Events of the server lost for {_remote.Sequence.DisplayTitle}: {ex.Message}");
|
||||
}
|
||||
try
|
||||
{
|
||||
var delay = Math.Min(MaxBackoff.Ticks, MinBackoff.Ticks << Math.Min(failures++, 10));
|
||||
await Task.Delay(TimeSpan.FromTicks(delay), cancellationToken).ConfigureAwait(false);
|
||||
await RefreshTrackedAsync(cancellationToken).ConfigureAwait(false);
|
||||
// A frames change announced while the socket was down is found now rather than at the next save.
|
||||
if (Volatile.Read(ref _framesVersion) >= 0) await CheckFramesAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested) return;
|
||||
Log.Info("editor", $"Jobs of {_remote.Sequence.DisplayTitle} could not be read again: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task OnEventAsync(ServerEvent e, CancellationToken cancellationToken)
|
||||
{
|
||||
switch (e)
|
||||
{
|
||||
case SequenceChangedEvent changed when changed.SequenceId == Id && changed.FramesVersion != Volatile.Read(ref _framesVersion):
|
||||
await CheckFramesAsync(cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
// A late progress event never brings a finished job back to running.
|
||||
case JobProgressEvent progress when _jobs.TryGetValue(progress.JobId, out var job) && job.State is JobState.Queued or JobState.Running:
|
||||
Publish(job with
|
||||
{
|
||||
State = JobState.Running,
|
||||
ProgressDone = progress.Done,
|
||||
ProgressTotal = progress.Total,
|
||||
ItemsPerSecond = progress.ItemsPerSecond,
|
||||
Eta = JobEta.FromSeconds(progress.EtaSeconds),
|
||||
});
|
||||
break;
|
||||
case JobStateEvent state when !_foreign.ContainsKey(state.JobId):
|
||||
await FetchAsync(state.JobId, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads a job the events named: tracked when it concerns this sequence, remembered as foreign otherwise.</summary>
|
||||
private async Task FetchAsync(Guid jobId, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (JobWire.FromDto(await _api.GetJobAsync(jobId, cancellationToken).ConfigureAwait(false)) is { } job && Concerns(job)) Publish(job);
|
||||
else _foreign[jobId] = 0;
|
||||
}
|
||||
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or JsonException
|
||||
|| (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
|
||||
{
|
||||
Log.Info("editor", $"Job {jobId} could not be read: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Frames added or removed on the server: whether this PC's frames are still the sequence's.</summary>
|
||||
private async Task CheckFramesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
Compare(await _api.GetManifestAsync(Id, cancellationToken).ConfigureAwait(false));
|
||||
}
|
||||
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or JsonException
|
||||
|| (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
|
||||
{
|
||||
Log.Info("editor", $"The frames of {_remote.Sequence.DisplayTitle} could not be compared: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sets a priority other than the user's on a job the server just queued; the job stays queued if that fails.</summary>
|
||||
private async Task<JobDto> PrioritiseAsync(JobDto dto, JobPriority priority, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _api.SetJobPriorityAsync(dto.Id, JobWire.Priority(priority), cancellationToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException)
|
||||
{
|
||||
// Already claimed (409) or refused: the job runs at the user's priority, which is never later than asked.
|
||||
Log.Info("editor", $"Job {dto.Id} keeps the user's priority on the server: {ex.Message}");
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>After a lost event socket: the tracked jobs as the server has them now.</summary>
|
||||
private async Task RefreshTrackedAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var job in _jobs.Values.Where(j => j.State is JobState.Queued or JobState.Running or JobState.Paused).ToList())
|
||||
await FetchAsync(job.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private void Publish(Job job)
|
||||
{
|
||||
_jobs[job.Id] = job;
|
||||
JobChanged?.Invoke(job);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes the server's frames as <paramref name="manifest"/> lists them: their frames version when they are this PC's
|
||||
/// (saves name it), outdated otherwise. Returns whether they are.
|
||||
/// </summary>
|
||||
private bool Compare(SequenceManifest manifest)
|
||||
{
|
||||
if (!SameFrames(manifest))
|
||||
{
|
||||
MarkOutdated();
|
||||
return false;
|
||||
}
|
||||
Volatile.Write(ref _framesVersion, manifest.FramesVersion);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The server's frames are the cached ones, in the same order (frame positions in the project mean the same frames).</summary>
|
||||
private bool SameFrames(SequenceManifest manifest) =>
|
||||
manifest.Frames.OrderBy(f => f.Index).Select(f => f.Id).SequenceEqual(_remote.Frames.Select(f => f.Id));
|
||||
|
||||
/// <summary>The frames changed on the server: from now on the project is only shown.</summary>
|
||||
private ProxiesOutdatedException Outdated()
|
||||
{
|
||||
MarkOutdated();
|
||||
return new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged"));
|
||||
}
|
||||
|
||||
private void MarkOutdated()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _outdated, 1) == 1) return;
|
||||
Log.Info("editor", $"The frames of {_remote.Sequence.DisplayTitle} changed on the server; its proxies are out of date");
|
||||
ReadOnlyChanged?.Invoke();
|
||||
}
|
||||
|
||||
private bool Concerns(Job job) => job.TargetIds.Contains(Id) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
|
||||
|
||||
/// <summary>The frame of the project's hero, or <see cref="Guid.Empty"/> (the first frame shows) without one.</summary>
|
||||
private Guid HeroFrameId(ProjectSettings project) =>
|
||||
project.HeroFrame is { } hero && (uint)hero < (uint)_remote.Frames.Count ? _remote.Frames[hero].Id : Guid.Empty;
|
||||
|
||||
/// <exception cref="EditorException">The settings are not a project or come from a newer Chronos.</exception>
|
||||
private static ProjectSettings Parse(string? json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json)) return new ProjectSettings();
|
||||
try
|
||||
{
|
||||
return ProjectSettings.FromJson(json);
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or InvalidDataException)
|
||||
{
|
||||
throw new EditorException(Loc.L("Editor.Error.Project"), ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The server's deep report when it describes the frames this PC has; whether one of another number of frames came instead.</summary>
|
||||
private (DeepAnalysisReport? Report, bool OtherFrames) Report(string? json, int frameCount)
|
||||
{
|
||||
if (json is null) return (null, false);
|
||||
try
|
||||
{
|
||||
var report = DeepAnalysisReport.FromJson(json);
|
||||
return report.FrameCount == frameCount ? (report, false) : (null, true);
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or InvalidDataException)
|
||||
{
|
||||
Log.Warning("editor", $"The analysis of {_remote.Sequence.DisplayTitle} on the server cannot be read", ex);
|
||||
return (null, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A sequence deleted on the server reads as gone, like a local one removed from the index.</summary>
|
||||
private static async Task<T> Call<T>(Func<Task<T>> call)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await call();
|
||||
}
|
||||
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
|
||||
{
|
||||
throw new EditorException(Loc.L("Editor.Error.Missing"), ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The server's settings as last read or written, with the version a save must name.</summary>
|
||||
private sealed record Stored(ProjectSettings Project, int Version);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settings the editor changed were changed to other values on the server meanwhile (BRIEF §14.5): nothing is saved
|
||||
/// until the user keeps the editor's values or takes the server's (<see cref="EditorSession.ResolveConflict"/>).
|
||||
/// </summary>
|
||||
/// <param name="server">The server's project now.</param>
|
||||
/// <param name="differences">The settings both changed: the editor's value, then the server's.</param>
|
||||
public sealed class ProjectConflictException(string message, ProjectSettings server, IReadOnlyList<SettingsDifference> differences) : IOException(message)
|
||||
{
|
||||
public ProjectSettings Server { get; } = server;
|
||||
|
||||
public IReadOnlyList<SettingsDifference> Differences { get; } = differences;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The proxies of a server sequence are for frames the server no longer has (added or removed since they were fetched):
|
||||
/// they must be fetched again before the sequence can be edited.
|
||||
/// </summary>
|
||||
public sealed class ProxiesOutdatedException(string message) : EditorException(message);
|
||||
@@ -0,0 +1,51 @@
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data.Sync;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>This PC's project kept by "Save both" when a sync conflict was settled (BRIEF §12.7), local time of the choice.</summary>
|
||||
public sealed record SavedCopy(string Path, DateTime SavedAt)
|
||||
{
|
||||
/// <summary>"03/10/2026 14:22" in the user's format.</summary>
|
||||
public string Label => SavedAt.ToString("g", Loc.Culture);
|
||||
}
|
||||
|
||||
/// <summary>The "Save both" copies of a sequence: <c>.chronos/project.this-pc-<time>.json</c> beside <c>project.json</c>.</summary>
|
||||
public static class SavedCopies
|
||||
{
|
||||
/// <summary>The copies in a sequence's <c>.chronos</c> folder, newest first; none when the folder cannot be read.</summary>
|
||||
public static IReadOnlyList<SavedCopy> List(string metaDirectory)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(metaDirectory)) return [];
|
||||
return [.. Directory.EnumerateFiles(metaDirectory, SyncService.SavedCopyPattern)
|
||||
.Select(path => new SavedCopy(path, SyncService.SavedCopyTime(path) ?? File.GetLastWriteTime(path)))
|
||||
.OrderByDescending(c => c.SavedAt)];
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("editor", $"The saved projects in {metaDirectory} cannot be listed", ex);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The project of a copy.</summary>
|
||||
/// <exception cref="InvalidDataException">The copy is gone, unreadable, or not a project of this Chronos.</exception>
|
||||
public static ProjectSettings Read(SavedCopy copy)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(copy);
|
||||
try
|
||||
{
|
||||
return ProjectSettings.FromJson(File.ReadAllText(copy.Path));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
|
||||
{
|
||||
throw new InvalidDataException(Loc.L("Editor.Error.SavedCopy", System.IO.Path.GetFileName(copy.Path)), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using Chronos.Core.Model;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// The analyses and renders of the open sequence that wait, run or are paused, as the source reports them (BRIEF §12.3
|
||||
/// "while a job runs on this sequence, settings are disabled", §11.5): the editor's busy lock, whether Analyse would
|
||||
/// queue a second analysis, and the server job the header of a server sequence shows. Call from one thread.
|
||||
/// </summary>
|
||||
public sealed class SequenceJobs(Guid sequenceId)
|
||||
{
|
||||
private readonly Dictionary<Guid, Job> _active = [];
|
||||
|
||||
/// <summary>An analysis or render runs: settings wait.</summary>
|
||||
public bool IsBusy => _active.Values.Any(j => j.State == JobState.Running);
|
||||
|
||||
/// <summary>A deep analysis waits, runs or is paused.</summary>
|
||||
public bool IsAnalysing => _active.Values.Any(j => j.Kind == JobKind.DeepAnalyse);
|
||||
|
||||
/// <summary>The job to show: one running, else one paused, else the oldest waiting; null when there is none.</summary>
|
||||
public Job? Shown => First(_active.Values);
|
||||
|
||||
/// <summary>The job of <paramref name="kind"/> to show, chosen as <see cref="Shown"/> is (the Edit path's steps).</summary>
|
||||
public Job? Active(JobKind kind) => First(_active.Values.Where(j => j.Kind == kind));
|
||||
|
||||
/// <summary>An analysis or render of this sequence.</summary>
|
||||
public bool Concerns(Job job)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
return job.TargetIds.Contains(sequenceId) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
|
||||
}
|
||||
|
||||
/// <summary>The job is one of those that wait, run or are paused.</summary>
|
||||
public bool IsActive(Guid jobId) => _active.ContainsKey(jobId);
|
||||
|
||||
/// <summary>Takes in a job's new state.</summary>
|
||||
/// <returns>Whether a job joined or left the active ones or changed state; progress alone does not count.</returns>
|
||||
public bool Track(Job job)
|
||||
{
|
||||
if (!Concerns(job)) return false;
|
||||
if (job.State is not (JobState.Queued or JobState.Running or JobState.Paused)) return _active.Remove(job.Id);
|
||||
var changed = !_active.TryGetValue(job.Id, out var known) || known.State != job.State;
|
||||
_active[job.Id] = job;
|
||||
return changed;
|
||||
}
|
||||
|
||||
private static Job? First(IEnumerable<Job> jobs) => jobs
|
||||
.OrderBy(j => j.State switch { JobState.Running => 0, JobState.Paused => 1, _ => 2 })
|
||||
.ThenBy(j => j.Started ?? j.Created)
|
||||
.FirstOrDefault();
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
using System.Numerics;
|
||||
using System.Windows.Input;
|
||||
using Chronos.Core.Advice;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Ui.Mvvm;
|
||||
|
||||
namespace Chronos.App.Editor;
|
||||
|
||||
/// <summary>One row of a section's settings column; <see cref="Refresh"/> re-reads the project after any change.</summary>
|
||||
public abstract class SettingRow(string headerKey, string toolTipKey) : LocalizedViewModel
|
||||
{
|
||||
private bool _refreshing;
|
||||
|
||||
public string Header => Loc.L(headerKey);
|
||||
|
||||
/// <summary>What the control does and what moving it the wrong way costs (BRIEF §12.3).</summary>
|
||||
public string ToolTip => Loc.L(toolTipKey);
|
||||
|
||||
public void Refresh()
|
||||
{
|
||||
_refreshing = true;
|
||||
try
|
||||
{
|
||||
Read();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_refreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>True while <see cref="Refresh"/> pushes values into the bindings (they must not edit the project back).</summary>
|
||||
protected bool IsRefreshing => _refreshing;
|
||||
|
||||
protected abstract void Read();
|
||||
|
||||
/// <summary>The tooltip of an Auto pill: the stored reason, else the advisor's current one, else why there is none.</summary>
|
||||
protected static string Reason<T>(EditorSession session, AutoSetting<T> setting)
|
||||
where T : notnull
|
||||
{
|
||||
var auto = setting.Get(session.Project);
|
||||
if (auto.ReasonKey is { } key) return Advisor.Explain(key, auto.ReasonArgs);
|
||||
return session.Advice.Find(setting.Id) is { } recommendation ? Advisor.Explain(recommendation) : Loc.L("Tooltips.Editor.Auto.Default");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An Auto/manual slider (<see cref="Ui.Controls.AutoSlider"/>). Non-generic so the view can template it; the setting's
|
||||
/// value type lives in <see cref="AutoNumberRow{T}"/>.
|
||||
/// </summary>
|
||||
public abstract class AutoNumberRow(string headerKey, string toolTipKey, double minimum, double maximum, double step, string format)
|
||||
: SettingRow(headerKey, toolTipKey)
|
||||
{
|
||||
private double _value;
|
||||
private bool _isAuto = true;
|
||||
private double _autoValue;
|
||||
private string? _autoReason;
|
||||
private string? _notApplicableReason;
|
||||
|
||||
public double Minimum { get; } = minimum;
|
||||
public double Maximum { get; } = maximum;
|
||||
public double Step { get; } = step;
|
||||
public string Format { get; } = format;
|
||||
|
||||
/// <summary>The slider value; the user moving it stores a manual value (one undo step per drag: the view ends the run when the drag ends).</summary>
|
||||
public double Value
|
||||
{
|
||||
get => _value;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _value, value) || IsRefreshing || _isAuto) return;
|
||||
StoreManual(value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Touching the slider clears it (manual at the current value); the reset button sets it.</summary>
|
||||
public bool IsAuto
|
||||
{
|
||||
get => _isAuto;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _isAuto, value) || IsRefreshing) return;
|
||||
StoreAuto(value);
|
||||
}
|
||||
}
|
||||
|
||||
public double AutoValue { get => _autoValue; protected set => Set(ref _autoValue, value); }
|
||||
|
||||
public string? AutoReason { get => _autoReason; protected set => Set(ref _autoReason, value); }
|
||||
|
||||
public bool IsApplicable => _notApplicableReason is null;
|
||||
|
||||
public string? NotApplicableReason
|
||||
{
|
||||
get => _notApplicableReason;
|
||||
protected set
|
||||
{
|
||||
if (Set(ref _notApplicableReason, value)) OnPropertyChanged(nameof(IsApplicable));
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract void StoreManual(double value);
|
||||
|
||||
/// <summary>True: back to the advice; false: the value in force becomes manual.</summary>
|
||||
protected abstract void StoreAuto(bool auto);
|
||||
}
|
||||
|
||||
/// <summary><see cref="AutoNumberRow"/> over an <see cref="AutoSetting{T}"/> of <typeparamref name="T"/>.</summary>
|
||||
public sealed class AutoNumberRow<T> : AutoNumberRow
|
||||
where T : struct, INumber<T>
|
||||
{
|
||||
private readonly EditorSession _session;
|
||||
private readonly AutoSetting<T> _setting;
|
||||
private readonly Func<ProjectSettings, string?>? _notApplicable;
|
||||
|
||||
/// <param name="notApplicable">Why the setting does nothing with the current project (shown as "n/a"); null when it applies.</param>
|
||||
public AutoNumberRow(EditorSession session, AutoSetting<T> setting, string headerKey, string toolTipKey, double minimum, double maximum, double step,
|
||||
string format, Func<ProjectSettings, string?>? notApplicable = null)
|
||||
: base(headerKey, toolTipKey, minimum, maximum, step, format)
|
||||
{
|
||||
(_session, _setting, _notApplicable) = (session, setting, notApplicable);
|
||||
Refresh();
|
||||
}
|
||||
|
||||
protected override void StoreManual(double value) => _session.Edit(p => _setting.WithManual(p, Convert(value)), _setting.Id);
|
||||
|
||||
/// <summary>Back to Auto is a step of its own; taking over joins the drag that follows it.</summary>
|
||||
protected override void StoreAuto(bool auto)
|
||||
{
|
||||
if (auto) _session.Edit(_setting.Reset);
|
||||
else _session.Edit(p => _setting.WithManual(p, _setting.Effective(p, _session.Content.Deep)), _setting.Id);
|
||||
}
|
||||
|
||||
protected override void Read()
|
||||
{
|
||||
var project = _session.Project;
|
||||
AutoValue = double.CreateChecked(_setting.AutoValue(project, _session.Content.Deep));
|
||||
IsAuto = _setting.IsAuto(project);
|
||||
Value = double.CreateChecked(_setting.Effective(project, _session.Content.Deep));
|
||||
AutoReason = Reason(_session, _setting);
|
||||
NotApplicableReason = _notApplicable?.Invoke(project);
|
||||
}
|
||||
|
||||
private static T Convert(double value) => typeof(T) == typeof(int) ? T.CreateChecked(double.Round(value)) : T.CreateChecked(value);
|
||||
}
|
||||
|
||||
/// <summary>An Auto/manual switch (module on/off): the pill shows the advisor's choice, the switch takes it over.</summary>
|
||||
public sealed class AutoSwitchRow : SettingRow
|
||||
{
|
||||
private readonly EditorSession _session;
|
||||
private readonly AutoSetting<bool> _setting;
|
||||
private bool _isOn;
|
||||
private bool _isAuto;
|
||||
private string _autoText = string.Empty;
|
||||
private string? _autoReason;
|
||||
|
||||
public AutoSwitchRow(EditorSession session, AutoSetting<bool> setting, string headerKey, string toolTipKey)
|
||||
: base(headerKey, toolTipKey)
|
||||
{
|
||||
(_session, _setting) = (session, setting);
|
||||
ResetCommand = new RelayCommand(() => _session.Edit(_setting.Reset));
|
||||
Refresh();
|
||||
}
|
||||
|
||||
public bool IsOn
|
||||
{
|
||||
get => _isOn;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _isOn, value) || IsRefreshing) return;
|
||||
_session.Edit(p => _setting.WithManual(p, value));
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsAuto { get => _isAuto; private set => Set(ref _isAuto, value); }
|
||||
|
||||
/// <summary>"Auto · On".</summary>
|
||||
public string AutoText { get => _autoText; private set => Set(ref _autoText, value); }
|
||||
|
||||
public string? AutoReason { get => _autoReason; private set => Set(ref _autoReason, value); }
|
||||
|
||||
public ICommand ResetCommand { get; }
|
||||
|
||||
protected override void Read()
|
||||
{
|
||||
var project = _session.Project;
|
||||
IsOn = _setting.Effective(project, _session.Content.Deep);
|
||||
IsAuto = _setting.IsAuto(project);
|
||||
AutoText = Loc.L("Common.Auto") + Loc.Separator + Loc.L(IsOn ? "Editor.Value.On" : "Editor.Value.Off");
|
||||
AutoReason = Reason(_session, _setting);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A labelled value of a choice list.</summary>
|
||||
public sealed record Choice(object Value, string LabelKey, params object[] Args)
|
||||
{
|
||||
public string Label => Loc.L(LabelKey, Args);
|
||||
}
|
||||
|
||||
/// <summary>An Auto/manual drop-down (regions, flow quality, timing mode, aspect, playback rate); non-generic for the view.</summary>
|
||||
public abstract class AutoChoiceRow(string headerKey, string toolTipKey, IReadOnlyList<Choice> options) : SettingRow(headerKey, toolTipKey)
|
||||
{
|
||||
private Choice? _selected;
|
||||
private bool _isAuto;
|
||||
private string _autoText = string.Empty;
|
||||
private string? _autoReason;
|
||||
private string? _notApplicableReason;
|
||||
|
||||
public IReadOnlyList<Choice> Options { get; } = options;
|
||||
|
||||
public Choice? Selected
|
||||
{
|
||||
get => _selected;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _selected, value) || IsRefreshing || value is null) return;
|
||||
StoreManual(value.Value);
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsAuto { get => _isAuto; protected set => Set(ref _isAuto, value); }
|
||||
|
||||
/// <summary>"Auto · horizon".</summary>
|
||||
public string AutoText { get => _autoText; protected set => Set(ref _autoText, value); }
|
||||
|
||||
public string? AutoReason { get => _autoReason; protected set => Set(ref _autoReason, value); }
|
||||
|
||||
public bool IsApplicable => _notApplicableReason is null;
|
||||
|
||||
public string? NotApplicableReason
|
||||
{
|
||||
get => _notApplicableReason;
|
||||
protected set
|
||||
{
|
||||
if (Set(ref _notApplicableReason, value)) OnPropertyChanged(nameof(IsApplicable));
|
||||
}
|
||||
}
|
||||
|
||||
public abstract ICommand ResetCommand { get; }
|
||||
|
||||
protected abstract void StoreManual(object value);
|
||||
}
|
||||
|
||||
/// <summary><see cref="AutoChoiceRow"/> over an <see cref="AutoSetting{T}"/> of <typeparamref name="T"/>.</summary>
|
||||
public sealed class AutoChoiceRow<T> : AutoChoiceRow
|
||||
where T : notnull
|
||||
{
|
||||
private readonly EditorSession _session;
|
||||
private readonly AutoSetting<T> _setting;
|
||||
private readonly Func<ProjectSettings, string?>? _notApplicable;
|
||||
|
||||
public AutoChoiceRow(EditorSession session, AutoSetting<T> setting, string headerKey, string toolTipKey, IReadOnlyList<Choice> options,
|
||||
Func<ProjectSettings, string?>? notApplicable = null)
|
||||
: base(headerKey, toolTipKey, options)
|
||||
{
|
||||
(_session, _setting, _notApplicable) = (session, setting, notApplicable);
|
||||
ResetCommand = new RelayCommand(() => _session.Edit(_setting.Reset));
|
||||
Refresh();
|
||||
}
|
||||
|
||||
public override ICommand ResetCommand { get; }
|
||||
|
||||
protected override void StoreManual(object value)
|
||||
{
|
||||
if (value is T chosen) _session.Edit(p => _setting.WithManual(p, chosen));
|
||||
}
|
||||
|
||||
protected override void Read()
|
||||
{
|
||||
var project = _session.Project;
|
||||
var value = _setting.Effective(project, _session.Content.Deep);
|
||||
Selected = Options.FirstOrDefault(o => Equals(o.Value, value));
|
||||
IsAuto = _setting.IsAuto(project);
|
||||
var auto = _setting.AutoValue(project, _session.Content.Deep);
|
||||
AutoText = Loc.L("Common.Auto") + Loc.Separator + (Options.FirstOrDefault(o => Equals(o.Value, auto))?.Label ?? auto.ToString());
|
||||
AutoReason = Reason(_session, _setting);
|
||||
NotApplicableReason = _notApplicable?.Invoke(project);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A plain slider (no advice): exposure offset, placement, stack length, fit-to duration.</summary>
|
||||
public sealed class NumberRow : SettingRow
|
||||
{
|
||||
private readonly EditorSession _session;
|
||||
private readonly Func<ProjectSettings, double> _get;
|
||||
private readonly Func<ProjectSettings, double, ProjectSettings> _set;
|
||||
private readonly Func<double, string> _display;
|
||||
private readonly Func<ProjectSettings, string?>? _notApplicable;
|
||||
private readonly string _mergeKey;
|
||||
private double _value;
|
||||
private string _displayValue = string.Empty;
|
||||
private string? _notApplicableReason;
|
||||
|
||||
public NumberRow(EditorSession session, string headerKey, string toolTipKey, double minimum, double maximum, double step,
|
||||
Func<ProjectSettings, double> get, Func<ProjectSettings, double, ProjectSettings> set, Func<double, string> display,
|
||||
Func<ProjectSettings, string?>? notApplicable = null)
|
||||
: base(headerKey, toolTipKey)
|
||||
{
|
||||
(_session, _get, _set, _display, _notApplicable, _mergeKey) = (session, get, set, display, notApplicable, headerKey);
|
||||
(Minimum, Maximum, Step) = (minimum, maximum, step);
|
||||
Refresh();
|
||||
}
|
||||
|
||||
public double Minimum { get; }
|
||||
public double Maximum { get; }
|
||||
public double Step { get; }
|
||||
|
||||
public double Value
|
||||
{
|
||||
get => _value;
|
||||
set
|
||||
{
|
||||
var snapped = Step > 0 ? double.Round(value / Step) * Step : value;
|
||||
if (!Set(ref _value, snapped)) return;
|
||||
DisplayValue = _display(snapped);
|
||||
if (!IsRefreshing) _session.Edit(p => _set(p, snapped), _mergeKey);
|
||||
}
|
||||
}
|
||||
|
||||
public string DisplayValue { get => _displayValue; private set => Set(ref _displayValue, value); }
|
||||
|
||||
public bool IsApplicable => _notApplicableReason is null;
|
||||
|
||||
public string? NotApplicableReason
|
||||
{
|
||||
get => _notApplicableReason;
|
||||
private set
|
||||
{
|
||||
if (Set(ref _notApplicableReason, value)) OnPropertyChanged(nameof(IsApplicable));
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Read()
|
||||
{
|
||||
Value = _get(_session.Project);
|
||||
DisplayValue = _display(_value);
|
||||
NotApplicableReason = _notApplicable?.Invoke(_session.Project);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A plain drop-down (stacking mode).</summary>
|
||||
public sealed class ChoiceRow : SettingRow
|
||||
{
|
||||
private readonly EditorSession _session;
|
||||
private readonly Func<ProjectSettings, object> _get;
|
||||
private readonly Func<ProjectSettings, object, ProjectSettings> _set;
|
||||
private Choice? _selected;
|
||||
|
||||
public ChoiceRow(EditorSession session, string headerKey, string toolTipKey, IReadOnlyList<Choice> options, Func<ProjectSettings, object> get,
|
||||
Func<ProjectSettings, object, ProjectSettings> set)
|
||||
: base(headerKey, toolTipKey)
|
||||
{
|
||||
(_session, _get, _set, Options) = (session, get, set, options);
|
||||
Refresh();
|
||||
}
|
||||
|
||||
public IReadOnlyList<Choice> Options { get; }
|
||||
|
||||
public Choice? Selected
|
||||
{
|
||||
get => _selected;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _selected, value) || IsRefreshing || value is null) return;
|
||||
_session.Edit(p => _set(p, value.Value));
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Read()
|
||||
{
|
||||
var current = _get(_session.Project);
|
||||
Selected = Options.FirstOrDefault(o => Equals(o.Value, current));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A measured value shown read-only, "n/a" with the reason when there is none (colour temperature).</summary>
|
||||
public sealed class InfoRow(string headerKey, string toolTipKey, Func<(string? Value, string? NotApplicableReason)> read) : SettingRow(headerKey, toolTipKey)
|
||||
{
|
||||
private string? _value;
|
||||
private string? _notApplicableReason;
|
||||
|
||||
public string? Value { get => _value; private set => Set(ref _value, value); }
|
||||
|
||||
public bool IsApplicable => _notApplicableReason is null;
|
||||
|
||||
public string? NotApplicableReason
|
||||
{
|
||||
get => _notApplicableReason;
|
||||
private set
|
||||
{
|
||||
if (Set(ref _notApplicableReason, value)) OnPropertyChanged(nameof(IsApplicable));
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Read() => (Value, NotApplicableReason) = read();
|
||||
}
|
||||
Reference in new issue
Block a user