diff --git a/i18n/en/Editor.resx b/i18n/en/Editor.resx
index 4e0abcf9..ddf0e3d0 100644
--- a/i18n/en/Editor.resx
+++ b/i18n/en/Editor.resx
@@ -45,11 +45,16 @@
target curveWaveformluma of frame {0}
+ Project restored
+ Nothing to restore
+ UndoPick a sequence in the LibraryThis sequence is no longer in the archive.longJobs cannot run until the archive index is open.longThe settings of this sequence cannot be read.long
+ Your account cannot change the sequences of this server.longThe settings of this sequence were changed elsewhere at the same time.long
+ The saved settings {0} cannot be read.longabout {0}Add to queueBatch…
@@ -79,12 +84,15 @@
RecommendedRender nowResolution
+ Restore · {0}
+ Restore copyResultshow fileSave toSequence exports/Estimated sizesoftware
+ SyncEstimated timeNo encoder hereWidth
@@ -174,6 +182,7 @@
Render · {0}Render finishedRender queued
+ Render queued on {0}Show in folderRenderReset
@@ -181,6 +190,7 @@
Changes not savedRetrySections
+ {0} leftf/{0}invariant{0} mminvariantISO {0}invariant
diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx
index 2601110d..c08e14dc 100644
--- a/i18n/en/Tooltips.resx
+++ b/i18n/en/Tooltips.resx
@@ -114,6 +114,7 @@
Click or drag to show that frameLuma waveform of the frame on screen: exposure and clipping at a glanceLuma of the corrected frame across the picture: white at the top, black at the bottom
+ Bring back the project as it was before the restore · Ctrl+ZAdd this render to the queue and keep editingApply this sequence preset to every section · {0}Queue every ticked preset as one job; the sequence is prepared once
@@ -124,6 +125,7 @@
MP4, AVI, GIF, APNG or a folder of images; the codec list followsEncoder on this PC; Auto prefers hardwareWhere renders go: {0}
+ Renders of a server sequence go to its exports folder on the serverFrames per second of the video fileAuto: the preset’s {0} fpsReturn to the preset’s frame rate
@@ -134,7 +136,14 @@
Render with {0}; editing a value makes it CustomImage quality; 95 looks lossless, lower makes smaller filesAdvisor pick: {0}
+ Make this PC’s settings kept on {0} the project; Ctrl+Z undoes it
+ Choose another copy of this PC’s settings, kept when a sync conflict was settledEnter a size between 16 and 16384 pixels
+ After each render on this PC, also send the file to the server; large files take time
+ Your account cannot send files to the server
+ The server does not have this sequence: upload it from the Server screen first
+ Renders of a server sequence are made on the server and stay there
+ Connect to the server first to send renders to itOutput width in pixels; empty uses the preset or the source · Enter applies, Esc revertsRemoves frame-to-frame brightness flicker; off keeps the camera’s own exposureTurns ISO, shutter and aperture steps into smooth ramps; off keeps the jumps
@@ -148,7 +157,7 @@
Click or drag to show a frame; markers show exposure steps, warnings and keyframesLeave this frame out of every render; the photo is not deletedShow the first frame concerned
- Make this the hero frame; the editor opens on it
+ Use the frame as the sequence thumbnailUse this frame in renders againSort by this column; click again to reverseClick a row to show the frame
@@ -183,6 +192,7 @@
Show or hide the shot dataOverlay the motion to the next frame measured by the engineDrag the line to compare · drag to pan · wheel zooms · double-click 1:1
+ Edited with proxies on this PC; changes are saved on {0} and analyses and renders run thereRender with the selected preset; progress in the job bar · Ctrl+RFix the file name first: {0}Every frame is excluded: include some in the Frames tab
@@ -192,6 +202,7 @@
Choose another presetReturn every control of this section to Auto · Ctrl+Z undoesTry to save now; saving is also retried automatically
+ {0} running on {1}Frames combined into each output frame; trails and smoothing grow with itMedian and mean remove noise and moving things; star trails keep the brightest pixelsCrop, aspect, virtual camera moves
diff --git a/i18n/it/Editor.it.resx b/i18n/it/Editor.it.resx
index 2d7f8f68..27e657ee 100644
--- a/i18n/it/Editor.it.resx
+++ b/i18n/it/Editor.it.resx
@@ -44,11 +44,16 @@
curva obiettivoForma d’ondaluma del fotogramma {0}
+ Progetto ripristinato
+ Niente da ripristinare
+ AnnullaScegli una sequenza in LibreriaQuesta sequenza non è più nell’archivio.I lavori non possono partire finché l’indice dell’archivio non è aperto.Le impostazioni di questa sequenza non sono leggibili.
+ Il tuo account non può modificare le sequenze di questo server.Le impostazioni di questa sequenza sono state modificate altrove nello stesso momento.
+ Le impostazioni salvate {0} non si possono leggere.circa {0}Metti in codaIn serie…
@@ -74,12 +79,15 @@
ConsigliatoRenderizza oraRisoluzione
+ Ripristina · {0}
+ Ripristina copiaRisultatomostra fileSalva inexports/ della sequenzaDimensione stimatasoftware
+ SincronizzaTempo stimatoNessun encoder quiLarghezza
@@ -164,6 +172,7 @@
Renderizza · {0}Render completatoRender in coda
+ Render in coda su {0}Mostra nella cartellaRenderizzaRipristina
@@ -171,6 +180,7 @@
Modifiche non salvateRiprovaSezioni
+ mancano {0}LunghezzaMediaMediana
diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx
index 2d899232..c197722d 100644
--- a/i18n/it/Tooltips.it.resx
+++ b/i18n/it/Tooltips.it.resx
@@ -114,6 +114,7 @@
Clic o trascina per mostrare quel fotogrammaForma d’onda della luma del fotogramma a schermo: esposizione e clipping a colpo d’occhioLuma del fotogramma corretto lungo l’immagine: bianco in alto, nero in basso
+ Riporta il progetto com’era prima del ripristino · Ctrl+ZMette in coda questo render; puoi continuare a modificareApplica questo preset di sequenza a tutte le sezioni · {0}Mette in coda i preset spuntati come un unico lavoro; la sequenza si prepara una volta
@@ -124,6 +125,7 @@
MP4, AVI, GIF, APNG o una cartella di immagini; l’elenco dei codec si adeguaEncoder di questo PC; Auto preferisce l’hardwareDove vanno i render: {0}
+ I render di una sequenza del server vanno nella sua cartella exports sul serverFotogrammi al secondo del file videoAuto: i {0} fps del presetTorna ai fotogrammi al secondo del preset
@@ -134,7 +136,14 @@
Renderizza con {0}; modificare un valore lo rende PersonalizzatoQualità dell’immagine; 95 sembra senza perdite, meno fa file più piccoliScelta del consulente: {0}
+ Rende progetto le impostazioni di questo PC conservate il {0}; Ctrl+Z annulla
+ Scegli un’altra copia delle impostazioni di questo PC, conservata quando un conflitto di sincronizzazione è stato risoltoInserisci una dimensione tra 16 e 16384 pixel
+ Dopo ogni render su questo PC invia il file anche al server; i file grandi richiedono tempo
+ Il tuo account non può inviare file al server
+ Il server non ha questa sequenza: caricala prima dalla schermata Server
+ I render di una sequenza del server si fanno sul server e restano lì
+ Connettiti prima al server per inviargli i renderLarghezza in pixel; vuoto usa il preset o la sorgente · Invio applica, Esc annullaElimina lo sfarfallio di luminosità tra fotogrammi; spento lascia l’esposizione della fotocameraTrasforma i salti di ISO, tempo e diaframma in rampe morbide; spento li lascia
@@ -148,7 +157,7 @@
Clic o trascina per mostrare un fotogramma; i segni indicano salti di esposizione, avvisi e fotogrammi chiaveLascia fuori questo fotogramma da ogni render; la foto non viene eliminataMostra il primo fotogramma interessato
- Rende questo fotogramma la copertina; l’editor si apre qui
+ Usa il fotogramma come copertina della sequenzaUsa di nuovo questo fotogramma nei renderOrdina per questa colonna; un altro clic inverteFai clic su una riga per mostrare il fotogramma
@@ -183,6 +192,7 @@
Mostra o nasconde i dati di scattoSovrappone il movimento verso il fotogramma successivo misurato dal motoreTrascina la linea per confrontare · trascina per spostare · la rotellina ingrandisce · doppio clic 1:1
+ Modificata con i proxy su questo PC; le modifiche si salvano su {0} e analisi e render vengono eseguiti lìRenderizza con il preset scelto; avanzamento nella barra dei lavori · Ctrl+RCorreggi prima il nome del file: {0}Tutti i fotogrammi sono esclusi: includine alcuni nella scheda Fotogrammi
@@ -192,6 +202,7 @@
Scegli un altro presetRiporta in Auto ogni controllo di questa sezione · Ctrl+Z annullaProva a salvare ora; il salvataggio viene anche ritentato da solo
+ {0} in corso su {1}Fotogrammi combinati in ogni fotogramma d’uscita; scie e levigatura crescono con essoMediana e media tolgono rumore e ciò che si muove; le scie stellari tengono i pixel più luminosiRitaglio, formato, movimenti della camera virtuale
diff --git a/src/Titano.App/DesignTime/SampleData.cs b/src/Titano.App/DesignTime/SampleData.cs
index 49ff67d8..9adecab5 100644
--- a/src/Titano.App/DesignTime/SampleData.cs
+++ b/src/Titano.App/DesignTime/SampleData.cs
@@ -48,6 +48,9 @@ public sealed class SampleData
private SampleData(AppServices services) => _services = services;
+ /// The server-only sequence whose proxies keeps on this PC (Sunrise over Superga).
+ public Guid ProxiedSequenceId => _sunrise;
+
/// Points the services at fakes (server, encoders, update check) for an empty first-run state.
public static SampleData Configure(AppServices services)
{
@@ -61,6 +64,7 @@ public sealed class SampleData
services.Devices = new SampleDeviceMonitor();
var sample = new SampleData(services);
services.Sync.RemoteFactory = (_, _, _) => sample._remote;
+ services.Sync.EditorFactory = (_, _, _) => sample._remote;
return sample;
}
@@ -617,13 +621,15 @@ public sealed class SampleData
}
///
- /// 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); uploads, originals and
+ /// analysis reports are not part of the screenshots.
///
- private sealed class SampleSyncRemote : ISyncRemote
+ private sealed class SampleSyncRemote : ISyncRemote, IRemoteSequenceApi
{
private readonly Dictionary _sequences = [];
+ private readonly Dictionary _jobs = [];
public string Server => ServerAddress;
@@ -707,6 +713,26 @@ public sealed class SampleData
yield break;
}
+ public Task GetAnalysisReportAsync(Guid id, CancellationToken cancellationToken) => Task.FromResult(null);
+
+ public Task 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);
+ }
+
+ public Task GetJobAsync(Guid id, CancellationToken cancellationToken)
+ {
+ lock (_jobs) return Task.FromResult(_jobs[id]);
+ }
+
+ public Task> ListActiveJobsAsync(CancellationToken cancellationToken)
+ {
+ lock (_jobs) return Task.FromResult>([.. _jobs.Values]);
+ }
+
public void Dispose()
{
}
diff --git a/src/Titano.App/Editor/EditorPanels.xaml b/src/Titano.App/Editor/EditorPanels.xaml
index 0ce71b18..1f0825f5 100644
--- a/src/Titano.App/Editor/EditorPanels.xaml
+++ b/src/Titano.App/Editor/EditorPanels.xaml
@@ -1,6 +1,7 @@
@@ -288,10 +289,15 @@
+ ToolTip="{l:Loc Tooltips.Editor.Render.Reveal}" Margin="6,0,0,0" Visibility="{Binding CanReveal, Converter={StaticResource BoolToVisibility}}" />
+
+
@@ -399,8 +405,17 @@
shell:EditBehavior.Field="{Binding NameTemplate}" ToolTip="{Binding NameTemplate.ToolTip}" AutomationProperties.Name="{l:Loc Editor.Export.FileName}" />
-
+
+
+
+
+
+
+
+
+
diff --git a/src/Titano.App/Editor/EditorSession.cs b/src/Titano.App/Editor/EditorSession.cs
index 26b79100..514d3e54 100644
--- a/src/Titano.App/Editor/EditorSession.cs
+++ b/src/Titano.App/Editor/EditorSession.cs
@@ -51,6 +51,9 @@ public sealed class EditorSession : IAsyncDisposable
public ISequenceSource Source { get; }
+ /// A server sequence edited with proxies: saved, analysed and rendered on the server.
+ public bool IsRemote => Source.IsRemote;
+
public SequenceContent Content { get; private set; }
public SequenceContext Context { get; private set; }
@@ -133,6 +136,25 @@ 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);
+ ///
+ /// The jobs that render 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).
+ ///
+ public IReadOnlyList RenderRequests(ExportSettings export) => IsRemote
+ ? ProcessingJobs.RenderEach(Content.Sequence, export, Content.SourceWidth, Content.SourceHeight, Project with { Export = export })
+ : [RenderRequest(export)];
+
+ ///
+ /// Makes a "Save both" copy of this PC's settings the project, as one undoable step; false when it stores the same values.
+ ///
+ /// The copy cannot be read.
+ public async Task RestoreAsync(SavedCopy copy)
+ {
+ ArgumentNullException.ThrowIfNull(copy);
+ var restored = await Task.Run(() => SavedCopies.Read(copy));
+ return Edit(_ => restored);
+ }
+
/// The export of the project with preset chosen (own values, no batch).
public ExportSettings ExportFor(string presetId) =>
Project.Export with { Preset = Project.Export.Preset.WithManual(presetId), Overrides = new ExportOverrides(), Batch = [] };
diff --git a/src/Titano.App/Editor/EditorTab.cs b/src/Titano.App/Editor/EditorTab.cs
index ef8314ed..c728295c 100644
--- a/src/Titano.App/Editor/EditorTab.cs
+++ b/src/Titano.App/Editor/EditorTab.cs
@@ -84,6 +84,11 @@ public abstract class EditorTab : LocalizedViewModel
{
}
+ /// Whether this sequence can send its renders to the server changed ().
+ public virtual void OnSyncGateChanged()
+ {
+ }
+
public override void Dispose()
{
foreach (var row in Rows) row.Dispose();
diff --git a/src/Titano.App/Editor/EditorText.cs b/src/Titano.App/Editor/EditorText.cs
index b9830240..fe04a36b 100644
--- a/src/Titano.App/Editor/EditorText.cs
+++ b/src/Titano.App/Editor/EditorText.cs
@@ -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,24 @@ public static class EditorText
return string.Join(Separator, parts);
}
+ /// "Render · 46 %": a job the server runs for a server sequence (the job bar shows this PC's jobs only).
+ public static string ServerJob(Job job)
+ {
+ ArgumentNullException.ThrowIfNull(job);
+ return job.ProgressTotal > 0 ? JobText.Kind(job.Kind) + Separator + Formatting.Percent((double)job.ProgressDone / job.ProgressTotal) : JobText.Kind(job.Kind);
+ }
+
+ /// "Render running on Studio NAS · 1,240 / 3,600 · 11.3 fps · 3 min left".
+ public static string ServerJobDetail(Job job, string server)
+ {
+ ArgumentNullException.ThrowIfNull(job);
+ var parts = new List { Loc.L("Tooltips.Editor.ServerJob", 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);
+ }
+
/// "3,600 frames · 24 fps · 2 min 30 s · 3840×2160 · source 8192×5464": what the export makes of the sequence (Export.html header).
public static string OutputSummary(SequenceContent content, ExportPlan plan)
{
diff --git a/src/Titano.App/Editor/EditorViewModel.cs b/src/Titano.App/Editor/EditorViewModel.cs
index 22d0dcf0..e6dd82b8 100644
--- a/src/Titano.App/Editor/EditorViewModel.cs
+++ b/src/Titano.App/Editor/EditorViewModel.cs
@@ -69,6 +69,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
private IThumbnailSource _thumbnails;
private int _playLimit;
private double? _analysisSecondsPerFrame;
+ private ExportSyncGate _syncGate = ExportSyncGate.SignedOut;
private bool _disposed;
public EditorViewModel(ShellViewModel shell, EditorSession session, IReadOnlyList encoders, EncoderHost host)
@@ -107,7 +108,8 @@ 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.Source.JobChanged += OnJobChanged;
+ shell.Services.Sync.Changed += OnSyncChanged;
UpdateMarkers();
RequestCorrections();
RequestPlan();
@@ -122,6 +124,25 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
public string Title => Session.Content.Sequence.DisplayTitle;
+ /// A server sequence edited with proxies (the header says where it lives).
+ public bool IsRemote => Session.IsRemote;
+
+ /// "Studio NAS" beside the title of a server sequence.
+ public string? RemoteText => IsRemote ? Shell.Services.Server.ServerName ?? Loc.L("Server.Label.Server") : null;
+
+ public string? RemoteToolTip => IsRemote ? Loc.L("Tooltips.Editor.Remote", RemoteText ?? string.Empty) : null;
+
+ /// "Render · 46 %" while an analysis or render of a server sequence runs on the server (the job bar shows this PC's jobs).
+ public string? ServerJobText => ServerJob is { } job ? EditorText.ServerJob(job) : null;
+
+ /// Frames, speed and time left of the server job.
+ public string? ServerJobToolTip => ServerJob is { } job ? EditorText.ServerJobDetail(job, RemoteText ?? string.Empty) : null;
+
+ /// The Export "Sync" option: available, or why not.
+ public ExportSyncGate SyncGate { get => _syncGate; private set => Set(ref _syncGate, value); }
+
+ private Job? ServerJob => IsRemote ? _jobs.Values.Where(j => j.State == JobState.Running).OrderBy(j => j.Started).FirstOrDefault() : null;
+
///
/// "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).
@@ -364,7 +385,8 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
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 +421,17 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
/// "Optimise section": the advisor's heavier decisions, reported in a toast (what changed, from what to what).
public void Optimise(AdvisorSection section) => Report(Session.Optimise(section));
- /// Queues a render of the project's export (with its batch presets when ).
+ ///
+ /// Queues a render of the project's export (with its batch presets when ): on this PC's
+ /// engine, or one server job per preset for a server sequence.
+ ///
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 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", RemoteText ?? string.Empty), 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));
}
/// Re-reads the enabled state of every command (the async ones keep their own event).
@@ -452,14 +478,29 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
Task[] Work() => [_preview.Idle, _corrections.Idle, _plans.Idle, .. Tabs.OfType().Select(t => t.EstimatesIdle)];
}
- /// Loads the jobs of this sequence already queued or running (busy state) and the speed of the last analysis.
+ ///
+ /// 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.
+ ///
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);
+ var jobs = await Session.Source.ListJobsAsync(CancellationToken.None);
+ foreach (var job in jobs) Track(job);
+ foreach (var job in jobs.OrderBy(j => j.Finished)) LearnAnalysisSpeed(job);
OnBusyChanged();
+ await RefreshSyncGateAsync();
+ }
+
+ /// Reads again whether this sequence can send its renders to the signed-in server (session, link, rights).
+ 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()
@@ -473,7 +514,8 @@ 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.Source.JobChanged -= OnJobChanged;
+ Shell.Services.Sync.Changed -= OnSyncChanged;
foreach (var tab in Tabs) tab.Dispose();
base.Dispose();
await Session.DisposeAsync();
@@ -757,6 +799,22 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
});
}
+ /// The session, the sync links or the rights changed (any thread): whether the Export "Sync" option applies.
+ 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);
+ }
+ }
+
private void Track(Job job)
{
if (!job.TargetIds.Contains(Session.Content.Sequence.Id) || job.Kind is not (JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render)) return;
@@ -777,13 +835,17 @@ 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)
{
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"),
@@ -802,6 +864,8 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
OnPropertyChanged(nameof(BusyToolTip));
OnPropertyChanged(nameof(AnalyseToolTip));
OnPropertyChanged(nameof(OptimiseAllToolTip));
+ OnPropertyChanged(nameof(ServerJobText));
+ OnPropertyChanged(nameof(ServerJobToolTip));
foreach (var tab in Tabs) tab.OnBusyChanged();
RefreshCommands();
}
diff --git a/src/Titano.App/Editor/ExportSync.cs b/src/Titano.App/Editor/ExportSync.cs
new file mode 100644
index 00000000..8ddce131
--- /dev/null
+++ b/src/Titano.App/Editor/ExportSync.cs
@@ -0,0 +1,70 @@
+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;
+
+/// Whether the Export "Sync" option can be used, or why not (its tooltip says which).
+public enum ExportSyncGate
+{
+ Available,
+
+ /// A server sequence: its renders are made on the server and stay there.
+ Remote,
+
+ /// No server session is open.
+ SignedOut,
+
+ /// The server does not have this sequence.
+ NotLinked,
+
+ /// The account may not send files to the server.
+ NoUpload,
+}
+
+///
+/// Export "Sync" (Export.html, 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 (), while signed in with
+/// the Upload right. The choice travels inside the render job (its export), so it holds after the editor closes.
+///
+public sealed class ExportSync(TitanoDatabase db, SyncService sync, JobEngine engine)
+{
+ /// The option's state for a sequence.
+ /// Key of the signed-in server; null while signed out.
+ /// The server has the sequence (a sync link joins them).
+ 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;
+
+ ///
+ /// Queues sending a finished render's output; returns the send job, or null when the job is not a finished render
+ /// of this PC that asked for it, or the sequence cannot be sent now.
+ ///
+ public async Task 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;
+ if (Gate(false, server, linked, canUpload) != ExportSyncGate.Available) return null;
+ return await sync.EnqueueSendExportsAsync(engine, server!, local, cancellationToken);
+ }
+
+ private static bool Wanted(Job job)
+ {
+ try
+ {
+ return ProcessingJobs.ReadRender(job.ParametersJson).Export.SyncToServer;
+ }
+ catch (InvalidDataException)
+ {
+ return false;
+ }
+ }
+}
diff --git a/src/Titano.App/Editor/ExportTab.cs b/src/Titano.App/Editor/ExportTab.cs
index d536157d..e6d3a34b 100644
--- a/src/Titano.App/Editor/ExportTab.cs
+++ b/src/Titano.App/Editor/ExportTab.cs
@@ -106,6 +106,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 _cards = [];
private IReadOnlyList _codecChoices = [];
private IReadOnlyList _encoders = [];
@@ -122,11 +124,13 @@ public sealed class ExportTab : EditorTab
_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.IsBusy && 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();
}
@@ -153,6 +157,62 @@ public sealed class ExportTab : EditorTab
public bool HasHistory => Editor.Session.Content.Renders.Count > 0;
+ /// The newest render is a file on this PC (a server's renders stay on the server).
+ public bool CanReveal => Editor.Session.Content.Renders is [{ OutputPath.Length: > 0 }, ..];
+
+ // ---- Export "Sync" (Export.html, next to Save to) ----
+
+ /// Send each render made on this PC to the server the sequence is linked to; remembered in the project.
+ 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;
+
+ /// What Sync does, or why it cannot be used for this sequence now.
+ 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",
+ });
+
+ /// A server sequence renders into its exports folder on the server.
+ public bool CanChooseFolder => !Editor.IsRemote;
+
+ // ---- "Save both" copies of this PC's settings ----
+
+ public IReadOnlyList SavedCopies => Editor.Session.Content.SavedCopies;
+
+ public bool HasSavedCopies => SavedCopies.Count > 0;
+
+ /// The copy Restore makes the project: the newest unless another is chosen in the menu.
+ public SavedCopy? SelectedCopy
+ {
+ get => _selectedCopy;
+ set
+ {
+ if (!Set(ref _selectedCopy, value)) return;
+ OnPropertyChanged(nameof(RestoreText));
+ OnPropertyChanged(nameof(RestoreToolTip));
+ _restore.RaiseCanExecuteChanged();
+ }
+ }
+
+ /// "Restore · 03/10/2026 14:22".
+ public string RestoreText => Loc.L("Editor.Export.Restore", SelectedCopy?.Label ?? string.Empty);
+
+ public string RestoreToolTip => Editor.IsBusy ? Loc.L("Tooltips.Editor.Busy") : Loc.L("Tooltips.Editor.Export.Restore", SelectedCopy?.Label ?? string.Empty);
+
+ public ICommand RestoreCommand => _restore;
+
public ICommand ResetFrameRateCommand { get; }
/// "Output · 4K archive".
@@ -287,7 +347,9 @@ 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;
@@ -370,6 +432,7 @@ public sealed class ExportTab : EditorTab
public override void OnContentChanged()
{
LoadCards();
+ if (SelectedCopy is null || !SavedCopies.Contains(SelectedCopy)) SelectedCopy = SavedCopies.FirstOrDefault();
base.OnContentChanged();
}
@@ -378,8 +441,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()
@@ -434,6 +505,26 @@ public sealed class ExportTab : EditorTab
for (var i = 0; i < cards.Count; i++) cards[i].Update(plans[i]);
}
+ /// Makes the chosen copy the project as one undo step; the toast offers Undo.
+ private async Task RestoreAsync()
+ {
+ if (SelectedCopy is not { } copy) return;
+ try
+ {
+ if (!await Editor.Session.RestoreAsync(copy))
+ {
+ Editor.Shell.Notify(Loc.L("Editor.Copy.Same"), copy.Label);
+ return;
+ }
+ }
+ catch (InvalidDataException ex)
+ {
+ Editor.Shell.ReportError(ex);
+ return;
+ }
+ Editor.Shell.Notify(Loc.L("Editor.Copy.Restored"), copy.Label, Loc.L("Editor.Copy.Undo"), Loc.L("Tooltips.Editor.Copy.Undo"), () => Editor.Session.Undo());
+ }
+
private void OpenHistory()
{
Editor.Shell.Jobs.Filter = Jobs.JobFilter.All;
diff --git a/src/Titano.App/Editor/IRemoteSequenceApi.cs b/src/Titano.App/Editor/IRemoteSequenceApi.cs
new file mode 100644
index 00000000..718f4071
--- /dev/null
+++ b/src/Titano.App/Editor/IRemoteSequenceApi.cs
@@ -0,0 +1,33 @@
+using Titano.Protocol;
+using Titano.Protocol.Client;
+
+namespace Titano.App.Editor;
+
+///
+/// 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 s (404 gone, 409 settings
+/// changed meanwhile) or network exceptions. The editor disposes its connection when it closes.
+///
+public interface IRemoteSequenceApi : IDisposable
+{
+ Task GetSequenceAsync(Guid id, CancellationToken cancellationToken);
+
+ /// The settings JSON and its version, the frames and the renders.
+ Task GetManifestAsync(Guid id, CancellationToken cancellationToken);
+
+ /// A 409 means the settings version moved on the server.
+ Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken);
+
+ /// The full deep-analysis report (analysis.json); null when the sequence was never deep-analysed.
+ Task GetAnalysisReportAsync(Guid id, CancellationToken cancellationToken);
+
+ Task CreateJobAsync(CreateJobRequest request, CancellationToken cancellationToken);
+
+ Task GetJobAsync(Guid id, CancellationToken cancellationToken);
+
+ /// Jobs waiting or running on the server.
+ Task> ListActiveJobsAsync(CancellationToken cancellationToken);
+
+ /// Server events until cancelled or the socket closes.
+ IAsyncEnumerable EventsAsync(CancellationToken cancellationToken);
+}
diff --git a/src/Titano.App/Editor/ISequenceSource.cs b/src/Titano.App/Editor/ISequenceSource.cs
index 1423c73f..4ffde1b5 100644
--- a/src/Titano.App/Editor/ISequenceSource.cs
+++ b/src/Titano.App/Editor/ISequenceSource.cs
@@ -9,11 +9,20 @@ namespace Titano.App.Editor;
///
/// Where the sequence open in the editor lives: the local archive () 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 (: 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.
///
public interface ISequenceSource : IAsyncDisposable
{
+ ///
+ /// 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.
+ ///
+ bool IsRemote { get; }
+
+ /// A job that may concern the sequence changed (any thread): this PC's engine, or the server's events.
+ event Action? JobChanged;
+
/// Everything the editor shows of the sequence; read off the UI thread.
/// The project cannot be read (corrupt, or written by a newer Titano).
Task LoadAsync(CancellationToken cancellationToken);
@@ -33,6 +42,9 @@ public interface ISequenceSource : IAsyncDisposable
/// Queues an analysis or render job for the sequence; returns the job id.
Task SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken);
+
+ /// Recent jobs that may concern the sequence (queued, running, finished), for the busy state and the cost of Analyse.
+ Task> ListJobsAsync(CancellationToken cancellationToken);
}
/// A sequence as the editor opens it.
@@ -41,7 +53,8 @@ public interface ISequenceSource : IAsyncDisposable
/// The saved deep analysis when it describes the current frames, else null.
/// Dominant oriented full-resolution width (0 when unknown).
/// Default output folder of renders; null when the sequence is not on this PC.
-/// Finished renders, newest first.
+/// Finished renders, newest first (an empty output path when the file is not on this PC).
+/// This PC's projects kept by "Save both" when a sync conflict was settled, newest first.
public sealed record SequenceContent(
Sequence Sequence,
IReadOnlyList Frames,
@@ -51,7 +64,8 @@ public sealed record SequenceContent(
int SourceWidth,
int SourceHeight,
string? ExportsFolder,
- IReadOnlyList Renders)
+ IReadOnlyList Renders,
+ IReadOnlyList SavedCopies)
{
/// Flags of frames that never reach a render (as the render job skips them).
public const FrameFlags NotRendered = FrameFlags.Missing | FrameFlags.Corrupt | FrameFlags.Excluded | FrameFlags.Undecodable;
diff --git a/src/Titano.App/Editor/LocalSequenceSource.cs b/src/Titano.App/Editor/LocalSequenceSource.cs
index 1b67b25c..0de57ef6 100644
--- a/src/Titano.App/Editor/LocalSequenceSource.cs
+++ b/src/Titano.App/Editor/LocalSequenceSource.cs
@@ -20,33 +20,56 @@ namespace Titano.App.Editor;
///
/// A sequence of an archive on this PC: rows from the index, originals decoded by the client's decoder chain, the
-/// project in .titano/project.json 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 .titano/project.json 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.
///
-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 event Action? JobChanged;
+
+ /// A save changed the frame the Library shows for the sequence: the stored row (any thread).
+ public event Action? HeroChanged;
+
public async Task 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();
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 +79,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 +95,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 +109,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 +143,19 @@ public sealed class LocalSequenceSource(TitanoDatabase db, Guid sequenceId, Imag
public async Task 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> ListJobsAsync(CancellationToken cancellationToken) =>
+ (await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items;
+
+ public ValueTask DisposeAsync()
+ {
+ if (_engine is not null) _engine.JobChanged -= OnJobChanged;
+ return ValueTask.CompletedTask;
+ }
/// The settings in force: the index copy, else project.json, else defaults.
/// The settings are not a project or come from a newer Titano.
@@ -141,6 +173,10 @@ public sealed class LocalSequenceSource(TitanoDatabase db, Guid sequenceId, Imag
}
}
+ /// The frame of the project's hero, or (the first frame shows) without one.
+ private static Guid HeroFrameId(ProjectSettings project, Guid[] frameIds) =>
+ project.HeroFrame is { } hero && (uint)hero < (uint)frameIds.Length ? frameIds[hero] : Guid.Empty;
+
/// The saved deep report when it describes the current frames.
private static DeepAnalysisReport? ReadReport(SequencePaths folder, int frameCount)
{
@@ -157,5 +193,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"));
}
diff --git a/src/Titano.App/Editor/RemoteSequenceSource.cs b/src/Titano.App/Editor/RemoteSequenceSource.cs
new file mode 100644
index 00000000..a237f17e
--- /dev/null
+++ b/src/Titano.App/Editor/RemoteSequenceSource.cs
@@ -0,0 +1,302 @@
+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;
+
+///
+/// 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 (), 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 as
+/// the local archive does (: the editor wins on members both changed). Nothing is written to a
+/// local archive. Analyses and renders are server jobs; their state and progress come from the server's events.
+///
+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 _jobs = new();
+ private readonly ConcurrentDictionary _foreign = new();
+ private readonly CancellationTokenSource _stopping = new();
+ private readonly Task _listening;
+ private ProjectSettings? _stored;
+ private int _version;
+
+ public RemoteSequenceSource(RemoteSequence remote, IRemoteSequenceApi api, ImageDecoder decoder)
+ {
+ ArgumentNullException.ThrowIfNull(remote);
+ ArgumentNullException.ThrowIfNull(api);
+ ArgumentNullException.ThrowIfNull(decoder);
+ _remote = remote;
+ _api = api;
+ _frames = remote.OpenFrames(decoder);
+ _pixels = (IFrameSource)_frames;
+ var stopping = _stopping.Token;
+ _listening = Task.Run(() => ListenAsync(stopping), CancellationToken.None);
+ }
+
+ public bool IsRemote => true;
+
+ public event Action? JobChanged;
+
+ /// The server sequence's id.
+ public Guid Id => _remote.Sequence.Id;
+
+ public async Task LoadAsync(CancellationToken cancellationToken)
+ {
+ var dto = await Call(() => _api.GetSequenceAsync(Id, cancellationToken));
+ var manifest = await Call(() => _api.GetManifestAsync(Id, cancellationToken));
+ var report = await Call(() => _api.GetAnalysisReportAsync(Id, cancellationToken));
+ return await Task.Run(() =>
+ {
+ var project = Parse(manifest.SettingsJson);
+ (_stored, _version) = (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 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 SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(project);
+ ArgumentNullException.ThrowIfNull(basis);
+ for (var attempt = 1; ; attempt++)
+ {
+ var stored = _stored ?? throw new InvalidOperationException("LoadAsync first.");
+ var merged = ProjectMerge.SameValues(stored, basis) ? project : ProjectMerge.Merge(basis, project, stored);
+ if (ProjectMerge.SameValues(merged, stored)) return merged;
+ 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));
+ (_stored, _version) = (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));
+ (_stored, _version) = (Parse(manifest.SettingsJson), manifest.SettingsVersion);
+ }
+ }
+ }
+
+ public async Task SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
+ {
+ ArgumentNullException.ThrowIfNull(request);
+ var dto = await Call(() => _api.CreateJobAsync(new CreateJobRequest(JobWire.Kind(request.Kind), request.Targets, request.ParametersJson), 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> ListJobsAsync(CancellationToken cancellationToken)
+ {
+ var active = await Call(() => _api.ListActiveJobsAsync(cancellationToken));
+ var mine = active.Select(JobWire.FromDto).OfType().Where(Concerns).ToList();
+ foreach (var job in mine) _jobs[job.Id] = job;
+ return mine;
+ }
+
+ public async ValueTask DisposeAsync()
+ {
+ await _stopping.CancelAsync();
+ await _listening;
+ _stopping.Dispose();
+ if (_frames is IAsyncDisposable frames) await frames.DisposeAsync();
+ _api.Dispose();
+ }
+
+ /// Follows the server's job events, reconnecting with a growing delay (events lost meanwhile are read back from the job).
+ private async Task ListenAsync(CancellationToken cancellationToken)
+ {
+ var failures = 0;
+ while (!cancellationToken.IsCancellationRequested)
+ {
+ try
+ {
+ await foreach (var e in _api.EventsAsync(cancellationToken).ConfigureAwait(false))
+ {
+ failures = 0;
+ await OnEventAsync(e, cancellationToken).ConfigureAwait(false);
+ }
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ return;
+ }
+ catch (Exception ex) when (ex is not OutOfMemoryException)
+ {
+ Log.Info("editor", $"Events of the server lost for {_remote.Sequence.DisplayTitle}: {ex.Message}");
+ }
+ try
+ {
+ await Task.Delay(TimeSpan.FromTicks(Math.Min(MaxBackoff.Ticks, MinBackoff.Ticks << Math.Min(failures++, 10))), cancellationToken).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException)
+ {
+ return;
+ }
+ await RefreshTrackedAsync(cancellationToken).ConfigureAwait(false);
+ }
+ }
+
+ private async Task OnEventAsync(ServerEvent e, CancellationToken cancellationToken)
+ {
+ switch (e)
+ {
+ case JobProgressEvent progress when _jobs.TryGetValue(progress.JobId, out var job):
+ 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;
+ }
+ }
+
+ /// Reads a job the events named: tracked when it concerns this sequence, remembered as foreign otherwise.
+ 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}");
+ }
+ }
+
+ /// After a lost event socket: the tracked jobs as the server has them now.
+ 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);
+ }
+
+ private bool Concerns(Job job) => job.TargetIds.Contains(Id) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
+
+ /// The frame of the project's hero, or (the first frame shows) without one.
+ private Guid HeroFrameId(ProjectSettings project) =>
+ project.HeroFrame is { } hero && (uint)hero < (uint)_remote.Frames.Count ? _remote.Frames[hero].Id : Guid.Empty;
+
+ /// The settings are not a project or come from a newer Titano.
+ 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);
+ }
+ }
+
+ /// The server's deep report when it describes the frames this PC has.
+ 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;
+ }
+ }
+
+ /// A sequence deleted on the server reads as gone, like a local one removed from the index.
+ private static async Task Call(Func> call)
+ {
+ try
+ {
+ return await call();
+ }
+ catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
+ {
+ throw new InvalidOperationException(Loc.L("Editor.Error.Missing"), ex);
+ }
+ }
+}
diff --git a/src/Titano.App/Editor/SavedCopies.cs b/src/Titano.App/Editor/SavedCopies.cs
new file mode 100644
index 00000000..cf4c2513
--- /dev/null
+++ b/src/Titano.App/Editor/SavedCopies.cs
@@ -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;
+
+/// This PC's project kept by "Save both" when a sync conflict was settled (BRIEF §12.7), local time of the choice.
+public sealed record SavedCopy(string Path, DateTime SavedAt)
+{
+ /// "03/10/2026 14:22" in the user's format.
+ public string Label => SavedAt.ToString("g", Loc.Culture);
+}
+
+/// The "Save both" copies of a sequence: .titano/project.this-pc-<time>.json beside project.json.
+public static class SavedCopies
+{
+ /// The copies in a sequence's .titano folder, newest first; none when the folder cannot be read.
+ public static IReadOnlyList 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 [];
+ }
+ }
+
+ /// The project of a copy.
+ /// The copy is gone, unreadable, or not a project of this Titano.
+ 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);
+ }
+ }
+}
diff --git a/src/Titano.App/Sections/SequenceView.xaml b/src/Titano.App/Sections/SequenceView.xaml
index 24bd5fe0..53e63f9c 100644
--- a/src/Titano.App/Sections/SequenceView.xaml
+++ b/src/Titano.App/Sections/SequenceView.xaml
@@ -45,8 +45,14 @@
-
+
+
+
+
+
+
diff --git a/src/Titano.App/Sections/SequenceViewModel.cs b/src/Titano.App/Sections/SequenceViewModel.cs
index 685347a3..1e2c9fed 100644
--- a/src/Titano.App/Sections/SequenceViewModel.cs
+++ b/src/Titano.App/Sections/SequenceViewModel.cs
@@ -1,5 +1,6 @@
using System.ComponentModel;
using System.Windows.Input;
+using System.Windows.Threading;
using Titano.App.Editor;
using Titano.App.Infrastructure;
using Titano.App.Shell;
@@ -7,18 +8,20 @@ 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.Ui.Mvvm;
namespace Titano.App.Sections;
///
-/// The Sequence section (BRIEF §12.3): opens the sequence the Library (or Jobs) chose into an
-/// 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
+/// (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 failed open is reported and leaves the
+/// section usable; an edit that cannot be saved is never dropped without the user's confirmation.
///
public sealed class SequenceViewModel : SectionViewModel
{
+ private readonly Dispatcher _dispatcher = Dispatcher.CurrentDispatcher;
private EditorViewModel? _editor;
private Guid? _openId;
private bool _isLoading;
@@ -112,6 +115,35 @@ public sealed class SequenceViewModel : SectionViewModel
if (e.PropertyName == nameof(ShellViewModel.CurrentSequenceId) && IsSelected) OnActivated();
}
+ ///
+ /// Where 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).
+ ///
+ private async Task 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 not null)
+ {
+ var local = new LocalSequenceSource(db, sequenceId, decoder, services.Engine, processing?.Archive);
+ local.HeroChanged += OnHeroChanged;
+ return local;
+ }
+ var sync = services.Sync;
+ if (sync.Server is not { } server || sync.Service?.OpenRemote(server, sequenceId) is not { } remote) throw new InvalidOperationException(Loc.L("Editor.Error.Missing"));
+ // An editor whose saves the server refuses would only lose edits.
+ if (!sync.Policy.CanEdit) throw new InvalidOperationException(Loc.L("Editor.Error.RemoteReadOnly"));
+ var api = sync.ConnectEditor() ?? throw new InvalidOperationException(Loc.L("Editor.Error.Missing"));
+ return new RemoteSequenceSource(remote, api, decoder);
+ }
+
+ /// Set hero changed the frame the Library shows (any thread): its card loads the new thumbnail.
+ private void OnHeroChanged(Sequence row) => _dispatcher.BeginInvoke(() =>
+ {
+ if (Shell.Library.Items.FirstOrDefault(i => i.Id == row.Id) is { } item) item.Update(row);
+ });
+
/// Waits for ; its failure was reported where it happened.
private static async Task Settled(Task task)
{
@@ -142,11 +174,18 @@ public sealed class SequenceViewModel : SectionViewModel
await old.DisposeAsync();
}
_openId = sequenceId;
- if (services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
+ var source = await OpenSourceAsync(services, sequenceId);
+ SequenceContent content;
+ try
+ {
+ content = await source.LoadAsync(CancellationToken.None);
+ }
+ 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);
diff --git a/src/Titano.App/Server/RemoteSequenceApi.cs b/src/Titano.App/Server/RemoteSequenceApi.cs
new file mode 100644
index 00000000..5b4efd25
--- /dev/null
+++ b/src/Titano.App/Server/RemoteSequenceApi.cs
@@ -0,0 +1,38 @@
+using Titano.App.Editor;
+using Titano.Protocol;
+using Titano.Protocol.Client;
+
+namespace Titano.App.Server;
+
+/// Makes the connection of the editor of a server sequence for a signed-in session.
+public delegate IRemoteSequenceApi RemoteSequenceApiFactory(Uri address, string token, IReadOnlyCollection trustedFingerprints);
+
+/// over a signed-in , which it owns.
+public sealed class TitanoRemoteSequenceApi(TitanoClient client) : IRemoteSequenceApi
+{
+ private static readonly string[] ActiveStates = ["queued", "running", "paused"];
+
+ public Task GetSequenceAsync(Guid id, CancellationToken cancellationToken) => client.GetSequenceAsync(id, cancellationToken);
+
+ public Task GetManifestAsync(Guid id, CancellationToken cancellationToken) => client.GetManifestAsync(id, cancellationToken);
+
+ public Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) =>
+ client.UpdateSequenceAsync(id, request, cancellationToken);
+
+ public Task GetAnalysisReportAsync(Guid id, CancellationToken cancellationToken) => client.GetAnalysisReportAsync(id, cancellationToken);
+
+ public Task CreateJobAsync(CreateJobRequest request, CancellationToken cancellationToken) => client.CreateJobAsync(request, cancellationToken);
+
+ public Task GetJobAsync(Guid id, CancellationToken cancellationToken) => client.GetJobAsync(id, cancellationToken);
+
+ public async Task> ListActiveJobsAsync(CancellationToken cancellationToken)
+ {
+ var jobs = new List();
+ foreach (var state in ActiveStates) jobs.AddRange((await client.ListJobsAsync(state, null, cancellationToken)).Items);
+ return jobs;
+ }
+
+ public IAsyncEnumerable EventsAsync(CancellationToken cancellationToken) => client.EventsAsync(cancellationToken);
+
+ public void Dispose() => client.Dispose();
+}
diff --git a/src/Titano.App/Server/SyncHost.cs b/src/Titano.App/Server/SyncHost.cs
index 445cb56a..738e5992 100644
--- a/src/Titano.App/Server/SyncHost.cs
+++ b/src/Titano.App/Server/SyncHost.cs
@@ -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
///
/// This PC's sync with the signed-in server (BRIEF §4.4, §14.5): the of the index, the
/// connection of upload and download jobs (), a that keeps the
-/// table current while a session is open, started and stopped in order as the session changes, and the
-/// for metered connections. Options come from ,
-/// and .
+/// table current while a session is open, started and stopped in order as the session changes, the
+/// for metered connections, the connections of editors of server sequences
+/// () and the Export "Sync" of finished renders (). Options come from
+/// , and
+/// .
///
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;
/// Connections over ; screenshots substitute a fake server.
public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted) =>
new TitanoSyncRemote(new TitanoClient(address, new CertificatePinning(trusted), $"Titano ({Environment.MachineName})") { Token = token }, ownsClient: true);
+ /// Connections of editors of server sequences over ; screenshots substitute a fake server.
+ public RemoteSequenceApiFactory EditorFactory { get; set; } = (address, token, trusted) =>
+ new TitanoRemoteSequenceApi(new TitanoClient(address, new CertificatePinning(trusted), $"Titano ({Environment.MachineName})") { Token = token });
+
/// The engine; null until the index is open.
public SyncService? Service { get; private set; }
@@ -44,8 +53,10 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
public string? Server => Volatile.Read(ref _credentials) is { } c ? SyncService.ServerKey(c.Address) : null;
/// The options, and whether the account may change server sequences (without it this PC's edits are not sent).
- 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));
+
+ /// The signed-in account may send files (originals, renders) to the server.
+ public bool CanUpload => Allows(Permissions.Upload);
/// Pauses uploads while the connection is metered and the option is on.
public UploadHold Uploads { get; } = new(services);
@@ -74,9 +85,17 @@ 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;
+ _renders = engine;
+ engine.JobChanged += OnJobChanged;
}
+ /// A connection for the editor of a sequence of the signed-in server; null while signed out.
+ public IRemoteSequenceApi? ConnectEditor() =>
+ Volatile.Read(ref _credentials) is { } c ? EditorFactory(c.Address, c.Token, c.Fingerprints) : null;
+
/// Compares now, once the session switch in progress settled; null while signed out.
public async Task RefreshAsync(CancellationToken ct = default)
{
@@ -116,10 +135,33 @@ 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;
+
+ /// Export "Sync": a render of this PC that asked for it is sent to the server once done ().
+ 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;
+ _ = SendRenderAsync(new ExportSync(db, service, engine), job);
+ }
+
+ private async Task SendRenderAsync(ExportSync exports, Job job)
+ {
+ try
+ {
+ if (await exports.SendAsync(job, Server, CanUpload) is { } send) Log.Info("sync", $"{job.TargetLabel} will be sent to the server (job {send.Id})");
+ }
+ catch (Exception ex) when (ex is Data.DatabaseException or InvalidOperationException)
+ {
+ 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;
diff --git a/src/Titano.App/Shell/ScreenCapture.cs b/src/Titano.App/Shell/ScreenCapture.cs
index 60073f16..b592340e 100644
--- a/src/Titano.App/Shell/ScreenCapture.cs
+++ b/src/Titano.App/Shell/ScreenCapture.cs
@@ -17,7 +17,8 @@ namespace Titano.App.Shell;
///
/// Titano.exe --capture <dir>: renders every client screen at 1440×900 in the dark and light themes to
/// <screen>-<theme>.png from (first run on an empty index, then a populated
-/// one, then the sync table with transfers, a conflict and its confirmation), 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), for visual review and phase reports (BRIEF §20.2), then exits.
///
public static class ScreenCapture
{
@@ -134,6 +135,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;
}
@@ -224,6 +226,31 @@ public static class ScreenCapture
return written;
}
+ ///
+ /// 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 (sequence-remote-<theme>.png).
+ ///
+ private static async Task 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);
+ editor.SelectedTab = editor.Exposure;
+ foreach (var theme in Themes)
+ {
+ ThemeManager.Apply(theme);
+ written += await SaveEditorAsync(window, editor, directory, "sequence-remote", theme);
+ }
+ return written;
+ }
+
private static async Task SaveEditorAsync(Window window, EditorViewModel editor, string directory, string screen, AppTheme theme)
{
await Settle(window);
diff --git a/src/Titano.Core/Project/ProjectSettings.cs b/src/Titano.Core/Project/ProjectSettings.cs
index 42cb5690..9a52011a 100644
--- a/src/Titano.Core/Project/ProjectSettings.cs
+++ b/src/Titano.Core/Project/ProjectSettings.cs
@@ -158,6 +158,12 @@ public sealed record ExportSettings
/// Presets queued together by "Render another preset" / batch.
public IReadOnlyList Batch { get; init; } = [];
+
+ ///
+ /// 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).
+ ///
+ public bool SyncToServer { get; init; }
}
///
diff --git a/src/Titano.Data/Jobs/JobWire.cs b/src/Titano.Data/Jobs/JobWire.cs
new file mode 100644
index 00000000..40498295
--- /dev/null
+++ b/src/Titano.Data/Jobs/JobWire.cs
@@ -0,0 +1,75 @@
+using System.Text;
+using Titano.Core.Model;
+using Titano.Protocol;
+
+namespace Titano.Data.Jobs;
+
+///
+/// Wire names of job kinds, states and priorities in API v1: kebab-case (deep-analyse) and lower-case
+/// (running). The server writes them; clients read the server's jobs back with .
+///
+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);
+
+ /// A server job as the client's job model; null for a kind or state this build does not know.
+ 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(string? text, Func name, out T value) where T : struct, Enum
+ {
+ foreach (var candidate in Enum.GetValues())
+ {
+ if (string.Equals(name(candidate), text, StringComparison.OrdinalIgnoreCase))
+ {
+ value = candidate;
+ return true;
+ }
+ }
+ value = default;
+ return false;
+ }
+}
diff --git a/src/Titano.Data/Processing/ProcessingJobs.cs b/src/Titano.Data/Processing/ProcessingJobs.cs
index bc990d70..ab468707 100644
--- a/src/Titano.Data/Processing/ProcessingJobs.cs
+++ b/src/Titano.Data/Processing/ProcessingJobs.cs
@@ -107,7 +107,7 @@ public static class ProcessingJobs
/// The parameters of a render job and the export they select.
/// The job has no valid render parameters.
- 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));
diff --git a/src/Titano.Data/Processing/ProjectStore.cs b/src/Titano.Data/Processing/ProjectStore.cs
index 046d94f0..1479d459 100644
--- a/src/Titano.Data/Processing/ProjectStore.cs
+++ b/src/Titano.Data/Processing/ProjectStore.cs
@@ -48,14 +48,25 @@ 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 = edited.HeroFrame == current.HeroFrame ? (Guid?)null : await HeroFrameIdAsync(sequence.Id, 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;
}
}
}
+
+ /// The id of the frame at (frame indices are positions), or to clear the hero.
+ private async Task HeroFrameIdAsync(Guid sequenceId, int? index, CancellationToken cancellationToken)
+ {
+ if (index is not >= 0) return Guid.Empty;
+ var frames = await db.Frames.ListBySequenceAsync(sequenceId, index.Value - 1, 1, cancellationToken).ConfigureAwait(false);
+ return frames is [{ } frame] && frame.Index == index ? frame.Id : Guid.Empty;
+ }
}
diff --git a/src/Titano.Data/Repositories/SequenceRepository.cs b/src/Titano.Data/Repositories/SequenceRepository.cs
index 943d2e57..fec992f5 100644
--- a/src/Titano.Data/Repositories/SequenceRepository.cs
+++ b/src/Titano.Data/Repositories/SequenceRepository.cs
@@ -68,6 +68,12 @@ public sealed record SequenceEdit
public int? Rating { get; init; }
public string? Notes { get; init; }
public string? SettingsJson { get; init; }
+
+ ///
+ /// The frame the Library shows for the sequence (the project's hero frame); clears it, so
+ /// the first frame shows. A frame of another sequence is ignored.
+ ///
+ public Guid? HeroFrameId { get; init; }
}
public enum SequenceEditOutcome
@@ -227,12 +233,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("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,
};
diff --git a/src/Titano.Data/Sync/SyncService.cs b/src/Titano.Data/Sync/SyncService.cs
index a1a3232d..7d6609ff 100644
--- a/src/Titano.Data/Sync/SyncService.cs
+++ b/src/Titano.Data/Sync/SyncService.cs
@@ -270,6 +270,10 @@ public sealed class SyncService
/// A server sequence from the proxy cache, for the editor; null when its proxies were never fetched or were cleared.
public RemoteSequence? OpenRemote(string server, Guid remoteId) => Proxies.Load(server, remoteId);
+ /// The link of a local sequence to a sequence of ; null when the server does not have it.
+ public Task LinkOfAsync(string server, Guid localId, CancellationToken cancellationToken = default) =>
+ _links.FindByLocalAsync(server, localId, cancellationToken);
+
// ---------------- Engine ----------------
/// Server ids of the sequences an upload or download job is working on.
@@ -649,7 +653,24 @@ public sealed class SyncService
return path;
}
- internal static string SavedCopyName(DateTime localTime) => string.Create(CultureInfo.InvariantCulture, $"project.this-pc-{localTime:yyyyMMdd-HHmmss}.json");
+ internal static string SavedCopyName(DateTime localTime) =>
+ string.Create(CultureInfo.InvariantCulture, $"{SavedCopyPrefix}{localTime.ToString(SavedCopyTimeFormat, CultureInfo.InvariantCulture)}.json");
+
+ /// File name pattern of "Save both" copies in a sequence's .titano folder.
+ public const string SavedCopyPattern = SavedCopyPrefix + "*.json";
+
+ private const string SavedCopyPrefix = "project.this-pc-";
+ private const string SavedCopyTimeFormat = "yyyyMMdd-HHmmss";
+
+ /// When a "Save both" copy was kept (local time, from its name); null for a name of another shape.
+ 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)
{
diff --git a/src/Titano.Protocol/Client/TitanoClient.cs b/src/Titano.Protocol/Client/TitanoClient.cs
index 96fe88a8..dc793a08 100644
--- a/src/Titano.Protocol/Client/TitanoClient.cs
+++ b/src/Titano.Protocol/Client/TitanoClient.cs
@@ -99,6 +99,21 @@ public sealed class TitanoClient : IDisposable
public Task GetManifestAsync(Guid id, CancellationToken ct = default) =>
GetAsync($"api/v1/sequences/{id}/manifest", ProtocolJson.Default.SequenceManifest, ct);
+ /// The full deep-analysis report of a sequence (analysis.json); null when it was never deep-analysed.
+ public async Task 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> 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);
diff --git a/src/Titano.Protocol/Sequences.cs b/src/Titano.Protocol/Sequences.cs
index eaebcc0d..8ad09422 100644
--- a/src/Titano.Protocol/Sequences.cs
+++ b/src/Titano.Protocol/Sequences.cs
@@ -32,14 +32,18 @@ public sealed record Page(IReadOnlyList Items, string? NextCursor, long? T
/// POST /api/v1/sequences.
public sealed record CreateSequenceRequest(string? Title, string? CameraHint);
-/// PATCH /api/v1/sequences/{id}. enables conflict detection (409).
+///
+/// PATCH /api/v1/sequences/{id}. enables conflict detection (409).
+/// names the frame the sequence shows (one of its own; clears it).
+///
public sealed record UpdateSequenceRequest(
string? Title,
IReadOnlyList? Tags,
int? Rating,
string? Notes,
string? SettingsJson,
- int? ExpectedSettingsVersion);
+ int? ExpectedSettingsVersion,
+ Guid? HeroFrameId = null);
public sealed record FrameDto(
Guid Id,
diff --git a/src/Titano.Server/Api/ArchiveEndpoints.cs b/src/Titano.Server/Api/ArchiveEndpoints.cs
index daf097d1..3a42f89d 100644
--- a/src/Titano.Server/Api/ArchiveEndpoints.cs
+++ b/src/Titano.Server/Api/ArchiveEndpoints.cs
@@ -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;
diff --git a/src/Titano.Server/Api/Dto.cs b/src/Titano.Server/Api/Dto.cs
index 7d02ecd3..a80cf647 100644
--- a/src/Titano.Server/Api/Dto.cs
+++ b/src/Titano.Server/Api/Dto.cs
@@ -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
}
}
}
-
-/// Wire names of job kinds, states and priorities: kebab-case (deep-analyse) and lower-case (running).
-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(string? text, Func name, out T value) where T : struct, Enum
- {
- foreach (var candidate in Enum.GetValues())
- {
- if (string.Equals(name(candidate), text, StringComparison.OrdinalIgnoreCase))
- {
- value = candidate;
- return true;
- }
- }
- value = default;
- return false;
- }
-}
diff --git a/src/Titano.Server/Api/JobEndpoints.cs b/src/Titano.Server/Api/JobEndpoints.cs
index a86a08db..4ee09131 100644
--- a/src/Titano.Server/Api/JobEndpoints.cs
+++ b/src/Titano.Server/Api/JobEndpoints.cs
@@ -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;
diff --git a/src/Titano.Server/Api/SequenceEndpoints.cs b/src/Titano.Server/Api/SequenceEndpoints.cs
index af64e3cc..dd7f68d6 100644
--- a/src/Titano.Server/Api/SequenceEndpoints.cs
+++ b/src/Titano.Server/Api/SequenceEndpoints.cs
@@ -35,6 +35,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.
@@ -123,7 +124,15 @@ 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,
+ HeroFrameId = request.HeroFrameId,
+ };
var result = await db.Sequences.EditAsync(id, edit, expected, context.RequestAborted);
switch (result.Outcome)
{
@@ -212,6 +221,18 @@ public static class SequenceEndpoints
_ => ApiErrors.NotFound(context, "analysis"),
};
+ /// The full deep-analysis report (.titano/analysis.json) a client's editor shows for a server sequence.
+ private static async Task 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 StatsAsync(HttpContext context, Guid id, TitanoDatabase db)
{
if (await db.Sequences.GetAsync(id, context.RequestAborted) is not { } s) return ApiErrors.NotFound(context, "sequence");
diff --git a/tests/Titano.App.Tests/Editor/EditorFixture.cs b/tests/Titano.App.Tests/Editor/EditorFixture.cs
index 1e06fdd8..060b89c9 100644
--- a/tests/Titano.App.Tests/Editor/EditorFixture.cs
+++ b/tests/Titano.App.Tests/Editor/EditorFixture.cs
@@ -54,7 +54,7 @@ internal static class EditorFixture
};
var report = deep ? DeepAnalyzer.AnalyzeAsync(new Frames(sequence)).GetAwaiter().GetResult() : null;
return new SequenceContent(row, frames, project ?? new ProjectSettings(), LightAnalyzer.Analyze(frames), report, sequence.Options.Width,
- sequence.Options.Height, null, []);
+ sequence.Options.Height, null, [], []);
}
/// Synthetic frames as the deep analysis reads them.
@@ -83,6 +83,12 @@ internal sealed class FakeSequenceSource(SyntheticSequence sequence, SequenceCon
public List Submitted { get; } = [];
+ /// A server sequence: renders become one job per preset.
+ public bool IsRemote { get; init; }
+
+ /// Jobs returns.
+ public List Jobs { get; } = [];
+
public int Saves { get; private set; }
public int Decodes { get; private set; }
@@ -128,5 +134,12 @@ internal sealed class FakeSequenceSource(SyntheticSequence sequence, SequenceCon
return Task.FromResult(Guid.CreateVersion7());
}
+ public event Action? JobChanged;
+
+ public Task> ListJobsAsync(CancellationToken cancellationToken) => Task.FromResult>([.. Jobs]);
+
+ /// A job of the sequence changed (as the engine or the server reports it).
+ public void Report(Job job) => JobChanged?.Invoke(job);
+
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
diff --git a/tests/Titano.Data.Tests/Repositories/SequenceEditTests.cs b/tests/Titano.Data.Tests/Repositories/SequenceEditTests.cs
new file mode 100644
index 00000000..5ab34ca1
--- /dev/null
+++ b/tests/Titano.Data.Tests/Repositories/SequenceEditTests.cs
@@ -0,0 +1,108 @@
+using Titano.Core.Diagnostics.Synthetic;
+using Titano.Data.Archiving;
+using Titano.Data.Processing;
+using Titano.Data.Repositories;
+using Titano.Data.Tests.Infrastructure;
+using Titano.Data.Tests.Processing;
+using Titano.Testing;
+
+namespace Titano.Data.Tests.Repositories;
+
+/// Client edits of a sequence row () on both dialects: the hero frame the Library shows.
+public abstract class SequenceEditTests(TestContext context) : RepositoryTest(context)
+{
+ [Test]
+ public async Task TheHeroFrameIsSetKeptAndCleared()
+ {
+ var db = await OpenTitanoAsync();
+ var archive = TestData.Archive();
+ await db.Archives.UpsertAsync(archive, Ct);
+ var sequence = TestData.Sequence(archive.Id);
+ await db.Sequences.UpsertAsync(sequence, Ct);
+ var frames = Enumerable.Range(0, 5).Select(i => TestData.Frame(sequence.Id, i)).ToList();
+ await db.Frames.BulkInsertAsync(frames, Ct);
+
+ var set = await db.Sequences.EditAsync(sequence.Id, new SequenceEdit { SettingsJson = "{\"heroFrame\":3}", HeroFrameId = frames[3].Id }, null, Ct);
+ Assert.Equal(SequenceEditOutcome.Updated, set.Outcome);
+ Assert.Equal(frames[3].Id, set.Sequence!.HeroFrameId);
+ Assert.Equal(frames[3].Id, (await db.Sequences.GetAsync(sequence.Id, Ct))!.HeroFrameId);
+
+ var kept = await db.Sequences.EditAsync(sequence.Id, new SequenceEdit { Rating = 4 }, set.Sequence.SettingsVersion, Ct);
+ Assert.Equal(frames[3].Id, kept.Sequence!.HeroFrameId, "an edit without a hero leaves it alone");
+
+ var cleared = await db.Sequences.EditAsync(sequence.Id, new SequenceEdit { HeroFrameId = Guid.Empty }, null, Ct);
+ Assert.Null(cleared.Sequence!.HeroFrameId, "Guid.Empty goes back to the first frame");
+ }
+
+ [Test]
+ public async Task AFrameOfAnotherSequenceIsNotAHero()
+ {
+ var db = await OpenTitanoAsync();
+ var archive = TestData.Archive();
+ await db.Archives.UpsertAsync(archive, Ct);
+ var mine = TestData.Sequence(archive.Id, title: "Mine");
+ var other = TestData.Sequence(archive.Id, title: "Other");
+ await db.Sequences.UpsertAsync(mine, Ct);
+ await db.Sequences.UpsertAsync(other, Ct);
+ var own = TestData.Frame(mine.Id, 0);
+ var foreign = TestData.Frame(other.Id, 0);
+ await db.Frames.BulkInsertAsync([own, foreign], Ct);
+
+ await db.Sequences.EditAsync(mine.Id, new SequenceEdit { HeroFrameId = own.Id }, null, Ct);
+ var result = await db.Sequences.EditAsync(mine.Id, new SequenceEdit { HeroFrameId = foreign.Id }, null, Ct);
+ Assert.Equal(SequenceEditOutcome.Updated, result.Outcome);
+ Assert.Equal(own.Id, result.Sequence!.HeroFrameId);
+ }
+
+ [Test]
+ public async Task AConflictLeavesTheHeroAsItWas()
+ {
+ var db = await OpenTitanoAsync();
+ var archive = TestData.Archive();
+ await db.Archives.UpsertAsync(archive, Ct);
+ var sequence = TestData.Sequence(archive.Id);
+ await db.Sequences.UpsertAsync(sequence, Ct);
+ var frame = TestData.Frame(sequence.Id, 0);
+ await db.Frames.BulkInsertAsync([frame], Ct);
+
+ var result = await db.Sequences.EditAsync(sequence.Id, new SequenceEdit { HeroFrameId = frame.Id }, sequence.SettingsVersion + 7, Ct);
+ Assert.Equal(SequenceEditOutcome.Conflict, result.Outcome);
+ Assert.Null((await db.Sequences.GetAsync(sequence.Id, Ct))!.HeroFrameId);
+ }
+}
+
+public sealed class SqliteSequenceEditTests(TestContext context) : SequenceEditTests(context)
+{
+ protected override Backend Backend => Backend.SqliteMemory;
+}
+
+[RequiresEnvironment(PgTestServer.Variable)]
+public sealed class PostgresSequenceEditTests(TestContext context) : SequenceEditTests(context)
+{
+ protected override Backend Backend => Backend.Postgres;
+}
+
+/// Project writes of the engine (advice, sync) carry the project's hero frame to the index, so the Library shows it.
+public sealed class ProjectStoreHeroTests(TestContext context)
+{
+ [Test]
+ public async Task AdviceThatPicksAHeroReachesTheIndex()
+ {
+ await using var fixture = await ProcessingFixture.CreateAsync(context);
+ var sequence = await fixture.AddAsync(SyntheticSequence.Create(new SyntheticSequenceOptions { Width = 64, Height = 48, FrameCount = 6 }));
+ var frames = await fixture.Db.Frames.ListBySequenceAsync(sequence.Id, cancellationToken: fixture.Ct);
+ var store = new ProjectStore(fixture.Db, new SequenceWriter(new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) }));
+
+ Assert.True(await store.UpdateAsync(fixture.Archive.Paths, sequence, p => p with { HeroFrame = 4 }, fixture.Ct));
+ Assert.Equal(frames[4].Id, (await fixture.Db.Sequences.GetAsync(sequence.Id, fixture.Ct))!.HeroFrameId);
+
+ Assert.True(await store.UpdateAsync(fixture.Archive.Paths, sequence, p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.5 } }, fixture.Ct));
+ Assert.Equal(frames[4].Id, (await fixture.Db.Sequences.GetAsync(sequence.Id, fixture.Ct))!.HeroFrameId, "other changes keep the hero");
+
+ Assert.True(await store.UpdateAsync(fixture.Archive.Paths, sequence, p => p with { HeroFrame = null }, fixture.Ct));
+ Assert.Null((await fixture.Db.Sequences.GetAsync(sequence.Id, fixture.Ct))!.HeroFrameId);
+
+ Assert.True(await store.UpdateAsync(fixture.Archive.Paths, sequence, p => p with { HeroFrame = 99 }, fixture.Ct));
+ Assert.Null((await fixture.Db.Sequences.GetAsync(sequence.Id, fixture.Ct))!.HeroFrameId, "an index past the last frame shows the first");
+ }
+}