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.Ui.Controls;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Workspace;
/// What the project menu asks of the window it lives in: its in-window dialogs, confirmations, toasts and the editor's open project.
public interface IWorkspaceUi
{
/// The dialog open now; null when none is.
ArchiveDialogViewModel? Dialog { get; }
/// Shows now, in place of an open one (the dialog the user acted in leads to it).
void ShowDialog(ArchiveDialogViewModel dialog);
///
/// Shows 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.
///
void ShowDialogWhenFree(ArchiveDialogViewModel dialog);
void CloseDialog(ArchiveDialogViewModel dialog);
/// True when the user chose the action (a destructive confirmation).
bool Confirm(ConfirmRequest request);
void Notify(string title, string? message = null, string? actionText = null, string? actionToolTip = null, Action? action = null, bool isError = false);
/// Opens project of in the editor (checked out and copied first when it is not here).
Task OpenProjectAsync(Guid sequenceId, Guid projectId);
/// Closes the open project (its last edit stored first); the picker shows. False when the user kept it open.
Task CloseProjectAsync();
/// The home's sequence changed (a version of Main sent: its settings and hero frame): what shows it reads it again.
Task SequenceChangedAsync(Guid sequenceId);
}
///
/// 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. Call from the UI thread.
///
public sealed class ProjectMenuViewModel : LocalizedViewModel
{
/// How long after the last edit the chip reads the working state again (a little after the editor's save).
public static readonly TimeSpan StateRefreshDelay = TimeSpan.FromMilliseconds(600);
private readonly WorkspaceHost _host;
private readonly WorkspaceSequenceSource _source;
private readonly EditorSession _session;
private readonly IWorkspaceUi _ui;
private readonly AsyncRelayCommand _sync;
private readonly AsyncRelayCommand _updateMedia;
/// The thread the menu was made on (the UI's); null where there is none (tests run inline).
private readonly SynchronizationContext? _context = SynchronizationContext.Current;
private WorkspaceStatus? _status;
private bool _isSyncing;
private bool _homeFramesChanged;
private Guid _copyJob;
private bool _disposed;
/// Counts the editor's changes, so only the last one's state read applies.
private int _changes;
/// The conflict dialog asked in the background, until it is closed (one is asked at a time).
private ConflictDialogViewModel? _asking;
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);
source.JobChanged += OnJobChanged;
session.ProjectChanged += OnProjectChanged;
}
public Guid ProjectId => _source.ProjectId;
public Guid SequenceId => _session.Content.Sequence.Id;
public bool IsMain => _source.Workspace?.IsMain == true;
/// The project's name (Main in the UI language).
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);
public StatusKind StateKind => WorkspaceText.Kind(_status, _isSyncing);
public string StateToolTip => WorkspaceText.StateToolTip(_status, _isSyncing);
/// The ▾ button: its name, then where the project stands, then what the menu holds.
public string MenuToolTip => Loc.L("Tooltips.Editor.Project.Menu", Name, StateText);
/// The button's accessible name: the project and its state.
public string MenuName => string.Join(Loc.Separator, Name, StateText);
///
/// 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.
///
public bool HasMediaUpdate => _homeFramesChanged || _status is { MediaOutdated: true };
/// A copy of the media runs (Update media): the banner says so.
public bool IsUpdatingMedia => _copyJob != Guid.Empty;
public string MediaUpdateText => Loc.L(IsUpdatingMedia ? "Editor.Workspace.Updating" : "Editor.Workspace.MediaChanged");
/// 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.
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 ? Loc.L("Errors.Workspace.DeletedAtHome")
: _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") : Loc.L("Tooltips.Editor.Project.Delete");
/// Save version… (Ctrl+S): the note dialog.
public ICommand SaveVersionCommand { get; }
public ICommand SyncCommand => _sync;
public ICommand HistoryCommand { get; }
/// Open project…: another project of the sequence, one of the library's (a Save both sibling, another PC's) or a new one.
public ICommand OpenProjectCommand { get; }
public ICommand NewProjectCommand { get; }
public ICommand RenameCommand { get; }
public ICommand DeleteCommand { get; }
public ICommand RemoveCopyCommand { get; }
public ICommand UpdateMediaCommand => _updateMedia;
/// Reads where the project stands (against its home) and whether the home's frames moved.
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);
}
}
///
/// 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.
///
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);
}
///
/// Saves the working state as a version with , sent at once with Sync automatically; what the
/// sync took from the home comes into the editor, a conflict it met is asked about.
///
/// Why no version could be saved (the edit could not be stored, a conflict, read-only).
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), 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);
}
///
/// 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 : the sync ran in the background).
///
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(Loc.L(ex is HomeUnavailableException ? "Editor.Workspace.Offline" : "Editor.Workspace.SyncFailed"), WorkspaceText.Failure(ex),
isError: ex is not HomeUnavailableException);
await RefreshAsync();
}
finally
{
SetSyncing(false);
}
}
///
/// Settles the conflict 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).
///
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(Loc.L("Editor.Workspace.TookLibrary"), Name, Loc.L("Editor.Workspace.Undo"), Loc.L("Tooltips.Editor.Workspace.UndoTake"), () => step.Undo());
if (result.Pushed.Count > 0 && IsMain) await _ui.SequenceChangedAsync(SequenceId);
}
else
{
await TakeAsync(result, force: true);
}
NotifySavedAs(result);
}
/// The project Save both made, offered by its toast.
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));
}
/// The library no longer has the project: nothing more is sent, its work stays here (Remove local copy keeps it aside).
private void NotifyGone() => _ui.Notify(Loc.L("Editor.Workspace.State.Gone"), Loc.L("Errors.Workspace.DeletedAtHome"));
///
/// Restores 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.
///
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();
}
///
/// The settings that differ between the project now and , 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).
///
public IReadOnlyList 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;
// 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));
}
private async Task OpenHistoryAsync()
{
var dialog = new HistoryDialogViewModel(Name, v => Task.FromResult(Compare(v)), RestoreAsync, _ui.CloseDialog);
_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);
}
}
///
/// Open project…: "Open in workspace" over the library'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).
///
private async Task OpenOtherProjectAsync()
{
try
{
await StoreEditAsync();
var projects = (await _host.HomeProjectsAsync(SequenceId)).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)]);
_ui.ShowDialog(dialog);
if (await dialog.Choice is not { } choice || _disposed) return;
var id = choice.ProjectId ?? (await _host.CreateProjectAsync(SequenceId, 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), isError: true);
}
}
private async Task OpenNewProjectAsync()
{
var names = await OtherNamesAsync(null);
_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(SequenceId, name, _status?.Base?.VersionId);
_ui.Notify(Loc.L("Editor.Workspace.Created", created.Name), _session.Content.Sequence.DisplayTitle);
_ = _ui.OpenProjectAsync(SequenceId, created.Id);
}, _ui.CloseDialog));
}
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));
}
private async Task DeleteAsync()
{
if (IsMain) return;
var name = Name;
if (!_ui.Confirm(new ConfirmRequest
{
Heading = Loc.L("Editor.Project.DeleteTitle", name),
Message = Loc.L("Editor.Project.DeleteMessage"),
SafeText = Loc.L("Editor.Project.Keep"),
SafeToolTip = Loc.L("Tooltips.Editor.Project.Keep"),
ActionText = Loc.L("Editor.Project.DeleteAction"),
ActionToolTip = Loc.L("Tooltips.Editor.Project.DeleteAction"),
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), 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));
}
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), isError: true);
}
}
///
/// 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.
///
/// Something could not be sent: a conflict to settle first, or the work not in the library yet.
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 library no longer has: only Discard takes the copy, its work kept aside.
if (result.Status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
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(Loc.L("Errors.Workspace.Unsent"));
}
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(Loc.L("Errors.Workspace.Unsent"));
}
var name = Name;
if (!await _ui.CloseProjectAsync()) return;
await _host.RemoveLocalCopyAsync(projectId, discard);
_ui.Notify(Loc.L("Editor.Workspace.Removed"), name);
}
private async Task> OtherNamesAsync(Guid? except)
{
try
{
return [.. (await _host.HomeProjectsAsync(SequenceId)).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), isError: true);
}
}
/// The editor's last edit stored in the working state before an operation reads it.
/// It could not be stored (it is retried in the background; nothing was lost).
private async Task StoreEditAsync()
{
if (await _session.FlushAsync()) return;
throw new WorkspaceException(Loc.L("Errors.Workspace.EditNotStored"), _session.LastSaveError);
}
/// What a sync, resolve or restore took from the home comes into the editor, merged with what was edited meanwhile.
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);
}
///
/// Asks how to settle , the choice applying to it as listed. One a sync met in the
/// (after an analysis) waits for the open dialog to close, and is asked once: the chip
/// says Conflict meanwhile, and Sync asks again.
///
private void AskConflict(WorkspaceConflict conflict, bool background = false)
{
if (background && _asking is { IsClosed: false }) return;
var lines = WorkspaceText.ConflictLines(conflict.Differences, 10);
var dialog = new ConflictDialogViewModel(Name, WorkspaceHost.SiblingName(_source.Workspace?.Name ?? Name), lines, choice => ResolveAsync(choice, conflict),
_ui.CloseDialog, conflict.NewerFormat);
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);
}
/// The editor's project changed (an edit, undo, a merge; the UI thread): the chip reads the working state again a moment later.
private void OnProjectChanged()
{
if (_disposed) return;
_ = RefreshLocalAsync(++_changes);
}
///
/// 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.
///
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}");
}
}
///
/// The state read without the home () 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.
///
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 };
}
/// A job of the engine changed (any thread): the end of the copy Update media queued is handled on the menu's thread.
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);
}
/// The copy of Update media ended: the editor reads the new frames (its positions follow them), or the toast says why not.
private async Task CopyEndedAsync(Job job)
{
if (_disposed || job.Id != _copyJob) return;
_copyJob = Guid.Empty;
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();
}
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), 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));
_updateMedia.RaiseCanExecuteChanged();
CommandManager.InvalidateRequerySuggested();
}
}