A workspace project that holds its originals now renders locally (JobKind.WorkspaceRender), so the full-resolution render no longer waits on the home. This holds also when the home is a server. - The handler reads its inputs under the project's lease. It refuses proxies-only media, and it refuses frames without an original, saying how many lack one. It renders into exports/ with unique names and a resumable checkpoint. - Each output gets a ledger entry: SHA-256, the render id from RenderJobHandler.RenderId, and the version, recorded only when versions/ holds it and its hash verifies. - After rendering, the handler queues a WorkspaceSend follow-up for the outputs it recorded. A cancel leaves no partial file. - The editor routes Originals media to the local engine even for a server home, and lists those jobs beside the server's. It treats WorkspaceRender like Render for the toast and the reload, says "Sent home" when a send ends, and shows unsent ledger renders as "Not sent". - Version on render saves a changed project as a version noted "Render" before it renders, and sends it with Sync automatically. With the setting off, the render behaves as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1041 lines
50 KiB
C#
1041 lines
50 KiB
C#
using System.Windows.Input;
|
||
using Chronos.App.Archiving;
|
||
using Chronos.App.Editor;
|
||
using Chronos.App.Infrastructure;
|
||
using Chronos.Core.Diagnostics;
|
||
using Chronos.Core.Localization;
|
||
using Chronos.Core.Model;
|
||
using Chronos.Core.Project;
|
||
using Chronos.Data.Projects;
|
||
using Chronos.Data.Sync;
|
||
using Chronos.Data.Workspaces;
|
||
using Chronos.Protocol;
|
||
using Chronos.Ui.Controls;
|
||
using Chronos.Ui.Mvvm;
|
||
|
||
namespace Chronos.App.Workspace;
|
||
|
||
/// <summary>What the project menu asks of the window it lives in: its in-window dialogs, confirmations, toasts and the editor's open project.</summary>
|
||
public interface IWorkspaceUi
|
||
{
|
||
/// <summary>The dialog open now; null when none is.</summary>
|
||
ArchiveDialogViewModel? Dialog { get; }
|
||
|
||
/// <summary>Shows <paramref name="dialog"/> now, in place of an open one (the dialog the user acted in leads to it).</summary>
|
||
void ShowDialog(ArchiveDialogViewModel dialog);
|
||
|
||
/// <summary>
|
||
/// Shows <paramref name="dialog"/> now when no dialog is open, else once the open one closes: something found in the
|
||
/// background (a conflict an automatic sync met) never replaces what the user is doing.
|
||
/// </summary>
|
||
void ShowDialogWhenFree(ArchiveDialogViewModel dialog);
|
||
|
||
void CloseDialog(ArchiveDialogViewModel dialog);
|
||
|
||
/// <summary>True when the user chose the action (a destructive confirmation).</summary>
|
||
bool Confirm(ConfirmRequest request);
|
||
|
||
void Notify(string title, string? message = null, string? actionText = null, string? actionToolTip = null, Action? action = null, bool isError = false);
|
||
|
||
/// <summary>Opens project <paramref name="projectId"/> of <paramref name="sequenceId"/> in the editor (checked out and copied first when it is not here).</summary>
|
||
Task OpenProjectAsync(Guid sequenceId, Guid projectId);
|
||
|
||
/// <summary>Closes the open project (its last edit stored first); the picker shows. False when the user kept it open.</summary>
|
||
Task<bool> CloseProjectAsync();
|
||
|
||
/// <summary>The home's sequence changed (a version of Main sent: its settings and hero frame): what shows it reads it again.</summary>
|
||
Task SequenceChangedAsync(Guid sequenceId);
|
||
}
|
||
|
||
/// <summary>
|
||
/// The project menu of the editor's title (▾, owner review 2, R8) for a workspace project: where it stands (the chip, read
|
||
/// again a moment after each edit), Save version (Ctrl+S, an optional note; sent at once with Settings › Workspace › Sync
|
||
/// automatically), Sync, History (Compare, Restore as one undo step), Open project (another project of the sequence, at
|
||
/// the library or here), New project, Rename, Delete project (never Main) and Remove local copy, and the "Update media"
|
||
/// banner when the home's frames moved past the workspace's. Every operation first stores the editor's last edit; what a
|
||
/// pull, a restore or taking the library's values changed comes back into the editor (merged, or as an undo step). A
|
||
/// conflict is asked about only when the merge met settings both sides changed, and a choice settles only the conflict
|
||
/// shown; one an automatic sync met waits for the dialog open to close. A project whose home is a server (phase 5b) words
|
||
/// its texts for the server, follows what the server tells of it (<see cref="WorkspaceHost.HomeChanged"/>: the chip reads
|
||
/// Server newer, or that the server no longer has it, its copy kept here), and renders only what the server holds
|
||
/// (<see cref="ReadyToRenderAsync"/>). Call from the UI thread.
|
||
/// </summary>
|
||
public sealed class ProjectMenuViewModel : LocalizedViewModel
|
||
{
|
||
/// <summary>How long after the last edit the chip reads the working state again (a little after the editor's save).</summary>
|
||
public static readonly TimeSpan StateRefreshDelay = TimeSpan.FromMilliseconds(600);
|
||
|
||
/// <summary>How long after an analysis ended a change the home tells is taken as its Auto values reaching Main.</summary>
|
||
private static readonly TimeSpan AnalysisTake = TimeSpan.FromMinutes(2);
|
||
|
||
private readonly WorkspaceHost _host;
|
||
private readonly WorkspaceSequenceSource _source;
|
||
private readonly EditorSession _session;
|
||
private readonly IWorkspaceUi _ui;
|
||
private readonly AsyncRelayCommand _sync;
|
||
private readonly AsyncRelayCommand _updateMedia;
|
||
|
||
/// <summary>The thread the menu was made on (the UI's); null where there is none (tests run inline).</summary>
|
||
private readonly SynchronizationContext? _context = SynchronizationContext.Current;
|
||
private WorkspaceStatus? _status;
|
||
private bool _isSyncing;
|
||
private bool _homeFramesChanged;
|
||
private Guid _copyJob;
|
||
private bool _copyingOriginals;
|
||
private bool _changingMedia;
|
||
private bool _disposed;
|
||
|
||
/// <summary>Counts the editor's changes, so only the last one's state read applies.</summary>
|
||
private int _changes;
|
||
|
||
/// <summary>The conflict dialog asked in the background, until it is closed (one is asked at a time).</summary>
|
||
private ConflictDialogViewModel? _asking;
|
||
|
||
/// <summary>
|
||
/// When an analysis of the sequence ended while Sync automatically is on and the home had not told its new Main yet
|
||
/// (a server catches up a moment later): the change it tells next is taken.
|
||
/// </summary>
|
||
private DateTime? _analysisEnded;
|
||
|
||
public ProjectMenuViewModel(WorkspaceHost host, WorkspaceSequenceSource source, EditorSession session, IWorkspaceUi ui)
|
||
{
|
||
_host = host;
|
||
_source = source;
|
||
_session = session;
|
||
_ui = ui;
|
||
_sync = new AsyncRelayCommand(() => SyncAsync(), () => !_isSyncing);
|
||
_updateMedia = new AsyncRelayCommand(UpdateMediaAsync, () => _copyJob == Guid.Empty);
|
||
SaveVersionCommand = new RelayCommand(OpenSaveVersion, () => CanSaveVersion);
|
||
HistoryCommand = new AsyncRelayCommand(OpenHistoryAsync);
|
||
OpenProjectCommand = new AsyncRelayCommand(OpenOtherProjectAsync);
|
||
NewProjectCommand = new AsyncRelayCommand(OpenNewProjectAsync);
|
||
RenameCommand = new AsyncRelayCommand(OpenRenameAsync);
|
||
DeleteCommand = new AsyncRelayCommand(DeleteAsync, () => !IsMain);
|
||
RemoveCopyCommand = new AsyncRelayCommand(OpenRemoveCopyAsync);
|
||
CopyOriginalsCommand = new AsyncRelayCommand(CopyOriginalsAsync, () => !HoldsOriginals && !IsMediaBusy);
|
||
ProxiesOnlyCommand = new AsyncRelayCommand(ProxiesOnlyAsync, () => HoldsOriginals && !IsMediaBusy);
|
||
source.JobChanged += OnJobChanged;
|
||
session.ProjectChanged += OnProjectChanged;
|
||
host.HomeChanged += OnHomeChanged;
|
||
}
|
||
|
||
public Guid ProjectId => _source.ProjectId;
|
||
|
||
public Guid SequenceId => _session.Content.Sequence.Id;
|
||
|
||
public bool IsMain => _source.Workspace?.IsMain == true;
|
||
|
||
/// <summary>The project's home is a server (phase 5b): its texts name the server, its renders are of what the server holds.</summary>
|
||
public bool IsServerHome => _source.IsServerHome;
|
||
|
||
/// <summary>The project's name (Main in the UI language).</summary>
|
||
public string Name => _source.Workspace is { } workspace ? WorkspaceText.ProjectName(workspace.Name, workspace.IsMain) : string.Empty;
|
||
|
||
public WorkspaceStatus? Status => _status;
|
||
|
||
public bool IsSyncing => _isSyncing;
|
||
|
||
public string StateText => WorkspaceText.State(_status, _isSyncing, IsServerHome);
|
||
|
||
public StatusKind StateKind => WorkspaceText.Kind(_status, _isSyncing);
|
||
|
||
public string StateToolTip => WorkspaceText.StateToolTip(_status, _isSyncing, IsServerHome);
|
||
|
||
/// <summary>The ▾ button: its name, then where the project stands, then what the menu holds.</summary>
|
||
public string MenuToolTip => Loc.L("Tooltips.Editor.Project.Menu", Name, StateText);
|
||
|
||
/// <summary>The button's accessible name: the project and its state.</summary>
|
||
public string MenuName => string.Join(Loc.Separator, Name, StateText);
|
||
|
||
/// <summary>
|
||
/// The home's frames moved past those the workspace holds, or the library names photos otherwise since the copy (hashed,
|
||
/// converted) and the media could not learn it yet (the last read of the library says so; a later one that taught them
|
||
/// clears it): the banner offers Update media.
|
||
/// </summary>
|
||
public bool HasMediaUpdate => _homeFramesChanged || _status is { MediaOutdated: true };
|
||
|
||
/// <summary>A copy of the media runs (Update media): the banner says so.</summary>
|
||
public bool IsUpdatingMedia => _copyJob != Guid.Empty;
|
||
|
||
public string MediaUpdateText => IsUpdatingMedia ? Loc.L("Editor.Workspace.Updating") : WorkspaceText.ForHome("Editor.Workspace.MediaChanged", IsServerHome);
|
||
|
||
public string MediaChangedToolTip => WorkspaceText.ForHome("Tooltips.Editor.Workspace.MediaChanged", IsServerHome);
|
||
|
||
public string UpdateMediaToolTip => WorkspaceText.ForHome("Tooltips.Editor.Workspace.UpdateMedia", IsServerHome);
|
||
|
||
/// <summary>A version can be saved: the settings are this Chronos's, no conflict waits, the media are here and the library still has the project.</summary>
|
||
public bool CanSaveVersion => !_session.IsReadOnly && _status is not { Conflict: not null } and not { MediaRemoved: true } and not { State: WorkspaceState.Gone };
|
||
|
||
public string SaveVersionToolTip => _session.IsReadOnly ? Loc.L("Errors.Workspace.ReadOnly")
|
||
: _status?.State == WorkspaceState.Gone ? WorkspaceText.ForHome("Errors.Workspace.DeletedAtHome", IsServerHome)
|
||
: _status?.Conflict is not null ? Loc.L("Errors.Workspace.Conflict")
|
||
: Loc.L("Tooltips.Editor.Project.SaveVersion");
|
||
|
||
public string DeleteToolTip => IsMain ? Loc.L("Errors.Workspace.MainKept") : WorkspaceText.ForHome("Tooltips.Editor.Project.Delete", IsServerHome);
|
||
|
||
public string RenameToolTip => WorkspaceText.ForHome("Tooltips.Editor.Project.Rename", IsServerHome);
|
||
|
||
public string RemoveCopyToolTip => WorkspaceText.ForHome("Tooltips.Editor.Project.RemoveCopy", IsServerHome);
|
||
|
||
/// <summary>Save version… (Ctrl+S): the note dialog.</summary>
|
||
public ICommand SaveVersionCommand { get; }
|
||
|
||
public ICommand SyncCommand => _sync;
|
||
|
||
public ICommand HistoryCommand { get; }
|
||
|
||
/// <summary>Open project…: another project of the sequence, one of the library's (a Save both sibling, another PC's) or a new one.</summary>
|
||
public ICommand OpenProjectCommand { get; }
|
||
|
||
public ICommand NewProjectCommand { get; }
|
||
|
||
public ICommand RenameCommand { get; }
|
||
|
||
public ICommand DeleteCommand { get; }
|
||
|
||
public ICommand RemoveCopyCommand { get; }
|
||
|
||
public ICommand UpdateMediaCommand => _updateMedia;
|
||
|
||
/// <summary>The workspace holds the project's originals besides its proxies (phase 5c): renders run on this PC.</summary>
|
||
public bool HoldsOriginals => _source.Workspace?.Media.Kind == BundleMedia.Originals;
|
||
|
||
/// <summary>
|
||
/// The media cannot change now: changes not saved as a version, a sync or a copy of the media running (the jobs of the
|
||
/// sequence are asked when the command runs).
|
||
/// </summary>
|
||
public bool IsMediaBusy => _changingMedia || _isSyncing || _copyJob != Guid.Empty || _status is { Modified: true, ReadOnly: false };
|
||
|
||
/// <summary>Copy originals… (phase 5c): the project's originals into the workspace, to render on this PC.</summary>
|
||
public ICommand CopyOriginalsCommand { get; }
|
||
|
||
/// <summary>Proxies only… (phase 5c): the originals copied here deleted once the home is checked to hold each one.</summary>
|
||
public ICommand ProxiesOnlyCommand { get; }
|
||
|
||
public string CopyOriginalsToolTip => IsMediaBusy ? Loc.L("Tooltips.Editor.Project.MediaBusy")
|
||
: WorkspaceText.ForHome("Tooltips.Editor.Project.CopyOriginals", IsServerHome);
|
||
|
||
public string ProxiesOnlyToolTip => IsMediaBusy ? Loc.L("Tooltips.Editor.Project.MediaBusy")
|
||
: WorkspaceText.ForHome("Tooltips.Editor.Project.ProxiesOnly", IsServerHome);
|
||
|
||
/// <summary>Reads where the project stands (against its home) and whether the home's frames moved.</summary>
|
||
public async Task RefreshAsync()
|
||
{
|
||
try
|
||
{
|
||
var status = await _host.StatusAsync(ProjectId);
|
||
var moved = await _source.HomeFramesChangedAsync(CancellationToken.None);
|
||
if (_disposed) return;
|
||
_homeFramesChanged = moved;
|
||
Apply(status);
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Warning("workspace", $"The state of project {ProjectId} could not be read", ex);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// A job of the sequence ended: where the project stands is read again; after an analysis, which writes its Auto
|
||
/// values into the library's settings (Main's), the project takes them at once with Sync automatically.
|
||
/// </summary>
|
||
public async Task JobEndedAsync(Job job)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(job);
|
||
await RefreshAsync();
|
||
if (_disposed || !_host.Settings.WorkspaceAutoSync || job.Kind is not (JobKind.DeepAnalyse or JobKind.LightAnalyse)) return;
|
||
if (_status is { State: WorkspaceState.Behind }) await SyncAsync(quiet: true);
|
||
// A server writes the Auto values into Main a moment after its analysis ends: what it tells next is taken then.
|
||
else if (IsServerHome) _analysisEnded = DateTime.UtcNow;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Before a render (phase 5b): a project whose home is a server renders what the server holds, so changes not saved as a
|
||
/// version, or versions not sent, are first offered to be saved and sent (Sync); false when the user kept them here,
|
||
/// the server could not take them or no longer has the project, or a conflict waits. A project of this PC's archive,
|
||
/// or one rendered on this PC from its originals (phase 5c), renders as it is: true. With Settings › Workspace › Version
|
||
/// on render, a changed project is saved as a version first (<see cref="SaveForRenderAsync"/>).
|
||
/// </summary>
|
||
public async Task<bool> ReadyToRenderAsync()
|
||
{
|
||
if (_host.Settings.WorkspaceVersionOnRender && !await SaveForRenderAsync()) return false;
|
||
// Rendered on this PC from the originals the workspace holds (phase 5c): the project renders as it is.
|
||
if (!IsServerHome || _source.RendersLocally) return true;
|
||
await StoreEditAsync();
|
||
var status = await _host.StatusAsync(ProjectId);
|
||
if (_disposed) return false;
|
||
Apply(status);
|
||
if (status.State is WorkspaceState.Gone or WorkspaceState.Offline or WorkspaceState.Damaged or WorkspaceState.MediaRemoved)
|
||
{
|
||
_ui.Notify(Loc.L("Editor.Workspace.RenderHeld"), WorkspaceText.StateToolTip(status, server: true), isError: status.State != WorkspaceState.Offline);
|
||
return false;
|
||
}
|
||
if (status.Conflict is not null)
|
||
{
|
||
AskConflict(status.Conflict);
|
||
return false;
|
||
}
|
||
if (status.Ahead == 0 && !status.Modified && _source.InStepWithHome(_session.Project) is not null) return true;
|
||
if (!_ui.Confirm(new ConfirmRequest
|
||
{
|
||
Heading = Loc.L("Editor.Workspace.SendFirst.Title"),
|
||
Message = Loc.L("Editor.Workspace.SendFirst.Message", Name),
|
||
SafeText = Loc.L("Editor.Project.Keep"),
|
||
SafeToolTip = Loc.L("Tooltips.Editor.Workspace.SendFirst.Keep"),
|
||
ActionText = Loc.L("Editor.Workspace.SendFirst.Action"),
|
||
ActionToolTip = Loc.L("Tooltips.Editor.Workspace.SendFirst.Action"),
|
||
}))
|
||
return false;
|
||
try
|
||
{
|
||
await SaveAndSendAsync();
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Warning("workspace", $"Project {ProjectId} could not be sent before its render", ex);
|
||
_ui.Notify(Loc.L("Editor.Workspace.RenderHeld"), WorkspaceText.Failure(ex, server: true), isError: ex is not HomeUnavailableException);
|
||
return false;
|
||
}
|
||
return !_disposed && _source.InStepWithHome(_session.Project) is not null;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Settings › Workspace › Version on render (phase 5c): a project changed since its last version is saved as a version
|
||
/// noted "Render" before its render, and sent at once with Sync automatically when the home can be reached (out of reach,
|
||
/// it waits here). False when it could not be saved, or the sync met a conflict to settle first.
|
||
/// </summary>
|
||
private async Task<bool> SaveForRenderAsync()
|
||
{
|
||
await StoreEditAsync();
|
||
var status = await _host.StatusAsync(ProjectId);
|
||
if (_disposed) return false;
|
||
Apply(status);
|
||
if (!status.Modified || !CanSaveVersion) return true;
|
||
WorkspaceSaveResult result;
|
||
try
|
||
{
|
||
result = await _host.SaveVersionAsync(ProjectId, Loc.L("Editor.Workspace.RenderNote"));
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Warning("workspace", $"Project {ProjectId} could not be saved before its render", ex);
|
||
_ui.Notify(Loc.L("Editor.Workspace.RenderHeld"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
|
||
return false;
|
||
}
|
||
if (_disposed) return false;
|
||
Apply(result.Status);
|
||
if (result.Synced is { } taken) await TakeAsync(taken);
|
||
if (result.Version is { } version)
|
||
{
|
||
// The home numbers what it stores: the last one sent is this version.
|
||
var number = result.Synced is { Pushed.Count: > 0 } synced ? synced.Pushed[^1].Number : version.Number;
|
||
_ui.Notify(Loc.L("Editor.Workspace.SavedForRender", Formatting.Count(number)), Name);
|
||
}
|
||
if (result.SyncError is { } error)
|
||
_ui.Notify(Loc.L("Editor.Workspace.NotSent"), WorkspaceText.Failure(error, IsServerHome), isError: error is not HomeUnavailableException);
|
||
if (result.Status.Conflict is not { } conflict) return true;
|
||
AskConflict(conflict);
|
||
return false;
|
||
}
|
||
|
||
/// <summary>
|
||
/// Saves the working state as a version with <paramref name="note"/>, sent at once with Sync automatically; what the
|
||
/// sync took from the home comes into the editor, a conflict it met is asked about.
|
||
/// </summary>
|
||
/// <exception cref="WorkspaceException">Why no version could be saved (the edit could not be stored, a conflict, read-only).</exception>
|
||
public async Task SaveVersionAsync(string? note)
|
||
{
|
||
await StoreEditAsync();
|
||
var result = await _host.SaveVersionAsync(ProjectId, note);
|
||
if (_disposed) return;
|
||
Apply(result.Status);
|
||
if (result.Synced is { } taken) await TakeAsync(taken);
|
||
if (result.Version is null)
|
||
{
|
||
_ui.Notify(Loc.L("Editor.Workspace.NothingNew"), Name);
|
||
}
|
||
else if (result.Synced is { Pushed.Count: > 0 } synced)
|
||
{
|
||
// The home numbers what it stores: the last one sent is this version.
|
||
_ui.Notify(Loc.L("Editor.Workspace.SavedSent", Formatting.Count(synced.Pushed[^1].Number)), Name);
|
||
}
|
||
else
|
||
{
|
||
_ui.Notify(Loc.L("Editor.Workspace.Saved", Formatting.Count(result.Version.Number)), Name);
|
||
}
|
||
if (result.SyncError is { } error)
|
||
_ui.Notify(Loc.L("Editor.Workspace.NotSent"), WorkspaceText.Failure(error, IsServerHome), isError: error is not HomeUnavailableException);
|
||
// Deleted in the library: said once, and no conflict is asked (nothing can be merged with it); the version stays here.
|
||
if (result.Status.State == WorkspaceState.Gone) NotifyGone();
|
||
else if (result.Status.Conflict is { } conflict) AskConflict(conflict);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Sync: the home's new versions taken into the editor, the local ones sent; a conflict is asked about (once the open
|
||
/// dialog closes when <paramref name="quiet"/>: the sync ran in the background).
|
||
/// </summary>
|
||
public async Task SyncAsync(bool quiet = false)
|
||
{
|
||
if (_isSyncing) return;
|
||
SetSyncing(true);
|
||
try
|
||
{
|
||
await StoreEditAsync();
|
||
var result = await _host.SyncAsync(ProjectId);
|
||
if (_disposed) return;
|
||
Apply(result.Status);
|
||
await TakeAsync(result);
|
||
if (result.Status.State == WorkspaceState.Gone) NotifyGone();
|
||
else if (result.Status.Conflict is { } conflict) AskConflict(conflict, background: quiet);
|
||
else if (!quiet) _ui.Notify(Loc.L(result.Status.State == WorkspaceState.InSync ? "Editor.Workspace.InSync" : "Editor.Workspace.Synced"), Name);
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Warning("workspace", $"Project {ProjectId} could not be synced", ex);
|
||
_ui.Notify(ex is HomeUnavailableException ? WorkspaceText.ForHome("Editor.Workspace.Offline", IsServerHome) : Loc.L("Editor.Workspace.SyncFailed"),
|
||
WorkspaceText.Failure(ex, IsServerHome), isError: ex is not HomeUnavailableException);
|
||
await RefreshAsync();
|
||
}
|
||
finally
|
||
{
|
||
SetSyncing(false);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Settles the conflict <paramref name="shown"/> listed (else the one recorded) as chosen, then brings the settled
|
||
/// working state into the editor: the library's values taken as one undo step (the toast's Undo, Ctrl+Z), what Save
|
||
/// both made offered by its toast. When what differs changed since it was shown, nothing is settled and it is asked again.
|
||
/// A project deleted in the library meanwhile is said so once, nothing asked again: its work stays here (the copy Save
|
||
/// both made holding it too, offered by its toast).
|
||
/// </summary>
|
||
public async Task ResolveAsync(ConflictChoice choice, WorkspaceConflict? shown = null)
|
||
{
|
||
await StoreEditAsync();
|
||
var result = await _host.ResolveAsync(ProjectId, choice, shown: shown);
|
||
if (_disposed) return;
|
||
Apply(result.Status);
|
||
if (result.Status.State == WorkspaceState.Gone)
|
||
{
|
||
NotifyGone();
|
||
NotifySavedAs(result);
|
||
return;
|
||
}
|
||
if (result.Status.Conflict is { } again)
|
||
{
|
||
await TakeAsync(result);
|
||
AskConflict(again);
|
||
return;
|
||
}
|
||
if (result.Kept is { } kept)
|
||
{
|
||
if (await _session.TakeOverAsync(kept) is { } step)
|
||
_ui.Notify(WorkspaceText.ForHome("Editor.Workspace.TookLibrary", IsServerHome), Name, Loc.L("Editor.Workspace.Undo"),
|
||
WorkspaceText.ForHome("Tooltips.Editor.Workspace.UndoTake", IsServerHome), () => step.Undo());
|
||
if (result.Pushed.Count > 0 && IsMain) await _ui.SequenceChangedAsync(SequenceId);
|
||
}
|
||
else
|
||
{
|
||
await TakeAsync(result, force: true);
|
||
}
|
||
NotifySavedAs(result);
|
||
}
|
||
|
||
/// <summary>The project Save both made, offered by its toast.</summary>
|
||
private void NotifySavedAs(WorkspaceSyncResult result)
|
||
{
|
||
if (result.SavedAs is not { } copy) return;
|
||
var sequenceId = SequenceId;
|
||
_ui.Notify(Loc.L("Editor.Workspace.SavedAs", copy.Name), Name, Loc.L("Editor.Workspace.OpenCopy"), Loc.L("Tooltips.Editor.Workspace.OpenCopy", copy.Name),
|
||
() => _ = _ui.OpenProjectAsync(sequenceId, copy.Id));
|
||
}
|
||
|
||
/// <summary>The home no longer has the project: nothing more is sent, its work stays here (Remove local copy keeps it aside).</summary>
|
||
private void NotifyGone() =>
|
||
_ui.Notify(WorkspaceText.ForHome("Editor.Workspace.State.Gone", IsServerHome), WorkspaceText.ForHome("Errors.Workspace.DeletedAtHome", IsServerHome));
|
||
|
||
/// <summary>
|
||
/// Restores <paramref name="version"/> as the project, as one undo step (uncommitted changes are saved as a version
|
||
/// first, so nothing is lost); the toast's Undo takes it back while it is the last change.
|
||
/// </summary>
|
||
public async Task RestoreAsync(ProjectVersion version)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(version);
|
||
await StoreEditAsync();
|
||
var restored = await _host.RestoreAsync(ProjectId, version.Id);
|
||
if (_disposed) return;
|
||
var before = _session.Project;
|
||
if (_session.Edit(_ => restored))
|
||
{
|
||
_session.EndEditRun();
|
||
var undo = new ProjectRestore(_session, before, _session.Project);
|
||
_ui.Notify(Loc.L("Editor.Workspace.Restored", Formatting.Count(version.Number)), Name, Loc.L("Editor.Workspace.Undo"), Loc.L("Tooltips.Editor.Workspace.Undo"),
|
||
() => undo.Undo());
|
||
}
|
||
else
|
||
{
|
||
_ui.Notify(Loc.L("Editor.Copy.Same"), Name);
|
||
}
|
||
await RefreshAsync();
|
||
}
|
||
|
||
/// <summary>
|
||
/// The settings that differ between the project now and <paramref name="version"/>, the version placed on the media's
|
||
/// frames first: exclusions, the hero and keyframes compare as the settings they are (a photo the media lack stays
|
||
/// parked, and reads as such).
|
||
/// </summary>
|
||
public IReadOnlyList<string> Compare(ProjectVersion version, int max = 12)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(version);
|
||
var photos = _source.Photos;
|
||
if (_session.Project.IsNewerFormat || ProjectContent.FormatOf(version.SettingsJson) > ProjectSettings.CurrentVersion)
|
||
return WorkspaceText.CompareLines(SyncRules.Differences(ProjectContent.ToPortable(_session.Project, photos), version.SettingsJson, 64), max);
|
||
var then = ProjectSettings.FromJson(ProjectContent.Place(ProjectContent.Rebind(version.SettingsJson, photos), photos), allowNewer: true);
|
||
return WorkspaceText.CompareLines(SyncRules.Differences(_session.Project.ToJson(), then.ToJson(), 64), max);
|
||
}
|
||
|
||
public override void Dispose()
|
||
{
|
||
_disposed = true;
|
||
_source.JobChanged -= OnJobChanged;
|
||
_session.ProjectChanged -= OnProjectChanged;
|
||
_host.HomeChanged -= OnHomeChanged;
|
||
// A conflict still waiting to be asked belongs to this editor: it is not asked once the editor closed (Sync asks it next time).
|
||
if (_asking is { } waiting && !ReferenceEquals(waiting, _ui.Dialog)) waiting.Dispose();
|
||
base.Dispose();
|
||
}
|
||
|
||
protected override void OnLanguageChanged()
|
||
{
|
||
base.OnLanguageChanged();
|
||
RaiseState();
|
||
}
|
||
|
||
private void OpenSaveVersion()
|
||
{
|
||
if (!CanSaveVersion) return;
|
||
_ui.ShowDialog(new SaveVersionDialogViewModel(Name, SaveVersionAsync, _ui.CloseDialog, IsServerHome));
|
||
}
|
||
|
||
private async Task OpenHistoryAsync()
|
||
{
|
||
var dialog = new HistoryDialogViewModel(Name, v => Task.FromResult(Compare(v)), RestoreAsync, _ui.CloseDialog, IsServerHome);
|
||
_ui.ShowDialog(dialog);
|
||
try
|
||
{
|
||
await StoreEditAsync();
|
||
var history = await _host.HistoryAsync(ProjectId, Math.Max(50, _host.Settings.WorkspaceKeptVersions));
|
||
dialog.Show(history, ProjectContent.Hash(ProjectContent.ToPortable(_session.Project, _source.Photos)));
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Warning("workspace", $"The history of project {ProjectId} could not be read", ex);
|
||
dialog.ShowFailure(ex);
|
||
}
|
||
}
|
||
|
||
/// <summary>The project's home (this PC's archive, or a server).</summary>
|
||
private BundleHome Home => _source.Workspace?.Home ?? WorkspaceHost.ArchiveHome(SequenceId);
|
||
|
||
/// <summary>
|
||
/// Open project…: "Open in workspace" over the home's projects of the sequence but the open one (a Save both
|
||
/// sibling, another PC's), or a new one; the choice opens in place of this one (checked out and copied when it is not
|
||
/// here yet).
|
||
/// </summary>
|
||
private async Task OpenOtherProjectAsync()
|
||
{
|
||
try
|
||
{
|
||
await StoreEditAsync();
|
||
var home = Home;
|
||
var projects = (await _host.HomeProjectsAsync(home)).Where(p => p.Id != ProjectId).ToList();
|
||
var dialog = new OpenInWorkspaceDialogViewModel(_session.Content.Sequence.DisplayTitle, projects, _ui.CloseDialog,
|
||
[.. projects.Select(p => p.Name).Append(_source.Workspace?.Name ?? string.Empty)], server: IsServerHome);
|
||
_ui.ShowDialog(dialog);
|
||
if (await dialog.Choice is not { } choice || _disposed) return;
|
||
var id = choice.ProjectId ?? (await _host.CreateProjectAsync(home, choice.NewName!, _status?.Base?.VersionId)).Id;
|
||
await _ui.OpenProjectAsync(SequenceId, id);
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Warning("workspace", $"Another project of sequence {SequenceId} could not be opened", ex);
|
||
_ui.Notify(Loc.L("Editor.Workspace.OpenFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
|
||
}
|
||
}
|
||
|
||
private async Task OpenNewProjectAsync()
|
||
{
|
||
var names = await OtherNamesAsync(null);
|
||
var home = Home;
|
||
_ui.ShowDialog(new ProjectNameDialogViewModel(false, string.Empty, names, async name =>
|
||
{
|
||
await StoreEditAsync();
|
||
// From the open project's last version at the home, so the new one starts where this one is there.
|
||
var created = await _host.CreateProjectAsync(home, name, _status?.Base?.VersionId);
|
||
_ui.Notify(Loc.L("Editor.Workspace.Created", created.Name), _session.Content.Sequence.DisplayTitle);
|
||
_ = _ui.OpenProjectAsync(SequenceId, created.Id);
|
||
}, _ui.CloseDialog, IsServerHome));
|
||
}
|
||
|
||
private async Task OpenRenameAsync()
|
||
{
|
||
var names = await OtherNamesAsync(ProjectId);
|
||
_ui.ShowDialog(new ProjectNameDialogViewModel(true, _source.Workspace?.Name ?? string.Empty, names, async name =>
|
||
{
|
||
await _host.RenameAsync(ProjectId, name);
|
||
await _session.ReloadAsync();
|
||
_ui.Notify(Loc.L("Editor.Workspace.Renamed"), name);
|
||
RaiseState();
|
||
}, _ui.CloseDialog, IsServerHome));
|
||
}
|
||
|
||
private async Task DeleteAsync()
|
||
{
|
||
if (IsMain) return;
|
||
var name = Name;
|
||
if (!_ui.Confirm(new ConfirmRequest
|
||
{
|
||
Heading = Loc.L("Editor.Project.DeleteTitle", name),
|
||
Message = WorkspaceText.ForHome("Editor.Project.DeleteMessage", IsServerHome),
|
||
SafeText = Loc.L("Editor.Project.Keep"),
|
||
SafeToolTip = Loc.L("Tooltips.Editor.Project.Keep"),
|
||
ActionText = Loc.L("Editor.Project.DeleteAction"),
|
||
ActionToolTip = WorkspaceText.ForHome("Tooltips.Editor.Project.DeleteAction", IsServerHome),
|
||
IsDestructive = true,
|
||
}))
|
||
return;
|
||
try
|
||
{
|
||
// Everything sent first, while the project is still open: a delete that cannot happen leaves it as it was.
|
||
await SaveAndSendAsync();
|
||
var (sequenceId, projectId) = (SequenceId, ProjectId);
|
||
if (!await _ui.CloseProjectAsync()) return;
|
||
// The library's delete stands even when the local copy could not go with it: it is said, and Remove local copy takes it later.
|
||
if (await _host.DeleteProjectAsync(projectId)) _ui.Notify(Loc.L("Editor.Workspace.Deleted", name));
|
||
else _ui.Notify(Loc.L("Editor.Workspace.Deleted", name), Loc.L("Errors.Workspace.CopyKept"), isError: true);
|
||
await _ui.SequenceChangedAsync(sequenceId);
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Warning("workspace", $"Project {ProjectId} was not deleted", ex);
|
||
_ui.Notify(Loc.L("Editor.Workspace.DeleteFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
|
||
}
|
||
}
|
||
|
||
private async Task OpenRemoveCopyAsync()
|
||
{
|
||
try
|
||
{
|
||
await StoreEditAsync();
|
||
var plan = await _host.PlanRemovalAsync(ProjectId);
|
||
var (projectId, name) = (ProjectId, Name);
|
||
_ui.ShowDialog(new RemoveCopyDialogViewModel(plan, discard => RemoveAsync(projectId, discard), async () =>
|
||
{
|
||
await SaveAndSendAsync();
|
||
await RemoveAsync(projectId, discard: false);
|
||
}, () => RemoveCopyDialogViewModel.ConfirmDiscard(_ui, name), _ui.CloseDialog, IsServerHome));
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Warning("workspace", $"The removal of project {ProjectId} could not be planned", ex);
|
||
_ui.Notify(Loc.L("Editor.Workspace.RemoveFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// The working state saved as a version and everything sent, for Send first and Delete project. A conflict the sync
|
||
/// meets is asked about at once (in place of the dialog that asked for it), never left behind a reason to discard.
|
||
/// </summary>
|
||
/// <exception cref="WorkspaceException">Something could not be sent: a conflict to settle first, or the work not in the library yet.</exception>
|
||
private async Task SaveAndSendAsync()
|
||
{
|
||
await StoreEditAsync();
|
||
if (CanSaveVersion) await _host.CommitAsync(ProjectId);
|
||
var result = await _host.SyncAsync(ProjectId);
|
||
Apply(result.Status);
|
||
await TakeAsync(result);
|
||
// Nothing can be sent to a project the home no longer has: only Discard takes the copy, its work kept aside.
|
||
if (result.Status.State == WorkspaceState.Gone) throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.DeletedAtHome", IsServerHome));
|
||
if (result.Status.Conflict is { } conflict)
|
||
{
|
||
AskConflict(conflict);
|
||
throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
|
||
}
|
||
if (result.Status is { Ahead: > 0 } or { Modified: true, ReadOnly: false })
|
||
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Unsent", IsServerHome));
|
||
}
|
||
|
||
private async Task RemoveAsync(Guid projectId, bool discard)
|
||
{
|
||
// Checked before the editor closes, so a copy that cannot go leaves it open.
|
||
if (!discard)
|
||
{
|
||
var status = await _host.StatusAsync(projectId, askHome: false);
|
||
if (status is { Ahead: > 0 } or { Conflict: not null } or { Modified: true, ReadOnly: false })
|
||
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Unsent", IsServerHome));
|
||
}
|
||
var name = Name;
|
||
if (!await _ui.CloseProjectAsync()) return;
|
||
await _host.RemoveLocalCopyAsync(projectId, discard);
|
||
_ui.Notify(Loc.L("Editor.Workspace.Removed"), name);
|
||
}
|
||
|
||
private async Task<IReadOnlyList<string>> OtherNamesAsync(Guid? except)
|
||
{
|
||
try
|
||
{
|
||
return [.. (await _host.HomeProjectsAsync(Home)).Where(p => p.Id != except).Select(p => p.Name)];
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
// The home checks the name again when the project is made.
|
||
Log.Info("workspace", $"The projects of sequence {SequenceId} could not be listed: {ex.Message}");
|
||
return [];
|
||
}
|
||
}
|
||
|
||
private async Task UpdateMediaAsync()
|
||
{
|
||
try
|
||
{
|
||
await StoreEditAsync();
|
||
var job = await _host.QueueCopyAsync(ProjectId);
|
||
_copyJob = job.Id;
|
||
RaiseState();
|
||
_ui.Notify(Loc.L("Editor.Workspace.Copying"), _session.Content.Sequence.DisplayTitle);
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Warning("workspace", $"The media of project {ProjectId} could not be copied again", ex);
|
||
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Copy originals…: refused while the media cannot change (<see cref="IsMediaBusy"/>, or a job of the sequence waits or
|
||
/// runs); otherwise the copy is queued, the banner says it runs, and the editor reads the media again once it is done.
|
||
/// </summary>
|
||
private async Task CopyOriginalsAsync()
|
||
{
|
||
try
|
||
{
|
||
await StoreEditAsync();
|
||
if (await MediaRefusalAsync() is { } refusal)
|
||
{
|
||
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), refusal, isError: true);
|
||
return;
|
||
}
|
||
var job = await _host.QueueOriginalsCopyAsync(ProjectId);
|
||
_copyJob = job.Id;
|
||
_copyingOriginals = true;
|
||
RaiseState();
|
||
_ui.Notify(Loc.L("Editor.Workspace.CopyingOriginals"), _session.Content.Sequence.DisplayTitle, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"));
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Warning("workspace", $"The originals of project {ProjectId} could not be queued for copy", ex);
|
||
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Proxies only…: the plan (each original hashed and weighed against the home, read now), confirmed by the user, then
|
||
/// applied; the home out of reach, or anything changed since the plan, removes nothing.
|
||
/// </summary>
|
||
private async Task ProxiesOnlyAsync()
|
||
{
|
||
try
|
||
{
|
||
await StoreEditAsync();
|
||
if (await MediaRefusalAsync() is { } refusal)
|
||
{
|
||
_ui.Notify(Loc.L("Editor.Workspace.OriginalsNotRemoved"), refusal, isError: true);
|
||
return;
|
||
}
|
||
SetChangingMedia(true);
|
||
var plan = await _host.PlanProxiesOnlyAsync(ProjectId);
|
||
if (_disposed) return;
|
||
var detail = new List<string>
|
||
{
|
||
Loc.L("Editor.ProxiesOnly.Originals", Formatting.Count(plan.Originals)),
|
||
Loc.L("Editor.ProxiesOnly.Size", Formatting.Bytes(plan.Bytes)),
|
||
};
|
||
if (plan.ToTrash > 0) detail.Add(Loc.L("Editor.ProxiesOnly.ToTrash", Formatting.Count(plan.ToTrash)));
|
||
if (!_ui.Confirm(new ConfirmRequest
|
||
{
|
||
Heading = Loc.L("Editor.ProxiesOnly.Title", Name),
|
||
Message = WorkspaceText.ForHome("Editor.ProxiesOnly.Message", IsServerHome),
|
||
Detail = string.Join(Environment.NewLine, detail),
|
||
IsDetailMonospaced = false,
|
||
DetailToolTip = plan.ToTrash > 0 ? WorkspaceText.ForHome("Tooltips.Editor.ProxiesOnly.ToTrash", IsServerHome) : null,
|
||
SafeText = Loc.L("Editor.Project.Keep"),
|
||
SafeToolTip = Loc.L("Tooltips.Editor.ProxiesOnly.Keep"),
|
||
ActionText = Loc.L("Editor.ProxiesOnly.Action"),
|
||
ActionToolTip = Loc.L("Tooltips.Editor.ProxiesOnly.Action"),
|
||
IsDestructive = true,
|
||
}))
|
||
return;
|
||
var trashed = await _host.ProxiesOnlyAsync(ProjectId, plan);
|
||
if (_disposed) return;
|
||
await _session.ReloadAsync();
|
||
_ui.Notify(Loc.L("Editor.Workspace.OriginalsRemoved"),
|
||
trashed > 0 ? Loc.L("Editor.ProxiesOnly.ToTrash", Formatting.Count(trashed)) : _session.Content.Sequence.DisplayTitle);
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Warning("workspace", $"The originals of project {ProjectId} were not removed", ex);
|
||
_ui.Notify(Loc.L("Editor.Workspace.OriginalsNotRemoved"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
|
||
}
|
||
finally
|
||
{
|
||
SetChangingMedia(false);
|
||
await RefreshAsync();
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// Why the media cannot change now (<c>Errors.Workspace.MediaBusy</c>): changes not saved as a version, a copy or sync
|
||
/// running, or an analysis, render or workspace job of the sequence waiting or running; null when they can.
|
||
/// </summary>
|
||
private async Task<string?> MediaRefusalAsync()
|
||
{
|
||
var local = await _host.StatusAsync(ProjectId, askHome: false);
|
||
if (_disposed) return null;
|
||
Apply(WithLocal(_status, local));
|
||
if (IsMediaBusy) return Loc.L("Errors.Workspace.MediaBusy");
|
||
var jobs = await _source.ListJobsAsync(CancellationToken.None);
|
||
var sequenceId = SequenceId;
|
||
return jobs.Any(j => j.State is JobState.Queued or JobState.Running or JobState.Paused && j.TargetIds.Contains(sequenceId)
|
||
&& j.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render or JobKind.WorkspaceCopy or JobKind.WorkspaceRender
|
||
or JobKind.WorkspaceSend)
|
||
? Loc.L("Errors.Workspace.MediaBusy")
|
||
: null;
|
||
}
|
||
|
||
/// <summary>The copy of the originals ended: said, with the frames that have none (they stay proxies, and a local render waits for them).</summary>
|
||
private void NotifyOriginalsCopied()
|
||
{
|
||
int missing;
|
||
try
|
||
{
|
||
missing = _source.Project.ReadMedia()?.Frames.Count(f => f.Original is null) ?? 0;
|
||
}
|
||
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or UnauthorizedAccessException)
|
||
{
|
||
Log.Warning("workspace", $"The media of project {ProjectId} could not be read after the copy of its originals", ex);
|
||
missing = 0;
|
||
}
|
||
if (missing == 0) _ui.Notify(Loc.L("Editor.Workspace.OriginalsCopied"), _session.Content.Sequence.DisplayTitle);
|
||
else _ui.Notify(Loc.L("Editor.Workspace.OriginalsCopied"), Loc.L("Editor.Workspace.OriginalsMissing", Formatting.Count(missing)));
|
||
}
|
||
|
||
private void SetChangingMedia(bool changing)
|
||
{
|
||
_changingMedia = changing;
|
||
RaiseState();
|
||
}
|
||
|
||
/// <summary>The editor's last edit stored in the working state before an operation reads it.</summary>
|
||
/// <exception cref="WorkspaceException">It could not be stored (it is retried in the background; nothing was lost).</exception>
|
||
private async Task StoreEditAsync()
|
||
{
|
||
if (await _session.FlushAsync()) return;
|
||
throw new WorkspaceException(Loc.L("Errors.Workspace.EditNotStored"), _session.LastSaveError);
|
||
}
|
||
|
||
/// <summary>What a sync, resolve or restore took from the home comes into the editor, merged with what was edited meanwhile.</summary>
|
||
private async Task TakeAsync(WorkspaceSyncResult result, bool force = false)
|
||
{
|
||
if (force || result.Pulled.Count > 0) await _session.ReloadAsync();
|
||
if (result.Pushed.Count > 0 && IsMain) await _ui.SequenceChangedAsync(SequenceId);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Asks how to settle <paramref name="conflict"/>, the choice applying to it as listed. One a sync met in the
|
||
/// <paramref name="background"/> (after an analysis) waits for the open dialog to close, and is asked once: the chip
|
||
/// says Conflict meanwhile, and Sync asks again.
|
||
/// </summary>
|
||
private void AskConflict(WorkspaceConflict conflict, bool background = false)
|
||
{
|
||
if (background && _asking is { IsClosed: false }) return;
|
||
var lines = WorkspaceText.ConflictLines(conflict.Differences, 10, IsServerHome);
|
||
var dialog = new ConflictDialogViewModel(Name, WorkspaceHost.SiblingName(_source.Workspace?.Name ?? Name), lines, choice => ResolveAsync(choice, conflict),
|
||
_ui.CloseDialog, conflict.NewerFormat, IsServerHome);
|
||
if (!background)
|
||
{
|
||
// Asked now: one still waiting from the background (or showing, which this one replaces) would only repeat an older list.
|
||
_asking?.Dispose();
|
||
_asking = null;
|
||
_ui.ShowDialog(dialog);
|
||
return;
|
||
}
|
||
_asking = dialog;
|
||
_ui.ShowDialogWhenFree(dialog);
|
||
}
|
||
|
||
/// <summary>The editor's project changed (an edit, undo, a merge; the UI thread): the chip reads the working state again a moment later.</summary>
|
||
private void OnProjectChanged()
|
||
{
|
||
if (_disposed) return;
|
||
_ = RefreshLocalAsync(++_changes);
|
||
}
|
||
|
||
/// <summary>
|
||
/// After the last change's save: where the working state stands now (changed, saved as versions), the library's facts
|
||
/// (newer, out of reach) kept from the last time it was asked; no read of the home on every edit.
|
||
/// </summary>
|
||
private async Task RefreshLocalAsync(int change)
|
||
{
|
||
try
|
||
{
|
||
// The save follows the change after a moment (and is retried after a failure): read once it is stored.
|
||
for (var wait = 0; wait == 0 || (_session.HasPendingSave && wait < 10); wait++)
|
||
{
|
||
await Task.Delay(StateRefreshDelay);
|
||
if (_disposed || change != _changes) return;
|
||
}
|
||
if (_isSyncing || _session.HasPendingSave) return;
|
||
var local = await _host.StatusAsync(ProjectId, askHome: false);
|
||
if (_disposed || change != _changes || _isSyncing) return;
|
||
Apply(WithLocal(_status, local));
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Debug("workspace", $"The state of project {ProjectId} could not be read after an edit: {ex.Message}");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// The state read without the home (<paramref name="local"/>) with what the last read of the home said (how far the
|
||
/// library is ahead, whether it could be reached, whether it still has the project), in the order the sync ranks them.
|
||
/// </summary>
|
||
internal static WorkspaceStatus WithLocal(WorkspaceStatus? last, WorkspaceStatus local)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(local);
|
||
if (last is null) return local;
|
||
var gone = last.State == WorkspaceState.Gone;
|
||
// A base that moved since (a sync) leaves how far the library is ahead unknown until it is asked again.
|
||
var behind = last.Base?.VersionId == local.Base?.VersionId ? last.Behind : 0;
|
||
// A project the library no longer has holds no conflict to answer (the one recorded stays for the record).
|
||
var status = local with
|
||
{
|
||
Behind = behind,
|
||
Offline = last.Offline,
|
||
HomeHead = last.HomeHead,
|
||
MediaOutdated = last.MediaOutdated,
|
||
Conflict = gone ? null : local.Conflict,
|
||
};
|
||
var state = gone ? WorkspaceState.Gone
|
||
: status.MediaRemoved ? WorkspaceState.MediaRemoved
|
||
: status.Damaged > 0 ? WorkspaceState.Damaged
|
||
: status.Conflict is not null ? WorkspaceState.Conflict
|
||
: status.Offline ? WorkspaceState.Offline
|
||
: status.Behind > 0 ? WorkspaceState.Behind
|
||
: status.Ahead > 0 ? WorkspaceState.Ahead
|
||
: status.Modified ? WorkspaceState.Modified
|
||
: WorkspaceState.InSync;
|
||
return status with { State = state };
|
||
}
|
||
|
||
/// <summary>A job of the engine changed (any thread): the end of the copy Update media queued is handled on the menu's thread.</summary>
|
||
private void OnJobChanged(Job job)
|
||
{
|
||
if (job.Id != _copyJob || job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled)) return;
|
||
if (_context is { } context) context.Post(_ => _ = CopyEndedAsync(job), null);
|
||
else _ = CopyEndedAsync(job);
|
||
}
|
||
|
||
/// <summary>
|
||
/// The home told that this project changed there, or that changes may have been missed (any thread; phase 5b): where it
|
||
/// stands is read again on the menu's thread, so the chip says Server newer, or that the server no longer has it.
|
||
/// </summary>
|
||
private void OnHomeChanged(WorkspaceHomeChange change)
|
||
{
|
||
if (_disposed || (change.ProjectId is { } id ? id != ProjectId : !IsServerHome || !string.Equals(change.Server, Home.Server, StringComparison.OrdinalIgnoreCase)))
|
||
return;
|
||
if (_context is { } context) context.Post(_ => _ = HomeChangedAsync(change), null);
|
||
else _ = HomeChangedAsync(change);
|
||
}
|
||
|
||
private async Task HomeChangedAsync(WorkspaceHomeChange change)
|
||
{
|
||
if (_disposed || _isSyncing) return;
|
||
await RefreshAsync();
|
||
// An analysis's Auto values reached Main at the server: with Sync automatically they are taken, as after an analysis here.
|
||
if (_disposed || _analysisEnded is not { } ended || change.Change != ProjectChanges.Pushed) return;
|
||
if (DateTime.UtcNow - ended > AnalysisTake)
|
||
{
|
||
_analysisEnded = null;
|
||
return;
|
||
}
|
||
if (_status is not { State: WorkspaceState.Behind } || !_host.Settings.WorkspaceAutoSync) return;
|
||
_analysisEnded = null;
|
||
await SyncAsync(quiet: true);
|
||
}
|
||
|
||
/// <summary>The copy of Update media ended: the editor reads the new frames (its positions follow them), or the toast says why not.</summary>
|
||
private async Task CopyEndedAsync(Job job)
|
||
{
|
||
if (_disposed || job.Id != _copyJob) return;
|
||
_copyJob = Guid.Empty;
|
||
var originals = _copyingOriginals;
|
||
_copyingOriginals = false;
|
||
if (job.State == JobState.Failed) _ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), job.Error ?? _session.Content.Sequence.DisplayTitle, isError: true);
|
||
try
|
||
{
|
||
if (job.State == JobState.Done) await _session.ReloadAsync();
|
||
if (job.State == JobState.Done && originals) NotifyOriginalsCopied();
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Warning("workspace", $"The new media of project {ProjectId} could not be read", ex);
|
||
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
|
||
}
|
||
await RefreshAsync();
|
||
RaiseState();
|
||
}
|
||
|
||
private void Apply(WorkspaceStatus status)
|
||
{
|
||
_status = status;
|
||
RaiseState();
|
||
}
|
||
|
||
private void SetSyncing(bool syncing)
|
||
{
|
||
_isSyncing = syncing;
|
||
_sync.RaiseCanExecuteChanged();
|
||
RaiseState();
|
||
}
|
||
|
||
private void RaiseState()
|
||
{
|
||
OnPropertyChanged(nameof(Status));
|
||
OnPropertyChanged(nameof(Name));
|
||
OnPropertyChanged(nameof(IsMain));
|
||
OnPropertyChanged(nameof(IsSyncing));
|
||
OnPropertyChanged(nameof(StateText));
|
||
OnPropertyChanged(nameof(StateKind));
|
||
OnPropertyChanged(nameof(StateToolTip));
|
||
OnPropertyChanged(nameof(MenuToolTip));
|
||
OnPropertyChanged(nameof(MenuName));
|
||
OnPropertyChanged(nameof(HasMediaUpdate));
|
||
OnPropertyChanged(nameof(IsUpdatingMedia));
|
||
OnPropertyChanged(nameof(MediaUpdateText));
|
||
OnPropertyChanged(nameof(CanSaveVersion));
|
||
OnPropertyChanged(nameof(SaveVersionToolTip));
|
||
OnPropertyChanged(nameof(DeleteToolTip));
|
||
OnPropertyChanged(nameof(IsServerHome));
|
||
OnPropertyChanged(nameof(RenameToolTip));
|
||
OnPropertyChanged(nameof(RemoveCopyToolTip));
|
||
OnPropertyChanged(nameof(MediaChangedToolTip));
|
||
OnPropertyChanged(nameof(UpdateMediaToolTip));
|
||
OnPropertyChanged(nameof(HoldsOriginals));
|
||
OnPropertyChanged(nameof(IsMediaBusy));
|
||
OnPropertyChanged(nameof(CopyOriginalsToolTip));
|
||
OnPropertyChanged(nameof(ProxiesOnlyToolTip));
|
||
_updateMedia.RaiseCanExecuteChanged();
|
||
CommandManager.InvalidateRequerySuggested();
|
||
}
|
||
}
|