diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 7ac63601..ad40e226 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -61,9 +61,9 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Housekeeping` | `BackupJobHandler`, `CleanupJobHandler`, `ICleanupStep` with the shared steps (`CleanupSteps`: job history, audit log, trash report that never deletes); hosts add their own steps through `ArchiveServiceOptions.CleanupSteps` | | `Archiving` | `ArchiveService` (create/adopt/open, archive settings written to `archive.json` then the index, `ArchiveSettings.CheckTemplates` and `TemplateRuleException` holding a template given anew to the template rules; `UnderLeaseAsync`: a write under a sequence's lease with its row read under it), `ArchiveIndexer` (scan, rebuild; a sequence found in another folder takes its exports' paths along; a full scan or a rebuild takes the projects' sidecars back too), `ArchiveIngest` (uploads and imports, named through `FrameNaming`; content a conversion replaced is a duplicate of the frame holding its conversion; a restore or a replacement not settled yet refuses the batch), `ImportService`, `ArchiveVerifier`, `ArchiveImages` (thumbnail and proxy passes, several photos at once through `OrderedWork`, which hands results back in frame order), `FrameTiers` (decode tier, `PreviewOnly`/`Undecodable` flags and preview size of frames, written to sidecar and index by the light analysis, deep analysis, renders and image passes), `GprCompanions` (the JPEG of each GoPro GPR, found in the index when an import kept it in another sequence), `ArchiveMaintenance` (also a conversion job's staging and journals, by the job's state; those of a job this index does not know go together, by age), `MassRenamer` (mass rename and Reorganize: the dry run reads each sidecar for a file template; each step checked under its leases before anything of it moves (where its sequences are, what is inside and at its new folder, a sidecar of a newer format, the title it was planned from when it changes it or names the folder or files after it), then the folder, with the sequences of the plan an earlier step left as they were inside it (taken along, their title and file names kept), every index row (the frame paths and render paths of the exports inside it, a file or an image-sequence folder, its own unless the export is still at the old place and another sequence's when it moved with it, follow it in one transaction; a sidecar that cannot be read or written then still has its row follow, and fails the step), then the files under the plan's journal in `journal/` (a sequence whose photos changed since, such as one still receiving them, or whose files are found changed or in use or have their new names taken keeps its file names, the renames being pinned by digest, and the step and the plan go on); the journal keeps the tally of the whole plan, and a plan its job held (paused, cancelled or failed) is left to that job, only its half-done file renames completed at an archive open, which completes any other plan an interruption left and tells each sequence changed; the file renames of a step: sidecar, a sequence whose sidecar cannot be read staying as it is with every folder around it, index (`FrameRepository.RenameFilesAsync`) and the sequence's journal), `SequenceFolders` (`Holds`: the folder the index has for a sequence is there and its sidecar names no other sequence; every writer into a sequence's folder asks it), `SequenceTrash` (delete into the archive's hidden trash with a dry run, restore; the folder moves back when the index step fails; lists sequence and photo entries; `SequenceTrash.Empty`: the emptying's dry run, fingerprint and erase, each entry checked against its fingerprint again under its lease, `TrashKept` with its `TrashKeptReason` for each entry kept; `SequenceTrash.Replaced`: where a replaced entry's conversions are, read from the archive's sidecars (in the index's or the entry's folder, in the trash, else by one `SidecarWalk` of the archive per dry run or emptying) through their replaced tombstones, a conversion deleted only on the archive's word (a tombstone, the trash, or an `ErasureRecord` in `trash/.erased/`, written when an emptying erases a deleted sequence a replaced entry still needs), `TrashEntry.ConversionDeleted` in the dry run and its fingerprint, the erase weighed under the entry's and the sequence's leases once the sequence is settled; `BusyAsync`: what running and paused jobs hold, but the job asking, from `JobRepository.ListHoldsAsync`), `FrameTrash` (photos of a sequence into `trash/photos` with a dry run, a journal that undoes an interrupted deletion whose entry stays unlisted until its sidecar is written, tombstones (a photo never hashed is hashed as it goes; one whose original is missing goes without a file or tombstone; a frame that stays and may be a twin is hashed, its hash kept), positions parked and placed back, proxies and thumbnails moved to follow their frames; `FrameTrash.Restore`: restore re-hashes each file and says why each kept photo stayed (`KeptReason`), under a journal of its own into the sequence that another writer settles only under the entry's lease, into a new sequence through the ingest when theirs is gone, each original staged inside its own entry and the record rewritten after each photo filed; a replaced entry swaps back while its converted frames are unchanged (`SwapBackAsync`); `FrameTrash.Replace`: the files of frames swapped in place, same ids and indices, the old files into one `Replaced` entry with their replacements' hashes, a copy of `analysis.json` and the job's id, the incoming files named never onto a file there, tombstones aliasing old content to new, under `.chronos/replace.pending.json` (its phase and the new names: the next writer completes it when the sidecar lists them, else undoes it; `EnsureReplaced`: the writers of a sequence's frames wait for one not settled); `ReplaceMissingAsync`: a frame missing here takes its photo back in another encoding, nothing to the trash; `FollowUps`: the passes a swap cleared), `MassConverter` (conversion's dry run: busy sequences (running and paused jobs, pending conversions), offline and unreadable ones, the space against `ArchiveServiceOptions.FreeSpace` for the archive root and its staging folder; `QueueAsync`: a confirmed plan's job queued under a process lock, its confirmed photos written first into `journal/convert-.photos` (`ConfirmedPhotos`) under the job's id, a second conversion of its sequences refused, `ConversionQueuedException`; the job, a sequence at a time: under its lease, settled, planned again and held to the confirmed photos (`Confirmed`, `Held`), pinned in `journal/convert-.pins` (`PinLog`); stage A converts into `staging/convert-/` with `OrderedWork`, the space watched before each photo, counting every photo still being written (`SpaceWatch`), each staged file appended to `journal/convert-.staged` (`StagedLog`); stage B per sequence, all or nothing: replace through `FrameTrash.ReplaceAsync` (the sequence's folder read again under its lease, as every writer does), or a new sequence through the ingest with the source's tags, rating, notes and project (a retry finishes the copy the journal names; a source another done conversion copied since is `Superseded`); `ConvertJournal` (`convert-.json`: each sequence's outcome and whether its passes were queued); each sequence replaced or made told, and its passes queued, as it completes), job handlers | | `Processing` | `ProcessingService`, `SequenceAnalyser`, `DeepReports` (a saved deep report while it still describes the frames), `SequenceRender`, `ProjectStore`, `ProjectBundles` (a `.chronos` file for a sequence, and the sequence a file names), `RenderNodeClient`, job handlers | -| `Projects` | `ProjectService` (`ArchiveService.Projects`: the projects of this PC's sequences as a home, under the sequence's lease and only in a folder that holds the sequence (`SequenceFolders.Holds`; otherwise `SequenceFolderMovedException`: reads answer from the index, writes are refused); reads wait 3 s for the lease, then answer from the index; a read-only archive is read without writing (an index-only Main written back once it takes writes): list, create, rename, delete (the folder into `projects/.trash` first, then the deleted record; never Main), history, head (NotFound once deleted), `StoredAsync` (a version file read back and checked), push with fast-forward / idempotent repeat / divergence / hash, portability, strict format and 64 MiB checks; each call first catches up: the sidecars into the index, Main made from the sequence's settings, settings another path wrote appended to Main as an `external` version or, with a push whose mirror was cut short, merged into one `merge` version where they win, a mirror never written over `project.json` settings it has not taken in (`MovedSharedAsync`), records behind the index healed (`HealAsync`, `UpdatedAfter`), projects the archive lost written back (`WriteBackAsync`); a push to Main mirrored into `project.json` and the settings with the settings version check), `ProjectIndexer` (the reconcile, also run by full scans and rebuilds: the projects' trash read before the live folders, so a deletion wins and the live folder's late version files move beside it; a record that cannot be read held back, never taken for a deletion; a lost record written again from the index only once its folder settled (`RecordSettle`, 2 minutes) and no trash folder holds it back (`TrashRecordGrace`, 1 day); a creation cut before its record left as it is; a version file a push left past its record adopted, a stray one moved to `versions/.stray`; `BehindAsync`, one rule for a record behind the index; `SettleMainAsync` and `SwapMainAsync`, one Main from the records, passed in one transaction), `ProjectSidecars` (record and immutable version files, the settings as a JSON string checked against their hash, `MaxVersionBytes` 64 MiB refused before writing), `ProjectMerge` (three-way merge member by member, pending frames merged photo by photo, conflicts, `Replay` of local commits on a moved head; `NewerSettingsException` rather than merge a newer format), `IProjectHome` and `ArchiveProjectHome` (the home a workspace pushes to and pulls from: `HoldsAsync` reads a version back, `FramesStampAsync` says when the frames changed, an offline archive or busy lease is `HomeUnavailableException`; a server is the other home, phase 5b), `HomePhotos` (a sequence's photos as positions name them, with the encodings its Replaced tombstones join; the server's frames endpoint and render nodes build the same), what each call changed (`ProjectChangeSet` to `ArchiveServiceOptions.ProjectsChanged`, once the lease is let go: projects made, renamed, deleted or with a new head, compared before and after under the lease, and whether Main's head was written into the sequence's settings), `CatchUpAsync` (the catch-up alone, saying why it cannot run), `ProjectWire` (projects, versions, push outcomes and a home's frames to and from API v1 DTOs, for the server and a client of it) | -| `Workspaces` | `WorkspaceStore` (a folder outside the library: `workspace.json` written atomically, one folder per project, no index; a leftover folder holding only stale lease files removed on listing), `WorkspaceProject` (`project.chronos` working state, `media/` with `media.json`, `proxies/.jpg` (and `-.jpg` while a copy replaces one) and `analysis.json`, `versions/` with `.replaced` (versions set aside, pruned by age and count) and `.replaced.since`, `sync.json` for a conflict, a restore or the journal of a replay or a Save both, `exports/`, the lease `.lock.lease`; `UnreadableVersions`), `WorkspaceMedia` (`NamedAsAt`: the media learn the home's hashes and aliases), `WorkspaceSync` (checkout, open under the lease, save, commit, push, pull with replay and merge, the base in `project.chronos` as every write's commit point, `SettleAsync` finishing or undoing a cut push, replay or Save both, conflicts settled by keep mine, take server or save both only as shown, restore, status with Gone, Damaged and `MediaOutdated`, the home's frames read again only when their stamp moved), `WorkspaceCopyJobHandler` (`WorkspaceJobs.Copy` and `CopyFactsAsync`, registered by the desktop only: the archive only read, from a folder that holds the sequence; a workspace inside a library refused; the archive's current proxies copied, the others made in the workspace, each hash-verified, resumable from a checkpoint of its frames version and folder, free space checked against its estimate plus 512 MiB; the encodings conversions joined kept in `media.json`; the working state's positions moved by frame where frames stay, by photo where they came or went; a cancelled first copy's media cleared under the project's lease only when no other copy of the project waits or runs, through `ICancelledJobHandler` too) | -| `Sync` | `SyncService` (sync table of one server: compare, link by content through the aliases, settle conflicts, enqueue transfers), `SyncRules` (status, settings merge and differences, the proxies this PC can send, aliases followed; no I/O), `SyncTombstones` (photos either side removed are not offered back; the replaced tombstones of both sides join the encodings of one photo, union-find, each compared as the smallest SHA-256 among them, a deletion covering them all; immutable once made), `SyncPositions` (the settings' frame positions translated by photo to the frames of the copy they go to), `SyncLinkStore` (`sync_links`, `sync_state`), `SyncTransfers` and `SyncJobHandler` (resumable, hash-verified uploads and downloads as jobs; downloads commit through the archive ingest, and a frame missing here whose photo the server holds in another encoding takes that file through `FrameTrash.ReplaceMissingAsync`; job log lines from the catalog), `SyncAgent` (background comparison, server events, backoff, offline proxies), `ProxyCache` and `RemoteSequence` (server sequences opened with proxies), `ISyncRemote` (the server calls; `ChronosSyncRemote` over `ChronosClient`) | +| `Projects` | `ProjectService` (`ArchiveService.Projects`: the projects of this PC's sequences as a home, under the sequence's lease and only in a folder that holds the sequence (`SequenceFolders.Holds`; otherwise `SequenceFolderMovedException`: reads answer from the index, writes are refused); reads wait 3 s for the lease, then answer from the index; a read-only archive is read without writing (an index-only Main written back once it takes writes): list, create, rename, delete (the folder into `projects/.trash` first, then the deleted record; never Main), history, head (NotFound once deleted), `StoredAsync` (a version file read back and checked), push with fast-forward / idempotent repeat / divergence / hash, portability, strict format and 64 MiB checks; each call first catches up: the sidecars into the index, Main made from the sequence's settings, settings another path wrote appended to Main as an `external` version or, with a push whose mirror was cut short, merged into one `merge` version where they win, a mirror never written over `project.json` settings it has not taken in (`MovedSharedAsync`), records behind the index healed (`HealAsync`, `UpdatedAfter`), projects the archive lost written back (`WriteBackAsync`); a push to Main mirrored into `project.json` and the settings with the settings version check), `ProjectIndexer` (the reconcile, also run by full scans and rebuilds: the projects' trash read before the live folders, so a deletion wins and the live folder's late version files move beside it; a record that cannot be read held back, never taken for a deletion; a lost record written again from the index only once its folder settled (`RecordSettle`, 2 minutes) and no trash folder holds it back (`TrashRecordGrace`, 1 day); a creation cut before its record left as it is; a version file a push left past its record adopted, a stray one moved to `versions/.stray`; `BehindAsync`, one rule for a record behind the index; `SettleMainAsync` and `SwapMainAsync`, one Main from the records, passed in one transaction), `ProjectSidecars` (record and immutable version files, the settings as a JSON string checked against their hash, `MaxVersionBytes` 64 MiB refused before writing), `ProjectMerge` (three-way merge member by member, pending frames merged photo by photo, conflicts, `Replay` of local commits on a moved head; `NewerSettingsException` rather than merge a newer format), `IProjectHome` and `ArchiveProjectHome` (the home a workspace pushes to and pulls from: `HoldsAsync` reads a version back, `FramesStampAsync` says when the frames changed, an offline archive or busy lease is `HomeUnavailableException`), `ServerProjectHome` (phase 5b: a server sequence's `/projects` over `ChronosClient`; a server out of reach, an expired sign-in, a 503 lease, offline archive or `projects_unreadable`, a 409 `folder_in_use` and a server without the projects are `HomeUnavailableException`, a 404 `sequence`/`project`/`version` and a refused name `ProjectException` (a deleted project's head is 404 `project`), a 422 `too_large` the `TooLarge` outcome, other refusals keep their `ChronosApiException`; `HoldsAsync` reads the version back, no frames stamp; its sequences name an archive id made from the server's key), `HomePhotos` (a sequence's photos as positions name them, with the encodings its Replaced tombstones join; the server's frames endpoint and render nodes build the same), what each call changed (`ProjectChangeSet` to `ArchiveServiceOptions.ProjectsChanged`, once the lease is let go: projects made, renamed, deleted or with a new head, compared before and after under the lease, and whether Main's head was written into the sequence's settings), `CatchUpAsync` (the catch-up alone, saying why it cannot run), `ProjectWire` (projects, versions, push outcomes and a home's frames to and from API v1 DTOs, for the server and a client of it) | +| `Workspaces` | `WorkspaceStore` (a folder outside the library: `workspace.json` written atomically, one folder per project, no index; a leftover folder holding only stale lease files removed on listing), `WorkspaceProject` (`project.chronos` working state, `media/` with `media.json`, `proxies/.jpg` (and `-.jpg` while a copy replaces one) and `analysis.json`, `versions/` with `.replaced` (versions set aside, pruned by age and count) and `.replaced.since`, `sync.json` for a conflict, a restore or the journal of a replay or a Save both, `exports/`, the lease `.lock.lease`; `UnreadableVersions`), `WorkspaceMedia` (`NamedAsAt`: the media learn the home's hashes and aliases), `WorkspaceSync` (checkout, open under the lease, save, commit, push, pull with replay and merge, the base in `project.chronos` as every write's commit point, `SettleAsync` finishing or undoing a cut push, replay or Save both, conflicts settled by keep mine, take server or save both only as shown, restore, status with Gone, Damaged and `MediaOutdated`, the home's frames read again only when their stamp moved), `WorkspaceCopyJobHandler` (`WorkspaceJobs.Copy` and `CopyFactsAsync`, registered by the desktop only: the archive only read, from a folder that holds the sequence; a workspace inside a library refused; the archive's current proxies copied, the others made in the workspace, each hash-verified, resumable from a checkpoint of its frames version and folder, free space checked against its estimate plus 512 MiB; the encodings conversions joined kept in `media.json`; the working state's positions moved by frame where frames stay, by photo where they came or went; a cancelled first copy's media cleared under the project's lease only when no other copy of the project waits or runs, through `ICancelledJobHandler` too; a project whose home is a server, `WorkspaceJobs.CopyFromServer`, phase 5b: downloaded through the desktop's session (`ISyncConnector`), never through this PC's archive, the frames of one frames version with the aliases of the server's conversions, each proxy (else the thumbnail standing in, `WorkspaceFrame.FileKind`) hashed as it arrives and checked on the disk, four at a time, the editor's current file never overwritten, resumable from the same checkpoint, free space checked against the server's proxy sizes) | +| `Sync` | `SyncService` (sync table of one server: compare, link by content through the aliases, settle conflicts, enqueue transfers), `SyncRules` (status, settings merge and differences, the proxies this PC can send, aliases followed; no I/O), `SyncTombstones` (photos either side removed are not offered back; the replaced tombstones of both sides join the encodings of one photo, union-find, each compared as the smallest SHA-256 among them, a deletion covering them all; immutable once made), `SyncPositions` (the settings' frame positions translated by photo to the frames of the copy they go to), `SyncLinkStore` (`sync_links`, `sync_state`), `SyncTransfers` and `SyncJobHandler` (resumable, hash-verified uploads and downloads as jobs; downloads commit through the archive ingest, and a frame missing here whose photo the server holds in another encoding takes that file through `FrameTrash.ReplaceMissingAsync`; job log lines from the catalog), `SyncAgent` (background comparison, server events, backoff, offline proxies; a server's `projectChanged` passed on as `ProjectChanged`, and null after a lost event stream once a comparison reached the server again), `ProxyCache` and `RemoteSequence` (server sequences opened with proxies), `ISyncRemote` (the server calls; `ChronosSyncRemote` over `ChronosClient`) | ### 2.3 Chronos.App areas @@ -72,8 +72,8 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Shell` | `MainWindow` (rail and its shortcuts, taskbar progress), `ShellViewModel` (rail, sections, first run), `OsNotifications` (toasts as Windows notifications while the window is minimised or in the background), dialogs, `ErrorText` (the sentence of an error toast), `ScreenCapture` (`--capture` scenes), `SectionTemplates.xaml` (view model → view) | | `Sections` | One `XxxView.xaml` + `XxxViewModel` per screen: Welcome, Library, Sequence (the Edit section: the editor, `SequencePickerView` choosing in place a project of the workspace or a sequence of the library, the in-window dialogs of the workspace, and the opening of this PC's sequences as workspace projects: the project opened last, else "Open in workspace", the checkout and the copy job followed until it opens), Import, Archive, Jobs (two tabs, Queue and Scheduled: `SchedulesView` shows `Jobs/SchedulesViewModel`), Server, Settings (its last page is About) | | `Library` | Filter, facets, pager, timeline, saved views, quick and mass actions (`MassActions`: Reorganize and Convert for the sequences of one archive), remote cards and thumbnails, thumbnail cache, list export | -| `Editor` | `EditorSession` (project, undo/redo, saving, merges through `Data/Projects/ProjectMerge`), `ISequenceSource` (`LocalSequenceSource`, `RemoteSequenceSource`, `WorkspaceSequenceSource`: a workspace project over its media, the working state saved in `project.chronos` under the project's lease and merged photo by photo in the portable form (`Merge`, a setting both sides changed asked through `ProjectConflictException`), `ReadOnlyChanged` for a project of a newer Chronos, an unstored edit kept aside in `versions/.replaced` (`SetAsideAsync`), renders at the home with the portable settings through `IProjectRenders`, naming a version only while none waits to be sent), the steps of the Edit path (`EditPath`: their order, each step's state, the step of each finding, the memory of the step shown; tabs Analysis, Frames, Exposure, Motion, Camera, Time, Stack, Export), `PreviewRenderer`, `ExportPlanner`, `ExportSync`, `SavedCopies`, `SequenceJobs`, `ProjectFiles` (save and open `.chronos` project files: format 2 opens its workspace project, format 1 gives its settings to Main) | -| `Workspace` | Owner review 2, R8: `WorkspaceHost` (the desktop's `WorkspaceStore` and `WorkspaceSync` over Settings › Workspace's folder, this PC's archive as the home; checkout and copy with its size and free space, status, Save version with the sync after it, sync, resolve, restore, history, open, new, rename, delete, the plan and removal of a local copy whose files but the media go to `/.trash` (put back whole when a move fails), pruning past Kept versions after `HoldsAsync`, copies a newer Chronos wrote or that cannot be read listed as such and never changed, a folder inside a library refused, `PlanFolderAsync` and `UseFolderAsync`), `WorkspaceFolderChange` (Settings › Workspace › Change… and the refused folder's Choose folder), `ProjectMenuViewModel` (the title's ▾: state chip read again after edits, the menu, Update media; `IWorkspaceUi` is what it asks of the section, `ShowDialogWhenFree` holding a background conflict until the open dialog closes), `WorkspaceDialogs` (Open in workspace with unreadable projects listed disabled, project name, Save version, History, conflict, a format conflict offering only Save both, Remove local copy with its typed confirmations; `WorkspaceDialogs.xaml`), `WorkspaceProjectItem` (a picker row), `WorkspaceText` (states, versions, authors, failures) | +| `Editor` | `EditorSession` (project, undo/redo, saving, merges through `Data/Projects/ProjectMerge`), `ISequenceSource` (`LocalSequenceSource`, `RemoteSequenceSource`, `WorkspaceSequenceSource`: a workspace project over its media, the working state saved in `project.chronos` under the project's lease and merged photo by photo in the portable form (`Merge`, a setting both sides changed asked through `ProjectConflictException`), `ReadOnlyChanged` for a project of a newer Chronos, an unstored edit kept aside in `versions/.replaced` (`SetAsideAsync`), renders at the home with the portable settings through `IProjectRenders`, naming a version only while none waits to be sent; a server home's analyses and renders are the server's jobs, a render naming the version the server holds when the project is in step with it), `ServerJobs` (a server sequence's analyses and renders followed through its events, shared by `RemoteSequenceSource` and a server home's `WorkspaceSequenceSource`), the steps of the Edit path (`EditPath`: their order, each step's state, the step of each finding, the memory of the step shown; tabs Analysis, Frames, Exposure, Motion, Camera, Time, Stack, Export), `PreviewRenderer`, `ExportPlanner`, `ExportSync`, `SavedCopies`, `SequenceJobs`, `ProjectFiles` (save and open `.chronos` project files: format 2 opens its workspace project, format 1 gives its settings to Main) | +| `Workspace` | Owner review 2, R8: `WorkspaceHost` (the desktop's `WorkspaceStore` and `WorkspaceSync` over Settings › Workspace's folder, this PC's archive or, through `SyncHost.ProjectHome`, the signed-in server as the home (a server it is not signed in to reads as offline; `HomeChanged` from the server's `projectChanged`, texts worded for it by `WorkspaceText.ForHome`); checkout and copy with its size and free space, status, Save version with the sync after it, sync, resolve, restore, history, open, new, rename, delete, the plan and removal of a local copy whose files but the media go to `/.trash` (put back whole when a move fails), pruning past Kept versions after `HoldsAsync`, copies a newer Chronos wrote or that cannot be read listed as such and never changed, a folder inside a library refused, `PlanFolderAsync` and `UseFolderAsync`), `WorkspaceFolderChange` (Settings › Workspace › Change… and the refused folder's Choose folder), `ProjectMenuViewModel` (the title's ▾: state chip read again after edits, the menu, Update media; `IWorkspaceUi` is what it asks of the section, `ShowDialogWhenFree` holding a background conflict until the open dialog closes), `WorkspaceDialogs` (Open in workspace with unreadable projects listed disabled, project name, Save version, History, conflict, a format conflict offering only Save both, Remove local copy with its typed confirmations; `WorkspaceDialogs.xaml`), `WorkspaceProjectItem` (a picker row), `WorkspaceText` (states, versions, authors, failures) | | `Import` | `CardPool` (inserted cards, remembered cards, folders), camera profiles, plans and choices, destinations (archive, folder, server through `ServerImportSink`), card actions (verified delete, format, eject) | | `Archive` | `CurrentArchive`, `ArchiveTree`, figures for the charts, maintenance reports, Reorganize (`ReorganizeDialogViewModel`: folder, file and title templates each with its switch, the dry run, Apply queues the `move` job of that plan; `ReorganizePlans`: each template's check, the plan as rows and a summary; `ReorganizeOffer`: per archive, the templates Settings › Archive's toast offers, joined while that archive's toast is up), Convert (`ConvertDialogViewModel`: format, JPEG quality and a mode chosen at every run, the dry run made once per format and quality, Apply behind the mode's confirmation queues the `convert` job of that plan through `MassConverter.QueueAsync`; `ConvertPlans`: the plan as rows in the mode's words, a summary, the space line, the Replace confirmation that types the number of photos and the New sequence one that counts the photos not copied; `ConvertUndo`: the Undo the Jobs screen's toast offers when Replace conversions end, which restores the `Replaced` trash entries their jobs made, by the job's id), retag, delete and trash dialogs (`SequenceDeletion`, `DeletePlans`, `TrashEmptyPlans`: Empty… behind a dry run and a typed confirmation, every entry whose conversion was deleted named first), `ArchiveFailures` | | `Server` | `ServerSession`, `ConnectFlow` (trust on first use), `SyncHost` (sync engine, agent, metered hold, editor connections, Export Sync), sync table, `RemoteSequenceApi` | @@ -98,7 +98,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | Host | Composition root | What it runs | |---|---|---| -| Chronos (desktop) | `App/Infrastructure/AppServices` | SQLite index in `%LOCALAPPDATA%\Chronos` (or `.\data` when portable, unless the copy is in a OneDrive folder); `ArchiveService` with WIC first, then managed decoders (a conversion orders its own chain, the managed decoders first), its free space measured by Windows (`VolumeInfo.FreeBytesAt`, UNC shares included); `ProcessingService` with Media Foundation, then managed encoders; one `JobEngine` with the handlers of both and the workspace copy; the workspace (`WorkspaceHost`: `%LOCALAPPDATA%\Chronos\workspace` or `.\data\workspace`, unless Settings › Workspace says otherwise; none in a capture); thumbnails; `ServerSession`; `SyncHost` while signed in (sync engine and agent, upload and download handlers, metered hold, editors of server sequences); the render node while opted in and signed in; update check and download (`About/UpdateCheck`, `About/UpdateDownload`, `About/UpdateFlow`: the setup, or the portable zip for a portable copy, verified against `SHA256SUMS`, resumable, cancellable, failing after 60 s without data); diagnostics bundle; the `Scheduler` on `DesktopScheduleHost`, started once the archive was reopened (an unplugged one is looked for every minute), which then runs the archive scan once (again when an unplugged archive is back), and whose system schedules replaced the rescan timer, the daily backup loop and the job-history purge (scans follow Settings › Analysis › After a scan at every run); the restore staged in Settings › Advanced (`DatabaseBackups`) | +| Chronos (desktop) | `App/Infrastructure/AppServices` | SQLite index in `%LOCALAPPDATA%\Chronos` (or `.\data` when portable, unless the copy is in a OneDrive folder); `ArchiveService` with WIC first, then managed decoders (a conversion orders its own chain, the managed decoders first), its free space measured by Windows (`VolumeInfo.FreeBytesAt`, UNC shares included); `ProcessingService` with Media Foundation, then managed encoders; one `JobEngine` with the handlers of both and the workspace copy; the workspace (`WorkspaceHost`: `%LOCALAPPDATA%\Chronos\workspace` or `.\data\workspace`, unless Settings › Workspace says otherwise; none in a capture); thumbnails; `ServerSession`; `SyncHost` while signed in (sync engine and agent, upload and download handlers, metered hold, editors of server sequences, the server as the home of workspace projects when it has the `projects` capability); the render node while opted in and signed in; update check and download (`About/UpdateCheck`, `About/UpdateDownload`, `About/UpdateFlow`: the setup, or the portable zip for a portable copy, verified against `SHA256SUMS`, resumable, cancellable, failing after 60 s without data); diagnostics bundle; the `Scheduler` on `DesktopScheduleHost`, started once the archive was reopened (an unplugged one is looked for every minute), which then runs the archive scan once (again when an unplugged archive is back), and whose system schedules replaced the rescan timer, the daily backup loop and the job-history purge (scans follow Settings › Analysis › After a scan at every run); the restore staged in Settings › Advanced (`DatabaseBackups`) | | Chronos Server | `Server/Hosting/ServerHost.Build` | Options from `server.json` + `CHRONOS_*`; PostgreSQL (or SQLite on Windows); `ArchiveModule` then `ProcessingModule` register job handler providers; `JobEngineHost` (renders only managed formats and MP4 jobs no render node can take, BRIEF §14.7); `RenderNodeService`/`RenderNodeMonitor`; `UploadService`; `VolumeSpace` (free space of the archive, the space path and `/data`, file system and mount from `/proc/self/mountinfo`; `WritableFree`, what a conversion counts on; tests replace it); `EventHub` (WebSocket); embedded admin panel; LAN discovery beacon; Windows service host; `SchedulerHost` with the system schedules `archive-scan` (every 10 minutes, also once at start), `upload-cleanup` (every 6 hours), `index-backup` (SQLite only, 03:00), `housekeeping` (job history, 04:00) and `audit-cleanup` (04:30; Settings › Logs shows and sets its age limit, 0 while it is off; seeded and reset from `AuditRetentionDays`, 0 by default: off, the audit log kept; `CHRONOS_AUDIT_RETENTION_DAYS` fixes it before the first pass), no other timer queues work (a 10-minute timer only reads archive.json again) | | Chronos Uploader | `Uploader/App.xaml.cs` | `ChronosClient`, persisted queue, watch folders; no database | | Chronos Setup | `Setup/Program` | TPK1 payload extraction, registry, shortcuts, file types named in setup's language, silent mode, uninstaller; only what starts a program its log or payload lists is changed: Windows services of those programs stopped once the programs have closed, started again (also after a failure) or deleted through the Service Control Manager (an elevated `/SERVICES … /NAMES` step when needed), sign-in entries of those programs moved to the program an upgrade renamed or removed, shared shortcuts handed to the product that keeps the program; the Server only for all users inside Program Files; "Remove my data" limited to the programs no other installed product uses | diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index a308aef6..4fe0ca83 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -5,6 +5,17 @@ commits follow Conventional Commits (release notes are generated from them by `C ## [Unreleased] +### Added +- A Chronos Server keeps its sequences' projects (owner review 2, phase 5b): Main and named projects with their + versions, under `/api/v1/sequences/{id}/projects`, with `projectChanged` events and the `projects` capability. The + admin panel lists a sequence's projects. +- Edit opens a server's sequence as a workspace project, as for this PC's library: *Open in workspace* asks which + project, its proxies are downloaded into the workspace (hash-checked, resumable), and Save version, Sync, History, + New, Rename, Delete and Remove local copy work against the server. A project already in the workspace opens while + the server is out of reach; its work waits. The chip follows what the server says (*Server newer*, *Not on + server*), texts name the server, analyses and renders run on the server, and a render first offers to send what is + not there yet. + ### Fixed - Chronos and the Uploader could not reach a server in a container whose ports are published as other host ports (owner review 3). The admin panel's Settings › Network and TLS listed the container's ports (8080, 8443) as if diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 2e56bac1..839fc554 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -626,3 +626,13 @@ One line per decision: date · decision · alternative · reason. | 2026-11-04 | `ChronosAddress` refuses a link-local IPv6 address with a zone index (`fe80::1%12`): *Invalid address*. | Keep the zone as `%25` | `Uri` and the connection would drop the zone, failing later with a less clear error; the LAN address or name works. | | 2026-11-04 | Screenshot baselines are captured on the development PC (Europe/Rome time zone) from a Release build and committed to `tests/visual/baselines` (156 screens, owner review 3, R2); CI no longer pushes its screenshots to a `ci-screenshots` branch, the branch is deleted, and the `windows` job's token is read-only. Until a Windows runner is registered (on that PC, or a new set accepted from the runner's PC), `screenshots diff` runs locally before a pull request that changes a screen. | Keep accepting from `ci-screenshots`; merge that branch | The owner chose it: no Windows runner exists, so CI never produced a set taken at `SampleData.Now`, and the old `ci-screenshots` commit predates the fixed clock; a branch that only CI writes and that never merges is noise once baselines live in `main`. | | 2026-11-04 | While `--capture` freezes `AppClock`, what the screens measure on the machine is shown as fixed sample values: free space 1.2 TB (`ArchiveLocations.FreeSpace` and the import plan's totals), a server latency of 12 ms, and the last sync comparison at the frozen moment taking 0.4 s. | Raise the diff tolerance; leave them measured | Measured, they moved the Server screens by 0.13–0.15 % (the latency's width shifts the rest of the status line) and the Import screens to the 0.05 % limit (the PC's free space), so baselines failed at random; a larger tolerance would hide real changes. | +| 2026-11-04 | Server home (owner review 2, R8, phase 5b): a server sequence's projects live under `/api/v1/sequences/{id}/projects` (list, create, rename, delete, head, versions, push, frames) on the same `ProjectService` as a PC's archive, gated by the `projects` capability; the desktop reaches them through `ServerProjectHome` over the signed-in session's `ChronosClient`. A server out of reach, an expired sign-in, a 503 (busy lease, offline archive, `projects_unreadable`), a 409 `folder_in_use` and a server without the projects are `HomeUnavailableException` (the workspace shows Offline and its work waits); a 404 `sequence`/`project`/`version` and a refused name are `ProjectException`s; other refusals keep their `ChronosApiException`. | A separate server-side project store | One implementation of the rules 5a hardened (leases, sidecars, journals, merges); the workspace treats both homes alike. | +| 2026-11-04 | A deleted project's head answers 404 `project` on the server, as `IProjectHome.HeadAsync` answers NotFound on a PC's archive (5a): the workspace reads Gone from the head alone. The original 5b's `IProjectHome.IsLiveAsync` and `WorkspaceStatus.Gone` are dropped in the port. | Keep the head readable and ask `IsLiveAsync` (the original 5b) | Final 5a already decides Gone from the head; one rule for both homes, and one request fewer per status. A deleted project's versions stay readable (`/versions`). | +| 2026-11-04 | Push outcomes gain `too_large` (422, `PushOutcome.TooLarge`, final 5a's 64 MiB limit), a version over the limit read by the server is 413 `too_large`, and `ProjectsUnreadableException` is 503 `projects_unreadable`; both are caught before the `IOException` → 409 `folder_in_use` mapping. The workspace words them for the home (`Errors.Workspace.VersionTooLarge.Server`). | Let them fall through as `folder_in_use` | They are not a folder in use: too large is final, unreadable is worth retrying. | +| 2026-11-04 | `ProjectService` tells what each call changed (`ProjectChangeSet` to `ArchiveServiceOptions.ProjectsChanged`) after the lease is let go, compared from the projects read before the reconcile and after the call; the server turns it into `projectChanged` events and its background `ProjectCatchUp` runs `CatchUpAsync`. The catch-up of a read-only archive (`ReadOnlyCatchUpAsync`) tells nothing. | Tell inside the lease; diff the index | Subscribers never run under a sequence's lease; the before/after read is the only one that sees records the reconcile healed. | +| 2026-11-04 | Kept versions on a server home are pruned as on a PC's archive: each version file goes only after `HoldsAsync` read that version back from the home with the same hash (one request per version). | One listing of the server's versions (the original 5b) | Final 5a's rule: a listing does not prove the stored bytes; pruning is rare and small. | +| 2026-11-04 | The workspace copy of a server's sequence (`WorkspaceJobs.CopyFromServer`) downloads through the desktop's session (`ISyncConnector`), never this PC's archive: one frames version with its aliases, each proxy (else the thumbnail standing in, `FileKind` thumb) hashed as it arrives and checked on disk, four at a time, resumable from final 5a's `copy:frame:fv:folder` checkpoint, the editor's current file never overwritten (other bytes under `ProxyName(id, sha)`), the space checked against the server's proxy sizes (the manifest has no file sizes), a cancelled first copy cleared like 5a's. | Copy through the proxy cache | The cache is the proxy editor's; the workspace owns its media. | +| 2026-11-04 | Texts of a server's project are their key's `.Server` form when one exists (`WorkspaceText.ForHome`), else the key itself; the chip says *Server newer* and *Not on server*. | Format "the library" / "the server" into one text | Word order and articles differ by language; a missing form falls back to the library's text, never to a key. | +| 2026-11-04 | A server's project renders what the server holds: before a render (`ProjectMenuViewModel.ReadyToRenderAsync`) unsaved or unsent work is offered to be saved and sent; Offline, Gone, Damaged or media removed hold the render. In step, the jobs name the version alone; out of step, the portable settings travel and only the project is recorded. An analysis's Auto values reaching Main at the server are taken by the next `projectChanged` (pushed) within 2 minutes, with Sync automatically. | Render the workspace's settings always | The server renders with its originals; only a version it holds can be named. | +| 2026-11-04 | Edit opens a server's sequence as a workspace project when the server has the `projects` capability (`OpenServerWorkspaceAsync`), with final 5a's refusals (a copy this Chronos cannot read, a damaged or newer Main listed disabled, a workspace folder refused). The *sequence left the index* refusal applies only to projects of this PC's archive. An older server's sequences open with proxies as before. | Refuse every project whose sequence is not in the index | A server's sequence is never in this PC's index. | +| 2026-11-04 | `ServerProjectHome` gives no frames stamp: a status reads the server's frames each time. | Add a stamp to the API | Kept for later; the frames endpoint is small and the 5a rule (stamp unchanged → frames not read) falls back safely. | diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx index 860ab020..fa269f93 100644 --- a/i18n/en/Archive.resx +++ b/i18n/en/Archive.resx @@ -282,6 +282,7 @@ Old trash entries: {0}, size: {1}; nothing was deletedlong: job log line; entries older than the clean-up's age limit Photos checked: {0}, intact: {1}, hashed: {2}, with problems: {3}long: job log line {0}: copied {1}, made {2}, unchanged {3}, without a file {4}long: job log line; {1} proxies copied from the archive; {2} made from the originals; {3} already in the workspace; {4} frames with neither + {0}: downloaded {1}, thumbnails {2}, unchanged {3}, without a file {4}long: job log line; {1} proxies downloaded from the server; {2} thumbnails standing in for proxies the server has not made yet; {3} already in the workspace; {4} frames with neither {0}: the frames changed during the copy; copying againlong: job log line Back up database Dry run diff --git a/i18n/en/Editor.resx b/i18n/en/Editor.resx index 4caa9f14..52cc2048 100644 --- a/i18n/en/Editor.resx +++ b/i18n/en/Editor.resx @@ -173,6 +173,7 @@ Versions Not sent Library offline + Server offline Restore Same as now History of {0}{0} project name @@ -239,6 +240,7 @@ Delete project… Delete Its versions are sent to the library first, then the project goes to the library's project trash; the sequence and its photos stay.long + Its versions are sent to the server first, then the project goes to the server's project trash; the sequence and its photos stay.long Delete project {0}?{0} project name History… Keep @@ -278,6 +280,7 @@ Discard the changes of {0}? Files The photos copied to this PC are deleted; the project stays in the library and opens again from there.long + The photos copied to this PC are deleted; the project stays on the server and opens again from there.long None Remove Send first @@ -382,39 +385,53 @@ Choose folder Later {0} was changed in the library while you edited it here. These settings differ: keep yours, take the library's, or keep both as two projects.long; {0} project name + {0} was changed on the server while you edited it here. These settings differ: keep yours, take the server's, or keep both as two projects.long; {0} project name Saved by a newer Chronoslong; the one line a conflict of format lists {0} was saved in the library by a newer Chronos, whose settings this one does not merge with yours. Keep both as two projects, or update Chronos.long; {0} project name + {0} was saved on the server by a newer Chronos, whose settings this one does not merge with yours. Keep both as two projects, or update Chronos.long; {0} project name Take library'stake the library's values where both sides changed a setting + Take server's Changed in the library too + Changed on the server too Workspace copy failed Copying to the workspace Project {0} created{0} project name Project not deleted Project {0} deleted{0} project name {0} {1} here, {2} in the librarylong; {0} setting name, {1} value in this workspace, {2} value in the library + {0} {1} here, {2} on the serverlong; {0} setting name, {1} value in this workspace, {2} value on the server Edit kept aside A newer Chronos saved this project before your last edit was stored: that edit is kept aside in the project's folder, and the newer settings show read-only.long {0} changed in the library while your edit waited to be saved. The settings below differ: keep your values, or take the library's.long + {0} changed on the server while your edit waited to be saved. The settings below differ: keep your values, or take the server's.long Project in sync Library photos changed + Server photos changed Version not sent yet Nothing new to save Library offline + Server offline Open Project not opened Project read-only Local copy not removed Local copy removed Project renamed + Not rendered Version {0} restored{0} version number Version {0} saved{0} version number Your versions saved as {0}{0} the name of the new project holding them Version {0} saved and sent{0} version number + Send and render + The server renders {0} as it holds it: save your changes as a version and send them first.long; {0} project name + Send before rendering Not sentversions saved here wait to be sent to the library Library newerthe library has versions the workspace has not taken + Server newer Conflict Damageda version or the project file saved in the workspace cannot be read Not in library + Not on server In sync No media Changedthe project has changes not saved as a version @@ -425,6 +442,7 @@ Sync failed Project synced Library's values taken + Server's values taken Undo Update media Updating media diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx index d3800727..fcc5c329 100644 --- a/i18n/en/Errors.resx +++ b/i18n/en/Errors.resx @@ -55,10 +55,13 @@ {0} did not match its source after it was copied.{0} file path A file of this project in the workspace cannot be read; the log names it. This project was deleted in the library; nothing was removed. Discard changes removes its local copy. + This project was deleted on the server; nothing was removed. Discard changes removes its local copy. The workspace drive needs {0} GB more for this copy.{0} gigabytes missing The last edit could not be stored yet; it is tried again, try once more in a moment. {0} cannot be used as the workspace folder; the log says why.long; {0} folder + Your account cannot change the projects of this server. The library's copy of this project does not match what was sent; nothing was removed. + The server's copy of this project does not match what was sent; nothing was removed. The workspace folder is inside a library; nothing is copied into it. The workspace folder {0} is inside a library, where Edit copies nothing: choose another workspace folder.long {0} is inside a library, where Edit copies nothing: choose a folder outside your libraries.long; {0} folder @@ -68,17 +71,23 @@ The workspace holds no photos of this project; open it again to copy them. Another project of this sequence has that name. A newer Chronos saved this copy in the workspace; update Chronos to open it or remove it. + This server keeps no projects: it needs an update before its sequences can be edited in the workspace. The drive of the workspace folder lacks room for this copy and the 0.5 GB the copy keeps free. The project is no longer in the workspace. The library cannot be reached now; your work stays in the workspace and can be sent once it is back. + The server cannot be reached now; your work stays in the workspace and can be sent once it is back. The workspace copies proxies for now; copying the originals comes in a later version. The workspace project belongs to another sequence. The workspace copy job has no valid parameters. This project is no longer in the library. + This project is no longer on the server. This project was saved by a newer Chronos: it opens read-only. The library is read-only now; your work stays in the workspace and can be sent once it is writable. The library refused a version of this project; the log says why. + The server refused a version of this project; the log says why. This project's sequence is no longer in the library: only its local copy can be removed, from the picker's menu.long Some work is not in the library yet: send it first, or discard it. + Some work is not on the server yet: send it first, or discard it. This version is larger than the {0} MB a version can be, so the library cannot store it; your work stays in the workspace.{0} megabytes + This version is larger than the {0} MB a version can be, so the server cannot store it; your work stays in the workspace.{0} megabytes diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx index a3dd2087..f3d7160f 100644 --- a/i18n/en/Server.resx +++ b/i18n/en/Server.resx @@ -199,6 +199,7 @@ Get exports Keep mine Open with proxies + Open in workspace Pause Resume Save both diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index 6f44750e..e7c68d6a 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -209,7 +209,9 @@ Show the settings that differ between version {0} and the project now{0} version number The project is this version now Saved here, waiting to be sent to the library + Saved here, waiting to be sent to the server The library cannot be reached: the versions this PC keeps are listed + The server cannot be reached: the versions this PC keeps are listed Make version {0} the project again (one step: Ctrl+Z takes it back); unsaved changes are saved as a version first{0} version number Adds blur along the motion like a slower shutter; costs optical flow on every frame Optical flow precision for blur and synthesised frames; Best is the slowest @@ -226,13 +228,16 @@ Not applicable: stabilisation is off Not applicable: stacking is off Open a project the library has for this sequence; Main holds its settings as they are + Open a project the server has for this sequence; Main holds its settings as they are Free space on the drive of the workspace folder; the copy keeps 0.5 GB free besides The new project's name: 1 to 60 characters, each name once per sequence A new project of this sequence, starting from Main Copy the project's photos into the workspace, then open it there Copying the originals, to render on this PC, comes in a later update The sequence's projects in the library + The sequence's projects on the server Copy the proxies: light and fast to edit; renders use the library's originals + Download the server's proxies: light and fast to edit; renders run on the server, with the originals What the copy of the proxies writes into the workspace, as reckoned before it starts Let the advisor set every section from the analysis and list what changed The advisor never stacks on its own: a median erases moving stars @@ -261,29 +266,38 @@ Overlay the motion to the next frame measured by the engine Drag the line to compare · drag to pan · wheel zooms · double-click 1:1 Send this project's versions to the library, then move it to the library's project trash + Send this project's versions to the server, then move it to the server's project trash Move the project, with all its versions, to the library's project trash + Move the project, with all its versions, to the server's project trash The project's versions: compare one with now, or restore it Keep the project as it is Project {0} ({1}): save a version, sync, history, other projects and the local copy{0} project name, {1} its state Make another project of this sequence, starting from this one (for example a vertical cut for social media) Open another project of this sequence: one in the library, or a new onelong Free this PC's space: delete the photos copied to the workspace; the project stays in the library + Free this PC's space: delete the photos copied to the workspace; the project stays on the server Give this project another name, here and in the library + Give this project another name, here and on the server Keep the project as it is now as a version of its history, with an optional note (Ctrl+S) Project files are for sequences in an archive on this PC Apply the project file’s settings again Save a .chronos file that opens this sequence with these settings when double-clicked Bring back the settings the sequence had before the file was opened · Ctrl+Z Rename the project here and in the library + Rename the project here and on the server Make the project in the library and open it in the workspace + Make the project on the server and open it in the workspace 1 to 60 characters, each name once per sequence Your account can look at this server sequence but not change it Edited with proxies on this PC; changes are saved on {0} and analyses and renders run there Shown from {0}; your account can look at this sequence but not change it Remove the copy without sending what is not in the library; that work is kept aside in the workspace's trash + Remove the copy without sending what is not on the server; that work is kept aside in the workspace's trash Keep the local copy as it is Delete the workspace copy; every version is in the library + Delete the workspace copy; every version is on the server Save and send what is not in the library yet, then remove the copy + Save and send what is not on the server yet, then remove the copy Render with the selected preset; progress in the job bar · Ctrl+R Fix the file name first: {0} Every frame is excluded: include some in the Frames step @@ -298,6 +312,7 @@ Try to save now; saving is also retried automatically What changed, as the history will show it (optional) Save the version, and send it to the library when Sync automatically is on + Save the version, and send it to the server when Sync automatically is on {0} running on {1} Cancel the job on {0}; Retry in the notice that follows queues it again from its last checkpoint {0} paused on {1} @@ -331,32 +346,53 @@ Stay in the editor; saving is retried in the background Choose a workspace folder outside your libraries; nothing is moved The settings that differ: your value, then the library's + The settings that differ: your value, then the server's Keep your values of these settings; they are sent to the library + Keep your values of these settings; they are sent to the server Decide later and keep editing; Sync asks again The library added, removed, converted or verified photos of this sequence after the workspace copied it + Photos were added to or removed from this sequence on the server after the workspace copied it, or the server now has proxies where thumbnails stand in The library's project was saved by a newer Chronos: its settings are not merged with yours, so Keep mine and Take library's are not offered + The server's project was saved by a newer Chronos: its settings are not merged with yours, so Keep mine and Take server's are not offered Open project {0}, which holds your versionslong Keep the library's values in this project, and send yours to a new project “{0}”{0} the new project's name + Keep the server's values in this project, and send yours to a new project “{0}” Send your versions to a new project “{0}”; this project takes the library's, read-only until Chronos is updated{0} the new project's name + Send your versions to a new project “{0}”; this project takes the server's, read-only until Chronos is updated{0} the new project's name + Save the changes as a version, send it to the server, then render that version there + Keep the changes here and render nothing now Versions saved here that wait to be sent to the library: {0}. Sync sends them{0} number of versions + Versions saved here that wait to be sent to the server: {0}. Sync sends them Versions in the library this workspace has not taken yet: {0}. Sync takes them{0} number of versions + Versions on the server this workspace has not taken yet: {0}. Sync takes them You and the library changed the same settings: Sync to choose which to keep + You and the server changed the same settings: Sync to choose which to keep A version saved here cannot be read (the log names its file): nothing is saved, sent or taken until it is repairedlong This copy's project file cannot be read, so it cannot open; Remove local copy keeps its files in the workspace's trash The library no longer has this project or its sequence: nothing more can be sent; remove the local copy (its work is kept aside)long + The server no longer has this project or its sequence: nothing more can be sent; remove the local copy (its work is kept aside) Every version of this project is in the library, and nothing changed since the last one + Every version of this project is on the server, and nothing changed since the last one The workspace holds no photos of this project: opening it copies them again Changes not saved as a version yet: Save version (Ctrl+S) keeps them in the history A newer Chronos saved this copy, so this one cannot open it; update Chronos: nothing in it is changed or removed herelong The library cannot be reached now: your work stays here and is sent once it is back + The server cannot be reached now: your work stays here and is sent once it is back The library cannot be reached now. Versions waiting to be sent once it is back: {0}{0} number of versions + The server cannot be reached now. Versions waiting to be sent once it is back: {0} Asking the library where this project stands + Asking the server where this project stands Taking the library's new versions and sending yours + Taking the server's new versions and sending yours Use the library's values of these settings in the editor + Use the server's values of these settings in the editor Use the library's values of these settings; Ctrl+Z brings yours backlong + Use the server's values of these settings; Ctrl+Z brings yours backlong Bring back the project as it was before the restore Bring back your values of the settings the library's replacedlong + Bring back your values of the settings the server's replacedlong Copy the library's frames into the workspace again; the frames you excluded or keyed follow their photos + Download the server's frames into the workspace again; the frames you excluded or keyed follow their photos Import photos already in the archive again; nothing is overwritten Copy into this PC's archive with the naming templates · {0} Start the import with this card's settings as soon as it is inserted; a toast lets you cancel @@ -678,6 +714,8 @@ When this PC last compared every sequence with the server, and how long it took Open the web admin in your browser (admins only) Open in Edit on the proxies; the render runs on the server + Edit a project of this sequence in the workspace: its proxies are copied to this PC, its versions sent to the server, its renders run there + This server keeps no projects yet (it needs an update): Open with proxies edits the sequence on the server as before Pause this transfer; it resumes where it stopped Resume this transfer where it stopped The last comparison failed: {0}. It is retried automatically.{0} reason diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx index 65b01228..c74b3721 100644 --- a/i18n/it/Archive.it.resx +++ b/i18n/it/Archive.it.resx @@ -276,6 +276,7 @@ Voci vecchie nel cestino: {0}, dimensione: {1}; nulla è stato eliminato Foto controllate: {0}, integre: {1}, con impronta nuova: {2}, con problemi: {3} {0}: copiati {1}, creati {2}, invariati {3}, senza file {4} + {0}: scaricati {1}, miniature {2}, invariati {3}, senza file {4} {0}: i fotogrammi sono cambiati durante la copia; nuova copia Copia del database Simulazione diff --git a/i18n/it/Editor.it.resx b/i18n/it/Editor.it.resx index 8fa0c5f2..6159d8d0 100644 --- a/i18n/it/Editor.it.resx +++ b/i18n/it/Editor.it.resx @@ -165,6 +165,7 @@ Versioni Non inviata Libreria non in linea + Server non in linea Ripristina Uguale ad ora Cronologia di {0} @@ -228,6 +229,7 @@ Elimina progetto… Elimina Le sue versioni vengono prima inviate alla libreria, poi il progetto va nel cestino dei progetti della libreria; la sequenza e le sue foto restano. + Le sue versioni vengono prima inviate al server, poi il progetto va nel cestino dei progetti del server; la sequenza e le sue foto restano. Eliminare il progetto {0}? Cronologia… Mantieni @@ -267,6 +269,7 @@ Scartare le modifiche di {0}? File Le foto copiate su questo PC vengono eliminate; il progetto resta nella libreria e si riapre da lì. + Le foto copiate su questo PC vengono eliminate; il progetto resta sul server e si riapre da lì. Nessuna Rimuovi Prima invia @@ -357,39 +360,53 @@ Scegli cartella Più tardi {0} è stato modificato nella libreria mentre lo modificavi qui. Queste impostazioni sono diverse: tieni le tue, prendi quelle della libreria o tienile entrambe come due progetti. + {0} è stato modificato sul server mentre lo modificavi qui. Queste impostazioni sono diverse: tieni le tue, prendi quelle del server o tienile entrambe come due progetti. Salvato da un Chronos più recente {0} è stato salvato nella libreria da un Chronos più recente, le cui impostazioni questo non unisce alle tue. Tienile entrambe come due progetti, oppure aggiorna Chronos. + {0} è stato salvato sul server da un Chronos più recente, le cui impostazioni questo non unisce alle tue. Tienile entrambe come due progetti, oppure aggiorna Chronos. Prendi la libreria + Prendi il server Modificato anche nella libreria + Modificato anche sul server Copia di lavoro non riuscita Copia nello spazio di lavoro Progetto {0} creato Progetto non eliminato Progetto {0} eliminato {0} {1} qui, {2} nella libreria + {0} {1} qui, {2} sul server Modifica da parte Un Chronos più recente ha salvato questo progetto prima che la tua ultima modifica fosse memorizzata: quella modifica è tenuta da parte nella cartella del progetto, e le impostazioni più recenti si vedono in sola lettura. {0} è cambiato nella libreria mentre la tua modifica attendeva il salvataggio. Le impostazioni qui sotto sono diverse: tieni i tuoi valori o prendi quelli della libreria. + {0} è cambiato sul server mentre la tua modifica attendeva il salvataggio. Le impostazioni qui sotto sono diverse: tieni i tuoi valori o prendi quelli del server. Progetto sincronizzato Foto della libreria cambiate + Foto del server cambiate Versione non ancora inviata Niente di nuovo da salvare Libreria non in linea + Server non in linea Apri Progetto non aperto Progetto in sola lettura Copia locale non rimossa Copia locale rimossa Progetto rinominato + Render non avviato Versione {0} ripristinata Versione {0} salvata Versioni salvate come {0} Versione {0} salvata e inviata + Invia e renderizza + Il server renderizza {0} come lo conserva: salva prima le modifiche come versione e inviale. + Invia prima del render Da inviare Libreria più nuova + Server più nuovo Conflitto Danneggiato Non in libreria + Non sul server Sincronizzato Senza media Modificato @@ -400,6 +417,7 @@ Sincronizzazione non riuscita Sincronizzazione eseguita Valori della libreria presi + Valori del server presi Annulla Aggiorna media Aggiornamento media diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx index 0fc124eb..a6b9e20d 100644 --- a/i18n/it/Errors.it.resx +++ b/i18n/it/Errors.it.resx @@ -55,10 +55,13 @@ {0} non corrispondeva all'originale dopo la copia. Un file di questo progetto nello spazio di lavoro non è leggibile; il log lo indica. Questo progetto è stato eliminato nella libreria; non è stato rimosso nulla. Scarta modifiche rimuove la sua copia locale. + Questo progetto è stato eliminato sul server; non è stato rimosso nulla. Scarta modifiche rimuove la sua copia locale. Al disco dello spazio di lavoro servono altri {0} GB per questa copia. L'ultima modifica non è ancora stata memorizzata; viene ritentata, riprova tra un momento. {0} non si può usare come cartella dello spazio di lavoro; il registro dice perché. + Il tuo account non può modificare i progetti di questo server. La copia di questo progetto nella libreria non corrisponde a quanto inviato; non è stato rimosso nulla. + La copia di questo progetto sul server non corrisponde a quanto inviato; non è stato rimosso nulla. La cartella dello spazio di lavoro è dentro una libreria; non vi viene copiato nulla. La cartella dello spazio di lavoro {0} è dentro una libreria, dove Modifica non copia nulla: scegli un'altra cartella dello spazio di lavoro. {0} è dentro una libreria, dove Modifica non copia nulla: scegli una cartella fuori dalle tue librerie. @@ -68,17 +71,23 @@ Lo spazio di lavoro non ha foto di questo progetto; riaprilo per copiarle. Un altro progetto di questa sequenza ha già quel nome. Un Chronos più recente ha salvato questa copia nello spazio di lavoro; aggiorna Chronos per aprirla o rimuoverla. + Questo server non conserva progetti: va aggiornato prima di poterne modificare le sequenze nello spazio di lavoro. All'unità della cartella dello spazio di lavoro manca lo spazio per questa copia e per gli 0,5 GB che la copia lascia liberi. Il progetto non è più nello spazio di lavoro. La libreria ora non è raggiungibile; il tuo lavoro resta nello spazio di lavoro e potrà essere inviato quando torna. + Il server ora non è raggiungibile; il tuo lavoro resta nello spazio di lavoro e potrà essere inviato quando torna. Per ora lo spazio di lavoro copia i proxy; la copia degli originali arriverà in una versione successiva. Il progetto dello spazio di lavoro appartiene a un'altra sequenza. Il job di copia di lavoro non ha parametri validi. Questo progetto non è più nella libreria. + Questo progetto non è più sul server. Questo progetto è stato salvato da un Chronos più recente: si apre in sola lettura. La libreria ora è di sola lettura; il tuo lavoro resta nello spazio di lavoro e potrà essere inviato quando sarà scrivibile. La libreria ha rifiutato una versione di questo progetto; il log spiega il motivo. + Il server ha rifiutato una versione di questo progetto; il log spiega il motivo. La sequenza di questo progetto non è più nella libreria: si può solo rimuoverne la copia locale, dal menu del selettore. Parte del lavoro non è ancora nella libreria: prima inviala oppure scartala. + Parte del lavoro non è ancora sul server: prima inviala oppure scartala. Questa versione supera i {0} MB che una versione può occupare, quindi la libreria non può conservarla; il tuo lavoro resta nello spazio di lavoro. + Questa versione supera i {0} MB che una versione può occupare, quindi il server non può conservarla; il tuo lavoro resta nello spazio di lavoro. diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx index 587062d4..d5282d1c 100644 --- a/i18n/it/Server.it.resx +++ b/i18n/it/Server.it.resx @@ -197,6 +197,7 @@ Ricevi esportazioni Tieni le mie Apri con i proxy + Apri nello spazio di lavoro Pausa Riprendi Salva entrambe diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index 6bbe14be..9c5f333c 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -209,7 +209,9 @@ Mostra le impostazioni diverse tra la versione {0} e il progetto attuale Il progetto ora è questa versione Salvata qui, in attesa di essere inviata alla libreria + Salvata qui, in attesa di essere inviata al server La libreria non è raggiungibile: sono elencate le versioni che questo PC conserva + Il server non è raggiungibile: sono elencate le versioni che questo PC conserva Rendi di nuovo la versione {0} il progetto (un passo: Ctrl+Z lo annulla); le modifiche non salvate diventano prima una versione Aggiunge mosso lungo il movimento come un tempo più lungo; richiede il flusso ottico su ogni fotogramma Precisione del flusso ottico per mosso e fotogrammi sintetici; Massima è la più lenta @@ -226,13 +228,16 @@ Non applicabile: la stabilizzazione è spenta Non applicabile: lo stacking è spento Apri un progetto che la libreria ha per questa sequenza; Principale ne contiene le impostazioni attuali + Apri un progetto che il server ha per questa sequenza; Principale ne contiene le impostazioni attuali Spazio libero sull'unità della cartella dello spazio di lavoro; la copia lascia liberi anche 0,5 GB Il nome del nuovo progetto: da 1 a 60 caratteri, ogni nome una sola volta per sequenza Un nuovo progetto di questa sequenza, a partire da Principale Copia le foto del progetto nello spazio di lavoro, poi aprilo lì La copia degli originali, per renderizzare su questo PC, arriverà in un aggiornamento successivo I progetti della sequenza nella libreria + I progetti della sequenza sul server Copia i proxy: leggeri e veloci da modificare; i render usano gli originali della libreria + Scarica i proxy del server: leggeri e veloci da modificare; i render avvengono sul server, con gli originali Quanto scrive nello spazio di lavoro la copia dei proxy, come stimato prima che inizi Lascia che il consulente imposti ogni sezione dall’analisi ed elenchi cosa è cambiato Il consulente non fa mai stacking da solo: una mediana cancella le stelle in movimento @@ -261,29 +266,38 @@ Sovrappone il movimento verso il fotogramma successivo misurato dal motore Trascina la linea per confrontare · trascina per spostare · la rotellina ingrandisce · doppio clic 1:1 Invia le versioni di questo progetto alla libreria, poi spostalo nel cestino dei progetti della libreria + Invia le versioni di questo progetto al server, poi spostalo nel cestino dei progetti del server Sposta il progetto, con tutte le sue versioni, nel cestino dei progetti della libreria + Sposta il progetto, con tutte le sue versioni, nel cestino dei progetti del server Le versioni del progetto: confrontane una con lo stato attuale o ripristinala Tieni il progetto com'è Progetto {0} ({1}): salva una versione, sincronizza, cronologia, altri progetti e copia locale Crea un altro progetto di questa sequenza a partire da questo (per esempio un taglio verticale per i social) Apri un altro progetto di questa sequenza: uno della libreria o uno nuovo Libera spazio su questo PC: elimina le foto copiate nello spazio di lavoro; il progetto resta nella libreria + Libera spazio su questo PC: elimina le foto copiate nello spazio di lavoro; il progetto resta sul server Dai un altro nome a questo progetto, qui e nella libreria + Dai un altro nome a questo progetto, qui e sul server Tieni il progetto com'è ora come versione della sua cronologia, con una nota facoltativa (Ctrl+S) I file di progetto sono per le sequenze di un archivio su questo PC Applica di nuovo le impostazioni del file di progetto Salva un file .chronos che, con un doppio clic, apre questa sequenza con queste impostazioni Ripristina le impostazioni che la sequenza aveva prima di aprire il file · Ctrl+Z Rinomina il progetto qui e nella libreria + Rinomina il progetto qui e sul server Crea il progetto nella libreria e aprilo nello spazio di lavoro + Crea il progetto sul server e aprilo nello spazio di lavoro Da 1 a 60 caratteri, ogni nome una sola volta per sequenza Il tuo account può vedere questa sequenza del server ma non modificarla Modificata con i proxy su questo PC; le modifiche si salvano su {0} e analisi e render vengono eseguiti lì Mostrata da {0}; il tuo account può vedere questa sequenza ma non modificarla Rimuovi la copia senza inviare ciò che non è nella libreria; quel lavoro resta da parte nel cestino dello spazio di lavoro + Rimuovi la copia senza inviare ciò che non è sul server; quel lavoro resta da parte nel cestino dello spazio di lavoro Mantieni la copia locale com'è Elimina la copia di lavoro; ogni versione è nella libreria + Elimina la copia di lavoro; ogni versione è sul server Salva e invia ciò che non è ancora nella libreria, poi rimuovi la copia + Salva e invia ciò che non è ancora sul server, poi rimuovi la copia Renderizza con il preset scelto; avanzamento nella barra dei lavori · Ctrl+R Correggi prima il nome del file: {0} Tutti i fotogrammi sono esclusi: includine alcuni nel passo Fotogrammi @@ -298,6 +312,7 @@ Prova a salvare ora; il salvataggio viene anche ritentato da solo Cosa è cambiato, come lo mostrerà la cronologia (facoltativo) Salva la versione e inviala alla libreria quando la sincronizzazione automatica è attiva + Salva la versione e inviala al server quando la sincronizzazione automatica è attiva {0} in corso su {1} Annulla l’attività su {0}; Riprova nell’avviso che segue la rimette in coda dall’ultimo punto di ripresa {0} in pausa su {1} @@ -330,32 +345,53 @@ Resta nell’editor; il salvataggio viene ritentato in background Scegli una cartella dello spazio di lavoro fuori dalle tue librerie; non viene spostato nulla Le impostazioni diverse: il tuo valore, poi quello della libreria + Le impostazioni diverse: il tuo valore, poi quello del server Tieni i tuoi valori di queste impostazioni; vengono inviati alla libreria + Tieni i tuoi valori di queste impostazioni; vengono inviati al server Decidi più tardi e continua a modificare; Sincronizza lo chiede di nuovo La libreria ha aggiunto, tolto, convertito o verificato foto di questa sequenza dopo che lo spazio di lavoro l'ha copiata + Sono state aggiunte o tolte foto a questa sequenza sul server dopo che lo spazio di lavoro l'ha copiata, oppure il server ora ha i proxy dove ci sono miniature Il progetto della libreria è stato salvato da un Chronos più recente: le sue impostazioni non si uniscono alle tue, quindi Tieni le mie e Prendi la libreria non sono proposti + Il progetto del server è stato salvato da un Chronos più recente: le sue impostazioni non si uniscono alle tue, quindi Tieni le mie e Prendi dal server non sono proposti Apri il progetto {0}, che contiene le tue versioni Tieni i valori della libreria in questo progetto e invia i tuoi a un nuovo progetto «{0}» + Tieni i valori del server in questo progetto e invia i tuoi a un nuovo progetto «{0}» Invia le tue versioni a un nuovo progetto «{0}»; questo progetto prende quello della libreria, in sola lettura finché Chronos non viene aggiornato + Invia le tue versioni a un nuovo progetto «{0}»; questo progetto prende quello del server, in sola lettura finché Chronos non viene aggiornato + Salva le modifiche come versione, inviala al server, poi renderizza lì quella versione + Tieni le modifiche qui e per ora non renderizzare Versioni salvate qui in attesa di essere inviate alla libreria: {0}. Sincronizza le invia + Versioni salvate qui in attesa di essere inviate al server: {0}. Sincronizza le invia Versioni nella libreria non ancora prese da questo spazio di lavoro: {0}. Sincronizza le prende + Versioni sul server non ancora prese da questo spazio di lavoro: {0}. Sincronizza le prende Tu e la libreria avete modificato le stesse impostazioni: sincronizza per scegliere quali tenere + Tu e il server avete modificato le stesse impostazioni: sincronizza per scegliere quali tenere Una versione salvata qui non è leggibile (il log indica il file): nulla viene salvato, inviato o ricevuto finché non è riparata Il file di progetto di questa copia non si può leggere, quindi non si apre; Rimuovi copia locale ne tiene i file nel cestino dello spazio di lavoro La libreria non ha più questo progetto o la sua sequenza: non si può più inviare nulla; rimuovi la copia locale (il suo lavoro resta da parte) + Il server non ha più questo progetto o la sua sequenza: non si può più inviare nulla; rimuovi la copia locale (il suo lavoro resta da parte) Ogni versione di questo progetto è nella libreria e nulla è cambiato dall'ultima + Ogni versione di questo progetto è sul server e nulla è cambiato dall'ultima Lo spazio di lavoro non ha foto di questo progetto: aprirlo le copia di nuovo Modifiche non ancora salvate come versione: Salva versione (Ctrl+S) le tiene nella cronologia Un Chronos più recente ha salvato questa copia, quindi questo non può aprirla; aggiorna Chronos: qui nulla viene cambiato o rimosso La libreria ora non è raggiungibile: il tuo lavoro resta qui e viene inviato quando torna + Il server ora non è raggiungibile: il tuo lavoro resta qui e viene inviato quando torna La libreria ora non è raggiungibile. Versioni in attesa di essere inviate quando torna: {0} + Il server ora non è raggiungibile. Versioni in attesa di essere inviate quando torna: {0} Chiede alla libreria lo stato di questo progetto + Chiede al server lo stato di questo progetto Prende le nuove versioni della libreria e invia le tue + Prende le nuove versioni del server e invia le tue Usa nell'editor i valori della libreria per queste impostazioni + Usa nell'editor i valori del server per queste impostazioni Usa i valori della libreria per queste impostazioni; Ctrl+Z riporta i tuoi + Usa i valori del server per queste impostazioni; Ctrl+Z riporta i tuoi Riporta il progetto com'era prima del ripristino Riporta i tuoi valori delle impostazioni sostituite da quelli della libreria + Riporta i tuoi valori delle impostazioni sostituite da quelli del server Copia di nuovo i fotogrammi della libreria nello spazio di lavoro; i fotogrammi esclusi o con keyframe seguono le loro foto + Scarica di nuovo i fotogrammi del server nello spazio di lavoro; i fotogrammi esclusi o con keyframe seguono le loro foto Importa di nuovo le foto già in archivio; nulla viene sovrascritto Copia nell'archivio di questo PC con i modelli dei nomi · {0} Avvia l'importazione con le impostazioni della scheda appena viene inserita; un avviso permette di annullare @@ -676,6 +712,8 @@ Quando questo PC ha confrontato per l'ultima volta tutte le sequenze con il server, e quanto ha impiegato Apri l'amministrazione web nel browser (solo amministratori) Apri in Modifica sui proxy; il rendering avviene sul server + Modifica un progetto di questa sequenza nello spazio di lavoro: i suoi proxy vengono copiati su questo PC, le versioni inviate al server e i render avvengono lì + Questo server non conserva ancora progetti (va aggiornato): Apri con i proxy modifica la sequenza sul server come prima Metti in pausa questo trasferimento; riprende da dove si è fermato Riprendi questo trasferimento da dove si è fermato L'ultimo confronto non è riuscito: {0}. Viene ripetuto automaticamente. diff --git a/src/Chronos.App/Editor/EditorViewModel.cs b/src/Chronos.App/Editor/EditorViewModel.cs index 5e8fa221..c36674aa 100644 --- a/src/Chronos.App/Editor/EditorViewModel.cs +++ b/src/Chronos.App/Editor/EditorViewModel.cs @@ -625,6 +625,8 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable /// public async Task RenderAsync(JobPriority priority, bool batch) { + // A workspace project whose home is a server renders what the server holds: changes not sent are offered to be sent first (phase 5b). + if (Project is { } project && !await project.ReadyToRenderAsync()) return; // The job embeds the project: its frame positions follow frames inserted since the editor read them first. A server // sequence whose frames changed is outdated instead, and its toast says so and offers fresh proxies. await Session.EnsureFramesAsync(); @@ -1074,22 +1076,25 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable private void OnConflictFound(ProjectConflictException conflict) => _dispatcher.BeginInvoke(() => { if (_disposed || Session.Conflict is null) return; - var request = Session.Source is WorkspaceSequenceSource ? LibraryConflictRequest(conflict, Title) : ConflictRequest(conflict, Title, ServerName ?? string.Empty); + var request = Session.Source is WorkspaceSequenceSource workspace ? LibraryConflictRequest(conflict, Title, workspace.IsServerHome) : ConflictRequest(conflict, Title, ServerName ?? string.Empty); var keepMine = Shell.Services.Dialogs.Confirm(request); if (!_disposed) Session.ResolveConflict(keepMine); }); - /// The conflict prompt of a workspace project: what differs (the editor's value, then the library's) and what each choice keeps. - internal static ConfirmRequest LibraryConflictRequest(ProjectConflictException conflict, string title) => new() + /// + /// The conflict prompt of a workspace project: what differs (the editor's value, then the home's) and what each choice + /// keeps, worded for a home (phase 5b) or the library. + /// + internal static ConfirmRequest LibraryConflictRequest(ProjectConflictException conflict, string title, bool server = false) => new() { Heading = Loc.L("Editor.Workspace.Conflict.Title"), - Message = Loc.L("Editor.Workspace.Edited.Message", title), - Detail = string.Join(Environment.NewLine, WorkspaceText.ConflictLines(conflict.Differences, 10)), - DetailToolTip = Loc.L("Tooltips.Editor.Workspace.Differences"), - SafeText = Loc.L("Editor.Workspace.Conflict.TakeHome"), - SafeToolTip = Loc.L("Tooltips.Editor.Workspace.TakeHomeUndo"), + Message = WorkspaceText.ForHome("Editor.Workspace.Edited.Message", server, title), + Detail = string.Join(Environment.NewLine, WorkspaceText.ConflictLines(conflict.Differences, 10, server)), + DetailToolTip = WorkspaceText.ForHome("Tooltips.Editor.Workspace.Differences", server), + SafeText = WorkspaceText.ForHome("Editor.Workspace.Conflict.TakeHome", server), + SafeToolTip = WorkspaceText.ForHome("Tooltips.Editor.Workspace.TakeHomeUndo", server), ActionText = Loc.L("Server.Sync.Action.KeepMine"), - ActionToolTip = Loc.L("Tooltips.Editor.Workspace.KeepMine"), + ActionToolTip = WorkspaceText.ForHome("Tooltips.Editor.Workspace.KeepMine", server), IsDestructive = true, }; diff --git a/src/Chronos.App/Editor/RemoteSequenceSource.cs b/src/Chronos.App/Editor/RemoteSequenceSource.cs index 48b63756..4675640f 100644 --- a/src/Chronos.App/Editor/RemoteSequenceSource.cs +++ b/src/Chronos.App/Editor/RemoteSequenceSource.cs @@ -38,17 +38,12 @@ namespace Chronos.App.Editor; public sealed class RemoteSequenceSource : ISequenceSource { private const int SaveAttempts = 3; - private static readonly TimeSpan MinBackoff = TimeSpan.FromSeconds(2); - private static readonly TimeSpan MaxBackoff = TimeSpan.FromMinutes(1); private readonly RemoteSequence _remote; private readonly IRemoteSequenceApi _api; private readonly IRenderFrameSource _frames; private readonly IFrameSource _pixels; - private readonly ConcurrentDictionary _jobs = new(); - private readonly ConcurrentDictionary _foreign = new(); - private readonly CancellationTokenSource _stopping = new(); - private readonly Task _listening; + private readonly ServerJobs _jobs; private readonly bool _noEditRight; private Stored? _stored; private int _framesVersion = -1; @@ -66,8 +61,7 @@ public sealed class RemoteSequenceSource : ISequenceSource _noEditRight = readOnly; _frames = remote.OpenFrames(decoder); _pixels = (IFrameSource)_frames; - var stopping = _stopping.Token; - _listening = Task.Run(() => ListenAsync(stopping), CancellationToken.None); + _jobs = new ServerJobs(api, remote.Sequence.Id, remote.Sequence.DisplayTitle, job => JobChanged?.Invoke(job), OnEventAsync, OnReconnectedAsync); } public bool IsRemote => true; @@ -190,126 +184,44 @@ public sealed class RemoteSequenceSource : ISequenceSource /// The server queues every job at the user's priority; another priority ("Add to queue") is set right after. A /// render embeds the project, whose frame positions mean nothing once the frames changed: refused while outdated. /// - public async Task SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken) + public Task SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(request); if (request.Kind == JobKind.Render && IsOutdated) throw new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged")); - var dto = await Call(() => _api.CreateJobAsync(new CreateJobRequest(JobWire.Kind(request.Kind), request.Targets, request.ParametersJson), cancellationToken)); - if (request.Priority != JobPriority.User) dto = await PrioritiseAsync(dto, request.Priority, cancellationToken); - // The server's events may have reported the job already; its first state never replaces a later one. - if (JobWire.FromDto(dto) is { } job && _jobs.TryAdd(job.Id, job)) JobChanged?.Invoke(job); - return dto.Id; + return _jobs.SubmitAsync(request, cancellationToken); } - public async Task> ListJobsAsync(CancellationToken cancellationToken) - { - var active = await Call(() => _api.ListActiveJobsAsync(cancellationToken)); - var mine = active.Select(JobWire.FromDto).OfType().Where(Concerns).ToList(); - foreach (var job in mine) _jobs[job.Id] = job; - return mine; - } + public Task> ListJobsAsync(CancellationToken cancellationToken) => _jobs.ListAsync(cancellationToken); - public async Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) - { - if (JobWire.FromDto(await _api.CancelJobAsync(jobId, cancellationToken)) is { } job) Publish(job); - } + public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) => _jobs.CancelAsync(jobId, cancellationToken); - public async Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) - { - if (JobWire.FromDto(await _api.RetryJobAsync(jobId, cancellationToken)) is { } job) Publish(job); - } + public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) => _jobs.RetryAsync(jobId, cancellationToken); public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref _disposed, 1) == 1) return; try { - await _stopping.CancelAsync(); - await _listening; + // Stops following the events, and closes the connection. + await _jobs.DisposeAsync(); } finally { - _stopping.Dispose(); if (_frames is IAsyncDisposable frames) await frames.DisposeAsync(); - _api.Dispose(); - } - } - - /// - /// Follows the server's events until the editor closes, reconnecting with a growing delay (job states lost meanwhile - /// are read back from the jobs, and the frames are compared again). Nothing that fails on the way ends it. - /// - private async Task ListenAsync(CancellationToken cancellationToken) - { - var failures = 0; - while (true) - { - try - { - await foreach (var e in _api.EventsAsync(cancellationToken).ConfigureAwait(false)) - { - failures = 0; - await OnEventAsync(e, cancellationToken).ConfigureAwait(false); - } - } - catch (Exception ex) when (ex is not OutOfMemoryException) - { - if (cancellationToken.IsCancellationRequested) return; - Log.Info("editor", $"Events of the server lost for {_remote.Sequence.DisplayTitle}: {ex.Message}"); - } - try - { - var delay = Math.Min(MaxBackoff.Ticks, MinBackoff.Ticks << Math.Min(failures++, 10)); - await Task.Delay(TimeSpan.FromTicks(delay), cancellationToken).ConfigureAwait(false); - await RefreshTrackedAsync(cancellationToken).ConfigureAwait(false); - // A frames change announced while the socket was down is found now rather than at the next save. - if (Volatile.Read(ref _framesVersion) >= 0) await CheckFramesAsync(cancellationToken).ConfigureAwait(false); - } - catch (Exception ex) when (ex is not OutOfMemoryException) - { - if (cancellationToken.IsCancellationRequested) return; - Log.Info("editor", $"Jobs of {_remote.Sequence.DisplayTitle} could not be read again: {ex.Message}"); - } } } + /// The server's events besides the jobs': frames added or removed on the server make the sequence outdated. private async Task OnEventAsync(ServerEvent e, CancellationToken cancellationToken) { - switch (e) - { - case SequenceChangedEvent changed when changed.SequenceId == Id && changed.FramesVersion != Volatile.Read(ref _framesVersion): - await CheckFramesAsync(cancellationToken).ConfigureAwait(false); - break; - // A late progress event never brings a finished job back to running. - case JobProgressEvent progress when _jobs.TryGetValue(progress.JobId, out var job) && job.State is JobState.Queued or JobState.Running: - Publish(job with - { - State = JobState.Running, - ProgressDone = progress.Done, - ProgressTotal = progress.Total, - ItemsPerSecond = progress.ItemsPerSecond, - Eta = JobEta.FromSeconds(progress.EtaSeconds), - }); - break; - case JobStateEvent state when !_foreign.ContainsKey(state.JobId): - await FetchAsync(state.JobId, cancellationToken).ConfigureAwait(false); - break; - } + if (e is SequenceChangedEvent changed && changed.SequenceId == Id && changed.FramesVersion != Volatile.Read(ref _framesVersion)) + await CheckFramesAsync(cancellationToken).ConfigureAwait(false); } - /// Reads a job the events named: tracked when it concerns this sequence, remembered as foreign otherwise. - private async Task FetchAsync(Guid jobId, CancellationToken cancellationToken) + /// A frames change announced while the event socket was down is found now rather than at the next save. + private async Task OnReconnectedAsync(CancellationToken cancellationToken) { - try - { - if (JobWire.FromDto(await _api.GetJobAsync(jobId, cancellationToken).ConfigureAwait(false)) is { } job && Concerns(job)) Publish(job); - else _foreign[jobId] = 0; - } - catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or JsonException - || (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested)) - { - Log.Info("editor", $"Job {jobId} could not be read: {ex.Message}"); - } + if (Volatile.Read(ref _framesVersion) >= 0) await CheckFramesAsync(cancellationToken).ConfigureAwait(false); } /// Frames added or removed on the server: whether this PC's frames are still the sequence's. @@ -326,34 +238,6 @@ public sealed class RemoteSequenceSource : ISequenceSource } } - /// Sets a priority other than the user's on a job the server just queued; the job stays queued if that fails. - private async Task PrioritiseAsync(JobDto dto, JobPriority priority, CancellationToken cancellationToken) - { - try - { - return await _api.SetJobPriorityAsync(dto.Id, JobWire.Priority(priority), cancellationToken); - } - catch (Exception ex) when (ex is ChronosApiException or HttpRequestException) - { - // Already claimed (409) or refused: the job runs at the user's priority, which is never later than asked. - Log.Info("editor", $"Job {dto.Id} keeps the user's priority on the server: {ex.Message}"); - return dto; - } - } - - /// After a lost event socket: the tracked jobs as the server has them now. - private async Task RefreshTrackedAsync(CancellationToken cancellationToken) - { - foreach (var job in _jobs.Values.Where(j => j.State is JobState.Queued or JobState.Running or JobState.Paused).ToList()) - await FetchAsync(job.Id, cancellationToken).ConfigureAwait(false); - } - - private void Publish(Job job) - { - _jobs[job.Id] = job; - JobChanged?.Invoke(job); - } - /// /// Takes the server's frames as lists them: their frames version when they are this PC's /// (saves name it), outdated otherwise. Returns whether they are. @@ -387,8 +271,6 @@ public sealed class RemoteSequenceSource : ISequenceSource ReadOnlyChanged?.Invoke(); } - private bool Concerns(Job job) => job.TargetIds.Contains(Id) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render; - /// The frame of the project's hero, or (the first frame shows) without one. private Guid HeroFrameId(ProjectSettings project) => project.HeroFrame is { } hero && (uint)hero < (uint)_remote.Frames.Count ? _remote.Frames[hero].Id : Guid.Empty; @@ -424,17 +306,7 @@ public sealed class RemoteSequenceSource : ISequenceSource } /// A sequence deleted on the server reads as gone, like a local one removed from the index. - private static async Task Call(Func> call) - { - try - { - return await call(); - } - catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound) - { - throw new EditorException(Loc.L("Editor.Error.Missing"), ex); - } - } + private static Task Call(Func> call) => ServerJobs.Call(call); /// The server's settings as last read or written, with the version a save must name. private sealed record Stored(ProjectSettings Project, int Version); diff --git a/src/Chronos.App/Editor/ServerJobs.cs b/src/Chronos.App/Editor/ServerJobs.cs new file mode 100644 index 00000000..f1cd4570 --- /dev/null +++ b/src/Chronos.App/Editor/ServerJobs.cs @@ -0,0 +1,225 @@ +using System.Collections.Concurrent; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using Chronos.Core.Diagnostics; +using Chronos.Core.Localization; +using Chronos.Core.Model; +using Chronos.Data.Archiving.Jobs; +using Chronos.Data.Jobs; +using Chronos.Protocol; +using Chronos.Protocol.Client; + +namespace Chronos.App.Editor; + +/// +/// The analyses and renders of one server sequence as an editor follows them (BRIEF §14.5): queued through the API (the +/// server queues each at the user's priority, another one is set right after), their states and progress taken from the +/// server's events, the jobs followed read again whenever the event socket comes back after a loss (reconnecting with a +/// growing delay; nothing that fails on the way ends it). What a server sequence opened with proxies +/// () and a workspace project whose home is a server (, +/// owner review 2, R8) run on the server. Events of other kinds go to other; reconnected runs after the jobs +/// were read again. Owns the connection: disposing stops listening and disposes it. +/// +internal sealed class ServerJobs : IAsyncDisposable +{ + private static readonly TimeSpan MinBackoff = TimeSpan.FromSeconds(2); + private static readonly TimeSpan MaxBackoff = TimeSpan.FromMinutes(1); + + private readonly Guid _sequenceId; + private readonly string _title; + private readonly Action _changed; + private readonly Func? _other; + private readonly Func? _reconnected; + private readonly ConcurrentDictionary _jobs = new(); + private readonly ConcurrentDictionary _foreign = new(); + private readonly CancellationTokenSource _stopping = new(); + private readonly Task _listening; + private int _disposed; + + /// A job of the sequence changed (any thread). + public ServerJobs(IRemoteSequenceApi api, Guid sequenceId, string title, Action changed, Func? other = null, + Func? reconnected = null) + { + ArgumentNullException.ThrowIfNull(api); + ArgumentNullException.ThrowIfNull(changed); + Api = api; + _sequenceId = sequenceId; + _title = title; + _changed = changed; + _other = other; + _reconnected = reconnected; + var stopping = _stopping.Token; + _listening = Task.Run(() => ListenAsync(stopping), CancellationToken.None); + } + + /// The connection the jobs travel on (the source's other calls use it too). + public IRemoteSequenceApi Api { get; } + + /// Queues on the server (its priority set after, when it is not the user's); returns the job id. + /// The sequence is gone from the server. + public async Task SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + var dto = await Call(() => Api.CreateJobAsync(new CreateJobRequest(JobWire.Kind(request.Kind), request.Targets, request.ParametersJson), cancellationToken)); + if (request.Priority != JobPriority.User) dto = await PrioritiseAsync(dto, request.Priority, cancellationToken); + // The server's events may have reported the job already; its first state never replaces a later one. + if (JobWire.FromDto(dto) is { } job && _jobs.TryAdd(job.Id, job)) _changed(job); + return dto.Id; + } + + /// The analyses and renders of the sequence waiting, running or paused on the server, followed from now on. + public async Task> ListAsync(CancellationToken cancellationToken) + { + var active = await Call(() => Api.ListActiveJobsAsync(cancellationToken)); + var mine = active.Select(JobWire.FromDto).OfType().Where(Concerns).ToList(); + foreach (var job in mine) _jobs[job.Id] = job; + return mine; + } + + public async Task CancelAsync(Guid jobId, CancellationToken cancellationToken) + { + if (JobWire.FromDto(await Api.CancelJobAsync(jobId, cancellationToken)) is { } job) Publish(job); + } + + public async Task RetryAsync(Guid jobId, CancellationToken cancellationToken) + { + if (JobWire.FromDto(await Api.RetryJobAsync(jobId, cancellationToken)) is { } job) Publish(job); + } + + public async ValueTask DisposeAsync() + { + if (Interlocked.Exchange(ref _disposed, 1) == 1) return; + try + { + await _stopping.CancelAsync(); + await _listening; + } + finally + { + _stopping.Dispose(); + Api.Dispose(); + } + } + + /// + /// Follows the server's events until disposed, reconnecting with a growing delay (job states lost meanwhile are read + /// back from the jobs, then reconnected runs). Nothing that fails on the way ends it. + /// + private async Task ListenAsync(CancellationToken cancellationToken) + { + var failures = 0; + while (true) + { + try + { + await foreach (var e in Api.EventsAsync(cancellationToken).ConfigureAwait(false)) + { + failures = 0; + await OnEventAsync(e, cancellationToken).ConfigureAwait(false); + } + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + if (cancellationToken.IsCancellationRequested) return; + Log.Info("editor", $"Events of the server lost for {_title}: {ex.Message}"); + } + try + { + var delay = Math.Min(MaxBackoff.Ticks, MinBackoff.Ticks << Math.Min(failures++, 10)); + await Task.Delay(TimeSpan.FromTicks(delay), cancellationToken).ConfigureAwait(false); + await RefreshTrackedAsync(cancellationToken).ConfigureAwait(false); + if (_reconnected is not null) await _reconnected(cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + if (cancellationToken.IsCancellationRequested) return; + Log.Info("editor", $"Jobs of {_title} could not be read again: {ex.Message}"); + } + } + } + + private async Task OnEventAsync(ServerEvent e, CancellationToken cancellationToken) + { + switch (e) + { + // A late progress event never brings a finished job back to running. + case JobProgressEvent progress when _jobs.TryGetValue(progress.JobId, out var job) && job.State is JobState.Queued or JobState.Running: + Publish(job with + { + State = JobState.Running, + ProgressDone = progress.Done, + ProgressTotal = progress.Total, + ItemsPerSecond = progress.ItemsPerSecond, + Eta = JobEta.FromSeconds(progress.EtaSeconds), + }); + break; + case JobProgressEvent: + break; + case JobStateEvent state: + if (!_foreign.ContainsKey(state.JobId)) await FetchAsync(state.JobId, cancellationToken).ConfigureAwait(false); + break; + default: + if (_other is not null) await _other(e, cancellationToken).ConfigureAwait(false); + break; + } + } + + /// Reads a job the events named: tracked when it concerns this sequence, remembered as foreign otherwise. + private async Task FetchAsync(Guid jobId, CancellationToken cancellationToken) + { + try + { + if (JobWire.FromDto(await Api.GetJobAsync(jobId, cancellationToken).ConfigureAwait(false)) is { } job && Concerns(job)) Publish(job); + else _foreign[jobId] = 0; + } + catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or JsonException + || (ex is OperationCanceledException && !cancellationToken.IsCancellationRequested)) + { + Log.Info("editor", $"Job {jobId} could not be read: {ex.Message}"); + } + } + + /// Sets a priority other than the user's on a job the server just queued; the job stays queued if that fails. + private async Task PrioritiseAsync(JobDto dto, JobPriority priority, CancellationToken cancellationToken) + { + try + { + return await Api.SetJobPriorityAsync(dto.Id, JobWire.Priority(priority), cancellationToken); + } + catch (Exception ex) when (ex is ChronosApiException or HttpRequestException) + { + // Already claimed (409) or refused: the job runs at the user's priority, which is never later than asked. + Log.Info("editor", $"Job {dto.Id} keeps the user's priority on the server: {ex.Message}"); + return dto; + } + } + + /// After a lost event socket: the tracked jobs as the server has them now. + private async Task RefreshTrackedAsync(CancellationToken cancellationToken) + { + foreach (var job in _jobs.Values.Where(j => j.State is JobState.Queued or JobState.Running or JobState.Paused).ToList()) + await FetchAsync(job.Id, cancellationToken).ConfigureAwait(false); + } + + private void Publish(Job job) + { + _jobs[job.Id] = job; + _changed(job); + } + + private bool Concerns(Job job) => job.TargetIds.Contains(_sequenceId) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render; + + /// A sequence deleted on the server reads as gone, like a local one removed from the index. + internal static async Task Call(Func> call) + { + try + { + return await call(); + } + catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound) + { + throw new EditorException(Loc.L("Editor.Error.Missing"), ex); + } + } +} diff --git a/src/Chronos.App/Editor/WorkspaceSequenceSource.cs b/src/Chronos.App/Editor/WorkspaceSequenceSource.cs index 477bc522..2dbbf536 100644 --- a/src/Chronos.App/Editor/WorkspaceSequenceSource.cs +++ b/src/Chronos.App/Editor/WorkspaceSequenceSource.cs @@ -19,6 +19,8 @@ using Chronos.Data.Processing; using Chronos.Data.Projects; using Chronos.Data.Workspaces; using Chronos.Protocol; +using Chronos.Protocol.Client; +using SequenceManifest = Chronos.Protocol.SequenceManifest; namespace Chronos.App.Editor; @@ -29,6 +31,13 @@ public interface IProjectRenders IReadOnlyList RenderRequests(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight); } +/// +/// A workspace project's home when it is a server (owner review 2, R8, phase 5b): the connection its analyses and renders +/// travel on, which the source owns; null while this PC is not signed in to that server (the project still opens from the +/// workspace, its jobs are refused saying so). +/// +public sealed record WorkspaceServerHome(IRemoteSequenceApi? Api); + /// /// A workspace project open in the editor (owner review 2, R8: editing happens in the workspace, never inside the /// library): the frames and pixels of the media the workspace holds (media/media.json, the proxies), the project @@ -42,6 +51,11 @@ public interface IProjectRenders /// (). The deep report is the home's while its frames are the media's, else the copy the /// workspace took. A copy job that changed the media (Update media) makes saves made against the frames read before refused /// () until the editor has read them again and moved its positions by frame. +/// A project whose home is a server (, phase 5b) is a remote one for the editor: its +/// analyses and renders are the server's jobs (), a render of the version the server holds when the +/// project is in step with it (else of the project's portable settings, recording the project), its deep report and renders +/// are read from the server when it can be reached (else the copy the workspace took), and "Update media" is offered when +/// the server's frames moved, or it has the proxy of a frame a thumbnail stands in for. /// public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders { @@ -51,19 +65,23 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders private readonly ChronosDatabase _db; private readonly ImageDecoder _decoder; private readonly JobEngine? _engine; + private readonly WorkspaceServerHome? _server; private readonly Lock _gate = new(); private readonly List _retired = []; private IRenderFrameSource? _frames; private IFrameSource? _pixels; + private ServerJobs? _serverJobs; private int _frameCount; private int _framesVersion = -1; private Guid[] _frameIds = []; + private HashSet _standIns = []; private FramePhotos _photos = new([]); private BundleWorkspace? _workspace; private bool _readOnly; private int _disposed; - public WorkspaceSequenceSource(WorkspaceSync sync, Guid projectId, ChronosDatabase db, ImageDecoder decoder, JobEngine? engine) + /// The server the project's home is (phase 5b); null for a project of this PC's archive. + public WorkspaceSequenceSource(WorkspaceSync sync, Guid projectId, ChronosDatabase db, ImageDecoder decoder, JobEngine? engine, WorkspaceServerHome? server = null) { ArgumentNullException.ThrowIfNull(sync); ArgumentNullException.ThrowIfNull(db); @@ -72,7 +90,9 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders _db = db; _decoder = decoder; _engine = engine; + _server = server; ProjectId = projectId; + // This PC's engine runs the copies of the media (Update media), whatever the home. if (engine is not null) engine.JobChanged += OnJobChanged; } @@ -90,7 +110,11 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders /// The photos of the media read last, in frame order (what positions name). public FramePhotos Photos => Volatile.Read(ref _photos); - public bool IsRemote => false; + /// The project's home is a server (phase 5b): its analyses and renders run there. + public bool IsServerHome => _server is not null; + + /// A server home's analyses and renders run on the server, as for a server sequence opened with proxies. + public bool IsRemote => _server is not null; /// Settings of a newer Chronos: shown, never saved. public bool IsReadOnly => Volatile.Read(ref _readOnly); @@ -132,6 +156,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders } if (session is not { Sequence: { } media, Media: { } index }) throw new EditorException(Loc.L("Errors.Workspace.MediaMissing")); var home = session.Bundle.Workspace!.Home; + if (_server is not null) return await LoadFromServerAsync(session, media, index, home, cancellationToken); var row = await _db.Sequences.GetAsync(home.SequenceId, cancellationToken); var archive = row is null ? null : await _db.Archives.GetAsync(row.ArchiveId, cancellationToken); IReadOnlyList renders = row is null ? [] : await _db.Renders.ListBySequenceAsync(home.SequenceId, cancellationToken); @@ -160,6 +185,123 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders }, cancellationToken); } + /// + /// A project whose home is a server: the media's frames and the working state as for any workspace project, with what + /// the server says of its sequence when it can be reached (title, camera, tags, renders, and its deep report while its + /// frames are the media's); the copy the workspace took of the report otherwise. The server's jobs are followed from + /// the first read on. + /// + private async Task LoadFromServerAsync(WorkspaceSession session, WorkspaceSequence media, WorkspaceMedia index, BundleHome home, + CancellationToken cancellationToken) + { + var jobs = ServerJobsOf(home.SequenceId, session.Bundle.Sequence.Title ?? media.Sequence.DisplayTitle); + SequenceDto? dto = null; + SequenceManifest? manifest = null; + string? report = null; + if (jobs is not null) + { + try + { + dto = await jobs.Api.GetSequenceAsync(home.SequenceId, cancellationToken); + manifest = await jobs.Api.GetManifestAsync(home.SequenceId, cancellationToken); + // The server's report only while its frames are the ones this workspace holds. + if (manifest.FramesVersion == index.FramesVersion) report = await jobs.Api.GetAnalysisReportAsync(home.SequenceId, cancellationToken); + } + catch (Exception ex) when (ServerProjectHome.IsUnavailable(ex, cancellationToken) || ex is ChronosApiException) + { + // Out of reach (or the sequence gone there): the workspace's own copy opens all the same. + Log.Info("editor", $"The server's view of workspace project {ProjectId} is not read now: {ex.Message}"); + } + } + return await Task.Run(() => + { + var frames = media.Frames; + Swap(media, index, session.Bundle.Workspace!, session.IsReadOnly); + var times = frames.Where(f => f.CapturedAt is not null).Select(f => f.CapturedAt!.Value).Order().ToList(); + var sequence = media.Sequence with + { + FrameCount = frames.Count, + FramesVersion = index.FramesVersion, + FirstCapture = times.Count > 0 ? times[0] : null, + LastCapture = times.Count > 0 ? times[^1] : null, + SettingsJson = session.Working.ToJson(), + }; + if (dto is not null) + { + sequence = sequence with + { + Title = dto.Title, + CameraMake = dto.CameraMake, + CameraModel = dto.CameraModel, + Lens = dto.Lens, + MedianInterval = dto.MedianInterval, + Tags = dto.Tags, + Rating = dto.Rating, + Notes = dto.Notes, + Status = (SequenceStatus)dto.Status, + RenderedCount = dto.RenderedCount, + WarningCount = dto.WarningCount, + PreviewOnlyCount = dto.PreviewOnlyCount, + OwnerUserId = dto.OwnerUserId, + UpdatedAt = dto.UpdatedAt, + }; + } + var renders = manifest?.Renders.OrderByDescending(r => r.Created).Select(r => new Render + { + Id = r.Id, + SequenceId = home.SequenceId, + PresetName = r.PresetName, + OutputPath = string.Empty, + Codec = r.Codec, + Width = r.Width, + Height = r.Height, + Fps = r.Fps, + DurationSeconds = r.DurationSeconds, + Bytes = r.Bytes, + Created = r.Created, + ProducedBy = r.ProducedBy, + }).ToList() ?? []; + var (deep, otherFrames) = ServerReport(report, session.Project.AnalysisPath, frames.Count); + var context = SequenceContext.FromFrames(frames); + return new SequenceContent(sequence, frames, session.Working, LightAnalyzer.Analyze(frames), deep, context.SourceWidth, context.SourceHeight, null, renders, []) + { + DeepOfOtherFrames = otherFrames, + }; + }, cancellationToken); + } + + /// The server's jobs of the sequence, followed from now on; null while this PC is not signed in to the server. + private ServerJobs? ServerJobsOf(Guid sequenceId, string title) + { + if (_server?.Api is not { } api) return null; + lock (_gate) + { + if (Volatile.Read(ref _disposed) == 1) return null; + return _serverJobs ??= new ServerJobs(api, sequenceId, title, job => JobChanged?.Invoke(job)); + } + } + + /// The server's deep report when it describes these frames, else the copy the workspace took; whether one of another number of frames was read instead. + private static (DeepAnalysisReport? Report, bool OtherFrames) ServerReport(string? json, string copied, int frameCount) + { + var otherFrames = false; + if (json is not null) + { + try + { + var report = DeepAnalysisReport.FromJson(json); + if (report.FrameCount == frameCount) return (report, false); + otherFrames = true; + } + catch (Exception ex) when (ex is JsonException or InvalidDataException) + { + Log.Warning("editor", "The server's deep report cannot be read; the workspace's copy is shown", ex); + } + } + var (deep, other) = ReadReport(null, false, copied, frameCount); + return (deep, deep is null && (other || otherFrames)); + } + /// Only a copy job changes the workspace's frames (Update media): its media index is compared with the one read last. public Task FramesCurrentAsync(CancellationToken cancellationToken) => Task.Run(() => { @@ -175,11 +317,26 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders } }, cancellationToken); - /// Whether the home's frames moved past those the workspace holds (frames added or removed there): "Update media" copies them again. + /// + /// Whether the home's frames moved past those the workspace holds (frames added or removed there), or a server now has + /// the proxy of a frame a thumbnail stands in for here: "Update media" copies them again. A server out of reach says no. + /// public async Task HomeFramesChangedAsync(CancellationToken cancellationToken) { if (Workspace is not { } workspace || MediaFramesVersion < 0) return false; - return await _db.Sequences.GetAsync(workspace.Home.SequenceId, cancellationToken) is { } row && row.FramesVersion != MediaFramesVersion; + if (_server is null) return await _db.Sequences.GetAsync(workspace.Home.SequenceId, cancellationToken) is { } row && row.FramesVersion != MediaFramesVersion; + if (_server.Api is not { } api) return false; + try + { + if ((await api.GetSequenceAsync(workspace.Home.SequenceId, cancellationToken)).FramesVersion != MediaFramesVersion) return true; + var standIns = Volatile.Read(ref _standIns); + return standIns.Count > 0 && (await api.GetManifestAsync(workspace.Home.SequenceId, cancellationToken)).Frames.Any(f => f.HasProxy && standIns.Contains(f.Id)); + } + catch (Exception ex) when (ServerProjectHome.IsUnavailable(ex, cancellationToken) || ex is ChronosApiException) + { + Log.Info("editor", $"The server's frames of workspace project {ProjectId} could not be compared: {ex.Message}"); + return false; + } } public async ValueTask DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken) @@ -293,27 +450,48 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders private static bool NamesPosition(string path) => path is "excludedFrames" or "heroFrame" || path.StartsWith("camera.keyframes", StringComparison.Ordinal) || path.StartsWith("pendingFrames", StringComparison.Ordinal); + /// A project whose home is a server queues its analyses and renders there; while this PC is not signed in to it, they are refused saying so. public async Task SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken) { + if (_server is not null) return await ServerJobsOrThrow().SubmitAsync(request, cancellationToken); if (_engine is null) throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine")); var job = await _engine.EnqueueAsync(request, cancellationToken: cancellationToken); return job.Id; } - public async Task> ListJobsAsync(CancellationToken cancellationToken) => - (await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items; + /// A server home's jobs are the server's; none are listed while it cannot be reached (the project opens all the same). + public async Task> ListJobsAsync(CancellationToken cancellationToken) + { + if (_server is null) return (await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items; + if (Volatile.Read(ref _serverJobs) is not { } jobs) return []; + try + { + return await jobs.ListAsync(cancellationToken); + } + catch (Exception ex) when (ServerProjectHome.IsUnavailable(ex, cancellationToken) || ex is ChronosApiException or EditorException) + { + Log.Info("editor", $"The server's jobs of workspace project {ProjectId} are not read now: {ex.Message}"); + return []; + } + } - public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) => - (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).CancelAsync(jobId, cancellationToken); + public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken) => _server is not null + ? ServerJobsOrThrow().CancelAsync(jobId, cancellationToken) + : (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).CancelAsync(jobId, cancellationToken); - public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) => - (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).ResumeAsync(jobId, cancellationToken); + public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken) => _server is not null + ? ServerJobsOrThrow().RetryAsync(jobId, cancellationToken) + : (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).ResumeAsync(jobId, cancellationToken); /// - /// The render at the home (owner review 2, R8: edit with proxies, render where the originals are): one job of this PC's - /// engine per preset, with the project's portable settings (positions parked by photo, placed on the home's frames by - /// the render) and the project recorded on the render; the version too when the settings are those of the last - /// version the home holds (an unsaved working state, or one saved here and not sent yet, renders as it is, without a version). + /// The render at the home (owner review 2, R8: edit with proxies, render where the originals are): one job per preset + /// (of this PC's engine, or the server's), with the project's portable settings (positions parked by photo, placed on + /// the home's frames by the render) and the project recorded on the render; the version too when the settings are those + /// of the last version the home holds (an unsaved working state, or one saved here and not sent yet, renders as it is, + /// without a version). A server home (phase 5b) renders the version it holds when the project is in step with it + /// (nothing saved or sent since its base): the jobs name that version alone and the server renders its settings with + /// the jobs' export; a project out of step renders its portable settings, recording the project only, as a server knows + /// no version of this workspace's that it was not sent. /// public IReadOnlyList RenderRequests(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight) { @@ -322,8 +500,18 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders ArgumentNullException.ThrowIfNull(export); var portable = ProjectContent.ToPortable(project with { Export = export }, Photos); var hash = ProjectContent.Hash(portable); + if (_server is not null) + { + if (InStepWithHome(project) is { } basis) + { + var version = new ProjectVersion { Id = basis.VersionId, ProjectId = ProjectId, Number = basis.Number, SettingsJson = portable, ContentHash = hash }; + return [.. ProcessingJobs.RenderVersion(sequence, version, export, sourceWidth, sourceHeight).Select(r => r with { ParametersJson = WithoutSettings(r.ParametersJson) })]; + } + var unsent = new ProjectVersion { Id = Guid.Empty, ProjectId = ProjectId, Number = 0, SettingsJson = portable, ContentHash = hash }; + return [.. ProcessingJobs.RenderVersion(sequence, unsent, export, sourceWidth, sourceHeight).Select(r => r with { ParametersJson = WithoutVersion(r.ParametersJson) })]; + } var (tipId, tipHash) = Tip(); - var version = new ProjectVersion + var tip = new ProjectVersion { Id = tipId ?? Guid.Empty, ProjectId = ProjectId, @@ -331,29 +519,65 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders SettingsJson = portable, ContentHash = hash, }; - var requests = ProcessingJobs.RenderVersion(sequence, version, export, sourceWidth, sourceHeight); + var requests = ProcessingJobs.RenderVersion(sequence, tip, export, sourceWidth, sourceHeight); if (tipId is not null && string.Equals(tipHash, hash, StringComparison.OrdinalIgnoreCase)) return requests; return [.. requests.Select(r => r with { ParametersJson = WithoutVersion(r.ParametersJson) })]; } + /// + /// The home's version the project is in step with: its base, when no version waits to be sent and the editor's project + /// () holds what the base holds; null otherwise. + /// + public BundleBase? InStepWithHome(ProjectSettings project) + { + ArgumentNullException.ThrowIfNull(project); + try + { + if (_sync.Unpushed(ProjectId).Count > 0 || Project.ReadBundle().Workspace?.Base is not { } basis) return null; + var working = ProjectContent.ToPortable(project, Photos); + if (string.Equals(ProjectContent.Hash(working), basis.ContentHash, StringComparison.OrdinalIgnoreCase)) return basis; + // Saved before a hash or a conversion at the home named its photos anew: the same choices are in step too. + return Project.Versions().FirstOrDefault(v => v.Id == basis.VersionId) is { } version && ProjectContent.SameChoices(version.SettingsJson, working, Photos) + ? basis + : null; + } + catch (Exception ex) when (ex is IOException or InvalidDataException or InvalidOperationException) + { + Log.Warning("editor", $"The versions of workspace project {ProjectId} cannot be read; the render names none", ex); + return null; + } + } + public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref _disposed, 1) == 1) return; if (_engine is not null) _engine.JobChanged -= OnJobChanged; List sources; + ServerJobs? jobs; lock (_gate) { sources = [.. _retired]; if (_frames is not null) sources.Add(_frames); _retired.Clear(); (_frames, _pixels) = (null, null); + (jobs, _serverJobs) = (_serverJobs, null); } + // The server's connection is the source's: it closes with it, also when no read made the jobs' listener. + if (jobs is not null) await jobs.DisposeAsync(); + else _server?.Api?.Dispose(); foreach (var source in sources) { if (source is IAsyncDisposable disposable) await disposable.DisposeAsync(); } } + /// The server's jobs of the project's sequence, or why there are none. + /// This PC is not signed in to the server of the project. + private ServerJobs ServerJobsOrThrow() => + Volatile.Read(ref _serverJobs) + ?? (Workspace is { } workspace ? ServerJobsOf(workspace.Home.SequenceId, Project.ReadBundle().Sequence.Title ?? string.Empty) : null) + ?? throw new EditorException(Loc.L("Editor.Error.SignedOut")); + /// /// Takes the media read now: a frame source over them when they differ from those read before (the old one is disposed /// with this source, as a decode may still read it), their frames and photos, the project's workspace section, and @@ -375,6 +599,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders _frameIds = ids; _framesVersion = index.FramesVersion; _photos = index.Photos; + _standIns = [.. index.Frames.Where(f => f.IsStandIn).Select(f => f.Id)]; _workspace = workspace; changed = _readOnly != readOnly; _readOnly = readOnly; @@ -407,6 +632,13 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders return JsonSerializer.Serialize(parameters with { ProjectVersionId = null }, ProtocolJson.Default.RenderJobParameters); } + /// A job of a version the home holds: the home renders that version's settings (with the job's export), so none travel with it. + private static string? WithoutSettings(string? parametersJson) + { + if (parametersJson is null || JsonSerializer.Deserialize(parametersJson, ProtocolJson.Default.RenderJobParameters) is not { } parameters) return parametersJson; + return JsonSerializer.Serialize(parameters with { SettingsJson = null }, ProtocolJson.Default.RenderJobParameters); + } + /// /// The deep report the editor shows: the home's while its frames are the workspace's, else the copy the workspace took; /// whether one of another number of frames was read instead. diff --git a/src/Chronos.App/Infrastructure/AppServices.cs b/src/Chronos.App/Infrastructure/AppServices.cs index f954a9b0..03c1c323 100644 --- a/src/Chronos.App/Infrastructure/AppServices.cs +++ b/src/Chronos.App/Infrastructure/AppServices.cs @@ -74,6 +74,9 @@ public sealed class AppServices : IAsyncDisposable Sync = new SyncHost(this); ScheduleHost = new DesktopScheduleHost(settings, () => Database, () => Archives); Workspace = new WorkspaceHost(environment, settings, saveSettings, () => Database, () => Archives, () => Engine); + // A server that keeps projects is the home of the workspace projects of its sequences (owner review 2, R8, phase 5b). + Workspace.ServerHomes = Sync.ProjectHome; + Sync.ProjectChanged += Workspace.OnServerProjectChanged; Server = new ServerSession(settings, saveSettings, new ChronosServerApiFactory(), new DpapiTokenProtector()); Encoders = new MediaFoundationInventory(); Formats = new WicFormatInventory(() => _wic); @@ -120,7 +123,7 @@ public sealed class AppServices : IAsyncDisposable /// public event Action? SequenceReorganized; - /// The workspace where Edit opens projects (owner review 2, R8), with this PC's archive as their home. + /// The workspace where Edit opens projects (owner review 2, R8), with this PC's archive or the signed-in server as their home. public WorkspaceHost Workspace { get; } public IEncoderInventory Encoders { get; set; } @@ -175,12 +178,13 @@ public sealed class AppServices : IAsyncDisposable typeof(AppServices).Assembly.GetCustomAttribute()?.InformationalVersion ?? "0.0.0"; /// The job handlers of this PC's engine — the single registration list; a kind without a handler stays - /// queued (it is never claimed here). The workspace copy is the desktop's alone: it writes into this PC's workspace. + /// queued (it is never claimed here). The workspace copy is the desktop's alone: it writes into this PC's workspace, from + /// this PC's archive or, through the signed-in session, from a server. public static IReadOnlyList CreateJobHandlers(AppServices services) => [ .. services.Archives?.CreateJobHandlers() ?? [], .. services.Processing?.CreateJobHandlers() ?? [], .. services.Sync.Service?.CreateJobHandlers(services.Sync) ?? [], - .. services.Database is { } db && services.Archives is { } archives ? WorkspaceJobs.CreateHandlers(db, archives) : [], + .. services.Database is { } db && services.Archives is { } archives ? WorkspaceJobs.CreateHandlers(db, archives, services.Sync) : [], ]; /// diff --git a/src/Chronos.App/Sections/SequencePickerViewModel.cs b/src/Chronos.App/Sections/SequencePickerViewModel.cs index 51aa322c..8cb7db73 100644 --- a/src/Chronos.App/Sections/SequencePickerViewModel.cs +++ b/src/Chronos.App/Sections/SequencePickerViewModel.cs @@ -26,6 +26,7 @@ namespace Chronos.App.Sections; public sealed class SequencePickerViewModel : LocalizedViewModel { private readonly SequenceViewModel _section; + private readonly Dispatcher _dispatcher; private readonly DispatcherTimer _searchDelay; private readonly RemoteMerge _merge = new(); private readonly AsyncRelayCommand _open; @@ -46,8 +47,10 @@ public sealed class SequencePickerViewModel : LocalizedViewModel public SequencePickerViewModel(SequenceViewModel section) { _section = section; + _dispatcher = Dispatcher.CurrentDispatcher; _searchDelay = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(250) }; _searchDelay.Tick += (_, _) => _ = ReloadAsync(); + section.Shell.Services.Workspace.HomeChanged += OnHomeChanged; _open = new AsyncRelayCommand(() => (Selected ?? Items.FirstOrDefault()) is { } item ? _section.PickAsync(item) : Task.CompletedTask, () => Items.Count > 0); OpenItemCommand = new AsyncRelayCommand((p, _) => p is SequenceItem item ? _section.PickAsync(item) : Task.CompletedTask); OpenProjectCommand = new AsyncRelayCommand((p, _) => (p as WorkspaceProjectItem ?? SelectedProject) is { } item ? _section.PickProjectAsync(item) : Task.CompletedTask); @@ -172,11 +175,34 @@ public sealed class SequencePickerViewModel : LocalizedViewModel { _searchDelay.Stop(); _pager?.Cancel(); + _section.Shell.Services.Workspace.HomeChanged -= OnHomeChanged; // The projects' states still being read stop asking. _generation++; base.Dispose(); } + /// + /// A project's home told it changed there (any thread; phase 5b: a server's projectChanged), or that changes may + /// have been missed: the listed projects it concerns read their state again (Server newer, Deleted). + /// + private void OnHomeChanged(WorkspaceHomeChange change) => _dispatcher.BeginInvoke(async () => + { + var generation = _generation; + foreach (var item in WorkspaceItems.Where(i => change.ProjectId is { } id ? i.ProjectId == id + : i.Entry.IsServerHome && string.Equals(i.Entry.Home.Server, change.Server, StringComparison.OrdinalIgnoreCase)).ToList()) + { + if (generation != _generation) return; + try + { + item.Status = await Shell.Services.Workspace.StatusAsync(item.ProjectId); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + Log.Info("workspace", $"The state of project {item.ProjectId} could not be read: {ex.Message}"); + } + } + }); + private async Task OpenFromSearchAsync() { await SettleAsync(); @@ -271,8 +297,13 @@ public sealed class SequencePickerViewModel : LocalizedViewModel { foreach (var entry in (await services.Workspace.ListAsync()).OrderByDescending(e => e.Saved)) { - var row = await db.Sequences.GetAsync(entry.SequenceId); - var item = new WorkspaceProjectItem(entry, row is null ? null : new SequenceItem(row, services.Thumbnails)); + var row = entry.IsServerHome ? null : await db.Sequences.GetAsync(entry.SequenceId); + // A server's sequence as the Library lists it (phase 5b), with the server's thumbnail; none while signed out. + var remote = row is null ? Shell.Library.RemoteSequences.FirstOrDefault(s => s.Id == entry.SequenceId) : null; + var sequence = row is not null ? new SequenceItem(row, services.Thumbnails) + : remote is not null ? new SequenceItem(remote, Shell.Library.RemoteThumbnails) + : null; + var item = new WorkspaceProjectItem(entry, sequence); if (text.Length > 0 && !item.Name.Contains(text, StringComparison.CurrentCultureIgnoreCase) && !item.SequenceTitle.Contains(text, StringComparison.CurrentCultureIgnoreCase)) continue; diff --git a/src/Chronos.App/Sections/SequenceView.xaml b/src/Chronos.App/Sections/SequenceView.xaml index f93fa080..10212366 100644 --- a/src/Chronos.App/Sections/SequenceView.xaml +++ b/src/Chronos.App/Sections/SequenceView.xaml @@ -123,11 +123,11 @@ - + - + @@ -164,13 +164,13 @@ - +