using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Sections;
using Chronos.App.Shell;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Project;
using Chronos.Data.Processing;
namespace Chronos.App.Editor;
///
/// .chronos project files (BRIEF ยง18): the editor saves one for the open sequence of this PC's archive, and
/// opening one (a double-click, which Windows passes to Chronos.exe) opens its sequence in the editor and gives it the
/// file's settings as one undoable step.
///
public sealed class ProjectFiles(ShellViewModel shell)
{
/// Asks for a folder and saves the session's sequence and current settings there; never replaces a file.
public async Task SaveAsync(EditorSession session)
{
if (session.IsRemote) return;
if (shell.Services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
if (shell.Services.Dialogs.PickFolder(Loc.L("Editor.ProjectFile.Title")) is not { } folder) return;
var bundle = await ProjectBundles.CreateAsync(db, session.Content.Sequence.Id, session.Project, session.Content.Count);
var path = await Task.Run(() =>
{
var free = ProjectBundle.FreePathIn(folder, bundle.Sequence.Title ?? session.Content.Sequence.DisplayTitle);
bundle.Save(free);
return free;
});
Log.Info("project", $"Project file '{path}' saved for sequence {bundle.Sequence.Id}");
shell.Notify(Loc.L("Editor.ProjectFile.Saved"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"),
() => ShellActions.Reveal(path));
}
///
/// Opens the project file at : its sequence in the editor (found by id, else by archive and
/// folder), then the file's settings as one undo step. Says in one sentence why when the file cannot be read, its
/// sequence is not in the library, or the sequence cannot take the settings now. With the workspace (owner review 2,
/// R8), a file of format 2 opens its project there (a workspace's own project.chronos as it is; a copy of one
/// gives that project its settings), and a file of format 1 gives its settings to the sequence's Main project, which
/// opens in the workspace (copied first when it is not there yet).
///
public async Task OpenAsync(string path)
{
ProjectBundle bundle;
try
{
bundle = await Task.Run(() => ProjectBundle.Load(path));
}
catch (Exception ex) when (ex is InvalidDataException or IOException or UnauthorizedAccessException)
{
Log.Warning("project", $"Project file '{path}' not opened", ex);
shell.Notify(Loc.L("Editor.ProjectFile.Unreadable"), Path.GetFileName(path), Loc.L("Common.OpenLogs"), Loc.L("Tooltips.Common.OpenLogs"),
() => ShellActions.Reveal(shell.Services.Environment.LogDirectory), isError: true);
return;
}
if (shell.Services.Database is not { } db) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"));
var home = bundle.Workspace is { Home: { IsArchive: true } h } ? await db.Sequences.GetAsync(h.SequenceId) : null;
if ((home ?? await ProjectBundles.ResolveAsync(db, bundle)) is not { } sequence)
{
Log.Info("project", $"Project file '{path}': sequence {bundle.Sequence.Id} ('{bundle.Sequence.Folder}' in archive {bundle.Archive.Id}) not in the index");
shell.Notify(Loc.L("Editor.ProjectFile.NotFound"), bundle.Sequence.Title ?? Path.GetFileName(path), Loc.L("Shell.Nav.Archive"),
Loc.L("Tooltips.Nav.Archive"), () => shell.Navigate(SectionKey.Archive), isError: true);
return;
}
if (!shell.Services.Workspace.IsEnabled)
{
// Not opened: the editor said why, or kept the open sequence's edit the user chose not to discard.
if (await shell.Sequence.ShowAsync(sequence.Id) is { } editor) Apply(editor, bundle);
return;
}
if (bundle.Workspace is { } workspace)
{
// A workspace's own working state opens as it is; a copy of one (saved elsewhere, another PC's) gives its project its settings.
var own = shell.Services.Workspace.Store.Find(workspace.ProjectId) is { } project
&& string.Equals(Path.GetFullPath(project.BundlePath), Path.GetFullPath(path), StringComparison.OrdinalIgnoreCase);
await shell.Sequence.ShowAsync(sequence.Id, new ProjectRequest(sequence.Id, workspace.ProjectId), own ? null : editor => Apply(editor, bundle));
return;
}
// Format 1: the settings go to the sequence's Main project, once it is open (now, or after its copy into the workspace).
await shell.Sequence.ShowAsync(sequence.Id, ProjectRequest.MainOf(sequence.Id), editor => Apply(editor, bundle));
}
/// Gives the open sequence the file's settings, unless the editor cannot change them now (a job runs, read-only).
private void Apply(EditorViewModel editor, ProjectBundle bundle)
{
var session = editor.Session;
var settings = bundle.ProjectFor(session.Project, session.Content.Count);
if (settings.ToJson() == session.Project.ToJson()) return;
if (editor.IsLocked)
{
shell.Notify(Loc.L("Editor.ProjectFile.Locked"), editor.LockedToolTip, Loc.L("Editor.ProjectFile.Retry"), Loc.L("Tooltips.Editor.ProjectFile.Retry"),
() =>
{
// Still the same editor: the file's settings, laid over the project as it is then.
if (ReferenceEquals(shell.Sequence.Editor, editor)) Apply(editor, bundle);
}, isError: true);
return;
}
var before = session.Project;
if (!session.Edit(_ => settings)) return;
session.EndEditRun();
var restore = new ProjectRestore(session, before, session.Project);
Log.Info("project", $"Project file settings applied to sequence {session.Content.Sequence.Id}");
shell.Notify(Loc.L("Editor.ProjectFile.Applied"), session.Content.Sequence.DisplayTitle, Loc.L("Editor.ProjectFile.Undo"),
Loc.L("Tooltips.Editor.ProjectFile.Undo"), () => restore.Undo());
}
}