feat(app): editor session, project history, local source, preview renderer and export planner

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 17:00:26 +00:00
1 parent 7d95536096
commit e6d1317aab
19 files changed
+2146

No files matched your search

+172
View File
@@ -0,0 +1,172 @@
using Titano.Core.Advice;
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 += ex => SaveFailed?.Invoke(ex);
(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; the next change tries again.</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>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);
}
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>
/// 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.</summary>
public Task FlushAsync() => _saver.FlushAsync();
public async ValueTask DisposeAsync()
{
History.Changed -= OnProjectChanged;
await _saver.FlushAsync();
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 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));
}
}
+131
View File
@@ -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));
}
+110
View File
@@ -0,0 +1,110 @@
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>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.");
}
}
+69
View File
@@ -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;
}
}
}
+50
View File
@@ -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,151 @@
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
{
return decoder.Decode(new DecodeRequest(file, maxLongEdge, purpose), 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);
// A conflict means the settings moved in the index meanwhile (server API): merge again on top of them.
if (result.Outcome != SequenceEditOutcome.Conflict || attempt == SaveAttempts) return merged;
}
}, 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"));
}
+318
View File
@@ -0,0 +1,318 @@
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.</param>
/// <param name="Vectors">Also measure the motion field to the next frame.</param>
public sealed record PreviewRequest(int Index, ProjectSettings Project, int LongEdge, PreviewFraming Framing, bool Vectors = 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; } = [];
public void Dispose()
{
Corrected.Dispose();
Original.Dispose();
}
}
/// <summary>
/// The corrected-frame preview through the render pipeline at preview size (BRIEF §12.3). Corrections come from
/// <see cref="RenderPreparation"/> exactly as a render prepares them (the deep analysis' luminance reused, the rest
/// measured on small decodes), cached per exposure/stabilisation settings; each frame then goes through the render's
/// exposure stage, its single geometry warp and the highlight knee. The render pipeline has no single-frame entry
/// point, so the per-frame steps of <c>RenderRun</c> are followed here; stacking and motion blur need neighbouring
/// frames and are left to the render.
/// </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;
private const int VectorSpacing = 24;
private readonly CachedFrames _frames = new(content, source);
private readonly Lock _gate = new();
private (string Key, RenderCorrections Corrections)? _latest;
/// <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), so nothing is shared between calls but the cache.
/// </summary>
public async Task<RenderCorrections> PrepareAsync(ProjectSettings project, CancellationToken cancellationToken)
{
if (Cached(project) is { } cached) return cached;
var key = Key(project);
var corrections = await RenderPreparation.PrepareAsync(Input(project), new RenderOptions { AnalysisLongEdge = AnalysisLongEdge }, null, cancellationToken)
.ConfigureAwait(false);
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, geometry, edge, corrected, 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,
};
}
catch
{
corrected.Dispose();
original.Dispose();
throw;
}
}
/// <summary>Cache key: the settings <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();
private RenderInput Input(ProjectSettings project) => 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 = content.Deep is { } deep && deep.FrameCount == content.Count
? new PrecomputedAnalysis { LogLuminance = [.. deep.Frames.LogLuminance.Select(v => v ?? double.NaN)] }
: null,
};
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 prepared the same way, sampled on a grid in picture pixels.</summary>
private async Task<IReadOnlyList<VectorSample>> VectorsAsync(PreviewRequest request, RenderCorrections? corrections, RenderGeometry geometry, int edge,
ImageBuffer current, CancellationToken cancellationToken)
{
var next = await PictureAsync(request.Index + 1, request, corrections, geometry, edge, cancellationToken).ConfigureAwait(false);
if (next is null) return [];
var (nextCorrected, nextOriginal, _) = next.Value;
nextOriginal.Dispose();
using (nextCorrected)
{
var scale = double.Min(1, (double)VectorLongEdge / int.Max(current.Width, current.Height));
var (w, h) = ((int)double.Max(8, current.Width * scale), (int)double.Max(8, current.Height * scale));
using var a = Resampler.Resize(current, w, h);
using var b = Resampler.Resize(nextCorrected, w, h);
using var engine = new OpticalFlowEngine(FlowQuality.Draft);
using var field = engine.Compute(a, b, cancellationToken);
var samples = new List<VectorSample>();
for (var y = VectorSpacing / 2.0; y < current.Height; y += VectorSpacing)
{
for (var x = VectorSpacing / 2.0; x < current.Width; x += VectorSpacing)
{
var (u, v) = field.Sample(x * w / current.Width, y * h / current.Height);
samples.Add(new VectorSample((float)x, (float)y, (float)(u * current.Width / w), (float)(v * current.Height / h)));
}
}
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 preparation reads it, with small decodes kept (within a memory budget) so changing a setting
/// does not decode the sequence again.
/// </summary>
private sealed class CachedFrames(SequenceContent content, ISequenceSource source) : IRenderFrameSource
{
private const long Budget = 64L << 20;
private readonly Lock _gate = new();
private readonly Dictionary<(int Index, int Edge), ImageBuffer> _cache = [];
private readonly Queue<(int Index, int Edge)> _order = new();
private long _bytes;
public int FrameCount => content.Count;
public int Width => content.SourceWidth;
public int Height => content.SourceHeight;
public async ValueTask<ImageBuffer> GetFrameAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
{
lock (_gate)
{
if (_cache.TryGetValue((index, maxLongEdge), out var hit)) return hit.Clone();
}
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(System.Globalization.CultureInfo.InvariantCulture), content.Frames[index].FileName]);
lock (_gate)
{
if (frame.ByteSize <= Budget && _cache.TryAdd((index, maxLongEdge), frame.Clone()))
{
_order.Enqueue((index, maxLongEdge));
_bytes += frame.ByteSize;
while (_bytes > Budget && _order.TryDequeue(out var oldest) && _cache.Remove(oldest, out var dropped))
{
_bytes -= dropped.ByteSize;
dropped.Dispose();
}
}
}
return frame;
}
}
}
+76
View File
@@ -0,0 +1,76 @@
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; any
/// other edit, undo or redo 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 Stack<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;
}
public bool Undo()
{
if (_undo.Last is not { } previous) return false;
_undo.RemoveLast();
_redo.Push(Current);
return Move(previous.Value);
}
public bool Redo()
{
if (!_redo.TryPop(out var next)) return false;
_undo.AddLast(Current);
return Move(next);
}
/// <summary>Adopts a project changed outside the editor (analysis advice, a merge on save) without an undo step.</summary>
public void Replace(ProjectSettings current)
{
ArgumentNullException.ThrowIfNull(current);
if (ProjectMerge.SameValues(current, Current)) return;
_runKey = null;
Current = current;
Changed?.Invoke();
}
private bool Move(ProjectSettings target)
{
_runKey = null;
Current = target;
Changed?.Invoke();
return true;
}
}
+42
View File
@@ -0,0 +1,42 @@
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);
var b = JsonNode.Parse(basis.ToJson());
var o = JsonNode.Parse(ours.ToJson());
var t = JsonNode.Parse(theirs.ToJson());
return ProjectSettings.FromJson(Merge(b, o, t)?.ToJsonString() ?? "{}");
}
/// <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;
}
}
+89
View File
@@ -0,0 +1,89 @@
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). <see cref="FlushAsync"/> skips the wait and returns once
/// everything scheduled is stored. A failed write is reported and the next change tries again.
/// </summary>
public sealed class ProjectSaver(Func<ProjectSettings, Task> save, TimeSpan delay)
{
private readonly Lock _gate = new();
private ProjectSettings? _pending;
private bool _running;
private Task _loop = Task.CompletedTask;
private CancellationTokenSource _wait = new();
/// <summary>A write failed (raised on the context that scheduled the write).</summary>
public event Action<Exception>? Failed;
public bool HasPendingChanges
{
get
{
lock (_gate) return _running;
}
}
public void Schedule(ProjectSettings project)
{
ArgumentNullException.ThrowIfNull(project);
TaskCompletionSource start;
lock (_gate)
{
_pending = project;
if (_running) return;
_running = true;
if (!_wait.TryReset()) _wait = new CancellationTokenSource();
start = new TaskCompletionSource();
_loop = LoopAsync(start.Task, _wait.Token);
}
// 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>
public Task FlushAsync()
{
lock (_gate)
{
_wait.Cancel();
return _loop;
}
}
private async Task LoopAsync(Task started, CancellationToken wait)
{
await started;
try
{
await Task.Delay(delay, wait);
}
catch (OperationCanceledException)
{
}
while (true)
{
ProjectSettings next;
lock (_gate)
{
if (_pending is null)
{
_running = false;
return;
}
next = _pending;
_pending = null;
}
try
{
await save(next);
}
catch (Exception ex)
{
Failed?.Invoke(ex);
}
}
}
}