feat(app): Edit opens workspace projects, with versions, sync and the project menu
Owner review 2, phase 5a (R8), desktop package: editing moves out of the library. A sequence of this PC's archive now opens in Edit as a project of the workspace (%LOCALAPPDATA%\Chronos\workspace, .\data\workspace when portable), with this PC's archive as its home; the editor writes the workspace's working state, never the library. - WorkspaceHost composes WorkspaceStore and WorkspaceSync over Settings > Workspace's folder: checkout and the WorkspaceCopy job, status, Save version with the sync after it (Sync automatically, on by default), sync (pull, then push), conflicts, restore, history, new / rename / delete project, and Remove local copy, which refuses while work is unsent unless the user sends it first or discards it, reads back the home's head and base and checks their hashes, and keeps discarded work in <workspace>/.trash; versions past Kept versions are pruned only once the home returns them with the same content. - WorkspaceSequenceSource: frames and pixels of the media (proxies), the working state saved atomically under the project's lease and merged against the basis, the home's deep report while its frames are the media's, renders at the home with the portable settings recording the project and the version. - Edit: the project opened last for the sequence, else "Open in workspace" (Main made from the sequence's settings, another project or a new one; proxies) checks out, copies and opens once the copy is done. The picker lists the workspace's projects with their state above the library. The title's project menu: Save version (Ctrl+S, note), Sync, History (compare, restore as one undo step), New project, Rename, Delete project, Remove local copy; a conflict dialog only on real conflicts (keep mine, take the library's, save both, later); Update media when the library's frames moved. .chronos files: format 2 opens its project, format 1 gives its settings to Main. - Settings > Workspace: folder (shown, Open), Sync automatically, Kept versions. Strings in English and Italian. - A capture (sample data without an engine) keeps editing the library. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> (cherry picked from commit da47a580ba9db3ce2a1db2f11c30cf7344c8b394)
This commit is contained in:
1 parent
03d32f18d3
commit
b9d1c396a1
37 files changed
+4547
-104
No files matched your search
@@ -0,0 +1,640 @@
|
||||
using System.IO;
|
||||
using Chronos.App.Infrastructure;
|
||||
using Chronos.Core.Archiving;
|
||||
using Chronos.Core.Diagnostics;
|
||||
using Chronos.Core.Localization;
|
||||
using Chronos.Core.Model;
|
||||
using Chronos.Core.Project;
|
||||
using Chronos.Data;
|
||||
using Chronos.Data.Archiving;
|
||||
using Chronos.Data.Jobs;
|
||||
using Chronos.Data.Projects;
|
||||
using Chronos.Data.Workspaces;
|
||||
|
||||
namespace Chronos.App.Workspace;
|
||||
|
||||
/// <summary>A workspace operation was refused for a reason the user can act on; the message is one localized sentence.</summary>
|
||||
public sealed class WorkspaceException(string message, Exception? inner = null) : InvalidOperationException(message, inner);
|
||||
|
||||
/// <summary>A project of this PC's workspace, as Edit's picker and the editor list it.</summary>
|
||||
/// <param name="HasMedia">The workspace holds the project's media (a copy that ended); without them it cannot open.</param>
|
||||
/// <param name="Saved">When its working state was last written.</param>
|
||||
public sealed record WorkspaceEntry(Guid ProjectId, Guid SequenceId, string Name, bool IsMain, BundleHome Home, string SequenceTitle, bool HasMedia,
|
||||
DateTimeOffset Saved);
|
||||
|
||||
/// <summary>A project brought into the workspace and the copy of its media that was queued.</summary>
|
||||
public sealed record WorkspaceCheckout(SequenceProject Project, Job Copy);
|
||||
|
||||
/// <summary>What Save version did: the version (null when nothing changed), its sync when Sync automatically is on, where the project stands.</summary>
|
||||
/// <param name="SyncError">Why the sync after it did not happen (the home out of reach, the project busy); the version waits here.</param>
|
||||
public sealed record WorkspaceSaveResult(ProjectVersion? Version, WorkspaceSyncResult? Synced, WorkspaceStatus Status, Exception? SyncError);
|
||||
|
||||
/// <summary>A project's history as the History flyout lists it: newest first, the versions not sent yet on top.</summary>
|
||||
/// <param name="Unsent">The ids among <paramref name="Versions"/> that wait to be sent to the home.</param>
|
||||
/// <param name="Offline">The home could not be asked: only the versions this workspace keeps are listed.</param>
|
||||
public sealed record WorkspaceHistory(IReadOnlyList<ProjectVersion> Versions, IReadOnlySet<Guid> Unsent, bool Offline);
|
||||
|
||||
/// <summary>
|
||||
/// The plan of "Remove local copy": what the project's folder holds (files and bytes) and what would not be at the home
|
||||
/// after it (versions not sent, changes not saved as a version, a conflict to settle).
|
||||
/// </summary>
|
||||
public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files, long Bytes, int Unsent, bool Modified, bool Conflict, bool Offline)
|
||||
{
|
||||
/// <summary>Everything the copy holds is at the home: it can go without discarding anything.</summary>
|
||||
public bool IsSafe => Unsent == 0 && !Modified && !Conflict;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The workspace of this PC (owner review 2, R8), composed for the desktop: its folder (Settings › Workspace, else
|
||||
/// <c>workspace</c> under the data folder: <c>%LOCALAPPDATA%\Chronos\workspace</c>, <c>.\data\workspace</c> for a portable
|
||||
/// copy), the <see cref="WorkspaceStore"/> and <see cref="WorkspaceSync"/> over it, and this PC's archive as the home of
|
||||
/// its projects (<see cref="ArchiveProjectHome"/>; a server home comes in phase 5b). Every operation runs off the UI thread
|
||||
/// and returns where the project stands. Nothing a workspace holds is lost: a version is sent before its copy goes, a copy
|
||||
/// is removed only once the home verifiably holds its head, the work a user chose to discard is kept in
|
||||
/// <c><workspace>/.trash</c>, and versions the home holds are pruned past Settings › Workspace › Kept versions only
|
||||
/// after the home was asked for each. A capture (sample data, no engine) has no workspace: Edit opens the library there.
|
||||
/// </summary>
|
||||
public sealed class WorkspaceHost
|
||||
{
|
||||
/// <summary>Where discarded work of removed local copies is kept (the store lists only folders named by a project id).</summary>
|
||||
public const string TrashFolder = ".trash";
|
||||
|
||||
private readonly AppEnvironment _environment;
|
||||
private readonly AppSettings _settings;
|
||||
private readonly Action _savePreferences;
|
||||
private readonly Func<ChronosDatabase?> _db;
|
||||
private readonly Func<ArchiveService?> _archives;
|
||||
private readonly Func<JobEngine?> _engine;
|
||||
private readonly Lock _gate = new();
|
||||
private readonly Dictionary<Guid, Guid> _copies = [];
|
||||
private OpenWorkspace? _open;
|
||||
|
||||
public WorkspaceHost(AppEnvironment environment, AppSettings settings, Action savePreferences, Func<ChronosDatabase?> db, Func<ArchiveService?> archives,
|
||||
Func<JobEngine?> engine)
|
||||
{
|
||||
_environment = environment;
|
||||
_settings = settings;
|
||||
_savePreferences = savePreferences;
|
||||
_db = db;
|
||||
_archives = archives;
|
||||
_engine = engine;
|
||||
}
|
||||
|
||||
/// <summary>The program and PC versions made here carry, as the archive's own versions do.</summary>
|
||||
public static string ClientName { get; } = "Chronos on " + Environment.MachineName;
|
||||
|
||||
/// <summary>How long an operation waits for a project another writer holds (a copy job writing its media index).</summary>
|
||||
public TimeSpan LockWait { get; init; } = TimeSpan.FromSeconds(30);
|
||||
|
||||
/// <summary>The workspace folder of a data folder: <c>workspace</c> beside the index.</summary>
|
||||
public static string DefaultRoot(AppEnvironment environment)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(environment);
|
||||
return Path.Combine(environment.DataDirectory, WorkspaceStore.DefaultFolderName);
|
||||
}
|
||||
|
||||
/// <summary>The folder in use: Settings › Workspace › Folder, else <see cref="DefaultRoot"/>.</summary>
|
||||
public string Root => _settings.WorkspaceFolder is { Length: > 0 } folder ? Path.GetFullPath(folder) : DefaultRoot(_environment);
|
||||
|
||||
/// <summary>Edit opens workspace projects (false in a capture, whose sample library has no engine to copy media).</summary>
|
||||
public bool IsEnabled => !_environment.IsCapture;
|
||||
|
||||
/// <summary>The workspace can be used now: enabled, with the index and the archive engine open.</summary>
|
||||
public bool IsAvailable => IsEnabled && _db() is not null && _archives() is not null;
|
||||
|
||||
public AppSettings Settings => _settings;
|
||||
|
||||
/// <summary>The sync over the workspace folder in use (made, with the folder and its manifest, at first use).</summary>
|
||||
/// <exception cref="IOException">The folder cannot be made or read.</exception>
|
||||
/// <exception cref="InvalidDataException">The folder holds another program's or a newer workspace manifest.</exception>
|
||||
public WorkspaceSync Sync
|
||||
{
|
||||
get
|
||||
{
|
||||
var root = Root;
|
||||
lock (_gate)
|
||||
{
|
||||
if (_open is not { } open || !string.Equals(open.Root, root, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var store = new WorkspaceStore(root);
|
||||
_open = open = new OpenWorkspace(root, new WorkspaceSync(store, ClientName) { LockWait = LockWait });
|
||||
}
|
||||
return open.Sync;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public WorkspaceStore Store => Sync.Store;
|
||||
|
||||
/// <summary>The home of a workspace project; null for a home this PC cannot reach in this phase (a server, phase 5b).</summary>
|
||||
public IProjectHome? HomeOf(BundleHome home)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(home);
|
||||
return home.IsArchive && _db() is { } db && _archives() is { } archives ? new ArchiveProjectHome(db, archives.Projects, home.SequenceId) : null;
|
||||
}
|
||||
|
||||
/// <summary>The home of a sequence of this PC's archive.</summary>
|
||||
/// <exception cref="WorkspaceException">The index or the archive engine is not open.</exception>
|
||||
public IProjectHome HomeOfSequence(Guid sequenceId) =>
|
||||
HomeOf(new BundleHome(BundleHome.ArchiveKind, sequenceId)) ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
|
||||
|
||||
/// <summary>The projects of the workspace (one whose working state cannot be read is left out, and logged).</summary>
|
||||
public Task<IReadOnlyList<WorkspaceEntry>> ListAsync(CancellationToken cancellationToken = default) =>
|
||||
Task.Run(() => (IReadOnlyList<WorkspaceEntry>)[.. Store.ListBundles().Select(b => Entry(b.Project, b.Bundle))], cancellationToken);
|
||||
|
||||
/// <summary>The workspace projects of one sequence.</summary>
|
||||
public async Task<IReadOnlyList<WorkspaceEntry>> ProjectsOfAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
|
||||
[.. (await ListAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.SequenceId == sequenceId)];
|
||||
|
||||
/// <summary>A workspace project by id; null when the workspace has none (or it cannot be read).</summary>
|
||||
public Task<WorkspaceEntry?> FindAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(() =>
|
||||
{
|
||||
if (Store.Find(projectId) is not { } project) return null;
|
||||
try
|
||||
{
|
||||
return Entry(project, project.ReadBundle());
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Warning("workspace", $"The project in {project.Folder} cannot be read", ex);
|
||||
return null;
|
||||
}
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>The project of <paramref name="sequenceId"/> opened last here, else the one saved last; null when the workspace has none.</summary>
|
||||
public async Task<WorkspaceEntry?> LastUsedAsync(Guid sequenceId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var projects = await ProjectsOfAsync(sequenceId, cancellationToken).ConfigureAwait(false);
|
||||
if (_settings.WorkspaceRecent.TryGetValue(sequenceId, out var last) && projects.FirstOrDefault(p => p.ProjectId == last) is { } recent) return recent;
|
||||
return projects.OrderByDescending(p => p.Saved).FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>Remembers <paramref name="projectId"/> as the project of <paramref name="sequenceId"/> to open next time.</summary>
|
||||
public void Remember(Guid sequenceId, Guid projectId)
|
||||
{
|
||||
if (_settings.WorkspaceRecent.TryGetValue(sequenceId, out var known) && known == projectId) return;
|
||||
_settings.WorkspaceRecent[sequenceId] = projectId;
|
||||
_savePreferences();
|
||||
}
|
||||
|
||||
/// <summary>The home's live projects of a sequence, Main first (made from the sequence's settings when it has none yet).</summary>
|
||||
public Task<IReadOnlyList<SequenceProject>> HomeProjectsAsync(Guid sequenceId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var home = HomeOfSequence(sequenceId);
|
||||
return Task.Run(() => home.ListAsync(cancellationToken), cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Brings a project of <paramref name="sequenceId"/> into the workspace and queues the copy of its media: the project
|
||||
/// <paramref name="projectId"/>, else a new one named <paramref name="newName"/> (from Main's head), else Main. A
|
||||
/// project already here keeps its working state; only its media are copied again.
|
||||
/// </summary>
|
||||
/// <exception cref="ProjectException">The home has no such project, or the name is invalid or taken.</exception>
|
||||
/// <exception cref="HomeUnavailableException">The archive is offline or busy.</exception>
|
||||
public async Task<WorkspaceCheckout> CheckoutAsync(Guid sequenceId, Guid? projectId, string? newName, string media = BundleMedia.Proxies,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var home = HomeOfSequence(sequenceId);
|
||||
var checkout = await Task.Run(async () =>
|
||||
{
|
||||
SequenceProject project;
|
||||
if (newName is not null)
|
||||
{
|
||||
project = await home.CreateAsync(newName, null, null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
else
|
||||
{
|
||||
var listed = await home.ListAsync(cancellationToken).ConfigureAwait(false);
|
||||
project = projectId is { } id
|
||||
? listed.FirstOrDefault(p => p.Id == id) ?? throw new ProjectException(ProjectError.NotFound, $"The home has no project {id}.")
|
||||
: listed.First(p => p.IsMain);
|
||||
}
|
||||
await Sync.CheckoutAsync(home, project.Id, media, cancellationToken).ConfigureAwait(false);
|
||||
Log.Info("workspace", $"Project {project.Id} ('{project.Name}') of sequence {sequenceId} checked out into {Store.Root}");
|
||||
return new WorkspaceCheckout(project, await QueueCopyCoreAsync(sequenceId, project.Id, media, cancellationToken).ConfigureAwait(false));
|
||||
}, cancellationToken);
|
||||
// Back on the caller's thread (the UI's): the settings are written there.
|
||||
Remember(sequenceId, checkout.Project.Id);
|
||||
return checkout;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues the copy of a workspace project's media again ("Update media": the home's frames changed), unless one is
|
||||
/// waiting or running already: that one is returned.
|
||||
/// </summary>
|
||||
public Task<Job> QueueCopyAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||||
{
|
||||
var bundle = Existing(projectId).ReadBundle();
|
||||
return await QueueCopyCoreAsync(bundle.Workspace!.Home.SequenceId, projectId, bundle.Workspace.Media.Kind, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Where a project stands. With <paramref name="askHome"/>, against its home's head too: a home that cannot be reached,
|
||||
/// or that no longer has the project (deleted elsewhere), reads as offline.
|
||||
/// </summary>
|
||||
public Task<WorkspaceStatus> StatusAsync(Guid projectId, bool askHome = true, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||||
{
|
||||
var project = Existing(projectId);
|
||||
var home = askHome ? HomeOf(project.ReadBundle().Workspace!.Home) : null;
|
||||
try
|
||||
{
|
||||
return await Sync.StatusAsync(projectId, home, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (home is not null && ex is ProjectException or DatabaseException or IOException)
|
||||
{
|
||||
Log.Info("workspace", $"The home of project {projectId} could not be asked: {ex.Message}");
|
||||
var local = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
|
||||
return local with { Offline = true, State = local.State is WorkspaceState.MediaRemoved or WorkspaceState.Conflict ? local.State : WorkspaceState.Offline };
|
||||
}
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// "Save version": the working state as a new local version with <paramref name="note"/> (none when nothing changed
|
||||
/// since the last), then, with Settings › Workspace › Sync automatically, the sync with the home
|
||||
/// (<see cref="SyncAsync"/>); a home out of reach leaves the version waiting here.
|
||||
/// </summary>
|
||||
/// <exception cref="InvalidOperationException">The project is read-only, has a conflict to settle, or names frames the workspace has no media of.</exception>
|
||||
public async Task<WorkspaceSaveResult> SaveVersionAsync(Guid projectId, string? note, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var version = await Task.Run(async () =>
|
||||
{
|
||||
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
|
||||
return await Sync.CommitAsync(projectId, note, null, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken).ConfigureAwait(false);
|
||||
if (version is not null) Log.Info("workspace", $"Version {version.Number} of project {projectId} saved");
|
||||
if (!_settings.WorkspaceAutoSync) return new WorkspaceSaveResult(version, null, await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false), null);
|
||||
try
|
||||
{
|
||||
var synced = await SyncAsync(projectId, cancellationToken).ConfigureAwait(false);
|
||||
return new WorkspaceSaveResult(version, synced, synced.Status, null);
|
||||
}
|
||||
catch (Exception ex) when (ex is HomeUnavailableException or LeaseUnavailableException or WorkspaceSyncException or WorkspaceException or ProjectException
|
||||
or DatabaseException)
|
||||
{
|
||||
// The version is saved here all the same: it waits for the next sync.
|
||||
Log.Info("workspace", $"Version of project {projectId} not sent yet: {ex.Message}");
|
||||
return new WorkspaceSaveResult(version, null, await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false), ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The working state as a new local version without a note and without sending it; null when nothing changed.</summary>
|
||||
public Task<ProjectVersion?> CommitAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||||
{
|
||||
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
|
||||
return await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// "Sync": the home's new versions taken (the working state and the local versions moved onto them), then the local
|
||||
/// versions sent in order, then the versions past Kept versions pruned. A real conflict stops it before anything is
|
||||
/// sent (<see cref="WorkspaceState.Conflict"/>).
|
||||
/// </summary>
|
||||
/// <exception cref="HomeUnavailableException">The home cannot be reached; nothing was lost.</exception>
|
||||
/// <exception cref="WorkspaceSyncException">The home refused a version for good.</exception>
|
||||
public Task<WorkspaceSyncResult> SyncAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||||
{
|
||||
var home = HomeOfProject(projectId);
|
||||
var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
|
||||
if (pulled.Status.State == WorkspaceState.Conflict) return pulled;
|
||||
var pushed = await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
|
||||
await PruneQuietlyAsync(projectId, home, cancellationToken).ConfigureAwait(false);
|
||||
Log.Info("workspace", $"Project {projectId} synced: {pushed.Pushed.Count} sent, {pulled.Pulled.Count + pushed.Pulled.Count} taken, {pushed.Status.State}");
|
||||
return new WorkspaceSyncResult(pushed.Status, pushed.Pushed, [.. pulled.Pulled, .. pushed.Pulled]);
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Settles the conflict a sync stopped at, then sends what waits. <see cref="ConflictChoice.SaveBoth"/> sends this
|
||||
/// workspace's versions to a sibling project named "<name> (<this PC>)" (a number added when that name is taken).
|
||||
/// </summary>
|
||||
public Task<WorkspaceSyncResult> ResolveAsync(Guid projectId, ConflictChoice choice, IReadOnlySet<string>? takeServer = null,
|
||||
CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||||
{
|
||||
var home = HomeOfProject(projectId);
|
||||
WorkspaceSyncResult resolved;
|
||||
if (choice == ConflictChoice.SaveBoth)
|
||||
{
|
||||
var name = SiblingName(Existing(projectId).ReadBundle().Workspace!.Name);
|
||||
try
|
||||
{
|
||||
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, name, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (ProjectException ex) when (ex.Reason is ProjectError.NameTaken or ProjectError.InvalidName)
|
||||
{
|
||||
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
Log.Info("workspace", $"Conflict of project {projectId} settled: {choice}{(resolved.SavedAs is { } copy ? $", saved as '{copy.Name}'" : string.Empty)}");
|
||||
if (resolved.Status.State == WorkspaceState.Conflict) return resolved;
|
||||
var pushed = await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
|
||||
return new WorkspaceSyncResult(pushed.Status, [.. resolved.Pushed, .. pushed.Pushed], [.. resolved.Pulled, .. pushed.Pulled], resolved.SavedAs);
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>"<paramref name="name"/> (<c>PC</c>)", within the 60 characters of a project name.</summary>
|
||||
public static string SiblingName(string name)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(name);
|
||||
var suffix = " (" + Environment.MachineName + ")";
|
||||
if (suffix.Length >= ProjectService.MaxNameLength) suffix = suffix[..(ProjectService.MaxNameLength / 2)] + ")";
|
||||
var room = ProjectService.MaxNameLength - suffix.Length;
|
||||
return (name.Length > room ? name[..room].TrimEnd() : name) + suffix;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Brings version <paramref name="versionId"/> back as the working state (uncommitted changes saved as a version first);
|
||||
/// returns it, its positions on the media's frames.
|
||||
/// </summary>
|
||||
public Task<ProjectSettings> RestoreAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||||
{
|
||||
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
|
||||
if (status.ReadOnly) throw new WorkspaceException(Loc.L("Errors.Workspace.ReadOnly"));
|
||||
if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
|
||||
var home = HomeOf(Existing(projectId).ReadBundle().Workspace!.Home);
|
||||
var restored = await Sync.RestoreAsync(projectId, versionId, home, cancellationToken).ConfigureAwait(false);
|
||||
Log.Info("workspace", $"Version {versionId} of project {projectId} restored as the working state");
|
||||
return restored;
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>The project's history, newest first: the versions not sent yet, then the home's (this workspace's own while the home is out of reach).</summary>
|
||||
public Task<WorkspaceHistory> HistoryAsync(Guid projectId, int limit = 50, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||||
{
|
||||
var project = Existing(projectId);
|
||||
var unsent = Sync.Unpushed(projectId);
|
||||
var home = HomeOf(project.ReadBundle().Workspace!.Home);
|
||||
IReadOnlyList<ProjectVersion> stored;
|
||||
var offline = false;
|
||||
try
|
||||
{
|
||||
stored = home is null
|
||||
? throw new HomeUnavailableException("The project's home cannot be reached from this PC.")
|
||||
: await home.HistoryAsync(projectId, null, limit, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException)
|
||||
{
|
||||
Log.Info("workspace", $"The history of project {projectId} is read from the workspace: {ex.Message}");
|
||||
offline = true;
|
||||
stored = [.. project.Versions().Where(v => v.StoredAt is not null).OrderByDescending(v => v.Number).Take(limit)];
|
||||
}
|
||||
var ids = unsent.Select(v => v.Id).ToHashSet();
|
||||
return new WorkspaceHistory([.. unsent.Reverse(), .. stored.Where(v => !ids.Contains(v.Id))], ids, offline);
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>A new project of the sequence named <paramref name="name"/> from <paramref name="fromVersionId"/> (a version the home holds), else from Main's head.</summary>
|
||||
/// <exception cref="ProjectException">The name is invalid or taken.</exception>
|
||||
public Task<SequenceProject> CreateProjectAsync(Guid sequenceId, string name, Guid? fromVersionId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var home = HomeOfSequence(sequenceId);
|
||||
return Task.Run(async () =>
|
||||
{
|
||||
var created = await home.CreateAsync(name, fromVersionId, null, cancellationToken).ConfigureAwait(false);
|
||||
Log.Info("workspace", $"Project '{created.Name}' ({created.Id}) made for sequence {sequenceId}");
|
||||
return created;
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>Renames a project at its home, then its working state here.</summary>
|
||||
/// <exception cref="ProjectException">The name is invalid or taken, or the project is gone.</exception>
|
||||
public Task<string> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||||
{
|
||||
var project = Existing(projectId);
|
||||
var renamed = await ArchiveProjects(project).RenameAsync(projectId, name, cancellationToken).ConfigureAwait(false);
|
||||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var bundle = project.ReadBundle();
|
||||
project.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Name = renamed.Name } });
|
||||
}
|
||||
Log.Info("workspace", $"Project {projectId} renamed '{renamed.Name}'");
|
||||
return renamed.Name;
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a project (never Main): the working state saved and sent first, so its home's trash
|
||||
/// (<c>.chronos/projects/.trash</c>) holds every version; then the local copy goes.
|
||||
/// </summary>
|
||||
/// <exception cref="WorkspaceException">Something could not be sent (the home out of reach, a conflict): nothing was deleted.</exception>
|
||||
/// <exception cref="ProjectException">Main, or the project is gone.</exception>
|
||||
public async Task DeleteProjectAsync(Guid projectId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var sequenceId = await Task.Run(async () =>
|
||||
{
|
||||
var project = Existing(projectId);
|
||||
var workspace = project.ReadBundle().Workspace!;
|
||||
if (workspace.IsMain) throw new ProjectException(ProjectError.MainCannotBeDeleted, "The Main project cannot be deleted.");
|
||||
var home = HomeOfProject(projectId);
|
||||
var local = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
|
||||
if (local.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
|
||||
if (!local.ReadOnly) await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
|
||||
var status = (await SendAsync(projectId, home, cancellationToken).ConfigureAwait(false)).Status;
|
||||
if (status.Ahead > 0 || status.Conflict is not null || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
|
||||
await ArchiveProjects(project).DeleteAsync(projectId, cancellationToken).ConfigureAwait(false);
|
||||
Log.Info("workspace", $"Project {projectId} ('{workspace.Name}') deleted at its home");
|
||||
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
|
||||
return workspace.Home.SequenceId;
|
||||
}, cancellationToken);
|
||||
Forget(sequenceId, projectId);
|
||||
}
|
||||
|
||||
/// <summary>The plan of "Remove local copy": the folder's files and size, and what would not be at the home after it.</summary>
|
||||
public Task<WorkspaceRemovalPlan> PlanRemovalAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||||
{
|
||||
var project = Existing(projectId);
|
||||
var name = project.ReadBundle().Workspace!.Name;
|
||||
var status = await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
var (files, bytes) = Measure(project.Folder);
|
||||
return new WorkspaceRemovalPlan(projectId, name, files, bytes, status.Ahead, status.Modified, status.Conflict is not null, status.Offline);
|
||||
}, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Removes a project's local copy. Without <paramref name="discard"/> it is refused while anything is not at the home,
|
||||
/// and the home's head and the base this copy was made from are read back and checked against their hashes first.
|
||||
/// With <paramref name="discard"/> (the user's explicit word) the versions not sent and the working state are moved to
|
||||
/// <c><workspace>/.trash</c> rather than erased. The media (copies the home can make again) are deleted.
|
||||
/// </summary>
|
||||
/// <exception cref="WorkspaceException">Something is not at the home yet, or the home's copy does not check out.</exception>
|
||||
public async Task RemoveLocalCopyAsync(Guid projectId, bool discard, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var sequenceId = await Task.Run(async () =>
|
||||
{
|
||||
var project = Existing(projectId);
|
||||
var workspace = project.ReadBundle().Workspace!;
|
||||
if (!discard)
|
||||
{
|
||||
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
|
||||
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly) || status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
|
||||
await VerifyHomeAsync(projectId, workspace, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
|
||||
Log.Info("workspace", $"Local copy of project {projectId} ('{workspace.Name}') removed{(discard ? ", its unsent work kept in " + TrashFolder : string.Empty)}");
|
||||
return workspace.Home.SequenceId;
|
||||
}, cancellationToken);
|
||||
Forget(sequenceId, projectId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drops the oldest versions this workspace took from the home, keeping Settings › Workspace › Kept versions of them
|
||||
/// (the base among them), the versions not sent and the set-aside ones; a version goes only once the home was asked
|
||||
/// and holds it with the same content.
|
||||
/// </summary>
|
||||
public async Task<int> PruneAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(home);
|
||||
var project = Existing(projectId);
|
||||
var keep = Math.Max(1, _settings.WorkspaceKeptVersions);
|
||||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
var basis = project.ReadBundle().Workspace!.Base;
|
||||
var stored = project.Versions().Where(v => v.StoredAt is not null).OrderByDescending(v => v.Number).ToList();
|
||||
var kept = stored.Where(v => v.Id != basis?.VersionId).Take(keep - (basis is null ? 0 : 1)).Select(v => v.Id).ToHashSet();
|
||||
var removed = 0;
|
||||
foreach (var version in stored.Where(v => v.Id != basis?.VersionId && !kept.Contains(v.Id)))
|
||||
{
|
||||
if (await home.GetVersionAsync(projectId, version.Id, cancellationToken).ConfigureAwait(false) is not { } atHome
|
||||
|| !string.Equals(atHome.ContentHash, version.ContentHash, StringComparison.OrdinalIgnoreCase)
|
||||
|| !ProjectContent.Verifies(atHome.SettingsJson, atHome.ContentHash))
|
||||
continue;
|
||||
File.Delete(project.VersionPath(version));
|
||||
removed++;
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task PruneQuietlyAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
var removed = await PruneAsync(projectId, home, cancellationToken).ConfigureAwait(false);
|
||||
if (removed > 0) Log.Info("workspace", $"{removed} older version(s) of project {projectId} dropped from the workspace (kept at the home)");
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or ProjectException)
|
||||
{
|
||||
Log.Warning("workspace", $"Older versions of project {projectId} could not be pruned", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The local versions sent (after the home's new ones were taken), as one sync without the pruning.</summary>
|
||||
private async Task<WorkspaceSyncResult> SendAsync(Guid projectId, IProjectHome home, CancellationToken cancellationToken)
|
||||
{
|
||||
var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
|
||||
return pulled.Status.State == WorkspaceState.Conflict ? pulled : await Sync.PushAsync(projectId, home, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>The home holds this copy's work: its head and the base this copy was last in step with read back, each matching its hash.</summary>
|
||||
private async Task VerifyHomeAsync(Guid projectId, BundleWorkspace workspace, CancellationToken cancellationToken)
|
||||
{
|
||||
var home = HomeOf(workspace.Home) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"));
|
||||
ProjectVersion head;
|
||||
ProjectVersion? basis;
|
||||
try
|
||||
{
|
||||
head = await home.HeadAsync(projectId, cancellationToken).ConfigureAwait(false);
|
||||
basis = workspace.Base is { } b ? await home.GetVersionAsync(projectId, b.VersionId, cancellationToken).ConfigureAwait(false) : head;
|
||||
}
|
||||
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException)
|
||||
{
|
||||
throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"), ex);
|
||||
}
|
||||
if (!ProjectContent.Verifies(head.SettingsJson, head.ContentHash) || basis is null || !ProjectContent.Verifies(basis.SettingsJson, basis.ContentHash)
|
||||
|| (workspace.Base is { } known && !string.Equals(known.ContentHash, basis.ContentHash, StringComparison.OrdinalIgnoreCase)))
|
||||
throw new WorkspaceException(Loc.L("Errors.Workspace.HomeCheck"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The project's folder taken out of the workspace under its lease: the working state, the versions, the sync state and
|
||||
/// the exports moved to <c>.trash/<id>-<time></c> (kept: nothing a user made is erased), the media deleted; the
|
||||
/// emptied folder goes once the lease is released.
|
||||
/// </summary>
|
||||
private async Task RemoveFolderAsync(WorkspaceProject project, CancellationToken cancellationToken)
|
||||
{
|
||||
// A copy of its media still under way would write them again behind the removal.
|
||||
Guid copy;
|
||||
lock (_gate) _copies.Remove(project.ProjectId, out copy);
|
||||
if (copy != Guid.Empty && _engine() is { } engine && _db() is { } db && await db.Jobs.GetAsync(copy, cancellationToken).ConfigureAwait(false) is
|
||||
{ State: JobState.Queued or JobState.Running or JobState.Paused })
|
||||
await engine.CancelAsync(copy, cancellationToken).ConfigureAwait(false);
|
||||
var aside = Path.Combine(Store.Root, TrashFolder, project.ProjectId.ToString("N") + "-" + DateTime.UtcNow.Ticks.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
|
||||
{
|
||||
Directory.CreateDirectory(aside);
|
||||
// The working state first: without it the folder is no project any more, whatever happens after.
|
||||
File.Move(project.BundlePath, Path.Combine(aside, WorkspaceProject.BundleFile));
|
||||
if (File.Exists(project.SyncPath)) File.Move(project.SyncPath, Path.Combine(aside, WorkspaceProject.SyncFile));
|
||||
if (Directory.Exists(project.VersionsDirectory)) Directory.Move(project.VersionsDirectory, Path.Combine(aside, WorkspaceProject.VersionsFolder));
|
||||
if (Directory.Exists(project.ExportsDirectory) && Directory.EnumerateFileSystemEntries(project.ExportsDirectory).Any())
|
||||
Directory.Move(project.ExportsDirectory, Path.Combine(aside, WorkspaceProject.ExportsFolder));
|
||||
if (Directory.Exists(project.MediaDirectory)) Directory.Delete(project.MediaDirectory, recursive: true);
|
||||
}
|
||||
try
|
||||
{
|
||||
Directory.Delete(project.Folder, recursive: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
Log.Info("workspace", $"The emptied folder {project.Folder} stays: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A version can be saved: no conflict waits, the settings are this Chronos's, the media are here.</summary>
|
||||
/// <exception cref="WorkspaceException">Why not.</exception>
|
||||
private static void EnsureWritable(WorkspaceStatus status)
|
||||
{
|
||||
if (status.ReadOnly) throw new WorkspaceException(Loc.L("Errors.Workspace.ReadOnly"));
|
||||
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
|
||||
if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
|
||||
}
|
||||
|
||||
private void Forget(Guid sequenceId, Guid projectId)
|
||||
{
|
||||
if (!_settings.WorkspaceRecent.TryGetValue(sequenceId, out var known) || known != projectId) return;
|
||||
_settings.WorkspaceRecent.Remove(sequenceId);
|
||||
_savePreferences();
|
||||
}
|
||||
|
||||
private async Task<Job> QueueCopyCoreAsync(Guid sequenceId, Guid projectId, string media, CancellationToken cancellationToken)
|
||||
{
|
||||
var engine = _engine() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
|
||||
var db = _db() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
|
||||
Guid known;
|
||||
lock (_gate) _copies.TryGetValue(projectId, out known);
|
||||
if (known != Guid.Empty && await db.Jobs.GetAsync(known, cancellationToken).ConfigureAwait(false) is { State: JobState.Queued or JobState.Running } running) return running;
|
||||
var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
|
||||
?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {sequenceId} is not in the index.");
|
||||
var job = await engine.EnqueueAsync(WorkspaceJobs.Copy(sequence, Store.Root, projectId, media), cancellationToken: cancellationToken).ConfigureAwait(false);
|
||||
lock (_gate) _copies[projectId] = job.Id;
|
||||
return job;
|
||||
}
|
||||
|
||||
private IProjectHome HomeOfProject(Guid projectId) =>
|
||||
HomeOf(Existing(projectId).ReadBundle().Workspace!.Home) ?? throw new HomeUnavailableException("The project's home cannot be reached from this PC.");
|
||||
|
||||
private ProjectService ArchiveProjects(WorkspaceProject project) =>
|
||||
project.ReadBundle().Workspace!.Home.IsArchive && _archives() is { } archives ? archives.Projects : throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"));
|
||||
|
||||
private WorkspaceProject Existing(Guid projectId) => Store.Find(projectId) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.NotCheckedOut"));
|
||||
|
||||
private static WorkspaceEntry Entry(WorkspaceProject project, ProjectBundle bundle)
|
||||
{
|
||||
var workspace = bundle.Workspace!;
|
||||
return new WorkspaceEntry(project.ProjectId, workspace.Home.SequenceId, workspace.Name, workspace.IsMain, workspace.Home,
|
||||
bundle.Sequence.Title is { Length: > 0 } title ? title : bundle.Sequence.Folder, File.Exists(project.MediaIndexPath), bundle.Saved);
|
||||
}
|
||||
|
||||
/// <summary>Files and bytes under <paramref name="folder"/>, the lease left out.</summary>
|
||||
private static (int Files, long Bytes) Measure(string folder)
|
||||
{
|
||||
var (files, bytes) = (0, 0L);
|
||||
if (!Directory.Exists(folder)) return (files, bytes);
|
||||
foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", SearchOption.AllDirectories))
|
||||
{
|
||||
if (file.Name.EndsWith(".lease", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
files++;
|
||||
bytes += file.Length;
|
||||
}
|
||||
return (files, bytes);
|
||||
}
|
||||
|
||||
private sealed record OpenWorkspace(string Root, WorkspaceSync Sync);
|
||||
}
|
||||
Reference in new issue
Block a user