From ffbea7cb74e8a47e27e55d25c0b3504916d2d5e9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 2 Oct 2026 12:26:58 +0000 Subject: [PATCH] feat(app): library, jobs, settings, server, welcome and about screens Local-mode composition root (SQLite index, one JobEngine fed by a single handler registration list), keyset-paged library with thumbnail cache and hover scrub, live job list with throttled updates and the shell job bar, settings with live template validation and encoder self-test, server connection with trust-on-first-use and DPAPI token, first-run welcome, About with update check, and --capture screenshots with synthetic data. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/About.resx | 14 + i18n/en/Common.resx | 1 + i18n/en/Errors.resx | 16 + i18n/en/Jobs.resx | 58 ++ i18n/en/Library.resx | 59 ++ i18n/en/Server.resx | 44 + i18n/en/Settings.resx | 85 ++ i18n/en/Shell.resx | 15 + i18n/en/Tooltips.resx | 156 ++++ i18n/it/About.it.resx | 14 + i18n/it/Common.it.resx | 1 + i18n/it/Errors.it.resx | 16 + i18n/it/Jobs.it.resx | 58 ++ i18n/it/Library.it.resx | 59 ++ i18n/it/Server.it.resx | 43 + i18n/it/Settings.it.resx | 85 ++ i18n/it/Shell.it.resx | 15 + i18n/it/Tooltips.it.resx | 156 ++++ src/Titano.App/About/UpdateCheck.cs | 76 ++ src/Titano.App/App.xaml.cs | 67 +- src/Titano.App/DesignTime/SampleData.cs | 343 ++++++++ .../Infrastructure/AppEnvironment.cs | 33 +- src/Titano.App/Infrastructure/AppServices.cs | 136 +++ src/Titano.App/Infrastructure/AppSettings.cs | 118 ++- src/Titano.App/Infrastructure/ArchiveSetup.cs | 104 +++ .../Infrastructure/DiagnosticsBundle.cs | 147 ++++ src/Titano.App/Infrastructure/Formatting.cs | 25 + src/Titano.App/Infrastructure/IAppDialogs.cs | 39 + src/Titano.App/Infrastructure/ProductLinks.cs | 10 +- src/Titano.App/Infrastructure/ShellActions.cs | 25 +- src/Titano.App/Infrastructure/UiLanguage.cs | 33 + src/Titano.App/Interop/FileDialogs.cs | 192 +++++ src/Titano.App/Jobs/JobListModel.cs | 164 ++++ src/Titano.App/Jobs/JobQueue.cs | 106 +++ src/Titano.App/Jobs/JobRowViewModel.cs | 133 +++ src/Titano.App/Jobs/JobText.cs | 68 ++ src/Titano.App/Jobs/JobUpdateBuffer.cs | 143 ++++ src/Titano.App/Library/FilterOption.cs | 10 + src/Titano.App/Library/LibraryFilter.cs | 65 ++ src/Titano.App/Library/LibraryPager.cs | 102 +++ src/Titano.App/Library/SequenceItem.cs | 179 ++++ src/Titano.App/Library/ThumbnailCache.cs | 152 ++++ src/Titano.App/Library/ThumbnailLoading.cs | 52 ++ src/Titano.App/Library/ThumbnailService.cs | 192 +++++ src/Titano.App/Sections/AboutView.xaml | 61 +- src/Titano.App/Sections/AboutViewModel.cs | 149 ++++ src/Titano.App/Sections/ArchiveViewModel.cs | 9 + src/Titano.App/Sections/ImportViewModel.cs | 9 + src/Titano.App/Sections/JobsView.xaml | 164 +++- src/Titano.App/Sections/JobsView.xaml.cs | 7 + src/Titano.App/Sections/JobsViewModel.cs | 379 +++++++++ src/Titano.App/Sections/LibraryView.xaml | 248 +++++- src/Titano.App/Sections/LibraryView.xaml.cs | 7 + src/Titano.App/Sections/LibraryViewModel.cs | 630 ++++++++++++++ src/Titano.App/Sections/Sections.cs | 164 ---- src/Titano.App/Sections/SequenceViewModel.cs | 12 + src/Titano.App/Sections/ServerView.xaml | 117 ++- src/Titano.App/Sections/ServerView.xaml.cs | 12 + src/Titano.App/Sections/ServerViewModel.cs | 209 +++++ src/Titano.App/Sections/SettingsView.xaml | 386 +++++++-- src/Titano.App/Sections/SettingsView.xaml.cs | 14 - src/Titano.App/Sections/SettingsViewModel.cs | 803 ++++++++++++++++++ src/Titano.App/Sections/WelcomeView.xaml | 115 +++ src/Titano.App/Sections/WelcomeView.xaml.cs | 8 + src/Titano.App/Sections/WelcomeViewModel.cs | 231 +++++ src/Titano.App/Server/ConnectFlow.cs | 298 +++++++ src/Titano.App/Server/ServerApi.cs | 143 ++++ src/Titano.App/Server/ServerSession.cs | 238 ++++++ src/Titano.App/Settings/EditableField.cs | 116 +++ src/Titano.App/Settings/EncoderInventory.cs | 205 +++++ src/Titano.App/Settings/LanguageCatalog.cs | 62 ++ src/Titano.App/Settings/NamingPreview.cs | 82 ++ src/Titano.App/Settings/SettingsRows.cs | 120 +++ src/Titano.App/Shell/AppDialogs.cs | 27 + src/Titano.App/Shell/AppResources.cs | 19 + src/Titano.App/Shell/AppStyles.xaml | 233 +++++ src/Titano.App/Shell/ConfirmDialog.xaml | 22 + src/Titano.App/Shell/ConfirmDialog.xaml.cs | 29 + src/Titano.App/Shell/EditBehavior.cs | 65 ++ src/Titano.App/Shell/LoginDialog.xaml | 34 + src/Titano.App/Shell/LoginDialog.xaml.cs | 61 ++ src/Titano.App/Shell/MainWindow.xaml | 20 +- src/Titano.App/Shell/MainWindow.xaml.cs | 15 +- src/Titano.App/Shell/ScreenCapture.cs | 148 +++- src/Titano.App/Shell/ShellViewModel.cs | 109 ++- src/Titano.Ui/Controls/JobBar.cs | 6 +- src/Titano.Ui/Themes/Controls.xaml | 4 +- .../About/UpdateCheckTests.cs | 74 ++ .../Jobs/JobListModelTests.cs | 187 ++++ .../Jobs/JobUpdateBufferTests.cs | 106 +++ .../Library/LibraryPagerTests.cs | 180 ++++ .../Library/ThumbnailCacheTests.cs | 164 ++++ .../Server/ConnectFlowTests.cs | 238 ++++++ .../Settings/SettingsLogicTests.cs | 156 ++++ 94 files changed, 10130 insertions(+), 374 deletions(-) create mode 100644 src/Titano.App/About/UpdateCheck.cs create mode 100644 src/Titano.App/DesignTime/SampleData.cs create mode 100644 src/Titano.App/Infrastructure/AppServices.cs create mode 100644 src/Titano.App/Infrastructure/ArchiveSetup.cs create mode 100644 src/Titano.App/Infrastructure/DiagnosticsBundle.cs create mode 100644 src/Titano.App/Infrastructure/IAppDialogs.cs create mode 100644 src/Titano.App/Infrastructure/UiLanguage.cs create mode 100644 src/Titano.App/Interop/FileDialogs.cs create mode 100644 src/Titano.App/Jobs/JobListModel.cs create mode 100644 src/Titano.App/Jobs/JobQueue.cs create mode 100644 src/Titano.App/Jobs/JobRowViewModel.cs create mode 100644 src/Titano.App/Jobs/JobText.cs create mode 100644 src/Titano.App/Jobs/JobUpdateBuffer.cs create mode 100644 src/Titano.App/Library/FilterOption.cs create mode 100644 src/Titano.App/Library/LibraryFilter.cs create mode 100644 src/Titano.App/Library/LibraryPager.cs create mode 100644 src/Titano.App/Library/SequenceItem.cs create mode 100644 src/Titano.App/Library/ThumbnailCache.cs create mode 100644 src/Titano.App/Library/ThumbnailLoading.cs create mode 100644 src/Titano.App/Library/ThumbnailService.cs create mode 100644 src/Titano.App/Sections/AboutViewModel.cs create mode 100644 src/Titano.App/Sections/ArchiveViewModel.cs create mode 100644 src/Titano.App/Sections/ImportViewModel.cs create mode 100644 src/Titano.App/Sections/JobsViewModel.cs create mode 100644 src/Titano.App/Sections/LibraryViewModel.cs delete mode 100644 src/Titano.App/Sections/Sections.cs create mode 100644 src/Titano.App/Sections/SequenceViewModel.cs create mode 100644 src/Titano.App/Sections/ServerViewModel.cs create mode 100644 src/Titano.App/Sections/SettingsViewModel.cs create mode 100644 src/Titano.App/Sections/WelcomeView.xaml create mode 100644 src/Titano.App/Sections/WelcomeView.xaml.cs create mode 100644 src/Titano.App/Sections/WelcomeViewModel.cs create mode 100644 src/Titano.App/Server/ConnectFlow.cs create mode 100644 src/Titano.App/Server/ServerApi.cs create mode 100644 src/Titano.App/Server/ServerSession.cs create mode 100644 src/Titano.App/Settings/EditableField.cs create mode 100644 src/Titano.App/Settings/EncoderInventory.cs create mode 100644 src/Titano.App/Settings/LanguageCatalog.cs create mode 100644 src/Titano.App/Settings/NamingPreview.cs create mode 100644 src/Titano.App/Settings/SettingsRows.cs create mode 100644 src/Titano.App/Shell/AppDialogs.cs create mode 100644 src/Titano.App/Shell/AppResources.cs create mode 100644 src/Titano.App/Shell/AppStyles.xaml create mode 100644 src/Titano.App/Shell/ConfirmDialog.xaml create mode 100644 src/Titano.App/Shell/ConfirmDialog.xaml.cs create mode 100644 src/Titano.App/Shell/EditBehavior.cs create mode 100644 src/Titano.App/Shell/LoginDialog.xaml create mode 100644 src/Titano.App/Shell/LoginDialog.xaml.cs create mode 100644 tests/Titano.App.Tests/About/UpdateCheckTests.cs create mode 100644 tests/Titano.App.Tests/Jobs/JobListModelTests.cs create mode 100644 tests/Titano.App.Tests/Jobs/JobUpdateBufferTests.cs create mode 100644 tests/Titano.App.Tests/Library/LibraryPagerTests.cs create mode 100644 tests/Titano.App.Tests/Library/ThumbnailCacheTests.cs create mode 100644 tests/Titano.App.Tests/Server/ConnectFlowTests.cs create mode 100644 tests/Titano.App.Tests/Settings/SettingsLogicTests.cs diff --git a/i18n/en/About.resx b/i18n/en/About.resx index a9d2a50d..ce8aea99 100644 --- a/i18n/en/About.resx +++ b/i18n/en/About.resx @@ -4,11 +4,25 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Build Data + Diagnostics bundle + Licence + View licence + Machine translated Data folder Releases + Suggest a fix Runtime System Third-party code None + Translation + Titano {0} available + Check for updates + Checking… + Up to date + Download + Check failed + Updates diff --git a/i18n/en/Common.resx b/i18n/en/Common.resx index 5b7c5adf..bcf09a3a 100644 --- a/i18n/en/Common.resx +++ b/i18n/en/Common.resx @@ -12,4 +12,5 @@ n/a Open Open logs + {0} % diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx index 702ea76f..2c90ab45 100644 --- a/i18n/en/Errors.resx +++ b/i18n/en/Errors.resx @@ -4,5 +4,21 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Enter a whole number from {0} to {1}. + Enter a folder. + This is not a valid folder path. + This path is a file, not a folder. + The drive of this folder is not available. + Enter a full path that starts with a drive or a network share. + Enter a server address such as nas.local:8443 or https://titano.example.com. + This file does not contain Titano settings. + The template is empty. + Empty token at position {1}: write a name between the braces. + File names cannot contain a slash; put folders in the folder template. + The format after the colon does not suit its token. + Names would repeat: add the frame number, the time or the original name. + The brace opened at position {1} is never closed. + Unknown token “{0}” at position {1}. + The closing brace at position {1} has no opening one; double it for a literal brace. Something went wrong. diff --git a/i18n/en/Jobs.resx b/i18n/en/Jobs.resx index 9be7175a..a165f36d 100644 --- a/i18n/en/Jobs.resx +++ b/i18n/en/Jobs.resx @@ -4,5 +4,63 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Cancel + Folder + Move up + Open + Pause + Remove + Resume + Retry + Show + {0} left + Clear done + Kind + Left + Progress + Speed + State + Target + Where + {0} / {1} No jobs yet + All · {0} + Done · {0} + Failed · {0} + Queued · {0} + Running · {0} + History keeps {0} day + History keeps {0} days + Adopt folder + Deep analysis + Duplicates + Import + Light analysis + Maintenance + Move archive + Orphans + Proxies + Rebuild index + Render + Scan + Thumbnails + Upload + Verify + after {0} + next + No log lines yet + Pause all + Rendering settings + Search target or kind + {0} fps + {0}/s + cancelled + done + failed + paused + queued + running + {0} · {1} + this PC + Workers {0} / {1} diff --git a/i18n/en/Library.resx b/i18n/en/Library.resx index 7db63837..8d365087 100644 --- a/i18n/en/Library.resx +++ b/i18n/en/Library.resx @@ -4,8 +4,67 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Analyse + Clear selection + Export list + Folder + Open + Proxies + Verify + Adopt a folder + Clear filters + Camera + Date + Folder + Frames + Interval + Sequence + Size + Span + State + Tags No sequences yet + Adopt a folder Connect to a server Import a card Open an archive + List exported + Show + Export the list to + All cameras + Any status + All tags + All years + Camera + Status + Analysed + Without proxies + Not analysed + Not verified + With proxies + Verified + With warnings + Tags + Year + {0} s + No sequences match the filters + {0} queued · {1} + Rescan + Search title, camera, tag + {0:N0} selected + {0:N0} selected + Sort + Most frames + Newest first + Oldest first + Largest first + Title + Analysed + Analysing + Proxies + Remote + Synced + View + Grid + List diff --git a/i18n/en/Server.resx b/i18n/en/Server.resx index b9ba718d..24a55d5c 100644 --- a/i18n/en/Server.resx +++ b/i18n/en/Server.resx @@ -4,5 +4,49 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + nas.local:8443invariant + Certificate + Forget + Keep + Titano trusts this certificate for this server. Forgetting it disconnects, and the next connection asks again.long + Server certificate + TLS {0} trusted {1} + Connect + Disconnect Not connected to a server + Wrong user name or password.long + The server certificate changed; confirm it and sign in again.long + The connection failed; the log has the details.long + That is not a valid server address.long + That address is not a Titano Server.long + The session expired; sign in again.long + The server does not answer; check the address and the network.long + The certificate was not trusted, so nothing was sent.long + Servers found + Account + Server + Status + {0} ms + Cancel + Password + Sign in + Sign in + User + {0} of {1} + {0} used + Offer this PC as render node + Admin + Editor + Uploader + Viewer + Sign out + Connected + Connecting… + Disconnected + Not connected + Trust + Cancel + {0} uses a certificate Titano does not know yet. Compare the fingerprint with the one in the server's admin panel before you trust it.long + Trust this server? + v{0} diff --git a/i18n/en/Settings.resx b/i18n/en/Settings.resx index bd1f5673..1604e694 100644 --- a/i18n/en/Settings.resx +++ b/i18n/en/Settings.resx @@ -4,7 +4,31 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Database + Index backed up + Back up now Data folder + Diagnostics + Diagnostics bundle saved + Save the diagnostics bundle to + Export bundle + Logs + Portable mode + Off + On + File names + Folders + {0} free + Full size + Choose the archive folder + Preview + Proxy size + Archive folder + Back to Auto + Choose folder + Export… + Settings exported + Export the settings to Check on start Language Theme @@ -12,6 +36,12 @@ Light System Updates + Usage counts + Send anonymous counts + Import… + Settings imported + Titano settings + Import settings Advanced Analysis Archive @@ -21,5 +51,60 @@ Licence Rendering Server + Storage Updates + Auto · {0} + Low priority while editing + Codec + Encoder + Max + Self-test + 10-bit + of {0} logical cores + {0} (built in) + {0} (hardware) + {0} (software) + {0} encoder + {0} encoders + Encoders on this PC + failed + {0} GB + Hardware encoding + of {0} GB installed + Memory budget + no limit + Parallelism + {0} fps · ok + Prefer hardware + Hardware for previews only + Quality profile + Balanced + Best + Fast + Re-detect + Run self-test + Software only + 10-bit + testing… + Reset section + Search settings + Trusted certificates + Default server + None + Render node + Clear + Spilled frames and decoded thumbnails are deleted and rebuilt when needed. Originals, proxies and renders are not touched.long + Clear the cache? + {0} freed + Cache folder + Keep + Cache limit + GB + Titano did not create this folder, so nothing was deleted.long + Choose the cache folder + Thumbnails in memory + thumbnails + {0} used · {1} free + {0} used + Latest version diff --git a/i18n/en/Shell.resx b/i18n/en/Shell.resx index 80a2fb84..a2ff72aa 100644 --- a/i18n/en/Shell.resx +++ b/i18n/en/Shell.resx @@ -5,6 +5,7 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Titanoinvariant + Ready Ready · {0} jobs queued About Archive @@ -17,9 +18,23 @@ Connected to "{0}" {0:N0} job {0:N0} jobs + No archive Not connected {0:N0} photo {0:N0} photos {0:N0} sequence {0:N0} sequences + Adopt an existing folder + Change… + Choose… + Help improve Titano with anonymous usage countslong + Continue + Found + Create a local archive + {0} · {1} free + Choose where the archive lives + Where should your time-lapses live?long + Connect to a server + {0} on this network · {1} + Welcome to Titano diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index fcb3a77b..7ca6cbe4 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -4,14 +4,90 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Ask the public releases page for a newer version · a few seconds + Zip the logs and an environment report into a folder you choose; settings and passwords are not included + Open the release page in the browser + Open the licence in the browser Open the folder with database, settings and logs Open the public releases page in the browser + Every language but English is machine-translated; propose a better wording on the public issue tracker + Titano uses no third-party code: everything beyond .NET and Windows is written in-house Dismiss Open the folder with the log files Return to the advisor's value + Stop this job; Retry continues later from its last checkpoint + Hide finished jobs from the list; they stay in the history + Every job + Finished jobs + Stopped with an error or cancelled + Waiting for a worker + Working now or paused + Show the folder in Explorer + Hide the log + Finished jobs older than this are removed when Titano starts + Raise the priority: it runs before jobs of lower priority + Open what this job worked on + Pause at the next checkpoint; Resume continues from there + Pause every running job; the queue keeps its order + Hold this job in the queue until you resume it + Remove from the queue; the job is cancelled + Parallelism, hardware preference, memory budget + Put the job back in the queue; it continues from its checkpoint + Run again from the last checkpoint + Filter by target or kind as you type + Open what this job worked on to see the problem + Show the last lines of the log + Cancelled; Retry continues from the last checkpoint + Finished; the run time follows the dot + Stopped with an error; Retry continues from the last checkpoint + Paused; Resume continues from the checkpoint + Waiting for a worker on this PC + Working now + Jobs running on this PC out of the job engine's workers + Index photos you already have, in place; choose their top folder + Deep analysis of every frame · runs as a job in the background + Deep analysis of the selected sequences · runs as one job + Show only one camera + Click selects · Ctrl+click adds · double-click opens · move over the picture to scrub + Show every sequence again + Deselect every sequence Work with the archive of a Titano Server + Save the selected rows as CSV in a folder you choose + Show the sequence folder in Explorer + Cards with thumbnails Copy and verify photos from a memory card + Table with sortable columns + Open in the sequence editor · Enter Use an existing archive folder on this PC or the network + Build JPEG proxies for fast editing · runs as a job + Build proxies of the selected sequences · runs as one job + Rescan the archive for changes · runs as a job + Click selects · double-click opens + Search titles, camera makes and models, and tags as you type + Add to the selection or remove from it + Show the file in Explorer + Order of the sequences + Sort by first capture; click again to reverse + Sort by number of frames, most first + Sort by size on disk, largest first + Sort by title, A to Z + Filter by analysis, proxies, verification or warnings + Analysed: exposure, flicker and motion are measured + An analysis job is running on this sequence + Some frames are missing or unreadable; open the sequence for details + No proxies yet; editing reads the originals + Not analysed yet + JPEG proxies built for fast editing + Lives on the server; this PC has proxies at most + Rendered once + Rendered {0:N0} times + The same on this PC and on the server + {0:N0} warning; open the sequence for details + {0:N0} warnings; open the sequence for details + Show only one tag + Re-read every file and compare its hash with the index · runs as a job + Verify the hashes of the selected sequences · runs as one job + Show only one year of first capture Version, diagnostics and links Scan, verify and maintain the archive · Ctrl+4 Import photos from a card or folder · Ctrl+2 @@ -20,13 +96,84 @@ Edit and render the open sequence · Ctrl+3 Connection, sync and render node · Ctrl+6 Preferences of this PC · Ctrl+, + Address of the Titano Server; https is assumed · Enter connects + Show the full fingerprint, or forget the trust + Fingerprint trusted on first use; a change blocks the connection and asks you again + Identify the server, confirm a new certificate, then sign in · Enter + Close the session and work with the local archive only; you stay signed in + Do not connect; nothing is sent to this server + SHA-256 fingerprint of the server certificate + Forget this certificate; the next connection asks again + Servers found on this network and used before + Keep trusting this certificate + Close without signing in · Esc + Sent only to this server; Titano keeps a session token, never the password + Your user name on the server + Space you use on the server out of your quota + Let the server send render jobs to this PC when it is idle; uses your GPU encoders + Admins manage users, the archive and the server + Editors import, edit and render; only admins manage users + Uploaders send photos; editing needs an editor + Viewers browse and download + Sign in; the token is stored encrypted for this Windows user · Enter + Sign out; the token is removed from this PC + Connection to the server + Trust this certificate for this server and continue to sign in + Use this address + Graphics adapter and Media Foundation encoders found + Free space on the archive drive + Root of the local archive; files are not moved · Enter applies, Esc reverts + Lower the job priority while Titano is in front so the interface stays fluid + Copy the index to the backups folder; the newest three are kept · a few seconds + Choose the archive folder + Choose the cache folder; a fast SSD helps + Where frames spill and thumbnails are kept; a fast SSD helps · Enter applies, Esc reverts + Largest size of the disk cache in GB · Enter applies, Esc reverts + Space the cache uses and free space on its drive Look for a new release when Titano starts · no data is sent + Delete the cache contents now + Delete spilled frames and cached thumbnails; asks first Database, settings, logs and caches of this PC + Server Titano connects to at start; changing it signs out · Enter applies, Esc reverts + Zip the logs and an environment report into a folder you choose + Save every setting as JSON, without the session token + File name of each frame, for example {date}_{time}_{n:0000}; the extension is added · Enter applies, Esc reverts + Archive folders, for example {year}/{date} {camera}; a slash starts a subfolder · Enter applies, Esc reverts + Load settings from a JSON file; the session and the window layout stay as they are + Keep the cache as it is Language of the interface · applies immediately + Daily log files, kept for 14 days + Frames stay in memory up to this budget, then spill to the cache folder + Auto: a quarter of installed memory + Back to Auto: a quarter of installed memory Open the data folder in Explorer + Portable mode, logs, diagnostics, database backup + Archive folder, naming templates, proxy size + Language, theme, usage counts + Quality profile, memory budget, parallelism, encoders + Default server, render node, trusted certificates + Cache folder, thumbnails in memory, cache limit + Update check on start + Worker threads for decoding and processing · Enter applies, Esc reverts + Auto: cores minus four so the interface stays responsive + Back to Auto: cores minus four + On when portable.txt sits next to Titano.exe: all data stays in its data folder + Use a hardware encoder when one supports the preset; software otherwise + First three names of a sample import with these templates + Hardware for previews, software for archive presets + Long edge of the JPEG proxies built for new sequences + Balanced suits most work; Best doubles sampling and never spills; Fast is for previews + List the encoders again after a driver or codec install + Return every control of this section to its default + Find a setting by name + Encode a short synthetic clip with every encoder and report pass or fail and speed · about a minute + Speed on the synthetic 1280×720 test clip + Always the Microsoft software H.264 encoder; slower, identical everywhere Dark interface (default) Light interface Follow the Windows app mode + Decoded thumbnails kept in memory; more scrolls faster and uses more RAM · Enter applies + Send a daily anonymous count of versions and languages in use; nothing else, off by default Install in Program Files for every account · asks for administrator approval Return to the options without changing anything Choose the installation folder @@ -53,6 +200,7 @@ Replace the installed version in place · your data is kept Collapse navigation to icons Show navigation names + Pause the job shown; it continues from its checkpoint when resumed Stop the current job · it can be resumed later Add a folder to watch Pick files, a folder or a card @@ -91,6 +239,14 @@ The folder cannot be reached; it is checked again every {0} · click to change or remove Network share; polled every {0} because change notifications are unreliable on SMB · click to change or remove Check the folder at this interval + Index photos you already have, without moving them + Choose another folder for the archive + Choose the folder to adopt + Start with the highlighted choice · Enter + Announced on this network a moment ago + Interface language; you can change it later in Settings + Creates the folder layout and the index here; you can move it later + Sign in to a Titano Server on your network or on the internet Close Maximize Minimize diff --git a/i18n/it/About.it.resx b/i18n/it/About.it.resx index 3f3261ff..2370ca1e 100644 --- a/i18n/it/About.it.resx +++ b/i18n/it/About.it.resx @@ -4,11 +4,25 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Build Dati + Pacchetto diagnostico + Licenza + Leggi la licenza + Traduzione automatica Cartella dati Versioni + Suggerisci una correzione Runtime Sistema Codice di terzi Nessuno + Traduzione + Titano {0} disponibile + Cerca aggiornamenti + Verifica in corso… + Aggiornato + Scarica + Verifica non riuscita + Aggiornamenti diff --git a/i18n/it/Common.it.resx b/i18n/it/Common.it.resx index 24f3494c..8794e75b 100644 --- a/i18n/it/Common.it.resx +++ b/i18n/it/Common.it.resx @@ -12,4 +12,5 @@ n/d Apri Apri log + {0}% diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx index cc83b7f7..44442694 100644 --- a/i18n/it/Errors.it.resx +++ b/i18n/it/Errors.it.resx @@ -4,5 +4,21 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Inserisci un numero intero da {0} a {1}. + Inserisci una cartella. + Questo non è un percorso di cartella valido. + Questo percorso è un file, non una cartella. + L'unità di questa cartella non è disponibile. + Inserisci un percorso completo che inizi con un'unità o una condivisione di rete. + Inserisci l'indirizzo di un server, ad esempio nas.local:8443 o https://titano.example.com. + Questo file non contiene impostazioni di Titano. + Il modello è vuoto. + Segnaposto vuoto alla posizione {1}: scrivi un nome tra le parentesi graffe. + I nomi dei file non possono contenere la barra; metti le cartelle nel modello delle cartelle. + Il formato dopo i due punti non è adatto al suo segnaposto. + I nomi si ripeterebbero: aggiungi il numero del fotogramma, l'ora o il nome originale. + La parentesi graffa aperta alla posizione {1} non viene mai chiusa. + Segnaposto sconosciuto «{0}» alla posizione {1}. + La parentesi graffa chiusa alla posizione {1} non ha un'apertura; raddoppiala per una graffa letterale. Si è verificato un problema. diff --git a/i18n/it/Jobs.it.resx b/i18n/it/Jobs.it.resx index 2495adbd..29507c5b 100644 --- a/i18n/it/Jobs.it.resx +++ b/i18n/it/Jobs.it.resx @@ -4,5 +4,63 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Annulla + Cartella + Anticipa + Apri + Pausa + Rimuovi + Riprendi + Riprova + Mostra + {0} rimanenti + Rimuovi concluse + Tipo + Rimanente + Avanzamento + Velocità + Stato + Oggetto + Dove + {0} / {1} Nessuna attività + Tutte · {0} + Concluse · {0} + Non riuscite · {0} + In coda · {0} + In corso · {0} + Cronologia di {0} giorno + Cronologia di {0} giorni + Adozione cartella + Analisi approfondita + Duplicati + Importazione + Analisi rapida + Manutenzione + Spostamento archivio + File orfani + Proxy + Ricostruzione indice + Rendering + Scansione + Miniature + Caricamento + Verifica + dopo {0} + prossima + Ancora nessuna riga di log + Sospendi tutte + Impostazioni di rendering + Cerca oggetto o tipo + {0} fps + {0}/s + annullata + conclusa + non riuscita + in pausa + in coda + in corso + {0} · {1} + questo PC + Processi {0} / {1} diff --git a/i18n/it/Library.it.resx b/i18n/it/Library.it.resx index 11ad6451..cbf7ca1a 100644 --- a/i18n/it/Library.it.resx +++ b/i18n/it/Library.it.resx @@ -4,8 +4,67 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Analizza + Deseleziona tutto + Esporta elenco + Cartella + Apri + Proxy + Verifica + Adotta una cartella + Azzera i filtri + Fotocamera + Data + Cartella + Fotogrammi + Intervallo + Sequenza + Dimensione + Durata + Stato + Tag Nessuna sequenza + Adotta una cartella Connetti a un server Importa una scheda Apri un archivio + Elenco esportato + Mostra + Esporta l'elenco in + Tutte le fotocamere + Qualsiasi stato + Tutti i tag + Tutti gli anni + Fotocamera + Stato + Analizzate + Senza proxy + Non analizzate + Non verificate + Con proxy + Verificate + Con avvisi + Tag + Anno + {0} s + Nessuna sequenza corrisponde + {0} in coda · {1} + Ripeti scansione + Cerca titolo, fotocamera, tag + {0:N0} selezionata + {0:N0} selezionate + Ordina + Più fotogrammi + Più recenti + Meno recenti + Più grandi + Titolo + Analizzata + In analisi + Proxy + Remota + Sincronizzata + Vista + Griglia + Elenco diff --git a/i18n/it/Server.it.resx b/i18n/it/Server.it.resx index d80ac2f7..8fdb24f3 100644 --- a/i18n/it/Server.it.resx +++ b/i18n/it/Server.it.resx @@ -4,5 +4,48 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Certificato + Dimentica + Mantieni + Titano considera attendibile questo certificato per questo server. Se lo dimentichi la connessione si chiude e la prossima volta te lo chiederà di nuovo. + Certificato del server + TLS {0} attendibile dal {1} + Connetti + Disconnetti Non connesso a un server + Nome utente o password errati. + Il certificato del server è cambiato; confermalo e accedi di nuovo. + La connessione non è riuscita; i dettagli sono nel log. + Questo non è un indirizzo di server valido. + Questo indirizzo non è un Titano Server. + La sessione è scaduta; accedi di nuovo. + Il server non risponde; controlla l'indirizzo e la rete. + Il certificato non è stato accettato, quindi non è stato inviato nulla. + Server trovati + Account + Server + Stato + {0} ms + Annulla + Password + Accedi + Accedi + Utente + {0} di {1} + {0} usati + Offri questo PC per il rendering + Amministratore + Editor + Caricatore + Visualizzatore + Esci + Connesso + Connessione… + Disconnesso + Non connesso + Considera attendibile + Annulla + {0} usa un certificato che Titano non conosce ancora. Confronta l'impronta con quella del pannello di amministrazione del server prima di considerarlo attendibile. + Ti fidi di questo server? + v{0} diff --git a/i18n/it/Settings.it.resx b/i18n/it/Settings.it.resx index bcfe6714..198c180c 100644 --- a/i18n/it/Settings.it.resx +++ b/i18n/it/Settings.it.resx @@ -4,7 +4,31 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Database + Copia dell'indice salvata + Salva una copia Cartella dati + Diagnostica + Pacchetto diagnostico salvato + Salva il pacchetto in + Esporta pacchetto + Log + Modalità portatile + Disattivata + Attiva + Nomi dei file + Cartelle + {0} liberi + Dimensione piena + Scegli la cartella dell'archivio + Anteprima + Dimensione proxy + Cartella archivio + Torna ad Auto + Scegli cartella + Esporta… + Impostazioni esportate + Esporta le impostazioni in Controlla all'avvio Lingua Tema @@ -12,6 +36,12 @@ Chiaro Sistema Aggiornamenti + Statistiche d'uso + Invia conteggi anonimi + Importa… + Impostazioni importate + Impostazioni di Titano + Importa impostazioni Avanzate Analisi Archivio @@ -21,5 +51,60 @@ Licenza Rendering Server + Spazio su disco Aggiornamenti + Auto · {0} + Priorità bassa in modifica + Codec + Encoder + Massimo + Autotest + 10 bit + di {0} core logici + {0} (integrato) + {0} (hardware) + {0} (software) + {0} encoder + {0} encoder + Encoder su questo PC + non riuscito + {0} GB + Codifica hardware + di {0} GB installati + Memoria disponibile + nessun limite + Parallelismo + {0} fps · ok + Preferisci hardware + Hardware solo per anteprime + Profilo di qualità + Bilanciato + Massima qualità + Veloce + Rileva di nuovo + Esegui autotest + Solo software + 10 bit + in prova… + Ripristina sezione + Cerca impostazioni + Certificati attendibili + Server predefinito + Nessuno + Nodo di rendering + Svuota + I fotogrammi temporanei e le miniature vengono eliminati e ricreati quando servono. Originali, proxy ed esportazioni restano intatti. + Svuotare la cache? + {0} liberati + Cartella cache + Mantieni + Limite della cache + GB + Questa cartella non è stata creata da Titano, quindi non è stato eliminato nulla. + Scegli la cartella della cache + Miniature in memoria + miniature + {0} usati · {1} liberi + {0} usati + Ultima versione diff --git a/i18n/it/Shell.it.resx b/i18n/it/Shell.it.resx index 471272fb..6da87848 100644 --- a/i18n/it/Shell.it.resx +++ b/i18n/it/Shell.it.resx @@ -4,6 +4,7 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Pronto Pronto · {0} attività in coda Informazioni Archivio @@ -16,9 +17,23 @@ Connesso a «{0}» {0:N0} attività {0:N0} attività + Nessun archivio Non connesso {0:N0} foto {0:N0} foto {0:N0} sequenza {0:N0} sequenze + Adotta una cartella esistente + Cambia… + Scegli… + Aiuta a migliorare Titano con conteggi d'uso anonimi + Continua + Trovato + Crea un archivio locale + {0} · {1} liberi + Scegli dove tenere l'archivio + Dove vuoi conservare i tuoi time-lapse? + Connettiti a un server + {0} in questa rete · {1} + Benvenuto in Titano diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index 039162d1..c81ad08f 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -4,14 +4,90 @@ 2.0 System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + Chiede alla pagina pubblica delle versioni se ne esiste una più recente · pochi secondi + Comprime i log e un rapporto sull'ambiente in una cartella a tua scelta; impostazioni e password non sono incluse + Apre la pagina della versione nel browser + Apre la licenza nel browser Apri la cartella con database, impostazioni e log Apri la pagina pubblica delle versioni nel browser + Tutte le lingue tranne l'inglese sono tradotte automaticamente; proponi una formulazione migliore nel tracker pubblico + Titano non usa codice di terze parti: tutto ciò che va oltre .NET e Windows è scritto internamente Chiudi Apri la cartella dei file di log Torna al valore consigliato + Ferma questa attività; Riprova la continua più tardi dall'ultimo punto di ripresa + Nasconde le attività concluse dall'elenco; restano nella cronologia + Tutte le attività + Attività concluse + Fermate per un errore o annullate + In attesa di un processo libero + In esecuzione o in pausa + Mostra la cartella in Esplora file + Nasconde il log + Le attività concluse più vecchie vengono rimosse all'avvio di Titano + Alza la priorità: verrà eseguita prima delle attività a priorità più bassa + Apre l'oggetto di questa attività + Mette in pausa al prossimo punto di ripresa; Riprendi continua da lì + Mette in pausa tutte le attività in corso; la coda mantiene il suo ordine + Trattiene l'attività in coda finché non la riprendi + Rimuove dalla coda; l'attività viene annullata + Parallelismo, preferenza hardware, memoria disponibile + Rimette l'attività in coda; riparte dal suo punto di ripresa + Esegue di nuovo dall'ultimo punto di ripresa + Filtra per oggetto o tipo mentre scrivi + Apre l'oggetto dell'attività per vedere il problema + Mostra le ultime righe del log + Annullata; Riprova continua dall'ultimo punto di ripresa + Conclusa; dopo il punto c'è la durata + Fermata per un errore; Riprova continua dall'ultimo punto di ripresa + In pausa; Riprendi continua dal punto di ripresa + In attesa di un processo libero su questo PC + In esecuzione + Attività in esecuzione su questo PC rispetto ai processi disponibili + Indicizza le foto che hai già, dove si trovano; scegli la loro cartella principale + Analisi approfondita di ogni fotogramma · viene eseguita come attività in background + Analisi approfondita delle sequenze selezionate · un'unica attività + Mostra una sola fotocamera + Clic seleziona · Ctrl+clic aggiunge · doppio clic apre · scorri sull'immagine per sfogliare + Mostra di nuovo tutte le sequenze + Deseleziona tutte le sequenze Lavora con l'archivio di un Titano Server + Salva le righe selezionate come CSV in una cartella a tua scelta + Mostra la cartella della sequenza in Esplora file + Schede con miniature Copia e verifica le foto da una scheda di memoria + Tabella con colonne ordinabili + Apre nell'editor della sequenza · Invio Usa una cartella archivio esistente su questo PC o in rete + Crea proxy JPEG per una modifica veloce · viene eseguita come attività + Crea i proxy delle sequenze selezionate · un'unica attività + Ripete la scansione dell'archivio per trovare modifiche · viene eseguita come attività + Clic seleziona · doppio clic apre + Cerca titoli, marche e modelli di fotocamera e tag mentre scrivi + Aggiunge alla selezione o la toglie + Mostra il file in Esplora file + Ordine delle sequenze + Ordina per primo scatto; fai clic di nuovo per invertire + Ordina per numero di fotogrammi, dal più alto + Ordina per spazio su disco, dalla più grande + Ordina per titolo, dalla A alla Z + Filtra per analisi, proxy, verifica o avvisi + Analizzata: esposizione, flicker e movimento sono misurati + Un'attività di analisi è in corso su questa sequenza + Alcuni fotogrammi mancano o sono illeggibili; apri la sequenza per i dettagli + Ancora nessun proxy; la modifica legge gli originali + Non ancora analizzata + Proxy JPEG pronti per una modifica veloce + Si trova sul server; questo PC ne ha al massimo i proxy + Esportata una volta + Esportata {0:N0} volte + Uguale su questo PC e sul server + {0:N0} avviso; apri la sequenza per i dettagli + {0:N0} avvisi; apri la sequenza per i dettagli + Mostra un solo tag + Rilegge ogni file e ne confronta l'hash con l'indice · viene eseguita come attività + Verifica gli hash delle sequenze selezionate · un'unica attività + Mostra un solo anno del primo scatto Versione, diagnostica e collegamenti Scansiona, verifica e gestisci l'archivio · Ctrl+4 Importa foto da una scheda o una cartella · Ctrl+2 @@ -20,13 +96,84 @@ Modifica e renderizza la sequenza aperta · Ctrl+3 Connessione, sincronizzazione e nodo di rendering · Ctrl+6 Preferenze di questo PC · Ctrl+, + Indirizzo del Titano Server; si presume https · Invio per connettersi + Mostra l'impronta completa o revoca la fiducia + Impronta accettata al primo utilizzo; se cambia, la connessione si blocca e te lo chiede di nuovo + Identifica il server, conferma un certificato nuovo e poi accedi · Invio + Chiude la sessione e lavora solo con l'archivio locale; l'accesso resta salvato + Non connetterti; a questo server non viene inviato nulla + Impronta SHA-256 del certificato del server + Dimentica questo certificato; alla prossima connessione verrà chiesto di nuovo + Server trovati in questa rete e usati in precedenza + Continua a considerare attendibile questo certificato + Chiude senza accedere · Esc + Inviata solo a questo server; Titano conserva un token di sessione, mai la password + Il tuo nome utente sul server + Spazio che usi sul server rispetto alla tua quota + Permette al server di inviare rendering a questo PC quando è inattivo; usa gli encoder della tua GPU + Gli amministratori gestiscono utenti, archivio e server + Gli editor importano, modificano ed esportano; solo gli amministratori gestiscono gli utenti + I caricatori inviano foto; per modificare serve un editor + I visualizzatori sfogliano e scaricano + Accedi; il token viene salvato cifrato per questo utente di Windows · Invio + Esci; il token viene rimosso da questo PC + Connessione al server + Considera attendibile questo certificato per questo server e prosegui con l'accesso + Usa questo indirizzo + Scheda grafica ed encoder Media Foundation trovati + Spazio libero sull'unità dell'archivio + Radice dell'archivio locale; i file non vengono spostati · Invio applica, Esc annulla + Abbassa la priorità delle attività mentre Titano è in primo piano, così l'interfaccia resta fluida + Copia l'indice nella cartella dei backup; vengono conservate le tre copie più recenti · pochi secondi + Scegli la cartella dell'archivio + Scegli la cartella della cache; un SSD veloce aiuta + Dove vanno i fotogrammi temporanei e le miniature; un SSD veloce aiuta · Invio applica, Esc annulla + Dimensione massima della cache su disco in GB · Invio applica, Esc annulla + Spazio usato dalla cache e spazio libero sulla sua unità Cerca una nuova versione all'avvio di Titano · nessun dato viene inviato + Elimina adesso il contenuto della cache + Elimina fotogrammi temporanei e miniature in cache; prima chiede conferma Database, impostazioni, log e cache di questo PC + Server a cui Titano si connette all'avvio; cambiarlo chiude l'accesso · Invio applica, Esc annulla + Comprime i log e un rapporto sull'ambiente in una cartella a tua scelta + Salva tutte le impostazioni in JSON, senza il token di sessione + Nome del file di ogni fotogramma, ad esempio {date}_{time}_{n:0000}; l'estensione viene aggiunta · Invio applica, Esc annulla + Cartelle dell'archivio, ad esempio {year}/{date} {camera}; la barra crea una sottocartella · Invio applica, Esc annulla + Carica le impostazioni da un file JSON; la sessione e la disposizione della finestra restano invariate + Lascia la cache com'è Lingua dell'interfaccia · si applica subito + File di log giornalieri, conservati per 14 giorni + I fotogrammi restano in memoria fino a questo limite, poi passano nella cartella della cache + Auto: un quarto della memoria installata + Torna ad Auto: un quarto della memoria installata Apri la cartella dati in Esplora file + Modalità portatile, log, diagnostica, backup del database + Cartella dell'archivio, modelli dei nomi, dimensione dei proxy + Lingua, tema, statistiche d'uso + Profilo di qualità, memoria, parallelismo, encoder + Server predefinito, nodo di rendering, certificati attendibili + Cartella della cache, miniature in memoria, limite della cache + Controllo degli aggiornamenti all'avvio + Thread di lavoro per decodifica ed elaborazione · Invio applica, Esc annulla + Auto: core meno quattro, così l'interfaccia resta reattiva + Torna ad Auto: core meno quattro + Attiva quando portable.txt si trova accanto a Titano.exe: tutti i dati restano nella sua cartella data + Usa un encoder hardware quando supporta il preset; altrimenti il software + I primi tre nomi di un'importazione di esempio con questi modelli + Hardware per le anteprime, software per i preset d'archivio + Lato lungo dei proxy JPEG creati per le nuove sequenze + Bilanciato va bene quasi sempre; Massima qualità raddoppia il campionamento e non usa la cache su disco; Veloce è per le anteprime + Elenca di nuovo gli encoder dopo l'installazione di un driver o di un codec + Riporta ogni controllo di questa sezione al valore predefinito + Trova un'impostazione per nome + Codifica una breve clip sintetica con ogni encoder e ne riporta esito e velocità · circa un minuto + Velocità sulla clip di prova sintetica 1280×720 + Sempre l'encoder software H.264 di Microsoft; più lento, identico ovunque Interfaccia scura (predefinita) Interfaccia chiara Segui la modalità app di Windows + Miniature decodificate tenute in memoria; più sono, più lo scorrimento è veloce e più RAM serve · Invio applica + Invia ogni giorno un conteggio anonimo di versioni e lingue in uso; nient'altro, disattivato per impostazione predefinita Installa in Programmi per tutti gli account · chiede l'autorizzazione di amministratore Torna alle opzioni senza modificare nulla Scegli la cartella di installazione @@ -53,6 +200,7 @@ Sostituisci la versione installata · i tuoi dati restano Riduci la navigazione alle icone Mostra i nomi della navigazione + Mette in pausa l'attività mostrata; quando la riprendi continua dal punto di ripresa Ferma l'attività in corso · potrai riprenderla Aggiungi una cartella da controllare Scegli file, una cartella o una scheda @@ -91,6 +239,14 @@ La cartella non è raggiungibile; viene ricontrollata ogni {0} · fai clic per modificare o rimuovere Condivisione di rete; controllata ogni {0} perché le notifiche di modifica non sono affidabili su SMB · fai clic per modificare o rimuovere Controlla la cartella con questo intervallo + Indicizza le foto che hai già, senza spostarle + Scegli un'altra cartella per l'archivio + Scegli la cartella da adottare + Inizia con la scelta evidenziata · Invio + Annunciato in questa rete poco fa + Lingua dell'interfaccia; puoi cambiarla più tardi nelle Impostazioni + Crea qui la struttura delle cartelle e l'indice; puoi spostarlo in seguito + Accedi a un Titano Server nella tua rete o su internet Chiudi Ingrandisci Riduci a icona diff --git a/src/Titano.App/About/UpdateCheck.cs b/src/Titano.App/About/UpdateCheck.cs new file mode 100644 index 00000000..8434cb88 --- /dev/null +++ b/src/Titano.App/About/UpdateCheck.cs @@ -0,0 +1,76 @@ +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; + +namespace Titano.App.About; + +/// The newest public release (BRIEF §18). +public sealed record ReleaseInfo(Version Version, string Tag, string PageUrl); + +/// +/// Update check against the GitHub Releases API of the public releases repository (BRIEF §18, §19.4): reads the +/// latest release, ignores drafts and pre-releases, and compares its tag with the running version. +/// +public static class UpdateCheck +{ + /// "v1.2.3", "1.2.3", "v1.2.3-beta.1" → 1.2.3; null for anything else. + public static Version? ParseVersion(string? tag) + { + if (string.IsNullOrWhiteSpace(tag)) return null; + var text = tag.Trim(); + if (text.StartsWith('v') || text.StartsWith('V')) text = text[1..]; + var end = text.IndexOfAny(['-', '+', ' ']); + if (end >= 0) text = text[..end]; + if (!Version.TryParse(text, out var version)) return null; + // Normalise to three parts so 1.2 equals 1.2.0. + return new Version(version.Major, version.Minor, Math.Max(0, version.Build)); + } + + /// The release described by a releases/latest response; null for drafts, pre-releases or unparsable tags. + public static ReleaseInfo? Parse(string json) + { + using var document = JsonDocument.Parse(json); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object) return null; + if (Flag(root, "draft") || Flag(root, "prerelease")) return null; + var tag = root.TryGetProperty("tag_name", out var t) && t.ValueKind == JsonValueKind.String ? t.GetString() : null; + var url = root.TryGetProperty("html_url", out var u) && u.ValueKind == JsonValueKind.String ? u.GetString() : null; + var version = ParseVersion(tag); + if (version is null || tag is null || url is null || !url.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) return null; + return new ReleaseInfo(version, tag, url); + } + + /// True when is newer than (build/revision ignored). + public static bool IsNewer(ReleaseInfo release, Version running) => + release.Version > new Version(running.Major, running.Minor, Math.Max(0, running.Build)); + + /// The running version from an informational version such as "0.1.0" or "0.1.0+abc". + public static Version RunningVersion(string informationalVersion) => ParseVersion(informationalVersion) ?? new Version(0, 0, 0); + + /// Asks the releases API for the latest release; null when there is none (404) or it cannot be read. + /// The request failed. + public static async Task FetchAsync(HttpClient http, string apiUrl, string userAgentVersion, CancellationToken ct) + { + using var request = new HttpRequestMessage(HttpMethod.Get, apiUrl); + request.Headers.UserAgent.Add(new ProductInfoHeaderValue("Titano", userAgentVersion)); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json")); + using var response = await http.SendAsync(request, ct).ConfigureAwait(false); + if (response.StatusCode == System.Net.HttpStatusCode.NotFound) return null; + response.EnsureSuccessStatusCode(); + var json = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false); + try + { + return Parse(json); + } + catch (JsonException) + { + return null; + } + } + + private static bool Flag(JsonElement root, string name) => + root.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.True; + + /// "0.2.0" for display. + public static string Display(Version version) => version.ToString(Math.Clamp(version.Build < 0 ? 2 : 3, 2, 3)); +} diff --git a/src/Titano.App/App.xaml.cs b/src/Titano.App/App.xaml.cs index 90c39120..e9900ac1 100644 --- a/src/Titano.App/App.xaml.cs +++ b/src/Titano.App/App.xaml.cs @@ -1,37 +1,45 @@ -using System.Globalization; using System.Windows; using System.Windows.Threading; +using Titano.App.DesignTime; using Titano.App.Infrastructure; using Titano.App.Shell; using Titano.Core.Diagnostics; -using Titano.Core.Localization; using Titano.Ui.Mvvm; using Titano.Ui.Theming; namespace Titano.App; +/// +/// Titano desktop client. Local mode starts here: settings and language before the first window, then the window, +/// then the index and the job engine () off the UI thread. --capture <dir> +/// renders every screen with synthetic data in a throw-away data folder and exits. +/// public partial class App : Application { private FileLogSink? _log; public AppEnvironment Environment { get; private set; } = null!; public AppSettings Settings { get; private set; } = null!; + public AppServices Services { get; private set; } = null!; public static new App Current => (App)Application.Current; protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); - Environment = AppEnvironment.Detect(); + var captureIndex = Array.IndexOf(e.Args, "--capture"); + var capture = captureIndex >= 0; + // Capture never reads or writes the user's data folder. + Environment = capture ? AppEnvironment.ForCapture() : AppEnvironment.Detect(); _log = new FileLogSink(Environment.LogDirectory, "titano"); - var capture = Array.IndexOf(e.Args, "--capture") >= 0; // Capture runs in CI: mirror the log to stderr so failures are visible in the job output. Log.SetSink(capture ? new TeeLogSink(_log, new StderrLogSink()) : _log); - Log.Info("app", $"Titano {typeof(App).Assembly.GetName().Version} starting; data at {Environment.DataDirectory}"); + Log.Info("app", $"Titano {AppServices.VersionText} starting; data at {Environment.DataDirectory}"); - Settings = AppSettings.Load(Environment.SettingsPath); - ApplyLanguage(Settings.Language); - ThemeManager.Initialize(this, Settings.Theme); + Settings = capture ? new AppSettings { Language = "en" } : AppSettings.Load(Environment.SettingsPath); + UiLanguage.Apply(Settings.Language); + ThemeManager.Initialize(this, capture ? AppTheme.Dark : Settings.Theme); + AppResources.Merge(this); DispatcherUnhandledException += OnUnhandledException; AppDomain.CurrentDomain.UnhandledException += (_, args) => Log.Error("app", "Unhandled exception", args.ExceptionObject as Exception); @@ -41,30 +49,37 @@ public partial class App : Application args.SetObserved(); }; - var shell = new ShellViewModel(Settings); + var dialogs = new AppDialogs(); + Services = new AppServices(Environment, Settings, SaveSettings, dialogs); + SampleData? sample = capture ? SampleData.Configure(Services) : null; + var shell = new ShellViewModel(Services); AsyncRelayCommand.Failed += ex => shell.ReportError(ex); var window = new MainWindow(shell); + dialogs.Owner = window; MainWindow = window; - var captureIndex = Array.IndexOf(e.Args, "--capture"); if (capture) { var dir = captureIndex + 1 < e.Args.Length ? e.Args[captureIndex + 1] : "screenshots"; - ScreenCapture.Run(window, shell, dir); + _ = ScreenCapture.RunAsync(window, shell, sample!, dir); return; } window.Show(); + _ = StartAsync(shell); } - /// Switches the UI language at run time (BRIEF §16) and remembers the choice. - public void ApplyLanguage(string? code) + /// Opens the index and the job engine after the window is visible, then fills the screens. + private async Task StartAsync(ShellViewModel shell) { - var culture = Languages.BestMatch(code is null ? CultureInfo.CurrentUICulture : CultureInfo.GetCultureInfo(code)); - CultureInfo.DefaultThreadCurrentUICulture = culture; - CultureInfo.CurrentUICulture = culture; - Loc.SetCulture(culture); - foreach (Window w in Windows) - w.FlowDirection = Loc.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; + try + { + await Services.OpenAsync(Environment.DatabasePath); + await shell.StartAsync(); + } + catch (Exception ex) + { + shell.ReportError(ex); + } } public void SaveSettings() @@ -73,7 +88,7 @@ public partial class App : Application { Settings.Save(Environment.SettingsPath); } - catch (System.IO.IOException ex) + catch (Exception ex) when (ex is System.IO.IOException or UnauthorizedAccessException) { Log.Warning("app", "Settings not saved", ex); } @@ -82,8 +97,20 @@ public partial class App : Application protected override void OnExit(ExitEventArgs e) { SaveSettings(); + if (MainWindow?.DataContext is ShellViewModel shell) shell.Dispose(); + try + { + // Data and engine code continue on the thread pool, so waiting here cannot deadlock the dispatcher. + if (Services is not null && !Services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10))) + Log.Warning("app", "Services did not stop within 10 s"); + } + catch (AggregateException ex) + { + Log.Warning("app", "Services stopped with an error", ex); + } Log.Info("app", "Titano exiting"); _log?.Dispose(); + if (Environment.IsCapture) Environment.DeleteCaptureData(); base.OnExit(e); } diff --git a/src/Titano.App/DesignTime/SampleData.cs b/src/Titano.App/DesignTime/SampleData.cs new file mode 100644 index 00000000..105b4f1a --- /dev/null +++ b/src/Titano.App/DesignTime/SampleData.cs @@ -0,0 +1,343 @@ +using System.IO; +using System.Net; +using Titano.App.About; +using Titano.App.Infrastructure; +using Titano.App.Server; +using Titano.App.Settings; +using Titano.Core.Codecs.Jpeg; +using Titano.Core.Imaging; +using Titano.Core.Model; +using Titano.Core.Video; +using Titano.Data; +using Titano.Protocol; +using Titano.Protocol.Client; + +namespace Titano.App.DesignTime; + +/// +/// Synthetic content for --capture screenshots and the screen smoke tests ONLY: a temporary SQLite index +/// with an archive of generated JPEGs (one sequence stores its thumbnail as an embedded preview inside a fake RAW +/// file), jobs in every state, a fake signed-in server and a fake encoder inventory. Everything lives in the +/// capture environment's temporary folder; nothing touches the network or the user's data. +/// +public sealed class SampleData +{ + public const string ServerFingerprint = "9A:3C:71:E0:5B:12:C4:88:0F:6D:2A:91:E7:44:B3:5C:19:D2:6F:80:A1:3E:57:C9:0B:64:F8:2D:93:A6:71:CE"; + + private readonly AppServices _services; + private TitanoDatabase? _db; + + private SampleData(AppServices services) => _services = services; + + /// Points the services at fakes (server, encoders, update check) for an empty first-run state. + public static SampleData Configure(AppServices services) + { + if (!services.Environment.IsCapture) throw new InvalidOperationException("Sample data only runs in a capture environment."); + var settings = services.Settings; + services.Server.Dispose(); + services.Server = new ServerSession(settings, services.SaveSettings, new SampleServerApiFactory(), new PlainTokenProtector()); + services.Encoders = new SampleEncoders(); + services.CheckForUpdateAsync = _ => Task.FromResult(null); + return new SampleData(services); + } + + /// Opens the empty temporary index (first run: no archive, nothing indexed). + public async Task OpenEmptyAsync() + { + _db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(_services.Environment.DatabasePath)); + await _services.AttachAsync(_db, startEngine: false); + } + + /// Fills the index with sample sequences, frames and jobs, and saves a signed-in server session. + public async Task FillAsync() + { + var db = _db ?? throw new InvalidOperationException("OpenEmptyAsync first."); + var settings = _services.Settings; + var root = Path.Combine(_services.Environment.DataDirectory, "archive"); + Directory.CreateDirectory(root); + var archive = new Archive { Id = Guid.CreateVersion7(), Name = "TitanoArchive", RootPath = root, Created = DateTimeOffset.UtcNow.AddYears(-2) }; + await db.Archives.UpsertAsync(archive); + + var sequences = Sequences(archive.Id).ToList(); + foreach (var (sequence, colours, raw) in sequences) + { + await db.Sequences.UpsertAsync(sequence); + await db.Frames.BulkInsertAsync(WriteFrames(root, sequence, colours, raw)); + } + await db.Sequences.SetTagsAsync(sequences[0].Sequence.Id, ["sunset", "harbour"]); + await db.Sequences.SetTagsAsync(sequences[9].Sequence.Id, ["holy grail"]); + + foreach (var job in Jobs(sequences.Select(s => s.Sequence).ToList(), archive.Id)) await db.Jobs.EnqueueAsync(job); + + settings.LastArchivePath = @"D:\TitanoArchive"; + settings.ServerUrl = "https://nas.local:8443"; + settings.ServerUsername = "alberto"; + settings.ProtectedToken = "sample-token"; + settings.TrustedCertificates = [new TrustedCertificate { Fingerprint = ServerFingerprint, Server = "https://nas.local:8443", TrustedAt = new DateTimeOffset(2026, 9, 1, 9, 30, 0, TimeSpan.Zero) }]; + settings.RecentServers = ["https://nas.local:8443"]; + settings.RenderNodeOptIn = true; + settings.FirstRunCompleted = true; + } + + private IEnumerable<(Sequence Sequence, string[] Colours, bool Raw)> Sequences(Guid archiveId) + { + var now = new DateTime(2026, 9, 28, 18, 2, 11); + (Sequence, string[], bool) Make(string? title, string folder, string make, string model, int frames, TimeSpan span, double interval, int daysAgo, + SequenceStatus status, string[] colours, int renders = 0, int warnings = 0, SequenceOrigin origin = SequenceOrigin.Local, + SyncState sync = SyncState.LocalOnly, bool raw = false) + { + var start = now.AddDays(-daysAgo); + return (new Sequence + { + Id = Guid.CreateVersion7(), + ArchiveId = archiveId, + Title = title, + Folder = folder, + CameraMake = make, + CameraModel = model, + FirstCapture = start, + LastCapture = start + span, + FrameCount = frames, + MedianInterval = interval, + TotalBytes = frames * 24_000_000L, + Status = status, + RenderedCount = renders, + WarningCount = warnings, + Origin = origin, + SyncState = sync, + UpdatedAt = DateTimeOffset.UtcNow, + }, colours, raw); + } + + const SequenceStatus Analysed = SequenceStatus.AnalyzedLight | SequenceStatus.AnalyzedDeep; + const SequenceStatus Full = Analysed | SequenceStatus.ProxiesBuilt | SequenceStatus.ThumbsBuilt | SequenceStatus.Verified; + yield return Make("Harbour sunset", "2026/2026-09-28 Canon EOS R5", "Canon", "Canon EOS R5", 3_600, TimeSpan.FromHours(2), 2, 0, Full, + ["#2A2F6B", "#B8452F", "#F0A04B", "#2B2B33"], renders: 2, sync: SyncState.InSync, raw: true); + yield return Make("Comet over the ridge", "2026/2026-08-13 GoPro HERO8 Black", "GoPro", "HERO8 Black", 1_005, new TimeSpan(5, 34, 0), 20, 46, Full, + ["#050914", "#0F1D3A", "#1E3A2F"], warnings: 1); + yield return Make(null, "2026/2026-09-27 Sony ILCE-7M4", "SONY", "ILCE-7M4", 2_140, new TimeSpan(1, 11, 0), 2, 1, Analysed, + ["#4A7FB5", "#A9C9E6", "#6F7D6A"]); + yield return Make("Aurora, Tromsø", "2026/2026-02-20 Nikon Z 8", "NIKON CORPORATION", "NIKON Z 8", 1_860, new TimeSpan(4, 8, 0), 8, 220, Full, + ["#0C2A3A", "#1AA08C", "#0B1A26"], sync: SyncState.InSync); + yield return Make("Construction cam · week 38", "2026/2026-09-14 Brinno TLC2020", "Brinno", "TLC2020", 8_920, TimeSpan.FromDays(7), 60, 14, + SequenceStatus.None, ["#7C8AA0", "#C9CFD6", "#4C5058"], origin: SequenceOrigin.Server, sync: SyncState.RemoteOnly); + yield return Make("Milan skyline dusk", "2026/2026-06-03 Apple iPhone 16 Pro", "Apple", "iPhone 16 Pro", 2_400, new TimeSpan(1, 20, 0), 2, 117, Full, + ["#1B2B4A", "#D67A4E", "#3A2A2A"], renders: 1); + yield return Make("Clouds over the Langhe", "2026/2026-05-11 Canon EOS R5", "Canon", "Canon EOS R5", 1_320, TimeSpan.FromMinutes(44), 2, 140, + SequenceStatus.None, ["#3B6FA6", "#E6EEF5", "#5C7A52"]); + yield return Make("Star trails, Colle del Nivolet", "2025/2025-08-02 Sony ILCE-7M4", "SONY", "ILCE-7M4", 640, new TimeSpan(5, 20, 0), 30, 422, Full, + ["#08101C", "#142A4A", "#0D0F14"], renders: 3); + yield return Make("Fog lifting, Asti", "2025/2025-11-21 DJI Osmo Action 5 Pro", "DJI", "Osmo Action 5 Pro", 980, new TimeSpan(1, 38, 0), 6, 311, + Analysed, ["#6A8FB0", "#F2E6D0", "#7A6A55"]); + yield return Make("Holy grail · Monviso", "2025/2025-07-14 Nikon Z 8", "NIKON CORPORATION", "NIKON Z 8", 1_720, new TimeSpan(3, 2, 0), 6, 441, Full, + ["#2C1F4D", "#C2455A", "#F5A524", "#26262C"], renders: 1, sync: SyncState.InSync); + for (var i = 0; i < 26; i++) + { + var shade = 40 + i * 6; + yield return Make($"Rooftop · day {i + 1}", $"2025/2025-03-{i + 1:00} Canon EOS R6", "Canon", "Canon EOS R6", 1_200 + i * 37, TimeSpan.FromHours(9), 30, + 480 + i, i % 3 == 0 ? Analysed : Full, [$"#{shade:X2}5A8C", "#C9D6E2", "#3D4A3A"]); + } + } + + /// Three small JPEG frames per sequence; a "raw" sequence wraps its JPEGs in a fake CR2 with an embedded preview. + private static IEnumerable WriteFrames(string root, Sequence sequence, string[] colours, bool raw) + { + var folder = Path.Combine(root, sequence.Folder.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(folder); + var count = sequence.Title?.StartsWith("Rooftop", StringComparison.Ordinal) == true ? 1 : 3; + var frames = new List(count); + for (var i = 0; i < count; i++) + { + var jpeg = Gradient(colours, 320, 180, i / 3.0); + var name = $"{sequence.FirstCapture:yyyy-MM-dd}_{i + 1:0000}.{(raw ? "CR2" : "JPG")}"; + long? previewOffset = null; + long? previewLength = null; + var bytes = jpeg; + if (raw) + { + // A fake RAW: a header the decoders cannot read, the JPEG preview, then trailing data. + var header = new byte[4096]; + "II*\0"u8.CopyTo(header); + bytes = [.. header, .. jpeg, .. new byte[2048]]; + previewOffset = header.Length; + previewLength = jpeg.Length; + } + File.WriteAllBytes(Path.Combine(folder, name), bytes); + frames.Add(new Frame + { + Id = Guid.CreateVersion7(), + SequenceId = sequence.Id, + Index = i, + RelativePath = sequence.Folder + "/" + name, + FileName = name, + Size = bytes.Length, + CapturedAt = sequence.FirstCapture!.Value.AddSeconds(i * (sequence.MedianInterval ?? 2)), + TimestampSource = TimestampSource.ExifOriginal, + Width = 320, + Height = 180, + Format = raw ? ImageFileFormat.Cr2 : ImageFileFormat.Jpeg, + PreviewOffset = previewOffset, + PreviewLength = previewLength, + ExposureTime = 1.0 / 250, + FNumber = 8, + Iso = 100, + }); + } + return frames; + } + + /// A vertical gradient through the given sRGB colours with a sun disc that moves with . + private static byte[] Gradient(string[] colours, int width, int height, double phase) + { + using var image = new ImageBuffer(width, height, 3, clear: false); + var stops = colours.Select(Parse).ToArray(); + var sunX = width * (0.3 + 0.4 * phase); + var sunY = height * (0.55 - 0.1 * phase); + for (var y = 0; y < height; y++) + { + var t = y / (double)(height - 1) * (stops.Length - 1); + var k = Math.Min((int)t, stops.Length - 2); + var f = t - k; + for (var x = 0; x < width; x++) + { + var d = Math.Sqrt((x - sunX) * (x - sunX) + (y - sunY) * (y - sunY)); + var sun = Math.Clamp(1 - d / 14, 0, 1); + for (var c = 0; c < 3; c++) + { + var value = stops[k][c] * (1 - f) + stops[k + 1][c] * f; + image.Plane(c)[y * width + x] = (float)(value + sun * (1.0 - value) * 0.9); + } + } + } + return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85 }); + + static double[] Parse(string hex) + { + var rgb = Convert.FromHexString(hex.TrimStart('#')); + return [Linear(rgb[0]), Linear(rgb[1]), Linear(rgb[2])]; + } + + static double Linear(byte v) + { + var s = v / 255.0; + return s <= 0.04045 ? s / 12.92 : Math.Pow((s + 0.055) / 1.055, 2.4); + } + } + + private IEnumerable Jobs(IReadOnlyList s, Guid archiveId) + { + var now = DateTimeOffset.UtcNow; + var here = _services.WorkerId; + Job Make(JobKind kind, Sequence? target, string label, JobState state, long done, long total, double? rate = null, TimeSpan? eta = null, + TimeSpan? startedAgo = null, TimeSpan? runFor = null, string? node = null, string? error = null, string? log = null, + JobPriority priority = JobPriority.Normal, TimeSpan? createdAgo = null) => new() + { + Id = Guid.CreateVersion7(), + Kind = kind, + TargetIds = target is null ? [archiveId] : [target.Id], + TargetLabel = label, + State = state, + Priority = priority, + ProgressDone = done, + ProgressTotal = total, + ItemsPerSecond = rate, + Eta = eta, + NodeId = state == JobState.Queued ? null : node ?? here, + Error = error, + LogTail = log, + Attempts = state == JobState.Queued ? 0 : 1, + Created = now - (createdAgo ?? startedAgo ?? TimeSpan.FromMinutes(1)), + Started = startedAgo is { } ago ? now - ago : null, + Finished = state is JobState.Done or JobState.Failed && startedAgo is { } a2 ? now - a2 + (runFor ?? TimeSpan.FromMinutes(1)) : null, + }; + + yield return Make(JobKind.Render, s[0], "Harbour sunset → 4K 10-bit HEVC · 24 fps", JobState.Running, 2_232, 3_600, 11.3, TimeSpan.FromMinutes(2), + startedAgo: TimeSpan.FromMinutes(3.4), log: + "10:14:02 window 41 · deflicker −67 % · 3 exposure steps redistributed over 18 frames\n" + + "10:14:03 stabilisation on · mean shake 0.42 px · crop 1.8 %\n" + + "10:14:03 encoder NVENC HEVC Main10 · 3840×2160 · 120 Mb/s · 24 fps · GOP 48\n" + + "10:15:41 frame 2232 / 3600 · 11.3 fps · spill 0 · memory 6.1 GB of 8 GB budget"); + yield return Make(JobKind.DeepAnalyse, s[4], s[4].DisplayTitle, JobState.Running, 2_498, 8_920, 41, TimeSpan.FromMinutes(6), startedAgo: TimeSpan.FromMinutes(1.1)); + yield return Make(JobKind.Proxies, s[1], s[1].DisplayTitle, JobState.Running, 915, 1_005, 118, TimeSpan.FromSeconds(8), startedAgo: TimeSpan.FromSeconds(8)); + yield return Make(JobKind.Render, s[3], "Aurora, Tromsø → 1080p share H.264", JobState.Queued, 0, 0, createdAgo: TimeSpan.FromMinutes(12)); + yield return Make(JobKind.Verify, null, "Archive · 2024", JobState.Queued, 0, 0, priority: JobPriority.Background, createdAgo: TimeSpan.FromMinutes(30)); + yield return Make(JobKind.Verify, s[7], s[7].DisplayTitle, JobState.Failed, 640, 640, 900, startedAgo: TimeSpan.FromMinutes(25), runFor: TimeSpan.FromSeconds(43), + error: "2 files whose hash no longer matches the sidecar", log: "09:58:01 verify 640 files\n09:58:43 2 hash mismatches: 2025-08-02_0213.ARW, 2025-08-02_0214.ARW"); + yield return Make(JobKind.Render, s[5], "Milan skyline dusk → 4K HEVC", JobState.Done, 2_400, 2_400, 14.8, startedAgo: TimeSpan.FromMinutes(70), + runFor: new TimeSpan(0, 2, 41), node: "studio-pc"); + yield return Make(JobKind.Import, s[0], "EOS R5 · card A → Archive · 4,812 photos", JobState.Done, 4_812, 4_812, 7.1, startedAgo: TimeSpan.FromMinutes(110), + runFor: new TimeSpan(0, 11, 52)); + yield return Make(JobKind.Thumbs, s[2], s[2].DisplayTitle, JobState.Done, 2_140, 2_140, 2_300, startedAgo: TimeSpan.FromMinutes(108), runFor: TimeSpan.FromSeconds(1)); + } + + /// A server that always answers as "Studio NAS" with a self-signed certificate the sample trusts. + private sealed class SampleServerApiFactory : IServerApiFactory + { + public IServerApi Create(Uri baseAddress, IReadOnlyCollection trustedFingerprints) => new SampleServerApi(baseAddress, trustedFingerprints); + } + + private sealed class SampleServerApi(Uri baseAddress, IReadOnlyCollection trusted) : IServerApi + { + private static readonly UserDto User = new(Guid.Empty, "alberto", "Alberto", "editor", 0, 5_000_000_000_000, 2_100_000_000_000, false, false, + new DateTimeOffset(2025, 1, 1, 0, 0, 0, TimeSpan.Zero), DateTimeOffset.UtcNow); + + public Uri BaseAddress { get; } = baseAddress; + + public string? Token { get; set; } + + public async Task GetInfoAsync(CancellationToken ct) + { + await Task.Delay(14, ct); + if (!trusted.Contains(ServerFingerprint, StringComparer.OrdinalIgnoreCase)) throw new UntrustedCertificateException(ServerFingerprint); + return new ServerInfo("Studio NAS", "1.3.0", 1, [], ServerFingerprint, [], new ServerLimits(0, 0)); + } + + public Task LoginAsync(string username, string password, CancellationToken ct) + { + Token = "sample-token"; + return Task.FromResult(new LoginResponse(Token, User, false, DateTimeOffset.UtcNow.AddDays(30))); + } + + public Task MeAsync(CancellationToken ct) => + Token == "sample-token" ? Task.FromResult(User) : throw new TitanoApiException(HttpStatusCode.Unauthorized, new ApiError("unauthorized", "Sign in")); + + public Task LogoutAsync(CancellationToken ct) => Task.CompletedTask; + + public void Dispose() + { + } + } + + /// No encryption: the capture environment is thrown away. + private sealed class PlainTokenProtector : ITokenProtector + { + public string Protect(string token) => token; + + public string? Unprotect(string protectedToken) => protectedToken; + } + + /// The encoders of the mockup's PC (NVIDIA RTX with NVENC) and canned self-test speeds. + private sealed class SampleEncoders : IEncoderInventory + { + public string? Adapter() => "NVIDIA GeForce RTX 4070"; + + public IReadOnlyList Detect() => + [ + new("HEVC", "NVIDIA HEVC Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, true, 8192, 8192, VideoCodec.Hevc), + new("H.264", "NVIDIA H.264 Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, false, 4096, 4096, VideoCodec.H264), + new("AV1", "NVIDIA AV1 Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, true, 8192, 8192, VideoCodec.Av1), + new("H.264", "H264 Encoder MFT", "Microsoft", EncoderSource.MediaFoundation, false, false, 4096, 2304, VideoCodec.H264), + new("MJPEG · AVI", "Titano", null, EncoderSource.BuiltInMjpeg, false, false, 0, 0, VideoCodec.Mjpeg), + new("GIF · APNG", "Titano", null, EncoderSource.BuiltInAnimation, false, false, 0, 0, null), + ]; + + public Task SelfTestAsync(EncoderRow row, CancellationToken ct) => Task.FromResult(row.Codec switch + { + "HEVC" => new SelfTestResult(true, 142, null), + "AV1" => new SelfTestResult(true, 96, null), + "H.264" when row.Hardware => new SelfTestResult(true, 188, null), + "H.264" => new SelfTestResult(true, 21, null), + _ => new SelfTestResult(true, 64, null), + }); + } +} diff --git a/src/Titano.App/Infrastructure/AppEnvironment.cs b/src/Titano.App/Infrastructure/AppEnvironment.cs index 5b0d9db2..349f91bd 100644 --- a/src/Titano.App/Infrastructure/AppEnvironment.cs +++ b/src/Titano.App/Infrastructure/AppEnvironment.cs @@ -8,10 +8,11 @@ namespace Titano.App.Infrastructure; /// public sealed class AppEnvironment { - private AppEnvironment(string dataDirectory, bool portable) + private AppEnvironment(string dataDirectory, bool portable, bool isCapture) { DataDirectory = dataDirectory; IsPortable = portable; + IsCapture = isCapture; Directory.CreateDirectory(DataDirectory); Directory.CreateDirectory(LogDirectory); Directory.CreateDirectory(CacheDirectory); @@ -19,8 +20,13 @@ public sealed class AppEnvironment public string DataDirectory { get; } public bool IsPortable { get; } + + /// A throw-away environment for --capture: nothing of the user's data is read or written. + public bool IsCapture { get; } + public string LogDirectory => Path.Combine(DataDirectory, "logs"); public string CacheDirectory => Path.Combine(DataDirectory, "cache"); + public string BackupDirectory => Path.Combine(DataDirectory, "backups"); public string DatabasePath => Path.Combine(DataDirectory, "titano.db"); public string SettingsPath => Path.Combine(DataDirectory, "settings.json"); @@ -28,8 +34,29 @@ public sealed class AppEnvironment { var exeDir = AppContext.BaseDirectory; if (File.Exists(Path.Combine(exeDir, "portable.txt"))) - return new AppEnvironment(Path.Combine(exeDir, "data"), portable: true); + return new AppEnvironment(Path.Combine(exeDir, "data"), portable: true, isCapture: false); var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - return new AppEnvironment(Path.Combine(local, "Titano"), portable: false); + return new AppEnvironment(Path.Combine(local, "Titano"), portable: false, isCapture: false); + } + + /// A fresh temporary data folder for screenshots and smoke tests; delete it with . + public static AppEnvironment ForCapture() => + new(Path.Combine(Path.GetTempPath(), "titano-capture-" + Guid.CreateVersion7().ToString("N")), portable: false, isCapture: true); + + /// Removes the temporary data folder of a capture environment (never a real one). + public void DeleteCaptureData() + { + if (!IsCapture) return; + try + { + Directory.Delete(DataDirectory, recursive: true); + } + catch (IOException) + { + // Files still open (log, database) are left to the OS temp cleanup. + } + catch (UnauthorizedAccessException) + { + } } } diff --git a/src/Titano.App/Infrastructure/AppServices.cs b/src/Titano.App/Infrastructure/AppServices.cs new file mode 100644 index 00000000..7e000a70 --- /dev/null +++ b/src/Titano.App/Infrastructure/AppServices.cs @@ -0,0 +1,136 @@ +using System.Net.Http; +using System.Reflection; +using Titano.App.About; +using Titano.App.Jobs; +using Titano.App.Library; +using Titano.App.Server; +using Titano.App.Settings; +using Titano.Core.Diagnostics; +using Titano.Data; +using Titano.Data.Jobs; + +namespace Titano.App.Infrastructure; + +/// +/// Composition root of local mode (BRIEF §4.4): the SQLite index under the data folder (migrated on open), the one +/// of this PC with the handlers of , thumbnails, the server +/// session, the encoder inventory, the update check and the archive setup. Started after the window shows, stopped +/// when the app exits. +/// +/// +/// Integration points (one place each): +/// +/// — register the archive handlers (scan, rebuild, verify, adopt, …) and the +/// render handler here. +/// — replace with the archive engine's +/// implementation (it receives the first-run choices: create a local archive, adopt a folder). +/// +/// +public sealed class AppServices : IAsyncDisposable +{ + private static readonly Lazy Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) }); + + public AppServices(AppEnvironment environment, AppSettings settings, Action saveSettings, IAppDialogs dialogs) + { + Environment = environment; + Settings = settings; + SaveSettingsAction = saveSettings; + Dialogs = dialogs; + ArchiveSetup = new LocalArchiveSetup(settings, saveSettings); + Server = new ServerSession(settings, saveSettings, new TitanoServerApiFactory(), new DpapiTokenProtector()); + Encoders = new MediaFoundationInventory(); + CheckForUpdateAsync = ct => UpdateCheck.FetchAsync(Http.Value, ProductLinks.LatestReleaseApi, VersionText, ct); + } + + public AppEnvironment Environment { get; } + public AppSettings Settings { get; } + public IAppDialogs Dialogs { get; } + + private Action SaveSettingsAction { get; } + + /// First-run archive actions; replaced by the integrator with the archive engine's implementation. + public IArchiveSetup ArchiveSetup { get; set; } + + public ServerSession Server { get; set; } + + public IEncoderInventory Encoders { get; set; } + + /// Latest public release (GitHub Releases API of the releases repository, BRIEF §18). + public Func> CheckForUpdateAsync { get; set; } + + /// The index; null until succeeded. + public TitanoDatabase? Database { get; private set; } + + public JobEngine? Engine { get; private set; } + + public IJobQueue? Jobs { get; private set; } + + public ThumbnailService? Thumbnails { get; private set; } + + /// Why the index could not be opened; null when it is open. + public Exception? OpenError { get; private set; } + + /// Node id of this PC's workers. + public string WorkerId { get; init; } = System.Environment.MachineName; + + /// "0.1.0" (informational version). + public static string VersionText { get; } = + typeof(AppServices).Assembly.GetCustomAttribute()?.InformationalVersion ?? "0.0.0"; + + /// + /// The job handlers of this PC's engine — the single registration list. The integrator adds the archive + /// handlers and the render handler here; a kind without a handler stays queued (it is never claimed here). + /// + public static IReadOnlyList CreateJobHandlers(AppServices services) => + [ + ]; + + public void SaveSettings() => SaveSettingsAction(); + + /// Opens (or creates) the index at , migrates it and starts the job engine. + public async Task OpenAsync(string databasePath, CancellationToken ct = default) + { + try + { + Database = await Task.Run(() => TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(databasePath), ct), ct); + Log.Info("app", $"Index open (schema {Database.SchemaVersion}) at {databasePath}"); + } + catch (Exception ex) when (ex is DatabaseException or System.IO.IOException or UnauthorizedAccessException or DllNotFoundException) + { + OpenError = ex; + Log.Error("app", "The index could not be opened", ex); + return; + } + await StartJobsAsync(Database, startEngine: true, ct); + Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems); + } + + /// Uses an already open index (capture, tests) instead of opening one; sample data keeps the engine stopped. + public async Task AttachAsync(TitanoDatabase database, bool startEngine = true, CancellationToken ct = default) + { + Database = database; + await StartJobsAsync(database, startEngine, ct); + Thumbnails = new ThumbnailService(database, Settings.ThumbnailMemoryItems); + } + + public async ValueTask DisposeAsync() + { + (Jobs as IDisposable)?.Dispose(); + if (Engine is not null) await Engine.DisposeAsync(); + Thumbnails?.Dispose(); + Server.Dispose(); + if (Database is not null) await Database.DisposeAsync(); + } + + private async Task StartJobsAsync(TitanoDatabase database, bool startEngine, CancellationToken ct) + { + var handlers = CreateJobHandlers(this); + var kinds = handlers.Select(h => h.Kind).Distinct().ToArray(); + Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds }); + // With no handler the engine must not run: an empty kind list would let workers claim (and fail) every job. + var started = startEngine && handlers.Count > 0; + if (started) await Engine.StartAsync(ct); + Jobs = new EngineJobQueue(database, Engine, started); + Log.Info("jobs", started ? $"Job engine started with {Engine.Options.Workers} worker(s) for {string.Join(", ", kinds)}" : "No job handlers registered; jobs stay queued"); + } +} diff --git a/src/Titano.App/Infrastructure/AppSettings.cs b/src/Titano.App/Infrastructure/AppSettings.cs index 9022de83..59385ce1 100644 --- a/src/Titano.App/Infrastructure/AppSettings.cs +++ b/src/Titano.App/Infrastructure/AppSettings.cs @@ -2,21 +2,119 @@ using System.IO; using System.Text.Json; using System.Text.Json.Serialization; using Titano.Core.IO; +using Titano.Core.Naming; +using Titano.Data.Repositories; using Titano.Ui.Theming; namespace Titano.App.Infrastructure; -/// Per-user preferences needed before the database opens (language, theme, window layout). +/// Library presentation (BRIEF §12.2). +public enum LibraryLayout +{ + Grid, + List, +} + +/// Rendering quality profile (Settings › Rendering). +public enum QualityProfile +{ + Best, + Balanced, + Fast, +} + +/// Which encoders a render may use (Settings › Rendering). +public enum HardwarePreference +{ + PreferHardware, + SoftwareOnly, + HardwareForPreviews, +} + +/// A server certificate the user trusted on first use (BRIEF §12.7). +public sealed class TrustedCertificate +{ + public string Fingerprint { get; set; } = string.Empty; + public string? Server { get; set; } + public DateTimeOffset TrustedAt { get; set; } +} + +/// +/// Per-user preferences (language, theme, window layout, archive defaults, server session). Kept in +/// settings.json next to the database and written atomically, because language and theme apply before the +/// database opens. +/// public sealed class AppSettings { + public const int DefaultThumbnailMemoryItems = 2_000; + public const int DefaultCacheLimitGb = 20; + + // ---- General ---- public string? Language { get; set; } public AppTheme Theme { get; set; } = AppTheme.Dark; public bool RailCollapsed { get; set; } - public bool CheckForUpdates { get; set; } = true; public bool AnonymousUsageCounts { get; set; } - public string? LastArchivePath { get; set; } public WindowPlacement? Window { get; set; } + /// The first-run choice (local archive, adopted folder or server) was made. + public bool FirstRunCompleted { get; set; } + + // ---- Updates ---- + public bool CheckForUpdates { get; set; } = true; + + // ---- Archive ---- + /// Root of the local archive; null until the first-run choice or Settings › Archive sets it. + public string? LastArchivePath { get; set; } + + public string FolderTemplate { get; set; } = TemplateDefaults.Folder; + public string FileTemplate { get; set; } = TemplateDefaults.File; + + /// Proxy long edge for new archives; 0 = full size. + public int ProxyLongEdge { get; set; } = 1920; + + // ---- Library ---- + public LibraryLayout LibraryLayout { get; set; } = LibraryLayout.Grid; + public SequenceSort LibrarySort { get; set; } = SequenceSort.Newest; + + // ---- Rendering ---- + public QualityProfile Quality { get; set; } = QualityProfile.Balanced; + + /// Frame memory budget in GB; null = Auto (a quarter of installed memory). + public int? MemoryBudgetGb { get; set; } + + /// Worker threads; null = Auto (cores minus four, at least one). + public int? Parallelism { get; set; } + + public bool BackgroundPriority { get; set; } = true; + public HardwarePreference HardwareEncoding { get; set; } = HardwarePreference.PreferHardware; + + // ---- Storage ---- + /// Cache (spill frames, thumbnails); null = cache under the data folder. + public string? CacheFolder { get; set; } + + /// Decoded thumbnails kept in memory. + public int ThumbnailMemoryItems { get; set; } = DefaultThumbnailMemoryItems; + + /// Upper bound of the disk cache in GB. + public int CacheLimitGb { get; set; } = DefaultCacheLimitGb; + + // ---- Server ---- + public string? ServerUrl { get; set; } + public string? ServerUsername { get; set; } + + /// The session token, encrypted for this Windows user with DPAPI (Base64). + public string? ProtectedToken { get; set; } + + public List TrustedCertificates { get; set; } = []; + public List RecentServers { get; set; } = []; + + /// Let the server send render jobs to this PC (BRIEF §14.7). + public bool RenderNodeOptIn { get; set; } + + // ---- Jobs ---- + /// "Clear done": finished jobs older than this are hidden from the Jobs list (they stay in the history). + public DateTimeOffset? JobsClearedAt { get; set; } + public sealed class WindowPlacement { public double Left { get; set; } @@ -30,8 +128,7 @@ public sealed class AppSettings { try { - if (File.Exists(path)) - return JsonSerializer.Deserialize(File.ReadAllText(path), AppSettingsJson.Default.AppSettings) ?? new AppSettings(); + if (File.Exists(path)) return Parse(File.ReadAllText(path)) ?? new AppSettings(); } catch (JsonException) { @@ -43,7 +140,16 @@ public sealed class AppSettings return new AppSettings(); } - public void Save(string path) => AtomicFile.WriteAllText(path, JsonSerializer.Serialize(this, AppSettingsJson.Default.AppSettings)); + /// Reads settings JSON (Settings › Import); null when the text is not a settings object. + /// The text is not valid JSON. + public static AppSettings? Parse(string json) => JsonSerializer.Deserialize(json, AppSettingsJson.Default.AppSettings); + + public string ToJson() => JsonSerializer.Serialize(this, AppSettingsJson.Default.AppSettings); + + public void Save(string path) => AtomicFile.WriteAllText(path, ToJson()); + + /// A deep copy (JSON round trip), used for import and reset. + public AppSettings Clone() => Parse(ToJson()) ?? new AppSettings(); } [JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true)] diff --git a/src/Titano.App/Infrastructure/ArchiveSetup.cs b/src/Titano.App/Infrastructure/ArchiveSetup.cs new file mode 100644 index 00000000..92975647 --- /dev/null +++ b/src/Titano.App/Infrastructure/ArchiveSetup.cs @@ -0,0 +1,104 @@ +using System.IO; +using Titano.Core.Diagnostics; + +namespace Titano.App.Infrastructure; + +/// +/// First-run archive choices (BRIEF §12.1): create a local archive or adopt an existing folder tree. The +/// integrator replaces with an implementation backed by the archive engine (folder +/// layout, index, adopt job); see . +/// +public interface IArchiveSetup +{ + /// Creates (or opens) the local archive rooted at . + Task CreateAsync(string root, CancellationToken cancellationToken = default); + + /// Indexes the photos under in place, or opens a previous Titano archive there. + Task AdoptAsync(string folder, CancellationToken cancellationToken = default); +} + +/// Until the archive engine is connected: remembers the chosen root in the settings and nothing else. +public sealed class LocalArchiveSetup(AppSettings settings, Action save) : IArchiveSetup +{ + public Task CreateAsync(string root, CancellationToken cancellationToken = default) + { + Remember(root); + Log.Info("archive", $"Local archive root set to {root}"); + return Task.CompletedTask; + } + + public Task AdoptAsync(string folder, CancellationToken cancellationToken = default) + { + Remember(folder); + Log.Info("archive", $"Adopted folder recorded: {folder}"); + return Task.CompletedTask; + } + + private void Remember(string path) + { + settings.LastArchivePath = Path.GetFullPath(path); + save(); + } +} + +/// Archive roots offered by default and their free space. +public static class ArchiveLocations +{ + public const string DefaultFolderName = "TitanoArchive"; + + /// "<fixed drive with the most free space>\TitanoArchive". + public static string SuggestRoot() + { + try + { + var best = DriveInfo.GetDrives() + .Where(d => d.DriveType == DriveType.Fixed && d.IsReady) + .OrderByDescending(d => d.AvailableFreeSpace) + .FirstOrDefault(); + if (best is not null) return Path.Combine(best.RootDirectory.FullName, DefaultFolderName); + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), DefaultFolderName); + } + + /// Free bytes on the volume of ; null when unknown. + public static long? FreeSpace(string? path) + { + if (string.IsNullOrWhiteSpace(path)) return null; + try + { + var root = Path.GetPathRoot(Path.GetFullPath(path)); + if (string.IsNullOrEmpty(root)) return null; + var drive = new DriveInfo(root); + return drive.IsReady ? drive.AvailableFreeSpace : null; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) + { + return null; + } + } + + /// The problem of an archive root as a localized sentence; null when it can be used. + public static string? Validate(string? path) + { + if (string.IsNullOrWhiteSpace(path)) return Core.Localization.Loc.L("Errors.Path.Empty"); + try + { + if (!Path.IsPathFullyQualified(path)) return Core.Localization.Loc.L("Errors.Path.NotAbsolute"); + var full = Path.GetFullPath(path); + if (File.Exists(full)) return Core.Localization.Loc.L("Errors.Path.IsFile"); + var root = Path.GetPathRoot(full); + if (string.IsNullOrEmpty(root) || !Directory.Exists(root)) return Core.Localization.Loc.L("Errors.Path.NoDrive"); + return null; + } + catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException) + { + return Core.Localization.Loc.L("Errors.Path.Invalid"); + } + } +} diff --git a/src/Titano.App/Infrastructure/DiagnosticsBundle.cs b/src/Titano.App/Infrastructure/DiagnosticsBundle.cs new file mode 100644 index 00000000..1bdb5217 --- /dev/null +++ b/src/Titano.App/Infrastructure/DiagnosticsBundle.cs @@ -0,0 +1,147 @@ +using System.Globalization; +using System.IO; +using System.IO.Compression; +using System.Runtime.InteropServices; +using System.Text; + +namespace Titano.App.Infrastructure; + +/// +/// The diagnostics bundle of About and Settings › Advanced (BRIEF §12.9): the log files plus an environment report +/// (versions, OS, runtime, culture, folders), zipped into a folder the user chose. Settings and tokens are not included. +/// +public static class DiagnosticsBundle +{ + /// Writes "Titano diagnostics yyyy-MM-dd HHmm.zip" into and returns its path. + public static Task CreateAsync(AppEnvironment environment, string folder, IEnumerable? extraLines = null, CancellationToken ct = default) => + Task.Run(() => + { + var path = Path.Combine(folder, $"Titano diagnostics {DateTime.Now.ToString("yyyy-MM-dd HHmm", CultureInfo.InvariantCulture)}.zip"); + var temp = path + ".tmp"; + using (var zip = ZipFile.Open(temp, ZipArchiveMode.Create)) + { + var report = zip.CreateEntry("environment.txt", CompressionLevel.Optimal); + using (var writer = new StreamWriter(report.Open(), new UTF8Encoding(false))) + { + writer.Write(Report(environment, extraLines)); + } + if (Directory.Exists(environment.LogDirectory)) + { + foreach (var log in Directory.EnumerateFiles(environment.LogDirectory, "*.log").OrderBy(f => f, StringComparer.Ordinal)) + { + ct.ThrowIfCancellationRequested(); + var entry = zip.CreateEntry("logs/" + Path.GetFileName(log), CompressionLevel.Optimal); + // The current log is open for writing: share the handle instead of copying the file. + using var source = new FileStream(log, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + using var target = entry.Open(); + source.CopyTo(target); + } + } + } + File.Move(temp, path, overwrite: true); + return path; + }, ct); + + /// Plain-text environment report. + public static string Report(AppEnvironment environment, IEnumerable? extraLines = null) + { + var sb = new StringBuilder(); + sb.AppendLine(CultureInfo.InvariantCulture, $"Titano {AppServices.VersionText}"); + sb.AppendLine(CultureInfo.InvariantCulture, $"Created {DateTimeOffset.Now:O}"); + sb.AppendLine(CultureInfo.InvariantCulture, $"OS {RuntimeInformation.OSDescription} ({RuntimeInformation.OSArchitecture})"); + sb.AppendLine(CultureInfo.InvariantCulture, $"Runtime {RuntimeInformation.FrameworkDescription} ({RuntimeInformation.ProcessArchitecture})"); + sb.AppendLine(CultureInfo.InvariantCulture, $"Culture {CultureInfo.CurrentCulture.Name} / UI {CultureInfo.CurrentUICulture.Name}"); + sb.AppendLine(CultureInfo.InvariantCulture, $"Processors {Environment.ProcessorCount}"); + sb.AppendLine(CultureInfo.InvariantCulture, $"Memory {GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / (1024 * 1024)} MB"); + sb.AppendLine(CultureInfo.InvariantCulture, $"Data {environment.DataDirectory} (portable: {environment.IsPortable})"); + if (extraLines is not null) + { + foreach (var line in extraLines) sb.AppendLine(line); + } + return sb.ToString(); + } +} + +/// +/// The disk cache (spilled frames, thumbnails): its folder, its size and clearing it. Only a folder Titano created +/// (it carries a marker file) is ever emptied, so pointing the cache at a folder with user files cannot delete them. +/// +public static class CacheStore +{ + public const string MarkerFile = ".titano-cache"; + + /// The cache folder in effect. + public static string Folder(AppEnvironment environment, AppSettings settings) => + string.IsNullOrWhiteSpace(settings.CacheFolder) ? environment.CacheDirectory : settings.CacheFolder!; + + /// Creates the folder (if needed) and marks it as Titano's. + public static void Prepare(string folder) + { + Directory.CreateDirectory(folder); + var marker = Path.Combine(folder, MarkerFile); + if (!File.Exists(marker)) File.WriteAllText(marker, "Titano cache folder. Its contents can be deleted at any time."); + } + + /// True when is a Titano cache folder (safe to empty). + public static bool IsOwned(string folder) => File.Exists(Path.Combine(folder, MarkerFile)); + + /// Total bytes of the files in the cache (0 when missing). + public static long Size(string folder) + { + if (!Directory.Exists(folder)) return 0; + long total = 0; + var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint }; + foreach (var file in new DirectoryInfo(folder).EnumerateFiles("*", options)) total += file.Length; + return total; + } + + /// Deletes everything inside an owned cache folder except the marker; returns the bytes freed. + /// The folder is not a Titano cache folder. + public static long Clear(string folder) + { + if (!Directory.Exists(folder)) return 0; + if (!IsOwned(folder)) throw new InvalidOperationException("Not a Titano cache folder: " + folder); + long freed = 0; + var root = new DirectoryInfo(folder); + foreach (var file in root.EnumerateFiles()) + { + if (file.Name == MarkerFile) continue; + freed += TryDelete(file); + } + foreach (var directory in root.EnumerateDirectories()) + { + if ((directory.Attributes & FileAttributes.ReparsePoint) != 0) continue; + var options = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint }; + foreach (var file in directory.EnumerateFiles("*", options)) freed += TryDelete(file); + try + { + directory.Delete(recursive: true); + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + } + return freed; + } + + private static long TryDelete(FileInfo file) + { + try + { + var length = file.Length; + file.Delete(); + return length; + } + catch (IOException) + { + return 0; // in use (a render spilling right now) + } + catch (UnauthorizedAccessException) + { + return 0; + } + } +} diff --git a/src/Titano.App/Infrastructure/Formatting.cs b/src/Titano.App/Infrastructure/Formatting.cs index 5a3c2ab8..18c48b23 100644 --- a/src/Titano.App/Infrastructure/Formatting.cs +++ b/src/Titano.App/Infrastructure/Formatting.cs @@ -26,9 +26,34 @@ public static class Formatting /// Compact duration: "2 h 00 m", "5 min", "40 s". public static string Duration(TimeSpan t) { + if (t < TimeSpan.Zero) t = TimeSpan.Zero; if (t.TotalHours >= 24) return Loc.L("Common.Duration.Days", (int)t.TotalDays, t.Hours); if (t.TotalHours >= 1) return Loc.L("Common.Duration.Hours", (int)t.TotalHours, t.Minutes.ToString("00", Loc.Culture)); if (t.TotalMinutes >= 1) return Loc.L("Common.Duration.Minutes", (int)Math.Round(t.TotalMinutes)); return Loc.L("Common.Duration.Seconds", (int)Math.Round(t.TotalSeconds)); } + + /// Clock-style elapsed time for finished jobs: "2:41", "1:02:41". + public static string Elapsed(TimeSpan t) + { + if (t < TimeSpan.Zero) t = TimeSpan.Zero; + return t.TotalHours >= 1 + ? ((int)t.TotalHours).ToString(Loc.Culture) + ":" + t.Minutes.ToString("00", Loc.Culture) + ":" + t.Seconds.ToString("00", Loc.Culture) + : ((int)t.TotalMinutes).ToString(Loc.Culture) + ":" + t.Seconds.ToString("00", Loc.Culture); + } + + /// 0.62 → "62 %". + public static string Percent(double fraction) => Loc.L("Common.Percent", Math.Round(Math.Clamp(fraction, 0, 1) * 100).ToString("0", Loc.Culture)); + + /// Items per second with one decimal below 100: "11.3", "118". + public static string Rate(double perSecond) => perSecond.ToString(perSecond < 100 ? "0.#" : "N0", Loc.Culture); + + /// Local time of day in the culture's short format ("09:12"). + public static string TimeOfDay(DateTimeOffset at) => at.ToLocalTime().ToString("t", Loc.Culture); + + /// Calendar date in the culture's short format. + public static string Date(DateTimeOffset at) => at.ToLocalTime().ToString("d", Loc.Culture); + + /// Camera wall-clock date in the culture's short format. + public static string Date(DateTime wallClock) => wallClock.ToString("d", Loc.Culture); } diff --git a/src/Titano.App/Infrastructure/IAppDialogs.cs b/src/Titano.App/Infrastructure/IAppDialogs.cs new file mode 100644 index 00000000..892964e2 --- /dev/null +++ b/src/Titano.App/Infrastructure/IAppDialogs.cs @@ -0,0 +1,39 @@ +namespace Titano.App.Infrastructure; + +/// Texts of a confirmation dialog (DESIGN §4: two buttons, safe action left and default). +public sealed record ConfirmRequest +{ + public required string Heading { get; init; } + public required string Message { get; init; } + + /// Monospaced detail (certificate fingerprint); null hides it. + public string? Detail { get; init; } + + public string? DetailToolTip { get; init; } + public required string SafeText { get; init; } + public required string SafeToolTip { get; init; } + public required string ActionText { get; init; } + public required string ActionToolTip { get; init; } + + /// Warning-outlined action (never a primary) for data-destroying choices. + public bool IsDestructive { get; init; } +} + +/// Modal questions and OS pickers the view models ask for (BRIEF §12.1: modals only for confirmations and login). +public interface IAppDialogs +{ + /// A folder chosen in the shell's folder picker; null when cancelled. + string? PickFolder(string title, string? initialFolder = null); + + /// A JSON file chosen in the shell's Open dialog; null when cancelled. + string? PickJsonFile(string title); + + /// True when the user chose the action. + bool Confirm(ConfirmRequest request); + + /// + /// The login form. receives user and password and returns null on success or the + /// error sentence to show; the form stays open until it succeeds or the user cancels. True when signed in. + /// + bool SignIn(string server, string? username, Func> signIn); +} diff --git a/src/Titano.App/Infrastructure/ProductLinks.cs b/src/Titano.App/Infrastructure/ProductLinks.cs index abdef10a..bcccb637 100644 --- a/src/Titano.App/Infrastructure/ProductLinks.cs +++ b/src/Titano.App/Infrastructure/ProductLinks.cs @@ -8,7 +8,15 @@ public static class ProductLinks .OfType() .FirstOrDefault(a => a.Key == "TitanoReleasesRepo")?.Value ?? "alby96/titano-releases"; - public static string Releases => $"https://github.com/{ReleasesRepository}/releases"; + public static string Repository => $"https://github.com/{ReleasesRepository}"; + + public static string Releases => $"{Repository}/releases"; public static string LatestReleaseApi => $"https://api.github.com/repos/{ReleasesRepository}/releases/latest"; + + /// The licence (EULA) published with the releases (BRIEF §12.9). + public static string Licence => $"{Repository}/blob/HEAD/LICENSE.md"; + + /// Where translations are reviewed by the community (BRIEF §16). + public static string Issues => $"{Repository}/issues"; } diff --git a/src/Titano.App/Infrastructure/ShellActions.cs b/src/Titano.App/Infrastructure/ShellActions.cs index ba546bb5..ef09d422 100644 --- a/src/Titano.App/Infrastructure/ShellActions.cs +++ b/src/Titano.App/Infrastructure/ShellActions.cs @@ -1,20 +1,31 @@ -using System.Diagnostics; using System.IO; +using Titano.Core.Diagnostics; +using Titano.Core.Windows.Shell; namespace Titano.App.Infrastructure; -/// The only shell launches the product performs (BRIEF §8.6): open a URL, reveal a folder. +/// The only shell launches the product performs (BRIEF §8.6): open a web or Store link, reveal a folder or file. public static class ShellActions { public static void OpenUrl(string url) { - if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || uri.Scheme is not ("https" or "http" or "ms-windows-store")) return; - Process.Start(new ProcessStartInfo(uri.AbsoluteUri) { UseShellExecute = true }); + if (!ShellLauncher.IsAllowedUrl(url)) return; + try + { + if (!ShellLauncher.OpenUrl(url)) Log.Warning("shell", $"The shell could not open {url}"); + } + catch (Exception ex) when (ex is ArgumentException or System.ComponentModel.Win32Exception) + { + Log.Warning("shell", $"The shell could not open {url}", ex); + } } - public static void OpenFolder(string path) + /// Opens a folder in Explorer, or shows a file selected in its folder. + public static void Reveal(string path) { - if (!Directory.Exists(path)) return; - Process.Start(new ProcessStartInfo(path) { UseShellExecute = true, Verb = "explore" }); + if (string.IsNullOrWhiteSpace(path) || !(Directory.Exists(path) || File.Exists(path))) return; + if (!ShellLauncher.RevealInExplorer(path)) Log.Warning("shell", $"Explorer could not show {path}"); } + + public static void OpenFolder(string path) => Reveal(path); } diff --git a/src/Titano.App/Infrastructure/UiLanguage.cs b/src/Titano.App/Infrastructure/UiLanguage.cs new file mode 100644 index 00000000..e2a5f783 --- /dev/null +++ b/src/Titano.App/Infrastructure/UiLanguage.cs @@ -0,0 +1,33 @@ +using System.Globalization; +using System.Windows; +using Titano.Core.Localization; + +namespace Titano.App.Infrastructure; + +/// Switches the UI language at run time without restart (BRIEF §16), mirroring right-to-left languages. +public static class UiLanguage +{ + /// Applies (or the OS language when null) and returns the culture in use. + public static CultureInfo Apply(string? code) + { + CultureInfo requested; + try + { + requested = code is null ? CultureInfo.CurrentUICulture : CultureInfo.GetCultureInfo(code); + } + catch (CultureNotFoundException) + { + requested = CultureInfo.CurrentUICulture; + } + var culture = Languages.BestMatch(requested); + CultureInfo.DefaultThreadCurrentUICulture = culture; + CultureInfo.CurrentUICulture = culture; + Loc.SetCulture(culture); + if (Application.Current is { } app) + { + foreach (Window window in app.Windows) + window.FlowDirection = Loc.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; + } + return culture; + } +} diff --git a/src/Titano.App/Interop/FileDialogs.cs b/src/Titano.App/Interop/FileDialogs.cs new file mode 100644 index 00000000..9f8e75de --- /dev/null +++ b/src/Titano.App/Interop/FileDialogs.cs @@ -0,0 +1,192 @@ +using System.Runtime.InteropServices; + +namespace Titano.App.Interop; + +/// A filter of the Open dialog: display name and patterns such as *.jpg;*.cr2. +public readonly record struct FileFilter(string Name, string Patterns); + +/// +/// The shell's Open dialog through IFileOpenDialog COM (no WinForms): one or several files, or one folder +/// (which also picks a card root such as E:\). Same wrapper as the uploader's (kept per program so neither +/// depends on the other). +/// +public static class FileDialogs +{ + private const uint FosPickFolders = 0x20; + private const uint FosForceFileSystem = 0x40; + private const uint FosAllowMultiSelect = 0x200; + private const uint FosPathMustExist = 0x800; + private const uint FosFileMustExist = 0x1000; + private const uint SigdnFileSysPath = 0x80058000; + private const int ErrorCancelled = unchecked((int)0x800704C7); + + /// Selected files; empty when cancelled. + public static IReadOnlyList PickFiles(IntPtr owner, string title, IReadOnlyList filters) => + Show(owner, title, FosAllowMultiSelect | FosFileMustExist, filters); + + /// One selected file; null when cancelled. + public static string? PickFile(IntPtr owner, string title, IReadOnlyList filters) => + Show(owner, title, FosFileMustExist, filters).FirstOrDefault(); + + /// Selected folder; null when cancelled. + public static string? PickFolder(IntPtr owner, string title) => Show(owner, title, FosPickFolders, []).FirstOrDefault(); + + private static List Show(IntPtr owner, string title, uint options, IReadOnlyList filters) + { + var dialog = (IFileOpenDialog)new FileOpenDialogClass(); + try + { + dialog.GetOptions(out var current); + dialog.SetOptions(current | options | FosForceFileSystem | FosPathMustExist); + dialog.SetTitle(title); + if (filters.Count > 0) + { + var specs = filters.Select(f => new FilterSpec { Name = f.Name, Spec = f.Patterns }).ToArray(); + dialog.SetFileTypes((uint)specs.Length, specs); + dialog.SetFileTypeIndex(1); + } + var hr = dialog.Show(owner); + if (hr == ErrorCancelled) return []; + Marshal.ThrowExceptionForHR(hr); + + dialog.GetResults(out var items); + try + { + items.GetCount(out var count); + var paths = new List((int)count); + for (uint i = 0; i < count; i++) + { + items.GetItemAt(i, out var item); + try + { + item.GetDisplayName(SigdnFileSysPath, out var path); + paths.Add(path); + } + finally + { + Marshal.ReleaseComObject(item); + } + } + return paths; + } + finally + { + Marshal.ReleaseComObject(items); + } + } + finally + { + Marshal.ReleaseComObject(dialog); + } + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + private struct FilterSpec + { + [MarshalAs(UnmanagedType.LPWStr)] + public string Name; + + [MarshalAs(UnmanagedType.LPWStr)] + public string Spec; + } + + [ComImport] + [Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")] + private class FileOpenDialogClass; + + // Classic COM interop does not inherit vtables: IModalWindow and IFileDialog members are repeated in order. + [ComImport] + [Guid("d57c7288-d4ad-4768-be02-9d969532d960")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IFileOpenDialog + { + [PreserveSig] + int Show(IntPtr owner); + + void SetFileTypes(uint count, [In, MarshalAs(UnmanagedType.LPArray)] FilterSpec[] filters); + + void SetFileTypeIndex(uint index); + + void GetFileTypeIndex(out uint index); + + void Advise(IntPtr events, out uint cookie); + + void Unadvise(uint cookie); + + void SetOptions(uint options); + + void GetOptions(out uint options); + + void SetDefaultFolder(IShellItem item); + + void SetFolder(IShellItem item); + + void GetFolder(out IShellItem item); + + void GetCurrentSelection(out IShellItem item); + + void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name); + + void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name); + + void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title); + + void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string text); + + void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label); + + void GetResult(out IShellItem item); + + void AddPlace(IShellItem item, int placement); + + void SetDefaultExtension([MarshalAs(UnmanagedType.LPWStr)] string extension); + + void Close(int hr); + + void SetClientGuid(ref Guid guid); + + void ClearClientData(); + + void SetFilter(IntPtr filter); + + void GetResults(out IShellItemArray items); + + void GetSelectedItems(out IShellItemArray items); + } + + [ComImport] + [Guid("43826d1e-e718-42ee-bc55-a1e261c37bfe")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellItem + { + void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result); + + void GetParent(out IShellItem parent); + + void GetDisplayName(uint form, [MarshalAs(UnmanagedType.LPWStr)] out string name); + + void GetAttributes(uint mask, out uint attributes); + + void Compare(IShellItem other, uint hint, out int order); + } + + [ComImport] + [Guid("b63ea76d-1f85-456f-a19c-48159efa858b")] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] + private interface IShellItemArray + { + void BindToHandler(IntPtr bindContext, ref Guid handler, ref Guid iid, out IntPtr result); + + void GetPropertyStore(int flags, ref Guid iid, out IntPtr store); + + void GetPropertyDescriptionList(IntPtr keyType, ref Guid iid, out IntPtr list); + + void GetAttributes(int flags, uint mask, out uint attributes); + + void GetCount(out uint count); + + void GetItemAt(uint index, out IShellItem item); + + void EnumItems(out IntPtr items); + } +} diff --git a/src/Titano.App/Jobs/JobListModel.cs b/src/Titano.App/Jobs/JobListModel.cs new file mode 100644 index 00000000..cd72b0c8 --- /dev/null +++ b/src/Titano.App/Jobs/JobListModel.cs @@ -0,0 +1,164 @@ +using Titano.Core.Model; +using Titano.Data.Jobs; + +namespace Titano.App.Jobs; + +/// Filter chips of the Jobs screen (BRIEF §12.6). +public enum JobFilter +{ + All, + Running, + Queued, + Done, + Failed, +} + +/// One job as the Jobs screen knows it: the last stored snapshot plus live progress while it runs. +public sealed class JobEntry(Job job) +{ + public Job Job { get; internal set; } = job; + + /// Latest progress event of the running job; null once it stops. + public JobProgressInfo? Live { get; internal set; } + + /// of the last update. + internal long Stamp { get; set; } + + public Guid Id => Job.Id; + public JobState State => Job.State; + public long Done => Live?.Done ?? Job.ProgressDone; + public long Total => Live?.Total ?? Job.ProgressTotal; + public double? ItemsPerSecond => Live?.ItemsPerSecond ?? Job.ItemsPerSecond; + public TimeSpan? Eta => Live?.Eta ?? Job.Eta; + public string? Message => Live?.Message; + + /// 0…1, or null while the total is unknown. + public double? Fraction => Total > 0 ? Math.Clamp((double)Done / Total, 0, 1) : null; + + public bool IsFinished => State is JobState.Done or JobState.Failed or JobState.Cancelled; +} + +/// +/// The job list behind the Jobs screen and the job bar: merges stored snapshots (, +/// repository pages) with live progress (), keeps queue order and answers the +/// filters. WPF-free and not thread-safe; feed it on the UI thread (through ). +/// +public sealed class JobListModel +{ + private readonly Dictionary _entries = []; + + private long _stamp; + + public int Count => _entries.Count; + + public JobEntry? this[Guid id] => _entries.GetValueOrDefault(id); + + /// + /// Change counter. Read it before requesting a page from the database and pass it to , + /// so a page that was read before an event cannot overwrite the newer state the event brought. + /// + public long Stamp => _stamp; + + /// Inserts or replaces a snapshot that is known to be current (an engine event). True when something changed. + public bool Apply(Job job) => Store(job, ++_stamp); + + /// Inserts a snapshot read from the database; skipped when an event updated the job after . + public bool ApplyLoaded(Job job, long readAt) + { + if (_entries.TryGetValue(job.Id, out var entry) && entry.Stamp > readAt) return false; + return Store(job, readAt); + } + + private bool Store(Job job, long stamp) + { + if (!_entries.TryGetValue(job.Id, out var entry)) + { + _entries[job.Id] = new JobEntry(job) { Stamp = stamp }; + return true; + } + entry.Stamp = Math.Max(entry.Stamp, stamp); + if (entry.Job == job) return false; + entry.Job = job; + if (job.State != JobState.Running) entry.Live = null; + return true; + } + + /// Live progress of a running job; ignored for unknown or no longer running jobs. True when something changed. + public bool Apply(JobProgressInfo progress) + { + if (!_entries.TryGetValue(progress.JobId, out var entry) || entry.State != JobState.Running) return false; + if (entry.Live == progress) return false; + entry.Live = progress; + return true; + } + + /// Removes jobs no longer present (e.g. purged history). + public bool Remove(Guid id) => _entries.Remove(id); + + /// + /// Display order: running (oldest start first), paused, queued in the order workers claim them (priority, then + /// age), then the history, newest finish first. Finished jobs before are hidden. + /// + public IReadOnlyList Ordered(JobFilter filter = JobFilter.All, string? search = null, DateTimeOffset? clearedBefore = null) + { + var text = string.IsNullOrWhiteSpace(search) ? null : search.Trim(); + return _entries.Values + .Where(e => Matches(e, filter) && Visible(e, clearedBefore) && (text is null || MatchesText(e, text))) + .OrderBy(Group) + .ThenBy(e => e.State == JobState.Queued ? -(int)e.Job.Priority : 0) + .ThenBy(e => e.IsFinished ? -(e.Job.Finished ?? e.Job.Created).UtcTicks : (e.Job.Started ?? e.Job.Created).UtcTicks) + .ThenBy(e => e.Job.Created) + .ThenBy(e => e.Id) + .ToList(); + } + + /// Jobs per filter chip (after "Clear done"). + public int CountOf(JobFilter filter, DateTimeOffset? clearedBefore = null) => + _entries.Values.Count(e => Matches(e, filter) && Visible(e, clearedBefore)); + + /// 1-based place of a queued job in the order workers claim jobs; 0 when it is not queued. + public int QueuePosition(Guid id) + { + if (!_entries.TryGetValue(id, out var entry) || entry.State != JobState.Queued) return 0; + return _entries.Values.Count(e => e.State == JobState.Queued && ClaimsBefore(e.Job, entry.Job)) + 1; + } + + /// The job the job bar mirrors: the running job with the most recent progress, else the first running one. + public JobEntry? Current => + _entries.Values.Where(e => e.State == JobState.Running) + .OrderByDescending(e => e.Live is not null) + .ThenBy(e => (e.Job.Started ?? e.Job.Created).UtcTicks) + .FirstOrDefault(); + + public int RunningCount => _entries.Values.Count(e => e.State == JobState.Running); + + public int QueuedCount => _entries.Values.Count(e => e.State == JobState.Queued); + + /// Same order as JobRepository.ClaimNextAsync: priority descending, then creation time and id. + public static bool ClaimsBefore(Job a, Job b) => + a.Priority != b.Priority ? a.Priority > b.Priority : a.Created != b.Created ? a.Created < b.Created : a.Id.CompareTo(b.Id) < 0; + + private static int Group(JobEntry e) => e.State switch + { + JobState.Running => 0, + JobState.Paused => 1, + JobState.Queued => 2, + _ => 3, + }; + + private static bool Matches(JobEntry e, JobFilter filter) => filter switch + { + JobFilter.Running => e.State is JobState.Running or JobState.Paused, + JobFilter.Queued => e.State == JobState.Queued, + JobFilter.Done => e.State == JobState.Done, + JobFilter.Failed => e.State is JobState.Failed or JobState.Cancelled, + _ => true, + }; + + private static bool Visible(JobEntry e, DateTimeOffset? clearedBefore) => + clearedBefore is null || !e.IsFinished || (e.Job.Finished ?? e.Job.Created) > clearedBefore; + + private static bool MatchesText(JobEntry e, string text) => + (e.Job.TargetLabel?.Contains(text, StringComparison.CurrentCultureIgnoreCase) ?? false) + || JobText.Kind(e.Job.Kind).Contains(text, StringComparison.CurrentCultureIgnoreCase); +} diff --git a/src/Titano.App/Jobs/JobQueue.cs b/src/Titano.App/Jobs/JobQueue.cs new file mode 100644 index 00000000..dbc587d1 --- /dev/null +++ b/src/Titano.App/Jobs/JobQueue.cs @@ -0,0 +1,106 @@ +using Titano.Core.Model; +using Titano.Data; +using Titano.Data.Jobs; +using Titano.Data.Repositories; + +namespace Titano.App.Jobs; + +/// What the Jobs screen, the job bar and the Library need from the job system. +public interface IJobQueue +{ + /// A job changed state (any thread). + event Action? JobChanged; + + /// Progress of a running job (any thread, high frequency). + event Action? Progress; + + /// Node id stamped on jobs run by this PC. + string WorkerId { get; } + + /// Concurrent workers of the local engine; 0 when it runs no handler yet. + int Workers { get; } + + /// Kinds this PC can run. + IReadOnlyCollection Kinds { get; } + + Task> ListAsync(string? cursor, int limit, CancellationToken ct = default); + + Task GetAsync(Guid id, CancellationToken ct = default); + + Task EnqueueAsync(JobKind kind, IReadOnlyList targets, string? targetLabel, JobPriority priority = JobPriority.User, CancellationToken ct = default); + + Task PauseAsync(Guid id); + + /// Resumes a paused job, or retries a failed or cancelled one from its checkpoint. + Task ResumeAsync(Guid id); + + /// Cancels a running or queued job. + Task CancelAsync(Guid id); + + /// Moves a queued job ahead of lower-priority jobs (one priority level up). + Task RaisePriorityAsync(Guid id); +} + +/// over the local and the job table. +public sealed class EngineJobQueue : IJobQueue, IDisposable +{ + private readonly TitanoDatabase _db; + private readonly JobEngine _engine; + private readonly bool _started; + + public EngineJobQueue(TitanoDatabase db, JobEngine engine, bool started) + { + _db = db; + _engine = engine; + _started = started; + _engine.JobChanged += OnJobChanged; + _engine.Progress += OnProgress; + } + + public event Action? JobChanged; + + public event Action? Progress; + + public string WorkerId => _engine.Options.WorkerId; + + public int Workers => _started ? _engine.Options.Workers : 0; + + public IReadOnlyCollection Kinds => _engine.Options.Kinds ?? []; + + public Task> ListAsync(string? cursor, int limit, CancellationToken ct = default) => _db.Jobs.ListAsync(null, limit, cursor, ct); + + public Task GetAsync(Guid id, CancellationToken ct = default) => _db.Jobs.GetAsync(id, ct); + + public Task EnqueueAsync(JobKind kind, IReadOnlyList targets, string? targetLabel, JobPriority priority = JobPriority.User, CancellationToken ct = default) => + _engine.EnqueueAsync(kind, targets, targetLabel, priority: priority, cancellationToken: ct); + + public Task PauseAsync(Guid id) => _engine.PauseAsync(id); + + public Task ResumeAsync(Guid id) => _engine.ResumeAsync(id); + + public Task CancelAsync(Guid id) => _engine.CancelAsync(id); + + public async Task RaisePriorityAsync(Guid id) + { + // JobRepository has no priority update yet; one guarded statement keeps it atomic (queued jobs only). + var session = await _db.Database.OpenAsync(CancellationToken.None); + await using (session) + { + await session.ExecuteAsync( + $"UPDATE jobs SET priority = priority + 1 WHERE id = $1 AND state = {(int)JobState.Queued} AND priority < {(int)JobPriority.User}", + [id], CancellationToken.None); + } + if (await _db.Jobs.GetAsync(id) is { } job) JobChanged?.Invoke(job); + _engine.Wake(); + } + + public void Dispose() + { + _engine.JobChanged -= OnJobChanged; + _engine.Progress -= OnProgress; + } + + private void OnJobChanged(Job job) => JobChanged?.Invoke(job); + + private void OnProgress(JobProgressInfo progress) => Progress?.Invoke(progress); +} diff --git a/src/Titano.App/Jobs/JobRowViewModel.cs b/src/Titano.App/Jobs/JobRowViewModel.cs new file mode 100644 index 00000000..7aed3470 --- /dev/null +++ b/src/Titano.App/Jobs/JobRowViewModel.cs @@ -0,0 +1,133 @@ +using System.Windows.Input; +using Titano.App.Infrastructure; +using Titano.App.Sections; +using Titano.Core.Localization; +using Titano.Core.Model; +using Titano.Ui.Controls; +using Titano.Ui.Mvvm; + +namespace Titano.App.Jobs; + +/// A row action: label, tooltip and command (26-px row buttons, DESIGN §4 tables). +public sealed record JobAction(string Text, string ToolTip, ICommand Command, bool IsDestructive = false); + +/// One row of the Jobs table (Jobs.html): kind, target, progress, speed, left, where, state, actions, log. +public sealed class JobRowViewModel : ObservableObject +{ + private readonly JobActions _actions; + private JobEntry _entry; + private int _queuePosition; + private bool _isExpanded; + private string? _logTail; + + internal JobRowViewModel(JobEntry entry, int queuePosition, JobActions actions) + { + _entry = entry; + _queuePosition = queuePosition; + _actions = actions; + ToggleLogCommand = new RelayCommand(() => IsExpanded = !IsExpanded); + } + + public JobEntry Entry => _entry; + public Guid Id => _entry.Id; + public Job Job => _entry.Job; + + public string Kind => JobText.Kind(_entry.Job.Kind); + + public string Target => _entry.Job.TargetLabel ?? string.Empty; + + /// Progress 0…1 (0 while unknown). + public double Progress => _entry.State == JobState.Done ? 1 : _entry.Fraction ?? 0; + + /// "62 %", "—" while queued or unknown. + public string PercentText => _entry.State == JobState.Done ? Formatting.Percent(1) : _entry.Fraction is { } f && _entry.State != JobState.Queued ? Formatting.Percent(f) : "—"; + + public string SpeedText => _entry.State is JobState.Running or JobState.Done ? Blank(JobText.Speed(_entry.Job.Kind, _entry.ItemsPerSecond)) : "—"; + + public string LeftText => Blank(JobText.Left(_entry, _queuePosition)); + + public string WhereText => _entry.State == JobState.Queued ? Loc.L("Jobs.Where.ThisPc") : Blank(JobText.Where(_entry.Job.NodeId, _actions.WorkerId)); + + public string StateText => JobText.State(_entry); + + /// Glyph and colour of the state (paired with the word, never colour alone). + public StatusKind StateKind => _entry.State switch + { + JobState.Running => StatusKind.Running, + JobState.Queued => StatusKind.Queued, + JobState.Paused => StatusKind.Paused, + JobState.Done => StatusKind.Done, + JobState.Failed => StatusKind.Failed, + _ => StatusKind.Offline, + }; + + /// The error of a failed job, or the state explanation. + public string StateToolTip => _entry.Job.Error is { Length: > 0 } error ? error : Loc.L("Tooltips.Jobs.State." + _entry.State); + + /// Muted text for rows that are not doing anything (queued, history), as in the mockup. + public bool IsDimmed => _entry.State is JobState.Queued or JobState.Done or JobState.Cancelled; + + public bool IsFailed => _entry.State == JobState.Failed; + public bool IsDone => _entry.State == JobState.Done; + + public IReadOnlyList Actions => _actions.For(_entry); + + public ICommand ToggleLogCommand { get; } + + public bool IsExpanded + { + get => _isExpanded; + set + { + if (!Set(ref _isExpanded, value)) return; + OnPropertyChanged(nameof(ToggleToolTip)); + if (value) _ = _actions.LoadLogAsync(this); + } + } + + public string ToggleToolTip => Loc.L(_isExpanded ? "Tooltips.Jobs.HideLog" : "Tooltips.Jobs.ShowLog"); + + /// The last lines of the job log, plus the live message while it runs. + public string LogText + { + get + { + var tail = _logTail ?? _entry.Job.LogTail ?? string.Empty; + if (_entry.State == JobState.Running && _entry.Message is { Length: > 0 } message && !tail.EndsWith(message, StringComparison.Ordinal)) + tail = tail.Length == 0 ? message : tail + "\n" + message; + return tail.Length == 0 ? Loc.L("Jobs.Log.Empty") : tail; + } + } + + internal void SetLog(string? logTail) + { + _logTail = logTail; + OnPropertyChanged(nameof(LogText)); + } + + /// Refreshes the row from the model; returns true when it changed position-relevant data. + internal void Update(JobEntry entry, int queuePosition) + { + var stateChanged = entry.State != _entry.State; + _entry = entry; + _queuePosition = queuePosition; + if (stateChanged) + { + _logTail = null; + OnAllPropertiesChanged(); + if (_isExpanded) _ = _actions.LoadLogAsync(this); + return; + } + OnPropertyChanged(nameof(Progress)); + OnPropertyChanged(nameof(PercentText)); + OnPropertyChanged(nameof(SpeedText)); + OnPropertyChanged(nameof(LeftText)); + OnPropertyChanged(nameof(WhereText)); + OnPropertyChanged(nameof(StateText)); + if (_isExpanded) OnPropertyChanged(nameof(LogText)); + } + + internal void Refresh() => OnAllPropertiesChanged(); + + private static string Blank(string text) => text.Length == 0 ? "—" : text; +} diff --git a/src/Titano.App/Jobs/JobText.cs b/src/Titano.App/Jobs/JobText.cs new file mode 100644 index 00000000..4bec41c4 --- /dev/null +++ b/src/Titano.App/Jobs/JobText.cs @@ -0,0 +1,68 @@ +using Titano.App.Infrastructure; +using Titano.Core.Localization; +using Titano.Core.Model; + +namespace Titano.App.Jobs; + +/// Localized texts of jobs: kind, speed, time left, place in the queue, state (Jobs screen and job bar). +public static class JobText +{ + /// "Render", "Deep analysis", … + public static string Kind(JobKind kind) => Loc.L("Jobs.Kind." + kind); + + /// True for jobs whose items are frames, so their speed reads in fps. + public static bool CountsFrames(JobKind kind) => + kind is JobKind.Render or JobKind.Proxies or JobKind.Thumbs or JobKind.LightAnalyse or JobKind.DeepAnalyse or JobKind.Verify; + + /// "11.3 fps" for frame jobs, "41/s" otherwise; empty when unknown. + public static string Speed(JobKind kind, double? perSecond) => + perSecond is > 0 and var rate + ? Loc.L(CountsFrames(kind) ? "Jobs.Speed.Fps" : "Jobs.Speed.PerSecond", Formatting.Rate(rate)) + : string.Empty; + + /// "1,240 / 3,600"; empty while the total is unknown. + public static string Counter(long done, long total) => + total > 0 ? Loc.L("Jobs.Counter", Formatting.Count(done), Formatting.Count(total)) : string.Empty; + + /// + /// The "Left" column: time left while running, "after n" while queued, the finish time of the history. + /// + public static string Left(JobEntry entry, int queuePosition) => entry.State switch + { + JobState.Running => entry.Eta is { } eta ? Formatting.Duration(eta) : string.Empty, + JobState.Queued => queuePosition > 1 ? Loc.L("Jobs.Left.After", queuePosition - 1) : Loc.L("Jobs.Left.Next"), + _ when entry.Job.Finished is { } finished => Formatting.TimeOfDay(finished), + _ => string.Empty, + }; + + /// State word, with the run time for done jobs ("done · 2:41"). + public static string State(JobEntry entry) + { + var word = Loc.L("Jobs.State." + entry.State); + return entry.State == JobState.Done && entry.Job is { Started: { } started, Finished: { } finished } + ? Loc.L("Jobs.State.WithDetail", word, Formatting.Elapsed(finished - started)) + : word; + } + + /// Where the job runs: "this PC" for this machine's workers, the node name otherwise. + public static string Where(string? nodeId, string localWorkerId) + { + if (string.IsNullOrEmpty(nodeId)) return string.Empty; + var hash = nodeId.IndexOf('#', StringComparison.Ordinal); + var name = hash < 0 ? nodeId : nodeId[..hash]; + return name.Equals(localWorkerId, StringComparison.OrdinalIgnoreCase) ? Loc.L("Jobs.Where.ThisPc") : name; + } + + /// + /// Job bar line (DESIGN §4): "Render · Harbour sunset · 2,232 / 3,600 · 11.3 fps · 2 min left". + /// + public static string Bar(JobEntry entry) + { + var parts = new List(5) { Kind(entry.Job.Kind) }; + if (!string.IsNullOrWhiteSpace(entry.Job.TargetLabel)) parts.Add(entry.Job.TargetLabel!); + if (Counter(entry.Done, entry.Total) is { Length: > 0 } counter) parts.Add(counter); + if (Speed(entry.Job.Kind, entry.ItemsPerSecond) is { Length: > 0 } speed) parts.Add(speed); + if (entry.Eta is { } eta) parts.Add(Loc.L("Jobs.Bar.Left", Formatting.Duration(eta))); + return string.Join(" · ", parts); + } +} diff --git a/src/Titano.App/Jobs/JobUpdateBuffer.cs b/src/Titano.App/Jobs/JobUpdateBuffer.cs new file mode 100644 index 00000000..a5b471a5 --- /dev/null +++ b/src/Titano.App/Jobs/JobUpdateBuffer.cs @@ -0,0 +1,143 @@ +using Titano.Core.Model; +using Titano.Data.Jobs; + +namespace Titano.App.Jobs; + +/// +/// Collects job events from worker threads and hands them to the UI in batches: per job only the newest snapshot +/// and the newest progress survive, so a handler reporting thousands of times per second costs the UI one update per +/// flush. Thread-safe. +/// +public sealed class JobUpdateBuffer +{ + private readonly Lock _gate = new(); + private Dictionary _jobs = []; + private Dictionary _progress = []; + private long _posted; + + /// Events accepted since creation (diagnostics, tests). + public long Posted => Interlocked.Read(ref _posted); + + /// Records a state change; true when the buffer was empty (the caller schedules a flush). + public bool Post(Job job) + { + lock (_gate) + { + var wasEmpty = IsEmptyLocked; + _jobs[job.Id] = job; + // A newer snapshot supersedes progress reported before it. + _progress.Remove(job.Id); + _posted++; + return wasEmpty; + } + } + + /// Records progress; true when the buffer was empty (the caller schedules a flush). + public bool Post(JobProgressInfo progress) + { + lock (_gate) + { + var wasEmpty = IsEmptyLocked; + _progress[progress.JobId] = progress; + _posted++; + return wasEmpty; + } + } + + public bool IsEmpty + { + get + { + lock (_gate) return IsEmptyLocked; + } + } + + /// Takes everything collected since the last drain (snapshots first, then progress). + public (IReadOnlyCollection Jobs, IReadOnlyCollection Progress) Drain() + { + lock (_gate) + { + var jobs = _jobs; + var progress = _progress; + _jobs = []; + _progress = []; + return (jobs.Values, progress.Values); + } + } + + private bool IsEmptyLocked => _jobs.Count == 0 && _progress.Count == 0; +} + +/// +/// Runs an action on a synchronization context at most once per interval, however often it is signalled from any +/// thread: the first signal after a flush schedules the next flush for interval after the previous one +/// (the job list refreshes at about 10 Hz). +/// +public sealed class CoalescingThrottle : IDisposable +{ + private readonly TimeSpan _interval; + private readonly SynchronizationContext? _context; + private readonly Action _flush; + private readonly Func _now; + private readonly Timer _timer; + private readonly Lock _gate = new(); + private long _lastFlush = long.MinValue; + private bool _scheduled; + private bool _disposed; + + /// Minimum time between two flushes. + /// Where runs (the UI); null runs it on the timer thread. + /// The batched work. + /// Milliseconds clock for tests; defaults to the high-resolution . + public CoalescingThrottle(TimeSpan interval, SynchronizationContext? context, Action flush, Func? clock = null) + { + _interval = interval; + _context = context; + _flush = flush; + _now = clock ?? (() => System.Diagnostics.Stopwatch.GetTimestamp() * 1000 / System.Diagnostics.Stopwatch.Frequency); + _timer = new Timer(_ => Dispatch(), null, Timeout.Infinite, Timeout.Infinite); + } + + /// Flushes performed (tests). + public int Flushes { get; private set; } + + /// Asks for a flush; coalesced with every other signal until it runs. + public void Signal() + { + lock (_gate) + { + if (_scheduled || _disposed) return; + _scheduled = true; + var wait = _lastFlush == long.MinValue ? 0 : (long)_interval.TotalMilliseconds - (_now() - _lastFlush); + if (wait <= 0) wait = 0; + _timer.Change(wait, Timeout.Infinite); + } + } + + public void Dispose() + { + lock (_gate) + { + _disposed = true; + _timer.Dispose(); + } + } + + private void Dispatch() + { + if (_context is null) Run(); + else _context.Post(_ => Run(), null); + } + + private void Run() + { + lock (_gate) + { + if (_disposed) return; + _scheduled = false; + _lastFlush = _now(); + Flushes++; + } + _flush(); + } +} diff --git a/src/Titano.App/Library/FilterOption.cs b/src/Titano.App/Library/FilterOption.cs new file mode 100644 index 00000000..81c0425d --- /dev/null +++ b/src/Titano.App/Library/FilterOption.cs @@ -0,0 +1,10 @@ +namespace Titano.App.Library; + +/// +/// One entry of a toolbar dropdown: in the open list, in the closed box +/// (the filter's name while nothing is chosen, e.g. "Year", the chosen value otherwise). +/// +public sealed record FilterOption(T Value, string Label, string BoxText, bool IsAny = false) +{ + public override string ToString() => Label; +} diff --git a/src/Titano.App/Library/LibraryFilter.cs b/src/Titano.App/Library/LibraryFilter.cs new file mode 100644 index 00000000..c0d64493 --- /dev/null +++ b/src/Titano.App/Library/LibraryFilter.cs @@ -0,0 +1,65 @@ +using Titano.Core.Model; +using Titano.Data.Repositories; + +namespace Titano.App.Library; + +/// Status choices of the Library toolbar; each maps onto status flags the index can filter on. +public enum StatusFilter +{ + Any, + Analysed, + NotAnalysed, + Proxies, + NoProxies, + Verified, + NotVerified, + Warnings, +} + +/// Library filters (search, year, camera, status, tag) and sort; immutable so a page request can carry it. +public sealed record LibraryFilter +{ + public string? Text { get; init; } + public int? Year { get; init; } + public string? Camera { get; init; } + public StatusFilter Status { get; init; } + public string? Tag { get; init; } + public SequenceSort Sort { get; init; } = SequenceSort.Newest; + + /// No filter narrows the list (the sort may differ): an empty result means an empty library. + public bool IsUnfiltered => string.IsNullOrWhiteSpace(Text) && Year is null && Camera is null && Status == StatusFilter.Any && Tag is null; + + /// The same sort without filters ("Clear filters"). + public LibraryFilter Cleared() => new() { Sort = Sort }; + + /// The repository query for one page. + public SequenceQuery ToQuery(int limit, string? cursor) + { + var (with, without) = Flags(Status); + return new SequenceQuery + { + Text = string.IsNullOrWhiteSpace(Text) ? null : Text.Trim(), + Year = Year, + Camera = Camera, + Tag = Tag, + WithStatus = with, + WithoutStatus = without, + Sort = Sort, + Limit = limit, + Cursor = cursor, + }; + } + + /// Flags that must be set and clear for a status choice. + public static (SequenceStatus With, SequenceStatus Without) Flags(StatusFilter status) => status switch + { + StatusFilter.Analysed => (SequenceStatus.AnalyzedLight, SequenceStatus.None), + StatusFilter.NotAnalysed => (SequenceStatus.None, SequenceStatus.AnalyzedLight), + StatusFilter.Proxies => (SequenceStatus.ProxiesBuilt, SequenceStatus.None), + StatusFilter.NoProxies => (SequenceStatus.None, SequenceStatus.ProxiesBuilt), + StatusFilter.Verified => (SequenceStatus.Verified, SequenceStatus.None), + StatusFilter.NotVerified => (SequenceStatus.None, SequenceStatus.Verified), + StatusFilter.Warnings => (SequenceStatus.HasWarnings, SequenceStatus.None), + _ => (SequenceStatus.None, SequenceStatus.None), + }; +} diff --git a/src/Titano.App/Library/LibraryPager.cs b/src/Titano.App/Library/LibraryPager.cs new file mode 100644 index 00000000..7995f47c --- /dev/null +++ b/src/Titano.App/Library/LibraryPager.cs @@ -0,0 +1,102 @@ +using Titano.Core.Model; +using Titano.Data.Repositories; + +namespace Titano.App.Library; + +/// A page of the Library list. pages replace the list, the others append to it. +public sealed record LibraryPage(int Generation, IReadOnlyList Items, bool IsFirst, bool HasMore); + +/// +/// Keyset paging of the Library (BRIEF §5: pagination on (first_capture, id)): the first page after a filter +/// change, then the next page whenever the view scrolls near the end. A filter change cancels the page in flight +/// and every result of an older filter is dropped, so stale rows never reach the list. Not thread-safe: call from +/// one thread (the UI). +/// +public sealed class LibraryPager(Func>> fetch, int pageSize = LibraryPager.DefaultPageSize) +{ + public const int DefaultPageSize = 200; + + private CancellationTokenSource _cancellation = new(); + private Task>? _pending; + private string? _cursor; + + public int PageSize { get; } = Math.Clamp(pageSize, 1, 1000); + + public LibraryFilter Filter { get; private set; } = new(); + + /// Incremented by every ; pages carry the generation they belong to. + public int Generation { get; private set; } + + /// More rows exist after the loaded ones. + public bool HasMore { get; private set; } + + public bool IsLoading => _pending is not null; + + /// Rows delivered for the current filter. + public int Loaded { get; private set; } + + /// Starts over with ; null when a newer reset superseded this one. + public Task ResetAsync(LibraryFilter filter) + { + _cancellation.Cancel(); + _cancellation.Dispose(); + _cancellation = new CancellationTokenSource(); + _pending = null; + Generation++; + Filter = filter; + _cursor = null; + Loaded = 0; + HasMore = true; + return LoadAsync(first: true); + } + + /// The next page; null when everything is loaded, a page is already loading, or the filter changed meanwhile. + public Task LoadMoreAsync() + { + if (_pending is not null || !HasMore || Generation == 0) return Task.FromResult(null); + return LoadAsync(first: false); + } + + /// Stops the page in flight (screen closed). + public void Cancel() + { + _cancellation.Cancel(); + _pending = null; + } + + private async Task LoadAsync(bool first) + { + var generation = Generation; + var cancellation = _cancellation; + var pending = fetch(Filter.ToQuery(PageSize, _cursor), cancellation.Token); + _pending = pending; + Page page; + try + { + page = await pending; + } + catch (OperationCanceledException) when (cancellation.IsCancellationRequested) + { + return null; + } + catch (Exception) when (generation != Generation) + { + return null; + } + catch + { + // A failing page stops the scroll-driven loading until the next reset instead of retrying on every scroll. + HasMore = false; + throw; + } + finally + { + if (ReferenceEquals(_pending, pending)) _pending = null; + } + if (generation != Generation || cancellation.IsCancellationRequested) return null; + _cursor = page.NextCursor; + HasMore = page.NextCursor is not null; + Loaded += page.Items.Count; + return new LibraryPage(generation, page.Items, first, HasMore); + } +} diff --git a/src/Titano.App/Library/SequenceItem.cs b/src/Titano.App/Library/SequenceItem.cs new file mode 100644 index 00000000..f1ed8d64 --- /dev/null +++ b/src/Titano.App/Library/SequenceItem.cs @@ -0,0 +1,179 @@ +using System.Windows.Media; +using Titano.App.Infrastructure; +using Titano.Core.Diagnostics; +using Titano.Core.Localization; +using Titano.Core.Model; +using Titano.Core.Naming; +using Titano.Ui.Controls; +using Titano.Ui.Mvvm; +using Titano.Ui.Visuals; + +namespace Titano.App.Library; + +/// One sequence of the Library grid and list (BRIEF §12.2). +public sealed class SequenceItem : ObservableObject +{ + private readonly ThumbnailService? _thumbnails; + private Sequence _sequence; + private ImageSource? _thumbnail; + private IThumbnailSource? _scrub; + private CancellationTokenSource? _loading; + private int _requestedWidth; + private bool _isSelected; + private bool _isAnalysing; + + public SequenceItem(Sequence sequence, ThumbnailService? thumbnails) + { + _sequence = sequence; + _thumbnails = thumbnails; + } + + public Sequence Sequence => _sequence; + public Guid Id => _sequence.Id; + + /// User title or "{date} {camera}". + public string Title => _sequence.DisplayTitle; + + /// "Canon EOS R5" (brand not repeated). + public string Camera => PathTemplate.CameraName(_sequence.CameraMake, _sequence.CameraModel); + + /// Card line: count · camera · span. + public string Subtitle => string.Join(" · ", new[] { FramesText, Camera, SpanText }.Where(s => s.Length > 0)); + + public string FramesText => Formatting.Count(_sequence.FrameCount); + + /// First capture date (camera clock). + public string DateText => _sequence.FirstCapture is { } first ? Formatting.Date(first) : string.Empty; + + /// Time from first to last capture. + public string SpanText => _sequence is { FirstCapture: { } a, LastCapture: { } b } && b > a ? Formatting.Duration(b - a) : string.Empty; + + public string IntervalText => _sequence.MedianInterval is > 0 and var s ? Loc.L("Library.Interval", s.ToString(s < 10 ? "0.#" : "0", Loc.Culture)) : string.Empty; + + public string SizeText => Formatting.Bytes(_sequence.TotalBytes); + + public string TagsText => string.Join(", ", _sequence.Tags); + + /// Status glyphs of the card and the list (DESIGN §4: glyph + word, never colour alone). + public IReadOnlyList Statuses => BuildStatuses(_sequence, _isAnalysing); + + /// The single most relevant status for the list's State column. + public CardStatus PrimaryStatus => Statuses.FirstOrDefault(s => s.Kind is StatusKind.Error or StatusKind.Warning or StatusKind.Analysing) + ?? Statuses[0]; + + public ImageSource? Thumbnail + { + get => _thumbnail; + private set => Set(ref _thumbnail, value); + } + + /// Frames for hover scrubbing; created on first use. + public IThumbnailSource? ScrubSource => _thumbnails is null || _sequence.FrameCount == 0 ? null : _scrub ??= _thumbnails.ScrubSource(_sequence); + + public bool IsSelected + { + get => _isSelected; + set => Set(ref _isSelected, value); + } + + /// An analysis job runs on this sequence ("◐ Analysing"). + public bool IsAnalysing + { + get => _isAnalysing; + set + { + if (Set(ref _isAnalysing, value)) RaiseStatuses(); + } + } + + /// Replaces the row with a fresher copy of the same sequence. + public void Update(Sequence sequence) + { + var heroChanged = sequence.HeroFrameId != _sequence.HeroFrameId || sequence.FrameCount != _sequence.FrameCount; + _sequence = sequence; + if (heroChanged) + { + _scrub = null; + if (_requestedWidth > 0) RequestThumbnail(_requestedWidth, force: true); + } + OnAllPropertiesChanged(); + } + + /// The card or row became visible: load the hero thumbnail (once per width). + public void RequestThumbnail(int pixelWidth, bool force = false) + { + if (_thumbnails is null || pixelWidth <= 0) return; + if (!force && _thumbnail is not null && pixelWidth <= _requestedWidth) return; + if (!force && _loading is not null && pixelWidth <= _requestedWidth) return; + _requestedWidth = pixelWidth; + _loading?.Cancel(); + var cancellation = new CancellationTokenSource(); + _loading = cancellation; + _ = LoadAsync(pixelWidth, cancellation); + } + + /// The card left the screen (recycled): stop its load. + public void ReleaseThumbnail() + { + _loading?.Cancel(); + _loading = null; + if (_thumbnail is null) _requestedWidth = 0; + } + + private async Task LoadAsync(int pixelWidth, CancellationTokenSource cancellation) + { + try + { + var image = await _thumbnails!.HeroAsync(_sequence, pixelWidth, cancellation.Token); + if (!cancellation.IsCancellationRequested) Thumbnail = image; + } + catch (OperationCanceledException) + { + } + catch (Exception ex) + { + Log.Warning("library", $"Thumbnail of {_sequence.Id} failed", ex); + } + finally + { + if (ReferenceEquals(_loading, cancellation)) _loading = null; + cancellation.Dispose(); + } + } + + private void RaiseStatuses() + { + OnPropertyChanged(nameof(Statuses)); + OnPropertyChanged(nameof(PrimaryStatus)); + } + + /// Card status row: analysed, proxies, renders, sync, warnings (Main.html). + public static IReadOnlyList BuildStatuses(Sequence s, bool analysing) + { + var list = new List(5); + if (analysing) list.Add(new CardStatus(StatusKind.Analysing, Loc.L("Library.Status.Analysing"), Loc.L("Tooltips.Library.Status.Analysing"))); + else if ((s.Status & SequenceStatus.AnalyzedLight) != 0) list.Add(new CardStatus(StatusKind.Analysed, Loc.L("Library.Status.Analysed"), Loc.L("Tooltips.Library.Status.Analysed"))); + else list.Add(new CardStatus(StatusKind.NotAnalysed, Loc.L("Library.Status.Analysed"), Loc.L("Tooltips.Library.Status.NotAnalysed"))); + + if (s.Origin == SequenceOrigin.Server && s.SyncState == SyncState.RemoteOnly) + { + list.Add(new CardStatus(StatusKind.Remote, Loc.L("Library.Status.Remote"), Loc.L("Tooltips.Library.Status.Remote"))); + } + else + { + list.Add((s.Status & SequenceStatus.ProxiesBuilt) != 0 + ? new CardStatus(StatusKind.Proxies, Loc.L("Library.Status.Proxies"), Loc.L("Tooltips.Library.Status.Proxies")) + : new CardStatus(StatusKind.NoProxies, Loc.L("Library.Status.Proxies"), Loc.L("Tooltips.Library.Status.NoProxies"))); + } + + if (s.RenderedCount > 0) + list.Add(new CardStatus(StatusKind.Rendered, Formatting.Count(s.RenderedCount), Loc.Plural("Tooltips.Library.Status.Rendered", s.RenderedCount))); + if (s.SyncState == SyncState.InSync) + list.Add(new CardStatus(StatusKind.Synced, Loc.L("Library.Status.Synced"), Loc.L("Tooltips.Library.Status.Synced"))); + if ((s.Status & SequenceStatus.HasErrors) != 0) + list.Add(new CardStatus(StatusKind.Error, Formatting.Count(Math.Max(1, s.WarningCount)), Loc.L("Tooltips.Library.Status.Errors"))); + else if (s.WarningCount > 0 || (s.Status & SequenceStatus.HasWarnings) != 0) + list.Add(new CardStatus(StatusKind.Warning, Formatting.Count(Math.Max(1, s.WarningCount)), Loc.Plural("Tooltips.Library.Status.Warnings", Math.Max(1, s.WarningCount)))); + return list; + } +} diff --git a/src/Titano.App/Library/ThumbnailCache.cs b/src/Titano.App/Library/ThumbnailCache.cs new file mode 100644 index 00000000..e6030b9d --- /dev/null +++ b/src/Titano.App/Library/ThumbnailCache.cs @@ -0,0 +1,152 @@ +using Titano.Ui.Visuals; + +namespace Titano.App.Library; + +/// +/// Decoded thumbnails in a least-recently-used cache, with loads shared between requests for the same key. A load +/// runs off the calling thread, at most maxConcurrentLoads at once; it is cancelled as soon as every request +/// waiting for it is cancelled (the card scrolled away), so the decoder never works for rows nobody sees. Results, +/// including "no thumbnail" (null), are cached; failures are not. +/// +public sealed class ThumbnailCache : IDisposable + where TKey : notnull + where TImage : class +{ + private readonly LruCache _cache; + private readonly Dictionary _loading = []; + private readonly Func> _load; + private readonly SemaphoreSlim _slots; + private readonly Lock _gate = new(); + + public ThumbnailCache(int capacity, Func> load, int maxConcurrentLoads = 4) + { + ArgumentOutOfRangeException.ThrowIfLessThan(maxConcurrentLoads, 1); + _cache = new LruCache(capacity); + _load = load; + _slots = new SemaphoreSlim(maxConcurrentLoads, maxConcurrentLoads); + } + + /// Cached entries. + public int Count + { + get + { + lock (_gate) return _cache.Count; + } + } + + /// Maximum cached entries; lowering it evicts the least recently used at once. + public int Capacity + { + get + { + lock (_gate) return _cache.Capacity; + } + set + { + lock (_gate) _cache.Capacity = value; + } + } + + /// Loads started and not yet finished or cancelled. + public int PendingLoads + { + get + { + lock (_gate) return _loading.Count; + } + } + + /// The cached image without loading; true also for a cached "no thumbnail". + public bool TryGet(TKey key, out TImage? image) + { + lock (_gate) return _cache.TryGet(key, out image); + } + + /// The image for , from the cache or a (shared) load. + /// was cancelled. + public async Task GetAsync(TKey key, CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + Load load; + lock (_gate) + { + if (_cache.TryGet(key, out var cached)) return cached; + if (!_loading.TryGetValue(key, out load!)) + { + load = new Load(); + _loading[key] = load; + load.Task = Task.Run(() => RunAsync(key, load), CancellationToken.None); + } + load.Waiters++; + } + try + { + return await load.Task.WaitAsync(cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + lock (_gate) + { + if (--load.Waiters == 0 && !load.Task.IsCompleted) + { + load.Cancellation.Cancel(); + if (_loading.TryGetValue(key, out var current) && ReferenceEquals(current, load)) _loading.Remove(key); + } + } + throw; + } + } + + /// Forgets every cached image (loads in flight complete normally). + public void Clear() + { + lock (_gate) _cache.Clear(); + } + + public void Dispose() + { + lock (_gate) + { + foreach (var load in _loading.Values) load.Cancellation.Cancel(); + _loading.Clear(); + _cache.Clear(); + } + } + + private async Task RunAsync(TKey key, Load load) + { + var token = load.Cancellation.Token; + try + { + await _slots.WaitAsync(token).ConfigureAwait(false); + try + { + var image = await _load(key, token).ConfigureAwait(false); + lock (_gate) + { + if (!token.IsCancellationRequested) _cache.Set(key, image); + } + return image; + } + finally + { + _slots.Release(); + } + } + finally + { + lock (_gate) + { + if (_loading.TryGetValue(key, out var current) && ReferenceEquals(current, load)) _loading.Remove(key); + } + } + } + + private sealed class Load + { + public CancellationTokenSource Cancellation { get; } = new(); + public Task Task { get; set; } = null!; + public int Waiters { get; set; } + } +} diff --git a/src/Titano.App/Library/ThumbnailLoading.cs b/src/Titano.App/Library/ThumbnailLoading.cs new file mode 100644 index 00000000..828849dd --- /dev/null +++ b/src/Titano.App/Library/ThumbnailLoading.cs @@ -0,0 +1,52 @@ +using System.Windows; +using System.Windows.Media; + +namespace Titano.App.Library; + +/// +/// Attached behaviour of the card template: requests the hero thumbnail when a card shows a sequence and cancels +/// it when the card is recycled for another sequence or leaves the tree (scrolled away). +/// +public static class ThumbnailLoading +{ + /// Width of the thumbnail in device-independent pixels; 0 disables loading. + public static readonly DependencyProperty WidthProperty = DependencyProperty.RegisterAttached( + "Width", typeof(double), typeof(ThumbnailLoading), new PropertyMetadata(0.0, OnWidthChanged)); + + public static double GetWidth(DependencyObject d) => (double)d.GetValue(WidthProperty); + + public static void SetWidth(DependencyObject d, double value) => d.SetValue(WidthProperty, value); + + private static void OnWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) + { + if (d is not FrameworkElement element) return; + element.DataContextChanged -= OnDataContextChanged; + element.Loaded -= OnLoaded; + element.Unloaded -= OnUnloaded; + if ((double)e.NewValue <= 0) return; + element.DataContextChanged += OnDataContextChanged; + element.Loaded += OnLoaded; + element.Unloaded += OnUnloaded; + Request(element); + } + + private static void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) + { + if (e.OldValue is SequenceItem old) old.ReleaseThumbnail(); + Request((FrameworkElement)sender); + } + + private static void OnLoaded(object sender, RoutedEventArgs e) => Request((FrameworkElement)sender); + + private static void OnUnloaded(object sender, RoutedEventArgs e) + { + if (((FrameworkElement)sender).DataContext is SequenceItem item) item.ReleaseThumbnail(); + } + + private static void Request(FrameworkElement element) + { + if (element.DataContext is not SequenceItem item || !element.IsLoaded) return; + var scale = VisualTreeHelper.GetDpi(element).DpiScaleX; + item.RequestThumbnail((int)Math.Ceiling(GetWidth(element) * scale)); + } +} diff --git a/src/Titano.App/Library/ThumbnailService.cs b/src/Titano.App/Library/ThumbnailService.cs new file mode 100644 index 00000000..439650c9 --- /dev/null +++ b/src/Titano.App/Library/ThumbnailService.cs @@ -0,0 +1,192 @@ +using System.Collections.Concurrent; +using System.IO; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using Titano.Core.Diagnostics; +using Titano.Core.Model; +using Titano.Data; +using Titano.Ui.Visuals; + +namespace Titano.App.Library; + +/// A thumbnail request: one frame at a width bucket (so nearby sizes share a decode). +public readonly record struct ThumbnailKey(Guid FrameId, int Width); + +/// +/// Library thumbnails (BRIEF §8.5): a frame's embedded preview, read straight from its offset/length in the +/// original and decoded by WIC at the requested width (falling back to decoding the original), turned upright, +/// frozen and kept in an LRU cache. Loads run off the UI thread and stop when the card scrolls away. +/// +public sealed class ThumbnailService : IDisposable +{ + /// Embedded previews larger than this are not read (a damaged index would make us read gigabytes). + private const long MaxPreviewBytes = 64L << 20; + + private const int WidthStep = 64; + + private readonly TitanoDatabase _db; + private readonly ThumbnailCache _cache; + private readonly ConcurrentDictionary _archiveRoots = new(); + private readonly ConcurrentDictionary _firstFrames = new(); + + public ThumbnailService(TitanoDatabase db, int capacity) + { + _db = db; + _cache = new ThumbnailCache(Math.Max(16, capacity), LoadAsync, maxConcurrentLoads: Math.Clamp(Environment.ProcessorCount / 2, 2, 6)); + } + + public int Count => _cache.Count; + + /// Decodes in flight (capture waits for them). + public int PendingLoads => _cache.PendingLoads; + + /// Maximum thumbnails kept in memory (Settings › Storage). + public int Capacity + { + get => _cache.Capacity; + set => _cache.Capacity = Math.Max(16, value); + } + + /// The hero thumbnail of a sequence: its hero frame, or the first frame. + public async Task HeroAsync(Sequence sequence, int pixelWidth, CancellationToken ct) + { + var frameId = sequence.HeroFrameId ?? await FirstFrameAsync(sequence.Id, ct).ConfigureAwait(false); + return frameId is { } id ? await _cache.GetAsync(Key(id, pixelWidth), ct).ConfigureAwait(false) : null; + } + + /// A frame of a sequence by index (hover scrubbing). + public async Task FrameAsync(Guid sequenceId, int index, int pixelWidth, CancellationToken ct) + { + var frames = await _db.Frames.ListBySequenceAsync(sequenceId, index - 1, 1, ct).ConfigureAwait(false); + return frames.Count == 0 ? null : await _cache.GetAsync(Key(frames[0].Id, pixelWidth), ct).ConfigureAwait(false); + } + + /// Hover-scrub frames of a sequence, sampled to at most positions. + public IThumbnailSource ScrubSource(Sequence sequence, int positions = 120) => new ScrubFrames(this, sequence, positions); + + /// Drops decoded thumbnails (Settings › Storage › Clear). + public void Clear() + { + _cache.Clear(); + _archiveRoots.Clear(); + _firstFrames.Clear(); + } + + public void Dispose() => _cache.Dispose(); + + private static ThumbnailKey Key(Guid frameId, int pixelWidth) => + new(frameId, Math.Clamp((pixelWidth + WidthStep - 1) / WidthStep * WidthStep, WidthStep, 2048)); + + private async Task FirstFrameAsync(Guid sequenceId, CancellationToken ct) + { + if (_firstFrames.TryGetValue(sequenceId, out var cached)) return cached; + var frames = await _db.Frames.ListBySequenceAsync(sequenceId, -1, 1, ct).ConfigureAwait(false); + var id = frames.Count > 0 ? frames[0].Id : (Guid?)null; + _firstFrames[sequenceId] = id; + return id; + } + + private async Task ArchiveRootAsync(Guid sequenceId, CancellationToken ct) + { + var sequence = await _db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false); + if (sequence is null) return null; + if (_archiveRoots.TryGetValue(sequence.ArchiveId, out var root)) return root; + root = (await _db.Archives.GetAsync(sequence.ArchiveId, ct).ConfigureAwait(false))?.RootPath; + _archiveRoots[sequence.ArchiveId] = root; + return root; + } + + private async Task LoadAsync(ThumbnailKey key, CancellationToken ct) + { + var frame = await _db.Frames.GetAsync(key.FrameId, ct).ConfigureAwait(false); + if (frame is null) return null; + var root = await ArchiveRootAsync(frame.SequenceId, ct).ConfigureAwait(false); + if (root is null) return null; + var path = Path.Combine(root, frame.RelativePath.Replace('/', Path.DirectorySeparatorChar)); + ct.ThrowIfCancellationRequested(); + try + { + return Decode(path, frame, key.Width, ct); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException or FileFormatException or ArgumentException or InvalidOperationException) + { + Log.Debug("thumbs", $"No thumbnail for {path}: {ex.Message}"); + return null; + } + } + + /// The embedded preview when the index knows it, otherwise the original, decoded at . + internal static BitmapSource? Decode(string path, Frame frame, int width, CancellationToken ct) + { + if (!File.Exists(path)) return null; + if (frame.PreviewOffset is > 0 and var offset && frame.PreviewLength is > 0 and <= MaxPreviewBytes and var length) + { + var bytes = new byte[length]; + using (var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 4096, FileOptions.RandomAccess)) + { + if (offset + length <= file.Length) + { + file.Seek(offset, SeekOrigin.Begin); + file.ReadExactly(bytes); + ct.ThrowIfCancellationRequested(); + try + { + using var memory = new MemoryStream(bytes, writable: false); + return DecodeStream(memory, frame.Orientation, width); + } + catch (Exception ex) when (ex is NotSupportedException or FileFormatException or ArgumentException) + { + // A broken preview falls through to the original. + } + } + } + } + ct.ThrowIfCancellationRequested(); + using var original = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 1 << 16, FileOptions.SequentialScan); + return DecodeStream(original, frame.Orientation, width); + } + + /// WIC decode with scaling during decode (JPEG DCT scaling), then the Exif orientation; frozen for any thread. + internal static BitmapSource DecodeStream(Stream stream, int orientation, int width) + { + var turned = orientation is 5 or 6 or 7 or 8; + var image = new BitmapImage(); + image.BeginInit(); + image.CacheOption = BitmapCacheOption.OnLoad; + image.CreateOptions = BitmapCreateOptions.IgnoreColorProfile; + if (turned) image.DecodePixelHeight = width; + else image.DecodePixelWidth = width; + image.StreamSource = stream; + image.EndInit(); + BitmapSource result = image; + if (orientation is > 1 and <= 8) + { + var transform = new TransformGroup(); + if (orientation is 2 or 4 or 5 or 7) transform.Children.Add(new ScaleTransform(-1, 1)); + var angle = orientation switch + { + 3 or 4 => 180, + 5 or 6 => 90, + 7 or 8 => 270, + _ => 0, + }; + if (angle != 0) transform.Children.Add(new RotateTransform(angle)); + result = new TransformedBitmap(image, transform); + } + result.Freeze(); + return result; + } + + /// Evenly spaced frames of one sequence for hover scrubbing. + private sealed class ScrubFrames(ThumbnailService owner, Sequence sequence, int positions) : IThumbnailSource + { + public int Count { get; } = Math.Clamp(Math.Min(sequence.FrameCount, positions), 0, positions); + + public async ValueTask GetAsync(int index, int pixelWidth, CancellationToken cancellationToken) + { + if (Count <= 1) return await owner.HeroAsync(sequence, pixelWidth, cancellationToken).ConfigureAwait(false); + var frameIndex = (int)Math.Round(index * (sequence.FrameCount - 1) / (double)(Count - 1)); + return await owner.FrameAsync(sequence.Id, frameIndex, pixelWidth, cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/src/Titano.App/Sections/AboutView.xaml b/src/Titano.App/Sections/AboutView.xaml index adaa0d17..30236370 100644 --- a/src/Titano.App/Sections/AboutView.xaml +++ b/src/Titano.App/Sections/AboutView.xaml @@ -3,19 +3,21 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ui="clr-namespace:Titano.Ui.Controls;assembly=Titano.Ui" xmlns:l="clr-namespace:Titano.Ui.Localization;assembly=Titano.Ui"> + - + - + - + + - + @@ -23,20 +25,47 @@ + + + + - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + +