feat(editor): visual crop, rotate/mirror/flip/straighten, colour looks (owner review 1 phase 4) #26

Merged
Alby96 merged 68 commits from or1-p4 into main 2026-11-05 01:09:17 +01:00
48 changed files with 3243 additions and 409 deletions
Showing only changes of commit 26bab759fe - Show all commits

No files matched your search

+6 -6
View File
@@ -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`); `FLine truncated
| `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/<frame id>.jpg` (and `<frame id>-<sha16>.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/<frame id>.jpg` (and `<frame id>-<sha16>.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 `<workspace>/.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 `<workspace>/.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 |
+11
View File
@@ -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
+10
View File
@@ -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. |
+1
View File
@@ -282,6 +282,7 @@
<data name="Archive.Log.TrashReport" xml:space="preserve"><value>Old trash entries: {0}, size: {1}; nothing was deleted</value><comment>long: job log line; entries older than the clean-up's age limit</comment></data>
<data name="Archive.Log.VerifyDone" xml:space="preserve"><value>Photos checked: {0}, intact: {1}, hashed: {2}, with problems: {3}</value><comment>long: job log line</comment></data>
<data name="Archive.Log.WorkspaceCopied" xml:space="preserve"><value>{0}: copied {1}, made {2}, unchanged {3}, without a file {4}</value><comment>long: job log line; {1} proxies copied from the archive; {2} made from the originals; {3} already in the workspace; {4} frames with neither</comment></data>
<data name="Archive.Log.WorkspaceDownloaded" xml:space="preserve"><value>{0}: downloaded {1}, thumbnails {2}, unchanged {3}, without a file {4}</value><comment>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</comment></data>
<data name="Archive.Log.WorkspaceFramesChanged" xml:space="preserve"><value>{0}: the frames changed during the copy; copying again</value><comment>long: job log line</comment></data>
<data name="Archive.Maintenance.Backup" xml:space="preserve"><value>Back up database</value></data>
<data name="Archive.Maintenance.DryRun" xml:space="preserve"><value>Dry run</value></data>
+18
View File
@@ -173,6 +173,7 @@
<data name="Editor.History.List" xml:space="preserve"><value>Versions</value></data>
<data name="Editor.History.NotSent" xml:space="preserve"><value>Not sent</value></data>
<data name="Editor.History.Offline" xml:space="preserve"><value>Library offline</value></data>
<data name="Editor.History.Offline.Server" xml:space="preserve"><value>Server offline</value></data>
<data name="Editor.History.Restore" xml:space="preserve"><value>Restore</value></data>
<data name="Editor.History.Same" xml:space="preserve"><value>Same as now</value></data>
<data name="Editor.History.Title" xml:space="preserve"><value>History of {0}</value><comment>{0} project name</comment></data>
@@ -239,6 +240,7 @@
<data name="Editor.Project.Delete" xml:space="preserve"><value>Delete project…</value></data>
<data name="Editor.Project.DeleteAction" xml:space="preserve"><value>Delete</value></data>
<data name="Editor.Project.DeleteMessage" xml:space="preserve"><value>Its versions are sent to the library first, then the project goes to the library's project trash; the sequence and its photos stay.</value><comment>long</comment></data>
<data name="Editor.Project.DeleteMessage.Server" xml:space="preserve"><value>Its versions are sent to the server first, then the project goes to the server's project trash; the sequence and its photos stay.</value><comment>long</comment></data>
<data name="Editor.Project.DeleteTitle" xml:space="preserve"><value>Delete project {0}?</value><comment>{0} project name</comment></data>
<data name="Editor.Project.History" xml:space="preserve"><value>History…</value></data>
<data name="Editor.Project.Keep" xml:space="preserve"><value>Keep</value></data>
@@ -278,6 +280,7 @@
<data name="Editor.RemoveCopy.DiscardTitle" xml:space="preserve"><value>Discard the changes of {0}?</value></data>
<data name="Editor.RemoveCopy.Files" xml:space="preserve"><value>Files</value></data>
<data name="Editor.RemoveCopy.Message" xml:space="preserve"><value>The photos copied to this PC are deleted; the project stays in the library and opens again from there.</value><comment>long</comment></data>
<data name="Editor.RemoveCopy.Message.Server" xml:space="preserve"><value>The photos copied to this PC are deleted; the project stays on the server and opens again from there.</value><comment>long</comment></data>
<data name="Editor.RemoveCopy.No" xml:space="preserve"><value>None</value></data>
<data name="Editor.RemoveCopy.Remove" xml:space="preserve"><value>Remove</value></data>
<data name="Editor.RemoveCopy.SendFirst" xml:space="preserve"><value>Send first</value></data>
@@ -382,39 +385,53 @@
<data name="Editor.Workspace.ChooseFolder" xml:space="preserve"><value>Choose folder</value></data>
<data name="Editor.Workspace.Conflict.Later" xml:space="preserve"><value>Later</value></data>
<data name="Editor.Workspace.Conflict.Message" xml:space="preserve"><value>{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.</value><comment>long; {0} project name</comment></data>
<data name="Editor.Workspace.Conflict.Message.Server" xml:space="preserve"><value>{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.</value><comment>long; {0} project name</comment></data>
<data name="Editor.Workspace.Conflict.NewerFormat" xml:space="preserve"><value>Saved by a newer Chronos</value><comment>long; the one line a conflict of format lists</comment></data>
<data name="Editor.Workspace.Conflict.NewerMessage" xml:space="preserve"><value>{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.</value><comment>long; {0} project name</comment></data>
<data name="Editor.Workspace.Conflict.NewerMessage.Server" xml:space="preserve"><value>{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.</value><comment>long; {0} project name</comment></data>
<data name="Editor.Workspace.Conflict.TakeHome" xml:space="preserve"><value>Take library's</value><comment>take the library's values where both sides changed a setting</comment></data>
<data name="Editor.Workspace.Conflict.TakeHome.Server" xml:space="preserve"><value>Take server's</value></data>
<data name="Editor.Workspace.Conflict.Title" xml:space="preserve"><value>Changed in the library too</value></data>
<data name="Editor.Workspace.Conflict.Title.Server" xml:space="preserve"><value>Changed on the server too</value></data>
<data name="Editor.Workspace.CopyFailed" xml:space="preserve"><value>Workspace copy failed</value></data>
<data name="Editor.Workspace.Copying" xml:space="preserve"><value>Copying to the workspace</value></data>
<data name="Editor.Workspace.Created" xml:space="preserve"><value>Project {0} created</value><comment>{0} project name</comment></data>
<data name="Editor.Workspace.DeleteFailed" xml:space="preserve"><value>Project not deleted</value></data>
<data name="Editor.Workspace.Deleted" xml:space="preserve"><value>Project {0} deleted</value><comment>{0} project name</comment></data>
<data name="Editor.Workspace.Difference" xml:space="preserve"><value>{0} {1} here, {2} in the library</value><comment>long; {0} setting name, {1} value in this workspace, {2} value in the library</comment></data>
<data name="Editor.Workspace.Difference.Server" xml:space="preserve"><value>{0} {1} here, {2} on the server</value><comment>long; {0} setting name, {1} value in this workspace, {2} value on the server</comment></data>
<data name="Editor.Workspace.EditSetAside" xml:space="preserve"><value>Edit kept aside</value></data>
<data name="Editor.Workspace.EditSetAsideMessage" xml:space="preserve"><value>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.</value><comment>long</comment></data>
<data name="Editor.Workspace.Edited.Message" xml:space="preserve"><value>{0} changed in the library while your edit waited to be saved. The settings below differ: keep your values, or take the library's.</value><comment>long</comment></data>
<data name="Editor.Workspace.Edited.Message.Server" xml:space="preserve"><value>{0} changed on the server while your edit waited to be saved. The settings below differ: keep your values, or take the server's.</value><comment>long</comment></data>
<data name="Editor.Workspace.InSync" xml:space="preserve"><value>Project in sync</value></data>
<data name="Editor.Workspace.MediaChanged" xml:space="preserve"><value>Library photos changed</value></data>
<data name="Editor.Workspace.MediaChanged.Server" xml:space="preserve"><value>Server photos changed</value></data>
<data name="Editor.Workspace.NotSent" xml:space="preserve"><value>Version not sent yet</value></data>
<data name="Editor.Workspace.NothingNew" xml:space="preserve"><value>Nothing new to save</value></data>
<data name="Editor.Workspace.Offline" xml:space="preserve"><value>Library offline</value></data>
<data name="Editor.Workspace.Offline.Server" xml:space="preserve"><value>Server offline</value></data>
<data name="Editor.Workspace.OpenCopy" xml:space="preserve"><value>Open</value></data>
<data name="Editor.Workspace.OpenFailed" xml:space="preserve"><value>Project not opened</value></data>
<data name="Editor.Workspace.ReadOnly" xml:space="preserve"><value>Project read-only</value></data>
<data name="Editor.Workspace.RemoveFailed" xml:space="preserve"><value>Local copy not removed</value></data>
<data name="Editor.Workspace.Removed" xml:space="preserve"><value>Local copy removed</value></data>
<data name="Editor.Workspace.Renamed" xml:space="preserve"><value>Project renamed</value></data>
<data name="Editor.Workspace.RenderHeld" xml:space="preserve"><value>Not rendered</value></data>
<data name="Editor.Workspace.Restored" xml:space="preserve"><value>Version {0} restored</value><comment>{0} version number</comment></data>
<data name="Editor.Workspace.Saved" xml:space="preserve"><value>Version {0} saved</value><comment>{0} version number</comment></data>
<data name="Editor.Workspace.SavedAs" xml:space="preserve"><value>Your versions saved as {0}</value><comment>{0} the name of the new project holding them</comment></data>
<data name="Editor.Workspace.SavedSent" xml:space="preserve"><value>Version {0} saved and sent</value><comment>{0} version number</comment></data>
<data name="Editor.Workspace.SendFirst.Action" xml:space="preserve"><value>Send and render</value></data>
<data name="Editor.Workspace.SendFirst.Message" xml:space="preserve"><value>The server renders {0} as it holds it: save your changes as a version and send them first.</value><comment>long; {0} project name</comment></data>
<data name="Editor.Workspace.SendFirst.Title" xml:space="preserve"><value>Send before rendering</value></data>
<data name="Editor.Workspace.State.Ahead" xml:space="preserve"><value>Not sent</value><comment>versions saved here wait to be sent to the library</comment></data>
<data name="Editor.Workspace.State.Behind" xml:space="preserve"><value>Library newer</value><comment>the library has versions the workspace has not taken</comment></data>
<data name="Editor.Workspace.State.Behind.Server" xml:space="preserve"><value>Server newer</value></data>
<data name="Editor.Workspace.State.Conflict" xml:space="preserve"><value>Conflict</value></data>
<data name="Editor.Workspace.State.Damaged" xml:space="preserve"><value>Damaged</value><comment>a version or the project file saved in the workspace cannot be read</comment></data>
<data name="Editor.Workspace.State.Gone" xml:space="preserve"><value>Not in library</value></data>
<data name="Editor.Workspace.State.Gone.Server" xml:space="preserve"><value>Not on server</value></data>
<data name="Editor.Workspace.State.InSync" xml:space="preserve"><value>In sync</value></data>
<data name="Editor.Workspace.State.MediaRemoved" xml:space="preserve"><value>No media</value></data>
<data name="Editor.Workspace.State.Modified" xml:space="preserve"><value>Changed</value><comment>the project has changes not saved as a version</comment></data>
@@ -425,6 +442,7 @@
<data name="Editor.Workspace.SyncFailed" xml:space="preserve"><value>Sync failed</value></data>
<data name="Editor.Workspace.Synced" xml:space="preserve"><value>Project synced</value></data>
<data name="Editor.Workspace.TookLibrary" xml:space="preserve"><value>Library's values taken</value></data>
<data name="Editor.Workspace.TookLibrary.Server" xml:space="preserve"><value>Server's values taken</value></data>
<data name="Editor.Workspace.Undo" xml:space="preserve"><value>Undo</value></data>
<data name="Editor.Workspace.UpdateMedia" xml:space="preserve"><value>Update media</value></data>
<data name="Editor.Workspace.Updating" xml:space="preserve"><value>Updating media</value></data>
+9
View File
@@ -55,10 +55,13 @@
<data name="Errors.Workspace.CopyMismatch" xml:space="preserve"><value>{0} did not match its source after it was copied.</value><comment>{0} file path</comment></data>
<data name="Errors.Workspace.Damaged" xml:space="preserve"><value>A file of this project in the workspace cannot be read; the log names it.</value></data>
<data name="Errors.Workspace.DeletedAtHome" xml:space="preserve"><value>This project was deleted in the library; nothing was removed. Discard changes removes its local copy.</value></data>
<data name="Errors.Workspace.DeletedAtHome.Server" xml:space="preserve"><value>This project was deleted on the server; nothing was removed. Discard changes removes its local copy.</value></data>
<data name="Errors.Workspace.DiskFull" xml:space="preserve"><value>The workspace drive needs {0} GB more for this copy.</value><comment>{0} gigabytes missing</comment></data>
<data name="Errors.Workspace.EditNotStored" xml:space="preserve"><value>The last edit could not be stored yet; it is tried again, try once more in a moment.</value></data>
<data name="Errors.Workspace.FolderUnusable" xml:space="preserve"><value>{0} cannot be used as the workspace folder; the log says why.</value><comment>long; {0} folder</comment></data>
<data name="Errors.Workspace.Forbidden" xml:space="preserve"><value>Your account cannot change the projects of this server.</value></data>
<data name="Errors.Workspace.HomeCheck" xml:space="preserve"><value>The library's copy of this project does not match what was sent; nothing was removed.</value></data>
<data name="Errors.Workspace.HomeCheck.Server" xml:space="preserve"><value>The server's copy of this project does not match what was sent; nothing was removed.</value></data>
<data name="Errors.Workspace.InsideLibrary" xml:space="preserve"><value>The workspace folder is inside a library; nothing is copied into it.</value></data>
<data name="Errors.Workspace.InsideLibraryEdit" xml:space="preserve"><value>The workspace folder {0} is inside a library, where Edit copies nothing: choose another workspace folder.</value><comment>long</comment></data>
<data name="Errors.Workspace.InsideLibraryFolder" xml:space="preserve"><value>{0} is inside a library, where Edit copies nothing: choose a folder outside your libraries.</value><comment>long; {0} folder</comment></data>
@@ -68,17 +71,23 @@
<data name="Errors.Workspace.MediaMissing" xml:space="preserve"><value>The workspace holds no photos of this project; open it again to copy them.</value></data>
<data name="Errors.Workspace.NameTaken" xml:space="preserve"><value>Another project of this sequence has that name.</value></data>
<data name="Errors.Workspace.NewerCopy" xml:space="preserve"><value>A newer Chronos saved this copy in the workspace; update Chronos to open it or remove it.</value></data>
<data name="Errors.Workspace.NoProjects" xml:space="preserve"><value>This server keeps no projects: it needs an update before its sequences can be edited in the workspace.</value></data>
<data name="Errors.Workspace.NoRoom" xml:space="preserve"><value>The drive of the workspace folder lacks room for this copy and the 0.5 GB the copy keeps free.</value></data>
<data name="Errors.Workspace.NotCheckedOut" xml:space="preserve"><value>The project is no longer in the workspace.</value></data>
<data name="Errors.Workspace.Offline" xml:space="preserve"><value>The library cannot be reached now; your work stays in the workspace and can be sent once it is back.</value></data>
<data name="Errors.Workspace.Offline.Server" xml:space="preserve"><value>The server cannot be reached now; your work stays in the workspace and can be sent once it is back.</value></data>
<data name="Errors.Workspace.OriginalsLater" xml:space="preserve"><value>The workspace copies proxies for now; copying the originals comes in a later version.</value></data>
<data name="Errors.Workspace.OtherHome" xml:space="preserve"><value>The workspace project belongs to another sequence.</value></data>
<data name="Errors.Workspace.Parameters" xml:space="preserve"><value>The workspace copy job has no valid parameters.</value></data>
<data name="Errors.Workspace.ProjectGone" xml:space="preserve"><value>This project is no longer in the library.</value></data>
<data name="Errors.Workspace.ProjectGone.Server" xml:space="preserve"><value>This project is no longer on the server.</value></data>
<data name="Errors.Workspace.ReadOnly" xml:space="preserve"><value>This project was saved by a newer Chronos: it opens read-only.</value></data>
<data name="Errors.Workspace.ReadOnlyHome" xml:space="preserve"><value>The library is read-only now; your work stays in the workspace and can be sent once it is writable.</value></data>
<data name="Errors.Workspace.Refused" xml:space="preserve"><value>The library refused a version of this project; the log says why.</value></data>
<data name="Errors.Workspace.Refused.Server" xml:space="preserve"><value>The server refused a version of this project; the log says why.</value></data>
<data name="Errors.Workspace.SequenceGone" xml:space="preserve"><value>This project's sequence is no longer in the library: only its local copy can be removed, from the picker's menu.</value><comment>long</comment></data>
<data name="Errors.Workspace.Unsent" xml:space="preserve"><value>Some work is not in the library yet: send it first, or discard it.</value></data>
<data name="Errors.Workspace.Unsent.Server" xml:space="preserve"><value>Some work is not on the server yet: send it first, or discard it.</value></data>
<data name="Errors.Workspace.VersionTooLarge" xml:space="preserve"><value>This version is larger than the {0} MB a version can be, so the library cannot store it; your work stays in the workspace.</value><comment>{0} megabytes</comment></data>
<data name="Errors.Workspace.VersionTooLarge.Server" xml:space="preserve"><value>This version is larger than the {0} MB a version can be, so the server cannot store it; your work stays in the workspace.</value><comment>{0} megabytes</comment></data>
</root>
+1
View File
@@ -199,6 +199,7 @@
<data name="Server.Sync.Action.GetExports" xml:space="preserve"><value>Get exports</value></data>
<data name="Server.Sync.Action.KeepMine" xml:space="preserve"><value>Keep mine</value></data>
<data name="Server.Sync.Action.OpenWithProxies" xml:space="preserve"><value>Open with proxies</value></data>
<data name="Server.Sync.Action.OpenInWorkspace" xml:space="preserve"><value>Open in workspace</value></data>
<data name="Server.Sync.Action.Pause" xml:space="preserve"><value>Pause</value></data>
<data name="Server.Sync.Action.Resume" xml:space="preserve"><value>Resume</value></data>
<data name="Server.Sync.Action.SaveBoth" xml:space="preserve"><value>Save both</value></data>
+38
View File
@@ -209,7 +209,9 @@
<data name="Tooltips.Editor.History.Compare" xml:space="preserve"><value>Show the settings that differ between version {0} and the project now</value><comment>{0} version number</comment></data>
<data name="Tooltips.Editor.History.Current" xml:space="preserve"><value>The project is this version now</value></data>
<data name="Tooltips.Editor.History.NotSent" xml:space="preserve"><value>Saved here, waiting to be sent to the library</value></data>
<data name="Tooltips.Editor.History.NotSent.Server" xml:space="preserve"><value>Saved here, waiting to be sent to the server</value></data>
<data name="Tooltips.Editor.History.Offline" xml:space="preserve"><value>The library cannot be reached: the versions this PC keeps are listed</value></data>
<data name="Tooltips.Editor.History.Offline.Server" xml:space="preserve"><value>The server cannot be reached: the versions this PC keeps are listed</value></data>
<data name="Tooltips.Editor.History.Restore" xml:space="preserve"><value>Make version {0} the project again (one step: Ctrl+Z takes it back); unsaved changes are saved as a version first</value><comment>{0} version number</comment></data>
<data name="Tooltips.Editor.Motion.Blur" xml:space="preserve"><value>Adds blur along the motion like a slower shutter; costs optical flow on every frame</value></data>
<data name="Tooltips.Editor.Motion.Flow" xml:space="preserve"><value>Optical flow precision for blur and synthesised frames; Best is the slowest</value></data>
@@ -226,13 +228,16 @@
<data name="Tooltips.Editor.NotApplicable.StabilizeOff" xml:space="preserve"><value>Not applicable: stabilisation is off</value></data>
<data name="Tooltips.Editor.NotApplicable.StackOff" xml:space="preserve"><value>Not applicable: stacking is off</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Existing" xml:space="preserve"><value>Open a project the library has for this sequence; Main holds its settings as they are</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Existing.Server" xml:space="preserve"><value>Open a project the server has for this sequence; Main holds its settings as they are</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Free" xml:space="preserve"><value>Free space on the drive of the workspace folder; the copy keeps 0.5 GB free besides</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Name" xml:space="preserve"><value>The new project's name: 1 to 60 characters, each name once per sequence</value></data>
<data name="Tooltips.Editor.OpenWorkspace.New" xml:space="preserve"><value>A new project of this sequence, starting from Main</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Open" xml:space="preserve"><value>Copy the project's photos into the workspace, then open it there</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Originals" xml:space="preserve"><value>Copying the originals, to render on this PC, comes in a later update</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Projects" xml:space="preserve"><value>The sequence's projects in the library</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Projects.Server" xml:space="preserve"><value>The sequence's projects on the server</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Proxies" xml:space="preserve"><value>Copy the proxies: light and fast to edit; renders use the library's originals</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Proxies.Server" xml:space="preserve"><value>Download the server's proxies: light and fast to edit; renders run on the server, with the originals</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Size" xml:space="preserve"><value>What the copy of the proxies writes into the workspace, as reckoned before it starts</value></data>
<data name="Tooltips.Editor.OptimiseAll" xml:space="preserve"><value>Let the advisor set every section from the analysis and list what changed</value></data>
<data name="Tooltips.Editor.OptimiseNone" xml:space="preserve"><value>The advisor never stacks on its own: a median erases moving stars</value></data>
@@ -261,29 +266,38 @@
<data name="Tooltips.Editor.Preview.Vectors" xml:space="preserve"><value>Overlay the motion to the next frame measured by the engine</value></data>
<data name="Tooltips.Editor.Preview.View" xml:space="preserve"><value>Drag the line to compare · drag to pan · wheel zooms · double-click 1:1</value></data>
<data name="Tooltips.Editor.Project.Delete" xml:space="preserve"><value>Send this project's versions to the library, then move it to the library's project trash</value></data>
<data name="Tooltips.Editor.Project.Delete.Server" xml:space="preserve"><value>Send this project's versions to the server, then move it to the server's project trash</value></data>
<data name="Tooltips.Editor.Project.DeleteAction" xml:space="preserve"><value>Move the project, with all its versions, to the library's project trash</value></data>
<data name="Tooltips.Editor.Project.DeleteAction.Server" xml:space="preserve"><value>Move the project, with all its versions, to the server's project trash</value></data>
<data name="Tooltips.Editor.Project.History" xml:space="preserve"><value>The project's versions: compare one with now, or restore it</value></data>
<data name="Tooltips.Editor.Project.Keep" xml:space="preserve"><value>Keep the project as it is</value></data>
<data name="Tooltips.Editor.Project.Menu" xml:space="preserve"><value>Project {0} ({1}): save a version, sync, history, other projects and the local copy</value><comment>{0} project name, {1} its state</comment></data>
<data name="Tooltips.Editor.Project.New" xml:space="preserve"><value>Make another project of this sequence, starting from this one (for example a vertical cut for social media)</value></data>
<data name="Tooltips.Editor.Project.Open" xml:space="preserve"><value>Open another project of this sequence: one in the library, or a new one</value><comment>long</comment></data>
<data name="Tooltips.Editor.Project.RemoveCopy" xml:space="preserve"><value>Free this PC's space: delete the photos copied to the workspace; the project stays in the library</value></data>
<data name="Tooltips.Editor.Project.RemoveCopy.Server" xml:space="preserve"><value>Free this PC's space: delete the photos copied to the workspace; the project stays on the server</value></data>
<data name="Tooltips.Editor.Project.Rename" xml:space="preserve"><value>Give this project another name, here and in the library</value></data>
<data name="Tooltips.Editor.Project.Rename.Server" xml:space="preserve"><value>Give this project another name, here and on the server</value></data>
<data name="Tooltips.Editor.Project.SaveVersion" xml:space="preserve"><value>Keep the project as it is now as a version of its history, with an optional note (Ctrl+S)</value></data>
<data name="Tooltips.Editor.ProjectFile.Remote" xml:space="preserve"><value>Project files are for sequences in an archive on this PC</value></data>
<data name="Tooltips.Editor.ProjectFile.Retry" xml:space="preserve"><value>Apply the project file’s settings again</value></data>
<data name="Tooltips.Editor.ProjectFile.Save" xml:space="preserve"><value>Save a .chronos file that opens this sequence with these settings when double-clicked</value></data>
<data name="Tooltips.Editor.ProjectFile.Undo" xml:space="preserve"><value>Bring back the settings the sequence had before the file was opened · Ctrl+Z</value></data>
<data name="Tooltips.Editor.ProjectName.Apply" xml:space="preserve"><value>Rename the project here and in the library</value></data>
<data name="Tooltips.Editor.ProjectName.Apply.Server" xml:space="preserve"><value>Rename the project here and on the server</value></data>
<data name="Tooltips.Editor.ProjectName.Create" xml:space="preserve"><value>Make the project in the library and open it in the workspace</value></data>
<data name="Tooltips.Editor.ProjectName.Create.Server" xml:space="preserve"><value>Make the project on the server and open it in the workspace</value></data>
<data name="Tooltips.Editor.ProjectName.Name" xml:space="preserve"><value>1 to 60 characters, each name once per sequence</value></data>
<data name="Tooltips.Editor.ReadOnly" xml:space="preserve"><value>Your account can look at this server sequence but not change it</value></data>
<data name="Tooltips.Editor.Remote" xml:space="preserve"><value>Edited with proxies on this PC; changes are saved on {0} and analyses and renders run there</value></data>
<data name="Tooltips.Editor.RemoteReadOnly" xml:space="preserve"><value>Shown from {0}; your account can look at this sequence but not change it</value></data>
<data name="Tooltips.Editor.RemoveCopy.Discard" xml:space="preserve"><value>Remove the copy without sending what is not in the library; that work is kept aside in the workspace's trash</value></data>
<data name="Tooltips.Editor.RemoveCopy.Discard.Server" xml:space="preserve"><value>Remove the copy without sending what is not on the server; that work is kept aside in the workspace's trash</value></data>
<data name="Tooltips.Editor.RemoveCopy.Keep" xml:space="preserve"><value>Keep the local copy as it is</value></data>
<data name="Tooltips.Editor.RemoveCopy.Remove" xml:space="preserve"><value>Delete the workspace copy; every version is in the library</value></data>
<data name="Tooltips.Editor.RemoveCopy.Remove.Server" xml:space="preserve"><value>Delete the workspace copy; every version is on the server</value></data>
<data name="Tooltips.Editor.RemoveCopy.SendFirst" xml:space="preserve"><value>Save and send what is not in the library yet, then remove the copy</value></data>
<data name="Tooltips.Editor.RemoveCopy.SendFirst.Server" xml:space="preserve"><value>Save and send what is not on the server yet, then remove the copy</value></data>
<data name="Tooltips.Editor.Render" xml:space="preserve"><value>Render with the selected preset; progress in the job bar · Ctrl+R</value></data>
<data name="Tooltips.Editor.Render.NameError" xml:space="preserve"><value>Fix the file name first: {0}</value></data>
<data name="Tooltips.Editor.Render.NoFrames" xml:space="preserve"><value>Every frame is excluded: include some in the Frames step</value></data>
@@ -298,6 +312,7 @@
<data name="Tooltips.Editor.Save.Retry" xml:space="preserve"><value>Try to save now; saving is also retried automatically</value></data>
<data name="Tooltips.Editor.SaveVersion.Note" xml:space="preserve"><value>What changed, as the history will show it (optional)</value></data>
<data name="Tooltips.Editor.SaveVersion.Save" xml:space="preserve"><value>Save the version, and send it to the library when Sync automatically is on</value></data>
<data name="Tooltips.Editor.SaveVersion.Save.Server" xml:space="preserve"><value>Save the version, and send it to the server when Sync automatically is on</value></data>
<data name="Tooltips.Editor.ServerJob" xml:space="preserve"><value>{0} running on {1}</value></data>
<data name="Tooltips.Editor.ServerJob.Cancel" xml:space="preserve"><value>Cancel the job on {0}; Retry in the notice that follows queues it again from its last checkpoint</value></data>
<data name="Tooltips.Editor.ServerJob.Paused" xml:space="preserve"><value>{0} paused on {1}</value></data>
@@ -331,32 +346,53 @@
<data name="Tooltips.Editor.Unsaved.Keep" xml:space="preserve"><value>Stay in the editor; saving is retried in the background</value></data>
<data name="Tooltips.Editor.Workspace.ChooseFolder" xml:space="preserve"><value>Choose a workspace folder outside your libraries; nothing is moved</value></data>
<data name="Tooltips.Editor.Workspace.Differences" xml:space="preserve"><value>The settings that differ: your value, then the library's</value></data>
<data name="Tooltips.Editor.Workspace.Differences.Server" xml:space="preserve"><value>The settings that differ: your value, then the server's</value></data>
<data name="Tooltips.Editor.Workspace.KeepMine" xml:space="preserve"><value>Keep your values of these settings; they are sent to the library</value></data>
<data name="Tooltips.Editor.Workspace.KeepMine.Server" xml:space="preserve"><value>Keep your values of these settings; they are sent to the server</value></data>
<data name="Tooltips.Editor.Workspace.Later" xml:space="preserve"><value>Decide later and keep editing; Sync asks again</value></data>
<data name="Tooltips.Editor.Workspace.MediaChanged" xml:space="preserve"><value>The library added, removed, converted or verified photos of this sequence after the workspace copied it</value></data>
<data name="Tooltips.Editor.Workspace.MediaChanged.Server" xml:space="preserve"><value>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</value></data>
<data name="Tooltips.Editor.Workspace.NewerFormat" xml:space="preserve"><value>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</value></data>
<data name="Tooltips.Editor.Workspace.NewerFormat.Server" xml:space="preserve"><value>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</value></data>
<data name="Tooltips.Editor.Workspace.OpenCopy" xml:space="preserve"><value>Open project {0}, which holds your versions</value><comment>long</comment></data>
<data name="Tooltips.Editor.Workspace.SaveBoth" xml:space="preserve"><value>Keep the library's values in this project, and send yours to a new project “{0}”</value><comment>{0} the new project's name</comment></data>
<data name="Tooltips.Editor.Workspace.SaveBoth.Server" xml:space="preserve"><value>Keep the server's values in this project, and send yours to a new project “{0}”</value></data>
<data name="Tooltips.Editor.Workspace.SaveBothNewer" xml:space="preserve"><value>Send your versions to a new project “{0}”; this project takes the library's, read-only until Chronos is updated</value><comment>{0} the new project's name</comment></data>
<data name="Tooltips.Editor.Workspace.SaveBothNewer.Server" xml:space="preserve"><value>Send your versions to a new project “{0}”; this project takes the server's, read-only until Chronos is updated</value><comment>{0} the new project's name</comment></data>
<data name="Tooltips.Editor.Workspace.SendFirst.Action" xml:space="preserve"><value>Save the changes as a version, send it to the server, then render that version there</value></data>
<data name="Tooltips.Editor.Workspace.SendFirst.Keep" xml:space="preserve"><value>Keep the changes here and render nothing now</value></data>
<data name="Tooltips.Editor.Workspace.State.Ahead" xml:space="preserve"><value>Versions saved here that wait to be sent to the library: {0}. Sync sends them</value><comment>{0} number of versions</comment></data>
<data name="Tooltips.Editor.Workspace.State.Ahead.Server" xml:space="preserve"><value>Versions saved here that wait to be sent to the server: {0}. Sync sends them</value></data>
<data name="Tooltips.Editor.Workspace.State.Behind" xml:space="preserve"><value>Versions in the library this workspace has not taken yet: {0}. Sync takes them</value><comment>{0} number of versions</comment></data>
<data name="Tooltips.Editor.Workspace.State.Behind.Server" xml:space="preserve"><value>Versions on the server this workspace has not taken yet: {0}. Sync takes them</value></data>
<data name="Tooltips.Editor.Workspace.State.Conflict" xml:space="preserve"><value>You and the library changed the same settings: Sync to choose which to keep</value></data>
<data name="Tooltips.Editor.Workspace.State.Conflict.Server" xml:space="preserve"><value>You and the server changed the same settings: Sync to choose which to keep</value></data>
<data name="Tooltips.Editor.Workspace.State.Damaged" xml:space="preserve"><value>A version saved here cannot be read (the log names its file): nothing is saved, sent or taken until it is repaired</value><comment>long</comment></data>
<data name="Tooltips.Editor.Workspace.State.DamagedCopy" xml:space="preserve"><value>This copy's project file cannot be read, so it cannot open; Remove local copy keeps its files in the workspace's trash</value></data>
<data name="Tooltips.Editor.Workspace.State.Gone" xml:space="preserve"><value>The library no longer has this project or its sequence: nothing more can be sent; remove the local copy (its work is kept aside)</value><comment>long</comment></data>
<data name="Tooltips.Editor.Workspace.State.Gone.Server" xml:space="preserve"><value>The server no longer has this project or its sequence: nothing more can be sent; remove the local copy (its work is kept aside)</value></data>
<data name="Tooltips.Editor.Workspace.State.InSync" xml:space="preserve"><value>Every version of this project is in the library, and nothing changed since the last one</value></data>
<data name="Tooltips.Editor.Workspace.State.InSync.Server" xml:space="preserve"><value>Every version of this project is on the server, and nothing changed since the last one</value></data>
<data name="Tooltips.Editor.Workspace.State.MediaRemoved" xml:space="preserve"><value>The workspace holds no photos of this project: opening it copies them again</value></data>
<data name="Tooltips.Editor.Workspace.State.Modified" xml:space="preserve"><value>Changes not saved as a version yet: Save version (Ctrl+S) keeps them in the history</value></data>
<data name="Tooltips.Editor.Workspace.State.NewerCopy" xml:space="preserve"><value>A newer Chronos saved this copy, so this one cannot open it; update Chronos: nothing in it is changed or removed here</value><comment>long</comment></data>
<data name="Tooltips.Editor.Workspace.State.Offline" xml:space="preserve"><value>The library cannot be reached now: your work stays here and is sent once it is back</value></data>
<data name="Tooltips.Editor.Workspace.State.Offline.Server" xml:space="preserve"><value>The server cannot be reached now: your work stays here and is sent once it is back</value></data>
<data name="Tooltips.Editor.Workspace.State.OfflineAhead" xml:space="preserve"><value>The library cannot be reached now. Versions waiting to be sent once it is back: {0}</value><comment>{0} number of versions</comment></data>
<data name="Tooltips.Editor.Workspace.State.OfflineAhead.Server" xml:space="preserve"><value>The server cannot be reached now. Versions waiting to be sent once it is back: {0}</value></data>
<data name="Tooltips.Editor.Workspace.State.Reading" xml:space="preserve"><value>Asking the library where this project stands</value></data>
<data name="Tooltips.Editor.Workspace.State.Reading.Server" xml:space="preserve"><value>Asking the server where this project stands</value></data>
<data name="Tooltips.Editor.Workspace.State.Syncing" xml:space="preserve"><value>Taking the library's new versions and sending yours</value></data>
<data name="Tooltips.Editor.Workspace.State.Syncing.Server" xml:space="preserve"><value>Taking the server's new versions and sending yours</value></data>
<data name="Tooltips.Editor.Workspace.TakeHome" xml:space="preserve"><value>Use the library's values of these settings in the editor</value></data>
<data name="Tooltips.Editor.Workspace.TakeHome.Server" xml:space="preserve"><value>Use the server's values of these settings in the editor</value></data>
<data name="Tooltips.Editor.Workspace.TakeHomeUndo" xml:space="preserve"><value>Use the library's values of these settings; Ctrl+Z brings yours back</value><comment>long</comment></data>
<data name="Tooltips.Editor.Workspace.TakeHomeUndo.Server" xml:space="preserve"><value>Use the server's values of these settings; Ctrl+Z brings yours back</value><comment>long</comment></data>
<data name="Tooltips.Editor.Workspace.Undo" xml:space="preserve"><value>Bring back the project as it was before the restore</value></data>
<data name="Tooltips.Editor.Workspace.UndoTake" xml:space="preserve"><value>Bring back your values of the settings the library's replaced</value><comment>long</comment></data>
<data name="Tooltips.Editor.Workspace.UndoTake.Server" xml:space="preserve"><value>Bring back your values of the settings the server's replaced</value><comment>long</comment></data>
<data name="Tooltips.Editor.Workspace.UpdateMedia" xml:space="preserve"><value>Copy the library's frames into the workspace again; the frames you excluded or keyed follow their photos</value></data>
<data name="Tooltips.Editor.Workspace.UpdateMedia.Server" xml:space="preserve"><value>Download the server's frames into the workspace again; the frames you excluded or keyed follow their photos</value></data>
<data name="Tooltips.Import.Again" xml:space="preserve"><value>Import photos already in the archive again; nothing is overwritten</value></data>
<data name="Tooltips.Import.Archive" xml:space="preserve"><value>Copy into this PC's archive with the naming templates · {0}</value></data>
<data name="Tooltips.Import.Auto" xml:space="preserve"><value>Start the import with this card's settings as soon as it is inserted; a toast lets you cancel</value></data>
@@ -678,6 +714,8 @@
<data name="Tooltips.Server.Sync.LastSync" xml:space="preserve"><value>When this PC last compared every sequence with the server, and how long it took</value></data>
<data name="Tooltips.Server.Sync.OpenAdmin" xml:space="preserve"><value>Open the web admin in your browser (admins only)</value></data>
<data name="Tooltips.Server.Sync.OpenWithProxies" xml:space="preserve"><value>Open in Edit on the proxies; the render runs on the server</value></data>
<data name="Tooltips.Server.Sync.OpenInWorkspace" xml:space="preserve"><value>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</value></data>
<data name="Tooltips.Server.Sync.OpenInWorkspace.NoProjects" xml:space="preserve"><value>This server keeps no projects yet (it needs an update): Open with proxies edits the sequence on the server as before</value></data>
<data name="Tooltips.Server.Sync.Pause" xml:space="preserve"><value>Pause this transfer; it resumes where it stopped</value></data>
<data name="Tooltips.Server.Sync.Resume" xml:space="preserve"><value>Resume this transfer where it stopped</value></data>
<data name="Tooltips.Server.Sync.Retrying" xml:space="preserve"><value>The last comparison failed: {0}. It is retried automatically.</value><comment>{0} reason</comment></data>
+1
View File
@@ -276,6 +276,7 @@
<data name="Archive.Log.TrashReport" xml:space="preserve"><value>Voci vecchie nel cestino: {0}, dimensione: {1}; nulla è stato eliminato</value></data>
<data name="Archive.Log.VerifyDone" xml:space="preserve"><value>Foto controllate: {0}, integre: {1}, con impronta nuova: {2}, con problemi: {3}</value></data>
<data name="Archive.Log.WorkspaceCopied" xml:space="preserve"><value>{0}: copiati {1}, creati {2}, invariati {3}, senza file {4}</value></data>
<data name="Archive.Log.WorkspaceDownloaded" xml:space="preserve"><value>{0}: scaricati {1}, miniature {2}, invariati {3}, senza file {4}</value></data>
<data name="Archive.Log.WorkspaceFramesChanged" xml:space="preserve"><value>{0}: i fotogrammi sono cambiati durante la copia; nuova copia</value></data>
<data name="Archive.Maintenance.Backup" xml:space="preserve"><value>Copia del database</value></data>
<data name="Archive.Maintenance.DryRun" xml:space="preserve"><value>Simulazione</value></data>
+18
View File
@@ -165,6 +165,7 @@
<data name="Editor.History.List" xml:space="preserve"><value>Versioni</value></data>
<data name="Editor.History.NotSent" xml:space="preserve"><value>Non inviata</value></data>
<data name="Editor.History.Offline" xml:space="preserve"><value>Libreria non in linea</value></data>
<data name="Editor.History.Offline.Server" xml:space="preserve"><value>Server non in linea</value></data>
<data name="Editor.History.Restore" xml:space="preserve"><value>Ripristina</value></data>
<data name="Editor.History.Same" xml:space="preserve"><value>Uguale ad ora</value></data>
<data name="Editor.History.Title" xml:space="preserve"><value>Cronologia di {0}</value></data>
@@ -228,6 +229,7 @@
<data name="Editor.Project.Delete" xml:space="preserve"><value>Elimina progetto…</value></data>
<data name="Editor.Project.DeleteAction" xml:space="preserve"><value>Elimina</value></data>
<data name="Editor.Project.DeleteMessage" xml:space="preserve"><value>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.</value></data>
<data name="Editor.Project.DeleteMessage.Server" xml:space="preserve"><value>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.</value></data>
<data name="Editor.Project.DeleteTitle" xml:space="preserve"><value>Eliminare il progetto {0}?</value></data>
<data name="Editor.Project.History" xml:space="preserve"><value>Cronologia…</value></data>
<data name="Editor.Project.Keep" xml:space="preserve"><value>Mantieni</value></data>
@@ -267,6 +269,7 @@
<data name="Editor.RemoveCopy.DiscardTitle" xml:space="preserve"><value>Scartare le modifiche di {0}?</value></data>
<data name="Editor.RemoveCopy.Files" xml:space="preserve"><value>File</value></data>
<data name="Editor.RemoveCopy.Message" xml:space="preserve"><value>Le foto copiate su questo PC vengono eliminate; il progetto resta nella libreria e si riapre da lì.</value></data>
<data name="Editor.RemoveCopy.Message.Server" xml:space="preserve"><value>Le foto copiate su questo PC vengono eliminate; il progetto resta sul server e si riapre da lì.</value></data>
<data name="Editor.RemoveCopy.No" xml:space="preserve"><value>Nessuna</value></data>
<data name="Editor.RemoveCopy.Remove" xml:space="preserve"><value>Rimuovi</value></data>
<data name="Editor.RemoveCopy.SendFirst" xml:space="preserve"><value>Prima invia</value></data>
@@ -357,39 +360,53 @@
<data name="Editor.Workspace.ChooseFolder" xml:space="preserve"><value>Scegli cartella</value></data>
<data name="Editor.Workspace.Conflict.Later" xml:space="preserve"><value>Più tardi</value></data>
<data name="Editor.Workspace.Conflict.Message" xml:space="preserve"><value>{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.</value></data>
<data name="Editor.Workspace.Conflict.Message.Server" xml:space="preserve"><value>{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.</value></data>
<data name="Editor.Workspace.Conflict.NewerFormat" xml:space="preserve"><value>Salvato da un Chronos più recente</value></data>
<data name="Editor.Workspace.Conflict.NewerMessage" xml:space="preserve"><value>{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.</value></data>
<data name="Editor.Workspace.Conflict.NewerMessage.Server" xml:space="preserve"><value>{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.</value></data>
<data name="Editor.Workspace.Conflict.TakeHome" xml:space="preserve"><value>Prendi la libreria</value></data>
<data name="Editor.Workspace.Conflict.TakeHome.Server" xml:space="preserve"><value>Prendi il server</value></data>
<data name="Editor.Workspace.Conflict.Title" xml:space="preserve"><value>Modificato anche nella libreria</value></data>
<data name="Editor.Workspace.Conflict.Title.Server" xml:space="preserve"><value>Modificato anche sul server</value></data>
<data name="Editor.Workspace.CopyFailed" xml:space="preserve"><value>Copia di lavoro non riuscita</value></data>
<data name="Editor.Workspace.Copying" xml:space="preserve"><value>Copia nello spazio di lavoro</value></data>
<data name="Editor.Workspace.Created" xml:space="preserve"><value>Progetto {0} creato</value></data>
<data name="Editor.Workspace.DeleteFailed" xml:space="preserve"><value>Progetto non eliminato</value></data>
<data name="Editor.Workspace.Deleted" xml:space="preserve"><value>Progetto {0} eliminato</value></data>
<data name="Editor.Workspace.Difference" xml:space="preserve"><value>{0} {1} qui, {2} nella libreria</value></data>
<data name="Editor.Workspace.Difference.Server" xml:space="preserve"><value>{0} {1} qui, {2} sul server</value></data>
<data name="Editor.Workspace.EditSetAside" xml:space="preserve"><value>Modifica da parte</value></data>
<data name="Editor.Workspace.EditSetAsideMessage" xml:space="preserve"><value>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.</value></data>
<data name="Editor.Workspace.Edited.Message" xml:space="preserve"><value>{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.</value></data>
<data name="Editor.Workspace.Edited.Message.Server" xml:space="preserve"><value>{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.</value></data>
<data name="Editor.Workspace.InSync" xml:space="preserve"><value>Progetto sincronizzato</value></data>
<data name="Editor.Workspace.MediaChanged" xml:space="preserve"><value>Foto della libreria cambiate</value></data>
<data name="Editor.Workspace.MediaChanged.Server" xml:space="preserve"><value>Foto del server cambiate</value></data>
<data name="Editor.Workspace.NotSent" xml:space="preserve"><value>Versione non ancora inviata</value></data>
<data name="Editor.Workspace.NothingNew" xml:space="preserve"><value>Niente di nuovo da salvare</value></data>
<data name="Editor.Workspace.Offline" xml:space="preserve"><value>Libreria non in linea</value></data>
<data name="Editor.Workspace.Offline.Server" xml:space="preserve"><value>Server non in linea</value></data>
<data name="Editor.Workspace.OpenCopy" xml:space="preserve"><value>Apri</value></data>
<data name="Editor.Workspace.OpenFailed" xml:space="preserve"><value>Progetto non aperto</value></data>
<data name="Editor.Workspace.ReadOnly" xml:space="preserve"><value>Progetto in sola lettura</value></data>
<data name="Editor.Workspace.RemoveFailed" xml:space="preserve"><value>Copia locale non rimossa</value></data>
<data name="Editor.Workspace.Removed" xml:space="preserve"><value>Copia locale rimossa</value></data>
<data name="Editor.Workspace.Renamed" xml:space="preserve"><value>Progetto rinominato</value></data>
<data name="Editor.Workspace.RenderHeld" xml:space="preserve"><value>Render non avviato</value></data>
<data name="Editor.Workspace.Restored" xml:space="preserve"><value>Versione {0} ripristinata</value></data>
<data name="Editor.Workspace.Saved" xml:space="preserve"><value>Versione {0} salvata</value></data>
<data name="Editor.Workspace.SavedAs" xml:space="preserve"><value>Versioni salvate come {0}</value></data>
<data name="Editor.Workspace.SavedSent" xml:space="preserve"><value>Versione {0} salvata e inviata</value></data>
<data name="Editor.Workspace.SendFirst.Action" xml:space="preserve"><value>Invia e renderizza</value></data>
<data name="Editor.Workspace.SendFirst.Message" xml:space="preserve"><value>Il server renderizza {0} come lo conserva: salva prima le modifiche come versione e inviale.</value></data>
<data name="Editor.Workspace.SendFirst.Title" xml:space="preserve"><value>Invia prima del render</value></data>
<data name="Editor.Workspace.State.Ahead" xml:space="preserve"><value>Da inviare</value></data>
<data name="Editor.Workspace.State.Behind" xml:space="preserve"><value>Libreria più nuova</value></data>
<data name="Editor.Workspace.State.Behind.Server" xml:space="preserve"><value>Server più nuovo</value></data>
<data name="Editor.Workspace.State.Conflict" xml:space="preserve"><value>Conflitto</value></data>
<data name="Editor.Workspace.State.Damaged" xml:space="preserve"><value>Danneggiato</value></data>
<data name="Editor.Workspace.State.Gone" xml:space="preserve"><value>Non in libreria</value></data>
<data name="Editor.Workspace.State.Gone.Server" xml:space="preserve"><value>Non sul server</value></data>
<data name="Editor.Workspace.State.InSync" xml:space="preserve"><value>Sincronizzato</value></data>
<data name="Editor.Workspace.State.MediaRemoved" xml:space="preserve"><value>Senza media</value></data>
<data name="Editor.Workspace.State.Modified" xml:space="preserve"><value>Modificato</value></data>
@@ -400,6 +417,7 @@
<data name="Editor.Workspace.SyncFailed" xml:space="preserve"><value>Sincronizzazione non riuscita</value></data>
<data name="Editor.Workspace.Synced" xml:space="preserve"><value>Sincronizzazione eseguita</value></data>
<data name="Editor.Workspace.TookLibrary" xml:space="preserve"><value>Valori della libreria presi</value></data>
<data name="Editor.Workspace.TookLibrary.Server" xml:space="preserve"><value>Valori del server presi</value></data>
<data name="Editor.Workspace.Undo" xml:space="preserve"><value>Annulla</value></data>
<data name="Editor.Workspace.UpdateMedia" xml:space="preserve"><value>Aggiorna media</value></data>
<data name="Editor.Workspace.Updating" xml:space="preserve"><value>Aggiornamento media</value></data>
+9
View File
@@ -55,10 +55,13 @@
<data name="Errors.Workspace.CopyMismatch" xml:space="preserve"><value>{0} non corrispondeva all'originale dopo la copia.</value></data>
<data name="Errors.Workspace.Damaged" xml:space="preserve"><value>Un file di questo progetto nello spazio di lavoro non è leggibile; il log lo indica.</value></data>
<data name="Errors.Workspace.DeletedAtHome" xml:space="preserve"><value>Questo progetto è stato eliminato nella libreria; non è stato rimosso nulla. Scarta modifiche rimuove la sua copia locale.</value></data>
<data name="Errors.Workspace.DeletedAtHome.Server" xml:space="preserve"><value>Questo progetto è stato eliminato sul server; non è stato rimosso nulla. Scarta modifiche rimuove la sua copia locale.</value></data>
<data name="Errors.Workspace.DiskFull" xml:space="preserve"><value>Al disco dello spazio di lavoro servono altri {0} GB per questa copia.</value></data>
<data name="Errors.Workspace.EditNotStored" xml:space="preserve"><value>L'ultima modifica non è ancora stata memorizzata; viene ritentata, riprova tra un momento.</value></data>
<data name="Errors.Workspace.FolderUnusable" xml:space="preserve"><value>{0} non si può usare come cartella dello spazio di lavoro; il registro dice perché.</value></data>
<data name="Errors.Workspace.Forbidden" xml:space="preserve"><value>Il tuo account non può modificare i progetti di questo server.</value></data>
<data name="Errors.Workspace.HomeCheck" xml:space="preserve"><value>La copia di questo progetto nella libreria non corrisponde a quanto inviato; non è stato rimosso nulla.</value></data>
<data name="Errors.Workspace.HomeCheck.Server" xml:space="preserve"><value>La copia di questo progetto sul server non corrisponde a quanto inviato; non è stato rimosso nulla.</value></data>
<data name="Errors.Workspace.InsideLibrary" xml:space="preserve"><value>La cartella dello spazio di lavoro è dentro una libreria; non vi viene copiato nulla.</value></data>
<data name="Errors.Workspace.InsideLibraryEdit" xml:space="preserve"><value>La cartella dello spazio di lavoro {0} è dentro una libreria, dove Modifica non copia nulla: scegli un'altra cartella dello spazio di lavoro.</value></data>
<data name="Errors.Workspace.InsideLibraryFolder" xml:space="preserve"><value>{0} è dentro una libreria, dove Modifica non copia nulla: scegli una cartella fuori dalle tue librerie.</value></data>
@@ -68,17 +71,23 @@
<data name="Errors.Workspace.MediaMissing" xml:space="preserve"><value>Lo spazio di lavoro non ha foto di questo progetto; riaprilo per copiarle.</value></data>
<data name="Errors.Workspace.NameTaken" xml:space="preserve"><value>Un altro progetto di questa sequenza ha già quel nome.</value></data>
<data name="Errors.Workspace.NewerCopy" xml:space="preserve"><value>Un Chronos più recente ha salvato questa copia nello spazio di lavoro; aggiorna Chronos per aprirla o rimuoverla.</value></data>
<data name="Errors.Workspace.NoProjects" xml:space="preserve"><value>Questo server non conserva progetti: va aggiornato prima di poterne modificare le sequenze nello spazio di lavoro.</value></data>
<data name="Errors.Workspace.NoRoom" xml:space="preserve"><value>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.</value></data>
<data name="Errors.Workspace.NotCheckedOut" xml:space="preserve"><value>Il progetto non è più nello spazio di lavoro.</value></data>
<data name="Errors.Workspace.Offline" xml:space="preserve"><value>La libreria ora non è raggiungibile; il tuo lavoro resta nello spazio di lavoro e potrà essere inviato quando torna.</value></data>
<data name="Errors.Workspace.Offline.Server" xml:space="preserve"><value>Il server ora non è raggiungibile; il tuo lavoro resta nello spazio di lavoro e potrà essere inviato quando torna.</value></data>
<data name="Errors.Workspace.OriginalsLater" xml:space="preserve"><value>Per ora lo spazio di lavoro copia i proxy; la copia degli originali arriverà in una versione successiva.</value></data>
<data name="Errors.Workspace.OtherHome" xml:space="preserve"><value>Il progetto dello spazio di lavoro appartiene a un'altra sequenza.</value></data>
<data name="Errors.Workspace.Parameters" xml:space="preserve"><value>Il job di copia di lavoro non ha parametri validi.</value></data>
<data name="Errors.Workspace.ProjectGone" xml:space="preserve"><value>Questo progetto non è più nella libreria.</value></data>
<data name="Errors.Workspace.ProjectGone.Server" xml:space="preserve"><value>Questo progetto non è più sul server.</value></data>
<data name="Errors.Workspace.ReadOnly" xml:space="preserve"><value>Questo progetto è stato salvato da un Chronos più recente: si apre in sola lettura.</value></data>
<data name="Errors.Workspace.ReadOnlyHome" xml:space="preserve"><value>La libreria ora è di sola lettura; il tuo lavoro resta nello spazio di lavoro e potrà essere inviato quando sarà scrivibile.</value></data>
<data name="Errors.Workspace.Refused" xml:space="preserve"><value>La libreria ha rifiutato una versione di questo progetto; il log spiega il motivo.</value></data>
<data name="Errors.Workspace.Refused.Server" xml:space="preserve"><value>Il server ha rifiutato una versione di questo progetto; il log spiega il motivo.</value></data>
<data name="Errors.Workspace.SequenceGone" xml:space="preserve"><value>La sequenza di questo progetto non è più nella libreria: si può solo rimuoverne la copia locale, dal menu del selettore.</value></data>
<data name="Errors.Workspace.Unsent" xml:space="preserve"><value>Parte del lavoro non è ancora nella libreria: prima inviala oppure scartala.</value></data>
<data name="Errors.Workspace.Unsent.Server" xml:space="preserve"><value>Parte del lavoro non è ancora sul server: prima inviala oppure scartala.</value></data>
<data name="Errors.Workspace.VersionTooLarge" xml:space="preserve"><value>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.</value></data>
<data name="Errors.Workspace.VersionTooLarge.Server" xml:space="preserve"><value>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.</value></data>
</root>
+1
View File
@@ -197,6 +197,7 @@
<data name="Server.Sync.Action.GetExports" xml:space="preserve"><value>Ricevi esportazioni</value></data>
<data name="Server.Sync.Action.KeepMine" xml:space="preserve"><value>Tieni le mie</value></data>
<data name="Server.Sync.Action.OpenWithProxies" xml:space="preserve"><value>Apri con i proxy</value></data>
<data name="Server.Sync.Action.OpenInWorkspace" xml:space="preserve"><value>Apri nello spazio di lavoro</value></data>
<data name="Server.Sync.Action.Pause" xml:space="preserve"><value>Pausa</value></data>
<data name="Server.Sync.Action.Resume" xml:space="preserve"><value>Riprendi</value></data>
<data name="Server.Sync.Action.SaveBoth" xml:space="preserve"><value>Salva entrambe</value></data>
+38
View File
@@ -209,7 +209,9 @@
<data name="Tooltips.Editor.History.Compare" xml:space="preserve"><value>Mostra le impostazioni diverse tra la versione {0} e il progetto attuale</value></data>
<data name="Tooltips.Editor.History.Current" xml:space="preserve"><value>Il progetto ora è questa versione</value></data>
<data name="Tooltips.Editor.History.NotSent" xml:space="preserve"><value>Salvata qui, in attesa di essere inviata alla libreria</value></data>
<data name="Tooltips.Editor.History.NotSent.Server" xml:space="preserve"><value>Salvata qui, in attesa di essere inviata al server</value></data>
<data name="Tooltips.Editor.History.Offline" xml:space="preserve"><value>La libreria non è raggiungibile: sono elencate le versioni che questo PC conserva</value></data>
<data name="Tooltips.Editor.History.Offline.Server" xml:space="preserve"><value>Il server non è raggiungibile: sono elencate le versioni che questo PC conserva</value></data>
<data name="Tooltips.Editor.History.Restore" xml:space="preserve"><value>Rendi di nuovo la versione {0} il progetto (un passo: Ctrl+Z lo annulla); le modifiche non salvate diventano prima una versione</value></data>
<data name="Tooltips.Editor.Motion.Blur" xml:space="preserve"><value>Aggiunge mosso lungo il movimento come un tempo più lungo; richiede il flusso ottico su ogni fotogramma</value></data>
<data name="Tooltips.Editor.Motion.Flow" xml:space="preserve"><value>Precisione del flusso ottico per mosso e fotogrammi sintetici; Massima è la più lenta</value></data>
@@ -226,13 +228,16 @@
<data name="Tooltips.Editor.NotApplicable.StabilizeOff" xml:space="preserve"><value>Non applicabile: la stabilizzazione è spenta</value></data>
<data name="Tooltips.Editor.NotApplicable.StackOff" xml:space="preserve"><value>Non applicabile: lo stacking è spento</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Existing" xml:space="preserve"><value>Apri un progetto che la libreria ha per questa sequenza; Principale ne contiene le impostazioni attuali</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Existing.Server" xml:space="preserve"><value>Apri un progetto che il server ha per questa sequenza; Principale ne contiene le impostazioni attuali</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Free" xml:space="preserve"><value>Spazio libero sull'unità della cartella dello spazio di lavoro; la copia lascia liberi anche 0,5 GB</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Name" xml:space="preserve"><value>Il nome del nuovo progetto: da 1 a 60 caratteri, ogni nome una sola volta per sequenza</value></data>
<data name="Tooltips.Editor.OpenWorkspace.New" xml:space="preserve"><value>Un nuovo progetto di questa sequenza, a partire da Principale</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Open" xml:space="preserve"><value>Copia le foto del progetto nello spazio di lavoro, poi aprilo lì</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Originals" xml:space="preserve"><value>La copia degli originali, per renderizzare su questo PC, arriverà in un aggiornamento successivo</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Projects" xml:space="preserve"><value>I progetti della sequenza nella libreria</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Projects.Server" xml:space="preserve"><value>I progetti della sequenza sul server</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Proxies" xml:space="preserve"><value>Copia i proxy: leggeri e veloci da modificare; i render usano gli originali della libreria</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Proxies.Server" xml:space="preserve"><value>Scarica i proxy del server: leggeri e veloci da modificare; i render avvengono sul server, con gli originali</value></data>
<data name="Tooltips.Editor.OpenWorkspace.Size" xml:space="preserve"><value>Quanto scrive nello spazio di lavoro la copia dei proxy, come stimato prima che inizi</value></data>
<data name="Tooltips.Editor.OptimiseAll" xml:space="preserve"><value>Lascia che il consulente imposti ogni sezione dall’analisi ed elenchi cosa è cambiato</value></data>
<data name="Tooltips.Editor.OptimiseNone" xml:space="preserve"><value>Il consulente non fa mai stacking da solo: una mediana cancella le stelle in movimento</value></data>
@@ -261,29 +266,38 @@
<data name="Tooltips.Editor.Preview.Vectors" xml:space="preserve"><value>Sovrappone il movimento verso il fotogramma successivo misurato dal motore</value></data>
<data name="Tooltips.Editor.Preview.View" xml:space="preserve"><value>Trascina la linea per confrontare · trascina per spostare · la rotellina ingrandisce · doppio clic 1:1</value></data>
<data name="Tooltips.Editor.Project.Delete" xml:space="preserve"><value>Invia le versioni di questo progetto alla libreria, poi spostalo nel cestino dei progetti della libreria</value></data>
<data name="Tooltips.Editor.Project.Delete.Server" xml:space="preserve"><value>Invia le versioni di questo progetto al server, poi spostalo nel cestino dei progetti del server</value></data>
<data name="Tooltips.Editor.Project.DeleteAction" xml:space="preserve"><value>Sposta il progetto, con tutte le sue versioni, nel cestino dei progetti della libreria</value></data>
<data name="Tooltips.Editor.Project.DeleteAction.Server" xml:space="preserve"><value>Sposta il progetto, con tutte le sue versioni, nel cestino dei progetti del server</value></data>
<data name="Tooltips.Editor.Project.History" xml:space="preserve"><value>Le versioni del progetto: confrontane una con lo stato attuale o ripristinala</value></data>
<data name="Tooltips.Editor.Project.Keep" xml:space="preserve"><value>Tieni il progetto com'è</value></data>
<data name="Tooltips.Editor.Project.Menu" xml:space="preserve"><value>Progetto {0} ({1}): salva una versione, sincronizza, cronologia, altri progetti e copia locale</value></data>
<data name="Tooltips.Editor.Project.New" xml:space="preserve"><value>Crea un altro progetto di questa sequenza a partire da questo (per esempio un taglio verticale per i social)</value></data>
<data name="Tooltips.Editor.Project.Open" xml:space="preserve"><value>Apri un altro progetto di questa sequenza: uno della libreria o uno nuovo</value></data>
<data name="Tooltips.Editor.Project.RemoveCopy" xml:space="preserve"><value>Libera spazio su questo PC: elimina le foto copiate nello spazio di lavoro; il progetto resta nella libreria</value></data>
<data name="Tooltips.Editor.Project.RemoveCopy.Server" xml:space="preserve"><value>Libera spazio su questo PC: elimina le foto copiate nello spazio di lavoro; il progetto resta sul server</value></data>
<data name="Tooltips.Editor.Project.Rename" xml:space="preserve"><value>Dai un altro nome a questo progetto, qui e nella libreria</value></data>
<data name="Tooltips.Editor.Project.Rename.Server" xml:space="preserve"><value>Dai un altro nome a questo progetto, qui e sul server</value></data>
<data name="Tooltips.Editor.Project.SaveVersion" xml:space="preserve"><value>Tieni il progetto com'è ora come versione della sua cronologia, con una nota facoltativa (Ctrl+S)</value></data>
<data name="Tooltips.Editor.ProjectFile.Remote" xml:space="preserve"><value>I file di progetto sono per le sequenze di un archivio su questo PC</value></data>
<data name="Tooltips.Editor.ProjectFile.Retry" xml:space="preserve"><value>Applica di nuovo le impostazioni del file di progetto</value></data>
<data name="Tooltips.Editor.ProjectFile.Save" xml:space="preserve"><value>Salva un file .chronos che, con un doppio clic, apre questa sequenza con queste impostazioni</value></data>
<data name="Tooltips.Editor.ProjectFile.Undo" xml:space="preserve"><value>Ripristina le impostazioni che la sequenza aveva prima di aprire il file · Ctrl+Z</value></data>
<data name="Tooltips.Editor.ProjectName.Apply" xml:space="preserve"><value>Rinomina il progetto qui e nella libreria</value></data>
<data name="Tooltips.Editor.ProjectName.Apply.Server" xml:space="preserve"><value>Rinomina il progetto qui e sul server</value></data>
<data name="Tooltips.Editor.ProjectName.Create" xml:space="preserve"><value>Crea il progetto nella libreria e aprilo nello spazio di lavoro</value></data>
<data name="Tooltips.Editor.ProjectName.Create.Server" xml:space="preserve"><value>Crea il progetto sul server e aprilo nello spazio di lavoro</value></data>
<data name="Tooltips.Editor.ProjectName.Name" xml:space="preserve"><value>Da 1 a 60 caratteri, ogni nome una sola volta per sequenza</value></data>
<data name="Tooltips.Editor.ReadOnly" xml:space="preserve"><value>Il tuo account può vedere questa sequenza del server ma non modificarla</value></data>
<data name="Tooltips.Editor.Remote" xml:space="preserve"><value>Modificata con i proxy su questo PC; le modifiche si salvano su {0} e analisi e render vengono eseguiti lì</value></data>
<data name="Tooltips.Editor.RemoteReadOnly" xml:space="preserve"><value>Mostrata da {0}; il tuo account può vedere questa sequenza ma non modificarla</value></data>
<data name="Tooltips.Editor.RemoveCopy.Discard" xml:space="preserve"><value>Rimuovi la copia senza inviare ciò che non è nella libreria; quel lavoro resta da parte nel cestino dello spazio di lavoro</value></data>
<data name="Tooltips.Editor.RemoveCopy.Discard.Server" xml:space="preserve"><value>Rimuovi la copia senza inviare ciò che non è sul server; quel lavoro resta da parte nel cestino dello spazio di lavoro</value></data>
<data name="Tooltips.Editor.RemoveCopy.Keep" xml:space="preserve"><value>Mantieni la copia locale com'è</value></data>
<data name="Tooltips.Editor.RemoveCopy.Remove" xml:space="preserve"><value>Elimina la copia di lavoro; ogni versione è nella libreria</value></data>
<data name="Tooltips.Editor.RemoveCopy.Remove.Server" xml:space="preserve"><value>Elimina la copia di lavoro; ogni versione è sul server</value></data>
<data name="Tooltips.Editor.RemoveCopy.SendFirst" xml:space="preserve"><value>Salva e invia ciò che non è ancora nella libreria, poi rimuovi la copia</value></data>
<data name="Tooltips.Editor.RemoveCopy.SendFirst.Server" xml:space="preserve"><value>Salva e invia ciò che non è ancora sul server, poi rimuovi la copia</value></data>
<data name="Tooltips.Editor.Render" xml:space="preserve"><value>Renderizza con il preset scelto; avanzamento nella barra dei lavori · Ctrl+R</value></data>
<data name="Tooltips.Editor.Render.NameError" xml:space="preserve"><value>Correggi prima il nome del file: {0}</value></data>
<data name="Tooltips.Editor.Render.NoFrames" xml:space="preserve"><value>Tutti i fotogrammi sono esclusi: includine alcuni nel passo Fotogrammi</value></data>
@@ -298,6 +312,7 @@
<data name="Tooltips.Editor.Save.Retry" xml:space="preserve"><value>Prova a salvare ora; il salvataggio viene anche ritentato da solo</value></data>
<data name="Tooltips.Editor.SaveVersion.Note" xml:space="preserve"><value>Cosa è cambiato, come lo mostrerà la cronologia (facoltativo)</value></data>
<data name="Tooltips.Editor.SaveVersion.Save" xml:space="preserve"><value>Salva la versione e inviala alla libreria quando la sincronizzazione automatica è attiva</value></data>
<data name="Tooltips.Editor.SaveVersion.Save.Server" xml:space="preserve"><value>Salva la versione e inviala al server quando la sincronizzazione automatica è attiva</value></data>
<data name="Tooltips.Editor.ServerJob" xml:space="preserve"><value>{0} in corso su {1}</value></data>
<data name="Tooltips.Editor.ServerJob.Cancel" xml:space="preserve"><value>Annulla l’attività su {0}; Riprova nell’avviso che segue la rimette in coda dall’ultimo punto di ripresa</value></data>
<data name="Tooltips.Editor.ServerJob.Paused" xml:space="preserve"><value>{0} in pausa su {1}</value></data>
@@ -330,32 +345,53 @@
<data name="Tooltips.Editor.Unsaved.Keep" xml:space="preserve"><value>Resta nell’editor; il salvataggio viene ritentato in background</value></data>
<data name="Tooltips.Editor.Workspace.ChooseFolder" xml:space="preserve"><value>Scegli una cartella dello spazio di lavoro fuori dalle tue librerie; non viene spostato nulla</value></data>
<data name="Tooltips.Editor.Workspace.Differences" xml:space="preserve"><value>Le impostazioni diverse: il tuo valore, poi quello della libreria</value></data>
<data name="Tooltips.Editor.Workspace.Differences.Server" xml:space="preserve"><value>Le impostazioni diverse: il tuo valore, poi quello del server</value></data>
<data name="Tooltips.Editor.Workspace.KeepMine" xml:space="preserve"><value>Tieni i tuoi valori di queste impostazioni; vengono inviati alla libreria</value></data>
<data name="Tooltips.Editor.Workspace.KeepMine.Server" xml:space="preserve"><value>Tieni i tuoi valori di queste impostazioni; vengono inviati al server</value></data>
<data name="Tooltips.Editor.Workspace.Later" xml:space="preserve"><value>Decidi più tardi e continua a modificare; Sincronizza lo chiede di nuovo</value></data>
<data name="Tooltips.Editor.Workspace.MediaChanged" xml:space="preserve"><value>La libreria ha aggiunto, tolto, convertito o verificato foto di questa sequenza dopo che lo spazio di lavoro l'ha copiata</value></data>
<data name="Tooltips.Editor.Workspace.MediaChanged.Server" xml:space="preserve"><value>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</value></data>
<data name="Tooltips.Editor.Workspace.NewerFormat" xml:space="preserve"><value>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</value></data>
<data name="Tooltips.Editor.Workspace.NewerFormat.Server" xml:space="preserve"><value>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</value></data>
<data name="Tooltips.Editor.Workspace.OpenCopy" xml:space="preserve"><value>Apri il progetto {0}, che contiene le tue versioni</value></data>
<data name="Tooltips.Editor.Workspace.SaveBoth" xml:space="preserve"><value>Tieni i valori della libreria in questo progetto e invia i tuoi a un nuovo progetto «{0}»</value></data>
<data name="Tooltips.Editor.Workspace.SaveBoth.Server" xml:space="preserve"><value>Tieni i valori del server in questo progetto e invia i tuoi a un nuovo progetto «{0}»</value></data>
<data name="Tooltips.Editor.Workspace.SaveBothNewer" xml:space="preserve"><value>Invia le tue versioni a un nuovo progetto «{0}»; questo progetto prende quello della libreria, in sola lettura finché Chronos non viene aggiornato</value></data>
<data name="Tooltips.Editor.Workspace.SaveBothNewer.Server" xml:space="preserve"><value>Invia le tue versioni a un nuovo progetto «{0}»; questo progetto prende quello del server, in sola lettura finché Chronos non viene aggiornato</value></data>
<data name="Tooltips.Editor.Workspace.SendFirst.Action" xml:space="preserve"><value>Salva le modifiche come versione, inviala al server, poi renderizza lì quella versione</value></data>
<data name="Tooltips.Editor.Workspace.SendFirst.Keep" xml:space="preserve"><value>Tieni le modifiche qui e per ora non renderizzare</value></data>
<data name="Tooltips.Editor.Workspace.State.Ahead" xml:space="preserve"><value>Versioni salvate qui in attesa di essere inviate alla libreria: {0}. Sincronizza le invia</value></data>
<data name="Tooltips.Editor.Workspace.State.Ahead.Server" xml:space="preserve"><value>Versioni salvate qui in attesa di essere inviate al server: {0}. Sincronizza le invia</value></data>
<data name="Tooltips.Editor.Workspace.State.Behind" xml:space="preserve"><value>Versioni nella libreria non ancora prese da questo spazio di lavoro: {0}. Sincronizza le prende</value></data>
<data name="Tooltips.Editor.Workspace.State.Behind.Server" xml:space="preserve"><value>Versioni sul server non ancora prese da questo spazio di lavoro: {0}. Sincronizza le prende</value></data>
<data name="Tooltips.Editor.Workspace.State.Conflict" xml:space="preserve"><value>Tu e la libreria avete modificato le stesse impostazioni: sincronizza per scegliere quali tenere</value></data>
<data name="Tooltips.Editor.Workspace.State.Conflict.Server" xml:space="preserve"><value>Tu e il server avete modificato le stesse impostazioni: sincronizza per scegliere quali tenere</value></data>
<data name="Tooltips.Editor.Workspace.State.Damaged" xml:space="preserve"><value>Una versione salvata qui non è leggibile (il log indica il file): nulla viene salvato, inviato o ricevuto finché non è riparata</value></data>
<data name="Tooltips.Editor.Workspace.State.DamagedCopy" xml:space="preserve"><value>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</value></data>
<data name="Tooltips.Editor.Workspace.State.Gone" xml:space="preserve"><value>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)</value></data>
<data name="Tooltips.Editor.Workspace.State.Gone.Server" xml:space="preserve"><value>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)</value></data>
<data name="Tooltips.Editor.Workspace.State.InSync" xml:space="preserve"><value>Ogni versione di questo progetto è nella libreria e nulla è cambiato dall'ultima</value></data>
<data name="Tooltips.Editor.Workspace.State.InSync.Server" xml:space="preserve"><value>Ogni versione di questo progetto è sul server e nulla è cambiato dall'ultima</value></data>
<data name="Tooltips.Editor.Workspace.State.MediaRemoved" xml:space="preserve"><value>Lo spazio di lavoro non ha foto di questo progetto: aprirlo le copia di nuovo</value></data>
<data name="Tooltips.Editor.Workspace.State.Modified" xml:space="preserve"><value>Modifiche non ancora salvate come versione: Salva versione (Ctrl+S) le tiene nella cronologia</value></data>
<data name="Tooltips.Editor.Workspace.State.NewerCopy" xml:space="preserve"><value>Un Chronos più recente ha salvato questa copia, quindi questo non può aprirla; aggiorna Chronos: qui nulla viene cambiato o rimosso</value></data>
<data name="Tooltips.Editor.Workspace.State.Offline" xml:space="preserve"><value>La libreria ora non è raggiungibile: il tuo lavoro resta qui e viene inviato quando torna</value></data>
<data name="Tooltips.Editor.Workspace.State.Offline.Server" xml:space="preserve"><value>Il server ora non è raggiungibile: il tuo lavoro resta qui e viene inviato quando torna</value></data>
<data name="Tooltips.Editor.Workspace.State.OfflineAhead" xml:space="preserve"><value>La libreria ora non è raggiungibile. Versioni in attesa di essere inviate quando torna: {0}</value></data>
<data name="Tooltips.Editor.Workspace.State.OfflineAhead.Server" xml:space="preserve"><value>Il server ora non è raggiungibile. Versioni in attesa di essere inviate quando torna: {0}</value></data>
<data name="Tooltips.Editor.Workspace.State.Reading" xml:space="preserve"><value>Chiede alla libreria lo stato di questo progetto</value></data>
<data name="Tooltips.Editor.Workspace.State.Reading.Server" xml:space="preserve"><value>Chiede al server lo stato di questo progetto</value></data>
<data name="Tooltips.Editor.Workspace.State.Syncing" xml:space="preserve"><value>Prende le nuove versioni della libreria e invia le tue</value></data>
<data name="Tooltips.Editor.Workspace.State.Syncing.Server" xml:space="preserve"><value>Prende le nuove versioni del server e invia le tue</value></data>
<data name="Tooltips.Editor.Workspace.TakeHome" xml:space="preserve"><value>Usa nell'editor i valori della libreria per queste impostazioni</value></data>
<data name="Tooltips.Editor.Workspace.TakeHome.Server" xml:space="preserve"><value>Usa nell'editor i valori del server per queste impostazioni</value></data>
<data name="Tooltips.Editor.Workspace.TakeHomeUndo" xml:space="preserve"><value>Usa i valori della libreria per queste impostazioni; Ctrl+Z riporta i tuoi</value></data>
<data name="Tooltips.Editor.Workspace.TakeHomeUndo.Server" xml:space="preserve"><value>Usa i valori del server per queste impostazioni; Ctrl+Z riporta i tuoi</value></data>
<data name="Tooltips.Editor.Workspace.Undo" xml:space="preserve"><value>Riporta il progetto com'era prima del ripristino</value></data>
<data name="Tooltips.Editor.Workspace.UndoTake" xml:space="preserve"><value>Riporta i tuoi valori delle impostazioni sostituite da quelli della libreria</value></data>
<data name="Tooltips.Editor.Workspace.UndoTake.Server" xml:space="preserve"><value>Riporta i tuoi valori delle impostazioni sostituite da quelli del server</value></data>
<data name="Tooltips.Editor.Workspace.UpdateMedia" xml:space="preserve"><value>Copia di nuovo i fotogrammi della libreria nello spazio di lavoro; i fotogrammi esclusi o con keyframe seguono le loro foto</value></data>
<data name="Tooltips.Editor.Workspace.UpdateMedia.Server" xml:space="preserve"><value>Scarica di nuovo i fotogrammi del server nello spazio di lavoro; i fotogrammi esclusi o con keyframe seguono le loro foto</value></data>
<data name="Tooltips.Import.Again" xml:space="preserve"><value>Importa di nuovo le foto già in archivio; nulla viene sovrascritto</value></data>
<data name="Tooltips.Import.Archive" xml:space="preserve"><value>Copia nell'archivio di questo PC con i modelli dei nomi · {0}</value></data>
<data name="Tooltips.Import.Auto" xml:space="preserve"><value>Avvia l'importazione con le impostazioni della scheda appena viene inserita; un avviso permette di annullare</value></data>
@@ -676,6 +712,8 @@
<data name="Tooltips.Server.Sync.LastSync" xml:space="preserve"><value>Quando questo PC ha confrontato per l'ultima volta tutte le sequenze con il server, e quanto ha impiegato</value></data>
<data name="Tooltips.Server.Sync.OpenAdmin" xml:space="preserve"><value>Apri l'amministrazione web nel browser (solo amministratori)</value></data>
<data name="Tooltips.Server.Sync.OpenWithProxies" xml:space="preserve"><value>Apri in Modifica sui proxy; il rendering avviene sul server</value></data>
<data name="Tooltips.Server.Sync.OpenInWorkspace" xml:space="preserve"><value>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ì</value></data>
<data name="Tooltips.Server.Sync.OpenInWorkspace.NoProjects" xml:space="preserve"><value>Questo server non conserva ancora progetti (va aggiornato): Apri con i proxy modifica la sequenza sul server come prima</value></data>
<data name="Tooltips.Server.Sync.Pause" xml:space="preserve"><value>Metti in pausa questo trasferimento; riprende da dove si è fermato</value></data>
<data name="Tooltips.Server.Sync.Resume" xml:space="preserve"><value>Riprendi questo trasferimento da dove si è fermato</value></data>
<data name="Tooltips.Server.Sync.Retrying" xml:space="preserve"><value>L'ultimo confronto non è riuscito: {0}. Viene ripetuto automaticamente.</value></data>
+14 -9
View File
@@ -625,6 +625,8 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
/// </summary>
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);
});
/// <summary>The conflict prompt of a workspace project: what differs (the editor's value, then the library's) and what each choice keeps.</summary>
internal static ConfirmRequest LibraryConflictRequest(ProjectConflictException conflict, string title) => new()
/// <summary>
/// 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 <paramref name="server"/> home (phase 5b) or the library.
/// </summary>
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,
};
+16 -144
View File
@@ -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<Guid, Job> _jobs = new();
private readonly ConcurrentDictionary<Guid, byte> _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.
/// </remarks>
public async Task<Guid> SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken)
public Task<Guid> 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<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken)
{
var active = await Call(() => _api.ListActiveJobsAsync(cancellationToken));
var mine = active.Select(JobWire.FromDto).OfType<Job>().Where(Concerns).ToList();
foreach (var job in mine) _jobs[job.Id] = job;
return mine;
}
public Task<IReadOnlyList<Job>> 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();
}
}
/// <summary>
/// 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.
/// </summary>
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}");
}
}
}
/// <summary>The server's events besides the jobs': frames added or removed on the server make the sequence outdated.</summary>
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);
}
/// <summary>Reads a job the events named: tracked when it concerns this sequence, remembered as foreign otherwise.</summary>
private async Task FetchAsync(Guid jobId, CancellationToken cancellationToken)
/// <summary>A frames change announced while the event socket was down is found now rather than at the next save.</summary>
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);
}
/// <summary>Frames added or removed on the server: whether this PC's frames are still the sequence's.</summary>
@@ -326,34 +238,6 @@ public sealed class RemoteSequenceSource : ISequenceSource
}
}
/// <summary>Sets a priority other than the user's on a job the server just queued; the job stays queued if that fails.</summary>
private async Task<JobDto> 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;
}
}
/// <summary>After a lost event socket: the tracked jobs as the server has them now.</summary>
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);
}
/// <summary>
/// Takes the server's frames as <paramref name="manifest"/> 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;
/// <summary>The frame of the project's hero, or <see cref="Guid.Empty"/> (the first frame shows) without one.</summary>
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
}
/// <summary>A sequence deleted on the server reads as gone, like a local one removed from the index.</summary>
private static async Task<T> Call<T>(Func<Task<T>> 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<T> Call<T>(Func<Task<T>> call) => ServerJobs.Call(call);
/// <summary>The server's settings as last read or written, with the version a save must name.</summary>
private sealed record Stored(ProjectSettings Project, int Version);
+225
View File
@@ -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;
/// <summary>
/// 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
/// (<see cref="RemoteSequenceSource"/>) and a workspace project whose home is a server (<see cref="WorkspaceSequenceSource"/>,
/// owner review 2, R8) run on the server. Events of other kinds go to <c>other</c>; <c>reconnected</c> runs after the jobs
/// were read again. Owns the connection: disposing stops listening and disposes it.
/// </summary>
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<Job> _changed;
private readonly Func<ServerEvent, CancellationToken, Task>? _other;
private readonly Func<CancellationToken, Task>? _reconnected;
private readonly ConcurrentDictionary<Guid, Job> _jobs = new();
private readonly ConcurrentDictionary<Guid, byte> _foreign = new();
private readonly CancellationTokenSource _stopping = new();
private readonly Task _listening;
private int _disposed;
/// <param name="changed">A job of the sequence changed (any thread).</param>
public ServerJobs(IRemoteSequenceApi api, Guid sequenceId, string title, Action<Job> changed, Func<ServerEvent, CancellationToken, Task>? other = null,
Func<CancellationToken, Task>? 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);
}
/// <summary>The connection the jobs travel on (the source's other calls use it too).</summary>
public IRemoteSequenceApi Api { get; }
/// <summary>Queues <paramref name="request"/> on the server (its priority set after, when it is not the user's); returns the job id.</summary>
/// <exception cref="EditorException">The sequence is gone from the server.</exception>
public async Task<Guid> 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;
}
/// <summary>The analyses and renders of the sequence waiting, running or paused on the server, followed from now on.</summary>
public async Task<IReadOnlyList<Job>> ListAsync(CancellationToken cancellationToken)
{
var active = await Call(() => Api.ListActiveJobsAsync(cancellationToken));
var mine = active.Select(JobWire.FromDto).OfType<Job>().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();
}
}
/// <summary>
/// Follows the server's events until disposed, reconnecting with a growing delay (job states lost meanwhile are read
/// back from the jobs, then <c>reconnected</c> runs). Nothing that fails on the way ends it.
/// </summary>
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;
}
}
/// <summary>Reads a job the events named: tracked when it concerns this sequence, remembered as foreign otherwise.</summary>
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}");
}
}
/// <summary>Sets a priority other than the user's on a job the server just queued; the job stays queued if that fails.</summary>
private async Task<JobDto> 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;
}
}
/// <summary>After a lost event socket: the tracked jobs as the server has them now.</summary>
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;
/// <summary>A sequence deleted on the server reads as gone, like a local one removed from the index.</summary>
internal static async Task<T> Call<T>(Func<Task<T>> call)
{
try
{
return await call();
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
throw new EditorException(Loc.L("Editor.Error.Missing"), ex);
}
}
}
+248 -16
View File
@@ -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<ArchiveJobRequest> RenderRequests(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight);
}
/// <summary>
/// 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).
/// </summary>
public sealed record WorkspaceServerHome(IRemoteSequenceApi? Api);
/// <summary>
/// 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 (<c>media/media.json</c>, the proxies), the project
@@ -42,6 +51,11 @@ public interface IProjectRenders
/// (<see cref="RenderRequests"/>). 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
/// (<see cref="FramesChangedException"/>) until the editor has read them again and moved its positions by frame.
/// A project whose home is a server (<see cref="WorkspaceServerHome"/>, phase 5b) is a remote one for the editor: its
/// analyses and renders are the server's jobs (<see cref="ServerJobs"/>), 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.
/// </summary>
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<IRenderFrameSource> _retired = [];
private IRenderFrameSource? _frames;
private IFrameSource? _pixels;
private ServerJobs? _serverJobs;
private int _frameCount;
private int _framesVersion = -1;
private Guid[] _frameIds = [];
private HashSet<Guid> _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)
/// <param name="server">The server the project's home is (phase 5b); null for a project of this PC's archive.</param>
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
/// <summary>The photos of the media read last, in frame order (what positions name).</summary>
public FramePhotos Photos => Volatile.Read(ref _photos);
public bool IsRemote => false;
/// <summary>The project's home is a server (phase 5b): its analyses and renders run there.</summary>
public bool IsServerHome => _server is not null;
/// <summary>A server home's analyses and renders run on the server, as for a server sequence opened with proxies.</summary>
public bool IsRemote => _server is not null;
/// <summary>Settings of a newer Chronos: shown, never saved.</summary>
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<Render> renders = row is null ? [] : await _db.Renders.ListBySequenceAsync(home.SequenceId, cancellationToken);
@@ -160,6 +185,123 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
}, cancellationToken);
}
/// <summary>
/// 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.
/// </summary>
private async Task<SequenceContent> 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);
}
/// <summary>The server's jobs of the sequence, followed from now on; null while this PC is not signed in to the server.</summary>
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));
}
}
/// <summary>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.</summary>
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));
}
/// <remarks>Only a copy job changes the workspace's frames (Update media): its media index is compared with the one read last.</remarks>
public Task<bool> FramesCurrentAsync(CancellationToken cancellationToken) => Task.Run(() =>
{
@@ -175,11 +317,26 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
}
}, cancellationToken);
/// <summary>Whether the home's frames moved past those the workspace holds (frames added or removed there): "Update media" copies them again.</summary>
/// <summary>
/// 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.
/// </summary>
public async Task<bool> 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<ImageBuffer?> 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);
/// <remarks>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.</remarks>
public async Task<Guid> 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<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken) =>
(await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items;
/// <remarks>A server home's jobs are the server's; none are listed while it cannot be reached (the project opens all the same).</remarks>
public async Task<IReadOnlyList<Job>> 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);
/// <summary>
/// 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.
/// </summary>
public IReadOnlyList<ArchiveJobRequest> 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) })];
}
/// <summary>
/// The home's version the project is in step with: its base, when no version waits to be sent and the editor's project
/// (<paramref name="project"/>) holds what the base holds; null otherwise.
/// </summary>
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<IRenderFrameSource> 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();
}
}
/// <summary>The server's jobs of the project's sequence, or why there are none.</summary>
/// <exception cref="EditorException">This PC is not signed in to the server of the project.</exception>
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"));
/// <summary>
/// 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);
}
/// <summary>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.</summary>
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);
}
/// <summary>
/// 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.
@@ -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
/// </summary>
public event Action<Guid>? SequenceReorganized;
/// <summary>The workspace where Edit opens projects (owner review 2, R8), with this PC's archive as their home.</summary>
/// <summary>The workspace where Edit opens projects (owner review 2, R8), with this PC's archive or the signed-in server as their home.</summary>
public WorkspaceHost Workspace { get; }
public IEncoderInventory Encoders { get; set; }
@@ -175,12 +178,13 @@ public sealed class AppServices : IAsyncDisposable
typeof(AppServices).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0";
/// <summary>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.</summary>
/// 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.</summary>
public static IReadOnlyList<IJobHandler> 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) : [],
];
/// <summary>
@@ -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();
}
/// <summary>
/// A project's home told it changed there (any thread; phase 5b: a server's <c>projectChanged</c>), or that changes may
/// have been missed: the listed projects it concerns read their state again (Server newer, Deleted).
/// </summary>
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;
+5 -5
View File
@@ -123,11 +123,11 @@
<Separator />
<MenuItem Header="{l:Loc Editor.Project.Open}" Command="{Binding Project.OpenProjectCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.Open}" />
<MenuItem Header="{l:Loc Editor.Project.New}" Command="{Binding Project.NewProjectCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.New}" />
<MenuItem Header="{l:Loc Editor.Project.Rename}" Command="{Binding Project.RenameCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.Rename}" />
<MenuItem Header="{l:Loc Editor.Project.Rename}" Command="{Binding Project.RenameCommand}" ToolTip="{Binding Project.RenameToolTip}" />
<MenuItem Header="{l:Loc Editor.Project.Delete}" Command="{Binding Project.DeleteCommand}" ToolTip="{Binding Project.DeleteToolTip}"
ToolTipService.ShowOnDisabled="True" />
<Separator />
<MenuItem Header="{l:Loc Editor.Project.RemoveCopy}" Command="{Binding Project.RemoveCopyCommand}" ToolTip="{l:Loc Tooltips.Editor.Project.RemoveCopy}" />
<MenuItem Header="{l:Loc Editor.Project.RemoveCopy}" Command="{Binding Project.RemoveCopyCommand}" ToolTip="{Binding Project.RemoveCopyToolTip}" />
</ContextMenu>
</Button.ContextMenu>
</Button>
@@ -164,13 +164,13 @@
</StackPanel>
</Grid>
<!-- Owner review 2, R8: the library's frames moved past the workspace's; Update media copies them again (positions follow their photos). -->
<!-- Owner review 2, R8: the home's frames (the library's or the server's) moved past the workspace's; Update media copies them again (positions follow their photos). -->
<Border Grid.Row="1" Style="{StaticResource Border.Card}" Padding="12,6" Margin="0,0,0,8"
Visibility="{Binding Project.HasMediaUpdate, Converter={StaticResource BoolToVisibility}, FallbackValue=Collapsed}">
<DockPanel>
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Compact}" Content="{l:Loc Editor.Workspace.UpdateMedia}" Command="{Binding Project.UpdateMediaCommand}"
ToolTip="{l:Loc Tooltips.Editor.Workspace.UpdateMedia}" ToolTipService.ShowOnDisabled="True" />
<ui:StatusGlyph Kind="Warning" Text="{Binding Project.MediaUpdateText}" ToolTip="{l:Loc Tooltips.Editor.Workspace.MediaChanged}" VerticalAlignment="Center"
ToolTip="{Binding Project.UpdateMediaToolTip}" ToolTipService.ShowOnDisabled="True" />
<ui:StatusGlyph Kind="Warning" Text="{Binding Project.MediaUpdateText}" ToolTip="{Binding Project.MediaChangedToolTip}" VerticalAlignment="Center"
infra:LiveRegion.Text="{Binding Project.MediaUpdateText}" AutomationProperties.LiveSetting="Polite" />
</DockPanel>
</Border>
+145 -24
View File
@@ -14,8 +14,10 @@ using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Protocol.Client;
using Chronos.Ui.Mvvm;
@@ -27,9 +29,11 @@ namespace Chronos.App.Sections;
/// Server screen or its own picker chose into an <see cref="EditorViewModel"/>. A sequence of this PC's archive opens as a
/// project of the workspace (owner review 2, R8: editing never happens inside the library): the project of that sequence
/// opened last here; else, after "Open in workspace" asked which project (Main, another of its home, or a new one) and
/// which media, the project is checked out and its media copied by a job, and it opens once they are here. A server
/// sequence opens with this PC's proxies (the workspace takes server homes in phase 5b), and a capture (sample data
/// without an engine) opens the library as before. The next sequence is read first; only then does the open one close,
/// which media, the project is checked out and its media copied by a job, and it opens once they are here. A sequence of
/// a server that keeps projects opens the same way as a project whose home is that server (phase 5b: its media downloaded
/// into the workspace; a project already there opens from it, the server reachable or not); one of an older server opens
/// with this PC's proxies, and a capture (sample data without an engine) opens the library as before. The next sequence
/// is read first; only then does the open one close,
/// after its last edit is stored. Without a sequence, or after Change sequence, it shows the picker (the editor stays
/// open behind it until another sequence opens). A server sequence whose proxies are missing or out of date fetches them
/// first and opens once they are here, the open sequence staying open meanwhile; a workspace copy is followed the same
@@ -540,9 +544,10 @@ public sealed class SequenceViewModel : SectionViewModel
/// <summary>
/// Where <paramref name="sequenceId"/> lives: this PC's index (opened as a workspace project,
/// <see cref="OpenWorkspaceAsync"/>; in a capture, the library itself), else a sequence of the signed-in server whose
/// proxies this PC keeps (Server screen, "Open with proxies"), edited through the server (BRIEF §14.5), or only shown
/// when the account may not change it. Null when it cannot open yet: its proxies are being fetched
/// <see cref="OpenWorkspaceAsync"/>; in a capture, the library itself), else a server's sequence: a workspace project
/// whose home is that server (<see cref="OpenServerWorkspaceAsync"/>), or, for a server that keeps no projects, one
/// whose proxies this PC keeps (Server screen, "Open with proxies"), edited through the server (BRIEF §14.5), or only
/// shown when the account may not change it. Null when it cannot open yet: its proxies are being fetched
/// (<see cref="FetchProxiesAsync"/>), its workspace copy runs, or the user closed "Open in workspace".
/// </summary>
private async Task<(ISequenceSource Source, string Title)?> OpenSourceAsync(AppServices services, Guid sequenceId)
@@ -557,14 +562,19 @@ public sealed class SequenceViewModel : SectionViewModel
local.HeroChanged += OnHeroChanged;
return (local, row.DisplayTitle);
}
// A workspace project whose sequence left the index (its trash emptied, its folder gone): not a server's sequence to
// fetch; its local copy can only be removed (the picker's Remove local copy).
// A workspace project of this PC's archive whose sequence left the index (its trash emptied, its folder gone): not a
// server's sequence to fetch; its local copy can only be removed (the picker's Remove local copy).
if (_requested is { ProjectId: { } projectId } asked && asked.SequenceId == sequenceId && services.Workspace.IsEnabled
&& await services.Workspace.FindAsync(projectId) is not null)
&& await services.Workspace.FindAsync(projectId) is { IsServerHome: false })
{
_requested = null;
throw new InvalidOperationException(Loc.L("Errors.Workspace.SequenceGone"));
}
// A server sequence (owner review 2, R8, phase 5b): a project of it in the workspace opens from there, the server
// reachable or not; one of a server that keeps projects is checked out (asked which); an older server's opens with
// proxies as before.
if (services.Workspace.IsEnabled && await OpenServerWorkspaceAsync(services, services.Workspace, db, decoder, sequenceId) is { } project)
return project.Opened;
var sync = services.Sync;
if (sync.Server is not { } server || sync.Service is not { } service || sync.ConnectEditor() is not { } api)
throw new InvalidOperationException(Loc.L("Editor.Error.SignedOut"));
@@ -610,7 +620,7 @@ public sealed class SequenceViewModel : SectionViewModel
// with Remove local copy for a damaged one, when nothing else could be chosen (Main asked for, or the home has no
// other project); otherwise "Open in workspace" lists Main as it is, disabled, and offers the others.
WorkspaceEntry? unreadableMain = null;
if (entry is null && request?.ProjectId is null && await UnreadableMainAsync(workspace, row.Id) is { } main)
if (entry is null && request?.ProjectId is null && await UnreadableMainAsync(workspace, WorkspaceHost.ArchiveHome(row.Id)) is { } main)
{
if (request is { Main: true } || (await workspace.HomeProjectsAsync(row.Id)).All(p => p.IsMain))
{
@@ -664,10 +674,10 @@ public sealed class SequenceViewModel : SectionViewModel
return null;
}
/// <summary>The workspace's copy of the sequence's Main when this Chronos cannot read it (damaged, or a newer Chronos's); null otherwise.</summary>
private static async Task<WorkspaceEntry?> UnreadableMainAsync(WorkspaceHost workspace, Guid sequenceId)
/// <summary>The workspace's copy of the Main of <paramref name="home"/>'s sequence when this Chronos cannot read it (damaged, or a newer Chronos's); null otherwise.</summary>
private static async Task<WorkspaceEntry?> UnreadableMainAsync(WorkspaceHost workspace, BundleHome home)
{
if ((await workspace.HomeProjectsAsync(sequenceId)).FirstOrDefault(p => p.IsMain) is not { } main) return null;
if ((await workspace.HomeProjectsAsync(home)).FirstOrDefault(p => p.IsMain) is not { } main) return null;
return await workspace.FindAsync(main.Id) is { IsReadable: false } copy ? copy : null;
}
@@ -689,22 +699,130 @@ public sealed class SequenceViewModel : SectionViewModel
}
/// <summary>
/// "Open in workspace": the projects of the sequence's home, the media, what their copy writes and the room the
/// workspace's drive has; null when closed without a choice. <paramref name="unreadableMain"/>, the copy of Main here
/// this Chronos cannot read, is listed disabled, why in its tooltip.
/// A sequence of a server opens as a project of the workspace whose home is that server (phase 5b): the project asked
/// for, else the one of the sequence opened last here. One the workspace holds the media of opens from there, whether
/// this PC can reach the server or not (its sync, analyses and renders wait for it). Otherwise, signed in to a server
/// that keeps projects, the project is checked out, after "Open in workspace" asked which (when the sequence has none
/// here), and its media downloaded by a job; it opens once they are here. A copy this Chronos cannot read is refused as
/// for this PC's archive. Null when the server keeps no projects, or this PC is not signed in to it: the sequence then
/// opens with proxies as before (or says to connect).
/// </summary>
private async Task<OpenChoice?> AskProjectAsync(WorkspaceHost workspace, Sequence row, WorkspaceEntry? unreadableMain = null)
private async Task<ServerOpen?> OpenServerWorkspaceAsync(AppServices services, WorkspaceHost workspace, ChronosDatabase db, ImageDecoder decoder, Guid remoteId)
{
var projects = await workspace.HomeProjectsAsync(row.Id);
WorkspaceCopyFacts? copy = null;
var request = _requested is { } asked && asked.SequenceId == remoteId ? asked : null;
var entry = request switch
{
{ ProjectId: { } id } => await workspace.FindAsync(id) is { IsServerHome: true } found && found.SequenceId == remoteId ? found : null,
{ Main: true } => (await workspace.ProjectsOfAsync(remoteId)).FirstOrDefault(p => p is { IsMain: true, IsServerHome: true }),
_ => await workspace.LastUsedAsync(remoteId) is { IsServerHome: true } last ? last : null,
};
var sync = services.Sync;
if (entry is { IsReadable: false } unreadable)
{
TakeRequest(remoteId);
throw WorkspaceHost.Unreadable(unreadable);
}
if (entry is { HasMedia: true })
{
TakeRequest(remoteId);
workspace.Remember(remoteId, entry.ProjectId);
// Its analyses and renders travel on a connection of the signed-in session, when that is the project's server.
var api = string.Equals(sync.Server, entry.Home.Server, StringComparison.OrdinalIgnoreCase) ? sync.ConnectEditor() : null;
return new ServerOpen((new WorkspaceSequenceSource(workspace.Sync, entry.ProjectId, db, decoder, services.Engine, new WorkspaceServerHome(api)),
entry.SequenceTitle));
}
if (sync.ServerHome(remoteId) is not { } home) return null;
TakeRequest(remoteId);
try
{
copy = await workspace.CopyFactsAsync(row.Id);
var reached = workspace.Reachable(home);
var title = (await Task.Run(() => reached.SequenceAsync(CancellationToken.None))).Sequence.Title ?? entry?.SequenceTitle ?? string.Empty;
// No project of the sequence here opens and its Main here cannot be read: refused, or listed disabled, as for this PC's archive.
WorkspaceEntry? unreadableMain = null;
if (entry is null && request?.ProjectId is null && await UnreadableMainAsync(workspace, home) is { } main)
{
if (request is { Main: true } || (await workspace.HomeProjectsAsync(home)).All(p => p.IsMain))
{
RefuseUnreadable(main);
_afterOpen = null;
Shell.KeepSequence(OpenSequenceId);
return new ServerOpen(null);
}
unreadableMain = main;
}
var projectId = entry?.ProjectId ?? request?.ProjectId;
string? newName = null;
if (entry is null && projectId is { } wanted && (await workspace.HomeProjectsAsync(home)).All(p => p.Id != wanted))
{
// A project the server does not have (deleted there, or another server's): the sequence's Main opens instead.
Log.Info("workspace", $"Project {wanted} is not a project of server sequence {remoteId}; its Main opens instead");
projectId = null;
if (_afterOpen is { } pending && pending.Request.SequenceId == remoteId) _afterOpen = (ProjectRequest.MainOf(remoteId), pending.Action);
}
else if (entry is null && projectId is null && request is not { Main: true })
{
if (await AskProjectAsync(workspace, home, title, unreadableMain) is not { } choice)
{
_afterOpen = null;
Shell.KeepSequence(OpenSequenceId);
return new ServerOpen(null);
}
(projectId, newName) = (choice.ProjectId, choice.NewName);
}
WorkspaceCheckout checkout;
try
{
checkout = await workspace.CheckoutAsync(home, projectId, newName);
}
catch (WorkspaceException ex) when (ex.FolderRefused)
{
// Nothing was written: the way on is another workspace folder, offered from the refusal.
Log.Info("workspace", $"Server sequence {remoteId} not checked out: {ex.Message}");
Shell.Notify(Loc.L("Editor.Workspace.OpenFailed"), ex.Message, Loc.L("Editor.Workspace.ChooseFolder"), Loc.L("Tooltips.Editor.Workspace.ChooseFolder"),
() => _ = WorkspaceFolderChange.ChooseAsync(Shell), isError: true);
_afterOpen = null;
Shell.KeepSequence(OpenSequenceId);
return new ServerOpen(null);
}
await FollowCopyAsync(remoteId, title, checkout.Project.Id, checkout.Copy);
return new ServerOpen(null);
}
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or DatabaseException or UnauthorizedAccessException)
catch (ProjectException ex) when (ex.Reason == ProjectError.SequenceNotFound)
{
// Only shown: the copy measures again before it writes.
Log.Info("workspace", $"The copy of sequence {row.Id} could not be measured: {ex.Message}");
throw new InvalidOperationException(Loc.L("Editor.Error.Missing"), ex);
}
catch (HomeUnavailableException ex)
{
// Said of the server, not of this PC's library.
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Offline", server: true), ex);
}
}
/// <summary>"Open in workspace" for a sequence of this PC's archive; null when closed without a choice.</summary>
private Task<OpenChoice?> AskProjectAsync(WorkspaceHost workspace, Sequence row, WorkspaceEntry? unreadableMain = null) =>
AskProjectAsync(workspace, WorkspaceHost.ArchiveHome(row.Id), row.DisplayTitle, unreadableMain);
/// <summary>
/// "Open in workspace" for a sequence of <paramref name="home"/> (this PC's archive, or a server): its projects, the
/// media, and for this PC's archive what their copy writes and the room the workspace's drive has; null when closed
/// without a choice. <paramref name="unreadableMain"/>, the copy of Main here this Chronos cannot read, is listed
/// disabled, why in its tooltip.
/// </summary>
private async Task<OpenChoice?> AskProjectAsync(WorkspaceHost workspace, BundleHome home, string title, WorkspaceEntry? unreadableMain)
{
var projects = await workspace.HomeProjectsAsync(home);
WorkspaceCopyFacts? copy = null;
if (home.IsArchive)
{
try
{
copy = await workspace.CopyFactsAsync(home.SequenceId);
}
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or DatabaseException or UnauthorizedAccessException)
{
// Only shown: the copy measures again before it writes.
Log.Info("workspace", $"The copy of sequence {home.SequenceId} could not be measured: {ex.Message}");
}
}
var unreadable = unreadableMain is { } main
? new Dictionary<Guid, string>
@@ -712,7 +830,7 @@ public sealed class SequenceViewModel : SectionViewModel
[main.ProjectId] = Loc.L(main.Newer ? "Tooltips.Editor.Workspace.State.NewerCopy" : "Tooltips.Editor.Workspace.State.DamagedCopy"),
}
: null;
var dialog = new OpenInWorkspaceDialogViewModel(row.DisplayTitle, projects, d => CloseDialog(d), copy: copy, unreadable: unreadable);
var dialog = new OpenInWorkspaceDialogViewModel(title, projects, d => CloseDialog(d), copy: copy, unreadable: unreadable, server: !home.IsArchive);
// The picker or the open sequence shows behind the dialog meanwhile, not the progress bar.
IsLoading = false;
OpenDialog(dialog);
@@ -888,6 +1006,9 @@ public sealed class SequenceViewModel : SectionViewModel
}
}
/// <summary>What the open of a server sequence as a workspace project came to: its source, or null while it waits (its copy runs, the dialog was closed).</summary>
private sealed record ServerOpen((ISequenceSource Source, string Title)? Opened);
/// <summary>
/// A job an open waits on, with its engine subscription: a server sequence's proxy download, or the workspace copy of a
/// project's media (<see cref="ProjectId"/>: the project that opens when it is done).
+1 -1
View File
@@ -260,7 +260,7 @@
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type srv:SyncRowAction}">
<Button Style="{StaticResource Button.Row}" Content="{Binding Text}" Command="{Binding Command}" ToolTip="{Binding ToolTip}"
AutomationProperties.Name="{Binding AccessibleName}" FontSize="12" Margin="0,2,6,2" />
ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{Binding AccessibleName}" FontSize="12" Margin="0,2,6,2" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
+74 -6
View File
@@ -3,9 +3,12 @@ using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.Core.Diagnostics;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Protocol.Client;
namespace Chronos.App.Server;
@@ -15,23 +18,28 @@ public delegate ISyncRemote SyncRemoteFactory(Uri address, string token, IReadOn
/// <summary>
/// This PC's sync with the signed-in server (BRIEF §4.4, §14.5): the <see cref="SyncService"/> of the index, the
/// connection of upload and download jobs (<see cref="ISyncConnector"/>), a <see cref="SyncAgent"/> that keeps the
/// table current while a session is open, started and stopped in order as the session changes, the
/// <see cref="UploadHold"/> for metered connections, the connections of editors of server sequences
/// (<see cref="ConnectEditor"/>) and the Export "Sync" of finished renders (<see cref="ExportSync"/>). Options come from
/// <see cref="AppSettings.SyncSettingsAutomatically"/>, <see cref="AppSettings.KeepProxiesOffline"/> and
/// <see cref="AppSettings.PauseUploadsOnMetered"/>.
/// connection of upload and download jobs (<see cref="ISyncConnector"/>, also the workspace copies of server projects), a
/// <see cref="SyncAgent"/> that keeps the table current while a session is open, started and stopped in order as the
/// session changes, the <see cref="UploadHold"/> for metered connections, the connections of editors of server sequences
/// (<see cref="ConnectEditor"/>), the server as the home of workspace projects when it keeps projects (owner review 2, R8,
/// phase 5b: <see cref="ProjectHome"/>, <see cref="ProjectChanged"/>) and the Export "Sync" of finished renders
/// (<see cref="ExportSync"/>). Options come from <see cref="AppSettings.SyncSettingsAutomatically"/>,
/// <see cref="AppSettings.KeepProxiesOffline"/> and <see cref="AppSettings.PauseUploadsOnMetered"/>.
/// </summary>
public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDisposable
{
/// <summary>How long a job resumed at start waits for the saved session to be restored.</summary>
private static readonly TimeSpan RestoreWait = TimeSpan.FromSeconds(30);
private readonly Lock _gate = new();
private Task _switch = Task.CompletedTask;
private Credentials? _credentials;
private Running? _running;
private JobEngine? _renders;
/// <summary>The client project homes of the session share, made at first use for the credentials it holds.</summary>
private SharedClient? _projects;
/// <summary>Connections over <see cref="ChronosClient"/>; screenshots substitute a fake server.</summary>
public SyncRemoteFactory RemoteFactory { get; set; } = (address, token, trusted) =>
new ChronosSyncRemote(new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token }, ownsClient: true);
@@ -40,6 +48,10 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
public RemoteSequenceApiFactory EditorFactory { get; set; } = (address, token, trusted) =>
new ChronosRemoteSequenceApi(new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token });
/// <summary>The client the session's project homes share (<see cref="ProjectHome"/>); tests substitute one of their own.</summary>
public Func<Uri, string, IReadOnlyCollection<string>, ChronosClient> ProjectClientFactory { get; set; } = (address, token, trusted) =>
new ChronosClient(address, new CertificatePinning(trusted), $"Chronos ({Environment.MachineName})") { Token = token };
/// <summary>The engine; null until the index is open.</summary>
public SyncService? Service { get; private set; }
@@ -61,6 +73,37 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
/// <summary>The signed-in account may queue renders on the server.</summary>
public bool CanRender => Allows(Permissions.Render);
/// <summary>
/// The signed-in server keeps its sequences' projects (owner review 2, R8: the <c>projects</c> capability), so Edit opens
/// its sequences as workspace projects; false while signed out and for an older server, whose sequences Edit opens with
/// proxies as before.
/// </summary>
public bool HasProjects =>
services.Server.IsConnected && services.Server.Flow.Info?.Capabilities is { } capabilities && capabilities.Contains(ServerCapabilities.Projects);
/// <summary>The home of a workspace project of server sequence <paramref name="remoteId"/>; null while signed out or when the server keeps no projects.</summary>
public BundleHome? ServerHome(Guid remoteId) => Server is { } server && HasProjects ? new BundleHome(BundleHome.ServerKind, remoteId, null, server) : null;
/// <summary>
/// The project home of a workspace project whose home is a server (<see cref="ServerProjectHome"/> over the session's
/// client); null while signed out, signed in to another server, or when the server keeps no projects: the workspace then
/// shows the project offline and its work waits.
/// </summary>
public IProjectHome? ProjectHome(BundleHome home)
{
ArgumentNullException.ThrowIfNull(home);
if (home.IsArchive || !HasProjects || Volatile.Read(ref _credentials) is not { } credentials
|| !string.Equals(home.Server, SyncService.ServerKey(credentials.Address), StringComparison.OrdinalIgnoreCase))
return null;
return new ServerProjectHome(SessionClient(credentials), home.SequenceId, services.Server.ServerName);
}
/// <summary>
/// A project of a sequence of the signed-in server changed there (the server's key, and its <c>projectChanged</c>), or,
/// with null, changes may have been missed while its events were lost (any thread).
/// </summary>
public event Action<string, ProjectChangedEvent?>? ProjectChanged;
/// <summary>Pauses uploads while the connection is metered and the option is on.</summary>
public UploadHold Uploads { get; } = new(services);
@@ -146,10 +189,31 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
if (_renders is not null) _renders.JobChanged -= OnJobChanged;
await _switch.ConfigureAwait(false);
await StopAsync().ConfigureAwait(false);
lock (_gate)
{
_projects?.Client.Dispose();
_projects = null;
}
}
private bool Allows(Permissions permission) => services.Server.User is { } user && (user.Permissions & (long)permission) != 0;
/// <summary>
/// The client of <paramref name="credentials"/>' session, made once for its address and token: another sign-in replaces
/// it (a call still on the old one fails as a server out of reach, and is tried again on the new one).
/// </summary>
private ChronosClient SessionClient(Credentials credentials)
{
lock (_gate)
{
if (_projects is { } current && current.Address == credentials.Address && current.Token == credentials.Token) return current.Client;
_projects?.Client.Dispose();
var client = ProjectClientFactory(credentials.Address, credentials.Token, credentials.Fingerprints);
_projects = new SharedClient(credentials.Address, credentials.Token, client);
return client;
}
}
/// <summary>
/// Export "Sync": a render of this PC that asked for it is sent to the server once done (<see cref="ExportSync"/>),
/// also when it ends while the session is down: the send is queued for the saved session's server and waits for it.
@@ -205,6 +269,7 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
var remote = RemoteFactory(start.Address, start.Token, start.Fingerprints);
var agent = new SyncAgent(service, remote, () => Policy, services.Engine);
agent.Changed += () => Changed?.Invoke();
agent.ProjectChanged += e => ProjectChanged?.Invoke(remote.Server, e);
agent.Start();
Volatile.Write(ref _running, new Running(agent, remote, start));
Log.Info("sync", $"Comparing with {remote.Server}");
@@ -221,6 +286,9 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection<string> Fingerprints);
/// <summary>The client project homes share, and the session it was made for.</summary>
private sealed record SharedClient(Uri Address, string Token, ChronosClient Client);
/// <summary>The agent of the signed-in session: one reference, so the UI thread never reads half of a switch.</summary>
private sealed record Running(SyncAgent Agent, ISyncRemote Remote, Credentials Credentials);
}
+27 -6
View File
@@ -8,14 +8,22 @@ using Chronos.Ui.Mvvm;
namespace Chronos.App.Server;
/// <summary>A row button: "Upload", "Keep mine", …; kept while the row offers it, so focus, tooltips and clicks survive updates.</summary>
public sealed class SyncRowAction(SyncAction action, ICommand command) : ObservableObject
public sealed class SyncRowAction : ObservableObject
{
private readonly AsyncRelayCommand _command;
private string _toolTip = string.Empty;
private string _sequence = string.Empty;
private bool _isEnabled = true;
public SyncAction Action { get; } = action;
public SyncRowAction(SyncAction action, Func<Task> execute)
{
Action = action;
_command = new AsyncRelayCommand(execute, () => _isEnabled);
}
public SyncAction Action { get; }
public string Text => Loc.L("Server.Sync.Action." + Action);
public ICommand Command { get; } = command;
public ICommand Command => _command;
public string ToolTip
{
@@ -23,6 +31,16 @@ public sealed class SyncRowAction(SyncAction action, ICommand command) : Observa
set => Set(ref _toolTip, value);
}
/// <summary>The button can be pressed (Open in workspace cannot on a server that keeps no projects; its tooltip says why).</summary>
public bool IsEnabled
{
get => _isEnabled;
set
{
if (Set(ref _isEnabled, value)) _command.RaiseCanExecuteChanged();
}
}
/// <summary>The title of the row's sequence.</summary>
public string Sequence
{
@@ -49,6 +67,7 @@ public sealed class SyncRow : ObservableObject
{
private readonly Func<SyncRow, SyncAction, Task> _act;
private SyncEntry _entry;
private SyncRights _rights;
private IReadOnlyList<SyncRowAction> _actions = [];
public SyncRow(SyncEntry entry, SyncRights rights, Func<SyncRow, SyncAction, Task> act)
@@ -103,22 +122,24 @@ public sealed class SyncRow : ObservableObject
foreach (var action in _actions)
{
action.Relabel();
action.ToolTip = SyncText.ToolTip(_entry, action.Action);
action.ToolTip = SyncText.ToolTip(_entry, action.Action, _rights);
}
RaiseTexts();
}
private void UpdateActions(SyncRights rights)
{
_rights = rights;
var wanted = SyncText.Actions(_entry, rights);
if (!wanted.SequenceEqual(_actions.Select(a => a.Action)))
{
var kept = _actions.ToDictionary(a => a.Action);
Actions = [.. wanted.Select(action => kept.GetValueOrDefault(action) ?? new SyncRowAction(action, new AsyncRelayCommand(() => _act(this, action))))];
Actions = [.. wanted.Select(action => kept.GetValueOrDefault(action) ?? new SyncRowAction(action, () => _act(this, action)))];
}
foreach (var action in _actions)
{
action.ToolTip = SyncText.ToolTip(_entry, action.Action);
action.ToolTip = SyncText.ToolTip(_entry, action.Action, rights);
action.IsEnabled = SyncText.IsEnabled(action.Action, rights);
action.Sequence = Title;
}
}
+7 -1
View File
@@ -171,7 +171,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
private SyncHost Host => _shell.Services.Sync;
private SyncRights Rights => _shell.Services.Server.User is { } user ? SyncRights.Of(user.Permissions) : default;
private SyncRights Rights => _shell.Services.Server.User is { } user ? SyncRights.Of(user.Permissions) with { KeepsProjects = Host.HasProjects } : default;
private IEnumerable<SyncEntry> LocalOnly => _entries.Where(e => e.Status == SyncStatus.LocalOnly);
@@ -326,6 +326,12 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
case SyncAction.GetExports:
await service.EnqueueDownloadAsync(engine, server, entry.Id, entry.Title, SyncDownloadMode.Exports, null);
break;
// Edit opens it as a workspace project of the server: the project opened last, else "Open in workspace" asks (phase 5b).
case SyncAction.OpenInWorkspace when Host.HasProjects:
_shell.OpenSequence(entry.Id);
return;
case SyncAction.OpenInWorkspace:
return;
case SyncAction.OpenWithProxies when entry.Status == SyncStatus.ProxiesOnly && service.OpenRemote(server, entry.Id) is not null:
_shell.OpenSequence(entry.Id);
return;
+22 -4
View File
@@ -33,13 +33,20 @@ public enum SyncAction
SendExports,
Pause,
Resume,
/// <summary>
/// Edit a project of the server's sequence in the workspace (owner review 2, R8, phase 5b): offered disabled by a server
/// that keeps no projects, whose sequences open with proxies as before.
/// </summary>
OpenInWorkspace,
}
/// <summary>What the signed-in account may do (server permission bits).</summary>
/// <summary>What the signed-in account may do (server permission bits), and whether its server keeps projects.</summary>
/// <param name="CanUpload">Send originals, settings and renders (upload and edit rights).</param>
/// <param name="CanFetchOriginals">Download originals (editors and render nodes).</param>
/// <param name="CanEdit">Change the server's copy of a sequence's settings, title, tags, rating and notes.</param>
public readonly record struct SyncRights(bool CanUpload, bool CanFetchOriginals, bool CanEdit)
/// <param name="KeepsProjects">The server keeps its sequences' projects (the <c>projects</c> capability): they open in the workspace.</param>
public readonly record struct SyncRights(bool CanUpload, bool CanFetchOriginals, bool CanEdit, bool KeepsProjects = false)
{
public static SyncRights Of(long permissions) => new(
(permissions & (long)Permissions.Upload) != 0 && (permissions & (long)Permissions.Edit) != 0,
@@ -227,9 +234,16 @@ public static class SyncText
case SyncStatus.LocalOnly when rights.CanUpload:
actions.Add(SyncAction.Upload);
break;
// A server that keeps projects edits its sequences in the workspace; an older one's open with proxies, the
// workspace offered disabled with the reason (phase 5b).
case SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly when rights.KeepsProjects:
actions.Add(SyncAction.OpenInWorkspace);
if (rights.CanFetchOriginals) actions.Add(SyncAction.DownloadOriginals);
break;
case SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly:
actions.Add(SyncAction.OpenWithProxies);
if (rights.CanFetchOriginals) actions.Add(SyncAction.DownloadOriginals);
actions.Add(SyncAction.OpenInWorkspace);
break;
case SyncStatus.LocalAhead when entry.Link is { MissingRemote: > 0 }:
if (rights.CanUpload) actions.Add(SyncAction.Upload);
@@ -265,12 +279,16 @@ public static class SyncText
_ => 0,
};
/// <summary>The tooltip of a row button: what it does and, for transfers, what it moves.</summary>
public static string ToolTip(SyncEntry entry, SyncAction action) => action switch
/// <summary>Whether a row button can be pressed: all can, but Open in workspace on a server that keeps no projects.</summary>
public static bool IsEnabled(SyncAction action, SyncRights rights) => action != SyncAction.OpenInWorkspace || rights.KeepsProjects;
/// <summary>The tooltip of a row button: what it does and, for transfers, what it moves; why not, for one disabled.</summary>
public static string ToolTip(SyncEntry entry, SyncAction action, SyncRights rights = default) => action switch
{
SyncAction.Upload or SyncAction.DownloadOriginals => Loc.L("Tooltips.Server.Sync." + action, Formatting.Bytes(Size(entry, action))),
SyncAction.GetExports => Loc.Plural("Tooltips.Server.Sync.GetExports", entry.Link!.ExportsToGet, Formatting.Bytes(Size(entry, action))),
SyncAction.SendExports => Loc.Plural("Tooltips.Server.Sync.SendExports", entry.Link!.ExportsToSend, Formatting.Bytes(Size(entry, action))),
SyncAction.OpenInWorkspace when !rights.KeepsProjects => Loc.L("Tooltips.Server.Sync.OpenInWorkspace.NoProjects"),
_ => Loc.L("Tooltips.Server.Sync." + action),
};
+154 -36
View File
@@ -9,6 +9,7 @@ using Chronos.Core.Project;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
using Chronos.Ui.Controls;
using Chronos.Ui.Mvvm;
@@ -54,13 +55,19 @@ public interface IWorkspaceUi
/// banner when the home's frames moved past the workspace's. Every operation first stores the editor's last edit; what a
/// pull, a restore or taking the library's values changed comes back into the editor (merged, or as an undo step). A
/// conflict is asked about only when the merge met settings both sides changed, and a choice settles only the conflict
/// shown; one an automatic sync met waits for the dialog open to close. Call from the UI thread.
/// shown; one an automatic sync met waits for the dialog open to close. A project whose home is a server (phase 5b) words
/// its texts for the server, follows what the server tells of it (<see cref="WorkspaceHost.HomeChanged"/>: the chip reads
/// Server newer, or that the server no longer has it, its copy kept here), and renders only what the server holds
/// (<see cref="ReadyToRenderAsync"/>). Call from the UI thread.
/// </summary>
public sealed class ProjectMenuViewModel : LocalizedViewModel
{
/// <summary>How long after the last edit the chip reads the working state again (a little after the editor's save).</summary>
public static readonly TimeSpan StateRefreshDelay = TimeSpan.FromMilliseconds(600);
/// <summary>How long after an analysis ended a change the home tells is taken as its Auto values reaching Main.</summary>
private static readonly TimeSpan AnalysisTake = TimeSpan.FromMinutes(2);
private readonly WorkspaceHost _host;
private readonly WorkspaceSequenceSource _source;
private readonly EditorSession _session;
@@ -82,6 +89,12 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
/// <summary>The conflict dialog asked in the background, until it is closed (one is asked at a time).</summary>
private ConflictDialogViewModel? _asking;
/// <summary>
/// When an analysis of the sequence ended while Sync automatically is on and the home had not told its new Main yet
/// (a server catches up a moment later): the change it tells next is taken.
/// </summary>
private DateTime? _analysisEnded;
public ProjectMenuViewModel(WorkspaceHost host, WorkspaceSequenceSource source, EditorSession session, IWorkspaceUi ui)
{
_host = host;
@@ -99,6 +112,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
RemoveCopyCommand = new AsyncRelayCommand(OpenRemoveCopyAsync);
source.JobChanged += OnJobChanged;
session.ProjectChanged += OnProjectChanged;
host.HomeChanged += OnHomeChanged;
}
public Guid ProjectId => _source.ProjectId;
@@ -107,6 +121,9 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
public bool IsMain => _source.Workspace?.IsMain == true;
/// <summary>The project's home is a server (phase 5b): its texts name the server, its renders are of what the server holds.</summary>
public bool IsServerHome => _source.IsServerHome;
/// <summary>The project's name (Main in the UI language).</summary>
public string Name => _source.Workspace is { } workspace ? WorkspaceText.ProjectName(workspace.Name, workspace.IsMain) : string.Empty;
@@ -114,11 +131,11 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
public bool IsSyncing => _isSyncing;
public string StateText => WorkspaceText.State(_status, _isSyncing);
public string StateText => WorkspaceText.State(_status, _isSyncing, IsServerHome);
public StatusKind StateKind => WorkspaceText.Kind(_status, _isSyncing);
public string StateToolTip => WorkspaceText.StateToolTip(_status, _isSyncing);
public string StateToolTip => WorkspaceText.StateToolTip(_status, _isSyncing, IsServerHome);
/// <summary>The ▾ button: its name, then where the project stands, then what the menu holds.</summary>
public string MenuToolTip => Loc.L("Tooltips.Editor.Project.Menu", Name, StateText);
@@ -136,17 +153,25 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
/// <summary>A copy of the media runs (Update media): the banner says so.</summary>
public bool IsUpdatingMedia => _copyJob != Guid.Empty;
public string MediaUpdateText => Loc.L(IsUpdatingMedia ? "Editor.Workspace.Updating" : "Editor.Workspace.MediaChanged");
public string MediaUpdateText => IsUpdatingMedia ? Loc.L("Editor.Workspace.Updating") : WorkspaceText.ForHome("Editor.Workspace.MediaChanged", IsServerHome);
public string MediaChangedToolTip => WorkspaceText.ForHome("Tooltips.Editor.Workspace.MediaChanged", IsServerHome);
public string UpdateMediaToolTip => WorkspaceText.ForHome("Tooltips.Editor.Workspace.UpdateMedia", IsServerHome);
/// <summary>A version can be saved: the settings are this Chronos's, no conflict waits, the media are here and the library still has the project.</summary>
public bool CanSaveVersion => !_session.IsReadOnly && _status is not { Conflict: not null } and not { MediaRemoved: true } and not { State: WorkspaceState.Gone };
public string SaveVersionToolTip => _session.IsReadOnly ? Loc.L("Errors.Workspace.ReadOnly")
: _status?.State == WorkspaceState.Gone ? Loc.L("Errors.Workspace.DeletedAtHome")
: _status?.State == WorkspaceState.Gone ? WorkspaceText.ForHome("Errors.Workspace.DeletedAtHome", IsServerHome)
: _status?.Conflict is not null ? Loc.L("Errors.Workspace.Conflict")
: Loc.L("Tooltips.Editor.Project.SaveVersion");
public string DeleteToolTip => IsMain ? Loc.L("Errors.Workspace.MainKept") : Loc.L("Tooltips.Editor.Project.Delete");
public string DeleteToolTip => IsMain ? Loc.L("Errors.Workspace.MainKept") : WorkspaceText.ForHome("Tooltips.Editor.Project.Delete", IsServerHome);
public string RenameToolTip => WorkspaceText.ForHome("Tooltips.Editor.Project.Rename", IsServerHome);
public string RemoveCopyToolTip => WorkspaceText.ForHome("Tooltips.Editor.Project.RemoveCopy", IsServerHome);
/// <summary>Save version… (Ctrl+S): the note dialog.</summary>
public ICommand SaveVersionCommand { get; }
@@ -195,6 +220,55 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
await RefreshAsync();
if (_disposed || !_host.Settings.WorkspaceAutoSync || job.Kind is not (JobKind.DeepAnalyse or JobKind.LightAnalyse)) return;
if (_status is { State: WorkspaceState.Behind }) await SyncAsync(quiet: true);
// A server writes the Auto values into Main a moment after its analysis ends: what it tells next is taken then.
else if (IsServerHome) _analysisEnded = DateTime.UtcNow;
}
/// <summary>
/// Before a render (phase 5b): a project whose home is a server renders what the server holds, so changes not saved as a
/// version, or versions not sent, are first offered to be saved and sent (Sync); false when the user kept them here,
/// the server could not take them or no longer has the project, or a conflict waits. A project of this PC's archive
/// renders as it is: true.
/// </summary>
public async Task<bool> ReadyToRenderAsync()
{
if (!IsServerHome) return true;
await StoreEditAsync();
var status = await _host.StatusAsync(ProjectId);
if (_disposed) return false;
Apply(status);
if (status.State is WorkspaceState.Gone or WorkspaceState.Offline or WorkspaceState.Damaged or WorkspaceState.MediaRemoved)
{
_ui.Notify(Loc.L("Editor.Workspace.RenderHeld"), WorkspaceText.StateToolTip(status, server: true), isError: status.State != WorkspaceState.Offline);
return false;
}
if (status.Conflict is not null)
{
AskConflict(status.Conflict);
return false;
}
if (status.Ahead == 0 && !status.Modified && _source.InStepWithHome(_session.Project) is not null) return true;
if (!_ui.Confirm(new ConfirmRequest
{
Heading = Loc.L("Editor.Workspace.SendFirst.Title"),
Message = Loc.L("Editor.Workspace.SendFirst.Message", Name),
SafeText = Loc.L("Editor.Project.Keep"),
SafeToolTip = Loc.L("Tooltips.Editor.Workspace.SendFirst.Keep"),
ActionText = Loc.L("Editor.Workspace.SendFirst.Action"),
ActionToolTip = Loc.L("Tooltips.Editor.Workspace.SendFirst.Action"),
}))
return false;
try
{
await SaveAndSendAsync();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Project {ProjectId} could not be sent before its render", ex);
_ui.Notify(Loc.L("Editor.Workspace.RenderHeld"), WorkspaceText.Failure(ex, server: true), isError: ex is not HomeUnavailableException);
return false;
}
return !_disposed && _source.InStepWithHome(_session.Project) is not null;
}
/// <summary>
@@ -222,7 +296,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
{
_ui.Notify(Loc.L("Editor.Workspace.Saved", Formatting.Count(result.Version.Number)), Name);
}
if (result.SyncError is { } error) _ui.Notify(Loc.L("Editor.Workspace.NotSent"), WorkspaceText.Failure(error), isError: error is not HomeUnavailableException);
if (result.SyncError is { } error)
_ui.Notify(Loc.L("Editor.Workspace.NotSent"), WorkspaceText.Failure(error, IsServerHome), isError: error is not HomeUnavailableException);
// Deleted in the library: said once, and no conflict is asked (nothing can be merged with it); the version stays here.
if (result.Status.State == WorkspaceState.Gone) NotifyGone();
else if (result.Status.Conflict is { } conflict) AskConflict(conflict);
@@ -250,8 +325,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Project {ProjectId} could not be synced", ex);
_ui.Notify(Loc.L(ex is HomeUnavailableException ? "Editor.Workspace.Offline" : "Editor.Workspace.SyncFailed"), WorkspaceText.Failure(ex),
isError: ex is not HomeUnavailableException);
_ui.Notify(ex is HomeUnavailableException ? WorkspaceText.ForHome("Editor.Workspace.Offline", IsServerHome) : Loc.L("Editor.Workspace.SyncFailed"),
WorkspaceText.Failure(ex, IsServerHome), isError: ex is not HomeUnavailableException);
await RefreshAsync();
}
finally
@@ -288,7 +363,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
if (result.Kept is { } kept)
{
if (await _session.TakeOverAsync(kept) is { } step)
_ui.Notify(Loc.L("Editor.Workspace.TookLibrary"), Name, Loc.L("Editor.Workspace.Undo"), Loc.L("Tooltips.Editor.Workspace.UndoTake"), () => step.Undo());
_ui.Notify(WorkspaceText.ForHome("Editor.Workspace.TookLibrary", IsServerHome), Name, Loc.L("Editor.Workspace.Undo"),
WorkspaceText.ForHome("Tooltips.Editor.Workspace.UndoTake", IsServerHome), () => step.Undo());
if (result.Pushed.Count > 0 && IsMain) await _ui.SequenceChangedAsync(SequenceId);
}
else
@@ -307,8 +383,9 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
() => _ = _ui.OpenProjectAsync(sequenceId, copy.Id));
}
/// <summary>The library no longer has the project: nothing more is sent, its work stays here (Remove local copy keeps it aside).</summary>
private void NotifyGone() => _ui.Notify(Loc.L("Editor.Workspace.State.Gone"), Loc.L("Errors.Workspace.DeletedAtHome"));
/// <summary>The home no longer has the project: nothing more is sent, its work stays here (Remove local copy keeps it aside).</summary>
private void NotifyGone() =>
_ui.Notify(WorkspaceText.ForHome("Editor.Workspace.State.Gone", IsServerHome), WorkspaceText.ForHome("Errors.Workspace.DeletedAtHome", IsServerHome));
/// <summary>
/// Restores <paramref name="version"/> as the project, as one undo step (uncommitted changes are saved as a version
@@ -355,6 +432,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
_disposed = true;
_source.JobChanged -= OnJobChanged;
_session.ProjectChanged -= OnProjectChanged;
_host.HomeChanged -= OnHomeChanged;
// A conflict still waiting to be asked belongs to this editor: it is not asked once the editor closed (Sync asks it next time).
if (_asking is { } waiting && !ReferenceEquals(waiting, _ui.Dialog)) waiting.Dispose();
base.Dispose();
@@ -369,12 +447,12 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
private void OpenSaveVersion()
{
if (!CanSaveVersion) return;
_ui.ShowDialog(new SaveVersionDialogViewModel(Name, SaveVersionAsync, _ui.CloseDialog));
_ui.ShowDialog(new SaveVersionDialogViewModel(Name, SaveVersionAsync, _ui.CloseDialog, IsServerHome));
}
private async Task OpenHistoryAsync()
{
var dialog = new HistoryDialogViewModel(Name, v => Task.FromResult(Compare(v)), RestoreAsync, _ui.CloseDialog);
var dialog = new HistoryDialogViewModel(Name, v => Task.FromResult(Compare(v)), RestoreAsync, _ui.CloseDialog, IsServerHome);
_ui.ShowDialog(dialog);
try
{
@@ -389,8 +467,11 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
}
}
/// <summary>The project's home (this PC's archive, or a server).</summary>
private BundleHome Home => _source.Workspace?.Home ?? WorkspaceHost.ArchiveHome(SequenceId);
/// <summary>
/// Open project…: "Open in workspace" over the library's projects of the sequence but the open one (a Save both
/// Open project…: "Open in workspace" over the home's projects of the sequence but the open one (a Save both
/// sibling, another PC's), or a new one; the choice opens in place of this one (checked out and copied when it is not
/// here yet).
/// </summary>
@@ -399,32 +480,34 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
try
{
await StoreEditAsync();
var projects = (await _host.HomeProjectsAsync(SequenceId)).Where(p => p.Id != ProjectId).ToList();
var home = Home;
var projects = (await _host.HomeProjectsAsync(home)).Where(p => p.Id != ProjectId).ToList();
var dialog = new OpenInWorkspaceDialogViewModel(_session.Content.Sequence.DisplayTitle, projects, _ui.CloseDialog,
[.. projects.Select(p => p.Name).Append(_source.Workspace?.Name ?? string.Empty)]);
[.. projects.Select(p => p.Name).Append(_source.Workspace?.Name ?? string.Empty)], server: IsServerHome);
_ui.ShowDialog(dialog);
if (await dialog.Choice is not { } choice || _disposed) return;
var id = choice.ProjectId ?? (await _host.CreateProjectAsync(SequenceId, choice.NewName!, _status?.Base?.VersionId)).Id;
var id = choice.ProjectId ?? (await _host.CreateProjectAsync(home, choice.NewName!, _status?.Base?.VersionId)).Id;
await _ui.OpenProjectAsync(SequenceId, id);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Another project of sequence {SequenceId} could not be opened", ex);
_ui.Notify(Loc.L("Editor.Workspace.OpenFailed"), WorkspaceText.Failure(ex), isError: true);
_ui.Notify(Loc.L("Editor.Workspace.OpenFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
}
private async Task OpenNewProjectAsync()
{
var names = await OtherNamesAsync(null);
var home = Home;
_ui.ShowDialog(new ProjectNameDialogViewModel(false, string.Empty, names, async name =>
{
await StoreEditAsync();
// From the open project's last version at the home, so the new one starts where this one is there.
var created = await _host.CreateProjectAsync(SequenceId, name, _status?.Base?.VersionId);
var created = await _host.CreateProjectAsync(home, name, _status?.Base?.VersionId);
_ui.Notify(Loc.L("Editor.Workspace.Created", created.Name), _session.Content.Sequence.DisplayTitle);
_ = _ui.OpenProjectAsync(SequenceId, created.Id);
}, _ui.CloseDialog));
}, _ui.CloseDialog, IsServerHome));
}
private async Task OpenRenameAsync()
@@ -436,7 +519,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
await _session.ReloadAsync();
_ui.Notify(Loc.L("Editor.Workspace.Renamed"), name);
RaiseState();
}, _ui.CloseDialog));
}, _ui.CloseDialog, IsServerHome));
}
private async Task DeleteAsync()
@@ -446,11 +529,11 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
if (!_ui.Confirm(new ConfirmRequest
{
Heading = Loc.L("Editor.Project.DeleteTitle", name),
Message = Loc.L("Editor.Project.DeleteMessage"),
Message = WorkspaceText.ForHome("Editor.Project.DeleteMessage", IsServerHome),
SafeText = Loc.L("Editor.Project.Keep"),
SafeToolTip = Loc.L("Tooltips.Editor.Project.Keep"),
ActionText = Loc.L("Editor.Project.DeleteAction"),
ActionToolTip = Loc.L("Tooltips.Editor.Project.DeleteAction"),
ActionToolTip = WorkspaceText.ForHome("Tooltips.Editor.Project.DeleteAction", IsServerHome),
IsDestructive = true,
}))
return;
@@ -468,7 +551,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Project {ProjectId} was not deleted", ex);
_ui.Notify(Loc.L("Editor.Workspace.DeleteFailed"), WorkspaceText.Failure(ex), isError: true);
_ui.Notify(Loc.L("Editor.Workspace.DeleteFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
}
@@ -483,12 +566,12 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
{
await SaveAndSendAsync();
await RemoveAsync(projectId, discard: false);
}, () => RemoveCopyDialogViewModel.ConfirmDiscard(_ui, name), _ui.CloseDialog));
}, () => RemoveCopyDialogViewModel.ConfirmDiscard(_ui, name), _ui.CloseDialog, IsServerHome));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The removal of project {ProjectId} could not be planned", ex);
_ui.Notify(Loc.L("Editor.Workspace.RemoveFailed"), WorkspaceText.Failure(ex), isError: true);
_ui.Notify(Loc.L("Editor.Workspace.RemoveFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
}
@@ -504,14 +587,15 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
var result = await _host.SyncAsync(ProjectId);
Apply(result.Status);
await TakeAsync(result);
// Nothing can be sent to a project the library no longer has: only Discard takes the copy, its work kept aside.
if (result.Status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
// Nothing can be sent to a project the home no longer has: only Discard takes the copy, its work kept aside.
if (result.Status.State == WorkspaceState.Gone) throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.DeletedAtHome", IsServerHome));
if (result.Status.Conflict is { } conflict)
{
AskConflict(conflict);
throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
}
if (result.Status is { Ahead: > 0 } or { Modified: true, ReadOnly: false }) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
if (result.Status is { Ahead: > 0 } or { Modified: true, ReadOnly: false })
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Unsent", IsServerHome));
}
private async Task RemoveAsync(Guid projectId, bool discard)
@@ -520,7 +604,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
if (!discard)
{
var status = await _host.StatusAsync(projectId, askHome: false);
if (status is { Ahead: > 0 } or { Conflict: not null } or { Modified: true, ReadOnly: false }) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
if (status is { Ahead: > 0 } or { Conflict: not null } or { Modified: true, ReadOnly: false })
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Unsent", IsServerHome));
}
var name = Name;
if (!await _ui.CloseProjectAsync()) return;
@@ -532,7 +617,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
{
try
{
return [.. (await _host.HomeProjectsAsync(SequenceId)).Where(p => p.Id != except).Select(p => p.Name)];
return [.. (await _host.HomeProjectsAsync(Home)).Where(p => p.Id != except).Select(p => p.Name)];
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
@@ -555,7 +640,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The media of project {ProjectId} could not be copied again", ex);
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex), isError: true);
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
}
@@ -582,9 +667,9 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
private void AskConflict(WorkspaceConflict conflict, bool background = false)
{
if (background && _asking is { IsClosed: false }) return;
var lines = WorkspaceText.ConflictLines(conflict.Differences, 10);
var lines = WorkspaceText.ConflictLines(conflict.Differences, 10, IsServerHome);
var dialog = new ConflictDialogViewModel(Name, WorkspaceHost.SiblingName(_source.Workspace?.Name ?? Name), lines, choice => ResolveAsync(choice, conflict),
_ui.CloseDialog, conflict.NewerFormat);
_ui.CloseDialog, conflict.NewerFormat, IsServerHome);
if (!background)
{
// Asked now: one still waiting from the background (or showing, which this one replaces) would only repeat an older list.
@@ -669,6 +754,34 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
else _ = CopyEndedAsync(job);
}
/// <summary>
/// The home told that this project changed there, or that changes may have been missed (any thread; phase 5b): where it
/// stands is read again on the menu's thread, so the chip says Server newer, or that the server no longer has it.
/// </summary>
private void OnHomeChanged(WorkspaceHomeChange change)
{
if (_disposed || (change.ProjectId is { } id ? id != ProjectId : !IsServerHome || !string.Equals(change.Server, Home.Server, StringComparison.OrdinalIgnoreCase)))
return;
if (_context is { } context) context.Post(_ => _ = HomeChangedAsync(change), null);
else _ = HomeChangedAsync(change);
}
private async Task HomeChangedAsync(WorkspaceHomeChange change)
{
if (_disposed || _isSyncing) return;
await RefreshAsync();
// An analysis's Auto values reached Main at the server: with Sync automatically they are taken, as after an analysis here.
if (_disposed || _analysisEnded is not { } ended || change.Change != ProjectChanges.Pushed) return;
if (DateTime.UtcNow - ended > AnalysisTake)
{
_analysisEnded = null;
return;
}
if (_status is not { State: WorkspaceState.Behind } || !_host.Settings.WorkspaceAutoSync) return;
_analysisEnded = null;
await SyncAsync(quiet: true);
}
/// <summary>The copy of Update media ended: the editor reads the new frames (its positions follow them), or the toast says why not.</summary>
private async Task CopyEndedAsync(Job job)
{
@@ -682,7 +795,7 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The new media of project {ProjectId} could not be read", ex);
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex), isError: true);
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
await RefreshAsync();
RaiseState();
@@ -718,6 +831,11 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
OnPropertyChanged(nameof(CanSaveVersion));
OnPropertyChanged(nameof(SaveVersionToolTip));
OnPropertyChanged(nameof(DeleteToolTip));
OnPropertyChanged(nameof(IsServerHome));
OnPropertyChanged(nameof(RenameToolTip));
OnPropertyChanged(nameof(RemoveCopyToolTip));
OnPropertyChanged(nameof(MediaChangedToolTip));
OnPropertyChanged(nameof(UpdateMediaToolTip));
_updateMedia.RaiseCanExecuteChanged();
CommandManager.InvalidateRequerySuggested();
}
+74 -28
View File
@@ -53,6 +53,7 @@ public static class ProjectNames
public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
{
private readonly TaskCompletionSource<OpenChoice?> _choice = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly bool _server;
private ProjectOption? _selected;
private bool _isNew;
@@ -61,10 +62,12 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
/// <param name="unreadable">
/// The projects whose copy here this Chronos cannot read (damaged, or a newer Chronos's), with why: listed, never chosen.
/// </param>
/// <param name="server">The sequence's home is a server (phase 5b): the texts name the server.</param>
public OpenInWorkspaceDialogViewModel(string sequenceTitle, IReadOnlyList<SequenceProject> projects, Action<ArchiveDialogViewModel> close,
IReadOnlyList<string>? taken = null, WorkspaceCopyFacts? copy = null, IReadOnlyDictionary<Guid, string>? unreadable = null)
IReadOnlyList<string>? taken = null, WorkspaceCopyFacts? copy = null, IReadOnlyDictionary<Guid, string>? unreadable = null, bool server = false)
: base(close)
{
_server = server;
SequenceTitle = sequenceTitle;
Copy = copy;
CopyFacts = copy is null ? []
@@ -138,6 +141,12 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
public EditableField NewName { get; }
public string ExistingToolTip => WorkspaceText.ForHome("Tooltips.Editor.OpenWorkspace.Existing", _server);
public string ProjectsToolTip => WorkspaceText.ForHome("Tooltips.Editor.OpenWorkspace.Projects", _server);
public string ProxiesToolTip => WorkspaceText.ForHome("Tooltips.Editor.OpenWorkspace.Proxies", _server);
/// <summary>The proxies, the only media this phase copies.</summary>
public bool IsProxies => true;
@@ -176,13 +185,17 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
public sealed class ProjectNameDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<string, Task> _save;
private readonly bool _server;
/// <param name="others">The names of the sequence's other projects (each name is used once).</param>
public ProjectNameDialogViewModel(bool rename, string name, IEnumerable<string> others, Func<string, Task> save, Action<ArchiveDialogViewModel> close)
/// <param name="server">The project's home is a server (phase 5b): the texts name the server.</param>
public ProjectNameDialogViewModel(bool rename, string name, IEnumerable<string> others, Func<string, Task> save, Action<ArchiveDialogViewModel> close,
bool server = false)
: base(close)
{
IsRename = rename;
_save = save;
_server = server;
var taken = others.ToList();
Name = new EditableField(name, n => ProjectNames.Validate(n, taken), _ => { }, () => Loc.L("Tooltips.Editor.ProjectName.Name"));
Name.PropertyChanged += (_, _) =>
@@ -203,7 +216,7 @@ public sealed class ProjectNameDialogViewModel : ArchiveDialogViewModel
public ICommand SaveCommand { get; }
public string SaveToolTip => Name.Error ?? Loc.L(IsRename ? "Tooltips.Editor.ProjectName.Apply" : "Tooltips.Editor.ProjectName.Create");
public string SaveToolTip => Name.Error ?? WorkspaceText.ForHome(IsRename ? "Tooltips.Editor.ProjectName.Apply" : "Tooltips.Editor.ProjectName.Create", _server);
private async Task SaveAsync()
{
@@ -217,7 +230,7 @@ public sealed class ProjectNameDialogViewModel : ArchiveDialogViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", "Naming a project failed", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
}
finally
{
@@ -233,13 +246,16 @@ public sealed class SaveVersionDialogViewModel : ArchiveDialogViewModel
public const int MaxNoteLength = 200;
private readonly Func<string?, Task> _save;
private readonly bool _server;
private string _note = string.Empty;
public SaveVersionDialogViewModel(string projectName, Func<string?, Task> save, Action<ArchiveDialogViewModel> close)
/// <param name="server">The project's home is a server (phase 5b): the texts name the server.</param>
public SaveVersionDialogViewModel(string projectName, Func<string?, Task> save, Action<ArchiveDialogViewModel> close, bool server = false)
: base(close)
{
ProjectName = projectName;
_save = save;
_server = server;
SaveCommand = new AsyncRelayCommand(SaveAsync, () => !IsBusy);
}
@@ -247,6 +263,8 @@ public sealed class SaveVersionDialogViewModel : ArchiveDialogViewModel
public string Heading => Loc.L("Editor.SaveVersion.Title", ProjectName);
public string SaveToolTip => WorkspaceText.ForHome("Tooltips.Editor.SaveVersion.Save", _server);
public string Note
{
get => _note;
@@ -267,7 +285,7 @@ public sealed class SaveVersionDialogViewModel : ArchiveDialogViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", "Saving a version failed", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
}
finally
{
@@ -277,10 +295,13 @@ public sealed class SaveVersionDialogViewModel : ArchiveDialogViewModel
}
/// <summary>A version in the History flyout: number, author, time, note, what made it, and Compare and Restore.</summary>
public sealed class HistoryRowViewModel(ProjectVersion version, bool unsent, bool isCurrent, ICommand compare, ICommand restore) : ObservableObject
public sealed class HistoryRowViewModel(ProjectVersion version, bool unsent, bool isCurrent, ICommand compare, ICommand restore, bool server = false) : ObservableObject
{
public ProjectVersion Version { get; } = version;
/// <summary>"Saved here, waiting to be sent to the library" (the server, for a server's project).</summary>
public string NotSentToolTip => WorkspaceText.ForHome("Tooltips.Editor.History.NotSent", server);
public string Number => Formatting.Count(Version.Number);
public string Author => WorkspaceText.Author(Version);
@@ -317,17 +338,20 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<ProjectVersion, Task<IReadOnlyList<string>>> _compare;
private readonly Func<ProjectVersion, Task> _restore;
private readonly bool _server;
private string? _comparedTitle;
private IReadOnlyList<string> _compared = [];
private bool _isLoaded;
/// <param name="server">The project's home is a server (phase 5b): the texts name the server.</param>
public HistoryDialogViewModel(string projectName, Func<ProjectVersion, Task<IReadOnlyList<string>>> compare, Func<ProjectVersion, Task> restore,
Action<ArchiveDialogViewModel> close)
Action<ArchiveDialogViewModel> close, bool server = false)
: base(close)
{
ProjectName = projectName;
_compare = compare;
_restore = restore;
_server = server;
}
public string ProjectName { get; }
@@ -339,6 +363,11 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
/// <summary>The home could not be asked: only this PC's versions are listed.</summary>
public bool IsOffline { get; private set; }
/// <summary>"Library offline", or "Server offline" for a server's project.</summary>
public string OfflineText => WorkspaceText.ForHome("Editor.History.Offline", _server);
public string OfflineToolTip => WorkspaceText.ForHome("Tooltips.Editor.History.Offline", _server);
public bool IsEmpty => _isLoaded && Rows.Count == 0;
/// <summary>"Version 3 → now" over the comparison; null before one.</summary>
@@ -355,7 +384,7 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
{
var current = currentHash is not null && string.Equals(version.ContentHash, currentHash, StringComparison.OrdinalIgnoreCase);
Rows.Add(new HistoryRowViewModel(version, history.Unsent.Contains(version.Id), current,
new AsyncRelayCommand(() => CompareAsync(version), () => !IsBusy), new AsyncRelayCommand(() => RestoreAsync(version), () => !IsBusy)));
new AsyncRelayCommand(() => CompareAsync(version), () => !IsBusy), new AsyncRelayCommand(() => RestoreAsync(version), () => !IsBusy), _server));
}
IsOffline = history.Offline;
_isLoaded = true;
@@ -369,7 +398,7 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
ArgumentNullException.ThrowIfNull(ex);
_isLoaded = true;
OnPropertyChanged(nameof(IsEmpty));
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
}
public async Task CompareAsync(ProjectVersion version)
@@ -385,7 +414,7 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Version {version.Number} could not be compared", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
}
}
@@ -403,7 +432,7 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Version {version.Number} could not be restored", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
IsBusy = false;
}
}
@@ -418,10 +447,12 @@ public sealed class HistoryDialogViewModel : ArchiveDialogViewModel
public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
{
private readonly Func<ConflictChoice, Task> _resolve;
private readonly bool _server;
/// <param name="newerFormat">The library holds a newer Chronos's settings: nothing is merged, Save both is the only choice.</param>
/// <param name="server">The project's home is a server (phase 5b): "Take server's", and the texts name the server.</param>
public ConflictDialogViewModel(string projectName, string siblingName, IReadOnlyList<string> differences, Func<ConflictChoice, Task> resolve,
Action<ArchiveDialogViewModel> close, bool newerFormat = false)
Action<ArchiveDialogViewModel> close, bool newerFormat = false, bool server = false)
: base(close)
{
ProjectName = projectName;
@@ -430,6 +461,7 @@ public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
// The format's number says nothing to the user: the line names the cause.
Differences = newerFormat ? [Loc.L("Editor.Workspace.Conflict.NewerFormat")] : differences;
_resolve = resolve;
_server = server;
KeepMineCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.KeepMine), () => !IsBusy && CanMerge);
TakeHomeCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.TakeServer), () => !IsBusy && CanMerge);
SaveBothCommand = new AsyncRelayCommand(() => ResolveAsync(ConflictChoice.SaveBoth), () => !IsBusy);
@@ -446,13 +478,13 @@ public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
/// <summary>The project Save both makes for this workspace's versions.</summary>
public string SiblingName { get; }
public string Heading => Loc.L("Editor.Workspace.Conflict.Title");
public string Heading => WorkspaceText.ForHome("Editor.Workspace.Conflict.Title", _server);
public string Message => Loc.L(IsNewerFormat ? "Editor.Workspace.Conflict.NewerMessage" : "Editor.Workspace.Conflict.Message", ProjectName);
public string Message => WorkspaceText.ForHome(IsNewerFormat ? "Editor.Workspace.Conflict.NewerMessage" : "Editor.Workspace.Conflict.Message", _server, ProjectName);
public IReadOnlyList<string> Differences { get; }
public string DifferencesToolTip => Loc.L(IsNewerFormat ? "Tooltips.Editor.Workspace.NewerFormat" : "Tooltips.Editor.Workspace.Differences");
public string DifferencesToolTip => WorkspaceText.ForHome(IsNewerFormat ? "Tooltips.Editor.Workspace.NewerFormat" : "Tooltips.Editor.Workspace.Differences", _server);
public ICommand KeepMineCommand { get; }
@@ -460,7 +492,14 @@ public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
public ICommand SaveBothCommand { get; }
public string SaveBothToolTip => Loc.L(IsNewerFormat ? "Tooltips.Editor.Workspace.SaveBothNewer" : "Tooltips.Editor.Workspace.SaveBoth", SiblingName);
/// <summary>"Take library's", or "Take server's" for a server's project.</summary>
public string TakeHomeText => WorkspaceText.ForHome("Editor.Workspace.Conflict.TakeHome", _server);
public string TakeHomeToolTip => WorkspaceText.ForHome("Tooltips.Editor.Workspace.TakeHome", _server);
public string KeepMineToolTip => WorkspaceText.ForHome("Tooltips.Editor.Workspace.KeepMine", _server);
public string SaveBothToolTip => WorkspaceText.ForHome(IsNewerFormat ? "Tooltips.Editor.Workspace.SaveBothNewer" : "Tooltips.Editor.Workspace.SaveBoth", _server, SiblingName);
private async Task ResolveAsync(ConflictChoice choice)
{
@@ -475,7 +514,7 @@ public sealed class ConflictDialogViewModel : ArchiveDialogViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The conflict of '{ProjectName}' could not be settled ({choice})", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
IsBusy = false;
}
}
@@ -493,15 +532,19 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
private readonly Func<bool, Task> _remove;
private readonly Func<Task> _sendFirst;
private readonly Func<bool> _confirmDiscard;
private readonly bool _server;
/// <param name="confirmDiscard">The typed confirmation Discard changes asks first (<see cref="ConfirmDiscard"/>); true when the user confirmed.</param>
public RemoveCopyDialogViewModel(WorkspaceRemovalPlan plan, Func<bool, Task> remove, Func<Task> sendFirst, Func<bool> confirmDiscard, Action<ArchiveDialogViewModel> close)
/// <param name="server">The project's home is a server (phase 5b): the texts name the server.</param>
public RemoveCopyDialogViewModel(WorkspaceRemovalPlan plan, Func<bool, Task> remove, Func<Task> sendFirst, Func<bool> confirmDiscard, Action<ArchiveDialogViewModel> close,
bool server = false)
: base(close)
{
Plan = plan;
_remove = remove;
_sendFirst = sendFirst;
_confirmDiscard = confirmDiscard;
_server = server;
Facts =
[
new DialogFact(Loc.L("Editor.RemoveCopy.Files"), Formatting.Count(plan.Files)),
@@ -532,19 +575,22 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
public ICommand DiscardCommand { get; }
/// <summary>What happens to the copy and the project, worded for the project's home.</summary>
public string Message => WorkspaceText.ForHome("Editor.RemoveCopy.Message", _server);
public string RemoveToolTip => Plan.Damaged ? Loc.L("Errors.Workspace.Damaged")
: Plan.Gone ? Loc.L("Errors.Workspace.ProjectGone")
: !Plan.IsSafe ? Loc.L("Errors.Workspace.Unsent")
: Plan.Offline ? Loc.L("Errors.Workspace.Offline")
: Loc.L("Tooltips.Editor.RemoveCopy.Remove");
: Plan.Gone ? WorkspaceText.ForHome("Errors.Workspace.ProjectGone", _server)
: !Plan.IsSafe ? WorkspaceText.ForHome("Errors.Workspace.Unsent", _server)
: Plan.Offline ? WorkspaceText.ForHome("Errors.Workspace.Offline", _server)
: WorkspaceText.ForHome("Tooltips.Editor.RemoveCopy.Remove", _server);
public string SendFirstToolTip => Plan.Damaged ? Loc.L("Errors.Workspace.Damaged")
: Plan.Gone ? Loc.L("Errors.Workspace.ProjectGone")
: Plan.Gone ? WorkspaceText.ForHome("Errors.Workspace.ProjectGone", _server)
: Plan.Conflict ? Loc.L("Errors.Workspace.Conflict")
: Plan.Offline ? Loc.L("Errors.Workspace.Offline")
: Loc.L("Tooltips.Editor.RemoveCopy.SendFirst");
: Plan.Offline ? WorkspaceText.ForHome("Errors.Workspace.Offline", _server)
: WorkspaceText.ForHome("Tooltips.Editor.RemoveCopy.SendFirst", _server);
public string DiscardToolTip => Loc.L("Tooltips.Editor.RemoveCopy.Discard");
public string DiscardToolTip => WorkspaceText.ForHome("Tooltips.Editor.RemoveCopy.Discard", _server);
/// <summary>
/// The typed confirmation of Discard changes (the plan's cross-cutting rule for what Chronos cannot bring back): the
@@ -614,7 +660,7 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The local copy of project {Plan.ProjectId} was not removed", ex);
ShowMessage(WorkspaceText.Failure(ex), ex.Message);
ShowMessage(WorkspaceText.Failure(ex, _server), ex.Message);
IsBusy = false;
}
}
+10 -10
View File
@@ -45,9 +45,9 @@
</Grid.RowDefinitions>
<TextBlock Text="{l:Loc Editor.OpenWorkspace.Project}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" />
<RadioButton Grid.Column="1" GroupName="Project" Content="{l:Loc Editor.OpenWorkspace.Existing}" IsChecked="{Binding IsExisting}" IsEnabled="{Binding HasProjects}"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Existing}" VerticalAlignment="Center" Margin="0,0,12,0" />
ToolTip="{Binding ExistingToolTip}" VerticalAlignment="Center" Margin="0,0,12,0" />
<ComboBox Grid.Column="2" ItemsSource="{Binding Projects}" SelectedItem="{Binding SelectedProject}" DisplayMemberPath="Label" IsEnabled="{Binding HasProjects}"
ItemContainerStyle="{StaticResource ComboBoxItem.Project}" ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Projects}" AutomationProperties.Name="{l:Loc Editor.OpenWorkspace.Project}" />
ItemContainerStyle="{StaticResource ComboBoxItem.Project}" ToolTip="{Binding ProjectsToolTip}" AutomationProperties.Name="{l:Loc Editor.OpenWorkspace.Project}" />
<RadioButton Grid.Row="1" Grid.Column="1" GroupName="Project" Content="{l:Loc Editor.OpenWorkspace.New}" IsChecked="{Binding IsNew}"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.New}" VerticalAlignment="Center" Margin="0,8,12,0" />
<TextBox Grid.Row="1" Grid.Column="2" Margin="0,8,0,0" Text="{Binding NewName.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
@@ -55,7 +55,7 @@
<TextBlock Grid.Row="2" Text="{l:Loc Editor.OpenWorkspace.Media}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" Margin="0,14,0,0" />
<StackPanel Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="2" Orientation="Horizontal" Margin="0,14,0,0">
<RadioButton GroupName="Media" Content="{l:Loc Editor.OpenWorkspace.Proxies}" IsChecked="{Binding IsProxies, Mode=OneWay}"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Proxies}" Margin="0,0,16,0" />
ToolTip="{Binding ProxiesToolTip}" Margin="0,0,16,0" />
<RadioButton GroupName="Media" Content="{l:Loc Editor.OpenWorkspace.Originals}" IsEnabled="{Binding CanCopyOriginals}" IsChecked="False"
ToolTip="{l:Loc Tooltips.Editor.OpenWorkspace.Originals}" ToolTipService.ShowOnDisabled="True" />
</StackPanel>
@@ -127,7 +127,7 @@
</Grid>
<DockPanel Margin="0,18,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Editor.SaveVersion.Save}" Command="{Binding SaveCommand}"
ToolTip="{l:Loc Tooltips.Editor.SaveVersion.Save}" IsDefault="True" MinWidth="96" Margin="8,0,0,0" />
ToolTip="{Binding SaveToolTip}" IsDefault="True" MinWidth="96" Margin="8,0,0,0" />
<Button DockPanel.Dock="Right" Content="{l:Loc Archive.Dialog.Cancel}" Command="{Binding CloseCommand}" ToolTip="{Binding CloseToolTip}" IsCancel="True" MinWidth="96" />
<ui:StatusGlyph Style="{StaticResource Status.DialogError}" Margin="0,0,12,0" />
</DockPanel>
@@ -146,7 +146,7 @@
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<DockPanel>
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Offline" Text="{l:Loc Editor.History.Offline}" ToolTip="{l:Loc Tooltips.Editor.History.Offline}" FontSize="12"
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Offline" Text="{Binding OfflineText}" ToolTip="{Binding OfflineToolTip}" FontSize="12"
VerticalAlignment="Center" Visibility="{Binding IsOffline, Converter={StaticResource BoolToVisibility}}" />
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
</DockPanel>
@@ -171,7 +171,7 @@
<TextBlock Grid.Column="3" Style="{StaticResource Text.Cell}" Text="{Binding When}" Margin="12,0,0,0" Foreground="{DynamicResource Brush.TextMuted}"
Typography.NumeralAlignment="Tabular" />
<DockPanel Grid.Column="4" Margin="12,0,0,0">
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Queued" Text="{l:Loc Editor.History.NotSent}" ToolTip="{l:Loc Tooltips.Editor.History.NotSent}" FontSize="12"
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Queued" Text="{l:Loc Editor.History.NotSent}" ToolTip="{Binding NotSentToolTip}" FontSize="12"
VerticalAlignment="Center" Margin="8,0,0,0" Visibility="{Binding IsUnsent, Converter={StaticResource BoolToVisibility}}" />
<ui:StatusGlyph DockPanel.Dock="Right" Kind="Done" Text="{l:Loc Editor.History.Current}" ToolTip="{l:Loc Tooltips.Editor.History.Current}" FontSize="12"
VerticalAlignment="Center" Margin="8,0,0,0" Visibility="{Binding IsCurrent, Converter={StaticResource BoolToVisibility}}" />
@@ -214,7 +214,7 @@
</Border>
</DataTemplate>
<!-- A sync that met settings both sides changed: what differs, then Keep mine, Take the library's, Save both, or Later (only Save both and Later for a newer Chronos's project). -->
<!-- A sync that met settings both sides changed: what differs, then Keep mine, Take the library's (the server's), Save both, or Later (only Save both and Later for a newer Chronos's project). -->
<DataTemplate DataType="{x:Type ws:ConflictDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="560">
<StackPanel>
@@ -234,10 +234,10 @@
MinWidth="96" Margin="0,0,8,8" />
<Button Content="{l:Loc Server.Sync.Action.SaveBoth}" Command="{Binding SaveBothCommand}" ToolTip="{Binding SaveBothToolTip}" MinWidth="96" Margin="0,0,8,8"
Visibility="{Binding CanMerge, Converter={StaticResource BoolToVisibility}}" />
<Button Content="{l:Loc Editor.Workspace.Conflict.TakeHome}" Command="{Binding TakeHomeCommand}" ToolTip="{l:Loc Tooltips.Editor.Workspace.TakeHome}"
<Button Content="{Binding TakeHomeText}" Command="{Binding TakeHomeCommand}" ToolTip="{Binding TakeHomeToolTip}"
MinWidth="96" Margin="0,0,8,8" Visibility="{Binding CanMerge, Converter={StaticResource BoolToVisibility}}" />
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Server.Sync.Action.KeepMine}" Command="{Binding KeepMineCommand}"
ToolTip="{l:Loc Tooltips.Editor.Workspace.KeepMine}" IsDefault="{Binding CanMerge, Mode=OneWay}" MinWidth="96" Margin="0,0,0,8"
ToolTip="{Binding KeepMineToolTip}" IsDefault="{Binding CanMerge, Mode=OneWay}" MinWidth="96" Margin="0,0,0,8"
Visibility="{Binding CanMerge, Converter={StaticResource BoolToVisibility}}" />
<!-- A conflict of format: Save both is the only choice that settles it. -->
<Button Style="{StaticResource Button.Primary}" Content="{l:Loc Server.Sync.Action.SaveBoth}" Command="{Binding SaveBothCommand}" ToolTip="{Binding SaveBothToolTip}"
@@ -254,7 +254,7 @@
<Border Style="{StaticResource Border.Dialog}" Width="520">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" TextTrimming="CharacterEllipsis" ToolTip="{Binding Heading}" />
<TextBlock Text="{l:Loc Editor.RemoveCopy.Message}" Margin="0,8,0,0" Foreground="{DynamicResource Brush.TextMuted}" TextWrapping="Wrap" LineHeight="18" />
<TextBlock Text="{Binding Message}" Margin="0,8,0,0" Foreground="{DynamicResource Brush.TextMuted}" TextWrapping="Wrap" LineHeight="18" />
<ItemsControl ItemsSource="{Binding Facts}" Focusable="False" Margin="0,14,0,0" Grid.IsSharedSizeScope="True">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type ar:DialogFact}">
+162 -44
View File
@@ -9,9 +9,11 @@ using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
namespace Chronos.App.Workspace;
@@ -51,6 +53,9 @@ public sealed record WorkspaceEntry(Guid ProjectId, Guid SequenceId, string Name
/// <summary>This Chronos reads its working state: it can open.</summary>
public bool IsReadable => !Damaged && !Newer;
/// <summary>The project's home is a server (phase 5b), not this PC's archive.</summary>
public bool IsServerHome => !Home.IsArchive;
}
/// <summary>What changing the workspace folder to <see cref="Folder"/> does: Edit lists its projects from then on; nothing is moved.</summary>
@@ -71,6 +76,13 @@ public sealed record WorkspaceCopyFacts(long Bytes, long? Free)
public bool TooLittleSpace => Free is { } free && free < Bytes + WorkspaceJobs.CopySpaceReserve;
}
/// <summary>
/// A workspace project's home told that the project changed there (owner review 2, R8, phase 5b: a server's
/// <c>projectChanged</c>): <see cref="Change"/> is one of <c>Protocol.ProjectChanges</c>; null for every project of
/// <see cref="Server"/> when changes may have been missed (its events were lost for a while).
/// </summary>
public sealed record WorkspaceHomeChange(string Server, Guid? ProjectId, string? Change);
/// <summary>A project brought into the workspace and the copy of its media that was queued.</summary>
public sealed record WorkspaceCheckout(SequenceProject Project, Job Copy);
@@ -108,12 +120,14 @@ public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files
/// <summary>
/// The workspace of this PC (owner review 2, R8), composed for the desktop: its folder (Settings › Workspace, else
/// <c>workspace</c> under the data folder: <c>%LOCALAPPDATA%\Chronos\workspace</c>, <c>.\data\workspace</c> for a portable
/// copy), the <see cref="WorkspaceStore"/> and <see cref="WorkspaceSync"/> over it, and this PC's archive as the home of
/// its projects (<see cref="ArchiveProjectHome"/>; a server home comes in phase 5b). Every operation runs off the UI thread
/// and returns where the project stands. Nothing a workspace holds is lost: a version is sent before its copy goes, a copy
/// is removed only once the home verifiably holds its head, the work a user chose to discard is kept in
/// <c>&lt;workspace&gt;/.trash</c>, and versions the home holds are pruned past Settings › Workspace › Kept versions only
/// after the home was asked for each. A capture (sample data, no engine) has no workspace: Edit opens the library there.
/// copy), the <see cref="WorkspaceStore"/> and <see cref="WorkspaceSync"/> over it, and the homes of its projects: this PC's
/// archive (<see cref="ArchiveProjectHome"/>) or, from phase 5b, the signed-in server (<see cref="ServerHomes"/>, a
/// <see cref="ServerProjectHome"/>; a project of a server this PC is not signed in to reads as offline, its work waiting
/// here). Every operation runs off the UI thread and returns where the project stands. Nothing a workspace holds is lost: a
/// version is sent before its copy goes, a copy is removed only once the home verifiably holds its head, the work a user
/// chose to discard is kept in <c>&lt;workspace&gt;/.trash</c>, and versions the home holds are pruned past Settings ›
/// Workspace › Kept versions only after the home returned each, a page of its history at a time. A capture (sample data, no
/// engine) has no workspace: Edit opens the library there.
/// </summary>
public sealed class WorkspaceHost
{
@@ -190,17 +204,64 @@ public sealed class WorkspaceHost
public WorkspaceStore Store => Sync.Store;
/// <summary>The home of a workspace project; null for a home this PC cannot reach in this phase (a server, phase 5b).</summary>
/// <summary>
/// The project home of a server home (phase 5b; the desktop's <c>SyncHost.ProjectHome</c>): null while this PC is not
/// signed in to that server, or it keeps no projects. Without it every server home reads as out of reach.
/// </summary>
public Func<BundleHome, IProjectHome?>? ServerHomes { get; set; }
/// <summary>A workspace project's home told that it changed there (any thread): its state is read again.</summary>
public event Action<WorkspaceHomeChange>? HomeChanged;
/// <summary>The home of a workspace project; null for a home this PC cannot reach now (the index not open, a server it is not signed in to).</summary>
public IProjectHome? HomeOf(BundleHome home)
{
ArgumentNullException.ThrowIfNull(home);
return home.IsArchive && _db() is { } db && _archives() is { } archives ? new ArchiveProjectHome(db, archives.Projects, home.SequenceId) : null;
if (!home.IsArchive) return ServerHomes?.Invoke(home);
return _db() is { } db && _archives() is { } archives ? new ArchiveProjectHome(db, archives.Projects, home.SequenceId) : null;
}
/// <summary>The home of a sequence of this PC's archive (<paramref name="sequenceId"/> is in its index).</summary>
public static BundleHome ArchiveHome(Guid sequenceId) => new(BundleHome.ArchiveKind, sequenceId);
/// <summary>The home of a sequence of this PC's archive.</summary>
/// <exception cref="WorkspaceException">The index or the archive engine is not open.</exception>
public IProjectHome HomeOfSequence(Guid sequenceId) =>
HomeOf(new BundleHome(BundleHome.ArchiveKind, sequenceId)) ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
public IProjectHome HomeOfSequence(Guid sequenceId) => Reachable(ArchiveHome(sequenceId));
/// <summary>The home <paramref name="home"/> names, which must be reachable now.</summary>
/// <exception cref="WorkspaceException">The index or the archive engine is not open (this PC's archive).</exception>
/// <exception cref="HomeUnavailableException">This PC is not signed in to the server, or it keeps no projects.</exception>
public IProjectHome Reachable(BundleHome home) =>
HomeOf(home) ?? (home.IsArchive
? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"))
: throw new HomeUnavailableException("This PC is not signed in to the server of the project, or it keeps no projects."));
/// <summary>
/// The signed-in server told that a project changed there (phase 5b), or (<paramref name="change"/> null) that changes
/// may have been missed: projects of this workspace whose home it is are told (<see cref="HomeChanged"/>).
/// </summary>
public void OnServerProjectChanged(string server, ProjectChangedEvent? change)
{
ArgumentNullException.ThrowIfNull(server);
if (change is null)
{
HomeChanged?.Invoke(new WorkspaceHomeChange(server, null, null));
return;
}
// The folder is named by the project's id: only a project this workspace holds, of that server and sequence, is told.
try
{
if (!IsAvailable || Store.Find(change.ProjectId)?.ReadBundle().Workspace?.Home is not { IsArchive: false } home || home.SequenceId != change.SequenceId
|| !string.Equals(home.Server, server, StringComparison.OrdinalIgnoreCase))
return;
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Info("workspace", $"A change of project {change.ProjectId} on {server} could not be matched: {ex.Message}");
return;
}
HomeChanged?.Invoke(new WorkspaceHomeChange(server, change.ProjectId, change.Change));
}
/// <summary>
/// The projects of the workspace; one whose working state cannot be read is listed as damaged (<see cref="WorkspaceEntry.Damaged"/>),
@@ -307,10 +368,15 @@ public sealed class WorkspaceHost
}
/// <summary>The home's live projects of a sequence, Main first (made from the sequence's settings when it has none yet).</summary>
public Task<IReadOnlyList<SequenceProject>> HomeProjectsAsync(Guid sequenceId, CancellationToken cancellationToken = default)
public Task<IReadOnlyList<SequenceProject>> HomeProjectsAsync(Guid sequenceId, CancellationToken cancellationToken = default) =>
HomeProjectsAsync(ArchiveHome(sequenceId), cancellationToken);
/// <summary>The live projects of <paramref name="home"/>'s sequence, Main first (made from the sequence's settings when it has none yet).</summary>
/// <exception cref="HomeUnavailableException">A server home this PC cannot reach now.</exception>
public Task<IReadOnlyList<SequenceProject>> HomeProjectsAsync(BundleHome home, CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
return Task.Run(() => home.ListAsync(cancellationToken), cancellationToken);
var reached = Reachable(home);
return Task.Run(() => reached.ListAsync(cancellationToken), cancellationToken);
}
/// <summary>
@@ -321,10 +387,22 @@ public sealed class WorkspaceHost
/// <exception cref="ProjectException">The home has no such project, or the name is invalid or taken.</exception>
/// <exception cref="HomeUnavailableException">The archive is offline or busy.</exception>
/// <exception cref="WorkspaceException">The workspace folder lies inside a library: nothing was written, here or at the home.</exception>
public async Task<WorkspaceCheckout> CheckoutAsync(Guid sequenceId, Guid? projectId, string? newName, string media = BundleMedia.Proxies,
public Task<WorkspaceCheckout> CheckoutAsync(Guid sequenceId, Guid? projectId, string? newName, string media = BundleMedia.Proxies,
CancellationToken cancellationToken = default) =>
CheckoutAsync(ArchiveHome(sequenceId), projectId, newName, media, cancellationToken);
/// <summary>
/// Brings a project of <paramref name="home"/>'s sequence (this PC's archive, or the signed-in server) into the workspace
/// and queues the copy of its media, as <see cref="CheckoutAsync(Guid, Guid?, string?, string, CancellationToken)"/>.
/// </summary>
/// <exception cref="ProjectException">The home has no such project, or the name is invalid or taken.</exception>
/// <exception cref="HomeUnavailableException">The home cannot be reached now.</exception>
/// <exception cref="WorkspaceException">The workspace folder lies inside a library: nothing was written, here or at the home.</exception>
public async Task<WorkspaceCheckout> CheckoutAsync(BundleHome home, Guid? projectId, string? newName, string media = BundleMedia.Proxies,
CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
var reached = Reachable(home);
var sequenceId = home.SequenceId;
var checkout = await Task.Run(async () =>
{
// Refused before anything is written: the copy job would refuse such a folder after the checkout filled it.
@@ -333,11 +411,11 @@ public sealed class WorkspaceHost
SequenceProject project;
if (newName is not null)
{
project = await home.CreateAsync(newName, null, null, cancellationToken).ConfigureAwait(false);
project = await reached.CreateAsync(newName, null, null, cancellationToken).ConfigureAwait(false);
}
else
{
var listed = await home.ListAsync(cancellationToken).ConfigureAwait(false);
var listed = await reached.ListAsync(cancellationToken).ConfigureAwait(false);
project = projectId is { } id
? listed.FirstOrDefault(p => p.Id == id) ?? throw new ProjectException(ProjectError.NotFound, $"The home has no project {id}.")
: listed.First(p => p.IsMain);
@@ -345,9 +423,10 @@ public sealed class WorkspaceHost
// A copy here this Chronos cannot read (damaged, or a newer Chronos's): nothing is checked out or copied over it.
if (Store.Find(project.Id) is { } here && await EntryOrUnreadableAsync(here, cancellationToken).ConfigureAwait(false) is { IsReadable: false } unreadable)
throw Unreadable(unreadable);
await Sync.CheckoutAsync(home, project.Id, media, cancellationToken).ConfigureAwait(false);
var folder = await Sync.CheckoutAsync(reached, project.Id, media, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {project.Id} ('{project.Name}') of sequence {sequenceId} checked out into {Store.Root}");
return new WorkspaceCheckout(project, await QueueCopyCoreAsync(sequenceId, project.Id, media, cancellationToken).ConfigureAwait(false));
var title = folder.ReadBundle().Sequence.Title ?? string.Empty;
return new WorkspaceCheckout(project, await QueueCopyCoreAsync(home, project.Id, media, title, cancellationToken).ConfigureAwait(false));
}, cancellationToken);
// Back on the caller's thread (the UI's): the settings are written there.
Remember(sequenceId, checkout.Project.Id);
@@ -361,20 +440,24 @@ public sealed class WorkspaceHost
public Task<Job> QueueCopyAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var bundle = Existing(projectId).ReadBundle();
return await QueueCopyCoreAsync(bundle.Workspace!.Home.SequenceId, projectId, bundle.Workspace.Media.Kind, cancellationToken).ConfigureAwait(false);
return await QueueCopyCoreAsync(bundle.Workspace!.Home, projectId, bundle.Workspace.Media.Kind, bundle.Sequence.Title ?? string.Empty, cancellationToken)
.ConfigureAwait(false);
}, cancellationToken);
/// <summary>
/// Where a project stands. With <paramref name="askHome"/>, against its home's head too: a home that cannot be reached
/// reads as offline; one that answers it no longer has the project or its sequence (the sequence left the index) reads
/// as <see cref="WorkspaceState.Gone"/>, whose local copy can then only be removed (nothing is removed by itself).
/// (a server this PC is not signed in to among them) reads as offline; one that answers it no longer has the project or
/// its sequence (the sequence left the index, the project was deleted there) reads as <see cref="WorkspaceState.Gone"/>,
/// whose local copy can then only be removed (nothing is removed by itself).
/// </summary>
public Task<WorkspaceStatus> StatusAsync(Guid projectId, bool askHome = true, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
var home = askHome ? HomeOf(project.ReadBundle().Workspace!.Home) : null;
var named = project.ReadBundle().Workspace!.Home;
var home = askHome ? HomeOf(named) : null;
try
{
if (askHome && home is null && !named.IsArchive) return Offline(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
return await Sync.StatusAsync(projectId, home, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (home is not null && ex is ProjectException or DatabaseException or IOException)
@@ -392,6 +475,13 @@ public sealed class WorkspaceHost
Conflict = gone ? null : local.Conflict,
};
}
static WorkspaceStatus Offline(WorkspaceStatus local) =>
local with
{
Offline = true,
State = local.State is WorkspaceState.MediaRemoved or WorkspaceState.Damaged or WorkspaceState.Conflict ? local.State : WorkspaceState.Offline,
};
}, cancellationToken);
/// <summary>
@@ -542,23 +632,30 @@ public sealed class WorkspaceHost
/// <summary>A new project of the sequence named <paramref name="name"/> from <paramref name="fromVersionId"/> (a version the home holds), else from Main's head.</summary>
/// <exception cref="ProjectException">The name is invalid or taken.</exception>
public Task<SequenceProject> CreateProjectAsync(Guid sequenceId, string name, Guid? fromVersionId, CancellationToken cancellationToken = default)
public Task<SequenceProject> CreateProjectAsync(Guid sequenceId, string name, Guid? fromVersionId, CancellationToken cancellationToken = default) =>
CreateProjectAsync(ArchiveHome(sequenceId), name, fromVersionId, cancellationToken);
/// <summary>A new project of <paramref name="home"/>'s sequence named <paramref name="name"/> from <paramref name="fromVersionId"/>, else from Main's head.</summary>
/// <exception cref="ProjectException">The name is invalid or taken.</exception>
/// <exception cref="HomeUnavailableException">The home cannot be reached now.</exception>
public Task<SequenceProject> CreateProjectAsync(BundleHome home, string name, Guid? fromVersionId, CancellationToken cancellationToken = default)
{
var home = HomeOfSequence(sequenceId);
var reached = Reachable(home);
return Task.Run(async () =>
{
var created = await home.CreateAsync(name, fromVersionId, null, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project '{created.Name}' ({created.Id}) made for sequence {sequenceId}");
var created = await reached.CreateAsync(name, fromVersionId, null, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project '{created.Name}' ({created.Id}) made for sequence {home.SequenceId}");
return created;
}, cancellationToken);
}
/// <summary>Renames a project at its home, then its working state here.</summary>
/// <exception cref="ProjectException">The name is invalid or taken, or the project is gone.</exception>
/// <exception cref="HomeUnavailableException">The home cannot be reached now: the name stays.</exception>
public Task<string> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
var renamed = await ArchiveProjects(project).RenameAsync(projectId, name, cancellationToken).ConfigureAwait(false);
var renamed = await HomeOfProject(projectId).RenameAsync(projectId, name, cancellationToken).ConfigureAwait(false);
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
var bundle = project.ReadBundle();
@@ -592,8 +689,8 @@ public sealed class WorkspaceHost
var status = (await SendAsync(projectId, home, cancellationToken).ConfigureAwait(false)).Status;
if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
await ArchiveProjects(project).DeleteAsync(projectId, cancellationToken).ConfigureAwait(false);
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Unsent(workspace.Home));
await home.DeleteAsync(projectId, cancellationToken).ConfigureAwait(false);
Log.Info("workspace", $"Project {projectId} ('{workspace.Name}') deleted at its home");
try
{
@@ -624,7 +721,7 @@ public sealed class WorkspaceHost
var status = (await SyncAsync(projectId, cancellationToken).ConfigureAwait(false)).Status;
if (status.State == WorkspaceState.Gone) throw new WorkspaceException(Loc.L("Errors.Workspace.DeletedAtHome"));
if (status.Conflict is not null) throw new WorkspaceException(Loc.L("Errors.Workspace.Conflict"));
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
if (status.Ahead > 0 || (status.Modified && !status.ReadOnly)) throw new WorkspaceException(Unsent(Existing(projectId).ReadBundle().Workspace!.Home));
}
/// <summary>The plan of "Remove local copy": the folder's files and size, and what would not be at the home after it.</summary>
@@ -682,7 +779,7 @@ public sealed class WorkspaceHost
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
// A version saved here that cannot be read may be one the home never had: only discarding keeps it aside.
if (status.Ahead > 0 || status.Damaged > 0 || (status.Modified && !status.ReadOnly) || status.Conflict is not null)
throw new WorkspaceException(Loc.L("Errors.Workspace.Unsent"));
throw new WorkspaceException(Unsent(workspace.Home));
await VerifyHomeAsync(projectId, workspace, cancellationToken).ConfigureAwait(false);
}
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
@@ -742,7 +839,8 @@ public sealed class WorkspaceHost
/// <summary>The home holds this copy's work: its head and the base this copy was last in step with read back, each matching its hash.</summary>
private async Task VerifyHomeAsync(Guid projectId, BundleWorkspace workspace, CancellationToken cancellationToken)
{
var home = HomeOf(workspace.Home) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"));
var server = !workspace.Home.IsArchive;
var home = HomeOf(workspace.Home) ?? throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Offline", server));
ProjectVersion head;
ProjectVersion? basis;
bool held;
@@ -761,13 +859,16 @@ public sealed class WorkspaceHost
}
catch (Exception ex) when (ex is HomeUnavailableException or ProjectException or DatabaseException)
{
throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"), ex);
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.Offline", server), ex);
}
if (!held || !ProjectContent.Verifies(head.SettingsJson, head.ContentHash) || basis is null || !ProjectContent.Verifies(basis.SettingsJson, basis.ContentHash)
|| (workspace.Base is { } known && !string.Equals(known.ContentHash, basis.ContentHash, StringComparison.OrdinalIgnoreCase)))
throw new WorkspaceException(Loc.L("Errors.Workspace.HomeCheck"));
throw new WorkspaceException(WorkspaceText.ForHome("Errors.Workspace.HomeCheck", server));
}
/// <summary>"Some work is not in the library (on the server) yet": worded for the project's home.</summary>
private static string Unsent(BundleHome home) => WorkspaceText.ForHome("Errors.Workspace.Unsent", !home.IsArchive);
/// <summary>
/// The project's folder taken out of the workspace under its lease: every file and folder in it but the media and the
/// lease (the working state, the versions, the sync state, the exports, and whatever else a Chronos keeps there) moved
@@ -889,25 +990,42 @@ public sealed class WorkspaceHost
_savePreferences();
}
private async Task<Job> QueueCopyCoreAsync(Guid sequenceId, Guid projectId, string media, CancellationToken cancellationToken)
/// <summary>
/// The copy of a project's media from its home, unless one is waiting or running: a sequence of this PC's archive copied
/// from there, a server's downloaded from it (<paramref name="title"/> labels that job: the index has no row for it).
/// </summary>
private async Task<Job> QueueCopyCoreAsync(BundleHome home, Guid projectId, string media, string title, CancellationToken cancellationToken)
{
var engine = _engine() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var db = _db() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
Guid known;
lock (_gate) _copies.TryGetValue(projectId, out known);
if (known != Guid.Empty && await db.Jobs.GetAsync(known, cancellationToken).ConfigureAwait(false) is { State: JobState.Queued or JobState.Running } running) return running;
var sequence = await db.Sequences.GetAsync(sequenceId, cancellationToken).ConfigureAwait(false)
?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {sequenceId} is not in the index.");
var job = await engine.EnqueueAsync(WorkspaceJobs.Copy(sequence, Store.Root, projectId, media), cancellationToken: cancellationToken).ConfigureAwait(false);
ArchiveJobRequest request;
if (home.IsArchive)
{
var sequence = await db.Sequences.GetAsync(home.SequenceId, cancellationToken).ConfigureAwait(false)
?? throw new ProjectException(ProjectError.SequenceNotFound, $"Sequence {home.SequenceId} is not in the index.");
request = WorkspaceJobs.Copy(sequence, Store.Root, projectId, media);
}
else
{
request = WorkspaceJobs.CopyFromServer(home.SequenceId, title, home.Server ?? throw new InvalidDataException("A server home names no server."), Store.Root,
projectId, media);
}
var job = await engine.EnqueueAsync(request, cancellationToken: cancellationToken).ConfigureAwait(false);
lock (_gate) _copies[projectId] = job.Id;
return job;
}
private IProjectHome HomeOfProject(Guid projectId) =>
HomeOf(Existing(projectId).ReadBundle().Workspace!.Home) ?? throw new HomeUnavailableException("The project's home cannot be reached from this PC.");
private ProjectService ArchiveProjects(WorkspaceProject project) =>
project.ReadBundle().Workspace!.Home.IsArchive && _archives() is { } archives ? archives.Projects : throw new WorkspaceException(Loc.L("Errors.Workspace.Offline"));
/// <exception cref="HomeUnavailableException">The project's home cannot be reached now.</exception>
private IProjectHome HomeOfProject(Guid projectId)
{
var home = Existing(projectId).ReadBundle().Workspace!.Home;
return HomeOf(home) ?? throw new HomeUnavailableException(home.IsArchive
? "The project's home cannot be reached from this PC."
: "This PC is not signed in to the server of the project, or it keeps no projects.");
}
private WorkspaceProject Existing(Guid projectId) => Store.Find(projectId) ?? throw new WorkspaceException(Loc.L("Errors.Workspace.NotCheckedOut"));
@@ -7,9 +7,10 @@ using Chronos.Ui.Mvvm;
namespace Chronos.App.Workspace;
/// <summary>
/// A project of the workspace in Edit's picker (owner review 2, R8): its name, its sequence (title and thumbnail) and
/// where it stands, a chip read from its home after the list shows. A copy whose working state cannot be read is listed
/// as damaged, one a newer Chronos wrote as such, by the name each is still known by.
/// A project of the workspace in Edit's picker (owner review 2, R8): its name, its sequence (title and thumbnail; a server's
/// as the Library lists it, phase 5b) and where it stands, a chip read from its home after the list shows and again when
/// the home tells it changed. A copy whose working state cannot be read is listed as damaged, one a newer Chronos wrote
/// as such, by the name each is still known by.
/// </summary>
public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? sequence) : ObservableObject
{
@@ -53,7 +54,7 @@ public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? seq
public string StateText => Entry.Newer ? Loc.L("Editor.Workspace.State.NewerCopy")
: Entry.Damaged ? Loc.L("Editor.Workspace.State.Damaged")
: Entry.HasMedia || _status is not null ? WorkspaceText.State(_status) : Loc.L("Editor.Workspace.State.MediaRemoved");
: Entry.HasMedia || _status is not null ? WorkspaceText.State(_status, server: Entry.IsServerHome) : Loc.L("Editor.Workspace.State.MediaRemoved");
public StatusKind StateKind => Entry.Newer ? StatusKind.Warning
: Entry.Damaged ? StatusKind.Error
@@ -61,7 +62,7 @@ public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? seq
public string StateToolTip => Entry.Newer ? Loc.L("Tooltips.Editor.Workspace.State.NewerCopy")
: Entry.Damaged ? Loc.L("Tooltips.Editor.Workspace.State.DamagedCopy")
: Entry.HasMedia || _status is not null ? WorkspaceText.StateToolTip(_status) : Loc.L("Tooltips.Editor.Workspace.State.MediaRemoved");
: Entry.HasMedia || _status is not null ? WorkspaceText.StateToolTip(_status, server: Entry.IsServerHome) : Loc.L("Tooltips.Editor.Workspace.State.MediaRemoved");
/// <summary>"Vertical social · Harbour sunset · In sync": what screen readers hear for the row.</summary>
public string Description => string.Join(Loc.Separator, Name, SequenceTitle, StateText);
+52 -19
View File
@@ -1,27 +1,53 @@
using System.IO;
using System.Net;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Server;
using Chronos.App.Shell;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
using Chronos.Protocol.Client;
using Chronos.Ui.Controls;
namespace Chronos.App.Workspace;
/// <summary>How the workspace's states, projects, versions and failures read in the UI (owner review 2, R8). WPF-free.</summary>
/// <summary>
/// How the workspace's states, projects, versions and failures read in the UI (owner review 2, R8). WPF-free. A text that
/// names the project's home has a form for each: "the library" (this PC's archive) and, with <c>server</c>, "the server"
/// (phase 5b: its key with <see cref="ServerSuffix"/>).
/// </summary>
public static class WorkspaceText
{
/// <summary>The suffix of a text's key in its form for a project whose home is a server.</summary>
public const string ServerSuffix = ".Server";
/// <summary>The project's name; the Main project in the UI language.</summary>
public static string ProjectName(string name, bool isMain) =>
isMain && string.Equals(name, ProjectService.MainName, StringComparison.Ordinal) ? Loc.L("Editor.Project.Main") : name;
/// <summary>The state chip: "In sync", "Not sent", "Conflict"…; "Syncing" while a sync runs.</summary>
public static string State(WorkspaceStatus? status, bool syncing = false) =>
syncing ? Loc.L("Editor.Workspace.State.Syncing") : status is null ? Loc.L("Editor.Workspace.State.Reading") : Loc.L("Editor.Workspace.State." + status.State);
/// <summary>
/// The text of <paramref name="key"/> worded for the project's home: its server form (<see cref="ServerSuffix"/>) when
/// <paramref name="server"/>, the key itself for a text that names no home.
/// </summary>
public static string ForHome(string key, bool server, params object?[] args)
{
ArgumentNullException.ThrowIfNull(key);
var worded = server && Loc.Get(key + ServerSuffix, Loc.Culture) is not null ? key + ServerSuffix : key;
return args.Length == 0 ? Loc.L(worded) : Loc.L(worded, args);
}
/// <summary>
/// The state chip: "In sync", "Not sent", "Conflict"…; "Syncing" while a sync runs; worded for a server's project where
/// the state names the home ("Server newer", "Not on server").
/// </summary>
public static string State(WorkspaceStatus? status, bool syncing = false, bool server = false) =>
syncing ? Loc.L("Editor.Workspace.State.Syncing")
: status is null ? Loc.L("Editor.Workspace.State.Reading")
: ForHome("Editor.Workspace.State." + status.State, server);
public static StatusKind Kind(WorkspaceStatus? status, bool syncing = false) => syncing ? StatusKind.Running : status?.State switch
{
@@ -36,15 +62,16 @@ public static class WorkspaceText
_ => StatusKind.Queued,
};
/// <summary>What the state means and what to do, with the counts behind it.</summary>
public static string StateToolTip(WorkspaceStatus? status, bool syncing = false) => syncing ? Loc.L("Tooltips.Editor.Workspace.State.Syncing")
: status is null ? Loc.L("Tooltips.Editor.Workspace.State.Reading")
/// <summary>What the state means and what to do, with the counts behind it, worded for the project's home.</summary>
public static string StateToolTip(WorkspaceStatus? status, bool syncing = false, bool server = false) =>
syncing ? ForHome("Tooltips.Editor.Workspace.State.Syncing", server)
: status is null ? ForHome("Tooltips.Editor.Workspace.State.Reading", server)
: status.State switch
{
WorkspaceState.Ahead => Loc.L("Tooltips.Editor.Workspace.State.Ahead", Formatting.Count(status.Ahead)),
WorkspaceState.Behind => Loc.L("Tooltips.Editor.Workspace.State.Behind", Formatting.Count(status.Behind)),
WorkspaceState.Offline when status.Ahead > 0 => Loc.L("Tooltips.Editor.Workspace.State.OfflineAhead", Formatting.Count(status.Ahead)),
var state => Loc.L("Tooltips.Editor.Workspace.State." + state),
WorkspaceState.Ahead => ForHome("Tooltips.Editor.Workspace.State.Ahead", server, Formatting.Count(status.Ahead)),
WorkspaceState.Behind => ForHome("Tooltips.Editor.Workspace.State.Behind", server, Formatting.Count(status.Behind)),
WorkspaceState.Offline when status.Ahead > 0 => ForHome("Tooltips.Editor.Workspace.State.OfflineAhead", server, Formatting.Count(status.Ahead)),
var state => ForHome("Tooltips.Editor.Workspace.State." + state, server),
};
/// <summary>"Saved", "Merged", "Restored", "Imported", "Outside change".</summary>
@@ -76,34 +103,40 @@ public static class WorkspaceText
/// One line per setting both sides changed ("Deflicker window 41 here, 33 in the library"), at most <paramref name="max"/>.
/// A conflict of format (<see cref="ProjectMerge.FormatPath"/>) reads as its cause, never as the format's numbers.
/// </summary>
public static IReadOnlyList<string> ConflictLines(IEnumerable<SettingsDifference> differences, int max)
public static IReadOnlyList<string> ConflictLines(IEnumerable<SettingsDifference> differences, int max, bool server = false)
{
ArgumentNullException.ThrowIfNull(differences);
var list = differences.ToList();
if (list.Any(d => d.Path == ProjectMerge.FormatPath)) return [Loc.L("Editor.Workspace.Conflict.NewerFormat")];
return SyncText.Differences(list, max, (label, mine, theirs) => Loc.L("Editor.Workspace.Difference", label, mine, theirs));
return SyncText.Differences(list, max, (label, mine, theirs) => ForHome("Editor.Workspace.Difference", server, label, mine, theirs));
}
/// <summary>One line per setting that differs between now and a version ("Deflicker window 41 now, 33 in that version").</summary>
public static IReadOnlyList<string> CompareLines(IEnumerable<SettingsDifference> differences, int max) =>
SyncText.Differences(differences, max, (label, now, then) => Loc.L("Editor.History.Difference", label, now, then));
/// <summary>Why a workspace operation stopped, as one localized sentence chosen by cause; the exception's own text goes to the log.</summary>
public static string Failure(Exception ex) => ex switch
/// <summary>
/// Why a workspace operation stopped, as one localized sentence chosen by cause and worded for the project's home; the
/// exception's own text goes to the log.
/// </summary>
public static string Failure(Exception ex, bool server = false) => ex switch
{
WorkspaceException or LeaseUnavailableException => ex.Message,
// A library that can be read but not written (a read-only share, a write-protected disk): the work waits here as offline.
HomeUnavailableException { InnerException: ArchiveOfflineException { Availability: ArchiveAvailability.ReadOnly } }
or ArchiveOfflineException { Availability: ArchiveAvailability.ReadOnly } => Loc.L("Errors.Workspace.ReadOnlyHome"),
HomeUnavailableException or ArchiveOfflineException => Loc.L("Errors.Workspace.Offline"),
HomeUnavailableException or ArchiveOfflineException => ForHome("Errors.Workspace.Offline", server),
ProjectException { Reason: ProjectError.NameTaken } => Loc.L("Errors.Workspace.NameTaken"),
ProjectException { Reason: ProjectError.InvalidName } => Loc.L("Errors.Workspace.InvalidName"),
ProjectException { Reason: ProjectError.MainCannotBeDeleted } => Loc.L("Errors.Workspace.MainKept"),
ProjectException => Loc.L("Errors.Workspace.ProjectGone"),
ProjectException => ForHome("Errors.Workspace.ProjectGone", server),
// A version over the size one may be: saved here (refused before anything was written) or sent (the home stored nothing).
ProjectVersionTooLargeException or WorkspaceSyncException { Outcome: PushOutcome.TooLarge } =>
Loc.L("Errors.Workspace.VersionTooLarge", ProjectSidecars.MaxVersionBytes >> 20),
WorkspaceSyncException => Loc.L("Errors.Workspace.Refused"),
ForHome("Errors.Workspace.VersionTooLarge", server, ProjectSidecars.MaxVersionBytes >> 20),
WorkspaceSyncException => ForHome("Errors.Workspace.Refused", server),
// A server's refusal that keeps its meaning: an account that may not change projects there, above all.
ChronosApiException { Status: HttpStatusCode.Forbidden } => Loc.L("Errors.Workspace.Forbidden"),
ChronosApiException api => ErrorText.ForServer(api),
InvalidDataException => Loc.L("Errors.Workspace.Damaged"),
Editor.EditorException => ex.Message,
_ => ArchiveFailures.Cause(ex),
+27 -2
View File
@@ -13,11 +13,21 @@ public sealed record HomeSequence(BundleArchive Archive, BundleSequence Sequence
/// <summary>
/// Where a sequence's projects live (owner review 2, R8): the side a workspace pushes to and pulls from, "like git". This
/// PC's archive is one (<see cref="ArchiveProjectHome"/>); a server is the other (phase 5b). Every call may throw
/// <see cref="HomeUnavailableException"/> when the home cannot be reached, and <see cref="ProjectException"/> when it refuses.
/// PC's archive is one (<see cref="ArchiveProjectHome"/>); a server is the other (<see cref="ServerProjectHome"/>, phase
/// 5b). Every call may throw <see cref="HomeUnavailableException"/> when the home cannot be reached, and
/// <see cref="ProjectException"/> when it refuses.
/// </summary>
public interface IProjectHome
{
/// <summary>Gives a project another name (1–60 characters, unique among the sequence's live projects whatever the case).</summary>
/// <exception cref="ProjectException">Unknown project, or the name is invalid or taken.</exception>
Task<SequenceProject> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken) =>
throw new NotSupportedException("This home does not rename projects.");
/// <summary>Deletes a project (never Main) into the home's project trash, with all its versions, which stay readable there.</summary>
/// <exception cref="ProjectException">Unknown project, or the Main project.</exception>
Task DeleteAsync(Guid projectId, CancellationToken cancellationToken) => throw new NotSupportedException("This home does not delete projects.");
/// <summary>The sequence and where it is.</summary>
Task<HomeSequence> SequenceAsync(CancellationToken cancellationToken);
@@ -146,6 +156,21 @@ public sealed class ArchiveProjectHome(ChronosDatabase db, ProjectService projec
public Task<HomeFrames> FramesAsync(CancellationToken cancellationToken) => projects.FramesAsync(sequenceId, cancellationToken);
public Task<SequenceProject> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken) =>
Reach(async () =>
{
await Own(projectId, cancellationToken).ConfigureAwait(false);
return await projects.RenameAsync(projectId, name, cancellationToken).ConfigureAwait(false);
});
public Task DeleteAsync(Guid projectId, CancellationToken cancellationToken) =>
Reach(async () =>
{
await Own(projectId, cancellationToken).ConfigureAwait(false);
await projects.DeleteAsync(projectId, cancellationToken).ConfigureAwait(false);
return true;
});
/// <summary>
/// The sequence's frames version (frames added, removed, converted or renamed), with how many of its photos the index has
/// hashed and a checksum of those hashes (a Verify hashes them, or finds other bytes, without another frames version)
@@ -0,0 +1,192 @@
using System.Net;
using System.Text.Json;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Protocol.Client;
namespace Chronos.Data.Projects;
/// <summary>
/// A sequence of a Chronos Server as its projects' home (owner review 2, R8, phase 5b): the server's
/// <c>/api/v1/sequences/{sid}/projects</c> through <see cref="ChronosClient"/>, read into the model a workspace works with
/// (<see cref="ProjectWire"/>), so a workspace pushes to and pulls from a server as it does with this PC's archive. A
/// server out of reach (no answer, a timeout, a certificate it no longer presents, an answer that is not the API's), a
/// sign-in that expired, a sequence the server holds busy or an archive offline there (503), a project file it cannot write
/// for now and a server that keeps no projects are <see cref="HomeUnavailableException"/>s: the workspace shows Offline and
/// its work waits. A sequence, project or version the server does not have, and a name it refuses, are
/// <see cref="ProjectException"/>s as on this PC's archive; anything else (an account without the right, a request the
/// server takes for wrong) keeps its <see cref="ChronosApiException"/>. A push answers its outcome without throwing (a
/// divergence carries the head). The client is the caller's: the home never disposes it, and a client disposed meanwhile
/// (the session ended) is a home out of reach.
/// </summary>
public sealed class ServerProjectHome : IProjectHome
{
/// <summary>The largest page of versions the server answers.</summary>
private const int MaxPage = 200;
/// <param name="serverName">The server's name as its <c>server/info</c> gives it, for the project file; the address's host when null.</param>
public ServerProjectHome(ChronosClient client, Guid sequenceId, string? serverName = null)
{
ArgumentNullException.ThrowIfNull(client);
Client = client;
SequenceId = sequenceId;
Server = SyncService.ServerKey(client.BaseAddress);
ServerName = string.IsNullOrWhiteSpace(serverName) ? client.BaseAddress.Host : serverName.Trim();
}
public ChronosClient Client { get; }
/// <summary>The server's sequence.</summary>
public Guid SequenceId { get; }
/// <summary>The server as workspace projects and sync links name it (<see cref="SyncService.ServerKey"/>).</summary>
public string Server { get; }
public string ServerName { get; }
/// <summary>The home of a workspace project of this server's sequence.</summary>
public BundleHome Home => new(BundleHome.ServerKind, SequenceId, null, Server);
/// <remarks>
/// A project file names an archive by id: a server's sequences carry one made from the server's key
/// (<see cref="ArchiveIdOf"/>), with the server's name and no path.
/// </remarks>
public Task<HomeSequence> SequenceAsync(CancellationToken cancellationToken) =>
Reach(async () =>
{
var sequence = await Client.GetSequenceAsync(SequenceId, cancellationToken).ConfigureAwait(false);
return new HomeSequence(new BundleArchive(ArchiveIdOf(Server), ServerName, null), new BundleSequence(sequence.Id, sequence.Folder, sequence.DisplayTitle,
sequence.FrameCount), Home);
}, cancellationToken);
/// <summary>
/// The archive id a server's sequences carry in a workspace's project file, which names one: the same for every
/// sequence of <paramref name="server"/> (<see cref="SyncService.ServerKey"/>), made from its key (a version 8 UUID),
/// never one of this PC's archives.
/// </summary>
public static Guid ArchiveIdOf(string server)
{
ArgumentNullException.ThrowIfNull(server);
var hash = System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes("chronos-server-archive:" + server));
hash[6] = (byte)((hash[6] & 0x0F) | 0x80);
hash[8] = (byte)((hash[8] & 0x3F) | 0x80);
return new Guid(hash.AsSpan(0, 16), bigEndian: true);
}
public Task<IReadOnlyList<SequenceProject>> ListAsync(CancellationToken cancellationToken) =>
Reach<IReadOnlyList<SequenceProject>>(async () =>
[.. (await Client.ListProjectsAsync(SequenceId, cancellationToken).ConfigureAwait(false)).Select(ProjectWire.ToProject)], cancellationToken);
/// <remarks>The server records the account that makes the project as its maker, whatever <paramref name="author"/> says.</remarks>
public Task<SequenceProject> CreateAsync(string name, Guid? fromVersionId, string? author, CancellationToken cancellationToken) =>
Reach(async () => ProjectWire.ToProject(await Client.CreateProjectAsync(SequenceId, new CreateProjectRequest(name, fromVersionId), cancellationToken)
.ConfigureAwait(false)), cancellationToken);
public Task<ProjectVersion> HeadAsync(Guid projectId, CancellationToken cancellationToken) =>
Reach(async () => ProjectWire.ToVersion(await Client.GetProjectHeadAsync(SequenceId, projectId, cancellationToken).ConfigureAwait(false)), cancellationToken);
public Task<ProjectVersion?> GetVersionAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken) =>
Reach(async () => await Client.GetProjectVersionAsync(SequenceId, projectId, versionId, cancellationToken).ConfigureAwait(false) is { } version
? ProjectWire.ToVersion(version)
: null, cancellationToken);
public Task<IReadOnlyList<ProjectVersion>> VersionsAfterAsync(Guid projectId, int afterNumber, int limit, CancellationToken cancellationToken) =>
Reach<IReadOnlyList<ProjectVersion>>(async () =>
[
.. (await Client.ListProjectVersionsAsync(SequenceId, projectId, after: Math.Max(0, afterNumber), limit: Page(limit), ct: cancellationToken)
.ConfigureAwait(false)).Items.Select(ProjectWire.ToVersion),
], cancellationToken);
public Task<IReadOnlyList<ProjectVersion>> HistoryAsync(Guid projectId, int? beforeNumber, int limit, CancellationToken cancellationToken) =>
Reach<IReadOnlyList<ProjectVersion>>(async () =>
[
.. (await Client.ListProjectVersionsAsync(SequenceId, projectId, before: beforeNumber is { } before ? Math.Max(0, before) : null, limit: Page(limit),
ct: cancellationToken).ConfigureAwait(false)).Items.Select(ProjectWire.ToVersion),
], cancellationToken);
/// <remarks>The server numbers the version (head + 1) and records the account that pushed it as its author.</remarks>
public Task<PushResult> PushAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(version);
return Reach(async () => ProjectWire.ToResult(await Client.PushProjectVersionAsync(SequenceId, projectId, ProjectWire.ToDto(version), cancellationToken)
.ConfigureAwait(false)), cancellationToken);
}
public Task<HomeFrames> FramesAsync(CancellationToken cancellationToken) =>
Reach(async () => ProjectWire.ToHomeFrames(await Client.GetProjectFramesAsync(SequenceId, cancellationToken).ConfigureAwait(false)), cancellationToken);
public Task<SequenceProject> RenameAsync(Guid projectId, string name, CancellationToken cancellationToken) =>
Reach(async () => ProjectWire.ToProject(await Client.RenameProjectAsync(SequenceId, projectId, name, cancellationToken).ConfigureAwait(false)),
cancellationToken);
public Task DeleteAsync(Guid projectId, CancellationToken cancellationToken) =>
Reach(async () =>
{
await Client.DeleteProjectAsync(SequenceId, projectId, cancellationToken).ConfigureAwait(false);
return true;
}, cancellationToken);
/// <summary>
/// Whether <paramref name="exception"/> says a server is out of reach for now (see the class remarks), not that it
/// refused: what a workspace waits out.
/// </summary>
public static bool IsUnavailable(Exception exception, CancellationToken cancellationToken = default) => exception switch
{
HomeUnavailableException => true,
// A refusal for good, which is an IOException too.
Workspaces.WorkspaceSyncException => false,
ChronosApiException api => Unavailable(api),
UntrustedCertificateException or HttpRequestException or JsonException or ObjectDisposedException => true,
// A timeout of the client's (not the caller's cancellation).
OperationCanceledException => !cancellationToken.IsCancellationRequested,
IOException => true,
_ => false,
};
private static int Page(int limit) => Math.Clamp(limit, 1, MaxPage);
/// <summary>A refusal of the server as this PC's archive gives it, or a server out of reach.</summary>
private static async Task<T> Reach<T>(Func<Task<T>> call, CancellationToken cancellationToken)
{
try
{
return await call().ConfigureAwait(false);
}
catch (ChronosApiException ex) when (Refusal(ex) is { } refusal)
{
throw refusal;
}
catch (Exception ex) when (ex is not ProjectException && IsUnavailable(ex, cancellationToken))
{
throw new HomeUnavailableException(ex is ChronosApiException { Status: HttpStatusCode.Unauthorized }
? $"The sign-in on the server expired: {ex.Message}"
: $"The server cannot be reached: {ex.Message}", ex);
}
}
/// <summary>The project error a refusal stands for (a sequence, project or version the server does not have, a name it refuses); null for any other.</summary>
private static ProjectException? Refusal(ChronosApiException ex) => (ex.Status, ex.Error.Code, ex.Error.Details) switch
{
(HttpStatusCode.NotFound, _, "sequence") => new ProjectException(ProjectError.SequenceNotFound, ex.Message),
(HttpStatusCode.NotFound, _, "project" or "version") => new ProjectException(ProjectError.NotFound, ex.Message),
(HttpStatusCode.BadRequest, ProjectErrors.InvalidName, _) => new ProjectException(ProjectError.InvalidName, ex.Message),
(HttpStatusCode.Conflict, ProjectErrors.NameTaken, _) => new ProjectException(ProjectError.NameTaken, ex.Message),
(HttpStatusCode.Conflict, ProjectErrors.MainCannotBeDeleted, _) => new ProjectException(ProjectError.MainCannotBeDeleted, ex.Message),
_ => null,
};
/// <summary>
/// An answer that says the server cannot serve the call for now: busy, its archive offline or its sequence's folder
/// moved (503), a gateway or a timeout, the sign-in expired (401), a project file it cannot write now (409
/// <c>folder_in_use</c>), a server without the projects (404 with nothing named: the API's fallback), or a success
/// that is no answer of the API (a portal's or a proxy's page).
/// </summary>
private static bool Unavailable(ChronosApiException ex) =>
ex.IsTransient
|| ex.Status == HttpStatusCode.Unauthorized
|| (int)ex.Status is >= 200 and < 300
|| ex is { Status: HttpStatusCode.Conflict, Error.Code: "folder_in_use" }
|| ex is { Status: HttpStatusCode.NotFound, Error.Details: null or "" };
}
+31
View File
@@ -59,6 +59,9 @@ public sealed class SyncAgent : IAsyncDisposable
private readonly SemaphoreSlim _refreshing = new(1, 1);
private Task _running = Task.CompletedTask;
/// <summary>1 while project changes may have been missed (the event stream was lost), until a comparison reached the server.</summary>
private int _projectsMissed;
private SyncSnapshot? _snapshot;
private Exception? _lastError;
@@ -84,6 +87,13 @@ public sealed class SyncAgent : IAsyncDisposable
/// <summary><see cref="Snapshot"/> or <see cref="LastError"/> changed (any thread).</summary>
public event Action? Changed;
/// <summary>
/// A project of one of the server's sequences changed there (owner review 2, R8: <c>projectChanged</c>, any thread), or,
/// with null, a comparison reached the server again after its event stream was lost, so changes may have been missed:
/// workspace projects whose home is this server read where they stand again.
/// </summary>
public event Action<ProjectChangedEvent?>? ProjectChanged;
/// <summary>Starts the comparison and event loops.</summary>
public void Start()
{
@@ -110,6 +120,7 @@ public sealed class SyncAgent : IAsyncDisposable
Volatile.Write(ref _lastError, null);
if (policy.KeepProxiesOffline && _engine is not null) await QueueProxiesAsync(snapshot, linked.Token).ConfigureAwait(false);
Changed?.Invoke();
if (Interlocked.Exchange(ref _projectsMissed, 0) == 1) TellProjects(null);
return snapshot;
}
finally
@@ -172,6 +183,11 @@ public sealed class SyncAgent : IAsyncDisposable
await foreach (var e in _remote.EventsAsync(cancellationToken).ConfigureAwait(false))
{
failures = 0;
if (e is ProjectChangedEvent project)
{
TellProjects(project);
continue;
}
if (e is not SequenceChangedEvent changed) continue;
_changed[changed.SequenceId] = 0;
_eventWake.Writer.TryWrite(true);
@@ -185,6 +201,8 @@ public sealed class SyncAgent : IAsyncDisposable
{
Log.Info(LogCategory, $"Event stream of {Server} lost: {ex.Message}");
}
// Project changes said meanwhile are missed: the next comparison that reaches the server says so.
Volatile.Write(ref _projectsMissed, 1);
try
{
await Task.Delay(Backoff(failures++), cancellationToken).ConfigureAwait(false);
@@ -197,6 +215,19 @@ public sealed class SyncAgent : IAsyncDisposable
}
}
/// <summary>Tells <see cref="ProjectChanged"/>; what a listener throws is logged, never ends the event loop.</summary>
private void TellProjects(ProjectChangedEvent? change)
{
try
{
ProjectChanged?.Invoke(change);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning(LogCategory, $"A project change of {Server} was not handled", ex);
}
}
/// <summary>Compares the sequences named by events, a short while after the first one arrived.</summary>
private async Task ChangedLoopAsync(CancellationToken cancellationToken)
{
+14
View File
@@ -63,6 +63,16 @@ public interface ISyncRemote : IDisposable
/// <summary>Server events until cancelled or the socket closes.</summary>
IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken);
/// <summary>
/// Every frame of a sequence as of one frames version, with the photo aliases of its conversions (owner review 2, R8:
/// what a workspace copy of a server project holds; servers with the <c>projects</c> capability). A remote without the
/// call (the screenshots' sample server) throws <see cref="NotSupportedException"/>.
/// </summary>
Task<ProjectFramesDto> GetProjectFramesAsync(Guid sequenceId, CancellationToken cancellationToken) => throw new NotSupportedException();
/// <summary>The sequence's deep-analysis report (<c>analysis.json</c>); null when it was never deep-analysed, or the remote has no such call.</summary>
Task<string?> GetAnalysisReportAsync(Guid sequenceId, CancellationToken cancellationToken) => Task.FromResult<string?>(null);
}
/// <summary>Where sync jobs find their server connection.</summary>
@@ -138,6 +148,10 @@ public sealed class ChronosSyncRemote(ChronosClient client, bool ownsClient) : I
public IAsyncEnumerable<ServerEvent> EventsAsync(CancellationToken cancellationToken) => client.EventsAsync(cancellationToken);
public Task<ProjectFramesDto> GetProjectFramesAsync(Guid sequenceId, CancellationToken cancellationToken) => client.GetProjectFramesAsync(sequenceId, cancellationToken);
public Task<string?> GetAnalysisReportAsync(Guid sequenceId, CancellationToken cancellationToken) => client.GetAnalysisReportAsync(sequenceId, cancellationToken);
public void Dispose()
{
if (ownsClient) client.Dispose();
+96 -9
View File
@@ -774,32 +774,54 @@ internal sealed class SyncTransfers(SyncService sync)
var cached = new FileInfo(path) is { Exists: true, Length: > 0 };
if (cached && (cachedKind == ProxyCache.Proxy || !offered.Contains(ProxyCache.Proxy))) return (name, cachedKind ?? ProxyCache.Thumb);
var part = path + ".part";
foreach (var kind in offered)
// The cached file is as good as the server's thumbnail.
var kind = await DownloadFirstAsync(remote, frameId, offered.TakeWhile(k => !(cached && k == ProxyCache.Thumb)), part, null, cancellationToken)
.ConfigureAwait(false);
if (kind is not null)
{
File.Move(part, path, overwrite: true);
return (name, kind);
}
return cached ? (name, ProxyCache.Thumb) : null;
}
/// <summary>
/// Downloads the first of <paramref name="kinds"/> a frame has on the server (a 404 tries the next) into a fresh
/// <paramref name="part"/> file, written through <paramref name="through"/> when given (a hash of what arrives, which
/// leaves the file open) and flushed to the disk when <paramref name="durable"/>; the kind it got, or null when the server
/// has none of them, no part file left then. The proxy cache and the workspace copy of a server project (owner review 2,
/// R8) download alike.
/// </summary>
internal static async Task<string?> DownloadFirstAsync(ISyncRemote remote, Guid frameId, IEnumerable<string> kinds, string part, Func<Stream, Stream>? through,
CancellationToken cancellationToken, bool durable = false)
{
foreach (var kind in kinds)
{
// The cached file is as good as the server's thumbnail.
if (cached && kind == ProxyCache.Thumb) break;
try
{
await using (var file = new FileStream(part, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
await remote.DownloadFrameAsync(frameId, kind, file, cancellationToken).ConfigureAwait(false);
File.Move(part, path, overwrite: true);
return (name, kind);
{
await remote.DownloadFrameAsync(frameId, kind, through?.Invoke(file) ?? file, cancellationToken).ConfigureAwait(false);
if (durable) file.Flush(flushToDisk: true);
}
return kind;
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
File.Delete(part);
}
}
return cached ? (name, ProxyCache.Thumb) : null;
return null;
}
/// <summary>
/// A frame missing or damaged on the server: its manifest never asks for its proxy and a pass makes none of a missing
/// one, so the thumbnail (or the lack of a file) that stands in for it does not keep the cache stale.
/// </summary>
private static bool NeverProxied(FrameDto frame) => ((FrameFlags)frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0;
internal static bool NeverProxied(FrameDto frame) => ((FrameFlags)frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0;
private static string[] Kinds(ManifestFrame frame) => (frame.HasProxy, frame.HasThumb) switch
/// <summary>The kinds of a frame's assets the server offers, the proxy before the thumbnail that stands in while it has none.</summary>
internal static string[] Kinds(ManifestFrame frame) => (frame.HasProxy, frame.HasThumb) switch
{
(true, true) => [ProxyCache.Proxy, ProxyCache.Thumb],
(true, false) => [ProxyCache.Proxy],
@@ -867,3 +889,68 @@ internal sealed class SyncTransfers(SyncService sync)
public ValueTask ReportAsync() => context.ReportAsync(done, total);
}
}
/// <summary>
/// A write-only stream that hashes (SHA-256) what passes through it into <paramref name="inner"/>, which it leaves open: the
/// hash of a download as it arrived, to check the file it was written to against (owner review 2, R8). It cannot seek,
/// so a download through it always starts from the beginning.
/// </summary>
internal sealed class HashingStream(Stream inner) : Stream
{
private readonly System.Security.Cryptography.IncrementalHash _hash = System.Security.Cryptography.IncrementalHash.CreateHash(
System.Security.Cryptography.HashAlgorithmName.SHA256);
private long _written;
/// <summary>The bytes written through.</summary>
public long Written => _written;
/// <summary>The lower-case hex SHA-256 of what was written through (once; it resets the hash).</summary>
public string Sha256() => Convert.ToHexStringLower(_hash.GetHashAndReset());
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => throw new NotSupportedException();
public override long Position
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
public override void Flush() => inner.Flush();
public override Task FlushAsync(CancellationToken cancellationToken) => inner.FlushAsync(cancellationToken);
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => Write(buffer.AsSpan(offset, count));
public override void Write(ReadOnlySpan<byte> buffer)
{
_hash.AppendData(buffer);
_written += buffer.Length;
inner.Write(buffer);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
_hash.AppendData(buffer.Span);
_written += buffer.Length;
return inner.WriteAsync(buffer, cancellationToken);
}
protected override void Dispose(bool disposing)
{
if (disposing) _hash.Dispose();
base.Dispose(disposing);
}
}
@@ -1,4 +1,5 @@
using System.Globalization;
using System.Net;
using System.Security.Cryptography;
using System.Text.Json;
using Chronos.Core.Archiving;
@@ -12,6 +13,9 @@ using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using SequenceManifest = Chronos.Protocol.SequenceManifest;
namespace Chronos.Data.Workspaces;
@@ -31,10 +35,28 @@ public static class WorkspaceJobs
}
/// <summary>
/// The handlers of the workspace's jobs for a desktop's engine (never a server's: the job writes into a folder its
/// parameters name).
/// <see cref="JobKind.WorkspaceCopy"/> of a project whose home is a server (phase 5b): the media of workspace project
/// <paramref name="projectId"/> (checked out first) downloaded from sequence <paramref name="sequenceId"/> of
/// <paramref name="server"/> (<see cref="SyncService.ServerKey"/>), into the workspace alone. The job's target is the
/// server's sequence, as for a sync download.
/// </summary>
public static IReadOnlyList<IJobHandler> CreateHandlers(ChronosDatabase db, ArchiveService archives) => [new WorkspaceCopyJobHandler(db, archives)];
public static ArchiveJobRequest CopyFromServer(Guid sequenceId, string title, string server, string workspaceRoot, Guid projectId, string media = BundleMedia.Proxies)
{
ArgumentException.ThrowIfNullOrWhiteSpace(server);
ArgumentException.ThrowIfNullOrWhiteSpace(workspaceRoot);
return new ArchiveJobRequest(JobKind.WorkspaceCopy, [sequenceId], title,
JsonSerializer.Serialize(new WorkspaceCopyParameters(workspaceRoot, projectId, media, server), WorkspaceJson.Default.WorkspaceCopyParameters), JobPriority.User);
}
/// <summary>
/// The handlers of the workspace's jobs for a desktop's engine (never a server's: the job writes into a folder its
/// parameters name); copies from a server fail without a connection to it.
/// </summary>
public static IReadOnlyList<IJobHandler> CreateHandlers(ChronosDatabase db, ArchiveService archives) => CreateHandlers(db, archives, null);
/// <param name="servers">The connection a copy from a server's sequence downloads through (the desktop's signed-in session).</param>
public static IReadOnlyList<IJobHandler> CreateHandlers(ChronosDatabase db, ArchiveService archives, ISyncConnector? servers) =>
[new WorkspaceCopyJobHandler(db, archives, servers)];
/// <summary>
/// What a first copy of a sequence's proxies writes into a workspace, as the copy reckons it before it starts (the
@@ -70,11 +92,26 @@ public static class WorkspaceJobs
/// project goes on with them (<see cref="RemovePartialMediaAsync"/>); one cancelled while paused or failed, which no handler
/// runs, has them removed the same way (<see cref="CancelledAsync"/>).
/// Originals come in phase 5c: asked for, the job fails saying so.
/// A project whose home is a server (phase 5b, <see cref="WorkspaceJobs.CopyFromServer"/>) has its media downloaded from
/// the server through the desktop's session (<see cref="ISyncConnector"/>), never through this PC's archive: the frames as
/// of one frames version with the aliases of the server's conversions (<c>GET …/projects/frames</c>), each frame's proxy as
/// the proxy cache fetches it (<see cref="SyncTransfers.DownloadFirstAsync"/>: the proxy, else the thumbnail standing in
/// while the server has none, recorded as such and replaced by a later copy once the server has the proxy), hashed as it
/// arrives and checked against the file written, four at a time; then the server's deep report. A file the editor's media
/// or this run hold of the same photo is hashed again and kept; the editor's file is never written over, as above. The
/// space, the passes, the checkpoint and a cancelled first copy go as for a copy from this PC's archive (the server's
/// folder of the sequence in the checkpoint). Like the sync's downloads it is not held on a metered connection.
/// </summary>
internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService archives) : ICancelledJobHandler
internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService archives, ISyncConnector? servers = null) : ICancelledJobHandler
{
private const int PageSize = 1000;
private const int Passes = 3;
/// <summary>Frames downloaded at once from a server (as the sync's downloads).</summary>
private const int Downloads = 4;
/// <summary>Frames downloaded between two looks at the checkpoint clock.</summary>
private const int DownloadBatch = 32;
private static readonly TimeSpan LockWait = TimeSpan.FromMinutes(2);
private static readonly TimeSpan CheckpointEvery = TimeSpan.FromSeconds(5);
@@ -97,6 +134,11 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
var parameters = Parameters(context.Job);
if (parameters.Media == BundleMedia.Originals) throw new NotSupportedException(Loc.L("Errors.Workspace.OriginalsLater"));
if (parameters.Media != BundleMedia.Proxies) throw new InvalidDataException(Loc.L("Errors.Workspace.Parameters"));
if (parameters.Server is { Length: > 0 } server)
{
await RunFromServerAsync(context, parameters, server).ConfigureAwait(false);
return;
}
if (context.Job.TargetIds is not [var sequenceId] || await db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false) is not { } sequence
|| await db.Archives.GetAsync(sequence.ArchiveId, ct).ConfigureAwait(false) is not { } archive)
throw new InvalidOperationException(Loc.L("Archive.Log.SequenceMissing", context.Job.TargetIds.FirstOrDefault()));
@@ -336,7 +378,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
// The working state is the editor's meanwhile: it is held only while the media index and the positions move.
using (await project.LockAsync(LockWait, ct).ConfigureAwait(false))
{
Commit(project, project.ReadBundle(), media, row);
Commit(project, project.ReadBundle(), media, row.Folder, row.DisplayTitle);
RemoveStale(project, media);
}
context.Log(Loc.L("Archive.Log.WorkspaceCopied", row.DisplayTitle, tally.Copied, tally.Made, tally.Kept, tally.Missing));
@@ -345,6 +387,286 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
}
}
/// <summary>
/// The copy of a project whose home is a server (see the class remarks): its frames and their files downloaded into the
/// workspace, then the media index and the working state moved onto them as for a copy from this PC's archive.
/// </summary>
private async Task RunFromServerAsync(JobContext context, WorkspaceCopyParameters parameters, string server)
{
var ct = context.Cancellation;
if (context.Job.TargetIds is not [var sequenceId]) throw new InvalidDataException(Loc.L("Errors.Workspace.Parameters"));
// Asked before the store is opened, which makes its folder (as for a copy from this PC's archive).
if (await InsideALibraryAsync(parameters.WorkspaceRoot, ct).ConfigureAwait(false)) throw new InvalidOperationException(Loc.L("Errors.Workspace.InsideLibrary"));
var store = new WorkspaceStore(parameters.WorkspaceRoot);
var project = store.Find(parameters.ProjectId) ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.NotCheckedOut"));
if (project.ReadBundle().Workspace is not { Home: { Kind: BundleHome.ServerKind } home } || home.SequenceId != sequenceId
|| !string.Equals(home.Server, server, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException(Loc.L("Errors.Workspace.OtherHome"));
try
{
using (WritingMedia(project))
{
using var remote = (servers is null ? null : await servers.ConnectAsync(server, ct).ConfigureAwait(false))
?? throw new InvalidOperationException(Loc.L("Errors.Sync.NotConnected"));
await DownloadAsync(context, project, remote, sequenceId, parameters, ct).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// Stopped writing: what a first copy the user cancelled wrote goes (a pause or a shutdown resumes it).
await RemovePartialMediaAsync(context.Job, project).ConfigureAwait(false);
throw;
}
}
private async Task DownloadAsync(JobContext context, WorkspaceProject project, ISyncRemote remote, Guid sequenceId, WorkspaceCopyParameters parameters,
CancellationToken ct)
{
var (copied, checkpointVersion, checkpointFolder) = Parse(context.Checkpoint);
// What this run downloaded, pass after pass: kept where a frame still shows the same photo.
var fetched = new Dictionary<Guid, WorkspaceFrame>();
for (var pass = 1; ; pass++)
{
var (sequence, frames, assets, aliases, framesVersion, spec) = await ServerFramesAsync(remote, sequenceId, ct).ConfigureAwait(false);
var folder = sequence.Folder ?? string.Empty;
if ((checkpointVersion is { } version && version != framesVersion) || (checkpointFolder is { } read && read != folder)) copied = 0;
var total = (long)frames.Count;
var tally = new Tally();
var entries = new WorkspaceFrame[frames.Count];
// The media the editor reads until this copy commits: their files stay until then (RemoveStale).
var current = TryReadMedia(project)?.Frames.Where(f => f.File is not null).ToDictionary(f => f.Id) ?? [];
Directory.CreateDirectory(project.ProxiesDirectory);
// The workspace is on this PC's own drive: the copy never fills it (the server's files estimated at its proxy size).
var remaining = RemainingDownloads(project, frames, assets, spec);
EnsureSpace(parameters.WorkspaceRoot, remaining[0]);
var clock = System.Diagnostics.Stopwatch.StartNew();
var options = new ParallelOptions { MaxDegreeOfParallelism = Downloads, CancellationToken = ct };
for (var start = 0; start < frames.Count; start += DownloadBatch)
{
var end = Math.Min(frames.Count, start + DownloadBatch);
var done = copied;
await Parallel.ForEachAsync(Enumerable.Range(start, end - start), options, async (i, token) =>
entries[i] = await DownloadAsync(remote, project, frames[i], assets.GetValueOrDefault(frames[i].Id), i < done, current.GetValueOrDefault(frames[i].Id),
fetched.GetValueOrDefault(frames[i].Id), tally, token).ConfigureAwait(false)).ConfigureAwait(false);
if (clock.Elapsed >= CheckpointEvery || end == frames.Count)
{
await context.CheckpointAsync(Checkpoint(Stage.Copy, end, framesVersion, folder), end, total).ConfigureAwait(false);
// Another program may take the space meanwhile.
EnsureSpace(parameters.WorkspaceRoot, remaining[end]);
clock.Restart();
}
else
{
await context.ReportAsync(end, total).ConfigureAwait(false);
}
}
foreach (var entry in entries.Where(e => e.File is not null)) fetched[entry.Id] = entry;
var analysis = await CopyServerAnalysisAsync(remote, sequenceId, project, frames.Count, ct).ConfigureAwait(false);
var after = await remote.GetSequenceAsync(sequenceId, ct).ConfigureAwait(false);
if (after.FramesVersion != framesVersion && pass < Passes)
{
// The files read may be of other frames now: the next pass reads the frames again, keeping what still shows them,
// and so does a run resumed after a crash in it (the checkpoint stored says so).
context.Log(Loc.L("Archive.Log.WorkspaceFramesChanged", sequence.DisplayTitle));
await context.CheckpointAsync(Checkpoint(Stage.Copy, 0, after.FramesVersion, after.Folder ?? string.Empty), 0, total).ConfigureAwait(false);
(copied, checkpointVersion, checkpointFolder) = (0, null, null);
continue;
}
// Frames still arriving are copied as they were read (Update media takes the rest).
var media = new WorkspaceMedia(WorkspaceMedia.FormatName, WorkspaceMedia.CurrentFormatVersion, BundleMedia.Proxies, sequenceId, framesVersion, entries,
DateTimeOffset.UtcNow, analysis, aliases.Count > 0 ? aliases : null);
// The working state is the editor's meanwhile: it is held only while the media index and the positions move.
using (await project.LockAsync(LockWait, ct).ConfigureAwait(false))
{
Commit(project, project.ReadBundle(), media, folder, sequence.DisplayTitle);
RemoveStale(project, media);
}
context.Log(Loc.L("Archive.Log.WorkspaceDownloaded", sequence.DisplayTitle, tally.Copied, tally.Made, tally.Kept, tally.Missing));
await context.CheckpointAsync(Checkpoint(Stage.Done, frames.Count, framesVersion, folder), total, total).ConfigureAwait(false);
return;
}
}
/// <summary>
/// A server sequence's frames in index order as of one frames version, the assets the server holds of each, the links
/// of its conversions, that frames version and the server's proxy size: the frames read twice around the manifest until
/// both are of the same one.
/// </summary>
private static async Task<(SequenceDto Sequence, List<Frame> Frames, Dictionary<Guid, ManifestFrame> Assets, IReadOnlyList<PhotoAlias> Aliases, int FramesVersion,
ProxySpec? Spec)> ServerFramesAsync(ISyncRemote remote, Guid sequenceId, CancellationToken cancellationToken)
{
for (var attempt = 1; ; attempt++)
{
ProjectFramesDto frames;
SequenceManifest manifest;
SequenceDto sequence;
try
{
sequence = await remote.GetSequenceAsync(sequenceId, cancellationToken).ConfigureAwait(false);
frames = await remote.GetProjectFramesAsync(sequenceId, cancellationToken).ConfigureAwait(false);
manifest = await remote.GetManifestAsync(sequenceId, cancellationToken).ConfigureAwait(false);
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
// The sequence is gone, or the server keeps no projects (its API knows no such call).
throw new InvalidOperationException(ex.Error.Details == "sequence" ? Loc.L("Archive.Log.SequenceMissing", sequenceId) : Loc.L("Errors.Workspace.NoProjects"), ex);
}
if (manifest.FramesVersion == frames.FramesVersion || attempt == Passes)
{
var home = ProjectWire.ToHomeFrames(frames);
var aliases = (frames.Aliases ?? []).Where(a => !string.IsNullOrEmpty(a.Sha256) && !string.IsNullOrEmpty(a.Replacement))
.Select(a => new PhotoAlias(a.Sha256, a.Replacement!)).ToList();
return (sequence, [.. home.Frames], manifest.Frames.ToDictionary(f => f.Id), aliases, frames.FramesVersion, manifest.Proxies);
}
}
}
/// <summary>
/// A frame's file from the server: kept when this run downloaded it before it stopped or in an earlier pass, or the
/// editor's media hold one of the same photo that is no thumbnail standing in for a proxy the server has now (hashed
/// again: a file that no longer matches is fetched anew); else its proxy, or the thumbnail while the server has none,
/// hashed as it arrives and checked against the file written (downloaded once more when they differ, then refused);
/// none for a frame without either, or missing or damaged on the server. The editor's file (<paramref name="current"/>)
/// is never written over: other bytes for it go under a name of their own, as for a copy from this PC's archive.
/// </summary>
private static async Task<WorkspaceFrame> DownloadAsync(ISyncRemote remote, WorkspaceProject project, Frame frame, ManifestFrame? asset, bool done,
WorkspaceFrame? current, WorkspaceFrame? fetched, Tally tally, CancellationToken cancellationToken)
{
var name = WorkspaceProject.ProxyName(frame.Id);
var target = project.MediaFile(name);
var listed = current is not null && string.Equals(current.File, name, StringComparison.OrdinalIgnoreCase);
IReadOnlyList<string> offered = asset is null || (frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0 ? [] : SyncTransfers.Kinds(asset);
if (done && File.Exists(target))
{
var keptSha = await ContentHash.Sha256Async(target, cancellationToken: cancellationToken).ConfigureAwait(false);
// The editor's file of another photo of the frame (a conversion since) was left by an earlier copy, not this run.
if (!listed || keptSha != current!.FileSha256 || SamePhoto(current, frame))
{
tally.Keep();
return WorkspaceFrame.Of(frame, name, keptSha, new FileInfo(target).Length,
KindOf(fetched, keptSha) ?? KindOf(current, keptSha) ?? offered.FirstOrDefault() ?? ProxyCache.Proxy);
}
}
// What this run downloaded in an earlier pass, then the editor's file of the same photo, unless a thumbnail stands in
// there for a proxy the server has now.
foreach (var held in new[] { fetched, current })
{
if (held is not { File: { } file, FileSha256: { } heldSha } || !SamePhoto(held, frame) || (held.IsStandIn && offered.Contains(ProxyCache.Proxy))) continue;
var path = project.MediaFile(file);
if (!File.Exists(path)
|| !string.Equals(await ContentHash.Sha256Async(path, cancellationToken: cancellationToken).ConfigureAwait(false), heldSha, StringComparison.OrdinalIgnoreCase))
continue;
tally.Keep();
return WorkspaceFrame.Of(frame, file, heldSha.ToLowerInvariant(), new FileInfo(path).Length, held.FileKind ?? ProxyCache.Proxy);
}
if (offered.Count == 0)
{
// A file an earlier copy left for the frame is never kept as its photo: a regenerable copy, it goes, unless the
// editor's media name it (it goes once this copy commits).
if (!listed && File.Exists(target)) TryDelete(target);
tally.Miss();
return WorkspaceFrame.Of(frame, null, null, 0);
}
var part = target + ".part";
for (var attempt = 1; ; attempt++)
{
HashingStream? hashing = null;
string? kind;
string received;
long bytes;
try
{
kind = await SyncTransfers.DownloadFirstAsync(remote, frame.Id, offered, part, file =>
{
hashing?.Dispose();
return hashing = new HashingStream(file);
}, cancellationToken, durable: true).ConfigureAwait(false);
(received, bytes) = hashing is null ? (string.Empty, 0L) : (hashing.Sha256(), hashing.Written);
}
finally
{
hashing?.Dispose();
}
if (kind is null || bytes == 0)
{
if (File.Exists(part)) File.Delete(part);
if (!listed && File.Exists(target)) TryDelete(target);
tally.Miss();
return WorkspaceFrame.Of(frame, null, null, 0);
}
// Other bytes for the file the editor's media name: under a name of their own, never over the editor's file.
var (file, path) = (name, target);
if (listed && current!.FileSha256 is { } editors && !string.Equals(editors, received, StringComparison.OrdinalIgnoreCase)
&& Holds(target, editors.ToLowerInvariant()))
{
file = WorkspaceProject.ProxyName(frame.Id, received);
path = project.MediaFile(file);
}
File.Move(part, path, overwrite: true);
if (await ContentHash.Sha256Async(path, cancellationToken: cancellationToken).ConfigureAwait(false) == received)
{
if (kind == ProxyCache.Proxy) tally.Copy();
else tally.Make();
return WorkspaceFrame.Of(frame, file, received, bytes, kind);
}
if (attempt == 2) throw new IOException(Loc.L("Errors.Workspace.CopyMismatch", path));
}
static string? KindOf(WorkspaceFrame? entry, string sha) =>
entry is { FileSha256: { } held } && string.Equals(held, sha, StringComparison.OrdinalIgnoreCase) ? entry.FileKind ?? ProxyCache.Proxy : null;
}
/// <summary>
/// The bytes a copy from a server still writes from each frame on (index <c>i</c>: frames <c>i</c> to the last; one more
/// entry, 0): nothing for a frame the workspace holds a file of already or the server has neither proxy nor thumbnail of,
/// else an estimate at the server's proxy size (its manifest gives no file's size).
/// </summary>
private static long[] RemainingDownloads(WorkspaceProject project, List<Frame> frames, Dictionary<Guid, ManifestFrame> assets, ProxySpec? spec)
{
var held = Directory.Exists(project.ProxiesDirectory) ? HeldFrames(Directory.EnumerateFiles(project.ProxiesDirectory, "*.jpg")) : [];
var policy = spec is null ? new ProxyPolicy() : new ProxyPolicy { LongEdge = spec.LongEdge, Quality = spec.Quality };
var remaining = new long[frames.Count + 1];
for (var i = frames.Count - 1; i >= 0; i--)
{
var frame = frames[i];
var bytes = held.Contains(frame.Id) || assets.GetValueOrDefault(frame.Id) is not { } asset || SyncTransfers.Kinds(asset).Length == 0 ? 0 : Estimate(frame, policy);
remaining[i] = remaining[i + 1] + bytes;
}
return remaining;
}
/// <summary>The server's deep report into the media folder when it describes these frames; its SHA-256, or null without one.</summary>
private static async Task<string?> CopyServerAnalysisAsync(ISyncRemote remote, Guid sequenceId, WorkspaceProject project, int frameCount,
CancellationToken cancellationToken)
{
string? json;
try
{
json = await remote.GetAnalysisReportAsync(sequenceId, cancellationToken).ConfigureAwait(false);
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
json = null;
}
try
{
if (json is null || Core.Analysis.Deep.DeepAnalysisReport.FromJson(json).FrameCount != frameCount)
{
if (File.Exists(project.AnalysisPath)) File.Delete(project.AnalysisPath);
return null;
}
}
catch (Exception ex) when (ex is InvalidDataException or JsonException)
{
Log.Warning("workspace", $"The deep report of server sequence {sequenceId} cannot be read; the workspace takes none", ex);
return null;
}
var bytes = System.Text.Encoding.UTF8.GetBytes(json);
var sha = Sha(bytes);
WriteVerified(project.AnalysisPath, bytes, sha);
return sha;
}
/// <summary>Whether <paramref name="folder"/> is an archive's root of this index or lies inside one.</summary>
private async Task<bool> InsideALibraryAsync(string folder, CancellationToken cancellationToken)
{
@@ -397,7 +719,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
// The editor's file of another photo of the frame (a conversion since) was left by an earlier copy, not this run.
if (!listed || keptSha != current!.FileSha256 || SamePhoto(current, frame))
{
tally.Kept++;
tally.Keep();
return WorkspaceFrame.Of(frame, name, keptSha, kept.Length);
}
}
@@ -424,7 +746,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
// A file an earlier copy left for the frame (of other frames, or another folder's) is never kept as its photo by a
// resumed run: a regenerable copy, it goes, unless the editor's media name it (it goes once this copy commits).
if (!listed && File.Exists(target)) TryDelete(target);
tally.Missing++;
tally.Miss();
return WorkspaceFrame.Of(frame, null, null, 0);
}
var sha = Sha(bytes);
@@ -432,12 +754,12 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
if (current?.File is { } held && !string.Equals(held, name, StringComparison.OrdinalIgnoreCase)
&& string.Equals(current.FileSha256, sha, StringComparison.OrdinalIgnoreCase) && Holds(project.MediaFile(held), sha))
{
tally.Kept++;
tally.Keep();
return WorkspaceFrame.Of(frame, held, sha, bytes.Length);
}
if (Holds(target, sha))
{
tally.Kept++;
tally.Keep();
return WorkspaceFrame.Of(frame, name, sha, bytes.Length);
}
// Other bytes for the file the editor's media name (a conversion since): written under a name of their own, never over
@@ -450,13 +772,13 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
target = project.MediaFile(name);
if (Holds(target, sha))
{
tally.Kept++;
tally.Keep();
return WorkspaceFrame.Of(frame, name, sha, bytes.Length);
}
}
WriteVerified(target, bytes, sha);
if (made) tally.Made++;
else tally.Copied++;
if (made) tally.Make();
else tally.Copy();
return WorkspaceFrame.Of(frame, name, sha, bytes.Length);
}
@@ -504,11 +826,11 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
/// as the photo they hold for it, so one whose file a conversion replaced (the same frame, another SHA-256) keeps its
/// positions, as the archive's own settings do (<see cref="ProjectPositions"/>).
/// </summary>
private static void Commit(WorkspaceProject project, ProjectBundle bundle, WorkspaceMedia media, Sequence row)
private static void Commit(WorkspaceProject project, ProjectBundle bundle, WorkspaceMedia media, string folder, string title)
{
var old = TryReadMedia(project);
var workspace = bundle.Workspace! with { Media = new BundleMedia(BundleMedia.Proxies, media.FramesVersion) };
var sequence = bundle.Sequence with { Folder = row.Folder, Title = row.DisplayTitle, Frames = media.Frames.Count };
var sequence = bundle.Sequence with { Folder = folder, Title = title, Frames = media.Frames.Count };
var working = bundle.Project;
// Without the media index the positions were made against, they are taken as naming these frames.
if (!working.IsNewerFormat && old is not null)
@@ -534,11 +856,14 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
held.Size == frame.Size && held.CapturedAt == frame.CapturedAt
&& (string.IsNullOrEmpty(held.Sha256) || string.IsNullOrEmpty(frame.Sha256) || string.Equals(held.Sha256, frame.Sha256, StringComparison.OrdinalIgnoreCase));
/// <summary>Proxies of frames the sequence no longer has: regenerable copies, removed so the media folder holds the frames listed.</summary>
/// <summary>
/// Proxies of frames the sequence no longer has, and downloads a stopped copy from a server left half done: regenerable
/// copies, removed so the media folder holds the frames listed.
/// </summary>
private static void RemoveStale(WorkspaceProject project, WorkspaceMedia media)
{
var listed = media.Frames.Where(f => f.File is not null).Select(f => Path.GetFileName(f.File!)).ToHashSet(StringComparer.OrdinalIgnoreCase);
foreach (var file in Directory.EnumerateFiles(project.ProxiesDirectory, "*.jpg"))
foreach (var file in Directory.EnumerateFiles(project.ProxiesDirectory, "*.jpg").Concat(Directory.EnumerateFiles(project.ProxiesDirectory, "*.part")))
{
if (!listed.Contains(Path.GetFileName(file))) TryDelete(file);
}
@@ -718,11 +1043,30 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
return (next, version, parts.Length == 4 ? parts[3] : null);
}
/// <summary>What a copy did with each frame, counted from the workers that download them at once.</summary>
private sealed class Tally
{
public int Copied { get; set; }
public int Made { get; set; }
public int Kept { get; set; }
public int Missing { get; set; }
private int _copied;
private int _made;
private int _kept;
private int _missing;
/// <summary>Proxies copied (from the archive) or downloaded (from a server).</summary>
public int Copied => Volatile.Read(ref _copied);
/// <summary>Proxies made from the originals (from the archive), or thumbnails standing in for them (from a server).</summary>
public int Made => Volatile.Read(ref _made);
public int Kept => Volatile.Read(ref _kept);
public int Missing => Volatile.Read(ref _missing);
public void Copy() => Interlocked.Increment(ref _copied);
public void Make() => Interlocked.Increment(ref _made);
public void Keep() => Interlocked.Increment(ref _kept);
public void Miss() => Interlocked.Increment(ref _missing);
}
}
+13 -4
View File
@@ -13,6 +13,10 @@ namespace Chronos.Data.Workspaces;
/// editor read) and the file the workspace holds for it, with its SHA-256 and size as copied.
/// </summary>
/// <param name="File">The file relative to the media folder ("proxies/&lt;frame id&gt;.jpg"); null when the workspace holds none.</param>
/// <param name="FileKind">
/// What the file is when a server sent it (phase 5b): <c>proxy</c>, or <c>thumb</c>, a thumbnail standing in while the server
/// had no proxy of the frame, which a later copy replaces once it has one; null for a proxy (copies from this PC's archive).
/// </param>
public sealed record WorkspaceFrame(
Guid Id,
int Index,
@@ -41,18 +45,23 @@ public sealed record WorkspaceFrame(
FrameFlags Flags,
string? File,
string? FileSha256,
long FileBytes)
long FileBytes,
string? FileKind = null)
{
/// <summary>The record of a home's frame, with the file the workspace holds for it.</summary>
public static WorkspaceFrame Of(Frame frame, string? file, string? fileSha256, long fileBytes)
/// <summary>The record of a home's frame, with the file the workspace holds for it (<paramref name="fileKind"/>: what a server sent).</summary>
public static WorkspaceFrame Of(Frame frame, string? file, string? fileSha256, long fileBytes, string? fileKind = null)
{
ArgumentNullException.ThrowIfNull(frame);
return new WorkspaceFrame(frame.Id, frame.Index, frame.FileName, frame.OriginalFileName, frame.Size, frame.Sha256, frame.CapturedAt, frame.UtcOffsetMinutes,
frame.TimestampSource, frame.ExposureTime, frame.FNumber, frame.Iso, frame.FocalLength, frame.ExposureBias, frame.WhiteBalance, frame.Orientation,
frame.Width, frame.Height, frame.Format, frame.PreviewWidth, frame.PreviewHeight, frame.MeanLogLuminance, frame.ClipLow, frame.ClipHigh, frame.Flags,
file, fileSha256, fileBytes);
file, fileSha256, fileBytes, fileKind);
}
/// <summary>A thumbnail stands in for the frame's proxy (a server had none when it was copied).</summary>
[JsonIgnore]
public bool IsStandIn => FileKind == Sync.ProxyCache.Thumb;
/// <summary>The frame as the processing engine reads it; flagged missing while the workspace holds no file for it.</summary>
public Frame ToFrame(Guid sequenceId) => new()
{
@@ -93,7 +93,8 @@ public sealed record WorkspaceConflict(Guid TheirsVersionId, int TheirsNumber, G
/// Parameters of a <see cref="JobKind.WorkspaceCopy"/> job: target = the home's sequence; the workspace folder, the
/// project whose media to copy and what to copy (<see cref="BundleMedia.Proxies"/>; originals in phase 5c).
/// </summary>
public sealed record WorkspaceCopyParameters(string WorkspaceRoot, Guid ProjectId, string Media);
/// <param name="Server">The server the home's sequence is on (<see cref="SyncService.ServerKey"/>, phase 5b); null for a sequence of this PC's archive.</param>
public sealed record WorkspaceCopyParameters(string WorkspaceRoot, Guid ProjectId, string Media, string? Server = null);
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
UseStringEnumConverter = true, WriteIndented = true)]
+2 -1
View File
@@ -50,10 +50,11 @@ public enum WorkspaceState
/// <summary>
/// A workspace project's state (owner review 2, R8): the leading <see cref="State"/> and every fact behind it. Without a
/// home to ask, <see cref="Behind"/> is 0 and <see cref="Offline"/> false.
/// home to ask, <see cref="Behind"/> is 0 and <see cref="Offline"/> and <see cref="Gone"/> false.
/// </summary>
/// <param name="Base">The home's version the project was last in step with.</param>
/// <param name="HomeHead">The home's newest version, when it was asked.</param>
/// <param name="Gone">The home was asked and no longer has the project (<see cref="WorkspaceState.Gone"/>).</param>
public sealed record WorkspaceStatus(WorkspaceState State, bool Modified, int Ahead, int Behind, bool Offline, bool MediaRemoved, bool ReadOnly,
WorkspaceConflict? Conflict, BundleBase? Base, ProjectVersion? HomeHead)
{
+1 -1
View File
@@ -532,7 +532,7 @@ public sealed class ChronosClient : IDisposable
/// Pushes <paramref name="version"/>, made in a workspace from the project's head (<see cref="ProjectVersionDto.ParentId"/>):
/// the server stores it as the new head, numbered head + 1 (201, <c>stored</c>), or answers it again for a repeated push
/// (200, <c>already_stored</c>), or refuses it, storing nothing: 409 <c>diverged</c> with the head, 422
/// <c>hash_mismatch</c>, <c>newer_format</c> or <c>invalid</c>. These come back as <see cref="ProjectPushResultDto"/>
/// <c>hash_mismatch</c>, <c>newer_format</c>, <c>too_large</c> or <c>invalid</c>. These come back as <see cref="ProjectPushResultDto"/>
/// without throwing; any other failure (the sequence or project gone, no permission, the archive offline or the sequence
/// busy: 503) throws <see cref="ChronosApiException"/>. Safe to repeat: the version's id makes a second push a no-op.
/// </summary>
@@ -48,8 +48,10 @@ public sealed class SyncTextTests
{
Assert.SequenceEqual([SyncAction.Upload], SyncText.Actions(Entry(SyncStatus.LocalOnly, link: null), Editor));
Assert.Empty(SyncText.Actions(Entry(SyncStatus.LocalOnly, link: null), Viewer));
Assert.SequenceEqual([SyncAction.OpenWithProxies, SyncAction.DownloadOriginals], SyncText.Actions(Entry(SyncStatus.RemoteOnly, local: null), Editor));
Assert.SequenceEqual([SyncAction.OpenWithProxies], SyncText.Actions(Entry(SyncStatus.ProxiesOnly, local: null), Viewer));
// A server that keeps no projects opens its sequences with proxies; the workspace is offered disabled (owner review 2, R8).
Assert.SequenceEqual([SyncAction.OpenWithProxies, SyncAction.DownloadOriginals, SyncAction.OpenInWorkspace],
SyncText.Actions(Entry(SyncStatus.RemoteOnly, local: null), Editor));
Assert.SequenceEqual([SyncAction.OpenWithProxies, SyncAction.OpenInWorkspace], SyncText.Actions(Entry(SyncStatus.ProxiesOnly, local: null), Viewer));
Assert.SequenceEqual([SyncAction.Upload], SyncText.Actions(Entry(SyncStatus.LocalAhead, Link with { MissingRemote = 4 }), Editor));
Assert.SequenceEqual([SyncAction.DownloadOriginals], SyncText.Actions(Entry(SyncStatus.ServerAhead, Link with { MissingLocal = 2 }), Editor));
Assert.SequenceEqual([SyncAction.SyncSettings], SyncText.Actions(Entry(SyncStatus.ServerAhead), Editor));
@@ -74,6 +76,37 @@ public sealed class SyncTextTests
Assert.SequenceEqual([SyncAction.Resume], SyncText.Actions(Entry(SyncStatus.Transferring, transfer: Upload(JobState.Paused)), Editor));
}
[Test]
public async Task AServerThatKeepsProjectsOpensItsSequencesInTheWorkspace()
{
// Owner review 2, R8, phase 5b: the workspace replaces Open with proxies, and the originals can still come down.
var projects = Editor with { KeepsProjects = true };
Assert.SequenceEqual([SyncAction.OpenInWorkspace, SyncAction.DownloadOriginals], SyncText.Actions(Entry(SyncStatus.RemoteOnly, local: null), projects));
Assert.SequenceEqual([SyncAction.OpenInWorkspace], SyncText.Actions(Entry(SyncStatus.ProxiesOnly, local: null), Viewer with { KeepsProjects = true }));
Assert.True(SyncText.IsEnabled(SyncAction.OpenInWorkspace, projects), "a server that keeps projects opens them");
Assert.Equal(Loc.L("Tooltips.Server.Sync.OpenInWorkspace"), SyncText.ToolTip(Entry(SyncStatus.RemoteOnly, local: null), SyncAction.OpenInWorkspace, projects));
// An older server's row says why its workspace action is disabled; the other actions are not.
Assert.False(SyncText.IsEnabled(SyncAction.OpenInWorkspace, Editor), "an older server keeps no projects");
Assert.True(SyncText.IsEnabled(SyncAction.OpenWithProxies, Editor), "proxies open as before");
Assert.Equal(Loc.L("Tooltips.Server.Sync.OpenInWorkspace.NoProjects"), SyncText.ToolTip(Entry(SyncStatus.RemoteOnly, local: null), SyncAction.OpenInWorkspace, Editor));
// The row's button is disabled with its reason, and enabled once the server keeps projects.
var acted = new List<SyncAction>();
var row = new SyncRow(Entry(SyncStatus.RemoteOnly, local: null), Editor, (_, action) =>
{
acted.Add(action);
return Task.CompletedTask;
});
var workspace = row.Actions.Single(a => a.Action == SyncAction.OpenInWorkspace);
Assert.Equal((false, Loc.L("Tooltips.Server.Sync.OpenInWorkspace.NoProjects")), (workspace.Command.CanExecute(null), workspace.ToolTip));
row.Update(Entry(SyncStatus.RemoteOnly, local: null), projects);
workspace = row.Actions.First();
Assert.Equal((SyncAction.OpenInWorkspace, true), (workspace.Action, workspace.Command.CanExecute(null)));
workspace.Command.Execute(null);
await Task.Yield();
Assert.SequenceEqual([SyncAction.OpenInWorkspace], acted);
}
[Test]
public void ColumnsSayWhatEachSideHolds()
{
@@ -0,0 +1,302 @@
using System.Globalization;
using System.Text.Json;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Workspace;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Windows.Shell;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
using Chronos.Testing;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// Workspace projects whose home is a server (owner review 2, R8, phase 5b), as the desktop handles them: the home asked
/// through the signed-in session (offline without it), the copy downloaded from the server, the states the server's
/// changes and deletions lead to, its texts, and renders of what the server holds only. The server here is this PC's
/// archive seen through a home that names a server, so its versions, pushes and merges are the engine's own.
/// </summary>
[Category("workspace")]
public sealed class ServerHomeTests(TestContext context)
{
private const string Server = "https://nas.test:8443";
static ServerHomeTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public async Task TheServerIsTheHomeWhileThisPcIsSignedInToIt()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host();
var named = ServerHome(bed);
Assert.Null(host.HomeOf(named), "no session: the server cannot be asked");
await Assert.ThrowsAsync<HomeUnavailableException>(() => host.HomeProjectsAsync(named, bed.Ct));
Assert.Equal(Loc.L("Errors.Workspace.Offline.Server"), WorkspaceText.Failure(new HomeUnavailableException("down"), server: true));
var server = new FakeServer(bed);
Connect(host, server);
Assert.Same(server, host.HomeOf(named));
Assert.Null(host.HomeOf(named with { Server = "https://elsewhere:8443" }), "another server than the session's");
Assert.Equal("Main", (await host.HomeProjectsAsync(named, bed.Ct)).Single().Name);
// Checked out from the server: its media are downloaded by a copy job that names the server, never this PC's archive.
var checkout = await host.CheckoutAsync(named, null, null, cancellationToken: bed.Ct);
var bundle = host.Store.Find(checkout.Project.Id)!.ReadBundle();
Assert.Equal((BundleHome.ServerKind, Server, bed.SequenceId), (bundle.Workspace!.Home.Kind, bundle.Workspace.Home.Server, bundle.Workspace.Home.SequenceId));
using (var parameters = JsonDocument.Parse(checkout.Copy.ParametersJson!))
{
var root = parameters.RootElement;
Assert.Equal((Server, checkout.Project.Id.ToString(), BundleMedia.Proxies),
(root.GetProperty("server").GetString(), root.GetProperty("projectId").GetString(), root.GetProperty("media").GetString()));
}
Assert.SequenceEqual([bed.SequenceId], checkout.Copy.TargetIds);
// This test bed's engine has no session to download through: the job says to connect.
var failed = await bed.WaitForJobAsync(checkout.Copy.Id, JobState.Failed);
Assert.Equal(Loc.L("Errors.Sync.NotConnected"), failed.Error);
var entry = Assert.NotNull(await host.FindAsync(checkout.Project.Id));
Assert.True(entry.IsServerHome && !entry.HasMedia, "listed as the server's, without media yet");
}
[Test]
public async Task AServerProjectsStateFollowsWhatTheServerSays()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var server = new FakeServer(bed);
Connect(host, server);
var projectId = await CheckoutAsync(bed, host);
var status = await host.StatusAsync(projectId, cancellationToken: bed.Ct);
Assert.Equal(WorkspaceState.InSync, status.State);
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.State.InSync.Server"), WorkspaceText.StateToolTip(status, server: true));
// Another PC sends a version: this one reads as Server newer.
var other = bed.Host(name: "other-pc");
var otherId = await bed.CheckoutAsync(other);
Assert.Equal(projectId, otherId);
var session = await other.Sync.OpenAsync(projectId, bed.Ct);
await other.Sync.SaveAsync(projectId, session.Working with { HeroFrame = 2 }, bed.Ct);
await other.SaveVersionAsync(projectId, null, bed.Ct);
status = await host.StatusAsync(projectId, cancellationToken: bed.Ct);
Assert.Equal((WorkspaceState.Behind, 1), (status.State, status.Behind));
Assert.Equal(Loc.L("Editor.Workspace.State.Behind.Server"), WorkspaceText.State(status, server: true));
Assert.Equal(Loc.L("Editor.Workspace.State.Behind"), WorkspaceText.State(status));
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.State.Behind.Server", "1"), WorkspaceText.StateToolTip(status, server: true));
// Signed out, or the server out of reach: offline, its work kept.
server.Reachable = false;
Assert.Equal(WorkspaceState.Offline, (await host.StatusAsync(projectId, cancellationToken: bed.Ct)).State);
server.Reachable = true;
host.ServerHomes = null;
status = await host.StatusAsync(projectId, cancellationToken: bed.Ct);
Assert.Equal((WorkspaceState.Offline, true), (status.State, status.Offline));
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.State.Offline.Server"), WorkspaceText.StateToolTip(status, server: true));
Connect(host, server);
// Deleted on the server (its head answers 404 project): not on the server, with its copy kept here as it was.
server.Deleted.Add(projectId);
status = await host.StatusAsync(projectId, cancellationToken: bed.Ct);
Assert.Equal((WorkspaceState.Gone, 0), (status.State, status.Behind));
Assert.Equal(Loc.L("Editor.Workspace.State.Gone.Server"), WorkspaceText.State(status, server: true));
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.State.Gone.Server"), WorkspaceText.StateToolTip(status, server: true));
Assert.Equal(StatusKind.Warning, WorkspaceText.Kind(status));
Assert.NotNull(host.Store.Find(projectId)?.ReadMedia());
// A server that answers 404 for the project itself (deleted with its sequence) is gone too.
server.Deleted.Clear();
server.Missing = true;
Assert.Equal(WorkspaceState.Gone, (await host.StatusAsync(projectId, cancellationToken: bed.Ct)).State);
}
[Test]
public void TheServersProjectChangesReachOnlyTheProjectsItIsHomeOf()
{
var local = context.CreateTempDirectory("local");
var environment = AppEnvironment.From(AppPaths.Resolve(context.CreateTempDirectory("app"), local, []));
var host = new WorkspaceHost(environment, new AppSettings(), () => { }, () => null, () => null, () => null);
var told = new List<WorkspaceHomeChange>();
host.HomeChanged += told.Add;
// Missed changes (the event stream came back) are told for every project of that server.
host.OnServerProjectChanged(Server, null);
Assert.Equal(new WorkspaceHomeChange(Server, null, null), told.Single());
// A project this workspace does not hold is not told (and the workspace without an index holds none).
host.OnServerProjectChanged(Server, new ProjectChangedEvent(Guid.CreateVersion7(), Guid.CreateVersion7(), ProjectChanges.Pushed, 2, Guid.CreateVersion7()));
Assert.Count(1, told);
}
[Test]
public async Task TheEditorFollowsTheServerAndRendersOnlyWhatItHolds()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var server = new FakeServer(bed);
Connect(host, server);
var projectId = await CheckoutAsync(bed, host);
var told = new List<WorkspaceHomeChange>();
host.HomeChanged += told.Add;
var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine, new WorkspaceServerHome(null));
var content = await source.LoadAsync(bed.Ct);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
var ui = new RecordingUi();
await using (session)
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
{
await menu.RefreshAsync();
Assert.True(source.IsServerHome && source.IsRemote && menu.IsServerHome, "analyses and renders run on the server");
Assert.Equal(Loc.L("Errors.Workspace.MainKept"), menu.DeleteToolTip);
Assert.Equal(Loc.L("Tooltips.Editor.Project.Rename.Server"), menu.RenameToolTip);
Assert.Equal(Loc.L("Tooltips.Editor.Project.RemoveCopy.Server"), menu.RemoveCopyToolTip);
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.UpdateMedia.Server"), menu.UpdateMediaToolTip);
// Not signed in to the server: the project opens, its jobs are refused saying so.
Assert.Empty(await source.ListJobsAsync(bed.Ct));
var refused = await Assert.ThrowsAsync<EditorException>(() => source.SubmitAsync(session.RenderRequests(session.Project.Export)[0], bed.Ct));
Assert.Equal(Loc.L("Editor.Error.SignedOut"), refused.Message);
// In step with the server: the render names the version it holds, whose settings the server renders.
Assert.True(await menu.ReadyToRenderAsync(), "nothing to send");
Assert.Empty(ui.Confirmations);
var basis = host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!;
var (held, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal<(Guid?, Guid?, string?)>((projectId, basis.VersionId, null), (held.ProjectId, held.ProjectVersionId, held.SettingsJson));
// A change not sent: the render of the working state names the project alone, and is offered to be sent first.
Assert.True(session.SetHero(3));
Assert.True(await session.FlushAsync());
var (unsent, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal<(Guid?, Guid?)>((projectId, null), (unsent.ProjectId, unsent.ProjectVersionId));
Assert.NotNull(unsent.SettingsJson);
ui.ConfirmAnswer = false;
Assert.False(await menu.ReadyToRenderAsync(), "kept here: nothing renders");
Assert.Equal(Loc.L("Editor.Workspace.SendFirst.Title"), ui.Confirmations.Single().Heading);
Assert.Equal(WorkspaceState.Modified, menu.Status!.State);
ui.ConfirmAnswer = true;
Assert.True(await menu.ReadyToRenderAsync(), "saved and sent: the server holds it");
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
var sent = host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!;
Assert.NotEqual(basis.VersionId, sent.VersionId);
var (version, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal<(Guid?, string?)>((sent.VersionId, null), (version.ProjectVersionId, version.SettingsJson));
Assert.Equal(3, ProjectSettings.FromJson(Assert.NotNull((await bed.RowAsync()).SettingsJson)).HeroFrame, "the server holds the version");
// The server out of reach: the render waits, said in a toast.
server.Reachable = false;
Assert.True(session.SetHero(1));
Assert.True(await session.FlushAsync());
Assert.False(await menu.ReadyToRenderAsync());
Assert.Equal(Loc.L("Editor.Workspace.RenderHeld"), ui.Toasts[^1].Title);
Assert.False(ui.Toasts[^1].IsError, "out of reach is no error");
server.Reachable = true;
await menu.SaveVersionAsync(null);
await menu.SyncAsync();
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
// Another PC sends a version and the server says so: the chip reads Server newer at once.
var other = bed.Host(name: "other-pc");
await bed.CheckoutAsync(other);
var theirs = await other.Sync.OpenAsync(projectId, bed.Ct);
await other.Sync.SaveAsync(projectId, theirs.Working with { Exposure = theirs.Working.Exposure with { ExposureOffsetEv = 0.7 } }, bed.Ct);
var stored = (await other.SaveVersionAsync(projectId, null, bed.Ct)).Version!;
host.OnServerProjectChanged(Server, new ProjectChangedEvent(bed.SequenceId, projectId, ProjectChanges.Pushed, stored.Number, stored.Id));
Assert.Equal(projectId, told.Single().ProjectId);
await WorkspaceTestBed.UntilAsync(() => menu.Status?.State == WorkspaceState.Behind, "the chip follows the server's change");
Assert.Equal(Loc.L("Editor.Workspace.State.Behind.Server"), menu.StateText);
// A change of another server, or of a project this workspace does not hold, is not told.
host.OnServerProjectChanged("https://elsewhere:8443", new ProjectChangedEvent(bed.SequenceId, projectId, ProjectChanges.Pushed, 9, Guid.CreateVersion7()));
host.OnServerProjectChanged(Server, new ProjectChangedEvent(Guid.CreateVersion7(), projectId, ProjectChanges.Pushed, 9, Guid.CreateVersion7()));
Assert.Count(1, told);
await menu.SyncAsync();
Assert.Equal(0.7, session.Project.Exposure.ExposureOffsetEv);
// Deleted on the server: the chip says so, the copy and the editor stay.
server.Deleted.Add(projectId);
host.OnServerProjectChanged(Server, new ProjectChangedEvent(bed.SequenceId, projectId, ProjectChanges.Deleted, stored.Number, stored.Id));
await WorkspaceTestBed.UntilAsync(() => menu.Status?.State == WorkspaceState.Gone, "the chip says the project is gone");
Assert.Equal(Loc.L("Editor.Workspace.State.Gone.Server"), menu.StateText);
Assert.False(await menu.ReadyToRenderAsync(), "nothing to render it from");
Assert.True(ui.Toasts[^1].IsError);
Assert.NotNull(host.Store.Find(projectId)?.ReadMedia());
}
}
/// <summary>The home a workspace project of the test sequence names on <see cref="Server"/>.</summary>
private static BundleHome ServerHome(WorkspaceTestBed bed) => new(BundleHome.ServerKind, bed.SequenceId, null, Server);
/// <summary>The host signed in to <paramref name="server"/>, as the desktop's SyncHost gives it.</summary>
private static void Connect(WorkspaceHost host, FakeServer server) =>
host.ServerHomes = home => string.Equals(home.Server, Server, StringComparison.OrdinalIgnoreCase) && home.SequenceId == server.Inner.SequenceId ? server : null;
/// <summary>
/// Main checked out with its media copied from the archive, then named the server's: as a copy downloaded from the
/// server leaves it (that download is the server tests' own).
/// </summary>
private static async Task<Guid> CheckoutAsync(WorkspaceTestBed bed, WorkspaceHost host)
{
var projectId = await bed.CheckoutAsync(host);
var folder = host.Store.Find(projectId)!;
var bundle = folder.ReadBundle();
folder.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Home = ServerHome(bed) } });
return projectId;
}
/// <summary>A server that keeps the archive's projects: reachable or not, with projects deleted there, or none of the sequence's.</summary>
private sealed class FakeServer(WorkspaceTestBed bed) : IProjectHome
{
public ArchiveProjectHome Inner { get; } = new(bed.Db, bed.Archives.Projects, bed.SequenceId);
public bool Reachable { get; set; } = true;
/// <summary>The server answers 404 for the sequence's projects (deleted with their sequence).</summary>
public bool Missing { get; set; }
public HashSet<Guid> Deleted { get; } = [];
public async Task<HomeSequence> SequenceAsync(CancellationToken cancellationToken)
{
var sequence = await Reach(() => Inner.SequenceAsync(cancellationToken));
return sequence with { Home = ServerHome(bed), Archive = sequence.Archive with { Id = ServerProjectHome.ArchiveIdOf(Server), Path = null } };
}
public Task<IReadOnlyList<SequenceProject>> ListAsync(CancellationToken cancellationToken) => Reach(() => Inner.ListAsync(cancellationToken));
public Task<SequenceProject> CreateAsync(string name, Guid? fromVersionId, string? author, CancellationToken cancellationToken) =>
Reach(() => Inner.CreateAsync(name, fromVersionId, author, cancellationToken));
/// <remarks>A project deleted there has no head (404 <c>project</c>), as the server answers.</remarks>
public Task<ProjectVersion> HeadAsync(Guid projectId, CancellationToken cancellationToken) =>
Deleted.Contains(projectId)
? throw new ProjectException(ProjectError.NotFound, "deleted on the server")
: Reach(() => Inner.HeadAsync(projectId, cancellationToken));
public Task<ProjectVersion?> GetVersionAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken) =>
Reach(() => Inner.GetVersionAsync(projectId, versionId, cancellationToken));
public Task<IReadOnlyList<ProjectVersion>> VersionsAfterAsync(Guid projectId, int afterNumber, int limit, CancellationToken cancellationToken) =>
Reach(() => Inner.VersionsAfterAsync(projectId, afterNumber, limit, cancellationToken));
public Task<IReadOnlyList<ProjectVersion>> HistoryAsync(Guid projectId, int? beforeNumber, int limit, CancellationToken cancellationToken) =>
Reach(() => Inner.HistoryAsync(projectId, beforeNumber, limit, cancellationToken));
public Task<PushResult> PushAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken) =>
Deleted.Contains(projectId)
? throw new ProjectException(ProjectError.NotFound, "deleted on the server")
: Reach(() => Inner.PushAsync(projectId, version, cancellationToken));
public Task<HomeFrames> FramesAsync(CancellationToken cancellationToken) => Reach(() => Inner.FramesAsync(cancellationToken));
private Task<T> Reach<T>(Func<Task<T>> call)
{
if (!Reachable) throw new HomeUnavailableException("The server cannot be reached.");
if (Missing) throw new ProjectException(ProjectError.NotFound, "not on the server");
return call();
}
}
}
@@ -0,0 +1,231 @@
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using Chronos.Testing;
namespace Chronos.Data.Tests.Projects;
/// <summary>
/// A server as the home of workspace projects (owner review 2, R8, phase 5b): the calls <see cref="ServerProjectHome"/> makes
/// and how it reads the server's answers, a server out of reach, an expired sign-in, a busy sequence or a server without
/// projects being a home out of reach, and its refusals the archive's own.
/// </summary>
[Category("workspace")]
public sealed class ServerProjectHomeTests(TestContext context)
{
private static readonly Uri Address = new("https://nas.local:8443/");
private static readonly Guid SequenceId = Guid.CreateVersion7();
private static readonly Guid ProjectId = Guid.CreateVersion7();
[Test]
public async Task ItAsksTheServersProjectsAndReadsThemAsTheArchiveGivesThem()
{
var head = Version(3);
var handler = new FakeHandler(request => (request.Method.Method, request.RequestUri!.PathAndQuery) switch
{
("GET", var path) when path == $"/api/v1/sequences/{SequenceId}" => Json(Sequence()),
("GET", var path) when path == $"/api/v1/sequences/{SequenceId}/projects" => Json(new List<ProjectDto> { Project() }),
("POST", var path) when path == $"/api/v1/sequences/{SequenceId}/projects" => Json(Project() with { Name = "Vertical", IsMain = false }, HttpStatusCode.Created),
("GET", var path) when path == $"/api/v1/sequences/{SequenceId}/projects/{ProjectId}/head" => Json(head),
("GET", var path) when path.StartsWith($"/api/v1/sequences/{SequenceId}/projects/{ProjectId}/versions?", StringComparison.Ordinal) =>
Json(new ProjectVersionPageDto([Version(2), Version(1)], 3, false)),
("GET", var path) when path == $"/api/v1/sequences/{SequenceId}/projects/{ProjectId}/versions/{head.Id}" => Json(head),
("GET", var path) when path.StartsWith($"/api/v1/sequences/{SequenceId}/projects/{ProjectId}/versions/", StringComparison.Ordinal) =>
Error(HttpStatusCode.NotFound, "not_found", "version"),
("PATCH", var path) when path == $"/api/v1/sequences/{SequenceId}/projects/{ProjectId}" => Json(Project() with { Name = "Main renamed" }),
("GET", var path) when path == $"/api/v1/sequences/{SequenceId}/projects/{ProjectId}" => Json(Project()),
("DELETE", _) => new HttpResponseMessage(HttpStatusCode.NoContent),
_ => Error(HttpStatusCode.NotFound, "not_found", null),
});
using var client = Client(handler);
var home = new ServerProjectHome(client, SequenceId, "Studio NAS");
// The sequence as a workspace's project file names it: the server's key (as sync links name it) and its name.
var sequence = await home.SequenceAsync(context.Cancellation);
Assert.Equal((BundleHome.ServerKind, SequenceId, (Guid?)null, "https://nas.local:8443"), (sequence.Home.Kind, sequence.Home.SequenceId, sequence.Home.ArchiveId, sequence.Home.Server));
Assert.Equal(("Studio NAS", "Harbour sunset", "2026/harbour", 3), (sequence.Archive.Name, sequence.Sequence.Title, sequence.Sequence.Folder, sequence.Sequence.Frames));
// A project file names an archive: the server's sequences carry one made from its key, the same each time.
Assert.Equal(ServerProjectHome.ArchiveIdOf("https://nas.local:8443"), sequence.Archive.Id);
Assert.NotEqual(Guid.Empty, sequence.Archive.Id);
Assert.NotEqual(ServerProjectHome.ArchiveIdOf("https://other:8443"), sequence.Archive.Id);
var main = (await home.ListAsync(context.Cancellation)).Single();
Assert.Equal((ProjectId, true, "Main", 3), (main.Id, main.IsMain, main.Name, main.HeadNumber));
Assert.Equal("Vertical", (await home.CreateAsync("Vertical", head.Id, "ignored", context.Cancellation)).Name);
var read = await home.HeadAsync(ProjectId, context.Cancellation);
Assert.Equal((head.Id, 3, ProjectVersionKind.Commit, head.ContentHash), (read.Id, read.Number, read.Kind, read.ContentHash));
Assert.SequenceEqual([2, 1], (await home.HistoryAsync(ProjectId, 3, 500, context.Cancellation)).Select(v => v.Number));
Assert.SequenceEqual([2, 1], (await home.VersionsAfterAsync(ProjectId, 0, 100, context.Cancellation)).Select(v => v.Number));
Assert.Equal(head.Id, (await home.GetVersionAsync(ProjectId, head.Id, context.Cancellation))?.Id);
// A version the server does not have is none, as on this PC's archive.
Assert.Null(await home.GetVersionAsync(ProjectId, Guid.CreateVersion7(), context.Cancellation));
Assert.Equal("Main renamed", (await home.RenameAsync(ProjectId, "Main renamed", context.Cancellation)).Name);
await home.DeleteAsync(ProjectId, context.Cancellation);
// Pages are asked within the server's 1–200, oldest first above a number or newest first below one.
Assert.Contains(handler.Requests, r => r.EndsWith("/versions?before=3&limit=200", StringComparison.Ordinal));
Assert.Contains(handler.Requests, r => r.EndsWith("/versions?after=0&limit=100", StringComparison.Ordinal));
// The server makes the project from that version, its maker the account: no author travels.
Assert.Equal($"{{\"name\":\"Vertical\",\"fromVersionId\":\"{head.Id}\"}}", handler.Bodies.Single(b => b.Contains("Vertical", StringComparison.Ordinal)));
}
[Test]
public async Task APushAnswersItsOutcomeAsTheArchiveDoes()
{
var head = Version(4);
var outcomes = new Queue<HttpResponseMessage>(
[
Json(new ProjectPushResultDto(ProjectPushOutcomes.Stored, Version(5), Version(5)), HttpStatusCode.Created),
Json(new ProjectPushResultDto(ProjectPushOutcomes.AlreadyStored, Version(5), Version(5))),
Json(new ProjectPushResultDto(ProjectPushOutcomes.Diverged, null, head, ProjectErrors.Diverged, "moved"), HttpStatusCode.Conflict),
Json(new ProjectPushResultDto(ProjectPushOutcomes.HashMismatch, null, head, ProjectErrors.HashMismatch, "damaged"), HttpStatusCode.UnprocessableEntity),
Json(new ProjectPushResultDto("from_a_newer_server", null, head, "something", "new"), HttpStatusCode.UnprocessableEntity),
]);
using var client = Client(new FakeHandler(_ => outcomes.Dequeue()));
var home = new ServerProjectHome(client, SequenceId);
var local = ProjectWire.ToVersion(Version(5) with { StoredAt = null });
Assert.Equal((PushOutcome.Stored, 5), Outcome(await home.PushAsync(ProjectId, local, context.Cancellation)));
Assert.Equal((PushOutcome.AlreadyStored, 5), Outcome(await home.PushAsync(ProjectId, local, context.Cancellation)));
var diverged = await home.PushAsync(ProjectId, local, context.Cancellation);
Assert.Equal((PushOutcome.Diverged, (ProjectVersion?)null, (Guid?)head.Id), (diverged.Outcome, diverged.Version, diverged.Head?.Id));
Assert.Equal(PushOutcome.HashMismatch, (await home.PushAsync(ProjectId, local, context.Cancellation)).Outcome);
// An outcome this build does not know is a refusal, never a stored version.
Assert.Equal(PushOutcome.Invalid, (await home.PushAsync(ProjectId, local, context.Cancellation)).Outcome);
static (PushOutcome, int?) Outcome(PushResult result) => (result.Outcome, result.Version?.Number);
}
[Test]
public async Task AServerOutOfReachBusyOrSignedOutIsAHomeOutOfReach()
{
foreach (var (what, answer) in new (string, Func<HttpResponseMessage>)[]
{
("no answer", () => throw new HttpRequestException("refused")),
("the sign-in expired", () => Error(HttpStatusCode.Unauthorized, "unauthorized", null)),
("the sequence busy", () => Error(HttpStatusCode.ServiceUnavailable, "sequence_busy", null)),
("the archive offline", () => Error(HttpStatusCode.ServiceUnavailable, "archive_offline", null)),
("a gateway", () => new HttpResponseMessage(HttpStatusCode.BadGateway) { Content = new StringContent("<html>502</html>") }),
("a project file in use", () => Error(HttpStatusCode.Conflict, "folder_in_use", null)),
("a server without projects", () => Error(HttpStatusCode.NotFound, "not_found", null)),
("an answer that is not the API's", () => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("<html>portal</html>", Encoding.UTF8, "text/html") }),
})
{
using var client = Client(new FakeHandler(_ => answer()));
var home = new ServerProjectHome(client, SequenceId);
var unavailable = await Assert.ThrowsAsync<HomeUnavailableException>(() => home.HeadAsync(ProjectId, context.Cancellation));
Assert.True(unavailable.InnerException is not null, what);
await Assert.ThrowsAsync<HomeUnavailableException>(() => home.ListAsync(context.Cancellation));
await Assert.ThrowsAsync<HomeUnavailableException>(() => home.PushAsync(ProjectId, ProjectWire.ToVersion(Version(2)), context.Cancellation));
}
// A client disposed meanwhile (the session ended) is a server out of reach too.
var gone = Client(new FakeHandler(_ => Json(Version(1))));
gone.Dispose();
await Assert.ThrowsAsync<HomeUnavailableException>(() => new ServerProjectHome(gone, SequenceId).HeadAsync(ProjectId, context.Cancellation));
// The caller's own cancellation stays a cancellation.
using var cancelled = new CancellationTokenSource();
await cancelled.CancelAsync();
using var slow = Client(new FakeHandler(_ => Json(Version(1))));
await Assert.ThrowsAsync<OperationCanceledException>(() => new ServerProjectHome(slow, SequenceId).HeadAsync(ProjectId, cancelled.Token));
}
[Test]
public async Task RefusalsReadAsTheArchivesAndTheOthersKeepTheirMeaning()
{
async Task<ProjectException> RefusedAsync(HttpResponseMessage answer, Func<ServerProjectHome, Task> call)
{
using var client = Client(new FakeHandler(_ => answer));
return await Assert.ThrowsAsync<ProjectException>(() => call(new ServerProjectHome(client, SequenceId)));
}
Assert.Equal(ProjectError.SequenceNotFound, (await RefusedAsync(Error(HttpStatusCode.NotFound, "not_found", "sequence"), h => h.ListAsync(default))).Reason);
Assert.Equal(ProjectError.NotFound, (await RefusedAsync(Error(HttpStatusCode.NotFound, "not_found", "project"), h => h.HeadAsync(ProjectId, default))).Reason);
Assert.Equal(ProjectError.NotFound, (await RefusedAsync(Error(HttpStatusCode.NotFound, "not_found", "version"), h => h.CreateAsync("Copy", Guid.CreateVersion7(), null, default))).Reason);
Assert.Equal(ProjectError.InvalidName, (await RefusedAsync(Error(HttpStatusCode.BadRequest, ProjectErrors.InvalidName, null), h => h.CreateAsync(" ", null, null, default))).Reason);
Assert.Equal(ProjectError.NameTaken, (await RefusedAsync(Error(HttpStatusCode.Conflict, ProjectErrors.NameTaken, null), h => h.RenameAsync(ProjectId, "Main", default))).Reason);
Assert.Equal(ProjectError.MainCannotBeDeleted,
(await RefusedAsync(Error(HttpStatusCode.Conflict, ProjectErrors.MainCannotBeDeleted, null), h => h.DeleteAsync(ProjectId, default))).Reason);
// An account that may not change projects there: the server's own refusal, not a home out of reach.
using var viewer = Client(new FakeHandler(_ => Error(HttpStatusCode.Forbidden, "forbidden", null)));
var forbidden = await Assert.ThrowsAsync<ChronosApiException>(() => new ServerProjectHome(viewer, SequenceId).CreateAsync("Mine", null, null, default));
Assert.Equal(HttpStatusCode.Forbidden, forbidden.Status);
}
[Test]
public async Task AWorkspaceOfAServerOutOfReachIsOfflineAndItsWorkWaits()
{
var head = Version(1);
var reachable = true;
var handler = new FakeHandler(request =>
{
if (!reachable) throw new HttpRequestException("refused");
var path = request.RequestUri!.AbsolutePath;
if (path == $"/api/v1/sequences/{SequenceId}") return Json(Sequence());
if (path.EndsWith("/projects", StringComparison.Ordinal)) return Json(new List<ProjectDto> { Project() with { HeadNumber = 1, HeadVersionId = head.Id } });
if (path.EndsWith("/head", StringComparison.Ordinal)) return Json(head);
return Json(Project() with { HeadNumber = 1, HeadVersionId = head.Id });
});
using var client = Client(handler);
var home = new ServerProjectHome(client, SequenceId);
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("ws"), "workspace"));
var sync = new WorkspaceSync(store, "Chronos on PC-A");
var project = await sync.CheckoutAsync(home, ProjectId, cancellationToken: context.Cancellation);
Assert.Equal((BundleHome.ServerKind, "https://nas.local:8443"), (project.ReadBundle().Workspace!.Home.Kind, project.ReadBundle().Workspace!.Home.Server));
// No media yet (the copy job brings them): its settings name no frame, so a version can still be saved.
await sync.SaveAsync(ProjectId, new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = 0.4 } }, context.Cancellation);
Assert.NotNull(await sync.CommitAsync(ProjectId, "warmer", cancellationToken: context.Cancellation));
reachable = false;
var status = await sync.StatusAsync(ProjectId, home, context.Cancellation);
Assert.Equal((WorkspaceState.MediaRemoved, true, 1), (status.State, status.Offline, status.Ahead));
await Assert.ThrowsAsync<HomeUnavailableException>(() => sync.PushAsync(ProjectId, home, context.Cancellation));
// Nothing was lost: the version still waits here.
Assert.Equal(1, sync.Unpushed(ProjectId).Count);
}
private static ChronosClient Client(HttpMessageHandler handler) => new(Address, new CertificatePinning([]), "tests", handler) { Token = "token" };
private static SequenceDto Sequence() => new(SequenceId, "Harbour sunset", "Harbour sunset", "2026/harbour", "Canon", "Canon EOS R5", null, null, null, 3, 60, 0,
0, 0, null, [], 0, null, 2, 1, 0, null, DateTimeOffset.UtcNow);
private static ProjectDto Project() => new(ProjectId, SequenceId, "Main", true, Guid.CreateVersion7(), 3, null, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow, "commit",
"alberto", "Chronos on PC-A", DateTimeOffset.UtcNow);
private static ProjectVersionDto Version(int number)
{
var portable = ProjectContent.ToPortable(new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = number / 10.0 } }, new FramePhotos([]));
return new ProjectVersionDto(Guid.CreateVersion7(), ProjectId, null, number, "commit", "alberto", "Chronos on PC-A", null, portable, ProjectContent.Hash(portable),
ProjectContent.FormatOf(portable), 1, null, DateTimeOffset.UtcNow, DateTimeOffset.UtcNow);
}
private static HttpResponseMessage Json<T>(T body, HttpStatusCode status = HttpStatusCode.OK) =>
new(status) { Content = JsonContent.Create(body, (System.Text.Json.Serialization.Metadata.JsonTypeInfo<T>)ProtocolJson.Default.GetTypeInfo(typeof(T))!) };
private static HttpResponseMessage Error(HttpStatusCode status, string code, string? details) => Json(new ApiError(code, "refused", details), status);
/// <summary>The server as the test answers it, with the requests it was sent.</summary>
private sealed class FakeHandler(Func<HttpRequestMessage, HttpResponseMessage> answer) : HttpMessageHandler
{
public List<string> Requests { get; } = [];
public List<string> Bodies { get; } = [];
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
Requests.Add(request.Method.Method + " " + request.RequestUri!.PathAndQuery);
if (request.Content is not null) Bodies.Add(await request.Content.ReadAsStringAsync(cancellationToken));
return answer(request);
}
}
}
@@ -27,6 +27,9 @@ internal sealed class FakeSyncRemote : ISyncRemote
/// <summary>Listings still to fail with a network error.</summary>
public int FailingListings { get; set; }
/// <summary>Event streams still to be lost right after they opened.</summary>
public int FailingEvents { get; set; }
/// <summary>The next original download of this frame returns damaged bytes.</summary>
public Guid? CorruptOnce { get; set; }
@@ -251,6 +254,14 @@ internal sealed class FakeSyncRemote : ISyncRemote
public async IAsyncEnumerable<ServerEvent> EventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
lock (_gate)
{
if (FailingEvents > 0)
{
FailingEvents--;
throw new HttpRequestException("socket closed");
}
}
while (await _events.Reader.WaitToReadAsync(cancellationToken))
{
while (_events.Reader.TryRead(out var e)) yield return e;
@@ -51,6 +51,35 @@ public sealed class SyncAgentTests(TestContext context)
Assert.Same(first, agent.Snapshot);
}
[Test]
public async Task ProjectChangesAreToldAndALostStreamSaysSomeWereMissed()
{
// Owner review 2, R8, phase 5b: the server's projectChanged reaches the workspace through the agent.
await using var f = await SyncFixture.CreateAsync(context);
f.Remote.Add("Harbour", f.NewPhotos(1));
f.Remote.FailingEvents = 1;
var told = new List<ProjectChangedEvent?>();
var missed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var changed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(), null, EventsOnly);
agent.ProjectChanged += e =>
{
lock (told) told.Add(e);
(e is null ? missed : changed).TrySetResult();
// What a listener throws never ends the event loop.
throw new InvalidOperationException("a listener that fails");
};
agent.Start();
// The stream was lost once: the comparison after it says changes may have been missed.
await SignalAsync(missed.Task, "the missed changes told");
var change = new ProjectChangedEvent(Guid.CreateVersion7(), Guid.CreateVersion7(), ProjectChanges.Pushed, 3, Guid.CreateVersion7());
f.Remote.Publish(change);
await SignalAsync(changed.Task, "the project change told");
lock (told) Assert.Equal(change, told.Single(e => e is not null));
Assert.Equal(1, agent.Snapshot!.ServerSequences);
}
[Test]
public async Task FailedComparisonsAreRetriedWithBackoff()
{
@@ -0,0 +1,450 @@
using System.Security.Cryptography;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
using Chronos.Protocol.Client;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests.Workspaces;
/// <summary>
/// A server as the home of desktop workspaces (owner review 2, R8, phase 5b), end to end through the protocol client:
/// two workspaces of two accounts on one server project (checkout, the copy of its media, commit, push, the other's
/// fast-forward pull, replays and merges, a real conflict settled by keep mine, take server and save both, restore), the
/// copy job resuming after an interruption and keeping what it holds, and a server out of reach.
/// </summary>
[Category("server")]
[Category("workspace")]
public sealed class ServerWorkspaceTests(TestContext context)
{
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(TestTiming.Budget(60));
[Test]
public async Task TwoWorkspacesShareAProjectOfTheServerLikeGit()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (_, _, albertoToken) = await server.UserAsync("alberto", "editor");
var (_, _, giuliaToken) = await server.UserAsync("giulia", "editor");
var sid = await SequenceAsync(server, albertoToken, 3);
await using var a = await WorkspaceClient.StartAsync(context, server, albertoToken, "PC-A");
await using var b = await WorkspaceClient.StartAsync(context, server, giuliaToken, "PC-B");
var homeA = a.Home(sid);
var homeB = b.Home(sid);
var main = (await homeA.ListAsync(context.Cancellation)).Single(p => p.IsMain);
// Each workspace takes the server's Main and downloads its media.
await a.CheckoutAsync(homeA, main.Id);
await b.CheckoutAsync(homeB, main.Id);
Assert.Equal((BundleHome.ServerKind, a.Server, sid), (a.Bundle(main.Id).Workspace!.Home.Kind, a.Bundle(main.Id).Workspace!.Home.Server, a.Bundle(main.Id).Workspace!.Home.SequenceId));
Assert.Equal(WorkspaceState.InSync, (await a.Sync.StatusAsync(main.Id, homeA, context.Cancellation)).State);
// A saves a version and sends it: a fast-forward, numbered and signed by the server.
await a.EditAsync(main.Id, s => s with { Exposure = s.Exposure with { ExposureOffsetEv = 0.3 } });
Assert.NotNull(await a.Sync.CommitAsync(main.Id, "warmer", cancellationToken: context.Cancellation));
var pushed = await a.Sync.PushAsync(main.Id, homeA, context.Cancellation);
var v2 = pushed.Pushed.Single();
Assert.Equal((2, "alberto", "warmer", WorkspaceState.InSync), (v2.Number, v2.Author, v2.Note, pushed.Status.State));
// B is behind and takes it.
Assert.Equal((WorkspaceState.Behind, 1), ((await b.Sync.StatusAsync(main.Id, homeB, context.Cancellation)).State, (await b.Sync.StatusAsync(main.Id, homeB, context.Cancellation)).Behind));
var pulled = await b.Sync.PullAsync(main.Id, homeB, context.Cancellation);
Assert.Equal((v2.Id, WorkspaceState.InSync), (pulled.Pulled.Single().Id, pulled.Status.State));
Assert.Equal(0.3, (await b.Sync.OpenAsync(main.Id, context.Cancellation)).Working.Exposure.ExposureOffsetEv);
// Both change different settings: B's push meets A's, replays on it and merges, no question asked.
await a.EditAsync(main.Id, s => s with { ExcludedFrames = [1] });
await a.CommitAndPushAsync(homeA, main.Id);
await b.EditAsync(main.Id, s => s with { HeroFrame = 2 });
Assert.NotNull(await b.Sync.CommitAsync(main.Id, cancellationToken: context.Cancellation));
var replayed = await b.Sync.PushAsync(main.Id, homeB, context.Cancellation);
Assert.Equal((1, 1, WorkspaceState.InSync), (replayed.Pulled.Count, replayed.Pushed.Count, replayed.Status.State));
var both = await a.PlacedHeadAsync(homeA, main.Id);
Assert.SequenceEqual([1], both.ExcludedFrames);
Assert.Equal((2, 0.3), (both.HeroFrame, both.Exposure.ExposureOffsetEv));
await a.Sync.PullAsync(main.Id, homeA, context.Cancellation);
Assert.Equal(2, (await a.Sync.OpenAsync(main.Id, context.Cancellation)).Working.HeroFrame);
// The same setting changed on both sides: a real conflict, settled by keeping mine.
Assert.Equal(0.9, (await ConflictAsync(a, b, homeA, homeB, main.Id, 0.5, 0.9, ConflictChoice.KeepMine)).Exposure.ExposureOffsetEv);
// Taking the server's.
Assert.Equal(0.1, (await ConflictAsync(a, b, homeA, homeB, main.Id, 0.1, 0.2, ConflictChoice.TakeServer)).Exposure.ExposureOffsetEv);
// Saving both: B's versions go to a new project of the server, its Main takes A's.
var savedBoth = await ConflictAsync(a, b, homeA, homeB, main.Id, 0.6, 0.7, ConflictChoice.SaveBoth, "Main (PC-B)");
Assert.Equal(0.6, savedBoth.Exposure.ExposureOffsetEv);
var sibling = Assert.NotNull((await homeA.ListAsync(context.Cancellation)).SingleOrDefault(p => p.Name == "Main (PC-B)"));
Assert.Equal(0.7, (await a.PlacedHeadAsync(homeA, sibling.Id)).Exposure.ExposureOffsetEv);
Assert.Equal("giulia", sibling.CreatedBy);
// A restores the first version it sent: the next version says so, and the server keeps it as a restore.
await a.Sync.PullAsync(main.Id, homeA, context.Cancellation);
var restored = await a.Sync.RestoreAsync(main.Id, v2.Id, homeA, context.Cancellation);
Assert.Equal(0.3, restored.Exposure.ExposureOffsetEv);
var restore = Assert.NotNull(await a.Sync.CommitAsync(main.Id, cancellationToken: context.Cancellation));
Assert.Equal((ProjectVersionKind.Restore, (Guid?)v2.Id), (restore.Kind, restore.RestoredFrom));
await a.Sync.PushAsync(main.Id, homeA, context.Cancellation);
var head = await homeB.HeadAsync(main.Id, context.Cancellation);
Assert.Equal((ProjectVersionKind.Restore, (Guid?)v2.Id, "alberto"), (head.Kind, head.RestoredFrom, head.Author));
// Main's head is the sequence's own settings, for older clients and the panel.
var sequence = ProjectSettings.FromJson(Assert.NotNull((await server.Database.Sequences.GetAsync(sid))!.SettingsJson));
Assert.Equal(0.3, sequence.Exposure.ExposureOffsetEv);
}
/// <summary>
/// A and B change one setting from the same version, A first: B's push stops at a conflict, which B settles as
/// <paramref name="choice"/>; returns Main's head at the server as placed on its frames.
/// </summary>
private async Task<ProjectSettings> ConflictAsync(WorkspaceClient a, WorkspaceClient b, ServerProjectHome homeA, ServerProjectHome homeB, Guid projectId,
double theirs, double mine, ConflictChoice choice, string? saveBothName = null)
{
await a.Sync.PullAsync(projectId, homeA, context.Cancellation);
await b.Sync.PullAsync(projectId, homeB, context.Cancellation);
await a.EditAsync(projectId, s => s with { Exposure = s.Exposure with { ExposureOffsetEv = theirs } });
await a.CommitAndPushAsync(homeA, projectId);
await b.EditAsync(projectId, s => s with { Exposure = s.Exposure with { ExposureOffsetEv = mine } });
Assert.NotNull(await b.Sync.CommitAsync(projectId, cancellationToken: context.Cancellation));
var met = await b.Sync.PushAsync(projectId, homeB, context.Cancellation);
var conflict = Assert.NotNull(met.Status.Conflict, "both changed the exposure offset");
Assert.Equal(WorkspaceState.Conflict, met.Status.State);
Assert.Contains(conflict.Differences, d => d.Path.StartsWith("exposure.exposureOffsetEv", StringComparison.Ordinal));
var settled = await b.Sync.ResolveAsync(projectId, homeB, choice, saveBothName: saveBothName, cancellationToken: context.Cancellation);
Assert.Null(settled.Status.Conflict);
if (choice == ConflictChoice.SaveBoth) Assert.Equal(saveBothName, settled.SavedAs?.Name);
var sent = await b.Sync.PushAsync(projectId, homeB, context.Cancellation);
Assert.Equal(WorkspaceState.InSync, sent.Status.State, $"after {choice}");
return await b.PlacedHeadAsync(homeB, projectId);
}
[Test]
public async Task TheCopyDownloadsVerifiedProxiesResumesAndKeepsWhatItHolds()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (_, _, token) = await server.UserAsync("alberto", "editor");
var sid = await SequenceAsync(server, token, 4);
await using var a = await WorkspaceClient.StartAsync(context, server, token, "PC-A");
var home = a.Home(sid);
var main = (await home.ListAsync(context.Cancellation)).Single();
var project = await a.Sync.CheckoutAsync(home, main.Id, cancellationToken: context.Cancellation);
Assert.Equal(WorkspaceState.MediaRemoved, (await a.Sync.StatusAsync(main.Id, home, context.Cancellation)).State);
var library = Listing(a.Archive.RootPath);
// The frames as the server holds them, each file hashed as it arrived and checked on the disk; this PC's library never written.
var job = await a.CopyAsync(sid, main.Id);
var media = Assert.NotNull(project.ReadMedia());
var manifest = await a.Client.GetManifestAsync(sid, context.Cancellation);
Assert.Equal((BundleMedia.Proxies, sid, manifest.FramesVersion, 4), (media.Kind, media.SequenceId, media.FramesVersion, media.Frames.Count));
foreach (var (frame, entry) in manifest.Frames.OrderBy(f => f.Index).Zip(media.Frames))
{
Assert.Equal((frame.Id, frame.Sha256), (entry.Id, entry.Sha256));
Assert.Equal(entry.FileSha256, Sha(project.MediaFile(Assert.NotNull(entry.File))));
Assert.Equal(frame.HasProxy ? "proxy" : "thumb", entry.FileKind);
}
var downloaded = media.Frames.Count(f => f.FileKind == "proxy");
Assert.Contains(Loc.L("Archive.Log.WorkspaceDownloaded", Title, downloaded, 4 - downloaded, 0, 0), job.LogTail!);
Assert.SequenceEqual(library, Listing(a.Archive.RootPath), "this PC's library is as it was");
var session = await a.Sync.OpenAsync(main.Id, context.Cancellation);
Assert.Equal(4, Assert.NotNull(session.Sequence).Files.Count(f => f is not null));
// A run stopped after two frames, a later file left damaged and the media index gone: the two are kept as they are,
// the others downloaded again.
File.WriteAllText(project.MediaFile(media.Frames[3].File!), "not a photo");
File.Delete(project.MediaIndexPath);
job = await a.CopyAsync(sid, main.Id, $"copy:2:{manifest.FramesVersion}");
Assert.Contains(Loc.L("Archive.Log.WorkspaceDownloaded", Title, Downloaded(media, 2..), media.Frames.Count - 2 - Downloaded(media, 2..), 2, 0), job.LogTail!);
var again = Assert.NotNull(project.ReadMedia());
Assert.SequenceEqual(media.Frames.Select(f => f.FileSha256), again.Frames.Select(f => f.FileSha256));
// Update media while nothing changed keeps every file it holds of the same photo, hashed again; one damaged since is fetched anew.
job = await a.CopyAsync(sid, main.Id);
Assert.Contains(Loc.L("Archive.Log.WorkspaceDownloaded", Title, 0, 0, 4, 0), job.LogTail!);
File.WriteAllText(project.MediaFile(media.Frames[0].File!), "damaged");
job = await a.CopyAsync(sid, main.Id);
Assert.Contains(Loc.L("Archive.Log.WorkspaceDownloaded", Title, Downloaded(media, ..1), 1 - Downloaded(media, ..1), 3, 0), job.LogTail!);
Assert.Equal(media.Frames[0].FileSha256, Sha(project.MediaFile(media.Frames[0].File!)));
// Positions follow their photos when the server's frames change and the copy runs again.
await a.EditAsync(main.Id, s => s with { ExcludedFrames = [2] });
var uploader = server.NewClient(token);
await Uploads.UploadAsync(uploader, Photo(99), "IMG_0000.JPG", sid, capturedAt: new DateTime(2026, 9, 28, 17, 59, 11));
await JobsDoneAsync(server);
await a.CopyAsync(sid, main.Id);
var moved = await a.Sync.OpenAsync(main.Id, context.Cancellation);
Assert.Equal(5, moved.Media!.Frames.Count);
Assert.SequenceEqual([3], moved.Working.ExcludedFrames);
Assert.Equal(media.Frames[2].Id, moved.Media.Frames[3].Id);
static int Downloaded(WorkspaceMedia media, Range frames) => media.Frames.Take(frames).Count(f => f.FileKind == "proxy");
}
[Test]
public async Task ACopyIsRefusedForAnotherHomeOrWithoutTheServer()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (_, _, token) = await server.UserAsync("alberto", "editor");
var sid = await SequenceAsync(server, token, 1);
await using var a = await WorkspaceClient.StartAsync(context, server, token, "PC-A");
var main = (await a.Home(sid).ListAsync(context.Cancellation)).Single();
await a.Sync.CheckoutAsync(a.Home(sid), main.Id, cancellationToken: context.Cancellation);
// Another server's job for this project, or this server's for another sequence: refused, nothing downloaded.
var other = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, "https://elsewhere:8443", a.Store.Root, main.Id));
Assert.Equal(Loc.L("Errors.Workspace.OtherHome"), (await a.WaitAsync(other.Id, JobState.Failed)).Error);
var originals = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, a.Server, a.Store.Root, main.Id, BundleMedia.Originals));
Assert.Equal(Loc.L("Errors.Workspace.OriginalsLater"), (await a.WaitAsync(originals.Id, JobState.Failed)).Error);
a.Connected = false;
var signedOut = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, a.Server, a.Store.Root, main.Id));
Assert.Equal(Loc.L("Errors.Sync.NotConnected"), (await a.WaitAsync(signedOut.Id, JobState.Failed)).Error);
Assert.Null(a.Store.Find(main.Id)!.ReadMedia());
}
[Test]
public async Task AProjectDeletedOnTheServerIsGoneAndItsCopyStays()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (_, _, token) = await server.UserAsync("alberto", "editor");
var sid = await SequenceAsync(server, token, 2);
await using var a = await WorkspaceClient.StartAsync(context, server, token, "PC-A");
var home = a.Home(sid);
var vertical = await home.CreateAsync("Vertical", null, null, context.Cancellation);
Assert.Equal("alberto", vertical.CreatedBy);
await a.CheckoutAsync(home, vertical.Id);
await a.EditAsync(vertical.Id, s => s with { HeroFrame = 1 });
Assert.NotNull(await a.Sync.CommitAsync(vertical.Id, cancellationToken: context.Cancellation));
// Deleted on the server (by its maker, from another program): the copy here reads as gone, with its unsent version.
using (var deleted = await server.NewClient(token).DeleteAsync($"/api/v1/sequences/{sid}/projects/{vertical.Id}"))
Assert.Equal(System.Net.HttpStatusCode.NoContent, deleted.StatusCode);
// The server has no head for it any more (404 project): the copy here reads as gone, never as in step.
Assert.Equal(ProjectError.NotFound, (await Assert.ThrowsAsync<ProjectException>(() => home.HeadAsync(vertical.Id, context.Cancellation))).Reason);
var status = await a.Sync.StatusAsync(vertical.Id, home, context.Cancellation);
Assert.Equal((WorkspaceState.Gone, 0, 1), (status.State, status.Behind, status.Ahead));
// A push sends nothing to it: the copy keeps reading as gone, its version kept here.
var pushed = await a.Sync.PushAsync(vertical.Id, home, context.Cancellation);
Assert.Equal((WorkspaceState.Gone, 0), (pushed.Status.State, pushed.Pushed.Count));
Assert.Equal(1, a.Sync.Unpushed(vertical.Id).Count);
Assert.Equal(1, (await a.Sync.OpenAsync(vertical.Id, context.Cancellation)).Working.HeroFrame);
// Its versions stay readable on the server, as in its project trash.
Assert.SequenceEqual([1], (await home.HistoryAsync(vertical.Id, null, 10, context.Cancellation)).Select(v => v.Number));
}
[Test]
public async Task AServerOutOfReachLeavesTheProjectOfflineAndItsWorkWaits()
{
var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var running = true;
WorkspaceClient? a = null;
try
{
var (_, _, token) = await server.UserAsync("alberto", "editor");
var sid = await SequenceAsync(server, token, 2);
a = await WorkspaceClient.StartAsync(context, server, token, "PC-A");
var home = a.Home(sid);
var main = (await home.ListAsync(context.Cancellation)).Single();
await a.CheckoutAsync(home, main.Id);
await a.EditAsync(main.Id, s => s with { HeroFrame = 1 });
Assert.NotNull(await a.Sync.CommitAsync(main.Id, cancellationToken: context.Cancellation));
running = false;
await server.DisposeAsync();
var status = await a.Sync.StatusAsync(main.Id, home, context.Cancellation);
Assert.Equal((WorkspaceState.Offline, true, 1), (status.State, status.Offline, status.Ahead));
await Assert.ThrowsAsync<HomeUnavailableException>(() => a.Sync.PushAsync(main.Id, home, context.Cancellation));
await Assert.ThrowsAsync<HomeUnavailableException>(() => a.Sync.PullAsync(main.Id, home, context.Cancellation));
// Nothing was lost: the version still waits, and the project still opens from the workspace.
Assert.Equal(1, a.Sync.Unpushed(main.Id).Count);
Assert.Equal(1, (await a.Sync.OpenAsync(main.Id, context.Cancellation)).Working.HeroFrame);
}
finally
{
if (a is not null) await a.DisposeAsync();
if (running) await server.DisposeAsync();
}
}
private const string Title = "harbour";
private static string Sha(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));
/// <summary>Every file and folder under <paramref name="root"/> with its size, in order.</summary>
private static List<string> Listing(string root) =>
[.. new DirectoryInfo(root).EnumerateFileSystemInfos("*", SearchOption.AllDirectories).Select(e => $"{Path.GetRelativePath(root, e.FullName)} {(e as FileInfo)?.Length}")
.Order(StringComparer.Ordinal)];
/// <summary>A sequence of <paramref name="photos"/> JPEG photos a minute apart, filed by the archive engine, once its jobs are done.</summary>
private static async Task<Guid> SequenceAsync(TestServer server, string token, int photos)
{
var uploader = server.NewClient(token);
Guid id = default;
for (var i = 0; i < photos; i++)
id = (await Uploads.UploadAsync(uploader, Photo(i), $"IMG_{i + 1:0000}.JPG", sessionKey: Title, capturedAt: new DateTime(2026, 9, 28, 18, i, 11))).SequenceId;
await JobsDoneAsync(server);
var admin = await server.AdminAsync();
using var titled = await admin.PatchAsync($"/api/v1/sequences/{id}",
System.Net.Http.Json.JsonContent.Create(new UpdateSequenceRequest(Title, null, null, null, null, null), ProtocolJson.Default.UpdateSequenceRequest));
titled.EnsureSuccessStatusCode();
return id;
}
/// <summary>Waits until the server's jobs (thumbnails, proxies, analyses) are done.</summary>
private static async Task JobsDoneAsync(TestServer server)
{
var until = DateTime.UtcNow + Wait;
foreach (var state in new[] { JobState.Queued, JobState.Running, JobState.Queued, JobState.Running })
{
while ((await server.Database.Jobs.ListAsync(state)).Items.Any(j => j.Kind != JobKind.Render))
{
Assert.True(DateTime.UtcNow < until, $"jobs still {state}");
await Task.Delay(50);
}
}
}
private static byte[] Photo(int seed)
{
const int width = 96, height = 64;
var pixels = new byte[width * height * 3];
for (var i = 0; i < pixels.Length; i++) pixels[i] = (byte)((i * 7 + seed * 31) % 251);
return JpegEncoder.Encode(pixels, width, height, 3, new JpegEncodeOptions { Quality = 90 });
}
/// <summary>A desktop's side: its own index (for the job engine), the workspace copy job connected to the test server, a workspace and its sync.</summary>
private sealed class WorkspaceClient : IAsyncDisposable
{
private readonly TestContext _context;
private WorkspaceClient(TestContext context, ChronosDatabase db, Archive archive, ChronosClient client, JobEngine engine, WorkspaceStore store, string name)
{
_context = context;
Db = db;
Archive = archive;
Client = client;
Engine = engine;
Store = store;
Sync = new WorkspaceSync(store, "Chronos on " + name) { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) };
}
public ChronosDatabase Db { get; }
public Archive Archive { get; }
public ChronosClient Client { get; }
public JobEngine Engine { get; }
public WorkspaceStore Store { get; }
public WorkspaceSync Sync { get; }
public string Server => SyncService.ServerKey(Client.BaseAddress);
/// <summary>Whether the copy job finds this PC signed in to the server.</summary>
public bool Connected { get; set; } = true;
public static async Task<WorkspaceClient> StartAsync(TestContext context, TestServer server, string token, string name)
{
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory(name + "-db"), "chronos.db")), context.Cancellation);
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = name });
// This PC's own library: the copy of a server project never writes into it.
var archive = await archives.CreateAsync(context.CreateTempDirectory(name + "-archive"), "Local", cancellationToken: context.Cancellation);
var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), name) { Token = token };
WorkspaceClient? created = null;
var engine = new JobEngine(db, WorkspaceJobs.CreateHandlers(db, archives, new Connector(client, () => created?.Connected ?? true)),
new JobEngineOptions { Workers = 1, WorkerId = name, PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync(context.Cancellation);
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory(name + "-ws"), "workspace"));
created = new WorkspaceClient(context, db, archive, client, engine, store, name);
return created;
}
public ServerProjectHome Home(Guid sequenceId) => new(Client, sequenceId, "Test server");
public ProjectBundle Bundle(Guid projectId) => Store.Find(projectId)!.ReadBundle();
/// <summary>The project checked out and its media downloaded.</summary>
public async Task CheckoutAsync(ServerProjectHome home, Guid projectId)
{
await Sync.CheckoutAsync(home, projectId, cancellationToken: _context.Cancellation);
await CopyAsync(home.SequenceId, projectId);
}
/// <summary>A copy job of the project's media from the server to its end (from <paramref name="checkpoint"/> when given).</summary>
public async Task<Job> CopyAsync(Guid sequenceId, Guid projectId, string? checkpoint = null)
{
var request = WorkspaceJobs.CopyFromServer(sequenceId, Title, Server, Store.Root, projectId);
var job = await EnqueueAsync(request, checkpoint);
return await WaitAsync(job.Id, JobState.Done);
}
public async Task<Job> EnqueueAsync(Data.Archiving.Jobs.ArchiveJobRequest request, string? checkpoint = null)
{
if (checkpoint is null) return await Engine.EnqueueAsync(request, cancellationToken: _context.Cancellation);
var job = new Job
{
Id = Guid.CreateVersion7(),
Kind = request.Kind,
TargetIds = request.Targets,
TargetLabel = request.Label,
ParametersJson = request.ParametersJson,
State = JobState.Queued,
Checkpoint = checkpoint,
Created = DateTimeOffset.UtcNow,
};
await Db.Jobs.EnqueueAsync(job, _context.Cancellation);
Engine.Wake();
return job;
}
public async Task<Job> WaitAsync(Guid jobId, JobState state)
{
var until = DateTime.UtcNow + Wait;
while (true)
{
var job = await Db.Jobs.GetAsync(jobId, _context.Cancellation);
if (job?.State == state) return job;
if (job?.State is JobState.Failed or JobState.Done or JobState.Cancelled) Assert.Fail($"Job ended {job.State}: {job.Error}\n{job.LogTail}");
if (DateTime.UtcNow > until) Assert.Fail($"Job {jobId} did not reach {state} (now {job?.State})");
await Task.Delay(25, _context.Cancellation);
}
}
/// <summary>The working state edited as the editor does: read, changed, stored.</summary>
public async Task EditAsync(Guid projectId, Func<ProjectSettings, ProjectSettings> edit)
{
var session = await Sync.OpenAsync(projectId, _context.Cancellation);
await Sync.SaveAsync(projectId, edit(session.Working), _context.Cancellation);
}
public async Task CommitAndPushAsync(ServerProjectHome home, Guid projectId)
{
Assert.NotNull(await Sync.CommitAsync(projectId, cancellationToken: _context.Cancellation));
Assert.Equal(1, (await Sync.PushAsync(projectId, home, _context.Cancellation)).Pushed.Count);
}
/// <summary>The project's head at the server, its positions placed on the server's frames.</summary>
public async Task<ProjectSettings> PlacedHeadAsync(ServerProjectHome home, Guid projectId)
{
var head = await home.HeadAsync(projectId, _context.Cancellation);
var frames = await home.FramesAsync(_context.Cancellation);
return ProjectSettings.FromJson(ProjectContent.Place(head.SettingsJson, frames.Photos));
}
public async ValueTask DisposeAsync()
{
await Engine.DisposeAsync();
Client.Dispose();
await Db.DisposeAsync();
}
/// <summary>The copy job's connection: a remote over the signed-in client while <c>connected</c> says so.</summary>
private sealed class Connector(ChronosClient client, Func<bool> connected) : ISyncConnector
{
public ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken)
{
ISyncRemote remote = new ChronosSyncRemote(client, ownsClient: false);
return ValueTask.FromResult<ISyncRemote?>(connected() && remote.Server == server ? remote : null);
}
}
}
}