774 lines
34 KiB
C#
774 lines
34 KiB
C#
using System.Collections.ObjectModel;
|
||
using System.Windows.Input;
|
||
using Chronos.App.Archiving;
|
||
using Chronos.App.Infrastructure;
|
||
using Chronos.App.Settings;
|
||
using Chronos.Core.Diagnostics;
|
||
using Chronos.Core.Localization;
|
||
using Chronos.Core.Model;
|
||
using Chronos.Core.Project;
|
||
using Chronos.Data.Projects;
|
||
using Chronos.Data.Workspaces;
|
||
using Chronos.Ui.Mvvm;
|
||
|
||
namespace Chronos.App.Workspace;
|
||
|
||
/// <summary>What "Open in workspace" chose: an existing project of the home (<see cref="ProjectId"/>) or a new one (<see cref="NewName"/>), and the media.</summary>
|
||
public sealed record OpenChoice(Guid? ProjectId, string? NewName, string Media);
|
||
|
||
/// <summary>
|
||
/// A project of the home offered by "Open in workspace" (Main in the UI language). One whose copy here this Chronos cannot
|
||
/// read (<paramref name="Unreadable"/>: why) is shown, disabled, its reason in the tooltip.
|
||
/// </summary>
|
||
public sealed record ProjectOption(SequenceProject Project, string? Unreadable = null)
|
||
{
|
||
public string Label => WorkspaceText.ProjectName(Project.Name, Project.IsMain);
|
||
|
||
/// <summary>It can be chosen: its copy here, if any, is one this Chronos reads.</summary>
|
||
public bool IsAvailable => Unreadable is null;
|
||
|
||
public string ToolTip => Unreadable ?? Loc.L("Tooltips.Editor.OpenWorkspace.Projects");
|
||
|
||
public override string ToString() => Label;
|
||
}
|
||
|
||
/// <summary>Project names as the home takes them: 1 to 60 characters, no control character, each once per sequence (case does not count).</summary>
|
||
public static class ProjectNames
|
||
{
|
||
/// <summary>The problem of <paramref name="name"/>, or null when the home takes it.</summary>
|
||
public static string? Validate(string name, IEnumerable<string> others)
|
||
{
|
||
var trimmed = name?.Trim() ?? string.Empty;
|
||
if (trimmed.Length is 0 or > ProjectService.MaxNameLength || trimmed.Any(char.IsControl)) return Loc.L("Errors.Workspace.InvalidName");
|
||
return others.Any(o => string.Equals(o, trimmed, StringComparison.OrdinalIgnoreCase)) ? Loc.L("Errors.Workspace.NameTaken") : null;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// "Open in workspace" (owner review 2, R8), asked when a sequence has no project in the workspace yet, and by the project
|
||
/// menu's Open project: which project of its home (Main, made from the sequence's settings as they are, or another) or a
|
||
/// new one with its name, and the media to copy: the proxies, or (phase 5c) the originals besides, to render on this PC,
|
||
/// offered while the workspace's drive has room for them (Settings › Workspace › Media chooses the default). Open queues
|
||
/// the copy; the sequence opens once it is done.
|
||
/// </summary>
|
||
public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
|
||
{
|
||
private readonly TaskCompletionSource<OpenChoice?> _choice = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
private readonly bool _server;
|
||
private ProjectOption? _selected;
|
||
private bool _isNew;
|
||
private bool _isOriginals;
|
||
|
||
/// <param name="taken">The names a new project cannot take (default: those of <paramref name="projects"/>).</param>
|
||
/// <param name="copy">What the copy of the media writes and the free space of the workspace's drive; null when not measured (shown as nothing).</param>
|
||
/// <param name="unreadable">
|
||
/// The projects whose copy here this Chronos cannot read (damaged, or a newer Chronos's), with why: listed, never chosen.
|
||
/// </param>
|
||
/// <param name="server">The sequence's home is a server (phase 5b): the texts name the server.</param>
|
||
/// <param name="defaultMedia">The media chosen first (<see cref="AppSettings.WorkspaceDefaultMedia"/>); the proxies when the originals have no room.</param>
|
||
public OpenInWorkspaceDialogViewModel(string sequenceTitle, IReadOnlyList<SequenceProject> projects, Action<ArchiveDialogViewModel> close,
|
||
IReadOnlyList<string>? taken = null, WorkspaceCopyFacts? copy = null, IReadOnlyDictionary<Guid, string>? unreadable = null, bool server = false,
|
||
string defaultMedia = BundleMedia.Proxies)
|
||
: base(close)
|
||
{
|
||
_server = server;
|
||
SequenceTitle = sequenceTitle;
|
||
Copy = copy;
|
||
CopyFacts = copy is null ? []
|
||
:
|
||
[
|
||
new DialogFact(Loc.L("Editor.OpenWorkspace.Size"), Formatting.Bytes(copy.Bytes), Reason: Loc.L("Tooltips.Editor.OpenWorkspace.Size")),
|
||
new DialogFact(Loc.L("Editor.OpenWorkspace.Free"), copy.Free is { } free ? Formatting.Bytes(free) : Loc.L("Server.Sync.None"),
|
||
Reason: Loc.L(copy.TooLittleSpace ? "Errors.Workspace.NoRoom" : "Tooltips.Editor.OpenWorkspace.Free")),
|
||
.. copy.OriginalsBytes is { } originals
|
||
? [new DialogFact(Loc.L("Editor.OpenWorkspace.Originals"), Formatting.Bytes(originals), Reason: Loc.L("Tooltips.Editor.OpenWorkspace.OriginalsSize"))]
|
||
: Array.Empty<DialogFact>(),
|
||
];
|
||
_isOriginals = defaultMedia == BundleMedia.Originals && CanCopyOriginals;
|
||
Projects = [.. projects.OrderByDescending(p => p.IsMain).Select(p => new ProjectOption(p, unreadable?.GetValueOrDefault(p.Id)))];
|
||
_selected = Projects.FirstOrDefault(p => p.IsAvailable);
|
||
_isNew = !HasProjects;
|
||
var names = taken ?? [.. projects.Select(p => p.Name)];
|
||
NewName = new EditableField(string.Empty, n => ProjectNames.Validate(n, names), _ => { }, () => Loc.L("Tooltips.Editor.OpenWorkspace.Name"));
|
||
NewName.PropertyChanged += (_, _) => Refresh();
|
||
OpenCommand = new RelayCommand(Open, () => CanOpen);
|
||
}
|
||
|
||
/// <summary>Completes with the user's choice, or null when the dialog was closed without one.</summary>
|
||
public Task<OpenChoice?> Choice => _choice.Task;
|
||
|
||
public string SequenceTitle { get; }
|
||
|
||
/// <summary>The copy's bytes and the drive's free space, when measured.</summary>
|
||
public WorkspaceCopyFacts? Copy { get; }
|
||
|
||
/// <summary>"Copy size" and "Free space", under the media.</summary>
|
||
public IReadOnlyList<DialogFact> CopyFacts { get; }
|
||
|
||
/// <summary>The drive lacks room for the copy of the media chosen: the free space says so (the copy would stop saying how much is missing).</summary>
|
||
public bool IsShortOfSpace => Copy?.TooLittleSpaceFor(Media) == true;
|
||
|
||
public string Heading => Loc.L("Editor.OpenWorkspace.Title");
|
||
|
||
public IReadOnlyList<ProjectOption> Projects { get; }
|
||
|
||
/// <summary>A project of the home can be chosen (one this Chronos cannot read here is only listed).</summary>
|
||
public bool HasProjects => Projects.Any(p => p.IsAvailable);
|
||
|
||
public ProjectOption? SelectedProject
|
||
{
|
||
get => _selected;
|
||
set
|
||
{
|
||
if (value is { IsAvailable: false }) return;
|
||
if (Set(ref _selected, value) && value is not null) IsExisting = true;
|
||
}
|
||
}
|
||
|
||
/// <summary>A project the home has.</summary>
|
||
public bool IsExisting
|
||
{
|
||
get => !_isNew;
|
||
set
|
||
{
|
||
if (value) IsNew = false;
|
||
}
|
||
}
|
||
|
||
/// <summary>A new project, named in <see cref="NewName"/>.</summary>
|
||
public bool IsNew
|
||
{
|
||
get => _isNew;
|
||
set
|
||
{
|
||
if (!Set(ref _isNew, value || !HasProjects)) return;
|
||
OnPropertyChanged(nameof(IsExisting));
|
||
Refresh();
|
||
}
|
||
}
|
||
|
||
public EditableField NewName { get; }
|
||
|
||
public string ExistingToolTip => WorkspaceText.ForHome("Tooltips.Editor.OpenWorkspace.Existing", _server);
|
||
|
||
public string ProjectsToolTip => WorkspaceText.ForHome("Tooltips.Editor.OpenWorkspace.Projects", _server);
|
||
|
||
public string ProxiesToolTip => WorkspaceText.ForHome("Tooltips.Editor.OpenWorkspace.Proxies", _server);
|
||
|
||
/// <summary>The proxies alone: light to edit, renders run where the originals are.</summary>
|
||
public bool IsProxies
|
||
{
|
||
get => !_isOriginals;
|
||
set
|
||
{
|
||
if (value) IsOriginals = false;
|
||
}
|
||
}
|
||
|
||
/// <summary>The proxies and the originals (phase 5c): renders run on this PC.</summary>
|
||
public bool IsOriginals
|
||
{
|
||
get => _isOriginals;
|
||
set
|
||
{
|
||
if (!Set(ref _isOriginals, value && CanCopyOriginals)) return;
|
||
OnPropertyChanged(nameof(IsProxies));
|
||
OnPropertyChanged(nameof(IsShortOfSpace));
|
||
}
|
||
}
|
||
|
||
/// <summary>The media <see cref="Open"/> copies.</summary>
|
||
public string Media => _isOriginals ? BundleMedia.Originals : BundleMedia.Proxies;
|
||
|
||
/// <summary>The originals can be chosen: the drive has room for them besides the proxies (or was not measured: the copy measures again).</summary>
|
||
public bool CanCopyOriginals => Copy?.TooLittleSpaceFor(BundleMedia.Originals) != true;
|
||
|
||
public string OriginalsToolTip => CanCopyOriginals
|
||
? WorkspaceText.ForHome("Tooltips.Editor.OpenWorkspace.OriginalsReady", _server)
|
||
: Loc.L("Tooltips.Editor.OpenWorkspace.NoRoomOriginals");
|
||
|
||
public ICommand OpenCommand { get; }
|
||
|
||
public bool CanOpen => _isNew ? !NewName.HasErrors : _selected is { IsAvailable: true };
|
||
|
||
public string OpenToolTip => _isNew && NewName.Error is { } error ? error : Loc.L("Tooltips.Editor.OpenWorkspace.Open");
|
||
|
||
public override void Dispose()
|
||
{
|
||
// Closed without a choice (Cancel, Esc, another sequence asked for).
|
||
_choice.TrySetResult(null);
|
||
base.Dispose();
|
||
}
|
||
|
||
private void Open()
|
||
{
|
||
if (!CanOpen) return;
|
||
_choice.TrySetResult(_isNew ? new OpenChoice(null, NewName.Text.Trim(), Media) : new OpenChoice(_selected!.Project.Id, null, Media));
|
||
Close();
|
||
}
|
||
|
||
private void Refresh()
|
||
{
|
||
OnPropertyChanged(nameof(CanOpen));
|
||
OnPropertyChanged(nameof(OpenToolTip));
|
||
CommandManager.InvalidateRequerySuggested();
|
||
}
|
||
}
|
||
|
||
/// <summary>A project of the workspace offered by "Open which project?" (Main in the UI language).</summary>
|
||
public sealed record WorkspaceProjectChoice(WorkspaceEntry Entry)
|
||
{
|
||
public string Label => WorkspaceText.ProjectName(Entry.Name, Entry.IsMain);
|
||
|
||
public override string ToString() => Label;
|
||
}
|
||
|
||
/// <summary>
|
||
/// "Open which project?" (phase 5c, Settings › Workspace › Open project: Ask): Edit asks which of the sequence's projects in
|
||
/// the workspace opens, the one opened last chosen first.
|
||
/// </summary>
|
||
public sealed class OpenProjectDialogViewModel : ArchiveDialogViewModel
|
||
{
|
||
private readonly TaskCompletionSource<WorkspaceEntry?> _choice = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||
private WorkspaceProjectChoice? _selected;
|
||
|
||
/// <param name="projects">The sequence's readable projects in the workspace.</param>
|
||
/// <param name="last">The project opened last, chosen first; null: Main.</param>
|
||
public OpenProjectDialogViewModel(string sequenceTitle, IReadOnlyList<WorkspaceEntry> projects, Guid? last, Action<ArchiveDialogViewModel> close)
|
||
: base(close)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(projects);
|
||
Message = Loc.L("Editor.OpenProject.Message", sequenceTitle);
|
||
Projects = [.. projects.OrderByDescending(p => p.IsMain).ThenBy(p => p.Name, StringComparer.CurrentCultureIgnoreCase).Select(p => new WorkspaceProjectChoice(p))];
|
||
_selected = Projects.FirstOrDefault(p => p.Entry.ProjectId == last) ?? Projects.FirstOrDefault();
|
||
OpenCommand = new RelayCommand(Open, () => _selected is not null);
|
||
}
|
||
|
||
/// <summary>Completes with the project chosen, or null when the dialog was closed without one.</summary>
|
||
public Task<WorkspaceEntry?> Choice => _choice.Task;
|
||
|
||
public string Heading => Loc.L("Editor.OpenProject.Title");
|
||
|
||
public string Message { get; }
|
||
|
||
public IReadOnlyList<WorkspaceProjectChoice> Projects { get; }
|
||
|
||
public WorkspaceProjectChoice? SelectedProject
|
||
{
|
||
get => _selected;
|
||
set
|
||
{
|
||
if (Set(ref _selected, value)) CommandManager.InvalidateRequerySuggested();
|
||
}
|
||
}
|
||
|
||
public ICommand OpenCommand { get; }
|
||
|
||
public override void Dispose()
|
||
{
|
||
_choice.TrySetResult(null);
|
||
base.Dispose();
|
||
}
|
||
|
||
private void Open()
|
||
{
|
||
if (_selected is null) return;
|
||
_choice.TrySetResult(_selected.Entry);
|
||
Close();
|
||
}
|
||
}
|
||
|
||
/// <summary>Names a project: "New project" (made from the open project's last version at the home) or "Rename".</summary>
|
||
public sealed class ProjectNameDialogViewModel : ArchiveDialogViewModel
|
||
{
|
||
private readonly Func<string, Task> _save;
|
||
private readonly bool _server;
|
||
|
||
/// <param name="others">The names of the sequence's other projects (each name is used once).</param>
|
||
/// <param name="server">The project's home is a server (phase 5b): the texts name the server.</param>
|
||
public ProjectNameDialogViewModel(bool rename, string name, IEnumerable<string> others, Func<string, Task> save, Action<ArchiveDialogViewModel> close,
|
||
bool server = false)
|
||
: base(close)
|
||
{
|
||
IsRename = rename;
|
||
_save = save;
|
||
_server = server;
|
||
var taken = others.ToList();
|
||
Name = new EditableField(name, n => ProjectNames.Validate(n, taken), _ => { }, () => Loc.L("Tooltips.Editor.ProjectName.Name"));
|
||
Name.PropertyChanged += (_, _) =>
|
||
{
|
||
OnPropertyChanged(nameof(SaveToolTip));
|
||
CommandManager.InvalidateRequerySuggested();
|
||
};
|
||
SaveCommand = new AsyncRelayCommand(SaveAsync, () => !IsBusy && !Name.HasErrors);
|
||
}
|
||
|
||
public bool IsRename { get; }
|
||
|
||
public string Heading => Loc.L(IsRename ? "Editor.ProjectName.Rename" : "Editor.ProjectName.New");
|
||
|
||
public string SaveText => Loc.L(IsRename ? "Editor.ProjectName.Apply" : "Editor.ProjectName.Create");
|
||
|
||
public EditableField Name { get; }
|
||
|
||
public ICommand SaveCommand { get; }
|
||
|
||
public string SaveToolTip => Name.Error ?? WorkspaceText.ForHome(IsRename ? "Tooltips.Editor.ProjectName.Apply" : "Tooltips.Editor.ProjectName.Create", _server);
|
||
|
||
private async Task SaveAsync()
|
||
{
|
||
ClearError();
|
||
IsBusy = true;
|
||
try
|
||
{
|
||
await _save(Name.Text.Trim());
|
||
Close();
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Warning("workspace", "Naming a project failed", ex);
|
||
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
|
||
}
|
||
finally
|
||
{
|
||
IsBusy = false;
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>"Save version" (Ctrl+S): an optional note, then the version is saved (and sent when Sync automatically is on).</summary>
|
||
public sealed class SaveVersionDialogViewModel : ArchiveDialogViewModel
|
||
{
|
||
/// <summary>A note is a line of the history: longer text is cut there.</summary>
|
||
public const int MaxNoteLength = 200;
|
||
|
||
private readonly Func<string?, Task> _save;
|
||
private readonly bool _server;
|
||
private string _note = string.Empty;
|
||
|
||
/// <param name="server">The project's home is a server (phase 5b): the texts name the server.</param>
|
||
public SaveVersionDialogViewModel(string projectName, Func<string?, Task> save, Action<ArchiveDialogViewModel> close, bool server = false)
|
||
: base(close)
|
||
{
|
||
ProjectName = projectName;
|
||
_save = save;
|
||
_server = server;
|
||
SaveCommand = new AsyncRelayCommand(SaveAsync, () => !IsBusy);
|
||
}
|
||
|
||
public string ProjectName { get; }
|
||
|
||
public string Heading => Loc.L("Editor.SaveVersion.Title", ProjectName);
|
||
|
||
public string SaveToolTip => WorkspaceText.ForHome("Tooltips.Editor.SaveVersion.Save", _server);
|
||
|
||
public string Note
|
||
{
|
||
get => _note;
|
||
set => Set(ref _note, (value ?? string.Empty).Length > MaxNoteLength ? value![..MaxNoteLength] : value ?? string.Empty);
|
||
}
|
||
|
||
public ICommand SaveCommand { get; }
|
||
|
||
private async Task SaveAsync()
|
||
{
|
||
ClearError();
|
||
IsBusy = true;
|
||
try
|
||
{
|
||
await _save(string.IsNullOrWhiteSpace(_note) ? null : _note.Trim());
|
||
Close();
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Warning("workspace", "Saving a version failed", ex);
|
||
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
|
||
}
|
||
finally
|
||
{
|
||
IsBusy = false;
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>A version in the History flyout: number, author, time, note, what made it, and Compare and Restore.</summary>
|
||
public sealed class HistoryRowViewModel(ProjectVersion version, bool unsent, bool isCurrent, ICommand compare, ICommand restore, bool server = false) : ObservableObject
|
||
{
|
||
public ProjectVersion Version { get; } = version;
|
||
|
||
/// <summary>"Saved here, waiting to be sent to the library" (the server, for a server's project).</summary>
|
||
public string NotSentToolTip => WorkspaceText.ForHome("Tooltips.Editor.History.NotSent", server);
|
||
|
||
public string Number => Formatting.Count(Version.Number);
|
||
|
||
public string Author => WorkspaceText.Author(Version);
|
||
|
||
public string When => WorkspaceText.When(Version.CreatedAt);
|
||
|
||
public string Note => Version.Note ?? string.Empty;
|
||
|
||
public string KindText => WorkspaceText.VersionKind(Version.Kind);
|
||
|
||
/// <summary>Saved here, waiting to be sent.</summary>
|
||
public bool IsUnsent { get; } = unsent;
|
||
|
||
/// <summary>The version the working state was last saved as (nothing differs).</summary>
|
||
public bool IsCurrent { get; } = isCurrent;
|
||
|
||
/// <summary>"Version 3 · Saved · STUDIO-PC · 28/10/2026 18:02 · note": the row for screen readers and its tooltip.</summary>
|
||
public string Description => string.Join(Loc.Separator, new[] { Loc.L("Editor.History.Version", Number), KindText, Author, When, Note }.Where(s => s.Length > 0));
|
||
|
||
public ICommand CompareCommand { get; } = compare;
|
||
|
||
public ICommand RestoreCommand { get; } = restore;
|
||
|
||
public string CompareToolTip => Loc.L("Tooltips.Editor.History.Compare", Number);
|
||
|
||
public string RestoreToolTip => Loc.L("Tooltips.Editor.History.Restore", Number);
|
||
}
|
||
|
||
/// <summary>
|
||
/// The History flyout of a workspace project: its versions newest first (those not sent yet marked), Compare (the
|
||
/// settings that differ from the project now) and Restore (the version as the project again, one undo step).
|
||
/// </summary>
|
||
public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
|
||
{
|
||
private readonly Func<ProjectVersion, Task<IReadOnlyList<string>>> _compare;
|
||
private readonly Func<ProjectVersion, Task> _restore;
|
||
private readonly bool _server;
|
||
private string? _comparedTitle;
|
||
private IReadOnlyList<string> _compared = [];
|
||
private bool _isLoaded;
|
||
|
||
/// <param name="server">The project's home is a server (phase 5b): the texts name the server.</param>
|
||
public HistoryDialogViewModel(string projectName, Func<ProjectVersion, Task<IReadOnlyList<string>>> compare, Func<ProjectVersion, Task> restore,
|
||
Action<ArchiveDialogViewModel> close, bool server = false)
|
||
: base(close)
|
||
{
|
||
ProjectName = projectName;
|
||
_compare = compare;
|
||
_restore = restore;
|
||
_server = server;
|
||
}
|
||
|
||
public string ProjectName { get; }
|
||
|
||
public string Heading => Loc.L("Editor.History.Title", ProjectName);
|
||
|
||
public ObservableCollection<HistoryRowViewModel> Rows { get; } = [];
|
||
|
||
/// <summary>The home could not be asked: only this PC's versions are listed.</summary>
|
||
public bool IsOffline { get; private set; }
|
||
|
||
/// <summary>"Library offline", or "Server offline" for a server's project.</summary>
|
||
public string OfflineText => WorkspaceText.ForHome("Editor.History.Offline", _server);
|
||
|
||
public string OfflineToolTip => WorkspaceText.ForHome("Tooltips.Editor.History.Offline", _server);
|
||
|
||
public bool IsEmpty => _isLoaded && Rows.Count == 0;
|
||
|
||
/// <summary>"Version 3 → now" over the comparison; null before one.</summary>
|
||
public string? ComparedTitle { get => _comparedTitle; private set => Set(ref _comparedTitle, value); }
|
||
|
||
public IReadOnlyList<string> Compared { get => _compared; private set => Set(ref _compared, value); }
|
||
|
||
/// <summary>Lists <paramref name="history"/>; <paramref name="currentHash"/> marks the version the project is now.</summary>
|
||
public void Show(WorkspaceHistory history, string? currentHash)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(history);
|
||
Rows.Clear();
|
||
foreach (var version in history.Versions)
|
||
{
|
||
var current = currentHash is not null && string.Equals(version.ContentHash, currentHash, StringComparison.OrdinalIgnoreCase);
|
||
Rows.Add(new HistoryRowViewModel(version, history.Unsent.Contains(version.Id), current,
|
||
new AsyncRelayCommand(() => CompareAsync(version), () => !IsBusy), new AsyncRelayCommand(() => RestoreAsync(version), () => !IsBusy), _server));
|
||
}
|
||
IsOffline = history.Offline;
|
||
_isLoaded = true;
|
||
OnPropertyChanged(nameof(IsOffline));
|
||
OnPropertyChanged(nameof(IsEmpty));
|
||
}
|
||
|
||
/// <summary>A failure of the read that lists the versions, shown in the flyout.</summary>
|
||
public void ShowFailure(Exception ex)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(ex);
|
||
_isLoaded = true;
|
||
OnPropertyChanged(nameof(IsEmpty));
|
||
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
|
||
}
|
||
|
||
public async Task CompareAsync(ProjectVersion version)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(version);
|
||
ClearError();
|
||
try
|
||
{
|
||
var lines = await _compare(version);
|
||
ComparedTitle = Loc.L("Editor.History.Compared", Formatting.Count(version.Number));
|
||
Compared = lines.Count == 0 ? [Loc.L("Editor.History.Same")] : lines;
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Warning("workspace", $"Version {version.Number} could not be compared", ex);
|
||
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
|
||
}
|
||
}
|
||
|
||
public async Task RestoreAsync(ProjectVersion version)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(version);
|
||
ClearError();
|
||
IsBusy = true;
|
||
try
|
||
{
|
||
await _restore(version);
|
||
IsBusy = false;
|
||
Close();
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Warning("workspace", $"Version {version.Number} could not be restored", ex);
|
||
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
|
||
IsBusy = false;
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// A sync that met settings both sides changed (owner review 2, R8: asked only on real conflicts): what differs, then
|
||
/// Keep mine, Take the library's, or Save both (this workspace's versions go to a sibling project). Later leaves the
|
||
/// conflict for the next Sync; editing goes on meanwhile. A conflict of format (the library's project saved by a newer
|
||
/// Chronos, <see cref="WorkspaceConflict.NewerFormat"/>) cannot be merged either way: only Save both and Later are offered.
|
||
/// </summary>
|
||
public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
|
||
{
|
||
private readonly Func<ConflictChoice, Task> _resolve;
|
||
private readonly bool _server;
|
||
|
||
/// <param name="newerFormat">The library holds a newer Chronos's settings: nothing is merged, Save both is the only choice.</param>
|
||
/// <param name="server">The project's home is a server (phase 5b): "Take server's", and the texts name the server.</param>
|
||
public ConflictDialogViewModel(string projectName, string siblingName, IReadOnlyList<string> differences, Func<ConflictChoice, Task> resolve,
|
||
Action<ArchiveDialogViewModel> close, bool newerFormat = false, bool server = false)
|
||
: base(close)
|
||
{
|
||
ProjectName = projectName;
|
||
SiblingName = siblingName;
|
||
IsNewerFormat = newerFormat;
|
||
// The format's number says nothing to the user: the line names the cause.
|
||
Differences = newerFormat ? [Loc.L("Editor.Workspace.Conflict.NewerFormat")] : differences;
|
||
_resolve = resolve;
|
||
_server = server;
|
||
KeepMineCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.KeepMine), () => !IsBusy && CanMerge);
|
||
TakeHomeCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.TakeServer), () => !IsBusy && CanMerge);
|
||
SaveBothCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.SaveBoth), () => !IsBusy);
|
||
}
|
||
|
||
/// <summary>The library's project was saved by a newer Chronos.</summary>
|
||
public bool IsNewerFormat { get; }
|
||
|
||
/// <summary>Keep mine and Take the library's are offered (not for a conflict of format, which neither can settle).</summary>
|
||
public bool CanMerge => !IsNewerFormat;
|
||
|
||
public string ProjectName { get; }
|
||
|
||
/// <summary>The project Save both makes for this workspace's versions.</summary>
|
||
public string SiblingName { get; }
|
||
|
||
public string Heading => WorkspaceText.ForHome("Editor.Workspace.Conflict.Title", _server);
|
||
|
||
public string Message => WorkspaceText.ForHome(IsNewerFormat ? "Editor.Workspace.Conflict.NewerMessage" : "Editor.Workspace.Conflict.Message", _server, ProjectName);
|
||
|
||
public IReadOnlyList<string> Differences { get; }
|
||
|
||
public string DifferencesToolTip => WorkspaceText.ForHome(IsNewerFormat ? "Tooltips.Editor.Workspace.NewerFormat" : "Tooltips.Editor.Workspace.Differences", _server);
|
||
|
||
public ICommand KeepMineCommand { get; }
|
||
|
||
public ICommand TakeHomeCommand { get; }
|
||
|
||
public ICommand SaveBothCommand { get; }
|
||
|
||
/// <summary>"Take library's", or "Take server's" for a server's project.</summary>
|
||
public string TakeHomeText => WorkspaceText.ForHome("Editor.Workspace.Conflict.TakeHome", _server);
|
||
|
||
public string TakeHomeToolTip => WorkspaceText.ForHome("Tooltips.Editor.Workspace.TakeHome", _server);
|
||
|
||
public string KeepMineToolTip => WorkspaceText.ForHome("Tooltips.Editor.Workspace.KeepMine", _server);
|
||
|
||
public string SaveBothToolTip => WorkspaceText.ForHome(IsNewerFormat ? "Tooltips.Editor.Workspace.SaveBothNewer" : "Tooltips.Editor.Workspace.SaveBoth", _server, SiblingName);
|
||
|
||
private async Task ResolveAsync(ConflictChoice choice)
|
||
{
|
||
ClearError();
|
||
IsBusy = true;
|
||
try
|
||
{
|
||
await _resolve(choice);
|
||
IsBusy = false;
|
||
Close();
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Warning("workspace", $"The conflict of '{ProjectName}' could not be settled ({choice})", ex);
|
||
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
|
||
IsBusy = false;
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// "Remove local copy": the plan (files and size of the copy; versions not sent and changes not saved), then Remove
|
||
/// (only when everything is at the library), Send first (sends, then removes), or Discard changes (removes once the
|
||
/// user typed the project's name; the unsent work is kept aside in the workspace's trash). A project the library no
|
||
/// longer has (<see cref="WorkspaceRemovalPlan.Gone"/>), or a copy whose working state cannot be read
|
||
/// (<see cref="WorkspaceRemovalPlan.Damaged"/>), can only be discarded that way.
|
||
/// </summary>
|
||
public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
|
||
{
|
||
private readonly Func<bool, Task> _remove;
|
||
private readonly Func<Task> _sendFirst;
|
||
private readonly Func<bool> _confirmDiscard;
|
||
private readonly bool _server;
|
||
|
||
/// <param name="confirmDiscard">The typed confirmation Discard changes asks first (<see cref="ConfirmDiscard"/>); true when the user confirmed.</param>
|
||
/// <param name="server">The project's home is a server (phase 5b): the texts name the server.</param>
|
||
public RemoveCopyDialogViewModel(WorkspaceRemovalPlan plan, Func<bool, Task> remove, Func<Task> sendFirst, Func<bool> confirmDiscard, Action<ArchiveDialogViewModel> close,
|
||
bool server = false)
|
||
: base(close)
|
||
{
|
||
Plan = plan;
|
||
_remove = remove;
|
||
_sendFirst = sendFirst;
|
||
_confirmDiscard = confirmDiscard;
|
||
_server = server;
|
||
Facts =
|
||
[
|
||
new DialogFact(Loc.L("Editor.RemoveCopy.Files"), Formatting.Count(plan.Files)),
|
||
new DialogFact(Loc.L("Editor.RemoveCopy.Size"), Formatting.Bytes(plan.Bytes)),
|
||
new DialogFact(Loc.L("Editor.RemoveCopy.Unsent"), Formatting.Count(plan.Unsent)),
|
||
new DialogFact(Loc.L("Editor.RemoveCopy.Changed"), Loc.L(plan.Modified ? "Editor.RemoveCopy.Yes" : "Editor.RemoveCopy.No")),
|
||
// Phase 5c: renders made here not sent yet, and originals the home lost (they go to the trash): shown only when there are some.
|
||
.. plan.UnsentRenders > 0
|
||
? [new DialogFact(Loc.L("Editor.RemoveCopy.UnsentRenders"), Formatting.Count(plan.UnsentRenders),
|
||
Reason: WorkspaceText.ForHome("Tooltips.Editor.RemoveCopy.UnsentRenders", server))]
|
||
: Array.Empty<DialogFact>(),
|
||
.. plan.LastOriginals > 0
|
||
? [new DialogFact(Loc.L("Editor.RemoveCopy.LastOriginals"), Formatting.Count(plan.LastOriginals),
|
||
Reason: WorkspaceText.ForHome("Tooltips.Editor.RemoveCopy.LastOriginals", server))]
|
||
: Array.Empty<DialogFact>(),
|
||
];
|
||
RemoveCommand = new AsyncRelayCommand(() => RunAsync(() => _remove(false)), () => !IsBusy && plan.IsSafe && !plan.Offline && !plan.Gone);
|
||
SendFirstCommand = new AsyncRelayCommand(() => RunAsync(_sendFirst), () => !IsBusy && !plan.IsSafe && !plan.Conflict && !plan.Offline && !plan.Gone && !plan.Damaged);
|
||
DiscardCommand = new AsyncRelayCommand(DiscardAsync, () => !IsBusy && HasUnsent);
|
||
}
|
||
|
||
public WorkspaceRemovalPlan Plan { get; }
|
||
|
||
/// <summary>"Remove local copy of Main"; a damaged copy by the name it is still known by, else as a damaged copy (never by its folder's id).</summary>
|
||
public string Heading => !Plan.Damaged ? Loc.L("Editor.RemoveCopy.Title", WorkspaceText.ProjectName(Plan.Name, false))
|
||
: Plan.KnownName is { Length: > 0 } known ? Loc.L("Editor.RemoveCopy.Title", known)
|
||
: Loc.L("Editor.RemoveCopy.DamagedTitle");
|
||
|
||
public IReadOnlyList<DialogFact> Facts { get; }
|
||
|
||
/// <summary>Something would not be at the library after the removal (or the library no longer has the project): Discard changes shows.</summary>
|
||
public bool HasUnsent => !Plan.IsSafe || Plan.Gone;
|
||
|
||
public ICommand RemoveCommand { get; }
|
||
|
||
public ICommand SendFirstCommand { get; }
|
||
|
||
public ICommand DiscardCommand { get; }
|
||
|
||
/// <summary>What happens to the copy and the project, worded for the project's home.</summary>
|
||
public string Message => WorkspaceText.ForHome("Editor.RemoveCopy.Message", _server);
|
||
|
||
public string RemoveToolTip => Plan.Damaged ? Loc.L("Errors.Workspace.Damaged")
|
||
: Plan.Gone ? WorkspaceText.ForHome("Errors.Workspace.ProjectGone", _server)
|
||
: !Plan.IsSafe ? WorkspaceText.ForHome("Errors.Workspace.Unsent", _server)
|
||
: Plan.Offline ? WorkspaceText.ForHome("Errors.Workspace.Offline", _server)
|
||
: WorkspaceText.ForHome("Tooltips.Editor.RemoveCopy.Remove", _server);
|
||
|
||
public string SendFirstToolTip => Plan.Damaged ? Loc.L("Errors.Workspace.Damaged")
|
||
: Plan.Gone ? WorkspaceText.ForHome("Errors.Workspace.ProjectGone", _server)
|
||
: Plan.Conflict ? Loc.L("Errors.Workspace.Conflict")
|
||
: Plan.Offline ? WorkspaceText.ForHome("Errors.Workspace.Offline", _server)
|
||
: WorkspaceText.ForHome("Tooltips.Editor.RemoveCopy.SendFirst", _server);
|
||
|
||
public string DiscardToolTip => WorkspaceText.ForHome("Tooltips.Editor.RemoveCopy.Discard", _server);
|
||
|
||
/// <summary>
|
||
/// The typed confirmation of Discard changes (the plan's cross-cutting rule for what Chronos cannot bring back): the
|
||
/// project's name, as shown, typed before Discard enables.
|
||
/// </summary>
|
||
public static ConfirmRequest DiscardRequest(string projectName) => new()
|
||
{
|
||
Heading = Loc.L("Editor.RemoveCopy.DiscardTitle", projectName),
|
||
Message = Loc.L("Editor.RemoveCopy.DiscardMessage"),
|
||
SafeText = Loc.L("Editor.Project.Keep"),
|
||
SafeToolTip = Loc.L("Tooltips.Editor.RemoveCopy.Keep"),
|
||
ActionText = Loc.L("Editor.RemoveCopy.Discard"),
|
||
ActionToolTip = Loc.L("Tooltips.Editor.RemoveCopy.Discard"),
|
||
IsDestructive = true,
|
||
TypedConfirmation = projectName,
|
||
TypedPrompt = Loc.L("Editor.RemoveCopy.TypeName"),
|
||
};
|
||
|
||
/// <summary>
|
||
/// The typed confirmation of discarding a damaged copy (<see cref="WorkspaceRemovalPlan.Damaged"/>): the name it is still
|
||
/// known by (<see cref="WorkspaceRemovalPlan.KnownName"/>), never its folder's id; with no name known, the number of its
|
||
/// files, as the plan shows it.
|
||
/// </summary>
|
||
public static ConfirmRequest DiscardRequest(WorkspaceRemovalPlan plan)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(plan);
|
||
if (plan.KnownName is { Length: > 0 } known) return DiscardRequest(known);
|
||
var files = Formatting.Count(plan.Files);
|
||
return DiscardRequest(string.Empty) with
|
||
{
|
||
Heading = Loc.L("Editor.RemoveCopy.DamagedDiscard"),
|
||
TypedConfirmation = files,
|
||
TypedPrompt = Loc.L("Editor.RemoveCopy.TypeFiles", files),
|
||
};
|
||
}
|
||
|
||
/// <summary>Asks <see cref="DiscardRequest(string)"/> through <paramref name="ui"/>: true when the user typed the name and confirmed.</summary>
|
||
public static bool ConfirmDiscard(IWorkspaceUi ui, string projectName)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(ui);
|
||
return ui.Confirm(DiscardRequest(projectName));
|
||
}
|
||
|
||
/// <summary>Asks <see cref="DiscardRequest(WorkspaceRemovalPlan)"/> through <paramref name="ui"/>: true when the user typed what it asks and confirmed.</summary>
|
||
public static bool ConfirmDiscard(IWorkspaceUi ui, WorkspaceRemovalPlan plan)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(ui);
|
||
return ui.Confirm(DiscardRequest(plan));
|
||
}
|
||
|
||
private async Task DiscardAsync()
|
||
{
|
||
if (!_confirmDiscard()) return;
|
||
await RunAsync(() => _remove(true));
|
||
}
|
||
|
||
private async Task RunAsync(Func<Task> action)
|
||
{
|
||
ClearError();
|
||
IsBusy = true;
|
||
try
|
||
{
|
||
await action();
|
||
IsBusy = false;
|
||
Close();
|
||
}
|
||
catch (Exception ex) when (ex is not OutOfMemoryException)
|
||
{
|
||
Log.Warning("workspace", $"The local copy of project {Plan.ProjectId} was not removed", ex);
|
||
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
|
||
IsBusy = false;
|
||
}
|
||
}
|
||
}
|