using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
using Titano.App.Infrastructure;
using Titano.Core.Advice;
using Titano.Core.Export;
using Titano.Core.Localization;
using Titano.Core.Mathematics;
using Titano.Core.Project;
using Titano.Ui.Mvvm;
using Titano.Ui.Visuals;
namespace Titano.App.Editor;
/// Margins of the free crop, in the order of CameraTab.Margins (opposites differ in the lowest bit).
public enum CropSide
{
Left,
Right,
Top,
Bottom,
}
///
/// 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.
///
public sealed class CameraTab : EditorTab
{
/// Zoom at the top of the curve editor.
public const double MaxZoom = 4;
/// Largest crop margin; opposite margins together leave at least of the frame.
public const double MaxCropMargin = 0.45;
public const double MinCropSize = 0.1;
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(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.IsBusy && Keys.All(k => k.Frame != Editor.CurrentIndex));
RemoveKeyCommand = new RelayCommand(RemoveKey, () => !Editor.IsBusy && SelectedKey >= 0);
CommitCurveCommand = new RelayCommand(CommitCurve);
Refresh();
}
/// Keyframes as curve points: X = frame / (count − 1), Y = (zoom − 1) / ( − 1). Edited in place by the curve editor.
public ObservableCollection KeyPoints { get; } = [];
public int SelectedKey
{
get => _selectedKey;
set
{
if (!Set(ref _selectedKey, value)) return;
OnSelectedKeyChanged();
}
}
public bool HasSelectedKey => SelectedKey >= 0 && SelectedKey < Keys.Count;
/// Framing of the selected keyframe: centre (0–1) and zoom.
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));
/// "Keyframe 2 of 3 · frame 0413".
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 XFormatter => x => EditorText.Position((int)double.Round(x * (Editor.FrameCount - 1)), Editor.FrameCount);
public Func 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; }
/// What Add keyframe does, or why it cannot run now.
public string AddKeyToolTip => Loc.L(Editor.IsBusy ? "Tooltips.Editor.Busy"
: Keys.Any(k => k.Frame == Editor.CurrentIndex) ? "Tooltips.Editor.Camera.KeyExists" : "Tooltips.Editor.Camera.AddKey");
public string RemoveKeyToolTip => Loc.L(Editor.IsBusy ? "Tooltips.Editor.Busy" : HasSelectedKey ? "Tooltips.Editor.Camera.RemoveKey" : "Tooltips.Editor.Camera.NoKey");
/// Run by the curve editor after each finished edit.
public ICommand CommitCurveCommand { get; }
/// Keyframes in frame order (the order of ).
private List 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();
}
/// The curve editor finished an edit (add, move, delete): the points become the keyframes, keeping each one's framing.
public void CommitCurve()
{
var old = Keys;
var keys = new List();
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));
}
/// A margin of the free crop (, normalised x, y, width, height); all zero = the whole frame.
private static NumberRow CropRow(EditorSession session, CropSide side, string headerKey) => new(session, headerKey, "Tooltips.Editor.Camera.Crop", 0,
MaxCropMargin, 0.01, p => Margins(p.Camera.Crop)[(int)side], (p, v) => p with { Camera = p.Camera with { Crop = WithMargin(p.Camera.Crop, side, v) } },
v => Formatting.Percent(v));
/// Left, right, top and bottom margins of a crop rectangle.
private static double[] Margins(double[]? crop) => crop is [var x, var y, var w, var h] && new[] { x, y, w, h }.All(double.IsFinite)
? [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];
private static double[]? WithMargin(double[]? crop, CropSide side, double value)
{
var margins = Margins(crop);
var opposite = (int)side ^ 1;
margins[(int)side] = double.Clamp(value, 0, double.Min(MaxCropMargin, 1 - MinCropSize - 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];
}
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 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));
}
}
///
/// 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).
///
public sealed class TimeTab : EditorTab
{
private Func? _evaluator;
private string? _planText;
private IReadOnlyList _planSeries = [];
private IReadOnlyList _planMarkers = [];
public TimeTab(EditorViewModel editor)
: base(editor, "Time", AdvisorSection.Timing)
{
var s = editor.Session;
Rows =
[
new AutoChoiceRow(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(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();
}
/// Remap control points (output fraction → source fraction), edited in place by the curve editor.
public ObservableCollection RemapPoints { get; } = [];
/// The monotone spline through .
public Func? Evaluator { get => _evaluator; private set => Set(ref _evaluator, value); }
/// Run by the curve editor after each finished edit.
public ICommand CommitCurveCommand { get; }
/// "3,600 frames → 2 min 30 s · 24 fps".
public string? PlanText { get => _planText; private set => Set(ref _planText, value); }
/// Video frames each photo is shown for (0 = skipped by a speed-up, gap = excluded), over the sequence.
public IReadOnlyList PlanSeries { get => _planSeries; private set => Set(ref _planSeries, value); }
/// Cuts of the plan (deliberate pauses, gaps, long exclusion runs).
public IReadOnlyList PlanMarkers { get => _planMarkers; private set => Set(ref _planMarkers, value); }
public IReadOnlyList PlanLegend { get; } = [new(Loc.L("Editor.Chart.Shown"), "Brush.Accent")];
public Func PlanFormatter { get; } = v => v.ToString("0.#", Loc.Culture);
public double Playhead => Editor.FrameCount > 1 ? (double)Editor.CurrentIndex / (Editor.FrameCount - 1) : double.NaN;
public Func XFormatter { get; } = x => Loc.L("Editor.Time.Output", (x * 100).ToString("0", Loc.Culture));
public Func 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")))];
}
/// The curve editor finished an edit: the points become the remap curve, and the timing mode follows it.
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));
private static Func? Spline(IReadOnlyList 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);
}
}