26 Commits
Author SHA1 Message Date
Alby96 5fc7f02abf Merge branch 'p5c-p1p2' into review2-p5c 2026-11-04 16:04:00 +01:00
Alby96andClaude Opus 5.5 59e7aca006 feat(workspace): render a project on this PC from its originals
A workspace project that holds its originals now renders locally
(JobKind.WorkspaceRender), so the full-resolution render no longer
waits on the home. This holds also when the home is a server.

- The handler reads its inputs under the project's lease. It refuses
  proxies-only media, and it refuses frames without an original,
  saying how many lack one. It renders into exports/ with unique
  names and a resumable checkpoint.
- Each output gets a ledger entry: SHA-256, the render id from
  RenderJobHandler.RenderId, and the version, recorded only when
  versions/ holds it and its hash verifies.
- After rendering, the handler queues a WorkspaceSend follow-up for
  the outputs it recorded. A cancel leaves no partial file.
- The editor routes Originals media to the local engine even for a
  server home, and lists those jobs beside the server's. It treats
  WorkspaceRender like Render for the toast and the reload, says
  "Sent home" when a send ends, and shows unsent ledger renders as
  "Not sent".
- Version on render saves a changed project as a version noted
  "Render" before it renders, and sends it with Sync automatically.
  With the setting off, the render behaves as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 16:03:05 +01:00
Alby96andClaude Opus 5.5 0c51d11080 feat(workspace): copy originals into the workspace and choose the project Edit opens
Phase 5c P1. A workspace copy of kind "originals" now copies each frame's
original beside its proxy, so a later local render has full-quality input:
streamed into a .part file, hashed as written, checked against the home's
SHA-256, renamed and read back. Archive and server homes both work, a stopped
copy resumes (originals: checkpoint), and the space check counts the
originals. A frame whose original is gone, damaged or refused keeps its proxy
and the job says how many; the copy does not fail. Stale originals are
deleted only when the home holds the same SHA-256, otherwise moved to the
workspace's trash.

Proxies only... plans first (every original hashed against the home's
frames), asks for an explicit confirmation, rewrites the media to proxies
before it touches a file, refuses a plan that changed since, and trashes what
the home no longer holds instead of deleting it.

Edit: Open in workspace offers Originals (the settings' default, disabled
when the drive lacks room) with the originals' size for archive and server
homes; Settings > Workspace > Open project picks Last used, Main or asks
which; each open is recorded for the clean-up. The project menu gains Copy
originals... and Proxies only..., refused while changes are unsaved or jobs
of the sequence run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:43:42 +01:00
Alby96andClaude Opus 5.5 2e1c67f531 feat(workspace): lay the phase 5c foundation
Phase 5c (owner review 2, R8) is built by six packages in parallel. This
commit settles everything they share, so each one touches its own files:

- job kinds WorkspaceRender (21), WorkspaceSend (22) and WorkspaceMove (23)
  with their wire names, default priorities, notices and parameter records;
  their handlers are registered as skeletons that throw until their
  package lands
- WorkspaceJobOptions and a new CreateHandlers overload; the earlier ones
  stay and default the options
- originals in the media index (an index of phase 5b reads as proxies
  only), their file names, and the exports/renders.json ledger of local
  renders, written atomically
- the optional project and version of an uploaded render
- the workspace settings (size limit, default media, version on render,
  clean-up age, project to open) and when each project was opened, which
  Reset and Import keep and Export leaves out
- WorkspaceHost split into partial files, with stubs for usage, trash and
  the folder move, removal hooks for unsent renders and last originals,
  and a guard that holds work while the workspace moves
- every new string of the phase in English and Italian, with tooltips

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 15:05:09 +01:00
Alby96andClaude Opus 5.5 102f28b5df docs(plan): phase 5c work packages
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:31:00 +01:00
Alby96andClaude Opus 5.5 31df8beb9a docs(i18n): translate the phase 5b strings and split the changelog by release
CI / Build and test (pull_request) Successful in 8m15s
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 10s
CI / PostgreSQL 16 integration (pull_request) Successful in 8m46s
CI / PostgreSQL 17 integration (pull_request) Successful in 9m51s
CI / Docker image (pull_request) Successful in 1m45s
The 119 new phase 5b strings are translated into the 36 machine-translated
languages. The changelog separates what shipped in 0.1.0-rc.9 (ports and
baselines) from the unreleased phase 5b work, and the index settings decision
names the rare cases where a newer project.json is kept as version 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:21:36 +01:00
Alby96andClaude Opus 5.5 2068656f44 docs: record the phase 5b final check
DECISIONS: IndexSettingsMayLead (Main's birth and meeting on a server keep the
index's settings), the name follow that never fails a pull, the capture's
sample paths and the Server actions column; the rows on the Main meeting, the
settings PATCH and the name follow point to them. CHANGELOG: the fix wording
is now true for servers upgraded from an earlier release, with an upgrade note;
BRIEF's Main mirror rule and STATUS follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 13:54:27 +01:00
Alby96andClaude Opus 5.5 bc4d8e0768 fix(app): captures show no machine paths, Server row actions stay on one line
The capture's data folder lives in the machine's temporary folder, so 8
baselines showed %TEMP% and the user name and differed on any other machine.
AppEnvironment.Shown now shows a capture's folders as a sample user's
(C:\Users\Studio\AppData\Local\Chronos, the sample archive as D:\ChronosArchive)
in Settings > Storage, Workspace and Advanced, the Rebuild index dialog and the
cache's Clear confirmation; AppEnvironment.Actual maps a typed path back, so the
capture still writes only to its temporary folder. Two captures with different
TEMP folders are identical.

On the Server screen the row actions column is at least 400 px wide, so a
remote row's three actions (an older server's disabled Open in workspace after
Open with proxies and Download originals, as BRIEF 12.7 asks) fit one 40 px
line at the capture size instead of wrapping.

Baselines recaptured: server, server-sync, server-conflict, server-signedout
(column layout; the disabled action of phase 5b), settings-storage,
settings-workspace, settings-advanced and archive-rebuild (sample paths), light
and dark.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 13:54:26 +01:00
Alby96andClaude Opus 5.5 5ff9c086fd fix(workspace): a pull that succeeded never fails on the name it follows
The name follow after a pull caught only the home's own exceptions, so a 403
or any other error from the home's list (or a bundle in use) made a pull that
had already pulled and replayed report a failure. It is now logged as a
warning and the name is followed at the next pull; a cancellation still passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 13:35:47 +01:00
Alby96andClaude Opus 5.5 ab6cad51b2 fix(projects): never revert a server's index settings to an older project.json
Before phase 5b the server's settings PATCH wrote the index alone, and every
desktop edit of a linked sequence arrives as one, so an upgraded server holds
sequences whose index settings are newer than their project.json. Main's birth
read project.json first and mirrored it over the index; sequenceChanged then
carried the loss to the desktops' linked copies.

ArchiveServiceOptions.IndexSettingsMayLead, set by the server, keeps both: Main
is born with project.json's settings as version 1 and the index's as version 2,
in force and mirrored (on a read-only archive both go to the index only). A Main
the sidecars already hold, met with no mirror known, keeps index settings that
none of its versions hold as an External version below what project.json gives
(the head again as a Restore, a merge, or the file's). The desktop is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 13:35:47 +01:00
Alby96 ccc10ec8b8 Merge remote-tracking branch 'origin/main' into review2-p5b-final
# Conflicts:
#	docs/BRIEF.md
#	docs/CHANGELOG.md
#	docs/DECISIONS.md
#	docs/requests/2026-10-26-owner-review-2.md
#	i18n/en/Server.resx
#	i18n/it/Server.it.resx
2026-11-04 13:21:31 +01:00
Alby96andClaude Opus 5.5 3ade4b8d6c docs: document phase 5b, the server as a project home
Phase 5b had only module rows and the review's DECISIONS and CHANGELOG lines.
The brief now describes the server home as the code does after the review
fixes: the projects API, projectChanged, the capability, the settings PATCH
under the lease, renders of a project version, the panel's Projects section,
and the desktop's server projects (open, copy, sync, chip, renders, viewers).

DECISIONS gains the phase's own rows; the 5b rows are dated 2026-10-26 like
the other review-2 phases, and three 5a rows are marked partly superseded.
CHANGELOG, STATUS, the request's 5b row and ARCHITECTURE follow the code
(frames stamp, stored reads, the .thumb marker, followed renames, the
editor's sign-in).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 13:19:55 +01:00
Alby96andClaude Opus 5.5 ae41c95682 docs: record the phase 5b review fixes in DECISIONS and CHANGELOG
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 12:54:46 +01:00
Alby96andClaude Opus 5.5 48d8158fd7 fix(app): viewers open server sequences with proxies, the editor follows the sign-in
An account without Edit is offered Open with proxies on a server that keeps
projects and checks nothing out, since it could never push. The editor of a
server's workspace project connects with the sign-in in use at each call, so a
project opened signed out renders once signed in; SyncHost tells every session
start and stop so workspace projects read their state again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 12:54:46 +01:00
Alby96andClaude Opus 5.5 cdd29f8e84 fix(workspace): follow server renames, never keep a thumbnail as a proxy on resume
A pull and the server's renamed event write the home's name into the copy, so
a rename made on the server reaches the workspace. A copy from a server marks
a thumbnail taken for a missing proxy before moving it into place; a resumed
run reads the marker and fetches the proxy the server has now, instead of
recording the thumbnail as one. Tests also cover the frames stamp (frames read
only when it moves), an older server's copy refusal and a viewer's 403 push.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 12:54:45 +01:00
Alby96andClaude Opus 5.5 44f0d30147 test(projects): cover empty sequences, push size, byte-capped pages, maker rights, PATCH vs project.json, stored checks, rescan events
Each behavioural fix of the previous commit gets a test that fails without it:
an empty sequence writes nothing and refuses projects, a 24 MiB version is
stored and one over the limit is too_large, a page of large versions stops
short and a server home pages on, a reused username deletes nothing, a PATCH
made after project.json stays Main's head, HoldsAsync is false for a missing
file or a deleted project, and a full rescan tells the rename it found.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 12:54:44 +01:00
Alby96andClaude Opus 5.5 4f652c4025 fix(projects): empty sequences, push size, version paging, delete rights, settings PATCH, change events
- An unplaced sequence (no photos) lists no projects and refuses to create one
  with sequence_empty, instead of writing sidecars at the archive root.
- A push accepts a full-size version; a 413 is reported as too_large.
- Version pages are capped in bytes and say when more follow; the summary form
  leaves settings out; server homes page on.
- Deleting by its maker needs the same account, not just the same username.
- A settings PATCH writes project.json under the sequence lease, so Main's
  later birth no longer wipes it.
- Reconcile, read-only catch-up and a Main flip publish projectChanged.
- Server homes read the frames stamp and check a version is really stored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 12:31:52 +01:00
Alby96andClaude Opus 5.5 ed7452e739 fix(sync): tell missed project changes only once the event stream is open again
The agent told "changes may have been missed" as soon as the stream dropped,
so a workspace re-read before the server's events could reach it again and
missed changes made in between. The signal now waits for the reconnected
stream and the refresh that follows it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 12:31:51 +01:00
Alby96andClaude Opus 5.5 353024fc71 fix(panel): projects table fits narrow widths, keeps loaded versions on refresh, skips settings
The projects table sits in a min-width-0 host so fitColumns can drop columns.
A live refresh re-reads only the changed, expanded projects and keeps as many
versions as were shown (Load more included). Version pages ask for the summary
form, so the panel no longer downloads settings it never shows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 12:31:51 +01:00
Alby96andClaude Opus 5.5 26bab759fe feat(app): workspace projects whose home is a server, pushed and pulled like this PC's archive
Owner review 2, R8, phase 5b (client part), ported onto the final phase 5a.
A Chronos Server with the "projects" capability is now the home of
workspace projects. A server sequence is edited in the workspace like a
local one, not inside the library, and its versions sync with the server
"like git".

- Data: ServerProjectHome is an IProjectHome over ChronosClient.
  - These are HomeUnavailableException, so the workspace shows Offline: a
    server out of reach, an expired sign-in, a 503 (lease, offline archive,
    projects_unreadable), a 409 folder_in_use, and a server without projects.
  - 404 sequence/project/version and refused names are ProjectException;
    other refusals keep their meaning.
  - A deleted project's head is 404 project, so final 5a's HeadAsync NotFound
    rule reads it as Gone. The original 5b's IsLiveAsync and
    WorkspaceStatus.Gone are dropped. IProjectHome gains rename and delete.
- Data: WorkspaceJobs.CopyFromServer downloads into the workspace, through
  the desktop's session, the proxies of one frames version (or the
  thumbnails standing in for them), with the aliases of the server's
  conversions. It is rebuilt on final 5a's copy handler:
  - the copy:frame:fv:folder checkpoint, EnsureSpace (from the server's proxy
    sizes), WritingMedia, and the cancelled-copy clean-up;
  - the editor's current file is never overwritten;
  - each file is hashed as it arrives and checked on disk, four at a time.
  It never writes this PC's archive. Originals are still refused until 5c.
- Data: SyncAgent passes on the server's projectChanged events, and after a
  lost event stream it reports that changes may have been missed.
- App: SyncHost gives the server home over one session client. The Server
  screen offers Open in workspace, disabled with its reason on older
  servers, whose sequences keep opening with proxies.
- App: Edit opens or checks out server projects with final 5a's refusals:
  unreadable copies, a disabled damaged or newer Main, a refused folder. The
  "sequence left the index" refusal now applies only to projects of this
  PC's archive.
- App: the picker and the chip follow projectChanged (Server newer, Not on
  server). Every state, conflict, delete, remove and failure text uses its
  ".Server" form when one exists (WorkspaceText.ForHome). That includes 5a's
  newer-format conflict, the save conflict, the taken-values toast, Gone and
  version-too-large.
- App: a render of a server project first offers to send what is not on the
  server, then renders the version the server holds. Offline, Gone, Damaged
  and missing media hold the render. Analyses and renders run as server jobs
  (ServerJobs, shared with RemoteSequenceSource).
- Pruning keeps final 5a's rule: a version is pruned only after HoldsAsync
  reads it back.
- Strings in en and it; ARCHITECTURE, DECISIONS and CHANGELOG.

Tests:
- ServerProjectHome error mapping, using a fake handler.
- Against the in-process server:
  - two workspaces on one project: fast-forward, replay and merge, keep mine,
    take server, save both, restore;
  - the copy job verifying, resuming and following new frames;
  - a project deleted on the server (Gone from its head; a push sends
    nothing);
  - an offline server.
- SyncAgent project events.
- App tests for the host, the project menu and renders of a server home.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 11:45:06 +01:00
Alby96andClaude Opus 5.5 e2ecc409a3 feat(server): the server keeps its sequences' projects, pushed and pulled like a PC's archive
Owner review 2, phase 5b (R8): a server is a project home. A workspace can
list a sequence's projects, make, rename and delete them, read their
versions and push new ones through /api/v1/sequences/{sid}/projects. The
endpoints run on the archive's ProjectService exactly as a desktop's archive
does (sidecars first, then the index, under the sequence's lease), so no
version is stored apart and a desktop sharing the archive sees the same
projects.

- Protocol: project, version, create, rename, version page, push answer
  (outcome, stored version, head, plus code and message on 409/422) and
  home frames DTOs, the projectChanged event, the "projects" capability and
  the ChronosClient calls; a push returns its outcome without throwing on
  409 or 422. ProjectWire maps them to and from the model for both sides.
- Server: Read lists and reads, Edit makes, renames and pushes, Delete (the
  sequence's owner, the project's maker or an admin) deletes; refusals with
  stable codes, 503 while the sequence is busy, offline or moved; the
  pushing account becomes the version's author; creations, renames and
  deletions audited, pushes logged.
- ProjectService tells the host what each call changed, compared under the
  lease, so projectChanged also follows Main's external versions; a Main
  version mirrored into the settings sends sequenceChanged too, for older
  clients. ProjectCatchUp takes settings a PATCH, an analysis or a
  conversion wrote into Main at once, for sequences that have a Main.
- Renders of a project version: POST /jobs checks the project and version
  against the sequence and pins a project alone to its head; render nodes
  get the version's settings placed on the frames they claim; the render
  records the project and version.
- Admin panel: the sequence page lists its projects (Main marked, head,
  last change, versions on demand) with Rename and Delete for the others,
  live on projectChanged. It edits no settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 11:15:19 +01:00
Alby96 917cddde41 Merge remote-tracking branch 'origin/main' into review3-ports
CI / Build and test (pull_request) Successful in 11m22s
CI / Windows tests and installer (pull_request) Skipped
CI / YAML check (pull_request) Successful in 7s
CI / PostgreSQL 16 integration (pull_request) Successful in 10m51s
CI / PostgreSQL 17 integration (pull_request) Successful in 10m55s
CI / Docker image (pull_request) Successful in 1m33s
2026-11-04 11:04:25 +01:00
Alby96andClaude Opus 5.5 7273eec2bb feat: screenshot baselines from the development PC, fixed capture values, ports strings in all languages
The owner chose to capture the baselines on the development PC (owner
review 3, R2): 156 screens go to tests/visual/baselines and CI no longer
pushes a ci-screenshots branch. While --capture freezes AppClock, free
space, a server's latency and the last sync are fixed sample values; they
moved the Server and Import screens past the diff tolerance at random.
The 22 new or changed Admin strings are translated into the 36 other
languages, and the request file records the owner's text and answers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 11:04:23 +01:00
Alby96andClaude Opus 5.5 2585b5d45f fix(protocol): report Chronos's own info error as that error, not a disposed stream
The identity check reads Chronos's error body to tell it from another
service; GetInfoAsync then read it again and threw ObjectDisposedException.
The identity now carries the parsed error and GetInfoAsync throws it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 10:42:58 +01:00
Alby96andClaude Opus 5.5 0aa2fb8135 fix(server): client address from the page's port, stricter Chronos identity, Host networking notes
Review fixes on top of the public ports change (owner review 3):

- Settings > Network and TLS: opened over HTTPS, the client address uses the port
  the page came through (a container's 8443 published as 8444 with Public HTTPS
  port still empty showed the wrong 8443), and a "Use <port>" button fills that
  port in. Saving a Public HTTPS port other than the page's asks first, since the
  HTTPS redirect follows it at once and a typo would lock the panel's link out.
- GetInfoAsync tells Chronos from other services by stricter rules on both the
  trusted and the untrusted-certificate path: any redirect, any answer that is not
  JSON, more than 1 MB, or an error without the X-Chronos-Api header is not
  Chronos. Another service's certificate is no longer offered for trust after a
  cross-scheme redirect, an error page or a JSON 401/403/404, and a JSON 401 over
  HTTP no longer reads as a wrong password.
- The HTTP port typed without a scheme (TLS to a plain HTTP port) now gives the
  not-Chronos error instead of "the server did not answer".
- The Uploader's certificate question names the address with its port.
- A link-local IPv6 address with a zone index is refused instead of losing it.
- In a container, the first save of the settings removes HttpPort/HttpsPort from
  server.json, so the start-up warning stops; the warning says so.
- Guide, README, compose and template: with network type Host the mappings do
  nothing and CHRONOS_HTTP_PORT / CHRONOS_HTTPS_PORT move the listening ports off
  ones another service uses; the template overview is back to two sentences.
- BRIEF, DECISIONS and CHANGELOG updated; en/it strings added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 10:28:08 +01:00
Alby96andClaude Opus 5.5 369e754bec fix(server): public ports as settings, container port lock and client address; clients default to 8443 and name non-Chronos servers
The owner's Uploader could not connect: the panel showed the container's
listening ports (8080/8443) as if clients used them, the public ports were
only environment variables (CHRONOS_PUBLIC_HTTP_PORT not even in the Unraid
template), and the clients mapped a bare host to 443, where another service
answered.

- Public HTTP/HTTPS ports are settings (server.json, or locked by
  CHRONOS_PUBLIC_*) and apply at once; ServerSettingsDto gains appended
  PublicHttpPort, PublicHttpsPort and InContainer members.
- In a container the listening ports are fixed by the template: locked in the
  panel, and saved values from earlier versions are ignored with a warning.
- Settings > Network and TLS shows the client address with a Copy button; the
  discovery tooltip says a container needs network type Host.
- ChronosAddress (shared by Chronos and the Uploader): no scheme and no port is
  https on 8443, https:// keeps 443, a typed port is kept, IPv6 is bracketed.
- GetInfoAsync throws NotChronosServerException for answers that are not a
  Chronos server; another service's certificate is never offered for trust
  and no credentials are sent to it. Both clients name the address asked.
- Unraid template, compose file, user guide, README, BRIEF, DECISIONS,
  CHANGELOG (with an Unraid upgrade note) and ARCHITECTURE updated; en/it
  strings added.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:53:49 +01:00
66 changed files with 4074 additions and 222 deletions

No files matched your search

+181
View File
@@ -0,0 +1,181 @@
# Phase 5c plan (owner review 2, R8): originals, local render, clean-up, all Workspace settings
Working plan for the implementation. Line numbers refer to the tree at the end of phase 5b (commit 31df8beb) and drift.
The highest `JobKind` is `WorkspaceCopy = 20` (src/Chronos.Core/Model/Enums.cs); 5c appends 21–23. No migration: `renders`
already has `project_id`/`project_version_id`, and the workspace state lives in files.
## A. Already done (do not redo)
- Remove local copy: plan first, refused while work is unsent, Send first / Discard (typed), hash read-back of the home's
head and base before deleting (`WorkspaceHost.PlanRemovalAsync`, `RemoveLocalCopyAsync`, `VerifyHomeAsync`,
`RemoveFolderAsync` moves into `.trash/<id>-<ticks>`; `WorkspaceRemovalPlan.IsSafe`; `RemoveCopyDialogViewModel`).
Missing: emptying `.trash`.
- Kept versions (default 20, `AppSettings.WorkspaceKeptVersions`, `WorkspaceHost.PruneAsync`, `WorkspaceSettingsRows.KeptChoices`).
- Sync automatically (`AppSettings.WorkspaceAutoSync = true`, checkbox in SettingsView.xaml Workspace page).
- Folder Open / Change… (Change shows a plan, moves nothing: `WorkspaceFolderChange.cs`). Moving with projects is missing.
- Building blocks: `BundleMedia.Originals`; `WorkspaceProject.OriginalsFolder`/`OriginalsDirectory`;
`RenderJobParameters.ProjectId/ProjectVersionId`; `RenderStore.CommitAsync(projectId, projectVersionId)`; server
renders of a project version checked against the sequence; `SequenceRender` has an `originals` flag.
- Last used project: `WorkspaceHost.LastUsedAsync` + `WorkspaceRecent`. Main and Ask policies missing.
## B. 5a/5b limitations that 5c closes
- Downloads into the workspace are not held on a metered connection (`UploadHold` only filters `UploadCommit`). → P3
- Originals from a server: `WorkspaceCopyJobHandler` throws `Errors.Workspace.OriginalsLater`. Building block:
`SyncTransfers.FetchOriginalAsync` (private static; hash-checked, retried, resumable) and
`ISyncRemote.DownloadFrameAsync(…, "original", …)`; `/frames/{id}/original` needs Edit or RenderNode. → P1
- A render upload carries no project or version (`RenderUploadRequest` in Protocol/Uploads.cs; `RenderUploads.CompleteAsync`). → P3
- Move folder with projects (P6), empty `<workspace>/.trash` (P4), automatic clean-up and size limit (P4), the rest of
Settings › Workspace (P5).
- Not 5c (leave): address-alias Offline, frames in one answer, History downloading every version, restoring from the
projects' trash.
## C. Work packages
Order: P0 first. Then P1, P3, P4, P5, P6 (independent files). P2 after P1. P7 last.
i18n: P0 adds every new key in `i18n/en` and `i18n/it` with final text; later packages only reference keys; if one must
add a key it appends at the end of the resx file.
### P0 – Foundation
- `JobKind`: append `WorkspaceRender = 21`, `WorkspaceSend = 22`, `WorkspaceMove = 23`; `JobWire` names
`workspace-render`, `workspace-send`, `workspace-move`.
- Register: `JobPriorityQueue.DefaultLevels` (Render High, Send Normal, Move High); `SettingsViewModel.PriorityKinds`;
`JobText.CountsFrames` (+WorkspaceRender); `JobNotices.Announces` (+ all three). Not in the server's list
(ServerSettingsStore.cs).
- `AppSettings`: `WorkspaceSizeLimitGb = 100` (0 = none); `WorkspaceDefaultMedia = "proxies"` (BundleMedia constants);
`WorkspaceVersionOnRender = true`; `WorkspaceCleanAfterDays = 30` (0 = never); `WorkspaceOpenProject` enum
`WorkspaceOpenPolicy { LastUsed, Main, Ask }` default LastUsed; `WorkspaceOpened` `Dictionary<Guid, DateTimeOffset>`
treated like `WorkspaceRecent` in Reset / Import / Export (kept by Reset all and Import, left out of Export).
- `WorkspaceFrame` (Data/Workspaces/WorkspaceMedia.cs): append optional `Original`, `OriginalSha256`, `OriginalBytes`;
`ToOriginalFrame(sequenceId)` (RelativePath = Original, Missing when null). `WorkspaceMedia.Kind` can be `originals`
(proxies plus originals).
- `WorkspaceProject`: `OriginalName(frameId, sha, extension)` → `originals/<frameId>-<sha8><ext>` (keep the real
extension, decoders use it); `ExportsDirectory`; `RendersFile = "exports/renders.json"`.
- New `Data/Workspaces/WorkspaceRenders.cs`: `WorkspaceRenderEntry(RenderId, JobId, File, Sha256, Size, PresetName,
Codec, Width, Height, Fps, DurationSeconds, ProjectId, ProjectVersionId?, SettingsHash?, Rendered, State
pending|sent|failed, Sent?, Error?)`, ledger `WorkspaceRenders(Format, FormatVersion=1, Entries)`, atomic Read/Write.
- Parameter records in the `WorkspaceJson` context: `WorkspaceRenderParameters(WorkspaceRoot, ProjectId,
ProjectVersionId?, RenderJson, Server?)`, `WorkspaceSendParameters(WorkspaceRoot, ProjectId, RenderIds, Server?)`,
`WorkspaceMoveParameters(From, To, PlanFingerprint)`; `WorkspaceJobs.Render/Send/Move` request builders.
- `CreateHandlers(db, archives, ISyncConnector? servers, WorkspaceJobOptions options)` with
`WorkspaceJobOptions(ProcessingOptions Processing, Func<bool> HoldTransfers, Func<string,string,Task>? Moved)`;
skeleton handlers for Render, Send, Move. Wire in AppServices.
- App: `WorkspaceHost` becomes `partial`; stubs `UsageAsync` → `WorkspaceUsage(MediaBytes, TotalBytes, TrashBytes,
TrashItems)`, `PlanTrashAsync`/`EmptyTrashAsync`, `PlanMoveAsync(to)`/`QueueMoveAsync(plan)`,
`WorkspaceFolderChange.MoveAsync`.
- Protocol: append optional `ProjectId`, `ProjectVersionId` to `RenderUploadRequest`.
- Strings (en + it, labels ≤ 3 words, every one with a `Tooltips.*` twin): job kinds (Local render, Send render, Move
workspace); Settings.Workspace.* (Move…, Size limit/No limit, Default media/Proxies/Originals, Version on render, Clean
after/Never/Days plural, Open project/Last used/Main/Ask, Trash, Empty…, "{0} used"); Editor.OpenWorkspace.OriginalsSize
"Originals: {0}" and a new `Tooltips.Editor.OpenWorkspace.OriginalsReady` (old "later update" key stops being used);
Workspace.Menu.CopyOriginals "Copy originals…", Workspace.Menu.ProxiesOnly "Proxies only…"; errors Moving,
MoveTargetNotEmpty, MoveSameFolder, OriginalsMissing, RenderNoOriginals, SendHashMismatch, JobsRunning; schedule
Jobs.Schedule.System.WorkspaceCleanup and steps WorkspaceClean / WorkspaceTrash; `Server.PauseMeteredTransfers` "Pause
metered transfers" (new key, keep the old); Workspace.MovePlan.*, Workspace.TrashPlan.*, Workspace.Removal.UnsentRenders
/ LastOriginals.
- Tests: priority defaults; settings defaults and Reset/Import/Export of WorkspaceOpened; RenderUploadRequest without
the fields deserializes; 5b media.json without original fields reads; JobWire names.
### P1 – Originals in the workspace, opening a project
- Copy job: remove the OriginalsLater throw. With Media Originals: proxies first as now, then per frame stream into
`media/originals/<name>.part` hashing as it copies, compare with the home frame's Sha256 (record it if the home has
none), rename, checkpoint `copy:<frame>:<fv>:originals`. Archive source under the read lease as the proxy copy does;
server source via `SyncTransfers.FetchOriginalAsync` made `internal static`. Missing original (file gone, 404, 403):
keep the proxy, `Original = null`, finish with a warning count.
- Space: estimate adds originals not held yet; keep the 512 MiB reserve. `CopyFactsAsync` reports `OriginalsBytes`
(archive frames' Size, or a server's `SequenceDto.TotalBytes`).
- Commit writes the chosen media kind (replace the hard-coded Proxies).
- Proxies only…: plan (files, bytes) with explicit confirmation; before deleting, the home still holds each frame with
the same SHA; originals the home no longer holds go to `.trash`; rewrite media.json Kind Proxies.
- Copy originals…: queue a WorkspaceCopy with Media Originals (existing dedupe).
- Open dialog: originals selectable, default from `WorkspaceDefaultMedia`, originals size and free space, TooLittleSpace
counts originals, Open passes the chosen media.
- SequenceViewModel: pass the media into CheckoutAsync; apply `WorkspaceOpenProject` (LastUsed / Main / Ask);
AskProjectAsync gets copy facts for a server home; each open records `WorkspaceOpened[id] = now`.
- ProjectMenuViewModel: Copy originals… / Proxies only… (by media kind; refused while Modified or jobs run).
- Tests: archive copy with originals (hashes, files), corrupt source refused and .part removed, resume by checkpoint, too
little space, missing original leaves the frame proxied, from a server (FakeSyncRemote `original` payload, 403
tolerated); dialog default; the three policies; Proxies only refuses when the home lost a frame and trashes it.
- Risks: stream originals, never buffer; older Chronos meeting kind `originals` reports OriginalsLater (DECISIONS).
### P2 – Local render, `WorkspaceRender = 21`
- `WorkspaceRenderJobHandler` mirrors `RenderJobHandler.RunAsync`: workspace lease; media.json must be Originals with
an original for every placed frame (else `RenderNoOriginals` with the count); `SequenceFrames` over the originals;
parse the head version or the named `ProjectVersionId` from `versions/`; analysis from media; `SequenceRender(...,
originals: true, companions: null)` into `exports/<name>.part` then rename, unique names, `RenderCheckpoint`; per
output SHA-256 and a ledger entry with `RenderId = RenderJobHandler.RenderId(jobId, index)`; then follow-up
`WorkspaceSend` with the new ids. Extract `ProvenanceAsync` into a shared internal helper. Cancel deletes `.part` only.
- Routing (WorkspaceSequenceSource): Originals media → `WorkspaceJobs.Render(...)` with portable settings and head
version id; such requests go to the local engine even for a server home; ListJobsAsync merges the local
Render/Send jobs; `IProjectRenders.RendersLocally`.
- Version on render (`ProjectMenuViewModel.ReadyToRenderAsync`): setting on + Modified → save a version (label
"Render") and sync it when auto sync is on and the home is reachable; off → today's behaviour.
- Editor: WorkspaceRender treated like Render for toast and reload; WorkspaceSend Done = "Sent home"; SequenceJobs and
ServerJobs know both kinds; Renders list shows pending ledger entries as "Not sent".
- Tests (Data, Linux-runnable): renders a preset from originals into exports, ledger SHA and id, follow-up queued,
missing original fails cleanly, cancel leaves no .part, output matches an archive render's frame count and size;
App: Originals routes locally for a server home, Version on render saves first, off still prompts.
### P3 – Send home (`WorkspaceSend = 22`), server provenance, metered transfers
- `WorkspaceSendJobHandler`, per pending ledger entry: re-hash (mismatch → `SendHashMismatch`, file stays); push the
named version first if the home lacks it (failure → job fails, entry stays pending); archive home: file like
`SyncTransfers.GetExportsAsync` (lease, SequenceFolders, unique name, copy, hash read-back, `Renders.InsertAsync` with
project and version after checking the version belongs to this sequence); server home:
`ISyncRemote.UploadRenderAsync(sequenceId, path, new RenderUploadRequest(..., ProjectId, ProjectVersionId))` (not
UploadCommit). Mark sent; the file stays until clean-up. Idempotent by RenderId.
- Server `RenderUploads.CompleteAsync`: check the project fields against the sequence (422 `project_mismatch`), pass to
`RenderStore.CommitAsync`; `RenderDto` gains optional project fields.
- `UploadHold`: hold `UploadCommit`, `WorkspaceSend` and `WorkspaceCopy` jobs naming a `Server` while
`PauseUploadsOnMetered && MeteredNetwork.IsMetered()`; archive-home copies never held. Server screen checkbox uses
"Pause metered transfers".
- Tests: archive-home send files the render with project and version; changed file refused; unpushed version pushed
first; retry; duplicate harmless; server upload with fields stores them, foreign version 422, without fields as
before; UploadHold pauses server copy and send when metered, not an archive copy.
### P4 – Clean-up, size limit, workspace trash
- `WorkspaceCleaner`: eligible = StatusAsync InSync with the home asked (not Offline), not open, no
Copy/Render/Send/Move job pending or running, no pending ledger render. Removes `media/proxies`, `media/originals`
(media.json rewritten with File/Original null, frames stay), and sent files in `exports/`; never `project.chronos`,
`versions/`, `sync.json`, `analysis.json`. An original is deleted only when the home still holds the same frame with
the same SHA; otherwise it goes to `.trash/<id>-<ticks>/originals`. Policies: Clean after N days (by
`WorkspaceOpened`, fallback the bundle's Saved), Size limit (LRU while above). 0 disables. Report with skipped reasons.
- `WorkspaceTrash`: Plan (items, bytes, dates, fingerprint over names, sizes, mtimes) and Empty(plan) only if the
fingerprint still matches; the UI asks for the item count typed. Schedules and the size limit never empty the trash.
- Schedule: system key `workspace-cleanup`, daily 04:30, steps `workspace-clean` and `workspace-trash` (report only) as
App-side cleanup steps like `CacheTrimStep`; seeded by `DesktopScheduleHost`; ScheduleText maps; runs without an
archive. The size limit also runs after each WorkspaceCopy (never the project just copied).
- `WorkspaceHost.Cleanup.cs` fills the P0 stubs. Removal plan: `UnsentRenders` blocks IsSafe until Send first (queues
WorkspaceSend) or Discard; `LastOriginals` go to `.trash`.
- Tests: each skip reason, original the home lost goes to trash, LRU order, Clean after with fallback, trash untouched by
clean-up and Empty refuses a stale fingerprint; schedule seeded once, step without an archive, removal plan counts
unsent renders.
### P5 – Settings › Workspace page
Rows in order: Folder (path, Open, Change…, Move… showing P6's plan; "{0} used"); Size limit (25, 50, 100, 200, 500,
1000 GB, No limit); Default media (Proxies, Originals); Sync automatically; Version on render; Kept versions; Clean
after (7, 14, 30, 60, 90 days, Never); Open project (Last used, Main, Ask); Trash ("{n} items, {size}", Empty… with the
plan dialog and typed confirmation, disabled when empty). Search keys, Reset restores defaults, every control has a
tooltip. Tests: rows read/write and Reset; the screen smoke test (page builds, tooltips).
### P6 – Move the workspace folder, `WorkspaceMove = 23`
- Plan: projects, bytes, free space at the target, unsent or Modified projects as a warning; refused when the target is
inside the source or the same, already holds `workspace.json` or same-id project folders, too little space, or any
workspace job pending or running; fingerprint.
- Job: re-check the fingerprint; journal `<from>/.move.json`; same volume `Directory.Move` per project, then
`workspace.json`, then `.trash`; other volume copy each file, hash both sides, delete the source only after every file
of that project verified; checkpoint per file; resume from the journal. At the end `Moved(from, to)` sets
`AppSettings.WorkspaceFolder` and refreshes `WorkspaceHost.Root`; delete the journal. On failure the source stays the
truth and unverified partial copies are removed.
- App: while moving, sync and open are refused (`Errors.Workspace.Moving`); MoveAsync closes the open project first; a
leftover `.move.json` at start raises a notice to resume.
- Tests: same-volume, cross-volume (injected flag), a corrupt copy never deletes the source, resume, refusals; App: the
setting switches only on success, the workspace is gated while moving.
### P7 – Documentation
DECISIONS rows (originals media and naming, local render and ledger, send home idempotence, server provenance fields,
metered transfers covering downloads, clean-up eligibility and originals rule, trash fingerprint, workspace-cleanup key,
move journal, Open project policy, defaults, no migration, no GPR companions); BRIEF §4.4, §12.3, §12.7, §12.8, §14.3,
§14.5; CHANGELOG [Unreleased] (remove the 5b limitations 5c closes; metered now pauses downloads); STATUS; ARCHITECTURE
job table; request files (owner review 2 row 5c, owner review 3 phase 2).
## D. Cross-cutting rules
- BRIEF rule 8: every deletion is a plan, derived data, or preceded by a home SHA read-back; trash when in doubt.
- Mixed versions: older clients see kind `originals` (OriginalsLater); older servers ignore the provenance fields.
- Logic in Chronos.Data (Linux-testable); the App wires it.
+10
View File
@@ -433,4 +433,14 @@
<data name="Archive.View.Health" xml:space="preserve"><value>Health</value></data>
<data name="Archive.View.Name" xml:space="preserve"><value>View</value></data>
<data name="Archive.View.Overview" xml:space="preserve"><value>Overview</value></data>
<data name="Archive.Log.WorkspaceOriginals" xml:space="preserve"><value>{0}: originals copied: {1}, unchanged: {2}, without one: {3}</value><comment>long: job log line; {0} sequence; {1} originals copied; {2} already in the workspace; {3} frames whose original the home lacks</comment></data>
<data name="Archive.Log.WorkspaceOriginalsDownloaded" xml:space="preserve"><value>{0}: originals downloaded: {1}, unchanged: {2}, without one: {3}</value><comment>long: job log line; {0} sequence; {1} originals downloaded; {2} already in the workspace; {3} frames whose original the server did not give</comment></data>
<data name="Archive.Log.WorkspaceOriginalMissing" xml:space="preserve"><value>{0}: frame {1} has no original at its home; its proxy stays</value><comment>long: job log line; {0} sequence; {1} frame file name</comment></data>
<data name="Archive.Log.WorkspaceOriginalsTrashed" xml:space="preserve"><value>{0}: originals the home no longer holds, kept in the trash: {1}</value><comment>long: job log line; {0} project name; {1} a count</comment></data>
<data name="Archive.Log.WorkspaceSent" xml:space="preserve"><value>{0}: renders sent: {1}, already there: {2}</value><comment>long: job log line; {0} project name; {1} renders sent; {2} the home held already</comment></data>
<data name="Archive.Log.WorkspaceVersionPushed" xml:space="preserve"><value>{0}: version {1} sent first, for its render</value><comment>long: job log line; {0} project name; {1} version number</comment></data>
<data name="Archive.Log.WorkspaceSendHeld" xml:space="preserve"><value>Held while the connection is metered</value><comment>long: job log line</comment></data>
<data name="Archive.Log.WorkspaceMoved" xml:space="preserve"><value>Workspace moved to {0}: projects: {1}, files: {2}</value><comment>long: job log line; {0} target folder; {1} and {2} counts</comment></data>
<data name="Archive.Log.WorkspaceMoveResumed" xml:space="preserve"><value>Move resumed from its journal: {0}</value><comment>long: job log line; {0} the journal file</comment></data>
<data name="Archive.Log.WorkspaceMoveProject" xml:space="preserve"><value>Moved: {0}</value><comment>long: job log line; {0} project name</comment></data>
</root>
+32
View File
@@ -447,4 +447,36 @@
<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>
<data name="Editor.OpenWorkspace.OriginalsSize" xml:space="preserve"><value>Originals: {0}</value><comment>long; {0} a size, &quot;1.2 GB&quot;</comment></data>
<data name="Editor.Project.CopyOriginals" xml:space="preserve"><value>Copy originals…</value></data>
<data name="Editor.Project.ProxiesOnly" xml:space="preserve"><value>Proxies only…</value></data>
<data name="Editor.ProxiesOnly.Title" xml:space="preserve"><value>Proxies only for {0}</value><comment>{0} project name</comment></data>
<data name="Editor.ProxiesOnly.Message" xml:space="preserve"><value>The originals copied to this PC are deleted once the library is checked to hold each one; renders then run where the originals are.</value><comment>long</comment></data>
<data name="Editor.ProxiesOnly.Message.Server" xml:space="preserve"><value>The originals downloaded to this PC are deleted once the server is checked to hold each one; renders then run on the server.</value><comment>long</comment></data>
<data name="Editor.ProxiesOnly.Originals" xml:space="preserve"><value>Originals: {0}</value><comment>long; {0} a count</comment></data>
<data name="Editor.ProxiesOnly.Size" xml:space="preserve"><value>Size: {0}</value><comment>long; {0} a size, &quot;1.2 GB&quot;</comment></data>
<data name="Editor.ProxiesOnly.ToTrash" xml:space="preserve"><value>Kept in trash: {0}</value><comment>long; {0} a count</comment></data>
<data name="Editor.ProxiesOnly.Action" xml:space="preserve"><value>Delete originals</value></data>
<data name="Editor.Workspace.CopyingOriginals" xml:space="preserve"><value>Copying originals</value></data>
<data name="Editor.Workspace.OriginalsCopied" xml:space="preserve"><value>Originals copied</value></data>
<data name="Editor.Workspace.OriginalsRemoved" xml:space="preserve"><value>Originals removed</value></data>
<data name="Editor.Workspace.OriginalsNotRemoved" xml:space="preserve"><value>Originals not removed</value></data>
<data name="Editor.Workspace.OriginalsMissing" xml:space="preserve"><value>Without original: {0}</value><comment>long; {0} a count of frames</comment></data>
<data name="Editor.Workspace.Media.Proxies" xml:space="preserve"><value>Proxies</value></data>
<data name="Editor.Workspace.Media.Originals" xml:space="preserve"><value>Originals</value></data>
<data name="Editor.OpenProject.Title" xml:space="preserve"><value>Open which project?</value></data>
<data name="Editor.OpenProject.Message" xml:space="preserve"><value>{0} has several projects in the workspace: choose the one to open.</value><comment>long; {0} sequence title</comment></data>
<data name="Editor.Render.QueuedLocal" xml:space="preserve"><value>Render queued on this PC</value></data>
<data name="Editor.Render.Local" xml:space="preserve"><value>On this PC</value></data>
<data name="Editor.Render.SentHome" xml:space="preserve"><value>Sent home</value></data>
<data name="Editor.Render.SentTo" xml:space="preserve"><value>{0} is in the library</value><comment>{0} render file name</comment></data>
<data name="Editor.Render.SentTo.Server" xml:space="preserve"><value>{0} is on the server</value><comment>{0} render file name</comment></data>
<data name="Editor.Render.NotSent" xml:space="preserve"><value>Not sent</value></data>
<data name="Editor.Render.SendFailed" xml:space="preserve"><value>Render not sent</value></data>
<data name="Editor.Render.SendAgain" xml:space="preserve"><value>Send again</value></data>
<data name="Editor.Render.Sending" xml:space="preserve"><value>Sending render</value></data>
<data name="Editor.Workspace.RenderNote" xml:space="preserve"><value>Render</value><comment>the note of the version Version on render saves before a render</comment></data>
<data name="Editor.Workspace.SavedForRender" xml:space="preserve"><value>Version {0} saved for render</value><comment>{0} version number</comment></data>
<data name="Editor.RemoveCopy.UnsentRenders" xml:space="preserve"><value>Renders not sent</value></data>
<data name="Editor.RemoveCopy.LastOriginals" xml:space="preserve"><value>Last originals</value></data>
</root>
+24
View File
@@ -90,4 +90,28 @@
<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>
<data name="Errors.Workspace.JobParameters" xml:space="preserve"><value>This workspace job has no valid parameters.</value></data>
<data name="Errors.Workspace.OriginalsMissing" xml:space="preserve"><value>The workspace holds no originals of this project: Copy originals… copies them from the library.</value></data>
<data name="Errors.Workspace.OriginalsMissing.Server" xml:space="preserve"><value>The workspace holds no originals of this project: Copy originals… downloads them from the server.</value></data>
<data name="Errors.Workspace.OriginalMismatch" xml:space="preserve"><value>The original {0} did not match its SHA-256 after it was copied; it was not kept.</value></data>
<data name="Errors.Workspace.OriginalsCheck" xml:space="preserve"><value>The library cannot be reached to check the originals against it; nothing was removed.</value></data>
<data name="Errors.Workspace.OriginalsCheck.Server" xml:space="preserve"><value>The server cannot be reached to check the originals against it; nothing was removed.</value></data>
<data name="Errors.Workspace.MediaBusy" xml:space="preserve"><value>Save your changes as a version and wait for this project's jobs to end before changing its media.</value></data>
<data name="Errors.Workspace.RenderNoOriginals" xml:space="preserve"><value>Frames without an original in the workspace: {0}. Copy originals… copies them, then render again.</value></data>
<data name="Errors.Workspace.RenderVersion" xml:space="preserve"><value>The version to render is not in the workspace: sync the project, then render again.</value></data>
<data name="Errors.Workspace.RenderProject" xml:space="preserve"><value>The project to render is no longer in the workspace.</value></data>
<data name="Errors.Workspace.SendHashMismatch" xml:space="preserve"><value>{0} changed after it was rendered: it was not sent, and stays in the workspace.</value></data>
<data name="Errors.Workspace.SendVersion" xml:space="preserve"><value>The version this render was made from could not be sent first; the render waits in the workspace.</value></data>
<data name="Errors.Workspace.SendFailed" xml:space="preserve"><value>Renders not sent: {0} of {1}; the job log says why.</value></data>
<data name="Errors.Workspace.SendMissing" xml:space="preserve"><value>{0} is no longer in the workspace's exports; it cannot be sent.</value></data>
<data name="Errors.Workspace.UnsentRenders" xml:space="preserve"><value>Some renders made here are not in the library yet: send them first, or discard them.</value></data>
<data name="Errors.Workspace.UnsentRenders.Server" xml:space="preserve"><value>Some renders made here are not on the server yet: send them first, or discard them.</value></data>
<data name="Errors.Workspace.TrashChanged" xml:space="preserve"><value>The workspace's trash changed after it was listed; nothing was erased: look at it again.</value></data>
<data name="Errors.Workspace.Moving" xml:space="preserve"><value>The workspace folder is being moved; try again once the move ends.</value></data>
<data name="Errors.Workspace.MoveTargetNotEmpty" xml:space="preserve"><value>{0} already holds a workspace or a project of this one: choose another folder.</value></data>
<data name="Errors.Workspace.MoveSameFolder" xml:space="preserve"><value>{0} is the workspace folder or lies inside it: choose a folder elsewhere.</value></data>
<data name="Errors.Workspace.JobsRunning" xml:space="preserve"><value>A workspace job is queued or running: move the folder once it ends.</value></data>
<data name="Errors.Workspace.MoveChanged" xml:space="preserve"><value>The workspace changed after its plan was shown; nothing was moved: plan the move again.</value></data>
<data name="Errors.Workspace.MoveVerify" xml:space="preserve"><value>{0} did not match its source after it was copied; the workspace stays where it was.</value></data>
<data name="Errors.Workspace.MoveNoRoom" xml:space="preserve"><value>The target drive needs {0} GB more for the workspace.</value></data>
</root>
+19
View File
@@ -187,4 +187,23 @@
<data name="Jobs.Target.Render" xml:space="preserve"><value>{0} → {1}</value><comment>invariant; {0} sequence title; {1} export preset</comment></data>
<data name="Jobs.Target.RenderRtl" xml:space="preserve"><value>{0} ← {1}</value><comment>invariant; right-to-left languages: the arrow points from the sequence to the preset</comment></data>
<data name="Jobs.Where.ThisPc" xml:space="preserve"><value>this PC</value></data>
<data name="Jobs.Kind.WorkspaceRender" xml:space="preserve"><value>Local render</value></data>
<data name="Jobs.Kind.WorkspaceSend" xml:space="preserve"><value>Send render</value></data>
<data name="Jobs.Kind.WorkspaceMove" xml:space="preserve"><value>Move workspace</value></data>
<data name="Jobs.Schedule.System.WorkspaceCleanup" xml:space="preserve"><value>Workspace clean-up</value></data>
<data name="Jobs.Schedule.Step.WorkspaceClean" xml:space="preserve"><value>Workspace media</value></data>
<data name="Jobs.Schedule.Step.WorkspaceTrash" xml:space="preserve"><value>Workspace trash</value></data>
<data name="Jobs.Log.WorkspaceCleaned" xml:space="preserve"><value>Workspace: projects cleaned: {0}, freed: {1}, kept: {2}</value><comment>long: job log line; {0} a count; {1} a size; {2} a count of projects kept, each logged with why</comment></data>
<data name="Jobs.Log.WorkspaceNothing" xml:space="preserve"><value>Workspace: {0} used, nothing to clean</value><comment>long: job log line; {0} a size</comment></data>
<data name="Jobs.Log.WorkspaceKept" xml:space="preserve"><value>Workspace: {0} kept: {1}</value><comment>long: job log line; {0} project name; {1} a reason, Jobs.Log.WorkspaceSkip.*</comment></data>
<data name="Jobs.Log.WorkspaceTrash" xml:space="preserve"><value>Workspace trash: items: {0}, size: {1}; nothing was deleted</value><comment>long: job log line</comment></data>
<data name="Jobs.Log.WorkspaceUnavailable" xml:space="preserve"><value>Workspace not cleaned: its folder cannot be read</value><comment>long: job log line</comment></data>
<data name="Jobs.Log.WorkspaceSkip.Open" xml:space="preserve"><value>open in Edit</value></data>
<data name="Jobs.Log.WorkspaceSkip.NotInSync" xml:space="preserve"><value>not in step with its home</value></data>
<data name="Jobs.Log.WorkspaceSkip.Offline" xml:space="preserve"><value>its home is out of reach</value></data>
<data name="Jobs.Log.WorkspaceSkip.Jobs" xml:space="preserve"><value>a job is using it</value></data>
<data name="Jobs.Log.WorkspaceSkip.UnsentRenders" xml:space="preserve"><value>renders not sent</value></data>
<data name="Jobs.Log.WorkspaceSkip.Unreadable" xml:space="preserve"><value>it cannot be read</value></data>
<data name="Jobs.Log.WorkspaceSkip.NoMedia" xml:space="preserve"><value>no media to remove</value></data>
<data name="Jobs.Log.WorkspaceSkip.JustCopied" xml:space="preserve"><value>just copied</value></data>
</root>
+2
View File
@@ -256,4 +256,6 @@
<data name="Server.Trust.Message" xml:space="preserve"><value>{0} uses a certificate Chronos does not know yet. Compare the fingerprint with the one in the server's admin panel before you trust it.</value><comment>long</comment></data>
<data name="Server.Trust.Title" xml:space="preserve"><value>Trust this server?</value></data>
<data name="Server.Version" xml:space="preserve"><value>v{0}</value></data>
<data name="Server.Error.ProjectMismatch" xml:space="preserve"><value>The project or version named with this render is not one of this sequence's.</value><comment>long</comment></data>
<data name="Server.PauseMeteredTransfers" xml:space="preserve"><value>Pause metered transfers</value></data>
</root>
+50
View File
@@ -212,4 +212,54 @@
<data name="Settings.Workspace.Use" xml:space="preserve"><value>Use folder</value></data>
<data name="Settings.Workspace.Versions.one" xml:space="preserve"><value>{0} version</value></data>
<data name="Settings.Workspace.Versions.other" xml:space="preserve"><value>{0} versions</value></data>
<data name="Settings.Workspace.TrashPlan.Title" xml:space="preserve"><value>Empty the workspace's trash?</value></data>
<data name="Settings.Workspace.TrashPlan.Message" xml:space="preserve"><value>What these entries kept, removed local copies and originals set aside among them, is erased for good; this cannot be undone.</value><comment>long</comment></data>
<data name="Settings.Workspace.TrashPlan.Items" xml:space="preserve"><value>Entries: {0}</value><comment>long; {0} a count</comment></data>
<data name="Settings.Workspace.TrashPlan.Size" xml:space="preserve"><value>Size: {0}</value><comment>long; {0} a size, &quot;1.2 GB&quot;</comment></data>
<data name="Settings.Workspace.TrashPlan.Item" xml:space="preserve"><value>{0} · {1} · {2}</value><comment>invariant; {0} entry name; {1} its size; {2} when it was put in the trash</comment></data>
<data name="Settings.Workspace.TrashPlan.Type" xml:space="preserve"><value>Type the number of entries, {0}, to confirm</value><comment>long; {0} a count</comment></data>
<data name="Settings.Workspace.TrashPlan.Action" xml:space="preserve"><value>Erase for good</value></data>
<data name="Settings.Workspace.TrashEmptied" xml:space="preserve"><value>Workspace trash emptied</value></data>
<data name="Settings.Workspace.TrashNotEmptied" xml:space="preserve"><value>Trash not emptied</value></data>
<data name="Settings.Workspace.Used" xml:space="preserve"><value>{0} used</value><comment>{0} a size, &quot;12.4 GB&quot;</comment></data>
<data name="Settings.Workspace.Measuring" xml:space="preserve"><value>Measuring…</value></data>
<data name="Settings.Workspace.Move" xml:space="preserve"><value>Move…</value></data>
<data name="Settings.Workspace.SizeLimit" xml:space="preserve"><value>Size limit</value></data>
<data name="Settings.Workspace.NoLimit" xml:space="preserve"><value>No limit</value></data>
<data name="Settings.Workspace.DefaultMedia" xml:space="preserve"><value>Default media</value></data>
<data name="Settings.Workspace.Proxies" xml:space="preserve"><value>Proxies</value></data>
<data name="Settings.Workspace.Originals" xml:space="preserve"><value>Originals</value></data>
<data name="Settings.Workspace.VersionOnRender" xml:space="preserve"><value>Version on render</value></data>
<data name="Settings.Workspace.SaveBeforeRender" xml:space="preserve"><value>Save before rendering</value></data>
<data name="Settings.Workspace.CleanAfter" xml:space="preserve"><value>Clean after</value></data>
<data name="Settings.Workspace.Never" xml:space="preserve"><value>Never</value></data>
<data name="Settings.Workspace.Days.one" xml:space="preserve"><value>{0} day</value></data>
<data name="Settings.Workspace.Days.other" xml:space="preserve"><value>{0} days</value></data>
<data name="Settings.Workspace.OpenProject" xml:space="preserve"><value>Open project</value></data>
<data name="Settings.Workspace.LastUsed" xml:space="preserve"><value>Last used</value></data>
<data name="Settings.Workspace.Main" xml:space="preserve"><value>Main</value></data>
<data name="Settings.Workspace.Ask" xml:space="preserve"><value>Ask</value></data>
<data name="Settings.Workspace.Trash" xml:space="preserve"><value>Trash</value></data>
<data name="Settings.Workspace.TrashItems.one" xml:space="preserve"><value>{0} item, {1}</value><comment>{1} a size, &quot;1.2 GB&quot;</comment></data>
<data name="Settings.Workspace.TrashItems.other" xml:space="preserve"><value>{0} items, {1}</value><comment>{1} a size, &quot;1.2 GB&quot;</comment></data>
<data name="Settings.Workspace.TrashIsEmpty" xml:space="preserve"><value>Nothing in trash</value></data>
<data name="Settings.Workspace.EmptyTrash" xml:space="preserve"><value>Empty…</value></data>
<data name="Settings.Workspace.MoveTitle" xml:space="preserve"><value>Choose where to move the workspace</value><comment>long: folder picker title</comment></data>
<data name="Settings.Workspace.MovePlan.Title" xml:space="preserve"><value>Move the workspace?</value></data>
<data name="Settings.Workspace.MovePlan.Message" xml:space="preserve"><value>The projects in {0} move to {1}, each file checked before its source is removed. Edit waits until the move ends.</value><comment>long; {0} the folder in use; {1} the folder chosen</comment></data>
<data name="Settings.Workspace.MovePlan.Projects" xml:space="preserve"><value>Projects: {0}</value><comment>long; {0} a count</comment></data>
<data name="Settings.Workspace.MovePlan.Files" xml:space="preserve"><value>Files: {0}</value><comment>long; {0} a count</comment></data>
<data name="Settings.Workspace.MovePlan.Size" xml:space="preserve"><value>Size: {0}</value><comment>long; {0} a size, &quot;1.2 GB&quot;</comment></data>
<data name="Settings.Workspace.MovePlan.Free" xml:space="preserve"><value>Free at target: {0}</value><comment>long; {0} a size, &quot;1.2 GB&quot;</comment></data>
<data name="Settings.Workspace.MovePlan.SameVolume" xml:space="preserve"><value>Same drive: folders renamed</value><comment>long</comment></data>
<data name="Settings.Workspace.MovePlan.OtherVolume" xml:space="preserve"><value>Other drive: files copied and checked</value><comment>long</comment></data>
<data name="Settings.Workspace.MovePlan.Unsent" xml:space="preserve"><value>Not sent yet: {0}</value><comment>long; {0} a count of projects</comment></data>
<data name="Settings.Workspace.MovePlan.Action" xml:space="preserve"><value>Move</value></data>
<data name="Settings.Workspace.MovePlan.Refused" xml:space="preserve"><value>Move not possible</value></data>
<data name="Settings.Workspace.Moving" xml:space="preserve"><value>Moving the workspace</value></data>
<data name="Settings.Workspace.Moved" xml:space="preserve"><value>Workspace moved</value></data>
<data name="Settings.Workspace.NotMoved" xml:space="preserve"><value>Workspace not moved</value></data>
<data name="Settings.Workspace.MoveUnfinished" xml:space="preserve"><value>Move not finished</value></data>
<data name="Settings.Workspace.MoveUnfinishedMessage" xml:space="preserve"><value>A move of the workspace to {0} stopped before it ended; its projects are still in {1}.</value><comment>long; {0} the target folder; {1} the folder in use</comment></data>
<data name="Settings.Workspace.ResumeMove" xml:space="preserve"><value>Resume</value></data>
</root>
+54
View File
@@ -937,4 +937,58 @@
<data name="Tooltips.Window.Maximize" xml:space="preserve"><value>Maximize</value></data>
<data name="Tooltips.Window.Minimize" xml:space="preserve"><value>Minimize</value></data>
<data name="Tooltips.Window.Restore" xml:space="preserve"><value>Restore</value></data>
<data name="Tooltips.Editor.OpenWorkspace.OriginalsSize" xml:space="preserve"><value>What the copy of the originals writes into the workspace besides the proxies, as reckoned before it starts</value></data>
<data name="Tooltips.Editor.OpenWorkspace.OriginalsReady" xml:space="preserve"><value>Copy the proxies and the originals: renders then run on this PC, from the workspace; it takes the most space</value></data>
<data name="Tooltips.Editor.OpenWorkspace.OriginalsReady.Server" xml:space="preserve"><value>Download the server's proxies and originals: renders then run on this PC, from the workspace; it takes the most space</value></data>
<data name="Tooltips.Editor.OpenWorkspace.NoRoomOriginals" xml:space="preserve"><value>The drive of the workspace folder lacks room for the originals and the 0.5 GB the copy keeps free: copy the proxies, or free some space</value></data>
<data name="Tooltips.Editor.Project.CopyOriginals" xml:space="preserve"><value>Copy this project's originals from the library into the workspace, to render on this PC</value></data>
<data name="Tooltips.Editor.Project.CopyOriginals.Server" xml:space="preserve"><value>Download this project's originals from the server into the workspace, to render on this PC</value></data>
<data name="Tooltips.Editor.Project.ProxiesOnly" xml:space="preserve"><value>Free this PC's space: delete the originals copied to the workspace once the library is checked to hold each one; the proxies stay</value></data>
<data name="Tooltips.Editor.Project.ProxiesOnly.Server" xml:space="preserve"><value>Free this PC's space: delete the originals downloaded to the workspace once the server is checked to hold each one; the proxies stay</value></data>
<data name="Tooltips.Editor.Project.MediaBusy" xml:space="preserve"><value>Save your changes as a version and wait for this project's jobs to end first</value></data>
<data name="Tooltips.Editor.ProxiesOnly.ToTrash" xml:space="preserve"><value>Originals the library no longer holds as they are here: they go to the workspace's trash, not deleted</value></data>
<data name="Tooltips.Editor.ProxiesOnly.ToTrash.Server" xml:space="preserve"><value>Originals the server no longer holds as they are here: they go to the workspace's trash, not deleted</value></data>
<data name="Tooltips.Editor.ProxiesOnly.Action" xml:space="preserve"><value>Delete the originals listed from the workspace; the proxies and the project stay</value></data>
<data name="Tooltips.Editor.ProxiesOnly.Keep" xml:space="preserve"><value>Keep the originals in the workspace</value></data>
<data name="Tooltips.Editor.Workspace.OriginalsMissing" xml:space="preserve"><value>The library had no original of these frames: they stay proxies here, and a local render waits until they are copied</value></data>
<data name="Tooltips.Editor.Workspace.OriginalsMissing.Server" xml:space="preserve"><value>The server had no original of these frames (or your account cannot read them): they stay proxies here</value></data>
<data name="Tooltips.Editor.Workspace.Media.Proxies" xml:space="preserve"><value>The workspace holds the proxies of this project: renders run where the originals are</value></data>
<data name="Tooltips.Editor.Workspace.Media.Originals" xml:space="preserve"><value>The workspace holds the proxies and the originals of this project: renders run on this PC</value></data>
<data name="Tooltips.Editor.OpenProject.Choose" xml:space="preserve"><value>Open this project of the sequence; Settings › Workspace › Open project says whether Edit asks</value></data>
<data name="Tooltips.Editor.Render.Local" xml:space="preserve"><value>Rendered on this PC from the workspace's originals; the file is in the project's exports folder</value></data>
<data name="Tooltips.Editor.Render.NotSent" xml:space="preserve"><value>Rendered on this PC, not in the library yet: it is sent with the next send; the file stays in the workspace</value></data>
<data name="Tooltips.Editor.Render.NotSent.Server" xml:space="preserve"><value>Rendered on this PC, not on the server yet: it is sent with the next send; the file stays in the workspace</value></data>
<data name="Tooltips.Editor.Render.SendAgain" xml:space="preserve"><value>Send the renders made here that the library does not have yet</value></data>
<data name="Tooltips.Editor.Render.SendAgain.Server" xml:space="preserve"><value>Send the renders made here that the server does not have yet</value></data>
<data name="Tooltips.Server.PauseMeteredTransfers" xml:space="preserve"><value>Pause uploads and downloads with the server, workspace copies and renders sent among them, while Windows reports this connection as metered</value></data>
<data name="Tooltips.Jobs.Schedule.Step.WorkspaceClean" xml:space="preserve"><value>Removes the media of workspace projects in step with their home: unopened past Clean after, or the oldest past Size limit</value></data>
<data name="Tooltips.Jobs.Schedule.Step.WorkspaceTrash" xml:space="preserve"><value>Lists what the workspace's trash holds; nothing is deleted</value></data>
<data name="Tooltips.Editor.RemoveCopy.UnsentRenders" xml:space="preserve"><value>Renders made on this PC that the library does not have yet: Send first sends them, Discard keeps them in the workspace's trash</value></data>
<data name="Tooltips.Editor.RemoveCopy.UnsentRenders.Server" xml:space="preserve"><value>Renders made on this PC that the server does not have yet: Send first sends them, Discard keeps them in the workspace's trash</value></data>
<data name="Tooltips.Editor.RemoveCopy.LastOriginals" xml:space="preserve"><value>Originals the library no longer holds as they are here: they go to the workspace's trash, not deleted</value></data>
<data name="Tooltips.Editor.RemoveCopy.LastOriginals.Server" xml:space="preserve"><value>Originals the server no longer holds as they are here: they go to the workspace's trash, not deleted</value></data>
<data name="Tooltips.Settings.Workspace.TrashPlan.Action" xml:space="preserve"><value>Erase every entry listed from the workspace's trash, for good; type their number above first</value></data>
<data name="Tooltips.Settings.Workspace.TrashPlan.Keep" xml:space="preserve"><value>Keep the workspace's trash as it is</value></data>
<data name="Tooltips.Settings.Workspace.Used" xml:space="preserve"><value>What the workspace folder takes on its drive, its trash included</value></data>
<data name="Tooltips.Settings.Workspace.Folder" xml:space="preserve"><value>The workspace's folder (a fast disk is best); Change uses another one, Move takes the projects along</value></data>
<data name="Tooltips.Settings.Workspace.Move" xml:space="preserve"><value>Move the workspace folder with its projects to another folder, after a plan; each file is checked before its source goes</value></data>
<data name="Tooltips.Settings.Workspace.SizeLimit" xml:space="preserve"><value>Past this size, the media of the projects used longest ago are removed once they are in step with their home; their versions stay</value></data>
<data name="Tooltips.Settings.Workspace.NoLimit" xml:space="preserve"><value>The workspace grows as needed; only Clean after removes media</value></data>
<data name="Tooltips.Settings.Workspace.DefaultMedia" xml:space="preserve"><value>What Open in workspace copies unless you choose otherwise there</value></data>
<data name="Tooltips.Settings.Workspace.Proxies" xml:space="preserve"><value>Copy the proxies: light and fast to edit; renders run where the originals are</value></data>
<data name="Tooltips.Settings.Workspace.Originals" xml:space="preserve"><value>Copy the originals too, to render on this PC; it takes the most space</value></data>
<data name="Tooltips.Settings.Workspace.VersionOnRender" xml:space="preserve"><value>A render first saves your changes as a version (sent at once when Sync is on), so the render names the version it shows</value></data>
<data name="Tooltips.Settings.Workspace.CleanAfter" xml:space="preserve"><value>Remove the media of projects not opened for this long, once they are in step with their home; opening one copies them again</value></data>
<data name="Tooltips.Settings.Workspace.Never" xml:space="preserve"><value>Media stay until you remove them, or Size limit does</value></data>
<data name="Tooltips.Settings.Workspace.OpenProject" xml:space="preserve"><value>Which project Edit opens for a sequence with several in the workspace</value></data>
<data name="Tooltips.Settings.Workspace.LastUsed" xml:space="preserve"><value>The project you opened last for the sequence</value></data>
<data name="Tooltips.Settings.Workspace.Main" xml:space="preserve"><value>The sequence's Main project, which holds its own settings</value></data>
<data name="Tooltips.Settings.Workspace.Ask" xml:space="preserve"><value>List the sequence's projects each time</value></data>
<data name="Tooltips.Settings.Workspace.Trash" xml:space="preserve"><value>What removed local copies and the clean-up kept aside; only Empty… erases it</value></data>
<data name="Tooltips.Settings.Workspace.EmptyTrash" xml:space="preserve"><value>Erase the workspace's trash for good, after a list of what it holds and a typed confirmation</value></data>
<data name="Tooltips.Settings.Workspace.EmptyTrash.Disabled" xml:space="preserve"><value>The workspace's trash is empty</value></data>
<data name="Tooltips.Settings.Workspace.MovePlan.Unsent" xml:space="preserve"><value>Projects with versions, changes or renders not at their home: they move with the rest, nothing is lost</value></data>
<data name="Tooltips.Settings.Workspace.MovePlan.Action" xml:space="preserve"><value>Queue the move: the projects are moved or copied and checked, then Edit uses the new folder</value></data>
<data name="Tooltips.Settings.Workspace.MovePlan.Keep" xml:space="preserve"><value>Keep the workspace where it is</value></data>
<data name="Tooltips.Settings.Workspace.ResumeMove" xml:space="preserve"><value>Queue the move again: it takes up from its journal, nothing is copied twice</value></data>
</root>
+10
View File
@@ -425,4 +425,14 @@
<data name="Archive.View.Health" xml:space="preserve"><value>Stato</value></data>
<data name="Archive.View.Name" xml:space="preserve"><value>Vista</value></data>
<data name="Archive.View.Overview" xml:space="preserve"><value>Panoramica</value></data>
<data name="Archive.Log.WorkspaceOriginals" xml:space="preserve"><value>{0}: originali copiati: {1}, invariati: {2}, assenti: {3}</value></data>
<data name="Archive.Log.WorkspaceOriginalsDownloaded" xml:space="preserve"><value>{0}: originali scaricati: {1}, invariati: {2}, assenti: {3}</value></data>
<data name="Archive.Log.WorkspaceOriginalMissing" xml:space="preserve"><value>{0}: il fotogramma {1} non ha l'originale all'origine; resta il suo proxy</value></data>
<data name="Archive.Log.WorkspaceOriginalsTrashed" xml:space="preserve"><value>{0}: originali che l'origine non ha più, tenuti nel cestino: {1}</value></data>
<data name="Archive.Log.WorkspaceSent" xml:space="preserve"><value>{0}: render inviati: {1}, già presenti: {2}</value></data>
<data name="Archive.Log.WorkspaceVersionPushed" xml:space="preserve"><value>{0}: versione {1} inviata prima, per il suo render</value></data>
<data name="Archive.Log.WorkspaceSendHeld" xml:space="preserve"><value>In attesa finché la connessione è a consumo</value></data>
<data name="Archive.Log.WorkspaceMoved" xml:space="preserve"><value>Spazio di lavoro spostato in {0}: progetti: {1}, file: {2}</value></data>
<data name="Archive.Log.WorkspaceMoveResumed" xml:space="preserve"><value>Spostamento ripreso dal suo registro: {0}</value></data>
<data name="Archive.Log.WorkspaceMoveProject" xml:space="preserve"><value>Spostato: {0}</value></data>
</root>
+32
View File
@@ -422,4 +422,36 @@
<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>
<data name="Editor.OpenWorkspace.OriginalsSize" xml:space="preserve"><value>Originali: {0}</value></data>
<data name="Editor.Project.CopyOriginals" xml:space="preserve"><value>Copia originali…</value></data>
<data name="Editor.Project.ProxiesOnly" xml:space="preserve"><value>Solo proxy…</value></data>
<data name="Editor.ProxiesOnly.Title" xml:space="preserve"><value>Solo proxy per {0}</value></data>
<data name="Editor.ProxiesOnly.Message" xml:space="preserve"><value>Gli originali copiati su questo PC vengono eliminati dopo aver verificato che la libreria li abbia tutti; i render avvengono poi dove sono gli originali.</value></data>
<data name="Editor.ProxiesOnly.Message.Server" xml:space="preserve"><value>Gli originali scaricati su questo PC vengono eliminati dopo aver verificato che il server li abbia tutti; i render avvengono poi sul server.</value></data>
<data name="Editor.ProxiesOnly.Originals" xml:space="preserve"><value>Originali: {0}</value></data>
<data name="Editor.ProxiesOnly.Size" xml:space="preserve"><value>Dimensione: {0}</value></data>
<data name="Editor.ProxiesOnly.ToTrash" xml:space="preserve"><value>Tenuti nel cestino: {0}</value></data>
<data name="Editor.ProxiesOnly.Action" xml:space="preserve"><value>Elimina originali</value></data>
<data name="Editor.Workspace.CopyingOriginals" xml:space="preserve"><value>Copia degli originali</value></data>
<data name="Editor.Workspace.OriginalsCopied" xml:space="preserve"><value>Originali copiati</value></data>
<data name="Editor.Workspace.OriginalsRemoved" xml:space="preserve"><value>Originali rimossi</value></data>
<data name="Editor.Workspace.OriginalsNotRemoved" xml:space="preserve"><value>Originali non rimossi</value></data>
<data name="Editor.Workspace.OriginalsMissing" xml:space="preserve"><value>Senza originale: {0}</value></data>
<data name="Editor.Workspace.Media.Proxies" xml:space="preserve"><value>Proxy</value></data>
<data name="Editor.Workspace.Media.Originals" xml:space="preserve"><value>Originali</value></data>
<data name="Editor.OpenProject.Title" xml:space="preserve"><value>Quale progetto aprire?</value></data>
<data name="Editor.OpenProject.Message" xml:space="preserve"><value>{0} ha più progetti nello spazio di lavoro: scegli quello da aprire.</value></data>
<data name="Editor.Render.QueuedLocal" xml:space="preserve"><value>Render in coda su questo PC</value></data>
<data name="Editor.Render.Local" xml:space="preserve"><value>Su questo PC</value></data>
<data name="Editor.Render.SentHome" xml:space="preserve"><value>Render inviato</value></data>
<data name="Editor.Render.SentTo" xml:space="preserve"><value>{0} è nella libreria</value></data>
<data name="Editor.Render.SentTo.Server" xml:space="preserve"><value>{0} è sul server</value></data>
<data name="Editor.Render.NotSent" xml:space="preserve"><value>Non inviato</value></data>
<data name="Editor.Render.SendFailed" xml:space="preserve"><value>Render non inviato</value></data>
<data name="Editor.Render.SendAgain" xml:space="preserve"><value>Invia di nuovo</value></data>
<data name="Editor.Render.Sending" xml:space="preserve"><value>Invio del render</value></data>
<data name="Editor.Workspace.RenderNote" xml:space="preserve"><value>Render</value></data>
<data name="Editor.Workspace.SavedForRender" xml:space="preserve"><value>Versione {0} salvata per il render</value></data>
<data name="Editor.RemoveCopy.UnsentRenders" xml:space="preserve"><value>Render non inviati</value></data>
<data name="Editor.RemoveCopy.LastOriginals" xml:space="preserve"><value>Ultimi originali</value></data>
</root>
+24
View File
@@ -90,4 +90,28 @@
<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>
<data name="Errors.Workspace.JobParameters" xml:space="preserve"><value>Questa attività dello spazio di lavoro non ha parametri validi.</value></data>
<data name="Errors.Workspace.OriginalsMissing" xml:space="preserve"><value>Lo spazio di lavoro non ha gli originali di questo progetto: Copia originali… li copia dalla libreria.</value></data>
<data name="Errors.Workspace.OriginalsMissing.Server" xml:space="preserve"><value>Lo spazio di lavoro non ha gli originali di questo progetto: Copia originali… li scarica dal server.</value></data>
<data name="Errors.Workspace.OriginalMismatch" xml:space="preserve"><value>L'originale {0} non corrispondeva al suo SHA-256 dopo la copia; non è stato tenuto.</value></data>
<data name="Errors.Workspace.OriginalsCheck" xml:space="preserve"><value>Non si raggiunge la libreria per verificare gli originali; non è stato rimosso nulla.</value></data>
<data name="Errors.Workspace.OriginalsCheck.Server" xml:space="preserve"><value>Non si raggiunge il server per verificare gli originali; non è stato rimosso nulla.</value></data>
<data name="Errors.Workspace.MediaBusy" xml:space="preserve"><value>Salva le modifiche come versione e attendi la fine delle attività di questo progetto prima di cambiarne i media.</value></data>
<data name="Errors.Workspace.RenderNoOriginals" xml:space="preserve"><value>Fotogrammi senza originale nello spazio di lavoro: {0}. Copia originali… li copia, poi renderizza di nuovo.</value></data>
<data name="Errors.Workspace.RenderVersion" xml:space="preserve"><value>La versione da renderizzare non è nello spazio di lavoro: sincronizza il progetto, poi renderizza di nuovo.</value></data>
<data name="Errors.Workspace.RenderProject" xml:space="preserve"><value>Il progetto da renderizzare non è più nello spazio di lavoro.</value></data>
<data name="Errors.Workspace.SendHashMismatch" xml:space="preserve"><value>{0} è cambiato dopo il render: non è stato inviato e resta nello spazio di lavoro.</value></data>
<data name="Errors.Workspace.SendVersion" xml:space="preserve"><value>Non è stato possibile inviare prima la versione da cui è stato fatto questo render; il render attende nello spazio di lavoro.</value></data>
<data name="Errors.Workspace.SendFailed" xml:space="preserve"><value>Render non inviati: {0} di {1}; il log dell'attività dice perché.</value></data>
<data name="Errors.Workspace.SendMissing" xml:space="preserve"><value>{0} non è più negli export dello spazio di lavoro; non si può inviare.</value></data>
<data name="Errors.Workspace.UnsentRenders" xml:space="preserve"><value>Alcuni render fatti qui non sono ancora nella libreria: prima inviali oppure scartali.</value></data>
<data name="Errors.Workspace.UnsentRenders.Server" xml:space="preserve"><value>Alcuni render fatti qui non sono ancora sul server: prima inviali oppure scartali.</value></data>
<data name="Errors.Workspace.TrashChanged" xml:space="preserve"><value>Il cestino dello spazio di lavoro è cambiato dopo l'elenco; non è stato eliminato nulla: guardalo di nuovo.</value></data>
<data name="Errors.Workspace.Moving" xml:space="preserve"><value>La cartella dello spazio di lavoro è in spostamento; riprova a spostamento finito.</value></data>
<data name="Errors.Workspace.MoveTargetNotEmpty" xml:space="preserve"><value>{0} contiene già uno spazio di lavoro o un progetto di questo: scegli un'altra cartella.</value></data>
<data name="Errors.Workspace.MoveSameFolder" xml:space="preserve"><value>{0} è la cartella dello spazio di lavoro o si trova al suo interno: scegli una cartella altrove.</value></data>
<data name="Errors.Workspace.JobsRunning" xml:space="preserve"><value>Un'attività dello spazio di lavoro è in coda o in corso: sposta la cartella quando finisce.</value></data>
<data name="Errors.Workspace.MoveChanged" xml:space="preserve"><value>Lo spazio di lavoro è cambiato dopo che il piano è stato mostrato; non è stato spostato nulla: pianifica di nuovo.</value></data>
<data name="Errors.Workspace.MoveVerify" xml:space="preserve"><value>{0} non corrispondeva alla sua origine dopo la copia; lo spazio di lavoro resta dov'era.</value></data>
<data name="Errors.Workspace.MoveNoRoom" xml:space="preserve"><value>Al disco di destinazione servono altri {0} GB per lo spazio di lavoro.</value></data>
</root>
+19
View File
@@ -185,4 +185,23 @@
<data name="Jobs.Tab.Queue" xml:space="preserve"><value>Coda</value></data>
<data name="Jobs.Tab.Scheduled" xml:space="preserve"><value>Pianificate</value></data>
<data name="Jobs.Where.ThisPc" xml:space="preserve"><value>questo PC</value></data>
<data name="Jobs.Kind.WorkspaceRender" xml:space="preserve"><value>Rendering locale</value></data>
<data name="Jobs.Kind.WorkspaceSend" xml:space="preserve"><value>Invio rendering</value></data>
<data name="Jobs.Kind.WorkspaceMove" xml:space="preserve"><value>Sposta spazio di lavoro</value></data>
<data name="Jobs.Schedule.System.WorkspaceCleanup" xml:space="preserve"><value>Pulizia spazio di lavoro</value></data>
<data name="Jobs.Schedule.Step.WorkspaceClean" xml:space="preserve"><value>Media spazio di lavoro</value></data>
<data name="Jobs.Schedule.Step.WorkspaceTrash" xml:space="preserve"><value>Cestino spazio di lavoro</value></data>
<data name="Jobs.Log.WorkspaceCleaned" xml:space="preserve"><value>Spazio di lavoro: progetti puliti: {0}, liberati: {1}, tenuti: {2}</value></data>
<data name="Jobs.Log.WorkspaceNothing" xml:space="preserve"><value>Spazio di lavoro: {0} usati, niente da pulire</value></data>
<data name="Jobs.Log.WorkspaceKept" xml:space="preserve"><value>Spazio di lavoro: {0} tenuto: {1}</value></data>
<data name="Jobs.Log.WorkspaceTrash" xml:space="preserve"><value>Cestino dello spazio di lavoro: elementi: {0}, dimensione: {1}; non è stato eliminato nulla</value></data>
<data name="Jobs.Log.WorkspaceUnavailable" xml:space="preserve"><value>Spazio di lavoro non pulito: la sua cartella non è leggibile</value></data>
<data name="Jobs.Log.WorkspaceSkip.Open" xml:space="preserve"><value>aperto in Modifica</value></data>
<data name="Jobs.Log.WorkspaceSkip.NotInSync" xml:space="preserve"><value>non allineato con l'origine</value></data>
<data name="Jobs.Log.WorkspaceSkip.Offline" xml:space="preserve"><value>origine non raggiungibile</value></data>
<data name="Jobs.Log.WorkspaceSkip.Jobs" xml:space="preserve"><value>un'attività lo sta usando</value></data>
<data name="Jobs.Log.WorkspaceSkip.UnsentRenders" xml:space="preserve"><value>render non inviati</value></data>
<data name="Jobs.Log.WorkspaceSkip.Unreadable" xml:space="preserve"><value>non leggibile</value></data>
<data name="Jobs.Log.WorkspaceSkip.NoMedia" xml:space="preserve"><value>nessun media da rimuovere</value></data>
<data name="Jobs.Log.WorkspaceSkip.JustCopied" xml:space="preserve"><value>appena copiato</value></data>
</root>
+2
View File
@@ -253,4 +253,6 @@
<data name="Server.Trust.Message" xml:space="preserve"><value>{0} usa un certificato che Chronos non conosce ancora. Confronta l'impronta con quella del pannello di amministrazione del server prima di considerarlo attendibile.</value></data>
<data name="Server.Trust.Title" xml:space="preserve"><value>Ti fidi di questo server?</value></data>
<data name="Server.Version" xml:space="preserve"><value>v{0}</value></data>
<data name="Server.Error.ProjectMismatch" xml:space="preserve"><value>Il progetto o la versione indicati con questo render non sono di questa sequenza.</value></data>
<data name="Server.PauseMeteredTransfers" xml:space="preserve"><value>Pausa trasferimenti a consumo</value></data>
</root>
+50
View File
@@ -209,4 +209,54 @@
<data name="Settings.Workspace.Use" xml:space="preserve"><value>Usa cartella</value></data>
<data name="Settings.Workspace.Versions.one" xml:space="preserve"><value>{0} versione</value></data>
<data name="Settings.Workspace.Versions.other" xml:space="preserve"><value>{0} versioni</value></data>
<data name="Settings.Workspace.TrashPlan.Title" xml:space="preserve"><value>Svuotare il cestino?</value></data>
<data name="Settings.Workspace.TrashPlan.Message" xml:space="preserve"><value>Ciò che queste voci tenevano, comprese copie locali rimosse e originali messi da parte, viene eliminato per sempre; non si può annullare.</value></data>
<data name="Settings.Workspace.TrashPlan.Items" xml:space="preserve"><value>Voci: {0}</value></data>
<data name="Settings.Workspace.TrashPlan.Size" xml:space="preserve"><value>Dimensione: {0}</value></data>
<data name="Settings.Workspace.TrashPlan.Item" xml:space="preserve"><value>{0} · {1} · {2}</value></data>
<data name="Settings.Workspace.TrashPlan.Type" xml:space="preserve"><value>Scrivi il numero di voci, {0}, per confermare</value></data>
<data name="Settings.Workspace.TrashPlan.Action" xml:space="preserve"><value>Elimina per sempre</value></data>
<data name="Settings.Workspace.TrashEmptied" xml:space="preserve"><value>Cestino svuotato</value></data>
<data name="Settings.Workspace.TrashNotEmptied" xml:space="preserve"><value>Cestino non svuotato</value></data>
<data name="Settings.Workspace.Used" xml:space="preserve"><value>{0} usati</value></data>
<data name="Settings.Workspace.Measuring" xml:space="preserve"><value>Misura in corso…</value></data>
<data name="Settings.Workspace.Move" xml:space="preserve"><value>Sposta…</value></data>
<data name="Settings.Workspace.SizeLimit" xml:space="preserve"><value>Limite dimensione</value></data>
<data name="Settings.Workspace.NoLimit" xml:space="preserve"><value>Nessun limite</value></data>
<data name="Settings.Workspace.DefaultMedia" xml:space="preserve"><value>Media predefiniti</value></data>
<data name="Settings.Workspace.Proxies" xml:space="preserve"><value>Proxy</value></data>
<data name="Settings.Workspace.Originals" xml:space="preserve"><value>Originali</value></data>
<data name="Settings.Workspace.VersionOnRender" xml:space="preserve"><value>Versione al render</value></data>
<data name="Settings.Workspace.SaveBeforeRender" xml:space="preserve"><value>Salva prima del render</value></data>
<data name="Settings.Workspace.CleanAfter" xml:space="preserve"><value>Pulisci dopo</value></data>
<data name="Settings.Workspace.Never" xml:space="preserve"><value>Mai</value></data>
<data name="Settings.Workspace.Days.one" xml:space="preserve"><value>{0} giorno</value></data>
<data name="Settings.Workspace.Days.other" xml:space="preserve"><value>{0} giorni</value></data>
<data name="Settings.Workspace.OpenProject" xml:space="preserve"><value>Apri progetto</value></data>
<data name="Settings.Workspace.LastUsed" xml:space="preserve"><value>Ultimo usato</value></data>
<data name="Settings.Workspace.Main" xml:space="preserve"><value>Principale</value></data>
<data name="Settings.Workspace.Ask" xml:space="preserve"><value>Chiedi</value></data>
<data name="Settings.Workspace.Trash" xml:space="preserve"><value>Cestino</value></data>
<data name="Settings.Workspace.TrashItems.one" xml:space="preserve"><value>{0} elemento, {1}</value></data>
<data name="Settings.Workspace.TrashItems.other" xml:space="preserve"><value>{0} elementi, {1}</value></data>
<data name="Settings.Workspace.TrashIsEmpty" xml:space="preserve"><value>Cestino vuoto</value></data>
<data name="Settings.Workspace.EmptyTrash" xml:space="preserve"><value>Svuota…</value></data>
<data name="Settings.Workspace.MoveTitle" xml:space="preserve"><value>Scegli dove spostare lo spazio di lavoro</value></data>
<data name="Settings.Workspace.MovePlan.Title" xml:space="preserve"><value>Spostare lo spazio di lavoro?</value></data>
<data name="Settings.Workspace.MovePlan.Message" xml:space="preserve"><value>I progetti in {0} vanno in {1}, ogni file verificato prima di rimuoverne l'origine. Modifica attende la fine dello spostamento.</value></data>
<data name="Settings.Workspace.MovePlan.Projects" xml:space="preserve"><value>Progetti: {0}</value></data>
<data name="Settings.Workspace.MovePlan.Files" xml:space="preserve"><value>File: {0}</value></data>
<data name="Settings.Workspace.MovePlan.Size" xml:space="preserve"><value>Dimensione: {0}</value></data>
<data name="Settings.Workspace.MovePlan.Free" xml:space="preserve"><value>Libero alla meta: {0}</value></data>
<data name="Settings.Workspace.MovePlan.SameVolume" xml:space="preserve"><value>Stesso disco: cartelle rinominate</value></data>
<data name="Settings.Workspace.MovePlan.OtherVolume" xml:space="preserve"><value>Altro disco: file copiati e verificati</value></data>
<data name="Settings.Workspace.MovePlan.Unsent" xml:space="preserve"><value>Non ancora inviati: {0}</value></data>
<data name="Settings.Workspace.MovePlan.Action" xml:space="preserve"><value>Sposta</value></data>
<data name="Settings.Workspace.MovePlan.Refused" xml:space="preserve"><value>Spostamento non possibile</value></data>
<data name="Settings.Workspace.Moving" xml:space="preserve"><value>Spostamento in corso</value></data>
<data name="Settings.Workspace.Moved" xml:space="preserve"><value>Spazio di lavoro spostato</value></data>
<data name="Settings.Workspace.NotMoved" xml:space="preserve"><value>Spazio di lavoro non spostato</value></data>
<data name="Settings.Workspace.MoveUnfinished" xml:space="preserve"><value>Spostamento non finito</value></data>
<data name="Settings.Workspace.MoveUnfinishedMessage" xml:space="preserve"><value>Uno spostamento dello spazio di lavoro in {0} si è fermato prima della fine; i progetti sono ancora in {1}.</value></data>
<data name="Settings.Workspace.ResumeMove" xml:space="preserve"><value>Riprendi</value></data>
</root>
+54
View File
@@ -935,4 +935,58 @@
<data name="Tooltips.Window.Maximize" xml:space="preserve"><value>Ingrandisci</value></data>
<data name="Tooltips.Window.Minimize" xml:space="preserve"><value>Riduci a icona</value></data>
<data name="Tooltips.Window.Restore" xml:space="preserve"><value>Ripristina</value></data>
<data name="Tooltips.Editor.OpenWorkspace.OriginalsSize" xml:space="preserve"><value>Quanto scrive nello spazio di lavoro la copia degli originali oltre ai proxy, stimato prima che inizi</value></data>
<data name="Tooltips.Editor.OpenWorkspace.OriginalsReady" xml:space="preserve"><value>Copia i proxy e gli originali: i render avvengono poi su questo PC, dallo spazio di lavoro; occupa più spazio</value></data>
<data name="Tooltips.Editor.OpenWorkspace.OriginalsReady.Server" xml:space="preserve"><value>Scarica i proxy e gli originali del server: i render avvengono poi su questo PC, dallo spazio di lavoro; occupa più spazio</value></data>
<data name="Tooltips.Editor.OpenWorkspace.NoRoomOriginals" xml:space="preserve"><value>Al disco della cartella dello spazio di lavoro manca spazio per gli originali e per gli 0,5 GB che la copia lascia liberi: copia i proxy o libera spazio</value></data>
<data name="Tooltips.Editor.Project.CopyOriginals" xml:space="preserve"><value>Copia gli originali di questo progetto dalla libreria nello spazio di lavoro, per renderizzare su questo PC</value></data>
<data name="Tooltips.Editor.Project.CopyOriginals.Server" xml:space="preserve"><value>Scarica gli originali di questo progetto dal server nello spazio di lavoro, per renderizzare su questo PC</value></data>
<data name="Tooltips.Editor.Project.ProxiesOnly" xml:space="preserve"><value>Libera spazio su questo PC: elimina gli originali copiati nello spazio di lavoro dopo aver verificato che la libreria li abbia tutti; i proxy restano</value></data>
<data name="Tooltips.Editor.Project.ProxiesOnly.Server" xml:space="preserve"><value>Libera spazio su questo PC: elimina gli originali scaricati nello spazio di lavoro dopo aver verificato che il server li abbia tutti; i proxy restano</value></data>
<data name="Tooltips.Editor.Project.MediaBusy" xml:space="preserve"><value>Prima salva le modifiche come versione e attendi la fine delle attività di questo progetto</value></data>
<data name="Tooltips.Editor.ProxiesOnly.ToTrash" xml:space="preserve"><value>Originali che la libreria non ha più come sono qui: vanno nel cestino dello spazio di lavoro, non vengono eliminati</value></data>
<data name="Tooltips.Editor.ProxiesOnly.ToTrash.Server" xml:space="preserve"><value>Originali che il server non ha più come sono qui: vanno nel cestino dello spazio di lavoro, non vengono eliminati</value></data>
<data name="Tooltips.Editor.ProxiesOnly.Action" xml:space="preserve"><value>Elimina dallo spazio di lavoro gli originali elencati; i proxy e il progetto restano</value></data>
<data name="Tooltips.Editor.ProxiesOnly.Keep" xml:space="preserve"><value>Tieni gli originali nello spazio di lavoro</value></data>
<data name="Tooltips.Editor.Workspace.OriginalsMissing" xml:space="preserve"><value>La libreria non aveva l'originale di questi fotogrammi: qui restano proxy, e un render locale attende finché non vengono copiati</value></data>
<data name="Tooltips.Editor.Workspace.OriginalsMissing.Server" xml:space="preserve"><value>Il server non aveva l'originale di questi fotogrammi (o il tuo account non può leggerli): qui restano proxy</value></data>
<data name="Tooltips.Editor.Workspace.Media.Proxies" xml:space="preserve"><value>Lo spazio di lavoro contiene i proxy di questo progetto: i render avvengono dove sono gli originali</value></data>
<data name="Tooltips.Editor.Workspace.Media.Originals" xml:space="preserve"><value>Lo spazio di lavoro contiene i proxy e gli originali di questo progetto: i render avvengono su questo PC</value></data>
<data name="Tooltips.Editor.OpenProject.Choose" xml:space="preserve"><value>Apri questo progetto della sequenza; Impostazioni › Spazio di lavoro › Apri progetto dice se Modifica lo chiede</value></data>
<data name="Tooltips.Editor.Render.Local" xml:space="preserve"><value>Renderizzato su questo PC dagli originali dello spazio di lavoro; il file è nella cartella exports del progetto</value></data>
<data name="Tooltips.Editor.Render.NotSent" xml:space="preserve"><value>Renderizzato su questo PC, non ancora nella libreria: viene inviato col prossimo invio; il file resta nello spazio di lavoro</value></data>
<data name="Tooltips.Editor.Render.NotSent.Server" xml:space="preserve"><value>Renderizzato su questo PC, non ancora sul server: viene inviato col prossimo invio; il file resta nello spazio di lavoro</value></data>
<data name="Tooltips.Editor.Render.SendAgain" xml:space="preserve"><value>Invia i render fatti qui che la libreria non ha ancora</value></data>
<data name="Tooltips.Editor.Render.SendAgain.Server" xml:space="preserve"><value>Invia i render fatti qui che il server non ha ancora</value></data>
<data name="Tooltips.Server.PauseMeteredTransfers" xml:space="preserve"><value>Mette in pausa caricamenti e download col server, comprese copie dello spazio di lavoro e render inviati, mentre Windows segnala la connessione a consumo</value></data>
<data name="Tooltips.Jobs.Schedule.Step.WorkspaceClean" xml:space="preserve"><value>Rimuove i media dei progetti allineati con la loro origine: non aperti oltre Pulisci dopo, o i più vecchi oltre Limite dimensione</value></data>
<data name="Tooltips.Jobs.Schedule.Step.WorkspaceTrash" xml:space="preserve"><value>Elenca cosa contiene il cestino dello spazio di lavoro; non elimina niente</value></data>
<data name="Tooltips.Editor.RemoveCopy.UnsentRenders" xml:space="preserve"><value>Render fatti su questo PC che la libreria non ha ancora: Prima invia li invia, Scarta li tiene nel cestino dello spazio di lavoro</value></data>
<data name="Tooltips.Editor.RemoveCopy.UnsentRenders.Server" xml:space="preserve"><value>Render fatti su questo PC che il server non ha ancora: Prima invia li invia, Scarta li tiene nel cestino dello spazio di lavoro</value></data>
<data name="Tooltips.Editor.RemoveCopy.LastOriginals" xml:space="preserve"><value>Originali che la libreria non ha più come sono qui: vanno nel cestino dello spazio di lavoro, non vengono eliminati</value></data>
<data name="Tooltips.Editor.RemoveCopy.LastOriginals.Server" xml:space="preserve"><value>Originali che il server non ha più come sono qui: vanno nel cestino dello spazio di lavoro, non vengono eliminati</value></data>
<data name="Tooltips.Settings.Workspace.TrashPlan.Action" xml:space="preserve"><value>Elimina per sempre ogni voce elencata dal cestino dello spazio di lavoro; prima scrivi il loro numero qui sopra</value></data>
<data name="Tooltips.Settings.Workspace.TrashPlan.Keep" xml:space="preserve"><value>Lascia il cestino dello spazio di lavoro com'è</value></data>
<data name="Tooltips.Settings.Workspace.Used" xml:space="preserve"><value>Quanto occupa la cartella dello spazio di lavoro sul suo disco, cestino compreso</value></data>
<data name="Tooltips.Settings.Workspace.Folder" xml:space="preserve"><value>La cartella dello spazio di lavoro (meglio un disco veloce); Cambia ne usa un'altra, Sposta porta con sé i progetti</value></data>
<data name="Tooltips.Settings.Workspace.Move" xml:space="preserve"><value>Sposta la cartella dello spazio di lavoro con i suoi progetti in un'altra cartella, dopo un piano; ogni file è verificato prima di rimuovere l'origine</value></data>
<data name="Tooltips.Settings.Workspace.SizeLimit" xml:space="preserve"><value>Oltre questa dimensione, i media dei progetti usati meno di recente vengono rimossi quando sono allineati con la loro origine; le versioni restano</value></data>
<data name="Tooltips.Settings.Workspace.NoLimit" xml:space="preserve"><value>Lo spazio di lavoro cresce quanto serve; solo Pulisci dopo rimuove i media</value></data>
<data name="Tooltips.Settings.Workspace.DefaultMedia" xml:space="preserve"><value>Cosa copia Apri nello spazio di lavoro, se lì non scegli altro</value></data>
<data name="Tooltips.Settings.Workspace.Proxies" xml:space="preserve"><value>Copia i proxy: leggeri e veloci da modificare; i render avvengono dove sono gli originali</value></data>
<data name="Tooltips.Settings.Workspace.Originals" xml:space="preserve"><value>Copia anche gli originali, per renderizzare su questo PC; occupa più spazio</value></data>
<data name="Tooltips.Settings.Workspace.VersionOnRender" xml:space="preserve"><value>Un render salva prima le modifiche come versione (inviata subito con la sincronizzazione attiva), così il render indica la versione che mostra</value></data>
<data name="Tooltips.Settings.Workspace.CleanAfter" xml:space="preserve"><value>Rimuove i media dei progetti non aperti da tanto, quando sono allineati con la loro origine; aprirne uno li ricopia</value></data>
<data name="Tooltips.Settings.Workspace.Never" xml:space="preserve"><value>I media restano finché non li rimuovi tu o Limite dimensione</value></data>
<data name="Tooltips.Settings.Workspace.OpenProject" xml:space="preserve"><value>Quale progetto apre Modifica per una sequenza con più progetti nello spazio di lavoro</value></data>
<data name="Tooltips.Settings.Workspace.LastUsed" xml:space="preserve"><value>Il progetto che hai aperto per ultimo per la sequenza</value></data>
<data name="Tooltips.Settings.Workspace.Main" xml:space="preserve"><value>Il progetto Principale della sequenza, che ne tiene le impostazioni</value></data>
<data name="Tooltips.Settings.Workspace.Ask" xml:space="preserve"><value>Elenca ogni volta i progetti della sequenza</value></data>
<data name="Tooltips.Settings.Workspace.Trash" xml:space="preserve"><value>Ciò che le copie locali rimosse e la pulizia hanno messo da parte; solo Svuota… lo elimina</value></data>
<data name="Tooltips.Settings.Workspace.EmptyTrash" xml:space="preserve"><value>Svuota per sempre il cestino dello spazio di lavoro, dopo un elenco di ciò che contiene e una conferma scritta</value></data>
<data name="Tooltips.Settings.Workspace.EmptyTrash.Disabled" xml:space="preserve"><value>Il cestino dello spazio di lavoro è vuoto</value></data>
<data name="Tooltips.Settings.Workspace.MovePlan.Unsent" xml:space="preserve"><value>Progetti con versioni, modifiche o render non ancora all'origine: si spostano col resto, non si perde nulla</value></data>
<data name="Tooltips.Settings.Workspace.MovePlan.Action" xml:space="preserve"><value>Mette in coda lo spostamento: i progetti vengono spostati o copiati e verificati, poi Modifica usa la nuova cartella</value></data>
<data name="Tooltips.Settings.Workspace.MovePlan.Keep" xml:space="preserve"><value>Lascia lo spazio di lavoro dov'è</value></data>
<data name="Tooltips.Settings.Workspace.ResumeMove" xml:space="preserve"><value>Rimette in coda lo spostamento: riparte dal suo registro, niente viene copiato due volte</value></data>
</root>
+3
View File
@@ -327,6 +327,9 @@
ToolTip="{l:Loc Tooltips.Editor.Export.History}" Margin="6,0,0,0" Visibility="{Binding CanOpenHistory, Converter={StaticResource BoolToVisibility}}" />
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Link}" Content="{l:Loc Editor.Export.Reveal}" Command="{Binding RevealLastCommand}"
ToolTip="{l:Loc Tooltips.Editor.Render.Reveal}" Margin="6,0,0,0" Visibility="{Binding CanReveal, Converter={StaticResource BoolToVisibility}}" />
<TextBlock DockPanel.Dock="Right" Text="{l:Loc Editor.Render.NotSent}" Style="{StaticResource Text.Faint}" FontSize="{StaticResource Size.Chip}"
VerticalAlignment="Center" Margin="6,0,0,0" ToolTip="{Binding UnsentToolTip}"
Visibility="{Binding HasUnsent, Converter={StaticResource BoolToVisibility}}" />
<TextBlock Text="{Binding HistoryText}" Style="{StaticResource Text.Faint}" FontSize="{StaticResource Size.Chip}" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"
ToolTip="{Binding HistoryText}" />
</DockPanel>
+13 -5
View File
@@ -634,7 +634,9 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
var export = batch ? RenderExport : RenderExport with { Batch = [] };
var requests = Session.RenderRequests(export);
foreach (var request in requests) await Session.SubmitAsync(request with { Priority = priority });
if (IsRemote) Shell.Notify(Loc.L("Editor.Render.QueuedServer", ServerName), requests[0].Label);
if (Session.Source is IProjectRenders { RendersLocally: true })
Shell.Notify(Loc.L("Editor.Render.QueuedLocal"), requests[0].Label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
else if (IsRemote) Shell.Notify(Loc.L("Editor.Render.QueuedServer", ServerName), requests[0].Label);
else Shell.Notify(Loc.L("Editor.Render.Queued"), requests[0].Label, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
}
@@ -957,7 +959,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
private void RefreshSteps()
{
if (_disposed) return;
var facts = new PathFacts(Session.Content, Session.Advice, Session.Project, _jobs.Active(JobKind.DeepAnalyse), _jobs.Active(JobKind.Render),
var facts = new PathFacts(Session.Content, Session.Advice, Session.Project, _jobs.Active(JobKind.DeepAnalyse), _jobs.Active(JobKind.Render) ?? _jobs.Active(JobKind.WorkspaceRender),
_planned ? RenderBlockedReason : null, _rendered.Matches(Session.Project));
foreach (var tab in Tabs) tab.SetStep(EditPath.Of(tab.Key, facts));
Analysis.OnStepChanged();
@@ -1174,7 +1176,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
if (_disposed)
{
// Closed after the Jobs screen left this render's end to it (FollowsRender): said without a read.
if (job is { Kind: JobKind.Render, State: JobState.Done } && _jobs.IsActive(job.Id) && Shell.Jobs.ClaimRenderToast(job.Id))
if (job is { State: JobState.Done } && IsRender(job.Kind) && _jobs.IsActive(job.Id) && Shell.Jobs.ClaimRenderToast(job.Id))
AnnounceRender(job, read: false);
return;
}
@@ -1186,13 +1188,19 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
if (!wasActive) return;
if (job is { Kind: JobKind.DeepAnalyse, State: JobState.Done }) ClearVisited();
// A render this editor followed to its end is said here, with its output, unless the Jobs screen said it first.
if (job.State == JobState.Done) _ = ReloadAsync(job.Kind == JobKind.Render && Shell.Jobs.ClaimRenderToast(job.Id) ? job : null);
if (job.State == JobState.Done) _ = ReloadAsync(IsRender(job.Kind) && Shell.Jobs.ClaimRenderToast(job.Id) ? job : null);
// A local render's send home (phase 5c): said once, here or on the Jobs screen.
if (job is { Kind: JobKind.WorkspaceSend, State: JobState.Done } && Shell.Jobs.ClaimRenderToast(job.Id)) Shell.Notify(Loc.L("Editor.Render.SentHome"), Title);
// An analysis may have written its Auto values into the library's settings (Main): the project takes them or says so.
if (job.State == JobState.Done && _project is { } project) _ = project.JobEndedAsync(job);
else if (IsRemote && job.State is JobState.Failed or JobState.Cancelled) ReportServerJobEnded(job);
else if (IsRemote && job.Kind is not (JobKind.WorkspaceRender or JobKind.WorkspaceSend) && job.State is JobState.Failed or JobState.Cancelled)
ReportServerJobEnded(job);
});
}
/// <summary>A render of the sequence: at its home, or on this PC from a workspace project's originals (phase 5c).</summary>
private static bool IsRender(JobKind kind) => kind is JobKind.Render or JobKind.WorkspaceRender;
/// <summary>
/// The frames of the server sequence changed while it is open, or a workspace project's sync took a newer Chronos's
/// settings (any thread): everything that changes the project is disabled and says why, and a toast says so (for a
+8
View File
@@ -403,6 +403,14 @@ public sealed class ExportTab : EditorTab
? Loc.Plural("Editor.Export.History", renders.Count, Formatting.Date(renders[0].Created))
: Loc.L("Editor.Export.NoHistory");
/// <summary>A workspace project's renders made on this PC that are not at its home yet (phase 5c): "Not sent".</summary>
public bool HasUnsent => Editor.Session.Source is WorkspaceSequenceSource { UnsentRenders: > 0 };
/// <summary>Why the renders are not in the library (or on the server) yet, and that their files stay in the workspace.</summary>
public string? UnsentToolTip => Editor.Session.Source is WorkspaceSequenceSource { UnsentRenders: > 0 } source
? Loc.L(source.IsServerHome ? "Tooltips.Editor.Render.NotSent.Server" : "Tooltips.Editor.Render.NotSent")
: null;
public IReadOnlyList<string> Batch => Export.Batch;
/// <summary>Completes when the card estimates in flight are done.</summary>
+8 -4
View File
@@ -11,8 +11,8 @@ public sealed class SequenceJobs(Guid sequenceId)
{
private readonly Dictionary<Guid, Job> _active = [];
/// <summary>An analysis or render runs: settings wait.</summary>
public bool IsBusy => _active.Values.Any(j => j.State == JobState.Running);
/// <summary>An analysis or render runs: settings wait (a local render's send home does not hold them).</summary>
public bool IsBusy => _active.Values.Any(j => j.State == JobState.Running && j.Kind != JobKind.WorkspaceSend);
/// <summary>A deep analysis waits, runs or is paused.</summary>
public bool IsAnalysing => _active.Values.Any(j => j.Kind == JobKind.DeepAnalyse);
@@ -23,13 +23,17 @@ public sealed class SequenceJobs(Guid sequenceId)
/// <summary>The job of <paramref name="kind"/> to show, chosen as <see cref="Shown"/> is (the Edit path's steps).</summary>
public Job? Active(JobKind kind) => First(_active.Values.Where(j => j.Kind == kind));
/// <summary>An analysis or render of this sequence.</summary>
/// <summary>An analysis or render of this sequence, a workspace project's render on this PC or its send home (phase 5c).</summary>
public bool Concerns(Job job)
{
ArgumentNullException.ThrowIfNull(job);
return job.TargetIds.Contains(sequenceId) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
return job.TargetIds.Contains(sequenceId) && IsSequenceKind(job.Kind);
}
/// <summary>The kinds the editor follows.</summary>
public static bool IsSequenceKind(JobKind kind) =>
kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render or JobKind.WorkspaceRender or JobKind.WorkspaceSend;
/// <summary>The job is one of those that wait, run or are paused.</summary>
public bool IsActive(Guid jobId) => _active.ContainsKey(jobId);
+1 -1
View File
@@ -208,7 +208,7 @@ internal sealed class ServerJobs : IAsyncDisposable
_changed(job);
}
private bool Concerns(Job job) => job.TargetIds.Contains(_sequenceId) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render;
private bool Concerns(Job job) => job.TargetIds.Contains(_sequenceId) && SequenceJobs.IsSequenceKind(job.Kind);
/// <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)
+114 -11
View File
@@ -29,6 +29,9 @@ public interface IProjectRenders
{
/// <summary>The jobs that render <paramref name="export"/> of <paramref name="project"/> (the editor's settings, positions on the source's frames).</summary>
IReadOnlyList<ArchiveJobRequest> RenderRequests(Sequence sequence, ProjectSettings project, ExportSettings export, int sourceWidth, int sourceHeight);
/// <summary>The renders run on this PC (a workspace project holding its originals, phase 5c), whatever the home.</summary>
bool RendersLocally { get; }
}
/// <summary>
@@ -95,6 +98,8 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
private FramePhotos _photos = new([]);
private BundleWorkspace? _workspace;
private bool _readOnly;
private bool _holdsOriginals;
private int _unsent;
private int _disposed;
/// <param name="server">The server the project's home is (phase 5b); null for a project of this PC's archive.</param>
@@ -136,6 +141,15 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// <summary>Settings of a newer Chronos: shown, never saved.</summary>
public bool IsReadOnly => Volatile.Read(ref _readOnly);
/// <summary>
/// The media read last hold the originals (phase 5c): the project renders on this PC's engine from them, into its
/// <c>exports/</c>, and the renders are sent home after (<see cref="JobKind.WorkspaceRender"/>), also for a server home.
/// </summary>
public bool RendersLocally => Volatile.Read(ref _holdsOriginals);
/// <summary>The local renders of the project's ledger not at the home yet, as read last.</summary>
public int UnsentRenders => Volatile.Read(ref _unsent);
public bool IsOutdated => false;
/// <summary>The library's values and the editor's are asked about where both changed a setting, as a sync asks.</summary>
@@ -179,6 +193,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
IReadOnlyList<Render> renders = row is null ? [] : await _db.Renders.ListBySequenceAsync(home.SequenceId, cancellationToken);
return await Task.Run(() =>
{
renders = [.. renders, .. UnsentOf(session.Project, home.SequenceId)];
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();
@@ -278,6 +293,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
Created = r.Created,
ProducedBy = r.ProducedBy,
}).ToList() ?? [];
renders = [.. renders.Concat(UnsentOf(session.Project, home.SequenceId)).OrderByDescending(r => r.Created)];
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, [])
@@ -495,7 +511,9 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// <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);
ArgumentNullException.ThrowIfNull(request);
// A render from the workspace's originals and its send run on this PC's engine, whatever the home (phase 5c).
if (_server is not null && !RunsHere(request.Kind)) 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;
@@ -504,26 +522,40 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
/// <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 (Api() is null || Volatile.Read(ref _serverJobs) is not { } jobs) return [];
var local = (await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items;
if (_server is null) return local;
// This PC's renders from the originals and their sends beside the server's jobs (phase 5c).
IReadOnlyList<Job> here = [.. local.Where(j => RunsHere(j.Kind))];
if (Api() is null || Volatile.Read(ref _serverJobs) is not { } jobs) return here;
try
{
return await jobs.ListAsync(cancellationToken);
return [.. (await jobs.ListAsync(cancellationToken)).Concat(here)];
}
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 [];
return here;
}
}
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 async Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken)
{
if (_server is not null && !await IsLocalJobAsync(jobId, cancellationToken)) await ServerJobsOrThrow().CancelAsync(jobId, cancellationToken);
else await (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).CancelAsync(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);
public async Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken)
{
if (_server is not null && !await IsLocalJobAsync(jobId, cancellationToken)) await ServerJobsOrThrow().RetryAsync(jobId, cancellationToken);
else await (_engine ?? throw new InvalidOperationException(Loc.L("Editor.Error.NoEngine"))).ResumeAsync(jobId, cancellationToken);
}
/// <summary>The kinds a workspace project runs on this PC's engine whatever its home: a render from its originals and its send home.</summary>
private static bool RunsHere(JobKind kind) => kind is JobKind.WorkspaceRender or JobKind.WorkspaceSend;
/// <summary>A job of this PC's engine that runs here whatever the home (<see cref="RunsHere"/>).</summary>
private async Task<bool> IsLocalJobAsync(Guid jobId, CancellationToken cancellationToken) =>
await _db.Jobs.GetAsync(jobId, cancellationToken) is { } job && RunsHere(job.Kind);
/// <summary>
/// The render at the home (owner review 2, R8: edit with proxies, render where the originals are): one job per preset
@@ -542,6 +574,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
ArgumentNullException.ThrowIfNull(export);
var portable = ProjectContent.ToPortable(project with { Export = export }, Photos);
var hash = ProjectContent.Hash(portable);
if (RendersLocally && Workspace is { } workspace) return LocalRenderRequests(sequence, workspace.Home, portable, hash, export, sourceWidth, sourceHeight);
if (_server is not null)
{
if (InStepWithHome(project) is { } basis)
@@ -566,6 +599,75 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
return [.. requests.Select(r => r with { ParametersJson = WithoutVersion(r.ParametersJson) })];
}
/// <summary>
/// The render on this PC from the originals the workspace holds (phase 5c): one <see cref="JobKind.WorkspaceRender"/> per
/// preset with the project's portable settings, naming the head version of <c>versions/</c> when the settings are the
/// ones it holds (the render records it; an unsaved working state renders without a version), sent home after.
/// </summary>
private IReadOnlyList<ArchiveJobRequest> LocalRenderRequests(Sequence sequence, BundleHome home, string portable, string hash, ExportSettings export,
int sourceWidth, int sourceHeight)
{
var head = HeadVersion(hash);
var version = new ProjectVersion { Id = head ?? Guid.Empty, ProjectId = ProjectId, Number = 0, SettingsJson = portable, ContentHash = hash };
var root = _sync.Store.Root;
var server = home.IsArchive ? null : home.Server;
return
[
.. ProcessingJobs.RenderVersion(sequence, version, export, sourceWidth, sourceHeight).Select(r => WorkspaceJobs.Render(home.SequenceId,
r.Label ?? sequence.DisplayTitle, root, ProjectId, head, (head is null ? WithoutVersion(r.ParametersJson) : r.ParametersJson)!, server)),
];
}
/// <summary>The id of the newest version the workspace holds when it holds <paramref name="hash"/>; null otherwise.</summary>
private Guid? HeadVersion(string hash)
{
try
{
return Project.Versions() is [.., var last] && string.Equals(last.ContentHash, hash, StringComparison.OrdinalIgnoreCase) ? last.Id : null;
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("editor", $"The versions of workspace project {ProjectId} cannot be read; the render names none", ex);
return null;
}
}
/// <summary>The local renders of the project's ledger not at the home yet, as renders of <paramref name="sequenceId"/> (newest first).</summary>
private IReadOnlyList<Render> UnsentOf(WorkspaceProject project, Guid sequenceId)
{
try
{
var unsent = project.ReadRenders().Unsent;
Volatile.Write(ref _unsent, unsent.Count);
return
[
.. unsent.OrderByDescending(e => e.Rendered).Select(e => new Render
{
Id = e.RenderId,
SequenceId = sequenceId,
PresetName = e.PresetName,
OutputPath = project.ExportFile(e.File),
Codec = e.Codec,
Width = e.Width,
Height = e.Height,
Fps = e.Fps,
DurationSeconds = e.DurationSeconds,
Bytes = e.Size,
Created = e.Rendered,
ProducedBy = Environment.MachineName,
ProjectId = e.ProjectId,
ProjectVersionId = e.ProjectVersionId,
}),
];
}
catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("editor", $"The render ledger of workspace project {ProjectId} cannot be read", ex);
Volatile.Write(ref _unsent, 0);
return [];
}
}
/// <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.
@@ -643,6 +745,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders
_photos = index.Photos;
_standIns = [.. index.Frames.Where(f => f.IsStandIn).Select(f => f.Id)];
_workspace = workspace;
_holdsOriginals = index.HoldsOriginals;
changed = _readOnly != readOnly;
_readOnly = readOnly;
}
+15 -3
View File
@@ -178,15 +178,27 @@ 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, from
/// this PC's archive or, through the signed-in session, from a server.</summary>
/// queued (it is never claimed here). The workspace's jobs are the desktop's alone: they write into this PC's workspace
/// (a copy from this PC's archive or, through the signed-in session, from a server; a local render with this PC's
/// encoders; the sending of its renders home; the move of its folder, which Settings › Workspace then names).</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.Sync) : [],
.. services.Database is { } db && services.Archives is { } archives
? WorkspaceJobs.CreateHandlers(db, archives, services.Sync, WorkspaceOptions(services, archives))
: [],
];
/// <summary>
/// The workspace jobs' share of the desktop (phase 5c): its processing options for local renders, the metered hold of
/// Settings › Server over transfers with a server, and the workspace that follows a moved folder.
/// </summary>
private static WorkspaceJobOptions WorkspaceOptions(AppServices services, ArchiveService archives) =>
new(services.Processing?.Options ?? WorkspaceJobOptions.For(archives).Processing,
() => services.Settings.PauseUploadsOnMetered && MeteredNetwork.IsMetered(),
services.Workspace.MovedAsync);
/// <summary>
/// Queues a scan of <paramref name="archive"/> unless one is already waiting or running; the sequences it indexes get
/// a background deep analysis when Settings › Analysis asks for it.
@@ -7,6 +7,7 @@ using Chronos.Core.Diagnostics;
using Chronos.Core.Import;
using Chronos.Core.IO;
using Chronos.Core.Naming;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Repositories;
using Chronos.Ui.Theming;
@@ -39,6 +40,21 @@ public enum HardwarePreference
HardwareForPreviews,
}
/// <summary>
/// Which project Edit opens for a sequence that has several in the workspace (Settings › Workspace › Open project, phase 5c).
/// </summary>
public enum WorkspaceOpenPolicy
{
/// <summary>The project opened last for the sequence (<see cref="AppSettings.WorkspaceRecent"/>), else the one saved last.</summary>
LastUsed,
/// <summary>The sequence's Main project.</summary>
Main,
/// <summary>Ask each time, listing the sequence's projects.</summary>
Ask,
}
/// <summary>A server certificate the user trusted on first use (BRIEF §12.7).</summary>
public sealed class TrustedCertificate
{
@@ -58,6 +74,8 @@ public sealed class AppSettings
public const int DefaultCacheLimitGb = 20;
public const int DefaultScanIntervalMinutes = 10;
public const int DefaultWorkspaceKeptVersions = 20;
public const int DefaultWorkspaceSizeLimitGb = 100;
public const int DefaultWorkspaceCleanAfterDays = 30;
/// <summary>2⁻⁴ of white: the deep analysis' night threshold (a mean log2 luminance of −4).</summary>
public const double DefaultNightBrightnessPercent = 6.25;
@@ -169,6 +187,36 @@ public sealed class AppSettings
/// <summary>The workspace project opened last for each sequence (sequence id → project id); Edit opens it again.</summary>
public Dictionary<Guid, Guid> WorkspaceRecent { get; set; } = [];
/// <summary>
/// Phase 5c: past this size (GB of 2³⁰ bytes) the workspace's clean-up removes the media of the projects used longest ago
/// that are in step with their home (never one open, with jobs, or with renders not sent); 0 = no limit.
/// </summary>
public int WorkspaceSizeLimitGb { get; set; } = DefaultWorkspaceSizeLimitGb;
/// <summary>
/// What "Open in workspace" copies unless chosen otherwise: <see cref="BundleMedia.Proxies"/> or
/// <see cref="BundleMedia.Originals"/> (the proxies plus the originals, to render on this PC).
/// </summary>
public string WorkspaceDefaultMedia { get; set; } = BundleMedia.Proxies;
/// <summary>A render of a project with changes not saved as a version saves one first (and sends it when Sync automatically is on).</summary>
public bool WorkspaceVersionOnRender { get; set; } = true;
/// <summary>
/// The workspace's clean-up removes the media of a project not opened for this many days, once it is in step with its
/// home; 0 = never.
/// </summary>
public int WorkspaceCleanAfterDays { get; set; } = DefaultWorkspaceCleanAfterDays;
/// <summary>Which project Edit opens for a sequence with several in the workspace.</summary>
public WorkspaceOpenPolicy WorkspaceOpenProject { get; set; } = WorkspaceOpenPolicy.LastUsed;
/// <summary>
/// When each workspace project was last opened in Edit (project id → time), which the clean-up goes by (else the time
/// its working state was saved). This PC's, like <see cref="WorkspaceRecent"/>.
/// </summary>
public Dictionary<Guid, DateTimeOffset> WorkspaceOpened { get; set; } = [];
// ---- Server ----
public string? ServerUrl { get; set; }
public string? ServerUsername { get; set; }
@@ -285,6 +333,64 @@ public sealed class AppSettings
/// <summary>A deep copy (JSON round trip), used for import and reset.</summary>
public AppSettings Clone() => Parse(ToJson()) ?? new AppSettings();
/// <summary>
/// Settings › Advanced › Reset: every default, but the values that are this PC's or this user's state rather than
/// preferences: the archive and the session, the window and its rail, the sequence edited last, the first-run flag, the
/// jobs cleared, and the workspace (its folder, moved only by its own operation, the projects opened last and when).
/// </summary>
public AppSettings ResetKeepingState() => new()
{
LastArchivePath = LastArchivePath,
ServerUrl = ServerUrl,
ServerUsername = ServerUsername,
ProtectedToken = ProtectedToken,
TrustedCertificates = TrustedCertificates,
RecentServers = RecentServers,
Window = Window,
RailCollapsed = RailCollapsed,
LastEditedSequence = LastEditedSequence,
FirstRunCompleted = FirstRunCompleted,
JobsClearedAt = JobsClearedAt,
WorkspaceFolder = WorkspaceFolder,
WorkspaceRecent = WorkspaceRecent,
WorkspaceOpened = WorkspaceOpened,
};
/// <summary>
/// Settings › Export: a copy without secrets and machine-bound values (the session, the window, the workspace's folder and
/// what it remembers of its projects: another PC's ids mean nothing there).
/// </summary>
public AppSettings ForExport()
{
var copy = Clone();
copy.ProtectedToken = null;
copy.Window = null;
copy.WorkspaceFolder = null;
copy.WorkspaceRecent = [];
copy.WorkspaceOpened = [];
return copy;
}
/// <summary>
/// Settings › Import: <paramref name="imported"/> with this PC's own values taken from these settings: the session, the
/// window and its rail, the sequence edited last, the first-run flag, and the workspace (its folder, the projects opened
/// last and when). Changes and returns <paramref name="imported"/>.
/// </summary>
public AppSettings KeepLocalIn(AppSettings imported)
{
ArgumentNullException.ThrowIfNull(imported);
imported.ProtectedToken = ProtectedToken;
imported.ServerUrl = ServerUrl;
imported.Window = Window;
imported.RailCollapsed = RailCollapsed;
imported.LastEditedSequence = LastEditedSequence;
imported.FirstRunCompleted = FirstRunCompleted;
imported.WorkspaceFolder = WorkspaceFolder;
imported.WorkspaceRecent = WorkspaceRecent;
imported.WorkspaceOpened = WorkspaceOpened;
return imported;
}
}
[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true)]
+2 -1
View File
@@ -40,7 +40,8 @@ public static class JobNotices
private static bool Announces(JobKind kind) =>
kind is JobKind.Render or JobKind.DeepAnalyse or JobKind.Verify or JobKind.Rebuild or JobKind.Maintenance or JobKind.UploadCommit
or JobKind.Move or JobKind.Adopt or JobKind.EmptyTrash or JobKind.Convert;
or JobKind.Move or JobKind.Adopt or JobKind.EmptyTrash or JobKind.Convert or JobKind.WorkspaceRender or JobKind.WorkspaceSend
or JobKind.WorkspaceMove;
/// <summary>
/// Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing.
+1 -1
View File
@@ -12,7 +12,7 @@ public static class JobText
/// <summary>True for jobs whose items are frames, so their speed reads in fps.</summary>
public static bool CountsFrames(JobKind kind) =>
kind is JobKind.Render or JobKind.Proxies or JobKind.Thumbs or JobKind.DeepAnalyse;
kind is JobKind.Render or JobKind.Proxies or JobKind.Thumbs or JobKind.DeepAnalyse or JobKind.WorkspaceRender;
/// <summary>True for jobs whose progress counts bytes (hash verification, card import).</summary>
public static bool CountsBytes(JobKind kind) => kind is JobKind.Verify or JobKind.Import;
+1 -1
View File
@@ -303,7 +303,7 @@ public sealed class JobsViewModel : SectionViewModel
else if (before != JobState.Failed && !IsSelected) _unseenFailures.Add(job.Id);
var notice = JobNotices.For(before, job);
// A flush can take the end before the editor that follows the render has seen it: the editor says it, with its output.
if (notice == JobNotice.Done && job.Kind == JobKind.Render
if (notice == JobNotice.Done && job.Kind is JobKind.Render or JobKind.WorkspaceRender or JobKind.WorkspaceSend
&& (Shell.Sequence.Editor?.FollowsRender(job.Id) == true || !ClaimRenderToast(job.Id))) return;
_endings.Add(notice, job);
}
@@ -127,6 +127,10 @@
<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.CopyOriginals}" Command="{Binding Project.CopyOriginalsCommand}" ToolTip="{Binding Project.CopyOriginalsToolTip}"
ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Editor.Project.ProxiesOnly}" Command="{Binding Project.ProxiesOnlyCommand}" ToolTip="{Binding Project.ProxiesOnlyToolTip}"
ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Editor.Project.RemoveCopy}" Command="{Binding Project.RemoveCopyCommand}" ToolTip="{Binding Project.RemoveCopyToolTip}" />
</ContextMenu>
</Button.ContextMenu>
+77 -27
View File
@@ -608,12 +608,20 @@ public sealed class SequenceViewModel : SectionViewModel
ImageDecoder decoder, Sequence row)
{
var request = TakeRequest(row.Id);
var entry = request switch
WorkspaceEntry? entry;
if (request is { ProjectId: { } id }) entry = await workspace.FindAsync(id);
else if (request is { Main: true }) entry = (await workspace.ProjectsOfAsync(row.Id)).FirstOrDefault(p => p.IsMain);
else
{
{ ProjectId: { } id } => await workspace.FindAsync(id),
{ Main: true } => (await workspace.ProjectsOfAsync(row.Id)).FirstOrDefault(p => p.IsMain),
_ => await workspace.LastUsedAsync(row.Id),
};
var (cancelled, chosen) = await PolicyEntryAsync(services, workspace, row.Id, row.DisplayTitle, _ => true);
if (cancelled)
{
_afterOpen = null;
Shell.KeepSequence(OpenSequenceId);
return null;
}
entry = chosen;
}
// This Chronos cannot read its working state (damaged, or a newer Chronos's): nothing is checked out over it.
if (entry is { IsReadable: false } unreadable) throw WorkspaceHost.Unreadable(unreadable);
// No project of the sequence here opens, and its Main here is such a copy (never among its projects): said at once,
@@ -634,10 +642,12 @@ public sealed class SequenceViewModel : SectionViewModel
if (entry is { HasMedia: true })
{
workspace.Remember(row.Id, entry.ProjectId);
workspace.RecordOpened(entry.ProjectId);
return (new WorkspaceSequenceSource(workspace.Sync, entry.ProjectId, db, decoder, services.Engine), row.DisplayTitle);
}
var projectId = entry?.ProjectId ?? request?.ProjectId;
string? newName = null;
var media = DefaultMedia(services);
if (entry is null && projectId is { } wanted && (await workspace.HomeProjectsAsync(row.Id)).All(p => p.Id != wanted))
{
// A project file of a project this home does not have (another PC's workspace): its sequence's Main takes it.
@@ -653,12 +663,12 @@ public sealed class SequenceViewModel : SectionViewModel
Shell.KeepSequence(OpenSequenceId);
return null;
}
(projectId, newName) = (choice.ProjectId, choice.NewName);
(projectId, newName, media) = (choice.ProjectId, choice.NewName, choice.Media);
}
WorkspaceCheckout checkout;
try
{
checkout = await workspace.CheckoutAsync(row.Id, projectId, newName);
checkout = await workspace.CheckoutAsync(row.Id, projectId, newName, media);
}
catch (WorkspaceException ex) when (ex.FolderRefused)
{
@@ -710,12 +720,20 @@ public sealed class SequenceViewModel : SectionViewModel
private async Task<ServerOpen?> OpenServerWorkspaceAsync(AppServices services, WorkspaceHost workspace, ChronosDatabase db, ImageDecoder decoder, Guid remoteId)
{
var request = _requested is { } asked && asked.SequenceId == remoteId ? asked : null;
var entry = request switch
WorkspaceEntry? entry;
if (request is { ProjectId: { } id }) entry = await workspace.FindAsync(id) is { IsServerHome: true } found && found.SequenceId == remoteId ? found : null;
else if (request is { Main: true }) entry = (await workspace.ProjectsOfAsync(remoteId)).FirstOrDefault(p => p is { IsMain: true, IsServerHome: true });
else
{
{ 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 (cancelled, chosen) = await PolicyEntryAsync(services, workspace, remoteId, null, p => p.IsServerHome);
if (cancelled)
{
_afterOpen = null;
Shell.KeepSequence(OpenSequenceId);
return new ServerOpen(null);
}
entry = chosen;
}
var sync = services.Sync;
if (entry is { IsReadable: false } unreadable)
{
@@ -726,6 +744,7 @@ public sealed class SequenceViewModel : SectionViewModel
{
TakeRequest(remoteId);
workspace.Remember(remoteId, entry.ProjectId);
workspace.RecordOpened(entry.ProjectId);
// Its analyses and renders travel on a connection of the signed-in session, when that is the project's server:
// made again whenever the sign-in changes, so a project opened signed out renders once signed in.
var server = entry.Home.Server;
@@ -755,6 +774,7 @@ public sealed class SequenceViewModel : SectionViewModel
}
var projectId = entry?.ProjectId ?? request?.ProjectId;
string? newName = null;
var media = DefaultMedia(services);
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.
@@ -770,12 +790,12 @@ public sealed class SequenceViewModel : SectionViewModel
Shell.KeepSequence(OpenSequenceId);
return new ServerOpen(null);
}
(projectId, newName) = (choice.ProjectId, choice.NewName);
(projectId, newName, media) = (choice.ProjectId, choice.NewName, choice.Media);
}
WorkspaceCheckout checkout;
try
{
checkout = await workspace.CheckoutAsync(home, projectId, newName);
checkout = await workspace.CheckoutAsync(home, projectId, newName, media);
}
catch (WorkspaceException ex) when (ex.FolderRefused)
{
@@ -811,25 +831,23 @@ public sealed class SequenceViewModel : SectionViewModel
/// <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
/// media (Settings › Workspace › Media chosen first), 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
{
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}");
}
copy = await workspace.CopyFactsAsync(home);
}
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or InvalidOperationException or DatabaseException
or UnauthorizedAccessException or ChronosApiException or System.Net.Http.HttpRequestException)
{
// 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>
@@ -837,7 +855,8 @@ 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(title, projects, d => CloseDialog(d), copy: copy, unreadable: unreadable, server: !home.IsArchive);
var dialog = new OpenInWorkspaceDialogViewModel(title, projects, d => CloseDialog(d), copy: copy, unreadable: unreadable, server: !home.IsArchive,
defaultMedia: DefaultMedia(Shell.Services));
// The picker or the open sequence shows behind the dialog meanwhile, not the progress bar.
IsLoading = false;
OpenDialog(dialog);
@@ -851,6 +870,37 @@ public sealed class SequenceViewModel : SectionViewModel
}
}
/// <summary>The media a checkout copies unless "Open in workspace" chose: Settings › Workspace › Media.</summary>
private static string DefaultMedia(AppServices services) =>
services.Settings.WorkspaceDefaultMedia == BundleMedia.Originals ? BundleMedia.Originals : BundleMedia.Proxies;
/// <summary>
/// The project of the sequence Edit opens when none was asked for (phase 5c, Settings › Workspace › Open project): the
/// one opened last, Main, or the one chosen in "Open which project?" when the workspace holds several (Cancelled: closed
/// without a choice). Only projects <paramref name="fits"/> takes count; none here: null.
/// </summary>
private async Task<(bool Cancelled, WorkspaceEntry? Entry)> PolicyEntryAsync(AppServices services, WorkspaceHost workspace, Guid sequenceId, string? title,
Func<WorkspaceEntry, bool> fits)
{
var last = await workspace.LastUsedAsync(sequenceId) is { } used && fits(used) ? used : null;
var policy = services.Settings.WorkspaceOpenProject;
if (policy == WorkspaceOpenPolicy.LastUsed) return (false, last);
var here = (await workspace.ProjectsOfAsync(sequenceId)).Where(p => fits(p) && p.IsReadable).ToList();
if (policy == WorkspaceOpenPolicy.Main) return (false, here.FirstOrDefault(p => p.IsMain) ?? last);
if (here.Count < 2) return (false, last ?? here.FirstOrDefault());
var dialog = new OpenProjectDialogViewModel(title ?? here[0].SequenceTitle, here, last?.ProjectId, d => CloseDialog(d));
IsLoading = false;
OpenDialog(dialog);
try
{
return await dialog.Choice is { } chosen ? (false, chosen) : (true, null);
}
finally
{
IsLoading = true;
}
}
/// <summary>The project the next open of <paramref name="sequenceId"/> takes, taken once; null when none was asked for.</summary>
private ProjectRequest? TakeRequest(Guid sequenceId)
{
+8 -35
View File
@@ -1207,7 +1207,8 @@ public sealed class SettingsViewModel : SectionViewModel
[
JobKind.Render, JobKind.Import, JobKind.Download, JobKind.UploadCommit, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse,
JobKind.DeepAnalyse, JobKind.Thumbs, JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move,
JobKind.Backup, JobKind.Cleanup, JobKind.EmptyTrash, JobKind.Convert, JobKind.WorkspaceCopy,
JobKind.Backup, JobKind.Cleanup, JobKind.EmptyTrash, JobKind.Convert, JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend,
JobKind.WorkspaceMove,
];
/// <summary>Stores <paramref name="level"/> for <paramref name="kind"/>, keeping only the levels that differ from the defaults.</summary>
@@ -1632,23 +1633,8 @@ public sealed class SettingsViewModel : SectionViewModel
IsDestructive = true,
});
if (!confirmed) return;
var defaults = new AppSettings
{
LastArchivePath = _s.LastArchivePath,
ServerUrl = _s.ServerUrl,
ServerUsername = _s.ServerUsername,
ProtectedToken = _s.ProtectedToken,
TrustedCertificates = _s.TrustedCertificates,
RecentServers = _s.RecentServers,
Window = _s.Window,
RailCollapsed = _s.RailCollapsed,
LastEditedSequence = _s.LastEditedSequence,
FirstRunCompleted = _s.FirstRunCompleted,
JobsClearedAt = _s.JobsClearedAt,
// The workspace holds this PC's work: its folder stays where it is (moving it is its own operation).
WorkspaceFolder = _s.WorkspaceFolder,
WorkspaceRecent = _s.WorkspaceRecent,
};
// The workspace holds this PC's work: its folder stays where it is (moving it is its own operation).
var defaults = _s.ResetKeepingState();
// Start with Windows lives in the registry, not in the settings file: its default is off.
Startup.SetEnabled(false);
ApplyAll(defaults);
@@ -1690,12 +1676,8 @@ public sealed class SettingsViewModel : SectionViewModel
{
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Settings.Export.Title"));
if (folder is null) return;
var copy = _s.Clone();
// Secrets and machine-bound values stay on this PC.
copy.ProtectedToken = null;
copy.Window = null;
copy.WorkspaceFolder = null;
copy.WorkspaceRecent = [];
var copy = _s.ForExport();
var path = Path.Combine(folder, $"Chronos settings {DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}.json");
await Task.Run(() => AtomicFile.WriteAllText(path, copy.ToJson()));
Shell.Notify(Loc.L("Settings.Export.Done"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
@@ -1720,18 +1702,9 @@ public sealed class SettingsViewModel : SectionViewModel
Shell.Notify(Loc.L("Errors.Settings.Import"), isError: true);
return;
}
// Everything but the session, the window and its rail, the sequence edited last (another PC's ids mean nothing here)
// and the first-run flag.
imported.ProtectedToken = _s.ProtectedToken;
imported.ServerUrl = _s.ServerUrl;
imported.Window = _s.Window;
imported.RailCollapsed = _s.RailCollapsed;
imported.LastEditedSequence = _s.LastEditedSequence;
imported.FirstRunCompleted = _s.FirstRunCompleted;
// The workspace is this PC's: its folder and the projects opened last stay.
imported.WorkspaceFolder = _s.WorkspaceFolder;
imported.WorkspaceRecent = _s.WorkspaceRecent;
ApplyAll(imported);
// Everything but the session, the window and its rail, the sequence edited last (another PC's ids mean nothing here),
// the first-run flag and the workspace, which is this PC's (its folder, the projects opened last and when).
ApplyAll(_s.KeepLocalIn(imported));
// Settings of a PC never rewrite the shared archive.json: the imported templates and sizes are the defaults of new
// archives, and the rows show the own settings of the archive at the (possibly imported) archive folder.
_retarget = RetargetArchiveAsync();
@@ -81,6 +81,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
private bool _isSyncing;
private bool _homeFramesChanged;
private Guid _copyJob;
private bool _copyingOriginals;
private bool _changingMedia;
private bool _disposed;
/// <summary>Counts the editor's changes, so only the last one's state read applies.</summary>
@@ -110,6 +112,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
RenameCommand = new AsyncRelayCommand(OpenRenameAsync);
DeleteCommand = new AsyncRelayCommand(DeleteAsync, () => !IsMain);
RemoveCopyCommand = new AsyncRelayCommand(OpenRemoveCopyAsync);
CopyOriginalsCommand = new AsyncRelayCommand(CopyOriginalsAsync, () => !HoldsOriginals && !IsMediaBusy);
ProxiesOnlyCommand = new AsyncRelayCommand(ProxiesOnlyAsync, () => HoldsOriginals && !IsMediaBusy);
source.JobChanged += OnJobChanged;
session.ProjectChanged += OnProjectChanged;
host.HomeChanged += OnHomeChanged;
@@ -193,6 +197,27 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
public ICommand UpdateMediaCommand => _updateMedia;
/// <summary>The workspace holds the project's originals besides its proxies (phase 5c): renders run on this PC.</summary>
public bool HoldsOriginals => _source.Workspace?.Media.Kind == BundleMedia.Originals;
/// <summary>
/// The media cannot change now: changes not saved as a version, a sync or a copy of the media running (the jobs of the
/// sequence are asked when the command runs).
/// </summary>
public bool IsMediaBusy => _changingMedia || _isSyncing || _copyJob != Guid.Empty || _status is { Modified: true, ReadOnly: false };
/// <summary>Copy originals… (phase 5c): the project's originals into the workspace, to render on this PC.</summary>
public ICommand CopyOriginalsCommand { get; }
/// <summary>Proxies only… (phase 5c): the originals copied here deleted once the home is checked to hold each one.</summary>
public ICommand ProxiesOnlyCommand { get; }
public string CopyOriginalsToolTip => IsMediaBusy ? Loc.L("Tooltips.Editor.Project.MediaBusy")
: WorkspaceText.ForHome("Tooltips.Editor.Project.CopyOriginals", IsServerHome);
public string ProxiesOnlyToolTip => IsMediaBusy ? Loc.L("Tooltips.Editor.Project.MediaBusy")
: WorkspaceText.ForHome("Tooltips.Editor.Project.ProxiesOnly", IsServerHome);
/// <summary>Reads where the project stands (against its home) and whether the home's frames moved.</summary>
public async Task RefreshAsync()
{
@@ -227,12 +252,15 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
/// <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.
/// the server could not take them or no longer has the project, or a conflict waits. A project of this PC's archive,
/// or one rendered on this PC from its originals (phase 5c), renders as it is: true. With Settings › Workspace › Version
/// on render, a changed project is saved as a version first (<see cref="SaveForRenderAsync"/>).
/// </summary>
public async Task<bool> ReadyToRenderAsync()
{
if (!IsServerHome) return true;
if (_host.Settings.WorkspaceVersionOnRender && !await SaveForRenderAsync()) return false;
// Rendered on this PC from the originals the workspace holds (phase 5c): the project renders as it is.
if (!IsServerHome || _source.RendersLocally) return true;
await StoreEditAsync();
var status = await _host.StatusAsync(ProjectId);
if (_disposed) return false;
@@ -271,6 +299,45 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
return !_disposed && _source.InStepWithHome(_session.Project) is not null;
}
/// <summary>
/// Settings › Workspace › Version on render (phase 5c): a project changed since its last version is saved as a version
/// noted "Render" before its render, and sent at once with Sync automatically when the home can be reached (out of reach,
/// it waits here). False when it could not be saved, or the sync met a conflict to settle first.
/// </summary>
private async Task<bool> SaveForRenderAsync()
{
await StoreEditAsync();
var status = await _host.StatusAsync(ProjectId);
if (_disposed) return false;
Apply(status);
if (!status.Modified || !CanSaveVersion) return true;
WorkspaceSaveResult result;
try
{
result = await _host.SaveVersionAsync(ProjectId, Loc.L("Editor.Workspace.RenderNote"));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"Project {ProjectId} could not be saved before its render", ex);
_ui.Notify(Loc.L("Editor.Workspace.RenderHeld"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
return false;
}
if (_disposed) return false;
Apply(result.Status);
if (result.Synced is { } taken) await TakeAsync(taken);
if (result.Version is { } version)
{
// The home numbers what it stores: the last one sent is this version.
var number = result.Synced is { Pushed.Count: > 0 } synced ? synced.Pushed[^1].Number : version.Number;
_ui.Notify(Loc.L("Editor.Workspace.SavedForRender", Formatting.Count(number)), Name);
}
if (result.SyncError is { } error)
_ui.Notify(Loc.L("Editor.Workspace.NotSent"), WorkspaceText.Failure(error, IsServerHome), isError: error is not HomeUnavailableException);
if (result.Status.Conflict is not { } conflict) return true;
AskConflict(conflict);
return false;
}
/// <summary>
/// Saves the working state as a version with <paramref name="note"/>, sent at once with Sync automatically; what the
/// sync took from the home comes into the editor, a conflict it met is asked about.
@@ -644,6 +711,130 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
}
}
/// <summary>
/// Copy originals…: refused while the media cannot change (<see cref="IsMediaBusy"/>, or a job of the sequence waits or
/// runs); otherwise the copy is queued, the banner says it runs, and the editor reads the media again once it is done.
/// </summary>
private async Task CopyOriginalsAsync()
{
try
{
await StoreEditAsync();
if (await MediaRefusalAsync() is { } refusal)
{
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), refusal, isError: true);
return;
}
var job = await _host.QueueOriginalsCopyAsync(ProjectId);
_copyJob = job.Id;
_copyingOriginals = true;
RaiseState();
_ui.Notify(Loc.L("Editor.Workspace.CopyingOriginals"), _session.Content.Sequence.DisplayTitle, Loc.L("Shell.Nav.Jobs"), Loc.L("Tooltips.Nav.Jobs"));
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The originals of project {ProjectId} could not be queued for copy", ex);
_ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
}
/// <summary>
/// Proxies only…: the plan (each original hashed and weighed against the home, read now), confirmed by the user, then
/// applied; the home out of reach, or anything changed since the plan, removes nothing.
/// </summary>
private async Task ProxiesOnlyAsync()
{
try
{
await StoreEditAsync();
if (await MediaRefusalAsync() is { } refusal)
{
_ui.Notify(Loc.L("Editor.Workspace.OriginalsNotRemoved"), refusal, isError: true);
return;
}
SetChangingMedia(true);
var plan = await _host.PlanProxiesOnlyAsync(ProjectId);
if (_disposed) return;
var detail = new List<string>
{
Loc.L("Editor.ProxiesOnly.Originals", Formatting.Count(plan.Originals)),
Loc.L("Editor.ProxiesOnly.Size", Formatting.Bytes(plan.Bytes)),
};
if (plan.ToTrash > 0) detail.Add(Loc.L("Editor.ProxiesOnly.ToTrash", Formatting.Count(plan.ToTrash)));
if (!_ui.Confirm(new ConfirmRequest
{
Heading = Loc.L("Editor.ProxiesOnly.Title", Name),
Message = WorkspaceText.ForHome("Editor.ProxiesOnly.Message", IsServerHome),
Detail = string.Join(Environment.NewLine, detail),
IsDetailMonospaced = false,
DetailToolTip = plan.ToTrash > 0 ? WorkspaceText.ForHome("Tooltips.Editor.ProxiesOnly.ToTrash", IsServerHome) : null,
SafeText = Loc.L("Editor.Project.Keep"),
SafeToolTip = Loc.L("Tooltips.Editor.ProxiesOnly.Keep"),
ActionText = Loc.L("Editor.ProxiesOnly.Action"),
ActionToolTip = Loc.L("Tooltips.Editor.ProxiesOnly.Action"),
IsDestructive = true,
}))
return;
var trashed = await _host.ProxiesOnlyAsync(ProjectId, plan);
if (_disposed) return;
await _session.ReloadAsync();
_ui.Notify(Loc.L("Editor.Workspace.OriginalsRemoved"),
trashed > 0 ? Loc.L("Editor.ProxiesOnly.ToTrash", Formatting.Count(trashed)) : _session.Content.Sequence.DisplayTitle);
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
Log.Warning("workspace", $"The originals of project {ProjectId} were not removed", ex);
_ui.Notify(Loc.L("Editor.Workspace.OriginalsNotRemoved"), WorkspaceText.Failure(ex, IsServerHome), isError: true);
}
finally
{
SetChangingMedia(false);
await RefreshAsync();
}
}
/// <summary>
/// Why the media cannot change now (<c>Errors.Workspace.MediaBusy</c>): changes not saved as a version, a copy or sync
/// running, or an analysis, render or workspace job of the sequence waiting or running; null when they can.
/// </summary>
private async Task<string?> MediaRefusalAsync()
{
var local = await _host.StatusAsync(ProjectId, askHome: false);
if (_disposed) return null;
Apply(WithLocal(_status, local));
if (IsMediaBusy) return Loc.L("Errors.Workspace.MediaBusy");
var jobs = await _source.ListJobsAsync(CancellationToken.None);
var sequenceId = SequenceId;
return jobs.Any(j => j.State is JobState.Queued or JobState.Running or JobState.Paused && j.TargetIds.Contains(sequenceId)
&& j.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render or JobKind.WorkspaceCopy or JobKind.WorkspaceRender
or JobKind.WorkspaceSend)
? Loc.L("Errors.Workspace.MediaBusy")
: null;
}
/// <summary>The copy of the originals ended: said, with the frames that have none (they stay proxies, and a local render waits for them).</summary>
private void NotifyOriginalsCopied()
{
int missing;
try
{
missing = _source.Project.ReadMedia()?.Frames.Count(f => f.Original is null) ?? 0;
}
catch (Exception ex) when (ex is System.IO.IOException or System.IO.InvalidDataException or UnauthorizedAccessException)
{
Log.Warning("workspace", $"The media of project {ProjectId} could not be read after the copy of its originals", ex);
missing = 0;
}
if (missing == 0) _ui.Notify(Loc.L("Editor.Workspace.OriginalsCopied"), _session.Content.Sequence.DisplayTitle);
else _ui.Notify(Loc.L("Editor.Workspace.OriginalsCopied"), Loc.L("Editor.Workspace.OriginalsMissing", Formatting.Count(missing)));
}
private void SetChangingMedia(bool changing)
{
_changingMedia = changing;
RaiseState();
}
/// <summary>The editor's last edit stored in the working state before an operation reads it.</summary>
/// <exception cref="WorkspaceException">It could not be stored (it is retried in the background; nothing was lost).</exception>
private async Task StoreEditAsync()
@@ -787,10 +978,13 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
{
if (_disposed || job.Id != _copyJob) return;
_copyJob = Guid.Empty;
var originals = _copyingOriginals;
_copyingOriginals = false;
if (job.State == JobState.Failed) _ui.Notify(Loc.L("Editor.Workspace.CopyFailed"), job.Error ?? _session.Content.Sequence.DisplayTitle, isError: true);
try
{
if (job.State == JobState.Done) await _session.ReloadAsync();
if (job.State == JobState.Done && originals) NotifyOriginalsCopied();
}
catch (Exception ex) when (ex is not OutOfMemoryException)
{
@@ -836,6 +1030,10 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel
OnPropertyChanged(nameof(RemoveCopyToolTip));
OnPropertyChanged(nameof(MediaChangedToolTip));
OnPropertyChanged(nameof(UpdateMediaToolTip));
OnPropertyChanged(nameof(HoldsOriginals));
OnPropertyChanged(nameof(IsMediaBusy));
OnPropertyChanged(nameof(CopyOriginalsToolTip));
OnPropertyChanged(nameof(ProxiesOnlyToolTip));
_updateMedia.RaiseCanExecuteChanged();
CommandManager.InvalidateRequerySuggested();
}
+107 -10
View File
@@ -47,8 +47,9 @@ public static class ProjectNames
/// <summary>
/// "Open in workspace" (owner review 2, R8), asked when a sequence has no project in the workspace yet, and by the project
/// menu's Open project: which project of its home (Main, made from the sequence's settings as they are, or another) or a
/// new one with its name, and the media to copy (proxies; the originals come in phase 5c). Open queues the copy; the
/// sequence opens once it is done.
/// new one with its name, and the media to copy: the proxies, or (phase 5c) the originals besides, to render on this PC,
/// offered while the workspace's drive has room for them (Settings › Workspace › Media chooses the default). Open queues
/// the copy; the sequence opens once it is done.
/// </summary>
public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
{
@@ -56,6 +57,7 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
private readonly bool _server;
private ProjectOption? _selected;
private bool _isNew;
private bool _isOriginals;
/// <param name="taken">The names a new project cannot take (default: those of <paramref name="projects"/>).</param>
/// <param name="copy">What the copy of the media writes and the free space of the workspace's drive; null when not measured (shown as nothing).</param>
@@ -63,8 +65,10 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
/// 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>
/// <param name="defaultMedia">The media chosen first (<see cref="AppSettings.WorkspaceDefaultMedia"/>); the proxies when the originals have no room.</param>
public OpenInWorkspaceDialogViewModel(string sequenceTitle, IReadOnlyList<SequenceProject> projects, Action<ArchiveDialogViewModel> close,
IReadOnlyList<string>? taken = null, WorkspaceCopyFacts? copy = null, IReadOnlyDictionary<Guid, string>? unreadable = null, bool server = false)
IReadOnlyList<string>? taken = null, WorkspaceCopyFacts? copy = null, IReadOnlyDictionary<Guid, string>? unreadable = null, bool server = false,
string defaultMedia = BundleMedia.Proxies)
: base(close)
{
_server = server;
@@ -76,7 +80,11 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
new DialogFact(Loc.L("Editor.OpenWorkspace.Size"), Formatting.Bytes(copy.Bytes), Reason: Loc.L("Tooltips.Editor.OpenWorkspace.Size")),
new DialogFact(Loc.L("Editor.OpenWorkspace.Free"), copy.Free is { } free ? Formatting.Bytes(free) : Loc.L("Server.Sync.None"),
Reason: Loc.L(copy.TooLittleSpace ? "Errors.Workspace.NoRoom" : "Tooltips.Editor.OpenWorkspace.Free")),
.. copy.OriginalsBytes is { } originals
? [new DialogFact(Loc.L("Editor.OpenWorkspace.Originals"), Formatting.Bytes(originals), Reason: Loc.L("Tooltips.Editor.OpenWorkspace.OriginalsSize"))]
: Array.Empty<DialogFact>(),
];
_isOriginals = defaultMedia == BundleMedia.Originals && CanCopyOriginals;
Projects = [.. projects.OrderByDescending(p => p.IsMain).Select(p => new ProjectOption(p, unreadable?.GetValueOrDefault(p.Id)))];
_selected = Projects.FirstOrDefault(p => p.IsAvailable);
_isNew = !HasProjects;
@@ -97,8 +105,8 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
/// <summary>"Copy size" and "Free space", under the media.</summary>
public IReadOnlyList<DialogFact> CopyFacts { get; }
/// <summary>The drive lacks room for the copy: the free space says so (the copy would stop saying how much is missing).</summary>
public bool IsShortOfSpace => Copy?.TooLittleSpace == true;
/// <summary>The drive lacks room for the copy of the media chosen: the free space says so (the copy would stop saying how much is missing).</summary>
public bool IsShortOfSpace => Copy?.TooLittleSpaceFor(Media) == true;
public string Heading => Loc.L("Editor.OpenWorkspace.Title");
@@ -147,11 +155,37 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
public string ProxiesToolTip => WorkspaceText.ForHome("Tooltips.Editor.OpenWorkspace.Proxies", _server);
/// <summary>The proxies, the only media this phase copies.</summary>
public bool IsProxies => true;
/// <summary>The proxies alone: light to edit, renders run where the originals are.</summary>
public bool IsProxies
{
get => !_isOriginals;
set
{
if (value) IsOriginals = false;
}
}
/// <summary>The originals: offered from phase 5c, to render on this PC.</summary>
public bool CanCopyOriginals => false;
/// <summary>The proxies and the originals (phase 5c): renders run on this PC.</summary>
public bool IsOriginals
{
get => _isOriginals;
set
{
if (!Set(ref _isOriginals, value && CanCopyOriginals)) return;
OnPropertyChanged(nameof(IsProxies));
OnPropertyChanged(nameof(IsShortOfSpace));
}
}
/// <summary>The media <see cref="Open"/> copies.</summary>
public string Media => _isOriginals ? BundleMedia.Originals : BundleMedia.Proxies;
/// <summary>The originals can be chosen: the drive has room for them besides the proxies (or was not measured: the copy measures again).</summary>
public bool CanCopyOriginals => Copy?.TooLittleSpaceFor(BundleMedia.Originals) != true;
public string OriginalsToolTip => CanCopyOriginals
? WorkspaceText.ForHome("Tooltips.Editor.OpenWorkspace.OriginalsReady", _server)
: Loc.L("Tooltips.Editor.OpenWorkspace.NoRoomOriginals");
public ICommand OpenCommand { get; }
@@ -169,7 +203,7 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
private void Open()
{
if (!CanOpen) return;
_choice.TrySetResult(_isNew ? new OpenChoice(null, NewName.Text.Trim(), BundleMedia.Proxies) : new OpenChoice(_selected!.Project.Id, null, BundleMedia.Proxies));
_choice.TrySetResult(_isNew ? new OpenChoice(null, NewName.Text.Trim(), Media) : new OpenChoice(_selected!.Project.Id, null, Media));
Close();
}
@@ -181,6 +215,69 @@ public sealed class OpenInWorkspaceDialogViewModel : ArchiveDialogViewModel
}
}
/// <summary>A project of the workspace offered by "Open which project?" (Main in the UI language).</summary>
public sealed record WorkspaceProjectChoice(WorkspaceEntry Entry)
{
public string Label => WorkspaceText.ProjectName(Entry.Name, Entry.IsMain);
public override string ToString() => Label;
}
/// <summary>
/// "Open which project?" (phase 5c, Settings › Workspace › Open project: Ask): Edit asks which of the sequence's projects in
/// the workspace opens, the one opened last chosen first.
/// </summary>
public sealed class OpenProjectDialogViewModel : ArchiveDialogViewModel
{
private readonly TaskCompletionSource<WorkspaceEntry?> _choice = new(TaskCreationOptions.RunContinuationsAsynchronously);
private WorkspaceProjectChoice? _selected;
/// <param name="projects">The sequence's readable projects in the workspace.</param>
/// <param name="last">The project opened last, chosen first; null: Main.</param>
public OpenProjectDialogViewModel(string sequenceTitle, IReadOnlyList<WorkspaceEntry> projects, Guid? last, Action<ArchiveDialogViewModel> close)
: base(close)
{
ArgumentNullException.ThrowIfNull(projects);
Message = Loc.L("Editor.OpenProject.Message", sequenceTitle);
Projects = [.. projects.OrderByDescending(p => p.IsMain).ThenBy(p => p.Name, StringComparer.CurrentCultureIgnoreCase).Select(p => new WorkspaceProjectChoice(p))];
_selected = Projects.FirstOrDefault(p => p.Entry.ProjectId == last) ?? Projects.FirstOrDefault();
OpenCommand = new RelayCommand(Open, () => _selected is not null);
}
/// <summary>Completes with the project chosen, or null when the dialog was closed without one.</summary>
public Task<WorkspaceEntry?> Choice => _choice.Task;
public string Heading => Loc.L("Editor.OpenProject.Title");
public string Message { get; }
public IReadOnlyList<WorkspaceProjectChoice> Projects { get; }
public WorkspaceProjectChoice? SelectedProject
{
get => _selected;
set
{
if (Set(ref _selected, value)) CommandManager.InvalidateRequerySuggested();
}
}
public ICommand OpenCommand { get; }
public override void Dispose()
{
_choice.TrySetResult(null);
base.Dispose();
}
private void Open()
{
if (_selected is null) return;
_choice.TrySetResult(_selected.Entry);
Close();
}
}
/// <summary>Names a project: "New project" (made from the open project's last version at the home) or "Rename".</summary>
public sealed class ProjectNameDialogViewModel : ArchiveDialogViewModel
{
@@ -54,10 +54,10 @@
IsEnabled="{Binding IsNew}" ToolTip="{Binding NewName.ToolTip}" MaxLength="60" AutomationProperties.Name="{l:Loc Editor.OpenWorkspace.New}" />
<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}"
<RadioButton GroupName="Media" Content="{l:Loc Editor.OpenWorkspace.Proxies}" IsChecked="{Binding IsProxies}"
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" />
<RadioButton GroupName="Media" Content="{l:Loc Editor.OpenWorkspace.Originals}" IsEnabled="{Binding CanCopyOriginals}" IsChecked="{Binding IsOriginals}"
ToolTip="{Binding OriginalsToolTip}" ToolTipService.ShowOnDisabled="True" />
</StackPanel>
</Grid>
<!-- What the copy writes and the room the workspace's drive has for it. -->
@@ -88,6 +88,30 @@
</DataTemplate>
<!-- New project and Rename: the name, checked as it is typed. -->
<!-- Open which project? (Settings › Workspace › Open project: Ask): the sequence's projects in the workspace. -->
<DataTemplate DataType="{x:Type ws:OpenProjectDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="460">
<StackPanel>
<TextBlock Text="{Binding Heading}" Style="{StaticResource Text.Title}" />
<TextBlock Text="{Binding Message}" Style="{StaticResource Text.Secondary}" Margin="0,4,0,0" TextWrapping="Wrap" />
<Grid Margin="0,14,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" MinWidth="116" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Editor.OpenWorkspace.Project}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" />
<ComboBox Grid.Column="1" ItemsSource="{Binding Projects}" SelectedItem="{Binding SelectedProject}" DisplayMemberPath="Label"
ToolTip="{l:Loc Tooltips.Editor.OpenProject.Choose}" AutomationProperties.Name="{l:Loc Editor.OpenWorkspace.Project}" />
</Grid>
<DockPanel Margin="0,18,0,0">
<Button DockPanel.Dock="Right" Style="{StaticResource Button.Primary}" Content="{l:Loc Editor.OpenWorkspace.Open}" Command="{Binding OpenCommand}"
ToolTip="{l:Loc Tooltips.Editor.OpenProject.Choose}" 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" />
</DockPanel>
</StackPanel>
</Border>
</DataTemplate>
<DataTemplate DataType="{x:Type ws:ProjectNameDialogViewModel}">
<Border Style="{StaticResource Border.Dialog}" Width="460">
<StackPanel>
@@ -66,6 +66,31 @@ public static class WorkspaceFolderChange
}
}
/// <summary>
/// Settings › Workspace › Move… (phase 5c): the shell's flow over <see cref="MoveAsync(WorkspaceHost, IAppDialogs, Func{Task{bool}}, Action{string})"/>,
/// with its folder picker, confirmation, editor and toasts. True when the move was queued.
/// </summary>
public static Task<bool> MoveAsync(ShellViewModel shell)
{
ArgumentNullException.ThrowIfNull(shell);
throw new NotImplementedException("Moving the workspace folder comes with phase 5c (P6).");
}
/// <summary>
/// Picks the folder the workspace moves to through <paramref name="dialogs"/>, shows its plan
/// (<see cref="WorkspaceHost.PlanMoveAsync"/>) and asks for the user's word, lets <paramref name="closeProject"/> close a
/// workspace project open in the editor (false keeps everything as it is), then queues the move
/// (<see cref="WorkspaceHost.QueueMoveAsync"/>). <paramref name="failed"/> hears why it was refused. True when it was queued.
/// </summary>
public static Task<bool> MoveAsync(WorkspaceHost host, IAppDialogs dialogs, Func<Task<bool>> closeProject, Action<string> failed)
{
ArgumentNullException.ThrowIfNull(host);
ArgumentNullException.ThrowIfNull(dialogs);
ArgumentNullException.ThrowIfNull(closeProject);
ArgumentNullException.ThrowIfNull(failed);
throw new NotImplementedException("Moving the workspace folder comes with phase 5c (P6).");
}
/// <summary>The plan as a confirmation: where Edit's projects come from now, and what stays where it is.</summary>
public static ConfirmRequest Request(WorkspaceFolderPlan plan)
{
@@ -0,0 +1,102 @@
using System.IO;
using Chronos.Core.Project;
using Chronos.Data.Workspaces;
namespace Chronos.App.Workspace;
/// <summary>
/// What the workspace takes of its drive (Settings › Workspace, phase 5c): the projects' media (proxies and originals, which
/// the clean-up and the size limit may remove), the whole folder, and its trash (<see cref="WorkspaceHost.TrashFolder"/>).
/// </summary>
/// <param name="MediaBytes">The bytes of every project's <c>media/</c> folder.</param>
/// <param name="TotalBytes">The bytes of the whole workspace folder, its trash included.</param>
/// <param name="TrashBytes">The bytes of the workspace's trash.</param>
/// <param name="TrashItems">The entries of the workspace's trash (one per copy removed or originals set aside).</param>
public sealed record WorkspaceUsage(long MediaBytes, long TotalBytes, long TrashBytes, int TrashItems)
{
/// <summary>A workspace that holds nothing.</summary>
public static WorkspaceUsage None { get; } = new(0, 0, 0, 0);
}
/// <summary>One entry of the workspace's trash as Empty… lists it: its folder name, size, files and when it was put there.</summary>
public sealed record WorkspaceTrashItem(string Name, long Bytes, int Files, DateTimeOffset Trashed);
/// <summary>
/// The plan of Settings › Workspace › Trash › Empty… (phase 5c): every entry of the workspace's trash and their bytes, and a
/// fingerprint over their names, sizes and times. Emptying erases exactly these entries, and only while the fingerprint
/// still matches (the user types the number of entries to confirm); schedules and the size limit never empty the trash.
/// </summary>
public sealed record WorkspaceTrashPlan(string Folder, IReadOnlyList<WorkspaceTrashItem> Items, long Bytes, string Fingerprint)
{
/// <summary>Nothing to erase: Empty… is disabled.</summary>
public bool IsEmpty => Items.Count == 0;
}
/// <summary>What emptying the workspace's trash erased.</summary>
public sealed record WorkspaceTrashResult(int Items, long Bytes);
/// <summary>
/// The workspace's clean-up side (phase 5c, P4): its usage, the plan and emptying of its trash, and what a local copy's removal
/// keeps of renders not sent and originals the home lost. Stubs until the clean-up lands: usage and the trash read as empty,
/// and a removal finds nothing more to keep.
/// </summary>
public sealed partial class WorkspaceHost
{
/// <summary>What the workspace takes of its drive (<see cref="WorkspaceUsage"/>), measured off the UI thread.</summary>
public Task<WorkspaceUsage> UsageAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(WorkspaceUsage.None);
}
/// <summary>The plan of emptying the workspace's trash (<see cref="WorkspaceTrashPlan"/>); nothing is erased.</summary>
public Task<WorkspaceTrashPlan> PlanTrashAsync(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult(new WorkspaceTrashPlan(Path.Combine(Root, TrashFolder), [], 0, string.Empty));
}
/// <summary>
/// Erases the entries of <paramref name="plan"/> from the workspace's trash for good, after the user typed their number;
/// refused when the trash changed since the plan (<c>Errors.Workspace.TrashChanged</c>).
/// </summary>
/// <exception cref="WorkspaceException">The trash changed since the plan; nothing was erased.</exception>
public Task<WorkspaceTrashResult> EmptyTrashAsync(WorkspaceTrashPlan plan, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(plan);
throw new NotImplementedException("Emptying the workspace's trash comes with phase 5c (P4).");
}
/// <summary>
/// What a local copy's removal plan counts besides its versions (<see cref="WorkspaceRemovalPlan.UnsentRenders"/>,
/// <see cref="WorkspaceRemovalPlan.LastOriginals"/>): renders of its ledger not sent, and originals the home no longer holds.
/// </summary>
private Task<(int UnsentRenders, int LastOriginals)> RemovalMediaAsync(WorkspaceProject project, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(project);
cancellationToken.ThrowIfCancellationRequested();
return Task.FromResult((0, 0));
}
/// <summary>A removal without Discard is refused while the project's ledger holds renders not sent (Send first sends them).</summary>
/// <exception cref="WorkspaceException">Renders wait to be sent.</exception>
private Task EnsureRendersSentAsync(WorkspaceProject project, BundleWorkspace workspace, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(project);
ArgumentNullException.ThrowIfNull(workspace);
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
/// <summary>
/// Before a removed copy's media are deleted, under the project's lease: the originals the home no longer holds with the
/// same SHA-256 moved into <paramref name="aside"/> (the copy's trash entry), never deleted.
/// </summary>
private Task KeepLastOriginalsAsync(WorkspaceProject project, string aside, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(project);
ArgumentException.ThrowIfNullOrEmpty(aside);
cancellationToken.ThrowIfCancellationRequested();
return Task.CompletedTask;
}
}
@@ -0,0 +1,129 @@
using System.IO;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
namespace Chronos.App.Workspace;
/// <summary>
/// The workspace's media (phase 5c, P1): what a copy writes (proxies, and the originals besides), copying the originals of a
/// project, and going back to proxies only.
/// </summary>
public sealed partial class WorkspaceHost
{
/// <summary>A server's proxy when it says nothing of its size: some 1.5 MB, as the copy reckons one at 1920 px.</summary>
private const long ServerProxyEstimate = 1_500_000;
/// <summary>
/// The bytes the first copy of a sequence's media writes into the workspace (the proxies; the originals besides in
/// <see cref="WorkspaceCopyFacts.OriginalsBytes"/>), and the free bytes of the workspace's drive.
/// </summary>
/// <exception cref="WorkspaceException">The index or the archive engine is not open.</exception>
public Task<WorkspaceCopyFacts> CopyFactsAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{
var db = _db() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var archives = _archives() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var root = Root;
return Task.Run(async () =>
{
var (bytes, free) = await WorkspaceJobs.CopyFactsAsync(db, archives, sequenceId, root, cancellationToken).ConfigureAwait(false);
var originals = await WorkspaceOriginals.ArchiveOriginalsBytesAsync(db, archives, sequenceId, cancellationToken: cancellationToken).ConfigureAwait(false);
return new WorkspaceCopyFacts(bytes, free, originals);
}, cancellationToken);
}
/// <summary>
/// What the copy of a sequence of <paramref name="home"/> writes: for this PC's archive as
/// <see cref="CopyFactsAsync(Guid, CancellationToken)"/>; for a server, reckoned from its frames (a proxy some 1.5 MB, the
/// originals as large as the server says they are).
/// </summary>
/// <exception cref="HomeUnavailableException">The server cannot be reached now.</exception>
public Task<WorkspaceCopyFacts> CopyFactsAsync(BundleHome home, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(home);
if (home.IsArchive) return CopyFactsAsync(home.SequenceId, cancellationToken);
var reached = Reachable(home);
var root = Root;
return Task.Run(async () =>
{
var frames = (await reached.FramesAsync(cancellationToken).ConfigureAwait(false)).Frames;
var present = frames.Where(f => (f.Flags & FrameFlags.Missing) == 0).ToList();
return new WorkspaceCopyFacts(present.Count * ServerProxyEstimate, FreeBytes(root), present.Sum(f => Math.Max(0, f.Size)));
}, cancellationToken);
}
/// <summary>
/// "Copy originals…": queues the copy of a workspace project's media with its originals (phase 5c), unless a copy is
/// waiting or running already (that one is returned). The project file says originals once the copy commits.
/// </summary>
/// <exception cref="WorkspaceException">The project is not here, or the workspace folder is being moved.</exception>
public Task<Job> QueueOriginalsCopyAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
var bundle = Existing(projectId).ReadBundle();
Log.Info("workspace", $"Originals of project {projectId} queued for copy");
return await QueueCopyCoreAsync(bundle.Workspace!.Home, projectId, BundleMedia.Originals, bundle.Sequence.Title ?? string.Empty, cancellationToken)
.ConfigureAwait(false);
}, cancellationToken);
/// <summary>
/// The plan of "Proxies only…" (phase 5c): each original of the project hashed and weighed against the home's frames,
/// read now. Nothing is changed.
/// </summary>
/// <exception cref="WorkspaceException">The home cannot be reached to check the originals (<c>Errors.Workspace.OriginalsCheck</c>).</exception>
public Task<WorkspaceProxiesOnlyPlan> PlanProxiesOnlyAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
var project = Existing(projectId);
var home = await CheckedHomeFramesAsync(project, cancellationToken).ConfigureAwait(false);
return WorkspaceOriginals.PlanProxiesOnly(project, home);
}, cancellationToken);
/// <summary>
/// Applies "Proxies only…" as planned (the user confirmed it): the home's frames read again, the plan refused when the
/// project or the home changed since; then the originals the home holds are deleted, the others moved to the trash.
/// </summary>
/// <returns>The originals moved to the workspace's trash.</returns>
/// <exception cref="WorkspaceException">The home cannot be reached, or the workspace folder is being moved.</exception>
/// <exception cref="InvalidOperationException">The project or the home changed since the plan (<c>Errors.Workspace.MediaChanged</c>).</exception>
public Task<int> ProxiesOnlyAsync(Guid projectId, WorkspaceProxiesOnlyPlan plan, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
ArgumentNullException.ThrowIfNull(plan);
EnsureNotMoving();
var project = Existing(projectId);
var home = await CheckedHomeFramesAsync(project, cancellationToken).ConfigureAwait(false);
return await WorkspaceOriginals.ApplyProxiesOnlyAsync(project, plan, home, LockWait, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
/// <summary>The frames of the project's home, as it answers now; one out of reach refuses ("nothing was removed").</summary>
private async Task<HomeFrames> CheckedHomeFramesAsync(WorkspaceProject project, CancellationToken cancellationToken)
{
var named = project.ReadBundle().Workspace!.Home;
var refused = WorkspaceText.ForHome("Errors.Workspace.OriginalsCheck", !named.IsArchive);
var home = HomeOf(named) ?? throw new WorkspaceException(refused);
try
{
return await home.FramesAsync(cancellationToken).ConfigureAwait(false);
}
catch (HomeUnavailableException ex)
{
throw new WorkspaceException(refused, ex);
}
}
/// <summary>Free bytes on the drive of <paramref name="folder"/>; null when it cannot be measured (a network share).</summary>
private static long? FreeBytes(string folder)
{
try
{
var root = Path.GetPathRoot(Path.GetFullPath(folder));
return string.IsNullOrEmpty(root) ? null : new DriveInfo(root).AvailableFreeSpace;
}
catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException)
{
return null;
}
}
}
@@ -0,0 +1,76 @@
using Chronos.Core.Localization;
using Chronos.Core.Model;
namespace Chronos.App.Workspace;
/// <summary>A project of the workspace as the plan of a move lists it: its size, and work not at its home yet (a warning, never a refusal).</summary>
/// <param name="Unsent">Versions or renders wait to be sent to its home.</param>
/// <param name="Modified">Changes not saved as a version.</param>
public sealed record WorkspaceMoveProject(Guid ProjectId, string Name, int Files, long Bytes, bool Unsent, bool Modified);
/// <summary>
/// The plan of Settings › Workspace › Move… (phase 5c): the workspace folder <see cref="From"/> moved with its projects to
/// <see cref="To"/>: the projects and their bytes, the free bytes at the target, whether both lie on one volume (folders
/// renamed) or not (files copied and hash-verified), why it is refused (null when it can go), and a fingerprint of what
/// the plan read, which the move job checks again.
/// </summary>
/// <param name="Free">The free bytes of the target's drive; null when they cannot be measured.</param>
/// <param name="Refusal">
/// Why the move cannot go, one localized sentence: the target is the folder itself or inside it
/// (<c>Errors.Workspace.MoveSameFolder</c>), already holds a workspace or a project of the same id
/// (<c>Errors.Workspace.MoveTargetNotEmpty</c>), lacks the room (<c>Errors.Workspace.DiskFull</c>), or a workspace job is
/// pending or running (<c>Errors.Workspace.JobsRunning</c>); null when it can go.
/// </param>
public sealed record WorkspaceMovePlan(string From, string To, IReadOnlyList<WorkspaceMoveProject> Projects, int Files, long Bytes, long? Free, bool SameVolume,
string? Refusal, string Fingerprint)
{
/// <summary>Nothing refuses the move.</summary>
public bool CanMove => Refusal is null;
/// <summary>Projects with work not at their home: the move keeps it, the plan says so.</summary>
public int Warnings => Projects.Count(p => p.Unsent || p.Modified);
}
/// <summary>
/// Moving the workspace folder with its projects (phase 5c, P6): the plan, the <see cref="JobKind.WorkspaceMove"/> that
/// carries it out, and the workspace that follows the folder once every file is verified there. While a move is queued or
/// running the workspace is refused for syncs, saves and opens (<see cref="EnsureNotMoving"/>). Stubs until the move lands.
/// </summary>
public sealed partial class WorkspaceHost
{
/// <summary>A move of the workspace folder is queued or running: syncs, saves and opens wait for it.</summary>
public bool IsMoving => false;
/// <summary>The plan of moving the workspace folder to <paramref name="to"/> (<see cref="WorkspaceMovePlan"/>); nothing is written.</summary>
public Task<WorkspaceMovePlan> PlanMoveAsync(string to, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(to);
throw new NotImplementedException("Moving the workspace folder comes with phase 5c (P6).");
}
/// <summary>Queues the <see cref="JobKind.WorkspaceMove"/> of a plan the user confirmed.</summary>
/// <exception cref="WorkspaceException">The plan refuses the move.</exception>
public Task<Job> QueueMoveAsync(WorkspaceMovePlan plan, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(plan);
throw new NotImplementedException("Moving the workspace folder comes with phase 5c (P6).");
}
/// <summary>
/// Told by the move job once every file of the workspace is verified at <paramref name="to"/>
/// (<c>WorkspaceJobOptions.Moved</c>): Settings › Workspace names the new folder and the workspace opens there.
/// </summary>
public Task MovedAsync(string from, string to)
{
ArgumentException.ThrowIfNullOrWhiteSpace(from);
ArgumentException.ThrowIfNullOrWhiteSpace(to);
throw new NotImplementedException("Moving the workspace folder comes with phase 5c (P6).");
}
/// <summary>Refuses an operation that writes into the workspace while its folder is being moved.</summary>
/// <exception cref="WorkspaceException">A move is queued or running (<c>Errors.Workspace.Moving</c>).</exception>
private void EnsureNotMoving()
{
if (IsMoving) throw new WorkspaceException(Loc.L("Errors.Workspace.Moving"));
}
}
@@ -0,0 +1,9 @@
namespace Chronos.App.Workspace;
/// <summary>
/// The workspace's local renders (phase 5c, P2): rendering a project from the originals it holds on this PC, and sending its
/// renders home.
/// </summary>
public sealed partial class WorkspaceHost
{
}
+53 -21
View File
@@ -70,8 +70,17 @@ public sealed record WorkspaceFolderPlan(string Current, string Folder, int Proj
}
/// <summary>What "Open in workspace" shows of the copy it queues: its bytes (as the copy reckons them) and the free bytes of the workspace's drive.</summary>
public sealed record WorkspaceCopyFacts(long Bytes, long? Free)
/// <param name="Bytes">What the copy of the proxies writes.</param>
/// <param name="OriginalsBytes">What the copy of the originals writes besides (phase 5c); null when not known.</param>
public sealed record WorkspaceCopyFacts(long Bytes, long? Free, long? OriginalsBytes = null)
{
/// <summary>
/// The drive lacks room for the copy of <paramref name="media"/> (<see cref="BundleMedia.Originals"/>: the proxies and the
/// originals) and the reserve the copy keeps free.
/// </summary>
public bool TooLittleSpaceFor(string media) =>
Free is { } free && free < Bytes + (media == BundleMedia.Originals ? OriginalsBytes ?? 0 : 0) + WorkspaceJobs.CopySpaceReserve;
/// <summary>The drive lacks the copy and the reserve the copy keeps: it would stop saying so.</summary>
public bool TooLittleSpace => Free is { } free && free < Bytes + WorkspaceJobs.CopySpaceReserve;
}
@@ -113,8 +122,20 @@ public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files
/// </summary>
public string? KnownName { get; init; }
/// <summary>
/// Local renders not at the home yet (phase 5c, the project's ledger): Send first sends them, Discard keeps them in the
/// workspace's trash with the rest of the work not sent.
/// </summary>
public int UnsentRenders { get; init; }
/// <summary>
/// Originals the workspace holds that the home no longer holds with the same SHA-256 (phase 5c): they go to the
/// workspace's trash, never deleted, when the copy is removed.
/// </summary>
public int LastOriginals { get; init; }
/// <summary>Everything the copy holds is at the home: it can go without discarding anything.</summary>
public bool IsSafe => Unsent == 0 && !Modified && !Conflict && !Damaged;
public bool IsSafe => Unsent == 0 && UnsentRenders == 0 && !Modified && !Conflict && !Damaged;
}
/// <summary>
@@ -129,7 +150,7 @@ public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files
/// 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
public sealed partial class WorkspaceHost
{
/// <summary>Where discarded work of removed local copies is kept (the store lists only folders named by a project id).</summary>
public const string TrashFolder = ".trash";
@@ -358,20 +379,6 @@ public sealed class WorkspaceHost
Log.Info("workspace", $"The workspace folder is now {plan.Folder} ({plan.ProjectsLeft} project(s) stay in {plan.Current})");
}
/// <summary>The bytes the first copy of a sequence's media writes into the workspace, and the free bytes of the workspace's drive.</summary>
/// <exception cref="WorkspaceException">The index or the archive engine is not open.</exception>
public Task<WorkspaceCopyFacts> CopyFactsAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{
var db = _db() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var archives = _archives() ?? throw new WorkspaceException(Loc.L("Editor.Error.NoEngine"));
var root = Root;
return Task.Run(async () =>
{
var (bytes, free) = await WorkspaceJobs.CopyFactsAsync(db, archives, sequenceId, root, cancellationToken).ConfigureAwait(false);
return new WorkspaceCopyFacts(bytes, free);
}, cancellationToken);
}
/// <summary>The project of <paramref name="sequenceId"/> opened last here, else the one saved last; null when the workspace has none.</summary>
public async Task<WorkspaceEntry?> LastUsedAsync(Guid sequenceId, CancellationToken cancellationToken = default)
{
@@ -388,6 +395,16 @@ public sealed class WorkspaceHost
_savePreferences();
}
/// <summary>
/// Records that Edit opened <paramref name="projectId"/> at <paramref name="at"/> (now when null): the clean-up's Clean
/// after goes by it (phase 5c, <see cref="AppSettings.WorkspaceOpened"/>). Call it on the UI thread, which writes the settings.
/// </summary>
public void RecordOpened(Guid projectId, DateTimeOffset? at = null)
{
_settings.WorkspaceOpened[projectId] = at ?? DateTimeOffset.UtcNow;
_savePreferences();
}
/// <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) =>
HomeProjectsAsync(ArchiveHome(sequenceId), cancellationToken);
@@ -426,6 +443,7 @@ public sealed class WorkspaceHost
var sequenceId = home.SequenceId;
var checkout = await Task.Run(async () =>
{
EnsureNotMoving();
// Refused before anything is written: the copy job would refuse such a folder after the checkout filled it.
if (await InsideALibraryAsync(cancellationToken).ConfigureAwait(false))
throw new WorkspaceException(Loc.L("Errors.Workspace.InsideLibraryEdit", Root)) { FolderRefused = true };
@@ -461,6 +479,7 @@ public sealed class WorkspaceHost
/// </summary>
public Task<Job> QueueCopyAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
var bundle = Existing(projectId).ReadBundle();
return await QueueCopyCoreAsync(bundle.Workspace!.Home, projectId, bundle.Workspace.Media.Kind, bundle.Sequence.Title ?? string.Empty, cancellationToken)
.ConfigureAwait(false);
@@ -516,6 +535,7 @@ public sealed class WorkspaceHost
{
var version = await Task.Run(async () =>
{
EnsureNotMoving();
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
return await Sync.CommitAsync(projectId, note, null, cancellationToken).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
@@ -538,6 +558,7 @@ public sealed class WorkspaceHost
/// <summary>The working state as a new local version without a note and without sending it; null when nothing changed.</summary>
public Task<ProjectVersion?> CommitAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
EnsureWritable(await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false));
return await Sync.CommitAsync(projectId, null, null, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
@@ -551,6 +572,7 @@ public sealed class WorkspaceHost
/// <exception cref="WorkspaceSyncException">The home refused a version for good.</exception>
public Task<WorkspaceSyncResult> SyncAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
var home = HomeOfProject(projectId);
var pulled = await Sync.PullAsync(projectId, home, cancellationToken).ConfigureAwait(false);
// Deleted at the library: nothing to send, nothing to prune; the copy stays as it is.
@@ -570,6 +592,7 @@ public sealed class WorkspaceHost
public Task<WorkspaceSyncResult> ResolveAsync(Guid projectId, ConflictChoice choice, IReadOnlySet<string>? takeServer = null,
WorkspaceConflict? shown = null, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
var home = HomeOfProject(projectId);
WorkspaceSyncResult resolved;
if (choice == ConflictChoice.SaveBoth)
@@ -619,6 +642,7 @@ public sealed class WorkspaceHost
/// </summary>
public Task<ProjectSettings> RestoreAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken = default) => Task.Run(async () =>
{
EnsureNotMoving();
var status = await Sync.StatusAsync(projectId, null, cancellationToken).ConfigureAwait(false);
if (status.ReadOnly) throw new WorkspaceException(Loc.L("Errors.Workspace.ReadOnly"));
if (status.MediaRemoved) throw new WorkspaceException(Loc.L("Errors.Workspace.MediaMissing"));
@@ -766,8 +790,9 @@ public sealed class WorkspaceHost
// A conflict recorded counts as work not at the home, also once the library no longer has the project (Gone asks none);
// one a settling replay took past its commit point is over, as the status reads it.
var conflict = status.Conflict is not null || project.OpenConflict() is not null;
var (unsentRenders, lastOriginals) = await RemovalMediaAsync(project, cancellationToken).ConfigureAwait(false);
return new WorkspaceRemovalPlan(projectId, name, files, bytes, status.Ahead + status.Damaged, status.Modified, conflict, status.Offline,
status.State == WorkspaceState.Gone);
status.State == WorkspaceState.Gone) { UnsentRenders = unsentRenders, LastOriginals = lastOriginals };
}, cancellationToken);
/// <summary>
@@ -802,6 +827,7 @@ public sealed class WorkspaceHost
// 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(Unsent(workspace.Home));
await EnsureRendersSentAsync(project, workspace, cancellationToken).ConfigureAwait(false);
await VerifyHomeAsync(projectId, workspace, cancellationToken).ConfigureAwait(false);
}
await RemoveFolderAsync(project, cancellationToken).ConfigureAwait(false);
@@ -950,6 +976,8 @@ public sealed class WorkspaceHost
}
throw;
}
// Originals the home no longer holds go aside with the rest; only what the home can make again is deleted.
await KeepLastOriginalsAsync(project, aside, cancellationToken).ConfigureAwait(false);
if (Directory.Exists(project.MediaDirectory)) Directory.Delete(project.MediaDirectory, recursive: true);
void Move(string from, string to)
@@ -1007,9 +1035,13 @@ public sealed class WorkspaceHost
private void Forget(Guid sequenceId, Guid projectId)
{
if (!_settings.WorkspaceRecent.TryGetValue(sequenceId, out var known) || known != projectId) return;
_settings.WorkspaceRecent.Remove(sequenceId);
_savePreferences();
var changed = _settings.WorkspaceOpened.Remove(projectId);
if (_settings.WorkspaceRecent.TryGetValue(sequenceId, out var known) && known == projectId)
{
_settings.WorkspaceRecent.Remove(sequenceId);
changed = true;
}
if (changed) _savePreferences();
}
/// <summary>
+18
View File
@@ -105,6 +105,24 @@ public enum JobKind
/// and resumable (owner review 2, R8); stored as 20.
/// </summary>
WorkspaceCopy = 20,
/// <summary>
/// Renders a workspace project from the originals the workspace holds, on this PC, into the project's <c>exports/</c>
/// with a ledger entry per output (owner review 2, R8, phase 5c); stored as 21.
/// </summary>
WorkspaceRender = 21,
/// <summary>
/// Sends a workspace project's local renders home (this PC's archive or its server) with their project and version,
/// each hash-checked and idempotent by render id (owner review 2, R8, phase 5c); stored as 22.
/// </summary>
WorkspaceSend = 22,
/// <summary>
/// Moves the workspace folder with its projects to another folder, journaled and hash-verified across volumes, the
/// source kept until every file is verified (owner review 2, R8, phase 5c); stored as 23.
/// </summary>
WorkspaceMove = 23,
}
/// <summary>Why a photo left a sequence (its tombstone, owner review 2, R6); stored as a number.</summary>
+6 -2
View File
@@ -23,8 +23,9 @@ public sealed record JobPriorityQueue
{
/// <summary>
/// The levels a kind has unless the user changed it: renders, imports and downloads first, and the copy of a project's
/// media into the workspace, which Edit waits for (owner review 2, R8); the long passes that resume anywhere, and the
/// housekeeping of the schedules (backups, clean-ups), last.
/// media into the workspace, which Edit waits for (owner review 2, R8), a workspace's local render and the move of the
/// workspace folder, which Edit is held for (phase 5c); a local render's sending home at the normal level; the long
/// passes that resume anywhere, and the housekeeping of the schedules (backups, clean-ups), last.
/// </summary>
public static IReadOnlyDictionary<JobKind, JobKindPriority> DefaultLevels { get; } = new Dictionary<JobKind, JobKindPriority>
{
@@ -32,6 +33,9 @@ public sealed record JobPriorityQueue
[JobKind.Import] = JobKindPriority.High,
[JobKind.Download] = JobKindPriority.High,
[JobKind.WorkspaceCopy] = JobKindPriority.High,
[JobKind.WorkspaceRender] = JobKindPriority.High,
[JobKind.WorkspaceSend] = JobKindPriority.Normal,
[JobKind.WorkspaceMove] = JobKindPriority.High,
[JobKind.Verify] = JobKindPriority.Low,
[JobKind.Proxies] = JobKindPriority.Low,
[JobKind.Backup] = JobKindPriority.Low,
+3 -3
View File
@@ -558,14 +558,14 @@ internal sealed class SyncTransfers(SyncService sync)
}
}
private static string? SafeFileName(string? name)
internal static string? SafeFileName(string? name)
{
var file = Path.GetFileName(name?.Trim());
return string.IsNullOrEmpty(file) || file.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || file is "." or ".." ? null : file;
}
/// <summary>"name.mp4", else "name (2).mp4", … — an existing export is never replaced.</summary>
private static string Unique(string folder, string fileName)
internal static string Unique(string folder, string fileName)
{
var candidate = Path.Combine(folder, fileName);
var stem = Path.GetFileNameWithoutExtension(fileName);
@@ -693,7 +693,7 @@ internal sealed class SyncTransfers(SyncService sync)
/// manifest's SHA-256 (two attempts). A part as long as the file (a job stopped while hashing it) is only hashed again;
/// a part the server can no longer resume (416) starts over.
/// </summary>
private static async Task<(string Path, string Sha256)> FetchOriginalAsync(ISyncRemote remote, ManifestFrame frame, string staging,
internal static async Task<(string Path, string Sha256)> FetchOriginalAsync(ISyncRemote remote, ManifestFrame frame, string staging,
CancellationToken cancellationToken)
{
if (frame.Sha256.Length == 0) return await FetchUnhashedAsync(remote, frame, staging, cancellationToken).ConfigureAwait(false);
@@ -19,60 +19,6 @@ using SequenceManifest = Chronos.Protocol.SequenceManifest;
namespace Chronos.Data.Workspaces;
/// <summary>Builds the jobs of the workspace (owner review 2, R8), and their handlers for the desktop's engine.</summary>
public static class WorkspaceJobs
{
/// <summary>
/// <see cref="JobKind.WorkspaceCopy"/>: the media of workspace project <paramref name="projectId"/> (checked out first,
/// <see cref="WorkspaceSync.CheckoutAsync"/>) copied from its home, the sequence of this PC's archive.
/// </summary>
public static ArchiveJobRequest Copy(Sequence sequence, string workspaceRoot, Guid projectId, string media = BundleMedia.Proxies)
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentException.ThrowIfNullOrWhiteSpace(workspaceRoot);
return new ArchiveJobRequest(JobKind.WorkspaceCopy, [sequence.Id], sequence.DisplayTitle,
JsonSerializer.Serialize(new WorkspaceCopyParameters(workspaceRoot, projectId, media), WorkspaceJson.Default.WorkspaceCopyParameters), JobPriority.User);
}
/// <summary>
/// <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 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
/// archive's proxies' sizes, an estimate for those it makes), and the free bytes on <paramref name="workspaceRoot"/>'s
/// drive (null when it cannot be measured): "Open in workspace" shows both. The copy keeps <see cref="CopySpaceReserve"/>
/// free besides.
/// </summary>
/// <exception cref="InvalidOperationException">The index has no such sequence or archive.</exception>
public static Task<(long Bytes, long? Free)> CopyFactsAsync(ChronosDatabase db, ArchiveService archives, Guid sequenceId, string workspaceRoot,
CancellationToken cancellationToken = default) =>
new WorkspaceCopyJobHandler(db, archives).FactsAsync(sequenceId, workspaceRoot, cancellationToken);
/// <summary>Bytes the copy leaves free on the workspace's drive besides what it copies.</summary>
public static long CopySpaceReserve => WorkspaceCopyJobHandler.SpaceReserve;
}
/// <summary>
/// <see cref="JobKind.WorkspaceCopy"/> for a sequence of this PC's archive (owner review 2, R8): its proxies into the
/// workspace project's <c>media/proxies/&lt;frame id&gt;.jpg</c>, the archive's own when current, else made here from the
@@ -91,7 +37,14 @@ public static class WorkspaceJobs
/// removes the media it wrote itself, once it has stopped writing and under the project's lease, unless another copy of the
/// 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.
/// With <see cref="BundleMedia.Originals"/> (phase 5c) the proxies are copied first as above, then each frame's original into
/// <c>media/originals/&lt;frame id&gt;-&lt;sha8&gt;&lt;ext&gt;</c> (<see cref="WorkspaceProject.OriginalName"/>): streamed into a
/// <c>.part</c> file and hashed as it is written, the SHA-256 checked against the home's (recorded as copied when the home has
/// none), the file read back after its rename; one already there with the same SHA-256 is kept. A frame whose original the
/// home lacks (gone, flagged missing or damaged, refused by a server, not matching its SHA-256 twice) keeps its proxy: the
/// copy finishes saying how many. The space reckoned adds the originals not held yet; the checkpoint of that stage is
/// <c>originals:&lt;frame&gt;:&lt;frames version&gt;:&lt;folder&gt;</c>. Originals the committed media no longer name are deleted
/// only when the home holds a frame of the same SHA-256, else kept in the workspace's trash (<see cref="WorkspaceOriginals"/>).
/// 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
@@ -135,8 +88,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
{
var ct = context.Cancellation;
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.Media is not (BundleMedia.Proxies or BundleMedia.Originals)) throw new InvalidDataException(Loc.L("Errors.Workspace.Parameters"));
if (parameters.Server is { Length: > 0 } server)
{
await RunFromServerAsync(context, parameters, server).ConfigureAwait(false);
@@ -313,6 +265,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
// Read only: a read-only archive is copied from like any other.
if (ArchiveVolume.Probe(paths) == ArchiveAvailability.Offline) throw new ArchiveOfflineException(archive.RootPath, ArchiveAvailability.Offline);
var (copied, checkpointVersion, checkpointFolder) = Parse(context.Checkpoint);
var withOriginals = parameters.Media == BundleMedia.Originals;
for (var pass = 1; ; pass++)
{
var (row, frames) = await FramesAsync(sequenceId, ct).ConfigureAwait(false);
@@ -328,15 +281,18 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
// Files kept from an earlier run are this frames version's and this folder's only (a conversion keeps a frame's id,
// not its photo; a sequence moved meanwhile may have left its photos' names to another sequence's).
if ((checkpointVersion is { } version && version != row.FramesVersion) || (checkpointFolder is { } read && read != row.Folder)) copied = 0;
var total = (long)frames.Count;
var total = (long)frames.Count * (withOriginals ? 2 : 1);
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) ?? [];
var held = TryReadMedia(project)?.Frames ?? [];
var current = held.Where(f => f.File is not null).ToDictionary(f => f.Id);
var heldOriginals = held.Where(f => f.Original is not null).ToDictionary(f => f.Id);
Directory.CreateDirectory(project.ProxiesDirectory);
// The workspace is on this PC's own drive, with the index, the settings and the logs: the copy never fills it.
var remaining = Remaining(project, folder, frames, policy);
EnsureSpace(parameters.WorkspaceRoot, remaining[0]);
var originalsLeft = withOriginals ? RemainingOriginals(project, frames, heldOriginals, (f, _) => f.Size) : new long[frames.Count + 1];
EnsureSpace(parameters.WorkspaceRoot, remaining[0] + originalsLeft[0]);
var clock = System.Diagnostics.Stopwatch.StartNew();
for (var i = 0; i < frames.Count; i++)
{
@@ -346,7 +302,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
{
await context.CheckpointAsync(Checkpoint(Stage.Copy, i + 1, row.FramesVersion, row.Folder), i + 1, total).ConfigureAwait(false);
// Another program may take the space meanwhile.
EnsureSpace(parameters.WorkspaceRoot, remaining[i + 1]);
EnsureSpace(parameters.WorkspaceRoot, remaining[i + 1] + originalsLeft[0]);
clock.Restart();
}
else
@@ -354,6 +310,27 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
await context.ReportAsync(i + 1, total).ConfigureAwait(false);
}
}
var originals = new OriginalsTally();
if (withOriginals)
{
for (var i = 0; i < frames.Count; i++)
{
ct.ThrowIfCancellationRequested();
entries[i] = await CopyOriginalAsync(project, paths, frames[i], entries[i], heldOriginals.GetValueOrDefault(frames[i].Id),
originals, ct).ConfigureAwait(false);
var done = frames.Count + i + 1;
if (clock.Elapsed >= CheckpointEvery)
{
await context.CheckpointAsync(Checkpoint(Stage.Originals, i + 1, row.FramesVersion, row.Folder), done, total).ConfigureAwait(false);
EnsureSpace(parameters.WorkspaceRoot, originalsLeft[i + 1]);
clock.Restart();
}
else
{
await context.ReportAsync(done, total).ConfigureAwait(false);
}
}
}
var analysis = CopyAnalysis(folder, project, frames.Count);
var (after, now) = await FramesAsync(sequenceId, ct).ConfigureAwait(false);
var moved = after.Folder != row.Folder || !SequenceFolders.Holds(paths.Sequence(after.Folder), sequenceId) || Renamed(frames, now, entries);
@@ -376,15 +353,16 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
}
}
var aliases = await HomePhotos.AliasesAsync(db, sequenceId, ct).ConfigureAwait(false);
var media = new WorkspaceMedia(WorkspaceMedia.FormatName, WorkspaceMedia.CurrentFormatVersion, BundleMedia.Proxies, sequenceId, row.FramesVersion, entries,
var media = new WorkspaceMedia(WorkspaceMedia.FormatName, WorkspaceMedia.CurrentFormatVersion, parameters.Media, sequenceId, row.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, row.Folder, row.DisplayTitle);
RemoveStale(project, media);
RemoveStale(project, media, frames);
}
context.Log(Loc.L("Archive.Log.WorkspaceCopied", row.DisplayTitle, tally.Copied, tally.Made, tally.Kept, tally.Missing));
if (withOriginals) originals.LogTo(context, "Archive.Log.WorkspaceOriginals", row.DisplayTitle);
await context.CheckpointAsync(Checkpoint(Stage.Done, frames.Count, row.FramesVersion, row.Folder), total, total).ConfigureAwait(false);
return;
}
@@ -426,6 +404,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
CancellationToken ct)
{
var (copied, checkpointVersion, checkpointFolder) = Parse(context.Checkpoint);
var withOriginals = parameters.Media == BundleMedia.Originals;
// 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++)
@@ -433,15 +412,20 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
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 total = (long)frames.Count * (withOriginals ? 2 : 1);
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) ?? [];
var held = TryReadMedia(project)?.Frames ?? [];
var current = held.Where(f => f.File is not null).ToDictionary(f => f.Id);
var heldOriginals = held.Where(f => f.Original 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 originalsLeft = withOriginals
? RemainingOriginals(project, frames, heldOriginals, (f, _) => assets.GetValueOrDefault(f.Id) is { } asset ? asset.Size : 0)
: new long[frames.Count + 1];
EnsureSpace(parameters.WorkspaceRoot, remaining[0] + originalsLeft[0]);
var clock = System.Diagnostics.Stopwatch.StartNew();
var options = new ParallelOptions { MaxDegreeOfParallelism = Downloads, CancellationToken = ct };
for (var start = 0; start < frames.Count; start += DownloadBatch)
@@ -455,7 +439,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
{
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]);
EnsureSpace(parameters.WorkspaceRoot, remaining[end] + originalsLeft[0]);
clock.Restart();
}
else
@@ -464,6 +448,27 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
}
}
foreach (var entry in entries.Where(e => e.File is not null)) fetched[entry.Id] = entry;
var originals = new OriginalsTally();
if (withOriginals)
{
for (var start = 0; start < frames.Count; start += DownloadBatch)
{
var end = Math.Min(frames.Count, start + DownloadBatch);
await Parallel.ForEachAsync(Enumerable.Range(start, end - start), options, async (i, token) =>
entries[i] = await DownloadOriginalAsync(remote, project, frames[i], assets.GetValueOrDefault(frames[i].Id), entries[i],
heldOriginals.GetValueOrDefault(frames[i].Id), originals, token).ConfigureAwait(false)).ConfigureAwait(false);
if (clock.Elapsed >= CheckpointEvery || end == frames.Count)
{
await context.CheckpointAsync(Checkpoint(Stage.Originals, end, framesVersion, folder), frames.Count + end, total).ConfigureAwait(false);
EnsureSpace(parameters.WorkspaceRoot, originalsLeft[end]);
clock.Restart();
}
else
{
await context.ReportAsync(frames.Count + end, total).ConfigureAwait(false);
}
}
}
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)
@@ -476,15 +481,16 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
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,
var media = new WorkspaceMedia(WorkspaceMedia.FormatName, WorkspaceMedia.CurrentFormatVersion, parameters.Media, 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);
RemoveStale(project, media, frames);
}
context.Log(Loc.L("Archive.Log.WorkspaceDownloaded", sequence.DisplayTitle, tally.Copied, tally.Made, tally.Kept, tally.Missing));
if (withOriginals) originals.LogTo(context, "Archive.Log.WorkspaceOriginalsDownloaded", sequence.DisplayTitle);
await context.CheckpointAsync(Checkpoint(Stage.Done, frames.Count, framesVersion, folder), total, total).ConfigureAwait(false);
return;
}
@@ -626,6 +632,166 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
entry is { FileSha256: { } held } && string.Equals(held, sha, StringComparison.OrdinalIgnoreCase) ? entry.FileKind ?? ProxyCache.Proxy : null;
}
/// <summary>
/// A frame's original from this PC's archive into <c>media/originals/</c> (phase 5c), beside its proxy in
/// <paramref name="entry"/>: kept when the workspace holds it already with the same SHA-256, else streamed into a
/// <c>.part</c> file hashed as it is written (never held in memory), checked against the home's SHA-256, renamed and read
/// back. A frame flagged missing or damaged at the home, or whose file is gone, keeps its proxy alone; so does one whose
/// original twice does not match the SHA-256 the home has of it (the part is removed, the copy goes on).
/// </summary>
private static async Task<WorkspaceFrame> CopyOriginalAsync(WorkspaceProject project, ArchivePaths paths, Frame frame, WorkspaceFrame entry,
WorkspaceFrame? held, OriginalsTally tally, CancellationToken cancellationToken)
{
var extension = OriginalExtension(frame);
var expected = string.IsNullOrEmpty(frame.Sha256) ? null : frame.Sha256.ToLowerInvariant();
if ((frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0) return tally.Missed(entry, frame.Index);
if (await HeldOriginalAsync(project, frame, expected, extension, held, cancellationToken).ConfigureAwait(false) is { } kept)
{
tally.Keep();
return entry with { Original = kept.Name, OriginalSha256 = kept.Sha256, OriginalBytes = kept.Bytes };
}
var source = paths.FromRelative(frame.RelativePath);
if (!File.Exists(source)) return tally.Missed(entry, frame.Index);
Directory.CreateDirectory(project.OriginalsDirectory);
var part = Path.Combine(project.OriginalsDirectory, frame.Id.ToString("N") + ".part");
for (var attempt = 1; ; attempt++)
{
string sha;
long bytes;
try
{
await using var input = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, StreamBuffer,
FileOptions.Asynchronous | FileOptions.SequentialScan);
await using var output = new FileStream(part, FileMode.Create, FileAccess.Write, FileShare.None, StreamBuffer, FileOptions.Asynchronous);
using var hashing = new HashingStream(output);
await input.CopyToAsync(hashing, StreamBuffer, cancellationToken).ConfigureAwait(false);
output.Flush(flushToDisk: true);
(sha, bytes) = (hashing.Sha256(), hashing.Written);
}
catch (FileNotFoundException)
{
// Gone while it was read (a Reorganize): the frame keeps its proxy, the pass's check of the folder decides the rest.
TryDelete(part);
return tally.Missed(entry, frame.Index);
}
catch (OperationCanceledException)
{
// A part is never resumed from (a source is read whole): it goes, so a cancel leaves nothing half written.
TryDelete(part);
throw;
}
if (expected is not null && sha != expected)
{
TryDelete(part);
if (attempt == 1) continue;
Log.Warning("workspace", Loc.L("Errors.Workspace.OriginalMismatch", source));
return tally.Missed(entry, frame.Index);
}
var name = WorkspaceProject.OriginalName(frame.Id, sha, extension);
var target = project.MediaFile(name);
File.Move(part, target, overwrite: true);
if (string.Equals(await ContentHash.Sha256Async(target, cancellationToken: cancellationToken).ConfigureAwait(false), sha, StringComparison.OrdinalIgnoreCase))
{
tally.Copy();
return entry with { Original = name, OriginalSha256 = sha, OriginalBytes = bytes };
}
TryDelete(target);
if (attempt == 2) throw new IOException(Loc.L("Errors.Workspace.CopyMismatch", target));
}
}
/// <summary>
/// A frame's original from a server into <c>media/originals/</c> (phase 5c): kept when held already, else downloaded with
/// <see cref="SyncTransfers.FetchOriginalAsync"/> (resumable, checked against the server's SHA-256, two attempts) into a
/// staging folder beside the originals, then renamed into place. A frame the server has no original of (flagged missing
/// or damaged, 404), one this account may not read (403), or one that does not match twice keeps its proxy alone.
/// </summary>
private static async Task<WorkspaceFrame> DownloadOriginalAsync(ISyncRemote remote, WorkspaceProject project, Frame frame, ManifestFrame? asset, WorkspaceFrame entry,
WorkspaceFrame? held, OriginalsTally tally, CancellationToken cancellationToken)
{
if (asset is null || (frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0 || (((FrameFlags)asset.Flags) & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0)
return tally.Missed(entry, frame.Index);
var extension = Path.GetExtension(asset.FileName);
var expected = string.IsNullOrEmpty(asset.Sha256) ? null : asset.Sha256.ToLowerInvariant();
if (await HeldOriginalAsync(project, frame, expected, extension, held, cancellationToken).ConfigureAwait(false) is { } kept)
{
tally.Keep();
return entry with { Original = kept.Name, OriginalSha256 = kept.Sha256, OriginalBytes = kept.Bytes };
}
var staging = Path.Combine(project.OriginalsDirectory, OriginalsStaging);
Directory.CreateDirectory(staging);
string path, sha;
try
{
(path, sha) = await SyncTransfers.FetchOriginalAsync(remote, asset, staging, cancellationToken).ConfigureAwait(false);
}
catch (ChronosApiException ex) when (ex.Status is HttpStatusCode.NotFound or HttpStatusCode.Forbidden)
{
return tally.Missed(entry, frame.Index);
}
catch (InvalidDataException ex)
{
Log.Warning("workspace", $"The original of frame {frame.Id} did not match the server's SHA-256", ex);
return tally.Missed(entry, frame.Index);
}
var name = WorkspaceProject.OriginalName(frame.Id, sha, extension);
var target = project.MediaFile(name);
var bytes = new FileInfo(path).Length;
File.Move(path, target, overwrite: true);
tally.Copy();
return entry with { Original = name, OriginalSha256 = sha, OriginalBytes = bytes };
}
/// <summary>
/// The original the workspace holds of <paramref name="frame"/>, hashed again: the one the media name for it (the same
/// photo, of the SHA-256 the home has when it has one), else the file a copy of <paramref name="expected"/> takes; null when
/// none holds it (a file that no longer matches is copied anew).
/// </summary>
private static async Task<(string Name, string Sha256, long Bytes)?> HeldOriginalAsync(WorkspaceProject project, Frame frame, string? expected, string extension,
WorkspaceFrame? held, CancellationToken cancellationToken)
{
var candidates = new List<(string Name, string? Sha)>();
if (held is { Original: { } heldName, OriginalSha256: { } heldSha } && SamePhoto(held, frame) && (expected is null || string.Equals(heldSha, expected, StringComparison.OrdinalIgnoreCase)))
candidates.Add((heldName, heldSha.ToLowerInvariant()));
if (expected is not null) candidates.Add((WorkspaceProject.OriginalName(frame.Id, expected, extension), expected));
foreach (var (name, sha) in candidates)
{
var path = project.MediaFile(name);
if (!File.Exists(path)) continue;
var found = await ContentHash.Sha256Async(path, cancellationToken: cancellationToken).ConfigureAwait(false);
if (string.Equals(found, sha, StringComparison.OrdinalIgnoreCase)) return (name, found.ToLowerInvariant(), new FileInfo(path).Length);
}
return null;
}
/// <summary>
/// The bytes a copy of the originals still writes from each frame on (index <c>i</c>: frames <c>i</c> to the last; one
/// more entry, 0): <paramref name="size"/> of each frame whose original the workspace does not hold yet under the name a
/// copy gives it, nothing for one the media name already, or flagged missing.
/// </summary>
private static long[] RemainingOriginals(WorkspaceProject project, List<Frame> frames, Dictionary<Guid, WorkspaceFrame> held, Func<Frame, int, long> size)
{
var remaining = new long[frames.Count + 1];
for (var i = frames.Count - 1; i >= 0; i--)
{
var frame = frames[i];
var there = (held.GetValueOrDefault(frame.Id) is { Original: { } name } && File.Exists(project.MediaFile(name)))
|| (!string.IsNullOrEmpty(frame.Sha256) && File.Exists(project.MediaFile(WorkspaceProject.OriginalName(frame.Id, frame.Sha256, OriginalExtension(frame)))));
var bytes = there || (frame.Flags & FrameFlags.Missing) != 0 ? 0 : Math.Max(0, size(frame, i));
remaining[i] = remaining[i + 1] + bytes;
}
return remaining;
}
/// <summary>The extension of a frame's original as its path at the home has it (else its file name), which decoders go by.</summary>
private static string OriginalExtension(Frame frame) => Path.GetExtension(frame.RelativePath) is { Length: > 0 } extension ? extension : Path.GetExtension(frame.FileName);
/// <summary>The folder beside the originals a download from a server stages them in (resumable parts), emptied by the commit.</summary>
private const string OriginalsStaging = ".staging";
/// <summary>The buffer an original is streamed through.</summary>
private const int StreamBuffer = 1 << 20;
/// <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,
@@ -839,7 +1005,7 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
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 workspace = bundle.Workspace! with { Media = new BundleMedia(media.Kind, media.FramesVersion) };
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.
@@ -868,8 +1034,36 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
/// <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.
/// copies, removed so the media folder holds the frames listed. Media of kind originals (phase 5c) clear their folder
/// alike, but an original is never erased on a guess: one the media no longer name is deleted only when the home's
/// frames (<paramref name="home"/>, as this copy read them) hold a photo of its SHA-256, else it goes to the workspace's
/// trash (<see cref="WorkspaceOriginals.DeleteOrTrash"/>). A copy of the proxies alone leaves the originals as they are.
/// </summary>
private static void RemoveStale(WorkspaceProject project, WorkspaceMedia media, IReadOnlyList<Frame> home)
{
RemoveStale(project, media);
if (!media.HoldsOriginals || !Directory.Exists(project.OriginalsDirectory)) return;
var staging = Path.Combine(project.OriginalsDirectory, OriginalsStaging);
if (Directory.Exists(staging))
{
try
{
Directory.Delete(staging, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("workspace", $"{staging} could not be removed", ex);
}
}
var originals = media.Frames.Where(f => f.Original is not null).Select(f => Path.GetFileName(f.Original!)).ToHashSet(StringComparer.OrdinalIgnoreCase);
var stale = Directory.EnumerateFiles(project.OriginalsDirectory).Where(f => !originals.Contains(Path.GetFileName(f))).ToList();
foreach (var part in stale.Where(IsPart)) TryDelete(part);
WorkspaceOriginals.DeleteOrTrash(project, [.. stale.Where(f => !IsPart(f))], home);
}
private static bool IsPart(string file) => file.EndsWith(".part", StringComparison.OrdinalIgnoreCase);
/// <summary>The proxies' folder cleared as <see cref="RemoveStale(WorkspaceProject, WorkspaceMedia, IReadOnlyList{Frame})"/> says.</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);
@@ -943,6 +1137,18 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
return (Remaining([], paths.Sequence(row.Folder), frames, policy)[0], FreeBytes(workspaceRoot));
}
/// <summary>
/// The bytes a copy of the sequence's originals writes (phase 5c): every frame's original the archive has, or, for a
/// workspace project that holds some already (<paramref name="project"/>), only those it lacks.
/// </summary>
internal async Task<long> OriginalsBytesAsync(Guid sequenceId, WorkspaceProject? project, CancellationToken cancellationToken)
{
var (_, frames) = await FramesAsync(sequenceId, cancellationToken).ConfigureAwait(false);
if (project is null || !File.Exists(project.MediaIndexPath)) return frames.Where(f => (f.Flags & FrameFlags.Missing) == 0).Sum(f => Math.Max(0, f.Size));
var held = (TryReadMedia(project)?.Frames ?? []).Where(f => f.Original is not null).ToDictionary(f => f.Id);
return RemainingOriginals(project, frames, held, (f, _) => f.Size)[0];
}
/// <summary>A proxy's size when the archive has none to measure: some 1.5 MB at 1920 px, scaled by the area at the copy's long edge.</summary>
private static long Estimate(Frame frame, ProxyPolicy policy)
{
@@ -1034,6 +1240,9 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
{
Copy,
Done,
/// <summary>The proxies are copied; the originals are (phase 5c).</summary>
Originals,
}
private static string Checkpoint(Stage stage, int frame, int framesVersion, string folder) =>
@@ -1048,11 +1257,46 @@ internal sealed class WorkspaceCopyJobHandler(ChronosDatabase db, ArchiveService
private static (int Copied, int? FramesVersion, string? Folder) Parse(string? checkpoint)
{
var parts = checkpoint?.Split(':', 4);
if (parts is not ([_, _] or [_, _, _] or [_, _, _, _]) || !Enum.TryParse<Stage>(parts[0], ignoreCase: true, out var stage) || stage != Stage.Copy
if (parts is not ([_, _] or [_, _, _] or [_, _, _, _]) || !Enum.TryParse<Stage>(parts[0], ignoreCase: true, out var stage) || stage is not (Stage.Copy or Stage.Originals)
|| !int.TryParse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var next))
return (0, null, null);
int? version = parts.Length >= 3 && int.TryParse(parts[2], NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var v) ? v : null;
return (next, version, parts.Length == 4 ? parts[3] : null);
return (stage == Stage.Originals ? int.MaxValue : next, version, parts.Length == 4 ? parts[3] : null);
}
/// <summary>What a copy of the originals did with each frame (phase 5c), counted from the workers that download them at once.</summary>
private sealed class OriginalsTally
{
/// <summary>Frames named one by one in the job's log when they have no original; the count says the rest.</summary>
private const int Named = 20;
private readonly System.Collections.Concurrent.ConcurrentQueue<(int Index, string Name)> _missed = new();
private int _copied;
private int _kept;
public int Copied => Volatile.Read(ref _copied);
public int Kept => Volatile.Read(ref _kept);
public int Missing => _missed.Count;
public void Copy() => Interlocked.Increment(ref _copied);
public void Keep() => Interlocked.Increment(ref _kept);
/// <summary>The frame keeps its proxy alone: <paramref name="entry"/> with no original.</summary>
public WorkspaceFrame Missed(WorkspaceFrame entry, int index)
{
_missed.Enqueue((index, entry.FileName));
return entry with { Original = null, OriginalSha256 = null, OriginalBytes = 0 };
}
/// <summary>Says in the job's log what was copied (<paramref name="key"/>), and names the first frames without an original.</summary>
public void LogTo(JobContext context, string key, string title)
{
foreach (var (_, name) in _missed.OrderBy(m => m.Index).Take(Named)) context.Log(Loc.L("Archive.Log.WorkspaceOriginalMissing", title, name));
context.Log(Loc.L(key, title, Copied, Kept, Missing));
}
}
/// <summary>What a copy did with each frame, counted from the workers that download them at once.</summary>
@@ -0,0 +1,183 @@
using System.Text.Json;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Sync;
namespace Chronos.Data.Workspaces;
/// <summary>
/// What the workspace's job handlers take from the desktop besides the index and the archive engine (phase 5c).
/// </summary>
/// <param name="Processing">
/// Decoders, encoders and tuning of a local render (<see cref="JobKind.WorkspaceRender"/>): the desktop's
/// <see cref="ProcessingService.Options"/>.
/// </param>
/// <param name="HoldTransfers">
/// True while transfers with a server are held (Settings › Server › Pause metered transfers on a metered connection): a
/// <see cref="JobKind.WorkspaceCopy"/> or <see cref="JobKind.WorkspaceSend"/> naming a server is not started then. Never
/// holds a copy from or a send to this PC's archive.
/// </param>
/// <param name="Moved">
/// Told once a <see cref="JobKind.WorkspaceMove"/> verified every file at its target (from, to): the desktop names the new
/// folder in Settings › Workspace and refreshes the workspace; null where nothing follows the folder.
/// </param>
public sealed record WorkspaceJobOptions(ProcessingOptions Processing, Func<bool> HoldTransfers, Func<string, string, Task>? Moved = null)
{
/// <summary>The options of an engine without a processing service of its own: the archive engine's decoders, nothing held, no move followed.</summary>
public static WorkspaceJobOptions For(ArchiveService archives)
{
ArgumentNullException.ThrowIfNull(archives);
return new WorkspaceJobOptions(new ProcessingOptions { Archive = new ArchiveServiceOptions { Decoder = archives.Decoder } }, () => false);
}
}
/// <summary>Builds the jobs of the workspace (owner review 2, R8), and their handlers for the desktop's engine.</summary>
public static class WorkspaceJobs
{
/// <summary>
/// <see cref="JobKind.WorkspaceCopy"/>: the media of workspace project <paramref name="projectId"/> (checked out first,
/// <see cref="WorkspaceSync.CheckoutAsync"/>) copied from its home, the sequence of this PC's archive.
/// </summary>
public static ArchiveJobRequest Copy(Sequence sequence, string workspaceRoot, Guid projectId, string media = BundleMedia.Proxies)
{
ArgumentNullException.ThrowIfNull(sequence);
ArgumentException.ThrowIfNullOrWhiteSpace(workspaceRoot);
return new ArchiveJobRequest(JobKind.WorkspaceCopy, [sequence.Id], sequence.DisplayTitle,
JsonSerializer.Serialize(new WorkspaceCopyParameters(workspaceRoot, projectId, media), WorkspaceJson.Default.WorkspaceCopyParameters), JobPriority.User);
}
/// <summary>
/// <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 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>
/// <see cref="JobKind.WorkspaceRender"/> (phase 5c): workspace project <paramref name="projectId"/> rendered on this PC from
/// the originals its media hold, into its <c>exports/</c>, as <paramref name="renderJson"/> says (Protocol
/// <c>RenderJobParameters</c> with the portable settings: what <see cref="ProcessingJobs"/> writes for a render), each
/// output recorded with <paramref name="projectVersionId"/> in the project's ledger and sent home after. The target is the
/// home's sequence (this PC's archive, or <paramref name="server"/>'s, <see cref="SyncService.ServerKey"/>), so the
/// editor follows it as it follows a render of that sequence.
/// </summary>
public static ArchiveJobRequest Render(Guid sequenceId, string title, string workspaceRoot, Guid projectId, Guid? projectVersionId, string renderJson,
string? server = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(workspaceRoot);
ArgumentException.ThrowIfNullOrWhiteSpace(renderJson);
return new ArchiveJobRequest(JobKind.WorkspaceRender, [sequenceId], title,
JsonSerializer.Serialize(new WorkspaceRenderParameters(workspaceRoot, projectId, projectVersionId, renderJson, server),
WorkspaceJson.Default.WorkspaceRenderParameters), JobPriority.User);
}
/// <summary>
/// <see cref="JobKind.WorkspaceSend"/> (phase 5c): the local renders <paramref name="renderIds"/> of workspace project
/// <paramref name="projectId"/> (every unsent one of its ledger when empty) sent to its home, the sequence of this PC's
/// archive or of <paramref name="server"/> (<see cref="SyncService.ServerKey"/>), with their project and version.
/// </summary>
public static ArchiveJobRequest Send(Guid sequenceId, string title, string workspaceRoot, Guid projectId, IReadOnlyList<Guid> renderIds, string? server = null,
JobPriority priority = JobPriority.User)
{
ArgumentException.ThrowIfNullOrWhiteSpace(workspaceRoot);
ArgumentNullException.ThrowIfNull(renderIds);
return new ArchiveJobRequest(JobKind.WorkspaceSend, [sequenceId], title,
JsonSerializer.Serialize(new WorkspaceSendParameters(workspaceRoot, projectId, [.. renderIds], server), WorkspaceJson.Default.WorkspaceSendParameters),
priority);
}
/// <summary>
/// <see cref="JobKind.WorkspaceMove"/> (phase 5c): the workspace folder <paramref name="from"/> moved with its projects to
/// <paramref name="to"/>, as the plan of fingerprint <paramref name="planFingerprint"/> the user confirmed showed it. The
/// job has no target; its label is the folder it moves to.
/// </summary>
public static ArchiveJobRequest Move(string from, string to, string planFingerprint)
{
ArgumentException.ThrowIfNullOrWhiteSpace(from);
ArgumentException.ThrowIfNullOrWhiteSpace(to);
ArgumentException.ThrowIfNullOrWhiteSpace(planFingerprint);
return new ArchiveJobRequest(JobKind.WorkspaceMove, [], to,
JsonSerializer.Serialize(new WorkspaceMoveParameters(from, to, planFingerprint), WorkspaceJson.Default.WorkspaceMoveParameters), JobPriority.User);
}
/// <summary>The parameters of a <see cref="JobKind.WorkspaceRender"/> job; null when it has none that read.</summary>
public static WorkspaceRenderParameters? RenderParameters(Job job) => Read(job, JobKind.WorkspaceRender, WorkspaceJson.Default.WorkspaceRenderParameters);
/// <summary>The parameters of a <see cref="JobKind.WorkspaceSend"/> job; null when it has none that read.</summary>
public static WorkspaceSendParameters? SendParameters(Job job) => Read(job, JobKind.WorkspaceSend, WorkspaceJson.Default.WorkspaceSendParameters);
/// <summary>The parameters of a <see cref="JobKind.WorkspaceMove"/> job; null when it has none that read.</summary>
public static WorkspaceMoveParameters? MoveParameters(Job job) => Read(job, JobKind.WorkspaceMove, WorkspaceJson.Default.WorkspaceMoveParameters);
/// <summary>The parameters of a <see cref="JobKind.WorkspaceCopy"/> job; null when it has none that read.</summary>
public static WorkspaceCopyParameters? CopyParameters(Job job) => Read(job, JobKind.WorkspaceCopy, WorkspaceJson.Default.WorkspaceCopyParameters);
/// <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) =>
CreateHandlers(db, archives, servers, WorkspaceJobOptions.For(archives));
/// <summary>
/// The handlers of every workspace job (phase 5c): the copy of a project's media, its local render, the sending of its
/// renders home and the move of the workspace folder.
/// </summary>
/// <param name="servers">The connection a copy from, or a send to, a server's sequence goes through (the desktop's signed-in session).</param>
/// <param name="options">The desktop's processing options, its hold on transfers and what follows a moved folder.</param>
public static IReadOnlyList<IJobHandler> CreateHandlers(ChronosDatabase db, ArchiveService archives, ISyncConnector? servers, WorkspaceJobOptions options)
{
ArgumentNullException.ThrowIfNull(db);
ArgumentNullException.ThrowIfNull(archives);
ArgumentNullException.ThrowIfNull(options);
return
[
new WorkspaceCopyJobHandler(db, archives, servers),
new WorkspaceRenderJobHandler(db, archives, options),
new WorkspaceSendJobHandler(db, archives, servers, options),
new WorkspaceMoveJobHandler(db, options),
];
}
/// <summary>
/// What a first copy of a sequence's proxies writes into a workspace, as the copy reckons it before it starts (the
/// archive's proxies' sizes, an estimate for those it makes), and the free bytes on <paramref name="workspaceRoot"/>'s
/// drive (null when it cannot be measured): "Open in workspace" shows both. The copy keeps <see cref="CopySpaceReserve"/>
/// free besides.
/// </summary>
/// <exception cref="InvalidOperationException">The index has no such sequence or archive.</exception>
public static Task<(long Bytes, long? Free)> CopyFactsAsync(ChronosDatabase db, ArchiveService archives, Guid sequenceId, string workspaceRoot,
CancellationToken cancellationToken = default) =>
new WorkspaceCopyJobHandler(db, archives).FactsAsync(sequenceId, workspaceRoot, cancellationToken);
/// <summary>Bytes the copy leaves free on the workspace's drive besides what it copies.</summary>
public static long CopySpaceReserve => WorkspaceCopyJobHandler.SpaceReserve;
private static T? Read<T>(Job job, JobKind kind, System.Text.Json.Serialization.Metadata.JsonTypeInfo<T> info) where T : class
{
ArgumentNullException.ThrowIfNull(job);
if (job.Kind != kind || job.ParametersJson is not { Length: > 0 } json) return null;
try
{
return JsonSerializer.Deserialize(json, info);
}
catch (JsonException)
{
return null;
}
}
}
+40 -3
View File
@@ -17,6 +17,13 @@ namespace Chronos.Data.Workspaces;
/// 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>
/// <param name="Original">
/// The frame's original the workspace holds, relative to the media folder (<see cref="WorkspaceProject.OriginalName"/>:
/// "originals/&lt;frame id&gt;-&lt;sha8&gt;&lt;ext&gt;", phase 5c), in media of kind <see cref="BundleMedia.Originals"/>; null
/// when it holds none (proxies only, or the home had no original of the frame: the proxy stands in for editing).
/// </param>
/// <param name="OriginalSha256">The original's SHA-256 as copied and checked (lower case); null with <paramref name="Original"/>.</param>
/// <param name="OriginalBytes">The original's size as copied; 0 with no original.</param>
public sealed record WorkspaceFrame(
Guid Id,
int Index,
@@ -46,7 +53,10 @@ public sealed record WorkspaceFrame(
string? File,
string? FileSha256,
long FileBytes,
string? FileKind = null)
string? FileKind = null,
string? Original = null,
string? OriginalSha256 = null,
long OriginalBytes = 0)
{
/// <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)
@@ -62,6 +72,24 @@ public sealed record WorkspaceFrame(
[JsonIgnore]
public bool IsStandIn => FileKind == Sync.ProxyCache.Thumb;
/// <summary>The workspace holds the frame's original (media of kind <see cref="BundleMedia.Originals"/>).</summary>
[JsonIgnore]
public bool HasOriginal => Original is not null;
/// <summary>
/// The frame as a render from the workspace's originals reads it (phase 5c): its file is <see cref="Original"/>, and
/// it is flagged missing while the workspace holds no original for it (a render refuses such media first).
/// </summary>
public Frame ToOriginalFrame(Guid sequenceId)
{
var frame = ToFrame(sequenceId);
return frame with
{
RelativePath = Original ?? FileName,
Flags = Original is null ? Flags | FrameFlags.Missing : Flags,
};
}
/// <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()
{
@@ -97,8 +125,10 @@ public sealed record WorkspaceFrame(
/// <summary>
/// What a workspace project holds of its sequence's photos (<c>media/media.json</c>, owner review 2, R8): the kind
/// (<see cref="BundleMedia.Proxies"/>; originals in phase 5c), the sequence and its frames version at the home when they
/// were copied, and every frame in index order. Written last by a copy, so a copy cut short leaves the previous index.
/// (<see cref="BundleMedia.Proxies"/>, or from phase 5c <see cref="BundleMedia.Originals"/>: the proxies plus each frame's
/// original, <see cref="WorkspaceFrame.Original"/>), the sequence and its frames version at the home when they were
/// copied, and every frame in index order. Written last by a copy, so a copy cut short leaves the previous index. An index
/// of phase 5b has no original fields: it reads as proxies only.
/// </summary>
/// <param name="Aliases">The encodings of the sequence's photos a conversion joined at the home (R7, its tombstones of reason
/// "replaced") when the media were copied: a version parked on a photo before its file was converted still finds its frame.</param>
@@ -115,6 +145,13 @@ public sealed record WorkspaceMedia(string Format, int FormatVersion, string Kin
/// <summary>The frames held, as the processing engine reads them.</summary>
public IReadOnlyList<Frame> ToFrames() => [.. Frames.Select(f => f.ToFrame(SequenceId))];
/// <summary>The frames over the originals the workspace holds (<see cref="WorkspaceFrame.ToOriginalFrame"/>), as a local render reads them.</summary>
public IReadOnlyList<Frame> ToOriginalFrames() => [.. Frames.Select(f => f.ToOriginalFrame(SequenceId))];
/// <summary>Media of kind <see cref="BundleMedia.Originals"/>: the proxies plus the originals the frames name.</summary>
[JsonIgnore]
public bool HoldsOriginals => Kind == BundleMedia.Originals;
/// <summary>
/// These media with their photos named as <paramref name="home"/> names them now (owner review 2, R8): a frame copied
/// before the home hashed its photo (a folder adopted, verified since) takes the SHA-256 the home's frame of that id has
@@ -0,0 +1,23 @@
using Chronos.Core.Model;
using Chronos.Data.Jobs;
namespace Chronos.Data.Workspaces;
/// <summary>
/// <see cref="JobKind.WorkspaceMove"/> (phase 5c, <see cref="WorkspaceJobs.Move"/>): the workspace folder moved with its
/// projects, after the plan the user confirmed (its fingerprint checked again): journaled in <c>&lt;from&gt;/.move.json</c>,
/// moved per project on one volume, copied and hash-verified on both sides across volumes, a project's source deleted only
/// once every file of it is verified, resumable from the journal; at the end <see cref="WorkspaceJobOptions.Moved"/> is told.
/// On failure the source stays the workspace and unverified partial copies are removed.
/// </summary>
internal sealed class WorkspaceMoveJobHandler(ChronosDatabase db, WorkspaceJobOptions options) : IJobHandler
{
public JobKind Kind => JobKind.WorkspaceMove;
public Task RunAsync(JobContext context)
{
ArgumentNullException.ThrowIfNull(context);
_ = (db, options);
throw new NotImplementedException("Moving the workspace folder comes with phase 5c (P6).");
}
}
@@ -0,0 +1,186 @@
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Diagnostics;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Projects;
namespace Chronos.Data.Workspaces;
/// <summary>
/// What "Proxies only" (phase 5c) does to a workspace project that holds its originals: <paramref name="Originals"/> files
/// of <paramref name="Bytes"/> the home holds with the same SHA-256, deleted; <paramref name="ToTrash"/> files of
/// <paramref name="TrashBytes"/> it does not (gone there, damaged, or another photo now), moved to the workspace's trash.
/// <paramref name="Fingerprint"/> names the files and the home's answer the plan read: an apply refuses a plan the
/// project or the home changed since.
/// </summary>
public sealed record WorkspaceProxiesOnlyPlan(Guid ProjectId, int Originals, long Bytes, int ToTrash, long TrashBytes, string Fingerprint)
{
/// <summary>Nothing to remove: the project holds no originals.</summary>
public bool IsEmpty => Originals == 0 && ToTrash == 0;
}
/// <summary>
/// The originals of a workspace project (phase 5c): what a copy of them writes, and their removal. An original is never
/// erased on a guess: a file is deleted only when the home holds a photo of its SHA-256, read from the file at that moment,
/// that the home has not flagged missing or damaged; any other goes to the workspace's trash
/// (<c>&lt;root&gt;/.trash/&lt;project id&gt;-&lt;ticks&gt;/originals/</c>, which the clean-up empties).
/// </summary>
public static class WorkspaceOriginals
{
/// <summary>The workspace's trash folder, under its root (the App's <c>WorkspaceHost.TrashFolder</c>).</summary>
public const string TrashFolder = ".trash";
/// <summary>
/// The bytes a copy of the sequence's originals writes from this PC's archive: all the archive has, or only those
/// <paramref name="project"/> lacks when it holds some already.
/// </summary>
public static Task<long> ArchiveOriginalsBytesAsync(ChronosDatabase db, ArchiveService archives, Guid sequenceId, WorkspaceProject? project = null,
CancellationToken cancellationToken = default) =>
new WorkspaceCopyJobHandler(db, archives).OriginalsBytesAsync(sequenceId, project, cancellationToken);
/// <summary>
/// What "Proxies only" removes from <paramref name="project"/>, each original hashed now and weighed against
/// <paramref name="home"/> (the home's frames as read just before): nothing when it holds none.
/// </summary>
/// <exception cref="InvalidDataException">The media index is damaged or newer.</exception>
public static WorkspaceProxiesOnlyPlan PlanProxiesOnly(WorkspaceProject project, HomeFrames home)
{
ArgumentNullException.ThrowIfNull(project);
ArgumentNullException.ThrowIfNull(home);
var files = Files(project);
var held = HeldAtHome(home.Frames);
var fingerprint = new StringBuilder(home.FramesVersion.ToString(CultureInfo.InvariantCulture));
int deleted = 0, trashed = 0;
long deletedBytes = 0, trashedBytes = 0;
foreach (var file in files)
{
var (sha, bytes) = Hash(file);
var atHome = sha is not null && held.Contains(sha);
if (atHome) (deleted, deletedBytes) = (deleted + 1, deletedBytes + bytes);
else (trashed, trashedBytes) = (trashed + 1, trashedBytes + bytes);
fingerprint.Append('|').Append(Path.GetFileName(file)).Append(':').Append(sha).Append(':').Append(atHome ? 'd' : 't');
}
var digest = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(fingerprint.ToString())));
return new WorkspaceProxiesOnlyPlan(project.ProjectId, deleted, deletedBytes, trashed, trashedBytes, digest);
}
/// <summary>
/// Applies a plan of <see cref="PlanProxiesOnly"/> under the project's lease: planned again, refused when anything changed
/// (<c>Errors.Workspace.MediaChanged</c>); then the media index and the project file say proxies first (so a stop
/// half way leaves media that name no original that is gone), and last each original is deleted or trashed as the plan
/// says, hashed again as it goes.
/// </summary>
/// <returns>The files moved to the trash.</returns>
/// <exception cref="InvalidOperationException">The project or the home changed since the plan.</exception>
/// <exception cref="Chronos.Core.Archiving.LeaseUnavailableException">Another writer holds the project.</exception>
public static async Task<int> ApplyProxiesOnlyAsync(WorkspaceProject project, WorkspaceProxiesOnlyPlan plan, HomeFrames home, TimeSpan lockWait,
CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(project);
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(home);
using (await project.LockAsync(lockWait, cancellationToken).ConfigureAwait(false))
{
var now = PlanProxiesOnly(project, home);
if (now.ProjectId != plan.ProjectId || now.Fingerprint != plan.Fingerprint) throw new InvalidOperationException(Loc.L("Errors.Workspace.MediaChanged"));
var media = project.ReadMedia();
var files = Files(project);
if (media is not null)
{
project.WriteMedia(media with
{
Kind = BundleMedia.Proxies,
Frames = [.. media.Frames.Select(f => f with { Original = null, OriginalSha256 = null, OriginalBytes = 0 })],
});
}
var bundle = project.ReadBundle();
if (bundle.Workspace is { } workspace && workspace.Media.Kind != BundleMedia.Proxies)
project.WriteBundle(bundle with { Workspace = workspace with { Media = workspace.Media with { Kind = BundleMedia.Proxies } } });
var trashed = DeleteOrTrash(project, files, home.Frames);
var staging = Path.Combine(project.OriginalsDirectory, ".staging");
if (Directory.Exists(staging)) TryDeleteFolder(staging);
if (Directory.Exists(project.OriginalsDirectory) && !Directory.EnumerateFileSystemEntries(project.OriginalsDirectory).Any()) TryDeleteFolder(project.OriginalsDirectory);
Log.Info("workspace", $"Originals of project {project.ProjectId} removed: {plan.Originals} deleted, {trashed} kept in {TrashFolder}");
return trashed;
}
}
/// <summary>
/// Deletes each of <paramref name="files"/> (originals of <paramref name="project"/>) whose SHA-256, read now, is that of a
/// photo <paramref name="home"/> holds, not flagged missing or damaged; moves the others to the workspace's trash.
/// </summary>
/// <returns>The files moved to the trash.</returns>
internal static int DeleteOrTrash(WorkspaceProject project, IReadOnlyList<string> files, IReadOnlyList<Frame> home)
{
if (files.Count == 0) return 0;
var held = HeldAtHome(home);
string? trash = null;
var trashed = 0;
foreach (var file in files)
{
try
{
var (sha, _) = Hash(file);
if (sha is not null && held.Contains(sha))
{
File.Delete(file);
continue;
}
trash ??= Path.Combine(project.Store.Root, TrashFolder,
project.ProjectId.ToString("N") + "-" + DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture), WorkspaceProject.OriginalsFolder);
Directory.CreateDirectory(trash);
File.Move(file, Path.Combine(trash, Path.GetFileName(file)), overwrite: true);
trashed++;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("workspace", $"{file} could not be removed", ex);
}
}
return trashed;
}
/// <summary>The original files in the project's folder of originals (never a part a copy writes, nor its staging folder).</summary>
private static List<string> Files(WorkspaceProject project)
{
if (!Directory.Exists(project.OriginalsDirectory)) return [];
return [.. Directory.EnumerateFiles(project.OriginalsDirectory)
.Where(f => !f.EndsWith(".part", StringComparison.OrdinalIgnoreCase))
.Order(StringComparer.OrdinalIgnoreCase)];
}
/// <summary>The SHA-256 (lower case) of the photos the home holds, flagged neither missing nor damaged.</summary>
private static HashSet<string> HeldAtHome(IReadOnlyList<Frame> home) =>
home.Where(f => !string.IsNullOrEmpty(f.Sha256) && (f.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) == 0)
.Select(f => f.Sha256!.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
private static (string? Sha256, long Bytes) Hash(string file)
{
try
{
using var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 20, FileOptions.SequentialScan);
return (Convert.ToHexStringLower(SHA256.HashData(stream)), stream.Length);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("workspace", $"{file} could not be read", ex);
return (null, 0);
}
}
private static void TryDeleteFolder(string folder)
{
try
{
Directory.Delete(folder, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("workspace", $"{folder} could not be removed", ex);
}
}
}
@@ -0,0 +1,286 @@
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Chronos.Core.Analysis.Deep;
using Chronos.Core.Archiving;
using Chronos.Core.Export;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Render;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Processing.Jobs;
using SequenceFrames = Chronos.Data.Processing.SequenceFrames;
namespace Chronos.Data.Workspaces;
/// <summary>
/// <see cref="JobKind.WorkspaceRender"/> (phase 5c, <see cref="WorkspaceJobs.Render"/>): a workspace project rendered on this
/// PC from the originals its media hold, as <see cref="Processing.Jobs.RenderJobHandler"/> renders an archive's sequence,
/// into the project's <c>exports/</c> (each output written by the encoder under a hidden temporary name, then renamed), each
/// output hashed and recorded in the project's ledger (<see cref="WorkspaceRenders"/>, its id
/// <c>RenderJobHandler.RenderId(jobId, index)</c>), then a <see cref="JobKind.WorkspaceSend"/> queued with the new ids.
/// Media without an original for every placed frame are refused. The project's lease is held while the inputs are read
/// and while each ledger entry is written, not for the whole render: the editor keeps saving its working state meanwhile.
/// The settings rendered are the ones the job embeds (the editor's portable settings), else the version it names from
/// <c>versions/</c>; the version is recorded only when <c>versions/</c> holds it with the content hash of what rendered.
/// Checkpoint: the entries recorded and the output being written; a resumed job removes that output's leftovers (never one
/// the ledger names) and renders only what is not recorded yet.
/// </summary>
internal sealed class WorkspaceRenderJobHandler(ChronosDatabase db, ArchiveService archives, WorkspaceJobOptions options) : IJobHandler
{
private static readonly TimeSpan LockWait = TimeSpan.FromMinutes(2);
public JobKind Kind => JobKind.WorkspaceRender;
public async Task RunAsync(JobContext context)
{
ArgumentNullException.ThrowIfNull(context);
// The index and the archive engine are not read: everything a local render needs is in the workspace project.
_ = (db, archives);
var cancellation = context.Cancellation;
var parameters = WorkspaceJobs.RenderParameters(context.Job) ?? throw new InvalidDataException(Loc.L("Errors.Workspace.JobParameters"));
var (render, export) = ProcessingJobs.ReadRender(parameters.RenderJson);
var store = new WorkspaceStore(parameters.WorkspaceRoot);
var project = store.Find(parameters.ProjectId) ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.RenderProject"));
var inputs = await ReadInputsAsync(project, parameters, render, cancellation).ConfigureAwait(false);
var (sequence, frames, settings, versionId) = (inputs.Sequence, inputs.Frames, inputs.Settings, inputs.VersionId);
// A local render's outputs stay in the project's exports, from where they are sent home.
var projectSettings = ProjectStore.Parse(settings) with { Export = export with { Folder = null } };
var settingsJson = projectSettings.ToJson();
var settingsHash = ProjectContent.Hash(inputs.Portable);
var exports = project.ExportsDirectory;
Directory.CreateDirectory(exports);
using var names = new OutputNames();
var all = RenderJobHandler.Targets(projectSettings.Export, render.PresetName);
var resume = RenderCheckpoint.Parse(context.Checkpoint);
var done = resume.Done.ToList();
var ledger = project.ReadRenders();
for (var i = 0; i < all.Count; i++)
{
if (!done.Contains(i) && ledger.Find(RenderJobHandler.RenderId(context.Job.Id, i)) is not null) done.Add(i);
}
if (resume is { Pending: { } pending, PendingOutput: { } chosen } && !done.Contains(pending) && Inside(exports, chosen) && names.TryReserve(chosen))
{
Discard(chosen, keepOutput: ledger.Entries.Any(e => SamePath(project.ExportFile(e.File), chosen)));
names.Release(chosen);
}
var targets = all.Select((t, i) => (i, t)).Where(t => !done.Contains(t.i)).ToList();
var recorded = new List<Guid>();
if (targets.Count > 0)
{
string? writing = null;
IReadOnlyList<TargetOutcome> outcomes;
try
{
await using var renderer = new SequenceRender(frames, projectSettings, inputs.Analysis, options.Processing, originals: true, companions: null);
outcomes = await renderer.RenderAllAsync(
targets,
(target, setup) => names.Reserve(taken => ExportNaming.OutputPath(projectSettings.Export, exports, SequenceRender.NameContext(sequence, target, setup),
name => taken(name) || ledger.Entries.Any(e => SamePath(project.ExportFile(e.File), name)))),
(index, path) =>
{
writing = path;
return context.CheckpointAsync(new RenderCheckpoint(done, index, path).ToJson(), context.Done, context.Total);
},
async (index, target, result) =>
{
// The output is complete: recorded even if the job is being cancelled, so it is never orphaned.
var id = RenderJobHandler.RenderId(context.Job.Id, index);
var entry = await EntryAsync(project, context.Job.Id, id, target, result, versionId, settingsHash).ConfigureAwait(false);
using (await project.LockAsync(LockWait, CancellationToken.None).ConfigureAwait(false))
{
ledger = project.ReadRenders().With(entry);
project.WriteRenders(ledger);
}
done.Add(index);
recorded.Add(id);
writing = null;
await context.CheckpointAsync(new RenderCheckpoint(done, null, null).ToJson(), context.Done, context.Total).ConfigureAwait(false);
context.Log(Loc.L("Export.Log.Rendered", target.PresetName, Path.GetFileName(result.OutputPath)));
foreach (var remark in SequenceRender.Remarks(result)) context.Log(remark);
},
context.ReportAsync,
cancellation).ConfigureAwait(false);
if (renderer.StandIns.Count > 0)
context.Log(Loc.L("Export.Log.StandIns", string.Join(", ", renderer.StandIns.Select(i => (i + 1).ToString(Loc.Culture)))));
}
catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
{
// What the encoder was writing goes; every output recorded stays, and a resumed job renders the rest.
if (writing is { } partial) Discard(partial, keepOutput: true);
await QueueSendAsync(context, parameters, sequence, recorded).ConfigureAwait(false);
throw;
}
var failed = outcomes.Where(o => o.Error is not null).ToList();
foreach (var outcome in failed) context.Log(Loc.L("Export.Log.Failed", outcome.Target.PresetName, outcome.Error));
await QueueSendAsync(context, parameters, sequence, recorded).ConfigureAwait(false);
if (failed.Count > 0)
throw new InvalidOperationException(failed.Count == 1 ? failed[0].Error : Loc.L("Errors.Render.Failed", failed.Count, outcomes.Count));
}
}
/// <summary>What the render reads, taken under the project's lease so the media, the versions and the project file agree.</summary>
private sealed record Inputs(Sequence Sequence, SequenceFrames Frames, string Settings, string Portable, Guid? VersionId, DeepAnalysisReport? Analysis);
/// <summary>
/// The sequence over the workspace's originals, the settings to render (placed on its frames) and the version they are,
/// read under the project's lease.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The project is gone (<c>Errors.Workspace.RenderProject</c>), holds no originals (<c>Errors.Workspace.OriginalsMissing</c>),
/// lacks the original of a frame the render places (<c>Errors.Workspace.RenderNoOriginals</c>, with their number), or the
/// version the job names is not in <c>versions/</c> (<c>Errors.Workspace.RenderVersion</c>).
/// </exception>
private static async Task<Inputs> ReadInputsAsync(WorkspaceProject project, WorkspaceRenderParameters parameters, Protocol.RenderJobParameters render,
CancellationToken cancellationToken)
{
using (await project.LockAsync(LockWait, cancellationToken).ConfigureAwait(false))
{
if (!File.Exists(project.BundlePath)) throw new InvalidOperationException(Loc.L("Errors.Workspace.RenderProject"));
var bundle = project.ReadBundle();
var workspace = bundle.Workspace!;
var media = project.ReadMedia();
if (media is not { HoldsOriginals: true })
throw new InvalidOperationException(Loc.L(workspace.Home.IsArchive ? "Errors.Workspace.OriginalsMissing" : "Errors.Workspace.OriginalsMissing.Server"));
var versions = project.Versions();
var named = parameters.ProjectVersionId ?? render.ProjectVersionId;
var version = named is { } id ? versions.FirstOrDefault(v => v.Id == id) : null;
string portable;
if (render.SettingsJson is { Length: > 0 } embedded) portable = embedded;
else if (named is not null) portable = version?.SettingsJson ?? throw new InvalidOperationException(Loc.L("Errors.Workspace.RenderVersion"));
else portable = versions.Count > 0 ? versions[^1].SettingsJson : ProjectContent.ToPortable(bundle.Project, media.Photos);
// Recorded only for the settings it holds (a version is never named for settings it did not render).
Guid? versionId = version is not null && ProjectContent.Verifies(portable, version.ContentHash) ? version.Id : null;
var settings = portable.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase) ? Place(portable, media.Photos) : portable;
var placed = ProjectStore.Parse(settings);
var excluded = placed.ExcludedFrames.ToHashSet();
var lacking = media.Frames.Count(f => f.Original is null && !excluded.Contains(f.Index) && (f.Flags & SequenceFrames.NotRendered) == 0);
if (lacking > 0) throw new InvalidOperationException(Loc.L("Errors.Workspace.RenderNoOriginals", lacking));
var frames = media.ToOriginalFrames();
var files = media.Frames.Select(f => f.Original is { } original ? project.MediaFile(original) : null).ToList();
var sequence = SequenceOf(bundle, media, frames);
return new Inputs(sequence, new SequenceFrames(sequence, frames, files), settings, portable, versionId, Analysis(project, frames.Count));
}
}
/// <summary>The home's sequence as the project file and the media name it (the workspace keeps no index row of it).</summary>
private static Sequence SequenceOf(ProjectBundle bundle, WorkspaceMedia media, IReadOnlyList<Frame> frames)
{
var times = frames.Where(f => f.CapturedAt is not null).Select(f => f.CapturedAt!.Value).Order().ToList();
var home = bundle.Workspace!.Home;
return new Sequence
{
Id = home.SequenceId,
ArchiveId = bundle.Archive.Id,
Title = bundle.Sequence.Title,
Folder = bundle.Sequence.Folder,
FrameCount = frames.Count,
FirstCapture = times.Count > 0 ? times[0] : null,
LastCapture = times.Count > 0 ? times[^1] : null,
FramesVersion = media.FramesVersion,
Origin = home.IsArchive ? SequenceOrigin.Local : SequenceOrigin.Server,
};
}
/// <summary>The deep report the copy brought from the home, when it describes these frames; null otherwise.</summary>
private static DeepAnalysisReport? Analysis(WorkspaceProject project, int frameCount)
{
if (!File.Exists(project.AnalysisPath)) return null;
try
{
var report = DeepAnalysisReport.Load(project.AnalysisPath);
return report.FrameCount == frameCount ? report : null;
}
catch (Exception ex) when (ex is IOException or InvalidDataException or JsonException or UnauthorizedAccessException)
{
Core.Diagnostics.Log.Warning("workspace", $"{project.AnalysisPath} cannot be read", ex);
return null;
}
}
/// <summary>Portable settings placed on the media's frames; others as they are.</summary>
private static string Place(string portable, FramePhotos photos)
{
try
{
return ProjectContent.Place(portable, photos);
}
catch (JsonException)
{
// Not a project: reading it says so.
return portable;
}
}
/// <summary>The ledger entry of a finished output: hashed as it is on the disk now.</summary>
private static async Task<WorkspaceRenderEntry> EntryAsync(WorkspaceProject project, Guid jobId, Guid renderId, ExportTarget target, RenderResult result,
Guid? versionId, string settingsHash)
{
var sha = await HashAsync(result.OutputPath).ConfigureAwait(false);
var file = Path.GetRelativePath(project.ExportsDirectory, result.OutputPath).Replace('\\', '/');
return new WorkspaceRenderEntry(renderId, jobId, file, sha, result.Bytes, target.PresetName, result.Codec.ToString(), result.Width, result.Height,
result.FrameRate.Value, result.DurationSeconds, project.ProjectId, versionId, settingsHash, DateTimeOffset.UtcNow);
}
/// <summary>
/// The SHA-256 of an output: of the file, or, for an image sequence's folder, of its files' relative paths and SHA-256 in
/// order (a send checks the folder the same way).
/// </summary>
internal static async Task<string> HashAsync(string output)
{
if (File.Exists(output)) return await ContentHash.Sha256Async(output, cancellationToken: CancellationToken.None).ConfigureAwait(false);
var listing = new StringBuilder();
foreach (var file in Directory.EnumerateFiles(output, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal))
{
var sha = await ContentHash.Sha256Async(file, cancellationToken: CancellationToken.None).ConfigureAwait(false);
listing.Append(Path.GetRelativePath(output, file).Replace('\\', '/')).Append(' ').Append(sha).Append('\n');
}
return Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(listing.ToString())));
}
/// <summary>Queues the send home of the renders this run recorded, whatever stops the job now (they are done).</summary>
private static async Task QueueSendAsync(JobContext context, WorkspaceRenderParameters parameters, Sequence sequence, List<Guid> recorded)
{
if (recorded.Count == 0) return;
var send = WorkspaceJobs.Send(sequence.Id, sequence.DisplayTitle, parameters.WorkspaceRoot, parameters.ProjectId, [.. recorded],
parameters.Server, context.Job.Priority);
await context.EnqueueFollowUpAsync(send.Kind, send.Targets, send.Label, send.ParametersJson, send.Priority, CancellationToken.None).ConfigureAwait(false);
}
private static bool Inside(string folder, string path)
{
var relative = Path.GetRelativePath(folder, path);
return !relative.StartsWith("..", StringComparison.Ordinal) && !Path.IsPathRooted(relative);
}
private static bool SamePath(string a, string b) =>
string.Equals(Path.GetFullPath(a), Path.GetFullPath(b), OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
/// <summary>
/// Removes what an interrupted attempt left of <paramref name="output"/>: the encoder's hidden temporary file or folder,
/// and an output completed but never recorded (it renders again under the same name) unless <paramref name="keepOutput"/>.
/// </summary>
private static void Discard(string output, bool keepOutput)
{
var parent = Path.GetDirectoryName(output);
if (parent is null || !Directory.Exists(parent)) return;
var leftovers = Directory.EnumerateFileSystemEntries(parent, "." + Path.GetFileName(output) + ".*.tmp").ToList();
if (!keepOutput) leftovers.Add(output);
foreach (var leftover in leftovers)
{
try
{
if (Directory.Exists(leftover)) Directory.Delete(leftover, recursive: true);
else if (File.Exists(leftover)) File.Delete(leftover);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Core.Diagnostics.Log.Warning("workspace", $"{leftover} could not be removed", ex);
}
}
}
}
@@ -0,0 +1,136 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using Chronos.Core.IO;
using Chronos.Core.Model;
namespace Chronos.Data.Workspaces;
/// <summary>
/// One local render of a workspace project (phase 5c), as its ledger (<see cref="WorkspaceRenders"/>) records it: the output
/// a <see cref="JobKind.WorkspaceRender"/> wrote into the project's <c>exports/</c>, its SHA-256 and size as written, what it
/// is (preset, codec, size, rate, length), the project and version it was rendered from, and whether it went home
/// (<see cref="JobKind.WorkspaceSend"/>). The file stays in <c>exports/</c> after it is sent, until a clean-up removes it.
/// </summary>
/// <param name="RenderId">
/// The render's id, the same at the home once sent (<c>RenderJobHandler.RenderId(jobId, index)</c>): a send repeated after a
/// cut finds the home holding it already, and nothing is filed twice.
/// </param>
/// <param name="JobId">The <see cref="JobKind.WorkspaceRender"/> job that wrote it.</param>
/// <param name="File">The output, relative to the project's <c>exports/</c> folder (forward slashes; <see cref="WorkspaceProject.ExportFile"/>).</param>
/// <param name="Sha256">The output's SHA-256 (lower case) as it was written: a send hashes the file again and refuses another.</param>
/// <param name="Size">The output's size in bytes.</param>
/// <param name="ProjectVersionId">The project version rendered; null for a working state no version names.</param>
/// <param name="SettingsHash">The content hash of the portable settings rendered (<c>ProjectContent</c>); null when not known.</param>
/// <param name="Rendered">When the output was finished.</param>
/// <param name="State"><see cref="Pending"/>, <see cref="SentState"/> or <see cref="Failed"/> (a later Chronos may write others: read as pending).</param>
/// <param name="Sent">When the home took it; null until then.</param>
/// <param name="Error">Why the last send failed (one localized sentence); null otherwise.</param>
public sealed record WorkspaceRenderEntry(
Guid RenderId,
Guid JobId,
string File,
string Sha256,
long Size,
string PresetName,
string? Codec,
int Width,
int Height,
double Fps,
double DurationSeconds,
Guid ProjectId,
Guid? ProjectVersionId,
string? SettingsHash,
DateTimeOffset Rendered,
string State = WorkspaceRenderEntry.Pending,
DateTimeOffset? Sent = null,
string? Error = null)
{
/// <summary>Written, not at the home yet.</summary>
public const string Pending = "pending";
/// <summary>The home holds it (a render row of the home's sequence with this id).</summary>
public const string SentState = "sent";
/// <summary>The last send failed (<see cref="Error"/> says why); sent again by the next send.</summary>
public const string Failed = "failed";
/// <summary>The home holds this render.</summary>
[JsonIgnore]
public bool IsSent => State == SentState;
/// <summary>Not at the home yet: pending, failed, or a state this Chronos does not know. A clean-up never removes its file.</summary>
[JsonIgnore]
public bool IsUnsent => !IsSent;
/// <summary>This entry as taken by the home at <paramref name="at"/>.</summary>
public WorkspaceRenderEntry AsSent(DateTimeOffset at) => this with { State = SentState, Sent = at, Error = null };
/// <summary>This entry after a send that failed for <paramref name="error"/>; it stays to be sent again.</summary>
public WorkspaceRenderEntry AsFailed(string error) => this with { State = Failed, Error = error };
}
/// <summary>
/// The ledger of a workspace project's local renders (<c>exports/renders.json</c>, phase 5c): every output a
/// <see cref="JobKind.WorkspaceRender"/> finished, oldest first, one entry per render id. Read whole and written whole and
/// atomically (temporary file, flush, rename), always under the project's lease; a missing ledger is an empty one.
/// </summary>
public sealed record WorkspaceRenders(string Format, int FormatVersion, IReadOnlyList<WorkspaceRenderEntry> Entries)
{
public const string FormatName = "chronos-workspace-renders";
public const int CurrentFormatVersion = 1;
/// <summary>A ledger without entries.</summary>
public static WorkspaceRenders Empty { get; } = new(FormatName, CurrentFormatVersion, []);
/// <summary>The entries not at the home yet (<see cref="WorkspaceRenderEntry.IsUnsent"/>), oldest first.</summary>
[JsonIgnore]
public IReadOnlyList<WorkspaceRenderEntry> Unsent => [.. Entries.Where(e => e.IsUnsent)];
/// <summary>The entry of <paramref name="renderId"/>; null when the ledger has none.</summary>
public WorkspaceRenderEntry? Find(Guid renderId) => Entries.FirstOrDefault(e => e.RenderId == renderId);
/// <summary>This ledger with <paramref name="entry"/> in place of the entry of its render id, or appended when it has none.</summary>
public WorkspaceRenders With(WorkspaceRenderEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
var entries = Entries.ToList();
var at = entries.FindIndex(e => e.RenderId == entry.RenderId);
if (at >= 0) entries[at] = entry;
else entries.Add(entry);
return this with { Entries = entries };
}
/// <summary>This ledger without the entry of <paramref name="renderId"/> (a sent file a clean-up removed, a discarded render).</summary>
public WorkspaceRenders Without(Guid renderId) => Entries.Any(e => e.RenderId == renderId) ? this with { Entries = [.. Entries.Where(e => e.RenderId != renderId)] } : this;
/// <summary>The ledger at <paramref name="path"/>; <see cref="Empty"/> when there is none.</summary>
/// <exception cref="InvalidDataException">The file is no ledger, is damaged, or a newer Chronos wrote it.</exception>
/// <exception cref="IOException">The file cannot be read.</exception>
public static WorkspaceRenders Read(string path)
{
ArgumentException.ThrowIfNullOrEmpty(path);
if (!System.IO.File.Exists(path)) return Empty;
WorkspaceRenders? renders;
try
{
renders = JsonSerializer.Deserialize(AtomicFile.ReadAllText(path), WorkspaceJson.Default.WorkspaceRenders);
}
catch (JsonException ex)
{
throw new InvalidDataException($"{path} cannot be read.", ex);
}
if (renders is null || renders.Format != FormatName || renders.Entries is null) throw new InvalidDataException($"{path} is not a renders ledger.");
if (renders.FormatVersion > CurrentFormatVersion) throw new InvalidDataException($"{path} is newer than this Chronos.");
return renders;
}
/// <summary>Writes <paramref name="renders"/> to <paramref name="path"/> whole and atomically, making its folder when needed.</summary>
/// <exception cref="IOException">The file cannot be written; the ledger there stays as it was.</exception>
public static void Write(string path, WorkspaceRenders renders)
{
ArgumentException.ThrowIfNullOrEmpty(path);
ArgumentNullException.ThrowIfNull(renders);
if (Path.GetDirectoryName(Path.GetFullPath(path)) is { Length: > 0 } folder) Directory.CreateDirectory(folder);
AtomicFile.WriteAllText(path, JsonSerializer.Serialize(renders with { Format = FormatName, FormatVersion = CurrentFormatVersion }, WorkspaceJson.Default.WorkspaceRenders));
}
}
@@ -0,0 +1,25 @@
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Sync;
namespace Chronos.Data.Workspaces;
/// <summary>
/// <see cref="JobKind.WorkspaceSend"/> (phase 5c, <see cref="WorkspaceJobs.Send"/>): the local renders of a workspace project
/// sent home with their project and version, per unsent ledger entry: the file hashed again (another is refused and stays),
/// the version it names pushed first when the home lacks it, then filed in this PC's archive (as the sync files a server's
/// exports) or uploaded to its server (<c>RenderUploadRequest</c> with <c>ProjectId</c> and <c>ProjectVersionId</c>), and the
/// entry marked sent. Idempotent by render id: a send repeated after a cut finds the home holding it already.
/// </summary>
internal sealed class WorkspaceSendJobHandler(ChronosDatabase db, ArchiveService archives, ISyncConnector? servers, WorkspaceJobOptions options) : IJobHandler
{
public JobKind Kind => JobKind.WorkspaceSend;
public Task RunAsync(JobContext context)
{
ArgumentNullException.ThrowIfNull(context);
_ = (db, archives, servers, options);
throw new NotImplementedException("Sending a workspace project's renders home comes with phase 5c (P3).");
}
}
+72 -4
View File
@@ -91,17 +91,48 @@ public sealed record WorkspaceConflict(Guid TheirsVersionId, int TheirsNumber, G
/// <summary>
/// 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).
/// project whose media to copy and what to copy (<see cref="BundleMedia.Proxies"/>, or <see cref="BundleMedia.Originals"/>:
/// the proxies plus the originals, phase 5c).
/// </summary>
/// <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);
/// <summary>
/// Parameters of a <see cref="JobKind.WorkspaceRender"/> job (phase 5c): target = the home's sequence; the workspace folder,
/// the project rendered from the originals its media hold, the version rendered (null: the head version the workspace
/// holds), and the render's export settings as Protocol <c>RenderJobParameters</c> JSON (portable settings, preset,
/// overrides, batch), as <see cref="Processing.ProcessingJobs"/> writes them for a render.
/// </summary>
/// <param name="ProjectVersionId">The version rendered and recorded with each output; null renders the head version the workspace holds.</param>
/// <param name="RenderJson">Protocol <c>RenderJobParameters</c> as JSON.</param>
/// <param name="Server">The server the home's sequence is on (<see cref="SyncService.ServerKey"/>); null for a sequence of this PC's archive.</param>
public sealed record WorkspaceRenderParameters(string WorkspaceRoot, Guid ProjectId, Guid? ProjectVersionId, string RenderJson, string? Server = null);
/// <summary>
/// Parameters of a <see cref="JobKind.WorkspaceSend"/> job (phase 5c): target = the home's sequence; the workspace folder,
/// the project, and the ledger entries (<see cref="WorkspaceRenderEntry.RenderId"/>) whose files go home.
/// </summary>
/// <param name="RenderIds">The renders sent; empty sends every pending entry of the project's ledger.</param>
/// <param name="Server">The server the home's sequence is on (<see cref="SyncService.ServerKey"/>); null for a sequence of this PC's archive.</param>
public sealed record WorkspaceSendParameters(string WorkspaceRoot, Guid ProjectId, IReadOnlyList<Guid> RenderIds, string? Server = null);
/// <summary>
/// Parameters of a <see cref="JobKind.WorkspaceMove"/> job (phase 5c): no target; the workspace folder moved
/// (<paramref name="From"/>), the folder it goes to, and the fingerprint of the plan the user confirmed (the job refuses a
/// workspace that changed since).
/// </summary>
public sealed record WorkspaceMoveParameters(string From, string To, string PlanFingerprint);
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
UseStringEnumConverter = true, WriteIndented = true)]
[JsonSerializable(typeof(WorkspaceManifest))]
[JsonSerializable(typeof(WorkspaceMedia))]
[JsonSerializable(typeof(WorkspaceSyncState))]
[JsonSerializable(typeof(WorkspaceCopyParameters))]
[JsonSerializable(typeof(WorkspaceRenderParameters))]
[JsonSerializable(typeof(WorkspaceSendParameters))]
[JsonSerializable(typeof(WorkspaceMoveParameters))]
[JsonSerializable(typeof(WorkspaceRenders))]
internal sealed partial class WorkspaceJson : JsonSerializerContext;
/// <summary>
@@ -309,9 +340,11 @@ public sealed class WorkspaceStore
/// <summary>
/// One project in the workspace (owner review 2, R8): <c>&lt;root&gt;/&lt;project id&gt;/</c> with
/// <c>project.chronos</c> (the working state: a project file of format 2, its settings placed on the media's frames),
/// <c>media/media.json</c> with <c>media/proxies/&lt;frame id&gt;.jpg</c> (originals later) and <c>media/analysis.json</c>
/// (the home's deep report), <c>versions/&lt;number&gt;-&lt;id&gt;.json</c> (commits not pushed yet, and the versions pulled),
/// <c>sync.json</c>, <c>exports/</c> and the lease <c>.lock.lease</c> that one writer at a time holds.
/// <c>media/media.json</c> with <c>media/proxies/&lt;frame id&gt;.jpg</c>, <c>media/originals/&lt;frame id&gt;-&lt;sha8&gt;&lt;ext&gt;</c>
/// (media of kind originals, phase 5c) and <c>media/analysis.json</c> (the home's deep report),
/// <c>versions/&lt;number&gt;-&lt;id&gt;.json</c> (commits not pushed yet, and the versions pulled), <c>sync.json</c>,
/// <c>exports/</c> with the local renders and their ledger <c>exports/renders.json</c> (phase 5c), and the lease
/// <c>.lock.lease</c> that one writer at a time holds.
/// </summary>
public sealed class WorkspaceProject
{
@@ -324,6 +357,12 @@ public sealed class WorkspaceProject
public const string ExportsFolder = "exports";
public const string SyncFile = "sync.json";
/// <summary>The name of the ledger of the project's local renders (<see cref="WorkspaceRenders"/>) in <see cref="ExportsFolder"/>.</summary>
public const string RendersFileName = "renders.json";
/// <summary>The ledger of the project's local renders (phase 5c), relative to <see cref="Folder"/>.</summary>
public const string RendersFile = ExportsFolder + "/" + RendersFileName;
/// <summary>
/// Old local commits replaced by their replay on top of the home's head, files the home's copy replaced, and the working
/// states a take of the server's values replaced: kept up to a month, the newest 20 at most (<see cref="PruneReplaced"/>).
@@ -365,6 +404,9 @@ public sealed class WorkspaceProject
public string ExportsDirectory => Path.Combine(Folder, ExportsFolder);
public string SyncPath => Path.Combine(Folder, SyncFile);
/// <summary>The ledger of the project's local renders (<see cref="RendersFile"/>, phase 5c).</summary>
public string RendersPath => Path.Combine(ExportsDirectory, RendersFileName);
public bool Exists => File.Exists(BundlePath);
/// <summary>The file a frame's proxy is copied to, relative to <see cref="MediaDirectory"/>.</summary>
@@ -380,9 +422,35 @@ public sealed class WorkspaceProject
return ProxiesFolder + "/" + frameId.ToString("N") + "-" + sha256[..Math.Min(16, sha256.Length)].ToLowerInvariant() + ".jpg";
}
/// <summary>
/// The file a frame's original is copied to, relative to <see cref="MediaDirectory"/> (phase 5c):
/// <c>originals/&lt;frame id&gt;-&lt;sha8&gt;&lt;ext&gt;</c>. The first 8 hex digits of its SHA-256 tell two encodings of one
/// frame apart (a conversion since: the editor keeps the one it reads until the copy commits), and the original's own
/// extension is kept, lower case, since decoders go by it.
/// </summary>
/// <param name="extension">The original's extension, with or without its dot (".CR3", "dng", or the file name's <see cref="Path.GetExtension(string)"/>); empty or null for none.</param>
public static string OriginalName(Guid frameId, string sha256, string? extension)
{
ArgumentException.ThrowIfNullOrEmpty(sha256);
var ext = (extension ?? string.Empty).Trim().TrimStart('.').ToLowerInvariant();
if (ext.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 || ext.Contains('/') || ext.Contains('\\')) ext = string.Empty;
return OriginalsFolder + "/" + frameId.ToString("N") + "-" + sha256[..Math.Min(8, sha256.Length)].ToLowerInvariant() + (ext.Length > 0 ? "." + ext : string.Empty);
}
/// <summary>The ledger of the project's local renders; empty while it has none (<see cref="WorkspaceRenders.Read"/>).</summary>
/// <exception cref="InvalidDataException">The ledger is damaged or newer.</exception>
/// <exception cref="IOException">The ledger cannot be read.</exception>
public WorkspaceRenders ReadRenders() => WorkspaceRenders.Read(RendersPath);
/// <summary>Writes the ledger of the project's local renders whole and atomically (<see cref="WorkspaceRenders.Write"/>); the caller holds the project's lease.</summary>
public void WriteRenders(WorkspaceRenders renders) => WorkspaceRenders.Write(RendersPath, renders);
/// <summary>The absolute path of a file named relative to <see cref="MediaDirectory"/>.</summary>
public string MediaFile(string relative) => LongPath.FromPortableRelative(MediaDirectory, relative);
/// <summary>The absolute path of a local render named relative to <see cref="ExportsDirectory"/> (<see cref="WorkspaceRenderEntry.File"/>).</summary>
public string ExportFile(string relative) => LongPath.FromPortableRelative(ExportsDirectory, relative);
/// <summary>Holds the project for one writer (this program's sync, a copy job) until disposed.</summary>
/// <exception cref="LeaseUnavailableException">Another writer kept it for longer than <paramref name="wait"/>.</exception>
public async Task<IDisposable> LockAsync(TimeSpan wait, CancellationToken cancellationToken = default)
+7 -1
View File
@@ -46,6 +46,10 @@ public sealed record CardImportReport(Guid ImportId, string Card, string State,
/// and files the render under the sequence's exports. A completion that cannot file it for now answers 503
/// <c>sequence_busy</c>, <c>archive_offline</c> or <c>folder_moved</c> (another index moved the sequence's folder; the
/// server's next scan finds it) and keeps the upload, to be completed again.
/// A render a workspace made on a client (phase 5c) names the project and version it was rendered from
/// (<see cref="ProjectId"/>, <see cref="ProjectVersionId"/>): the server records them with the render once it checked that
/// the project is the sequence's and the version the project's (422 <c>project_mismatch</c> otherwise). Both are optional
/// and appended: a request of an earlier client has neither, and an earlier server ignores them.
/// </summary>
public sealed record RenderUploadRequest(
Guid RenderId,
@@ -58,4 +62,6 @@ public sealed record RenderUploadRequest(
int Height,
double Fps,
double DurationSeconds,
string? ProducedBy);
string? ProducedBy,
Guid? ProjectId = null,
Guid? ProjectVersionId = null);
@@ -17,6 +17,9 @@ public sealed class JobNoticesTests
[Case(JobKind.Move)]
[Case(JobKind.Adopt)]
[Case(JobKind.Convert)]
[Case(JobKind.WorkspaceRender)]
[Case(JobKind.WorkspaceSend)]
[Case(JobKind.WorkspaceMove)]
public void ALongOperationThatEndsSaysSo(JobKind kind)
{
Assert.Equal(JobNotice.Done, JobNotices.For(JobState.Running, Job(kind, JobState.Done)));
@@ -137,7 +137,7 @@ public sealed class ServerHomeTests(TestContext context)
public async Task TheEditorFollowsTheServerAndRendersOnlyWhatItHolds()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false, WorkspaceVersionOnRender = false });
var server = new FakeServer(bed);
Connect(host, server);
var projectId = await CheckoutAsync(bed, host);
@@ -266,7 +266,8 @@ public sealed class WorkspaceFallbackTests(TestContext context)
Assert.False(facts.TooLittleSpace, "the test drive has room for four small proxies");
var dialog = new OpenInWorkspaceDialogViewModel("Synthetic", await host.HomeProjectsAsync(bed.SequenceId), _ => { }, copy: facts);
Assert.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free")], dialog.CopyFacts.Select(f => f.Label));
Assert.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free"), Loc.L("Editor.OpenWorkspace.Originals")], dialog.CopyFacts.Select(f => f.Label));
Assert.Equal(Formatting.Bytes(facts.OriginalsBytes!.Value), dialog.CopyFacts[2].Value);
Assert.Equal(Formatting.Bytes(facts.Bytes), dialog.CopyFacts[0].Value);
Assert.False(dialog.IsShortOfSpace);
@@ -75,6 +75,102 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.Empty(older.WorkspaceRecent);
}
[Test]
public void ThePhase5cWorkspaceSettingsHaveTheirDefaultsAndSurviveTheSettingsFile()
{
var fresh = new AppSettings();
Assert.Equal((100, BundleMedia.Proxies, true, 30, WorkspaceOpenPolicy.LastUsed),
(fresh.WorkspaceSizeLimitGb, fresh.WorkspaceDefaultMedia, fresh.WorkspaceVersionOnRender, fresh.WorkspaceCleanAfterDays, fresh.WorkspaceOpenProject));
Assert.Empty(fresh.WorkspaceOpened);
// A settings file of phase 5b gets them too.
var older = AppSettings.Parse("""{ "Theme": "Light", "WorkspaceKeptVersions": 50 }""")!;
Assert.Equal((100, BundleMedia.Proxies, true, 30, WorkspaceOpenPolicy.LastUsed, 50),
(older.WorkspaceSizeLimitGb, older.WorkspaceDefaultMedia, older.WorkspaceVersionOnRender, older.WorkspaceCleanAfterDays, older.WorkspaceOpenProject,
older.WorkspaceKeptVersions));
Assert.Empty(older.WorkspaceOpened);
var project = Guid.CreateVersion7();
var at = new DateTimeOffset(2026, 11, 4, 9, 30, 0, TimeSpan.FromHours(1));
var settings = new AppSettings
{
WorkspaceSizeLimitGb = 0,
WorkspaceDefaultMedia = BundleMedia.Originals,
WorkspaceVersionOnRender = false,
WorkspaceCleanAfterDays = 0,
WorkspaceOpenProject = WorkspaceOpenPolicy.Ask,
};
settings.WorkspaceOpened[project] = at;
var copy = AppSettings.Parse(settings.ToJson())!;
Assert.Equal((0, BundleMedia.Originals, false, 0, WorkspaceOpenPolicy.Ask),
(copy.WorkspaceSizeLimitGb, copy.WorkspaceDefaultMedia, copy.WorkspaceVersionOnRender, copy.WorkspaceCleanAfterDays, copy.WorkspaceOpenProject));
Assert.Equal(at, copy.WorkspaceOpened[project]);
Assert.Contains("\"Ask\"", settings.ToJson());
}
[Test]
public void WhenEachProjectWasOpenedStaysOnThisPc()
{
var project = Guid.CreateVersion7();
var sequence = Guid.CreateVersion7();
var at = new DateTimeOffset(2026, 11, 4, 9, 30, 0, TimeSpan.Zero);
var mine = new AppSettings { WorkspaceFolder = @"D:\Fast\Workspace", WorkspaceSizeLimitGb = 250, WorkspaceOpenProject = WorkspaceOpenPolicy.Main };
mine.WorkspaceRecent[sequence] = project;
mine.WorkspaceOpened[project] = at;
// Reset puts the preferences back and keeps what this PC knows of its projects.
var reset = mine.ResetKeepingState();
Assert.Equal((AppSettings.DefaultWorkspaceSizeLimitGb, WorkspaceOpenPolicy.LastUsed), (reset.WorkspaceSizeLimitGb, reset.WorkspaceOpenProject));
Assert.Equal((@"D:\Fast\Workspace", project, at), (reset.WorkspaceFolder, reset.WorkspaceRecent[sequence], reset.WorkspaceOpened[project]));
// Export carries the preferences, not this PC's projects.
var exported = AppSettings.Parse(mine.ForExport().ToJson())!;
Assert.Equal((250, WorkspaceOpenPolicy.Main, (string?)null), (exported.WorkspaceSizeLimitGb, exported.WorkspaceOpenProject, exported.WorkspaceFolder));
Assert.Empty(exported.WorkspaceOpened);
Assert.Empty(exported.WorkspaceRecent);
Assert.Equal(at, mine.WorkspaceOpened[project]);
// Import takes another PC's preferences and keeps this PC's projects.
var theirs = new AppSettings { WorkspaceSizeLimitGb = 40, WorkspaceFolder = @"E:\Elsewhere" };
theirs.WorkspaceOpened[Guid.CreateVersion7()] = at.AddDays(-3);
var imported = mine.KeepLocalIn(AppSettings.Parse(theirs.ToJson())!);
Assert.Equal((40, @"D:\Fast\Workspace"), (imported.WorkspaceSizeLimitGb, imported.WorkspaceFolder));
Assert.Equal(at, imported.WorkspaceOpened.Values.Single());
Assert.Count(1, imported.WorkspaceOpened);
}
[Test]
public void OpeningAProjectRecordsWhenAndSavesIt()
{
var local = context.CreateTempDirectory("local");
var installed = AppEnvironment.From(AppPaths.Resolve(context.CreateTempDirectory("app"), local, []));
var settings = new AppSettings();
var saves = 0;
var host = new WorkspaceHost(installed, settings, () => saves++, () => null, () => null, () => null);
var project = Guid.CreateVersion7();
var at = new DateTimeOffset(2026, 11, 4, 10, 0, 0, TimeSpan.Zero);
host.RecordOpened(project, at);
Assert.Equal((at, 1), (settings.WorkspaceOpened[project], saves));
host.RecordOpened(project);
Assert.True(settings.WorkspaceOpened[project] > at, "opened again later");
Assert.Equal(2, saves);
Assert.False(host.IsMoving);
}
[Test]
public void AProjectWithRendersNotSentIsNotSafeToRemoveAndOriginalsNeedTheirRoom()
{
var plan = new WorkspaceRemovalPlan(Guid.CreateVersion7(), "Main", 12, 1_000, 0, false, false, false);
Assert.True(plan.IsSafe);
Assert.False((plan with { UnsentRenders = 1 }).IsSafe);
Assert.True((plan with { LastOriginals = 3 }).IsSafe, "the last originals go to the trash, never deleted");
var facts = new WorkspaceCopyFacts(1_000, 1_000 + WorkspaceJobs.CopySpaceReserve + 500, 2_000);
Assert.False(facts.TooLittleSpaceFor(BundleMedia.Proxies));
Assert.True(facts.TooLittleSpaceFor(BundleMedia.Originals));
Assert.False((facts with { Free = null }).TooLittleSpaceFor(BundleMedia.Originals), "a drive whose room is unknown is tried");
}
[Test]
public void SettingsWorkspaceRowsStoreEachChoiceAtOnce()
{
@@ -0,0 +1,128 @@
using System.Globalization;
using System.IO;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Workspace;
using Chronos.Core.Export;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Processing;
using Chronos.Data.Workspaces;
using Chronos.Protocol.Client;
using Chronos.Testing;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// Phase 5c in Edit: a workspace project that holds its originals renders on this PC (<see cref="JobKind.WorkspaceRender"/>),
/// also when its home is a server, and Settings › Workspace › Version on render saves a changed project as a version first.
/// </summary>
[Category("workspace")]
public sealed class WorkspaceLocalRenderTests(TestContext context)
{
private const string Server = "https://nas.test:8443";
private static readonly ExportSettings Mjpeg = new()
{
Preset = new Auto<string>().WithManual("mjpeg-avi"),
Overrides = new ExportOverrides { Width = 96, Height = 64 },
NameTemplate = "clip-{codec}",
};
static WorkspaceLocalRenderTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public async Task TheOriginalsRenderOnThisPcEvenForAServerHome()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false, WorkspaceVersionOnRender = false });
var checkout = await host.CheckoutAsync(bed.SequenceId, null, null, BundleMedia.Originals, cancellationToken: bed.Ct);
await bed.WaitForJobAsync(checkout.Copy.Id);
var projectId = checkout.Project.Id;
// Named the server's, as a copy downloaded from the server leaves it.
var folder = host.Store.Find(projectId)!;
var bundle = folder.ReadBundle();
var home = new BundleHome(BundleHome.ServerKind, bed.SequenceId, null, Server);
folder.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Home = home } });
// Not signed in to the server: a render from the originals runs here all the same.
var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
new WorkspaceServerHome((IRemoteSequenceApi?)null));
var content = await source.LoadAsync(bed.Ct);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
await using (session)
{
Assert.True(source is { IsServerHome: true, RendersLocally: true, UnsentRenders: 0 });
var requests = session.RenderRequests(Mjpeg);
var request = requests.Single();
Assert.Equal(JobKind.WorkspaceRender, request.Kind);
Assert.SequenceEqual([bed.SequenceId], request.Targets);
var parameters = Assert.NotNull(WorkspaceJobs.RenderParameters(new Job { Id = Guid.CreateVersion7(), Kind = request.Kind, ParametersJson = request.ParametersJson }));
Assert.Equal((projectId, host.Store.Root, Server), (parameters.ProjectId, parameters.WorkspaceRoot, parameters.Server));
var (render, _) = ProcessingJobs.ReadRender(parameters.RenderJson);
Assert.NotNull(render.SettingsJson, "the portable settings travel with the job");
// Queued on this PC's engine and listed beside the server's jobs (the render itself is the Data tests': this bed decodes nothing).
var jobId = await source.SubmitAsync(request, bed.Ct);
var queued = Assert.NotNull(await bed.Db.Jobs.GetAsync(jobId, bed.Ct));
Assert.Equal(JobKind.WorkspaceRender, queued.Kind);
Assert.Contains(await source.ListJobsAsync(bed.Ct), j => j.Id == jobId);
await WorkspaceTestBed.UntilAsync(() => bed.Db.Jobs.GetAsync(jobId).GetAwaiter().GetResult()?.State is JobState.Done or JobState.Failed, "the render ends");
// A render the ledger holds and the home has not taken: listed with the others, not sent.
var output = Path.Combine(folder.ExportsDirectory, "clip-MJPEG.avi");
Directory.CreateDirectory(folder.ExportsDirectory);
await File.WriteAllBytesAsync(output, [1, 2, 3], bed.Ct);
var entry = new WorkspaceRenderEntry(Guid.CreateVersion7(), jobId, "clip-MJPEG.avi", new string('0', 64), 3, "Custom", "Mjpeg", 96, 64, 25, 0.16,
projectId, null, null, DateTimeOffset.UtcNow);
using (await folder.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(10)), bed.Ct)) folder.WriteRenders(WorkspaceRenders.Empty.With(entry));
var reread = await source.LoadAsync(bed.Ct);
Assert.Equal(1, source.UnsentRenders);
Assert.Equal((entry.RenderId, output), (reread.Renders[0].Id, reread.Renders[0].OutputPath));
}
}
[Test]
public async Task VersionOnRenderSavesAChangedProjectFirst()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var settings = new AppSettings();
Assert.True(settings is { WorkspaceVersionOnRender: true, WorkspaceAutoSync: true }, "on by default");
var host = bed.Host(settings);
var projectId = await bed.CheckoutAsync(host);
var (source, session) = await bed.OpenAsync(host, projectId);
var ui = new RecordingUi();
await using (session)
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
{
await menu.RefreshAsync();
var folder = host.Store.Find(projectId)!;
var before = folder.Versions().Count;
// Nothing changed: nothing saved.
Assert.True(await menu.ReadyToRenderAsync());
Assert.Equal(before, folder.Versions().Count);
// Changed: saved as a version noted Render and sent (Sync automatically); the render names it.
Assert.True(session.SetHero(2));
Assert.True(await session.FlushAsync());
Assert.True(await menu.ReadyToRenderAsync());
var saved = folder.Versions()[^1];
Assert.Equal((before + 1, Loc.L("Editor.Workspace.RenderNote")), (folder.Versions().Count, saved.Note));
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
Assert.Equal(Loc.L("Editor.Workspace.SavedForRender", Formatting.Count(folder.ReadBundle().Workspace!.Base!.Number)), ui.Toasts[^1].Title);
var (render, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal(folder.ReadBundle().Workspace!.Base!.VersionId, render.ProjectVersionId);
// Off: the project renders as it is, no version saved.
settings.WorkspaceVersionOnRender = false;
Assert.True(session.SetHero(3));
Assert.True(await session.FlushAsync());
Assert.True(await menu.ReadyToRenderAsync());
Assert.Equal(before + 1, folder.Versions().Count);
Assert.Empty(ui.Confirmations);
}
}
}
@@ -0,0 +1,185 @@
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Shell;
using Chronos.App.Tests.Editor;
using Chronos.App.Tests.Windows;
using Chronos.App.Workspace;
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Localization;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Windows.Shell;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// Phase 5c in Edit: "Open in workspace" offers the originals (Settings › Workspace › Media first, the proxies when the
/// drive has no room), and Settings › Workspace › Open project picks the project a sequence with several opens.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
[Category("workspace")]
public sealed class WorkspaceOpenPolicyTests(TestContext context)
{
private static readonly SequenceProject Main = new() { Id = Guid.CreateVersion7(), SequenceId = Guid.CreateVersion7(), Name = ProjectService.MainName, IsMain = true };
[Test]
public void TheOpenDialogStartsWithTheMediaOfTheSettingsWhenTheyFit()
{
UiLanguage.Apply("en");
var room = new WorkspaceCopyFacts(10_000_000, 100_000_000_000, 4_000_000_000);
using var proxies = new OpenInWorkspaceDialogViewModel("Harbour", [Main], _ => { }, copy: room);
Assert.True(proxies is { IsProxies: true, IsOriginals: false, CanCopyOriginals: true });
Assert.Equal(BundleMedia.Proxies, proxies.Media);
Assert.Contains(proxies.CopyFacts, f => f.Label == Loc.L("Editor.OpenWorkspace.Originals"));
using var originals = new OpenInWorkspaceDialogViewModel("Harbour", [Main], _ => { }, copy: room, defaultMedia: BundleMedia.Originals);
Assert.True(originals is { IsOriginals: true, IsProxies: false, IsShortOfSpace: false });
Assert.Equal(Loc.L("Tooltips.Editor.OpenWorkspace.OriginalsReady"), originals.OriginalsToolTip);
originals.OpenCommand.Execute(null);
Assert.Equal(new OpenChoice(Main.Id, null, BundleMedia.Originals), originals.Choice.Result);
// The drive has room for the proxies, not the originals: they are offered disabled, why in the tooltip.
var tight = new WorkspaceCopyFacts(10_000_000, WorkspaceJobs.CopySpaceReserve + 20_000_000, 4_000_000_000);
using var refused = new OpenInWorkspaceDialogViewModel("Harbour", [Main], _ => { }, copy: tight, defaultMedia: BundleMedia.Originals);
Assert.True(refused is { IsProxies: true, CanCopyOriginals: false, IsShortOfSpace: false });
refused.IsOriginals = true;
Assert.False(refused.IsOriginals, "never chosen without room");
Assert.Equal(Loc.L("Tooltips.Editor.OpenWorkspace.NoRoomOriginals"), refused.OriginalsToolTip);
refused.OpenCommand.Execute(null);
Assert.Equal(BundleMedia.Proxies, refused.Choice.Result!.Media);
// Not measured (a server out of reach): offered, the copy measures again before it writes.
using var unmeasured = new OpenInWorkspaceDialogViewModel("Harbour", [Main], _ => { }, server: true);
Assert.True(unmeasured.CanCopyOriginals);
Assert.Equal(Loc.L("Tooltips.Editor.OpenWorkspace.OriginalsReady.Server"), unmeasured.OriginalsToolTip);
unmeasured.IsOriginals = true;
Assert.Equal(BundleMedia.Originals, unmeasured.Media);
}
[Test]
public Task TheOriginalsAreCopiedAndTheOpenProjectFollowsTheSettings() => ScreenHost.RunAsync(async () =>
{
var directory = context.CreateTempDirectory("workspace-open-policy");
var environment = AppEnvironment.From(AppPaths.Resolve(Directory.CreateDirectory(Path.Combine(directory, "app")).FullName,
Directory.CreateDirectory(Path.Combine(directory, "local")).FullName, []));
UiLanguage.Apply("en");
var settings = new AppSettings
{
Language = "en", FirstRunCompleted = true, CheckForUpdates = false, WorkspaceDefaultMedia = BundleMedia.Originals,
};
var services = new AppServices(environment, settings, () => { }, new NoDialogs());
await services.AttachAsync(await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(environment.DatabasePath)), startEngine: true);
var shell = new ShellViewModel(services);
try
{
var sequenceId = await SequenceAsync(services, Path.Combine(directory, "archive"));
var section = shell.Sequence;
// The originals, as the settings say: copied beside the proxies, and the project's menu offers Proxies only.
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time");
var ask = (OpenInWorkspaceDialogViewModel)section.Dialog!;
Assert.True(ask.IsOriginals, "the settings' media first");
ask.OpenCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "the project opens once its media are copied");
var mainId = section.OpenProjectId!.Value;
var menu = Assert.NotNull(section.Editor!.Project);
Assert.True(menu.HoldsOriginals);
var media = services.Workspace.Store.Find(mainId)!.ReadMedia()!;
Assert.True(media.HoldsOriginals && media.Frames.All(f => f.HasOriginal), "every frame has its original");
Assert.True(settings.WorkspaceOpened.ContainsKey(mainId), "the open is recorded for the clean-up");
Assert.True(await section.ConfirmCloseAsync());
await section.CloseAsync();
shell.KeepSequence(null);
// A second project here, opened last.
var vertical = (await services.Archives!.Projects.CreateAsync(sequenceId, "Vertical", cancellationToken: context.Cancellation)).Id;
var checkout = await services.Workspace.CheckoutAsync(sequenceId, vertical, null);
await WorkspaceTestBed.UntilAsync(() => services.Database!.Jobs.GetAsync(checkout.Copy.Id).GetAwaiter().GetResult()?.State == JobState.Done, "its media are copied");
services.Workspace.Remember(sequenceId, vertical);
// Last used: Vertical.
settings.WorkspaceOpenProject = WorkspaceOpenPolicy.LastUsed;
Assert.Equal(vertical, await OpenAsync(shell, sequenceId));
// Main, whichever opened last.
settings.WorkspaceOpenProject = WorkspaceOpenPolicy.Main;
Assert.Equal(mainId, await OpenAsync(shell, sequenceId));
// Ask: the projects here are listed, the one opened last first; closing it opens nothing.
settings.WorkspaceOpenProject = WorkspaceOpenPolicy.Ask;
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenProjectDialogViewModel, "Open which project? asks");
var which = (OpenProjectDialogViewModel)section.Dialog!;
Assert.Equal(2, which.Projects.Count);
Assert.Equal(mainId, which.SelectedProject!.Entry.ProjectId);
which.CloseCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is null, "closed without a choice");
Assert.Null(section.Editor);
shell.KeepSequence(null);
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenProjectDialogViewModel, "Open which project? asks again");
which = (OpenProjectDialogViewModel)section.Dialog!;
which.SelectedProject = which.Projects.Single(p => p.Entry.ProjectId == vertical);
which.OpenCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "the project chosen opens");
Assert.Equal(vertical, section.OpenProjectId);
}
finally
{
await shell.Sequence.CloseAsync();
shell.Dispose();
await services.DisposeAsync();
}
});
/// <summary>Opens the sequence in Edit as the settings say and returns the project that opened, closed again.</summary>
private static async Task<Guid> OpenAsync(ShellViewModel shell, Guid sequenceId)
{
var section = shell.Sequence;
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "the project opens");
Assert.Null(section.Dialog);
var opened = section.OpenProjectId!.Value;
Assert.True(await section.ConfirmCloseAsync());
await section.CloseAsync();
shell.KeepSequence(null);
return opened;
}
/// <summary>An archive with one sequence of six synthetic photos, indexed.</summary>
private async Task<Guid> SequenceAsync(AppServices services, string root)
{
var archives = services.Archives!;
var archive = await archives.CreateAsync(root, "Test");
var sequence = EditorFixture.Sequence(6);
var folder = Path.Combine(root, "Synthetic");
Directory.CreateDirectory(folder);
for (var i = 0; i < sequence.Count; i++)
{
using var image = sequence.Render(i);
var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i]);
File.WriteAllBytes(Path.Combine(folder, $"IMG_{i + 1:0000}.JPG"), JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] }));
}
await archives.Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, context.Cancellation);
return (await services.Database!.Sequences.ListLocationsAsync(archive.Id, context.Cancellation)).Single().Id;
}
/// <summary>Dialogs that pick nothing and decline every confirmation.</summary>
private sealed class NoDialogs : IAppDialogs
{
public string? PickFolder(string title, string? initialFolder = null) => null;
public string? PickJsonFile(string title) => null;
public bool Confirm(ConfirmRequest request) => false;
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
}
}
@@ -53,7 +53,7 @@ public sealed class WorkspaceSectionTests(TestContext context)
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time");
var ask = (OpenInWorkspaceDialogViewModel)section.Dialog!;
Assert.Equal(Loc.L("Editor.Project.Main"), ask.SelectedProject!.Label, "Main, made from the sequence's settings, is offered first");
Assert.True(ask.IsProxies && !ask.CanCopyOriginals, "proxies; the originals come later");
Assert.True(ask.IsProxies && ask.CanCopyOriginals, "the proxies first, the originals offered (Settings › Workspace › Media)");
Assert.True(section.ShowsPicker && !section.IsLoading, "the picker shows behind the dialog, not the progress bar");
ask.OpenCommand.Execute(null);
Assert.Null(section.Dialog);
@@ -143,7 +143,8 @@ public sealed class WorkspaceSectionTests(TestContext context)
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time");
var ask = (OpenInWorkspaceDialogViewModel)section.Dialog!;
Assert.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free")], ask.CopyFacts.Select(f => f.Label), "the copy's facts reach the dialog");
Assert.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free"), Loc.L("Editor.OpenWorkspace.Originals")], ask.CopyFacts.Select(f => f.Label),
"the copy's facts reach the dialog");
ask.OpenCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Title == Loc.L("Editor.Workspace.OpenFailed")), "the refusal is said");
var refused = toasts.Single(t => t.Title == Loc.L("Editor.Workspace.OpenFailed"));
@@ -30,6 +30,30 @@ public sealed class JobPriorityQueueTests
Assert.Equal(JobKindPriority.Low, (queue with { Levels = new Dictionary<JobKind, JobKindPriority> { [JobKind.Render] = JobKindPriority.Low } }).LevelOf(JobKind.Render));
}
[Test]
public void ALocalRenderAndAWorkspaceMoveGoFirstAndSendingARenderHomeWaitsItsTurn()
{
var queue = new JobPriorityQueue();
// The user waits on a local render as on a render, and Edit is held while the workspace moves.
Assert.Equal(JobKindPriority.High, queue.LevelOf(JobKind.WorkspaceRender));
Assert.Equal(JobKindPriority.High, queue.LevelOf(JobKind.WorkspaceMove));
Assert.Equal(JobKindPriority.Normal, queue.LevelOf(JobKind.WorkspaceSend));
var on = queue with { Enabled = true };
Assert.True(on.Interrupts(JobKind.WorkspaceRender, JobKind.WorkspaceSend));
Assert.False(on.Interrupts(JobKind.WorkspaceSend, JobKind.Scan));
// The defaults are no change: settings store none of them, and read back as they are.
var defaults = new Dictionary<JobKind, JobKindPriority>
{
[JobKind.WorkspaceRender] = JobKindPriority.High,
[JobKind.WorkspaceSend] = JobKindPriority.Normal,
[JobKind.WorkspaceMove] = JobKindPriority.High,
};
Assert.Empty(JobPriorityQueue.Changed(defaults));
var changed = JobPriorityQueue.Changed(new Dictionary<JobKind, JobKindPriority> { [JobKind.WorkspaceSend] = JobKindPriority.Low });
Assert.Equal("low", changed["workspace-send"]);
Assert.Equal(JobKindPriority.Low, JobPriorityQueue.From(true, changed).LevelOf(JobKind.WorkspaceSend));
}
[Test]
public void OnlyAHigherLevelInterruptsAndOnlyWhileTheQueueIsOn()
{
@@ -0,0 +1,31 @@
using Chronos.Core.Model;
using Chronos.Data.Jobs;
using Chronos.Testing;
namespace Chronos.Data.Tests.Jobs;
/// <summary>The names the jobs' kinds carry on the wire and in settings (BRIEF §14.6): stable once shipped.</summary>
[Category("jobs")]
public sealed class JobWireTests
{
[Theory]
[Case(JobKind.WorkspaceCopy, 20, "workspace-copy")]
[Case(JobKind.WorkspaceRender, 21, "workspace-render")]
[Case(JobKind.WorkspaceSend, 22, "workspace-send")]
[Case(JobKind.WorkspaceMove, 23, "workspace-move")]
public void TheWorkspaceJobsKeepTheirValueAndName(JobKind kind, int value, string name)
{
Assert.Equal(value, (int)kind);
Assert.Equal(name, JobWire.Kind(kind));
Assert.True(JobWire.TryParseKind(name, out var parsed), name);
Assert.Equal(kind, parsed);
}
[Test]
public void EveryKindHasItsOwnName()
{
var names = Enum.GetValues<JobKind>().Select(JobWire.Kind).ToList();
Assert.Equal(names.Count, names.Distinct(StringComparer.Ordinal).Count());
Assert.False(JobWire.TryParseKind("workspace-teleport", out _));
}
}
@@ -0,0 +1,211 @@
using System.Text.Json.Nodes;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Tests.Archiving;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.Data.Tests.Workspaces;
/// <summary>
/// The shared types of phase 5c (owner review 2, R8): originals in the media index, the ledger of local renders, the names
/// of the workspace's files, and the jobs of the workspace with their parameters.
/// </summary>
[Category("workspace")]
public sealed class WorkspaceFoundationTests(TestContext context)
{
private static readonly DateTimeOffset T0 = new(2026, 11, 4, 9, 0, 0, TimeSpan.Zero);
private static WorkspaceMedia Media(Guid sequenceId, string kind, params WorkspaceFrame[] frames) =>
new(WorkspaceMedia.FormatName, WorkspaceMedia.CurrentFormatVersion, kind, sequenceId, 3, frames, T0);
private static WorkspaceFrame Frame(Guid sequenceId, int index) =>
WorkspaceFrame.Of(TestData.Frame(sequenceId, index), $"proxies/{Guid.NewGuid():N}.jpg", new string('a', 64), 1_500_000);
[Test]
public void AMediaIndexOfPhase5bReadsAsProxiesWithoutOriginals()
{
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("ws"), "workspace"));
var project = store.Project(Guid.CreateVersion7());
var sequenceId = Guid.CreateVersion7();
project.WriteMedia(Media(sequenceId, BundleMedia.Proxies, Frame(sequenceId, 0), Frame(sequenceId, 1)));
// As phase 5b wrote it: no original fields at all.
var json = JsonNode.Parse(File.ReadAllText(project.MediaIndexPath))!.AsObject();
foreach (var frame in json["frames"]!.AsArray())
{
var fields = frame!.AsObject();
foreach (var name in new[] { "original", "originalSha256", "originalBytes" }) fields.Remove(name);
}
File.WriteAllText(project.MediaIndexPath, json.ToJsonString());
Assert.False(File.ReadAllText(project.MediaIndexPath).Contains("\"original\"", StringComparison.Ordinal), "no original field is left");
var media = Assert.NotNull(project.ReadMedia());
Assert.Equal(BundleMedia.Proxies, media.Kind);
Assert.False(media.HoldsOriginals);
foreach (var frame in media.Frames)
{
Assert.Equal(((string?)null, (string?)null, 0L, false), (frame.Original, frame.OriginalSha256, frame.OriginalBytes, frame.HasOriginal));
// A render from originals finds none: every frame is missing there, while the editor reads its proxy.
Assert.True(frame.ToOriginalFrame(sequenceId).Flags.HasFlag(FrameFlags.Missing));
Assert.False(frame.ToFrame(sequenceId).Flags.HasFlag(FrameFlags.Missing));
}
}
[Test]
public void OriginalsInTheMediaIndexAreReadBackAndRenderedFrom()
{
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("ws"), "workspace"));
var project = store.Project(Guid.CreateVersion7());
var sequenceId = Guid.CreateVersion7();
var held = Frame(sequenceId, 0);
var sha = new string('c', 64);
var original = WorkspaceProject.OriginalName(held.Id, sha, Path.GetExtension(held.FileName));
held = held with { Original = original, OriginalSha256 = sha, OriginalBytes = held.Size };
var proxied = Frame(sequenceId, 1);
project.WriteMedia(Media(sequenceId, BundleMedia.Originals, held, proxied));
var media = Assert.NotNull(project.ReadMedia());
Assert.True(media.HoldsOriginals);
Assert.Equal((original, sha, held.Size), (media.Frames[0].Original, media.Frames[0].OriginalSha256, media.Frames[0].OriginalBytes));
var frames = media.ToOriginalFrames();
Assert.Equal(original, frames[0].RelativePath);
Assert.False(frames[0].Flags.HasFlag(FrameFlags.Missing));
// A frame whose original the home lacked stays a proxy for the editor and is missing for a local render.
Assert.True(frames[1].Flags.HasFlag(FrameFlags.Missing));
Assert.Equal(proxied.File, media.ToFrames()[1].RelativePath);
Assert.Equal(Path.Combine(project.OriginalsDirectory, Path.GetFileName(original)), project.MediaFile(original));
}
[Test]
public void OriginalsKeepTheirExtensionAndAShortHashInTheirName()
{
var id = Guid.Parse("0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01");
var sha = "ABCDEF0123456789" + new string('0', 48);
Assert.Equal("originals/0192a4c17b3e7cc08a512f9d0e6b1a01-abcdef01.cr3", WorkspaceProject.OriginalName(id, sha, ".CR3"));
Assert.Equal("originals/0192a4c17b3e7cc08a512f9d0e6b1a01-abcdef01.dng", WorkspaceProject.OriginalName(id, sha, "dng"));
Assert.Equal("originals/0192a4c17b3e7cc08a512f9d0e6b1a01-abcdef01", WorkspaceProject.OriginalName(id, sha, null));
Assert.Equal("originals/0192a4c17b3e7cc08a512f9d0e6b1a01-abcdef01", WorkspaceProject.OriginalName(id, sha, "a/b"));
Assert.Throws<ArgumentException>(() => WorkspaceProject.OriginalName(id, string.Empty, ".jpg"));
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("ws"), "workspace"));
var project = store.Project(id);
Assert.Equal("exports/renders.json", WorkspaceProject.RendersFile);
Assert.Equal(Path.Combine(project.Folder, "exports", "renders.json"), project.RendersPath);
Assert.Equal(Path.Combine(project.ExportsDirectory, "Roof 4K.mp4"), project.ExportFile("Roof 4K.mp4"));
}
private static WorkspaceRenderEntry Entry(Guid projectId, string file) =>
new(Guid.CreateVersion7(), Guid.CreateVersion7(), file, new string('b', 64), 12_345, "4K HEVC", "hevc", 3840, 2160, 30, 10, projectId,
Guid.CreateVersion7(), "hash", T0);
[Test]
public void TheLedgerOfLocalRendersIsWrittenWholeAndReadBack()
{
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("ws"), "workspace"));
var project = store.Project(Guid.CreateVersion7());
// No ledger yet: no renders.
Assert.Empty(project.ReadRenders().Entries);
Assert.Same(WorkspaceRenders.Empty, project.ReadRenders());
var first = Entry(project.ProjectId, "Roof 4K.mp4");
var second = Entry(project.ProjectId, "Roof 1080p.mp4") with { ProjectVersionId = null, SettingsHash = null };
var ledger = WorkspaceRenders.Empty.With(first).With(second);
project.WriteRenders(ledger);
Assert.FileExists(project.RendersPath);
Assert.Empty(Directory.GetFiles(project.ExportsDirectory, "*.tmp"));
var read = project.ReadRenders();
Assert.Equal((WorkspaceRenders.FormatName, 1, 2), (read.Format, read.FormatVersion, read.Entries.Count));
Assert.Equal(first, read.Entries[0]);
Assert.Equal(second, read.Entries[1]);
Assert.Equal(WorkspaceRenderEntry.Pending, read.Entries[0].State);
Assert.Count(2, read.Unsent);
Assert.Contains("\"state\": \"pending\"", File.ReadAllText(project.RendersPath));
// One entry per render id: a send that went home replaces it, a second time changes nothing.
var sent = read.With(first.AsSent(T0.AddMinutes(5)));
Assert.Count(2, sent.Entries);
Assert.True(Assert.NotNull(sent.Find(first.RenderId)).IsSent);
Assert.True(sent.Entries.SequenceEqual(sent.With(first.AsSent(T0.AddMinutes(5))).Entries), "the same send twice changes nothing");
Assert.True(sent.Unsent.Select(e => e.RenderId).SequenceEqual([second.RenderId]), "only the render not sent is unsent");
var failed = sent.With(second.AsFailed("The library cannot be reached now."));
Assert.Equal((WorkspaceRenderEntry.Failed, "The library cannot be reached now."), (failed.Find(second.RenderId)!.State, failed.Find(second.RenderId)!.Error));
Assert.True(failed.Find(second.RenderId)!.IsUnsent, "a failed send is sent again");
Assert.Count(1, failed.Without(first.RenderId).Entries);
Assert.Null(failed.Find(Guid.NewGuid()));
project.WriteRenders(failed);
Assert.True(failed.Entries.SequenceEqual(project.ReadRenders().Entries), "the ledger reads back as written");
}
[Test]
public void ALedgerDamagedOrOfANewerChronosIsRefused()
{
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("ws"), "workspace"));
var project = store.Project(Guid.CreateVersion7());
Directory.CreateDirectory(project.ExportsDirectory);
File.WriteAllText(project.RendersPath, "{ \"format\": \"chronos-workspace-renders\", \"formatVersion\": 1, \"entries\": [ { \"renderId\": ");
Assert.Throws<InvalidDataException>(() => project.ReadRenders());
File.WriteAllText(project.RendersPath, """{ "format": "something-else", "formatVersion": 1, "entries": [] }""");
Assert.Throws<InvalidDataException>(() => project.ReadRenders());
File.WriteAllText(project.RendersPath, """{ "format": "chronos-workspace-renders", "formatVersion": 2, "entries": [] }""");
Assert.Throws<InvalidDataException>(() => project.ReadRenders());
// A state a later Chronos wrote counts as not sent: its file is never cleaned up.
var entry = Entry(project.ProjectId, "Roof.mp4") with { State = "queued-elsewhere" };
project.WriteRenders(WorkspaceRenders.Empty.With(entry));
Assert.True(project.ReadRenders().Entries.Single().IsUnsent);
}
[Test]
public void TheWorkspaceJobsCarryTheirParameters()
{
var sequenceId = Guid.CreateVersion7();
var projectId = Guid.CreateVersion7();
var versionId = Guid.CreateVersion7();
var root = Path.Combine(context.CreateTempDirectory("ws"), "workspace");
var render = WorkspaceJobs.Render(sequenceId, "Roof", root, projectId, versionId, """{ "presetName": "4K HEVC" }""", "https://studio:8443");
Assert.Equal((JobKind.WorkspaceRender, "Roof", JobPriority.User), (render.Kind, render.Label, render.Priority));
Assert.True(render.Targets.SequenceEqual([sequenceId]), "the render targets its sequence");
var rendered = Assert.NotNull(WorkspaceJobs.RenderParameters(Job(render)));
Assert.Equal(new WorkspaceRenderParameters(root, projectId, versionId, """{ "presetName": "4K HEVC" }""", "https://studio:8443"), rendered);
var ids = new[] { Guid.CreateVersion7(), Guid.CreateVersion7() };
var send = WorkspaceJobs.Send(sequenceId, "Roof", root, projectId, ids);
Assert.Equal((JobKind.WorkspaceSend, JobPriority.User), (send.Kind, send.Priority));
var sending = Assert.NotNull(WorkspaceJobs.SendParameters(Job(send)));
Assert.Equal((root, projectId, (string?)null), (sending.WorkspaceRoot, sending.ProjectId, sending.Server));
Assert.True(sending.RenderIds.SequenceEqual(ids), "the send names its renders");
var target = Path.Combine(context.CreateTempDirectory("fast"), "workspace");
var move = WorkspaceJobs.Move(root, target, "fingerprint");
Assert.Equal((JobKind.WorkspaceMove, target, 0), (move.Kind, move.Label, move.Targets.Count));
Assert.Equal(new WorkspaceMoveParameters(root, target, "fingerprint"), WorkspaceJobs.MoveParameters(Job(move)));
// Parameters of another kind, or none that read, are none.
Assert.Null(WorkspaceJobs.RenderParameters(Job(send)));
Assert.Null(WorkspaceJobs.MoveParameters(Job(move) with { ParametersJson = "{" }));
Assert.Equal(BundleMedia.Originals, WorkspaceJobs.CopyParameters(Job(WorkspaceJobs.CopyFromServer(sequenceId, "Roof", "https://studio:8443", root,
projectId, BundleMedia.Originals)))!.Media);
Assert.Throws<ArgumentException>(() => WorkspaceJobs.Move(root, target, " "));
static Job Job(ArchiveJobRequest request) => TestData.Job(request.Kind) with { TargetIds = request.Targets, ParametersJson = request.ParametersJson };
}
[Test]
public async Task TheWorkspaceRegistersAHandlerForEachOfItsJobs()
{
await using var archive = await ArchiveFixture.CreateAsync(context);
var kinds = new[] { JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend, JobKind.WorkspaceMove };
var handlers = WorkspaceJobs.CreateHandlers(archive.Db, archive.Service, null, WorkspaceJobOptionsFor());
Assert.True(handlers.Select(h => h.Kind).SequenceEqual(kinds), string.Join(", ", handlers.Select(h => h.Kind)));
// The overloads of phase 5b register them all too.
Assert.True(WorkspaceJobs.CreateHandlers(archive.Db, archive.Service).Select(h => h.Kind).SequenceEqual(kinds), "the earlier overload");
static WorkspaceJobOptions WorkspaceJobOptionsFor() => new(new Chronos.Data.Processing.ProcessingOptions(), () => false);
}
}
@@ -0,0 +1,187 @@
using System.Security.Cryptography;
using Chronos.Core.Localization;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Core.Model;
using Chronos.Data.Tests.Archiving;
using Chronos.Data.Tests.Infrastructure;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.Data.Tests.Workspaces;
/// <summary>A workspace project's originals (phase 5c): their copy from the archive, checked and resumable, and "Proxies only".</summary>
[Category("workspace")]
public abstract class WorkspaceOriginalsTests(TestContext context) : DatabaseTest(context)
{
private async Task<WorkspaceFixture> FixtureAsync(int frames = 3, Func<ArchiveServiceOptions, ArchiveServiceOptions>? configure = null)
{
var archive = Own(await ArchiveFixture.CreateAsync(Context, database: await NewOptionsAsync(multiConnection: true), configure: configure));
var fx = Own(await WorkspaceFixture.CreateAsync(Context, archive, frames));
// The archive's own proxies: the copy takes those, so a damaged original never changes a proxy.
await archive.Service.Images.BuildProxiesAsync(archive.Archive, fx.Sequence, force: false, 0, (_, _) => ValueTask.CompletedTask, fx.Ct);
return fx;
}
private static string Sha(string path) => Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path)));
private static async Task<(WorkspaceStore Store, WorkspaceProject Project)> CheckoutOriginalsAsync(WorkspaceFixture fx)
{
var (store, sync) = fx.Workspace();
var main = await fx.Archive.Service.Projects.MainAsync(fx.Sequence.Id, fx.Ct);
var project = await sync.CheckoutAsync(fx.Home, main.Id, BundleMedia.Originals, fx.Ct);
return (store, project);
}
private string Source(WorkspaceFixture fx, int index) => fx.Archive.Paths.FromRelative(fx.Frames.Single(f => f.Index == index).RelativePath);
[Test]
public async Task ACopyOfTheOriginalsHoldsEachPhotoCheckedAgainstTheHome()
{
var fx = await FixtureAsync();
var (store, project) = await CheckoutOriginalsAsync(fx);
Assert.Equal(fx.Frames.Sum(f => f.Size), await WorkspaceOriginals.ArchiveOriginalsBytesAsync(fx.Db, fx.Archive.Service, fx.Sequence.Id, cancellationToken: fx.Ct));
await fx.CopyAsync(store, project.ProjectId, media: BundleMedia.Originals);
var media = project.ReadMedia()!;
Assert.True(media.HoldsOriginals);
Assert.Equal(BundleMedia.Originals, project.ReadBundle().Workspace!.Media.Kind);
foreach (var frame in fx.Frames)
{
var entry = media.Frames.Single(f => f.Id == frame.Id);
Assert.NotNull(entry.File);
var original = project.MediaFile(Assert.NotNull(entry.Original));
Assert.Equal(frame.Sha256!.ToLowerInvariant(), entry.OriginalSha256);
Assert.Equal(entry.OriginalSha256, Sha(original));
Assert.Equal(frame.Size, entry.OriginalBytes);
Assert.Equal(WorkspaceProject.OriginalName(frame.Id, frame.Sha256, Path.GetExtension(frame.RelativePath)), entry.Original);
}
Assert.Empty(Directory.GetFiles(project.OriginalsDirectory, "*.part"));
Assert.Equal(0L, await WorkspaceOriginals.ArchiveOriginalsBytesAsync(fx.Db, fx.Archive.Service, fx.Sequence.Id, project, fx.Ct));
// The frames read by a local render are the originals.
Assert.SequenceEqual(media.Frames.Select(f => f.Original), media.ToOriginalFrames().Select(f => f.RelativePath));
}
[Test]
public async Task AnOriginalThatIsGoneOrDamagedAtTheHomeLeavesItsFrameProxied()
{
var fx = await FixtureAsync();
var (store, project) = await CheckoutOriginalsAsync(fx);
File.Delete(Source(fx, 0));
var damaged = Source(fx, 1);
var bytes = File.ReadAllBytes(damaged);
bytes[^3] ^= 0x5A;
File.WriteAllBytes(damaged, bytes);
await fx.CopyAsync(store, project.ProjectId, media: BundleMedia.Originals);
var media = project.ReadMedia()!;
Assert.True(media.HoldsOriginals);
var gone = media.Frames.Single(f => f.Index == 0);
var mismatched = media.Frames.Single(f => f.Index == 1);
Assert.Null(gone.Original);
Assert.Null(mismatched.Original);
Assert.NotNull(mismatched.File);
Assert.NotNull(media.Frames.Single(f => f.Index == 2).Original);
Assert.Equal(1, Directory.GetFiles(project.OriginalsDirectory).Length);
Assert.True(media.ToOriginalFrames().Count(f => (f.Flags & FrameFlags.Missing) != 0) == 2, "a render counts the two frames without an original");
}
[Test]
public async Task ACopyStoppedAmongTheOriginalsResumesWithWhatItHad()
{
var fx = await FixtureAsync();
var (store, project) = await CheckoutOriginalsAsync(fx);
await fx.CopyAsync(store, project.ProjectId, media: BundleMedia.Originals);
var media = project.ReadMedia()!;
var kept = project.MediaFile(media.Frames[0].Original!);
var written = File.GetLastWriteTimeUtc(kept);
var lost = project.MediaFile(media.Frames[2].Original!);
File.Delete(lost);
File.WriteAllBytes(Path.Combine(project.OriginalsDirectory, media.Frames[2].Id.ToString("N") + ".part"), [1, 2, 3]);
var row = (await fx.Db.Sequences.GetAsync(fx.Sequence.Id))!;
await fx.CopyAsync(store, project.ProjectId, checkpoint: $"originals:2:{row.FramesVersion}:{row.Folder}", media: BundleMedia.Originals);
Assert.Equal(written, File.GetLastWriteTimeUtc(kept));
Assert.Equal(media.Frames[2].OriginalSha256, Sha(lost));
Assert.Empty(Directory.GetFiles(project.OriginalsDirectory, "*.part"));
Assert.Equal(3, project.ReadMedia()!.Frames.Count(f => f.HasOriginal));
}
[Test]
public async Task TheOriginalsAreNotCopiedWhenTheDriveLacksTheirRoom()
{
long? free = null;
var fx = await FixtureAsync(configure: options => options with { FreeSpace = _ => free });
var (store, project) = await CheckoutOriginalsAsync(fx);
await fx.CopyAsync(store, project.ProjectId);
free = WorkspaceJobs.CopySpaceReserve + fx.Frames.Sum(f => f.Size) - 1;
var job = await fx.CopyAsync(store, project.ProjectId, JobState.Failed, media: BundleMedia.Originals);
var parts = Loc.L("Errors.Workspace.DiskFull", "\u0001").Split('\u0001');
Assert.True(job.Error!.StartsWith(parts[0], StringComparison.Ordinal), job.Error);
Assert.False(project.ReadMedia()!.HoldsOriginals);
Assert.False(Directory.Exists(project.OriginalsDirectory) && Directory.EnumerateFiles(project.OriginalsDirectory).Any());
}
[Test]
public async Task ProxiesOnlyDeletesWhatTheHomeHoldsAndTrashesTheRest()
{
var fx = await FixtureAsync();
var (store, project) = await CheckoutOriginalsAsync(fx);
await fx.CopyAsync(store, project.ProjectId, media: BundleMedia.Originals);
var media = project.ReadMedia()!;
// The home lost frame 1's photo: its only copy is the workspace's, which goes to the trash, not away.
var lostAtHome = project.MediaFile(media.Frames[1].Original!);
var home = await fx.Home.FramesAsync(fx.Ct);
home = home with { Frames = [.. home.Frames.Select(f => f.Index == 1 ? f with { Flags = f.Flags | FrameFlags.Missing } : f)] };
var plan = WorkspaceOriginals.PlanProxiesOnly(project, home);
Assert.Equal((2, 1), (plan.Originals, plan.ToTrash));
Assert.Equal(fx.Frames.Where(f => f.Index != 1).Sum(f => f.Size), plan.Bytes);
var trashed = await WorkspaceOriginals.ApplyProxiesOnlyAsync(project, plan, home, TimeSpan.FromSeconds(10), fx.Ct);
Assert.Equal(1, trashed);
Assert.False(Directory.Exists(project.OriginalsDirectory));
var after = project.ReadMedia()!;
Assert.False(after.HoldsOriginals);
Assert.True(after.Frames.All(f => f.Original is null && f.File is not null));
Assert.Equal(BundleMedia.Proxies, project.ReadBundle().Workspace!.Media.Kind);
var inTrash = Directory.GetFiles(Path.Combine(store.Root, WorkspaceOriginals.TrashFolder), Path.GetFileName(lostAtHome), SearchOption.AllDirectories);
Assert.Equal(1, inTrash.Length);
Assert.Equal(media.Frames[1].OriginalSha256, Sha(inTrash[0]));
}
[Test]
public async Task ProxiesOnlyRefusesAPlanTheFilesChangedSince()
{
var fx = await FixtureAsync();
var (store, project) = await CheckoutOriginalsAsync(fx);
await fx.CopyAsync(store, project.ProjectId, media: BundleMedia.Originals);
var home = await fx.Home.FramesAsync(fx.Ct);
var plan = WorkspaceOriginals.PlanProxiesOnly(project, home);
Assert.Equal((3, 0), (plan.Originals, plan.ToTrash));
var changed = project.MediaFile(project.ReadMedia()!.Frames[0].Original!);
File.AppendAllText(changed, "x");
var error = await Assert.ThrowsAsync<InvalidOperationException>(() => WorkspaceOriginals.ApplyProxiesOnlyAsync(project, plan, home, TimeSpan.FromSeconds(10), fx.Ct));
Assert.Equal(Loc.L("Errors.Workspace.MediaChanged"), error.Message);
Assert.True(project.ReadMedia()!.HoldsOriginals);
Assert.Equal(3, Directory.GetFiles(project.OriginalsDirectory).Length);
// Planned again, the changed file is no photo the home holds: it goes to the trash.
var again = WorkspaceOriginals.PlanProxiesOnly(project, home);
Assert.Equal((2, 1), (again.Originals, again.ToTrash));
Assert.Equal(1, await WorkspaceOriginals.ApplyProxiesOnlyAsync(project, again, home, TimeSpan.FromSeconds(10), fx.Ct));
}
}
public sealed class SqliteWorkspaceOriginalsTests(TestContext context) : WorkspaceOriginalsTests(context)
{
protected override Backend Backend => Backend.SqliteFile;
}
[RequiresEnvironment(PgTestServer.Variable)]
public sealed class PostgresWorkspaceOriginalsTests(TestContext context) : WorkspaceOriginalsTests(context)
{
protected override Backend Backend => Backend.Postgres;
}
@@ -0,0 +1,189 @@
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Export;
using Chronos.Core.Imaging;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Processing.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Tests.Processing;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.Data.Tests.Workspaces;
/// <summary>
/// A workspace project rendered on this PC from the originals its media hold (phase 5c, <see cref="JobKind.WorkspaceRender"/>):
/// into its exports, recorded in its ledger and sent home after; refused without the originals; a cancel leaves nothing half written.
/// </summary>
[Category("workspace")]
public sealed class WorkspaceRenderTests(TestContext context)
{
private const int Frames = 24;
private static readonly ExportSettings Mjpeg = new()
{
Preset = new Auto<string>().WithManual("mjpeg-avi"),
Overrides = new ExportOverrides { Width = 96, Height = 64 },
NameTemplate = "clip-{codec}",
};
private static SyntheticSequence Scene() => SyntheticSequence.Create(new SyntheticSequenceOptions { FrameCount = Frames, StartEv = 0.5, EndEv = -0.5 });
private sealed record Bed(ProcessingFixture Fx, Sequence Sequence, WorkspaceStore Store, WorkspaceProject Project, JobEngine Engine) : IAsyncDisposable
{
public async ValueTask DisposeAsync()
{
await Engine.DisposeAsync();
await Fx.DisposeAsync();
}
}
/// <summary>A sequence of the archive, Main checked out into a workspace with <paramref name="media"/> copied, and an engine running every handler.</summary>
private async Task<Bed> BedAsync(string media = BundleMedia.Originals, Action<ProcessingFixture, Sequence>? beforeCopy = null)
{
var fx = await ProcessingFixture.CreateAsync(context);
var sequence = await fx.AddAsync(Scene());
var engine = new JobEngine(fx.Db,
[
.. fx.Archive.Service.CreateJobHandlers(), .. fx.Processing.CreateJobHandlers(),
.. WorkspaceJobs.CreateHandlers(fx.Db, fx.Archive.Service, null, new WorkspaceJobOptions(fx.Processing.Options, () => false)),
],
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync(fx.Ct);
var store = new WorkspaceStore(Path.Combine(context.CreateTempDirectory("render-ws"), "workspace"));
var sync = new WorkspaceSync(store, "test") { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) };
var home = new ArchiveProjectHome(fx.Db, fx.Archive.Service.Projects, sequence.Id);
var main = await fx.Archive.Service.Projects.MainAsync(sequence.Id, fx.Ct);
var project = await sync.CheckoutAsync(home, main.Id, media, fx.Ct);
beforeCopy?.Invoke(fx, sequence);
var copy = await engine.EnqueueAsync(WorkspaceJobs.Copy(sequence, store.Root, main.Id, media), cancellationToken: fx.Ct);
await fx.WaitForAsync(copy.Id, JobState.Done);
return new Bed(fx, sequence, store, project, engine);
}
private static ArchiveJobRequest RenderRequest(Bed bed, Guid? versionId = null)
{
var json = ProcessingJobs.Render(bed.Sequence, Mjpeg, 96, 64, new ProjectSettings()).ParametersJson!;
return WorkspaceJobs.Render(bed.Sequence.Id, bed.Sequence.DisplayTitle, bed.Store.Root, bed.Project.ProjectId, versionId, json);
}
[Test]
public async Task ARenderFromTheOriginalsIsWrittenToExportsRecordedAndSentAfter()
{
await using var bed = await BedAsync();
var fx = bed.Fx;
var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
var output = Path.Combine(bed.Project.ExportsDirectory, "clip-MJPEG.avi");
Assert.FileExists(output);
Assert.Empty(Directory.EnumerateFileSystemEntries(bed.Project.ExportsDirectory, ".*"));
var entry = bed.Project.ReadRenders().Entries.Single();
Assert.Equal(RenderJobHandler.RenderId(job.Id, 0), entry.RenderId);
Assert.Equal((job.Id, "clip-MJPEG.avi", new FileInfo(output).Length, WorkspaceRenderEntry.Pending, bed.Project.ProjectId),
(entry.JobId, entry.File, entry.Size, entry.State, entry.ProjectId));
Assert.Equal(await Chronos.Core.Archiving.ContentHash.Sha256Async(output), entry.Sha256);
Assert.Equal(("Mjpeg", 96, 64), (entry.Codec, entry.Width, entry.Height));
Assert.Null(entry.ProjectVersionId, "the working state the job embeds is no version this workspace holds");
Assert.Empty(await fx.Db.Renders.ListBySequenceAsync(bed.Sequence.Id, fx.Ct));
// The send home follows with the new render.
var send = (await fx.Db.Jobs.ListAsync(null, 50, null, fx.Ct)).Items.Single(j => j.Kind == JobKind.WorkspaceSend);
var sent = Assert.NotNull(WorkspaceJobs.SendParameters(send));
Assert.SequenceEqual([entry.RenderId], sent.RenderIds);
Assert.Equal((bed.Project.ProjectId, bed.Store.Root), (sent.ProjectId, sent.WorkspaceRoot));
// The same render of the archive's own sequence: the same pictures, at the same size and length.
var archive = await bed.Engine.EnqueueAsync(ProcessingJobs.Render(bed.Sequence, Mjpeg, 96, 64), cancellationToken: fx.Ct);
await fx.WaitForAsync(archive.Id, JobState.Done);
var row = (await fx.Db.Renders.ListBySequenceAsync(bed.Sequence.Id, fx.Ct)).Single();
Assert.Equal((row.Width, row.Height, row.Fps, row.DurationSeconds), (entry.Width, entry.Height, entry.Fps, entry.DurationSeconds));
// Again: another name, the first output and its entry kept.
var again = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
await fx.WaitForAsync(again.Id, JobState.Done);
var entries = bed.Project.ReadRenders().Entries;
Assert.Equal(2, entries.Count);
Assert.True(entries[1].File != entries[0].File, entries[1].File);
Assert.Equal(entry, entries[0]);
}
[Test]
public async Task AVersionHeldInTheWorkspaceIsRecordedWithTheRender()
{
await using var bed = await BedAsync();
var fx = bed.Fx;
var (_, sync) = (bed.Store, new WorkspaceSync(bed.Store, "test"));
var session = await sync.OpenAsync(bed.Project.ProjectId, fx.Ct);
await sync.SaveAsync(bed.Project.ProjectId, session.Working with { ExcludedFrames = [2] }, fx.Ct);
var version = Assert.NotNull(await sync.CommitAsync(bed.Project.ProjectId, "Render", cancellationToken: fx.Ct));
var json = ProcessingJobs.Render(bed.Sequence, Mjpeg, 96, 64).ParametersJson!;
// The job names the version alone: the settings come from versions/.
var stripped = System.Text.Json.Nodes.JsonNode.Parse(json)!.AsObject();
stripped.Remove("settingsJson");
var job = await bed.Engine.EnqueueAsync(
WorkspaceJobs.Render(bed.Sequence.Id, bed.Sequence.DisplayTitle, bed.Store.Root, bed.Project.ProjectId, version.Id, stripped.ToJsonString()), cancellationToken: fx.Ct);
await fx.WaitForAsync(job.Id, JobState.Done);
var entry = bed.Project.ReadRenders().Entries.Single();
Assert.Equal(version.Id, entry.ProjectVersionId);
Assert.Equal(version.ContentHash, entry.SettingsHash);
// A version the workspace does not hold: refused, saying so.
var unknown = await bed.Engine.EnqueueAsync(
WorkspaceJobs.Render(bed.Sequence.Id, bed.Sequence.DisplayTitle, bed.Store.Root, bed.Project.ProjectId, Guid.CreateVersion7(), stripped.ToJsonString()),
cancellationToken: fx.Ct);
Assert.Equal(Loc.L("Errors.Workspace.RenderVersion"), (await fx.WaitForAsync(unknown.Id, JobState.Failed)).Error);
}
[Test]
public async Task WithoutTheOriginalsTheRenderIsRefusedSayingHowManyLack()
{
await using var bed = await BedAsync(beforeCopy: (fx, sequence) =>
{
File.Delete(Path.Combine(fx.Archive.Paths.Root, "Synthetic", ProcessingFixture.FileName(3)));
File.Delete(Path.Combine(fx.Archive.Paths.Root, "Synthetic", ProcessingFixture.FileName(7)));
});
var fx = bed.Fx;
Assert.Equal(Frames - 2, bed.Project.ReadMedia()!.Frames.Count(f => f.HasOriginal));
var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
Assert.Equal(Loc.L("Errors.Workspace.RenderNoOriginals", 2), (await fx.WaitForAsync(job.Id, JobState.Failed)).Error);
Assert.Empty(bed.Project.ReadRenders().Entries);
Assert.False(Directory.Exists(bed.Project.ExportsDirectory) && Directory.EnumerateFileSystemEntries(bed.Project.ExportsDirectory).Any());
}
[Test]
public async Task ProxiesAloneAreRefused()
{
await using var bed = await BedAsync(BundleMedia.Proxies);
var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: bed.Fx.Ct);
Assert.Equal(Loc.L("Errors.Workspace.OriginalsMissing"), (await bed.Fx.WaitForAsync(job.Id, JobState.Failed)).Error);
}
[Test]
public async Task ACancelledRenderLeavesNoPartialOutput()
{
await using var bed = await BedAsync();
var fx = bed.Fx;
fx.Decoder.HoldPurpose = DecodePurpose.Render;
fx.Decoder.Hold = Path.GetFileName(bed.Project.ReadMedia()!.Frames[12].Original);
var job = await bed.Engine.EnqueueAsync(RenderRequest(bed), cancellationToken: fx.Ct);
await fx.Decoder.Holding.Task.WaitAsync(TimeSpan.FromSeconds(60), fx.Ct);
await bed.Engine.CancelAsync(job.Id, fx.Ct);
await fx.WaitForAsync(job.Id, JobState.Cancelled);
var until = DateTime.UtcNow.AddSeconds(30);
while (bed.Engine.RunningJobIds.Contains(job.Id))
{
Assert.True(DateTime.UtcNow < until, "the render did not stop");
await Task.Delay(20, fx.Ct);
}
var left = Directory.Exists(bed.Project.ExportsDirectory) ? Directory.GetFileSystemEntries(bed.Project.ExportsDirectory) : [];
Assert.Empty(left);
Assert.Empty(bed.Project.ReadRenders().Entries);
Assert.False((await fx.Db.Jobs.ListAsync(null, 50, null, fx.Ct)).Items.Any(j => j.Kind == JobKind.WorkspaceSend), "nothing to send");
}
}
@@ -192,14 +192,17 @@ public abstract class WorkspaceTests(TestContext context) : DatabaseTest(context
}
[Test]
public async Task CopyingTheOriginalsIsRefusedForNowWithItsReason()
public async Task CopyingTheOriginalsCopiesTheProxiesToo()
{
var fx = await FixtureAsync(2);
var (store, sync) = fx.Workspace();
var main = await fx.Archive.Service.Projects.MainAsync(fx.Sequence.Id, fx.Ct);
await sync.CheckoutAsync(fx.Home, main.Id, BundleMedia.Originals, fx.Ct);
var job = await fx.CopyAsync(store, main.Id, JobState.Failed, media: BundleMedia.Originals);
Assert.Equal(Loc.L("Errors.Workspace.OriginalsLater"), job.Error);
var project = await sync.CheckoutAsync(fx.Home, main.Id, BundleMedia.Originals, fx.Ct);
await fx.CopyAsync(store, main.Id, media: BundleMedia.Originals);
var media = project.ReadMedia()!;
Assert.True(media.HoldsOriginals);
Assert.True(media.Frames.All(f => f.HasOriginal), "every frame has its original");
Assert.Equal(media.Frames.Count, (await sync.OpenAsync(main.Id, fx.Ct)).Media!.Frames.Count);
}
[Test]
@@ -341,6 +341,25 @@ public sealed class UploadTests(TestContext context)
Assert.Equal("cancelled", (await state.ReadAsync(ProtocolJson.Default.UploadState)).State);
}
[Test]
public void ARenderOfferOfAnEarlierClientReadsWithoutItsProjectAndAWorkspaceOneKeepsIt()
{
// As a client of phase 5b sends it: no project, no version.
var earlier = System.Text.Json.JsonSerializer.Deserialize("""
{ "renderId": "0192a4c1-7b3e-7cc0-8a51-2f9d0e6b1a01", "fileName": "Roof.mp4", "size": 10, "sha256": "ab", "presetName": "4K HEVC",
"codec": "hevc", "width": 3840, "height": 2160, "fps": 30, "durationSeconds": 10 }
""", ProtocolJson.Default.RenderUploadRequest);
Assert.NotNull(earlier);
Assert.Equal(("Roof.mp4", (Guid?)null, (Guid?)null), (earlier.FileName, earlier.ProjectId, earlier.ProjectVersionId));
var omitted = System.Text.Json.JsonSerializer.Serialize(earlier, ProtocolJson.Default.RenderUploadRequest);
Assert.False(omitted.Contains("projectId", StringComparison.Ordinal), "an offer without a project names none");
var workspace = earlier with { ProjectId = Guid.CreateVersion7(), ProjectVersionId = Guid.CreateVersion7() };
var json = System.Text.Json.JsonSerializer.Serialize(workspace, ProtocolJson.Default.RenderUploadRequest);
Assert.Contains("\"projectVersionId\"", json);
Assert.Equal(workspace, System.Text.Json.JsonSerializer.Deserialize(json, ProtocolJson.Default.RenderUploadRequest));
}
/// <summary>Reports synchronously (Progress&lt;T&gt; posts to the thread pool and may arrive late).</summary>
private sealed class SyncProgress<T>(Action<T> report) : IProgress<T>
{
@@ -197,14 +197,45 @@ public sealed class ServerWorkspaceTests(TestContext context)
// 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 TheOriginalsAreDownloadedCheckedAndKeptBesideTheProxies()
{
await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
var (_, _, token) = await server.UserAsync("alberto", "editor");
var sid = await SequenceAsync(server, token, 3);
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, BundleMedia.Originals, context.Cancellation);
var library = Listing(a.Archive.RootPath);
var job = await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, a.Server, a.Store.Root, main.Id, BundleMedia.Originals));
job = await a.WaitAsync(job.Id, JobState.Done);
Assert.Contains(Loc.L("Archive.Log.WorkspaceOriginalsDownloaded", Title, 3, 0, 0), job.LogTail!);
var media = Assert.NotNull(project.ReadMedia());
Assert.True(media.HoldsOriginals);
Assert.Equal(BundleMedia.Originals, project.ReadBundle().Workspace!.Media.Kind);
var manifest = await a.Client.GetManifestAsync(sid, context.Cancellation);
foreach (var (frame, entry) in manifest.Frames.OrderBy(f => f.Index).Zip(media.Frames))
{
Assert.Equal(frame.Sha256.ToLowerInvariant(), entry.OriginalSha256);
Assert.Equal(entry.OriginalSha256, Sha(project.MediaFile(Assert.NotNull(entry.Original))));
Assert.NotNull(entry.File);
}
Assert.False(Directory.Exists(Path.Combine(project.OriginalsDirectory, ".staging")));
Assert.SequenceEqual(library, Listing(a.Archive.RootPath), "this PC's library is as it was");
// Again: every original held is kept, hashed again.
job = await a.WaitAsync((await a.EnqueueAsync(WorkspaceJobs.CopyFromServer(sid, Title, a.Server, a.Store.Root, main.Id, BundleMedia.Originals))).Id, JobState.Done);
Assert.Contains(Loc.L("Archive.Log.WorkspaceOriginalsDownloaded", Title, 0, 3, 0), job.LogTail!);
}
[Test]
public async Task AProjectDeletedOnTheServerIsGoneAndItsCopyStays()
{