using System.ComponentModel; using System.Net; using System.Windows.Input; using System.Windows.Threading; using Titano.App.Editor; using Titano.App.Infrastructure; using Titano.App.Shell; using Titano.Core.Diagnostics; using Titano.Core.Export; using Titano.Core.Imaging.Decoders; using Titano.Core.Localization; using Titano.Core.Model; using Titano.Data.Jobs; using Titano.Data.Sync; using Titano.Protocol.Client; using Titano.Ui.Mvvm; namespace Titano.App.Sections; /// /// 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 server sequence whose proxies are /// missing or out of date fetches them first and opens once they are here. A failed open is reported and leaves the /// section usable; an edit that cannot be saved is never dropped without the user's confirmation. /// public sealed class SequenceViewModel : SectionViewModel { private readonly Dispatcher _dispatcher = Dispatcher.CurrentDispatcher; private EditorViewModel? _editor; private Guid? _openId; private bool _isLoading; private Task _switch = Task.CompletedTask; private ProxyFetch? _fetch; public SequenceViewModel(ShellViewModel shell) : base(SectionKey.Sequence, "Icon.Sequence") { Shell = shell; OpenLibraryCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Library)); shell.PropertyChanged += OnShellChanged; } public ShellViewModel Shell { get; } public ICommand OpenLibraryCommand { get; } /// The open sequence; null shows the empty state. public EditorViewModel? Editor { get => _editor; private set { if (!Set(ref _editor, value)) return; OnPropertyChanged(nameof(IsEmpty)); OnPropertyChanged(nameof(Title)); } } public bool IsLoading { get => _isLoading; private set => Set(ref _isLoading, value); } public bool IsEmpty => _editor is null && !_isLoading; /// The open sequence has an edit not stored yet (the save follows each change after a moment, and retries after a failure). public bool HasPendingSave => _editor?.Session.HasPendingSave == true; /// "Titano — Harbour sunset" while a sequence is open. public override string Title => _editor?.Title ?? Label; /// Opens (the editor of another sequence is saved and closed first). /// Opens it again even when it is the open one (its proxies were fetched again). public Task OpenAsync(Guid sequenceId, bool reload = false) { _switch = SwitchAsync(_switch, sequenceId, reload); return _switch; } /// /// Shows in the editor, as the Library does, and returns its editor once open; null /// when it did not open (the reason was reported, or the open sequence's unsaved edit was kept) or waits for its /// proxies. /// public async Task ShowAsync(Guid sequenceId) { Shell.OpenSequence(sequenceId); // Already chosen and shown but not open (an earlier open failed): opening it again is what is asked now. if (_openId != sequenceId && _switch.IsCompleted) _ = OpenAsync(sequenceId); await Settled(_switch); return _openId == sequenceId ? Editor : null; } /// /// Fetches the proxies of server sequence into this PC's cache (a download job, shown in /// the job bar and on the Jobs screen) and opens it in the editor once they are here, if it is still the sequence /// asked for. /// public async Task FetchProxiesAsync(Guid remoteId, string title) { var services = Shell.Services; var sync = services.Sync; if (sync.Server is not { } server || sync.Service is not { } service) throw new InvalidOperationException(Loc.L("Editor.Error.SignedOut")); if (services.Engine is not { } engine || services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine")); StopFetch(); var fetch = new ProxyFetch(remoteId, title, engine); fetch.Handler = job => _dispatcher.BeginInvoke(() => OnFetchChanged(fetch, job)); engine.JobChanged += fetch.Handler; _fetch = fetch; var job = await service.EnqueueDownloadAsync(engine, server, remoteId, title, SyncDownloadMode.Proxies, null); fetch.JobId = job.Id; Shell.Notify(Loc.L("Editor.Proxies.Fetching"), title, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs)); // A download that ended before its id was known here is handled now. if (await db.Jobs.GetAsync(job.Id) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } ended) OnFetchChanged(fetch, ended); } /// /// Stores the open sequence's last edit. When the save fails (archive offline, read-only, busy), asks whether to /// discard the edit (BRIEF §12.1: modals only for destructive confirmations). /// /// True when the editor may close: everything is stored or the user chose to discard. public async Task ConfirmCloseAsync() { if (Editor is not { } editor || await editor.Session.FlushAsync()) return true; return Shell.Services.Dialogs.Confirm(new ConfirmRequest { Heading = Loc.L("Editor.Unsaved.Title"), Message = Loc.L("Editor.Unsaved.Message", editor.Title, editor.Session.LastSaveError?.Message ?? string.Empty), SafeText = Loc.L("Editor.Unsaved.Keep"), SafeToolTip = Loc.L("Tooltips.Editor.Unsaved.Keep"), ActionText = Loc.L("Editor.Unsaved.Discard"), ActionToolTip = Loc.L("Tooltips.Editor.Unsaved.Discard"), IsDestructive = true, }); } /// Closes the open sequence (after , which stores its last edit). public async Task CloseAsync() { await Settled(_switch); if (Editor is not { } editor) return; Editor = null; _openId = null; await editor.DisposeAsync(); } public override void Dispose() { Shell.PropertyChanged -= OnShellChanged; StopFetch(); Editor?.Dispose(); base.Dispose(); } protected override void OnActivated() { if (Shell.CurrentSequenceId is { } id && id != _openId) _ = OpenAsync(id); } private void OnShellChanged(object? sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(ShellViewModel.CurrentSequenceId) && IsSelected) OnActivated(); } /// /// 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), or only shown when the /// account may not change it. Null when the proxies are not here yet: they are being fetched (). /// private async Task<(ISequenceSource Source, string Title)?> OpenSourceAsync(AppServices services, Guid sequenceId) { if (services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine")); var processing = services.Processing?.Options; var decoder = processing?.Archive.Decoder ?? DecoderFactory.CreateClient(null); if (await db.Sequences.GetAsync(sequenceId) is { } row) { var local = new LocalSequenceSource(db, sequenceId, decoder, services.Engine, processing?.Archive); local.HeroChanged += OnHeroChanged; return (local, row.DisplayTitle); } var sync = services.Sync; if (sync.Server is not { } server || sync.Service is not { } service || sync.ConnectEditor() is not { } api) throw new InvalidOperationException(Loc.L("Editor.Error.SignedOut")); // The proxy cache's index and files are read off the UI thread. if (await Task.Run(() => service.OpenRemote(server, sequenceId)) is { } remote) return (new RemoteSequenceSource(remote, api, decoder, readOnly: !sync.Policy.CanEdit), remote.Sequence.DisplayTitle); using (api) { string title; try { title = (await api.GetSequenceAsync(sequenceId, CancellationToken.None)).DisplayTitle; } catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound) { throw new InvalidOperationException(Loc.L("Editor.Error.Missing"), ex); } await FetchProxiesAsync(sequenceId, title); return null; } } /// The proxy download for an open waiting on it moved: opens the sequence once it is done, says why not when it failed. private void OnFetchChanged(ProxyFetch fetch, Job job) { if (!ReferenceEquals(fetch, _fetch) || job.Id != fetch.JobId || job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled)) return; StopFetch(); switch (job.State) { // Opened only when it is still the sequence asked for; otherwise the next visit opens it from the cache. case JobState.Done when Shell.CurrentSequenceId == fetch.RemoteId && IsSelected: _ = OpenAsync(fetch.RemoteId, reload: true); break; case JobState.Failed: Shell.Notify(Loc.L("Editor.Proxies.Failed"), job.Error ?? fetch.Title, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs), isError: true); break; } } private void StopFetch() { if (_fetch is not { } fetch) return; _fetch = null; if (fetch.Handler is { } handler) fetch.Engine.JobChanged -= handler; } /// 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) { try { await task; } catch (Exception ex) when (ex is not OutOfMemoryException) { Log.Debug("editor", $"An earlier open of the editor failed: {ex.Message}"); } } private async Task SwitchAsync(Task previous, Guid sequenceId, bool reload) { await Settled(previous); if (sequenceId == _openId && !reload) return; // The open sequence keeps its editor while its last edit is neither stored nor deliberately discarded. if (!await ConfirmCloseAsync()) return; var services = Shell.Services; IsLoading = true; OnPropertyChanged(nameof(IsEmpty)); try { if (Editor is { } old) { Editor = null; await old.DisposeAsync(); } _openId = sequenceId; if (await OpenSourceAsync(services, sequenceId) is not { } opened) { // The proxies are on their way; the sequence opens when they are here. _openId = null; return; } var (source, title) = opened; SequenceContent content; try { content = await source.LoadAsync(CancellationToken.None); } catch (ProxiesOutdatedException) { // The server's frames are no longer these proxies: fetch them again, then open. await source.DisposeAsync(); _openId = null; await FetchProxiesAsync(sequenceId, title); return; } catch { await source.DisposeAsync(); throw; } var processing = services.Processing?.Options; var encoders = processing?.Encoders ?? []; var session = new EditorSession(source, content, [.. encoders.SelectMany(e => e.Capabilities)]); var editor = new EditorViewModel(Shell, session, encoders, processing?.Host ?? EncoderHost.Client); Editor = editor; await editor.AttachJobsAsync(); } catch (Exception ex) when (ex is not OutOfMemoryException) { // Whatever failed (index, decoder set-up, advisor, the job list), the section stays usable: an editor that // opened stays open, otherwise the next Open tries again. if (Editor is null) _openId = null; Log.Warning("editor", $"Sequence {sequenceId} could not be opened", ex); Shell.ReportError(ex); } finally { IsLoading = false; OnPropertyChanged(nameof(IsEmpty)); } } /// A proxy download an open waits on, with its engine subscription. private sealed class ProxyFetch(Guid remoteId, string title, JobEngine engine) { public Guid RemoteId { get; } = remoteId; public string Title { get; } = title; public JobEngine Engine { get; } = engine; public Guid JobId { get; set; } public Action? Handler { get; set; } } }