using System.IO;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Workspaces;
namespace Chronos.App.Workspace;
/// A project of the workspace as the plan of a move lists it: its size, and work not at its home yet (a warning, never a refusal).
/// Versions or renders wait to be sent to its home.
/// Changes not saved as a version.
public sealed record WorkspaceMoveProject(Guid ProjectId, string Name, int Files, long Bytes, bool Unsent, bool Modified);
///
/// The plan of Settings › Workspace › Move… (phase 5c): the workspace folder moved with its projects to
/// : the projects and their bytes, the free bytes at the target, whether both lie on one volume (folders
/// renamed) or not (files copied and hash-verified), why it is refused (null when it can go), and a fingerprint of what
/// the plan read, which the move job checks again.
///
/// The free bytes of the target's drive; null when they cannot be measured.
///
/// Why the move cannot go, one localized sentence: the target is the folder itself or inside it
/// (Errors.Workspace.MoveSameFolder), already holds a workspace or a project of the same id
/// (Errors.Workspace.MoveTargetNotEmpty), lies inside a library (Errors.Workspace.InsideLibraryFolder), lacks
/// the room (Errors.Workspace.MoveNoRoom), or a workspace job is pending or running (Errors.Workspace.JobsRunning);
/// null when it can go.
///
public sealed record WorkspaceMovePlan(string From, string To, IReadOnlyList Projects, int Files, long Bytes, long? Free, bool SameVolume,
string? Refusal, string Fingerprint)
{
/// Nothing refuses the move.
public bool CanMove => Refusal is null;
/// Projects with work not at their home: the move keeps it, the plan says so.
public int Warnings => Projects.Count(p => p.Unsent || p.Modified);
}
///
/// Moving the workspace folder with its projects (phase 5c, P6): the plan, the that
/// carries it out, and the workspace that follows the folder once every file is verified there. While a move is queued,
/// running or paused, and while the folder in use holds a move's journal (a move under way, or one stopped before it
/// ended), the workspace is refused for checkouts, copies, saves, syncs, opens and another folder
/// ().
///
public sealed partial class WorkspaceHost
{
/// The kinds of job that write into the workspace folder: none may wait or run when a move starts.
private static readonly JobKind[] WorkspaceJobKinds = [JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend, JobKind.WorkspaceMove];
/// The thread the host was made on (the UI's): the settings are written there when a move ends.
private readonly SynchronizationContext? _moveContext = SynchronizationContext.Current;
/// The move job queued from here (or found waiting at start), until it ends; empty when there is none.
private Guid _moveJob;
/// The engine whose job changes the host follows, to see a move end.
private JobEngine? _followed;
///
/// A move of the workspace folder is queued, running or paused, or the folder in use holds the journal of one that has
/// not ended: syncs, saves and opens wait for it.
///
public bool IsMoving
{
get
{
lock (_gate)
{
if (_moveJob != Guid.Empty) return true;
}
return WorkspaceMover.HasJournal(Root);
}
}
///
/// A move of the workspace folder followed here ended, however it ended (any thread): the folder in use may have changed,
/// and the workspace is no longer held for it (Settings › Workspace shows the folder and what it takes again).
///
public event Action? MoveEnded;
/// A move job followed here waits, runs or is paused (no disk is read).
public bool IsMoveQueued
{
get
{
lock (_gate) return _moveJob != Guid.Empty;
}
}
///
/// A move stopped before it ended: the folder in use holds its journal and no move job waits, runs or is paused; or a
/// move switched to the folder in use and left part of the folder it came from (its journal there names what is left
/// to clear). Null when there is none (a move under way is no move to take up). A move job waiting at start is followed
/// from now on, so the workspace waits for it ().
///
public Task UnfinishedMoveAsync(CancellationToken cancellationToken = default) => Task.Run(async () =>
{
if (_db() is not { } db) return null;
foreach (var state in new[] { JobState.Running, JobState.Queued, JobState.Paused })
{
if ((await db.Jobs.ListAsync(state, JobKind.WorkspaceMove, 1, cancellationToken: cancellationToken).ConfigureAwait(false)).Items is [var pending, ..])
{
Follow(pending.Id);
return null;
}
}
if (WorkspaceMover.HasJournal(Root)) return WorkspaceMover.ReadJournal(Root);
// The folder in use is a move's target: the folder it left may hold what could not be cleared after the switch.
var root = Path.TrimEndingDirectorySeparator(Path.GetFullPath(Root));
foreach (var state in new[] { JobState.Done, JobState.Failed, JobState.Cancelled })
{
foreach (var job in (await db.Jobs.ListAsync(state, JobKind.WorkspaceMove, 5, cancellationToken: cancellationToken).ConfigureAwait(false)).Items)
{
if (WorkspaceJobs.MoveParameters(job) is not { From.Length: > 0 } moved || !WorkspaceMover.HasJournal(moved.From)) continue;
if (WorkspaceMover.ReadJournal(moved.From) is { Stage: WorkspaceMoveStage.Switched } left
&& string.Equals(Path.TrimEndingDirectorySeparator(Path.GetFullPath(left.To)), root, StringComparison.OrdinalIgnoreCase))
return left;
}
}
return null;
}, cancellationToken);
///
/// The plan of moving the workspace folder to (); nothing is
/// written. Each project is read here, never at its home: a move keeps whatever is not sent yet, the plan only says so.
///
/// The workspace folder cannot be read.
public Task PlanMoveAsync(string to, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(to);
var root = Root;
var free = _archives()?.FreeSpace;
return Task.Run(async () =>
{
var target = Path.GetFullPath(to);
var survey = new WorkspaceMover(root, target) { FreeSpace = free }.Survey();
var projects = new List();
foreach (var folder in survey.Projects.Where(p => p.IsProject))
{
cancellationToken.ThrowIfCancellationRequested();
projects.Add(await MoveProjectAsync(folder, cancellationToken).ConfigureAwait(false));
}
var refusal = survey.RefusalText;
if (refusal is null && await InsideALibraryAsync(survey.To, cancellationToken).ConfigureAwait(false))
refusal = Loc.L("Errors.Workspace.InsideLibraryFolder", survey.To);
if (refusal is null && (IsMoving || WorkspaceMover.HasJournal(survey.From))) refusal = Loc.L("Errors.Workspace.Moving");
if (refusal is null && _db() is { } db && await db.Jobs.HasPendingAsync(WorkspaceJobKinds, cancellationToken: cancellationToken).ConfigureAwait(false))
refusal = Loc.L("Errors.Workspace.JobsRunning");
return new WorkspaceMovePlan(survey.From, survey.To, projects, survey.Files, survey.Bytes, survey.Free, survey.SameVolume, refusal, survey.Fingerprint);
}, cancellationToken);
}
///
/// Queues the of a plan the user confirmed: from now until it ends the workspace is
/// refused for writes and opens ().
///
/// The plan refuses the move, or a move is under way already.
public async Task QueueMoveAsync(WorkspaceMovePlan plan, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(plan);
if (plan.Refusal is { } refusal) throw new WorkspaceException(refusal);
EnsureNotMoving();
var engine = _engine() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var job = await engine.EnqueueAsync(WorkspaceJobs.Move(plan.From, plan.To, plan.Fingerprint), cancellationToken: cancellationToken).ConfigureAwait(false);
Follow(job.Id);
Log.Info("workspace", $"Move {job.Id} of the workspace {plan.From} to {plan.To} queued ({plan.Projects.Count} project(s), {plan.Bytes} bytes)");
return job;
}
///
/// Queues again the move a journal records (): it goes on from the journal, nothing
/// verified is copied twice.
///
/// The index or the engine is not open.
public async Task ResumeMoveAsync(WorkspaceMoveJournal journal, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(journal);
var engine = _engine() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var job = await engine.EnqueueAsync(WorkspaceJobs.Move(journal.From, journal.To, journal.Fingerprint), cancellationToken: cancellationToken).ConfigureAwait(false);
Follow(job.Id);
Log.Info("workspace", $"Move {job.Id} of the workspace {journal.From} to {journal.To} queued again from its journal");
return job;
}
///
/// Told by the move job once every file of the workspace is verified at
/// (WorkspaceJobOptions.Moved, any thread): on the thread the host was made on, Settings › Workspace names the new
/// folder (none when it is the default) and the workspace opens there. A workspace that is no longer in
/// (another folder chosen meanwhile) keeps its folder.
///
public Task MovedAsync(string from, string to)
{
ArgumentException.ThrowIfNullOrWhiteSpace(from);
ArgumentException.ThrowIfNullOrWhiteSpace(to);
if (_moveContext is not { } context) return Task.Run(() => FollowFolder(from, to));
if (SynchronizationContext.Current == context)
{
FollowFolder(from, to);
return Task.CompletedTask;
}
var done = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
context.Post(_ =>
{
try
{
FollowFolder(from, to);
done.TrySetResult();
}
catch (Exception ex)
{
done.TrySetException(ex);
}
}, null);
return done.Task;
}
/// The settings name the folder a move verified everything in.
private void FollowFolder(string from, string to)
{
var target = Full(to);
if (!string.Equals(Full(Root), Full(from), StringComparison.OrdinalIgnoreCase) && !string.Equals(Full(Root), target, StringComparison.OrdinalIgnoreCase))
{
Log.Warning("workspace", $"The workspace moved from {from} to {to}, but {Root} is in use now: it stays so");
return;
}
_settings.WorkspaceFolder = string.Equals(target, Full(DefaultRoot(_environment)), StringComparison.OrdinalIgnoreCase) ? null : target;
_savePreferences();
lock (_gate) _open = null;
Log.Info("workspace", $"The workspace folder is now {target}, moved from {from}");
static string Full(string folder) => Path.TrimEndingDirectorySeparator(Path.GetFullPath(folder));
}
/// Refuses an operation that writes into the workspace while its folder is being moved.
/// A move is queued or running (Errors.Workspace.Moving).
private void EnsureNotMoving()
{
if (IsMoving) throw new WorkspaceException(Loc.L("Errors.Workspace.Moving"));
}
/// Holds the workspace while move job waits, runs or is paused; lets go once it ends, however it ends.
private void Follow(Guid jobId)
{
var engine = _engine();
lock (_gate)
{
_moveJob = jobId;
if (engine is null || ReferenceEquals(engine, _followed)) return;
if (_followed is { } before) before.JobChanged -= OnMoveJobChanged;
_followed = engine;
engine.JobChanged += OnMoveJobChanged;
}
}
private void OnMoveJobChanged(Job job)
{
if (job.Kind != JobKind.WorkspaceMove || job.State is not (JobState.Done or JobState.Failed or JobState.Cancelled)) return;
lock (_gate)
{
if (_moveJob != job.Id) return;
_moveJob = Guid.Empty;
}
MoveEnded?.Invoke();
}
/// A project as the move's plan lists it, read from the workspace alone (its versions not sent, its ledger, its changes).
private async Task MoveProjectAsync(WorkspaceMoveFolder folder, CancellationToken cancellationToken)
{
var project = Store.Project(folder.ProjectId);
var entry = await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false);
// What a copy this Chronos cannot read holds is not known: it moves as it is, counted as work not at its home.
if (!entry.IsReadable) return new WorkspaceMoveProject(folder.ProjectId, entry.KnownName ?? entry.Name, folder.Files, folder.Bytes, true, false);
try
{
var status = await Sync.StatusAsync(folder.ProjectId, null, cancellationToken).ConfigureAwait(false);
var renders = WorkspaceCleaner.UnsentRenders(project);
return new WorkspaceMoveProject(folder.ProjectId, entry.Name, folder.Files, folder.Bytes, status.Ahead + status.Damaged + renders > 0 || status.Conflict is not null,
status.Modified && !status.ReadOnly);
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Info("workspace", $"Where project {folder.ProjectId} stands could not be read for the move's plan: {ex.Message}");
return new WorkspaceMoveProject(folder.ProjectId, entry.Name, folder.Files, folder.Bytes, true, false);
}
}
}