using System.IO;
using Chronos.App.Infrastructure;
using Chronos.Core.Archiving;
using Chronos.Core.Diagnostics;
using Chronos.Core.IO;
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;
/// A workspace operation was refused for a reason the user can act on; the message is one localized sentence.
public sealed class WorkspaceException(string message, Exception? inner = null) : InvalidOperationException(message, inner);
/// A project of this PC's workspace, as Edit's picker and the editor list it.
/// The workspace holds the project's media (a copy that ended); without them it cannot open.
/// When its working state was last written.
public sealed record WorkspaceEntry(Guid ProjectId, Guid SequenceId, string Name, bool IsMain, BundleHome Home, string SequenceTitle, bool HasMedia,
DateTimeOffset Saved);
/// A project brought into the workspace and the copy of its media that was queued.
public sealed record WorkspaceCheckout(SequenceProject Project, Job Copy);
/// What Save version did: the version (null when nothing changed), its sync when Sync automatically is on, where the project stands.
/// Why the sync after it did not happen (the home out of reach, the project busy); the version waits here.
public sealed record WorkspaceSaveResult(ProjectVersion? Version, WorkspaceSyncResult? Synced, WorkspaceStatus Status, Exception? SyncError);
/// A project's history as the History flyout lists it: newest first, the versions not sent yet on top.
/// The ids among that wait to be sent to the home.
/// The home could not be asked: only the versions this workspace keeps are listed.
public sealed record WorkspaceHistory(IReadOnlyList Versions, IReadOnlySet Unsent, bool Offline);
///
/// 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).
///
///
/// The home answered it no longer has the project or its sequence: nothing can be sent or checked there, so the copy can
/// only go with its work kept aside (Discard).
///
public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files, long Bytes, int Unsent, bool Modified, bool Conflict, bool Offline, bool Gone = false)
{
/// Everything the copy holds is at the home: it can go without discarding anything.
public bool IsSafe => Unsent == 0 && !Modified && !Conflict;
}
///
/// The workspace of this PC (owner review 2, R8), composed for the desktop: its folder (Settings › Workspace, else
/// workspace under the data folder: %LOCALAPPDATA%\Chronos\workspace, .\data\workspace for a portable
/// copy), the and over it, and this PC's archive as the home of
/// its projects (; 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
/// <workspace>/.trash, 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.
///
public sealed class WorkspaceHost
{
/// Where discarded work of removed local copies is kept (the store lists only folders named by a project id).
public const string TrashFolder = ".trash";
private readonly AppEnvironment _environment;
private readonly AppSettings _settings;
private readonly Action _savePreferences;
private readonly Func _db;
private readonly Func _archives;
private readonly Func _engine;
private readonly Lock _gate = new();
private readonly Dictionary _copies = [];
private OpenWorkspace? _open;
public WorkspaceHost(AppEnvironment environment, AppSettings settings, Action savePreferences, Func db, Func archives,
Func engine)
{
_environment = environment;
_settings = settings;
_savePreferences = savePreferences;
_db = db;
_archives = archives;
_engine = engine;
}
///
/// The PC versions made here carry ("STUDIO-PC"): data, shown as it is by History (no words of the UI in it, so every
/// language reads it alike).
///
public static string ClientName { get; } = Environment.MachineName;
/// How long an operation waits for a project another writer holds (a copy job writing its media index).
public TimeSpan LockWait { get; init; } = TimeSpan.FromSeconds(30);
/// The workspace folder of a data folder: workspace beside the index.
public static string DefaultRoot(AppEnvironment environment)
{
ArgumentNullException.ThrowIfNull(environment);
return Path.Combine(environment.DataDirectory, WorkspaceStore.DefaultFolderName);
}
/// The folder in use: Settings › Workspace › Folder, else .
public string Root => _settings.WorkspaceFolder is { Length: > 0 } folder ? Path.GetFullPath(folder) : DefaultRoot(_environment);
/// Edit opens workspace projects (false in a capture, whose sample library has no engine to copy media).
public bool IsEnabled => !_environment.IsCapture;
/// The workspace can be used now: enabled, with the index and the archive engine open.
public bool IsAvailable => IsEnabled && _db() is not null && _archives() is not null;
public AppSettings Settings => _settings;
/// The sync over the workspace folder in use (made, with the folder and its manifest, at first use).
/// The folder cannot be made or read.
/// The folder holds another program's or a newer workspace manifest.
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;
/// The home of a workspace project; null for a home this PC cannot reach in this phase (a server, phase 5b).
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;
}
/// The home of a sequence of this PC's archive.
/// The index or the archive engine is not open.
public IProjectHome HomeOfSequence(Guid sequenceId) =>
HomeOf(new BundleHome(BundleHome.ArchiveKind, sequenceId)) ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
///
/// The projects of the workspace (one whose working state cannot be read is left out, and logged). A workspace folder
/// not made yet that lies inside a library is not made by listing it: it lists nothing.
///
public Task> ListAsync(CancellationToken cancellationToken = default) => Task.Run(async () =>
{
if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return [];
return (IReadOnlyList)[.. Store.ListBundles().Select(b => Entry(b.Project, b.Bundle))];
}, cancellationToken);
/// The workspace projects of one sequence.
public async Task> ProjectsOfAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
[.. (await ListAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.SequenceId == sequenceId)];
/// A workspace project by id; null when the workspace has none (or it cannot be read).
public Task FindAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return null;
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);
/// The project of opened last here, else the one saved last; null when the workspace has none.
public async Task 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();
}
/// Remembers as the project of to open next time.
public void Remember(Guid sequenceId, Guid projectId)
{
if (_settings.WorkspaceRecent.TryGetValue(sequenceId, out var known) && known == projectId) return;
_settings.WorkspaceRecent[sequenceId] = projectId;
_savePreferences();
}
/// The home's live projects of a sequence, Main first (made from the sequence's settings when it has none yet).
public Task> HomeProjectsAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
return Task.Run(() => home.ListAsync(cancellationToken), cancellationToken);
}
///
/// Brings a project of into the workspace and queues the copy of its media: the project
/// , else a new one named (from Main's head), else Main. A
/// project already here keeps its working state; only its media are copied again.
///
/// The home has no such project, or the name is invalid or taken.
/// The archive is offline or busy.
/// The workspace folder lies inside a library: nothing was written, here or at the home.
public async Task CheckoutAsync(Guid sequenceId, Guid? projectId, string? newName, string media = BundleMedia.Proxies,
CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
var checkout = await Task.Run(async () =>
{
// Refused before anything is written: the copy job would refuse such a folder after the checkout filled it.
if (await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) throw new WorkspaceException(Loc.L("Errors.Workspace.InsideLibraryEdit", Root));
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;
}
///
/// 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.
///
public Task 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);
///
/// Where a project stands. With , against its home's head too: a home that cannot be reached
/// reads as offline; one that answers it no longer has the project or its sequence (the sequence left the index) reads
/// as , whose local copy can then only be removed (nothing is removed by itself).
///
public Task 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)
{
var gone = ex is ProjectException { Reason: ProjectError.SequenceNotFound or ProjectError.NotFound };
Log.Info("workspace", gone ? $"The home no longer has project {projectId}: {ex.Message}" : $"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 && !gone ? local.State
: gone ? WorkspaceState.Gone
: WorkspaceState.Offline,
};
}
}, cancellationToken);
///
/// "Save version": the working state as a new local version with (none when nothing changed
/// since the last), then, with Settings › Workspace › Sync automatically, the sync with the home
/// (); a home out of reach leaves the version waiting here.
///
/// The project is read-only, has a conflict to settle, or names frames the workspace has no media of.
public async Task 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);
}
}
/// The working state as a new local version without a note and without sending it; null when nothing changed.
public Task 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);
///
/// "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 ().
///
/// The home cannot be reached; nothing was lost.
/// The home refused a version for good.
public Task 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);
///
/// Settles the conflict a sync stopped at, as listed it to the user (else as recorded), then
/// sends what waits. When what differs now is not what was shown, nothing is settled: the conflict found now comes back
/// () to be asked again. sends this
/// workspace's versions to a sibling project named "<name> (<this PC>)" (a number added when that name is taken).
///
public Task ResolveAsync(Guid projectId, ConflictChoice choice, IReadOnlySet? takeServer = null,
WorkspaceConflict? shown = 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, shown, cancellationToken).ConfigureAwait(false);
}
catch (ProjectException ex) when (ex.Reason is ProjectError.NameTaken or ProjectError.InvalidName)
{
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false);
}
}
else
{
resolved = await Sync.ResolveAsync(projectId, home, choice, takeServer, null, shown, cancellationToken).ConfigureAwait(false);
}
if (resolved.Status.State == WorkspaceState.Conflict)
{
Log.Info("workspace", $"Conflict of project {projectId} not settled ({choice}): what differs changed since it was shown");
return resolved;
}
Log.Info("workspace", $"Conflict of project {projectId} settled: {choice}{(resolved.SavedAs is { } copy ? $", saved as '{copy.Name}'" : string.Empty)}");
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)
{
Kept = resolved.Kept,
};
}, cancellationToken);
/// " (PC)", within the 60 characters of a project name.
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;
}
///
/// Brings version back as the working state (uncommitted changes saved as a version first);
/// returns it, its positions on the media's frames.
///
public Task 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);
/// 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).
public Task 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 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);
/// A new project of the sequence named from (a version the home holds), else from Main's head.
/// The name is invalid or taken.
public Task 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);
}
/// Renames a project at its home, then its working state here.
/// The name is invalid or taken, or the project is gone.
public Task 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);
///
/// Deletes a project (never Main): the working state saved and sent first, so its home's trash
/// (.chronos/projects/.trash) holds every version; then the local copy goes.
///
///
/// False when the home deleted the project but its local copy could not be removed (a file in use): the copy stays,
/// and Remove local copy takes it later.
///
/// Something could not be sent (the home out of reach, a conflict): nothing was deleted.
/// Main, or the project is gone.
public async Task DeleteProjectAsync(Guid projectId, CancellationToken cancellationToken = default)
{
var (sequenceId, removed) = 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.Conflict"));
if (!local.ReadOnly) await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
var status = (await SendAsync(projectId, home, cancellationToken).ConfigureAwait(false)).Status;
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
if (status.Ahead > 0 || (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");
try
{
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
return (workspace.Home.SequenceId, true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or LeaseUnavailableException)
{
// The home's delete stands (its trash holds every version); the copy, all of it sent, waits for Remove local copy.
Log.Warning("workspace", $"Project {projectId} was deleted at its home, but its local copy stays", ex);
return (workspace.Home.SequenceId, false);
}
}, cancellationToken);
Forget(sequenceId, projectId);
return removed;
}
///
/// "Send first" for a project not open in the editor (the picker's Remove local copy): its working state saved as a
/// version when it can be, then the sync.
///
/// A conflict waits (open the project and Sync to settle it), or something is still not at the home.
public async Task SendAllAsync(Guid projectId, CancellationToken cancellationToken = default)
{
var local = await Task.Run(() => Sync.StatusAsync(projectId, null, cancellationToken), cancellationToken).ConfigureAwait(false);
if (local is { Conflict: null, ReadOnly: false, MediaRemoved: false }) await CommitAsync(projectId, cancellationToken).ConfigureAwait(false);
var status = (await SyncAsync(projectId, cancellationToken).ConfigureAwait(false)).Status;
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
}
/// The plan of "Remove local copy": the folder's files and size, and what would not be at the home after it.
public Task 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,
status.State == WorkspaceState.Gone);
}, cancellationToken);
///
/// Removes a project's local copy. Without 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 (the user's explicit word) the versions not sent and the working state are moved to
/// <workspace>/.trash rather than erased. The media (copies the home can make again) are deleted.
///
/// Something is not at the home yet, or the home's copy does not check out.
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);
}
///
/// 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.
///
public async Task 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)))
{
// Read back from where the home keeps it, not from an index of it.
if (!await home.HoldsAsync(projectId, version, cancellationToken).ConfigureAwait(false)) 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);
}
}
/// The local versions sent (after the home's new ones were taken), as one sync without the pruning.
private async Task 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);
}
/// 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.
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;
bool held;
try
{
head = await home.HeadAsync(projectId, cancellationToken).ConfigureAwait(false);
basis = workspace.Base is { } b ? await home.GetVersionAsync(projectId, b.VersionId, cancellationToken).ConfigureAwait(false) : head;
// Read back from where the home keeps them, not from an index of them.
held = basis is not null && await home.HoldsAsync(projectId, head, cancellationToken).ConfigureAwait(false)
&& (basis.Id == head.Id || await home.HoldsAsync(projectId, basis, cancellationToken).ConfigureAwait(false));
}
catch (ProjectException ex) when (ex.Reason is ProjectError.NotFound or ProjectError.SequenceNotFound)
{
// Deleted at the home (its trash keeps every version sent): this copy goes only when its user discards it.
throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"), ex);
}
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException)
{
throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"), ex);
}
if (!held || !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"));
}
///
/// 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 .trash/<id>-<time> (kept: nothing a user made is erased), the media deleted; the
/// emptied folder goes once the lease is released.
///
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}");
}
}
/// A version can be saved: no conflict waits, the settings are this Chronos's, the media are here.
/// Why not.
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"));
}
///
/// The workspace folder lies inside a library this index knows (a portable copy's data folder under a library
/// at a drive's root): editing happens outside every library, so nothing is checked out or copied there.
///
private async Task InsideALibraryAsync(CancellationToken cancellationToken)
{
if (_db() is not { } db) return false;
var root = Plain(Path.GetFullPath(Root));
foreach (var archive in await db.Archives.ListAsync(cancellationToken).ConfigureAwait(false))
{
if (DataLocation.IsUnder(root, Plain(Path.GetFullPath(archive.RootPath)))) return true;
}
return false;
// Without the long-path prefix, which only one of the two may carry.
static string Plain(string path) =>
path.StartsWith(@"\\?\UNC\", StringComparison.Ordinal) ? @"\\" + path[8..]
: path.StartsWith(@"\\?\", StringComparison.Ordinal) ? path[4..]
: path;
}
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 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);
}
/// Files and bytes under , the lease left out.
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);
}