using System.Globalization; using System.IO; using System.Text.Json; using Chronos.App.Jobs; using Chronos.Core.Advice; using Chronos.Core.Analysis; using Chronos.Core.Analysis.Deep; using Chronos.Core.Imaging.Geometry; using Chronos.Core.Localization; using Chronos.Core.Model; using Chronos.Core.Project; namespace Chronos.App.Editor; /// /// Where a step of the Edit path stands (owner review 1, R7). Each status has its own badge glyph, so colour never /// carries it alone. A status guides: it never keeps the user out of a step. /// public enum StepStatus { /// Not done yet: the step's number in a ring. Todo, /// Nothing is missing: ✓. Done, /// Something waits for the user: ▲. Attention, /// The step's job runs, waits or is paused: ◐. Running, /// The step needs the deep analysis first: ○. Waiting, } /// A step's status, its text (three words at most) and, when there is more to say, a sentence for its tooltip. public sealed record StepState(StepStatus Status, string Text, string? Detail = null); /// The step a sequence showed and the steps visited, which the Edit section keeps for the rest of the run. /// The deep analysis the steps were seen with (): another one since resets the visited marks. public sealed record StepMemory(string Step, IReadOnlyCollection Visited, string? Analysis = null); /// What the statuses of the steps are worked out from. /// The sequence's deep analysis that runs, else the paused one, else the queued one. /// The same for its renders. /// Why the export cannot be rendered now, once its plan is known; null otherwise. /// A render was made from the current settings, or the newest says nothing about its settings. public sealed record PathFacts( SequenceContent Content, AdvisorResult Advice, ProjectSettings Project, Job? Analysis, Job? Render, string? RenderBlocked, bool RenderMatches); /// /// The Edit section's guided path (owner review 1, R7): each editor tab is one step, from the deep analysis to the /// export. This class says where each step stands, which step deals with each finding of the analyses, where the /// editor opens and whether the settings of a render are the current ones. /// public static class EditPath { public const string Analysis = "Analysis"; public const string Frames = "Frames"; public const string Exposure = "Exposure"; public const string Motion = "Motion"; public const string Camera = "Camera"; public const string Time = "Time"; public const string Stack = "Stack"; public const string Export = "Export"; /// The step that deals with each finding of the light and the deep analysis. public static IReadOnlyDictionary FindingSteps { get; } = new Dictionary(StringComparer.Ordinal) { [FindingKeys.NoTimestamps] = Time, [FindingKeys.Gaps] = Time, [FindingKeys.Sessions] = Time, [FindingKeys.IrregularInterval] = Time, [FindingKeys.DuplicateTimestamps] = Time, [FindingKeys.NonMonotonicTimestamps] = Time, [FindingKeys.ClockJumps] = Time, [FindingKeys.TimeZoneEstimated] = Time, [FindingKeys.ExposureSteps] = Exposure, [FindingKeys.ExposureStep] = Exposure, [FindingKeys.MissingExposure] = Exposure, [FindingKeys.DayNightTransition] = Exposure, [DeepFindingKeys.Flicker] = Exposure, [DeepFindingKeys.WhiteBalanceJitter] = Exposure, [DeepFindingKeys.StepsNotReceived] = Exposure, [FindingKeys.CameraChanged] = Frames, [FindingKeys.LensChanged] = Frames, [DeepFindingKeys.UnreadableFrames] = Frames, [DeepFindingKeys.BlackFrames] = Frames, [DeepFindingKeys.WhiteFrames] = Frames, [DeepFindingKeys.DuplicateFrames] = Frames, [DeepFindingKeys.SceneChanges] = Frames, // Single frames of another size or orientation: Frames excludes them (no Camera setting acts on single frames). [FindingKeys.MixedResolution] = Frames, [FindingKeys.MixedOrientation] = Frames, [DeepFindingKeys.Shake] = Motion, [DeepFindingKeys.Panning] = Motion, [DeepFindingKeys.StarField] = Stack, [DeepFindingKeys.Clouds] = Stack, [FindingKeys.PreviewOnly] = Export, }; /// The step that deals with ; null for a finding no step names. public static string? StepOf(string findingKey) => FindingSteps.GetValueOrDefault(findingKey); /// /// The step the editor opens on: the one last shown for this sequence in this run; else Analysis while the sequence /// has no current deep analysis or one waits, runs or is paused (, so the user sees it /// first); else Frames. /// public static string Start(string? remembered, SequenceContent content, Job? analysis = null) { ArgumentNullException.ThrowIfNull(content); return remembered ?? (content.Deep is null || analysis is not null ? Analysis : Frames); } /// /// Tells one deep analysis of the sequence from another (or from none), so that the step memory of a sequence closed /// while an analysis ran knows the steps changed meanwhile; null without a deep analysis. /// public static string? AnalysisStamp(SequenceContent content) { ArgumentNullException.ThrowIfNull(content); return content.Deep is not { } d ? null : string.Create(CultureInfo.InvariantCulture, $"{d.FrameCount}|{d.Findings.Count}|{d.Flicker.AmplitudeEv:R}|{d.Shake.RmsPx:R}|{d.Exposure.ReceivedSteps}|{d.Issues.Excludable().Length}|{d.HeroIndex}"); } /// Where stands. public static StepState Of(string step, PathFacts facts) { ArgumentNullException.ThrowIfNull(facts); return step switch { Analysis => AnalysisState(facts), Frames => FramesState(facts), Exposure => SettingsState(facts, AdvisorSection.Exposure), Motion => SettingsState(facts, AdvisorSection.Motion), Camera => SettingsState(facts, AdvisorSection.Camera), Time => SettingsState(facts, AdvisorSection.Timing), Stack => StackState(facts.Project), Export => ExportState(facts), _ => throw new ArgumentOutOfRangeException(nameof(step), step, null), }; } /// /// The settings of that make its video, for comparing them with a render's: without the /// hero (the Library's picture), the frames still to place, the batch, the output folder, the output's name and the /// server copy, none of which changes the video. /// public static string Signature(ProjectSettings project) { ArgumentNullException.ThrowIfNull(project); return (project with { HeroFrame = null, PendingFrames = null, Export = project.Export with { Batch = [], Folder = null, NameTemplate = string.Empty, SyncToServer = false }, }).ToJson(); } private static StepState AnalysisState(PathFacts facts) { if (facts.Analysis is { } job) return new StepState(StepStatus.Running, JobLine(job)); var content = facts.Content; if (content.Deep is null) { if ((content.Sequence.Status & SequenceStatus.AnalyzedDeep) == 0) return new StepState(StepStatus.Todo, Loc.L("Editor.Chart.NotAnalysed")); // Analysed, but the saved analysis describes frames the sequence no longer has, or cannot be read now (the // archive offline, the file moved or damaged, a server that sends none). return content.DeepOfOtherFrames ? new StepState(StepStatus.Attention, Loc.L("Editor.Step.FramesChanged"), Loc.L("Tooltips.Editor.Step.FramesChanged")) : new StepState(StepStatus.Attention, Loc.L("Editor.Step.AnalysisUnavailable"), Loc.L("Tooltips.Editor.Step.AnalysisUnavailable")); } var warnings = facts.Advice.Findings.Count(f => f.Severity >= FindingSeverity.Warning); var text = warnings == 0 ? Loc.L("Editor.Step.Analysed") : string.Join(Loc.Separator, Loc.L("Editor.Step.Analysed"), Loc.Plural("Editor.Summary.Warnings", warnings)); return new StepState(StepStatus.Done, text); } private static StepState FramesState(PathFacts facts) { if (facts.Content.Deep is not { } deep) return Waiting(); // Flagged frames the video still shows: neither excluded nor skipped by the render anyway. var flagged = deep.Issues.Excludable().Except(facts.Project.ExcludedFrames).Except(facts.Content.NotRenderable()).Count(); return flagged > 0 ? new StepState(StepStatus.Attention, Loc.Plural("Editor.Step.Flagged", flagged), Loc.Plural("Tooltips.Editor.Step.Flagged", flagged)) : new StepState(StepStatus.Done, Loc.L("Editor.Step.Excluded", facts.Project.ExcludedFrames.Count)); } /// /// A settings step: waiting while an Auto setting of its section needs the deep analysis, needing attention while one /// lacks other data (no timestamps, no exposure data, an unknown source size), which taking the value over by hand /// settles; otherwise Auto, or Edited when a setting or a value of the section was set by hand. /// private static StepState SettingsState(PathFacts facts, AdvisorSection section) { var deep = facts.Content.Deep; var missing = facts.Advice.In(section).Where(r => r.IsMissingData && Counts(r, facts.Project, deep)).ToList(); if (missing.Any(r => r.ReasonKey == AdvisorKeys.MissingDeep)) return Waiting(); if (missing.FirstOrDefault() is { } reason) return new StepState(StepStatus.Attention, Loc.L("Editor.Step.MissingData"), Advisor.Explain(reason)); var auto = EditorSettings.IsSectionAuto(facts.Project, section) && !HasHandValues(facts.Project, section); return new StepState(StepStatus.Done, Loc.L(auto ? "Common.Auto" : "Editor.Step.Edited")); } /// /// Advice without a value asks something of the user only for an Auto setting that applies now: a setting shown n/a /// (its switch is off) cannot be taken over by hand, and once a deep analysis exists, a value it could not measure /// (no usable region mask) stays at the engine's fallback rather than waiting for an analysis that has run. /// private static bool Counts(Recommendation recommendation, ProjectSettings project, DeepAnalysisReport? deep) { if (recommendation.ReasonKey == AdvisorKeys.MissingDeep && deep is not null) return false; return EditorSettings.All.FirstOrDefault(s => s.Id == recommendation.Parameter) is not { } setting || (setting.IsAuto(project) && EditorSettings.Applies(setting, project, deep)); } /// /// Values of the section set by hand that are not Auto settings: crop, offsets, orientation and camera moves; fit to a /// duration; the exposure offset and the look. /// private static bool HasHandValues(ProjectSettings project, AdvisorSection section) => section switch { AdvisorSection.Camera => !CropFrame.IsWhole(project.Camera.Crop) || project.Camera.OffsetX != 0 || project.Camera.OffsetY != 0 || project.Camera.Keyframes.Count > 0 || project.Camera.IsOriented, AdvisorSection.Timing => project.Timing.FitToSeconds is > 0, AdvisorSection.Exposure => project.Exposure.ExposureOffsetEv != 0 || project.Look is not null, _ => false, }; private static StepState StackState(ProjectSettings project) => project.Stack.Mode switch { StackSetting.None => new StepState(StepStatus.Todo, Loc.L("Editor.Step.Optional")), StackSetting.Median => new StepState(StepStatus.Done, Loc.L("Editor.Stack.Median")), StackSetting.Mean => new StepState(StepStatus.Done, Loc.L("Editor.Stack.Mean")), _ => new StepState(StepStatus.Done, Loc.L("Editor.Stack.StarTrails")), }; private static StepState ExportState(PathFacts facts) { if (facts.Render is { } job) return new StepState(StepStatus.Running, JobLine(job)); if (facts.RenderBlocked is { } reason) return new StepState(StepStatus.Attention, Loc.L("Editor.Step.Blocked"), reason); if (facts.Content.Renders.Count == 0) return new StepState(StepStatus.Todo, Loc.L("Editor.Step.NotRendered")); return facts.RenderMatches ? new StepState(StepStatus.Done, Loc.L("Editor.Step.Rendered")) : new StepState(StepStatus.Attention, Loc.L("Editor.Step.Outdated"), Loc.L("Tooltips.Editor.Step.Outdated")); } private static StepState Waiting() => new(StepStatus.Waiting, Loc.L("Editor.Step.Waiting"), Loc.L("Tooltips.Editor.NotApplicable.NeedsAnalysis")); /// "Deep analysis · running". private static string JobLine(Job job) => string.Join(Loc.Separator, JobText.Kind(job.Kind), Loc.L("Jobs.State." + job.State)); } /// /// The settings the sequence's renders were made from, read once when the sequence loads, so each change of the project /// only works out its own . /// public sealed class RenderedSettings { private readonly HashSet _signatures = new(StringComparer.Ordinal); /// Newest first, as . public RenderedSettings(IReadOnlyList renders) { ArgumentNullException.ThrowIfNull(renders); foreach (var render in renders) { if (render.SettingsJson is not { Length: > 0 } json) continue; try { _signatures.Add(EditPath.Signature(ProjectSettings.FromJson(json))); } catch (Exception ex) when (ex is JsonException or InvalidDataException) { // Settings no longer readable (or written by a newer Chronos) say nothing either way, like none. } } // A render that keeps no settings (a server's, or one fetched from it) cannot be compared: it counts as current. NewestUnknown = renders.Count > 0 && (renders[0].SettingsJson is not { Length: > 0 } || _signatures.Count == 0); } /// The newest render says nothing comparable about its settings. public bool NewestUnknown { get; } /// A render was made from settings that make the same video as 's, or the newest cannot tell. public bool Matches(ProjectSettings project) => NewestUnknown || _signatures.Contains(EditPath.Signature(project)); }