merge: integration branch claude/keen-knuth-uhxv8w (remote editor after review) into the Library workstream
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
81 files changed
+3827
-263
No files matched your search
@@ -46,22 +46,27 @@ public sealed class SampleData
|
||||
private TitanoDatabase? _db;
|
||||
private Guid _sunrise;
|
||||
private Guid _lakeComo;
|
||||
private Permissions _permissions = RolePermissions.Default(UserRole.Editor);
|
||||
|
||||
private SampleData(AppServices services) => _services = services;
|
||||
|
||||
/// <summary>The server-only sequence whose proxies <see cref="CacheProxiesAsync"/> keeps on this PC (Sunrise over Superga).</summary>
|
||||
public Guid ProxiedSequenceId => _sunrise;
|
||||
|
||||
/// <summary>Points the services at fakes (server, encoders, update check) for an empty first-run state.</summary>
|
||||
public static SampleData Configure(AppServices services)
|
||||
{
|
||||
if (!services.Environment.IsCapture) throw new InvalidOperationException("Sample data only runs in a capture environment.");
|
||||
var settings = services.Settings;
|
||||
var sample = new SampleData(services);
|
||||
services.Server.Dispose();
|
||||
services.Server = new ServerSession(settings, services.SaveSettings, new SampleServerApiFactory(), new PlainTokenProtector());
|
||||
services.Server = new ServerSession(settings, services.SaveSettings, new SampleServerApiFactory(sample), new PlainTokenProtector());
|
||||
services.Encoders = new SampleEncoders();
|
||||
services.CheckForUpdateAsync = _ => Task.FromResult<ReleaseInfo?>(null);
|
||||
services.Devices.Dispose();
|
||||
services.Devices = new SampleDeviceMonitor();
|
||||
var sample = new SampleData(services);
|
||||
services.Sync.RemoteFactory = (_, _, _) => sample._remote;
|
||||
services.Sync.EditorFactory = (_, _, _) => sample._remote;
|
||||
return sample;
|
||||
}
|
||||
|
||||
@@ -170,6 +175,44 @@ public sealed class SampleData
|
||||
for (var i = 0; i < 200 && await db.Jobs.GetAsync(job.Id) is { State: JobState.Queued or JobState.Running }; i++) await Task.Delay(50);
|
||||
}
|
||||
|
||||
/// <summary>A render of Sunrise over Superga running on the sample server, 43 % done (the remote editor's server job).</summary>
|
||||
public void RunServerRender() => _remote.Run(_sunrise, "render", 1_240, 2_880);
|
||||
|
||||
/// <summary>The sample server's jobs end (none waits or runs any more).</summary>
|
||||
public void EndServerJobs() => _remote.EndJobs();
|
||||
|
||||
/// <summary>
|
||||
/// The signed-in account keeps Read, Upload and Render but loses Edit (server sequences open read-only); the
|
||||
/// session is read again so the client sees it.
|
||||
/// </summary>
|
||||
public async Task RestrictAccountAsync()
|
||||
{
|
||||
_permissions = Permissions.Read | Permissions.Upload | Permissions.Render;
|
||||
await _services.Server.RestoreAsync();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The editor's sample as a sequence the sample server also has (so its Export "Sync" applies), with two copies of
|
||||
/// this PC's settings kept by "Save both" in its <c>.titano</c> folder.
|
||||
/// </summary>
|
||||
public async Task KeepEditorCopiesAsync(Guid sequenceId)
|
||||
{
|
||||
var db = _db ?? throw new InvalidOperationException("FillAsync first.");
|
||||
var sequence = await db.Sequences.GetAsync(sequenceId) ?? throw new InvalidOperationException("FillEditorAsync first.");
|
||||
var archive = await db.Archives.GetAsync(sequence.ArchiveId) ?? throw new InvalidOperationException("FillEditorAsync first.");
|
||||
var meta = new ArchivePaths(archive.RootPath).Sequence(sequence.Folder).MetaDirectory;
|
||||
Directory.CreateDirectory(meta);
|
||||
var project = sequence.SettingsJson is { } json ? ProjectSettings.FromJson(json) : new ProjectSettings();
|
||||
var copies = new (DateTime Saved, double OffsetEv)[] { (new DateTime(2026, 9, 30, 21, 14, 5), 0.3), (new DateTime(2026, 10, 2, 8, 41, 37), -0.2) };
|
||||
foreach (var (saved, offset) in copies)
|
||||
{
|
||||
var copy = project with { Exposure = project.Exposure with { ExposureOffsetEv = offset } };
|
||||
Titano.Core.IO.AtomicFile.WriteAllText(Path.Combine(meta, SyncService.SavedCopyName(saved)), copy.ToJson());
|
||||
}
|
||||
var remote = _remote.Add(SampleSyncRemote.Dto(sequence), sequence.SettingsJson, sequence.FrameCount);
|
||||
await _services.Sync.Service!.LinkAsync(ServerAddress, remote, sequence.Id);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The server's side: six sequences this PC also holds (two the same, one with settings changed on both sides, one
|
||||
/// with more originals on the server, one with more here, one with renders this PC lacks) and two only on the server
|
||||
@@ -600,15 +643,15 @@ public sealed class SampleData
|
||||
}
|
||||
|
||||
/// <summary>A server that always answers as "Studio NAS" with a self-signed certificate the sample trusts.</summary>
|
||||
private sealed class SampleServerApiFactory : IServerApiFactory
|
||||
private sealed class SampleServerApiFactory(SampleData sample) : IServerApiFactory
|
||||
{
|
||||
public IServerApi Create(Uri baseAddress, IReadOnlyCollection<string> trustedFingerprints) => new SampleServerApi(baseAddress, trustedFingerprints);
|
||||
public IServerApi Create(Uri baseAddress, IReadOnlyCollection<string> trustedFingerprints) => new SampleServerApi(sample, baseAddress, trustedFingerprints);
|
||||
}
|
||||
|
||||
private sealed class SampleServerApi(Uri baseAddress, IReadOnlyCollection<string> trusted) : IServerApi
|
||||
/// <summary>The sample account, an editor unless <see cref="RestrictAccountAsync"/> took the Edit right away.</summary>
|
||||
private sealed class SampleServerApi(SampleData sample, Uri baseAddress, IReadOnlyCollection<string> trusted) : IServerApi
|
||||
{
|
||||
private static readonly UserDto User = new(Guid.Empty, "alberto", "Alberto", "editor", (long)RolePermissions.Default(UserRole.Editor), 5_000_000_000_000,
|
||||
2_100_000_000_000, false, false,
|
||||
private UserDto User => new(Guid.Empty, "alberto", "Alberto", "editor", (long)sample._permissions, 5_000_000_000_000, 2_100_000_000_000, false, false,
|
||||
new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero), DateTimeOffset.UtcNow);
|
||||
|
||||
public Uri BaseAddress { get; } = baseAddress;
|
||||
@@ -639,13 +682,15 @@ public sealed class SampleData
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The sample server's sequences for the sync table: listings, manifests (frames hashed from their index, so
|
||||
/// unhashed sample frames match them by count; renders as many as the listing says), settings edits and proxies
|
||||
/// (generated JPEGs); uploads and originals are not part of the screenshots.
|
||||
/// The sample server's sequences for the sync table and the editor of a server sequence: listings, manifests
|
||||
/// (frames hashed from their index, so unhashed sample frames match them by count; renders as many as the listing
|
||||
/// says), settings edits, proxies (generated JPEGs) and jobs the editor posts (kept queued until cancelled, or run by
|
||||
/// <see cref="Run"/>); uploads, originals and analysis reports are not part of the screenshots.
|
||||
/// </summary>
|
||||
private sealed class SampleSyncRemote : ISyncRemote
|
||||
private sealed class SampleSyncRemote : ISyncRemote, IRemoteSequenceApi
|
||||
{
|
||||
private readonly Dictionary<Guid, (SequenceDto Dto, string? Settings, Guid[] Frames)> _sequences = [];
|
||||
private readonly Dictionary<Guid, JobDto> _jobs = [];
|
||||
|
||||
public string Server => ServerAddress;
|
||||
|
||||
@@ -698,9 +743,9 @@ public sealed class SampleData
|
||||
{
|
||||
lock (_sequences)
|
||||
{
|
||||
var (dto, _, frames) = _sequences[id];
|
||||
var (dto, settings, frames) = _sequences[id];
|
||||
var updated = dto with { SettingsVersion = dto.SettingsVersion + 1, UpdatedAt = DateTimeOffset.UtcNow };
|
||||
_sequences[id] = (updated, request.SettingsJson, frames);
|
||||
_sequences[id] = (updated, request.SettingsJson ?? settings, frames);
|
||||
return Task.FromResult(updated);
|
||||
}
|
||||
}
|
||||
@@ -729,6 +774,54 @@ public sealed class SampleData
|
||||
yield break;
|
||||
}
|
||||
|
||||
public Task<string?> GetAnalysisReportAsync(Guid id, CancellationToken cancellationToken) => Task.FromResult<string?>(null);
|
||||
|
||||
public Task<JobDto> CreateJobAsync(CreateJobRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
var job = new JobDto(Guid.CreateVersion7(), request.Kind, request.Target, null, "queued", "user", 0, 0, null, null, null, null, 0, null,
|
||||
DateTimeOffset.UtcNow, null, null);
|
||||
lock (_jobs) _jobs[job.Id] = job;
|
||||
return Task.FromResult(job);
|
||||
}
|
||||
|
||||
/// <summary>A job of <paramref name="kind"/> running for <paramref name="sequenceId"/>, <paramref name="done"/> of <paramref name="total"/> frames.</summary>
|
||||
public void Run(Guid sequenceId, string kind, long done, long total)
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
var job = new JobDto(Guid.CreateVersion7(), kind, [sequenceId], null, "running", "user", done, total, 11.3, (total - done) / 11.3, null, "studio-pc", 1,
|
||||
null, now.AddMinutes(-2), now.AddMinutes(-2), null);
|
||||
lock (_jobs) _jobs[job.Id] = job;
|
||||
}
|
||||
|
||||
public void EndJobs()
|
||||
{
|
||||
lock (_jobs) _jobs.Clear();
|
||||
}
|
||||
|
||||
public Task<JobDto> GetJobAsync(Guid id, CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_jobs) return Task.FromResult(_jobs[id]);
|
||||
}
|
||||
|
||||
public Task<IReadOnlyList<JobDto>> ListActiveJobsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
lock (_jobs) return Task.FromResult<IReadOnlyList<JobDto>>([.. _jobs.Values.Where(j => j.State is "queued" or "running" or "paused")]);
|
||||
}
|
||||
|
||||
public Task<JobDto> CancelJobAsync(Guid id, CancellationToken cancellationToken) =>
|
||||
Task.FromResult(Update(id, job => job with { State = "cancelled", Finished = DateTimeOffset.UtcNow }));
|
||||
|
||||
public Task<JobDto> RetryJobAsync(Guid id, CancellationToken cancellationToken) =>
|
||||
Task.FromResult(Update(id, job => job with { State = "queued", Error = null, Finished = null }));
|
||||
|
||||
public Task<JobDto> SetJobPriorityAsync(Guid id, string priority, CancellationToken cancellationToken) =>
|
||||
Task.FromResult(Update(id, job => job with { Priority = priority }));
|
||||
|
||||
private JobDto Update(Guid id, Func<JobDto, JobDto> change)
|
||||
{
|
||||
lock (_jobs) return _jobs[id] = change(_jobs[id]);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
}
|
||||
|
||||
@@ -45,8 +45,8 @@ public sealed class CameraTab : EditorTab
|
||||
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);
|
||||
AddKeyCommand = new RelayCommand(AddKey, () => !Editor.IsLocked && Keys.All(k => k.Frame != Editor.CurrentIndex));
|
||||
RemoveKeyCommand = new RelayCommand(RemoveKey, () => !Editor.IsLocked && SelectedKey >= 0);
|
||||
CommitCurveCommand = new RelayCommand(CommitCurve);
|
||||
Refresh();
|
||||
}
|
||||
@@ -103,13 +103,13 @@ public sealed class CameraTab : EditorTab
|
||||
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");
|
||||
public string AddKeyToolTip => Editor.LockedToolTip
|
||||
?? Loc.L(Keys.Any(k => k.Frame == Editor.CurrentIndex) ? "Tooltips.Editor.Camera.KeyExists" : "Tooltips.Editor.Camera.AddKey");
|
||||
|
||||
/// <summary>How to edit the keyframe curve, or why it waits.</summary>
|
||||
public string CurveToolTip => Loc.L(Editor.IsBusy ? "Tooltips.Editor.Busy" : "Tooltips.Editor.Camera.Curve");
|
||||
public string CurveToolTip => Editor.LockedToolTip ?? Loc.L("Tooltips.Editor.Camera.Curve");
|
||||
|
||||
public string RemoveKeyToolTip => Loc.L(Editor.IsBusy ? "Tooltips.Editor.Busy" : HasSelectedKey ? "Tooltips.Editor.Camera.RemoveKey" : "Tooltips.Editor.Camera.NoKey");
|
||||
public string RemoveKeyToolTip => Editor.LockedToolTip ?? Loc.L(HasSelectedKey ? "Tooltips.Editor.Camera.RemoveKey" : "Tooltips.Editor.Camera.NoKey");
|
||||
|
||||
/// <summary>Run by the curve editor after each finished edit.</summary>
|
||||
public ICommand CommitCurveCommand { get; }
|
||||
@@ -248,7 +248,7 @@ public sealed class TimeTab : EditorTab
|
||||
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");
|
||||
public string CurveToolTip => Editor.LockedToolTip ?? Loc.L("Tooltips.Editor.Time.Curve");
|
||||
|
||||
/// <summary>"3,600 frames → 2 min 30 s · 24 fps".</summary>
|
||||
public string? PlanText { get => _planText; private set => Set(ref _planText, value); }
|
||||
|
||||
@@ -228,8 +228,9 @@
|
||||
</ItemsControl.ItemsPanel>
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type e:PresetCard}">
|
||||
<!-- Disabled while a job runs or the project cannot change: the card's tooltip says why. -->
|
||||
<Button Style="{StaticResource Button.PresetCard}" Command="{Binding SelectCommand}" CommandParameter="{Binding}" ToolTip="{Binding ToolTip}"
|
||||
AutomationProperties.Name="{Binding Name}">
|
||||
ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{Binding Name}">
|
||||
<DockPanel>
|
||||
<!-- The chip moves under the name when both do not fit on one line. -->
|
||||
<WrapPanel DockPanel.Dock="Top">
|
||||
@@ -240,7 +241,7 @@
|
||||
</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" />
|
||||
ToolTip="{Binding BatchToolTip}" ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{l:Loc Editor.Export.InBatch}" Margin="6,0,0,0" />
|
||||
<TextBlock Text="{Binding Estimate}" FontSize="{StaticResource Size.Secondary}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"
|
||||
Typography.NumeralAlignment="Tabular" />
|
||||
</DockPanel>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<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:shell="clr-namespace:Titano.App.Shell"
|
||||
xmlns:e="clr-namespace:Titano.App.Editor">
|
||||
@@ -149,7 +150,7 @@
|
||||
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">
|
||||
<StackPanel IsEnabled="{Binding Editor.IsEditable}" ToolTip="{Binding Editor.LockedToolTip}" ToolTipService.ShowOnDisabled="True">
|
||||
<ItemsControl ItemsSource="{Binding Rows}" Focusable="False" />
|
||||
<ContentPresenter />
|
||||
</StackPanel>
|
||||
@@ -286,15 +287,21 @@
|
||||
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" />
|
||||
ToolTip="{l:Loc Tooltips.Editor.Export.History}" Margin="6,0,0,0" Visibility="{Binding CanOpenHistory, Converter={StaticResource BoolToVisibility}}" />
|
||||
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Editor.Export.Reveal}" Command="{Binding RevealLastCommand}"
|
||||
ToolTip="{l:Loc Tooltips.Editor.Render.Reveal}" Margin="6,0,0,0" Visibility="{Binding HasHistory, Converter={StaticResource BoolToVisibility}}" />
|
||||
ToolTip="{l:Loc Tooltips.Editor.Render.Reveal}" Margin="6,0,0,0" Visibility="{Binding CanReveal, Converter={StaticResource BoolToVisibility}}" />
|
||||
<TextBlock Text="{Binding HistoryText}" Style="{StaticResource Text.Faint}" FontSize="{StaticResource Size.Chip}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"
|
||||
ToolTip="{Binding HistoryText}" />
|
||||
</DockPanel>
|
||||
<!-- This PC's settings kept by "Save both" (sync conflicts): the newest, or another from the menu, becomes the project as one undo step. -->
|
||||
<v:SplitButton Margin="0,8,0,0" HorizontalAlignment="Left" Content="{Binding RestoreText}" Command="{Binding RestoreCommand}"
|
||||
ItemsSource="{Binding SavedCopies}" DisplayMemberPath="Label" SelectedItem="{Binding SelectedCopy}" ToolTip="{Binding RestoreToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True"
|
||||
DropDownToolTip="{l:Loc Tooltips.Editor.Export.RestoreChoice}" AutomationProperties.Name="{l:Loc Editor.Export.RestoreName}"
|
||||
Visibility="{Binding HasSavedCopies, Converter={StaticResource BoolToVisibility}}" />
|
||||
</StackPanel>
|
||||
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
|
||||
<StackPanel IsEnabled="{Binding Editor.IsEditable}" ToolTip="{Binding Editor.BusyToolTip}" ToolTipService.ShowOnDisabled="True">
|
||||
<StackPanel IsEnabled="{Binding Editor.IsEditable}" ToolTip="{Binding Editor.LockedToolTip}" ToolTipService.ShowOnDisabled="True">
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="{StaticResource Editor.Grid.Label}" />
|
||||
@@ -310,6 +317,7 @@
|
||||
<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"
|
||||
@@ -373,8 +381,8 @@
|
||||
<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}" />
|
||||
<ComboBox ItemsSource="{Binding Encoders}" SelectedItem="{Binding SelectedEncoder}" DisplayMemberPath="Label" IsEnabled="{Binding CanChooseEncoder}"
|
||||
ToolTip="{Binding EncoderToolTip}" ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{l:Loc Editor.Export.Encoder}" />
|
||||
<TextBlock Grid.Column="1" Text="{Binding EncoderKind}" FontSize="{StaticResource Size.Secondary}" VerticalAlignment="Center" Margin="8,0,0,0">
|
||||
<TextBlock.Style>
|
||||
<Style TargetType="TextBlock">
|
||||
@@ -399,8 +407,20 @@
|
||||
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}" />
|
||||
<!-- The folder ends in an ellipsis (its full path is in the tooltip). -->
|
||||
<ComboBox Grid.Row="8" Grid.Column="1" ItemsSource="{Binding SaveChoices}" SelectedItem="{Binding SelectedSave}" IsEnabled="{Binding CanChooseFolder}"
|
||||
ToolTip="{Binding SaveToolTip}" ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{l:Loc Editor.Export.SaveTo}">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate DataType="{x:Type e:SaveChoice}">
|
||||
<TextBlock Text="{Binding Label}" TextTrimming="CharacterEllipsis" />
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<!-- Export.html "Sync" (12 px): also send the render to the server the sequence is linked to. Under the folder rather than beside
|
||||
it, as in the mockup, so that neither is cut in the 194 px field column in longer languages. -->
|
||||
<CheckBox Grid.Row="9" Grid.Column="1" Margin="0,6,0,0" HorizontalAlignment="Left" FontSize="{StaticResource Size.Secondary}"
|
||||
Content="{l:Loc Editor.Export.Sync}" IsChecked="{Binding SyncToServer}" IsEnabled="{Binding CanSync}" ToolTip="{Binding SyncToolTip}"
|
||||
ToolTipService.ShowOnDisabled="True" />
|
||||
</Grid>
|
||||
|
||||
<Border Style="{StaticResource Border.Card}" Margin="0,12,0,0" Padding="12,10">
|
||||
|
||||
@@ -12,7 +12,8 @@ namespace Titano.App.Editor;
|
||||
/// 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).
|
||||
/// someone else (an analysis job, another client) is merged in. On a server sequence, settings both sides changed to
|
||||
/// different values wait for the user's choice (<see cref="Conflict"/>). Call from one thread (the UI thread).
|
||||
/// </summary>
|
||||
public sealed class EditorSession : IAsyncDisposable
|
||||
{
|
||||
@@ -46,11 +47,23 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
/// <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>
|
||||
/// <summary>
|
||||
/// Saving the project failed (raised once per run of failures; the save is retried until it succeeds). A conflict
|
||||
/// raises <see cref="ConflictFound"/> instead.
|
||||
/// </summary>
|
||||
public event Action<Exception>? SaveFailed;
|
||||
|
||||
/// <summary>A save met settings changed on the server too (<see cref="Conflict"/> was null): the user picks a side.</summary>
|
||||
public event Action<ProjectConflictException>? ConflictFound;
|
||||
|
||||
public ISequenceSource Source { get; }
|
||||
|
||||
/// <summary>A server sequence edited with proxies: saved, analysed and rendered on the server.</summary>
|
||||
public bool IsRemote => Source.IsRemote;
|
||||
|
||||
/// <summary>The project is shown, not changed (<see cref="ISequenceSource.IsReadOnly"/>): edits, undo and redo do nothing.</summary>
|
||||
public bool IsReadOnly => Source.IsReadOnly;
|
||||
|
||||
public SequenceContent Content { get; private set; }
|
||||
|
||||
public SequenceContext Context { get; private set; }
|
||||
@@ -71,20 +84,26 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
/// <summary>Why the pending change could not be stored; null when the last save succeeded.</summary>
|
||||
public Exception? LastSaveError => _saver.LastError;
|
||||
|
||||
/// <summary>
|
||||
/// Settings this editor and someone on the server changed to different values, as the last save found them; null
|
||||
/// when there are none. Saves wait (they are retried and meet it again) until <see cref="ResolveConflict"/>.
|
||||
/// </summary>
|
||||
public ProjectConflictException? Conflict { get; private set; }
|
||||
|
||||
/// <summary>Applies <paramref name="change"/> as an undoable step; false when it changes nothing.</summary>
|
||||
/// <param name="mergeKey">Consecutive edits with the same key are one undo step (a slider drag).</param>
|
||||
public bool Edit(Func<ProjectSettings, ProjectSettings> change, string? mergeKey = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(change);
|
||||
return History.Apply(change(Project), mergeKey);
|
||||
return !IsReadOnly && History.Apply(change(Project), mergeKey);
|
||||
}
|
||||
|
||||
/// <summary>The drag or key press behind a run of merged edits ended (<see cref="ProjectHistory.EndRun"/>).</summary>
|
||||
public void EndEditRun() => History.EndRun();
|
||||
|
||||
public bool Undo() => History.Undo();
|
||||
public bool Undo() => !IsReadOnly && History.Undo();
|
||||
|
||||
public bool Redo() => History.Redo();
|
||||
public bool Redo() => !IsReadOnly && History.Redo();
|
||||
|
||||
/// <summary>"Optimise section": the advisor's heavier decisions for <paramref name="section"/>, one undo step; returns what changed.</summary>
|
||||
public IReadOnlyList<SettingChange> Optimise(AdvisorSection section) => Optimise([section]);
|
||||
@@ -133,6 +152,47 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
public ArchiveJobRequest RenderRequest(ExportSettings export, bool useProxies = false) =>
|
||||
ProcessingJobs.Render(Content.Sequence, export, Content.SourceWidth, Content.SourceHeight, Project with { Export = export }, useProxies);
|
||||
|
||||
/// <summary>
|
||||
/// The jobs that render <paramref name="export"/> and its batch: one job on this PC (the sequence is prepared once),
|
||||
/// one per preset on a server, where a render node uploads one file per job (BRIEF §14.7).
|
||||
/// </summary>
|
||||
public IReadOnlyList<ArchiveJobRequest> RenderRequests(ExportSettings export) => IsRemote
|
||||
? ProcessingJobs.RenderEach(Content.Sequence, export, Content.SourceWidth, Content.SourceHeight, Project with { Export = export })
|
||||
: [RenderRequest(export)];
|
||||
|
||||
/// <summary>
|
||||
/// Makes a "Save both" copy of this PC's settings the project, as one undoable step; null when it stores the same values.
|
||||
/// </summary>
|
||||
/// <returns>The restore, which its toast can take back while it is the last change.</returns>
|
||||
/// <exception cref="System.IO.InvalidDataException">The copy cannot be read.</exception>
|
||||
public async Task<ProjectRestore?> RestoreAsync(SavedCopy copy)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(copy);
|
||||
var restored = await Task.Run(() => SavedCopies.Read(copy));
|
||||
var before = Project;
|
||||
return Edit(_ => restored) ? new ProjectRestore(this, before, Project) : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settles <see cref="Conflict"/> against the server's settings as the last save read them. Both choices first take
|
||||
/// in what only the server changed (like any merge, without an undo step). <paramref name="keepMine"/> then saves
|
||||
/// the editor's values of the settings both changed; otherwise the server's values become the project as one
|
||||
/// undoable step, so Ctrl+Z brings the editor's back (and saves them).
|
||||
/// </summary>
|
||||
/// <returns>False when there is no conflict to settle (a later save already went through).</returns>
|
||||
public bool ResolveConflict(bool keepMine)
|
||||
{
|
||||
if (Conflict is not { Server: var theirs }) return false;
|
||||
Conflict = null;
|
||||
var basis = _basis;
|
||||
_basis = theirs;
|
||||
History.Replace(ProjectMerge.Merge(basis, Project, theirs));
|
||||
if (!keepMine) History.Apply(ProjectMerge.Merge(basis, theirs, Project));
|
||||
// The change waiting for its retry goes now, on top of the server's settings.
|
||||
_ = _saver.FlushAsync();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>The export of the project with preset <paramref name="presetId"/> chosen (own values, no batch).</summary>
|
||||
public ExportSettings ExportFor(string presetId) =>
|
||||
Project.Export with { Preset = Project.Export.Preset.WithManual(presetId), Overrides = new ExportOverrides(), Batch = [] };
|
||||
@@ -146,10 +206,15 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
{
|
||||
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);
|
||||
// A server's settings that conflict with the editor's waiting change are not merged over it: that change's
|
||||
// retry meets them and asks (Conflict).
|
||||
if (Conflict is null && (!IsRemote || ProjectMerge.Conflicts(_basis, Project, content.Project).Count == 0))
|
||||
{
|
||||
var merged = ProjectMerge.Merge(_basis, Project, content.Project);
|
||||
_basis = content.Project;
|
||||
History.Replace(merged);
|
||||
}
|
||||
ContentChanged?.Invoke();
|
||||
}
|
||||
|
||||
@@ -177,6 +242,7 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
|
||||
private IReadOnlyList<SettingChange> Optimise(IReadOnlyList<AdvisorSection> sections)
|
||||
{
|
||||
if (IsReadOnly) return [];
|
||||
var settings = Project;
|
||||
var changes = new List<SettingChange>();
|
||||
foreach (var section in sections)
|
||||
@@ -191,6 +257,8 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
|
||||
private void OnSaveFailed(Exception ex, int failures)
|
||||
{
|
||||
// A conflict is retried without the network until the user settles it: noted once, when it is found.
|
||||
if (ex is ProjectConflictException) return;
|
||||
Log.Warning("editor", $"Saving the project of {Content.Sequence.DisplayTitle} failed (attempt {failures})", ex);
|
||||
if (failures == 1) SaveFailed?.Invoke(ex);
|
||||
}
|
||||
@@ -203,9 +271,37 @@ public sealed class EditorSession : IAsyncDisposable
|
||||
|
||||
private async Task SaveAsync(ProjectSettings project)
|
||||
{
|
||||
var stored = await Source.SaveProjectAsync(project, _basis, CancellationToken.None);
|
||||
ProjectSettings stored;
|
||||
try
|
||||
{
|
||||
stored = await Source.SaveProjectAsync(project, _basis, CancellationToken.None);
|
||||
}
|
||||
catch (ProjectConflictException ex)
|
||||
{
|
||||
var found = Conflict is null;
|
||||
Conflict = ex;
|
||||
if (found)
|
||||
{
|
||||
Log.Info("editor", $"Settings of {Content.Sequence.DisplayTitle} changed on the server too: {string.Join(", ", ex.Differences.Select(d => d.Path))}");
|
||||
ConflictFound?.Invoke(ex);
|
||||
}
|
||||
throw;
|
||||
}
|
||||
Conflict = null;
|
||||
_basis = stored;
|
||||
// Someone else's change was merged in: show it without an undo step (edits made since the save are kept).
|
||||
if (!ProjectMerge.SameValues(stored, project)) History.Replace(ProjectMerge.Merge(project, Project, stored));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A "Save both" copy made the project (<see cref="EditorSession.RestoreAsync"/>). Its Undo brings back the project from
|
||||
/// before as a new step, and only while the restore is still the last change: after another edit, an undo or a merged
|
||||
/// save it would take that change back instead.
|
||||
/// </summary>
|
||||
public sealed class ProjectRestore(EditorSession session, ProjectSettings before, ProjectSettings restored)
|
||||
{
|
||||
public bool CanUndo => ReferenceEquals(session.Project, restored);
|
||||
|
||||
public bool Undo() => CanUndo && session.Edit(_ => before);
|
||||
}
|
||||
@@ -16,8 +16,8 @@ public abstract class EditorTab : LocalizedViewModel
|
||||
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);
|
||||
OptimiseCommand = new RelayCommand(() => Editor.Optimise(Section), () => CanOptimise && !Editor.IsLocked);
|
||||
ResetCommand = new RelayCommand(() => Editor.Session.ResetSection(Section), () => CanReset && !Editor.IsLocked);
|
||||
}
|
||||
|
||||
public EditorViewModel Editor { get; }
|
||||
@@ -40,9 +40,9 @@ public abstract class EditorTab : LocalizedViewModel
|
||||
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 OptimiseToolTip => !CanOptimise ? Loc.L("Tooltips.Editor.OptimiseNone") : Editor.LockedToolTip ?? Loc.L("Tooltips.Editor.OptimiseSection");
|
||||
|
||||
public string ResetToolTip => Loc.L(Editor.IsBusy ? "Tooltips.Editor.Busy" : "Tooltips.Editor.ResetSection");
|
||||
public string ResetToolTip => Editor.LockedToolTip ?? Loc.L("Tooltips.Editor.ResetSection");
|
||||
|
||||
public ICommand OptimiseCommand { get; }
|
||||
|
||||
@@ -84,6 +84,11 @@ public abstract class EditorTab : LocalizedViewModel
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Whether this sequence can send its renders to the server changed (<see cref="EditorViewModel.SyncGate"/>).</summary>
|
||||
public virtual void OnSyncGateChanged()
|
||||
{
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
foreach (var row in Rows) row.Dispose();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Collections;
|
||||
using System.Globalization;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Jobs;
|
||||
using Titano.Core.Advice;
|
||||
using Titano.Core.Export;
|
||||
using Titano.Core.Localization;
|
||||
@@ -28,6 +29,38 @@ public static class EditorText
|
||||
return string.Join(Separator, parts);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// "Render · 46 %", "Render · queued", "Deep analysis · paused": a job the server runs for a server sequence (the job
|
||||
/// bar shows this PC's jobs only).
|
||||
/// </summary>
|
||||
public static string ServerJob(Job job)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
return job switch
|
||||
{
|
||||
{ State: JobState.Running, ProgressTotal: > 0 } => JobText.Kind(job.Kind) + Separator + Formatting.Percent((double)job.ProgressDone / job.ProgressTotal),
|
||||
{ State: JobState.Running } => JobText.Kind(job.Kind),
|
||||
_ => JobText.Kind(job.Kind) + Separator + Loc.L("Jobs.State." + job.State),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>"Render running on Studio NAS · 1,240 / 3,600 · 11.3 fps · 3 min left"; "Render waiting on Studio NAS".</summary>
|
||||
public static string ServerJobDetail(Job job, string server)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
var key = job.State switch
|
||||
{
|
||||
JobState.Queued => "Tooltips.Editor.ServerJob.Queued",
|
||||
JobState.Paused => "Tooltips.Editor.ServerJob.Paused",
|
||||
_ => "Tooltips.Editor.ServerJob",
|
||||
};
|
||||
var parts = new List<string> { Loc.L(key, JobText.Kind(job.Kind), server) };
|
||||
if (JobText.Counter(job.ProgressDone, job.ProgressTotal) is { Length: > 0 } counter) parts.Add(counter);
|
||||
if (JobText.Speed(job.Kind, job.ItemsPerSecond) is { Length: > 0 } speed) parts.Add(speed);
|
||||
if (job.Eta is { } eta) parts.Add(Loc.L("Editor.ServerJob.Left", Formatting.Duration(eta)));
|
||||
return string.Join(Separator, parts);
|
||||
}
|
||||
|
||||
/// <summary>"3,600 frames · 24 fps · 2 min 30 s · 3840×2160 · source 8192×5464": what the export makes of the sequence (Export.html header).</summary>
|
||||
public static string OutputSummary(SequenceContent content, ExportPlan plan)
|
||||
{
|
||||
|
||||
@@ -3,6 +3,8 @@ using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Threading;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Jobs;
|
||||
using Titano.App.Server;
|
||||
using Titano.App.Shell;
|
||||
using Titano.Core.Advice;
|
||||
using Titano.Core.Analysis;
|
||||
@@ -39,9 +41,10 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
private readonly LatestRunner _corrections = new(Debounce);
|
||||
private readonly LatestRunner _plans = new(Debounce);
|
||||
private readonly DispatcherTimer _player;
|
||||
private readonly Dictionary<Guid, Job> _jobs = [];
|
||||
private readonly SequenceJobs _jobs;
|
||||
private readonly AsyncRelayCommand _analyse;
|
||||
private readonly AsyncRelayCommand _render;
|
||||
private readonly AsyncRelayCommand _cancelServerJob;
|
||||
private PreviewRenderer _renderer;
|
||||
private int _currentIndex;
|
||||
private EditorTab _selectedTab;
|
||||
@@ -64,11 +67,14 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
private bool _previewBusy;
|
||||
private RenderCorrections? _correctionsValue;
|
||||
private ExportPlan? _plan;
|
||||
private int _planVersion;
|
||||
private bool _planned;
|
||||
private string? _renderPreset;
|
||||
private IReadOnlyList<TimelineMarker> _markers = [];
|
||||
private IThumbnailSource _thumbnails;
|
||||
private int _playLimit;
|
||||
private double? _analysisSecondsPerFrame;
|
||||
private ExportSyncGate _syncGate;
|
||||
private bool _disposed;
|
||||
|
||||
public EditorViewModel(ShellViewModel shell, EditorSession session, IReadOnlyList<IVideoEncoderProvider> encoders, EncoderHost host)
|
||||
@@ -78,6 +84,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
_encoders = encoders;
|
||||
_host = host;
|
||||
_dispatcher = Dispatcher.CurrentDispatcher;
|
||||
_jobs = new SequenceJobs(session.Content.Sequence.Id);
|
||||
_renderer = new PreviewRenderer(session.Content, session.Source);
|
||||
Planner = new ExportPlanner(session.Content, encoders, host);
|
||||
_thumbnails = new EditorThumbnails(session.Source, session.Content.Count);
|
||||
@@ -85,11 +92,12 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
_player.Tick += (_, _) => Advance();
|
||||
|
||||
BackCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Library));
|
||||
_analyse = new AsyncRelayCommand(AnalyseAsync, () => !IsBusy && !IsAnalysing);
|
||||
OptimiseAllCommand = new RelayCommand(OptimiseAll, () => !IsBusy);
|
||||
_analyse = new AsyncRelayCommand(AnalyseAsync, () => !IsLocked && !IsAnalysing);
|
||||
OptimiseAllCommand = new RelayCommand(OptimiseAll, () => !IsLocked);
|
||||
_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);
|
||||
_cancelServerJob = new AsyncRelayCommand(CancelServerJobAsync, () => ServerJob is not null);
|
||||
UndoCommand = new RelayCommand(() => Session.Undo(), () => !IsLocked && Session.History.CanUndo);
|
||||
RedoCommand = new RelayCommand(() => Session.Redo(), () => !IsLocked && Session.History.CanRedo);
|
||||
PlayCommand = new RelayCommand(() => TogglePlay(limit: 0));
|
||||
PreviewClipCommand = new RelayCommand(() => TogglePlay(limit: ClipFrames()));
|
||||
StepBackCommand = new RelayCommand(() => CurrentIndex--);
|
||||
@@ -102,12 +110,17 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
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;
|
||||
// Until the link is read (AttachJobsAsync), a sequence of this PC cannot send its renders.
|
||||
_syncGate = session.IsRemote ? ExportSyncGate.Remote : ExportSyncGate.SignedOut;
|
||||
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;
|
||||
session.ConflictFound += OnConflictFound;
|
||||
session.Source.JobChanged += OnJobChanged;
|
||||
session.Source.ReadOnlyChanged += OnReadOnlyChanged;
|
||||
shell.Services.Sync.Changed += OnSyncChanged;
|
||||
UpdateMarkers();
|
||||
RequestCorrections();
|
||||
RequestPlan();
|
||||
@@ -122,6 +135,58 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
|
||||
public string Title => Session.Content.Sequence.DisplayTitle;
|
||||
|
||||
/// <summary>A server sequence edited with proxies (the header says where it lives).</summary>
|
||||
public bool IsRemote => Session.IsRemote;
|
||||
|
||||
/// <summary>The server a server sequence lives on ("Studio NAS"); null for a sequence of this PC.</summary>
|
||||
public string? ServerName => IsRemote ? Shell.Services.Server.ServerName ?? Loc.L("Server.Label.Server") : null;
|
||||
|
||||
/// <summary>"Studio NAS" beside the title of a server sequence; "Studio NAS · read-only" when it is only shown.</summary>
|
||||
public string? RemoteText => !IsRemote ? null
|
||||
: IsOutdated ? Loc.L("Editor.Remote.Outdated", ServerName)
|
||||
: IsReadOnly ? Loc.L("Editor.Remote.ReadOnly", ServerName)
|
||||
: ServerName;
|
||||
|
||||
public string? RemoteToolTip => !IsRemote ? null
|
||||
: IsOutdated ? Loc.L("Tooltips.Editor.Outdated", ServerName)
|
||||
: IsReadOnly ? Loc.L("Tooltips.Editor.RemoteReadOnly", ServerName)
|
||||
: Loc.L("Tooltips.Editor.Remote", ServerName);
|
||||
|
||||
/// <summary>
|
||||
/// "Render · 46 %", "Render · queued": the analysis or render of a server sequence the server runs or holds (the job
|
||||
/// bar shows this PC's jobs); null when there is none.
|
||||
/// </summary>
|
||||
public string? ServerJobText => ServerJob is { } job ? EditorText.ServerJob(job) : null;
|
||||
|
||||
/// <summary>Frames, speed and time left of the server job.</summary>
|
||||
public string? ServerJobToolTip => ServerJob is { } job ? EditorText.ServerJobDetail(job, ServerName ?? string.Empty) : null;
|
||||
|
||||
/// <summary>The glyph of the server job (DESIGN §4): ◐ an analysis running, ● a render running, ○ waiting, paused.</summary>
|
||||
public StatusKind ServerJobKind => ServerJob switch
|
||||
{
|
||||
{ State: JobState.Running, Kind: JobKind.DeepAnalyse or JobKind.LightAnalyse } => StatusKind.Analysing,
|
||||
{ State: JobState.Running } => StatusKind.Running,
|
||||
{ State: JobState.Paused } => StatusKind.Paused,
|
||||
_ => StatusKind.Queued,
|
||||
};
|
||||
|
||||
/// <summary>The server job runs and reports how far it is (its progress bar shows).</summary>
|
||||
public bool HasServerJobProgress => ServerJob is { State: JobState.Running, ProgressTotal: > 0 };
|
||||
|
||||
/// <summary>Fraction of the server job done (0–1).</summary>
|
||||
public double ServerJobProgress => ServerJob is { State: JobState.Running, ProgressTotal: > 0 } job ? (double)job.ProgressDone / job.ProgressTotal : 0;
|
||||
|
||||
/// <summary>Cancels the server job (BRIEF §11.5: cancel is always available); the toast that follows offers Retry.</summary>
|
||||
public ICommand CancelServerJobCommand => _cancelServerJob;
|
||||
|
||||
public string? CancelServerJobToolTip => IsRemote ? Loc.L("Tooltips.Editor.ServerJob.Cancel", ServerName) : null;
|
||||
|
||||
/// <summary>The Export "Sync" option: available, or why not.</summary>
|
||||
public ExportSyncGate SyncGate { get => _syncGate; private set => Set(ref _syncGate, value); }
|
||||
|
||||
/// <summary>The server job the header shows (<see cref="SequenceJobs.Shown"/>).</summary>
|
||||
private Job? ServerJob => IsRemote ? _jobs.Shown : null;
|
||||
|
||||
/// <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).
|
||||
@@ -309,22 +374,38 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
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);
|
||||
public bool IsBusy => _jobs.IsBusy;
|
||||
|
||||
/// <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);
|
||||
/// <summary>A deep analysis of this sequence is queued, running or paused (Analyse would queue it twice).</summary>
|
||||
public bool IsAnalysing => _jobs.IsAnalysing;
|
||||
|
||||
public bool IsEditable => !IsBusy;
|
||||
/// <summary>
|
||||
/// The project is shown, not changed: a server sequence for an account without the Edit right, or one whose frames
|
||||
/// changed on the server (<see cref="IsOutdated"/>).
|
||||
/// </summary>
|
||||
public bool IsReadOnly => Session.IsReadOnly;
|
||||
|
||||
public string? BusyToolTip => IsBusy ? Loc.L("Tooltips.Editor.Busy") : null;
|
||||
/// <summary>The frames on the server are no longer the proxies this PC shows: nothing is saved or rendered until they are fetched again.</summary>
|
||||
public bool IsOutdated => Session.Source.IsOutdated;
|
||||
|
||||
/// <summary>Changes to the project wait (a job runs) or are not allowed (<see cref="IsReadOnly"/>); viewing tools stay live.</summary>
|
||||
public bool IsLocked => IsReadOnly || IsBusy;
|
||||
|
||||
public bool IsEditable => !IsLocked;
|
||||
|
||||
/// <summary>Why the controls that change the project are disabled; null while they are not.</summary>
|
||||
public string? LockedToolTip => IsOutdated ? Loc.L("Tooltips.Editor.Outdated", ServerName)
|
||||
: IsReadOnly ? Loc.L("Tooltips.Editor.ReadOnly")
|
||||
: 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")
|
||||
public string AnalyseToolTip => LockedToolTip
|
||||
?? (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");
|
||||
: Loc.L("Tooltips.Editor.Analyse"));
|
||||
|
||||
public string OptimiseAllToolTip => Loc.L(IsBusy ? "Tooltips.Editor.Busy" : "Tooltips.Editor.OptimiseAll");
|
||||
public string OptimiseAllToolTip => LockedToolTip ?? Loc.L("Tooltips.Editor.OptimiseAll");
|
||||
|
||||
public bool IsPlaying => _player.IsEnabled;
|
||||
|
||||
@@ -339,32 +420,60 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
|
||||
public IReadOnlyList<Choice> RenderChoices { get; }
|
||||
|
||||
/// <summary>The export preset the Render button renders (choosing another one sets it).</summary>
|
||||
/// <summary>
|
||||
/// The export preset the Render button renders: choosing another one sets it in the project, or, for an account that
|
||||
/// may render but not edit (<see cref="IsReadOnly"/>), only in this editor.
|
||||
/// </summary>
|
||||
public Choice? SelectedRenderChoice
|
||||
{
|
||||
get => RenderChoices.FirstOrDefault(c => string.Equals((string)c.Value, Plan?.Export.PresetId ?? EditorSettings.ExportPreset.Effective(Session.Project, null),
|
||||
StringComparison.OrdinalIgnoreCase));
|
||||
get
|
||||
{
|
||||
var id = (IsReadOnly ? _renderPreset : null) ?? Plan?.Export.PresetId ?? EditorSettings.ExportPreset.Effective(Session.Project, null);
|
||||
return RenderChoices.FirstOrDefault(c => string.Equals((string)c.Value, id, 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() } });
|
||||
if (!IsReadOnly)
|
||||
{
|
||||
Session.Edit(p => p with { Export = p.Export with { Preset = p.Export.Preset.WithManual(id), Overrides = new ExportOverrides() } });
|
||||
return;
|
||||
}
|
||||
if (string.Equals(id, _renderPreset, StringComparison.OrdinalIgnoreCase)) return;
|
||||
_renderPreset = id;
|
||||
OnPropertyChanged();
|
||||
RequestPlan();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The export Render renders: the project's, or with the preset chosen in the Render menu of a read-only session
|
||||
/// (the project keeps its own; the batch stays the project's).
|
||||
/// </summary>
|
||||
public ExportSettings RenderExport => IsReadOnly && _renderPreset is { } id
|
||||
? Session.ExportFor(id) with { Batch = Session.Project.Export.Batch }
|
||||
: Session.Project.Export;
|
||||
|
||||
/// <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 string RenderToolTip => RenderBlockedReason ?? (IsRemote ? Loc.L("Tooltips.Editor.RenderServer", ServerName) : Loc.L("Tooltips.Editor.Render"));
|
||||
|
||||
/// <summary>The ▾ part of Render: another preset for the project, or only for this render when the project cannot change.</summary>
|
||||
public string RenderChoiceToolTip => Loc.L(IsReadOnly ? "Tooltips.Editor.RenderChoiceReadOnly" : "Tooltips.Editor.RenderChoice");
|
||||
|
||||
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
|
||||
{
|
||||
_ when IsRemote && !Shell.Services.Sync.CanRender => Loc.L("Tooltips.Editor.Render.NoRight", ServerName),
|
||||
_ when IsOutdated => Loc.L("Tooltips.Editor.Outdated", ServerName),
|
||||
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
|
||||
// The server picks its encoder (a render node, or its managed fallback): this PC's encoders do not decide.
|
||||
{ Setup.Encoder.IsReady: false } plan when !IsRemote => 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"),
|
||||
@@ -399,13 +508,17 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
/// <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>
|
||||
/// <summary>
|
||||
/// Queues a render of the project's export (with its batch presets when <paramref name="batch"/>): on this PC's
|
||||
/// engine, or one server job per preset for a server sequence.
|
||||
/// </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));
|
||||
var export = batch ? RenderExport : RenderExport with { Batch = [] };
|
||||
var requests = Session.RenderRequests(export);
|
||||
foreach (var request in requests) await Session.SubmitAsync(request with { Priority = priority });
|
||||
if (IsRemote) Shell.Notify(Loc.L("Editor.Render.QueuedServer", ServerName), requests[0].Label);
|
||||
else Shell.Notify(Loc.L("Editor.Render.Queued"), requests[0].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>
|
||||
@@ -413,6 +526,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
{
|
||||
_analyse.RaiseCanExecuteChanged();
|
||||
_render.RaiseCanExecuteChanged();
|
||||
_cancelServerJob.RaiseCanExecuteChanged();
|
||||
foreach (var tab in Tabs) tab.RefreshCommands();
|
||||
CommandManager.InvalidateRequerySuggested();
|
||||
}
|
||||
@@ -452,16 +566,31 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
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>
|
||||
/// <summary>
|
||||
/// Loads the jobs of this sequence already queued or running (busy state), the speed of the last analysis and
|
||||
/// whether the Export "Sync" option applies.
|
||||
/// </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);
|
||||
await RefreshSyncGateAsync();
|
||||
var jobs = await Session.Source.ListJobsAsync(CancellationToken.None);
|
||||
foreach (var job in jobs) _jobs.Track(job);
|
||||
foreach (var job in jobs.OrderBy(j => j.Finished)) LearnAnalysisSpeed(job);
|
||||
OnBusyChanged();
|
||||
}
|
||||
|
||||
/// <summary>Reads again whether this sequence can send its renders to the signed-in server (session, link, rights).</summary>
|
||||
public async Task RefreshSyncGateAsync()
|
||||
{
|
||||
var sync = Shell.Services.Sync;
|
||||
var server = sync.Server;
|
||||
var linked = !IsRemote && server is not null && sync.Service is { } service
|
||||
&& await service.LinkOfAsync(server, Session.Content.Sequence.Id) is not null;
|
||||
if (_disposed) return;
|
||||
SyncGate = ExportSync.Gate(IsRemote, server, linked, sync.CanUpload);
|
||||
foreach (var tab in Tabs) tab.OnSyncGateChanged();
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_disposed) return;
|
||||
@@ -473,7 +602,10 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
Session.ProjectChanged -= OnProjectChanged;
|
||||
Session.ContentChanged -= OnContentChanged;
|
||||
Session.SaveFailed -= OnSaveFailed;
|
||||
if (Shell.Services.Jobs is { } jobs) jobs.JobChanged -= OnJobChanged;
|
||||
Session.ConflictFound -= OnConflictFound;
|
||||
Session.Source.JobChanged -= OnJobChanged;
|
||||
Session.Source.ReadOnlyChanged -= OnReadOnlyChanged;
|
||||
Shell.Services.Sync.Changed -= OnSyncChanged;
|
||||
foreach (var tab in Tabs) tab.Dispose();
|
||||
base.Dispose();
|
||||
await Session.DisposeAsync();
|
||||
@@ -572,9 +704,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
foreach (var tab in Tabs) tab.OnCorrectionsChanged();
|
||||
}
|
||||
|
||||
private void RequestPlan() => _ = RunPlanAsync(Planner, Session.Project);
|
||||
private void RequestPlan() => _ = RunPlanAsync(Planner, Session.Project, RenderExport, ++_planVersion);
|
||||
|
||||
private async Task RunPlanAsync(ExportPlanner planner, ProjectSettings project)
|
||||
private async Task RunPlanAsync(ExportPlanner planner, ProjectSettings project, ExportSettings export, int version)
|
||||
{
|
||||
ExportPlan? plan = null;
|
||||
// A superseded request ends quietly without planning; undo and redo bring back the very same project instance,
|
||||
@@ -584,7 +716,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
{
|
||||
await _plans.Schedule(_ =>
|
||||
{
|
||||
plan = planner.Plan(project);
|
||||
plan = planner.Plan(project, export);
|
||||
ran = true;
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
@@ -594,13 +726,11 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
Log.Warning("editor", "Planning the export failed", ex);
|
||||
ran = true;
|
||||
}
|
||||
if (!ran || _disposed || !ReferenceEquals(planner, Planner) || !ReferenceEquals(project, Session.Project)) return;
|
||||
// A later request (a new project, another render choice) owns the plan.
|
||||
if (!ran || _disposed || !ReferenceEquals(planner, Planner) || version != _planVersion) return;
|
||||
_planned = true;
|
||||
Plan = plan;
|
||||
OnPropertyChanged(nameof(RenderText));
|
||||
OnPropertyChanged(nameof(RenderToolTip));
|
||||
OnPropertyChanged(nameof(RenderBlockedReason));
|
||||
OnPropertyChanged(nameof(CanRender));
|
||||
OnRenderStateChanged();
|
||||
OnPropertyChanged(nameof(SelectedRenderChoice));
|
||||
OnPropertyChanged(nameof(Summary));
|
||||
foreach (var tab in Tabs) tab.OnPlanChanged();
|
||||
@@ -694,6 +824,32 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
ActionCommand = new RelayCommand(() => _ = Session.FlushAsync()),
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// A save met settings someone changed to other values on the server (BRIEF §14.5 "explicit conflict prompt"): the
|
||||
/// dialog lists them; Keep mine overwrites the server's, Take server (the safe default, also on Esc) shows theirs as
|
||||
/// one undoable step. Saving waits until then.
|
||||
/// </summary>
|
||||
private void OnConflictFound(ProjectConflictException conflict) => _dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
if (_disposed || Session.Conflict is null) return;
|
||||
var keepMine = Shell.Services.Dialogs.Confirm(ConflictRequest(conflict, Title, ServerName ?? string.Empty));
|
||||
if (!_disposed) Session.ResolveConflict(keepMine);
|
||||
});
|
||||
|
||||
/// <summary>The conflict prompt: what differs (the editor's value, then the server's) and what each choice replaces.</summary>
|
||||
internal static ConfirmRequest ConflictRequest(ProjectConflictException conflict, string title, string server) => new()
|
||||
{
|
||||
Heading = Loc.L("Editor.Conflict.Title", server),
|
||||
Message = Loc.L("Editor.Conflict.Message", title, server),
|
||||
Detail = string.Join(Environment.NewLine, SyncText.Differences(conflict.Differences, 10)),
|
||||
DetailToolTip = Loc.L("Tooltips.Server.Conflict.Detail"),
|
||||
SafeText = Loc.L("Server.Sync.Action.TakeServer"),
|
||||
SafeToolTip = Loc.L("Tooltips.Editor.Conflict.TakeServer", server),
|
||||
ActionText = Loc.L("Server.Sync.Action.KeepMine"),
|
||||
ActionToolTip = Loc.L("Tooltips.Editor.Conflict.KeepMine", server),
|
||||
IsDestructive = true,
|
||||
};
|
||||
|
||||
private void UpdateMarkers()
|
||||
{
|
||||
var content = Session.Content;
|
||||
@@ -745,28 +901,87 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
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));
|
||||
// The Jobs screen lists this PC's jobs; a server's analysis shows beside the title.
|
||||
if (IsRemote) Shell.Notify(Loc.L("Editor.Analyse.QueuedServer", ServerName), Title);
|
||||
else 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;
|
||||
if (!_jobs.Concerns(job)) return;
|
||||
_dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
if (_disposed) return;
|
||||
var wasActive = _jobs.ContainsKey(job.Id);
|
||||
Track(job);
|
||||
var wasActive = _jobs.IsActive(job.Id);
|
||||
// Progress alone (several times a second on a server) only moves the server job's text and bar.
|
||||
if (_jobs.Track(job)) OnBusyChanged();
|
||||
else OnServerJobChanged();
|
||||
LearnAnalysisSpeed(job);
|
||||
OnBusyChanged();
|
||||
if (wasActive && job.State == JobState.Done) _ = ReloadAsync(job.Kind == JobKind.Render ? job : null);
|
||||
if (!wasActive) return;
|
||||
if (job.State == JobState.Done) _ = ReloadAsync(job.Kind == JobKind.Render ? job : null);
|
||||
else if (IsRemote && job.State is JobState.Failed or JobState.Cancelled) ReportServerJobEnded(job);
|
||||
});
|
||||
}
|
||||
|
||||
private void Track(Job job)
|
||||
/// <summary>
|
||||
/// The frames of the server sequence changed while it is open (any thread): everything that changes the project is
|
||||
/// disabled and says why, and a toast offers to fetch the proxies again.
|
||||
/// </summary>
|
||||
private void OnReadOnlyChanged() => _dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
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);
|
||||
if (_disposed) return;
|
||||
OnPropertyChanged(nameof(IsReadOnly));
|
||||
OnPropertyChanged(nameof(IsOutdated));
|
||||
OnPropertyChanged(nameof(RemoteText));
|
||||
OnPropertyChanged(nameof(RemoteToolTip));
|
||||
OnPropertyChanged(nameof(RenderChoiceToolTip));
|
||||
OnRenderStateChanged();
|
||||
OnBusyChanged();
|
||||
if (!IsOutdated) return;
|
||||
var (id, title) = (Session.Content.Sequence.Id, Title);
|
||||
Shell.ShowToast(new Toast
|
||||
{
|
||||
Title = Loc.L("Editor.Outdated.Title", ServerName),
|
||||
Message = title,
|
||||
ActionText = Loc.L("Editor.Outdated.Fetch"),
|
||||
ActionToolTip = Loc.L("Tooltips.Editor.Outdated.Fetch"),
|
||||
ActionCommand = new AsyncRelayCommand(() => Shell.Sequence.FetchProxiesAsync(id, title)),
|
||||
});
|
||||
});
|
||||
|
||||
/// <summary>A server job of this sequence failed or was cancelled: what happened, and Retry (BRIEF §11.5).</summary>
|
||||
private void ReportServerJobEnded(Job job)
|
||||
{
|
||||
var server = ServerName ?? string.Empty;
|
||||
Shell.ShowToast(new Toast
|
||||
{
|
||||
Title = Loc.L("Editor.ServerJob.Ended", JobText.Kind(job.Kind), Loc.L("Jobs.State." + job.State), server),
|
||||
Message = job.Error ?? job.TargetLabel ?? Title,
|
||||
ActionText = Loc.L("Jobs.Action.Retry"),
|
||||
ActionToolTip = Loc.L("Tooltips.Editor.ServerJob.Retry", server),
|
||||
ActionCommand = new AsyncRelayCommand(() => Session.Source.RetryJobAsync(job.Id, CancellationToken.None), () => !_disposed),
|
||||
});
|
||||
}
|
||||
|
||||
private async Task CancelServerJobAsync()
|
||||
{
|
||||
if (ServerJob is { } job) await Session.Source.CancelJobAsync(job.Id, CancellationToken.None);
|
||||
}
|
||||
|
||||
/// <summary>The session, the sync links or the rights changed (any thread): whether the Export "Sync" option applies.</summary>
|
||||
private void OnSyncChanged() => _dispatcher.BeginInvoke(() => _ = OnSyncChangedAsync());
|
||||
|
||||
private async Task OnSyncChangedAsync()
|
||||
{
|
||||
if (_disposed) return;
|
||||
try
|
||||
{
|
||||
await RefreshSyncGateAsync();
|
||||
}
|
||||
catch (Data.DatabaseException ex)
|
||||
{
|
||||
Log.Warning("editor", "The sync state of the sequence could not be read", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Seconds per frame of the latest finished deep analysis (any sequence): the cost Analyse announces.</summary>
|
||||
@@ -782,13 +997,18 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
{
|
||||
await Session.ReloadAsync();
|
||||
}
|
||||
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or UnauthorizedAccessException)
|
||||
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or UnauthorizedAccessException
|
||||
or System.Net.Http.HttpRequestException or Protocol.Client.TitanoApiException or OperationCanceledException)
|
||||
{
|
||||
// A server that does not answer in time cancels the request (OperationCanceledException).
|
||||
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;
|
||||
// A server's render stays on the server: nothing to show in Explorer.
|
||||
var output = Session.Content.Renders.FirstOrDefault(r => render.Started is not { } started || r.Created >= started)?.OutputPath is { Length: > 0 } path
|
||||
? path
|
||||
: null;
|
||||
Shell.ShowToast(new Toast
|
||||
{
|
||||
Title = Loc.L("Editor.Render.Done"),
|
||||
@@ -803,14 +1023,36 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
|
||||
{
|
||||
OnPropertyChanged(nameof(IsBusy));
|
||||
OnPropertyChanged(nameof(IsAnalysing));
|
||||
OnPropertyChanged(nameof(IsLocked));
|
||||
OnPropertyChanged(nameof(IsEditable));
|
||||
OnPropertyChanged(nameof(BusyToolTip));
|
||||
OnPropertyChanged(nameof(LockedToolTip));
|
||||
OnPropertyChanged(nameof(AnalyseToolTip));
|
||||
OnPropertyChanged(nameof(OptimiseAllToolTip));
|
||||
OnServerJobChanged();
|
||||
foreach (var tab in Tabs) tab.OnBusyChanged();
|
||||
RefreshCommands();
|
||||
}
|
||||
|
||||
private void OnServerJobChanged()
|
||||
{
|
||||
if (!IsRemote) return;
|
||||
OnPropertyChanged(nameof(ServerJobText));
|
||||
OnPropertyChanged(nameof(ServerJobToolTip));
|
||||
OnPropertyChanged(nameof(ServerJobKind));
|
||||
OnPropertyChanged(nameof(HasServerJobProgress));
|
||||
OnPropertyChanged(nameof(ServerJobProgress));
|
||||
_cancelServerJob.RaiseCanExecuteChanged();
|
||||
}
|
||||
|
||||
/// <summary>What Render renders and whether it can (the plan, the rights or the frames changed).</summary>
|
||||
private void OnRenderStateChanged()
|
||||
{
|
||||
OnPropertyChanged(nameof(RenderText));
|
||||
OnPropertyChanged(nameof(RenderToolTip));
|
||||
OnPropertyChanged(nameof(RenderBlockedReason));
|
||||
OnPropertyChanged(nameof(CanRender));
|
||||
}
|
||||
|
||||
/// <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)
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
using System.IO;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Processing;
|
||||
using Titano.Data.Sync;
|
||||
|
||||
namespace Titano.App.Editor;
|
||||
|
||||
/// <summary>Whether the Export "Sync" option can be used, or why not (its tooltip says which).</summary>
|
||||
public enum ExportSyncGate
|
||||
{
|
||||
Available,
|
||||
|
||||
/// <summary>A server sequence: its renders are made on the server and stay there.</summary>
|
||||
Remote,
|
||||
|
||||
/// <summary>No server session is open.</summary>
|
||||
SignedOut,
|
||||
|
||||
/// <summary>The server does not have this sequence.</summary>
|
||||
NotLinked,
|
||||
|
||||
/// <summary>The account may not send files to the server.</summary>
|
||||
NoUpload,
|
||||
}
|
||||
|
||||
/// <summary>What became of the Export "Sync" of a finished render.</summary>
|
||||
/// <param name="Gate">Why the render was not sent, or <see cref="ExportSyncGate.Available"/>.</param>
|
||||
/// <param name="Send">The queued send job; null when it was not queued.</param>
|
||||
public sealed record ExportSyncResult(ExportSyncGate Gate, Job? Send);
|
||||
|
||||
/// <summary>
|
||||
/// Export "Sync" (Export.html "register the export on the server when connected", BRIEF §14.5): a render made on this
|
||||
/// PC whose export asked for it is sent to the server the sequence is linked to once it is done
|
||||
/// (<see cref="SyncService.EnqueueSendExportsAsync"/>). The choice travels inside the render job (its export), so it
|
||||
/// holds after the editor closes; a render that ends while the session is down is queued for the last session's server
|
||||
/// and its send waits for the session (and fails visibly on the Jobs screen when it does not come back).
|
||||
/// </summary>
|
||||
public sealed class ExportSync(TitanoDatabase db, SyncService sync, JobEngine engine)
|
||||
{
|
||||
/// <summary>The option's state for a sequence.</summary>
|
||||
/// <param name="server">Key of the signed-in server; null while signed out.</param>
|
||||
/// <param name="linked">The server has the sequence (a sync link joins them).</param>
|
||||
public static ExportSyncGate Gate(bool isRemote, string? server, bool linked, bool canUpload) =>
|
||||
isRemote ? ExportSyncGate.Remote
|
||||
: server is null ? ExportSyncGate.SignedOut
|
||||
: !linked ? ExportSyncGate.NotLinked
|
||||
: !canUpload ? ExportSyncGate.NoUpload
|
||||
: ExportSyncGate.Available;
|
||||
|
||||
/// <summary>Queues sending a finished render's output.</summary>
|
||||
/// <param name="server">Key of the server: the signed-in one, else the one of the saved session; null without either.</param>
|
||||
/// <param name="canUpload">The account may send files (assumed while the session is down: the server refuses the send otherwise).</param>
|
||||
/// <returns>The send job or why there is none; null when the job is not a finished render of this PC that asked for it.</returns>
|
||||
public async Task<ExportSyncResult?> SendAsync(Job job, string? server, bool canUpload, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
if (job is not { Kind: JobKind.Render, State: JobState.Done, TargetIds: [var target] } || !Wanted(job)) return null;
|
||||
if (await db.Sequences.GetAsync(target, cancellationToken) is not { } local) return null;
|
||||
var linked = server is not null && await sync.LinkOfAsync(server, local.Id, cancellationToken) is not null;
|
||||
var gate = Gate(false, server, linked, canUpload);
|
||||
return gate == ExportSyncGate.Available
|
||||
? new ExportSyncResult(gate, await sync.EnqueueSendExportsAsync(engine, server!, local, cancellationToken))
|
||||
: new ExportSyncResult(gate, null);
|
||||
}
|
||||
|
||||
private static bool Wanted(Job job)
|
||||
{
|
||||
try
|
||||
{
|
||||
return ProcessingJobs.ReadRender(job.ParametersJson).Export.SyncToServer;
|
||||
}
|
||||
catch (InvalidDataException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Video;
|
||||
using Titano.Data.Processing;
|
||||
using Titano.Ui.Controls;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.App.Editor;
|
||||
@@ -31,9 +32,12 @@ public sealed class PresetCard(ExportTab owner, ExportChoice choice) : Observabl
|
||||
/// <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
|
||||
/// <summary>What choosing the card does, or why it cannot be chosen now (a job runs, the project cannot change).</summary>
|
||||
public string ToolTip => owner.Editor.LockedToolTip ?? (Choice.Reason is { } reason
|
||||
? Loc.L(IsSequencePreset ? "Tooltips.Editor.Export.ApplyPreset" : "Tooltips.Editor.Export.Recommended", reason)
|
||||
: Loc.L("Tooltips.Editor.Export.Preset", Name);
|
||||
: Loc.L("Tooltips.Editor.Export.Preset", Name));
|
||||
|
||||
public string BatchToolTip => owner.Editor.LockedToolTip ?? Loc.L("Tooltips.Editor.Export.InBatch");
|
||||
|
||||
/// <summary>"MP4 · HEVC Main10 · 3840×2160 · 24 fps".</summary>
|
||||
public string? Format { get => _format; private set => Set(ref _format, value); }
|
||||
@@ -57,6 +61,7 @@ public sealed class PresetCard(ExportTab owner, ExportChoice choice) : Observabl
|
||||
|
||||
public ICommand SelectCommand => owner.SelectCommand;
|
||||
|
||||
/// <remarks>A server sequence renders on the server: this PC's encoders neither name nor rule out the encoding.</remarks>
|
||||
public void Update(ExportPlan? plan)
|
||||
{
|
||||
if (plan is null)
|
||||
@@ -65,12 +70,20 @@ public sealed class PresetCard(ExportTab owner, ExportChoice choice) : Observabl
|
||||
return;
|
||||
}
|
||||
var settings = plan.Setup.Encoder.Settings;
|
||||
var remote = owner.Editor.IsRemote;
|
||||
Format = EditorText.Format(plan.Export, settings.Width, settings.Height);
|
||||
Encoding = EditorText.Encoding(plan.Export, settings.BitRate, plan.Setup.Encoder.Capability?.Name);
|
||||
Estimate = plan.Setup.Encoder.IsReady ? EditorText.Estimate(plan.Estimate) : Loc.L("Editor.Export.Unavailable");
|
||||
Encoding = EditorText.Encoding(plan.Export, settings.BitRate, remote ? null : plan.Setup.Encoder.Capability?.Name);
|
||||
Estimate = remote || plan.Setup.Encoder.IsReady ? EditorText.Estimate(plan.Estimate) : Loc.L("Editor.Export.Unavailable");
|
||||
}
|
||||
|
||||
public void RefreshBatch() => OnPropertyChanged(nameof(IsInBatch));
|
||||
|
||||
/// <summary>A job of the sequence started or ended, or the project became read-only: the tooltips say why the card waits.</summary>
|
||||
public void RefreshLocked()
|
||||
{
|
||||
OnPropertyChanged(nameof(ToolTip));
|
||||
OnPropertyChanged(nameof(BatchToolTip));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A codec choice of the Output panel with the profile and depth it implies.</summary>
|
||||
@@ -106,6 +119,8 @@ public sealed class ExportTab : EditorTab
|
||||
private readonly AsyncRelayCommand _renderNow;
|
||||
private readonly AsyncRelayCommand _addToQueue;
|
||||
private readonly AsyncRelayCommand _batch;
|
||||
private readonly AsyncRelayCommand _restore;
|
||||
private SavedCopy? _selectedCopy;
|
||||
private IReadOnlyList<PresetCard> _cards = [];
|
||||
private IReadOnlyList<CodecChoice> _codecChoices = [];
|
||||
private IReadOnlyList<Choice> _encoders = [];
|
||||
@@ -117,16 +132,18 @@ public sealed class ExportTab : EditorTab
|
||||
public ExportTab(EditorViewModel editor)
|
||||
: base(editor, "Export", AdvisorSection.Export)
|
||||
{
|
||||
SelectCommand = new RelayCommand(p => Select(p as PresetCard), _ => !Editor.IsBusy);
|
||||
SelectCommand = new RelayCommand(p => Select(p as PresetCard), _ => !Editor.IsLocked);
|
||||
_renderNow = new AsyncRelayCommand(() => Editor.RenderAsync(JobPriority.User, batch: false), () => Editor.CanRender);
|
||||
_addToQueue = new AsyncRelayCommand(() => Editor.RenderAsync(JobPriority.Normal, batch: false), () => Editor.CanRender);
|
||||
_batch = new AsyncRelayCommand(() => Editor.RenderAsync(JobPriority.User, batch: true), () => Editor.CanRender && Batch.Count > 0);
|
||||
HistoryCommand = new RelayCommand(OpenHistory);
|
||||
RevealLastCommand = new RelayCommand(() => ShellActions.Reveal(Editor.Session.Content.Renders[0].OutputPath), () => Editor.Session.Content.Renders.Count > 0);
|
||||
RevealLastCommand = new RelayCommand(() => ShellActions.Reveal(Editor.Session.Content.Renders[0].OutputPath), () => CanReveal);
|
||||
_restore = new AsyncRelayCommand(RestoreAsync, () => !Editor.IsLocked && SelectedCopy is not null);
|
||||
ResetFrameRateCommand = new RelayCommand(() => EditOverrides(o => o with { FrameRate = null }));
|
||||
Width = new EditableField(string.Empty, ValidateSize, v => EditOverrides(o => o with { Width = ParseSize(v) }), () => Loc.L("Tooltips.Editor.Export.Width"));
|
||||
Height = new EditableField(string.Empty, ValidateSize, v => EditOverrides(o => o with { Height = ParseSize(v) }), () => Loc.L("Tooltips.Editor.Export.Height"));
|
||||
NameTemplate = new EditableField(string.Empty, ValidateTemplate, v => EditExport(e => e with { NameTemplate = v }), () => Loc.L("Tooltips.Editor.Export.Name"));
|
||||
_selectedCopy = SavedCopies.FirstOrDefault();
|
||||
LoadCards();
|
||||
Refresh();
|
||||
}
|
||||
@@ -149,10 +166,71 @@ public sealed class ExportTab : EditorTab
|
||||
|
||||
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 string BatchToolTip => Editor.RenderBlockedReason ?? (Batch.Count == 0 ? Loc.L("Tooltips.Editor.Export.BatchEmpty")
|
||||
: Editor.IsRemote ? Loc.L("Tooltips.Editor.Export.BatchServer", Editor.ServerName)
|
||||
: Loc.L("Tooltips.Editor.Export.Batch"));
|
||||
|
||||
public bool HasHistory => Editor.Session.Content.Renders.Count > 0;
|
||||
|
||||
/// <summary>The "history" link opens this PC's Jobs screen, which does not list a server's jobs.</summary>
|
||||
public bool CanOpenHistory => !Editor.IsRemote;
|
||||
|
||||
/// <summary>The newest render is a file on this PC (a server's renders stay on the server).</summary>
|
||||
public bool CanReveal => Editor.Session.Content.Renders is [{ OutputPath.Length: > 0 }, ..];
|
||||
|
||||
// ---- Export "Sync" (Export.html, next to Save to) ----
|
||||
|
||||
/// <summary>Send each render made on this PC to the server the sequence is linked to; remembered in the project.</summary>
|
||||
public bool SyncToServer
|
||||
{
|
||||
get => Export.SyncToServer;
|
||||
set
|
||||
{
|
||||
if (!_refreshing && value != Export.SyncToServer) EditExport(e => e with { SyncToServer = value });
|
||||
}
|
||||
}
|
||||
|
||||
public bool CanSync => Editor.SyncGate == ExportSyncGate.Available;
|
||||
|
||||
/// <summary>What Sync does, or why it cannot be used for this sequence now.</summary>
|
||||
public string SyncToolTip => Loc.L(Editor.SyncGate switch
|
||||
{
|
||||
ExportSyncGate.Remote => "Tooltips.Editor.Export.SyncRemote",
|
||||
ExportSyncGate.SignedOut => "Tooltips.Editor.Export.SyncSignedOut",
|
||||
ExportSyncGate.NotLinked => "Tooltips.Editor.Export.SyncNotLinked",
|
||||
ExportSyncGate.NoUpload => "Tooltips.Editor.Export.SyncNoUpload",
|
||||
_ => "Tooltips.Editor.Export.Sync",
|
||||
});
|
||||
|
||||
/// <summary>A server sequence renders into its exports folder on the server.</summary>
|
||||
public bool CanChooseFolder => !Editor.IsRemote;
|
||||
|
||||
// ---- "Save both" copies of this PC's settings ----
|
||||
|
||||
public IReadOnlyList<SavedCopy> SavedCopies => Editor.Session.Content.SavedCopies;
|
||||
|
||||
public bool HasSavedCopies => SavedCopies.Count > 0;
|
||||
|
||||
/// <summary>The copy Restore makes the project: the newest unless another is chosen in the menu.</summary>
|
||||
public SavedCopy? SelectedCopy
|
||||
{
|
||||
get => _selectedCopy;
|
||||
set
|
||||
{
|
||||
if (!Set(ref _selectedCopy, value)) return;
|
||||
OnPropertyChanged(nameof(RestoreText));
|
||||
OnPropertyChanged(nameof(RestoreToolTip));
|
||||
_restore.RaiseCanExecuteChanged();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"Restore settings · 03/10/2026 14:22".</summary>
|
||||
public string RestoreText => Loc.L("Editor.Export.Restore", SelectedCopy?.Label ?? string.Empty);
|
||||
|
||||
public string RestoreToolTip => Editor.LockedToolTip ?? Loc.L("Tooltips.Editor.Export.Restore", SelectedCopy?.Label ?? string.Empty);
|
||||
|
||||
public ICommand RestoreCommand => _restore;
|
||||
|
||||
public ICommand ResetFrameRateCommand { get; }
|
||||
|
||||
/// <summary>"Output · 4K archive".</summary>
|
||||
@@ -234,6 +312,11 @@ public sealed class ExportTab : EditorTab
|
||||
|
||||
public IReadOnlyList<Choice> Encoders { get => _encoders; private set => Set(ref _encoders, value); }
|
||||
|
||||
/// <summary>The encoder is this PC's choice only for its own renders; the server or its render node picks its own.</summary>
|
||||
public bool CanChooseEncoder => !Editor.IsRemote;
|
||||
|
||||
public string EncoderToolTip => Editor.IsRemote ? Loc.L("Tooltips.Editor.Export.EncoderServer", Editor.ServerName) : Loc.L("Tooltips.Editor.Export.Encoder");
|
||||
|
||||
public Choice? SelectedEncoder
|
||||
{
|
||||
get => Encoders.FirstOrDefault(e => Equals(e.Value, Export.Overrides.Encoder ?? string.Empty));
|
||||
@@ -243,10 +326,12 @@ public sealed class ExportTab : EditorTab
|
||||
}
|
||||
}
|
||||
|
||||
/// <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;
|
||||
/// <summary>"hardware", "software" for this PC's encoder (the word, not a colour, carries the state).</summary>
|
||||
public string? EncoderKind => !Editor.IsRemote && Editor.Plan?.Setup.Encoder.Capability is { } c
|
||||
? Loc.L(c.Hardware ? "Editor.Export.Hardware" : "Editor.Export.Software")
|
||||
: null;
|
||||
|
||||
public bool IsHardware => Editor.Plan?.Setup.Encoder.Capability?.Hardware == true;
|
||||
public bool IsHardware => !Editor.IsRemote && Editor.Plan?.Setup.Encoder.Capability?.Hardware == true;
|
||||
|
||||
public IReadOnlyList<Choice> Depths { get => _depths; private set => Set(ref _depths, value); }
|
||||
|
||||
@@ -270,9 +355,10 @@ public sealed class ExportTab : EditorTab
|
||||
|
||||
public IReadOnlyList<SaveChoice> SaveChoices { get => _saveChoices; private set => Set(ref _saveChoices, value); }
|
||||
|
||||
/// <summary>The project's folder; a server sequence always renders into its exports folder on the server.</summary>
|
||||
public SaveChoice? SelectedSave
|
||||
{
|
||||
get => SaveChoices.FirstOrDefault(c => !c.Browse && c.Folder == Export.Folder);
|
||||
get => SaveChoices.FirstOrDefault(c => !c.Browse && c.Folder == (CanChooseFolder ? Export.Folder : null));
|
||||
set
|
||||
{
|
||||
if (_refreshing || value is null) return;
|
||||
@@ -287,12 +373,15 @@ public sealed class ExportTab : EditorTab
|
||||
}
|
||||
}
|
||||
|
||||
public string SaveToolTip => Loc.L("Tooltips.Editor.Export.Folder", Export.Folder ?? Editor.Session.Content.ExportsFolder ?? string.Empty);
|
||||
public string SaveToolTip => Editor.IsRemote
|
||||
? Loc.L("Tooltips.Editor.Export.FolderServer")
|
||||
: Loc.L("Tooltips.Editor.Export.Folder", Export.Folder ?? Editor.Session.Content.ExportsFolder ?? string.Empty);
|
||||
|
||||
public string? EstimatedSize => Editor.Plan is { Setup.Encoder.IsReady: true } plan ? Formatting.Bytes(plan.Estimate.Bytes) : null;
|
||||
public string? EstimatedSize => Estimated is { } 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)
|
||||
/// <summary>"about 5 min · NVENC"; without this PC's encoder for a server sequence.</summary>
|
||||
public string? EstimatedTime => Estimated is { } plan
|
||||
? Loc.L("Editor.Export.About", Formatting.Duration(plan.Estimate.Time)) + (!Editor.IsRemote && plan.Setup.Encoder.Capability is { } c ? " · " + c.Name : string.Empty)
|
||||
: null;
|
||||
|
||||
public string? ResultName => Editor.Plan?.FileName;
|
||||
@@ -314,6 +403,9 @@ public sealed class ExportTab : EditorTab
|
||||
|
||||
private ResolvedExport Resolved => Editor.Plan?.Export ?? ExportResolver.Resolve(Export);
|
||||
|
||||
/// <summary>The plan when its estimates mean something: this PC can encode it, or the server renders it.</summary>
|
||||
private ExportPlan? Estimated => Editor.Plan is { } plan && (Editor.IsRemote || plan.Setup.Encoder.IsReady) ? plan : null;
|
||||
|
||||
public bool IsInBatch(string presetId) => Export.Batch.Contains(presetId, StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public void SetInBatch(string presetId, bool value)
|
||||
@@ -329,8 +421,8 @@ public sealed class ExportTab : EditorTab
|
||||
try
|
||||
{
|
||||
UpdateLists();
|
||||
SaveChoices = Export.Folder is { } folder
|
||||
? [new SaveChoice(null), new SaveChoice(folder), new SaveChoice(null, Browse: true)]
|
||||
SaveChoices = !CanChooseFolder ? [new SaveChoice(null)]
|
||||
: Export.Folder is { } folder ? [new SaveChoice(null), new SaveChoice(folder), new SaveChoice(null, Browse: true)]
|
||||
: [new SaveChoice(null), new SaveChoice(null, Browse: true)];
|
||||
if (!NameTemplate.IsDirty) NameTemplate.Load(Export.NameTemplate);
|
||||
OnAllPropertiesChanged();
|
||||
@@ -339,11 +431,8 @@ public sealed class ExportTab : EditorTab
|
||||
{
|
||||
_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();
|
||||
}
|
||||
SelectCards();
|
||||
foreach (var card in Cards) card.RefreshBatch();
|
||||
_ = EstimateCardsAsync();
|
||||
}
|
||||
|
||||
@@ -356,20 +445,27 @@ public sealed class ExportTab : EditorTab
|
||||
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()]
|
||||
: [];
|
||||
Notices = Editor.Plan is { } plan ? PlanNotices(plan) : [];
|
||||
OnAllPropertiesChanged();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_refreshing = false;
|
||||
}
|
||||
// The plan follows the preset a read-only session chose to render.
|
||||
SelectCards();
|
||||
}
|
||||
|
||||
public override void OnBusyChanged()
|
||||
{
|
||||
base.OnBusyChanged();
|
||||
foreach (var card in Cards) card.RefreshLocked();
|
||||
}
|
||||
|
||||
public override void OnContentChanged()
|
||||
{
|
||||
LoadCards();
|
||||
if (SelectedCopy is null || !SavedCopies.Contains(SelectedCopy)) SelectedCopy = SavedCopies.FirstOrDefault();
|
||||
base.OnContentChanged();
|
||||
}
|
||||
|
||||
@@ -378,8 +474,16 @@ public sealed class ExportTab : EditorTab
|
||||
_renderNow.RaiseCanExecuteChanged();
|
||||
_addToQueue.RaiseCanExecuteChanged();
|
||||
_batch.RaiseCanExecuteChanged();
|
||||
_restore.RaiseCanExecuteChanged();
|
||||
OnPropertyChanged(nameof(AddToQueueToolTip));
|
||||
OnPropertyChanged(nameof(BatchToolTip));
|
||||
OnPropertyChanged(nameof(RestoreToolTip));
|
||||
}
|
||||
|
||||
public override void OnSyncGateChanged()
|
||||
{
|
||||
OnPropertyChanged(nameof(CanSync));
|
||||
OnPropertyChanged(nameof(SyncToolTip));
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
@@ -406,6 +510,24 @@ public sealed class ExportTab : EditorTab
|
||||
|
||||
private void LoadCards() => Cards = [.. ExportPlanner.Choices(Editor.Session.Presets, Editor.Session.Advice).Select(c => new PresetCard(this, c))];
|
||||
|
||||
/// <summary>The card of the export preset the plan renders.</summary>
|
||||
private void SelectCards()
|
||||
{
|
||||
foreach (var card in Cards)
|
||||
card.IsSelected = card.Choice.Sequence is null && string.Equals(card.Choice.ExportPresetId, Resolved.PresetId, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// What the plan changed or cannot do, localised; for a server sequence without this PC's encoder notices (the server
|
||||
/// or its render node picks the encoder).
|
||||
/// </summary>
|
||||
private IReadOnlyList<string> PlanNotices(ExportPlan plan)
|
||||
{
|
||||
var encoder = Editor.IsRemote ? plan.Setup.Encoder.Notices.Select(n => n.Key).ToHashSet(StringComparer.Ordinal) : [];
|
||||
return [.. plan.Setup.Warnings.Where(w => !encoder.Contains(w.Key)).Select(w => Loc.L(w.Key, [.. w.Args]))
|
||||
.Concat(plan.Export.Warnings.Select(k => Loc.L(k))).Distinct()];
|
||||
}
|
||||
|
||||
/// <summary>Estimates every card off the UI thread for the project as it is now (latest request wins).</summary>
|
||||
private async Task EstimateCardsAsync()
|
||||
{
|
||||
@@ -437,6 +559,40 @@ public sealed class ExportTab : EditorTab
|
||||
for (var i = 0; i < cards.Count; i++) cards[i].Update(plans[i]);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes the chosen copy the project as one undo step. The toast's Undo brings back the project as it was before, as
|
||||
/// a new step, while the restore is still the last change of this editor (a later edit would otherwise be undone).
|
||||
/// </summary>
|
||||
private async Task RestoreAsync()
|
||||
{
|
||||
if (SelectedCopy is not { } copy) return;
|
||||
ProjectRestore? restore;
|
||||
try
|
||||
{
|
||||
restore = await Editor.Session.RestoreAsync(copy);
|
||||
}
|
||||
catch (InvalidDataException ex)
|
||||
{
|
||||
Editor.Shell.ReportError(ex);
|
||||
return;
|
||||
}
|
||||
if (restore is null)
|
||||
{
|
||||
Editor.Shell.Notify(Loc.L("Editor.Copy.Same"), copy.Label);
|
||||
return;
|
||||
}
|
||||
var editor = Editor;
|
||||
editor.Shell.ShowToast(new Toast
|
||||
{
|
||||
Title = Loc.L("Editor.Copy.Restored"),
|
||||
Message = copy.Label,
|
||||
ActionText = Loc.L("Editor.Copy.Undo"),
|
||||
ActionToolTip = Loc.L("Tooltips.Editor.Copy.Undo"),
|
||||
// Only in the editor that made it: another sequence opened meanwhile has its own project.
|
||||
ActionCommand = new RelayCommand(() => restore.Undo(), () => ReferenceEquals(editor.Shell.Sequence.Editor, editor) && restore.CanUndo),
|
||||
});
|
||||
}
|
||||
|
||||
private void OpenHistory()
|
||||
{
|
||||
Editor.Shell.Jobs.Filter = Jobs.JobFilter.All;
|
||||
|
||||
@@ -89,7 +89,7 @@ public sealed class FrameRow(FramesTab owner, Frame frame, int index) : Observab
|
||||
|
||||
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");
|
||||
public string ExcludeToolTip => owner.Editor.LockedToolTip ?? Loc.L(IsExcluded ? "Tooltips.Editor.Frames.Include" : "Tooltips.Editor.Frames.Exclude");
|
||||
|
||||
/// <summary>A job of the sequence started or ended: the action tooltips say why they wait.</summary>
|
||||
public void RefreshBusy() => OnPropertyChanged(nameof(ExcludeToolTip));
|
||||
@@ -125,8 +125,8 @@ public sealed class FramesTab : EditorTab
|
||||
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);
|
||||
ToggleExcludeCommand = new RelayCommand(p => ToggleExcluded(p is FrameRow row ? row.Index : Editor.CurrentIndex), _ => !Editor.IsLocked);
|
||||
SetHeroCommand = new RelayCommand(p => Editor.Session.SetHero(p is FrameRow row ? row.Index : Editor.CurrentIndex), _ => !Editor.IsLocked);
|
||||
SeekCommand = new RelayCommand(p =>
|
||||
{
|
||||
if (p is FindingItem { Frame: { } frame }) Editor.CurrentIndex = frame;
|
||||
@@ -179,10 +179,10 @@ public sealed class FramesTab : EditorTab
|
||||
|
||||
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");
|
||||
public string CurrentExcludeToolTip => Editor.LockedToolTip ?? Loc.L(IsCurrentExcluded ? "Tooltips.Editor.Frames.Include" : "Tooltips.Editor.Frames.Exclude");
|
||||
|
||||
/// <summary>What Set hero does, or why it waits.</summary>
|
||||
public string HeroToolTip => Loc.L(Editor.IsBusy ? "Tooltips.Editor.Busy" : "Tooltips.Editor.Frames.Hero");
|
||||
public string HeroToolTip => Editor.LockedToolTip ?? Loc.L("Tooltips.Editor.Frames.Hero");
|
||||
|
||||
public override bool CanReset => false;
|
||||
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
|
||||
namespace Titano.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// The server calls the editor of a server sequence makes (BRIEF §14.3): the sequence and its settings with their
|
||||
/// version, the analysis report, jobs and events. Failures are <see cref="TitanoApiException"/>s (404 gone, 409 settings
|
||||
/// changed meanwhile) or network exceptions. The editor disposes its connection when it closes.
|
||||
/// </summary>
|
||||
public interface IRemoteSequenceApi : IDisposable
|
||||
{
|
||||
Task<SequenceDto> GetSequenceAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The settings JSON and its version, the frames and the renders.</summary>
|
||||
Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>A 409 <see cref="TitanoApiException"/> means the settings version moved on the server.</summary>
|
||||
Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>The full deep-analysis report (<c>analysis.json</c>); null when the sequence was never deep-analysed.</summary>
|
||||
Task<string?> GetAnalysisReportAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
Task<JobDto> CreateJobAsync(CreateJobRequest request, CancellationToken cancellationToken);
|
||||
|
||||
Task<JobDto> GetJobAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Every analysis and render job waiting, running or paused on the server (all pages).</summary>
|
||||
Task<IReadOnlyList<JobDto>> ListActiveJobsAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Cancels a waiting or running job; returns it as the server now has it.</summary>
|
||||
Task<JobDto> CancelJobAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Queues a failed or cancelled job again from its checkpoint; returns it as the server now has it.</summary>
|
||||
Task<JobDto> RetryJobAsync(Guid id, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Moves a waiting job up or down the queue (<paramref name="priority"/>: background, normal or user).</summary>
|
||||
Task<JobDto> SetJobPriorityAsync(Guid id, string priority, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Server events until cancelled or the socket closes.</summary>
|
||||
IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -9,11 +9,37 @@ 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.
|
||||
/// client is connected to (<see cref="RemoteSequenceSource"/>: proxies from the cache, project and jobs through the
|
||||
/// API). The editor reads frames, saves the project, queues jobs and follows them only through this interface.
|
||||
/// </summary>
|
||||
public interface ISequenceSource : IAsyncDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// The sequence lives on a server (BRIEF §14.5 "edit with proxies, render where the originals are"): its project is
|
||||
/// saved there and its renders and analyses run there, one job per preset.
|
||||
/// </summary>
|
||||
bool IsRemote { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The project is shown, not changed: a server sequence for an account without the Edit right, or one whose frames
|
||||
/// changed on the server (<see cref="IsOutdated"/>). The editor disables every change and the source refuses to
|
||||
/// store one. It can turn true while the sequence is open (<see cref="ReadOnlyChanged"/>).
|
||||
/// </summary>
|
||||
bool IsReadOnly { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The frames this PC shows are no longer the sequence's (frames added or removed on the server since its proxies
|
||||
/// were fetched): frame positions in the project would point at other frames, so nothing is saved or rendered until
|
||||
/// the sequence is opened again with fresh proxies.
|
||||
/// </summary>
|
||||
bool IsOutdated { get; }
|
||||
|
||||
/// <summary><see cref="IsReadOnly"/> changed (any thread).</summary>
|
||||
event Action? ReadOnlyChanged;
|
||||
|
||||
/// <summary>A job that may concern the sequence changed (any thread): this PC's engine, or the server's events.</summary>
|
||||
event Action<Job>? JobChanged;
|
||||
|
||||
/// <summary>Everything the editor shows of the sequence; read off the UI thread.</summary>
|
||||
/// <exception cref="InvalidDataException">The project cannot be read (corrupt, or written by a newer Titano).</exception>
|
||||
Task<SequenceContent> LoadAsync(CancellationToken cancellationToken);
|
||||
@@ -33,6 +59,15 @@ public interface ISequenceSource : IAsyncDisposable
|
||||
|
||||
/// <summary>Queues an analysis or render job for the sequence; returns the job id.</summary>
|
||||
Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Recent jobs that may concern the sequence (queued, running, finished), for the busy state and the cost of Analyse.</summary>
|
||||
Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Cancels a job of the sequence that waits or runs; its new state arrives through <see cref="JobChanged"/>.</summary>
|
||||
Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Queues a failed or cancelled job of the sequence again from its checkpoint.</summary>
|
||||
Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>A sequence as the editor opens it.</summary>
|
||||
@@ -41,7 +76,8 @@ public interface ISequenceSource : IAsyncDisposable
|
||||
/// <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>
|
||||
/// <param name="Renders">Finished renders, newest first (an empty output path when the file is not on this PC).</param>
|
||||
/// <param name="SavedCopies">This PC's projects kept by "Save both" when a sync conflict was settled, newest first.</param>
|
||||
public sealed record SequenceContent(
|
||||
Sequence Sequence,
|
||||
IReadOnlyList<Frame> Frames,
|
||||
@@ -51,7 +87,8 @@ public sealed record SequenceContent(
|
||||
int SourceWidth,
|
||||
int SourceHeight,
|
||||
string? ExportsFolder,
|
||||
IReadOnlyList<Render> Renders)
|
||||
IReadOnlyList<Render> Renders,
|
||||
IReadOnlyList<SavedCopy> SavedCopies)
|
||||
{
|
||||
/// <summary>Flags of frames that never reach a render (as the render job skips them).</summary>
|
||||
public const FrameFlags NotRendered = FrameFlags.Missing | FrameFlags.Corrupt | FrameFlags.Excluded | FrameFlags.Undecodable;
|
||||
|
||||
@@ -20,33 +20,67 @@ 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.
|
||||
/// project in <c>.titano/project.json</c> mirrored in the index's settings column (with its hero frame, which the
|
||||
/// Library shows), jobs on this PC's engine. Project writes follow the archive engine's protocol: under the sequence's
|
||||
/// lease file (so the server and the job engine wait for it), file first (atomically), then the index with its settings
|
||||
/// version as an optimistic check.
|
||||
/// </summary>
|
||||
public sealed class LocalSequenceSource(TitanoDatabase db, Guid sequenceId, ImageDecoder decoder, JobEngine? engine, ArchiveServiceOptions? lease = null)
|
||||
: ISequenceSource
|
||||
public sealed class LocalSequenceSource : ISequenceSource
|
||||
{
|
||||
private const int PageSize = 1000;
|
||||
private const int SaveAttempts = 3;
|
||||
private const int JobsListed = 200;
|
||||
|
||||
private readonly ArchiveServiceOptions _lease = lease ?? new ArchiveServiceOptions();
|
||||
private readonly TitanoDatabase _db;
|
||||
private readonly Guid _sequenceId;
|
||||
private readonly ImageDecoder _decoder;
|
||||
private readonly JobEngine? _engine;
|
||||
private readonly ArchiveServiceOptions _lease;
|
||||
private string?[] _files = [];
|
||||
private Guid[] _frameIds = [];
|
||||
private ArchivePaths? _paths;
|
||||
private SequencePaths? _folder;
|
||||
|
||||
public LocalSequenceSource(TitanoDatabase db, Guid sequenceId, ImageDecoder decoder, JobEngine? engine, ArchiveServiceOptions? lease = null)
|
||||
{
|
||||
_db = db;
|
||||
_sequenceId = sequenceId;
|
||||
_decoder = decoder;
|
||||
_engine = engine;
|
||||
_lease = lease ?? new ArchiveServiceOptions();
|
||||
if (engine is not null) engine.JobChanged += OnJobChanged;
|
||||
}
|
||||
|
||||
public bool IsRemote => false;
|
||||
|
||||
public bool IsReadOnly => false;
|
||||
|
||||
public bool IsOutdated => false;
|
||||
|
||||
/// <summary>A sequence of this PC is never read-only.</summary>
|
||||
public event Action? ReadOnlyChanged
|
||||
{
|
||||
add { }
|
||||
remove { }
|
||||
}
|
||||
|
||||
public event Action<Job>? JobChanged;
|
||||
|
||||
/// <summary>A save changed the frame the Library shows for the sequence: the stored row (any thread).</summary>
|
||||
public event Action<Sequence>? HeroChanged;
|
||||
|
||||
public async Task<SequenceContent> LoadAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken) ?? throw Missing();
|
||||
var archive = await db.Archives.GetAsync(sequence.ArchiveId, cancellationToken) ?? throw Missing();
|
||||
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);
|
||||
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);
|
||||
var renders = await _db.Renders.ListBySequenceAsync(_sequenceId, cancellationToken);
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
var paths = new ArchivePaths(archive.RootPath);
|
||||
@@ -56,10 +90,10 @@ public sealed class LocalSequenceSource(TitanoDatabase db, Guid sequenceId, Imag
|
||||
{
|
||||
if ((frames[i].Flags & FrameFlags.Missing) == 0) files[i] = paths.FromRelative(frames[i].RelativePath);
|
||||
}
|
||||
(_paths, _folder, _files) = (paths, folder, files);
|
||||
(_paths, _folder, _files, _frameIds) = (paths, folder, files, [.. frames.Select(f => f.Id)]);
|
||||
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)]);
|
||||
context.SourceWidth, context.SourceHeight, folder.Exports, [.. renders.OrderByDescending(r => r.Created)], SavedCopies.List(folder.MetaDirectory));
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
@@ -72,7 +106,7 @@ public sealed class LocalSequenceSource(TitanoDatabase db, Guid sequenceId, Imag
|
||||
{
|
||||
// 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;
|
||||
return _decoder.Decode(request, cancellationToken)?.Pixels;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
@@ -86,25 +120,27 @@ public sealed class LocalSequenceSource(TitanoDatabase db, Guid sequenceId, Imag
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
var (paths, folder) = (_paths, _folder);
|
||||
var (paths, folder, frameIds) = (_paths, _folder, _frameIds);
|
||||
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,
|
||||
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 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);
|
||||
var edit = new SequenceEdit { SettingsJson = json, HeroFrameId = merged.HeroFrame == stored.HeroFrame ? null : HeroFrameId(merged, frameIds) };
|
||||
var result = await _db.Sequences.EditAsync(_sequenceId, edit, row.SettingsVersion, cancellationToken);
|
||||
switch (result.Outcome)
|
||||
{
|
||||
case SequenceEditOutcome.Updated:
|
||||
if (result.Sequence is { } updated && updated.HeroFrameId != row.HeroFrameId) HeroChanged?.Invoke(updated);
|
||||
return merged;
|
||||
case SequenceEditOutcome.NotFound:
|
||||
throw Missing();
|
||||
@@ -118,12 +154,25 @@ public sealed class LocalSequenceSource(TitanoDatabase db, Guid sequenceId, Imag
|
||||
|
||||
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);
|
||||
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;
|
||||
public async Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken) =>
|
||||
(await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items;
|
||||
|
||||
public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) =>
|
||||
(_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).CancelAsync(jobId, cancellationToken);
|
||||
|
||||
public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) =>
|
||||
(_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).ResumeAsync(jobId, cancellationToken);
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
if (_engine is not null) _engine.JobChanged -= OnJobChanged;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>The 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>
|
||||
@@ -141,6 +190,10 @@ public sealed class LocalSequenceSource(TitanoDatabase db, Guid sequenceId, Imag
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The frame of the project's hero, or <see cref="Guid.Empty"/> (the first frame shows) without one.</summary>
|
||||
private static Guid HeroFrameId(ProjectSettings project, Guid[] frameIds) =>
|
||||
project.HeroFrame is { } hero && (uint)hero < (uint)frameIds.Length ? frameIds[hero] : Guid.Empty;
|
||||
|
||||
/// <summary>The saved deep report when it describes the current frames.</summary>
|
||||
private static DeepAnalysisReport? ReadReport(SequencePaths folder, int frameCount)
|
||||
{
|
||||
@@ -157,5 +210,7 @@ public sealed class LocalSequenceSource(TitanoDatabase db, Guid sequenceId, Imag
|
||||
}
|
||||
}
|
||||
|
||||
private void OnJobChanged(Job job) => JobChanged?.Invoke(job);
|
||||
|
||||
private static InvalidOperationException Missing() => new(Loc.L("Editor.Error.Missing"));
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Data.Sync;
|
||||
|
||||
namespace Titano.App.Editor;
|
||||
|
||||
@@ -7,7 +8,8 @@ namespace Titano.App.Editor;
|
||||
/// 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).
|
||||
/// member both changed takes the editor's (the user is looking at it). <see cref="Conflicts"/> lists those members for
|
||||
/// a source that asks the user instead (a server sequence, BRIEF §14.5).
|
||||
/// </summary>
|
||||
public static class ProjectMerge
|
||||
{
|
||||
@@ -19,6 +21,20 @@ public static class ProjectMerge
|
||||
return new Rebase(basis, theirs).Apply(ours);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The members both sides changed to different values, in document order: the path below the project
|
||||
/// ("exposure.deflickerWindow.manual"), the editor's value and theirs as JSON (null when absent).
|
||||
/// </summary>
|
||||
public static IReadOnlyList<SettingsDifference> Conflicts(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
ArgumentNullException.ThrowIfNull(ours);
|
||||
ArgumentNullException.ThrowIfNull(theirs);
|
||||
var conflicts = new List<SettingsDifference>();
|
||||
Collect(JsonNode.Parse(basis.ToJson()), JsonNode.Parse(ours.ToJson()), JsonNode.Parse(theirs.ToJson()), string.Empty, conflicts);
|
||||
return conflicts;
|
||||
}
|
||||
|
||||
/// <summary>True when both projects store the same values.</summary>
|
||||
public static bool SameValues(ProjectSettings a, ProjectSettings b) => a.ToJson() == b.ToJson();
|
||||
|
||||
@@ -37,6 +53,20 @@ public static class ProjectMerge
|
||||
return merged;
|
||||
}
|
||||
|
||||
/// <summary>The members <see cref="Merge(JsonNode?, JsonNode?, JsonNode?)"/> settles for the editor although both sides changed them.</summary>
|
||||
private static void Collect(JsonNode? basis, JsonNode? ours, JsonNode? theirs, string path, List<SettingsDifference> conflicts)
|
||||
{
|
||||
if (JsonNode.DeepEquals(ours, basis) || JsonNode.DeepEquals(theirs, basis) || JsonNode.DeepEquals(theirs, ours)) return;
|
||||
if (ours is JsonObject mine && theirs is JsonObject other)
|
||||
{
|
||||
var common = basis as JsonObject;
|
||||
foreach (var name in mine.Select(p => p.Key).Union(other.Select(p => p.Key)))
|
||||
Collect(common?[name], mine[name], other[name], path.Length == 0 ? name : path + "." + name, conflicts);
|
||||
return;
|
||||
}
|
||||
conflicts.Add(new SettingsDifference(path.Length == 0 ? "settings" : path, ours?.ToJsonString(), theirs?.ToJsonString()));
|
||||
}
|
||||
|
||||
/// <summary>One outside change (<paramref name="basis"/> → <paramref name="theirs"/>) applied to any number of projects made from the basis.</summary>
|
||||
public sealed class Rebase(ProjectSettings basis, ProjectSettings theirs)
|
||||
{
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.Json;
|
||||
using Titano.Core.Advice;
|
||||
using Titano.Core.Analysis;
|
||||
using Titano.Core.Analysis.Deep;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Imaging;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Core.Render;
|
||||
using Titano.Data.Archiving.Jobs;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
|
||||
namespace Titano.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// A server sequence opened with proxies (BRIEF §4.4, §14.5 "edit with proxies, render where the originals are"):
|
||||
/// frames and thumbnails from this PC's proxy cache (<see cref="RemoteSequence.OpenFrames"/>), the project from the
|
||||
/// server's settings with their version, the deep analysis from the server's report. Saves send the settings with the
|
||||
/// version they were made from; a 409 (someone changed them meanwhile) reads the server's settings and merges again
|
||||
/// (<see cref="ProjectMerge"/>) when the two changes touch different settings. A setting both changed to different
|
||||
/// values is a conflict the user settles (BRIEF §14.5 "explicit conflict prompt"): <see cref="ProjectConflictException"/>,
|
||||
/// and nothing is sent until the editor's next save names the server's settings as its basis. Nothing is written to a
|
||||
/// local archive. Analyses and renders are server jobs; their state and progress come from the server's events.
|
||||
/// Project settings name frames by position, so the cached frames must be the server's: a load that finds other frames
|
||||
/// throws <see cref="ProxiesOutdatedException"/>, and frames that change on the server while the sequence is open make
|
||||
/// it <see cref="IsOutdated"/> (read-only, nothing saved or rendered).
|
||||
/// </summary>
|
||||
public sealed class RemoteSequenceSource : ISequenceSource
|
||||
{
|
||||
private const int SaveAttempts = 3;
|
||||
private static readonly TimeSpan MinBackoff = TimeSpan.FromSeconds(2);
|
||||
private static readonly TimeSpan MaxBackoff = TimeSpan.FromMinutes(1);
|
||||
|
||||
private readonly RemoteSequence _remote;
|
||||
private readonly IRemoteSequenceApi _api;
|
||||
private readonly IRenderFrameSource _frames;
|
||||
private readonly IFrameSource _pixels;
|
||||
private readonly ConcurrentDictionary<Guid, Job> _jobs = new();
|
||||
private readonly ConcurrentDictionary<Guid, byte> _foreign = new();
|
||||
private readonly CancellationTokenSource _stopping = new();
|
||||
private readonly Task _listening;
|
||||
private readonly bool _noEditRight;
|
||||
private Stored? _stored;
|
||||
private int _framesVersion = -1;
|
||||
private int _outdated;
|
||||
private int _disposed;
|
||||
|
||||
/// <param name="readOnly">The account may look at the sequence but not change it (no Edit right on the server).</param>
|
||||
public RemoteSequenceSource(RemoteSequence remote, IRemoteSequenceApi api, ImageDecoder decoder, bool readOnly = false)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(remote);
|
||||
ArgumentNullException.ThrowIfNull(api);
|
||||
ArgumentNullException.ThrowIfNull(decoder);
|
||||
_remote = remote;
|
||||
_api = api;
|
||||
_noEditRight = readOnly;
|
||||
_frames = remote.OpenFrames(decoder);
|
||||
_pixels = (IFrameSource)_frames;
|
||||
var stopping = _stopping.Token;
|
||||
_listening = Task.Run(() => ListenAsync(stopping), CancellationToken.None);
|
||||
}
|
||||
|
||||
public bool IsRemote => true;
|
||||
|
||||
public bool IsReadOnly => _noEditRight || IsOutdated;
|
||||
|
||||
public bool IsOutdated => Volatile.Read(ref _outdated) == 1;
|
||||
|
||||
public event Action? ReadOnlyChanged;
|
||||
|
||||
public event Action<Job>? JobChanged;
|
||||
|
||||
/// <summary>The server sequence's id.</summary>
|
||||
public Guid Id => _remote.Sequence.Id;
|
||||
|
||||
public async Task<SequenceContent> LoadAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var dto = await Call(() => _api.GetSequenceAsync(Id, cancellationToken));
|
||||
var manifest = await Call(() => _api.GetManifestAsync(Id, cancellationToken));
|
||||
if (!SameFrames(manifest)) throw Outdated();
|
||||
Volatile.Write(ref _framesVersion, manifest.FramesVersion);
|
||||
var report = await Call(() => _api.GetAnalysisReportAsync(Id, cancellationToken));
|
||||
return await Task.Run(() =>
|
||||
{
|
||||
var project = Parse(manifest.SettingsJson);
|
||||
Volatile.Write(ref _stored, new Stored(project, manifest.SettingsVersion));
|
||||
var frames = _remote.Frames;
|
||||
var sequence = _remote.Sequence with
|
||||
{
|
||||
Title = dto.Title,
|
||||
Tags = dto.Tags,
|
||||
Rating = dto.Rating,
|
||||
Notes = dto.Notes,
|
||||
Status = (SequenceStatus)dto.Status,
|
||||
RenderedCount = dto.RenderedCount,
|
||||
HeroFrameId = dto.HeroFrameId,
|
||||
WarningCount = dto.WarningCount,
|
||||
SettingsJson = manifest.SettingsJson,
|
||||
SettingsVersion = manifest.SettingsVersion,
|
||||
UpdatedAt = dto.UpdatedAt,
|
||||
};
|
||||
var context = SequenceContext.FromFrames(frames);
|
||||
var renders = manifest.Renders.OrderByDescending(r => r.Created).Select(r => new Render
|
||||
{
|
||||
Id = r.Id,
|
||||
SequenceId = Id,
|
||||
PresetName = r.PresetName,
|
||||
OutputPath = string.Empty,
|
||||
Codec = r.Codec,
|
||||
Width = r.Width,
|
||||
Height = r.Height,
|
||||
Fps = r.Fps,
|
||||
DurationSeconds = r.DurationSeconds,
|
||||
Bytes = r.Bytes,
|
||||
Created = r.Created,
|
||||
ProducedBy = r.ProducedBy,
|
||||
}).ToList();
|
||||
return new SequenceContent(sequence, frames, project, LightAnalyzer.Analyze(frames), Report(report, frames.Count), context.SourceWidth,
|
||||
context.SourceHeight, null, renders, []);
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
|
||||
{
|
||||
if ((uint)index >= (uint)_remote.Frames.Count) return null;
|
||||
return await Task.Run(() => _pixels.LoadAsync(index, maxLongEdge, cancellationToken).AsTask(), cancellationToken);
|
||||
}
|
||||
|
||||
public async Task<ProjectSettings> SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(project);
|
||||
ArgumentNullException.ThrowIfNull(basis);
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
var (stored, version) = Volatile.Read(ref _stored) ?? throw new InvalidOperationException("LoadAsync first.");
|
||||
var changedThere = !ProjectMerge.SameValues(stored, basis);
|
||||
var merged = changedThere ? ProjectMerge.Merge(basis, project, stored) : project;
|
||||
if (ProjectMerge.SameValues(merged, stored)) return merged;
|
||||
if (IsOutdated) throw new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged"));
|
||||
if (_noEditRight) throw new InvalidOperationException(Loc.L("Editor.Error.RemoteReadOnly"));
|
||||
if (changedThere && ProjectMerge.Conflicts(basis, project, stored) is { Count: > 0 } conflicts)
|
||||
throw new ProjectConflictException(Loc.L("Editor.Error.SaveConflict"), stored, conflicts);
|
||||
var hero = merged.HeroFrame == stored.HeroFrame ? (Guid?)null : HeroFrameId(merged);
|
||||
try
|
||||
{
|
||||
var updated = await Call(() => _api.UpdateSequenceAsync(Id, new UpdateSequenceRequest(null, null, null, null, merged.ToJson(), version, hero),
|
||||
cancellationToken));
|
||||
Volatile.Write(ref _stored, new Stored(merged, updated.SettingsVersion));
|
||||
return merged;
|
||||
}
|
||||
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
|
||||
{
|
||||
// Changed on the server since this editor read it: merge again on top of the server's settings.
|
||||
if (attempt == SaveAttempts) throw new IOException(Loc.L("Editor.Error.SaveConflict"), ex);
|
||||
var manifest = await Call(() => _api.GetManifestAsync(Id, cancellationToken));
|
||||
if (!SameFrames(manifest)) throw Outdated();
|
||||
Volatile.Write(ref _stored, new Stored(Parse(manifest.SettingsJson), manifest.SettingsVersion));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <remarks>
|
||||
/// The server queues every job at the user's priority; another priority ("Add to queue") is set right after. A
|
||||
/// render embeds the project, whose frame positions mean nothing once the frames changed: refused while outdated.
|
||||
/// </remarks>
|
||||
public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(request);
|
||||
if (request.Kind == JobKind.Render && IsOutdated) throw new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged"));
|
||||
var dto = await Call(() => _api.CreateJobAsync(new CreateJobRequest(JobWire.Kind(request.Kind), request.Targets, request.ParametersJson), cancellationToken));
|
||||
if (request.Priority != JobPriority.User) dto = await PrioritiseAsync(dto, request.Priority, cancellationToken);
|
||||
// The server's events may have reported the job already; its first state never replaces a later one.
|
||||
if (JobWire.FromDto(dto) is { } job && _jobs.TryAdd(job.Id, job)) JobChanged?.Invoke(job);
|
||||
return dto.Id;
|
||||
}
|
||||
|
||||
public async Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var active = await Call(() => _api.ListActiveJobsAsync(cancellationToken));
|
||||
var mine = active.Select(JobWire.FromDto).OfType<Job>().Where(Concerns).ToList();
|
||||
foreach (var job in mine) _jobs[job.Id] = job;
|
||||
return mine;
|
||||
}
|
||||
|
||||
public async Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (JobWire.FromDto(await _api.CancelJobAsync(jobId, cancellationToken)) is { } job) Publish(job);
|
||||
}
|
||||
|
||||
public async Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (JobWire.FromDto(await _api.RetryJobAsync(jobId, cancellationToken)) is { } job) Publish(job);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 1) return;
|
||||
try
|
||||
{
|
||||
await _stopping.CancelAsync();
|
||||
await _listening;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_stopping.Dispose();
|
||||
if (_frames is IAsyncDisposable frames) await frames.DisposeAsync();
|
||||
_api.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Follows the server's events until the editor closes, reconnecting with a growing delay (job states lost meanwhile
|
||||
/// are read back from the jobs). Nothing that fails on the way ends it.
|
||||
/// </summary>
|
||||
private async Task ListenAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var failures = 0;
|
||||
while (true)
|
||||
{
|
||||
try
|
||||
{
|
||||
await foreach (var e in _api.EventsAsync(cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
failures = 0;
|
||||
await OnEventAsync(e, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested) return;
|
||||
Log.Info("editor", $"Events of the server lost for {_remote.Sequence.DisplayTitle}: {ex.Message}");
|
||||
}
|
||||
try
|
||||
{
|
||||
var delay = Math.Min(MaxBackoff.Ticks, MinBackoff.Ticks << Math.Min(failures++, 10));
|
||||
await Task.Delay(TimeSpan.FromTicks(delay), cancellationToken).ConfigureAwait(false);
|
||||
await RefreshTrackedAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
if (cancellationToken.IsCancellationRequested) return;
|
||||
Log.Info("editor", $"Jobs of {_remote.Sequence.DisplayTitle} could not be read again: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task OnEventAsync(ServerEvent e, CancellationToken cancellationToken)
|
||||
{
|
||||
switch (e)
|
||||
{
|
||||
case SequenceChangedEvent changed when changed.SequenceId == Id && changed.FramesVersion != Volatile.Read(ref _framesVersion):
|
||||
await CheckFramesAsync(cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
// A late progress event never brings a finished job back to running.
|
||||
case JobProgressEvent progress when _jobs.TryGetValue(progress.JobId, out var job) && job.State is JobState.Queued or JobState.Running:
|
||||
Publish(job with
|
||||
{
|
||||
State = JobState.Running,
|
||||
ProgressDone = progress.Done,
|
||||
ProgressTotal = progress.Total,
|
||||
ItemsPerSecond = progress.ItemsPerSecond,
|
||||
Eta = progress.EtaSeconds is { } eta ? TimeSpan.FromSeconds(eta) : null,
|
||||
});
|
||||
break;
|
||||
case JobStateEvent state when !_foreign.ContainsKey(state.JobId):
|
||||
await FetchAsync(state.JobId, cancellationToken).ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads a job the events named: tracked when it concerns this sequence, remembered as foreign otherwise.</summary>
|
||||
private async Task FetchAsync(Guid jobId, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (JobWire.FromDto(await _api.GetJobAsync(jobId, cancellationToken).ConfigureAwait(false)) is { } job && Concerns(job)) Publish(job);
|
||||
else _foreign[jobId] = 0;
|
||||
}
|
||||
catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or JsonException
|
||||
|| (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
|
||||
{
|
||||
Log.Info("editor", $"Job {jobId} could not be read: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Frames added or removed on the server: whether this PC's frames are still the sequence's.</summary>
|
||||
private async Task CheckFramesAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var manifest = await _api.GetManifestAsync(Id, cancellationToken).ConfigureAwait(false);
|
||||
if (SameFrames(manifest)) Volatile.Write(ref _framesVersion, manifest.FramesVersion);
|
||||
else MarkOutdated();
|
||||
}
|
||||
catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or JsonException
|
||||
|| (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested))
|
||||
{
|
||||
Log.Info("editor", $"The frames of {_remote.Sequence.DisplayTitle} could not be compared: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Sets a priority other than the user's on a job the server just queued; the job stays queued if that fails.</summary>
|
||||
private async Task<JobDto> PrioritiseAsync(JobDto dto, JobPriority priority, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await _api.SetJobPriorityAsync(dto.Id, JobWire.Priority(priority), cancellationToken);
|
||||
}
|
||||
catch (Exception ex) when (ex is TitanoApiException or HttpRequestException)
|
||||
{
|
||||
// Already claimed (409) or refused: the job runs at the user's priority, which is never later than asked.
|
||||
Log.Info("editor", $"Job {dto.Id} keeps the user's priority on the server: {ex.Message}");
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>After a lost event socket: the tracked jobs as the server has them now.</summary>
|
||||
private async Task RefreshTrackedAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var job in _jobs.Values.Where(j => j.State is JobState.Queued or JobState.Running or JobState.Paused).ToList())
|
||||
await FetchAsync(job.Id, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private void Publish(Job job)
|
||||
{
|
||||
_jobs[job.Id] = job;
|
||||
JobChanged?.Invoke(job);
|
||||
}
|
||||
|
||||
/// <summary>The server's frames are the cached ones, in the same order (frame positions in the project mean the same frames).</summary>
|
||||
private bool SameFrames(SequenceManifest manifest) =>
|
||||
manifest.Frames.OrderBy(f => f.Index).Select(f => f.Id).SequenceEqual(_remote.Frames.Select(f => f.Id));
|
||||
|
||||
/// <summary>The frames changed on the server: from now on the project is only shown.</summary>
|
||||
private ProxiesOutdatedException Outdated()
|
||||
{
|
||||
MarkOutdated();
|
||||
return new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged"));
|
||||
}
|
||||
|
||||
private void MarkOutdated()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _outdated, 1) == 1) return;
|
||||
Log.Info("editor", $"The frames of {_remote.Sequence.DisplayTitle} changed on the server; its proxies are out of date");
|
||||
ReadOnlyChanged?.Invoke();
|
||||
}
|
||||
|
||||
private bool Concerns(Job job) => job.TargetIds.Contains(Id) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
|
||||
|
||||
/// <summary>The frame of the project's hero, or <see cref="Guid.Empty"/> (the first frame shows) without one.</summary>
|
||||
private Guid HeroFrameId(ProjectSettings project) =>
|
||||
project.HeroFrame is { } hero && (uint)hero < (uint)_remote.Frames.Count ? _remote.Frames[hero].Id : Guid.Empty;
|
||||
|
||||
/// <exception cref="InvalidDataException">The settings are not a project or come from a newer Titano.</exception>
|
||||
private static ProjectSettings Parse(string? json)
|
||||
{
|
||||
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 server's deep report when it describes the frames this PC has.</summary>
|
||||
private DeepAnalysisReport? Report(string? json, int frameCount)
|
||||
{
|
||||
if (json is null) return null;
|
||||
try
|
||||
{
|
||||
var report = DeepAnalysisReport.FromJson(json);
|
||||
return report.FrameCount == frameCount ? report : null;
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or InvalidDataException)
|
||||
{
|
||||
Log.Warning("editor", $"The analysis of {_remote.Sequence.DisplayTitle} on the server cannot be read", ex);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A sequence deleted on the server reads as gone, like a local one removed from the index.</summary>
|
||||
private static async Task<T> Call<T>(Func<Task<T>> call)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await call();
|
||||
}
|
||||
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
|
||||
{
|
||||
throw new InvalidOperationException(Loc.L("Editor.Error.Missing"), ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The server's settings as last read or written, with the version a save must name.</summary>
|
||||
private sealed record Stored(ProjectSettings Project, int Version);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Settings the editor changed were changed to other values on the server meanwhile (BRIEF §14.5): nothing is saved
|
||||
/// until the user keeps the editor's values or takes the server's (<see cref="EditorSession.ResolveConflict"/>).
|
||||
/// </summary>
|
||||
/// <param name="server">The server's project now.</param>
|
||||
/// <param name="differences">The settings both changed: the editor's value, then the server's.</param>
|
||||
public sealed class ProjectConflictException(string message, ProjectSettings server, IReadOnlyList<SettingsDifference> differences) : IOException(message)
|
||||
{
|
||||
public ProjectSettings Server { get; } = server;
|
||||
|
||||
public IReadOnlyList<SettingsDifference> Differences { get; } = differences;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The proxies of a server sequence are for frames the server no longer has (added or removed since they were fetched):
|
||||
/// they must be fetched again before the sequence can be edited.
|
||||
/// </summary>
|
||||
public sealed class ProxiesOutdatedException(string message) : IOException(message);
|
||||
@@ -0,0 +1,51 @@
|
||||
using System.IO;
|
||||
using System.Text.Json;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Data.Sync;
|
||||
|
||||
namespace Titano.App.Editor;
|
||||
|
||||
/// <summary>This PC's project kept by "Save both" when a sync conflict was settled (BRIEF §12.7), local time of the choice.</summary>
|
||||
public sealed record SavedCopy(string Path, DateTime SavedAt)
|
||||
{
|
||||
/// <summary>"03/10/2026 14:22" in the user's format.</summary>
|
||||
public string Label => SavedAt.ToString("g", Loc.Culture);
|
||||
}
|
||||
|
||||
/// <summary>The "Save both" copies of a sequence: <c>.titano/project.this-pc-<time>.json</c> beside <c>project.json</c>.</summary>
|
||||
public static class SavedCopies
|
||||
{
|
||||
/// <summary>The copies in a sequence's <c>.titano</c> folder, newest first; none when the folder cannot be read.</summary>
|
||||
public static IReadOnlyList<SavedCopy> List(string metaDirectory)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(metaDirectory)) return [];
|
||||
return [.. Directory.EnumerateFiles(metaDirectory, SyncService.SavedCopyPattern)
|
||||
.Select(path => new SavedCopy(path, SyncService.SavedCopyTime(path) ?? File.GetLastWriteTime(path)))
|
||||
.OrderByDescending(c => c.SavedAt)];
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("editor", $"The saved projects in {metaDirectory} cannot be listed", ex);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The project of a copy.</summary>
|
||||
/// <exception cref="InvalidDataException">The copy is gone, unreadable, or not a project of this Titano.</exception>
|
||||
public static ProjectSettings Read(SavedCopy copy)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(copy);
|
||||
try
|
||||
{
|
||||
return ProjectSettings.FromJson(File.ReadAllText(copy.Path));
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException)
|
||||
{
|
||||
throw new InvalidDataException(Loc.L("Editor.Error.SavedCopy", System.IO.Path.GetFileName(copy.Path)), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
using Titano.Core.Model;
|
||||
|
||||
namespace Titano.App.Editor;
|
||||
|
||||
/// <summary>
|
||||
/// The analyses and renders of the open sequence that wait, run or are paused, as the source reports them (BRIEF §12.3
|
||||
/// "while a job runs on this sequence, settings are disabled", §11.5): the editor's busy lock, whether Analyse would
|
||||
/// queue a second analysis, and the server job the header of a server sequence shows. Call from one thread.
|
||||
/// </summary>
|
||||
public sealed class SequenceJobs(Guid sequenceId)
|
||||
{
|
||||
private readonly Dictionary<Guid, Job> _active = [];
|
||||
|
||||
/// <summary>An analysis or render runs: settings wait.</summary>
|
||||
public bool IsBusy => _active.Values.Any(j => j.State == JobState.Running);
|
||||
|
||||
/// <summary>A deep analysis waits, runs or is paused.</summary>
|
||||
public bool IsAnalysing => _active.Values.Any(j => j.Kind == JobKind.DeepAnalyse);
|
||||
|
||||
/// <summary>The job to show: one running, else one paused, else the oldest waiting; null when there is none.</summary>
|
||||
public Job? Shown => _active.Values
|
||||
.OrderBy(j => j.State switch { JobState.Running => 0, JobState.Paused => 1, _ => 2 })
|
||||
.ThenBy(j => j.Started ?? j.Created)
|
||||
.FirstOrDefault();
|
||||
|
||||
/// <summary>An analysis or render of this sequence.</summary>
|
||||
public bool Concerns(Job job)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(job);
|
||||
return job.TargetIds.Contains(sequenceId) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
|
||||
}
|
||||
|
||||
/// <summary>The job is one of those that wait, run or are paused.</summary>
|
||||
public bool IsActive(Guid jobId) => _active.ContainsKey(jobId);
|
||||
|
||||
/// <summary>Takes in a job's new state.</summary>
|
||||
/// <returns>Whether a job joined or left the active ones or changed state; progress alone does not count.</returns>
|
||||
public bool Track(Job job)
|
||||
{
|
||||
if (!Concerns(job)) return false;
|
||||
if (job.State is not (JobState.Queued or JobState.Running or JobState.Paused)) return _active.Remove(job.Id);
|
||||
var changed = !_active.TryGetValue(job.Id, out var known) || known.State != job.State;
|
||||
_active[job.Id] = job;
|
||||
return changed;
|
||||
}
|
||||
}
|
||||
@@ -255,13 +255,14 @@ public sealed class AppServices : IAsyncDisposable
|
||||
var handlers = CreateJobHandlers(this);
|
||||
var kinds = handlers.Select(h => h.Kind).Distinct().ToArray();
|
||||
Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds });
|
||||
// Sync follows the engine's jobs before it runs any: a render resumed at start that finishes at once is still sent (Export "Sync").
|
||||
Sync.Update();
|
||||
// With no handler the engine must not run: an empty kind list would let workers claim (and fail) every job.
|
||||
var started = startEngine && handlers.Count > 0;
|
||||
if (started) await Engine.StartAsync(ct);
|
||||
Jobs = new EngineJobQueue(database, Engine, started);
|
||||
Log.Info("jobs", started ? $"Job engine started with {Engine.Options.Workers} worker(s) for {string.Join(", ", kinds)}" : "No job handlers registered; jobs stay queued");
|
||||
UpdateRenderNode();
|
||||
Sync.Update();
|
||||
}
|
||||
|
||||
/// <summary>Media Foundation (hardware first, software H.264; hardware as Settings › Rendering allows) then managed
|
||||
|
||||
@@ -47,15 +47,37 @@
|
||||
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}" />
|
||||
<!-- A server sequence edited with proxies: where it lives (read-only or out of date says so) and its analysis or render on the server,
|
||||
before the summary; all of it shares the space the actions leave and ends in an ellipsis. -->
|
||||
<DockPanel Grid.Column="2" VerticalAlignment="Center">
|
||||
<ui:StatusGlyph DockPanel.Dock="Left" Kind="Remote" Text="{Binding RemoteText}" ToolTip="{Binding RemoteToolTip}" FontSize="{StaticResource Size.Body}" Margin="0,0,12,0"
|
||||
MaxWidth="220" VerticalAlignment="Center" Visibility="{Binding IsRemote, Converter={StaticResource BoolToVisibility}}" />
|
||||
<!-- The server job: its bar, what it is and how far (the text gives way first), and Cancel, which always stays (BRIEF §11.5). -->
|
||||
<Grid DockPanel.Dock="Left" Margin="0,0,12,0" MaxWidth="300" VerticalAlignment="Center"
|
||||
Visibility="{Binding ServerJobText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ProgressBar Width="48" Maximum="1" Value="{Binding ServerJobProgress, Mode=OneWay}" VerticalAlignment="Center" Margin="0,0,8,0"
|
||||
AutomationProperties.Name="{Binding ServerJobText}" Visibility="{Binding HasServerJobProgress, Converter={StaticResource BoolToVisibility}}" />
|
||||
<ui:StatusGlyph Grid.Column="1" Kind="{Binding ServerJobKind}" Text="{Binding ServerJobText}" ToolTip="{Binding ServerJobToolTip}"
|
||||
FontSize="{StaticResource Size.Body}" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" />
|
||||
<Button Grid.Column="2" Style="{StaticResource Button.IconSubtle}" Width="26" Height="26" Margin="4,0,0,0" ui:ButtonIcon.Glyph="{StaticResource Icon.Cancel}"
|
||||
Command="{Binding CancelServerJobCommand}" ToolTip="{Binding CancelServerJobToolTip}" ToolTipService.ShowOnDisabled="True"
|
||||
AutomationProperties.Name="{l:Loc Editor.ServerJob.Cancel}" />
|
||||
</Grid>
|
||||
<TextBlock Text="{Binding Summary}" Style="{StaticResource Text.Secondary}" FontSize="{StaticResource Size.Body}" VerticalAlignment="Center"
|
||||
TextTrimming="CharacterEllipsis" Typography.NumeralAlignment="Tabular" ToolTip="{Binding Summary}" />
|
||||
</DockPanel>
|
||||
<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}"
|
||||
ToolTipService.ShowOnDisabled="True" DropDownToolTip="{Binding RenderChoiceToolTip}"
|
||||
AutomationProperties.Name="{l:Loc Editor.RenderButton}" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using System.ComponentModel;
|
||||
using System.Net;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Threading;
|
||||
using Titano.App.Editor;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.App.Shell;
|
||||
@@ -7,22 +9,29 @@ using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Export;
|
||||
using Titano.Core.Imaging.Decoders;
|
||||
using Titano.Core.Localization;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Protocol.Client;
|
||||
using Titano.Ui.Mvvm;
|
||||
|
||||
namespace Titano.App.Sections;
|
||||
|
||||
/// <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.
|
||||
/// The Sequence section (BRIEF §12.3): opens the sequence the Library, Jobs or the Server screen chose into an
|
||||
/// <see cref="EditorViewModel"/> (from this PC's archive, or a server sequence with this PC's proxies) and closes the
|
||||
/// previous one after saving it; without a sequence it shows the empty state. A server sequence whose proxies are
|
||||
/// missing or out of date fetches them first and opens once they are here. 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
|
||||
{
|
||||
private readonly Dispatcher _dispatcher = Dispatcher.CurrentDispatcher;
|
||||
private EditorViewModel? _editor;
|
||||
private Guid? _openId;
|
||||
private bool _isLoading;
|
||||
private Task _switch = Task.CompletedTask;
|
||||
private ProxyFetch? _fetch;
|
||||
|
||||
public SequenceViewModel(ShellViewModel shell)
|
||||
: base(SectionKey.Sequence, "Icon.Sequence")
|
||||
@@ -59,12 +68,36 @@ public sealed class SequenceViewModel : SectionViewModel
|
||||
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)
|
||||
/// <param name="reload">Opens it again even when it is the open one (its proxies were fetched again).</param>
|
||||
public Task OpenAsync(Guid sequenceId, bool reload = false)
|
||||
{
|
||||
_switch = SwitchAsync(_switch, sequenceId);
|
||||
_switch = SwitchAsync(_switch, sequenceId, reload);
|
||||
return _switch;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Fetches the proxies of server sequence <paramref name="remoteId"/> into this PC's cache (a download job, shown in
|
||||
/// the job bar and on the Jobs screen) and opens it in the editor once they are here, if it is still the sequence
|
||||
/// asked for.
|
||||
/// </summary>
|
||||
public async Task FetchProxiesAsync(Guid remoteId, string title)
|
||||
{
|
||||
var services = Shell.Services;
|
||||
var sync = services.Sync;
|
||||
if (sync.Server is not { } server || sync.Service is not { } service) throw new InvalidOperationException(Loc.L("Editor.Error.SignedOut"));
|
||||
if (services.Engine is not { } engine || services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
|
||||
StopFetch();
|
||||
var fetch = new ProxyFetch(remoteId, title, engine);
|
||||
fetch.Handler = job => _dispatcher.BeginInvoke(() => OnFetchChanged(fetch, job));
|
||||
engine.JobChanged += fetch.Handler;
|
||||
_fetch = fetch;
|
||||
var job = await service.EnqueueDownloadAsync(engine, server, remoteId, title, SyncDownloadMode.Proxies, null);
|
||||
fetch.JobId = job.Id;
|
||||
Shell.Notify(Loc.L("Editor.Proxies.Fetching"), title, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
|
||||
// A download that ended before its id was known here is handled now.
|
||||
if (await db.Jobs.GetAsync(job.Id) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } ended) OnFetchChanged(fetch, ended);
|
||||
}
|
||||
|
||||
/// <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).
|
||||
@@ -98,6 +131,7 @@ public sealed class SequenceViewModel : SectionViewModel
|
||||
public override void Dispose()
|
||||
{
|
||||
Shell.PropertyChanged -= OnShellChanged;
|
||||
StopFetch();
|
||||
Editor?.Dispose();
|
||||
base.Dispose();
|
||||
}
|
||||
@@ -112,6 +146,75 @@ public sealed class SequenceViewModel : SectionViewModel
|
||||
if (e.PropertyName == nameof(ShellViewModel.CurrentSequenceId) && IsSelected) OnActivated();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Where <paramref name="sequenceId"/> lives: this PC's index, else a sequence of the signed-in server whose proxies
|
||||
/// this PC keeps (Server screen, "Open with proxies"), edited through the server (BRIEF §14.5), or only shown when the
|
||||
/// account may not change it. Null when the proxies are not here yet: they are being fetched (<see cref="FetchProxiesAsync"/>).
|
||||
/// </summary>
|
||||
private async Task<(ISequenceSource Source, string Title)?> OpenSourceAsync(AppServices services, Guid sequenceId)
|
||||
{
|
||||
if (services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
|
||||
var processing = services.Processing?.Options;
|
||||
var decoder = processing?.Archive.Decoder ?? DecoderFactory.CreateClient(null);
|
||||
if (await db.Sequences.GetAsync(sequenceId) is { } row)
|
||||
{
|
||||
var local = new LocalSequenceSource(db, sequenceId, decoder, services.Engine, processing?.Archive);
|
||||
local.HeroChanged += OnHeroChanged;
|
||||
return (local, row.DisplayTitle);
|
||||
}
|
||||
var sync = services.Sync;
|
||||
if (sync.Server is not { } server || sync.Service is not { } service || sync.ConnectEditor() is not { } api)
|
||||
throw new InvalidOperationException(Loc.L("Editor.Error.SignedOut"));
|
||||
// The proxy cache's index and files are read off the UI thread.
|
||||
if (await Task.Run(() => service.OpenRemote(server, sequenceId)) is { } remote)
|
||||
return (new RemoteSequenceSource(remote, api, decoder, readOnly: !sync.Policy.CanEdit), remote.Sequence.DisplayTitle);
|
||||
using (api)
|
||||
{
|
||||
string title;
|
||||
try
|
||||
{
|
||||
title = (await api.GetSequenceAsync(sequenceId, CancellationToken.None)).DisplayTitle;
|
||||
}
|
||||
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
|
||||
{
|
||||
throw new InvalidOperationException(Loc.L("Editor.Error.Missing"), ex);
|
||||
}
|
||||
await FetchProxiesAsync(sequenceId, title);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The proxy download for an open waiting on it moved: opens the sequence once it is done, says why not when it failed.</summary>
|
||||
private void OnFetchChanged(ProxyFetch fetch, Job job)
|
||||
{
|
||||
if (!ReferenceEquals(fetch, _fetch) || job.Id != fetch.JobId || job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled)) return;
|
||||
StopFetch();
|
||||
switch (job.State)
|
||||
{
|
||||
// Opened only when it is still the sequence asked for; otherwise the next visit opens it from the cache.
|
||||
case JobState.Done when Shell.CurrentSequenceId == fetch.RemoteId && IsSelected:
|
||||
_ = OpenAsync(fetch.RemoteId, reload: true);
|
||||
break;
|
||||
case JobState.Failed:
|
||||
Shell.Notify(Loc.L("Editor.Proxies.Failed"), job.Error ?? fetch.Title, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"),
|
||||
() => Shell.Navigate(SectionKey.Jobs));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void StopFetch()
|
||||
{
|
||||
if (_fetch is not { } fetch) return;
|
||||
_fetch = null;
|
||||
if (fetch.Handler is { } handler) fetch.Engine.JobChanged -= handler;
|
||||
}
|
||||
|
||||
/// <summary>Set hero changed the frame the Library shows (any thread): its card loads the new thumbnail.</summary>
|
||||
private void OnHeroChanged(Sequence row) => _dispatcher.BeginInvoke(() =>
|
||||
{
|
||||
if (Shell.Library.Items.FirstOrDefault(i => i.Id == row.Id) is { } item) item.Update(row);
|
||||
});
|
||||
|
||||
/// <summary>Waits for <paramref name="task"/>; its failure was reported where it happened.</summary>
|
||||
private static async Task Settled(Task task)
|
||||
{
|
||||
@@ -125,10 +228,10 @@ public sealed class SequenceViewModel : SectionViewModel
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SwitchAsync(Task previous, Guid sequenceId)
|
||||
private async Task SwitchAsync(Task previous, Guid sequenceId, bool reload)
|
||||
{
|
||||
await Settled(previous);
|
||||
if (sequenceId == _openId) return;
|
||||
if (sequenceId == _openId && !reload) 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;
|
||||
@@ -142,11 +245,32 @@ public sealed class SequenceViewModel : SectionViewModel
|
||||
await old.DisposeAsync();
|
||||
}
|
||||
_openId = sequenceId;
|
||||
if (services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
|
||||
if (await OpenSourceAsync(services, sequenceId) is not { } opened)
|
||||
{
|
||||
// The proxies are on their way; the sequence opens when they are here.
|
||||
_openId = null;
|
||||
return;
|
||||
}
|
||||
var (source, title) = opened;
|
||||
SequenceContent content;
|
||||
try
|
||||
{
|
||||
content = await source.LoadAsync(CancellationToken.None);
|
||||
}
|
||||
catch (ProxiesOutdatedException)
|
||||
{
|
||||
// The server's frames are no longer these proxies: fetch them again, then open.
|
||||
await source.DisposeAsync();
|
||||
_openId = null;
|
||||
await FetchProxiesAsync(sequenceId, title);
|
||||
return;
|
||||
}
|
||||
catch
|
||||
{
|
||||
await source.DisposeAsync();
|
||||
throw;
|
||||
}
|
||||
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);
|
||||
@@ -167,4 +291,18 @@ public sealed class SequenceViewModel : SectionViewModel
|
||||
OnPropertyChanged(nameof(IsEmpty));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A proxy download an open waits on, with its engine subscription.</summary>
|
||||
private sealed class ProxyFetch(Guid remoteId, string title, JobEngine engine)
|
||||
{
|
||||
public Guid RemoteId { get; } = remoteId;
|
||||
|
||||
public string Title { get; } = title;
|
||||
|
||||
public JobEngine Engine { get; } = engine;
|
||||
|
||||
public Guid JobId { get; set; }
|
||||
|
||||
public Action<Job>? Handler { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
using Titano.App.Editor;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Protocol;
|
||||
using Titano.Protocol.Client;
|
||||
|
||||
namespace Titano.App.Server;
|
||||
|
||||
/// <summary>Makes the connection of the editor of a server sequence for a signed-in session.</summary>
|
||||
public delegate IRemoteSequenceApi RemoteSequenceApiFactory(Uri address, string token, IReadOnlyCollection<string> trustedFingerprints);
|
||||
|
||||
/// <summary><see cref="IRemoteSequenceApi"/> over a signed-in <see cref="TitanoClient"/>, which it owns.</summary>
|
||||
public sealed class TitanoRemoteSequenceApi(TitanoClient client) : IRemoteSequenceApi
|
||||
{
|
||||
private static readonly JobState[] ActiveStates = [JobState.Queued, JobState.Running, JobState.Paused];
|
||||
private static readonly JobKind[] EditorKinds = [JobKind.DeepAnalyse, JobKind.LightAnalyse, JobKind.Render];
|
||||
|
||||
public Task<SequenceDto> GetSequenceAsync(Guid id, CancellationToken cancellationToken) => client.GetSequenceAsync(id, cancellationToken);
|
||||
|
||||
public Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken) => client.GetManifestAsync(id, cancellationToken);
|
||||
|
||||
public Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) =>
|
||||
client.UpdateSequenceAsync(id, request, cancellationToken);
|
||||
|
||||
public Task<string?> GetAnalysisReportAsync(Guid id, CancellationToken cancellationToken) => client.GetAnalysisReportAsync(id, cancellationToken);
|
||||
|
||||
public Task<JobDto> CreateJobAsync(CreateJobRequest request, CancellationToken cancellationToken) => client.CreateJobAsync(request, cancellationToken);
|
||||
|
||||
public Task<JobDto> GetJobAsync(Guid id, CancellationToken cancellationToken) => client.GetJobAsync(id, cancellationToken);
|
||||
|
||||
/// <summary>Filtered by state and kind and read to the last page: a busy server queues thumbnails and proxies by the thousand.</summary>
|
||||
public async Task<IReadOnlyList<JobDto>> ListActiveJobsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var jobs = new List<JobDto>();
|
||||
foreach (var state in ActiveStates)
|
||||
{
|
||||
foreach (var kind in EditorKinds)
|
||||
{
|
||||
string? cursor = null;
|
||||
do
|
||||
{
|
||||
var page = await client.ListJobsAsync(JobWire.State(state), JobWire.Kind(kind), cursor, cancellationToken);
|
||||
jobs.AddRange(page.Items);
|
||||
cursor = page.NextCursor;
|
||||
}
|
||||
while (cursor is not null);
|
||||
}
|
||||
}
|
||||
return jobs;
|
||||
}
|
||||
|
||||
public Task<JobDto> CancelJobAsync(Guid id, CancellationToken cancellationToken) => client.CancelJobAsync(id, cancellationToken);
|
||||
|
||||
public Task<JobDto> RetryJobAsync(Guid id, CancellationToken cancellationToken) => client.RetryJobAsync(id, cancellationToken);
|
||||
|
||||
public Task<JobDto> SetJobPriorityAsync(Guid id, string priority, CancellationToken cancellationToken) =>
|
||||
client.SetJobPriorityAsync(id, priority, cancellationToken);
|
||||
|
||||
public IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken) => client.EventsAsync(cancellationToken);
|
||||
|
||||
public void Dispose() => client.Dispose();
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
using System.IO;
|
||||
using Titano.App.Editor;
|
||||
using Titano.App.Infrastructure;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Sync;
|
||||
using Titano.Protocol.Client;
|
||||
|
||||
@@ -14,9 +16,11 @@ public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOn
|
||||
/// <summary>
|
||||
/// This PC's sync with the signed-in server (BRIEF §4.4, §14.5): the <see cref="SyncService"/> of the index, the
|
||||
/// connection of upload and download jobs (<see cref="ISyncConnector"/>), a <see cref="SyncAgent"/> that keeps the
|
||||
/// table current while a session is open, started and stopped in order as the session changes, and the
|
||||
/// <see cref="UploadHold"/> for metered connections. Options come from <see cref="AppSettings.SyncSettingsAutomatically"/>,
|
||||
/// <see cref="AppSettings.KeepProxiesOffline"/> and <see cref="AppSettings.PauseUploadsOnMetered"/>.
|
||||
/// table current while a session is open, started and stopped in order as the session changes, the
|
||||
/// <see cref="UploadHold"/> for metered connections, the connections of editors of server sequences
|
||||
/// (<see cref="ConnectEditor"/>) and the Export "Sync" of finished renders (<see cref="ExportSync"/>). Options come from
|
||||
/// <see cref="AppSettings.SyncSettingsAutomatically"/>, <see cref="AppSettings.KeepProxiesOffline"/> and
|
||||
/// <see cref="AppSettings.PauseUploadsOnMetered"/>.
|
||||
/// </summary>
|
||||
public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDisposable
|
||||
{
|
||||
@@ -26,11 +30,16 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
private Task _switch = Task.CompletedTask;
|
||||
private Credentials? _credentials;
|
||||
private (SyncAgent Agent, ISyncRemote Remote, Credentials Credentials)? _running;
|
||||
private JobEngine? _renders;
|
||||
|
||||
/// <summary>Connections over <see cref="TitanoClient"/>; screenshots substitute a fake server.</summary>
|
||||
public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted) =>
|
||||
new TitanoSyncRemote(new TitanoClient(address, new CertificatePinning(trusted), $"Titano ({Environment.MachineName})") { Token = token }, ownsClient: true);
|
||||
|
||||
/// <summary>Connections of editors of server sequences over <see cref="TitanoClient"/>; screenshots substitute a fake server.</summary>
|
||||
public RemoteSequenceApiFactory EditorFactory { get; set; } = (address, token, trusted) =>
|
||||
new TitanoRemoteSequenceApi(new TitanoClient(address, new CertificatePinning(trusted), $"Titano ({Environment.MachineName})") { Token = token });
|
||||
|
||||
/// <summary>The engine; null until the index is open.</summary>
|
||||
public SyncService? Service { get; private set; }
|
||||
|
||||
@@ -44,8 +53,13 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
public string? Server => Volatile.Read(ref _credentials) is { } c ? SyncService.ServerKey(c.Address) : null;
|
||||
|
||||
/// <summary>The options, and whether the account may change server sequences (without it this PC's edits are not sent).</summary>
|
||||
public SyncPolicy Policy => new(services.Settings.SyncSettingsAutomatically, services.Settings.KeepProxiesOffline,
|
||||
services.Server.User is { } user && (user.Permissions & (long)Permissions.Edit) != 0);
|
||||
public SyncPolicy Policy => new(services.Settings.SyncSettingsAutomatically, services.Settings.KeepProxiesOffline, Allows(Permissions.Edit));
|
||||
|
||||
/// <summary>The signed-in account may send files (originals, renders) to the server.</summary>
|
||||
public bool CanUpload => Allows(Permissions.Upload);
|
||||
|
||||
/// <summary>The signed-in account may queue renders on the server.</summary>
|
||||
public bool CanRender => Allows(Permissions.Render);
|
||||
|
||||
/// <summary>Pauses uploads while the connection is metered and the option is on.</summary>
|
||||
public UploadHold Uploads { get; } = new(services);
|
||||
@@ -74,9 +88,18 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
: null;
|
||||
Volatile.Write(ref _credentials, wanted);
|
||||
_switch = SwitchAsync(_switch, wanted);
|
||||
if (services.Engine is { } engine) Uploads.Attach(engine);
|
||||
if (services.Engine is not { } engine) return;
|
||||
Uploads.Attach(engine);
|
||||
if (ReferenceEquals(_renders, engine)) return;
|
||||
if (_renders is not null) _renders.JobChanged -= OnJobChanged;
|
||||
_renders = engine;
|
||||
engine.JobChanged += OnJobChanged;
|
||||
}
|
||||
|
||||
/// <summary>A connection for the editor of a sequence of the signed-in server; null while signed out.</summary>
|
||||
public IRemoteSequenceApi? ConnectEditor() =>
|
||||
Volatile.Read(ref _credentials) is { } c ? EditorFactory(c.Address, c.Token, c.Fingerprints) : null;
|
||||
|
||||
/// <summary>Compares now, once the session switch in progress settled; null while signed out.</summary>
|
||||
public async Task<SyncSnapshot?> RefreshAsync(CancellationToken ct = default)
|
||||
{
|
||||
@@ -116,10 +139,50 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
|
||||
{
|
||||
Volatile.Write(ref _credentials, null);
|
||||
Uploads.Dispose();
|
||||
if (_renders is not null) _renders.JobChanged -= OnJobChanged;
|
||||
await _switch;
|
||||
await StopAsync();
|
||||
}
|
||||
|
||||
private bool Allows(Permissions permission) => services.Server.User is { } user && (user.Permissions & (long)permission) != 0;
|
||||
|
||||
/// <summary>
|
||||
/// Export "Sync": a render of this PC that asked for it is sent to the server once done (<see cref="ExportSync"/>),
|
||||
/// also when it ends while the session is down: the send is queued for the saved session's server and waits for it.
|
||||
/// </summary>
|
||||
private void OnJobChanged(Job job)
|
||||
{
|
||||
if (job is not { Kind: JobKind.Render, State: JobState.Done } || Service is not { } service || services.Database is not { } db || _renders is not { } engine)
|
||||
return;
|
||||
var signedIn = Server;
|
||||
_ = SendRenderAsync(new ExportSync(db, service, engine), job, signedIn ?? SavedServer(), signedIn is null || CanUpload);
|
||||
}
|
||||
|
||||
/// <summary>Key of the server of the saved session (Disconnect keeps it); null without one.</summary>
|
||||
private string? SavedServer() =>
|
||||
services.Server.HasSavedSession && ServerAddress.TryParse(services.Settings.ServerUrl, out var address) ? SyncService.ServerKey(address) : null;
|
||||
|
||||
private static async Task SendRenderAsync(ExportSync exports, Job job, string? server, bool canUpload)
|
||||
{
|
||||
try
|
||||
{
|
||||
switch (await exports.SendAsync(job, server, canUpload))
|
||||
{
|
||||
case { Send: { } send }:
|
||||
Log.Info("sync", $"{job.TargetLabel} will be sent to the server (job {send.Id})");
|
||||
break;
|
||||
case { Gate: var gate }:
|
||||
Log.Warning("sync", $"{job.TargetLabel} asked to be sent to the server but was not ({gate})");
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||||
{
|
||||
// Nobody awaits this: the render itself succeeded, and the send can be asked for again on the Server screen.
|
||||
Log.Warning("sync", $"The render {job.TargetLabel} could not be queued for the server", ex);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SwitchAsync(Task previous, Credentials? wanted)
|
||||
{
|
||||
await previous;
|
||||
|
||||
@@ -157,12 +157,20 @@ public static class SyncText
|
||||
/// What differs, one line per setting or sequence field in project order ("Deflicker window 41 here, 33 on the
|
||||
/// server", "Tags differ"), at most <paramref name="max"/>.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> Conflict(SyncEntry entry, int max)
|
||||
public static IReadOnlyList<string> Conflict(SyncEntry entry, int max) => entry is { Local: { } local, Link.ConflictRemote: { } theirs }
|
||||
? Differences(SyncRules.Differences(SyncPayload.Of(local), theirs, 64), max)
|
||||
: [];
|
||||
|
||||
/// <summary>
|
||||
/// One line per setting or sequence field among <paramref name="differences"/> ("Deflicker window 41 here, 33 on the
|
||||
/// server", "Tags differ"), at most <paramref name="max"/>; the editor's settings conflicts read the same.
|
||||
/// </summary>
|
||||
public static IReadOnlyList<string> Differences(IEnumerable<SettingsDifference> differences, int max)
|
||||
{
|
||||
if (entry is not { Local: { } local, Link.ConflictRemote: { } theirs }) return [];
|
||||
ArgumentNullException.ThrowIfNull(differences);
|
||||
var lines = new List<string>();
|
||||
var shown = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var difference in SyncRules.Differences(SyncPayload.Of(local), theirs, 64))
|
||||
foreach (var difference in differences)
|
||||
{
|
||||
var (key, field) = Setting(difference.Path);
|
||||
if (!shown.Add(key)) continue;
|
||||
|
||||
@@ -19,9 +19,10 @@ namespace Titano.App.Shell;
|
||||
/// <summary>
|
||||
/// <c>Titano.exe --capture <dir></c>: renders every client screen at 1440×900 in the dark and light themes to
|
||||
/// <c><screen>-<theme>.png</c> from <see cref="SampleData"/> (first run on an empty index, then a populated
|
||||
/// one, then the sync table with transfers, a conflict and its confirmation), plus the Library, the editor's Exposure
|
||||
/// tab and the import plan in Arabic (<c>*-rtl-dark.png</c>, right to left), for visual review and phase reports
|
||||
/// (BRIEF §20.2), then exits.
|
||||
/// one, then the sync table with transfers, a conflict and its confirmation, then the sequence editor on an archive
|
||||
/// sequence and on a server sequence with proxies, its server job and a read-only account), plus the Library, the
|
||||
/// editor's Exposure tab and the import plan in Arabic (<c>*-rtl-dark.png</c>, right to left), for visual review and
|
||||
/// phase reports (BRIEF §20.2), then exits.
|
||||
/// </summary>
|
||||
public static class ScreenCapture
|
||||
{
|
||||
@@ -144,6 +145,7 @@ public static class ScreenCapture
|
||||
}
|
||||
|
||||
written += await CaptureEditorAsync(window, shell, sample, directory);
|
||||
written += await CaptureRemoteEditorAsync(window, shell, sample, directory);
|
||||
Log.Info("capture", $"{written} screenshot(s) written to {Path.GetFullPath(directory)}");
|
||||
if (written == 0) Environment.ExitCode = 1;
|
||||
}
|
||||
@@ -207,7 +209,8 @@ 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.
|
||||
/// the preview overlays, the waveform, the "what changed" toast of Optimise all, the Export tab of the sequence once
|
||||
/// the server has it (Sync on) with two "Save both" copies to restore, and the busy state.
|
||||
/// </summary>
|
||||
private static async Task<int> CaptureEditorAsync(MainWindow window, ShellViewModel shell, SampleData sample, string directory)
|
||||
{
|
||||
@@ -247,6 +250,23 @@ public static class ScreenCapture
|
||||
foreach (var toast in window.Toasts.Toasts.ToList()) window.Toasts.Dismiss(toast);
|
||||
}
|
||||
|
||||
// The server has the sequence (Sync can be ticked) and two copies of this PC's settings were kept by "Save both".
|
||||
await sample.KeepEditorCopiesAsync(id);
|
||||
await editor.Session.ReloadAsync();
|
||||
await editor.RefreshSyncGateAsync();
|
||||
var export = editor.Tabs.OfType<ExportTab>().Single();
|
||||
export.SyncToServer = true;
|
||||
editor.SelectedTab = export;
|
||||
editor.IsCompare = false;
|
||||
foreach (var theme in Themes)
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
written += await SaveEditorAsync(window, editor, directory, "sequence-export-copies", theme);
|
||||
}
|
||||
export.SyncToServer = false;
|
||||
editor.SelectedTab = editor.Exposure;
|
||||
editor.IsCompare = true;
|
||||
|
||||
written += await CaptureRightToLeftAsync(window, shell, editor, directory);
|
||||
|
||||
// Last, as it stays: an analysis of the sequence running (settings disabled, viewing tools live).
|
||||
@@ -295,6 +315,65 @@ public static class ScreenCapture
|
||||
return written;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A server sequence open with this PC's proxies (Sunrise over Superga, cached by the sync captures): the server in
|
||||
/// the header, the preview from the proxies, the project from the server (<c>sequence-remote</c>); its Export tab,
|
||||
/// where the server picks the encoder and keeps the renders (<c>sequence-remote-export</c>); a render running on the
|
||||
/// server with its bar and Cancel (<c>sequence-remote-running</c>); then, last as it stays, the sequence opened by an
|
||||
/// account without the Edit right (<c>sequence-remote-readonly</c>).
|
||||
/// </summary>
|
||||
private static async Task<int> CaptureRemoteEditorAsync(MainWindow window, ShellViewModel shell, SampleData sample, string directory)
|
||||
{
|
||||
var written = 0;
|
||||
var id = sample.ProxiedSequenceId;
|
||||
shell.OpenSequence(id);
|
||||
await shell.Sequence.OpenAsync(id);
|
||||
if (shell.Sequence.Editor is not { IsRemote: true } editor)
|
||||
{
|
||||
Log.Warning("capture", "The server sequence did not open in the editor");
|
||||
return 0;
|
||||
}
|
||||
DismissToasts(window);
|
||||
var export = editor.Tabs.OfType<ExportTab>().Single();
|
||||
foreach (var theme in Themes)
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
editor.SelectedTab = editor.Exposure;
|
||||
editor.IsCompare = true;
|
||||
written += await SaveEditorAsync(window, editor, directory, "sequence-remote", theme);
|
||||
editor.SelectedTab = export;
|
||||
editor.IsCompare = false;
|
||||
written += await SaveEditorAsync(window, editor, directory, "sequence-remote-export", theme);
|
||||
}
|
||||
|
||||
sample.RunServerRender();
|
||||
await editor.AttachJobsAsync();
|
||||
editor.SelectedTab = editor.Exposure;
|
||||
editor.IsCompare = true;
|
||||
foreach (var theme in Themes)
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
written += await SaveEditorAsync(window, editor, directory, "sequence-remote-running", theme);
|
||||
}
|
||||
|
||||
sample.EndServerJobs();
|
||||
await sample.RestrictAccountAsync();
|
||||
await shell.Sequence.OpenAsync(id, reload: true);
|
||||
if (shell.Sequence.Editor is not { IsReadOnly: true } viewer)
|
||||
{
|
||||
Log.Warning("capture", "The server sequence did not open read-only");
|
||||
return written;
|
||||
}
|
||||
DismissToasts(window);
|
||||
viewer.SelectedTab = viewer.Exposure;
|
||||
foreach (var theme in Themes)
|
||||
{
|
||||
ThemeManager.Apply(theme);
|
||||
written += await SaveEditorAsync(window, viewer, directory, "sequence-remote-readonly", theme);
|
||||
}
|
||||
return written;
|
||||
}
|
||||
|
||||
private static async Task<int> SaveEditorAsync(Window window, EditorViewModel editor, string directory, string screen, AppTheme theme)
|
||||
{
|
||||
await Settle(window);
|
||||
|
||||
@@ -158,6 +158,12 @@ public sealed record ExportSettings
|
||||
|
||||
/// <summary>Presets queued together by "Render another preset" / batch.</summary>
|
||||
public IReadOnlyList<string> Batch { get; init; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Export "Sync": a render made on this PC is sent to the server the sequence is linked to once it is done. Off
|
||||
/// unless chosen, as renders travel on request (BRIEF §14.5).
|
||||
/// </summary>
|
||||
public bool SyncToServer { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
using System.Text;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Protocol;
|
||||
|
||||
namespace Titano.Data.Jobs;
|
||||
|
||||
/// <summary>
|
||||
/// Wire names of job kinds, states and priorities in API v1: kebab-case (<c>deep-analyse</c>) and lower-case
|
||||
/// (<c>running</c>). The server writes them; clients read the server's jobs back with <see cref="FromDto"/>.
|
||||
/// </summary>
|
||||
public static class JobWire
|
||||
{
|
||||
public static string Kind(JobKind kind)
|
||||
{
|
||||
var name = kind.ToString();
|
||||
var sb = new StringBuilder(name.Length + 4);
|
||||
for (var i = 0; i < name.Length; i++)
|
||||
{
|
||||
if (i > 0 && char.IsUpper(name[i])) sb.Append('-');
|
||||
sb.Append(char.ToLowerInvariant(name[i]));
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public static bool TryParseKind(string? text, out JobKind kind) => TryParse(text, Kind, out kind);
|
||||
|
||||
public static string State(JobState state) => state.ToString().ToLowerInvariant();
|
||||
|
||||
public static bool TryParseState(string? text, out JobState state) => TryParse(text, State, out state);
|
||||
|
||||
public static string Priority(JobPriority priority) => priority.ToString().ToLowerInvariant();
|
||||
|
||||
public static bool TryParsePriority(string? text, out JobPriority priority) => TryParse(text, Priority, out priority);
|
||||
|
||||
/// <summary>A server job as the client's job model; null for a kind or state this build does not know.</summary>
|
||||
public static Job? FromDto(JobDto dto)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(dto);
|
||||
if (!TryParseKind(dto.Kind, out var kind) || !TryParseState(dto.State, out var state)) return null;
|
||||
return new Job
|
||||
{
|
||||
Id = dto.Id,
|
||||
Kind = kind,
|
||||
TargetIds = dto.TargetIds,
|
||||
TargetLabel = dto.TargetLabel,
|
||||
State = state,
|
||||
Priority = TryParsePriority(dto.Priority, out var priority) ? priority : JobPriority.Normal,
|
||||
ProgressDone = dto.ProgressDone,
|
||||
ProgressTotal = dto.ProgressTotal,
|
||||
ItemsPerSecond = dto.ItemsPerSecond,
|
||||
Eta = dto.EtaSeconds is { } eta ? TimeSpan.FromSeconds(eta) : null,
|
||||
LogTail = dto.LogTail,
|
||||
NodeId = dto.NodeId,
|
||||
Attempts = dto.Attempts,
|
||||
Error = dto.Error,
|
||||
Created = dto.Created,
|
||||
Started = dto.Started,
|
||||
Finished = dto.Finished,
|
||||
};
|
||||
}
|
||||
|
||||
private static bool TryParse<T>(string? text, Func<T, string> name, out T value) where T : struct, Enum
|
||||
{
|
||||
foreach (var candidate in Enum.GetValues<T>())
|
||||
{
|
||||
if (string.Equals(name(candidate), text, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
value = candidate;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
value = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Data.Repositories;
|
||||
|
||||
namespace Titano.Data.Processing;
|
||||
|
||||
/// <summary>
|
||||
/// The index's hero frame (<see cref="Sequence.HeroFrameId"/>, the frame the Library shows) follows the project's hero
|
||||
/// (<see cref="ProjectSettings.HeroFrame"/>, a frame index; frame indices are positions).
|
||||
/// </summary>
|
||||
public static class HeroFrame
|
||||
{
|
||||
/// <summary>
|
||||
/// The <see cref="SequenceEdit.HeroFrameId"/> of a project whose hero went from <paramref name="before"/> to
|
||||
/// <paramref name="after"/>: null when it did not change, else the frame at the new index, or <see cref="Guid.Empty"/>
|
||||
/// (the first frame shows) when there is none.
|
||||
/// </summary>
|
||||
public static async Task<Guid?> EditAsync(TitanoDatabase db, Guid sequenceId, int? before, int? after, CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(db);
|
||||
if (before == after) return null;
|
||||
if (after is not >= 0) return Guid.Empty;
|
||||
var frames = await db.Frames.ListBySequenceAsync(sequenceId, after.Value - 1, 1, cancellationToken).ConfigureAwait(false);
|
||||
return frames is [{ } frame] && frame.Index == after ? frame.Id : Guid.Empty;
|
||||
}
|
||||
}
|
||||
@@ -110,7 +110,7 @@ public static class ProcessingJobs
|
||||
|
||||
/// <summary>The parameters of a render job and the export they select.</summary>
|
||||
/// <exception cref="InvalidDataException">The job has no valid render parameters.</exception>
|
||||
internal static (RenderJobParameters Parameters, ExportSettings Export) ReadRender(string? parametersJson)
|
||||
public static (RenderJobParameters Parameters, ExportSettings Export) ReadRender(string? parametersJson)
|
||||
{
|
||||
var parameters = ReadParameters(parametersJson);
|
||||
return (parameters, ReadExport(parameters.PresetJson));
|
||||
|
||||
@@ -48,11 +48,14 @@ internal sealed class ProjectStore(TitanoDatabase db, SequenceWriter writer)
|
||||
var row = await db.Sequences.GetAsync(sequence.Id, cancellationToken).ConfigureAwait(false) ?? sequence;
|
||||
var current = Read(row, folder);
|
||||
var before = current.ToJson();
|
||||
var after = edit(current).ToJson();
|
||||
var edited = edit(current);
|
||||
var after = edited.ToJson();
|
||||
if (after == before) return false;
|
||||
AtomicFile.WriteAllText(folder.ProjectPath, after);
|
||||
var result = await db.Sequences.EditAsync(sequence.Id, new SequenceEdit { SettingsJson = after }, row.SettingsVersion, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
// The Library shows the project's hero frame (advice fills it, a sync takes another PC's).
|
||||
var hero = await HeroFrame.EditAsync(db, sequence.Id, current.HeroFrame, edited.HeroFrame, cancellationToken).ConfigureAwait(false);
|
||||
var result = await db.Sequences.EditAsync(sequence.Id, new SequenceEdit { SettingsJson = after, HeroFrameId = hero }, row.SettingsVersion,
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
// A conflict means the API changed the settings meanwhile: apply the edit again on top of them.
|
||||
if (result.Outcome != SequenceEditOutcome.Conflict || attempt == Attempts) return true;
|
||||
}
|
||||
|
||||
@@ -74,6 +74,12 @@ public sealed record SequenceEdit
|
||||
public int? Rating { get; init; }
|
||||
public string? Notes { get; init; }
|
||||
public string? SettingsJson { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The frame the Library shows for the sequence (the project's hero frame); <see cref="Guid.Empty"/> clears it, so
|
||||
/// the first frame shows. A frame of another sequence is ignored.
|
||||
/// </summary>
|
||||
public Guid? HeroFrameId { get; init; }
|
||||
}
|
||||
|
||||
public enum SequenceEditOutcome
|
||||
@@ -233,12 +239,17 @@ public sealed class SequenceRepository
|
||||
if (current is null) return new SequenceEditResult(SequenceEditOutcome.NotFound, null);
|
||||
if (expectedSettingsVersion is { } expected && expected != current.SettingsVersion)
|
||||
return new SequenceEditResult(SequenceEditOutcome.Conflict, current);
|
||||
var hero = current.HeroFrameId;
|
||||
if (edit.HeroFrameId == Guid.Empty) hero = null;
|
||||
else if (edit.HeroFrameId is { } frame && await session.ScalarAsync<long>("SELECT count(*) FROM frames WHERE id = $1 AND sequence_id = $2",
|
||||
[frame, id], cancellationToken).ConfigureAwait(false) > 0) hero = frame;
|
||||
var updated = current with
|
||||
{
|
||||
Title = edit.Title is null ? current.Title : NullIfEmpty(edit.Title),
|
||||
Notes = edit.Notes is null ? current.Notes : NullIfEmpty(edit.Notes),
|
||||
Rating = edit.Rating ?? current.Rating,
|
||||
SettingsJson = edit.SettingsJson ?? current.SettingsJson,
|
||||
HeroFrameId = hero,
|
||||
SettingsVersion = current.SettingsVersion + 1,
|
||||
UpdatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
|
||||
@@ -20,8 +20,10 @@ namespace Titano.Data.Sync;
|
||||
/// </summary>
|
||||
public sealed class RemoteSequence
|
||||
{
|
||||
internal RemoteSequence(string server, Sequence sequence, IReadOnlyList<Frame> frames, IReadOnlyList<string?> files)
|
||||
/// <param name="files">Absolute path of each frame's proxy in frame order; null (and the frame flagged missing) when it is not cached.</param>
|
||||
public RemoteSequence(string server, Sequence sequence, IReadOnlyList<Frame> frames, IReadOnlyList<string?> files)
|
||||
{
|
||||
if (files.Count != frames.Count) throw new ArgumentException("One file entry per frame is required.", nameof(files));
|
||||
Server = server;
|
||||
Sequence = sequence;
|
||||
Frames = frames;
|
||||
|
||||
@@ -270,6 +270,10 @@ public sealed class SyncService
|
||||
/// <summary>A server sequence from the proxy cache, for the editor; null when its proxies were never fetched or were cleared.</summary>
|
||||
public RemoteSequence? OpenRemote(string server, Guid remoteId) => Proxies.Load(server, remoteId);
|
||||
|
||||
/// <summary>The link of a local sequence to a sequence of <paramref name="server"/>; null when the server does not have it.</summary>
|
||||
public Task<SyncLink?> LinkOfAsync(string server, Guid localId, CancellationToken cancellationToken = default) =>
|
||||
_links.FindByLocalAsync(server, localId, cancellationToken);
|
||||
|
||||
// ---------------- Engine ----------------
|
||||
|
||||
/// <summary>Server ids of the sequences an upload or download job is working on.</summary>
|
||||
@@ -649,7 +653,25 @@ public sealed class SyncService
|
||||
return path;
|
||||
}
|
||||
|
||||
internal static string SavedCopyName(DateTime localTime) => string.Create(CultureInfo.InvariantCulture, $"project.this-pc-{localTime:yyyyMMdd-HHmmss}.json");
|
||||
/// <summary>The file name of a "Save both" copy kept at <paramref name="localTime"/>.</summary>
|
||||
public static string SavedCopyName(DateTime localTime) =>
|
||||
string.Create(CultureInfo.InvariantCulture, $"{SavedCopyPrefix}{localTime.ToString(SavedCopyTimeFormat, CultureInfo.InvariantCulture)}.json");
|
||||
|
||||
/// <summary>File name pattern of "Save both" copies in a sequence's <c>.titano</c> folder.</summary>
|
||||
public const string SavedCopyPattern = SavedCopyPrefix + "*.json";
|
||||
|
||||
private const string SavedCopyPrefix = "project.this-pc-";
|
||||
private const string SavedCopyTimeFormat = "yyyyMMdd-HHmmss";
|
||||
|
||||
/// <summary>When a "Save both" copy was kept (local time, from its name); null for a name of another shape.</summary>
|
||||
public static DateTime? SavedCopyTime(string fileName)
|
||||
{
|
||||
var name = Path.GetFileNameWithoutExtension(fileName);
|
||||
return name.StartsWith(SavedCopyPrefix, StringComparison.Ordinal)
|
||||
&& DateTime.TryParseExact(name[SavedCopyPrefix.Length..], SavedCopyTimeFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out var time)
|
||||
? time
|
||||
: null;
|
||||
}
|
||||
|
||||
private async Task ForgetAsync(SyncLink link, CancellationToken cancellationToken)
|
||||
{
|
||||
|
||||
@@ -99,6 +99,21 @@ public sealed class TitanoClient : IDisposable
|
||||
public Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken ct = default) =>
|
||||
GetAsync($"api/v1/sequences/{id}/manifest", ProtocolJson.Default.SequenceManifest, ct);
|
||||
|
||||
/// <summary>The full deep-analysis report of a sequence (<c>analysis.json</c>); null when it was never deep-analysed.</summary>
|
||||
public async Task<string?> GetAnalysisReportAsync(Guid sequenceId, CancellationToken ct = default)
|
||||
{
|
||||
using var response = await SendRawAsync(new HttpRequestMessage(HttpMethod.Get, $"api/v1/sequences/{sequenceId}/analysis/report"), ct).ConfigureAwait(false);
|
||||
try
|
||||
{
|
||||
await EnsureSuccessAsync(response, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound && ex.Error.Details == "analysis")
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public Task<Page<FrameDto>> ListFramesAsync(Guid sequenceId, string? cursor = null, int limit = 1000, CancellationToken ct = default) =>
|
||||
GetAsync($"api/v1/sequences/{sequenceId}/frames?limit={limit}{Q("cursor", cursor)}", ProtocolJson.Default.PageFrameDto, ct);
|
||||
|
||||
@@ -258,7 +273,11 @@ public sealed class TitanoClient : IDisposable
|
||||
// ---------------- Jobs and render nodes ----------------
|
||||
|
||||
public Task<Page<JobDto>> ListJobsAsync(string? state = null, string? cursor = null, CancellationToken ct = default) =>
|
||||
GetAsync($"api/v1/jobs?limit=200{Q("state", state)}{Q("cursor", cursor)}", ProtocolJson.Default.PageJobDto, ct);
|
||||
ListJobsAsync(state, null, cursor, ct);
|
||||
|
||||
/// <summary>A page of jobs, newest first, in <paramref name="state"/> and of <paramref name="kind"/> (wire names; null for any).</summary>
|
||||
public Task<Page<JobDto>> ListJobsAsync(string? state, string? kind, string? cursor, CancellationToken ct = default) =>
|
||||
GetAsync($"api/v1/jobs?limit=200{Q("state", state)}{Q("kind", kind)}{Q("cursor", cursor)}", ProtocolJson.Default.PageJobDto, ct);
|
||||
|
||||
public Task<JobDto> CreateJobAsync(CreateJobRequest request, CancellationToken ct = default) =>
|
||||
SendAsync(HttpMethod.Post, "api/v1/jobs", request, ProtocolJson.Default.CreateJobRequest, ProtocolJson.Default.JobDto, ct);
|
||||
|
||||
@@ -32,14 +32,18 @@ public sealed record Page<T>(IReadOnlyList<T> Items, string? NextCursor, long? T
|
||||
/// <summary><c>POST /api/v1/sequences</c>.</summary>
|
||||
public sealed record CreateSequenceRequest(string? Title, string? CameraHint);
|
||||
|
||||
/// <summary><c>PATCH /api/v1/sequences/{id}</c>. <see cref="ExpectedSettingsVersion"/> enables conflict detection (409).</summary>
|
||||
/// <summary>
|
||||
/// <c>PATCH /api/v1/sequences/{id}</c>. <see cref="ExpectedSettingsVersion"/> enables conflict detection (409).
|
||||
/// <see cref="HeroFrameId"/> names the frame the sequence shows (one of its own; <see cref="Guid.Empty"/> clears it).
|
||||
/// </summary>
|
||||
public sealed record UpdateSequenceRequest(
|
||||
string? Title,
|
||||
IReadOnlyList<string>? Tags,
|
||||
int? Rating,
|
||||
string? Notes,
|
||||
string? SettingsJson,
|
||||
int? ExpectedSettingsVersion);
|
||||
int? ExpectedSettingsVersion,
|
||||
Guid? HeroFrameId = null);
|
||||
|
||||
public sealed record FrameDto(
|
||||
Guid Id,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Naming;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Repositories;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Jobs;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Protocol;
|
||||
|
||||
namespace Titano.Server.Api;
|
||||
@@ -48,43 +48,3 @@ public static class Dto
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Wire names of job kinds, states and priorities: kebab-case (<c>deep-analyse</c>) and lower-case (<c>running</c>).</summary>
|
||||
public static class JobWire
|
||||
{
|
||||
public static string Kind(JobKind kind)
|
||||
{
|
||||
var name = kind.ToString();
|
||||
var sb = new StringBuilder(name.Length + 4);
|
||||
for (var i = 0; i < name.Length; i++)
|
||||
{
|
||||
if (i > 0 && char.IsUpper(name[i])) sb.Append('-');
|
||||
sb.Append(char.ToLowerInvariant(name[i]));
|
||||
}
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public static bool TryParseKind(string? text, out JobKind kind) => TryParse(text, Kind, out kind);
|
||||
|
||||
public static string State(JobState state) => state.ToString().ToLowerInvariant();
|
||||
|
||||
public static bool TryParseState(string? text, out JobState state) => TryParse(text, State, out state);
|
||||
|
||||
public static string Priority(JobPriority priority) => priority.ToString().ToLowerInvariant();
|
||||
|
||||
public static bool TryParsePriority(string? text, out JobPriority priority) => TryParse(text, Priority, out priority);
|
||||
|
||||
private static bool TryParse<T>(string? text, Func<T, string> name, out T value) where T : struct, Enum
|
||||
{
|
||||
foreach (var candidate in Enum.GetValues<T>())
|
||||
{
|
||||
if (string.Equals(name(candidate), text, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
value = candidate;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
value = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using System.Text.Json;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Jobs;
|
||||
using Titano.Data.Processing;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Jobs;
|
||||
|
||||
@@ -2,10 +2,12 @@ using System.Buffers.Text;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Titano.Core.Model;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Titano.Core.Model;
|
||||
using Titano.Core.Project;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Data.Processing;
|
||||
using Titano.Data.Repositories;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Configuration;
|
||||
@@ -37,6 +39,7 @@ public static class SequenceEndpoints
|
||||
sequences.MapGet("/{id:guid}/manifest", ManifestAsync).Requires(Permissions.Read);
|
||||
sequences.MapGet("/{id:guid}/frames", FramesAsync).Requires(Permissions.Read);
|
||||
sequences.MapGet("/{id:guid}/analysis", AnalysisAsync).Requires(Permissions.Read);
|
||||
sequences.MapGet("/{id:guid}/analysis/report", ReportAsync).Requires(Permissions.Read);
|
||||
sequences.MapGet("/{id:guid}/stats", StatsAsync).Requires(Permissions.Read);
|
||||
sequences.MapGet("/{id:guid}/renders", RendersAsync).Requires(Permissions.Read);
|
||||
// Renders made on a client, sent on request (BRIEF §14.5); chunks go through /uploads.
|
||||
@@ -125,7 +128,17 @@ public static class SequenceEndpoints
|
||||
if (request.SettingsJson is not null && !IsJson(request.SettingsJson)) return ApiErrors.BadRequest(context, "invalid_settings");
|
||||
|
||||
var expected = request.ExpectedSettingsVersion ?? IfMatchVersion(context);
|
||||
var edit = new SequenceEdit { Title = request.Title, Tags = request.Tags, Rating = request.Rating, Notes = request.Notes, SettingsJson = request.SettingsJson };
|
||||
var edit = new SequenceEdit
|
||||
{
|
||||
Title = request.Title,
|
||||
Tags = request.Tags,
|
||||
Rating = request.Rating,
|
||||
Notes = request.Notes,
|
||||
SettingsJson = request.SettingsJson,
|
||||
// A client that sends only the settings (the sync of a local copy) moves the hero frame with the project's hero.
|
||||
HeroFrameId = request.HeroFrameId
|
||||
?? (request.SettingsJson is { } settings ? await SettingsHeroAsync(db, id, settings, context.RequestAborted) : null),
|
||||
};
|
||||
var result = await db.Sequences.EditAsync(id, edit, expected, context.RequestAborted);
|
||||
switch (result.Outcome)
|
||||
{
|
||||
@@ -245,6 +258,18 @@ public static class SequenceEndpoints
|
||||
_ => ApiErrors.NotFound(context, "analysis"),
|
||||
};
|
||||
|
||||
/// <summary>The full deep-analysis report (<c>.titano/analysis.json</c>) a client's editor shows for a server sequence.</summary>
|
||||
private static async Task<IResult> ReportAsync(HttpContext context, Guid id, TitanoDatabase db, ServerArchive archive)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, context.RequestAborted) is not { } sequence) return ApiErrors.NotFound(context, "sequence");
|
||||
if (string.IsNullOrEmpty(sequence.Folder)) return ApiErrors.NotFound(context, "analysis");
|
||||
var path = new Core.Archiving.ArchivePaths(archive.Root).Sequence(sequence.Folder).AnalysisPath;
|
||||
var file = new FileInfo(path);
|
||||
if (!file.Exists || file.LinkTarget is not null || !ArchivePathGuard.IsInside(archive.Root, path)) return ApiErrors.NotFound(context, "analysis");
|
||||
var etag = string.Create(CultureInfo.InvariantCulture, $"a-{file.Length}-{file.LastWriteTimeUtc.Ticks}");
|
||||
return FileResponses.Serve(context, file, 0, file.Length, "application/json; charset=utf-8", "no-cache", etag) ?? ApiErrors.NotFound(context, "analysis");
|
||||
}
|
||||
|
||||
private static async Task<IResult> StatsAsync(HttpContext context, Guid id, TitanoDatabase db)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, context.RequestAborted) is not { } s) return ApiErrors.NotFound(context, "sequence");
|
||||
@@ -305,6 +330,22 @@ public static class SequenceEndpoints
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>The hero frame edit of new settings: the frame of their hero when it is not the stored settings' hero.</summary>
|
||||
private static async Task<Guid?> SettingsHeroAsync(TitanoDatabase db, Guid id, string settingsJson, CancellationToken ct)
|
||||
{
|
||||
if (await db.Sequences.GetAsync(id, ct) is not { } current) return null;
|
||||
try
|
||||
{
|
||||
var before = string.IsNullOrWhiteSpace(current.SettingsJson) ? null : ProjectSettings.FromJson(current.SettingsJson).HeroFrame;
|
||||
return await HeroFrame.EditAsync(db, id, before, ProjectSettings.FromJson(settingsJson).HeroFrame, ct);
|
||||
}
|
||||
catch (Exception ex) when (ex is JsonException or InvalidDataException)
|
||||
{
|
||||
// Not a project of this Titano (a newer one, or free JSON): its hero is unknown here, the stored one stays.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsJson(string text)
|
||||
{
|
||||
try
|
||||
@@ -326,6 +367,7 @@ public static class SequenceEndpoints
|
||||
if (r.Rating is not null) fields.Add("rating");
|
||||
if (r.Notes is not null) fields.Add("notes");
|
||||
if (r.SettingsJson is not null) fields.Add("settings");
|
||||
if (r.HeroFrameId is not null) fields.Add("hero");
|
||||
return string.Join(", ", fields);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user