merge: sequence editor with Export tab (preview through the render pipeline, section tabs, autosave with undo/redo)
Keeps the sync captures and sample server next to the editor's sample sunset; the editor's capture runs last since it leaves an analysis running. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
53 files changed
+8622
-18
No files matched your search
@@ -1,14 +1,24 @@
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using Titano.App.About;
|
||||
using Titano.App.Editor;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Server;
|
||||
using Titano.App.Settings;
|
||||
using Titano.Core.Advice;
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Codecs.Jpeg;
|
||||
using Titano.Core.Diagnostics.Synthetic;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Imaging.Decoders;
|
||||
using Titano.Core.Metadata;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Video;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Protocol;
|
||||
@@ -195,6 +205,180 @@ public sealed class SampleData
|
||||
"""{"exposure":{"deflickerWindow":{"isAuto":false,"manual":""" + frames.ToString(System.Globalization.CultureInfo.InvariantCulture) + "}}}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sequence editor's sample: a second archive holding a synthetic harbour sunset of real JPEG frames with Exif
|
||||
/// (flicker, two received exposure steps, white-balance drift, a horizon), indexed by a scan, analysed (light and
|
||||
/// deep, saved as <c>analysis.json</c>), advised into <c>project.json</c> with one manual value and three camera
|
||||
/// keyframes, and given two past renders.
|
||||
/// </summary>
|
||||
/// <returns>The sequence id to open in the editor.</returns>
|
||||
public async Task<Guid> FillEditorAsync()
|
||||
{
|
||||
var db = _db ?? throw new InvalidOperationException("OpenEmptyAsync first.");
|
||||
var archives = _services.Archives ?? throw new InvalidOperationException("The archive engine is not attached.");
|
||||
var root = Path.Combine(_services.Environment.DataDirectory, "editor-archive");
|
||||
var archive = await archives.CreateAsync(root, "Editor sample");
|
||||
var sunset = SyntheticSequence.Create(EditorSunset);
|
||||
var folder = Path.Combine(root, "2026", "2026-09-28 Canon EOS R5");
|
||||
Directory.CreateDirectory(folder);
|
||||
for (var i = 0; i < sunset.Count; i++)
|
||||
{
|
||||
using var image = SunsetFrame(sunset, i);
|
||||
var exif = ExifWriter.BuildJpegApp1(sunset.Metadata[i]);
|
||||
File.WriteAllBytes(Path.Combine(folder, $"IMG_{4211 + i:0000}.JPG"), JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 88, App1Segments = [exif[4..]] }));
|
||||
}
|
||||
await archives.Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, CancellationToken.None);
|
||||
var id = (await db.Sequences.ListLocationsAsync(archive.Id)).Single().Id;
|
||||
await archives.SetSequenceInfoAsync(id, "Harbour sunset", ["sunset", "harbour"], 4, null);
|
||||
|
||||
var source = new LocalSequenceSource(db, id, DecoderFactory.CreateClient(null), null);
|
||||
var content = await source.LoadAsync(CancellationToken.None);
|
||||
var deep = await DeepAnalyzer.AnalyzeAsync(new SunsetFrames(sunset));
|
||||
var sequence = content.Sequence;
|
||||
deep.Save(new ArchivePaths(root).Sequence(sequence.Folder).AnalysisPath);
|
||||
var advice = Advisor.Recommend(content.Light, deep, SequenceContext.FromFrames(content.Frames));
|
||||
// As a user leaves it: the advice applied, one value taken over by hand (Sun track) and a slow push-in.
|
||||
var advised = Advisor.Apply(content.Project, advice);
|
||||
var project = advised with
|
||||
{
|
||||
Exposure = advised.Exposure with { DeflickerStrength = advised.Exposure.DeflickerStrength.WithManual(0.8) },
|
||||
Camera = advised.Camera with { Keyframes = [new CameraKey(0, 0.5, 0.5, 1, 0), new CameraKey(48, 0.6, 0.46, 1.4, 0), new CameraKey(95, 0.64, 0.4, 1.9, 0)] },
|
||||
};
|
||||
await source.SaveProjectAsync(project, content.Project, CancellationToken.None);
|
||||
await db.Sequences.RecordAnalysisAsync(id, SequenceStatus.AnalyzedLight | SequenceStatus.AnalyzedDeep | SequenceStatus.HasWarnings, SequenceStatus.None,
|
||||
advice.Findings.Count(f => f.Severity >= FindingSeverity.Warning), AnalysisSummary.From(deep).ToJson());
|
||||
foreach (var (preset, codec, width, height, daysAgo, bytes) in new[] { ("4K archive", "hevc", 3840, 2160, 7, 2_210_000_000L), ("1080p share", "h264", 1920, 1080, 3, 412_000_000L) })
|
||||
{
|
||||
await db.Renders.InsertAsync(new Render
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
SequenceId = id,
|
||||
PresetName = preset,
|
||||
OutputPath = Path.Combine(folder, "exports", $"2026-09-28 Harbour sunset - {preset}.mp4"),
|
||||
Codec = codec,
|
||||
Width = width,
|
||||
Height = height,
|
||||
Fps = 24,
|
||||
DurationSeconds = 5,
|
||||
Bytes = bytes,
|
||||
Created = DateTimeOffset.UtcNow.AddDays(-daysAgo),
|
||||
ProducedBy = "studio-pc",
|
||||
});
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
/// <summary>A deep analysis of <paramref name="sequenceId"/> half way through: the editor's busy state (settings wait, viewing stays live).</summary>
|
||||
public async Task MarkAnalysingAsync(Guid sequenceId)
|
||||
{
|
||||
var db = _db ?? throw new InvalidOperationException("OpenEmptyAsync first.");
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
await db.Jobs.EnqueueAsync(new Job
|
||||
{
|
||||
Id = Guid.CreateVersion7(),
|
||||
Kind = JobKind.DeepAnalyse,
|
||||
TargetIds = [sequenceId],
|
||||
TargetLabel = "Harbour sunset",
|
||||
State = JobState.Running,
|
||||
Priority = JobPriority.User,
|
||||
ProgressDone = 40,
|
||||
ProgressTotal = 96,
|
||||
ItemsPerSecond = 12,
|
||||
NodeId = Environment.MachineName,
|
||||
Attempts = 1,
|
||||
Created = now.AddSeconds(-5),
|
||||
Started = now.AddSeconds(-4),
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>A two-minute sunset at 2 s intervals: darkening scene, flicker, two shutter steps the pixels received, warming light.</summary>
|
||||
private static readonly SyntheticSequenceOptions EditorSunset = new()
|
||||
{
|
||||
Width = 600,
|
||||
Height = 400,
|
||||
FrameCount = 96,
|
||||
Seed = 28,
|
||||
Start = new DateTime(2026, 9, 28, 18, 2, 11),
|
||||
IntervalSeconds = 2,
|
||||
StartEv = 0.5,
|
||||
EndEv = -2.5,
|
||||
FlickerEv = 0.12,
|
||||
ExposureSteps = [new SyntheticExposureStep(32, -1), new SyntheticExposureStep(64, -1)],
|
||||
HorizonFraction = 0.62,
|
||||
HorizonWave = 0.02,
|
||||
SkyLevel = 0.32,
|
||||
LandLevel = 0.06,
|
||||
StartKelvin = 5600,
|
||||
EndKelvin = 3200,
|
||||
WhiteBalanceJitter = 0.03,
|
||||
NoiseSigma = 0.002,
|
||||
BaseExposureTime = 1.0 / 125,
|
||||
BaseFNumber = 8,
|
||||
BaseIso = 100,
|
||||
CameraMake = "Canon",
|
||||
CameraModel = "Canon EOS R5",
|
||||
Lens = "RF15-35mm F2.8 L IS USM",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The synthetic frame (its exposure truth: scene, steps, flicker, white balance) coloured as a harbour sunset: a
|
||||
/// blue-to-amber sky gradient normalised to unit luminance, so the measured luminance keeps the truth, and a setting sun.
|
||||
/// </summary>
|
||||
private static ImageBuffer SunsetFrame(SyntheticSequence sequence, int index)
|
||||
{
|
||||
var image = sequence.Render(index);
|
||||
var (w, h) = (image.Width, image.Height);
|
||||
var t = index / (double)(sequence.Count - 1);
|
||||
var horizon = sequence.Options.HorizonFraction * h;
|
||||
var (sunX, sunY) = (w * 0.64, h * (0.28 + 0.3 * t));
|
||||
var gain = Math.Pow(2, sequence.SceneEv[index] + sequence.ExposureOffsetEv[index] + sequence.FlickerEv[index]);
|
||||
double[][] sky = [Linear("#2A2F6B"), Linear("#8E3F57"), Linear("#E07A48"), Linear("#F5B45E")];
|
||||
var land = Linear("#3A3540");
|
||||
for (var y = 0; y < h; y++)
|
||||
{
|
||||
double[] colour;
|
||||
if (y < horizon)
|
||||
{
|
||||
var f = y / horizon * (sky.Length - 1);
|
||||
var k = Math.Min((int)f, sky.Length - 2);
|
||||
colour = [.. Enumerable.Range(0, 3).Select(c => sky[k][c] + (sky[k + 1][c] - sky[k][c]) * (f - k))];
|
||||
}
|
||||
else
|
||||
{
|
||||
colour = land;
|
||||
}
|
||||
var luminance = 0.2126 * colour[0] + 0.7152 * colour[1] + 0.0722 * colour[2];
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
var d = Math.Sqrt((x - sunX) * (x - sunX) + (y - sunY) * (y - sunY));
|
||||
var sun = y < horizon ? gain * 4 * Math.Exp(-d * d / 220) : 0;
|
||||
for (var c = 0; c < 3; c++)
|
||||
{
|
||||
var plane = image.Plane(c);
|
||||
plane[y * w + x] = (float)(plane[y * w + x] * colour[c] / luminance + sun * (c == 0 ? 1.0 : c == 1 ? 0.75 : 0.45));
|
||||
}
|
||||
}
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
private static double[] Linear(string hex)
|
||||
{
|
||||
var rgb = Convert.FromHexString(hex.TrimStart('#'));
|
||||
return [.. rgb.Select(v => ColorSpace.SrgbToLinear(v / 255.0))];
|
||||
}
|
||||
|
||||
/// <summary>The sunset as the deep analysis reads it (the pixels written to the JPEGs, before compression).</summary>
|
||||
private sealed class SunsetFrames(SyntheticSequence sequence) : IFrameSource
|
||||
{
|
||||
public int Count => sequence.Count;
|
||||
|
||||
public LightFrame Metadata(int index) => LightFrame.From(sequence.Metadata[index], index);
|
||||
|
||||
public ValueTask<ImageBuffer?> LoadAsync(int index, int maxLongEdge, CancellationToken cancellationToken) =>
|
||||
ValueTask.FromResult<ImageBuffer?>(SunsetFrame(sequence, index));
|
||||
}
|
||||
|
||||
private IEnumerable<(Sequence Sequence, string[] Colours, bool Raw)> Sequences(Guid archiveId)
|
||||
{
|
||||
var now = new DateTime(2026, 9, 28, 18, 2, 11);
|
||||
@@ -456,14 +640,14 @@ public sealed class SampleData
|
||||
lock (_sequences) return Task.FromResult(_sequences[id].Dto);
|
||||
}
|
||||
|
||||
public Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken)
|
||||
public Task<Protocol.SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_sequences)
|
||||
{
|
||||
var (dto, settings, frames) = _sequences[id];
|
||||
var hasProxy = (dto.Status & (long)SequenceStatus.ProxiesBuilt) != 0;
|
||||
var created = new DateTimeOffset(2026, 9, 20, 21, 0, 0, TimeSpan.Zero);
|
||||
return Task.FromResult(new SequenceManifest(id, dto.FramesVersion, dto.SettingsVersion, settings, dto.Tags,
|
||||
return Task.FromResult(new Protocol.SequenceManifest(id, dto.FramesVersion, dto.SettingsVersion, settings, dto.Tags,
|
||||
[.. frames.Select((frame, i) => new ManifestFrame(frame, i, $"IMG_{i + 1:0000}.JPG", 24_000_000,
|
||||
Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(BitConverter.GetBytes(i))), hasProxy, true))],
|
||||
[.. Enumerable.Range(0, dto.RenderedCount).Select(i => new RenderDto(Guid.CreateVersion7(), i == 0 ? "4K HEVC" : "1080p H.264", "hevc",
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
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;
|
||||
|
||||
/// <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.IsBusy && Keys.All(k => k.Frame != Editor.CurrentIndex));
|
||||
RemoveKeyCommand = new RelayCommand(RemoveKey, () => !Editor.IsBusy && 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 => Loc.L(Editor.IsBusy ? "Tooltips.Editor.Busy"
|
||||
: 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 => Loc.L(Editor.IsBusy ? "Tooltips.Editor.Busy" : "Tooltips.Editor.Camera.Curve");
|
||||
|
||||
public string RemoveKeyToolTip => Loc.L(Editor.IsBusy ? "Tooltips.Editor.Busy" : 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 => Loc.L(Editor.IsBusy ? "Tooltips.Editor.Busy" : "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 Titano.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 Titano.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 Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.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,85 @@
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.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,259 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
|
||||
xmlns:v="clr-namespace:Titano.Ui.Visuals;assembly=Titano.Ui"
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
|
||||
xmlns:e="clr-namespace:Titano.App.Editor">
|
||||
<!--
|
||||
The measuring tool of each editor section, below the tab strip (BRIEF §12.3): 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 tab's preset cards. Clicking a chart seeks the preview.
|
||||
-->
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="pack://application:,,,/Titano;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}" GroupName="ExposureChart" 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}" GroupName="ExposureChart" 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}" GroupName="ExposureChart" 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>
|
||||
|
||||
<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">
|
||||
<Grid>
|
||||
<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="*" MinWidth="56" />
|
||||
<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.6*" MinWidth="60" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="118" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Button Style="{StaticResource Button.SortHeader}" DataContext="{Binding Columns[0]}" Command="{Binding SortCommand}"
|
||||
Content="{l:Loc Editor.Frames.Column.Number}" ToolTip="{l:Loc Tooltips.Editor.Frames.Sort}" />
|
||||
<Button Grid.Column="1" Style="{StaticResource Button.SortHeader}" DataContext="{Binding Columns[1]}" Command="{Binding SortCommand}"
|
||||
Content="{l:Loc Editor.Frames.Column.Time}" ToolTip="{l:Loc Tooltips.Editor.Frames.Sort}" HorizontalContentAlignment="Right" />
|
||||
<Button Grid.Column="2" Style="{StaticResource Button.SortHeader}" DataContext="{Binding Columns[2]}" Command="{Binding SortCommand}"
|
||||
Content="{l:Loc Editor.Frames.Column.Exposure}" ToolTip="{l:Loc Tooltips.Editor.Frames.Sort}" HorizontalContentAlignment="Right" />
|
||||
<Button Grid.Column="3" Style="{StaticResource Button.SortHeader}" DataContext="{Binding Columns[3]}" Command="{Binding SortCommand}"
|
||||
Content="{l:Loc Editor.Frames.Column.Iso}" ToolTip="{l:Loc Tooltips.Editor.Frames.Sort}" HorizontalContentAlignment="Right" />
|
||||
<Button Grid.Column="4" Style="{StaticResource Button.SortHeader}" DataContext="{Binding Columns[4]}" Command="{Binding SortCommand}"
|
||||
Content="{l:Loc Editor.Frames.Column.Aperture}" ToolTip="{l:Loc Tooltips.Editor.Frames.Sort}" HorizontalContentAlignment="Right" />
|
||||
<Button Grid.Column="5" Style="{StaticResource Button.SortHeader}" DataContext="{Binding Columns[5]}" Command="{Binding SortCommand}"
|
||||
Content="{l:Loc Editor.Frames.Column.Size}" ToolTip="{l:Loc Tooltips.Editor.Frames.Sort}" HorizontalContentAlignment="Right" />
|
||||
<Button Grid.Column="6" Style="{StaticResource Button.SortHeader}" DataContext="{Binding Columns[6]}" Command="{Binding SortCommand}"
|
||||
Content="{l:Loc Editor.Frames.Column.Tier}" ToolTip="{l:Loc Tooltips.Editor.Frames.Sort}" Margin="10,0,0,0" />
|
||||
<Button Grid.Column="7" Style="{StaticResource Button.SortHeader}" DataContext="{Binding Columns[7]}" Command="{Binding SortCommand}"
|
||||
Content="{l:Loc Editor.Frames.Column.Flags}" ToolTip="{l:Loc Tooltips.Editor.Frames.Sort}" 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="*" MinWidth="56" />
|
||||
<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.6*" MinWidth="60" />
|
||||
<ColumnDefinition Width="Auto" MinWidth="118" />
|
||||
</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" />
|
||||
<TextBlock x:Name="Flags" Grid.Column="7" Style="{StaticResource Text.Cell}" Text="{Binding Flags}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
|
||||
<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}">
|
||||
<Button Style="{StaticResource Button.PresetCard}" Command="{Binding SelectCommand}" CommandParameter="{Binding}" ToolTip="{Binding ToolTip}"
|
||||
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="{l:Loc Tooltips.Editor.Export.InBatch}" 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,443 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
|
||||
xmlns:shell="clr-namespace:Titano.App.Shell"
|
||||
xmlns:e="clr-namespace:Titano.App.Editor">
|
||||
<!--
|
||||
The settings column of each editor section (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:,,,/Titano;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.BusyToolTip}" ToolTipService.ShowOnDisabled="True">
|
||||
<ItemsControl ItemsSource="{Binding Rows}" Focusable="False" />
|
||||
<ContentPresenter />
|
||||
</StackPanel>
|
||||
</ScrollViewer>
|
||||
</DockPanel>
|
||||
</Border>
|
||||
</ControlTemplate>
|
||||
|
||||
<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>
|
||||
<TextBlock Text="{l:Loc Editor.Frames.Warnings}" Style="{StaticResource Text.Section}" Margin="0,0,0,8" />
|
||||
<TextBlock Text="{l:Loc Editor.Frames.NoWarnings}" 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" />
|
||||
<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 HasHistory, Converter={StaticResource BoolToVisibility}}" />
|
||||
<TextBlock Text="{Binding HistoryText}" Style="{StaticResource Text.Faint}" FontSize="{StaticResource Size.Chip}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"
|
||||
ToolTip="{Binding HistoryText}" />
|
||||
</DockPanel>
|
||||
</StackPanel>
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
|
||||
<StackPanel IsEnabled="{Binding Editor.IsEditable}" ToolTip="{Binding Editor.BusyToolTip}" 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" />
|
||||
</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"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Export.Encoder}" 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}" />
|
||||
<ComboBox Grid.Row="8" Grid.Column="1" ItemsSource="{Binding SaveChoices}" SelectedItem="{Binding SelectedSave}" DisplayMemberPath="Label"
|
||||
ToolTip="{Binding SaveToolTip}" AutomationProperties.Name="{l:Loc Editor.Export.SaveTo}" />
|
||||
</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,211 @@
|
||||
using Titano.Core.Advice;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Export;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Video;
|
||||
using Titano.Data.Archiving.Jobs;
|
||||
using Titano.Data.Processing;
|
||||
|
||||
namespace Titano.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. Call from one thread (the UI thread).
|
||||
/// </summary>
|
||||
public sealed class EditorSession : IAsyncDisposable
|
||||
{
|
||||
public static readonly TimeSpan DefaultSaveDelay = TimeSpan.FromMilliseconds(400);
|
||||
|
||||
/// <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;
|
||||
|
||||
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).</summary>
|
||||
public event Action<Exception>? SaveFailed;
|
||||
|
||||
public ISequenceSource Source { get; }
|
||||
|
||||
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>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 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() => History.Undo();
|
||||
|
||||
public bool Redo() => 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 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>Reads the sequence again (an analysis finished): new reports and advice, the stored project merged into the open one.</summary>
|
||||
public async Task ReloadAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _saver.FlushAsync();
|
||||
var content = await Source.LoadAsync(cancellationToken);
|
||||
var merged = ProjectMerge.Merge(_basis, Project, content.Project);
|
||||
_basis = content.Project;
|
||||
(Content, Context, Advice, Presets) = Analyse(content, _codecs);
|
||||
History.Replace(merged);
|
||||
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>
|
||||
/// 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();
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
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)
|
||||
{
|
||||
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)
|
||||
{
|
||||
var stored = await Source.SaveProjectAsync(project, _basis, CancellationToken.None);
|
||||
_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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
using Titano.Core.Advice;
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Export;
|
||||
using Titano.Core.Motion;
|
||||
using Titano.Core.Project;
|
||||
|
||||
namespace Titano.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));
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui">
|
||||
<!--
|
||||
Styles of the sequence editor (Editor.html, Export.html) on the kit of Titano.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 Export tab its preset cards. -->
|
||||
<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" />
|
||||
<Setter Property="Margin" Value="0,0,6,0" />
|
||||
<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,0" />
|
||||
<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">
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="Center">
|
||||
<ContentPresenter VerticalAlignment="Center" />
|
||||
<ui:Icon x:Name="Arrow" Glyph="{StaticResource Icon.ChevronUp}" Size="12" Margin="2,0,0,0" VerticalAlignment="Center" Visibility="Collapsed" />
|
||||
</StackPanel>
|
||||
</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>
|
||||
|
||||
<!--
|
||||
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,92 @@
|
||||
using System.Windows.Input;
|
||||
using Titano.Core.Advice;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// One section of the editor (BRIEF §12.3): a tab with its measuring tool below the filmstrip and its settings column on
|
||||
/// the right, with "Optimise section" and "Reset". <see cref="Refresh"/> runs after every project change.
|
||||
/// </summary>
|
||||
public abstract class EditorTab : LocalizedViewModel
|
||||
{
|
||||
protected EditorTab(EditorViewModel editor, string key, AdvisorSection section)
|
||||
{
|
||||
Editor = editor;
|
||||
Key = key;
|
||||
Section = section;
|
||||
OptimiseCommand = new RelayCommand(() => Editor.Optimise(Section), () => CanOptimise && !Editor.IsBusy);
|
||||
ResetCommand = new RelayCommand(() => Editor.Session.ResetSection(Section), () => CanReset && !Editor.IsBusy);
|
||||
}
|
||||
|
||||
public EditorViewModel Editor { get; }
|
||||
|
||||
/// <summary>"Frames", "Exposure"… (resource key suffix).</summary>
|
||||
public string Key { get; }
|
||||
|
||||
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 has none).</summary>
|
||||
public virtual bool CanOptimise => true;
|
||||
|
||||
public virtual bool CanReset => true;
|
||||
|
||||
/// <summary>What Optimise section does, or why it cannot run now.</summary>
|
||||
public string OptimiseToolTip => Loc.L(!CanOptimise ? "Tooltips.Editor.OptimiseNone" : Editor.IsBusy ? "Tooltips.Editor.Busy" : "Tooltips.Editor.OptimiseSection");
|
||||
|
||||
public string ResetToolTip => Loc.L(Editor.IsBusy ? "Tooltips.Editor.Busy" : "Tooltips.Editor.ResetSection");
|
||||
|
||||
public ICommand OptimiseCommand { get; }
|
||||
|
||||
public ICommand ResetCommand { get; }
|
||||
|
||||
/// <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()
|
||||
{
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
foreach (var row in Rows) row.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
using System.Collections;
|
||||
using System.Globalization;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Advice;
|
||||
using Titano.Core.Export;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Video;
|
||||
|
||||
namespace Titano.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 const string 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>"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)));
|
||||
return string.Join(Separator, 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 · Titano" 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>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);
|
||||
}
|
||||
@@ -0,0 +1,821 @@
|
||||
using System.Windows;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Threading;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Core.Advice;
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Export;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Render;
|
||||
using Titano.Core.Video;
|
||||
using Titano.Ui.Controls;
|
||||
using Titano.Ui.Mvvm;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// The sequence editor of one open sequence (BRIEF §12.3, Editor.html): header actions, the preview with its tools
|
||||
/// (wipe compare, zoom, overlays) rendered through the pipeline at preview size (at the source's own size for 1:1 and
|
||||
/// wheel zoom), the filmstrip with markers, the section tabs and the keyboard (space, arrows, Ctrl+Z/Y, Ctrl+0/1,
|
||||
/// Ctrl+R, Ctrl+Shift+A). Preview frames, corrections, the export plan and the card estimates are computed off the UI
|
||||
/// thread; each request cancels the previous one. While an analysis or render of this sequence runs, settings are
|
||||
/// disabled and viewing tools stay live.
|
||||
/// </summary>
|
||||
public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
{
|
||||
public const int DefaultPreviewEdge = 1280;
|
||||
private static readonly TimeSpan Debounce = TimeSpan.FromMilliseconds(150);
|
||||
|
||||
private readonly IReadOnlyList<IVideoEncoderProvider> _encoders;
|
||||
private readonly EncoderHost _host;
|
||||
private readonly Dispatcher _dispatcher;
|
||||
private readonly LatestRunner _preview = new(Debounce);
|
||||
private readonly LatestRunner _corrections = new(Debounce);
|
||||
private readonly LatestRunner _plans = new(Debounce);
|
||||
private readonly DispatcherTimer _player;
|
||||
private readonly Dictionary<Guid, Job> _jobs = [];
|
||||
private readonly AsyncRelayCommand _analyse;
|
||||
private readonly AsyncRelayCommand _render;
|
||||
private PreviewRenderer _renderer;
|
||||
private int _currentIndex;
|
||||
private EditorTab _selectedTab;
|
||||
private ImageSource? _previewImage;
|
||||
private ImageSource? _originalImage;
|
||||
private ImageSource? _waveformImage;
|
||||
private string? _previewMessage;
|
||||
private bool _isCompare = true;
|
||||
private bool _showVectors;
|
||||
private bool _showRegions;
|
||||
private bool _showCropMask;
|
||||
private bool _exportCropMask = true;
|
||||
private CropMaskMode _cropMaskMode = CropMaskMode.ShowLoss;
|
||||
private PreviewZoomMode _zoomMode = PreviewZoomMode.Fit;
|
||||
private Rect _cropRect = new(0, 0, 1, 1);
|
||||
private IReadOnlyList<Point>? _regionBoundary;
|
||||
private IReadOnlyList<MotionVector>? _motionVectors;
|
||||
private int _previewEdge = DefaultPreviewEdge;
|
||||
private int _previewVersion;
|
||||
private bool _previewBusy;
|
||||
private RenderCorrections? _correctionsValue;
|
||||
private ExportPlan? _plan;
|
||||
private bool _planned;
|
||||
private IReadOnlyList<TimelineMarker> _markers = [];
|
||||
private IThumbnailSource _thumbnails;
|
||||
private int _playLimit;
|
||||
private double? _analysisSecondsPerFrame;
|
||||
private bool _disposed;
|
||||
|
||||
public EditorViewModel(ShellViewModel shell, EditorSession session, IReadOnlyList<IVideoEncoderProvider> encoders, EncoderHost host)
|
||||
{
|
||||
Shell = shell;
|
||||
Session = session;
|
||||
_encoders = encoders;
|
||||
_host = host;
|
||||
_dispatcher = Dispatcher.CurrentDispatcher;
|
||||
_renderer = new PreviewRenderer(session.Content, session.Source);
|
||||
Planner = new ExportPlanner(session.Content, encoders, host);
|
||||
_thumbnails = new EditorThumbnails(session.Source, session.Content.Count);
|
||||
_player = new DispatcherTimer(DispatcherPriority.Background, _dispatcher);
|
||||
_player.Tick += (_, _) => Advance();
|
||||
|
||||
BackCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Library));
|
||||
_analyse = new AsyncRelayCommand(AnalyseAsync, () => !IsBusy && !IsAnalysing);
|
||||
OptimiseAllCommand = new RelayCommand(OptimiseAll, () => !IsBusy);
|
||||
_render = new AsyncRelayCommand(() => RenderAsync(JobPriority.User, batch: false), () => CanRender);
|
||||
UndoCommand = new RelayCommand(() => Session.Undo(), () => !IsBusy && Session.History.CanUndo);
|
||||
RedoCommand = new RelayCommand(() => Session.Redo(), () => !IsBusy && Session.History.CanRedo);
|
||||
PlayCommand = new RelayCommand(() => TogglePlay(limit: 0));
|
||||
PreviewClipCommand = new RelayCommand(() => TogglePlay(limit: ClipFrames()));
|
||||
StepBackCommand = new RelayCommand(() => CurrentIndex--);
|
||||
StepForwardCommand = new RelayCommand(() => CurrentIndex++);
|
||||
FitCommand = new RelayCommand(() => ZoomMode = PreviewZoomMode.Fit);
|
||||
ActualSizeCommand = new RelayCommand(() => ZoomMode = PreviewZoomMode.Actual, () => !IsExportTab);
|
||||
|
||||
Frames = new FramesTab(this);
|
||||
Exposure = new ExposureTab(this);
|
||||
Tabs = [Frames, Exposure, new MotionTab(this), new CameraTab(this), new TimeTab(this), new StackTab(this), new ExportTab(this)];
|
||||
_selectedTab = Exposure;
|
||||
_currentIndex = session.Project.HeroFrame is { } hero && (uint)hero < (uint)FrameCount ? hero : 0;
|
||||
RenderChoices = [.. ExportPresets.BuiltIn.Select(p => new Choice(p.Id, p.NameKey))];
|
||||
|
||||
session.ProjectChanged += OnProjectChanged;
|
||||
session.ContentChanged += OnContentChanged;
|
||||
session.SaveFailed += OnSaveFailed;
|
||||
if (shell.Services.Jobs is { } jobs) jobs.JobChanged += OnJobChanged;
|
||||
UpdateMarkers();
|
||||
RequestCorrections();
|
||||
RequestPlan();
|
||||
RequestPreview(immediate: true);
|
||||
}
|
||||
|
||||
public ShellViewModel Shell { get; }
|
||||
|
||||
public EditorSession Session { get; }
|
||||
|
||||
public ExportPlanner Planner { get; private set; }
|
||||
|
||||
public string Title => Session.Content.Sequence.DisplayTitle;
|
||||
|
||||
/// <summary>
|
||||
/// "3,600 frames · Canon EOS R5 · 2 s interval · 2 h 00 m · 3 warnings"; on the Export tab what the video will be:
|
||||
/// "3,600 frames · 24 fps · 2 min 30 s · 3840×2160 · source 8192×5464" (Export.html).
|
||||
/// </summary>
|
||||
public string Summary => IsExportTab && Plan is { } plan
|
||||
? EditorText.OutputSummary(Session.Content, plan)
|
||||
: EditorText.Summary(Session.Content, Session.Advice.Findings.Count(f => f.Severity >= FindingSeverity.Warning));
|
||||
|
||||
public FramesTab Frames { get; }
|
||||
|
||||
public ExposureTab Exposure { get; }
|
||||
|
||||
public IReadOnlyList<EditorTab> Tabs { get; }
|
||||
|
||||
public EditorTab SelectedTab
|
||||
{
|
||||
get => _selectedTab;
|
||||
set
|
||||
{
|
||||
if (value is null || !Set(ref _selectedTab, value)) return;
|
||||
OnPropertyChanged(nameof(IsExportTab));
|
||||
OnPropertyChanged(nameof(Summary));
|
||||
OnToolsChanged();
|
||||
// 1:1 is not a tool of the Export tab (Export.html): its picture fits the view.
|
||||
if (IsExportTab) ZoomMode = PreviewZoomMode.Fit;
|
||||
UpdateInfo();
|
||||
RequestPreview(immediate: true);
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The Export tab swaps the preview tools for compare, crop mask and a 10-second preview (Export.html).</summary>
|
||||
public bool IsExportTab => SelectedTab is ExportTab;
|
||||
|
||||
// ---- Frames ----
|
||||
|
||||
public int FrameCount => Session.Content.Count;
|
||||
|
||||
/// <summary>The frame on screen; the filmstrip, the charts and the frame table seek it.</summary>
|
||||
public int CurrentIndex
|
||||
{
|
||||
get => _currentIndex;
|
||||
set
|
||||
{
|
||||
var clamped = FrameCount == 0 ? 0 : int.Clamp(value, 0, FrameCount - 1);
|
||||
if (!Set(ref _currentIndex, clamped)) return;
|
||||
foreach (var tab in Tabs) tab.OnCurrentFrameChanged();
|
||||
UpdateInfo();
|
||||
RequestPreview(immediate: _player.IsEnabled);
|
||||
}
|
||||
}
|
||||
|
||||
public IThumbnailSource Thumbnails { get => _thumbnails; private set => Set(ref _thumbnails, value); }
|
||||
|
||||
/// <summary>Exposure steps (as received), warnings and keyframes above the filmstrip.</summary>
|
||||
public IReadOnlyList<TimelineMarker> Markers { get => _markers; private set => Set(ref _markers, value); }
|
||||
|
||||
// ---- Preview ----
|
||||
|
||||
public ImageSource? PreviewImage { get => _previewImage; private set => Set(ref _previewImage, value); }
|
||||
|
||||
public ImageSource? OriginalImage { get => _originalImage; private set => Set(ref _originalImage, value); }
|
||||
|
||||
/// <summary>Luma waveform of the corrected preview (Exposure tab), as an alpha mask drawn in the accent colour.</summary>
|
||||
public ImageSource? WaveformImage { get => _waveformImage; private set => Set(ref _waveformImage, value); }
|
||||
|
||||
/// <summary>One sentence over the preview when the frame on screen cannot be shown; null otherwise.</summary>
|
||||
public string? PreviewMessage { get => _previewMessage; private set => Set(ref _previewMessage, value); }
|
||||
|
||||
public bool IsCompare { get => _isCompare; set => Set(ref _isCompare, value); }
|
||||
|
||||
/// <summary>The Vectors tool (kept while the Export tab hides it, shown again on the other tabs).</summary>
|
||||
public bool ShowVectors
|
||||
{
|
||||
get => _showVectors;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _showVectors, value)) return;
|
||||
OnPropertyChanged(nameof(ViewVectors));
|
||||
RequestPreview(immediate: true);
|
||||
}
|
||||
}
|
||||
|
||||
public bool ShowRegions
|
||||
{
|
||||
get => _showRegions;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _showRegions, value)) return;
|
||||
OnPropertyChanged(nameof(ViewRegions));
|
||||
RequestPreview(immediate: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The Crop mask tool of the current tab: the Export tab has its own, on by default (Export.html).</summary>
|
||||
public bool ShowCropMask
|
||||
{
|
||||
get => IsExportTab ? _exportCropMask : _showCropMask;
|
||||
set
|
||||
{
|
||||
if (value == ShowCropMask) return;
|
||||
if (IsExportTab) _exportCropMask = value;
|
||||
else _showCropMask = value;
|
||||
OnPropertyChanged();
|
||||
RequestPreview(immediate: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Overlays the viewport draws: only tools that have a button on the current tab.</summary>
|
||||
public bool ViewVectors => ShowVectors && !IsExportTab;
|
||||
|
||||
public bool ViewRegions => ShowRegions && !IsExportTab;
|
||||
|
||||
/// <summary>The crop mask shows "how it will look" (outside hidden) instead of "what I lose" (outside dimmed).</summary>
|
||||
public bool IsCropResult
|
||||
{
|
||||
get => _cropMaskMode == CropMaskMode.ShowResult;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _cropMaskMode, value ? CropMaskMode.ShowResult : CropMaskMode.ShowLoss, nameof(CropMaskMode))) return;
|
||||
OnPropertyChanged();
|
||||
OnPropertyChanged(nameof(CropModeToolTip));
|
||||
}
|
||||
}
|
||||
|
||||
public CropMaskMode CropMaskMode => _cropMaskMode;
|
||||
|
||||
public string CropModeToolTip => Loc.L(IsCropResult ? "Tooltips.Editor.Preview.CropLoss" : "Tooltips.Editor.Preview.CropResult");
|
||||
|
||||
public PreviewZoomMode ZoomMode
|
||||
{
|
||||
get => _zoomMode;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _zoomMode, value)) return;
|
||||
OnPropertyChanged(nameof(IsActualSize));
|
||||
// Fit renders at the view's size; 1:1 and wheel zoom need the source's own pixels.
|
||||
RequestPreview(immediate: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The 1:1 tool (raw pixels).</summary>
|
||||
public bool IsActualSize
|
||||
{
|
||||
get => _zoomMode == PreviewZoomMode.Actual;
|
||||
set => ZoomMode = value ? PreviewZoomMode.Actual : PreviewZoomMode.Fit;
|
||||
}
|
||||
|
||||
public Rect CropRect { get => _cropRect; private set => Set(ref _cropRect, value); }
|
||||
|
||||
public IReadOnlyList<Point>? RegionBoundary { get => _regionBoundary; private set => Set(ref _regionBoundary, value); }
|
||||
|
||||
public IReadOnlyList<MotionVector>? MotionVectors { get => _motionVectors; private set => Set(ref _motionVectors, value); }
|
||||
|
||||
/// <summary>Gain on vector lengths so a pixel of motion stays visible.</summary>
|
||||
public double VectorScale => 4;
|
||||
|
||||
public string WipeLabel => Loc.L("Editor.Preview.Wipe");
|
||||
|
||||
/// <summary>Shot data (bottom-right pill): frame, time, exposure; on the Export tab output time and size.</summary>
|
||||
public string? InfoText { get; private set; }
|
||||
|
||||
/// <summary>Long edge of the view in device pixels (the view reports its size); Fit renders at this size.</summary>
|
||||
public int PreviewEdge
|
||||
{
|
||||
get => _previewEdge;
|
||||
set
|
||||
{
|
||||
var rounded = int.Clamp((value + 63) / 64 * 64, 256, 4096);
|
||||
if (Set(ref _previewEdge, rounded) && _zoomMode == PreviewZoomMode.Fit) RequestPreview();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Long edge the preview renders at: the view's in Fit, the source's own when zoomed (1:1 shows raw pixels).</summary>
|
||||
public int RenderEdge => _zoomMode == PreviewZoomMode.Fit || SourceEdge <= 0 ? PreviewEdge : SourceEdge;
|
||||
|
||||
private int SourceEdge => int.Max(Session.Content.SourceWidth, Session.Content.SourceHeight);
|
||||
|
||||
// ---- Analysis, plan, jobs ----
|
||||
|
||||
/// <summary>The corrections of the current exposure settings, once prepared (target curves).</summary>
|
||||
public RenderCorrections? Corrections { get => _correctionsValue; private set => Set(ref _correctionsValue, value); }
|
||||
|
||||
/// <summary>What the project's export will produce (size, time, encoder, name).</summary>
|
||||
public ExportPlan? Plan { get => _plan; private set => Set(ref _plan, value); }
|
||||
|
||||
/// <summary>An analysis or render of this sequence is running: settings wait, viewing tools stay live.</summary>
|
||||
public bool IsBusy => _jobs.Values.Any(j => j.State == JobState.Running);
|
||||
|
||||
/// <summary>A deep analysis of this sequence is queued or running (Analyse would queue it twice).</summary>
|
||||
public bool IsAnalysing => _jobs.Values.Any(j => j.Kind == JobKind.DeepAnalyse);
|
||||
|
||||
public bool IsEditable => !IsBusy;
|
||||
|
||||
public string? BusyToolTip => IsBusy ? Loc.L("Tooltips.Editor.Busy") : null;
|
||||
|
||||
/// <summary>What Analyse does and costs ("about 6 min" from the speed of the last analysis), or why it is disabled.</summary>
|
||||
public string AnalyseToolTip => IsBusy ? Loc.L("Tooltips.Editor.Busy")
|
||||
: IsAnalysing ? Loc.L("Tooltips.Editor.AnalyseQueued")
|
||||
: _analysisSecondsPerFrame is { } perFrame ? Loc.L("Tooltips.Editor.AnalyseCost", Formatting.Duration(TimeSpan.FromSeconds(perFrame * FrameCount)))
|
||||
: Loc.L("Tooltips.Editor.Analyse");
|
||||
|
||||
public string OptimiseAllToolTip => Loc.L(IsBusy ? "Tooltips.Editor.Busy" : "Tooltips.Editor.OptimiseAll");
|
||||
|
||||
public bool IsPlaying => _player.IsEnabled;
|
||||
|
||||
public string PlayToolTip => Loc.L(IsPlaying ? "Tooltips.Editor.Pause" : "Tooltips.Editor.Play");
|
||||
|
||||
public string PlayName => Loc.L(IsPlaying ? "Editor.Preview.Pause" : "Editor.Preview.Play");
|
||||
|
||||
/// <summary>"Preview 10 s" (Export tab): plays ten seconds of the video's frames, or pauses them.</summary>
|
||||
public string ClipToolTip => Loc.L(IsPlaying ? "Tooltips.Editor.Pause" : "Tooltips.Editor.Preview.Clip");
|
||||
|
||||
// ---- Render ----
|
||||
|
||||
public IReadOnlyList<Choice> RenderChoices { get; }
|
||||
|
||||
/// <summary>The export preset the Render button renders (choosing another one sets it).</summary>
|
||||
public Choice? SelectedRenderChoice
|
||||
{
|
||||
get => RenderChoices.FirstOrDefault(c => string.Equals((string)c.Value, Plan?.Export.PresetId ?? EditorSettings.ExportPreset.Effective(Session.Project, null),
|
||||
StringComparison.OrdinalIgnoreCase));
|
||||
set
|
||||
{
|
||||
if (value?.Value is not string id) return;
|
||||
Session.Edit(p => p with { Export = p.Export with { Preset = p.Export.Preset.WithManual(id), Overrides = new ExportOverrides() } });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"Render · 4K archive".</summary>
|
||||
public string RenderText => Loc.L("Editor.Render", Plan?.PresetName ?? string.Empty);
|
||||
|
||||
public string RenderToolTip => RenderBlockedReason ?? Loc.L("Tooltips.Editor.Render");
|
||||
|
||||
public bool CanRender => RenderBlockedReason is null;
|
||||
|
||||
/// <summary>Why the project's export cannot be rendered now, localised; null when it can.</summary>
|
||||
public string? RenderBlockedReason => Plan switch
|
||||
{
|
||||
null when _planned => Loc.L("Tooltips.Editor.Render.NoSource"),
|
||||
null => Loc.L("Tooltips.Editor.Render.Planning"),
|
||||
{ NameError: { } error } => Loc.L("Tooltips.Editor.Render.NameError", error),
|
||||
{ Setup.Encoder.IsReady: false } plan => plan.Setup.Encoder.Notices.LastOrDefault() is { } notice
|
||||
? Loc.L(notice.Key, [.. notice.Args])
|
||||
: Loc.L("Editor.Export.Unavailable"),
|
||||
{ Setup.Plan.Frames.Count: 0 } => Loc.L("Tooltips.Editor.Render.NoFrames"),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
public ICommand BackCommand { get; }
|
||||
public ICommand AnalyseCommand => _analyse;
|
||||
public ICommand OptimiseAllCommand { get; }
|
||||
public ICommand RenderCommand => _render;
|
||||
public ICommand UndoCommand { get; }
|
||||
public ICommand RedoCommand { get; }
|
||||
public ICommand PlayCommand { get; }
|
||||
public ICommand PreviewClipCommand { get; }
|
||||
public ICommand StepBackCommand { get; }
|
||||
public ICommand StepForwardCommand { get; }
|
||||
public ICommand FitCommand { get; }
|
||||
public ICommand ActualSizeCommand { get; }
|
||||
|
||||
/// <summary>Exposure steps of the sequence: as received by the pixels when the deep analysis measured them, else from the metadata.</summary>
|
||||
public static IReadOnlyList<TimelineMarker> StepMarkers(SequenceContent content)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(content);
|
||||
if (content.Deep is { } deep)
|
||||
{
|
||||
return [.. deep.Exposure.Steps.Select(s => new TimelineMarker(s.Index, s.Received ? MarkerKind.ExposureStep : MarkerKind.Warning,
|
||||
Loc.L(s.Received ? "Editor.Marker.Step" : "Editor.Marker.StepIgnored", EditorText.Ev(s.MeasuredEv ?? s.ExpectedEv))))];
|
||||
}
|
||||
return [.. content.Light.ExposureSteps.Select(s => new TimelineMarker(s.Index, MarkerKind.ExposureStep, Loc.L("Editor.Marker.Step", EditorText.Ev(s.DeltaEv))))];
|
||||
}
|
||||
|
||||
/// <summary>"Optimise section": the advisor's heavier decisions, reported in a toast (what changed, from what to what).</summary>
|
||||
public void Optimise(AdvisorSection section) => Report(Session.Optimise(section));
|
||||
|
||||
/// <summary>Queues a render of the project's export (with its batch presets when <paramref name="batch"/>).</summary>
|
||||
public async Task RenderAsync(JobPriority priority, bool batch)
|
||||
{
|
||||
var export = batch ? Session.Project.Export : Session.Project.Export with { Batch = [] };
|
||||
var request = Session.RenderRequest(export) with { Priority = priority };
|
||||
await Session.SubmitAsync(request);
|
||||
Shell.Notify(Loc.L("Editor.Render.Queued"), request.Label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
|
||||
}
|
||||
|
||||
/// <summary>Re-reads the enabled state of every command (the async ones keep their own event).</summary>
|
||||
public void RefreshCommands()
|
||||
{
|
||||
_analyse.RaiseCanExecuteChanged();
|
||||
_render.RaiseCanExecuteChanged();
|
||||
foreach (var tab in Tabs) tab.RefreshCommands();
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
|
||||
/// <summary>The Exposure tab switched to or from its waveform: the preview measures it.</summary>
|
||||
public void OnWaveformNeeded() => RequestPreview(immediate: true);
|
||||
|
||||
/// <summary>
|
||||
/// Completes once the preview, corrections, plan, estimates and filmstrip thumbnails in flight are done (capture and
|
||||
/// tests); a finished step may start the next (corrections re-render the preview), so it waits until all are quiet.
|
||||
/// </summary>
|
||||
/// <returns>False when the work was still going on after <paramref name="timeout"/>.</returns>
|
||||
public async Task<bool> WhenIdleAsync(TimeSpan timeout)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (deadline - DateTime.UtcNow is { Ticks: > 0 } left)
|
||||
{
|
||||
var work = Work();
|
||||
try
|
||||
{
|
||||
await Task.WhenAll(work).WaitAsync(left);
|
||||
}
|
||||
catch (TimeoutException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
// A failed run was already logged by its owner; it counts as done.
|
||||
}
|
||||
await Task.Delay(50);
|
||||
// Quiet means nothing new was scheduled meanwhile (the same tasks) and no thumbnail is loading.
|
||||
if (work.SequenceEqual(Work()) && (Thumbnails as EditorThumbnails)?.Pending is null or 0) return true;
|
||||
}
|
||||
return false;
|
||||
|
||||
Task[] Work() => [_preview.Idle, _corrections.Idle, _plans.Idle, .. Tabs.OfType<ExportTab>().Select(t => t.EstimatesIdle)];
|
||||
}
|
||||
|
||||
/// <summary>Loads the jobs of this sequence already queued or running (busy state) and the speed of the last analysis.</summary>
|
||||
public async Task AttachJobsAsync()
|
||||
{
|
||||
if (Shell.Services.Jobs is not { } jobs) return;
|
||||
var page = await jobs.ListAsync(null, 200);
|
||||
foreach (var job in page.Items) Track(job);
|
||||
foreach (var job in page.Items.OrderBy(j => j.Finished)) LearnAnalysisSpeed(job);
|
||||
OnBusyChanged();
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_player.Stop();
|
||||
_preview.Dispose();
|
||||
_corrections.Dispose();
|
||||
_plans.Dispose();
|
||||
Session.ProjectChanged -= OnProjectChanged;
|
||||
Session.ContentChanged -= OnContentChanged;
|
||||
Session.SaveFailed -= OnSaveFailed;
|
||||
if (Shell.Services.Jobs is { } jobs) jobs.JobChanged -= OnJobChanged;
|
||||
foreach (var tab in Tabs) tab.Dispose();
|
||||
base.Dispose();
|
||||
await Session.DisposeAsync();
|
||||
}
|
||||
|
||||
public override void Dispose() => _ = DisposeAsync().AsTask();
|
||||
|
||||
// ---- Preview pipeline ----
|
||||
|
||||
private void RequestPreview(bool immediate = false)
|
||||
{
|
||||
if (_disposed || FrameCount == 0) return;
|
||||
var framing = ShowCropMask || ViewRegions ? PreviewFraming.Source : PreviewFraming.Output;
|
||||
var waveform = SelectedTab is ExposureTab { ChartMode: ExposureChart.Waveform };
|
||||
var request = new PreviewRequest(CurrentIndex, Session.Project, RenderEdge, framing, ViewVectors, waveform);
|
||||
var version = ++_previewVersion;
|
||||
_ = RunPreviewAsync(request, version, immediate);
|
||||
}
|
||||
|
||||
private async Task RunPreviewAsync(PreviewRequest request, int version, bool immediate)
|
||||
{
|
||||
var renderer = _renderer;
|
||||
PreviewResult? result = null;
|
||||
var ran = false;
|
||||
_previewBusy = true;
|
||||
try
|
||||
{
|
||||
await _preview.Schedule(async token =>
|
||||
{
|
||||
using var frame = await renderer.RenderAsync(request, renderer.Cached(request.Project) ?? renderer.Latest, token);
|
||||
if (frame is not null) result = PreviewResult.From(frame);
|
||||
ran = true;
|
||||
}, immediate);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
Log.Warning("editor", $"Preview of frame {request.Index + 1} failed", ex);
|
||||
ran = true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (version == _previewVersion) _previewBusy = false;
|
||||
}
|
||||
if (version != _previewVersion || _disposed || !ran) return;
|
||||
if (result is not { } r)
|
||||
{
|
||||
// The frame on screen cannot be shown: never leave the previous frame's picture under this frame's shot data.
|
||||
PreviewImage = OriginalImage = null;
|
||||
MotionVectors = null;
|
||||
WaveformImage = null;
|
||||
PreviewMessage = Loc.L("Editor.Preview.Unreadable");
|
||||
return;
|
||||
}
|
||||
PreviewMessage = null;
|
||||
PreviewImage = r.Corrected;
|
||||
OriginalImage = r.Original;
|
||||
CropRect = r.Crop;
|
||||
RegionBoundary = ViewRegions ? r.Horizon : null;
|
||||
MotionVectors = ViewVectors ? r.Vectors : null;
|
||||
WaveformImage = r.Waveform;
|
||||
}
|
||||
|
||||
private void RequestCorrections()
|
||||
{
|
||||
if (_disposed) return;
|
||||
var renderer = _renderer;
|
||||
var project = Session.Project;
|
||||
if (renderer.Cached(project) is { } cached)
|
||||
{
|
||||
Corrections = cached;
|
||||
NotifyCorrections();
|
||||
return;
|
||||
}
|
||||
_ = RunCorrectionsAsync(renderer, project);
|
||||
}
|
||||
|
||||
private async Task RunCorrectionsAsync(PreviewRenderer renderer, ProjectSettings project)
|
||||
{
|
||||
RenderCorrections? prepared = null;
|
||||
try
|
||||
{
|
||||
await _corrections.Schedule(async token => prepared = await renderer.PrepareAsync(project, token));
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
Log.Warning("editor", "Preparing the preview corrections failed", ex);
|
||||
}
|
||||
if (prepared is null || _disposed || !ReferenceEquals(renderer, _renderer) || !ReferenceEquals(project, Session.Project)) return;
|
||||
Corrections = prepared;
|
||||
NotifyCorrections();
|
||||
RequestPreview(immediate: true);
|
||||
}
|
||||
|
||||
private void NotifyCorrections()
|
||||
{
|
||||
foreach (var tab in Tabs) tab.OnCorrectionsChanged();
|
||||
}
|
||||
|
||||
private void RequestPlan() => _ = RunPlanAsync(Planner, Session.Project);
|
||||
|
||||
private async Task RunPlanAsync(ExportPlanner planner, ProjectSettings project)
|
||||
{
|
||||
ExportPlan? plan = null;
|
||||
try
|
||||
{
|
||||
await _plans.Schedule(_ =>
|
||||
{
|
||||
plan = planner.Plan(project);
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or RenderException)
|
||||
{
|
||||
Log.Warning("editor", "Planning the export failed", ex);
|
||||
}
|
||||
if (_disposed || !ReferenceEquals(planner, Planner) || !ReferenceEquals(project, Session.Project)) return;
|
||||
_planned = true;
|
||||
Plan = plan;
|
||||
OnPropertyChanged(nameof(RenderText));
|
||||
OnPropertyChanged(nameof(RenderToolTip));
|
||||
OnPropertyChanged(nameof(RenderBlockedReason));
|
||||
OnPropertyChanged(nameof(CanRender));
|
||||
OnPropertyChanged(nameof(SelectedRenderChoice));
|
||||
OnPropertyChanged(nameof(Summary));
|
||||
foreach (var tab in Tabs) tab.OnPlanChanged();
|
||||
UpdateInfo();
|
||||
RefreshCommands();
|
||||
}
|
||||
|
||||
// ---- Playback ----
|
||||
|
||||
private void TogglePlay(int limit)
|
||||
{
|
||||
if (_player.IsEnabled)
|
||||
{
|
||||
_player.Stop();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (CurrentIndex >= FrameCount - 1) CurrentIndex = 0;
|
||||
_playLimit = limit;
|
||||
var fps = double.Clamp(Plan?.Setup.Plan.FrameRate.Value ?? 24, 5, 30);
|
||||
_player.Interval = TimeSpan.FromSeconds(1 / fps);
|
||||
_player.Start();
|
||||
}
|
||||
OnPropertyChanged(nameof(IsPlaying));
|
||||
OnPropertyChanged(nameof(PlayToolTip));
|
||||
OnPropertyChanged(nameof(PlayName));
|
||||
OnPropertyChanged(nameof(ClipToolTip));
|
||||
}
|
||||
|
||||
/// <summary>Next frame while playing; frames are skipped rather than queued when the preview is slower than the clock.</summary>
|
||||
private void Advance()
|
||||
{
|
||||
if (_previewBusy) return;
|
||||
if (CurrentIndex >= FrameCount - 1 || (_playLimit > 0 && --_playLimit == 0))
|
||||
{
|
||||
TogglePlay(0);
|
||||
return;
|
||||
}
|
||||
CurrentIndex++;
|
||||
}
|
||||
|
||||
/// <summary>Source frames that make ten seconds of video.</summary>
|
||||
private int ClipFrames()
|
||||
{
|
||||
if (Plan is not { } plan || plan.Setup.Plan.DurationSeconds <= 0) return 240;
|
||||
return int.Max(1, (int)(plan.Setup.Plan.IncludedFrames.Count * double.Min(1, 10 / plan.Setup.Plan.DurationSeconds)));
|
||||
}
|
||||
|
||||
// ---- Changes ----
|
||||
|
||||
private void OnToolsChanged()
|
||||
{
|
||||
OnPropertyChanged(nameof(ShowCropMask));
|
||||
OnPropertyChanged(nameof(ViewVectors));
|
||||
OnPropertyChanged(nameof(ViewRegions));
|
||||
}
|
||||
|
||||
private void OnProjectChanged()
|
||||
{
|
||||
foreach (var tab in Tabs) tab.Refresh();
|
||||
UpdateMarkers();
|
||||
RequestCorrections();
|
||||
RequestPlan();
|
||||
RequestPreview();
|
||||
RefreshCommands();
|
||||
}
|
||||
|
||||
private void OnContentChanged()
|
||||
{
|
||||
_renderer = new PreviewRenderer(Session.Content, Session.Source);
|
||||
Planner = new ExportPlanner(Session.Content, _encoders, _host);
|
||||
if (Thumbnails.Count != FrameCount) Thumbnails = new EditorThumbnails(Session.Source, FrameCount);
|
||||
Corrections = null;
|
||||
foreach (var tab in Tabs) tab.OnContentChanged();
|
||||
OnPropertyChanged(nameof(Summary));
|
||||
OnPropertyChanged(nameof(FrameCount));
|
||||
CurrentIndex = int.Min(CurrentIndex, int.Max(0, FrameCount - 1));
|
||||
UpdateMarkers();
|
||||
RequestCorrections();
|
||||
RequestPlan();
|
||||
RequestPreview(immediate: true);
|
||||
}
|
||||
|
||||
/// <summary>The first failure of a run of failed saves (they are retried until one succeeds); Retry tries at once.</summary>
|
||||
private void OnSaveFailed(Exception ex) => Shell.ShowToast(new Toast
|
||||
{
|
||||
Title = Loc.L("Editor.Save.Failed"),
|
||||
Message = ex.Message,
|
||||
ActionText = Loc.L("Editor.Save.Retry"),
|
||||
ActionToolTip = Loc.L("Tooltips.Editor.Save.Retry"),
|
||||
ActionCommand = new RelayCommand(() => _ = Session.FlushAsync()),
|
||||
});
|
||||
|
||||
private void UpdateMarkers()
|
||||
{
|
||||
var content = Session.Content;
|
||||
var markers = new List<TimelineMarker>(StepMarkers(content));
|
||||
foreach (var finding in Session.Advice.Findings.Where(f => f.Severity >= FindingSeverity.Warning))
|
||||
{
|
||||
var text = Loc.L(finding.Key, finding.Arguments);
|
||||
markers.AddRange(finding.Frames.Take(64).Select(i => new TimelineMarker(i, finding.Severity == FindingSeverity.Error ? MarkerKind.Error : MarkerKind.Warning, text)));
|
||||
}
|
||||
markers.AddRange(Session.Project.Camera.Keyframes.Select(k => new TimelineMarker(k.Frame, MarkerKind.Keyframe, Loc.L("Editor.Marker.Keyframe"))));
|
||||
if (!markers.SequenceEqual(Markers)) Markers = markers;
|
||||
}
|
||||
|
||||
private void UpdateInfo()
|
||||
{
|
||||
if (FrameCount == 0)
|
||||
{
|
||||
InfoText = null;
|
||||
}
|
||||
else if (IsExportTab && Plan is { } plan)
|
||||
{
|
||||
var settings = plan.Setup.Encoder.Settings;
|
||||
var position = plan.Setup.Plan.DurationSeconds * CurrentIndex / double.Max(1, FrameCount - 1);
|
||||
InfoText = string.Join(" · ", EditorText.Position(CurrentIndex, FrameCount),
|
||||
Loc.L("Editor.Preview.OutputTime", EditorText.Clock(position), EditorText.Clock(plan.Setup.Plan.DurationSeconds)),
|
||||
Loc.L("Editor.Preview.OutputSize", EditorText.Size(settings.Width, settings.Height)));
|
||||
}
|
||||
else
|
||||
{
|
||||
InfoText = EditorText.Shot(Session.Content.Frames[CurrentIndex], CurrentIndex, FrameCount);
|
||||
}
|
||||
OnPropertyChanged(nameof(InfoText));
|
||||
}
|
||||
|
||||
private void OptimiseAll() => Report(Session.OptimiseAll());
|
||||
|
||||
private void Report(IReadOnlyList<SettingChange> changes)
|
||||
{
|
||||
if (changes.Count == 0)
|
||||
{
|
||||
Shell.Notify(Loc.L("Editor.Optimise.Nothing"));
|
||||
return;
|
||||
}
|
||||
var lines = changes.Select(c => Loc.L("Editor.Optimise.Change", EditorText.ParameterLabel(c.Parameter), EditorText.Value(c.Parameter, c.Before),
|
||||
EditorText.Value(c.Parameter, c.After)));
|
||||
Shell.Notify(Loc.Plural("Editor.Optimise.Done", changes.Count), string.Join(Environment.NewLine, lines));
|
||||
}
|
||||
|
||||
private async Task AnalyseAsync()
|
||||
{
|
||||
await Session.SubmitAsync(Session.AnalysisRequest());
|
||||
Shell.Notify(Loc.L("Editor.Analyse.Queued"), Title, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
|
||||
}
|
||||
|
||||
private void OnJobChanged(Job job)
|
||||
{
|
||||
if (!job.TargetIds.Contains(Session.Content.Sequence.Id) || job.Kind is not (JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render)) return;
|
||||
_dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
if (_disposed) return;
|
||||
var wasActive = _jobs.ContainsKey(job.Id);
|
||||
Track(job);
|
||||
LearnAnalysisSpeed(job);
|
||||
OnBusyChanged();
|
||||
if (wasActive && job.State == JobState.Done) _ = ReloadAsync(job.Kind == JobKind.Render ? job : null);
|
||||
});
|
||||
}
|
||||
|
||||
private void Track(Job job)
|
||||
{
|
||||
if (!job.TargetIds.Contains(Session.Content.Sequence.Id) || job.Kind is not (JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render)) return;
|
||||
if (job.State is JobState.Queued or JobState.Running) _jobs[job.Id] = job;
|
||||
else _jobs.Remove(job.Id);
|
||||
}
|
||||
|
||||
/// <summary>Seconds per frame of the latest finished deep analysis (any sequence): the cost Analyse announces.</summary>
|
||||
private void LearnAnalysisSpeed(Job job)
|
||||
{
|
||||
if (job is { Kind: JobKind.DeepAnalyse, State: JobState.Done, ItemsPerSecond: > 0 and var speed }) _analysisSecondsPerFrame = 1 / speed;
|
||||
}
|
||||
|
||||
/// <summary>Reads the sequence again after a job; a finished render offers its follow-ups (BRIEF §11.5).</summary>
|
||||
private async Task ReloadAsync(Job? render)
|
||||
{
|
||||
try
|
||||
{
|
||||
await Session.ReloadAsync();
|
||||
}
|
||||
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or UnauthorizedAccessException)
|
||||
{
|
||||
Shell.ReportError(ex);
|
||||
return;
|
||||
}
|
||||
if (render is null || _disposed) return;
|
||||
var output = Session.Content.Renders.FirstOrDefault(r => render.Started is not { } started || r.Created >= started)?.OutputPath;
|
||||
Shell.ShowToast(new Toast
|
||||
{
|
||||
Title = Loc.L("Editor.Render.Done"),
|
||||
Message = output is null ? render.TargetLabel : System.IO.Path.GetFileName(output),
|
||||
ActionText = output is null ? null : Loc.L("Editor.Render.Reveal"),
|
||||
ActionToolTip = output is null ? null : Loc.L("Tooltips.Editor.Render.Reveal"),
|
||||
ActionCommand = output is null ? null : new RelayCommand(() => ShellActions.Reveal(output)),
|
||||
});
|
||||
}
|
||||
|
||||
private void OnBusyChanged()
|
||||
{
|
||||
OnPropertyChanged(nameof(IsBusy));
|
||||
OnPropertyChanged(nameof(IsAnalysing));
|
||||
OnPropertyChanged(nameof(IsEditable));
|
||||
OnPropertyChanged(nameof(BusyToolTip));
|
||||
OnPropertyChanged(nameof(AnalyseToolTip));
|
||||
OnPropertyChanged(nameof(OptimiseAllToolTip));
|
||||
foreach (var tab in Tabs) tab.OnBusyChanged();
|
||||
RefreshCommands();
|
||||
}
|
||||
|
||||
/// <summary>A rendered preview as frozen bitmaps and overlays in picture pixels (built off the UI thread).</summary>
|
||||
private sealed record PreviewResult(ImageSource Corrected, ImageSource Original, Rect Crop, IReadOnlyList<Point> Horizon, IReadOnlyList<MotionVector> Vectors,
|
||||
ImageSource? Waveform)
|
||||
{
|
||||
public static PreviewResult From(PreviewFrame frame) => new(
|
||||
EditorImages.ToBitmap(frame.Corrected),
|
||||
EditorImages.ToBitmap(frame.Original),
|
||||
new Rect(frame.Crop.X, frame.Crop.Y, frame.Crop.Width, frame.Crop.Height),
|
||||
[.. frame.Horizon.Select(p => new Point(p.X, p.Y))],
|
||||
[.. frame.Vectors.Select(v => new MotionVector(v.X, v.Y, v.Dx, v.Dy))],
|
||||
frame.Waveform is { } waveform ? EditorImages.ToMask(waveform) : null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using Titano.Core.Advice;
|
||||
using Titano.Core.Export;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Render;
|
||||
using Titano.Core.Video;
|
||||
using Titano.Data.Processing;
|
||||
|
||||
namespace Titano.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,499 @@
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Windows.Input;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Settings;
|
||||
using Titano.Core.Advice;
|
||||
using Titano.Core.Export;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Video;
|
||||
using Titano.Data.Processing;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.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;
|
||||
|
||||
public string ToolTip => Choice.Reason is { } reason
|
||||
? Loc.L(IsSequencePreset ? "Tooltips.Editor.Export.ApplyPreset" : "Tooltips.Editor.Export.Recommended", reason)
|
||||
: Loc.L("Tooltips.Editor.Export.Preset", Name);
|
||||
|
||||
/// <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;
|
||||
|
||||
public void Update(ExportPlan? plan)
|
||||
{
|
||||
if (plan is null)
|
||||
{
|
||||
Format = Encoding = Estimate = null;
|
||||
return;
|
||||
}
|
||||
var settings = plan.Setup.Encoder.Settings;
|
||||
Format = EditorText.Format(plan.Export, settings.Width, settings.Height);
|
||||
Encoding = EditorText.Encoding(plan.Export, settings.BitRate, plan.Setup.Encoder.Capability?.Name);
|
||||
Estimate = plan.Setup.Encoder.IsReady ? EditorText.Estimate(plan.Estimate) : Loc.L("Editor.Export.Unavailable");
|
||||
}
|
||||
|
||||
public void RefreshBatch() => OnPropertyChanged(nameof(IsInBatch));
|
||||
}
|
||||
|
||||
/// <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 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.IsBusy);
|
||||
_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), () => Editor.Session.Content.Renders.Count > 0);
|
||||
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"));
|
||||
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 ?? Loc.L(Batch.Count > 0 ? "Tooltips.Editor.Export.Batch" : "Tooltips.Editor.Export.BatchEmpty");
|
||||
|
||||
public bool HasHistory => Editor.Session.Content.Renders.Count > 0;
|
||||
|
||||
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); }
|
||||
|
||||
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" (the word, not a colour, carries the state).</summary>
|
||||
public string? EncoderKind => Editor.Plan?.Setup.Encoder.Capability is { } c ? Loc.L(c.Hardware ? "Editor.Export.Hardware" : "Editor.Export.Software") : null;
|
||||
|
||||
public bool IsHardware => 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); }
|
||||
|
||||
public SaveChoice? SelectedSave
|
||||
{
|
||||
get => SaveChoices.FirstOrDefault(c => !c.Browse && c.Folder == Export.Folder);
|
||||
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 => Loc.L("Tooltips.Editor.Export.Folder", Export.Folder ?? Editor.Session.Content.ExportsFolder ?? string.Empty);
|
||||
|
||||
public string? EstimatedSize => Editor.Plan is { Setup.Encoder.IsReady: true } plan ? Formatting.Bytes(plan.Estimate.Bytes) : null;
|
||||
|
||||
public string? EstimatedTime => Editor.Plan is { Setup.Encoder.IsReady: true } plan
|
||||
? Loc.L("Editor.Export.About", Formatting.Duration(plan.Estimate.Time)) + (plan.Setup.Encoder.Capability is { } c ? " · " + 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);
|
||||
|
||||
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))] });
|
||||
}
|
||||
|
||||
public override void Refresh()
|
||||
{
|
||||
base.Refresh();
|
||||
_refreshing = true;
|
||||
try
|
||||
{
|
||||
UpdateLists();
|
||||
SaveChoices = 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;
|
||||
}
|
||||
foreach (var card in Cards)
|
||||
{
|
||||
card.IsSelected = card.Choice.Sequence is null && string.Equals(card.Choice.ExportPresetId, Resolved.PresetId, StringComparison.OrdinalIgnoreCase);
|
||||
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
|
||||
? [.. plan.Setup.Warnings.Select(w => Loc.L(w.Key, [.. w.Args])).Concat(plan.Export.Warnings.Select(k => Loc.L(k))).Distinct()]
|
||||
: [];
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_refreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnContentChanged()
|
||||
{
|
||||
LoadCards();
|
||||
base.OnContentChanged();
|
||||
}
|
||||
|
||||
public override void RefreshCommands()
|
||||
{
|
||||
_renderNow.RaiseCanExecuteChanged();
|
||||
_addToQueue.RaiseCanExecuteChanged();
|
||||
_batch.RaiseCanExecuteChanged();
|
||||
OnPropertyChanged(nameof(AddToQueueToolTip));
|
||||
OnPropertyChanged(nameof(BatchToolTip));
|
||||
}
|
||||
|
||||
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>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];
|
||||
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);
|
||||
}
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException)
|
||||
{
|
||||
Core.Diagnostics.Log.Warning("editor", "Preset estimates failed", ex);
|
||||
return;
|
||||
}
|
||||
if (!ReferenceEquals(cards, Cards) || !ReferenceEquals(project, Editor.Session.Project)) return;
|
||||
for (var i = 0; i < cards.Count; i++) cards[i].Update(plans[i]);
|
||||
}
|
||||
|
||||
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,189 @@
|
||||
using Titano.Core.Advice;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Render;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.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;
|
||||
string? NoDeflicker(ProjectSettings p) => EditorSettings.Deflicker.Effective(p, s.Content.Deep) ? null : Loc.L("Tooltips.Editor.NotApplicable.DeflickerOff");
|
||||
string? NoHolyGrail(ProjectSettings p) => EditorSettings.HolyGrail.Effective(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", double.Round(low, -1).ToString("N0", Loc.Culture), double.Round(high, -1).ToString("N0", Loc.Culture)), null);
|
||||
return (null, Loc.L("Tooltips.Editor.NotApplicable.Kelvin"));
|
||||
}
|
||||
|
||||
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(" · ", parts);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
using System.Windows.Input;
|
||||
using Titano.Core.Advice;
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Ui.Controls;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.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 sort state and the command that sorts on it.</summary>
|
||||
public sealed class FrameColumn(FramesTab owner, FrameSort sort) : ObservableObject
|
||||
{
|
||||
public FrameSort Sort { get; } = 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(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(" · ", parts);
|
||||
}
|
||||
}
|
||||
|
||||
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 => Loc.L(owner.Editor.IsBusy ? "Tooltips.Editor.Busy" : 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(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; 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.IsBusy);
|
||||
SetHeroCommand = new RelayCommand(p => Editor.Session.SetHero(p is FrameRow row ? row.Index : Editor.CurrentIndex), _ => !Editor.IsBusy);
|
||||
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 => Loc.L(Editor.IsBusy ? "Tooltips.Editor.Busy" : IsCurrentExcluded ? "Tooltips.Editor.Frames.Include" : "Tooltips.Editor.Frames.Exclude");
|
||||
|
||||
/// <summary>What Set hero does, or why it waits.</summary>
|
||||
public string HeroToolTip => Loc.L(Editor.IsBusy ? "Tooltips.Editor.Busy" : "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();
|
||||
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();
|
||||
Findings = [.. Editor.Session.Advice.Findings.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);
|
||||
|
||||
private static FindingItem ToItem(Finding finding) => new(
|
||||
finding.Severity switch
|
||||
{
|
||||
FindingSeverity.Error => StatusKind.Error,
|
||||
FindingSeverity.Warning => StatusKind.Warning,
|
||||
_ => StatusKind.NotAnalysed,
|
||||
},
|
||||
Loc.L(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,30 @@
|
||||
<Window x:Class="Titano.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:Titano.Ui.Controls;assembly=Titano.Ui"
|
||||
xmlns:v="clr-namespace:Titano.Ui.Visuals;assembly=Titano.Ui"
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.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:,,,/Titano;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>
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<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 Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.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,69 @@
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Data.Archiving.Jobs;
|
||||
|
||||
namespace Titano.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 (a source that reads proxies and posts jobs to the API). The editor reads frames, saves the
|
||||
/// project and queues jobs only through this interface.
|
||||
/// </summary>
|
||||
public interface ISequenceSource : IAsyncDisposable
|
||||
{
|
||||
/// <summary>Everything the editor shows of the sequence; read off the UI thread.</summary>
|
||||
/// <exception cref="InvalidDataException">The project cannot be read (corrupt, or written by a newer Titano).</exception>
|
||||
Task<SequenceContent> LoadAsync(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>
|
||||
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>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.</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.</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)
|
||||
{
|
||||
/// <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>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,50 @@
|
||||
namespace Titano.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);
|
||||
await Task.Run(() => work(token), 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,161 @@
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using Titano.Core.Advice;
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Archiving;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.IO;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Data.Archiving.Jobs;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Repositories;
|
||||
|
||||
namespace Titano.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>.titano/project.json</c> mirrored in the index's settings column, 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.
|
||||
/// </summary>
|
||||
public sealed class LocalSequenceSource(TitanoDatabase db, Guid sequenceId, ImageDecoder decoder, JobEngine? engine, ArchiveServiceOptions? lease = null)
|
||||
: ISequenceSource
|
||||
{
|
||||
private const int PageSize = 1000;
|
||||
private const int SaveAttempts = 3;
|
||||
|
||||
private readonly ArchiveServiceOptions _lease = lease ?? new ArchiveServiceOptions();
|
||||
private string?[] _files = [];
|
||||
private ArchivePaths? _paths;
|
||||
private SequencePaths? _folder;
|
||||
|
||||
public async Task<SequenceContent> LoadAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken) ?? throw Missing();
|
||||
var archive = await db.Archives.GetAsync(sequence.ArchiveId, 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 renders = await db.Renders.ListBySequenceAsync(sequenceId, 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);
|
||||
}
|
||||
(_paths, _folder, _files) = (paths, folder, files);
|
||||
var context = SequenceContext.FromFrames(frames);
|
||||
return new SequenceContent(sequence, frames, ReadProject(sequence, folder), LightAnalyzer.Analyze(frames), ReadReport(folder, frames.Count),
|
||||
context.SourceWidth, context.SourceHeight, folder.Exports, [.. renders.OrderByDescending(r => r.Created)]);
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
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;
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
try
|
||||
{
|
||||
// Thumbnails take an embedded preview when it is large enough (no RAW development for a filmstrip cell).
|
||||
var request = new DecodeRequest(file, maxLongEdge, purpose, ForcePreview: purpose == DecodePurpose.Thumbnail);
|
||||
return decoder.Decode(request, cancellationToken)?.Pixels;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("editor", $"Frame {file} could not be read", ex);
|
||||
return null;
|
||||
}
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
public Task<ProjectSettings> SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
var (paths, folder) = (_paths, _folder);
|
||||
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();
|
||||
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 result = await db.Sequences.EditAsync(sequenceId, new SequenceEdit { SettingsJson = json }, row.SettingsVersion, cancellationToken);
|
||||
switch (result.Outcome)
|
||||
{
|
||||
case SequenceEditOutcome.Updated:
|
||||
return merged;
|
||||
case SequenceEditOutcome.NotFound:
|
||||
throw Missing();
|
||||
// The settings moved in the index meanwhile (server API): merge again on top of them; the file follows the next write.
|
||||
case SequenceEditOutcome.Conflict when attempt == SaveAttempts:
|
||||
throw new IOException(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 ValueTask DisposeAsync() => ValueTask.CompletedTask;
|
||||
|
||||
/// <summary>The settings in force: the index copy, else <c>project.json</c>, else defaults.</summary>
|
||||
/// <exception cref="InvalidDataException">The settings are not a project or come from a newer Titano.</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 (JsonException ex)
|
||||
{
|
||||
throw new InvalidDataException(Loc.L("Editor.Error.Project"), ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The saved deep report when it describes the current frames.</summary>
|
||||
private static DeepAnalysisReport? ReadReport(SequencePaths folder, int frameCount)
|
||||
{
|
||||
if (!File.Exists(folder.AnalysisPath)) return null;
|
||||
try
|
||||
{
|
||||
var report = DeepAnalysisReport.Load(folder.AnalysisPath);
|
||||
return report.FrameCount == frameCount ? report : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or JsonException)
|
||||
{
|
||||
Log.Warning("editor", $"{folder.AnalysisPath} cannot be read", ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static InvalidOperationException Missing() => new(Loc.L("Editor.Error.Missing"));
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using Titano.Core.Imaging;
|
||||
|
||||
namespace Titano.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,159 @@
|
||||
using Titano.Core.Advice;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Ui.Visuals;
|
||||
|
||||
namespace Titano.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;
|
||||
string? NoBlur(ProjectSettings p) => EditorSettings.MotionBlur.Effective(p, null) ? null : Loc.L("Tooltips.Editor.NotApplicable.BlurOff");
|
||||
string? NoFlow(ProjectSettings p) =>
|
||||
EditorSettings.MotionBlur.Effective(p, null) || EditorSettings.TimingMode.Effective(p, null) == TimingMode.Interpolated
|
||||
? null
|
||||
: Loc.L("Tooltips.Editor.NotApplicable.NoFlow");
|
||||
string? NoStabilize(ProjectSettings p) => EditorSettings.Stabilize.Effective(p, null) ? 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(" · ", 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 Titano.Core.Analysis;
|
||||
using Titano.Core.Export;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Imaging.Geometry;
|
||||
using Titano.Core.Motion;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Render;
|
||||
|
||||
namespace Titano.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,93 @@
|
||||
using Titano.Core.Project;
|
||||
|
||||
namespace Titano.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();
|
||||
}
|
||||
|
||||
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,52 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using Titano.Core.Project;
|
||||
|
||||
namespace Titano.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).
|
||||
/// </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>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>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,151 @@
|
||||
using Titano.Core.Project;
|
||||
|
||||
namespace Titano.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. 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>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>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();
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
ProjectSettings next;
|
||||
lock (_gate)
|
||||
{
|
||||
_flushRequested = false;
|
||||
if (_pending is null)
|
||||
{
|
||||
_running = false;
|
||||
Complete(true);
|
||||
return;
|
||||
}
|
||||
next = _pending;
|
||||
_pending = null;
|
||||
}
|
||||
int failures;
|
||||
try
|
||||
{
|
||||
await save(next);
|
||||
lock (_gate) _failures = 0;
|
||||
LastError = null;
|
||||
// A change made during the write is written right after it.
|
||||
wait = TimeSpan.Zero;
|
||||
continue;
|
||||
}
|
||||
catch (Exception 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;
|
||||
}
|
||||
LastError = ex;
|
||||
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 Complete(bool stored)
|
||||
{
|
||||
foreach (var flush in _flushes) flush.TrySetResult(stored);
|
||||
_flushes.Clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
using System.Numerics;
|
||||
using System.Windows.Input;
|
||||
using Titano.Core.Advice;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.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.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") + " · " + (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();
|
||||
}
|
||||
@@ -2,10 +2,172 @@
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui"
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui">
|
||||
<Grid Margin="20">
|
||||
<ui:EmptyState Message="{l:Loc Editor.Empty}">
|
||||
xmlns:v="clr-namespace:Titano.Ui.Visuals;assembly=Titano.Ui"
|
||||
xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"
|
||||
KeyDown="OnKeyDown" Loaded="OnLoaded">
|
||||
<UserControl.Resources>
|
||||
<ResourceDictionary>
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="pack://application:,,,/Titano;component/Editor/EditorStyles.xaml" />
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
</ResourceDictionary>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Grid>
|
||||
<ui:EmptyState Message="{l:Loc Editor.Empty}" Visibility="{Binding IsEmpty, Converter={StaticResource BoolToVisibility}}">
|
||||
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Shell.Nav.Library}" Command="{Binding OpenLibraryCommand}" ToolTip="{l:Loc Tooltips.Nav.Library}" />
|
||||
</ui:EmptyState>
|
||||
<ProgressBar Width="240" IsIndeterminate="True" VerticalAlignment="Center" Visibility="{Binding IsLoading, Converter={StaticResource BoolToVisibility}}"
|
||||
AutomationProperties.Name="{l:Loc Editor.Loading}" />
|
||||
|
||||
<!-- Editor.html: header, then the preview, filmstrip and section tabs on the left and the section's settings on the right. -->
|
||||
<Grid x:Name="EditorRoot" DataContext="{Binding Editor}" Margin="16,0,16,12" IsVisibleChanged="OnEditorVisibleChanged"
|
||||
Visibility="{Binding Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
|
||||
<Grid.InputBindings>
|
||||
<KeyBinding Key="Z" Modifiers="Control" Command="{Binding UndoCommand}" />
|
||||
<KeyBinding Key="Y" Modifiers="Control" Command="{Binding RedoCommand}" />
|
||||
<KeyBinding Key="D0" Modifiers="Control" Command="{Binding FitCommand}" />
|
||||
<KeyBinding Key="D1" Modifiers="Control" Command="{Binding ActualSizeCommand}" />
|
||||
<KeyBinding Key="R" Modifiers="Control" Command="{Binding RenderCommand}" />
|
||||
<KeyBinding Key="A" Modifiers="Control+Shift" Command="{Binding AnalyseCommand}" />
|
||||
</Grid.InputBindings>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="52" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<Button Style="{StaticResource Button.IconSubtle}" ui:ButtonIcon.Glyph="{StaticResource Icon.Back}" Command="{Binding BackCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Back}" AutomationProperties.Name="{l:Loc Editor.Back}" Margin="-6,0,0,0" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding Title}" Style="{StaticResource Text.Title}" VerticalAlignment="Center" Margin="6,0,12,0" MaxWidth="320"
|
||||
TextTrimming="CharacterEllipsis" />
|
||||
<TextBlock Grid.Column="2" Text="{Binding Summary}" Style="{StaticResource Text.Secondary}" FontSize="{StaticResource Size.Body}" VerticalAlignment="Center"
|
||||
TextTrimming="CharacterEllipsis" Typography.NumeralAlignment="Tabular" ToolTip="{Binding Summary}" />
|
||||
<StackPanel Grid.Column="3" Orientation="Horizontal" VerticalAlignment="Center" Margin="12,0,0,0">
|
||||
<Button Content="{l:Loc Editor.Analyse}" Command="{Binding AnalyseCommand}" ToolTip="{Binding AnalyseToolTip}" ToolTipService.ShowOnDisabled="True" />
|
||||
<Button Content="{l:Loc Editor.OptimiseAll}" Command="{Binding OptimiseAllCommand}" ToolTip="{Binding OptimiseAllToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" Margin="12,0,0,0" />
|
||||
<v:SplitButton x:Name="RenderButton" IsPrimary="True" Margin="12,0,0,0" Content="{Binding RenderText}" Command="{Binding RenderCommand}"
|
||||
ItemsSource="{Binding RenderChoices}" DisplayMemberPath="Label" SelectedItem="{Binding SelectedRenderChoice}" ToolTip="{Binding RenderToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" DropDownToolTip="{l:Loc Tooltips.Editor.RenderChoice}"
|
||||
AutomationProperties.Name="{l:Loc Editor.RenderButton}" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
|
||||
<Grid Grid.Row="1">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="{StaticResource Editor.Grid.Panel}" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<Grid Margin="0,0,16,0">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition MinHeight="160">
|
||||
<RowDefinition.Style>
|
||||
<Style TargetType="RowDefinition">
|
||||
<Setter Property="Height" Value="{StaticResource Editor.Grid.Preview}" />
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsExportTab}" Value="True">
|
||||
<Setter Property="Height" Value="{StaticResource Editor.Grid.ExportPreview}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</RowDefinition.Style>
|
||||
</RowDefinition>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition MinHeight="150">
|
||||
<RowDefinition.Style>
|
||||
<Style TargetType="RowDefinition">
|
||||
<Setter Property="Height" Value="{StaticResource Editor.Grid.Measure}" />
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsExportTab}" Value="True">
|
||||
<Setter Property="Height" Value="{StaticResource Editor.Grid.ExportMeasure}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</RowDefinition.Style>
|
||||
</RowDefinition>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<v:PreviewViewport x:Name="Preview" Source="{Binding PreviewImage}" OriginalSource="{Binding OriginalImage}" IsCompareEnabled="{Binding IsCompare}"
|
||||
WipeLabel="{Binding WipeLabel}" ZoomMode="{Binding ZoomMode, Mode=TwoWay}" ShowVectors="{Binding ViewVectors}"
|
||||
MotionVectors="{Binding MotionVectors}" VectorScale="{Binding VectorScale}" ShowRegions="{Binding ViewRegions}"
|
||||
RegionBoundary="{Binding RegionBoundary}" ShowCropMask="{Binding ShowCropMask}" CropRect="{Binding CropRect}"
|
||||
CropMaskMode="{Binding CropMaskMode}" InfoText="{Binding InfoText}" ToolTip="{l:Loc Tooltips.Editor.Preview.View}"
|
||||
AutomationProperties.Name="{l:Loc Editor.Preview}" SizeChanged="OnPreviewSizeChanged">
|
||||
<v:PreviewViewport.ToolsContent>
|
||||
<!-- Tools give the keyboard back to the preview after a click, so Space keeps playing (OnToolClicked). -->
|
||||
<StackPanel Orientation="Horizontal" DataContext="{Binding DataContext, ElementName=EditorRoot}" ButtonBase.Click="OnToolClicked">
|
||||
<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 Visibility="{Binding IsExportTab, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" Style="{StaticResource ToggleButton.PreviewTool}"
|
||||
IsChecked="{Binding ShowVectors}" ui:ButtonIcon.Glyph="{StaticResource Icon.Vectors}" Content="{l:Loc Editor.Preview.Vectors}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Preview.Vectors}" />
|
||||
<ToggleButton Visibility="{Binding IsExportTab, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" Style="{StaticResource ToggleButton.PreviewTool}"
|
||||
IsChecked="{Binding ShowRegions}" ui:ButtonIcon.Glyph="{StaticResource Icon.Regions}" Content="{l:Loc Editor.Preview.Regions}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Preview.Regions}" />
|
||||
<ToggleButton Style="{StaticResource ToggleButton.PreviewTool}" IsChecked="{Binding ShowCropMask}" ui:ButtonIcon.Glyph="{StaticResource Icon.CropMask}"
|
||||
Content="{l:Loc Editor.Preview.CropMask}" ToolTip="{l:Loc Tooltips.Editor.Preview.CropMask}" />
|
||||
<!-- "What I lose" (dimmed) or "how it will look" (hidden) outside the crop (BRIEF §12.3). -->
|
||||
<ToggleButton Visibility="{Binding ShowCropMask, Converter={StaticResource BoolToVisibility}}" Style="{StaticResource ToggleButton.PreviewToolIcon}"
|
||||
IsChecked="{Binding IsCropResult}" ui:ButtonIcon.Glyph="{StaticResource Icon.Eye}" ToolTip="{Binding CropModeToolTip}"
|
||||
AutomationProperties.Name="{l:Loc Editor.Preview.CropResult}" />
|
||||
<ToggleButton Visibility="{Binding IsExportTab, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" Style="{StaticResource ToggleButton.PreviewTool}"
|
||||
IsChecked="{Binding IsActualSize}" Content="{l:Loc Editor.Preview.ActualSize}" ToolTip="{l:Loc Tooltips.Editor.Preview.ActualSize}" />
|
||||
<Button Visibility="{Binding IsExportTab, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" Style="{StaticResource Button.PreviewToolIcon}"
|
||||
ui:ButtonIcon.Glyph="{StaticResource Icon.Fullscreen}" Click="OnFullScreen" ToolTip="{l:Loc Tooltips.Editor.Preview.FullScreen}"
|
||||
AutomationProperties.Name="{l:Loc Editor.Preview.FullScreen}" />
|
||||
<Button Visibility="{Binding IsExportTab, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" Style="{StaticResource Button.PlayTool}"
|
||||
Command="{Binding PlayCommand}" ToolTip="{Binding PlayToolTip}" AutomationProperties.Name="{Binding PlayName}" />
|
||||
<Button Content="{l:Loc Editor.Preview.Clip}" Command="{Binding PreviewClipCommand}" ToolTip="{Binding ClipToolTip}"
|
||||
Visibility="{Binding IsExportTab, Converter={StaticResource BoolToVisibility}}">
|
||||
<Button.Style>
|
||||
<Style TargetType="Button" BasedOn="{StaticResource Button.PreviewTool}">
|
||||
<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>
|
||||
</Button.Style>
|
||||
</Button>
|
||||
</StackPanel>
|
||||
</v:PreviewViewport.ToolsContent>
|
||||
</v:PreviewViewport>
|
||||
<!-- The frame on screen cannot be read: one sentence instead of another frame's picture. -->
|
||||
<TextBlock Text="{Binding PreviewMessage}" Style="{StaticResource Text.Secondary}" HorizontalAlignment="Center" VerticalAlignment="Center"
|
||||
IsHitTestVisible="False" Visibility="{Binding PreviewMessage, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
|
||||
|
||||
<v:Filmstrip Grid.Row="1" Margin="0,10,0,0" Source="{Binding Thumbnails}" CurrentIndex="{Binding CurrentIndex, Mode=TwoWay}" Markers="{Binding Markers}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Filmstrip}" AutomationProperties.Name="{l:Loc Editor.Filmstrip}" />
|
||||
|
||||
<TabControl Grid.Row="2" Margin="0,10,0,0" ItemsSource="{Binding Tabs}" SelectedItem="{Binding SelectedTab}" AutomationProperties.Name="{l:Loc Editor.Sections}">
|
||||
<TabControl.Resources>
|
||||
<ResourceDictionary Source="pack://application:,,,/Titano;component/Editor/EditorMeasures.xaml" />
|
||||
</TabControl.Resources>
|
||||
<TabControl.ItemContainerStyle>
|
||||
<Style TargetType="TabItem" BasedOn="{StaticResource {x:Type TabItem}}">
|
||||
<Setter Property="Header" Value="{Binding Header}" />
|
||||
<Setter Property="ToolTip" Value="{Binding ToolTip}" />
|
||||
<Setter Property="AutomationProperties.Name" Value="{Binding Header}" />
|
||||
</Style>
|
||||
</TabControl.ItemContainerStyle>
|
||||
</TabControl>
|
||||
</Grid>
|
||||
|
||||
<ContentControl Grid.Column="1" Content="{Binding SelectedTab}" Focusable="False">
|
||||
<ContentControl.Resources>
|
||||
<ResourceDictionary Source="pack://application:,,,/Titano;component/Editor/EditorPanels.xaml" />
|
||||
</ContentControl.Resources>
|
||||
</ContentControl>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -1,8 +1,129 @@
|
||||
using System.ComponentModel;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Controls.Primitives;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Threading;
|
||||
using Titano.App.Editor;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Core.Diagnostics;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
public partial class SequenceView : UserControl
|
||||
{
|
||||
public SequenceView() => InitializeComponent();
|
||||
/// <summary>Set on a window once its closing waits for the editor's last save.</summary>
|
||||
private static readonly DependencyProperty SavesBeforeClosingProperty =
|
||||
DependencyProperty.RegisterAttached("SavesBeforeClosing", typeof(bool), typeof(SequenceView), new PropertyMetadata(false));
|
||||
|
||||
public SequenceView()
|
||||
{
|
||||
InitializeComponent();
|
||||
// A drag, a click or a key press is one undo step even when it moves a slider many times (ProjectHistory runs);
|
||||
// handled events too, because sliders and repeat buttons mark theirs handled.
|
||||
EditorRoot.AddHandler(Thumb.DragCompletedEvent, new DragCompletedEventHandler((_, _) => EndEditRun()), handledEventsToo: true);
|
||||
EditorRoot.AddHandler(MouseLeftButtonUpEvent, new MouseButtonEventHandler((_, _) => EndEditRun()), handledEventsToo: true);
|
||||
EditorRoot.AddHandler(KeyUpEvent, new KeyEventHandler((_, _) => EndEditRun()), handledEventsToo: true);
|
||||
}
|
||||
|
||||
private EditorViewModel? Editor => (DataContext as SequenceViewModel)?.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// The project is saved a moment after each edit; closing the window first stores the last edit, and asks before
|
||||
/// discarding one that cannot be stored (once per window, so it holds even when another section is showing).
|
||||
/// </summary>
|
||||
private void OnLoaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
FocusPreview();
|
||||
if (Window.GetWindow(this) is not { } window || (bool)window.GetValue(SavesBeforeClosingProperty)) return;
|
||||
window.SetValue(SavesBeforeClosingProperty, true);
|
||||
var (saved, asking, closed) = (false, false, false);
|
||||
window.Closing += OnClosing;
|
||||
window.Closed += (_, _) => closed = true;
|
||||
|
||||
async void OnClosing(object? s, CancelEventArgs args)
|
||||
{
|
||||
if (saved || args.Cancel || window.DataContext is not ShellViewModel { Sequence: { HasPendingSave: true } section }) return;
|
||||
args.Cancel = true;
|
||||
if (asking) return;
|
||||
asking = true;
|
||||
var close = true;
|
||||
try
|
||||
{
|
||||
close = await section.ConfirmCloseAsync();
|
||||
if (close) await section.CloseAsync();
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Warning("editor", "The last edit was not saved before closing", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
asking = false;
|
||||
}
|
||||
// "Keep editing": the window stays open with the edit still pending.
|
||||
if (!close) return;
|
||||
saved = true;
|
||||
// An application shutdown closes the window without waiting.
|
||||
if (!closed) window.Close();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Space plays or pauses, arrows step a frame (BRIEF §12.3) — unless a text field or a control that uses the key has it.</summary>
|
||||
private void OnKeyDown(object sender, KeyEventArgs e)
|
||||
{
|
||||
if (e.Handled || Editor is not { } editor || Keyboard.Modifiers != ModifierKeys.None || e.OriginalSource is TextBoxBase) return;
|
||||
var 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;
|
||||
}
|
||||
|
||||
/// <summary>An opened editor takes the keyboard, so its shortcuts work without clicking into it first.</summary>
|
||||
private void OnEditorVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.NewValue is true) FocusPreview();
|
||||
}
|
||||
|
||||
/// <summary>A tool clicked with the mouse hands the keyboard back to the preview (Space keeps playing); keyboard users keep their focus.</summary>
|
||||
private void OnToolClicked(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (InputManager.Current.MostRecentInputDevice is MouseDevice) Preview.Focus();
|
||||
}
|
||||
|
||||
private void FocusPreview()
|
||||
{
|
||||
if (Editor is null) return;
|
||||
Dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
if (Preview.IsVisible && !IsKeyboardFocusWithin) Keyboard.Focus(Preview);
|
||||
}, DispatcherPriority.Input);
|
||||
}
|
||||
|
||||
private void EndEditRun() => Editor?.Session.EndEditRun();
|
||||
|
||||
/// <summary>The preview renders at the size it is shown, in device pixels.</summary>
|
||||
private void OnPreviewSizeChanged(object sender, SizeChangedEventArgs e)
|
||||
{
|
||||
if (Editor is not { } editor) return;
|
||||
var scale = VisualTreeHelper.GetDpi(this).DpiScaleX;
|
||||
editor.PreviewEdge = (int)(double.Max(e.NewSize.Width, e.NewSize.Height) * scale);
|
||||
}
|
||||
|
||||
private void OnFullScreen(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (Editor is not { } editor) return;
|
||||
var restore = editor.PreviewEdge;
|
||||
var window = new FullScreenPreview(editor) { Owner = Window.GetWindow(this) };
|
||||
window.ShowDialog();
|
||||
editor.PreviewEdge = restore;
|
||||
Preview.Focus();
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,170 @@
|
||||
using System.ComponentModel;
|
||||
using System.Windows.Input;
|
||||
using Titano.App.Editor;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Export;
|
||||
using Titano.Core.Imaging.Decoders;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
/// <summary>Sequence editor (BRIEF §12.3).</summary>
|
||||
public sealed class SequenceViewModel(ShellViewModel shell) : SectionViewModel(SectionKey.Sequence, "Icon.Sequence")
|
||||
/// <summary>
|
||||
/// The Sequence section (BRIEF §12.3): opens the sequence the Library (or Jobs) chose into an <see cref="EditorViewModel"/>
|
||||
/// and closes the previous one after saving it; without a sequence it shows the empty state. A failed open is reported
|
||||
/// and leaves the section usable; an edit that cannot be saved is never dropped without the user's confirmation.
|
||||
/// </summary>
|
||||
public sealed class SequenceViewModel : SectionViewModel
|
||||
{
|
||||
public ShellViewModel Shell { get; } = shell;
|
||||
public ICommand OpenLibraryCommand => new RelayCommand(() => Shell.Navigate(SectionKey.Library));
|
||||
private EditorViewModel? _editor;
|
||||
private Guid? _openId;
|
||||
private bool _isLoading;
|
||||
private Task _switch = Task.CompletedTask;
|
||||
|
||||
public SequenceViewModel(ShellViewModel shell)
|
||||
: base(SectionKey.Sequence, "Icon.Sequence")
|
||||
{
|
||||
Shell = shell;
|
||||
OpenLibraryCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Library));
|
||||
shell.PropertyChanged += OnShellChanged;
|
||||
}
|
||||
|
||||
public ShellViewModel Shell { get; }
|
||||
|
||||
public ICommand OpenLibraryCommand { get; }
|
||||
|
||||
/// <summary>The open sequence; null shows the empty state.</summary>
|
||||
public EditorViewModel? Editor
|
||||
{
|
||||
get => _editor;
|
||||
private set
|
||||
{
|
||||
if (!Set(ref _editor, value)) return;
|
||||
OnPropertyChanged(nameof(IsEmpty));
|
||||
OnPropertyChanged(nameof(Title));
|
||||
}
|
||||
}
|
||||
|
||||
public bool IsLoading { get => _isLoading; private set => Set(ref _isLoading, value); }
|
||||
|
||||
public bool IsEmpty => _editor is null && !_isLoading;
|
||||
|
||||
/// <summary>The open sequence has an edit not stored yet (the save follows each change after a moment, and retries after a failure).</summary>
|
||||
public bool HasPendingSave => _editor?.Session.HasPendingSave == true;
|
||||
|
||||
/// <summary>"Titano — Harbour sunset" while a sequence is open.</summary>
|
||||
public override string Title => _editor?.Title ?? Label;
|
||||
|
||||
/// <summary>Opens <paramref name="sequenceId"/> (the editor of another sequence is saved and closed first).</summary>
|
||||
public Task OpenAsync(Guid sequenceId)
|
||||
{
|
||||
_switch = SwitchAsync(_switch, sequenceId);
|
||||
return _switch;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores the open sequence's last edit. When the save fails (archive offline, read-only, busy), asks whether to
|
||||
/// discard the edit (BRIEF §12.1: modals only for destructive confirmations).
|
||||
/// </summary>
|
||||
/// <returns>True when the editor may close: everything is stored or the user chose to discard.</returns>
|
||||
public async Task<bool> ConfirmCloseAsync()
|
||||
{
|
||||
if (Editor is not { } editor || await editor.Session.FlushAsync()) return true;
|
||||
return Shell.Services.Dialogs.Confirm(new ConfirmRequest
|
||||
{
|
||||
Heading = Loc.L("Editor.Unsaved.Title"),
|
||||
Message = Loc.L("Editor.Unsaved.Message", editor.Title, editor.Session.LastSaveError?.Message ?? string.Empty),
|
||||
SafeText = Loc.L("Editor.Unsaved.Keep"),
|
||||
SafeToolTip = Loc.L("Tooltips.Editor.Unsaved.Keep"),
|
||||
ActionText = Loc.L("Editor.Unsaved.Discard"),
|
||||
ActionToolTip = Loc.L("Tooltips.Editor.Unsaved.Discard"),
|
||||
IsDestructive = true,
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Closes the open sequence (after <see cref="ConfirmCloseAsync"/>, which stores its last edit).</summary>
|
||||
public async Task CloseAsync()
|
||||
{
|
||||
await Settled(_switch);
|
||||
if (Editor is not { } editor) return;
|
||||
Editor = null;
|
||||
_openId = null;
|
||||
await editor.DisposeAsync();
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
Shell.PropertyChanged -= OnShellChanged;
|
||||
Editor?.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
|
||||
protected override void OnActivated()
|
||||
{
|
||||
if (Shell.CurrentSequenceId is { } id && id != _openId) _ = OpenAsync(id);
|
||||
}
|
||||
|
||||
private void OnShellChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName == nameof(ShellViewModel.CurrentSequenceId) && IsSelected) OnActivated();
|
||||
}
|
||||
|
||||
/// <summary>Waits for <paramref name="task"/>; its failure was reported where it happened.</summary>
|
||||
private static async Task Settled(Task task)
|
||||
{
|
||||
try
|
||||
{
|
||||
await task;
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
Log.Debug("editor", $"An earlier open of the editor failed: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SwitchAsync(Task previous, Guid sequenceId)
|
||||
{
|
||||
await Settled(previous);
|
||||
if (sequenceId == _openId) return;
|
||||
// The open sequence keeps its editor while its last edit is neither stored nor deliberately discarded.
|
||||
if (!await ConfirmCloseAsync()) return;
|
||||
var services = Shell.Services;
|
||||
IsLoading = true;
|
||||
OnPropertyChanged(nameof(IsEmpty));
|
||||
try
|
||||
{
|
||||
if (Editor is { } old)
|
||||
{
|
||||
Editor = null;
|
||||
await old.DisposeAsync();
|
||||
}
|
||||
_openId = sequenceId;
|
||||
if (services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
|
||||
var processing = services.Processing?.Options;
|
||||
var source = new LocalSequenceSource(db, sequenceId, processing?.Archive.Decoder ?? DecoderFactory.CreateClient(null), services.Engine,
|
||||
processing?.Archive);
|
||||
var content = await source.LoadAsync(CancellationToken.None);
|
||||
var encoders = processing?.Encoders ?? [];
|
||||
var session = new EditorSession(source, content, [.. encoders.SelectMany(e => e.Capabilities)]);
|
||||
var editor = new EditorViewModel(Shell, session, encoders, processing?.Host ?? EncoderHost.Client);
|
||||
Editor = editor;
|
||||
await editor.AttachJobsAsync();
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// Whatever failed (index, decoder set-up, advisor, the job list), the section stays usable: an editor that
|
||||
// opened stays open, otherwise the next Open tries again.
|
||||
if (Editor is null) _openId = null;
|
||||
Log.Warning("editor", $"Sequence {sequenceId} could not be opened", ex);
|
||||
Shell.ReportError(ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
IsLoading = false;
|
||||
OnPropertyChanged(nameof(IsEmpty));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,9 +48,10 @@
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<!-- Job bar (DESIGN §4): current job, progress, time left, pause; "Ready" when idle. -->
|
||||
<!-- Job bar (DESIGN §4): current job, progress, time left, pause; "Ready" when idle, hidden when idle in the editor. -->
|
||||
<ui:JobBar Text="{Binding JobText}" Progress="{Binding JobProgress}" IsActive="{Binding IsJobActive}" IsIndeterminate="{Binding IsJobIndeterminate}"
|
||||
StopCommand="{Binding StopJobCommand}" StopToolTip="{l:Loc Tooltips.Shell.PauseJob}" ActionGlyph="{StaticResource Icon.Pause}" />
|
||||
StopCommand="{Binding StopJobCommand}" StopToolTip="{l:Loc Tooltips.Shell.PauseJob}" ActionGlyph="{StaticResource Icon.Pause}"
|
||||
Visibility="{Binding IsJobBarVisible, Converter={StaticResource BoolToVisibility}}" />
|
||||
|
||||
<ContentControl Grid.Row="1" Content="{Binding Current}" Focusable="False" />
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Threading;
|
||||
using Titano.App.DesignTime;
|
||||
using Titano.App.Editor;
|
||||
using Titano.App.Server;
|
||||
using Titano.App.Settings;
|
||||
using Titano.Core.Diagnostics;
|
||||
@@ -118,6 +119,8 @@ public static class ScreenCapture
|
||||
"server-conflict-confirm", theme);
|
||||
SelectSyncFilter(shell, SyncFilter.All);
|
||||
}
|
||||
|
||||
written += await CaptureEditorAsync(window, shell, sample, directory);
|
||||
Log.Info("capture", $"{written} screenshot(s) written to {Path.GetFullPath(directory)}");
|
||||
if (written == 0) Environment.ExitCode = 1;
|
||||
}
|
||||
@@ -154,6 +157,67 @@ public static class ScreenCapture
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sequence editor on the synthetic sunset: every section in both themes (<c>sequence-<tab>-<theme>.png</c>,
|
||||
/// the Camera tab with a keyframe selected, the Export tab as Export.html with the crop mask and no compare), then
|
||||
/// the preview overlays, the waveform, the "what changed" toast of Optimise all and the busy state.
|
||||
/// </summary>
|
||||
private static async Task<int> CaptureEditorAsync(MainWindow window, ShellViewModel shell, SampleData sample, string directory)
|
||||
{
|
||||
var written = 0;
|
||||
var id = await sample.FillEditorAsync();
|
||||
shell.OpenSequence(id);
|
||||
await shell.Sequence.OpenAsync(id);
|
||||
if (shell.Sequence.Editor is not { } editor)
|
||||
{
|
||||
Log.Warning("capture", "The editor sample did not open");
|
||||
return 0;
|
||||
}
|
||||
foreach (var camera in editor.Tabs.OfType<CameraTab>()) camera.SelectedKey = 1;
|
||||
foreach (var theme in Themes)
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
foreach (var tab in editor.Tabs)
|
||||
{
|
||||
editor.SelectedTab = tab;
|
||||
editor.IsCompare = tab is not ExportTab;
|
||||
editor.CurrentIndex = tab is ExportTab ? 40 : 45;
|
||||
written += await SaveEditorAsync(window, editor, directory, "sequence-" + tab.Key.ToLowerInvariant(), theme);
|
||||
}
|
||||
|
||||
editor.SelectedTab = editor.Exposure;
|
||||
editor.IsCompare = true;
|
||||
editor.ShowVectors = editor.ShowRegions = true;
|
||||
written += await SaveEditorAsync(window, editor, directory, "sequence-exposure-overlays", theme);
|
||||
editor.ShowVectors = editor.ShowRegions = false;
|
||||
editor.Exposure.ChartMode = ExposureChart.Waveform;
|
||||
written += await SaveEditorAsync(window, editor, directory, "sequence-exposure-waveform", theme);
|
||||
editor.Exposure.ChartMode = ExposureChart.Luminance;
|
||||
|
||||
editor.OptimiseAllCommand.Execute(null);
|
||||
written += await SaveEditorAsync(window, editor, directory, "sequence-optimise", theme);
|
||||
editor.Session.Undo();
|
||||
foreach (var toast in window.Toasts.Toasts.ToList()) window.Toasts.Dismiss(toast);
|
||||
}
|
||||
|
||||
// Last, as it stays: an analysis of the sequence running (settings disabled, viewing tools live).
|
||||
await sample.MarkAnalysingAsync(id);
|
||||
await editor.AttachJobsAsync();
|
||||
foreach (var theme in Themes)
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
written += await SaveEditorAsync(window, editor, directory, "sequence-busy", theme);
|
||||
}
|
||||
return written;
|
||||
}
|
||||
|
||||
private static async Task<int> SaveEditorAsync(Window window, EditorViewModel editor, string directory, string screen, AppTheme theme)
|
||||
{
|
||||
await Settle(window);
|
||||
if (!await editor.WhenIdleAsync(TimeSpan.FromSeconds(30))) Log.Warning("capture", $"{screen} was still busy");
|
||||
return await SaveAsync(window, directory, screen, theme);
|
||||
}
|
||||
|
||||
private static async Task<int> SaveAsync(Window window, string directory, string screen, AppTheme theme, ShellViewModel? waitForThumbnails = null)
|
||||
{
|
||||
await Settle(window);
|
||||
|
||||
@@ -45,6 +45,7 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
BottomSections = [Settings, About];
|
||||
_current = Library;
|
||||
Library.IsSelected = true;
|
||||
Library.PropertyChanged += OnCurrentChanged;
|
||||
|
||||
NavigateCommand = new RelayCommand(p =>
|
||||
{
|
||||
@@ -95,7 +96,12 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
get => _current;
|
||||
private set
|
||||
{
|
||||
if (Set(ref _current, value)) OnPropertyChanged(nameof(WindowTitle));
|
||||
var previous = _current;
|
||||
if (!Set(ref _current, value)) return;
|
||||
previous.PropertyChanged -= OnCurrentChanged;
|
||||
value.PropertyChanged += OnCurrentChanged;
|
||||
OnPropertyChanged(nameof(WindowTitle));
|
||||
OnPropertyChanged(nameof(IsJobBarVisible));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,7 +163,17 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
: _queuedCount > 0 ? Loc.L("Shell.JobBar.Ready", _queuedCount) : Loc.L("Shell.JobBar.Idle");
|
||||
|
||||
public double JobProgress { get => _jobProgress; private set => Set(ref _jobProgress, value); }
|
||||
public bool IsJobActive { get => _jobActive; private set => Set(ref _jobActive, value); }
|
||||
public bool IsJobActive
|
||||
{
|
||||
get => _jobActive;
|
||||
private set
|
||||
{
|
||||
if (Set(ref _jobActive, value)) OnPropertyChanged(nameof(IsJobBarVisible));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The job bar shows "Ready" when idle, except in the editor where it gives its 40 px to the preview (DESIGN §4).</summary>
|
||||
public bool IsJobBarVisible => _jobActive || _current != Sequence;
|
||||
public bool IsJobIndeterminate { get => _jobIndeterminate; private set => Set(ref _jobIndeterminate, value); }
|
||||
|
||||
/// <summary>Pauses the job the bar shows.</summary>
|
||||
@@ -217,6 +233,12 @@ public sealed class ShellViewModel : LocalizedViewModel
|
||||
|
||||
public void ShowToast(Toast toast) => PendingToasts.Add(toast);
|
||||
|
||||
/// <summary>The section on screen renamed itself (the editor opened a sequence): the window title follows.</summary>
|
||||
private void OnCurrentChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName is nameof(SectionViewModel.Title) or "" or null) OnPropertyChanged(nameof(WindowTitle));
|
||||
}
|
||||
|
||||
/// <summary>A one-line notice with one action (job done, update available).</summary>
|
||||
public void Notify(string title, string? message = null, string? actionText = null, string? actionToolTip = null, Action? action = null) =>
|
||||
ShowToast(new Toast
|
||||
|
||||
@@ -159,8 +159,8 @@
|
||||
<Border Background="{TemplateBinding Background}" CornerRadius="{StaticResource Radius.Card}">
|
||||
<Grid>
|
||||
<v:PreviewSurface x:Name="PART_Surface" CornerRadius="8" />
|
||||
<ContentPresenter Content="{TemplateBinding ToolsContent}" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="12" />
|
||||
<Grid x:Name="Info" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="12" IsHitTestVisible="False">
|
||||
<ContentPresenter x:Name="PART_Tools" Content="{TemplateBinding ToolsContent}" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="12" />
|
||||
<Grid x:Name="PART_Info" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="12" IsHitTestVisible="False">
|
||||
<Border Background="{DynamicResource Brush.Chrome}" Opacity="0.85" CornerRadius="{StaticResource Radius.Control}" />
|
||||
<TextBlock Text="{TemplateBinding InfoText}" Margin="10,6" Typography.NumeralAlignment="Tabular" TextTrimming="CharacterEllipsis" />
|
||||
</Grid>
|
||||
@@ -168,10 +168,10 @@
|
||||
</Border>
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="InfoText" Value="{x:Null}">
|
||||
<Setter TargetName="Info" Property="Visibility" Value="Collapsed" />
|
||||
<Setter TargetName="PART_Info" Property="Visibility" Value="Collapsed" />
|
||||
</Trigger>
|
||||
<Trigger Property="InfoText" Value="">
|
||||
<Setter TargetName="Info" Property="Visibility" Value="Collapsed" />
|
||||
<Setter TargetName="PART_Info" Property="Visibility" Value="Collapsed" />
|
||||
</Trigger>
|
||||
</ControlTemplate.Triggers>
|
||||
</ControlTemplate>
|
||||
|
||||
@@ -42,9 +42,13 @@ public readonly record struct MotionVector(float X, float Y, float Dx, float Dy)
|
||||
/// Fit and 1:1; Ctrl+0 fits, Ctrl+1 shows 1:1.
|
||||
/// </summary>
|
||||
[TemplatePart(Name = PartSurface, Type = typeof(FrameworkElement))]
|
||||
[TemplatePart(Name = PartTools, Type = typeof(FrameworkElement))]
|
||||
[TemplatePart(Name = PartInfo, Type = typeof(FrameworkElement))]
|
||||
public class PreviewViewport : Control
|
||||
{
|
||||
public const string PartSurface = "PART_Surface";
|
||||
public const string PartTools = "PART_Tools";
|
||||
public const string PartInfo = "PART_Info";
|
||||
|
||||
public static readonly RoutedCommand FitCommand = new(nameof(FitCommand), typeof(PreviewViewport), [new KeyGesture(Key.D0, ModifierKeys.Control)]);
|
||||
public static readonly RoutedCommand ActualSizeCommand = new(nameof(ActualSizeCommand), typeof(PreviewViewport), [new KeyGesture(Key.D1, ModifierKeys.Control)]);
|
||||
@@ -106,6 +110,9 @@ public class PreviewViewport : Control
|
||||
private const double DividerGrip = 6;
|
||||
|
||||
private PreviewSurface? _surface;
|
||||
private FrameworkElement? _tools;
|
||||
private FrameworkElement? _info;
|
||||
private Thickness _infoMargin;
|
||||
private ViewTransform _view = new(1, 0, 0);
|
||||
private Size _imageSize = Size.Empty;
|
||||
private bool _syncingZoom;
|
||||
@@ -192,6 +199,9 @@ public class PreviewViewport : Control
|
||||
{
|
||||
if (_surface is not null) _surface.SizeChanged -= OnSurfaceSizeChanged;
|
||||
base.OnApplyTemplate();
|
||||
_tools = GetTemplateChild(PartTools) as FrameworkElement;
|
||||
_info = GetTemplateChild(PartInfo) as FrameworkElement;
|
||||
if (_info is not null) _infoMargin = _info.Margin;
|
||||
_surface = GetTemplateChild(PartSurface) as PreviewSurface;
|
||||
if (_surface is null) return;
|
||||
_surface.Owner = this;
|
||||
@@ -200,6 +210,19 @@ public class PreviewViewport : Control
|
||||
ApplyZoomMode();
|
||||
}
|
||||
|
||||
/// <summary>The shot data pill sits beside the tools at the bottom, and just above them when both do not fit in one row.</summary>
|
||||
protected override Size ArrangeOverride(Size arrangeBounds)
|
||||
{
|
||||
var size = base.ArrangeOverride(arrangeBounds);
|
||||
if (_tools is not null && _info is not null)
|
||||
{
|
||||
var lifted = _tools.DesiredSize.Width + _info.DesiredSize.Width > arrangeBounds.Width;
|
||||
var margin = lifted ? _infoMargin with { Bottom = _tools.DesiredSize.Height - _tools.Margin.Top + 6 } : _infoMargin;
|
||||
if (_info.Margin != margin) _info.Margin = margin;
|
||||
}
|
||||
return size;
|
||||
}
|
||||
|
||||
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
|
||||
{
|
||||
base.OnMouseLeftButtonDown(e);
|
||||
@@ -285,6 +308,9 @@ public class PreviewViewport : Control
|
||||
var viewport = (PreviewViewport)d;
|
||||
var size = PixelSize(viewport.Source);
|
||||
var resized = size != viewport._imageSize;
|
||||
// The same picture at another resolution (a 1:1 render replacing the fitted one) keeps what is on screen.
|
||||
if (resized && !size.IsEmpty && !viewport._imageSize.IsEmpty && viewport._view.Scale > 0)
|
||||
viewport._view = viewport._view with { Scale = viewport._view.Scale * viewport._imageSize.Width / size.Width };
|
||||
viewport._imageSize = size;
|
||||
viewport._surface?.SetImages(viewport.Source, viewport.OriginalSource, size);
|
||||
// Same-size frames (scrubbing) keep zoom and pan; a new size refits or re-clamps.
|
||||
|
||||
Reference in new issue
Block a user